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:
Different implementations of decorators in python
Sorry for long question, but I don't know how to make it shorter.
1. Decorators without args
Implementation 1.1 (through function)
import time
import functools
def pause(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
time.sleep(1)
return f(*args, **kwargs)
return wrapper
@pause
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(*args, **kwargs)
desc
It's "classical" implementation - a lot of articles contain it.
-breaks function signature (can be solved by nonstandard module decorator)
-you must use functools for saving name and doc string of function (not very big problem, but slightly more code and magic)
+you can modify function args (not always necessary)
+-? Anything else?
Implementation 1.2 (through function)
import time
def pause(f):
time.sleep(1)
return f
@pause
def func(x, y):
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(x, y)
desc
? Why it implementation rarely used in articles and examples? What have I missed?
-you can't modify function args
+not breaks function signature
+less code
+-? Anything else?
Implementation 1.3 (through classes)
import time
class pause(object):
def __init__(self, f):
self.f = f
def __call__(self, *args, **kwargs):
time.sleep(1)
return self.f(*args, **kwargs)
@pause
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on pause in module __main__ object:
class pause(__builtin__.object)
| Methods defined here:
|
| __call__(self, *args, **kwargs)
|
| __init__(self, f)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
IMHO, ugly.
Implementation 1.4 (through classes)
import time
class pause(object):
def __call__(self, f):
time.sleep(1)
return f
@pause()
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(x, y)
desc
-you can't modify function args
-nonstandard syntax for decorator use
+not breaks function signature
+-less code (but more than implementation 2 :) )
+-? Anything else?
2. Decorators with args
Implementation 2.1 (through function)
import time
import functools
def pause(t):
def wrapper(f):
@functools.wraps(f)
def tmp(*args, **kwargs):
time.sleep(t)
return f(*args, **kwargs)
return tmp
return wrapper
@pause(1)
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(*args, **kwargs)
desc
It's "classical" implementation - a lot of articles contain it.
-breaks function signature
-nested is worse than flat
-you must use functools for saving name and doc string of function
+you can modify function args
+-? Anything else?
Implementation 2.2 (through function)
import time
def pause(t):
def wrapper(f):
time.sleep(t)
return f
return wrapper
@pause(1)
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(x, y)
desc
? Why it implementation rarely used in articles and examples? What have I missed?
-you can't modify function args
+not breaks function signature
+less code
+-? Anything else?
Implementation 2.3 (through classes)
import time
class pause(object):
def __init__(self, darg):
self.darg = darg
def __call__(self, f):
time.sleep(self.darg)
return f
@pause(1)
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(x, y)
desc
-you can't modify function args
+not breaks function signature
+-less code (but more than implementation 2 :) )
IMHO+ little clearer than nested functions
+-? Anything else?
Questions in one place
Why implementations 1.1/2.1 are more common in articles and examples as compared with implementations 1.2/2.2?
What are the pros and cons I missed?
Did I missed something else?
A:
It sure is good that the implementations 1.2 & 2.2 are "less common than" 1.1 and 2.1, because they do different things. In fact, I wouldn't call them "decorators", because they don't really wrap ("decorate") the function. Instead, they only perform their action once, at the moment the decorated function is parsed. That is, their action (sleep in your case) is performed at function definition time, not at function invocation time.
Try invoking your decorated functions several times and you will see the difference.
| Different implementations of decorators in python | Sorry for long question, but I don't know how to make it shorter.
1. Decorators without args
Implementation 1.1 (through function)
import time
import functools
def pause(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
time.sleep(1)
return f(*args, **kwargs)
return wrapper
@pause
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(*args, **kwargs)
desc
It's "classical" implementation - a lot of articles contain it.
-breaks function signature (can be solved by nonstandard module decorator)
-you must use functools for saving name and doc string of function (not very big problem, but slightly more code and magic)
+you can modify function args (not always necessary)
+-? Anything else?
Implementation 1.2 (through function)
import time
def pause(f):
time.sleep(1)
return f
@pause
def func(x, y):
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(x, y)
desc
? Why it implementation rarely used in articles and examples? What have I missed?
-you can't modify function args
+not breaks function signature
+less code
+-? Anything else?
Implementation 1.3 (through classes)
import time
class pause(object):
def __init__(self, f):
self.f = f
def __call__(self, *args, **kwargs):
time.sleep(1)
return self.f(*args, **kwargs)
@pause
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on pause in module __main__ object:
class pause(__builtin__.object)
| Methods defined here:
|
| __call__(self, *args, **kwargs)
|
| __init__(self, f)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
IMHO, ugly.
Implementation 1.4 (through classes)
import time
class pause(object):
def __call__(self, f):
time.sleep(1)
return f
@pause()
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(x, y)
desc
-you can't modify function args
-nonstandard syntax for decorator use
+not breaks function signature
+-less code (but more than implementation 2 :) )
+-? Anything else?
2. Decorators with args
Implementation 2.1 (through function)
import time
import functools
def pause(t):
def wrapper(f):
@functools.wraps(f)
def tmp(*args, **kwargs):
time.sleep(t)
return f(*args, **kwargs)
return tmp
return wrapper
@pause(1)
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(*args, **kwargs)
desc
It's "classical" implementation - a lot of articles contain it.
-breaks function signature
-nested is worse than flat
-you must use functools for saving name and doc string of function
+you can modify function args
+-? Anything else?
Implementation 2.2 (through function)
import time
def pause(t):
def wrapper(f):
time.sleep(t)
return f
return wrapper
@pause(1)
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(x, y)
desc
? Why it implementation rarely used in articles and examples? What have I missed?
-you can't modify function args
+not breaks function signature
+less code
+-? Anything else?
Implementation 2.3 (through classes)
import time
class pause(object):
def __init__(self, darg):
self.darg = darg
def __call__(self, f):
time.sleep(self.darg)
return f
@pause(1)
def func(x, y):
"""desc"""
return x + y
print func(1, 2)
help(func)
Output:
3
Help on function func in module __main__:
func(x, y)
desc
-you can't modify function args
+not breaks function signature
+-less code (but more than implementation 2 :) )
IMHO+ little clearer than nested functions
+-? Anything else?
Questions in one place
Why implementations 1.1/2.1 are more common in articles and examples as compared with implementations 1.2/2.2?
What are the pros and cons I missed?
Did I missed something else?
| [
"It sure is good that the implementations 1.2 & 2.2 are \"less common than\" 1.1 and 2.1, because they do different things. In fact, I wouldn't call them \"decorators\", because they don't really wrap (\"decorate\") the function. Instead, they only perform their action once, at the moment the decorated function is ... | [
2
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0004112873_decorator_python.txt |
Q:
twisted web: how do I properly images from an images directory
I've successfully written a twisted web server that displays dynamically generated content.
However, when I attempt to display image (png) files from a directory (~cwd/plots/image.png), the server fails without error and the browser either displays the alt text or the broken image icon. What am I doing wrong?
import sys
from twisted.internet import reactor
import twisted.python.filepath
from twisted.web import server, resource, static
FILES = ["plot/10.53.174.1.png", "plot/10.53.174.2.png", "plot/10.53.174.3.png"]
class Child(resource.Resource):
def __init__(self,link, filename):
resource.Resource.__init__(self)
self.filename = filename
self.link = link
pass
def render(self, request ):
filepath = "/%s" % (self.filename)
linkpath = "%s%s" % (self.link, filepath)
self.getChild(linkpath, static.File(self.filename))
return """
<html><body> <head> <title>%s</title> </head> <body> <h1>%s</h1><br> <img src="%s" alt = "angry beaver" /> </body>""" % (self.link, self.link, linkpath)
class Toplevel(resource.Resource):
#addSlash = True
def render(self, request):
request.write("""<html><body> <head> <title>monitor server listing</title> </head> <body> <h1>Server List</h1> <ul>""" )
#assume a pre-validated list of plot file names. validate their presence anyway
if FILES:
for fileName in FILES:
if os.path.exists(fileName):
try:
link = fileName.split('.png')[0]
link = link.split('plot')[1]
path = link[1:]
request.write('<li> <a href="%s">%s</a><br>' % (link, link))
root.putChild(path, Child(link, fileName))
#root.putChild(path, Child(fileName))
except Exception as why:
request.write("%s <br>" % (str(why)))
else:
request.write(" you may think %s exists but it doesn't " % (fileName))
else:
request.write("""No files given""")
request.write("""</ul></body></html>""")
return ""
if __name__ == "__main__":
root = resource.Resource()
home = Toplevel()
png_file = twisted.python.filepath.FilePath('./plot/')
root.putChild('', home)
site = server.Site(root)
reactor.listenTCP(8007, site)
reactor.run()
A:
First: View Source at
http://localhost:8007/10.53.174.1,
you must change code to render
correct link to image.
Second: Use twisted.web.static.File to
serve static content
Corrected code:
import sys
import os
from twisted.internet import reactor
import twisted.python.filepath
from twisted.web.static import File
from twisted.web import server, resource, static
FILES = ["plot/10.53.174.1.png", "plot/10.53.174.2.png", "plot/10.53.174.3.png"]
class Child(resource.Resource):
def __init__(self,link, filename):
resource.Resource.__init__(self)
self.filename = filename
self.link = link
pass
def render(self, request ):
filepath = "/%s" % (self.filename)
linkpath = filepath
#linkpath = "%s%s" % (self.link, filepath)
self.getChild(linkpath, static.File(self.filename))
return """
<html><body> <head> <title>%s</title> </head> <body> <h1>%s</h1><br> <img src="%s" alt = "angry beaver" /> </body>""" % (self.link, self.link, linkpath)
class Toplevel(resource.Resource):
#addSlash = True
def render(self, request):
request.write("""<html><body> <head> <title>monitor server listing</title> </head> <body> <h1>Server List</h1> <ul>""" )
#assume a pre-validated list of plot file names. validate their presence anyway
if FILES:
for fileName in FILES:
request.write(fileName)
if os.path.exists(fileName):
try:
link = fileName.split('.png')[0]
link = link.split('plot')[1]
path = link[1:]
request.write('<li> <a href="%s">%s</a><br>' % (link, link))
root.putChild(path, Child(link, fileName))
#root.putChild(path, Child(fileName))
except Exception as why:
request.write("%s <br>" % (str(why)))
else:
request.write(" you may think %s exists but it doesn't " % (fileName))
else:
request.write("""No files given""")
request.write("""</ul></body></html>""")
return ""
if __name__ == "__main__":
root = resource.Resource()
home = Toplevel()
png_file = twisted.python.filepath.FilePath('./plot/')
plot_resource = File('./plot')
root.putChild('', home)
root.putChild('plot', plot_resource)
site = server.Site(root)
reactor.listenTCP(8007, site)
reactor.run()
PS. You code is little ugly. You can improve it. Try to read this:
http://jcalderone.livejournal.com/50562.html
http://twistedmatrix.com/documents/10.1.0/core/howto/tutorial/index.html
| twisted web: how do I properly images from an images directory | I've successfully written a twisted web server that displays dynamically generated content.
However, when I attempt to display image (png) files from a directory (~cwd/plots/image.png), the server fails without error and the browser either displays the alt text or the broken image icon. What am I doing wrong?
import sys
from twisted.internet import reactor
import twisted.python.filepath
from twisted.web import server, resource, static
FILES = ["plot/10.53.174.1.png", "plot/10.53.174.2.png", "plot/10.53.174.3.png"]
class Child(resource.Resource):
def __init__(self,link, filename):
resource.Resource.__init__(self)
self.filename = filename
self.link = link
pass
def render(self, request ):
filepath = "/%s" % (self.filename)
linkpath = "%s%s" % (self.link, filepath)
self.getChild(linkpath, static.File(self.filename))
return """
<html><body> <head> <title>%s</title> </head> <body> <h1>%s</h1><br> <img src="%s" alt = "angry beaver" /> </body>""" % (self.link, self.link, linkpath)
class Toplevel(resource.Resource):
#addSlash = True
def render(self, request):
request.write("""<html><body> <head> <title>monitor server listing</title> </head> <body> <h1>Server List</h1> <ul>""" )
#assume a pre-validated list of plot file names. validate their presence anyway
if FILES:
for fileName in FILES:
if os.path.exists(fileName):
try:
link = fileName.split('.png')[0]
link = link.split('plot')[1]
path = link[1:]
request.write('<li> <a href="%s">%s</a><br>' % (link, link))
root.putChild(path, Child(link, fileName))
#root.putChild(path, Child(fileName))
except Exception as why:
request.write("%s <br>" % (str(why)))
else:
request.write(" you may think %s exists but it doesn't " % (fileName))
else:
request.write("""No files given""")
request.write("""</ul></body></html>""")
return ""
if __name__ == "__main__":
root = resource.Resource()
home = Toplevel()
png_file = twisted.python.filepath.FilePath('./plot/')
root.putChild('', home)
site = server.Site(root)
reactor.listenTCP(8007, site)
reactor.run()
| [
"\nFirst: View Source at\nhttp://localhost:8007/10.53.174.1,\nyou must change code to render\ncorrect link to image.\nSecond: Use twisted.web.static.File to\nserve static content\n\nCorrected code:\nimport sys\nimport os\nfrom twisted.internet import reactor\nimport twisted.python.filepath\nfrom twisted.web.static ... | [
1
] | [] | [] | [
"python",
"twisted",
"webserver"
] | stackoverflow_0004110579_python_twisted_webserver.txt |
Q:
List in HTTP request
I have an HTTP POST request with the following variables: "UnicodeMultiDict: ... (u'ids[]', u'568236498'), (u'ids[]', u'528900768')". It seems like it is a list, so how can I retireve these variables? When I use self.request.POST.get('ids[]') it only returns the first element.
I am using the webapp framework.
Thanks,
Joel
A:
self.request.POST.getall('ids[]') - see http://pythonpaste.org/webob/modules/webob.html#webob.multidict.MultiDict
| List in HTTP request | I have an HTTP POST request with the following variables: "UnicodeMultiDict: ... (u'ids[]', u'568236498'), (u'ids[]', u'528900768')". It seems like it is a list, so how can I retireve these variables? When I use self.request.POST.get('ids[]') it only returns the first element.
I am using the webapp framework.
Thanks,
Joel
| [
"self.request.POST.getall('ids[]') - see http://pythonpaste.org/webob/modules/webob.html#webob.multidict.MultiDict\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004113014_google_app_engine_python.txt |
Q:
.so module doesnt import in python: dynamic module does not define init function
I am trying to write a python wrapper for a C function. After writing all the code, and getting it to compile, Python can't import the module. I am following the example given here. I reproduce it here, after fixing some typos. There is a file myModule.c:
#include <Python.h>
/*
* Function to be called from Python
*/
static PyObject* py_myFunction(PyObject* self, PyObject* args)
{
char *s = "Hello from C!";
return Py_BuildValue("s", s);
}
/*
* Bind Python function names to our C functions
*/
static PyMethodDef myModule_methods[] = {
{"myFunction", py_myFunction, METH_VARARGS},
{NULL, NULL}
};
/*
* Python calls this to let us initialize our module
*/
void initmyModule()
{
(void) Py_InitModule("myModule", myModule_methods);
}
Since I am on a Mac with Macports python, I compile it as
$ g++ -dynamiclib -I/opt/local/Library/Frameworks/Python.framework/Headers -lpython2.6 -o myModule.dylib myModule.c
$ mv myModule.dylib myModule.so
However, I get an error when I try to import it.
$ ipython
In[1]: import myModule
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/Users/.../blahblah/.../<ipython console> in <module>()
ImportError: dynamic module does not define init function (initmyModule)
Why can't I import it?
A:
Since you're using a C++ compiler, function names will be mangled (for instance, my g++ mangles void initmyModule() into _Z12initmyModulev). Therefore, the python interpreter won't find your module's init function.
You need to either use a plain C compiler, or force C linkage throughout your module with an extern "C" directive:
#ifdef __cplusplus
extern "C" {
#endif
#include <Python.h>
/*
* Function to be called from Python
*/
static PyObject* py_myFunction(PyObject* self, PyObject* args)
{
char *s = "Hello from C!";
return Py_BuildValue("s", s);
}
/*
* Bind Python function names to our C functions
*/
static PyMethodDef myModule_methods[] = {
{"myFunction", py_myFunction, METH_VARARGS},
{NULL, NULL}
};
/*
* Python calls this to let us initialize our module
*/
void initmyModule()
{
(void) Py_InitModule("myModule", myModule_methods);
}
#ifdef __cplusplus
} // extern "C"
#endif
| .so module doesnt import in python: dynamic module does not define init function | I am trying to write a python wrapper for a C function. After writing all the code, and getting it to compile, Python can't import the module. I am following the example given here. I reproduce it here, after fixing some typos. There is a file myModule.c:
#include <Python.h>
/*
* Function to be called from Python
*/
static PyObject* py_myFunction(PyObject* self, PyObject* args)
{
char *s = "Hello from C!";
return Py_BuildValue("s", s);
}
/*
* Bind Python function names to our C functions
*/
static PyMethodDef myModule_methods[] = {
{"myFunction", py_myFunction, METH_VARARGS},
{NULL, NULL}
};
/*
* Python calls this to let us initialize our module
*/
void initmyModule()
{
(void) Py_InitModule("myModule", myModule_methods);
}
Since I am on a Mac with Macports python, I compile it as
$ g++ -dynamiclib -I/opt/local/Library/Frameworks/Python.framework/Headers -lpython2.6 -o myModule.dylib myModule.c
$ mv myModule.dylib myModule.so
However, I get an error when I try to import it.
$ ipython
In[1]: import myModule
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/Users/.../blahblah/.../<ipython console> in <module>()
ImportError: dynamic module does not define init function (initmyModule)
Why can't I import it?
| [
"Since you're using a C++ compiler, function names will be mangled (for instance, my g++ mangles void initmyModule() into _Z12initmyModulev). Therefore, the python interpreter won't find your module's init function.\nYou need to either use a plain C compiler, or force C linkage throughout your module with an extern... | [
5
] | [] | [] | [
"c",
"c++",
"python",
"python_c_api",
"python_extensions"
] | stackoverflow_0004112375_c_c++_python_python_c_api_python_extensions.txt |
Q:
How can I represent this in a Django model?
I'm having trouble working out what the relationships should be with this:
class Airport(models.Model):
airlines = models.ManyToManyField(Airline)
class Airline(models.Model):
terminal = models.CharField(max_length=200)
The problem is that each Airline is associated with a different terminal depending on which Airport is requested, so terminal can't just be static text.
Anyone know what the best way to model this is?
Thanks
A:
Surprised that there are so many different answers, I guess people each have their own preferences. This is how I'd do it:
class Airport(models.Model):
name = models.CharField(max_length=200)
class Airline(models.Model):
name = models.CharField(max_length=200)
terminals = models.ManyToManyField('Terminal', related_name='airlines')
class Terminal(models.Model):
name = models.CharField(max_length=200)
airport = models.ForeignKey('Airport', related_name='terminals')
This allows for and assumes the following conditions:
An airline can be present in one or
more terminals in a given airport
A terminal can have more one or more
airlines
A terminal can only exist in
a single airport
Note that in this setup airports and airlines are always linked indirectly via Terminals. I think this is a feature rather than a bug, personally. Airports always have at least one terminal, even if the terminal is the entire airport.
Or
You may consider it to be slightly more correct, from a logical point of view, to create the models like so:
class Airport(models.Model):
name = models.CharField(max_length=200)
class Airline(models.Model):
name = models.CharField(max_length=200)
class Terminal(models.Model):
name = models.CharField(max_length=200)
airport = models.ForeignKey('Airport', related_name='terminals')
airlines = models.ManyToManyField('Airline', related_name='terminals')
In practical terms the data will behave largely the same. One could make an argument, however, that thinking of a terminal having "Airlines" makes more sense conceptually than a given airline having terminals. After all, the airline does not contain the terminals, but each terminal contains these airlines.
A:
class Airport(models.Model):
airlines = models.ManyToManyField(Airline, through=Terminal)
class Terminal(models.Model):
terminal = models.CharField(max_length=200)
class Airline(models.Model):
terminal = models.ForeignKey(Terminal)
airport = models.ForeignKey(Airport)
A:
class Airport(models.Model):
airlines = models.ManyToManyField(Airline)
terminal = models.CharField(max_length=200)
i think it would solve your problem use just one class instead
| How can I represent this in a Django model? | I'm having trouble working out what the relationships should be with this:
class Airport(models.Model):
airlines = models.ManyToManyField(Airline)
class Airline(models.Model):
terminal = models.CharField(max_length=200)
The problem is that each Airline is associated with a different terminal depending on which Airport is requested, so terminal can't just be static text.
Anyone know what the best way to model this is?
Thanks
| [
"Surprised that there are so many different answers, I guess people each have their own preferences. This is how I'd do it:\nclass Airport(models.Model):\n name = models.CharField(max_length=200)\n\nclass Airline(models.Model):\n name = models.CharField(max_length=200)\n terminals = models.ManyToManyField(... | [
3,
0,
0
] | [] | [] | [
"data_modeling",
"django",
"django_models",
"python"
] | stackoverflow_0004112412_data_modeling_django_django_models_python.txt |
Q:
What is the Python equivalent of a Ruby class method?
In ruby you can do this:
class A
def self.a
'A.a'
end
end
puts A.a #-> A.a
How can this be done in python. I need a method of a class to be called without it being called on an instance of the class. When I try to do this I get this error:
unbound method METHOD must be called with CLASS instance as first argument (got nothing instead)
This is what I tried:
class A
def a():
return 'A.a'
print A.a()
A:
What you're looking for is the staticmethod decorator, which can be used to make methods that don't require a first implicit argument. It can be used like this:
class A(object):
@staticmethod
def a():
return 'A.a'
On the other hand, if you wish to access the class (not the instance) from the method, you can use the classmethod decorator, which is used mostly the same way:
class A(object):
@classmethod
def a(cls):
return '%s.a' % cls.__name__
Which can still be called without instanciating the object (A.a()).
A:
There are two ways to do this:
@staticmethod
def foo(): # No implicit parameter
print 'foo'
@classmethod
def foo(cls): # Class as implicit paramter
print cls
The difference is that a static method has no implicit parameters at all. A class method receives the class that it is called on in exactly the same way that a normal method receives the instance.
Which one you use depends on if you want the method to have access to the class or not.
Either one can be called without an instance.
A:
You can also access the class object in a static method using __class__:
class A() :
@staticmethod
def a() :
return '{}.a'.format( __class__.__name__ )
At least this works in Python 3.1
| What is the Python equivalent of a Ruby class method? | In ruby you can do this:
class A
def self.a
'A.a'
end
end
puts A.a #-> A.a
How can this be done in python. I need a method of a class to be called without it being called on an instance of the class. When I try to do this I get this error:
unbound method METHOD must be called with CLASS instance as first argument (got nothing instead)
This is what I tried:
class A
def a():
return 'A.a'
print A.a()
| [
"What you're looking for is the staticmethod decorator, which can be used to make methods that don't require a first implicit argument. It can be used like this:\nclass A(object):\n @staticmethod\n def a():\n return 'A.a'\n\nOn the other hand, if you wish to access the class (not the instance) from the... | [
18,
10,
0
] | [] | [] | [
"class_method",
"oop",
"python",
"ruby",
"static_methods"
] | stackoverflow_0004112608_class_method_oop_python_ruby_static_methods.txt |
Q:
Writing to a .txt file (UTF-8), python
I want to save the output (contents) to a file (saving it in UTF-8). The file shouldn't be overwritten, it should be saved as a new file - e.g. file2.txt
So, I fists open a file.txt, encode it in UTF-8, do some stuff and then wanna save it to file2.txt in UTF-8. How do I do this?
import codecs
def openfile(filename):
with codecs.open(filename, encoding="UTF-8") as F:
contents = F.read()
...
A:
The short way:
file('file2.txt','w').write( file('file.txt').read().encode('utf-8') )
The long way:
data = file('file.txt').read()
... process data ...
data = data.encode('utf-8')
file('file2.txt','w').write( data )
And using 'codecs' explicitly:
codecs.getwriter('utf-8')(file('/tmp/bla3','w')).write(data)
A:
I like to separate concerns in situations like this - I think it really makes the code cleaner, easier to maintain, and can be more efficient.
Here you've 3 concerns: reading a UTF-8 file, processing the lines, and writing a UTF-8 file. Assuming your processing is line-based, this works perfectly in Python, since opening and iterating over lines of a file is built in to the language. As well as being clearer, this is more efficient too since it allows you process huge files that don't fit into memory. Finally, it gives you a great way to test your code - because processing is separated from file io it lets you write unit tests, or even just run the processing code on example text and manually review the output without fiddling around with files.
I'm converting the lines to upper case for the purposes of example - presumably your processing will be more interesting. I like using yield here - it makes it easy for the processing to remove or insert extra lines although that's not being used in my trivial example.
def process(lines):
for line in lines:
yield line.upper()
with codecs.open(file1, 'r', 'utf-8') as infile:
with codecs.open(file2, 'w', 'utf-8') as outfile:
for line in process(infile):
outfile.write(line)
A:
Open a second file. Use contextlib.nested() if need be. Use shutil.copyfileobj() to copy the contents.
| Writing to a .txt file (UTF-8), python | I want to save the output (contents) to a file (saving it in UTF-8). The file shouldn't be overwritten, it should be saved as a new file - e.g. file2.txt
So, I fists open a file.txt, encode it in UTF-8, do some stuff and then wanna save it to file2.txt in UTF-8. How do I do this?
import codecs
def openfile(filename):
with codecs.open(filename, encoding="UTF-8") as F:
contents = F.read()
...
| [
"The short way:\nfile('file2.txt','w').write( file('file.txt').read().encode('utf-8') )\n\nThe long way:\ndata = file('file.txt').read()\n... process data ...\ndata = data.encode('utf-8')\nfile('file2.txt','w').write( data )\n\nAnd using 'codecs' explicitly:\ncodecs.getwriter('utf-8')(file('/tmp/bla3','w')).write(d... | [
16,
10,
2
] | [] | [] | [
"python",
"save"
] | stackoverflow_0004112894_python_save.txt |
Q:
Boost::Python raw_function returning void
Using Boost::Python, the normal mechanism for wrapping functions works correctly with C++ functions returning void. Unfortunately, the normal mechanism also has limitations, specifically with regards to the function arity it supports. So I need to use boost::python::raw_function to wrap my function, but it doesn't compile when my function returns void. Here's a simple test case:
#include <boost/python.hpp>
#include <boost/python/raw_function.hpp>
void entry_point(boost::python::tuple args, boost::python::dict kwargs) { }
BOOST_PYTHON_MODULE(module)
{
boost::python::def("entry_point", boost::python::raw_function(&entry_point));
}
Which gives the error:
/usr/local/include/boost/python/raw_function.hpp: In member function ‘PyObject* boost::python::detail::raw_dispatcher::operator()(PyObject*, PyObject*) [with F = void (*)(boost::python::tuple, boost::python::dict)]’:
/usr/local/include/boost/python/object/py_function.hpp:94: instantiated from ‘PyObject* boost::python::objects::full_py_function_impl::operator()(PyObject*, PyObject*) [with Caller = boost::python::detail::raw_dispatcher, Sig = boost::mpl::vector1]’
void.cpp:8: instantiated from here
/usr/local/include/boost/python/raw_function.hpp:36: error: invalid use of void expression
For the moment, I can work around this by having my function return a dummy value, but that's somewhat unsatisfying. Have other people run into this problem?
A:
I think this is the way that raw_function() works. It expects your function to return a Python object.
In Python the closest thing you will get to a function returning void is a function returning None. I think that approach would be best (and not even that ugly) in your case:
#include <boost/python.hpp>
#include <boost/python/raw_function.hpp>
using namespace boost::python;
namespace
{
object entry_point(tuple args, dict kwargs)
{
return object();
}
}
BOOST_PYTHON_MODULE(foo)
{
def("entry_point", raw_function(&entry_point));
}
| Boost::Python raw_function returning void | Using Boost::Python, the normal mechanism for wrapping functions works correctly with C++ functions returning void. Unfortunately, the normal mechanism also has limitations, specifically with regards to the function arity it supports. So I need to use boost::python::raw_function to wrap my function, but it doesn't compile when my function returns void. Here's a simple test case:
#include <boost/python.hpp>
#include <boost/python/raw_function.hpp>
void entry_point(boost::python::tuple args, boost::python::dict kwargs) { }
BOOST_PYTHON_MODULE(module)
{
boost::python::def("entry_point", boost::python::raw_function(&entry_point));
}
Which gives the error:
/usr/local/include/boost/python/raw_function.hpp: In member function ‘PyObject* boost::python::detail::raw_dispatcher::operator()(PyObject*, PyObject*) [with F = void (*)(boost::python::tuple, boost::python::dict)]’:
/usr/local/include/boost/python/object/py_function.hpp:94: instantiated from ‘PyObject* boost::python::objects::full_py_function_impl::operator()(PyObject*, PyObject*) [with Caller = boost::python::detail::raw_dispatcher, Sig = boost::mpl::vector1]’
void.cpp:8: instantiated from here
/usr/local/include/boost/python/raw_function.hpp:36: error: invalid use of void expression
For the moment, I can work around this by having my function return a dummy value, but that's somewhat unsatisfying. Have other people run into this problem?
| [
"I think this is the way that raw_function() works. It expects your function to return a Python object.\nIn Python the closest thing you will get to a function returning void is a function returning None. I think that approach would be best (and not even that ugly) in your case:\n#include <boost/python.hpp>\n#inclu... | [
2
] | [] | [] | [
"boost",
"boost_python",
"c++",
"python"
] | stackoverflow_0004111021_boost_boost_python_c++_python.txt |
Q:
Creating any kind of restful API with four HTTP methods only?
At the moment I'm trying to build a restful HTTP backend framework.
I've read a book called "Restful webservices" and it kicked off some brainwork on this area.
I have now a bigger picture about why resource oriented architecture is a good thing but there are still blurry parts I cannot understand. I'll try to explain my thoughts and see if someone could make me more clever.
Couldn't one say that everything is an object. Car, pen, book and even abstract things like an idea and a concept could be an object. Cause the word object is just a human invention for "something".
Couldn't you also say that every "something" is a resource. Coin, computer and even debt could be a resource. But the question is to whom. A debt is a resource, but not to the guy who owes, but to the guy he is owing. The same with human residues. They are resources, but not for us, but for mother nature because it needs balance - in and out - the basics of science (programming).
Resources (objects) seem to be nouns. How about adjective and verbs? It actually seems that everything could be described using nouns. Eg.
Adjective: The car is red
Noun: The car has a color red
Adjective: I am tired
Noun: I have a tiredness
Verb: I kill him
Noun: I create a kill
Verb: I kiss her
Noun: I create a kiss
This means that resource = object = noun. The same "something" from different perspectives.
Maybe there are verbs and adjectives that have no noun equivalent, but then that is only a flaw in the human language, not in the concept itself.
So back to what started all this.
When I really thought about that there are only 4 (I know there are some more) HTTP verbs - POST, GET, PUT, DELETE - I felt it couldn't create powerful restful APIs cause they are limiting the API to basic CRUD operations. But after some readings and thinking I realized that everything are just resources that could be either created, read, changed or deleted. Like in and out, simple rules, but yet powerful to create anything.
But then I thought, there is only "in" and "out". Maybe there is only "create" and "delete". Cause GET and PUT are verbs that could be replaced with "create a read" and "create a change".
All this is only me playing with the idea of basics of mother nature. In and Out, Create and Delete. The former is already widely accepted in the programming field. But the latter you don't hear about that much. But if that is correct, then this mean that HTTP Restful API could be used to create anything, in the right way, not by hacking it with modified versions (putting the verbs in the uri, request body etc), but only using POST, GET, PUT, DELETE.
We just have to convert all methods to resources/objects. Instead of:
result = Books.search("Foo");
we have to think:
result = Search.create(Books, "Foo");
What do you think about this?
With this in mind, could one create any kind of restful APIs with four HTTP methods only?
Are "create" and "delete" another piece of the law of the nature?
A:
You can create any system using only two methods, GET and POST, by equating GET = Read and POST = Write.
The other methods just help to add some visibility to the requests.
If you really want to try and model the REST request in terms of objects, I would do this:
result = new Search(Books,"Foo").Get();
However, I'm not sure this mapping is particularly valuable.
A:
A RESTful API is essentially an interface to some kind of data store: a DB, a file system, a distributed hash table, &c. This means that you really don't need custom verbs (standard interfaces are usually better anyway) because you can get everything done using GET, PUT, POST, and DELETE.
It's also important to note that a RESTful API specifically calls for using existing HTTP methods to CRUD resources. Also, API's don't need to be complex or verbose to be useful or even powerful. In most cases simplicity is your friend. Simple structures and simple interfaces, in many cases, do a much better job than equivalent complex structures/interfaces. Look at git, for example, the data structures it uses are very, very, simple and git is very, very, fast as a consequence.
As for your question: yes, people do it all the time and it works!
A:
But then I thought, there is only "in"
and "out". Maybe there is only
"create" and "delete". Cause GET and
PUT are verbs that could be replaced
with "create a read" and "create a
change".
You could do this. You can go even further, and do everything with a POST. You can then have an envelope inside your HTTP Request, that says the operation you wanted to perform. You could even have just one endpoint, and have as many different operations according to the content of your HTTP Request. You could have createBook, updateBook, getAllBooks, and so on.
And you have SOAP.
As someone who has had to build, maintain and code against SOAP and RESTful web services, do yourself (and everyone else) a favour, and use REST.
A:
I think you are relating two different aspects of a restful API. Reducing the HTTP methods to simply IN and OUT are already accomplished by request and response. Sure, you can map read to GET and PUT to create, but what about DELETE? Is that a "PUT of 0"? If so, then you require logic to handle that case.
For example, when you are opening a document into a text editor, you are performing an IN operation into the OS, and the OS performs and OUT operation to the text editor. The opposite is true for saving the document.
But that's just simple house keeping mechanics. Sure, the text editor can mask IN with GET and OUT with PUT, as in "save as", but what about DELETE? That would require it's own verb or overloading the PUT/OUT action to the OS. Then there's POST, which is equivalent to save*. Do we overload the PUT method to check to see if the file already exists? Why not just have it as its own verb?
If you're going to reduce to simple IN and OUT, then you have to overload OUT:
if(OUT){
if(file_exists) update_file
else if(file_size==0) delete_file
else create_file
}
*I'm speaking more theoretically, of course zzzzBov is correct in his post about HTTP's spec.
A:
GET, POST, PUT, and DELETE do not directly relate to Create, Read, Update, and Delete. They often can, but it is important to note that POST and PUT can both perform Update and Create functionality.
http://en.wikipedia.org/wiki/POST_%28HTTP%29
the POST method should be used for any
context in which a request is
non-idempotent
This means that POST should be used for any function that changes server (data) state, and GET, PUT, and DELETE should be used for any functions that do not change server state.
EDIT:
To answer the question: yes. There are a number of solutions I've seen for creating a restful API with html headers. They all boil down to using a directory structure and the right HTML headers.
http://en.wikipedia.org/wiki/Representational_State_Transfer#RESTful_web_services
| Creating any kind of restful API with four HTTP methods only? | At the moment I'm trying to build a restful HTTP backend framework.
I've read a book called "Restful webservices" and it kicked off some brainwork on this area.
I have now a bigger picture about why resource oriented architecture is a good thing but there are still blurry parts I cannot understand. I'll try to explain my thoughts and see if someone could make me more clever.
Couldn't one say that everything is an object. Car, pen, book and even abstract things like an idea and a concept could be an object. Cause the word object is just a human invention for "something".
Couldn't you also say that every "something" is a resource. Coin, computer and even debt could be a resource. But the question is to whom. A debt is a resource, but not to the guy who owes, but to the guy he is owing. The same with human residues. They are resources, but not for us, but for mother nature because it needs balance - in and out - the basics of science (programming).
Resources (objects) seem to be nouns. How about adjective and verbs? It actually seems that everything could be described using nouns. Eg.
Adjective: The car is red
Noun: The car has a color red
Adjective: I am tired
Noun: I have a tiredness
Verb: I kill him
Noun: I create a kill
Verb: I kiss her
Noun: I create a kiss
This means that resource = object = noun. The same "something" from different perspectives.
Maybe there are verbs and adjectives that have no noun equivalent, but then that is only a flaw in the human language, not in the concept itself.
So back to what started all this.
When I really thought about that there are only 4 (I know there are some more) HTTP verbs - POST, GET, PUT, DELETE - I felt it couldn't create powerful restful APIs cause they are limiting the API to basic CRUD operations. But after some readings and thinking I realized that everything are just resources that could be either created, read, changed or deleted. Like in and out, simple rules, but yet powerful to create anything.
But then I thought, there is only "in" and "out". Maybe there is only "create" and "delete". Cause GET and PUT are verbs that could be replaced with "create a read" and "create a change".
All this is only me playing with the idea of basics of mother nature. In and Out, Create and Delete. The former is already widely accepted in the programming field. But the latter you don't hear about that much. But if that is correct, then this mean that HTTP Restful API could be used to create anything, in the right way, not by hacking it with modified versions (putting the verbs in the uri, request body etc), but only using POST, GET, PUT, DELETE.
We just have to convert all methods to resources/objects. Instead of:
result = Books.search("Foo");
we have to think:
result = Search.create(Books, "Foo");
What do you think about this?
With this in mind, could one create any kind of restful APIs with four HTTP methods only?
Are "create" and "delete" another piece of the law of the nature?
| [
"You can create any system using only two methods, GET and POST, by equating GET = Read and POST = Write.\nThe other methods just help to add some visibility to the requests.\nIf you really want to try and model the REST request in terms of objects, I would do this:\nresult = new Search(Books,\"Foo\").Get();\n\nHow... | [
1,
1,
1,
1,
0
] | [] | [] | [
"java",
"javascript",
"python",
"rest",
"ruby"
] | stackoverflow_0004111756_java_javascript_python_rest_ruby.txt |
Q:
Handle a blocking function call in Python
I'm working with the Gnuradio framework. I handle flowgraphs I generate to send/receive signals. These flowgraphs initialize and start, but they don't return the control flow to my application:
I imported time
while time.time() < endtime:
# invoke GRC flowgraph for 1st sequence
if not seq1_sent:
tb = send_seq_2.top_block()
tb.Run(True)
seq1_sent = True
if time.time() < endtime:
break
# invoke GRC flowgraph for 2nd sequence
if not seq2_sent:
tb = send_seq_2.top_block()
tb.Run(True)
seq2_sent = True
if time.time() < endtime:
break
The problem is: only the first if statement invokes the flow-graph (that interacts with the hardware). I'm stuck in this. I could use a Thread, but I'm unexperienced how to timeout threads in Python. I doubt that this is possible, because it seems killing threads isn't within the APIs. This script only has to work on Linux...
How do you handle blocking functions with Python properly - without killing the whole program.
Another more concrete example for this problem is:
import signal, os
def handler(signum, frame):
# print 'Signal handler called with signal', signum
#raise IOError("Couldn't open device!")
import time
print "wait"
time.sleep(3)
def foo():
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
# This open() may hang indefinitely
fd = os.open('/dev/ttys0', os.O_RDWR)
signal.alarm(0) # Disable the alarm
foo()
print "hallo"
How do I still get print "hallo". ;)
Thanks,
Marius
A:
First of all - the use of signals should be avoided at all cost:
1) It may lead to a deadlock. SIGALRM may reach the process BEFORE the blocking syscall (imagine super-high load in the system!) and the syscall will not be interrupted. Deadlock.
2) Playing with signals may have some nasty non-local consequences. For example, syscalls in other threads may be interrupted which usually is not what you want. Normally syscalls are restarted when (not a deadly) signal is received. When you set up a signal handler it automatically turns off this behavior for the whole process, or thread group so to say. Check 'man siginterrupt' on that.
Believe me - I met two problems before and they are not fun at all.
In some cases the blocking can be avoided explicitely - I strongly recommend using select() and friends (check select module in Python) to handle blocking writes and reads. This will not solve blocking open() call, though.
For that I've tested this solution and it works well for named pipes. It opens in a non-blocking way, then turns it off and uses select() call to eventually timeout if nothing is available.
import sys, os, select, fcntl
f = os.open(sys.argv[1], os.O_RDONLY | os.O_NONBLOCK)
flags = fcntl.fcntl(f, fcntl.F_GETFL, 0)
fcntl.fcntl(f, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)
r, w, e = select.select([f], [], [], 2.0)
if r == [f]:
print 'ready'
print os.read(f, 100)
else:
print 'unready'
os.close(f)
Test this with:
mkfifo /tmp/fifo
python <code_above.py> /tmp/fifo (1st terminal)
echo abcd > /tmp/fifo (2nd terminal)
With some additional effort select() call can be used as a main loop of the whole program, aggregating all events - you can use libev or libevent, or some Python wrappers around them.
When you can't explicitely force non-blocking behavior, say you just use an external library, then it's going to be much harder. Threads may do, but obviously it is not a state-of-the-art solution, usually being just wrong.
I'm afraid that in general you can't solve this in a robust way - it really depends on WHAT you block.
A:
IIUC, each top_block has a stop method. So you actually can run the top_block in a thread, and issue a stop if the timeout has arrived. It would be better if the top_block's wait() also had a timeout, but alas, it doesn't.
In the main thread, you then need to wait for two cases: a) the top_block completes, and b) the timeout expires. Busy-waits are evil :-), so you should use the thread's join-with-timeout to wait for the thread. If the thread is still alive after the join, you need to stop the top_run.
A:
You can set a signal alarm that will interrupt your call with a timeout:
http://docs.python.org/library/signal.html
signal.alarm(1) # 1 second
my_blocking_call()
signal.alarm(0)
You can also set a signal handler if you want to make sure it won't destroy your application:
def my_handler(signum, frame):
pass
signal.signal(signal.SIGALRM, my_handler)
EDIT:
What's wrong with this piece of code ? This should not abort your application:
import signal, time
def handler(signum, frame):
print "Timed-out"
def foo():
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
# This open() may hang indefinitely
time.sleep(5)
signal.alarm(0) # Disable the alarm
foo()
print "hallo"
The thing is:
The default handler for SIGALRM is to abort the application, if you set your handler then it should no longer stop the application.
Receiving a signal usually interrupts system calls (then unblocks your application)
A:
The easy part of your question relates to the signal handling. From the perspective of the Python runtime a signal which has been received while the interpreter was making a system call is presented to your Python code as an OSError exception with an errno attributed corresponding to errno.EINTR
So this probably works roughly as you intended:
#!/usr/bin/env python
import signal, os, errno, time
def handler(signum, frame):
# print 'Signal handler called with signal', signum
#raise IOError("Couldn't open device!")
print "timed out"
time.sleep(3)
def foo():
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
try:
signal.alarm(3)
# This open() may hang indefinitely
fd = os.open('/dev/ttys0', os.O_RDWR)
except OSError, e:
if e.errno != errno.EINTR:
raise e
signal.alarm(0) # Disable the alarm
foo()
print "hallo"
Note I've moved the import of time out of the function definition as it seems to be poor form to hide imports in that way. It's not at all clear to me why you're sleeping in your signal handler and, in fact, it seems like a rather bad idea.
The key point I'm trying to make is that any (non-ignored) signal will interrupt your main line of Python code execution. Your handler will be invoked with arguments indicating which signal number triggered the execution (allowing for one Python function to be used for handling many different signals) and a frame object (which could be used for debugging or instrumentation of some sort).
Because the main flow through the code is interrupted it's necessary for you to wrap that code in some exception handling in order to regain control after such events have occurred. (Incidentally if you're writing code in C you'd have the same concern; you have to be prepared for any of your library functions with underlying system calls to return errors and handle -EINTR in the system errno by looping back to retry or branching to some alternative in your main line (such as proceeding to some other file, or without any file/input, etc).
As others have indicated in their responses to your question, basing your approach on SIGALARM is likely to be fraught with portability and reliability issues. Worse, some of these issues may be race conditions that you'll never encounter in your testing environment and may only occur under conditions that are extremely hard to reproduce. The ugly details tend to be in cases of re-entrancy --- what happens if signals are dispatched during execution of your signal handler?
I've used SIGALARM in some scripts and it hasn't been an issue for me, under Linux. The code I was working on was suitable to the task. It might be adequate for your needs.
Your primary question is difficult to answer without knowing more about how this Gnuradio code behaves, what sorts of objects you instantiate from it, and what sorts of objects they return.
Glancing at the docs to which you've linked, I see that they don't seem to offer any sort of "timeout" argument or setting that could be used to limit blocking behavior directly. In the table under "Controlling Flow Graphs" I see that they specifically say that .run() can execute indefinitely or until SIGINT is received. I also note that .start() can start threads in your application and, it seems, returns control to your Python code line while those are running. (That seems to depend on the nature of your flow graphs, which I don't understand sufficiently).
It sounds like you could create your flow graphs, .start() them, and then (after some time processing or sleeping in your main line of Python code) call the .lock() method on your controlling object (tb?). This, I'm guessing, puts the Python representation of the state ... the Python object ... into a quiescent mode to allow you to query the state or, as they say, reconfigure your flow graph. If you call .run() it will call .wait() after it calls .start(); and .wait() will apparently run until either all blocks "indicate they are done" or until you call the object's .stop() method.
So it sounds like you want to use .start() and neither .run() nor .wait(); then call .stop() after doing any other processing (including time.sleep()).
Perhaps something as simple as:
tb = send_seq_2.top_block()
tb.start()
time.sleep(endtime - time.time())
tb.stop()
seq1_sent = True
tb = send_seq_2.top_block()
tb.start()
seq2_sent = True
.. though I'm suspicious of my time.sleep() there. Perhaps you want to do something else where you query the tb object's state (perhaps entailing sleeping for smaller intervals, calling its .lock() method, and accessing attributes that I know nothing about and then calling its .unlock() before sleeping again.
A:
if not seq1_sent:
tb = send_seq_2.top_block()
tb.Run(True)
seq1_sent = True
if time.time() < endtime:
break
If the 'if time.time() < endtime:' then you will break out of the loop and the seq2_sent stuff will never be hit, maybe you mean 'time.time() > endtime' in that test?
A:
you could try using Deferred execution... Twisted framework uses them alot
http://www6.uniovi.es/python/pycon/papers/deferex/
A:
You mention killing threads in Python - this is partialy possible although you can kill/interrupt another thread only when Python code runs, not in C code, so this may not help you as you want.
see this answer to another question:
python: how to send packets in multi thread and then the thread kill itself
or google for killable python threads for more details like this:
http://code.activestate.com/recipes/496960-thread2-killable-threads/
| Handle a blocking function call in Python | I'm working with the Gnuradio framework. I handle flowgraphs I generate to send/receive signals. These flowgraphs initialize and start, but they don't return the control flow to my application:
I imported time
while time.time() < endtime:
# invoke GRC flowgraph for 1st sequence
if not seq1_sent:
tb = send_seq_2.top_block()
tb.Run(True)
seq1_sent = True
if time.time() < endtime:
break
# invoke GRC flowgraph for 2nd sequence
if not seq2_sent:
tb = send_seq_2.top_block()
tb.Run(True)
seq2_sent = True
if time.time() < endtime:
break
The problem is: only the first if statement invokes the flow-graph (that interacts with the hardware). I'm stuck in this. I could use a Thread, but I'm unexperienced how to timeout threads in Python. I doubt that this is possible, because it seems killing threads isn't within the APIs. This script only has to work on Linux...
How do you handle blocking functions with Python properly - without killing the whole program.
Another more concrete example for this problem is:
import signal, os
def handler(signum, frame):
# print 'Signal handler called with signal', signum
#raise IOError("Couldn't open device!")
import time
print "wait"
time.sleep(3)
def foo():
# Set the signal handler and a 5-second alarm
signal.signal(signal.SIGALRM, handler)
signal.alarm(3)
# This open() may hang indefinitely
fd = os.open('/dev/ttys0', os.O_RDWR)
signal.alarm(0) # Disable the alarm
foo()
print "hallo"
How do I still get print "hallo". ;)
Thanks,
Marius
| [
"First of all - the use of signals should be avoided at all cost:\n1) It may lead to a deadlock. SIGALRM may reach the process BEFORE the blocking syscall (imagine super-high load in the system!) and the syscall will not be interrupted. Deadlock.\n2) Playing with signals may have some nasty non-local consequences. ... | [
6,
4,
2,
2,
1,
0,
0
] | [
"If you want to set a timeout on a blocking function, threading.Thread as the method join(timeout) which blocks until the timeout.\nBasically, something like that should do what you want :\nimport threading\nmy_thread = threading.Thread(target=send_seq_2.top_block)\nmy_thread.start()\nmy_thread.join(TIMEOUT)\n\n"
] | [
-1
] | [
"blocking",
"gnuradio",
"multithreading",
"python"
] | stackoverflow_0004051261_blocking_gnuradio_multithreading_python.txt |
Q:
package data not installed from python .egg file
I'm trying to include some data files in a python package using the setuptools package_data option. I'm then accessing the files with pkg_resources. This works perfectly when the python .egg file is installed as-is (i.e. still zipped). But when the egg file is unzipped during installation, the data files are not installed.
In other words, if I run:
python setup.py bdist_egg
cd dist
sudo easy_install -z EnrichPy-0.1.001-py2.6.egg
then the egg file is installed (with the data safely zipped inside) and everything works.
On the other hand, if I run
sudo easy_install -Z EnrichPy-0.1.001-py2.6.egg
then the data files are not installed. I have a directory called
EnrichPy-0.1.001-py2.6.egg/enrichpy/ under dist-packages, but it contains only my source files, not my data files.
Can anyone suggest what I need to do to get the package_data files to be installed when easy_install unzips the egg file?
Notes:
The package is available at http://github.com/roban/EnrichPy
I can test it by running:
import enrichpy.yields
enrichpy.yields.Data_vdHG().data
If that exits without errors, then pkg_resources is finding the installed data.
A:
Problem solved, thanks to help from P.J. Eby on the distutils-sig email list:
http://mail.python.org/pipermail/distutils-sig/2010-November/017054.html
Just needed to rename files to avoid the '..' string.
| package data not installed from python .egg file | I'm trying to include some data files in a python package using the setuptools package_data option. I'm then accessing the files with pkg_resources. This works perfectly when the python .egg file is installed as-is (i.e. still zipped). But when the egg file is unzipped during installation, the data files are not installed.
In other words, if I run:
python setup.py bdist_egg
cd dist
sudo easy_install -z EnrichPy-0.1.001-py2.6.egg
then the egg file is installed (with the data safely zipped inside) and everything works.
On the other hand, if I run
sudo easy_install -Z EnrichPy-0.1.001-py2.6.egg
then the data files are not installed. I have a directory called
EnrichPy-0.1.001-py2.6.egg/enrichpy/ under dist-packages, but it contains only my source files, not my data files.
Can anyone suggest what I need to do to get the package_data files to be installed when easy_install unzips the egg file?
Notes:
The package is available at http://github.com/roban/EnrichPy
I can test it by running:
import enrichpy.yields
enrichpy.yields.Data_vdHG().data
If that exits without errors, then pkg_resources is finding the installed data.
| [
"Problem solved, thanks to help from P.J. Eby on the distutils-sig email list:\nhttp://mail.python.org/pipermail/distutils-sig/2010-November/017054.html\nJust needed to rename files to avoid the '..' string.\n"
] | [
1
] | [] | [] | [
"python",
"setuptools"
] | stackoverflow_0004043315_python_setuptools.txt |
Q:
How do I extract a long string of text from some JavaScript on a web page using BeautifulSoup?
I'm trying to write a script so I can log into a website, but in order to do that I need to present the captcha. The only way to get that direct image of the captcha from the URL is to extract the giant string name 'challenge' but I have not been able to do it with BeautifulSoup for some reason. What is the best way to extract the long string?
var RecaptchaState = {
site : '4LfjPgEA56AABAJExraAeYXdMbVhPcG__Hyv-URXF',
challenge : '03AHJ_VusE_PgNB0vfBpD2h53o8uGMt1MeKi9bzhOTsjt0ze7SKmHVNe8uADceoU3JLPjpp8cJCVDGiYKo1ho-r1JcV19tm26doUHqevixJjH8SZ26i4EWbUOQLEuODf0Kt6JI0ZhtfiIaIXDg9MhUyDCEt_qxFWbSHA',
is_incorrect : false,
programming_error : '',
error_message : '',
server : 'http://www.google.com/recaptcha/api/',
timeout : 18000
};
document.write('
<scr>
');
</scr>
A:
BeautifulSoup does not parse js, you need to dothis with a regex or similar.
A:
I'd just use a regular expression. Not sure about this, but I don't think beautifulsoup parses javascript--only (x)html:
challenge = re.search(r"challenge *: *'(\S+)'", x).group(1)
Gives:
'03AHJ_VusE_PgNB0vfBpD2h53o8uGMt1MeKi9bzhOTsjt0ze7SKmHVNe8uADceoU3JLPjpp8cJCVDGiYKo1ho-r1JcV19tm26doUHqevixJjH8SZ26i4EWbUOQLEuODf0Kt6JI0ZhtfiIaIXDg9MhUyDCEt_qxFWbSHA'
| How do I extract a long string of text from some JavaScript on a web page using BeautifulSoup? | I'm trying to write a script so I can log into a website, but in order to do that I need to present the captcha. The only way to get that direct image of the captcha from the URL is to extract the giant string name 'challenge' but I have not been able to do it with BeautifulSoup for some reason. What is the best way to extract the long string?
var RecaptchaState = {
site : '4LfjPgEA56AABAJExraAeYXdMbVhPcG__Hyv-URXF',
challenge : '03AHJ_VusE_PgNB0vfBpD2h53o8uGMt1MeKi9bzhOTsjt0ze7SKmHVNe8uADceoU3JLPjpp8cJCVDGiYKo1ho-r1JcV19tm26doUHqevixJjH8SZ26i4EWbUOQLEuODf0Kt6JI0ZhtfiIaIXDg9MhUyDCEt_qxFWbSHA',
is_incorrect : false,
programming_error : '',
error_message : '',
server : 'http://www.google.com/recaptcha/api/',
timeout : 18000
};
document.write('
<scr>
');
</scr>
| [
"BeautifulSoup does not parse js, you need to dothis with a regex or similar.\n",
"I'd just use a regular expression. Not sure about this, but I don't think beautifulsoup parses javascript--only (x)html:\nchallenge = re.search(r\"challenge *: *'(\\S+)'\", x).group(1)\n\nGives: \n'03AHJ_VusE_PgNB0vfBpD2h53o8uGMt1M... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"javascript",
"python"
] | stackoverflow_0004113552_beautifulsoup_javascript_python.txt |
Q:
Escape special character in Django Templates
i'm generating password with letters, digits and special characters ('¿"&$%/\>]{}(=?)*@!<-_¡+[') and i need to escape special character in templates like ASCII symbols, i generate a list of values like this
['0iw0Vqds)*\xc2Ni1P', '<gFLbKi}55(dN[R', '5G<E\\3}+vz72vu{', 'q3ojs$S33rQW$vs', 'IhAV$@3H3uNx\xbfOI', 'uA>>u\\g\xa1vf0\xc2o4t', 'siNyC$JX46bDXZ\xc2', 'R<8\xa1Y{\\]{Wcd/G>', 'D()SuvqdokB\xc2tcR', 'z31LPP{[$n{6_p\xc2']
i my template i do:
{% for var in password_list %}
{{var|escape}}
{% endfor %}
I'm using utf-8 in my views.py (# -- coding: UTF-8 --). and i tried with {{var|escape}} and {{var|escape|safe}} but the templates only show in this case the third element in list (q3ojs$S33rQW$vs)
what can i do??
thanks in advance!
A:
If you're going to be using ¿ and ¡ then you're going to need to be using unicodes instead of strs.
Unicode in Python, Completely Demystified
| Escape special character in Django Templates | i'm generating password with letters, digits and special characters ('¿"&$%/\>]{}(=?)*@!<-_¡+[') and i need to escape special character in templates like ASCII symbols, i generate a list of values like this
['0iw0Vqds)*\xc2Ni1P', '<gFLbKi}55(dN[R', '5G<E\\3}+vz72vu{', 'q3ojs$S33rQW$vs', 'IhAV$@3H3uNx\xbfOI', 'uA>>u\\g\xa1vf0\xc2o4t', 'siNyC$JX46bDXZ\xc2', 'R<8\xa1Y{\\]{Wcd/G>', 'D()SuvqdokB\xc2tcR', 'z31LPP{[$n{6_p\xc2']
i my template i do:
{% for var in password_list %}
{{var|escape}}
{% endfor %}
I'm using utf-8 in my views.py (# -- coding: UTF-8 --). and i tried with {{var|escape}} and {{var|escape|safe}} but the templates only show in this case the third element in list (q3ojs$S33rQW$vs)
what can i do??
thanks in advance!
| [
"If you're going to be using ¿ and ¡ then you're going to need to be using unicodes instead of strs.\nUnicode in Python, Completely Demystified\n"
] | [
3
] | [] | [] | [
"django",
"django_templates",
"encoding",
"python",
"utf_8"
] | stackoverflow_0004113559_django_django_templates_encoding_python_utf_8.txt |
Q:
Turn an AppEngine Blacklist into a Whitelist
AppEngine allows the definition of blacklists, to disallow access from certain IP Ranges (http://code.google.com/appengine/docs/python/config/dos.html).
What I would like to do is the inverse: A whitelist, that only allows access from certain IP Ranges.
I am not much of a network specialist, so I would appreciate some help:
If I wanted to limit access to IPs in the Range from 130.100.120.0 to 130.100.123.255, could that be done using AppEngines blacklist mechanism, or should I do the checking from within my application?
Thanks.
A:
No, the AppEngine blacklist functionality (which is documented here serves more to prevent denial of service attacks and so on. So, the file containing blacklisted IPs can, at most, contain 100 IPs. Thus, the blacklist isn't really intended for industrial strength access control.
Given this, it seems your only option is to do the checking within your application.
A:
Create a Servlet Filter. Something like this:
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// replace with your custom IP checking
if (!req.getRemoteAddr().equals("127.0.0.1")) {
HttpServletResponse response = (HttpServletResponse) servletResponse;
// send any response
response.sendError(404);
}
filterChain.doFilter(req, res);
}
| Turn an AppEngine Blacklist into a Whitelist | AppEngine allows the definition of blacklists, to disallow access from certain IP Ranges (http://code.google.com/appengine/docs/python/config/dos.html).
What I would like to do is the inverse: A whitelist, that only allows access from certain IP Ranges.
I am not much of a network specialist, so I would appreciate some help:
If I wanted to limit access to IPs in the Range from 130.100.120.0 to 130.100.123.255, could that be done using AppEngines blacklist mechanism, or should I do the checking from within my application?
Thanks.
| [
"No, the AppEngine blacklist functionality (which is documented here serves more to prevent denial of service attacks and so on. So, the file containing blacklisted IPs can, at most, contain 100 IPs. Thus, the blacklist isn't really intended for industrial strength access control.\nGiven this, it seems your only op... | [
3,
0
] | [] | [] | [
"blacklist",
"firewall",
"google_app_engine",
"python",
"whitelist"
] | stackoverflow_0004113583_blacklist_firewall_google_app_engine_python_whitelist.txt |
Q:
Importing a *.pyd library in IronPython's interpreter (ipy.exe)
Following this example, I've created a little hello.pyd library file, the contents of which are at the end of this question.
When I enter python interpreter I get the following:
D:\test\build\lib.win32-2.6>C:\Python26\python.exe
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
>>> hello.say_hello("Greg")
Hello Greg!
>>>
But trying this with IronPython's interpreter yields an error:
D:\test\build\lib.win32-2.6>"C:\Program Files (x86)\IronPython 2.7\ipy.exe"
IronPython 2.7 Alpha 1 (2.7.0.1) on .NET 4.0.30319.1
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named hello
>>>
How can I make ipy interpreter accept this C++ compiled library?
hellomodule.cpp
#include "C:\Python26\include\Python.h"
static PyObject* say_hello(PyObject* self, PyObject* args)
{
const char* name;
if (!PyArg_ParseTuple(args, "s", &name))
return NULL;
printf("Hello %s!\n", name);
Py_RETURN_NONE;
}
static PyMethodDef HelloMethods[] =
{
{"say_hello", say_hello, METH_VARARGS, "Greet somebody."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
inithello(void)
{
(void) Py_InitModule("hello", HelloMethods);
}
setup.py
from distutils.core import setup, Extension
module1 = Extension('hello', sources = ['hellomodule.cpp'])
setup (name = 'PackageName',
version = '1.0',
description = 'This is a demo package',
ext_modules = [module1])
Compiled as follows
python setup.py build -cmingw32
A:
You can try using Ironclad, but it hasn't seen much work recently.
A:
The answer is most likely that your .pyd library isn't in the correct path for IronPython to pick it up. Since you used Python and not IronPython's setup tools, it probably got built and setup in the PYTHONPATH rather than where it needs to be for IronPython.
The solution is to a.) change your path for IronPython or b.) rebuild in IronPython's path
| Importing a *.pyd library in IronPython's interpreter (ipy.exe) | Following this example, I've created a little hello.pyd library file, the contents of which are at the end of this question.
When I enter python interpreter I get the following:
D:\test\build\lib.win32-2.6>C:\Python26\python.exe
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
>>> hello.say_hello("Greg")
Hello Greg!
>>>
But trying this with IronPython's interpreter yields an error:
D:\test\build\lib.win32-2.6>"C:\Program Files (x86)\IronPython 2.7\ipy.exe"
IronPython 2.7 Alpha 1 (2.7.0.1) on .NET 4.0.30319.1
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named hello
>>>
How can I make ipy interpreter accept this C++ compiled library?
hellomodule.cpp
#include "C:\Python26\include\Python.h"
static PyObject* say_hello(PyObject* self, PyObject* args)
{
const char* name;
if (!PyArg_ParseTuple(args, "s", &name))
return NULL;
printf("Hello %s!\n", name);
Py_RETURN_NONE;
}
static PyMethodDef HelloMethods[] =
{
{"say_hello", say_hello, METH_VARARGS, "Greet somebody."},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC
inithello(void)
{
(void) Py_InitModule("hello", HelloMethods);
}
setup.py
from distutils.core import setup, Extension
module1 = Extension('hello', sources = ['hellomodule.cpp'])
setup (name = 'PackageName',
version = '1.0',
description = 'This is a demo package',
ext_modules = [module1])
Compiled as follows
python setup.py build -cmingw32
| [
"You can try using Ironclad, but it hasn't seen much work recently.\n",
"The answer is most likely that your .pyd library isn't in the correct path for IronPython to pick it up. Since you used Python and not IronPython's setup tools, it probably got built and setup in the PYTHONPATH rather than where it needs to ... | [
3,
0
] | [] | [] | [
"c++",
"ironpython",
"python",
"python_extensions"
] | stackoverflow_0004113643_c++_ironpython_python_python_extensions.txt |
Q:
Hadoop/Elastic Map Reduce with binary executable?
I am writing and distributed image processing application using hadoop streaming, python, matlab, and elastic map reduce. I have compiled a binary executable of my matlab code using the matlab compiler. I am wondering how I can incorporate this into my workflow so the binary is part of the processing on Amazon's elastic map reduce?
It looks like I have to use the Hadoop Distributed Cache?
The code is very complicated (and not written by me) so porting it to another language is not possible right now.
THanks
A:
The following is not exactly an answer to your Hadoop question, but I couldn't resist not asking why you don't execute your processing jobs on the Grid resources? There are proven solutions for executing compute intensive workflows on the Grid. And as far as I know matlab runtime environment is usually available on these resources. You may also consider using the Grid especially if you are in academia.
Good luck
A:
Joseph,
I've just asked a similar, but more general version of your question. Hopefully we'll get some answers. ;)
Hadoop Streaming: Mapper 'wrapping' a binary executable
Nick
| Hadoop/Elastic Map Reduce with binary executable? | I am writing and distributed image processing application using hadoop streaming, python, matlab, and elastic map reduce. I have compiled a binary executable of my matlab code using the matlab compiler. I am wondering how I can incorporate this into my workflow so the binary is part of the processing on Amazon's elastic map reduce?
It looks like I have to use the Hadoop Distributed Cache?
The code is very complicated (and not written by me) so porting it to another language is not possible right now.
THanks
| [
"The following is not exactly an answer to your Hadoop question, but I couldn't resist not asking why you don't execute your processing jobs on the Grid resources? There are proven solutions for executing compute intensive workflows on the Grid. And as far as I know matlab runtime environment is usually available o... | [
0,
0
] | [] | [] | [
"amazon_web_services",
"hadoop",
"mapreduce",
"matlab",
"python"
] | stackoverflow_0004101815_amazon_web_services_hadoop_mapreduce_matlab_python.txt |
Q:
python psycogp2 inserting into postgresql help
I have the following code to insert do an insert into my postgresql database
conn = psycopg2.connect("my connection setting are in here")
cur = conn.cursor()
cur.execute('INSERT INTO src_event (location_id, catname, title, name) VALUES (%i, \"%s\", \"%s\", \"%s\")' % (1441, "concert", item['title'], item['artists'] ))
However when I run this I get the following error:
psycopg2.ProgrammingError: column "concert" does not exist
LINE 1: ...(location_id, catname, title, name) VALUES (1441, concert, "...
But "concert" is not a column it is a value so I dont understand why I am getting this error.
EDIT - I have tried putting \" round the value concert and tried without
How can I get my data inserted with out getting this error?
A:
You really, really shouldn't use python string formatting to build queries - they are prone to SQL injection. And your actual problem is that you use " for quoting while you have to use ' for quoting (" quotes table/column names etc, ' quotes strings).
Use the following code instead:
cur.execute('INSERT INTO src_event (location_id, catname, title, name) VALUES (%s, %s, %s, %s)', (1441, 'concert', item['title'], item['artists']))
Note that you have to use %s no matter what type you actually have.
Also see http://initd.org/psycopg/docs/usage.html#query-parameters.
| python psycogp2 inserting into postgresql help | I have the following code to insert do an insert into my postgresql database
conn = psycopg2.connect("my connection setting are in here")
cur = conn.cursor()
cur.execute('INSERT INTO src_event (location_id, catname, title, name) VALUES (%i, \"%s\", \"%s\", \"%s\")' % (1441, "concert", item['title'], item['artists'] ))
However when I run this I get the following error:
psycopg2.ProgrammingError: column "concert" does not exist
LINE 1: ...(location_id, catname, title, name) VALUES (1441, concert, "...
But "concert" is not a column it is a value so I dont understand why I am getting this error.
EDIT - I have tried putting \" round the value concert and tried without
How can I get my data inserted with out getting this error?
| [
"You really, really shouldn't use python string formatting to build queries - they are prone to SQL injection. And your actual problem is that you use \" for quoting while you have to use ' for quoting (\" quotes table/column names etc, ' quotes strings).\nUse the following code instead:\ncur.execute('INSERT INTO s... | [
13
] | [] | [] | [
"postgresql",
"psycopg2",
"python",
"sql"
] | stackoverflow_0004113910_postgresql_psycopg2_python_sql.txt |
Q:
8 Character Random Code
I've been through answers to a few similar questions asked on SO, but could not find what I was looking for.
Is there a more efficient way to generate 8 character unique IDs, base 36 (0-9A-Z), than generating a unique ID and querying the DB to see if it already exists and repeating until you get a unique ID that has not been used?
Other solutions I found use time, but this is perhaps too easy to guess and may not work well in distributed systems. Consider these IDs to be promo codes.
A:
One option is to do it the other way round: generate a huge number of them in the database whenever you need to, then either fetch a single one from the DB when you need one, or reserve a whole bunch of them for your particular process (i.e. mark them as "potentially used" in the database) and then dole them out from memory.
A:
I question that your "inefficient" approach is actually inefficient. Consider this:
There are 36^8 == 2,821,109,907,456 (2.8 Trillion) possible IDs.
If you have N existing IDs, the chance of a new randomly generated ID colliding is N in ~2.8 trillion.
Unless N is in the hundreds of billions, you "generate a unique ID and querying the DB to see if it already exists" algorithm will almost always terminate in one cycle.
With careful design, you should be able to generate a guaranteed unique ID in one database request, almost all of the time ... unless you have an awfully large number of existing IDs. (And if you do, just add another couple of characters to the ID and the problem goes away again.)
If you want to, you can reduce the average number of database operations to less than one per ID by generating the IDs in batches, but their are potential complications, especially if you need to record the number of IDs that are actually in use.
But, if you have at most 150,000 IDs (I assume, generated over a long period of time) then creating the IDs in batches is not worth the effort ... unless you are doing a bulk upload operation.
A:
Unfortunately, 8 base 36 digits is a bit small. It's only 2 million million possible IDs, so if you generate 1.4 million randomly you have about a half chance of a collision.
You could possibly use a PRNG with a large period, and map its current state to your ID space via some bijection. A 41 bit LFSR wouldn't be uncrackable, but might be reasonably OK if the thing you're protecting isn't all that valuable. You could distribute somewhat without having to access the DB all the time, by providing different nodes with a different position to start the cycle.
The trouble with any such deterministic method, of course, is that once it's broken it's completely broken, and you can no longer trust any IDs. So doling numbers out of a database is probably the way to go, and distribute by doling them out in batches of a thousand or whatever.
If you had a larger ID space, then you could use more secure techniques, for example the ID could consist of something to identify the source, an incrementing serial number for that source, and an HMAC using a key unique to the source.
A:
If there is only one source of IDs (that is: you don't need to coordinate multiple independent sources on different machines) you can do the following:
Calculate the maximum number of bits that a number may have so that it doesn't exceed the information contained in an 8-symbol string of 0-9A-Z. This would be floor(log2(36^8)) = 41 bits.
Have a counter (with 41 bits) start at zero
Return transform(counter++) for each ID request
The transform function has to be bijective and can be an arbitrarily long sequence of the following operations (which are all bijective themselves when they are calculated modulo 2^41):
xor with a fixed value
rotate left or right by a fixed value
reorder the bits by a fixed mapping (a generalization of the rotation above)
add or subtract a fixed value
When you are finished with that, you only need another function encode(number) to transform the number to base36.
A:
Here's some python code for generating random, base36 IDs.
import random
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
'''
Convert positive integer to a base36 string.
Source: http://en.wikipedia.org/wiki/Base_36#Python_Conversion_Code
'''
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
# Special case for zero
if number == 0:
return '0'
base36 = ''
sign = ""
if number < 0:
sign ='-'
number=-number
while number != 0:
number, i = divmod(number, len(alphabet))
base36 = alphabet[i] + base36
return sign + base36
def generateID(length=8):
'''Generates a base36 ID.'''
random.seed()
id = base36encode(random.randint(0, (36**length)-1))
# append 0s to ensure desired length
while len(id) < length:
id = '0' + id
return id
def generateMultipleIDs(n):
'''Generate n number of unique, base36 IDs.'''
output = set()
while len(output) < n:
output.add(generateID())
return output
A:
I once solved a similar problem using C++ involving a smaller number of possible IDs, but there might be useful to consider some ways to scale it up. Basically I created a big bitmap for all the possible IDs and would just lookup whether one was in use by testing the proper bit for it.
To minimize RAM requirements, I stored the bitmap in a raw binary file and used random-access file i/o to seek to the byte with the corresponding bit in it I needed to check and/or set.
Your much larger ID space would require a 328 GB bitmap, which is likely out of the question. On the other hand, a Python set of the used IDs might be acceptable, depending on how many IDs you think might actually end up being used. Other alternatives might be some sort of sparse file or sparse matrix technique, such as those in scipy.sparse.
Hope this helps.
A:
I do something similar to generate activation codes: 8-letter lowercase strings that are single-use. They are intended to be used within a short time of being generated (usually within minutes, but possibly not for up to a week), but must be unique. When they have been used, they are removed from the database.
I just generate a value and see if it is in use in the database. This works for now, because there are not heaps of unused codes sitting in the database, but are still not easy to guess, even if you have been provided with one.
As for the generation code:
def _generate_code(self, length):
random.seed()
candidates = string.lowercase[:26]
result = ""
for i in range(length):
result += random.choice(candidates)
return result
A:
Does it need to be cryptographically secure?
If not, pc(n) = a + bn, where b is prime relative to 36^8 will do. Use an array of byte.
foo(int n, byte[] a, byte[] b) {
byte[] r = new byte[8];
int carry=0;
for(int i = 0; i<8;i++) {
int x = carry + a[i] + n*b[i];
r[i] = x % 36;
carry = x / 36;
}
}
| 8 Character Random Code | I've been through answers to a few similar questions asked on SO, but could not find what I was looking for.
Is there a more efficient way to generate 8 character unique IDs, base 36 (0-9A-Z), than generating a unique ID and querying the DB to see if it already exists and repeating until you get a unique ID that has not been used?
Other solutions I found use time, but this is perhaps too easy to guess and may not work well in distributed systems. Consider these IDs to be promo codes.
| [
"One option is to do it the other way round: generate a huge number of them in the database whenever you need to, then either fetch a single one from the DB when you need one, or reserve a whole bunch of them for your particular process (i.e. mark them as \"potentially used\" in the database) and then dole them out... | [
10,
7,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"algorithm",
"database",
"java",
"python",
"unique"
] | stackoverflow_0004102409_algorithm_database_java_python_unique.txt |
Q:
.pyc files and naive encryption
I have a fairly naive thing I want to do and I want to know if someone can answer can tell me if this is just flat out stupid. If what I am going to ask is not stupid but perhaps naive, I'd appreciate if I can get a nudge in a correct direction.
I have a file named pwds.py. Its contents are
import hashlib
class Pwds:
def __init__(self):
pass
def printGood(self,key):
y = hashlib.sha1()
y.update(key.encode('ascii'))
if y.hexdigest() == "db5f60442c78f08eefb0a2efeaa860b071c4cdae":
print("You entered the correct key!")
else:
print("Intruder!")
Then I have another file named runme.py, whose contents are
import pwds
x = input("Please type the password: ")
y = pwds.Pwds()
y.printGood(x)
x = input("Press any key to end")
The first time runme.py is run, a pwds.pyc file is created. My thought was that once the .pyc file was created, I could delete pwds.py and run runme.py as normal. Additionally, I thought the contents of pwds.py would be contained in .pyc but made unreadable since this is a "compiled" Python file. Thus, while I can delete pwds.py and successfully run runme.py, pwds.pyc is pretty much readable if I open it in, say, Notepad.
Thus, the question(s) in general: How can I keep the contents of pwds.py unreadable? What I wanted to do with the above code was to keep "secret" information in a Python file, compile it, and have its contents be accessible only if the correct key were typed. Is this approach too stupid to even consider? I didn't want to get into writing a "garbler" and a "degarbler". I thought this would be a simple and cheap solution.
Thanks for reading this! Please let me know if there is any other information I should provide.
A:
The .pyc file simply contains the compiled python code so it doesn't need to be recompiled everytime you run your program. Thus all strings in it are still readable (you could always look at the binary contents or step through the program via the pdb debugger).
If you want to protect something in your code with a password, you have to encrypt it with strong encryption and only store the encrypted version. The users's key/password is then used to decrypt the data.
| .pyc files and naive encryption | I have a fairly naive thing I want to do and I want to know if someone can answer can tell me if this is just flat out stupid. If what I am going to ask is not stupid but perhaps naive, I'd appreciate if I can get a nudge in a correct direction.
I have a file named pwds.py. Its contents are
import hashlib
class Pwds:
def __init__(self):
pass
def printGood(self,key):
y = hashlib.sha1()
y.update(key.encode('ascii'))
if y.hexdigest() == "db5f60442c78f08eefb0a2efeaa860b071c4cdae":
print("You entered the correct key!")
else:
print("Intruder!")
Then I have another file named runme.py, whose contents are
import pwds
x = input("Please type the password: ")
y = pwds.Pwds()
y.printGood(x)
x = input("Press any key to end")
The first time runme.py is run, a pwds.pyc file is created. My thought was that once the .pyc file was created, I could delete pwds.py and run runme.py as normal. Additionally, I thought the contents of pwds.py would be contained in .pyc but made unreadable since this is a "compiled" Python file. Thus, while I can delete pwds.py and successfully run runme.py, pwds.pyc is pretty much readable if I open it in, say, Notepad.
Thus, the question(s) in general: How can I keep the contents of pwds.py unreadable? What I wanted to do with the above code was to keep "secret" information in a Python file, compile it, and have its contents be accessible only if the correct key were typed. Is this approach too stupid to even consider? I didn't want to get into writing a "garbler" and a "degarbler". I thought this would be a simple and cheap solution.
Thanks for reading this! Please let me know if there is any other information I should provide.
| [
"The .pyc file simply contains the compiled python code so it doesn't need to be recompiled everytime you run your program. Thus all strings in it are still readable (you could always look at the binary contents or step through the program via the pdb debugger).\nIf you want to protect something in your code with a... | [
2
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0004113987_encryption_python.txt |
Q:
What would be the proper way of handling arguments for a method that could be ints or chars in python?
For example, I want to have a method that, depending on the first argument passed, can take either an int or a char as the second argument.
The way I thought of doing it is to have an if right after the method it calls to check what the first argument is, it can be one of 4. At this point, if it's of say, type 1 or 2 that expects an int as the second argument, it completes the code within the if. I then have an elif checking if the first argument is of type 3 or 4, then it goes into that block and completes the code within that block. The else will throw an exception or handle the issue accordingly.
Is this the right way to do it?
A:
You better have two different methods if inner code is different in both cases.
A:
If the code is same, with some transformation of parameteres (getting ASCII value of char for example - btw, char in python is just a string with length of 1), you should do the cast at the start of function and the rest of the code should be the same. For example:
def foo(a, b):
if a == 1:
b = ord(b)
# use b as if it is integer
If the rest of the code is totaly different you sholud be writing different functions and not trying to squeeze it in one.
| What would be the proper way of handling arguments for a method that could be ints or chars in python? | For example, I want to have a method that, depending on the first argument passed, can take either an int or a char as the second argument.
The way I thought of doing it is to have an if right after the method it calls to check what the first argument is, it can be one of 4. At this point, if it's of say, type 1 or 2 that expects an int as the second argument, it completes the code within the if. I then have an elif checking if the first argument is of type 3 or 4, then it goes into that block and completes the code within that block. The else will throw an exception or handle the issue accordingly.
Is this the right way to do it?
| [
"You better have two different methods if inner code is different in both cases.\n",
"If the code is same, with some transformation of parameteres (getting ASCII value of char for example - btw, char in python is just a string with length of 1), you should do the cast at the start of function and the rest of the ... | [
1,
0
] | [] | [] | [
"arguments",
"python"
] | stackoverflow_0004114055_arguments_python.txt |
Q:
ValueError when using Whoosh and Django Haystack
I'm trying to set up Haystack with Whoosh but am getting this value error "ValueError: dictionary update sequence element #0 has length 9; 2 is required" when I run the count method on the SearchQuerySet object in ./manage shell
>>> sqs.count()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/haystack/query.py", line 375, in count
return len(clone)
File "/usr/local/lib/python2.6/dist-packages/haystack/query.py", line 48, in __len__
self._result_count = self.query.get_count()
File "/usr/local/lib/python2.6/dist-packages/haystack/backends/__init__.py", line 399, in get_count
self.run()
File "/usr/local/lib/python2.6/dist-packages/haystack/backends/__init__.py", line 354, in run
results = self.backend.search(final_query, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/haystack/backends/__init__.py", line 47, in wrapper
return func(obj, query_string, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/haystack/backends/whoosh_backend.py", line 313, in search
return self._process_results(raw_results, start_offset, end_offset, highlight=highlight, query_string=query_string, spelling_query=spelling_query)
File "/usr/local/lib/python2.6/dist-packages/haystack/backends/whoosh_backend.py", line 350, in _process_results
raw_result = dict(raw_result)
ValueError: dictionary update sequence element #0 has length 9; 2 is required
A:
Found my answer here https://github.com/toastdriven/django-haystack/issues/closed#issue/281 It turns out it was a version problem.
It works if I use these specific versions of Haystack and Whoosh
pip install django-haystack==1.0.1-final
easy_install "Whoosh==1.0.0.b11"
| ValueError when using Whoosh and Django Haystack | I'm trying to set up Haystack with Whoosh but am getting this value error "ValueError: dictionary update sequence element #0 has length 9; 2 is required" when I run the count method on the SearchQuerySet object in ./manage shell
>>> sqs.count()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/haystack/query.py", line 375, in count
return len(clone)
File "/usr/local/lib/python2.6/dist-packages/haystack/query.py", line 48, in __len__
self._result_count = self.query.get_count()
File "/usr/local/lib/python2.6/dist-packages/haystack/backends/__init__.py", line 399, in get_count
self.run()
File "/usr/local/lib/python2.6/dist-packages/haystack/backends/__init__.py", line 354, in run
results = self.backend.search(final_query, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/haystack/backends/__init__.py", line 47, in wrapper
return func(obj, query_string, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/haystack/backends/whoosh_backend.py", line 313, in search
return self._process_results(raw_results, start_offset, end_offset, highlight=highlight, query_string=query_string, spelling_query=spelling_query)
File "/usr/local/lib/python2.6/dist-packages/haystack/backends/whoosh_backend.py", line 350, in _process_results
raw_result = dict(raw_result)
ValueError: dictionary update sequence element #0 has length 9; 2 is required
| [
"Found my answer here https://github.com/toastdriven/django-haystack/issues/closed#issue/281 It turns out it was a version problem.\nIt works if I use these specific versions of Haystack and Whoosh\npip install django-haystack==1.0.1-final\n\neasy_install \"Whoosh==1.0.0.b11\"\n\n"
] | [
2
] | [] | [] | [
"django",
"django_haystack",
"python",
"whoosh"
] | stackoverflow_0004114040_django_django_haystack_python_whoosh.txt |
Q:
How can I store files on Google Storage, but skip the GAE part for fetching them?
I like Google App Engine for the Datastore (and the fact that I can develop in Python) but they have 1MB limits on fetching and uploading files. On the other hand it wasn't made for that I guess.
I managed to create a service that is getting a URL (or a file from user), fetching it on GAE and then putting it on Google Storage. Works perfectly fine, but for files that are less than 1MB. There are workarounds of course, but I think it should be feasible to do it faster by skipping the GAE for data retrieval.
So my question is: Is it possible to keep my datastore on GAE and by knowing only the URL (or a special form to upload files) create the headers and then letting Google Storage to fetch the file and store it without the 1MB limit?
A:
No. Google Storage doesn't support fetching the file for you.
A:
It doesn't matter where the file is stored. Not only is there a 1MB datastore entity size limit, but there is a 1MB in-memory datastructure limit. So even if you stored the file somewhere else, you would have to split it into pieces to be able to operate on it on the app engine.
For Java on the GAE, I suggest looking at gaevfs (http://code.google.com/p/gaevfs/). It turns the app engine datastore into a filesystem that can store files of arbitrary size and operate on them just as normal files.
| How can I store files on Google Storage, but skip the GAE part for fetching them? | I like Google App Engine for the Datastore (and the fact that I can develop in Python) but they have 1MB limits on fetching and uploading files. On the other hand it wasn't made for that I guess.
I managed to create a service that is getting a URL (or a file from user), fetching it on GAE and then putting it on Google Storage. Works perfectly fine, but for files that are less than 1MB. There are workarounds of course, but I think it should be feasible to do it faster by skipping the GAE for data retrieval.
So my question is: Is it possible to keep my datastore on GAE and by knowing only the URL (or a special form to upload files) create the headers and then letting Google Storage to fetch the file and store it without the 1MB limit?
| [
"No. Google Storage doesn't support fetching the file for you.\n",
"It doesn't matter where the file is stored. Not only is there a 1MB datastore entity size limit, but there is a 1MB in-memory datastructure limit. So even if you stored the file somewhere else, you would have to split it into pieces to be able to... | [
1,
1
] | [] | [] | [
"google_app_engine",
"google_cloud_storage",
"python"
] | stackoverflow_0004112903_google_app_engine_google_cloud_storage_python.txt |
Q:
lxml can't parse ?
I want to parse tables in html, but i found lxml can't parse it? what's wrong?
# -*- coding: utf8 -*-
import urllib
import lxml.etree
keyword = 'lxml+tutorial'
url = 'http://www.baidu.com/s?wd='
if __name__ == '__main__':
page = 0
link = url + keyword + '&pn=' + str(page)
f = urllib.urlopen(link)
content = f.read()
f.close()
tree = lxml.etree.HTML(content)
query_link = '//table'
info_link = tree.xpath(query_link)
print info_link
the print result is just []...
A:
lxml's documentation says, "The support for parsing broken HTML depends entirely on libxml2's recovery algorithm. It is not the fault of lxml if you find documents that are so heavily broken that the parser cannot handle them. There is also no guarantee that the resulting tree will contain all data from the original document. The parser may have to drop seriously broken parts when struggling to keep parsing."
And sure enough, the HTML returned by Baidu is invalid: the W3C validator reports "173 Errors, 7 warnings". I don't know (and haven't investigated) whether these particular errors have caused your trouble with lxml, because I think that your strategy of using lxml to parse HTML found "in the wild" (which is nearly always invalid) is doomed.
For parsing invalid HTML, you need a parser that implements the (surprisingly bizarre!) HTML error recovery algorithm. So I recommend swapping lxml for html5lib, which handles Baidu's invalid HTML with no problems:
>>> import urllib
>>> from html5lib import html5parser, treebuilders
>>> p = html5parser.HTMLParser(tree = treebuilders.getTreeBuilder('dom'))
>>> dom = p.parse(urllib.urlopen('http://www.baidu.com/s?wd=foo').read())
>>> len(dom.getElementsByTagName('table'))
12
A:
I see several places that code could be improved but, for your question, here are my suggestions:
Use lxml.html.parse(link) rather than lxml.etree.HTML(content) so all the "just works" automatics can kick in. (eg. Handling character coding declarations in headers properly)
Try using tree.findall(".//table") rather than tree.xpath("//table"). I'm not sure whether it'll make a difference, but I just used that syntax in a project of my own a few hours ago without issue and, as a bonus, it's compatible with non-LXML ElementTree APIs.
The other major thing I'd suggest would be using Python's built-in functions for building URLs so you can be sure the URL you're building is valid and properly escaped in all circumstances.
If LXML can't find a table and the browser shows a table to exist, I can only imagine it's one of these three problems:
Bad request. LXML gets a page without a table in it. (eg. error 404 or 500)
Bad parsing. Something about the page confused lxml.etree.HTML when called directly.
Javascript needed. Maybe the table is generated client-side.
| lxml can't parse ? | I want to parse tables in html, but i found lxml can't parse it? what's wrong?
# -*- coding: utf8 -*-
import urllib
import lxml.etree
keyword = 'lxml+tutorial'
url = 'http://www.baidu.com/s?wd='
if __name__ == '__main__':
page = 0
link = url + keyword + '&pn=' + str(page)
f = urllib.urlopen(link)
content = f.read()
f.close()
tree = lxml.etree.HTML(content)
query_link = '//table'
info_link = tree.xpath(query_link)
print info_link
the print result is just []...
| [
"lxml's documentation says, \"The support for parsing broken HTML depends entirely on libxml2's recovery algorithm. It is not the fault of lxml if you find documents that are so heavily broken that the parser cannot handle them. There is also no guarantee that the resulting tree will contain all data from the origi... | [
3,
2
] | [] | [] | [
"lxml",
"parsing",
"python",
"web_crawler"
] | stackoverflow_0004093745_lxml_parsing_python_web_crawler.txt |
Q:
Pythonic way to select list elements with different probability
import random
pos = ["A", "B", "C"]
x = random.choice["A", "B", "C"]
This code gives me either "A", "B" or "C" with equal probability.
Is there a nice way to express it when you want "A" with 30%, "B" with 40% and "C" with 30% probability?
A:
Weights define a probability distribution function (pdf). Random numbers from any such pdf can be generated by applying its associated inverse cumulative distribution function to uniform random numbers between 0 and 1.
See also this SO explanation, or, as explained by Wikipedia:
If Y has a U[0,1] distribution then F⁻¹(Y) is distributed as F. This is
used in random number generation using
the inverse transform sampling-method.
import random
import bisect
import collections
def cdf(weights):
total = sum(weights)
result = []
cumsum = 0
for w in weights:
cumsum += w
result.append(cumsum / total)
return result
def choice(population, weights):
assert len(population) == len(weights)
cdf_vals = cdf(weights)
x = random.random()
idx = bisect.bisect(cdf_vals, x)
return population[idx]
weights=[0.3, 0.4, 0.3]
population = 'ABC'
counts = collections.defaultdict(int)
for i in range(10000):
counts[choice(population, weights)] += 1
print(counts)
# % test.py
# defaultdict(<type 'int'>, {'A': 3066, 'C': 2964, 'B': 3970})
The choice function above uses bisect.bisect, so selection of a weighted random variable is done in O(log n) where n is the length of weights.
Note that as of version 1.7.0, NumPy has a Cythonized np.random.choice function. For example, this generates 1000 samples from the population [0,1,2,3] with weights [0.1, 0.2, 0.3, 0.4]:
import numpy as np
np.random.choice(4, 1000, p=[0.1, 0.2, 0.3, 0.4])
np.random.choice also has a replace parameter for sampling with or without replacement.
A theoretically better algorithm is the Alias Method. It builds a table which requires O(n) time, but after that, samples can be drawn in O(1) time. So, if you need to draw many samples, in theory the Alias Method may be faster. There is a Python implementation of the Walker Alias Method here, and a numpy version here.
A:
Not... so much...
pos = ['A'] * 3 + ['B'] * 4 + ['C'] * 3
print random.choice(pos)
or
pos = {'A': 3, 'B': 4, 'C': 3}
print random.choice([x for x in pos for y in range(pos[x])])
A:
Here's a class to expose a bunch of items with relative probabilities, without actually expanding the list:
import bisect
class WeightedTuple(object):
"""
>>> p = WeightedTuple({'A': 2, 'B': 1, 'C': 3})
>>> len(p)
6
>>> p[0], p[1], p[2], p[3], p[4], p[5]
('A', 'A', 'B', 'C', 'C', 'C')
>>> p[-1], p[-2], p[-3], p[-4], p[-5], p[-6]
('C', 'C', 'C', 'B', 'A', 'A')
>>> p[6]
Traceback (most recent call last):
...
IndexError
>>> p[-7]
Traceback (most recent call last):
...
IndexError
"""
def __init__(self, items):
self.indexes = []
self.items = []
next_index = 0
for key in sorted(items.keys()):
val = items[key]
self.indexes.append(next_index)
self.items.append(key)
next_index += val
self.len = next_index
def __getitem__(self, n):
if n < 0:
n = self.len + n
if n < 0 or n >= self.len:
raise IndexError
idx = bisect.bisect_right(self.indexes, n)
return self.items[idx-1]
def __len__(self):
return self.len
Now, just say:
data = WeightedTuple({'A': 30, 'B': 40, 'C': 30})
random.choice(data)
A:
As of Python 3.6, there is random.choices for that.
original answer from 2010:
You can also make use this form, which does not create a list arbitrarily big (and can work with either integral or decimal probabilities):
pos = [("A", 30), ("B", 40), ("C", 30)]
from random import uniform
def w_choice(seq):
total_prob = sum(item[1] for item in seq)
chosen = random.uniform(0, total_prob)
cumulative = 0
for item, probality in seq:
cumulative += probality
if cumulative > chosen:
return item
A:
There are some good solutions offered here, but I would suggest that you look at Eli Bendersky's thorough discussion of this issue, which compares various algorithms to achieve this (with implementations in Python) before choosing one.
A:
Try this:
import random
from decimal import Decimal
pos = {'A': Decimal("0.3"), 'B': Decimal("0.4"), 'C': Decimal("0.3")}
choice = random.random()
F_x = 0
for k, p in pos.iteritems():
F_x += p
if choice <= F_x:
x = k
break
| Pythonic way to select list elements with different probability | import random
pos = ["A", "B", "C"]
x = random.choice["A", "B", "C"]
This code gives me either "A", "B" or "C" with equal probability.
Is there a nice way to express it when you want "A" with 30%, "B" with 40% and "C" with 30% probability?
| [
"Weights define a probability distribution function (pdf). Random numbers from any such pdf can be generated by applying its associated inverse cumulative distribution function to uniform random numbers between 0 and 1.\nSee also this SO explanation, or, as explained by Wikipedia:\n\nIf Y has a U[0,1] distribution ... | [
52,
30,
9,
8,
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0004113307_python.txt |
Q:
what is a quick way to delete all elements from a list that do not satisfy a constraint?
I have a list of strings. I have a function that given a string returns 0 or 1. How can I delete all strings in the list for which the function returns 0?
A:
[x for x in lst if fn(x) != 0]
This is a "list comprehension", one of Python's nicest pieces of syntactical sugar that often takes lines of code in other languages and additional variable declarations, etc.
See:
http://docs.python.org/tutorial/datastructures.html#list-comprehensions
A:
I would use a generator expression over a list comprehension to avoid a potentially large, intermediate list.
result = (x for x in l if f(x))
# print it, or something
print list(result)
Like a list comprehension, this will not modify your original list, in place.
A:
edit: see the bottom for the best answer.
If you need to mutate an existing list, for example because you have another reference to it somewhere else, you'll need to actually remove the values from the list.
I'm not aware of any such function in Python, but something like this would work (untested code):
def cull_list(lst, pred):
"""Removes all values from ``lst`` which for which ``pred(v)`` is false."""
def remove_all(v):
"""Remove all instances of ``v`` from ``lst``"""
try:
while True:
lst.remove(v)
except ValueError:
pass
values = set(lst)
for v in values:
if not pred(v):
remove_all(v)
A probably more-efficient alternative that may look a bit too much like C code for some people's taste:
def efficient_cull_list(lst, pred):
end = len(lst)
i = 0
while i < end:
if not pred(lst[i]):
del lst[i]
end -= 1
else:
i += 1
edit...: as Aaron pointed out in the comments, this can be done much more cleanly with something like
def reversed_cull_list(lst, pred):
for i in range(len(lst) - 1, -1, -1):
if not pred(lst[i]):
del lst[i]
...edit
The trick with these routines is that using a function like enumerate, as suggested by (an) other responder(s), will not take into account the fact that elements of the list have been removed. The only way (that I know of) to do that is to just track the index manually instead of allowing python to do the iteration. There's bound to be a speed compromise there, so it may end up being better just to do something like
lst[:] = (v for v in lst if pred(v))
Actually, now that I think of it, this is by far the most sensible way to do an 'in-place' filter on a list. The generator's values are iterated before filling lst's elements with them, so there are no index conflict issues. If you want to make this more explicit just do
lst[:] = [v for v in lst if pred(v)]
I don't think it will make much difference in this case, in terms of efficiency.
Either of these last two approaches will, if I understand correctly how they actually work, make an extra copy of the list, so one of the bona fide in-place solutions mentioned above would be better if you're dealing with some "huge tracts of land."
A:
>>> s = [1, 2, 3, 4, 5, 6]
>>> def f(x):
... if x<=2: return 0
... else: return 1
>>> for n,x in enumerate(s):
... if f(x) == 0: s[n]=None
>>> s=filter(None,s)
>>> s
[3, 4, 5, 6]
A:
With a generator expression:
alist[:] = (item for item in alist if afunction(item))
Functional:
alist[:] = filter(afunction, alist)
or:
import itertools
alist[:] = itertools.ifilter(afunction, alist)
All equivalent.
You can also use a list comprehension:
alist = [item for item in alist if afunction(item)]
An in-place modification:
import collections
indexes_to_delete= collections.deque(
idx
for idx, item in enumerate(alist)
if afunction(item))
while indexes_to_delete:
del alist[indexes_to_delete.pop()]
| what is a quick way to delete all elements from a list that do not satisfy a constraint? | I have a list of strings. I have a function that given a string returns 0 or 1. How can I delete all strings in the list for which the function returns 0?
| [
"[x for x in lst if fn(x) != 0]\n\nThis is a \"list comprehension\", one of Python's nicest pieces of syntactical sugar that often takes lines of code in other languages and additional variable declarations, etc.\nSee: \nhttp://docs.python.org/tutorial/datastructures.html#list-comprehensions\n",
"I would use a ge... | [
7,
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003895424_python.txt |
Q:
how to get the full contents of a node using xpath & lxml?
I am using lxml's xpath function to retrieve parts of a webpage. I am trying to get contents of a <font> tag, which includes html tags of its own. If I use
//td[@valign="top"]/p[1]/font[@face="verdana" and @color="#ffffff" and @size="2"]
I get the right amount of nodes, but they are returned as lxml objects (<Element font at 0x101fe5eb0>).
If I use
//td[@valign="top"]/p[1]/font[@face="verdana" and @color="#ffffff" and @size="2"]/text()
I get exactly what I want, except that I don't get any of the HTML code which is contained within the <font> nodes.
If I use
//td[@valign="top"]/p[1]/font[@face="verdana" and @color="#ffffff" and @size="2"]/node()
if get a mixture of text and lxml elements! (e.g. something something <Element a at 0x102ac2140> something)
Is there anyway to use a pure XPath query to get the contents of the <font> nodes, or even to force lxml to return a string of the contents from the .xpath() method, rather than an lxml object?
Note that I'm returning a list of many nodes from the XPath query so the solution needs to support that.
just to clarify... i want to return something something <a href="url">inside</a> something from something like...
<font face="verdana" color="#ffffff" size="2"><a href="url">inside</a> something</font>
A:
I'm not sure I understand -- is this close to what you are looking for?
import lxml.etree as le
import cStringIO
content='''\
<font face="verdana" color="#ffffff" size="2"><a href="url">inside</a> something</font>
'''
doc=le.parse(cStringIO.StringIO(content))
xpath='//font[@face="verdana" and @color="#ffffff" and @size="2"]/child::*'
x=doc.xpath(xpath)
print(map(le.tostring,x))
# ['<a href="url">inside</a> something']
A:
Is there anyway to use a pure XPath
query to get the contents of the
<font> nodes, or even to force lxml
to return a string of the contents
from the .xpath() method, rather
than an lxml object?
Note that I'm returning a list of many
nodes from the XPath query so the
solution needs to support that.
just to clarify... i want to return
something something <a
href="url">inside</a> something from
something like...
<font face="verdana" color="#ffffff" size="2"><a
href="url">inside something
Short answer: No.
XPath doesn't work on "tags" but with nodes
The selected nodes are represented as instances of specific objects in the language that is hosting XPath.
In case you need the string representation of a particular node's markup, such objects typically support an outerXML property -- check the documentation of the hosting language (lxml in this case).
As @Robert-Rossney pointed out in his comment: lxml's tostring() method is equivalent to other environments' outerXml property.
| how to get the full contents of a node using xpath & lxml? | I am using lxml's xpath function to retrieve parts of a webpage. I am trying to get contents of a <font> tag, which includes html tags of its own. If I use
//td[@valign="top"]/p[1]/font[@face="verdana" and @color="#ffffff" and @size="2"]
I get the right amount of nodes, but they are returned as lxml objects (<Element font at 0x101fe5eb0>).
If I use
//td[@valign="top"]/p[1]/font[@face="verdana" and @color="#ffffff" and @size="2"]/text()
I get exactly what I want, except that I don't get any of the HTML code which is contained within the <font> nodes.
If I use
//td[@valign="top"]/p[1]/font[@face="verdana" and @color="#ffffff" and @size="2"]/node()
if get a mixture of text and lxml elements! (e.g. something something <Element a at 0x102ac2140> something)
Is there anyway to use a pure XPath query to get the contents of the <font> nodes, or even to force lxml to return a string of the contents from the .xpath() method, rather than an lxml object?
Note that I'm returning a list of many nodes from the XPath query so the solution needs to support that.
just to clarify... i want to return something something <a href="url">inside</a> something from something like...
<font face="verdana" color="#ffffff" size="2"><a href="url">inside</a> something</font>
| [
"I'm not sure I understand -- is this close to what you are looking for?\nimport lxml.etree as le\nimport cStringIO\ncontent='''\\\n<font face=\"verdana\" color=\"#ffffff\" size=\"2\"><a href=\"url\">inside</a> something</font>\n'''\ndoc=le.parse(cStringIO.StringIO(content))\n\nxpath='//font[@face=\"verdana\" and @... | [
3,
2
] | [] | [] | [
"html",
"lxml",
"python",
"xpath"
] | stackoverflow_0004114731_html_lxml_python_xpath.txt |
Q:
Vector normalization
The formula for half vector is (Hv) = (Lv + Vv) / |Lv+Vv|, where Lv is light vector, and Vv is view vector.
Am I doing this right in Python code?
Vvx = 0-xi # view vector (calculating it from surface points)
Vvy = 0-yi
Vvz = 0-zi
Vv = math.sqrt((Vvx * Vvx) + (Vvy * Vvy) + (Vvz * Vvz)) # normalizing
Vvx = Vvx / Vv
Vvy = Vvy / Vv
Vvz = Vvz / Vv
Lv = (1,1,1) # light vector
Hn = math.sqrt(((1 + Vvx) * (1 + Vvx)) + ((1 + Vvy) * (1 + Vvy)) +
((1 + Vvz) * (1 + Vvz)))
Hv = ((1 + Vvx) / Hn, (1 + Vvy) / Hn, (1 + Vvz) / Hn) # half-way vector
A:
This is misnamed. What you've written is simple vector addition of two vectors, with the result being a normalized unit vector.
Here's how I'd do it:
import math
def magnitude(v):
return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))
def add(u, v):
return [ u[i]+v[i] for i in range(len(u)) ]
def sub(u, v):
return [ u[i]-v[i] for i in range(len(u)) ]
def dot(u, v):
return sum(u[i]*v[i] for i in range(len(u)))
def normalize(v):
vmag = magnitude(v)
return [ v[i]/vmag for i in range(len(v)) ]
if __name__ == '__main__':
l = [1, 1, 1]
v = [0, 0, 0]
h = normalize(add(l, v))
print h
| Vector normalization | The formula for half vector is (Hv) = (Lv + Vv) / |Lv+Vv|, where Lv is light vector, and Vv is view vector.
Am I doing this right in Python code?
Vvx = 0-xi # view vector (calculating it from surface points)
Vvy = 0-yi
Vvz = 0-zi
Vv = math.sqrt((Vvx * Vvx) + (Vvy * Vvy) + (Vvz * Vvz)) # normalizing
Vvx = Vvx / Vv
Vvy = Vvy / Vv
Vvz = Vvz / Vv
Lv = (1,1,1) # light vector
Hn = math.sqrt(((1 + Vvx) * (1 + Vvx)) + ((1 + Vvy) * (1 + Vvy)) +
((1 + Vvz) * (1 + Vvz)))
Hv = ((1 + Vvx) / Hn, (1 + Vvy) / Hn, (1 + Vvz) / Hn) # half-way vector
| [
"This is misnamed. What you've written is simple vector addition of two vectors, with the result being a normalized unit vector.\nHere's how I'd do it:\nimport math\n\ndef magnitude(v):\n return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))\n\ndef add(u, v):\n return [ u[i]+v[i] for i in range(len(u)) ]\n... | [
22
] | [] | [] | [
"math",
"python"
] | stackoverflow_0004114921_math_python.txt |
Q:
Greedy execution of statements?
I have something like this using BeautifulSoup:
for line in lines:
code = l.find('span', {'class':'boldHeader'}).text
coded = l.find('div', {'class':'Description'}).text
definition = l.find('ul', {'class':'definitions'}).text
print code, coded, def
However, not all elements exist at all times. I can enclose this in a try except so that it does not break the program execution like this:
for line in lines:
try:
code = l.find('span', {'class':'boldHeader'}).text
coded = l.find('div', {'class':'Description'}).text
definition = l.find('ul', {'class':'definitions'}).text
print code, coded, def
except:
pass
But how I execute the statements in a greedy fashion? For instance, if there are only two elements available code and coded, I just want to get those and continue with the execution. As of now, even if code and coded exist, if def does not exist, the print command is never executed.
One way of doing this is to put a try...except for every statement like this:
for line in lines:
try:
code = l.find('span', {'class':'boldHeader'}).text
except:
pass
try:
coded = l.find('div', {'class':'Description'}).text
except:
pass
try:
definition = l.find('ul', {'class':'definitions'}).text
except:
pass
print code, coded, def
But this is an ugly approach and I want something cleaner. Any suggestions?
A:
First of all, you can test for None instead of catching an exception. l.find should return None if it doesn't find your item. Exceptions should be reserved for errors and really extraordinary situations.
Second thing you can do is to create an array of all HTML elements you want to check and then have a nested for loop. Since it's been a while since I've used python, I will outline the code and then (hopefully) edit the answer when I test it.
Something like:
elementsToCheck = [
[ 'span', {'class':'boldHeader'} ],
[ 'div', {'class':'Description'} ],
[ 'ul', {'class':'definitions'} ]]
concatenated = ''
for line in lines:
for something in elementsToCheck
element = l.find(something[0], something[1])
if element is not None
concatenated += element.text
print concatenated
Obviously the code above won't work, but you should get the idea. :)
A:
How about capture the "ugly" code in a function, and just call the function as needed:
def get_txt(l,tag,classname):
try:
txt=l.find(tag, {'class':classname}).text
except AttributeError:
txt=None
return txt
for line in lines:
code = get_txt(l,'span','boldHeader')
coded = get_txt(l,'div','Description')
defn = get_txt(l,'ul','definitions')
print code, coded, defn
PS. I changed def to defn because def is a Python keyword. Using it as a variable name raises a SyntaxError.
PPS. It's not a good practice to use bare exceptions:
try:
....
except:
...
because it almost always captures more that you intend. Much better to be explicit about what you want to catch:
try:
...
except AttributeError as err:
...
| Greedy execution of statements? | I have something like this using BeautifulSoup:
for line in lines:
code = l.find('span', {'class':'boldHeader'}).text
coded = l.find('div', {'class':'Description'}).text
definition = l.find('ul', {'class':'definitions'}).text
print code, coded, def
However, not all elements exist at all times. I can enclose this in a try except so that it does not break the program execution like this:
for line in lines:
try:
code = l.find('span', {'class':'boldHeader'}).text
coded = l.find('div', {'class':'Description'}).text
definition = l.find('ul', {'class':'definitions'}).text
print code, coded, def
except:
pass
But how I execute the statements in a greedy fashion? For instance, if there are only two elements available code and coded, I just want to get those and continue with the execution. As of now, even if code and coded exist, if def does not exist, the print command is never executed.
One way of doing this is to put a try...except for every statement like this:
for line in lines:
try:
code = l.find('span', {'class':'boldHeader'}).text
except:
pass
try:
coded = l.find('div', {'class':'Description'}).text
except:
pass
try:
definition = l.find('ul', {'class':'definitions'}).text
except:
pass
print code, coded, def
But this is an ugly approach and I want something cleaner. Any suggestions?
| [
"First of all, you can test for None instead of catching an exception. l.find should return None if it doesn't find your item. Exceptions should be reserved for errors and really extraordinary situations.\nSecond thing you can do is to create an array of all HTML elements you want to check and then have a nested fo... | [
3,
3
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004114886_beautifulsoup_python.txt |
Q:
Python html parsing that actually works
I'm trying to parse some html in Python. There were some methods that actually worked before... but nowadays there's nothing I can actually use without workarounds.
beautifulsoup has problems after SGMLParser went away
html5lib cannot parse half of what's "out there"
lxml is trying to be "too correct" for typical html (attributes and tags cannot contain unknown namespaces, or an exception is thrown, which means almost no page with Facebook connect can be parsed)
What other options are there these days? (if they support xpath, that would be great)
A:
Make sure that you use the html module when you parse HTML with lxml:
>>> from lxml import html
>>> doc = """<html>
... <head>
... <title> Meh
... </head>
... <body>
... Look at this interesting use of <p>
... rather than using <br /> tags as line breaks <p>
... </body>"""
>>> html.document_fromstring(doc)
<Element html at ...>
All the errors & exceptions will melt away, you'll be left with an amazingly fast parser that often deals with HTML soup better than BeautifulSoup.
A:
I've used pyparsing for a number of HTML page scraping projects. It is a sort of middle-ground between BeautifulSoup and the full HTML parsers on one end, and the too-low-level approach of regular expressions (that way lies madness).
With pyparsing, you can often get good HTML scraping results by identifying the specific subset of the page or data that you are trying to extract. This approach avoids the issues of trying to parse everything on the page, since some problematic HTML outside of your region of interest could throw off a comprehensive HTML parser.
While this sounds like just a glorified regex approach, pyparsing offers builtins for working with HTML- or XML-tagged text. Pyparsing avoids many of the pitfalls that frustrate the regex-based solutions:
accepts whitespace without littering '\s*' all over your expression
handles unexpected attributes within tags
handles attributes in any order
handles upper/lower case in tags
handles attribute names with namespaces
handles attribute values in double quotes, single quotes, or no quotes
handles empty tags (those of the form <blah />)
returns parsed tag data with object-attribute access to tag attributes
Here's a simple example from the pyparsing wiki that gets <a href=xxx> tags from a web page:
from pyparsing import makeHTMLTags, SkipTo
# read HTML from a web page
page = urllib.urlopen( "http://www.yahoo.com" )
htmlText = page.read()
page.close()
# define pyparsing expression to search for within HTML
anchorStart,anchorEnd = makeHTMLTags("a")
anchor = anchorStart + SkipTo(anchorEnd).setResultsName("body") + anchorEnd
for tokens,start,end in anchor.scanString(htmlText):
print tokens.body,'->',tokens.href
This will pull out the <a> tags, even if there are other portions of the page containing problematic HTML. There are other HTML examples at the pyparsing wiki:
http://pyparsing.wikispaces.com/file/view/makeHTMLTagExample.py
http://pyparsing.wikispaces.com/file/view/getNTPserversNew.py
http://pyparsing.wikispaces.com/file/view/htmlStripper.py
http://pyparsing.wikispaces.com/file/view/withAttribute.py
Pyparsing is not a total foolproof solution to this problem, but by exposing the parsing process to you, you can better control which pieces of the HTML you are specifically interested in, process them, and skip the rest.
A:
If you are scraping content, an excellent way to get around irritating details is the sitescraper package. It uses machine learning to determine which content to retrieve for you.
From the homepage:
>>> from sitescraper import sitescraper
>>> ss = sitescraper()
>>> url = 'http://www.amazon.com/s/ref=nb_ss_gw?url=search-alias%3Daps&field-keywords=python&x=0&y=0'
>>> data = ["Amazon.com: python",
["Learning Python, 3rd Edition",
"Programming in Python 3: A Complete Introduction to the Python Language (Developer's Library)",
"Python in a Nutshell, Second Edition (In a Nutshell (O'Reilly))"]]
>>> ss.add(url, data)
>>> # we can add multiple example cases, but this is a simple example so 1 will do (I generally use 3)
>>> # ss.add(url2, data2)
>>> ss.scrape('http://www.amazon.com/s/ref=nb_ss_gw?url=search-alias%3Daps&field- keywords=linux&x=0&y=0')
["Amazon.com: linux", ["A Practical Guide to Linux(R) Commands, Editors, and Shell Programming",
"Linux Pocket Guide",
"Linux in a Nutshell (In a Nutshell (O'Reilly))",
'Practical Guide to Ubuntu Linux (Versions 8.10 and 8.04), A (2nd Edition)',
'Linux Bible, 2008 Edition: Boot up to Ubuntu, Fedora, KNOPPIX, Debian, openSUSE, and 11 Other Distributions']]
A:
html5lib cannot parse half of what's "out there"
That sounds extremely implausible. html5lib uses exactly the same algorithm that's also implemented in recent versions of Firefox, Safari and Chrome. If that algorithm broke half the web, I think we would have heard. If you have particular problems with it, do file bugs.
A:
I think the problem is that most HTML is ill-formed. XHTML tried to fix that, but it never really caught on enough - especially as most browsers do "intelligent workarounds" for ill-formed code.
Even a few years ago I tried to parse HTML for a primitive spider-type app, and found the problems too difficult. I suspect writing your own might be on the cards, although we can't be the only people with this problem!
| Python html parsing that actually works | I'm trying to parse some html in Python. There were some methods that actually worked before... but nowadays there's nothing I can actually use without workarounds.
beautifulsoup has problems after SGMLParser went away
html5lib cannot parse half of what's "out there"
lxml is trying to be "too correct" for typical html (attributes and tags cannot contain unknown namespaces, or an exception is thrown, which means almost no page with Facebook connect can be parsed)
What other options are there these days? (if they support xpath, that would be great)
| [
"Make sure that you use the html module when you parse HTML with lxml:\n>>> from lxml import html\n>>> doc = \"\"\"<html>\n... <head>\n... <title> Meh\n... </head>\n... <body>\n... Look at this interesting use of <p>\n... rather than using <br /> tags as line breaks <p>\n... </body>\"\"\"\n>>> html.document_froms... | [
19,
7,
3,
3,
2
] | [] | [] | [
"html",
"parsing",
"python"
] | stackoverflow_0004114722_html_parsing_python.txt |
Q:
python threading and shared variables
how can i update a shared variable between different threading.Thread in python?
lets say that i have 5 threads working down a Queue.Queue(). after the queue is done i want to do an other operation but i want it to happen only once.
is it possible to share and update a variable betweeen the threads. so when Queue.empty() is True this event gets fired but if one of the threads is doing it i dont want the others to do do that too because i would get wrong results.
EDIT
i have a queue which reflects files on the filesystem.
the files are uploaded to a site by the threads and while each thread is uploading the file it updates a set() of keywords i got from the files.
when the queue is empty i need to contact the site and tell it to update the keyword counts. right now each thread does this and i get an update for each thread which is bad.
i also tried to empty the set but it doesnt work.
keywordset = set()
hkeywordset = set()
def worker():
while queue:
if queue.empty():
if len(keywordset) or len(hkeywordset):
# as soon as the queue is empty we send the keywords and hkeywords to the
# imageapp so it can start updating
apiurl = update_cols_url
if apiurl[-1] != '/':
apiurl = apiurl+'/'
try:
keywords = []
data = dict(keywords=list(keywordset), hkeywords=list(hkeywordset))
post = dict(data=simplejson.dumps(data))
post = urllib.urlencode(post)
urllib2.urlopen(apiurl, post)
hkeywordset.clear()
keywordset.clear()
print 'sent keywords and hkeywords to imageapp...'
except Exception, e: print e
# we get the task form the Queue and process the file based on the action
task = queue.get()
print str(task)
try:
reindex = task['reindex']
except:
reindex = False
data = updater.process_file(task['filename'], task['action'], task['fnamechange'], reindex)
# we parse the images keywords and hkeywords and add them to the sets above for later
# processing
try:
for keyword in data['keywords']:
keywordset.add(keyword)
except: pass
try:
for hkw in data['hkeywords']:
hkeywordset.add(hkw)
except:pass
queue.task_done()
for i in range(num_worker_threads):
t = threading.Thread(target=worker)
t.daemon = True
t.start()
while 1:
line = raw_input('type \'q\' to stop filewatcher... or \'qq\' to force quit...\n').strip()
this is what i was trying basically. but of course the part of queue.empty() gets exectued as many times as threads i have.
A:
If you are using a queue to run your thread (thread pool) so you are making sure that there will not be a race condition (thread safe) because the queue run your thread in a sequential way, so i think you can share a variable between the thread and you can be sure that there will not be a race condition over this variable.
Edit : Here is something similar about what you want to do hope this can give you answer to your question this time :) :
import Queue
import threading
import ftplib
import os
class SendFileThread(threading.Thread):
""" Thread that will handle sending files to the FTP server"""
# Make set of keywords a class variable.
Keywords = set()
def __init__(self, queue, conn):
self.conn = conn
self.queue = queue
threading.Thread.__init__(self)
def run(self):
while True:
# Grabs file from queue.
file_name = self.queue.get()
# Send file to FTP server.
f=open(file_name,'rb')
self.conn.storbinary('STOR '+os.path.basename(file_name),f)
# Suppose that this keywords are in the first line.
# Update the set of keywords.
SendFileThread.Keywords.update(f.readline().split(" ")))
# Signals to queue job is done.
self.queue.task_done()
def main():
# Files to send.
files = os.listdir('/tosend')
queue = Queue.Queue()
# Connect to the FTP server.
conn = ftplib.FTP('ftp_uri')
conn.login()
# Create 5 threads that will handle file to send.
for i in range(5):
t = SendFileThread(queue, conn)
t.start()
# Fill the queue with files to be send.
for file in files:
queue.put(file)
# Wait until or thread are finish
queue.join()
# Send the keywords to the FTP server.
# I didn't understand well the part update keywords count,
# how this count is stored ...
# Here i will just send the keywords to the FTP server.
with open("keywords", "w") as keywords_file
keywords_file.write(";".join(SendFileThread.Keywords))
conn.storbinary('STOR '+os.path.basename("keywords"),
keywords_file)
conn.close()
if __name__ == '__main__':
main()
A:
Why can't you just add the final step to the queue ?
A:
Have another queue where you place this event after first queue is empty.
Or have special thread for this event.
| python threading and shared variables | how can i update a shared variable between different threading.Thread in python?
lets say that i have 5 threads working down a Queue.Queue(). after the queue is done i want to do an other operation but i want it to happen only once.
is it possible to share and update a variable betweeen the threads. so when Queue.empty() is True this event gets fired but if one of the threads is doing it i dont want the others to do do that too because i would get wrong results.
EDIT
i have a queue which reflects files on the filesystem.
the files are uploaded to a site by the threads and while each thread is uploading the file it updates a set() of keywords i got from the files.
when the queue is empty i need to contact the site and tell it to update the keyword counts. right now each thread does this and i get an update for each thread which is bad.
i also tried to empty the set but it doesnt work.
keywordset = set()
hkeywordset = set()
def worker():
while queue:
if queue.empty():
if len(keywordset) or len(hkeywordset):
# as soon as the queue is empty we send the keywords and hkeywords to the
# imageapp so it can start updating
apiurl = update_cols_url
if apiurl[-1] != '/':
apiurl = apiurl+'/'
try:
keywords = []
data = dict(keywords=list(keywordset), hkeywords=list(hkeywordset))
post = dict(data=simplejson.dumps(data))
post = urllib.urlencode(post)
urllib2.urlopen(apiurl, post)
hkeywordset.clear()
keywordset.clear()
print 'sent keywords and hkeywords to imageapp...'
except Exception, e: print e
# we get the task form the Queue and process the file based on the action
task = queue.get()
print str(task)
try:
reindex = task['reindex']
except:
reindex = False
data = updater.process_file(task['filename'], task['action'], task['fnamechange'], reindex)
# we parse the images keywords and hkeywords and add them to the sets above for later
# processing
try:
for keyword in data['keywords']:
keywordset.add(keyword)
except: pass
try:
for hkw in data['hkeywords']:
hkeywordset.add(hkw)
except:pass
queue.task_done()
for i in range(num_worker_threads):
t = threading.Thread(target=worker)
t.daemon = True
t.start()
while 1:
line = raw_input('type \'q\' to stop filewatcher... or \'qq\' to force quit...\n').strip()
this is what i was trying basically. but of course the part of queue.empty() gets exectued as many times as threads i have.
| [
"If you are using a queue to run your thread (thread pool) so you are making sure that there will not be a race condition (thread safe) because the queue run your thread in a sequential way, so i think you can share a variable between the thread and you can be sure that there will not be a race condition over this ... | [
0,
0,
0
] | [] | [] | [
"python",
"queue",
"thread_safety"
] | stackoverflow_0004115033_python_queue_thread_safety.txt |
Q:
Remove characters from beginning and end or only end of line
I want to remove some symbols from a string using a regular expression, for example:
== (that occur both at the beginning and at the end of a line),
* (at the beginning of a line ONLY).
def some_func():
clean = re.sub(r'= {2,}', '', clean) #Removes 2 or more occurrences of = at the beg and at the end of a line.
clean = re.sub(r'^\* {1,}', '', clean) #Removes 1 or more occurrences of * at the beginning of a line.
What's wrong with my code? It seems like expressions are wrong. How do I remove a character/symbol if it's at the beginning or at the end of the line (with one or more occurrences)?
A:
If you only want to remove characters from the beginning and the end, you could use the string.strip() method. This would give some code like this:
>>> s1 = '== foo bar =='
>>> s1.strip('=')
' foo bar '
>>> s2 = '* foo bar'
>>> s2.lstrip('*')
' foo bar'
The strip method removes the characters given in the argument from the beginning and the end of the string, ltrip removes them from only the beginning, and rstrip removes them only from the end.
If you really want to use a regular expression, they would look something like this:
clean = re.sub(r'(^={2,})|(={2,}$)', '', clean)
clean = re.sub(r'^\*+', '', clean)
But IMHO, using strip/lstrip/rstrip would be the most appropriate for what you want to do.
Edit: On Nick's suggestion, here is a solution that would do all this in one line:
clean = clean.lstrip('*').strip('= ')
(A common mistake is to think that these methods remove characters in the order they're given in the argument, in fact, the argument is just a sequence of characters to remove, whatever their order is, that's why the .strip('= ') would remove every '=' and ' ' from the beginning and the end, and not just the string '= '.)
A:
You have extra spaces in your regexs. Even a space counts as a character.
r'^(?:\*|==)|==$'
A:
First of all you should pay attention to the spaces before "{" ... those are meaningful so the quantifier in your example applies to the space.
To remove "=" (two or more) only at begin or end also you need a different regexp... for example
clean = re.sub(r'^(==+)?(.*?)(==+)?$', r'\2', s)
If you don't put either "^" or "$" the expression can match anywhere (i.e. even in the middle of the string).
A:
And not substituting but keeping ? :
tu = ('======constellation==' , '==constant=====' ,
'=flower===' , '===bingo=' ,
'***seashore***' , '*winter*' ,
'====***conditions=**' , '=***trees====***' ,
'***=information***=' , '*=informative***==' )
import re
RE = '((===*)|\**)?(([^=]|=(?!=+\Z))+)'
pat = re.compile(RE)
for ch in tu:
print ch,' ',pat.match(ch).group(3)
Result:
======constellation== constellation
==constant===== constant
=flower=== =flower
===bingo= bingo=
***seashore*** seashore***
*winter* winter*
====***conditions=** ***conditions=**
=***trees====*** =***trees====***
***=information***= =information***=
*=informative***== =informative***
Do you want in fact
====***conditions=** to give conditions=** ?
***====hundred====*** to give hundred====*** ?
for the beginning ?**
A:
I think that the following code will do the job:
tu = ('======constellation==' , '==constant=====' ,
'=flower===' , '===bingo=' ,
'***seashore***' , '*winter*' ,
'====***conditions=**' , '=***trees====***' ,
'***=information***=' , '*=informative***==' )
import re,codecs
with codecs.open('testu.txt', encoding='utf-8', mode='w') as f:
pat = re.compile('(?:==+|\*+)?(.*?)(?:==+)?\Z')
xam = max(map(len,tu)) + 3
res = '\n'.join(ch.ljust(xam) + pat.match(ch).group(1)
for ch in tu)
f.write(res)
print res
Where was my brain when I wrote the RE in my earlier post ??! O!O
Non greedy quantifier .*? before ==+\Z is the real solution.
| Remove characters from beginning and end or only end of line | I want to remove some symbols from a string using a regular expression, for example:
== (that occur both at the beginning and at the end of a line),
* (at the beginning of a line ONLY).
def some_func():
clean = re.sub(r'= {2,}', '', clean) #Removes 2 or more occurrences of = at the beg and at the end of a line.
clean = re.sub(r'^\* {1,}', '', clean) #Removes 1 or more occurrences of * at the beginning of a line.
What's wrong with my code? It seems like expressions are wrong. How do I remove a character/symbol if it's at the beginning or at the end of the line (with one or more occurrences)?
| [
"If you only want to remove characters from the beginning and the end, you could use the string.strip() method. This would give some code like this:\n>>> s1 = '== foo bar =='\n>>> s1.strip('=')\n' foo bar '\n>>> s2 = '* foo bar'\n>>> s2.lstrip('*')\n' foo bar'\n\nThe strip method removes the characters given in the... | [
12,
3,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004113716_python_regex.txt |
Q:
When Popen.communicate() is not enough?
I found a lot of threads more or less related to this topic and still almost nothing like full answer... I'm looking for your advice on it.
So, here is my problem: I really need to communicate with a subprocess in both ways: I have to wright a lot of data to its input and get its output on the fly. There is no way around it. My subprocess is famous 'lame' mp3 encoder, the input is an hour or more long PCM sound generated by my function and the output is the mp3 file which also has to be sent to user chunk by chunk without waiting for encoder to finish.
According to docs, Popen.communicate() won't help me to handle IPC measured in dozens or hundreds of megabytes. At the same time, as I learned from here, this is very dangerous to try to create this approach from scratch since a lot of pitfalls are waiting: deadlocks, buffering, process management, etc.
So, my question is: is there some well known solution for this kind of problem: a python lib or a code example that really does solve the problem? May be at least there is an article or something clearly desribing most of problems one can run into trying to solve this by himself?
Thank you in advance,
Ilya.
A:
The easiest way is to split you own program in two: one which writes to LAME and the other which reads from lame and writes to the user. This is much easier to do than to have bidirectional communication.
If that doesn't work for you I have found development with named pipes much easier than traditional pipe IPC. It is easy to use various kind of plumbing during testing. Nonblocking I/O in Python 3 should make accessing them much easier.
| When Popen.communicate() is not enough? | I found a lot of threads more or less related to this topic and still almost nothing like full answer... I'm looking for your advice on it.
So, here is my problem: I really need to communicate with a subprocess in both ways: I have to wright a lot of data to its input and get its output on the fly. There is no way around it. My subprocess is famous 'lame' mp3 encoder, the input is an hour or more long PCM sound generated by my function and the output is the mp3 file which also has to be sent to user chunk by chunk without waiting for encoder to finish.
According to docs, Popen.communicate() won't help me to handle IPC measured in dozens or hundreds of megabytes. At the same time, as I learned from here, this is very dangerous to try to create this approach from scratch since a lot of pitfalls are waiting: deadlocks, buffering, process management, etc.
So, my question is: is there some well known solution for this kind of problem: a python lib or a code example that really does solve the problem? May be at least there is an article or something clearly desribing most of problems one can run into trying to solve this by himself?
Thank you in advance,
Ilya.
| [
"The easiest way is to split you own program in two: one which writes to LAME and the other which reads from lame and writes to the user. This is much easier to do than to have bidirectional communication.\nIf that doesn't work for you I have found development with named pipes much easier than traditional pipe IPC.... | [
2
] | [] | [] | [
"ipc",
"popen",
"python",
"subprocess"
] | stackoverflow_0004115051_ipc_popen_python_subprocess.txt |
Q:
Google Voice API
Is there a way to extract the text of a transcribed voicemail using pygooglevoice? Printing the message simply prints the filename.
A:
As of right now, according to the pygooglevoice docs, the Python binding for the Google Voice API doesn't have any methods to get the text of a transcribed voicemail. However, the project is only on version 0.5, and you can make a feature request (if one hasn't already been made).
You can also always contribute your own implementation of this behavior to pygooglevoice.
Sorry, I wish such a behavior existed, but it doesn't. You may be able to use other means (e.g. cURL, HTML/XML parsing, etc.) to achieve what you want to do but it's not in pygooglevoice.
| Google Voice API | Is there a way to extract the text of a transcribed voicemail using pygooglevoice? Printing the message simply prints the filename.
| [
"As of right now, according to the pygooglevoice docs, the Python binding for the Google Voice API doesn't have any methods to get the text of a transcribed voicemail. However, the project is only on version 0.5, and you can make a feature request (if one hasn't already been made).\nYou can also always contribute y... | [
0
] | [] | [] | [
"python",
"voice"
] | stackoverflow_0004115103_python_voice.txt |
Q:
Simple function error
code:
date=int(raw_input("Date:"))
ammount=int(raw_input("Ammount:"))
desc=str(raw_input("Description:"))
account=str(raw_input("Account:"))
def addEntry(date, ammount, desc, account):
transact=open("transactions.txt", "w")
transact.write(date, ammount, desc, account)
transact.close()
addEntry(date, ammount, desc, account)
gives
Traceback (most recent call last):
File "C:\tbank.py", line 11, in <module>
addEntry(date, ammount, desc, account)
File "C:\tbank.py", line 8, in addEntry
transact.write(date, ammount, desc, account)
TypeError: function takes exactly 1 argument (4 given)
how can i make it work?
A:
date=int(raw_input("Date:"))
ammount=int(raw_input("Ammount:"))
desc=str(raw_input("Description:"))
account=str(raw_input("Account:"))
def addEntry(date, ammount, desc, account):
transact=open("transactions.txt", "w")
transact.write('%s, %s, %s , %s' % (date, ammount, desc, account))
transact.close()
addEntry(date, ammount, desc, account)
A:
You are opening a file to write to it. It takes a single string as argument.
transact.write("your string")
Since all you are doing is write to file. You can avoid conversion. And raw_input returns a string.
date=raw_input("Date:")
amount =raw_input("Ammount:")
desc=raw_input("Description:")
account=raw_input("Account:")
You can add all of them as one string, before writing it to file
A:
As others have noted, you must pass write a single string argument. There is another way to write things out to an open file that should be mentioned: the special form of print
print >>transact, date, amount, desc, account
This directs print to output to the file that immediatedly follows the '>>'
It behaves exactly like print normally does, so it will write out all the values separated by a space, with a newline at the end (which you can suppress by adding a trailing comma).
| Simple function error | code:
date=int(raw_input("Date:"))
ammount=int(raw_input("Ammount:"))
desc=str(raw_input("Description:"))
account=str(raw_input("Account:"))
def addEntry(date, ammount, desc, account):
transact=open("transactions.txt", "w")
transact.write(date, ammount, desc, account)
transact.close()
addEntry(date, ammount, desc, account)
gives
Traceback (most recent call last):
File "C:\tbank.py", line 11, in <module>
addEntry(date, ammount, desc, account)
File "C:\tbank.py", line 8, in addEntry
transact.write(date, ammount, desc, account)
TypeError: function takes exactly 1 argument (4 given)
how can i make it work?
| [
"date=int(raw_input(\"Date:\"))\nammount=int(raw_input(\"Ammount:\"))\ndesc=str(raw_input(\"Description:\"))\naccount=str(raw_input(\"Account:\"))\n\ndef addEntry(date, ammount, desc, account):\n transact=open(\"transactions.txt\", \"w\")\n transact.write('%s, %s, %s , %s' % (date, ammount, desc, account))\n ... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004115275_python.txt |
Q:
Python argparse: nargs + or * depending on prior argument
I'm writing a server querying tool, and I have a little bit of code to parse arguments at the very top:
# Parse arguments
p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument('--odam', dest='query_type', action='store_const',
const='odam', help="Odamex Master query.")
g.add_argument('--odas', dest='query_type', action='store_const',
const='odas', help="Odamex Server query.")
p.add_argument('address', nargs='*')
args = p.parse_args()
# Default master server arguments.
if args.query_type == 'odam' and not args.address:
args.address = [
'master1.odamex.net:15000',
'master2.odamex.net:15000',
]
# If we don't have any addresses by now, we can't go on.
if not args.address:
print "If you are making a server query, you must pass an address."
sys.exit(1)
Is there a nicer way to do this, preferably all within the parser? That last error looks a little out of place, and it would be nice if I could make nargs for address depend on if --odam or ---odas is passed. I could create a subparser, but that would make help look a little odd since it would leave off the addresses part of the command.
A:
You can do this with an custom argparse.Action:
import argparse
import sys
class AddressAction(argparse.Action):
def __call__(self, parser, args, values, option = None):
args.address=values
if args.query_type=='odam' and not args.address:
args.address=[
'master1.odamex.net:15000',
'master2.odamex.net:15000',
]
if not args.address:
parser.error("If you are making a server query, you must pass an address.")
p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument('--odam', dest='query_type', action='store_const',
const='odam', help="Odamex Master query.")
g.add_argument('--odas', dest='query_type', action='store_const',
const='odas', help="Odamex Server query.")
p.add_argument('address', nargs='*', action=AddressAction)
args = p.parse_args()
yields
% test.py --odas
If you are making a server query, you must pass an address.
% test.py --odam
Namespace(address=['master1.odamex.net:15000', 'master2.odamex.net:15000'], query_type='odam')
% test.py --odam 1 2 3
Namespace(address=['1', '2', '3'], query_type='odam')
| Python argparse: nargs + or * depending on prior argument | I'm writing a server querying tool, and I have a little bit of code to parse arguments at the very top:
# Parse arguments
p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument('--odam', dest='query_type', action='store_const',
const='odam', help="Odamex Master query.")
g.add_argument('--odas', dest='query_type', action='store_const',
const='odas', help="Odamex Server query.")
p.add_argument('address', nargs='*')
args = p.parse_args()
# Default master server arguments.
if args.query_type == 'odam' and not args.address:
args.address = [
'master1.odamex.net:15000',
'master2.odamex.net:15000',
]
# If we don't have any addresses by now, we can't go on.
if not args.address:
print "If you are making a server query, you must pass an address."
sys.exit(1)
Is there a nicer way to do this, preferably all within the parser? That last error looks a little out of place, and it would be nice if I could make nargs for address depend on if --odam or ---odas is passed. I could create a subparser, but that would make help look a little odd since it would leave off the addresses part of the command.
| [
"You can do this with an custom argparse.Action:\nimport argparse\nimport sys\n\nclass AddressAction(argparse.Action):\n def __call__(self, parser, args, values, option = None):\n args.address=values\n if args.query_type=='odam' and not args.address:\n args.address=[\n 'ma... | [
12
] | [] | [] | [
"argparse",
"python"
] | stackoverflow_0004114996_argparse_python.txt |
Q:
Python sorted() key function weirdness
While I was debugging some illogical behavour I came to the following weirdness in Python 2.5 sorted() function calls:
>>> aa = [10, 5, 20]
>>> sorted(range(len(aa)))
[0, 1, 2]
sorted(range(len(aa)), key=lambda a: aa[a])
[1, 0, 2]
sorted(range(len(aa)), key=lambda a: -aa[a])
[2, 0, 1]
First two calls work as expected, but the last one is imho simply wrong! It should be: [1, 2, 0].
After further experiments for trying to come to the root of the problem I came to this (does not use lambda or negation operation, but it is otherwise the same problem):
>>> bb = [-10, -5, -20]
>>> sorted([0, 1, 2], key=bb.__getitem__)
[2, 0, 1]
Even things like following don't work and show that double negation works again:
>>> bb = [-10, -5, -20]
>>> def fun(i):
... return bb[i]
>>> sorted([0, 1, 2], key=fun)
[2, 0, 1]
>>> def fun2(i):
... return -bb[i]
>>> sorted([0, 1, 2], key=fun2)
[1, 0, 2]
Am I losing my mind or where is the problem? Or why doesn't Python 3.x have the cmp argument that used to work fine (compatibility is the reason why I am not using it)?
A:
The value returned by the key function acts as a proxy for the values being sorted.
So when you say
sorted(range(len(aa)), key=lambda a: -aa[a])
you are sorting range(len(aa)), that is [0, 1, 2], but using the values
-aa[0], -aa[1], -aa[2] as the proxy values.
range(len(aa)) 0 1 2 <-- values
aa[a] 10 5 20
-aa[a] -10 -5 -20 <-- proxy values
Since -20, or -aa[2], is the smallest proxy value, its associated value 2
becomes the first element in the sorted result.
Since -10, or -aa[0] is the next smallest, its associated value 0 becomes the second element in the sorted result.
Finally -5, or -aa[1] is the last value, so 1 is the last number in the sorted result.
Thus, sorted(range(len(aa)), key=lambda a: -aa[a]) equals [2, 0, 1].
The answer Python is giving is correct.
A:
the last one is imho simply wrong! It should be: [1, 2, 0]
In your second example, the key is lambda a: aa[a] which gives you the indices of the elements in increasing size order.
In the last example, the key is lambda a: -aa[a]. Due to the negation, this gives you the indices of the elements in decreasing size order.
So the last result should be [2, 0, 1] - it's the reverse of [1, 0, 2].
In this example
>>> bb = [-10, -5, -20]
>>> sorted([0, 1, 2], key=bb.__getitem__)
[2, 0, 1]
you're getting the indices of the elements in increasing size order - [2, 0, 1] corresponds to [-20, -10, -5].
In your last two examples, you're again getting the indices for the elements in increasing size order ([2, 0, 1]), or decreasing size order ([1, 0, 2]).
A:
This makes sense to me
>>> bb = [-10, -5, -20]
>>> sorted([0, 1, 2], key=bb.__getitem__)
[2, 0, 1] ==> corresponds to bb.__getitem__ of [-20, -10, -5]
| Python sorted() key function weirdness | While I was debugging some illogical behavour I came to the following weirdness in Python 2.5 sorted() function calls:
>>> aa = [10, 5, 20]
>>> sorted(range(len(aa)))
[0, 1, 2]
sorted(range(len(aa)), key=lambda a: aa[a])
[1, 0, 2]
sorted(range(len(aa)), key=lambda a: -aa[a])
[2, 0, 1]
First two calls work as expected, but the last one is imho simply wrong! It should be: [1, 2, 0].
After further experiments for trying to come to the root of the problem I came to this (does not use lambda or negation operation, but it is otherwise the same problem):
>>> bb = [-10, -5, -20]
>>> sorted([0, 1, 2], key=bb.__getitem__)
[2, 0, 1]
Even things like following don't work and show that double negation works again:
>>> bb = [-10, -5, -20]
>>> def fun(i):
... return bb[i]
>>> sorted([0, 1, 2], key=fun)
[2, 0, 1]
>>> def fun2(i):
... return -bb[i]
>>> sorted([0, 1, 2], key=fun2)
[1, 0, 2]
Am I losing my mind or where is the problem? Or why doesn't Python 3.x have the cmp argument that used to work fine (compatibility is the reason why I am not using it)?
| [
"The value returned by the key function acts as a proxy for the values being sorted.\nSo when you say\nsorted(range(len(aa)), key=lambda a: -aa[a])\n\nyou are sorting range(len(aa)), that is [0, 1, 2], but using the values\n-aa[0], -aa[1], -aa[2] as the proxy values.\nrange(len(aa)) 0 1 2 <-- values\naa[... | [
8,
1,
0
] | [] | [] | [
"key",
"python",
"sorting"
] | stackoverflow_0004115636_key_python_sorting.txt |
Q:
transforming url's, python
I have a txt file which contains some url's:
[http://igu.org.ru/ International Geographical Union - Russian National Committee]
[http://www.geografos.org Colegio de Geógrafos - España]
[http://www.geografs.org Col.legi de Geògrafs - Catalunya]
[http://www.geografs.org]
now I want to transform this external links in the following way (in the fixed order):
replace "[url any text]" with "any text", where "url" is an URL (e.g., starts with "http://").
replace "[url]" with "url"
import re
def openfile(filename):
with codecs.open(filename, encoding="utf-8") as F:
replace = F.read()
replace = re.sub(r'\[http://.+ ...) # should replace "[url any text]" with "any text"
replace = re.sub(...) # should replace "[url]" with "url"
any suggestions?
A:
re1 = re.compile(r'\[(http[^\s]*)\s(.*)\]')
re2 = re.compile(r'\[(http[^\s]*)\]')
with codecs.open(filename, encoding='utf-8') as F:
text = F.read()
pre_filter = re1.sub('\g<2>', text)
result = re2.sub('\g<1>', pre_filter)
to process the your text.
For further informations in the background you can read:
http://docs.python.org/howto/regex.html#search-and-replace
| transforming url's, python | I have a txt file which contains some url's:
[http://igu.org.ru/ International Geographical Union - Russian National Committee]
[http://www.geografos.org Colegio de Geógrafos - España]
[http://www.geografs.org Col.legi de Geògrafs - Catalunya]
[http://www.geografs.org]
now I want to transform this external links in the following way (in the fixed order):
replace "[url any text]" with "any text", where "url" is an URL (e.g., starts with "http://").
replace "[url]" with "url"
import re
def openfile(filename):
with codecs.open(filename, encoding="utf-8") as F:
replace = F.read()
replace = re.sub(r'\[http://.+ ...) # should replace "[url any text]" with "any text"
replace = re.sub(...) # should replace "[url]" with "url"
any suggestions?
| [
"re1 = re.compile(r'\\[(http[^\\s]*)\\s(.*)\\]')\nre2 = re.compile(r'\\[(http[^\\s]*)\\]')\nwith codecs.open(filename, encoding='utf-8') as F:\n text = F.read()\n pre_filter = re1.sub('\\g<2>', text)\n result = re2.sub('\\g<1>', pre_filter)\n\nto process the your text. \nFor further informations in the bac... | [
2
] | [] | [] | [
"python",
"regex",
"url"
] | stackoverflow_0004115585_python_regex_url.txt |
Q:
Import error and PythonPath
I'm trying to understand what the issue is:
I'm trying to import a module:
from main.models import Main
from django.contrib import admin
admin.site.register(Main)
However, when I attempt to hit the admin site, I get a django error page:
ImportError at /admin/
cannot import name Main
I noticed that it provides a dump of the **Python Path:**
Python Path: ['/Users/brian/src/SampleApp/src/SampleApp', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Python/2.6/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode']
However, what I don't understand is where is this Python Path set?
doing an export PYTHONPATH returns nothing as it is not set in the environmental variables.
I need to import a module which is located in /Users/brian/src/SampleApp/src/SampleApp/main/models.py
Thanks
A:
PYTHONPATH can be accessed via:
import sys
print sys.path
A bit of debugging to try would be to use:
from main import models
from django.contrib import admin
admin.site.register(models.Main)
and see if that gives you any more information.
A:
Do you have an __init__.py in /Users/brian/src/SampleApp/src/SampleApp/main/? This is required for the main directory to be considered for the search. An empty __init__.py will do.
You might also verify that Main is defined in there. Does a plain import main.models work?
| Import error and PythonPath | I'm trying to understand what the issue is:
I'm trying to import a module:
from main.models import Main
from django.contrib import admin
admin.site.register(Main)
However, when I attempt to hit the admin site, I get a django error page:
ImportError at /admin/
cannot import name Main
I noticed that it provides a dump of the **Python Path:**
Python Path: ['/Users/brian/src/SampleApp/src/SampleApp', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old', '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload', '/Library/Python/2.6/site-packages', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC', '/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode']
However, what I don't understand is where is this Python Path set?
doing an export PYTHONPATH returns nothing as it is not set in the environmental variables.
I need to import a module which is located in /Users/brian/src/SampleApp/src/SampleApp/main/models.py
Thanks
| [
"PYTHONPATH can be accessed via:\nimport sys\nprint sys.path\n\nA bit of debugging to try would be to use:\nfrom main import models\nfrom django.contrib import admin\n\nadmin.site.register(models.Main)\n\nand see if that gives you any more information.\n",
"Do you have an __init__.py in /Users/brian/src/SampleApp... | [
4,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004115827_django_python.txt |
Q:
Tkinter Toplevel Widget
def WhoisWin():
win1 = Toplevel()
win1.title("Whois")
win1.config(bg="black")
win1.geometry("300x300")
win1.resizable(0,0)
text = Text()
text1 = Text()
text1.config(width=15, height=1)
text1.config(bg="black", fg="white")
text1.pack()
def button1():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("com.whois-servers.net", 43))
s.send(text1.get("1.0", END) + "\r\n")
response = ''
while True:
a = s.recv(4096)
response += a
if a == '':
break
s.close()
text.insert(END, response)
def clear():
text.delete("1.0", END)
text1.delete("1.0", END)
frame = Frame(win1)
frame.config(bg="black")
frame.pack(pady=10, padx=5)
b = Button(frame, text="Enter", width=10, height=2, command=button1)
b.config(fg="white", bg="black")
b.pack(side=LEFT, padx=5)
c = Button(frame, text="Clear", width=10, height=2, command=clear)
c.config(fg="white", bg="black")
c.pack(side=RIGHT, padx=5)
scrollbar = Scrollbar(win1)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=35, height=15, bg="black", fg="white")
text.pack(side=LEFT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
This is just a child window that will popup when you click on the menu, I don't get any errors, but Text and Tex1 is not visible on the child window, but when I run this code on its own root window it works just find, maybe the ident is messed up or something? Any help will be appreciated, Thanks.
A:
You don't provide a parent for text or text1. When you call Text() you need to give it an argument like Text(win1) or Text(frame) so that Tkinter knows what to pack the Text widget on.
| Tkinter Toplevel Widget | def WhoisWin():
win1 = Toplevel()
win1.title("Whois")
win1.config(bg="black")
win1.geometry("300x300")
win1.resizable(0,0)
text = Text()
text1 = Text()
text1.config(width=15, height=1)
text1.config(bg="black", fg="white")
text1.pack()
def button1():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("com.whois-servers.net", 43))
s.send(text1.get("1.0", END) + "\r\n")
response = ''
while True:
a = s.recv(4096)
response += a
if a == '':
break
s.close()
text.insert(END, response)
def clear():
text.delete("1.0", END)
text1.delete("1.0", END)
frame = Frame(win1)
frame.config(bg="black")
frame.pack(pady=10, padx=5)
b = Button(frame, text="Enter", width=10, height=2, command=button1)
b.config(fg="white", bg="black")
b.pack(side=LEFT, padx=5)
c = Button(frame, text="Clear", width=10, height=2, command=clear)
c.config(fg="white", bg="black")
c.pack(side=RIGHT, padx=5)
scrollbar = Scrollbar(win1)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=35, height=15, bg="black", fg="white")
text.pack(side=LEFT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
This is just a child window that will popup when you click on the menu, I don't get any errors, but Text and Tex1 is not visible on the child window, but when I run this code on its own root window it works just find, maybe the ident is messed up or something? Any help will be appreciated, Thanks.
| [
"You don't provide a parent for text or text1. When you call Text() you need to give it an argument like Text(win1) or Text(frame) so that Tkinter knows what to pack the Text widget on.\n"
] | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004116157_python_tkinter.txt |
Q:
TypeError when running Mercurial on AppEngine
When I run "ported" Mercurial on GAE (from http://bitbucket.org/durin42/mercurial-appengine/), I meet:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 511, in __call__
handler.get(*groups)
File "/base/data/home/apps/yt-source/1.346021588701137656/hgappengine/multi_hgapps.py", line 45, in get
return self.run()
File "/base/data/home/apps/yt-source/1.346021588701137656/hgappengine/multi_hgapps.py", line 68, in run
code = self.dispatch(repo_name)
File "/base/data/home/apps/yt-source/1.346021588701137656/hgappengine/multi_hgapps.py", line 91, in dispatch
app.get()
File "/base/data/home/apps/yt-source/1.346021588701137656/hgappengine/hgapp_mod.py", line 160, in get
return self.run()
File "/base/data/home/apps/yt-source/1.346021588701137656/hgappengine/hgapp_mod.py", line 250, in run
content = getattr(webcommands, cmd)(self, req, tmpl)
File "/base/data/home/apps/yt-source/1.346021588701137656/mercurial/hgweb/webcommands.py", line 245, in shortlog
return changelog(web, req, tmpl, shortlog = True)
File "/base/data/home/apps/yt-source/1.346021588701137656/mercurial/hgweb/webcommands.py", line 224, in changelog
lessvars['revcount'] = revcount / 2
TypeError: 'function' object does not support item assignment
I'm newly in Python GAE...
A:
Found the problems: We need to use Mercurial 1.6.4 or older... Newest version (1.7) is not supported by appengine-mercurial
| TypeError when running Mercurial on AppEngine | When I run "ported" Mercurial on GAE (from http://bitbucket.org/durin42/mercurial-appengine/), I meet:
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 511, in __call__
handler.get(*groups)
File "/base/data/home/apps/yt-source/1.346021588701137656/hgappengine/multi_hgapps.py", line 45, in get
return self.run()
File "/base/data/home/apps/yt-source/1.346021588701137656/hgappengine/multi_hgapps.py", line 68, in run
code = self.dispatch(repo_name)
File "/base/data/home/apps/yt-source/1.346021588701137656/hgappengine/multi_hgapps.py", line 91, in dispatch
app.get()
File "/base/data/home/apps/yt-source/1.346021588701137656/hgappengine/hgapp_mod.py", line 160, in get
return self.run()
File "/base/data/home/apps/yt-source/1.346021588701137656/hgappengine/hgapp_mod.py", line 250, in run
content = getattr(webcommands, cmd)(self, req, tmpl)
File "/base/data/home/apps/yt-source/1.346021588701137656/mercurial/hgweb/webcommands.py", line 245, in shortlog
return changelog(web, req, tmpl, shortlog = True)
File "/base/data/home/apps/yt-source/1.346021588701137656/mercurial/hgweb/webcommands.py", line 224, in changelog
lessvars['revcount'] = revcount / 2
TypeError: 'function' object does not support item assignment
I'm newly in Python GAE...
| [
"Found the problems: We need to use Mercurial 1.6.4 or older... Newest version (1.7) is not supported by appengine-mercurial\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"mercurial",
"python",
"syntax"
] | stackoverflow_0004112441_google_app_engine_mercurial_python_syntax.txt |
Q:
How I am doing Ajax with Django now: looking for advices/comments
I would like share with you how I am doing my Ajax stuff with Django for the moment. I would like have your advices/comments to see if I am doing it right.
I will of course oversimplified the code, just to show the process.
Here is my template code:
<!-- I store the full url to access object details so I can use url feature.
If I just store the pk, I would have to hardcode the url to fetch the object
detail later. Isn't it? -->
<ul>
{% for item in items %}
<li url="{% url project.item.views.details item.pk %}">{{ item.name }}</li>
{% endfor %}
<ul>
<div id="details"></div>
<script>
$("li").click(function(elmt){
// I just reuse the url attribute from the element clicked
var url = $(elmt.currentTarget).attr('url');
$.getJSON(url, function(data) {
if (data.success) {
$("#details").html(data.html);
} else {
$("#details").html("Something went wrong");
}
});
});
</script>
Here is the code I use in my view:
def details(request, item_id):
item = Items.objects.get(pk=item_id)
# Just render a view with the details, and return the view
html = render_to_string("items/_details.html", {'item': item})
return HttResponse(simplejson.dumps({'success': True, 'html': html}), mimetype="application/json")
What do you think about my way to do that?
Thank you in advance for your help!
A:
Nothing wrong with the Django code but you may want it to work for non javascript clients as well and use valid HTML:
<ul>
{% for item in items %}
<li><a href="{{ item.get_absolute_url }}">{{ item.name }}</a></li>
{% endfor %}
<ul>
$("a").click(function(){
// I just reuse the url attribute from the element clicked
// li does not have an url attribute
var url = $(this).attr('href');
$.getJSON(url, function(data) {
if (data.success) {
$("#details").html(data.html);
} else {
$("#details").html("Something went wrong");
}
});
return false;
});
def details(request, item_id):
item = Items.objects.get(pk=item_id)
# Just render a view with the details, and return the view
if request.is_ajax():
html = render_to_string("items/_details.html", {'item': item})
return HttResponse(simplejson.dumps({'success': True, 'html': html}), mimetype="application/json")
else:
#non ajax request rendering complete html
return render_to_response("items/detail.html", {'item': item})
A:
I personally prefer using middleware to host web services since they allow you to not load Django in its entirety, but still access what you need to.
Still, using views for web services is certainly valid and works.
| How I am doing Ajax with Django now: looking for advices/comments | I would like share with you how I am doing my Ajax stuff with Django for the moment. I would like have your advices/comments to see if I am doing it right.
I will of course oversimplified the code, just to show the process.
Here is my template code:
<!-- I store the full url to access object details so I can use url feature.
If I just store the pk, I would have to hardcode the url to fetch the object
detail later. Isn't it? -->
<ul>
{% for item in items %}
<li url="{% url project.item.views.details item.pk %}">{{ item.name }}</li>
{% endfor %}
<ul>
<div id="details"></div>
<script>
$("li").click(function(elmt){
// I just reuse the url attribute from the element clicked
var url = $(elmt.currentTarget).attr('url');
$.getJSON(url, function(data) {
if (data.success) {
$("#details").html(data.html);
} else {
$("#details").html("Something went wrong");
}
});
});
</script>
Here is the code I use in my view:
def details(request, item_id):
item = Items.objects.get(pk=item_id)
# Just render a view with the details, and return the view
html = render_to_string("items/_details.html", {'item': item})
return HttResponse(simplejson.dumps({'success': True, 'html': html}), mimetype="application/json")
What do you think about my way to do that?
Thank you in advance for your help!
| [
"Nothing wrong with the Django code but you may want it to work for non javascript clients as well and use valid HTML:\n<ul>\n{% for item in items %}\n <li><a href=\"{{ item.get_absolute_url }}\">{{ item.name }}</a></li>\n{% endfor %}\n<ul>\n\n$(\"a\").click(function(){\n // I just reuse the url attribute fro... | [
2,
0
] | [] | [] | [
"ajax",
"django",
"python"
] | stackoverflow_0004116402_ajax_django_python.txt |
Q:
Match specific string + any float number in python
I am writing a script for Luxology modo (3D and VFX application), which is using python as scripting language. Somewhere in my script i am reading text file outputted from other app, and creating materials and image maps from the lines of this text file. one of the things i am doing there is creating a dictionary of the channel names from this text file, and mapping each channel name to the modo's internal channel name, so modo could understand what to do with this channels. This is a snippet that doing it:
# this is a dictionary of the channel names in the textures.txt file
# mapped to modo's internal channel names
channels = {'color':'diffColor', 'specular':'specAmount', 'normalmap':'normal'}
for channel in channels:
if channel in materials[mat].keys():
============AND SO ON==============
Everything works as expected, but there is one more channel - displacement. And the problem is that it's not just a string as other channels, but a string followed by a float number, which is a scale factor for displacement, like this:
displacement 19.378531
For now i want just to create displacement image map in modo, as i am already doing with other maps (color, normals, specular), without using this 'scale factor' number in any way. It seems easy enough, and i have tried to use Regular Expression to match string "displacement" followed by random float number, but it does not works (or, i do not use it properly)!
How can i tell python to do instead of
channels = {'color':'diffColor', 'specular':'specAmount', 'normalmap':'normal', 'displacement':'displace'}
to do this:
channels = {'color':'diffColor', 'specular':'specAmount', 'normalmap':'normal', 'displacement' + 'ANY_FLOAT_NUMBER':'displace'}
A:
You can do this using standard string methods to strip the coefficient from the string if it begins with 'displacement':
for material in materials[mat].keys():
if material.startswith('displacement'):
# coefficient = float(material.split('displacement')[1])
material = material.rstrip('0123456789.')
if material in channels:
channelName = channels[material]
...
I've added commented-out instruction that you can uncomment if you later decide you want the coefficient (might be important if you start getting displacement artefacts!).
Edit after reading comments and full code.
You can't have anything programmatic or varying in a dictionary key. But if you want to keep the pattern you've already got, the simplest solution would be to ignore my suggestion above and just remove the floats at the end before you start searching with a quick loop like this:
for channel in channels:
for key in materials[mat].keys():
if "." in key:
materials[mat][key.rstrip("0123456789.")] = materials[mat].pop(key)
if channel in materials[mat].keys():
A:
I'm not entirely sure I understand the question, but I think you just have to do something a bit less efficient:
for material in materials:
if material in channels:
...
if 'displacement' in material:
...
A:
Based on your pastebin, I believe this should work for you:
# ...
infile.close()
channels = {'color':'diffColor', 'specular':'specAmount', 'normalmap':'normal'}
re_dis = re.compile(r'displacement\s[-+]?[0-9]*\.?[0-9]+')
for material, values in materials.items():
lx.eval('select.item {Matr: %s} set textureLayer' % material)
uvmap = materials[material]['uvmap']
for v in values:
m = re_dis.match(v)
if m or v in channels.keys():
lx.eval('shader.create constant')
lx.eval('item.setType imageMap textureLayer')
imagepath = materials[material][v]
imagename = os.path.splitext(os.path.basename(imagepath))[0]
lx.eval('clip.addStill {%s}' % imagepath)
lx.eval('texture.setIMap {%s}' % imagename)
if m:
# we can't auto map to the channels dict
lx.eval('shader.setEffect %s' % 'displace')
else:
lx.eval('shader.setEffect %s' % channels[v])
Also don't forget to add import re to the top of your script.
| Match specific string + any float number in python | I am writing a script for Luxology modo (3D and VFX application), which is using python as scripting language. Somewhere in my script i am reading text file outputted from other app, and creating materials and image maps from the lines of this text file. one of the things i am doing there is creating a dictionary of the channel names from this text file, and mapping each channel name to the modo's internal channel name, so modo could understand what to do with this channels. This is a snippet that doing it:
# this is a dictionary of the channel names in the textures.txt file
# mapped to modo's internal channel names
channels = {'color':'diffColor', 'specular':'specAmount', 'normalmap':'normal'}
for channel in channels:
if channel in materials[mat].keys():
============AND SO ON==============
Everything works as expected, but there is one more channel - displacement. And the problem is that it's not just a string as other channels, but a string followed by a float number, which is a scale factor for displacement, like this:
displacement 19.378531
For now i want just to create displacement image map in modo, as i am already doing with other maps (color, normals, specular), without using this 'scale factor' number in any way. It seems easy enough, and i have tried to use Regular Expression to match string "displacement" followed by random float number, but it does not works (or, i do not use it properly)!
How can i tell python to do instead of
channels = {'color':'diffColor', 'specular':'specAmount', 'normalmap':'normal', 'displacement':'displace'}
to do this:
channels = {'color':'diffColor', 'specular':'specAmount', 'normalmap':'normal', 'displacement' + 'ANY_FLOAT_NUMBER':'displace'}
| [
"You can do this using standard string methods to strip the coefficient from the string if it begins with 'displacement':\nfor material in materials[mat].keys():\n if material.startswith('displacement'):\n # coefficient = float(material.split('displacement')[1])\n material = material.rstrip('012345... | [
1,
0,
0
] | [] | [] | [
"3d",
"python"
] | stackoverflow_0004113948_3d_python.txt |
Q:
anyone knows why my program is not giving result?
import copy
class Polynomial(dict):
def __init__(self, coefficients):
self.coeff = coefficients
def dictionary(self,x):
sum=0.0
d=self.coeff
for k in d:
sum +=d[k]*x**k
return sum
def __add__(self, other):
new=copy.deepcopy(self)
for k,d in other.coeff:
if k in new:
new[k] +=value
else:
new[k]=value
return Polynomial(new)
p = Polynomial({20:1,1:-1,100:4})
q = Polynomial({1:1,100:-3})
print q+q
A:
Iterating over a dict yields keys, not items.
for k, value in other.coeff.iteritems():
A:
for k in d:
sum +=d[k]*x**k
return sum
change to
for k, v in d.iteritems():
sum +=v*x**k
return sum
EDIT: I see the problem...
in __add__(), value is not defined therefore it gets set to None and no result will happen
| anyone knows why my program is not giving result? | import copy
class Polynomial(dict):
def __init__(self, coefficients):
self.coeff = coefficients
def dictionary(self,x):
sum=0.0
d=self.coeff
for k in d:
sum +=d[k]*x**k
return sum
def __add__(self, other):
new=copy.deepcopy(self)
for k,d in other.coeff:
if k in new:
new[k] +=value
else:
new[k]=value
return Polynomial(new)
p = Polynomial({20:1,1:-1,100:4})
q = Polynomial({1:1,100:-3})
print q+q
| [
"Iterating over a dict yields keys, not items.\nfor k, value in other.coeff.iteritems():\n\n",
" for k in d:\n sum +=d[k]*x**k\n return sum\n\nchange to\n for k, v in d.iteritems():\n sum +=v*x**k\n return sum\n\nEDIT: I see the problem...\nin __add__(), value is not defined therefore it... | [
4,
2
] | [] | [] | [
"class",
"python"
] | stackoverflow_0004117038_class_python.txt |
Q:
Confused by self["name"] = filename
I'm currently reading this amazing book called "Dive into Python". Up to now everything has made sense to me, but the following method has left me with some questions. Its in the chapter about initializing classes:
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
It's only the last line I don't get. The way I see it at the moment, the calling object has a list, whose item "name" is assigned the value of the argument passed. But this doesn't make sense to me, since I thought that you can only access list indices by integers.
The book says the following about this line: "You're assigning the argument filename as the value of this object's name key." Is the name key another variable that every object defines (like doc)? And if yes, why can it be accessed like that?
A:
[...] isn't just for lists. Any type can support it, and the index doesn't necessarily have to be an integer. self is the current object, which according to your code derives from UserDict, which supports the item manipulation methods.
A:
You're extending a dictionary, by doing class FileInfo(UserDict), that's why you can reference to the key doing self['name'] = filename
A:
The class inherits from UserDict which I presume is a dict-like class. For all subclasses of dicts (which keeps the dict interface intact), you can treat self as a dict, which is why you can do self[key] = value
A:
Since your class derives from UserDict, it inherits a __getitem__() method that takes an arbitrary key, not just an integer:
self["name"] = filename # Associate the filename with the "name" key.
A:
No, the self object is a subclass of UserDict, which is a form of hash table (known as a dictionary or dict in Python). The last line is simply creating a key "name" to the filename.
| Confused by self["name"] = filename | I'm currently reading this amazing book called "Dive into Python". Up to now everything has made sense to me, but the following method has left me with some questions. Its in the chapter about initializing classes:
class FileInfo(UserDict):
"store file metadata"
def __init__(self, filename=None):
UserDict.__init__(self)
self["name"] = filename
It's only the last line I don't get. The way I see it at the moment, the calling object has a list, whose item "name" is assigned the value of the argument passed. But this doesn't make sense to me, since I thought that you can only access list indices by integers.
The book says the following about this line: "You're assigning the argument filename as the value of this object's name key." Is the name key another variable that every object defines (like doc)? And if yes, why can it be accessed like that?
| [
"[...] isn't just for lists. Any type can support it, and the index doesn't necessarily have to be an integer. self is the current object, which according to your code derives from UserDict, which supports the item manipulation methods.\n",
"You're extending a dictionary, by doing class FileInfo(UserDict), that's... | [
6,
2,
2,
2,
2
] | [] | [] | [
"python",
"self"
] | stackoverflow_0004117060_python_self.txt |
Q:
How do I use the Twitter streaming API?
stream.filter(locations=[-122.75,36.8,-121.75,37.8,-74,40,-73,41],track=["twitpic"])
This works. However, it's not "AND". It's "OR". This line gets the location OR keyword.
How do I make it "AND"?
Here's the code to the library I'm using:
def filter(self, follow=None, track=None, async=False, locations=None):
self.parameters = {}
self.headers['Content-type'] = "application/x-www-form-urlencoded"
if self.running:
raise TweepError('Stream object already connected!')
self.url = '/%i/statuses/filter.json?delimited=length' % STREAM_VERSION
if follow:
self.parameters['follow'] = ','.join(map(str, follow))
if track:
self.parameters['track'] = ','.join(map(str, track))
if locations and len(locations) > 0:
assert len(locations) % 4 == 0
self.parameters['locations'] = ','.join(['%.2f' % l for l in locations])
self.body = urllib.urlencode(self.parameters)
self.parameters['delimited'] = 'length'
self._start(async)
https://github.com/joshthecoder/tweepy/blob/master/tweepy/streaming.py
A:
http://dev.twitter.com/pages/streaming_api_methods#locations
Bounding boxes are logical ORs. A
locations parameter may be combined
with track parameters, but note that
all terms are logically ORd, so the
query string
track=twitter&locations=-122.75,36.8,-121.75,37.8
would match any tweets containing the
term Twitter (even non-geo tweets) OR
coming from the San Francisco area.
...
Multiple bounding boxes may be
specified by concatenating
latitude/longitude pairs, for example:
locations=-122.75,36.8,-121.75,37.8,-74,40,-73,41 would track tweets from San Francisco
and New York City.
For more information read the full documentation.
| How do I use the Twitter streaming API? | stream.filter(locations=[-122.75,36.8,-121.75,37.8,-74,40,-73,41],track=["twitpic"])
This works. However, it's not "AND". It's "OR". This line gets the location OR keyword.
How do I make it "AND"?
Here's the code to the library I'm using:
def filter(self, follow=None, track=None, async=False, locations=None):
self.parameters = {}
self.headers['Content-type'] = "application/x-www-form-urlencoded"
if self.running:
raise TweepError('Stream object already connected!')
self.url = '/%i/statuses/filter.json?delimited=length' % STREAM_VERSION
if follow:
self.parameters['follow'] = ','.join(map(str, follow))
if track:
self.parameters['track'] = ','.join(map(str, track))
if locations and len(locations) > 0:
assert len(locations) % 4 == 0
self.parameters['locations'] = ','.join(['%.2f' % l for l in locations])
self.body = urllib.urlencode(self.parameters)
self.parameters['delimited'] = 'length'
self._start(async)
https://github.com/joshthecoder/tweepy/blob/master/tweepy/streaming.py
| [
"http://dev.twitter.com/pages/streaming_api_methods#locations\n\nBounding boxes are logical ORs. A\n locations parameter may be combined\n with track parameters, but note that\n all terms are logically ORd, so the\n query string\n track=twitter&locations=-122.75,36.8,-121.75,37.8\n would match any tweets cont... | [
2
] | [] | [] | [
"api",
"http",
"python",
"streaming",
"twitter"
] | stackoverflow_0004116799_api_http_python_streaming_twitter.txt |
Q:
how to speed up my couchdb views written with python
I'm writing my couchdb views with python. I think it's not very ... pythonic to do something like
def fun(doc):
import re
# do something with re
yield 1, 1
because re is for every document imported. putting import re at the beginning gives me an error (string should compile to a proper function), a
del re
at the view's end makes re unavailable within the function.
so how can I avoid importing re again and again?
A:
View server handles many documents with same context. So import re really imports module only while handles first document. All other map calls will only lookup sys.modules.
A:
I got into the same trouble recently and solved it like this:
import re
def foo(doc, re_xx=re.compile("required-pattern")):
# use re_xx
yield 1, 1
del re
A:
If you are using the re module, there may be things that could be done with your regular expressions and how they are compiled that would speed things up more than removing the module lookup would (dictionaries in python are extremely fast). I don't understand why you would want to del re at the end of the function, that will probably slow things down.
Do you have a way of timing this so that you can measure the improvements/regressions when you tune the view? Getting some timing established will make it much easier to tune.
| how to speed up my couchdb views written with python | I'm writing my couchdb views with python. I think it's not very ... pythonic to do something like
def fun(doc):
import re
# do something with re
yield 1, 1
because re is for every document imported. putting import re at the beginning gives me an error (string should compile to a proper function), a
del re
at the view's end makes re unavailable within the function.
so how can I avoid importing re again and again?
| [
"View server handles many documents with same context. So import re really imports module only while handles first document. All other map calls will only lookup sys.modules.\n",
"I got into the same trouble recently and solved it like this:\nimport re\n\ndef foo(doc, re_xx=re.compile(\"required-pattern\")):\n ... | [
1,
1,
0
] | [] | [] | [
"couchdb",
"python"
] | stackoverflow_0004079838_couchdb_python.txt |
Q:
Better ways to handle AppEngine requests that time out?
Sometimes, with requests that do a lot, Google AppEngine returns an error. I have been handling this by some trickery: memcaching intermediate processed data and just requesting the page again. This often works because the memcached data does not have to be recalculated and the request finishes in time.
However... this hack requires seeing an error, going back, and clicking again. Obviously less than ideal.
Any suggestions?
inb4: "optimize your process better", "split your page into sub-processes", and "use taskqueue".
Thanks for any thoughts.
Edit - To clarify:
Long wait for requests is ok because the function is administrative. I'm basically looking to run a data-mining function. I'm searching over my datastore and modifying a bunch of objects. I think the correct answer is that AppEngine may not be the right tool for this. I should be exporting the data to a computer where I can run functions like this on my own. It seems AppEngine is really intended for serving with lighter processing demands. Maybe the quota/pricing model should offer the option to increase processing timeouts and charge extra.
A:
I have been handling something similar by building a custom automatic retry dispatcher on the client. Whenever an ajax call to the server fails, the client will retry it.
This works very well if your page is ajaxy. If your app spits entire HTML pages then you can use a two pass process: first send an empty page containing only an ajax request. Then, when AppEngine receives that ajax request, it outputs the same HTML you had before. If the ajax call succeeds it fills the DOM with the result. If it fails, it retries once.
A:
If interactive user requests are hitting the 30 second deadline, you have bigger problems: your user has almost certainly given up and left anyway.
What you can do depends on what your code is doing. There's a lot to be optimized by batching datastore operations, or reducing them by changing how you model your data; you can offload work to the Task Queue; for URLFetches, you can execute them in parallel. Tell us more about what you're doing and we may be able to provide more concrete suggestions.
| Better ways to handle AppEngine requests that time out? | Sometimes, with requests that do a lot, Google AppEngine returns an error. I have been handling this by some trickery: memcaching intermediate processed data and just requesting the page again. This often works because the memcached data does not have to be recalculated and the request finishes in time.
However... this hack requires seeing an error, going back, and clicking again. Obviously less than ideal.
Any suggestions?
inb4: "optimize your process better", "split your page into sub-processes", and "use taskqueue".
Thanks for any thoughts.
Edit - To clarify:
Long wait for requests is ok because the function is administrative. I'm basically looking to run a data-mining function. I'm searching over my datastore and modifying a bunch of objects. I think the correct answer is that AppEngine may not be the right tool for this. I should be exporting the data to a computer where I can run functions like this on my own. It seems AppEngine is really intended for serving with lighter processing demands. Maybe the quota/pricing model should offer the option to increase processing timeouts and charge extra.
| [
"I have been handling something similar by building a custom automatic retry dispatcher on the client. Whenever an ajax call to the server fails, the client will retry it.\nThis works very well if your page is ajaxy. If your app spits entire HTML pages then you can use a two pass process: first send an empty page c... | [
1,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004112235_google_app_engine_python.txt |
Q:
Is it a bad idea to nest importing declarations in Python?
I'm reading App Engine's documentation and i saw that i could nest some imports, for example:
from google.appengine.ext import db, webapp #so on
Is it a bad thing to do so? If it's not (since it works), what's the limit/advantages/disadvantages of that?
A:
That's not nesting, that's just importing specific names. There's nothing wrong with that per se, but as always consult PEP 8 for style guidelines.
A:
No it's not. See the PEP8 python styling standards. Here's the pertinent excerpt:
Imports
- Imports should usually be on separate lines, e.g.:
Yes: import os
import sys
No: import sys, os
it's okay to say this though:
from subprocess import Popen, PIPE
- Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants.
Imports should be grouped in the following order:
1. standard library imports
2. related third party imports
3. local application/library specific imports
A:
I would avoid it. The examples given in PEP 8, quoted by sdolan, are imports of specific names from inside a module, but what you're asking about is importing multiple different packages on a single line. It won't break, but separating it out is neater, and makes it easier to refactor and change imports later.
| Is it a bad idea to nest importing declarations in Python? | I'm reading App Engine's documentation and i saw that i could nest some imports, for example:
from google.appengine.ext import db, webapp #so on
Is it a bad thing to do so? If it's not (since it works), what's the limit/advantages/disadvantages of that?
| [
"That's not nesting, that's just importing specific names. There's nothing wrong with that per se, but as always consult PEP 8 for style guidelines.\n",
"No it's not. See the PEP8 python styling standards. Here's the pertinent excerpt:\nImports\n\n- Imports should usually be on separate lines, e.g.:\n\n Yes: ... | [
3,
2,
1
] | [] | [] | [
"import",
"python"
] | stackoverflow_0004112042_import_python.txt |
Q:
PHP in command line
Using Python I can test my code in the terminal / command line by typing
python
python> print "hello world"
I would like to do this with PHP too, but when typing:
php
echo "hello world";
it does not work.. Is this possible? what should I do?
A quick search on the internet gives a lot of results that call an actual .php file to run. I only want to test a single sentence if possible, without creating files and stuff.
A:
Try
php -a
which starts an interactive PHP shell. Be aware that this requires PHP to be built with --with-readline (which is not the case if you're using the bundeled PHP with Mac OS X e.g.).
Alternatively, if you don't require the interactivity of a separate shell, use
php -r 'print_r(get_defined_constants());'
to execute a PHP snippet (this doesn't require the readline support).
A:
php -r "echo 'hello world';"
A:
If you run php without the -a option, don't forget the <?php at the start
| PHP in command line | Using Python I can test my code in the terminal / command line by typing
python
python> print "hello world"
I would like to do this with PHP too, but when typing:
php
echo "hello world";
it does not work.. Is this possible? what should I do?
A quick search on the internet gives a lot of results that call an actual .php file to run. I only want to test a single sentence if possible, without creating files and stuff.
| [
"Try \nphp -a\n\nwhich starts an interactive PHP shell. Be aware that this requires PHP to be built with --with-readline (which is not the case if you're using the bundeled PHP with Mac OS X e.g.).\nAlternatively, if you don't require the interactivity of a separate shell, use\nphp -r 'print_r(get_defined_constants... | [
8,
1,
1
] | [] | [] | [
"code_testing",
"command_line",
"php",
"python",
"terminal"
] | stackoverflow_0004117447_code_testing_command_line_php_python_terminal.txt |
Q:
Clearing a log file which is in use
On my job, I am working with a big .NET application which writes to a log file. Let's call the application CompanyApplication. I have written a simple Python script which clears the log:
file_object = open('C:\\log.txt', 'w')
file_object.write("")
file_object.close()
When CompanyApplication.exe is not running this works fine. However, when CompanyApplication.exe is running I get this error:
Traceback (most recent call last):
File "deleteLog.py", line 1, in <module>
file_object = open('C:\log.txt', 'w')
IOError: [Errno 13] Permission denied: 'C:\log.txt'
This must be because CompanyApplication holds a lock on the log file. Is there any way I can "unlock" the log file, clear it, and then "hand the lock back" to CompanyApplication? I would prefer a solution which could be automated (that's why I wrote the Python script in the first place).
Additional info: There is only so much I can do to change CompanyApplication itself. I am using Windows XP Pro. I have administrator privileges.
A:
You need to fill out the FileShare parameter for the open call on the log file in your .NET program.
Specifically you will want to allow read/write sharing.
Depending on how your .NET application works when writing to the log though, what you are suggesting might not work as expected and may cause problems with the .NET program.
You could simply start a thread in the .NET program which creates an event and waits on it. Later you can set that event from your Python program and the .NET will safely clear it's own log file and reset the event.
A:
It's likely that the output to the file is buffered, so even if you could take over the file and empty it, you would not be able to empty the buffer in the running program. The result would either be a partial entry at the beginning of the file, or that the program continues to write at the previous position which would fill everything up to that point with garbage.
To be able to empty the log while the application is running, the logging in the application has to be rewritten. It has to only open the log file when needed, and close it after writing to it. That way your script can attempt to clear the file, and if it fails it can wait a moment and then try again.
A:
No. As you said, CompanyApplication has a lock on the file. What would be the point of a lock if any other application can unlock it at any time?
| Clearing a log file which is in use | On my job, I am working with a big .NET application which writes to a log file. Let's call the application CompanyApplication. I have written a simple Python script which clears the log:
file_object = open('C:\\log.txt', 'w')
file_object.write("")
file_object.close()
When CompanyApplication.exe is not running this works fine. However, when CompanyApplication.exe is running I get this error:
Traceback (most recent call last):
File "deleteLog.py", line 1, in <module>
file_object = open('C:\log.txt', 'w')
IOError: [Errno 13] Permission denied: 'C:\log.txt'
This must be because CompanyApplication holds a lock on the log file. Is there any way I can "unlock" the log file, clear it, and then "hand the lock back" to CompanyApplication? I would prefer a solution which could be automated (that's why I wrote the Python script in the first place).
Additional info: There is only so much I can do to change CompanyApplication itself. I am using Windows XP Pro. I have administrator privileges.
| [
"You need to fill out the FileShare parameter for the open call on the log file in your .NET program.\nSpecifically you will want to allow read/write sharing.\nDepending on how your .NET application works when writing to the log though, what you are suggesting might not work as expected and may cause problems with ... | [
3,
1,
0
] | [] | [] | [
".net",
"file_io",
"file_permissions",
"python"
] | stackoverflow_0004117596_.net_file_io_file_permissions_python.txt |
Q:
Error when importing module, dlopen(): Symbol not found
I have written a python extension in C (using cython, actually, though that's beside the point) which uses the AudioUnit framework in Mac OSX. The module builds correctly, but when I try to import it from the python command line, I get the following error:
ImportError: dlopen(myproject/audiomodule.so, 2): Symbol not found: _AudioUnitSetProperty
Referenced from: /Views/python/lib/python3.1/site-packages/myproject/audiomodule.so
Expected in: dynamic lookup
How do I tell python that it needs to use the AudioUnit framework when loading this module?
A:
Bah, as was written in this answer regarding a similar question, the key was to pass the -framework and AudioUnit arguments as two separate tuple items. Furthermore, my platform detection was incorrect, so these flags were not being applied correctly during the build.
| Error when importing module, dlopen(): Symbol not found | I have written a python extension in C (using cython, actually, though that's beside the point) which uses the AudioUnit framework in Mac OSX. The module builds correctly, but when I try to import it from the python command line, I get the following error:
ImportError: dlopen(myproject/audiomodule.so, 2): Symbol not found: _AudioUnitSetProperty
Referenced from: /Views/python/lib/python3.1/site-packages/myproject/audiomodule.so
Expected in: dynamic lookup
How do I tell python that it needs to use the AudioUnit framework when loading this module?
| [
"Bah, as was written in this answer regarding a similar question, the key was to pass the -framework and AudioUnit arguments as two separate tuple items. Furthermore, my platform detection was incorrect, so these flags were not being applied correctly during the build.\n"
] | [
2
] | [] | [] | [
"dlopen",
"python"
] | stackoverflow_0004115702_dlopen_python.txt |
Q:
Properly evaluating double integral in python
I am trying to compute a definite double integral using scipy. The integrand is a bit complicated, as it contains some probability distributions to give weight to how likely is each value of x and y (like a mixture model). The following code evaluated to a negative number, but it should be bound by [0,1]. Additionally, it took about half an hour to compute.
I have two questions.
1) Is there a better way to calculate this integral?
2) Where is this negative value coming from? The big question for me is how to speed the calculation up, as I can find the bug in my code that's leading to the negative later on my own.
from scipy import stats
from scipy.integrate import dblquad
import itertools
p= [list whose entries are each different stats.beta(a,b) distributions]
def integrand(x,y):
delta=x-y
marg=0
for distA,distB in itertools.permutations(p,2):
first=distA.pdf(x)
second=distB.pdf(y)
weight1=0
weight2=0
for distC in p:
if distC == distA:
continue
w1=distC.cdf(x)-distC.cdf(y)
if weight1 == 0:
weight1=w1
else:
weight1=weight1*w1
marg+=(first*weight1*second)
I=delta*marg
return I
expect=dblquad(integrand,0,1,lambda x: 0, lambda x: x)
This is asking essentially what for the expected value of the maximal distance between two points is in a vector of distributions. The limits of integration are y ∊ [0,x] and x ∊ [0,1]. This gave me about -.49, with an estimated error of the integral on the order of 10e-10, so it shouldn't be due to the integration method.
I've been fighting with this for a while and appreciate any help. Thanks.
edit: corrected typo
A:
There are several ways to increase the speed of your computation.
You can use the epsabs and epsrel parameters to dblquad to increase the tolreance of your integration. Of course, your results will be less accurate, but for debugging this is fine.
You can considerably reduce the number of function evaluations in integrand by reordering the code like (warning, untested code)
def integrand(x, y):
marg = 0.0
cdf = dict((id(distC), distC.cdf(x) - distC.cdf(y)) for distC in p)
for distA in p:
weight = numpy.prod(cdf[id(distC)]
for distC in p if distC is not distA)
marg += weight * distA.pdf(x) * sum(
distB.pdf(y) for distB in p if distB is not distA)
return (x-y) * marg
But note that Python has quite an overhead for function calls, so writing this in pure Python won't get you too far (using something like Cython for this problem might help a bit).
I do not know why the integral becomes negative. Maybe I could tell you if you would give an example for p -- this would enable us to actually try your code.
A:
The error given by the integration method is just a number telling you how well the convergence behaviour is. Have you tried to calculate explicit values of the integrand?
By the way: Are you integrating pdf's? If yes: Are you sure about your integration limits?
| Properly evaluating double integral in python | I am trying to compute a definite double integral using scipy. The integrand is a bit complicated, as it contains some probability distributions to give weight to how likely is each value of x and y (like a mixture model). The following code evaluated to a negative number, but it should be bound by [0,1]. Additionally, it took about half an hour to compute.
I have two questions.
1) Is there a better way to calculate this integral?
2) Where is this negative value coming from? The big question for me is how to speed the calculation up, as I can find the bug in my code that's leading to the negative later on my own.
from scipy import stats
from scipy.integrate import dblquad
import itertools
p= [list whose entries are each different stats.beta(a,b) distributions]
def integrand(x,y):
delta=x-y
marg=0
for distA,distB in itertools.permutations(p,2):
first=distA.pdf(x)
second=distB.pdf(y)
weight1=0
weight2=0
for distC in p:
if distC == distA:
continue
w1=distC.cdf(x)-distC.cdf(y)
if weight1 == 0:
weight1=w1
else:
weight1=weight1*w1
marg+=(first*weight1*second)
I=delta*marg
return I
expect=dblquad(integrand,0,1,lambda x: 0, lambda x: x)
This is asking essentially what for the expected value of the maximal distance between two points is in a vector of distributions. The limits of integration are y ∊ [0,x] and x ∊ [0,1]. This gave me about -.49, with an estimated error of the integral on the order of 10e-10, so it shouldn't be due to the integration method.
I've been fighting with this for a while and appreciate any help. Thanks.
edit: corrected typo
| [
"There are several ways to increase the speed of your computation.\n\nYou can use the epsabs and epsrel parameters to dblquad to increase the tolreance of your integration. Of course, your results will be less accurate, but for debugging this is fine.\nYou can considerably reduce the number of function evaluations... | [
1,
0
] | [] | [] | [
"integration",
"python",
"scipy"
] | stackoverflow_0004035369_integration_python_scipy.txt |
Q:
3D grid interpolation in Python
I have a regularly sampled grid, x,y,z and variable v. I would like to interpolate based on given x,y, &z values. I do not want to use numpy or scipy, because they are not installed on the platform I will be running on.
If I can locate the surrounding 8 grid nodes what math can I use to interpolate?
Thanks
A:
This actually seems to be a math question, but you also mentioned Python, so I try to give some code. You would usually use trilinear interpolation.
So we assume your grid has the corners (0.0, 0.0, 0.0) and (max_x, max_y, max_z) and is aligned with the coordinate system. We denote the number of cells along each axis by (n_x, n_y, n_z) respectively and the point you wish to evaluate at by (x, y, z) (all of type float). Then your logic might be something similar to
a_x = x * n_x / max_x
a_y = y * n_y / max_y
a_z = z * n_z / max_z
i_x = math.floor(a_x)
i_y = math.floor(a_y)
i_z = math.floor(a_z)
l_x = a_x - i_x
l_y = a_y - i_y
l_z = a_z - i_z
The indices of the 8 adjacent grid vertices now are (i_x, i_y, i_z), (i_x+1, i_y, i_z), (i_x, i_y+1, i_z), ..., (i_x+1, i_y+1, i_z+1). The local coordinates of your point within the grid cell are (l_x, l_y, l_z). Together with the linked Wikipedia article, this should get you going (note that the notation is different there).
| 3D grid interpolation in Python | I have a regularly sampled grid, x,y,z and variable v. I would like to interpolate based on given x,y, &z values. I do not want to use numpy or scipy, because they are not installed on the platform I will be running on.
If I can locate the surrounding 8 grid nodes what math can I use to interpolate?
Thanks
| [
"This actually seems to be a math question, but you also mentioned Python, so I try to give some code. You would usually use trilinear interpolation.\nSo we assume your grid has the corners (0.0, 0.0, 0.0) and (max_x, max_y, max_z) and is aligned with the coordinate system. We denote the number of cells along eac... | [
2
] | [] | [] | [
"grid",
"interpolation",
"python"
] | stackoverflow_0004117172_grid_interpolation_python.txt |
Q:
Find in a dynamic pythonic way the minimum elements in a partially ordered set
Let Os be a partially ordered set, and given any two objects O1 and O2 in Os, F(O1,O2) will return 1 if O1 is bigger than O2, -1 if O1 is smaller than O2, 2 if they are incomparable, and 0 if O1 is equal to O2.
I need to find the subset Mn of elements is Os that are the minimum. That is for each A in Mn, and for each B in Os, F(A,B) is never equal to 1.
It is not hard to do, but I am convinced it could be done in a more pythonic way.
The fast and dirty way is:
def GetMinOs(Os):
Mn=set([])
NotMn=set([])
for O1 in Os:
for O2 in Os:
rel=f(O1,O2)
if rel==1: NotMn|=set([O1])
elif rel==-1: NotMn|=set([O2])
Mn=Os-NotMn
return Mn
In particular I am not happy with the fact that I am essentially going through all the elements N^2 times. I wonder if there could be a dynamic way.
By "dynamic" I don't mean merely fast, but also such that once something is discovered being not a possible in the minimum, maybe it could be taken off. And doing all this in a pythonic, elegant way
A:
GetMinOs2 below, "dynamically" removes elements which are known to be non-minimal. It uses a list Ol which starts with all the elements of Os.
A "pointer" index l points to the "end" of the list Ol. When a non-minimal element is found, its position is swapped with the value in Ol[l] and the pointer l is decremented so the effective length of Ol is shrunk.
Doing so removes non-minimal elements, so you don't check them again.
GetMinOs2 assumes f has the normal properties of a comparison function: transitivity, commutativity, etc.
In the test code below, with a dreamt-up f, my timeit run shows about a 54x improvement in speed:
def f(O1,O2):
if O1%4==3 or O2%4==3: return 2
return cmp(O1,O2)
def GetMinOs(Os):
Mn=set([])
NotMn=set([])
for O1 in Os:
for O2 in Os:
rel=f(O1,O2)
if rel==1: NotMn|=set([O1])
elif rel==-1: NotMn|=set([O2])
Mn=Os-NotMn
return Mn
def GetMinOs2(Os):
Ol=list(Os)
l=len(Ol)
i=0
j=1
while i<l:
while j<l:
rel=f(Ol[i],Ol[j])
if rel==1:
l-=1
Ol[i]=Ol[l]
j=i+1
break
elif rel==-1:
l-=1
Ol[j]=Ol[l]
else:
j+=1
else:
i+=1
j=i+1
return set(Ol[:l])
Os=set(range(1000))
if __name__=='__main__':
answer=GetMinOs(Os)
result=GetMinOs2(Os)
assert answer==result
The timeit results are:
% python -mtimeit -s'import test' 'test.GetMinOs2(test.Os)'
1000 loops, best of 3: 22.7 msec per loop
% python -mtimeit -s'import test' 'test.GetMinOs(test.Os)'
10 loops, best of 3: 1.23 sec per loop
PS. Please be warned: I haven't thoroughly checked the algorithm in GetMinOs2, but I think the general idea is right. I've put a little test at the end of the script which shows it works at least on the sample data set(range(1000)).
| Find in a dynamic pythonic way the minimum elements in a partially ordered set | Let Os be a partially ordered set, and given any two objects O1 and O2 in Os, F(O1,O2) will return 1 if O1 is bigger than O2, -1 if O1 is smaller than O2, 2 if they are incomparable, and 0 if O1 is equal to O2.
I need to find the subset Mn of elements is Os that are the minimum. That is for each A in Mn, and for each B in Os, F(A,B) is never equal to 1.
It is not hard to do, but I am convinced it could be done in a more pythonic way.
The fast and dirty way is:
def GetMinOs(Os):
Mn=set([])
NotMn=set([])
for O1 in Os:
for O2 in Os:
rel=f(O1,O2)
if rel==1: NotMn|=set([O1])
elif rel==-1: NotMn|=set([O2])
Mn=Os-NotMn
return Mn
In particular I am not happy with the fact that I am essentially going through all the elements N^2 times. I wonder if there could be a dynamic way.
By "dynamic" I don't mean merely fast, but also such that once something is discovered being not a possible in the minimum, maybe it could be taken off. And doing all this in a pythonic, elegant way
| [
"GetMinOs2 below, \"dynamically\" removes elements which are known to be non-minimal. It uses a list Ol which starts with all the elements of Os. \nA \"pointer\" index l points to the \"end\" of the list Ol. When a non-minimal element is found, its position is swapped with the value in Ol[l] and the pointer l is d... | [
2
] | [] | [] | [
"algorithm",
"math",
"python"
] | stackoverflow_0004117859_algorithm_math_python.txt |
Q:
How to gain root privileges in python via a graphical sudo?
Part of my python program needs administrator access. How can I gain root privileges using a GUI popup similar to the gksudo command?
I only need root privileges for a small part of my program so it would be preferable to only have the privileges for a particular function.
I'm hoping to be able to do something like:
gksudo(my_func, 'description of why password is needed')
A:
gksudo can be used to launch programs running with administrator privileges. The part of your application that needs to run as root, must be able to be invoked as a separate process from the command line. If you need some form of communication between the two, you could use sockets or watch for a file, etc.
A:
You have two options here:
You will need to make the part of the program that requires root privileges a separate file and then execute the file like this:
>>> import subprocess
>>> subprocess.call(['gksudo','python that_file.py'])
which will bring up the password prompt and run that_file.py as root
You could also require that a program be run as root from the start and just have the program user type "gksudo python your_program.py" in the command-line from the start which is obviously not the best idea if your program is normally launched from a menu.
| How to gain root privileges in python via a graphical sudo? | Part of my python program needs administrator access. How can I gain root privileges using a GUI popup similar to the gksudo command?
I only need root privileges for a small part of my program so it would be preferable to only have the privileges for a particular function.
I'm hoping to be able to do something like:
gksudo(my_func, 'description of why password is needed')
| [
"gksudo can be used to launch programs running with administrator privileges. The part of your application that needs to run as root, must be able to be invoked as a separate process from the command line. If you need some form of communication between the two, you could use sockets or watch for a file, etc.\n",
... | [
4,
3
] | [] | [] | [
"gksudo",
"python"
] | stackoverflow_0004112737_gksudo_python.txt |
Q:
Django model formsets - modifying form labels and defaults
I'm building a formset like so:
InterestFormSet = modelformset_factory(Interest, \
formset=BaseInterestFormSet, exclude=('userid',), extra=2)
And I want set default labels and values for elements of this form.
I know that in simple forms I can use the fields dict to change these things for specific fields of the form, but how is this done with a formset?
I tried extending the formset (as you can see) to see if I could access self.fields from within __init__, but no luck.
A:
Something like this should do what you want:
class InterestForm(ModelForm):
pub_date = DateField(label='Publication date')
class Meta:
model = Interest
exclude = ('userid',)
InterestFormSet = modelformset_factory(Interest, form=InterestForm, extra=2)
A:
Formsets don't have fields, they only have forms which have fields. So you have to deal directly with those forms.
| Django model formsets - modifying form labels and defaults | I'm building a formset like so:
InterestFormSet = modelformset_factory(Interest, \
formset=BaseInterestFormSet, exclude=('userid',), extra=2)
And I want set default labels and values for elements of this form.
I know that in simple forms I can use the fields dict to change these things for specific fields of the form, but how is this done with a formset?
I tried extending the formset (as you can see) to see if I could access self.fields from within __init__, but no luck.
| [
"Something like this should do what you want:\nclass InterestForm(ModelForm):\n pub_date = DateField(label='Publication date')\n\n class Meta:\n model = Interest\n exclude = ('userid',)\n\n\nInterestFormSet = modelformset_factory(Interest, form=InterestForm, extra=2)\n\n",
"Formsets don't have... | [
1,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0004115541_django_django_forms_python.txt |
Q:
Get second element text with XPath?
<span class='python'>
<a>google</a>
<a>chrome</a>
</span>
I want to get chrome and have it working like this already.
q = item.findall('.//span[@class="python"]//a')
t = q[1].text # first element = 0
I'd like to combine it into a single XPath expression and just get one item instead of a list.I tried this but it doesn't work.
t = item.findtext('.//span[@class="python"]//a[2]') # first element = 1
And the actual, not simplified, HTML is like this.
<span class='python'>
<span>
<span>
<img></img>
<a>google</a>
</span>
<a>chrome</a>
</span>
</span>
A:
I tried this but it doesn't work.
t = item.findtext('.//span[@class="python"]//a[2]')
This is a FAQ about the // abbreviation.
.//a[2] means: Select all a descendents of the current node that are the second a child of their parent. So this may select more than one element or no element -- depending on the concrete XML document.
To put it more simply, the [] operator has higher precedence than //.
If you want just one (the second) of all nodes returned you have to use brackets to force your wanted precedence:
(.//a)[2]
This really selects the second a descendent of the current node.
For the actual expression used in the question, change it to:
(.//span[@class="python"]//a)[2]
or change it to:
(.//span[@class="python"]//a)[2]/text()
A:
I'm not sure what the problem is...
>>> d = """<span class='python'>
... <a>google</a>
... <a>chrome</a>
... </span>"""
>>> from lxml import etree
>>> d = etree.HTML(d)
>>> d.xpath('.//span[@class="python"]/a[2]/text()')
['chrome']
>>>
A:
From Comments:
or the simplification of the actual
HTML I posted is too simple
You are right. What is the meaning of .//span[@class="python"]//a[2]? This will be expanded to:
self::node()
/descendant-or-self::node()
/child::span[attribute::class="python"]
/descendant-or-self::node()
/child::a[position()=2]
It will finaly select the second a child (fn:position() refers to the child axe). So, nothing will be select if your document is like:
<span class='python'>
<span>
<span>
<img></img>
<a>google</a><!-- This is the first "a" child of its parent -->
</span>
<a>chrome</a><!-- This is also the first "a" child of its parent -->
</span>
</span>
If you want the second of all descendants, use:
descendant::span[@class="python"]/descendant::a[2]
| Get second element text with XPath? | <span class='python'>
<a>google</a>
<a>chrome</a>
</span>
I want to get chrome and have it working like this already.
q = item.findall('.//span[@class="python"]//a')
t = q[1].text # first element = 0
I'd like to combine it into a single XPath expression and just get one item instead of a list.I tried this but it doesn't work.
t = item.findtext('.//span[@class="python"]//a[2]') # first element = 1
And the actual, not simplified, HTML is like this.
<span class='python'>
<span>
<span>
<img></img>
<a>google</a>
</span>
<a>chrome</a>
</span>
</span>
| [
"\nI tried this but it doesn't work.\nt = item.findtext('.//span[@class=\"python\"]//a[2]')\n\n\nThis is a FAQ about the // abbreviation. \n.//a[2] means: Select all a descendents of the current node that are the second a child of their parent. So this may select more than one element or no element -- depending on ... | [
42,
2,
2
] | [] | [] | [
"lxml",
"python",
"xpath"
] | stackoverflow_0004117953_lxml_python_xpath.txt |
Q:
MemoryError, python
I got a MemoryError when processing a .xml file = 1,45 Gb. I tried to run it on a smaller file and it works, so there shouldn't be any bugs in the code. The code, itself, implies to open a xml file, do some stuff inside and save it back to a new txt file. I run Win7 x86, 2 Gb RAM, Python 2.6
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
openfile('ukwiki-latest-pages-articles.xml')
File "C:\Users\Vof Freeman\Desktop\Python\test.py", line 7, in openfile
contents = F.read()
File "C:\Python26\lib\codecs.py", line 666, in read
return self.reader.read(size)
File "C:\Python26\lib\codecs.py", line 466, in read
newdata = self.stream.read()
MemoryError
A:
Since building an in-memory tree is not desirable (and in your case not practical either, given the amount of physical memory you have), there are two techniques you can use with lxml:
Supplying a target parser class
Using the iterparse method
Refer to the documentation here to see how this can be done.
A:
Simply put, you don't have enough RAM to read this file. You should split it up into smaller XML files and read it that way.
The fact that it worked on a smaller file tells me that there's nothing wrong with your code, it's just your hardware that can't handle it.
| MemoryError, python | I got a MemoryError when processing a .xml file = 1,45 Gb. I tried to run it on a smaller file and it works, so there shouldn't be any bugs in the code. The code, itself, implies to open a xml file, do some stuff inside and save it back to a new txt file. I run Win7 x86, 2 Gb RAM, Python 2.6
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
openfile('ukwiki-latest-pages-articles.xml')
File "C:\Users\Vof Freeman\Desktop\Python\test.py", line 7, in openfile
contents = F.read()
File "C:\Python26\lib\codecs.py", line 666, in read
return self.reader.read(size)
File "C:\Python26\lib\codecs.py", line 466, in read
newdata = self.stream.read()
MemoryError
| [
"Since building an in-memory tree is not desirable (and in your case not practical either, given the amount of physical memory you have), there are two techniques you can use with lxml:\n\nSupplying a target parser class\nUsing the iterparse method\n\nRefer to the documentation here to see how this can be done. \n"... | [
8,
0
] | [] | [] | [
"error_handling",
"python",
"xml"
] | stackoverflow_0004118409_error_handling_python_xml.txt |
Q:
Is 'if q and r:' evaluated separately?
It's a very simple question. Is
if q and r:
always guaranteed to be equivalent to this?
if q:
if r:
A:
Python's and and or are short-circuiting operators, so yes: in your example, if "q" is false, then the interpreter will not evaluate "r".
edit — after a little thought it occurs to me that it's important to note that Python's and and or work kind-of like Javascript && and ||. They do not produce a boolean result. In other words, the operands ("q" and "r") when evaluated are sort-of "internally" cast to boolean, but that's just to see how execution should proceed. Thus, if "q" and "r" are both non-empty strings, the result of q and r is the string value of "r", not boolean true. However, when used in the context given (an if statement), the if statement itself is going to cast the result to boolean in order to make its own control flow decision, so the answer for this example is still "yes" :-)
| Is 'if q and r:' evaluated separately? | It's a very simple question. Is
if q and r:
always guaranteed to be equivalent to this?
if q:
if r:
| [
"Python's and and or are short-circuiting operators, so yes: in your example, if \"q\" is false, then the interpreter will not evaluate \"r\".\nedit — after a little thought it occurs to me that it's important to note that Python's and and or work kind-of like Javascript && and ||. They do not produce a boolean res... | [
12
] | [] | [] | [
"python"
] | stackoverflow_0004118433_python.txt |
Q:
Adding audio to video produced from OpenCV
I've been using OpenCV under python to record video from a capture device. Two output AVI's are written each hour, at the top of each hour the file names are changed. One of the files is the original capture and one uses some of OpenCV's detection functions.
As always, things change and audio needs to be recorded which wasn't originally a concern. I'm wondering if anyone has any suggestions about how best to do this. Current thought is to separately record the audio track using pyaudio and then use ffmpeg to mux them together after the hour has finished recording although I do have some concerns about keeping accurate lipsync.
I'm wondering if anyone has any better ideas about how to do this accurately and without noticeable gaps in the recording?
A:
The pyaudio module may fit your needs, it is a wrapper aroung portaudio. On MacOsX, this hack installs the portaudio libray:
svn co https://www.portaudio.com/repos/portaudio/trunk portaudio
cd portaudio/
./configure
make
sudo make install
sudo /usr/bin/install -c -m 644 -m 644 ./include/pa_mac_core.h /usr/local/include/pa_mac_core.h
sudo easy_install pyaudio
Check their website: http://people.csail.mit.edu/hubert/pyaudio/
A:
As no better solutions have come up and incase its of use to anyone else, I've been going with my original plan and recording sound using PyAudio.
I'm actually using mencoder which is called using POpen with pipes for stdout and stderr, a bit of regex is then used to check that the job was successful and I'm achieving good enough results for my application although the audio is sometimes a frame or two out.
| Adding audio to video produced from OpenCV | I've been using OpenCV under python to record video from a capture device. Two output AVI's are written each hour, at the top of each hour the file names are changed. One of the files is the original capture and one uses some of OpenCV's detection functions.
As always, things change and audio needs to be recorded which wasn't originally a concern. I'm wondering if anyone has any suggestions about how best to do this. Current thought is to separately record the audio track using pyaudio and then use ffmpeg to mux them together after the hour has finished recording although I do have some concerns about keeping accurate lipsync.
I'm wondering if anyone has any better ideas about how to do this accurately and without noticeable gaps in the recording?
| [
"The pyaudio module may fit your needs, it is a wrapper aroung portaudio. On MacOsX, this hack installs the portaudio libray:\nsvn co https://www.portaudio.com/repos/portaudio/trunk portaudio\ncd portaudio/\n./configure\nmake\nsudo make install\nsudo /usr/bin/install -c -m 644 -m 644 ./include/pa_mac_core.h /usr/lo... | [
1,
0
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0003846634_opencv_python.txt |
Q:
django Facebook Registration Process
I've been searching some topics concerning facebook registration. Its just that i cant find any topics on how to save the user's facebook data to my users model.
Currently, users can Login successfully in my site.
here's my code:
base.html
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() { FB.init({ appId : 'XXXXXXXXXXXXXX', status : true, cookie : true, xfbml : true }); };
(function() { var e = document.createElement('script'); e.async = true; e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; document.getElementById('fb-root').appendChild(e); }());
</script>
<fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream" ></fb:login-button>
My problem is i dont know how to get the Data from facebook and save it to may users model.
do you have any idea on how to solve this problem? your answers are highly appreciated. thank you..!
A:
Does this help you: Facebook Connect: capturing user data with django-profiles and django-socialregistration or you need a more verbose answer?
EDIT:
that facebook.GraphAPI thing can be imported from this: https://github.com/facebook/python-sdk/
| django Facebook Registration Process | I've been searching some topics concerning facebook registration. Its just that i cant find any topics on how to save the user's facebook data to my users model.
Currently, users can Login successfully in my site.
here's my code:
base.html
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() { FB.init({ appId : 'XXXXXXXXXXXXXX', status : true, cookie : true, xfbml : true }); };
(function() { var e = document.createElement('script'); e.async = true; e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; document.getElementById('fb-root').appendChild(e); }());
</script>
<fb:login-button autologoutlink="true" perms="email,user_birthday,status_update,publish_stream" ></fb:login-button>
My problem is i dont know how to get the Data from facebook and save it to may users model.
do you have any idea on how to solve this problem? your answers are highly appreciated. thank you..!
| [
"Does this help you: Facebook Connect: capturing user data with django-profiles and django-socialregistration or you need a more verbose answer?\nEDIT:\nthat facebook.GraphAPI thing can be imported from this: https://github.com/facebook/python-sdk/\n"
] | [
1
] | [] | [] | [
"django",
"facebook",
"python"
] | stackoverflow_0004117898_django_facebook_python.txt |
Q:
Prevent OpenCV function CreateVideoWriter from printing to console in Python
I'm using the Python bindings for OpenCV and have run into a little annoyance using CreateVideoWriter where when I call the function, it prints something similar to the below to the console and I can't seem to surpress it or ideally redirect it into a variable.
Output #0, avi, to 'temp/Temp.0433.avi':
Stream #0.0: Video: mjpeg, yuvj420p, 320x240, q=2-31, 9830 kb/s, 90k tbn, 25
tbc
The command I'm using for testing is this:
self.file = cvCreateVideoWriter(nf,CV_FOURCC('M','J','P','G'),self.fps,cvSize(320,240),1)
Although in the long run this app will have a control GUI its currently console based, the function is called every minute so this means its difficult to present even a simple menu or more useful status information without this call filling up the console.
Just wondering if anyone has experienced the same and/or has any ideas how I might be able to prevent this happening or can offer pointers as to what I'm doing wrong?
A:
I think the easiest way for you to do this is temporarily to redirect sys.stdout while calling the messy function -- anything else will force you to change the Python bindings.
Fortunately, this is easy: just use a contextmanager:
>>> import contextlib
>>> @contextlib.contextmanager
... def stdout_as(stream):
... import sys
... sys.stdout = stream
... yield
... sys.stdout = sys.__stdout__
...
>>> print("hi")
hi
>>> import io
>>> stream = io.StringIO()
>>> with stdout_as(stream):
... print("hi")
...
>>> stream.seek(0)
0
>>> stream.read()
'hi\n'
>>> print("hi")
hi
| Prevent OpenCV function CreateVideoWriter from printing to console in Python | I'm using the Python bindings for OpenCV and have run into a little annoyance using CreateVideoWriter where when I call the function, it prints something similar to the below to the console and I can't seem to surpress it or ideally redirect it into a variable.
Output #0, avi, to 'temp/Temp.0433.avi':
Stream #0.0: Video: mjpeg, yuvj420p, 320x240, q=2-31, 9830 kb/s, 90k tbn, 25
tbc
The command I'm using for testing is this:
self.file = cvCreateVideoWriter(nf,CV_FOURCC('M','J','P','G'),self.fps,cvSize(320,240),1)
Although in the long run this app will have a control GUI its currently console based, the function is called every minute so this means its difficult to present even a simple menu or more useful status information without this call filling up the console.
Just wondering if anyone has experienced the same and/or has any ideas how I might be able to prevent this happening or can offer pointers as to what I'm doing wrong?
| [
"I think the easiest way for you to do this is temporarily to redirect sys.stdout while calling the messy function -- anything else will force you to change the Python bindings.\nFortunately, this is easy: just use a contextmanager:\n>>> import contextlib\n>>> @contextlib.contextmanager\n... def stdout_as(stream):\... | [
1
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0004118460_opencv_python.txt |
Q:
Is there a (simple) way to parse CRL in Python?
I'm trying to do something stupid: load a CRL and output the list of revoked certificates serials.
With M2Crypto loading the CRL is done with:
import M2Crypto
crl = M2crypto.X509.load_crl('my.crl')
But i'm really surpised that the returned object has only one usefull which is
crl.as_text()
With some regexp, i can parse the output to retrieve my revoked serials. But is there an another way to do that?
For information, here is a classical CRL as_text output.
Certificate Revocation List (CRL):
Version 2 (0x1)
Signature Algorithm: sha1WithRSAEncryption
Issuer: /C=FR/ST=IDF/L=Paris/O=XXXXX/OU=XXXXX/CN=XXXXX Certificate Authority
Last Update: Nov 6 21:49:51 2010 GMT
Next Update: Nov 7 21:49:51 2010 GMT
Revoked Certificates:
Serial Number: 02
Revocation Date: Aug 10 15:40:09 2010 GMT
Serial Number: 03
Revocation Date: Sep 9 15:12:24 2010 GMT
Serial Number: 05
Revocation Date: Aug 17 14:18:22 2010 GMT
Serial Number: 06
Revocation Date: Aug 18 08:57:15 2010 GMT
Signature Algorithm: sha1WithRSAEncryption
d1:05:da:1f:c0:1c:68:78:0e:e2:ea:78:de:b8:b2:58:9c:ba:
b4:7c:c5:e8:2a:8d:8c:82:1d:4b:ed:a7:2d:cb:f6:bf:da:fa:
38:a4:7a:3d:2b:19:6c:7a:ba:4c:1c:4c:e4:d8:e6:20:3d:0a:
95:03:75:bf:17:cf:97:ce:3e:4a:93:1c:a6:4c:36:62:97:a2:
d3:be:f2:78:38:89:13:3e:d4:b0:80:a1:24:52:0d:3a:01:67:
0d:4f:e7:0b:07:0c:80:04:b7:25:66:a4:61:36:dd:3a:24:29:
30:67:f6:23:31:34:6f:0b:a8:30:c1:c9:b7:ee:4e:2b:7a:e7:
6b:31:7d:0b:cb:12:8a:7c:5f:7e:73:a0:42:8d:ea:4f:f7:76:
ce:1b:0b:6c:6a:3e:eb:08:a6:d6:67:81:cb:cb:98:6d:40:ec:
8c:e5:a5:f7:f0:ed:0c:7f:38:fd:42:3d:19:c4:69:ec:eb:71:
7a:e1:30:b4:81:98:f5:00:a0:bd:ac:75:46:15:e6:2b:1c:da:
f4:09:19:e5:1b:4e:c9:a4:7c:11:79:24:a4:3b:13:84:84:a7:
5b:0e:07:80:ae:ae:26:8e:d7:b3:cb:b8:6c:79:df:9d:26:b0:
34:bc:c1:f4:8f:4b:3e:f5:9b:d0:e3:e7:ab:37:27:f6:79:09:
47:fb:76:07
A:
Job's done thanks to pyOpenSSL. Here is the code to use :
import OpenSSL
with open('path_to_the_crl', 'r') as _crl_file:
crl = "".join(_crl_file.readlines())
crl_object = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, crl)
revoked_objects = crl_object.get_revoked()
for rvk in revoked_objects:
print "Serial:", rvk.get_serial()
This code give the following output with my CRL example:
Serial: 02
Serial: 03
Serial: 05
Serial: 06
A:
pyOpenSSL has a CRL class with a get_revoked() method that should do exactly what you want it to, which I believe is getting revoked certificates (it's documented here).
I understand this may not be what you want, if for some reason you're tied to M2Crypto, but this seems to work as well.
| Is there a (simple) way to parse CRL in Python? | I'm trying to do something stupid: load a CRL and output the list of revoked certificates serials.
With M2Crypto loading the CRL is done with:
import M2Crypto
crl = M2crypto.X509.load_crl('my.crl')
But i'm really surpised that the returned object has only one usefull which is
crl.as_text()
With some regexp, i can parse the output to retrieve my revoked serials. But is there an another way to do that?
For information, here is a classical CRL as_text output.
Certificate Revocation List (CRL):
Version 2 (0x1)
Signature Algorithm: sha1WithRSAEncryption
Issuer: /C=FR/ST=IDF/L=Paris/O=XXXXX/OU=XXXXX/CN=XXXXX Certificate Authority
Last Update: Nov 6 21:49:51 2010 GMT
Next Update: Nov 7 21:49:51 2010 GMT
Revoked Certificates:
Serial Number: 02
Revocation Date: Aug 10 15:40:09 2010 GMT
Serial Number: 03
Revocation Date: Sep 9 15:12:24 2010 GMT
Serial Number: 05
Revocation Date: Aug 17 14:18:22 2010 GMT
Serial Number: 06
Revocation Date: Aug 18 08:57:15 2010 GMT
Signature Algorithm: sha1WithRSAEncryption
d1:05:da:1f:c0:1c:68:78:0e:e2:ea:78:de:b8:b2:58:9c:ba:
b4:7c:c5:e8:2a:8d:8c:82:1d:4b:ed:a7:2d:cb:f6:bf:da:fa:
38:a4:7a:3d:2b:19:6c:7a:ba:4c:1c:4c:e4:d8:e6:20:3d:0a:
95:03:75:bf:17:cf:97:ce:3e:4a:93:1c:a6:4c:36:62:97:a2:
d3:be:f2:78:38:89:13:3e:d4:b0:80:a1:24:52:0d:3a:01:67:
0d:4f:e7:0b:07:0c:80:04:b7:25:66:a4:61:36:dd:3a:24:29:
30:67:f6:23:31:34:6f:0b:a8:30:c1:c9:b7:ee:4e:2b:7a:e7:
6b:31:7d:0b:cb:12:8a:7c:5f:7e:73:a0:42:8d:ea:4f:f7:76:
ce:1b:0b:6c:6a:3e:eb:08:a6:d6:67:81:cb:cb:98:6d:40:ec:
8c:e5:a5:f7:f0:ed:0c:7f:38:fd:42:3d:19:c4:69:ec:eb:71:
7a:e1:30:b4:81:98:f5:00:a0:bd:ac:75:46:15:e6:2b:1c:da:
f4:09:19:e5:1b:4e:c9:a4:7c:11:79:24:a4:3b:13:84:84:a7:
5b:0e:07:80:ae:ae:26:8e:d7:b3:cb:b8:6c:79:df:9d:26:b0:
34:bc:c1:f4:8f:4b:3e:f5:9b:d0:e3:e7:ab:37:27:f6:79:09:
47:fb:76:07
| [
"Job's done thanks to pyOpenSSL. Here is the code to use :\nimport OpenSSL\n\nwith open('path_to_the_crl', 'r') as _crl_file:\n crl = \"\".join(_crl_file.readlines())\n\ncrl_object = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, crl)\n\nrevoked_objects = crl_object.get_revoked()\n\nfor rvk in revoked_obje... | [
10,
3
] | [] | [] | [
"certificate_revocation",
"pki",
"python",
"x509"
] | stackoverflow_0004115523_certificate_revocation_pki_python_x509.txt |
Q:
read a file contains list and comma separation in python
I have a file(.txt) which contains: [0 1,1 1,3 2,4 1]
I want to read the file in this way:
0 1 /n
1 1 /n
3 2 /n
4 1 /n
I have problem how to eliminate brackets and separate each line by comma.
Thanks for your suggestions :)
A:
>>> s = "[0 1,1 1,3 2,4 1]"
>>> print '\n'.join(s[1:-1].split(','))
0 1
1 1
3 2
4 1
A:
A different method that will also work if the brackets are not the first and the last character:
print s[s.index("[")+1:s.index("]")].replace(",", "\n")
If the brackets always are the ifrst and the last character of the string, you can simplify this to
print s[1:-1].replace(",", "\n")
A:
Simple snippet:
with open("file.txt", "r") as _f:
myfile = _f.readlines()
myline = myfile[0]
print '\n'.join(myline[1:-1].split(','))
If you have several similar lines on your file, on can iterate with a for statement on 'myfile'.
for line in myfile:
print '\n'.join(line[1:-1].split(','))
Note, if you are sure that brackets are on beginning and end of the line, you can use :
print "\n".join(line.strip('[]').split(','))
| read a file contains list and comma separation in python | I have a file(.txt) which contains: [0 1,1 1,3 2,4 1]
I want to read the file in this way:
0 1 /n
1 1 /n
3 2 /n
4 1 /n
I have problem how to eliminate brackets and separate each line by comma.
Thanks for your suggestions :)
| [
">>> s = \"[0 1,1 1,3 2,4 1]\"\n>>> print '\\n'.join(s[1:-1].split(','))\n0 1\n1 1\n3 2\n4 1\n\n",
"A different method that will also work if the brackets are not the first and the last character:\nprint s[s.index(\"[\")+1:s.index(\"]\")].replace(\",\", \"\\n\")\n\nIf the brackets always are the ifrst and the las... | [
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004118748_python.txt |
Q:
I want to nest loop ten times, Is there any better way than this?
Something like this. I want to brute force all characters with word of 10 size
lookup = map(chr, range(32, 127))
for i in lookup:
for j in lookup:
for k in lookup:
for l in lookup:
for m in lookup:
for n in lookup:
for o in lookup:
for p in lookup:
for q in lookup:
for r in lookup:
print(r) # whatever
Here are my questions
1) Is there any better way?
2) One problem with this code is print(any of i j k ... r) not working, can you help me figure out the problem? if I give any string it is working but not the variables
3) I tried same with perl even there not able to print variables in the loop like i, j, .. r
A:
While using the existing itertools package is normally better than rolling your own code, for educational value it's good to know how to do this yourself.
Obviously, nesting ten loops is not the best approach. I say "obviously" because it should immediately raise a red flag in your mind when you have to copy and paste code like that. It just doesn't look very elegant, does it?
There are several ways to solve this problem in a more elegant manner. One way is to use recursion. To do it recursively you need to break the problem into smaller pieces. These are the recursive rule and the base case. The recursive rule is where you assume you know how to solve a similar but slightly smaller version of the problem, and then use that to solve the larger case. The base case is where the recursion bottoms out because you can figure out the answer without any further recursion.
Recursive rule
In our case, how do you generate a 10-letter word? Let's say you know how to generate 9-letter words already. Then what?
for each 9-letter word:
for each letter 'A' through 'Z':
yield word + letter
It should be clear that this works the same for 9-letter words, 8-letter words, etc., with just a small adjustment to the outer loop. In general, to generate words of length n we combine every word of length n-1 with each letter of the alphabet. Or, in Python:
import string
def all_words(length):
for word in all_words(length - 1):
for letter in string.lowercase:
yield word + letter
Let's try to run it. We'll start small. How about just all words of length 1 to start with?
>>> list(all_words(1))
File "<stdin>", line 2, in all_words
File "<stdin>", line 2, in all_words
File "<stdin>", line 2, in all_words
File "<stdin>", line 2, in all_words
RuntimeError: maximum recursion depth exceeded
Base case
Oops, what happened? Oh, right. The base case. To generate words of length 2 we recursively generate words of length 1. To generate words of length 1 we generate words of length 0. To generate words of length 0 we generate words of length -1.
Wait. What? Words of length -1? That doesn't make sense. At some point we need to stop recursing and simply return a result, otherwise we will recurse forever. This is the base case. The base case is the point at which you don't need to bother recursing because the answer is simple enough to figure out right away.
In our case, when we're asked to generate words of length 0, we really don't need to do any heavy lifting. You can see that the only "word" of length 0 is "", the empty string. It's the only string that has 0 characters in it. So when length is 0, let's just return the empty string:
import string
def all_words(length):
# Base case
if length == 0:
yield ""
# Recursive rule
else:
for word in all_words(length - 1):
for letter in string.lowercase:
yield word + letter
OK, let's try that again, shall we?
>>> list(all_words(2))
['aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag', 'ah', 'ai', 'aj', 'ak', 'al', 'am', 'an', 'ao', 'ap', 'aq', 'ar', 'as', 'at', 'au', 'av', 'aw', 'ax', 'ay', 'az',
'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'bg', 'bh', 'bi', 'bj', 'bk', 'bl', 'bm', 'bn', 'bo', 'bp', 'bq', 'br', 'bs', 'bt', 'bu', 'bv', 'bw', 'bx', 'by', 'bz',
'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'cg', 'ch', 'ci', 'cj', 'ck', 'cl', 'cm', 'cn', 'co', 'cp', 'cq', 'cr', 'cs', 'ct', 'cu', 'cv', 'cw', 'cx', 'cy', 'cz',
'da', 'db', 'dc', 'dd', 'de', 'df', 'dg', 'dh', 'di', 'dj', 'dk', 'dl', 'dm', 'dn', 'do', 'dp', 'dq', 'dr', 'ds', 'dt', 'du', 'dv', 'dw', 'dx', 'dy', 'dz',
'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'eg', 'eh', 'ei', 'ej', 'ek', 'el', 'em', 'en', 'eo', 'ep', 'eq', 'er', 'es', 'et', 'eu', 'ev', 'ew', 'ex', 'ey', 'ez',
'fa', 'fb', 'fc', 'fd', 'fe', 'ff', 'fg', 'fh', 'fi', 'fj', 'fk', 'fl', 'fm', 'fn', 'fo', 'fp', 'fq', 'fr', 'fs', 'ft', 'fu', 'fv', 'fw', 'fx', 'fy', 'fz',
'ga', 'gb', 'gc', 'gd', 'ge', 'gf', 'gg', 'gh', 'gi', 'gj', 'gk', 'gl', 'gm', 'gn', 'go', 'gp', 'gq', 'gr', 'gs', 'gt', 'gu', 'gv', 'gw', 'gx', 'gy', 'gz',
'ha', 'hb', 'hc', 'hd', 'he', 'hf', 'hg', 'hh', 'hi', 'hj', 'hk', 'hl', 'hm', 'hn', 'ho', 'hp', 'hq', 'hr', 'hs', 'ht', 'hu', 'hv', 'hw', 'hx', 'hy', 'hz',
'ia', 'ib', 'ic', 'id', 'ie', 'if', 'ig', 'ih', 'ii', 'ij', 'ik', 'il', 'im', 'in', 'io', 'ip', 'iq', 'ir', 'is', 'it', 'iu', 'iv', 'iw', 'ix', 'iy', 'iz',
'ja', 'jb', 'jc', 'jd', 'je', 'jf', 'jg', 'jh', 'ji', 'jj', 'jk', 'jl', 'jm', 'jn', 'jo', 'jp', 'jq', 'jr', 'js', 'jt', 'ju', 'jv', 'jw', 'jx', 'jy', 'jz',
'ka', 'kb', 'kc', 'kd', 'ke', 'kf', 'kg', 'kh', 'ki', 'kj', 'kk', 'kl', 'km', 'kn', 'ko', 'kp', 'kq', 'kr', 'ks', 'kt', 'ku', 'kv', 'kw', 'kx', 'ky', 'kz',
'la', 'lb', 'lc', 'ld', 'le', 'lf', 'lg', 'lh', 'li', 'lj', 'lk', 'll', 'lm', 'ln', 'lo', 'lp', 'lq', 'lr', 'ls', 'lt', 'lu', 'lv', 'lw', 'lx', 'ly', 'lz',
'ma', 'mb', 'mc', 'md', 'me', 'mf', 'mg', 'mh', 'mi', 'mj', 'mk', 'ml', 'mm', 'mn', 'mo', 'mp', 'mq', 'mr', 'ms', 'mt', 'mu', 'mv', 'mw', 'mx', 'my', 'mz',
'na', 'nb', 'nc', 'nd', 'ne', 'nf', 'ng', 'nh', 'ni', 'nj', 'nk', 'nl', 'nm', 'nn', 'no', 'np', 'nq', 'nr', 'ns', 'nt', 'nu', 'nv', 'nw', 'nx', 'ny', 'nz',
'oa', 'ob', 'oc', 'od', 'oe', 'of', 'og', 'oh', 'oi', 'oj', 'ok', 'ol', 'om', 'on', 'oo', 'op', 'oq', 'or', 'os', 'ot', 'ou', 'ov', 'ow', 'ox', 'oy', 'oz',
'pa', 'pb', 'pc', 'pd', 'pe', 'pf', 'pg', 'ph', 'pi', 'pj', 'pk', 'pl', 'pm', 'pn', 'po', 'pp', 'pq', 'pr', 'ps', 'pt', 'pu', 'pv', 'pw', 'px', 'py', 'pz',
'qa', 'qb', 'qc', 'qd', 'qe', 'qf', 'qg', 'qh', 'qi', 'qj', 'qk', 'ql', 'qm', 'qn', 'qo', 'qp', 'qq', 'qr', 'qs', 'qt', 'qu', 'qv', 'qw', 'qx', 'qy', 'qz',
'ra', 'rb', 'rc', 'rd', 're', 'rf', 'rg', 'rh', 'ri', 'rj', 'rk', 'rl', 'rm', 'rn', 'ro', 'rp', 'rq', 'rr', 'rs', 'rt', 'ru', 'rv', 'rw', 'rx', 'ry', 'rz',
'sa', 'sb', 'sc', 'sd', 'se', 'sf', 'sg', 'sh', 'si', 'sj', 'sk', 'sl', 'sm', 'sn', 'so', 'sp', 'sq', 'sr', 'ss', 'st', 'su', 'sv', 'sw', 'sx', 'sy', 'sz',
'ta', 'tb', 'tc', 'td', 'te', 'tf', 'tg', 'th', 'ti', 'tj', 'tk', 'tl', 'tm', 'tn', 'to', 'tp', 'tq', 'tr', 'ts', 'tt', 'tu', 'tv', 'tw', 'tx', 'ty', 'tz',
'ua', 'ub', 'uc', 'ud', 'ue', 'uf', 'ug', 'uh', 'ui', 'uj', 'uk', 'ul', 'um', 'un', 'uo', 'up', 'uq', 'ur', 'us', 'ut', 'uu', 'uv', 'uw', 'ux', 'uy', 'uz',
'va', 'vb', 'vc', 'vd', 've', 'vf', 'vg', 'vh', 'vi', 'vj', 'vk', 'vl', 'vm', 'vn', 'vo', 'vp', 'vq', 'vr', 'vs', 'vt', 'vu', 'vv', 'vw', 'vx', 'vy', 'vz',
'wa', 'wb', 'wc', 'wd', 'we', 'wf', 'wg', 'wh', 'wi', 'wj', 'wk', 'wl', 'wm', 'wn', 'wo', 'wp', 'wq', 'wr', 'ws', 'wt', 'wu', 'wv', 'ww', 'wx', 'wy', 'wz',
'xa', 'xb', 'xc', 'xd', 'xe', 'xf', 'xg', 'xh', 'xi', 'xj', 'xk', 'xl', 'xm', 'xn', 'xo', 'xp', 'xq', 'xr', 'xs', 'xt', 'xu', 'xv', 'xw', 'xx', 'xy', 'xz',
'ya', 'yb', 'yc', 'yd', 'ye', 'yf', 'yg', 'yh', 'yi', 'yj', 'yk', 'yl', 'ym', 'yn', 'yo', 'yp', 'yq', 'yr', 'ys', 'yt', 'yu', 'yv', 'yw', 'yx', 'yy', 'yz',
'za', 'zb', 'zc', 'zd', 'ze', 'zf', 'zg', 'zh', 'zi', 'zj', 'zk', 'zl', 'zm', 'zn', 'zo', 'zp', 'zq', 'zr', 'zs', 'zt', 'zu', 'zv', 'zw', 'zx', 'zy', 'zz']
Cool.
A:
itertools is your friend.
>>> lookup = map(chr, range(32, 127))
>>> import itertools
>>> itertools.permutations(lookup, 10)
<itertools.permutations object at 0x023C8AE0>
Notice that permutations will give you every word, whereas combinations will give you every group of distinct characters. Note also that there are a lot of ten-letter words.
A:
I've read "Nine Billion Names of God" as well, but I don't think he world will end when your program finishes!
More seriously, Your code is going to be pretty quick and simple.
if you put the results in an array (or string), you create an index that pointed to the current level, then for each loop, simply increment the index. When the level is finished, decrement it to "move back".
This solution would not be quite as clear, but it would be dynamic - ie. You could choose the number of levels at run time.
A:
import itertools
lookup = map(chr, range(32, 127))
for i in itertools.product(lookup, repeat=10):
print i
but you will have like (Edit) 96^10 loop so ???
| I want to nest loop ten times, Is there any better way than this? | Something like this. I want to brute force all characters with word of 10 size
lookup = map(chr, range(32, 127))
for i in lookup:
for j in lookup:
for k in lookup:
for l in lookup:
for m in lookup:
for n in lookup:
for o in lookup:
for p in lookup:
for q in lookup:
for r in lookup:
print(r) # whatever
Here are my questions
1) Is there any better way?
2) One problem with this code is print(any of i j k ... r) not working, can you help me figure out the problem? if I give any string it is working but not the variables
3) I tried same with perl even there not able to print variables in the loop like i, j, .. r
| [
"While using the existing itertools package is normally better than rolling your own code, for educational value it's good to know how to do this yourself.\nObviously, nesting ten loops is not the best approach. I say \"obviously\" because it should immediately raise a red flag in your mind when you have to copy an... | [
13,
8,
1,
0
] | [] | [] | [
"perl",
"programming_languages",
"python"
] | stackoverflow_0004118684_perl_programming_languages_python.txt |
Q:
How do I update information in my datastore?
I need to check if the item is in datastore before I update it.
I have 2 lists: UNIQUES = ["B","K","V"] and COUNTS = [5, 10, 3]
This is the model:
class Rep(db.Model):
mAUTHOR = db.UserProperty(auto_current_user=True)
mUNIQUE = db.TextProperty()
mCOUNT = db.IntegerProperty()
mDATE = db.DateTimeProperty(auto_now_add=True)
This function updates the database:
def write_to_db(S, C):
REP = Rep(mUNIQUE=S, mCOUNT=C)
db.put(REP)
Inspired by this page I try:
for i in range(len(UNIQUES)):
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
if C_RESULT:
C = C_RESULT.mCOUNT + COUNTS[i]
S = db.Text(UNIQUES[i])
write_to_db(S,C)
else:
C = COUNTS[i]
S = UNIQUES[i]
write_to_db(S, C)
But the result is not what I expect. C_RESULT is always empty; and instead of updating, a new record is created. What am I doing wrong? Thanks!
EDIT3: Problem solved
As per David Underhill's comment I updated the code and it now works.
if C_RESULT:
rep=C_RESULT[0]
rep.mCOUNT+=COUNTS[i]
rep.put()
EDIT2: Related question
How do I update this query and put it back with updated information?
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
I want to change mCOUNT and then write it to datastore. How do I this? This looks like the exact same thing they do in this page but I could not make it work. Thanks for your help.
EDIT
I updated the code per David Underhill's answer. That solved the problem (but the functionality is not right. I am not sure if that should be a different question).
for i in range(len(UNIQUES)):
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
if C_RESULT:
C = C_RESULT[0].mCOUNT + COUNTS[i]
S = UNIQUES[i]
write_to_db(S, C)
else:
C = COUNTS[i]
S = UNIQUES[i]
write_to_db(S, C)
A:
The problem is that the query is trying to filter mUNIQUE. However, you declared mUNIQUE as a db.TextProperty which is never indexed. As a result, you query never finds any results.
Solution: Change mUNIQUE to a db.StringProperty (which is indexed by default).
You should also consider updating Rep in a transaction - the current code may fail to property add COUNTS[i] if two requests try to update the same entity concurrently.
Also, you can update S = db.Text(UNIQUES[i]) to simply S = UNIQUES[i].
| How do I update information in my datastore? | I need to check if the item is in datastore before I update it.
I have 2 lists: UNIQUES = ["B","K","V"] and COUNTS = [5, 10, 3]
This is the model:
class Rep(db.Model):
mAUTHOR = db.UserProperty(auto_current_user=True)
mUNIQUE = db.TextProperty()
mCOUNT = db.IntegerProperty()
mDATE = db.DateTimeProperty(auto_now_add=True)
This function updates the database:
def write_to_db(S, C):
REP = Rep(mUNIQUE=S, mCOUNT=C)
db.put(REP)
Inspired by this page I try:
for i in range(len(UNIQUES)):
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
if C_RESULT:
C = C_RESULT.mCOUNT + COUNTS[i]
S = db.Text(UNIQUES[i])
write_to_db(S,C)
else:
C = COUNTS[i]
S = UNIQUES[i]
write_to_db(S, C)
But the result is not what I expect. C_RESULT is always empty; and instead of updating, a new record is created. What am I doing wrong? Thanks!
EDIT3: Problem solved
As per David Underhill's comment I updated the code and it now works.
if C_RESULT:
rep=C_RESULT[0]
rep.mCOUNT+=COUNTS[i]
rep.put()
EDIT2: Related question
How do I update this query and put it back with updated information?
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
I want to change mCOUNT and then write it to datastore. How do I this? This looks like the exact same thing they do in this page but I could not make it work. Thanks for your help.
EDIT
I updated the code per David Underhill's answer. That solved the problem (but the functionality is not right. I am not sure if that should be a different question).
for i in range(len(UNIQUES)):
C_QUERY = Rep.all()
C_QUERY.filter("mAUTHOR =", user)
C_QUERY.filter("mUNIQUE =", UNIQUES[i])
C_RESULT = C_QUERY.fetch(1)
if C_RESULT:
C = C_RESULT[0].mCOUNT + COUNTS[i]
S = UNIQUES[i]
write_to_db(S, C)
else:
C = COUNTS[i]
S = UNIQUES[i]
write_to_db(S, C)
| [
"The problem is that the query is trying to filter mUNIQUE. However, you declared mUNIQUE as a db.TextProperty which is never indexed. As a result, you query never finds any results.\nSolution: Change mUNIQUE to a db.StringProperty (which is indexed by default).\nYou should also consider updating Rep in a transac... | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004118776_google_app_engine_google_cloud_datastore_python.txt |
Q:
How to search a Python List via Object Attribute?
Consider the following python class:
class Event(Document):
name = StringField()
time = DateField()
location = GeoPointField()
def __unicode__(self):
return self.name
Now I create a list of Events:
x = [Event(name='California Wine Mixer'),
Event(name='American Civil War'),
Event(name='Immaculate Conception')]
Now I want to add only unique events by searching via the event name.
How is this done with the boolean in syntax?
The following is incorrect:
a = Event(name='California Wine Mixer')
if a.name in x(Event.name):
x.append(a)
A:
By unique I think you want something like "if a.name not in x(Event.name):", which can be written as
if not any(y.name == a.name for y in x):
...
But if the name acts as an index, it is better to use a dictionary to avoid the O(N) searching time and the more complex interface.
event_list = [Event(name='California Wine Mixer'), ...]
event_dict = dict((b.name, b) for b in event_list)
# ignore event_list from now on.
....
a = Event(name='California Wine Mixer')
event_dict.setdefault(a.name, a)
| How to search a Python List via Object Attribute? | Consider the following python class:
class Event(Document):
name = StringField()
time = DateField()
location = GeoPointField()
def __unicode__(self):
return self.name
Now I create a list of Events:
x = [Event(name='California Wine Mixer'),
Event(name='American Civil War'),
Event(name='Immaculate Conception')]
Now I want to add only unique events by searching via the event name.
How is this done with the boolean in syntax?
The following is incorrect:
a = Event(name='California Wine Mixer')
if a.name in x(Event.name):
x.append(a)
| [
"By unique I think you want something like \"if a.name not in x(Event.name):\", which can be written as\nif not any(y.name == a.name for y in x):\n ...\n\nBut if the name acts as an index, it is better to use a dictionary to avoid the O(N) searching time and the more complex interface.\nevent_list = [Event(name='C... | [
3
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004119248_list_python.txt |
Q:
redefine default filtering behavior in Django templates
I have a project with many DecimalFields that are rendered in more than 300 templates. I would like that these decimal fields are rendered normalized. I don't care about precission or anything:
decimal.Decimal("10.0000").normalize()
I haven't found a way to change default rendering system. I know there is a humanize and a floatformat filter I could use in my templates. But I need a solution that doesn't mean editing all those files, even if a shell script could be written.
Thanks
A:
You could create a subclass of DecimalField where you override DecimalField.__str__ or DecimalField.__unicode__ to suit your needs. This method is called whenever the value needs to be rendered in a template or whatnot. You would only need to change your models.
The code for theField class is here. DecimalField is a subclass of this. Documentation about subclassing Field: http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#writing-a-field-subclass
Also, see this tip abount the __unicode__ method: http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#some-general-advice
Edit: I am waaay to tired to make any sense at the moment.
| redefine default filtering behavior in Django templates | I have a project with many DecimalFields that are rendered in more than 300 templates. I would like that these decimal fields are rendered normalized. I don't care about precission or anything:
decimal.Decimal("10.0000").normalize()
I haven't found a way to change default rendering system. I know there is a humanize and a floatformat filter I could use in my templates. But I need a solution that doesn't mean editing all those files, even if a shell script could be written.
Thanks
| [
"You could create a subclass of DecimalField where you override DecimalField.__str__ or DecimalField.__unicode__ to suit your needs. This method is called whenever the value needs to be rendered in a template or whatnot. You would only need to change your models.\nThe code for theField class is here. DecimalField i... | [
2
] | [] | [] | [
"django",
"django_models",
"django_templates",
"python"
] | stackoverflow_0004119151_django_django_models_django_templates_python.txt |
Q:
Python urlparse: small issue
I'm making an app that parses html and gets images from it. Parsing is easy using Beautiful Soup and downloading of the html and the images works too with urllib2.
I do have a problem with urlparse to make absolute paths out of relative ones. The problem is best explained with an example:
>>> import urlparse
>>> urlparse.urljoin("http://www.example.com/", "../test.png")
'http://www.example.com/../test.png'
As you can see, urlparse doesn't take away the ../ away. This gives a problem when I try to download the image:
HTTPError: HTTP Error 400: Bad Request
Is there a way to fix this problem in urllib?
A:
".." would bring you up one directory ("." is current directory), so combining that with a domain name url doesn't make much sense. Maybe what you need is:
>>> urlparse.urljoin("http://www.example.com","./test.png")
'http://www.example.com/test.png'
A:
I think the best you can do is to pre-parse the original URL, and check the path component. A simple test is
if len(urlparse.urlparse(baseurl).path) > 1:
Then you can combine it with the indexing suggested by demas. For example:
start_offset = (len(urlparse.urlparse(baseurl).path) <= 1) and 2 or 0
img_url = urlparse.urljoin("http://www.example.com/", "../test.png"[start_offset:])
This way, you will not attempt to go to the parent of the root URL.
A:
If you'd like that /../test would mean the same as /test like paths in a file system then you could use normpath():
>>> url = urlparse.urljoin("http://example.com/", "../test")
>>> p = urlparse.urlparse(url)
>>> path = posixpath.normpath(p.path)
>>> urlparse.urlunparse((p.scheme, p.netloc, path, p.params, p.query,p.fragment))
'http://example.com/test'
A:
urlparse.urljoin("http://www.example.com/", "../test.png"[2:])
It is what you need?
| Python urlparse: small issue | I'm making an app that parses html and gets images from it. Parsing is easy using Beautiful Soup and downloading of the html and the images works too with urllib2.
I do have a problem with urlparse to make absolute paths out of relative ones. The problem is best explained with an example:
>>> import urlparse
>>> urlparse.urljoin("http://www.example.com/", "../test.png")
'http://www.example.com/../test.png'
As you can see, urlparse doesn't take away the ../ away. This gives a problem when I try to download the image:
HTTPError: HTTP Error 400: Bad Request
Is there a way to fix this problem in urllib?
| [
"\"..\" would bring you up one directory (\".\" is current directory), so combining that with a domain name url doesn't make much sense. Maybe what you need is:\n>>> urlparse.urljoin(\"http://www.example.com\",\"./test.png\")\n'http://www.example.com/test.png'\n\n",
"I think the best you can do is to pre-parse th... | [
3,
2,
1,
0
] | [] | [] | [
"python",
"urllib2",
"urlparse"
] | stackoverflow_0004114225_python_urllib2_urlparse.txt |
Q:
Find the closest hour
I have a list with these items:
hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
Assuming that now it's 20:18, how can I get the '20:10' item from list? I want to use this to find the current running show in a TV Guide.
A:
>>> import datetime
>>> hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
>>> now = datetime.datetime.strptime("20:18", "%H:%M")
>>> min(hours, key=lambda t: abs(now - datetime.datetime.strptime(t, "%H:%M")))
'20:10'
A:
easy but dirty way
max(t for t in sorted(hours) if t<=now)
A:
I'm not a Python programmer, but I'd use the following algorithm:
Convert everything to "minutes after midnight", e.g. hours = [1170 (= 19*60+30), 1210, ...], currenttime = 1218 (= 20*60+18).
Then just loop thorugh hours and find the last entry which is smaller than currenttime.
A:
You can use functions in the time module; time.strptime() allows you to parse a string into a time-tuple, then time.mktime() converts this to seconds. You can then simply compare all items in seconds, and find the smallest difference.
A:
import bisect
# you can use the time module like katrielalex answer which a standard library
# in python, but sadly for me i become an addict to dateutil :)
from dateutil import parser
hour_to_get = parser.parse('20:18')
hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
hours = map(parser.parse, hours) # Convert to datetime.
hours.sort() # In case the list of hours isn't sorted.
index = bisect.bisect(hours, hour_to_get)
if index in (0, len(hours) - 1):
print "there is no show running at the moment"
else:
print "running show started at %s " % hours[index-1]
Hope this can help you :)
A:
@katrielalex & Tim
import itertools
[x for x in itertools.takewhile( lambda t: now > datetime.datetime.strptime(t, "%H:%M"), hours )][-1]
| Find the closest hour | I have a list with these items:
hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
Assuming that now it's 20:18, how can I get the '20:10' item from list? I want to use this to find the current running show in a TV Guide.
| [
">>> import datetime\n>>> hours = ['19:30', '20:10', '20:30', '21:00', '22:00']\n>>> now = datetime.datetime.strptime(\"20:18\", \"%H:%M\")\n>>> min(hours, key=lambda t: abs(now - datetime.datetime.strptime(t, \"%H:%M\")))\n'20:10'\n\n",
"easy but dirty way\nmax(t for t in sorted(hours) if t<=now)\n\n",
"I'm no... | [
10,
5,
2,
1,
1,
1
] | [] | [] | [
"arrays",
"python",
"time"
] | stackoverflow_0004118526_arrays_python_time.txt |
Q:
Dictionaries in Python
I have a dictionary that has a place name as a key and as the value it has several lists of words, eg, 1 entry looks like:
{'myPlaceName': [u'silly', u'i', u'wish!', u'lol', [u'the', u'lotto'], [, u'me', u'a', u'baby?'], [u'new', u'have', u'new', u'silly', u'new', u'today,', u'cant', u'tell', u'yet,', u'but', u'all', u'guesses', u'silly']]}
How can I join them all so I can get the common words associated with each place?
I would like my output to get silly and new as the common words for the dictionary.
A:
This function takes a list of a list of words, and returns all words that are found in all the lists.
eg get_common_words([['hi', 'hello'], ['bye', 'hi']]) returns ['hi']
def get_common_words(places):
common_words = []
for word in places[0]:
is_common = all(word in place for place in places[1:]) #check to see that this word is in all places
if is_common:
common_words.append(word)
return common_words
or the giant one-liner:
get_common_words = lambda places: [word for word in places[0] if all(word in place for place in places[1:])]
or just go with one of the methods suggested in the comments of this answer.
A:
print ', '.join(dictname['myPlaceName'])
This will create a comma-separated list of all the entries in the list. Replace dictname with the name of your dict.
A:
If it s a list containing only words, use join.
>>> k = [u'silly', u'i', u'wish!', u'lol']
>>> " ".join(k)
u'silly i wish! lol'
>>>
| Dictionaries in Python | I have a dictionary that has a place name as a key and as the value it has several lists of words, eg, 1 entry looks like:
{'myPlaceName': [u'silly', u'i', u'wish!', u'lol', [u'the', u'lotto'], [, u'me', u'a', u'baby?'], [u'new', u'have', u'new', u'silly', u'new', u'today,', u'cant', u'tell', u'yet,', u'but', u'all', u'guesses', u'silly']]}
How can I join them all so I can get the common words associated with each place?
I would like my output to get silly and new as the common words for the dictionary.
| [
"This function takes a list of a list of words, and returns all words that are found in all the lists.\neg get_common_words([['hi', 'hello'], ['bye', 'hi']]) returns ['hi']\ndef get_common_words(places):\n common_words = []\n for word in places[0]:\n is_common = all(word in place for place in places[1:... | [
2,
1,
1
] | [] | [] | [
"dictionary",
"keyword",
"python"
] | stackoverflow_0004119404_dictionary_keyword_python.txt |
Q:
Python Regular Expression
I'd like to extract the designator and ops from the string designator: op1 op2, in which there could be 0 or more ops and multiple spaces are allowed. I used the following regular expression in Python
import re
match = re.match(r"^(\w+):(\s+(\w+))*", "des1: op1 op2")
The problems is that only des1 and op2 is found in the matching groups, op1 is not. Does anyone know why?
The groups from above code is
Group 0: des1: op1 op2
Group 1: des1
Group 2: op2
Group 3: op2
A:
both are 'found', but only one can be 'captured' by the group. if you need to capture more than one group, then you need to use the regular expression functionality multiple times. You could do something like this, first by rewriting the main expression:
match = re.match(r"^(\w+):(.*)", "des1: op1 op2")
then you need to extract the individual subsections:
ops = re.split(r"\s+", match.groups()[1])[1:]
A:
I don't really see why you'd need regex, it's quite simple to parse with string methods:
>>> des, _, ops = 'des1: op1 op2'.partition(':')
>>> ops
' op1 op2'
>>> ops.split()
['op1', 'op2']
A:
I'd do sth like this:
>>> import re
>>> tokenize = re.compile(flags=re.VERBOSE, pattern="""
... (?P<de> \w+ (?=:) ) |
... (?P<op> \w+)
... """).finditer
...
>>>
>>> for each in tokenize("des1: op1 op2"):
... print each.lastgroup, ':', each.group()
...
de : des1
op : op1
op : op2
| Python Regular Expression | I'd like to extract the designator and ops from the string designator: op1 op2, in which there could be 0 or more ops and multiple spaces are allowed. I used the following regular expression in Python
import re
match = re.match(r"^(\w+):(\s+(\w+))*", "des1: op1 op2")
The problems is that only des1 and op2 is found in the matching groups, op1 is not. Does anyone know why?
The groups from above code is
Group 0: des1: op1 op2
Group 1: des1
Group 2: op2
Group 3: op2
| [
"both are 'found', but only one can be 'captured' by the group. if you need to capture more than one group, then you need to use the regular expression functionality multiple times. You could do something like this, first by rewriting the main expression: \nmatch = re.match(r\"^(\\w+):(.*)\", \"des1: op1 op2\")... | [
4,
4,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004119599_python_regex.txt |
Q:
Django - converting URL into links, images, objects
I'm creating simple comment-like application and need to convert normal urls into links, image links into images and yt/vimeo/etc. links into flash objects. E.g.:
http://foo.bar to <a href="http://foo.bar">http://foo.bar</a>
http://foo.bar/image.gif to <img src="http://foo.bar/image.gif"/>
etc.
Of course i can write all of that by myself, but i think it's such obvious piece of code that somebody has already wrote it (maybe even with splitting text into paragraphs). I was googling for some time but couldn't find anything complex, just few snippets. Does filter (or something like that) exist?
Thanks!
PS. There is urlize but it works only for the first case.
A:
Write a custom filter to handle all the necessary cases. Look at the source code for urlize to get started. You'll also need the urlize function from utils.
In your filter, first test for the first case and call urlize on that. Handle the second case and any other cases you may have.
| Django - converting URL into links, images, objects | I'm creating simple comment-like application and need to convert normal urls into links, image links into images and yt/vimeo/etc. links into flash objects. E.g.:
http://foo.bar to <a href="http://foo.bar">http://foo.bar</a>
http://foo.bar/image.gif to <img src="http://foo.bar/image.gif"/>
etc.
Of course i can write all of that by myself, but i think it's such obvious piece of code that somebody has already wrote it (maybe even with splitting text into paragraphs). I was googling for some time but couldn't find anything complex, just few snippets. Does filter (or something like that) exist?
Thanks!
PS. There is urlize but it works only for the first case.
| [
"Write a custom filter to handle all the necessary cases. Look at the source code for urlize to get started. You'll also need the urlize function from utils.\nIn your filter, first test for the first case and call urlize on that. Handle the second case and any other cases you may have.\n"
] | [
4
] | [] | [] | [
"django",
"filter",
"parsing",
"python"
] | stackoverflow_0004119813_django_filter_parsing_python.txt |
Q:
Interpreter in Python: Making your own programming language?
Remember, this is using python.
Well, I was fiddling around with an app I made called Pyline, today. It is a command line-like interface, with some cool features. However, I had an idea while making it: Since its like a "OS", wont it have its own language?
Well, I have seen some articles online on how to make a interpreter, and parser, and compiler, but it wasn't really readable for me. All I saw was a crapload of code. I am one of those guys who need comments or a readme or SOME form or communication towards the user without the code itself, so I think that Stack Overflow would be great for a teenager like me. Can I get some help?
A:
You need some grounding first in order to actually create a programming language.
I strongly suggest picking up a copy of Programming Language Pragmatics, which is quite readable (much more so than the Dragon book) and suitable for self study.
Once you are ready to start messing with parsers, ANTLR is the "gold" standard for parser generators in terms of usability (though flex+bison/yacc are quite capable).
A:
I just came by Xtext, a language development framework. Perhaps that's something you might want to take a look at.
Considering Python you might find it instructive to implement a version of Logo. If you want, you can skip the parsing/lexing stage for now and come up with a object oriented version first to get you going if your OOP skills are up to it. Later on you can hook it up with some graphics library to actually draw something.
In addition to Logo you might want to check out L-systems. See particularly The Algorithmic Beauty of Plants for inspiration.
A:
Like theatrus, I'd suggest starting with a good book on the subject. I can definitely recommend Language Implementation Patterns by Terence Parr (the man behind ANTLR, a common parser generator).
A:
See Peter Norvig's Scheme interpreter in 2 pages of Python with plenty of explanation. There's also a fancier version linked from there, worth reading once you've grokked the simpler one.
| Interpreter in Python: Making your own programming language? | Remember, this is using python.
Well, I was fiddling around with an app I made called Pyline, today. It is a command line-like interface, with some cool features. However, I had an idea while making it: Since its like a "OS", wont it have its own language?
Well, I have seen some articles online on how to make a interpreter, and parser, and compiler, but it wasn't really readable for me. All I saw was a crapload of code. I am one of those guys who need comments or a readme or SOME form or communication towards the user without the code itself, so I think that Stack Overflow would be great for a teenager like me. Can I get some help?
| [
"You need some grounding first in order to actually create a programming language.\nI strongly suggest picking up a copy of Programming Language Pragmatics, which is quite readable (much more so than the Dragon book) and suitable for self study.\nOnce you are ready to start messing with parsers, ANTLR is the \"gold... | [
10,
2,
1,
1
] | [] | [] | [
"compiler_construction",
"interpreter",
"parsing",
"python"
] | stackoverflow_0003115971_compiler_construction_interpreter_parsing_python.txt |
Q:
QTreeView and QDataWidgetMapper interaction
So I have a QTreeView witdget connected to a model, and the same model connected to a QDataWidgetMapper object which connects to a few LineEdits. My problem is that I can't figure out how to change the QDataWidgetMapper index when I click on another item in the QTreeView...
I tried this connect:
i = QtCore.QModelIndex()
self.ui.MyQTree.clicked(i).connect(self.MyDataMapper.setCurrentIndex(i))
But it doesn't work...I get a:
TypeError: native Qt signal is not callable
Really at the end of my rope here...
A:
You cannot connect the result of method execution as slot, but you try.
What you need to do is:
self.ui.MyQTree.clicked.connect(self.MyDataMapper.setCurrentIndex)
and the index, that view will provide when 'clicked' fires will be transferred to slot.
| QTreeView and QDataWidgetMapper interaction | So I have a QTreeView witdget connected to a model, and the same model connected to a QDataWidgetMapper object which connects to a few LineEdits. My problem is that I can't figure out how to change the QDataWidgetMapper index when I click on another item in the QTreeView...
I tried this connect:
i = QtCore.QModelIndex()
self.ui.MyQTree.clicked(i).connect(self.MyDataMapper.setCurrentIndex(i))
But it doesn't work...I get a:
TypeError: native Qt signal is not callable
Really at the end of my rope here...
| [
"You cannot connect the result of method execution as slot, but you try.\nWhat you need to do is:\nself.ui.MyQTree.clicked.connect(self.MyDataMapper.setCurrentIndex)\n\nand the index, that view will provide when 'clicked' fires will be transferred to slot.\n"
] | [
0
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0004112720_pyqt_python.txt |
Q:
Threading to quickly create a large number of charts
I have been trying to find ways to make the following piece of code perform faster:
def do_chart(target="IMG_BACK", xlabel="xlabel", ylabel="ylabel", title="title", ydata=pylab.arange(1961, 2031, 1)):
global MYRAMDICT
MYRAMDICT = {}
print "here"
for i in range(70):
MYRAMDICT[i] = cStringIO.StringIO()
xdata = pylab.arange(1961, 2031, 1)
pylab.figure(num=None, figsize=(10.24, 5.12), dpi=1, facecolor='w', edgecolor='k')
pylab.plot(xdata, ydata, linewidth=3.0)
pylab.xlabel(xlabel); pylab.ylabel(ylabel); pylab.title(i)
pylab.grid(True)
pylab.savefig(MYRAMDICT[i], format='png')
pylab.close()
This function (please ignore the pylab commands, they are here just for illustration) creates a dictionary (MYTAMDICT) which i populated with cString objects that are used to store charts on memmory. These charts are later dynamically presented to the user.
Would somebody please help me to make use of threading so that I can use all of my cores and make this function perform faster? Or point me towards ideas to improve it?
A:
For the description, you'd be far better off using multiprocessing than threading... You have an "embarrassingly parallel" problem, and no disk IO constraints (you're writing to memory) Of course, passing large stuff back and forth between the processes will get expensive, but returning a string representing a .png shouldn't be too bad..
It can be done quite simply:
import multiprocessing
import cStringIO
import matplotlib.pyplot as plt
import numpy as np
import itertools
def main():
"""Generates 1000 random plots and saves them as .png's in RAM"""
pool = multiprocessing.Pool()
same_title = itertools.repeat('Plot %i')
fig_files = pool.map(plot, itertools.izip(xrange(1000), same_title))
def plot(args):
"""Make a random plot"""
# Unfortunately, pool.map (and imap) only support a single argument to
# the function, so you'll have to unpack a tuple of arguments...
i, titlestring = args
outfile = cStringIO.StringIO()
x = np.cumsum(np.random.random(100) - 0.5)
fig = plt.figure()
plt.plot(x)
fig.savefig(outfile, format='png', bbox_inches='tight')
plt.title(titlestring % i)
plt.close()
# cStringIO files aren't pickelable, so we'll return the string instead...
outfile.seek(0)
return outfile.read()
main()
Without using multiprocessing, this takes ~250 secs on my machine. With multiprocessing (8 cores), it takes ~40 secs.
Hope that helps a bit...
A:
Threading will help you if and only if pylab is releasing the gil while executing.
Moreover, pylib must be thread-safe, and your code must use it in a thread-safe way, and this may not be always the case.
That said, if you are going to use threads, I think this is a classical case of job queue; therefore, I would use a queue object, that is nice enough to take care of this pattern.
Here is an example I have put out just by meddling with your code and the example given in the queue documentation. I did not even checked it thoroughly, so it WILL have bugs; it is more to give an idea than anything else.
# "Business" code
def do_chart(target="IMG_BACK", xlabel="xlabel", ylabel="ylabel", title="title", ydata=pylab.arange(1961, 2031, 1)):
global MYRAMDICT
MYRAMDICT = {}
print "here"
for i in range(70):
q.put(i)
q.join() # block until all tasks are done
def do_work(i):
MYRAMDICT[i] = cStringIO.StringIO()
xdata = pylab.arange(1961, 2031, 1)
pylab.figure(num=None, figsize=(10.24, 5.12), dpi=1, facecolor='w', edgecolor='k')
pylab.plot(xdata, ydata, linewidth=3.0)
pylab.xlabel(xlabel); pylab.ylabel(ylabel); pylab.title(i)
pylab.grid(True)
pylab.savefig(MYRAMDICT[i], format='png')
pylab.close()
# Handling the queue
def worker():
while True:
i = q.get()
do_work(i)
q.task_done()
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
| Threading to quickly create a large number of charts | I have been trying to find ways to make the following piece of code perform faster:
def do_chart(target="IMG_BACK", xlabel="xlabel", ylabel="ylabel", title="title", ydata=pylab.arange(1961, 2031, 1)):
global MYRAMDICT
MYRAMDICT = {}
print "here"
for i in range(70):
MYRAMDICT[i] = cStringIO.StringIO()
xdata = pylab.arange(1961, 2031, 1)
pylab.figure(num=None, figsize=(10.24, 5.12), dpi=1, facecolor='w', edgecolor='k')
pylab.plot(xdata, ydata, linewidth=3.0)
pylab.xlabel(xlabel); pylab.ylabel(ylabel); pylab.title(i)
pylab.grid(True)
pylab.savefig(MYRAMDICT[i], format='png')
pylab.close()
This function (please ignore the pylab commands, they are here just for illustration) creates a dictionary (MYTAMDICT) which i populated with cString objects that are used to store charts on memmory. These charts are later dynamically presented to the user.
Would somebody please help me to make use of threading so that I can use all of my cores and make this function perform faster? Or point me towards ideas to improve it?
| [
"For the description, you'd be far better off using multiprocessing than threading... You have an \"embarrassingly parallel\" problem, and no disk IO constraints (you're writing to memory) Of course, passing large stuff back and forth between the processes will get expensive, but returning a string representing a .... | [
3,
2
] | [] | [] | [
"matplotlib",
"multithreading",
"optimization",
"python"
] | stackoverflow_0004119473_matplotlib_multithreading_optimization_python.txt |
Q:
Global Name Error when deploying with Fabric
The other person on my dev team has been deploying our Django app to the server via Fabric. Since I need to be able to deploy as well I setup Fabric on my system, but when I try to deploy I get a Global Name error:
File ".../fabfile.py", line 4, in staging
config.settings = 'staging'
NameError: global name 'config' is not defined
Since we know the fabfile is fine, it must be a problem in my setup. Any ideas?
A:
ohhh i know this error , this error is happening because you have installed in your machine fabric version higher than 0.9 and the fabric file that you want to use has been developed using and old version of fabric < 0.9.
For more detail the config obj has been replaced with env in fabric 0.9 so if you run yor fabfile using fabric version higher than 0.9 it will not recognize the config object.
so you should install an old version of the fabric package or just update your fabfile i think it's time for that :)
Hope this can help you :)
| Global Name Error when deploying with Fabric | The other person on my dev team has been deploying our Django app to the server via Fabric. Since I need to be able to deploy as well I setup Fabric on my system, but when I try to deploy I get a Global Name error:
File ".../fabfile.py", line 4, in staging
config.settings = 'staging'
NameError: global name 'config' is not defined
Since we know the fabfile is fine, it must be a problem in my setup. Any ideas?
| [
"ohhh i know this error , this error is happening because you have installed in your machine fabric version higher than 0.9 and the fabric file that you want to use has been developed using and old version of fabric < 0.9.\nFor more detail the config obj has been replaced with env in fabric 0.9 so if you run yor fa... | [
7
] | [] | [] | [
"django",
"fabric",
"python"
] | stackoverflow_0004119700_django_fabric_python.txt |
Q:
app engine python setup
<< Big update below implies it's simply a logging issue >>
I'm trying to get app engine setup with python and having some problem that I suspect is some simple step I've missed. My app.yaml says this:
application: something #name here is the one I used to register i.e. something.appspot.com
version: 1
runtime: python
api_version: 1
handlers:
- url: .*
script: myapp.py
and my myapp.py says this:
import cgi
import Utils
import Sample
import logging
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
self.response.out.write('Welcome to my server! Why is this not working?')
self.response.out.write('</body></html>')
def main():
application = webapp.WSGIApplication([('/', MainPage),
('/Sample', Sample.HttpRequestHandler)],
debug=True)
run_wsgi_app(application)
if __name__ == "__main__":
main()
When I run this on localhost, I get my html "Welcome" message when passing in / but when I pass in /Sample I don't get any where. Also, I can't seem to log messages. I call logging.debug() and nothing shows on the log console. Any ideas? Here is my Sample.py. Sorry about the strange tabbing. Copy paste didn't line them up and editing it by hand didn't seem to correct it.
class HttpRequestHandler(webapp.RequestHandler):
def get(self):
Utils.log("Sample handler called")
try:
if HttpRequestHandler.requestIsValid(self):
intParam = int(self.request.get('param1'))
floatParam = float(self.request.get('param1'))
stringParam = self.request.get('param1')
Utils.log("params: " + str(intParam) + " " + str(floatParam) + " " + stringParam)
if intParam == 1:
self.response.set_status(200, message="Success")
else:
self.response.set_status(400, message="Error processing sample command")
else:
raise StandardError
except Exception, e:
logging.debug("Exception: %s" % (e))
self.response.set_status(400, message="Error processing sample command")
def requestIsValid(self):
if self.request.get('param1') != "" and \
self.request.get('param2') != "" and \
self.request.get('param3') != "":
return True
else:
return False
So I know this is totally lame, but since I couldn't see any log messages, I threw in a bunch of "raise StandardError" calls just to see what would throw exception output to my browser window when I try to invoke my Sample message. What I found was that the server is calling into the Sample handler just fine it seems, even checking the int param is right.
I think the problem is that I just can't see my log messages! Any idea why they aren't showing up? I call logging.debug() through those Util.log() calls. Is there some flag or something suppressing my output from showing in the log console?
A:
You don't have RequestHandler subclass for the "/Sample" path, like you do for the "/" path (i.e., MainPage).
To get logs, either start your SDK app server with dev_appserver.py and look at the logs it spits out, or click the Logs button in the Google App Engine Launcher GUI.
A:
I discovered that indeed it was a logging issue (everything underneath was working just fine). I use Google App Engine Launcher, so here's what I had to do with the settings to get it to work:
Go into Edit -> Application Settings
under Extra Flags add the flag -d
I also selected to clear the datastore at launch in my settings, but I don't think this impacts the logs.
| app engine python setup | << Big update below implies it's simply a logging issue >>
I'm trying to get app engine setup with python and having some problem that I suspect is some simple step I've missed. My app.yaml says this:
application: something #name here is the one I used to register i.e. something.appspot.com
version: 1
runtime: python
api_version: 1
handlers:
- url: .*
script: myapp.py
and my myapp.py says this:
import cgi
import Utils
import Sample
import logging
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
self.response.out.write('Welcome to my server! Why is this not working?')
self.response.out.write('</body></html>')
def main():
application = webapp.WSGIApplication([('/', MainPage),
('/Sample', Sample.HttpRequestHandler)],
debug=True)
run_wsgi_app(application)
if __name__ == "__main__":
main()
When I run this on localhost, I get my html "Welcome" message when passing in / but when I pass in /Sample I don't get any where. Also, I can't seem to log messages. I call logging.debug() and nothing shows on the log console. Any ideas? Here is my Sample.py. Sorry about the strange tabbing. Copy paste didn't line them up and editing it by hand didn't seem to correct it.
class HttpRequestHandler(webapp.RequestHandler):
def get(self):
Utils.log("Sample handler called")
try:
if HttpRequestHandler.requestIsValid(self):
intParam = int(self.request.get('param1'))
floatParam = float(self.request.get('param1'))
stringParam = self.request.get('param1')
Utils.log("params: " + str(intParam) + " " + str(floatParam) + " " + stringParam)
if intParam == 1:
self.response.set_status(200, message="Success")
else:
self.response.set_status(400, message="Error processing sample command")
else:
raise StandardError
except Exception, e:
logging.debug("Exception: %s" % (e))
self.response.set_status(400, message="Error processing sample command")
def requestIsValid(self):
if self.request.get('param1') != "" and \
self.request.get('param2') != "" and \
self.request.get('param3') != "":
return True
else:
return False
So I know this is totally lame, but since I couldn't see any log messages, I threw in a bunch of "raise StandardError" calls just to see what would throw exception output to my browser window when I try to invoke my Sample message. What I found was that the server is calling into the Sample handler just fine it seems, even checking the int param is right.
I think the problem is that I just can't see my log messages! Any idea why they aren't showing up? I call logging.debug() through those Util.log() calls. Is there some flag or something suppressing my output from showing in the log console?
| [
"You don't have RequestHandler subclass for the \"/Sample\" path, like you do for the \"/\" path (i.e., MainPage).\nTo get logs, either start your SDK app server with dev_appserver.py and look at the logs it spits out, or click the Logs button in the Google App Engine Launcher GUI.\n",
"I discovered that indeed i... | [
0,
0
] | [] | [] | [
"google_app_engine",
"installation",
"python"
] | stackoverflow_0004119050_google_app_engine_installation_python.txt |
Q:
How to translate this to SQLObject: SELECT DISTINCT columnname WHERE
I've been going through the sqlobject and sqlbuilder documentation and forums and I cannot seem to grasp the information there.
I have a specific SQL query that I need:
select distinct author from blogtable where keyword = "dust";
Multiple authors can post about multiple subjects.
The query works on the MySQL database if I use the raw sql query. But I can't seem to understand what I must do to get this correctly working in SQLObject.
I see heaps of references to sqlbuilder, but the manual page is not very extensive. The examples provided in the google groups also talk as if SQLbuilder is the answer, but again, no specific example (for my problem) that I can understand.
Could someone well versed in SQLObject explain to me how I implement the above SQL in SQLObject ?
If not possible, can I pass the raw sql in any way via SQLObject to the underlying db ?
A:
I don't have much experience with SQLObject, but from the docs I deduce that it should be something like this:
class Blog(SQLObject):
class sqlmeta:
table = 'blogtable'
author = StringCol()
keyword = StringCol()
Blog.select(Blog.q.keyword=='dust', distinct=True)
Version 2
select = Select(
[Blog.q.author],
Blog.q.keyword=='dust',
distinct=True,
)
sql = connection.sqlrepr(select)
for author in connection.queryAll(sql):
print author
| How to translate this to SQLObject: SELECT DISTINCT columnname WHERE | I've been going through the sqlobject and sqlbuilder documentation and forums and I cannot seem to grasp the information there.
I have a specific SQL query that I need:
select distinct author from blogtable where keyword = "dust";
Multiple authors can post about multiple subjects.
The query works on the MySQL database if I use the raw sql query. But I can't seem to understand what I must do to get this correctly working in SQLObject.
I see heaps of references to sqlbuilder, but the manual page is not very extensive. The examples provided in the google groups also talk as if SQLbuilder is the answer, but again, no specific example (for my problem) that I can understand.
Could someone well versed in SQLObject explain to me how I implement the above SQL in SQLObject ?
If not possible, can I pass the raw sql in any way via SQLObject to the underlying db ?
| [
"I don't have much experience with SQLObject, but from the docs I deduce that it should be something like this:\nclass Blog(SQLObject):\n class sqlmeta:\n table = 'blogtable'\n\n author = StringCol()\n keyword = StringCol()\n\nBlog.select(Blog.q.keyword=='dust', distinct=True)\n\nVersion 2\nselect =... | [
1
] | [] | [] | [
"python",
"sql",
"sqlobject"
] | stackoverflow_0004120165_python_sql_sqlobject.txt |
Q:
Problems with Toplevel Widget and Portscanner
def PortScanWin():
win2 = Toplevel()
win2.title("PortScan")
win2.wm_maxsize(width='190',height='370')
win2.wm_minsize(width='190',height='370')
def go():
global app
result.delete(1.0,END)
app=scan()
app.start()
def stop():
app.flag='stop'
def clear():
host_e.delete(0,END)
start_port_e.delete(0,END)
end_port_e.delete(0,END)
result.delete(1.0,END)
class scan(threading.Thread):
def _init_(self):
threading.thread._init_(self)
def run(self):
self.host=host_e.get()
self.start_port=int(start_port_e.get())
self.end_port=int(end_port_e.get())
self.open_counter=0
self.flag='scan'
start.config(text="Stop",command=stop)
win2.update()
result.insert(END,"Scanning "+str(self.host)+"...\n\n")
win2.update()
while self.start_port<=self.end_port and self.flag=='scan':
self.sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sk.settimeout(0.01)
try:
self.sk.connect((self.host,self.start_port))
except:
pass
else:
result.insert(END,str(self.start_port)+"\n")
win2.update()
self.open_counter=self.open_counter+1
self.sk.close()
self.start_port=self.start_port+1
if self.flag=='scan':
result.insert(END,"\nDone !!\nFound "+str(self.open_counter)+" opened ports")
win2.update()
start.config(text="Scan",command=go)
win2.update()
elif self.flag=='stop':
result.insert(END,"\n Scan stopped.")
start.config(text="Scan",command=go)
win2.update()
Label(win2,text="Host: ").grid(row=1,column=1,sticky="w")
host_e=Entry(win2)
host_e.grid(row=1,column=2,sticky="WE")
Label(win2,text="Start port: ").grid(row=2,column=1,sticky="w")
start_port_e=Entry(win2)
start_port_e.grid(row=2,column=2,sticky="WE")
Label(win2,text="End port: ").grid(row=3,column=1,sticky="w")
end_port_e=Entry(win2)
end_port_e.grid(row=3,column=2,sticky="WE")
start=Button(win2,text="Scan",command=go)
start.grid(row=5,columnspan=3,sticky="WE")
clear=Button(win2,text="Clear",command=clear)
clear.grid(row=6,columnspan=3,sticky="WE")
result=Text(win2,width=20,height=20)
result.grid(row=7,columnspan=3,sticky="WENS")
The portscanner is being run in a child window, but some how it doesnt work, When I click "Scan" I get "Scanning..None" and it doesnt do anything, Any help will be highly appreciated, Thank You.
A:
This isn't really an answer to your question, but you may like to check out Scapy. Scapy lets you build your own packets and read raw data from a network interface. Both are obviously very helpful in writing a port scanner. So, depending on what you need, you may wish to replace your port-scanner with one written in Scapy.
More information at: http://www.secdev.org/projects/scapy/
A:
Learn to trust the feedback you get. In your case the code is printing "Scanning... None". So, obviously something is "None" when it (presumably) should be something else. Figure out why self.host is None and you'll likely solve your problem
| Problems with Toplevel Widget and Portscanner | def PortScanWin():
win2 = Toplevel()
win2.title("PortScan")
win2.wm_maxsize(width='190',height='370')
win2.wm_minsize(width='190',height='370')
def go():
global app
result.delete(1.0,END)
app=scan()
app.start()
def stop():
app.flag='stop'
def clear():
host_e.delete(0,END)
start_port_e.delete(0,END)
end_port_e.delete(0,END)
result.delete(1.0,END)
class scan(threading.Thread):
def _init_(self):
threading.thread._init_(self)
def run(self):
self.host=host_e.get()
self.start_port=int(start_port_e.get())
self.end_port=int(end_port_e.get())
self.open_counter=0
self.flag='scan'
start.config(text="Stop",command=stop)
win2.update()
result.insert(END,"Scanning "+str(self.host)+"...\n\n")
win2.update()
while self.start_port<=self.end_port and self.flag=='scan':
self.sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sk.settimeout(0.01)
try:
self.sk.connect((self.host,self.start_port))
except:
pass
else:
result.insert(END,str(self.start_port)+"\n")
win2.update()
self.open_counter=self.open_counter+1
self.sk.close()
self.start_port=self.start_port+1
if self.flag=='scan':
result.insert(END,"\nDone !!\nFound "+str(self.open_counter)+" opened ports")
win2.update()
start.config(text="Scan",command=go)
win2.update()
elif self.flag=='stop':
result.insert(END,"\n Scan stopped.")
start.config(text="Scan",command=go)
win2.update()
Label(win2,text="Host: ").grid(row=1,column=1,sticky="w")
host_e=Entry(win2)
host_e.grid(row=1,column=2,sticky="WE")
Label(win2,text="Start port: ").grid(row=2,column=1,sticky="w")
start_port_e=Entry(win2)
start_port_e.grid(row=2,column=2,sticky="WE")
Label(win2,text="End port: ").grid(row=3,column=1,sticky="w")
end_port_e=Entry(win2)
end_port_e.grid(row=3,column=2,sticky="WE")
start=Button(win2,text="Scan",command=go)
start.grid(row=5,columnspan=3,sticky="WE")
clear=Button(win2,text="Clear",command=clear)
clear.grid(row=6,columnspan=3,sticky="WE")
result=Text(win2,width=20,height=20)
result.grid(row=7,columnspan=3,sticky="WENS")
The portscanner is being run in a child window, but some how it doesnt work, When I click "Scan" I get "Scanning..None" and it doesnt do anything, Any help will be highly appreciated, Thank You.
| [
"This isn't really an answer to your question, but you may like to check out Scapy. Scapy lets you build your own packets and read raw data from a network interface. Both are obviously very helpful in writing a port scanner. So, depending on what you need, you may wish to replace your port-scanner with one written ... | [
0,
0
] | [] | [] | [
"multithreading",
"python",
"tkinter",
"widget"
] | stackoverflow_0004116378_multithreading_python_tkinter_widget.txt |
Q:
Load a tag library for a template externally in Django?
I have a template tag that includes a template:
def WidgeLoaderNode(IncludeNode):
def __init__(tpl, scopes=None):
self.scopes = scopes
self.tpl = tpl
super(WidgeLoaderNode, self).__init__('""')
def render(self, context):
self.template_name = self.tpl.resolve(context)
scopes = self.scopes.resolve(context) if options else DEFAULT_SCOPES
context.push()
context['form'] = ScopeForm(scopes)
fragment = super(WidgeLoaderNode, self).render(context)
context.pop()
return fragment
@register.tag
def widget_form(parser, token):
bits = token.split_contents()
tpl = parser.compile_filter(bits[1])
scopes = parser.compile_filter(bits[2]) if len(bits) > 2 else None
return WidgeLoaderNode(tpl, scopes)
The template has to be specified from the template. In those templates, I need to include a couple of tag libraries:
{% load widgets_tags helpers %}
. Is it possible to reduce boilerplate template code in them by loading those libraries from my node code?
A:
Maybe you could use something like this: http://djangosnippets.org/snippets/342/ - i.e. django.template.add_to_builtins
| Load a tag library for a template externally in Django? | I have a template tag that includes a template:
def WidgeLoaderNode(IncludeNode):
def __init__(tpl, scopes=None):
self.scopes = scopes
self.tpl = tpl
super(WidgeLoaderNode, self).__init__('""')
def render(self, context):
self.template_name = self.tpl.resolve(context)
scopes = self.scopes.resolve(context) if options else DEFAULT_SCOPES
context.push()
context['form'] = ScopeForm(scopes)
fragment = super(WidgeLoaderNode, self).render(context)
context.pop()
return fragment
@register.tag
def widget_form(parser, token):
bits = token.split_contents()
tpl = parser.compile_filter(bits[1])
scopes = parser.compile_filter(bits[2]) if len(bits) > 2 else None
return WidgeLoaderNode(tpl, scopes)
The template has to be specified from the template. In those templates, I need to include a couple of tag libraries:
{% load widgets_tags helpers %}
. Is it possible to reduce boilerplate template code in them by loading those libraries from my node code?
| [
"Maybe you could use something like this: http://djangosnippets.org/snippets/342/ - i.e. django.template.add_to_builtins\n"
] | [
0
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0004119904_django_django_templates_python.txt |
Q:
Python bisect.bisect() counterpart in R?
I want to draw from discrete distribution.
I have a matrix, pi, which consists of vectors of probabilities (with the same number of columns, and sum of each row is 1).
In Python, I can do the following
cumsumpi = cumsum(pi, axis = 1)
[bisect.bisect(k, random.rand()) for k in cumsumpi]
to get the vector of draws by the probability given by pi.
Now I want to reproduce this with R. I know there is "sample" function in R, but it seems it uses some different algorithm then bisect so I get different draws, even though I use the same set.seed() in both cases.
I used rpy2 to get the exactly same random draws in Python as in R. For example,
instead of random.rand(), I used
[bisect.bisect(k, asarray(robjects.r('runif(1)'))) for k in cumsumpi]
Please let me know if there is other function than sample in R which do the same thing.
-Joon
edited:
I managed to reproduce the exactly same draws with the following, but it was slow.
cumsumpi = t(apply(pi, 1, cumsum))
getfirstindx = function(cumprobs) {
return(which(cumprobs > runif(1))[1])
}
apply(cumsumpi, 1, getfirstindx)
A:
here is an alternate approach that avoids using apply and instead vectorizes the operation. initial checks indicate that it is twice as fast, but one needs to explore more in detail.
cumsumpi = t(apply(pi, 1, cumsum));
u = runif(nrow(cumsumpi));
max.col((cumsumpi > u) * 1, "first")
to speed it up further, one could think of vectorizing the operation of calculating the cumulative column sums for each row. let me know if that step was the bottleneck, by running a profiler on your R code.
A:
I can't reconcile your question's title with the question body--in any event, here's an R function identical to python's bisect:
The package gtool*s has a binary search function, **binsearch*, that is nearly identical to python's bisect, e.g.,
# search for 25 in the range 0 through 100
> binseaerch(fun = function(x) x - 25, range=c(0, 100))
$call
binsearch(fun = function(x) x - 25, range = c(0, 100))
$numiter
[1] 2
$flag
[1] "Found"
$where
[1] 25
$value
[1] 0
A:
What I was looking for was findInterval - Find Interval Numbers or Indices. :)
A:
I did not post it, but what I ended up using was pretty similar:
cumsumpi = t(apply(pi, 1, cumsum))
1 + rowSums(cumsumpi > runif(nrow(pi)))
The speed was pretty much same as your code. If I were aware of max.col, I would have used that.
And following your suggestion, I vectorized the cumsum thing and it gave me nontrivial speed increase. Thank you.
-Joon
| Python bisect.bisect() counterpart in R? | I want to draw from discrete distribution.
I have a matrix, pi, which consists of vectors of probabilities (with the same number of columns, and sum of each row is 1).
In Python, I can do the following
cumsumpi = cumsum(pi, axis = 1)
[bisect.bisect(k, random.rand()) for k in cumsumpi]
to get the vector of draws by the probability given by pi.
Now I want to reproduce this with R. I know there is "sample" function in R, but it seems it uses some different algorithm then bisect so I get different draws, even though I use the same set.seed() in both cases.
I used rpy2 to get the exactly same random draws in Python as in R. For example,
instead of random.rand(), I used
[bisect.bisect(k, asarray(robjects.r('runif(1)'))) for k in cumsumpi]
Please let me know if there is other function than sample in R which do the same thing.
-Joon
edited:
I managed to reproduce the exactly same draws with the following, but it was slow.
cumsumpi = t(apply(pi, 1, cumsum))
getfirstindx = function(cumprobs) {
return(which(cumprobs > runif(1))[1])
}
apply(cumsumpi, 1, getfirstindx)
| [
"here is an alternate approach that avoids using apply and instead vectorizes the operation. initial checks indicate that it is twice as fast, but one needs to explore more in detail.\ncumsumpi = t(apply(pi, 1, cumsum));\nu = runif(nrow(cumsumpi));\n\nmax.col((cumsumpi > u) * 1, \"first\")\n\nto speed it up further... | [
2,
0,
0,
0
] | [] | [] | [
"python",
"r"
] | stackoverflow_0004111685_python_r.txt |
Q:
How to combine Cmd and Matplotlib in python
I'd like to combine interactive plotting in Matplotlib and the Command line interface Cmd in python. How can I do this?
Can I use threading? I tried the following:
from cmd import Cmd
import matplotlib.pylab as plt
from threading import Thread
class MyCmd(Cmd):
def __init__(self):
Cmd.__init__(self)
self.fig = plt.figure()
self.ax = self.fig.add_subplot(1,1,1)
def do_foo(self, arg):
self.ax.plot(range(10))
self.fig.canvas.draw()
if __name__=='__main__':
c = MyCmd()
Thread(target=c.cmdloop).start()
plt.show()
It opens a figure window and I can type commands in the console that are actually executed. When the "foo" command is executed it draws in the figure window. So far everything is ok. When I reenter the console, however, the console seems to be stuck and there is now new command window. But when I click into the figure window the console outputs a new command prompt and I can enter a new command.
It seems the two loops are not really interleaved or something. Is there a better, more common way?
A:
I found something that works, but is rather ugly
from cmd import Cmd
import matplotlib.pylab as plt
from threading import Thread
import time
class MyCmd(Cmd):
def __init__(self):
Cmd.__init__(self)
self.fig = plt.figure()
self.ax = self.fig.add_subplot(1,1,1)
def do_foo(self, arg):
self.ax.plot(range(10))
self.fig.canvas.draw()
if __name__=='__main__':
plt.ion()
c = MyCmd()
def loop():
while True:
c.fig.canvas.draw()
time.sleep(0.1)
Thread(target=loop).start()
c.cmdloop()
This simply calls the draw method of the figure periodically. If I don't do this, the figure is not redrawn, when it was occluded and comes to the front again.
But this seems ugly. Is there a better way?
A:
iPython is an pretty popular. Take a look at Using matplotlib in a python shell.
| How to combine Cmd and Matplotlib in python | I'd like to combine interactive plotting in Matplotlib and the Command line interface Cmd in python. How can I do this?
Can I use threading? I tried the following:
from cmd import Cmd
import matplotlib.pylab as plt
from threading import Thread
class MyCmd(Cmd):
def __init__(self):
Cmd.__init__(self)
self.fig = plt.figure()
self.ax = self.fig.add_subplot(1,1,1)
def do_foo(self, arg):
self.ax.plot(range(10))
self.fig.canvas.draw()
if __name__=='__main__':
c = MyCmd()
Thread(target=c.cmdloop).start()
plt.show()
It opens a figure window and I can type commands in the console that are actually executed. When the "foo" command is executed it draws in the figure window. So far everything is ok. When I reenter the console, however, the console seems to be stuck and there is now new command window. But when I click into the figure window the console outputs a new command prompt and I can enter a new command.
It seems the two loops are not really interleaved or something. Is there a better, more common way?
| [
"I found something that works, but is rather ugly\nfrom cmd import Cmd\nimport matplotlib.pylab as plt\nfrom threading import Thread\nimport time\n\nclass MyCmd(Cmd):\n\n def __init__(self):\n Cmd.__init__(self)\n self.fig = plt.figure()\n self.ax = self.fig.add_subplot(1,1,1)\n\n def do_... | [
3,
0
] | [] | [] | [
"cmd",
"interactive",
"matplotlib",
"plot",
"python"
] | stackoverflow_0003472088_cmd_interactive_matplotlib_plot_python.txt |
Q:
Python Cookies and PHP virtual()
I narrowed down the problem:
os.environ.get('HTTP_COOKIE')
This always seems to be None when calling the Python file with that line using PHP's virtual(). Does anyone know why this is?
I'm using Python 2.7 because of how much I need the Python Imaging Library.
EDIT: Never mind, it's been fixed. It was because I'm an idiot and didn't know I had to set the cookie's path to /, causing it only to work where the cookie was generated.
A:
Try to set cookies by your own with apache_setenv function.
But if the only thing that you need from python is PIL, then you probably don't need python at all. PHP have very powerful tools like MagickWand, a frontend to image magick.
| Python Cookies and PHP virtual() | I narrowed down the problem:
os.environ.get('HTTP_COOKIE')
This always seems to be None when calling the Python file with that line using PHP's virtual(). Does anyone know why this is?
I'm using Python 2.7 because of how much I need the Python Imaging Library.
EDIT: Never mind, it's been fixed. It was because I'm an idiot and didn't know I had to set the cookie's path to /, causing it only to work where the cookie was generated.
| [
"Try to set cookies by your own with apache_setenv function.\nBut if the only thing that you need from python is PIL, then you probably don't need python at all. PHP have very powerful tools like MagickWand, a frontend to image magick.\n"
] | [
0
] | [] | [] | [
"cgi",
"php",
"python"
] | stackoverflow_0004120258_cgi_php_python.txt |
Q:
Keyword search using python and sqlite
I have a plugin to a game server that writes down changes made to a map.The database contains entries formatted like this - id INTEGER PRIMARY KEY,matbefore INTEGER, matafter INTEGER, name VARCHAR(50), date DATE. I am trying to create a function that, when given a column name, an integer, string, or tuple of an integer or string, and a keyword, will find the selected entries. so far, this is the code that I have come to -
def readdb(self,keyword,column,returncolumn = "*"):
self.memwrite
if isinstance(keyword, int) or isinstance(keyword,str):
entry = [keyword]
qmarks = ("? OR " * len(entry))[:-4]
statement = 'SELECT all {0} FROM main WHERE {1} is {2}'.format(returncolumn,column,qmarks)
print(qmarks)
self.memcursor.execute(statement, entry)
return(self.memcursor.fetchall())
keyword is a keyword to search for, column is teh column to search in, and returncolumn is the column to return So I was wondering why this code always fetches no rows, EG - Returns None, no matter what I put for the function. It seems to work fine if I do these things in the console, but not if I wrap them in a function
A:
If entry is a list (like in yesterday's question) , it's not going to work.
>>> returncolumn = "*"
>>> column = "name"
>>> entry = ["Able", "Baker", "Charlie"]
>>> qmarks = ("? OR " * len(entry))[:-4]
>>> statement = 'SELECT all {0} FROM main WHERE {1} is {2}'.format(returncolumn,
column,qmarks)
>>> print statement
SELECT all * FROM main WHERE name is ? OR ? OR ?
and what SQLite will see is:
SELECT all * FROM main WHERE name is 'Able' OR 'Baker' OR 'Charlie'
which is not valid syntax because you need =, not is.
Even if you fix that then (using an integer query for example):
SELECT all * FROM main WHERE id = 1 or 2 or 3
you will get mysterious results because that means WHERE ((id = 1) or 2) or 3), not what you think it does ... you need WHERE id = 1 or id = 2 or id = 3 or (reverting to yesterday's question) WHERE id IN (1,2,3)
A:
def readdb(self,keyword,column,returncolumn = "*"):
self.memwrite # 1.
if isinstance(keyword, int) or isinstance(keyword,str): # 2.
entry = [keyword] # 3.
qmarks = ("? OR " * len(entry))[:-4] # 4.
statement = 'SELECT all {0} FROM main WHERE {1} is {2}'.format(returncolumn,column,qmarks)
print(qmarks) # 5.
self.memcursor.execute(statement, entry)
return(self.memcursor.fetchall())
Not sure what this is supposed to
do. Did you mean self.memwrite()?
Can be changed to if
isinstance(keyword, (int,str))
Or better yet, don't test the type.
As you've written it, keyword can
not be a unicode string. Why
restrict like this? In this case I
think it would be better to use
a try...except... block to catch the subsequent
error than to restrict type.
So at best len(entry) = 1. Notice
also, its possible to never reach
this line if keyword is not of type
int or str. In that case, you would
get an error on line (4) since entry
would not be defined..
This could also be written as
qmarks = ' OR '.join(['?']*len(entry))
It avoids the need for the somewhat magic number 4 in ("? OR " *1)[:-4].
What are you seeing here? If it was
empty, that should have been a clue. Also it would be worth running
print(statement) to get a full picture of what is being sent to .execute().
Perhaps try
statement = 'SELECT {0} FROM main WHERE {1} = ?'.format(
returncolumn,column)
In particular, the is should be changed to =.
| Keyword search using python and sqlite | I have a plugin to a game server that writes down changes made to a map.The database contains entries formatted like this - id INTEGER PRIMARY KEY,matbefore INTEGER, matafter INTEGER, name VARCHAR(50), date DATE. I am trying to create a function that, when given a column name, an integer, string, or tuple of an integer or string, and a keyword, will find the selected entries. so far, this is the code that I have come to -
def readdb(self,keyword,column,returncolumn = "*"):
self.memwrite
if isinstance(keyword, int) or isinstance(keyword,str):
entry = [keyword]
qmarks = ("? OR " * len(entry))[:-4]
statement = 'SELECT all {0} FROM main WHERE {1} is {2}'.format(returncolumn,column,qmarks)
print(qmarks)
self.memcursor.execute(statement, entry)
return(self.memcursor.fetchall())
keyword is a keyword to search for, column is teh column to search in, and returncolumn is the column to return So I was wondering why this code always fetches no rows, EG - Returns None, no matter what I put for the function. It seems to work fine if I do these things in the console, but not if I wrap them in a function
| [
"If entry is a list (like in yesterday's question) , it's not going to work.\n>>> returncolumn = \"*\"\n>>> column = \"name\"\n>>> entry = [\"Able\", \"Baker\", \"Charlie\"]\n>>> qmarks = (\"? OR \" * len(entry))[:-4]\n>>> statement = 'SELECT all {0} FROM main WHERE {1} is {2}'.format(returncolumn,\ncolumn,qmarks)\... | [
1,
0
] | [] | [] | [
"database",
"python",
"sqlite"
] | stackoverflow_0004119972_database_python_sqlite.txt |
Q:
python module layout
I'm just starting to get to the point in my python projects that I need to start using multiple packages and I'm a little confused on exactly how everything is supposed to work together. What exactly should go into the __init__.py of the package? Some projects I see just have blank inits and all of their code are in modules in that package. Other projects implement what seems to be the majority of the package's classes and functions inside the init.
Is there a document or style guide or something that describes what the python authors had in mind for the use of packages and the __init__ file and such?
Edit:
I know the point of having the __init__.py file in the simplest sense that it makes a folder a package. But why would I put a function there instead of a module in that same folder(package)?
A:
__init__.py can be empty, but what it really does is make sure Python treats your directories correctly, provide any initialization you might need for when your package is imported (configuring the environment or something along those lines), or defining __all__ so that Python knows what to do when someone uses from package import *.
Most everything you need to know is described in the docs on Packages. Dive Into Python also has a piece on packaging.
A:
You already know, I guess that __init__.py files are required to make Python treat the directories as containing packages.
In the above model __init__.py can remain empty.
You can can also execute initialization code for the package.
You can also set the __all__ variable.
[Edit: learnings]
When you do "from package import item", or "from package import *", then the variable __all__ can be used to import selected packages.
See : http://docs.python.org/tutorial/modules.html
| python module layout | I'm just starting to get to the point in my python projects that I need to start using multiple packages and I'm a little confused on exactly how everything is supposed to work together. What exactly should go into the __init__.py of the package? Some projects I see just have blank inits and all of their code are in modules in that package. Other projects implement what seems to be the majority of the package's classes and functions inside the init.
Is there a document or style guide or something that describes what the python authors had in mind for the use of packages and the __init__ file and such?
Edit:
I know the point of having the __init__.py file in the simplest sense that it makes a folder a package. But why would I put a function there instead of a module in that same folder(package)?
| [
"__init__.py can be empty, but what it really does is make sure Python treats your directories correctly, provide any initialization you might need for when your package is imported (configuring the environment or something along those lines), or defining __all__ so that Python knows what to do when someone uses fr... | [
8,
1
] | [] | [] | [
"python",
"python_module"
] | stackoverflow_0004120759_python_python_module.txt |
Q:
Python read() seems to return less data than it reads
Can anyone tell me why the length of data is much less than the position of the end of the file? I would have expected these to be equal.
>>> target = open('target.jpg')
>>> print target.tell()
0
>>> data = target.read()
>>> print target.tell()
40962
>>> print len(data)
52
A:
Open the file in binary mode:
target = open('target.jpg','rb')
I would not trust tell() on a file not opened as binary.
Later: actually, on reviewing the comments, I should have said I would not trust a read on a binary file opened as text.
| Python read() seems to return less data than it reads | Can anyone tell me why the length of data is much less than the position of the end of the file? I would have expected these to be equal.
>>> target = open('target.jpg')
>>> print target.tell()
0
>>> data = target.read()
>>> print target.tell()
40962
>>> print len(data)
52
| [
"Open the file in binary mode:\ntarget = open('target.jpg','rb')\n\nI would not trust tell() on a file not opened as binary.\n\nLater: actually, on reviewing the comments, I should have said I would not trust a read on a binary file opened as text.\n"
] | [
6
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0004121003_file_io_python.txt |
Q:
Scraping site that requires Javascript enabled with Mechanize + BeautifulSoup (Python)
So.. i got this site I am tryign to scrape, but as I understand lack of support of
mechanize for .js, and a stuborn site that requires javascript enabled browser is
not a good mix...
I am looking for ideas, on how to do this...
URL : https://members.iracing.com/membersite/login.jsp
A:
Depending on what you need to do, you could use webkit to parse the page, which will allow you to get the final html after the javascript has been executed. You could then use any decent html parser, beautifulsoup for example, to do the rest.
A:
With JavaScript I use Chickenfoot for simple websites and Webkit for more complex.
| Scraping site that requires Javascript enabled with Mechanize + BeautifulSoup (Python) | So.. i got this site I am tryign to scrape, but as I understand lack of support of
mechanize for .js, and a stuborn site that requires javascript enabled browser is
not a good mix...
I am looking for ideas, on how to do this...
URL : https://members.iracing.com/membersite/login.jsp
| [
"Depending on what you need to do, you could use webkit to parse the page, which will allow you to get the final html after the javascript has been executed. You could then use any decent html parser, beautifulsoup for example, to do the rest.\n",
"With JavaScript I use Chickenfoot for simple websites and Webkit ... | [
0,
0
] | [] | [] | [
"javascript",
"mechanize",
"python",
"screen_scraping"
] | stackoverflow_0004114219_javascript_mechanize_python_screen_scraping.txt |
Q:
Date sensitive regression testing using python
Hey,
I am helping to set up a regression testing suite for our python web application. Many of our tests are scheduling style tests where the current date is important. For example: create a recurring event that runs every week for a month starting on Feb 1.
In order to test this, what I really want to do is override the current date so I can move back and forward in time to check the state of the app. For example, I may add an test-only page that lets me set the 'current' date which gets passed to the python back end and is used for date calculations.
In the past when I have done this, I engineered it into the application architecture from day 1. Unfortunately, I am coming in late to this project and there is no application support for this.
So here's my question, is there any way I can override the current date on a web service call? For example, can I intercept calls for the current date (monkey patching possibly?). I would rather not have to do a whole IOC thing as it would mean changing hundreds of methods.
- dave
A:
You could do something like this:
from datetime import datetime
orig_datetime_now = datetime.now
datetime.now = lambda: datetime(2010, 2, 1)
# tests here
datetime.now = orig_datetime_now
Though, it's probably a better idea (as not to screw with third party libraries, etc.) to put a helper method on your class to get the current date, and do the same monkey patching as show above.
A:
Answering my own question:
Our current plan is to test on virtual machines and change the date/time on the VMs. This is a more complete solution as it gets the database and worker threads all at once.
I'll post an update with some real world experience when we come to actual do it.
| Date sensitive regression testing using python | Hey,
I am helping to set up a regression testing suite for our python web application. Many of our tests are scheduling style tests where the current date is important. For example: create a recurring event that runs every week for a month starting on Feb 1.
In order to test this, what I really want to do is override the current date so I can move back and forward in time to check the state of the app. For example, I may add an test-only page that lets me set the 'current' date which gets passed to the python back end and is used for date calculations.
In the past when I have done this, I engineered it into the application architecture from day 1. Unfortunately, I am coming in late to this project and there is no application support for this.
So here's my question, is there any way I can override the current date on a web service call? For example, can I intercept calls for the current date (monkey patching possibly?). I would rather not have to do a whole IOC thing as it would mean changing hundreds of methods.
- dave
| [
"You could do something like this:\nfrom datetime import datetime\norig_datetime_now = datetime.now\n\ndatetime.now = lambda: datetime(2010, 2, 1)\n\n# tests here\n\ndatetime.now = orig_datetime_now\n\nThough, it's probably a better idea (as not to screw with third party libraries, etc.) to put a helper method on y... | [
1,
0
] | [] | [] | [
"automated_tests",
"date",
"python",
"regression_testing"
] | stackoverflow_0004047049_automated_tests_date_python_regression_testing.txt |
Q:
Python: what does self.control in a subclass of wx.Frame mean?
I am following the Getting started with wxPython tutorial, to this part. What is control in the following line? I have searched in the Frame class reference and googled for a while but still no clue.
self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
Just in case next time I need information like this, where should I look?
Thanks,
A:
Never mind, I found it from The Python Language Reference
To create instance variables, they can be set in a method with self.name = value
So, control is just an instance variable, no more no less.
| Python: what does self.control in a subclass of wx.Frame mean? | I am following the Getting started with wxPython tutorial, to this part. What is control in the following line? I have searched in the Frame class reference and googled for a while but still no clue.
self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE)
Just in case next time I need information like this, where should I look?
Thanks,
| [
"Never mind, I found it from The Python Language Reference\n\nTo create instance variables, they can be set in a method with self.name = value\n\nSo, control is just an instance variable, no more no less.\n"
] | [
3
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004121198_python_wxpython.txt |
Q:
How to set python IDLE to use pythonpath variable in Ubuntu 10.04
I have set a pythonpath variable in my ~/.bashrc and it works fine when using python interpreter from the command line and bpython, but IDLE is not recognizing it.
How can I configure it to load the pythonpath variable?
Thanks in advance
A:
You can upgrade Ubuntu, because it works fine on my 10.10 machine with the idle-python2.7 package and PYTHONPATH set in my ~/.profile (which shouldn't matter because bash normally loads both)
Or you can change sys.path in /usr/bin/idle* as per Setting PYTHONPATH for idle?
| How to set python IDLE to use pythonpath variable in Ubuntu 10.04 | I have set a pythonpath variable in my ~/.bashrc and it works fine when using python interpreter from the command line and bpython, but IDLE is not recognizing it.
How can I configure it to load the pythonpath variable?
Thanks in advance
| [
"\nYou can upgrade Ubuntu, because it works fine on my 10.10 machine with the idle-python2.7 package and PYTHONPATH set in my ~/.profile (which shouldn't matter because bash normally loads both)\nOr you can change sys.path in /usr/bin/idle* as per Setting PYTHONPATH for idle?\n\n"
] | [
1
] | [] | [] | [
"python",
"python_idle",
"pythonpath"
] | stackoverflow_0004096223_python_python_idle_pythonpath.txt |
Q:
Accessing all objects created from ClientFactory in Twisted?
I'm working on a basic Twisted application to help me learn how reactors work with multiple services. The basic outline of what I'd like my script to do is as follows:
My script will be both a Web Server and an IRC Client. Every time a request is made to the web server, the script should say a message on IRC.
I've got an IRC client working, and a twisted.web server working, and can have them run simultaneously in one script. The problem occurs when I try to make them interact with one another. Here's how I initiate the server/client:
import sys
from twisted.words.protocols import irc
from twisted.web import server, resource
from twisted.internet import protocol, reactor
# Define my custom IRC Client, ClientFactory, and Web Application
chan = sys.argv[1]
site = server.Site(Home())
reactor.listenTCP(8080, site)
reactor.connectTCP('irc.freenote.net', 6667, IRCBotFactory(chan))
reactor.run()
Using the code above, the two parts of my client run simultaneously without issue. When trying to make the IRC Client send messages to the server upon HTTP request, however, I realized that I don't actually have reference to an IRCBot intance, as I initiated the reactor with the IRCBotFactory and let Twisted handle initialization of the actual bot object.
Is there a way to get all child instances of a factory in Twisted, or is there another way for me to initiate the IRC Client (perhaps bypassing the Factory and simply using an IRCBot instance)?
A:
One of the Twisted FAQ entries entries discusses a problem like this one. Just remember that a Site is a factory and it should be easy to apply a similar solution to your case.
| Accessing all objects created from ClientFactory in Twisted? | I'm working on a basic Twisted application to help me learn how reactors work with multiple services. The basic outline of what I'd like my script to do is as follows:
My script will be both a Web Server and an IRC Client. Every time a request is made to the web server, the script should say a message on IRC.
I've got an IRC client working, and a twisted.web server working, and can have them run simultaneously in one script. The problem occurs when I try to make them interact with one another. Here's how I initiate the server/client:
import sys
from twisted.words.protocols import irc
from twisted.web import server, resource
from twisted.internet import protocol, reactor
# Define my custom IRC Client, ClientFactory, and Web Application
chan = sys.argv[1]
site = server.Site(Home())
reactor.listenTCP(8080, site)
reactor.connectTCP('irc.freenote.net', 6667, IRCBotFactory(chan))
reactor.run()
Using the code above, the two parts of my client run simultaneously without issue. When trying to make the IRC Client send messages to the server upon HTTP request, however, I realized that I don't actually have reference to an IRCBot intance, as I initiated the reactor with the IRCBotFactory and let Twisted handle initialization of the actual bot object.
Is there a way to get all child instances of a factory in Twisted, or is there another way for me to initiate the IRC Client (perhaps bypassing the Factory and simply using an IRCBot instance)?
| [
"One of the Twisted FAQ entries entries discusses a problem like this one. Just remember that a Site is a factory and it should be easy to apply a similar solution to your case.\n"
] | [
1
] | [] | [] | [
"events",
"python",
"reactor",
"twisted"
] | stackoverflow_0004120996_events_python_reactor_twisted.txt |
Q:
Django Sphinx Text Search
I am trying out Sphinx search in my Django project. All setup done & it works but need some clarification from someone who has actually used this setup.
In my Sphinx search while indexing, I have used 'name' as the field in my MySQL to be searchable & all other fields in sql_query to be as attributes (according to Sphinx lingo).
So when I search from my Model instance in Django, I get the search results alright but it does not have the 'name' field in the search results. I get all the other attributes.
However, I get the 'id' of the search term. Technically, I could get the 'name' by again querying MySQL but I want to avoid this. Is there anything I am not doing here?
A:
Here's a shot in the dark -
Try to get the name of your index in sphinx.conf same as the table_name you are trying to index. This is a quirk which is missed by lot of people.
| Django Sphinx Text Search | I am trying out Sphinx search in my Django project. All setup done & it works but need some clarification from someone who has actually used this setup.
In my Sphinx search while indexing, I have used 'name' as the field in my MySQL to be searchable & all other fields in sql_query to be as attributes (according to Sphinx lingo).
So when I search from my Model instance in Django, I get the search results alright but it does not have the 'name' field in the search results. I get all the other attributes.
However, I get the 'id' of the search term. Technically, I could get the 'name' by again querying MySQL but I want to avoid this. Is there anything I am not doing here?
| [
"Here's a shot in the dark - \nTry to get the name of your index in sphinx.conf same as the table_name you are trying to index. This is a quirk which is missed by lot of people.\n"
] | [
1
] | [] | [] | [
"django",
"django_sphinx",
"full_text_search",
"python",
"search"
] | stackoverflow_0003897650_django_django_sphinx_full_text_search_python_search.txt |
Q:
Version of Canvas create_text() that supports word wrap?
Is there a create_text() mode or technique that supports word wrap? I'm stuck using create_text() vs. a Label or Text widget because I'm placing text on top of an image on my Canvas.
Also, is there a Tkinter API that truncates text that doesn't fit a certain width with an ellipsis like suffix, eg. Where very, very, very long text gets converted to something like Where very, very, ....
A:
There is indeed a word wrap feature in create_text(). You'd call it like so:
canvas.create_text(x, y, width=80)
You can set the width parameter to whatever max length you want, or 0 if you want no word wrapping. See this article for all the options, arguments etc. for create_text().
I'm not sure about truncating text, but I did see this talking about a way to limit the length of input in an Entry widget...
| Version of Canvas create_text() that supports word wrap? | Is there a create_text() mode or technique that supports word wrap? I'm stuck using create_text() vs. a Label or Text widget because I'm placing text on top of an image on my Canvas.
Also, is there a Tkinter API that truncates text that doesn't fit a certain width with an ellipsis like suffix, eg. Where very, very, very long text gets converted to something like Where very, very, ....
| [
"There is indeed a word wrap feature in create_text(). You'd call it like so:\ncanvas.create_text(x, y, width=80)\n\nYou can set the width parameter to whatever max length you want, or 0 if you want no word wrapping. See this article for all the options, arguments etc. for create_text().\nI'm not sure about truncat... | [
9
] | [] | [] | [
"python",
"tkinter_canvas",
"user_interface",
"word_wrap"
] | stackoverflow_0004121362_python_tkinter_canvas_user_interface_word_wrap.txt |
Q:
pyGTK - gtk.Entry in gtk.Dialog Yields no Text
In pyGTK (2.22 - version is very important), I'm encountering the bug detailed below. I think it's a pyGTK issue, but I could be wrong and don't want to report a non-bug.
Basically, I am extracting text from a gtk.Entry() using .get_text(), and this returns an empty string even with text in the widget. Here is some relevant code (with NOOP definitions to make it runnable):
import gtk
class Item: pass
def tofile(item): pass
# Described issues begin below
class ItemAddDialog:
"A dialog used when adding a menu item"
def __init__(self):
self.dialog = gtk.Dialog(title="Adding menu item...", buttons=btns)
self.fname, self.name, self.icon, self.exe, self.cats = [gtk.Entry() for i in range(5)]
self.obs = (self.fname, self.name, self.icon, self.exe, self.cats)
self._config()
def _config(self):
_ = self.dialog.vbox
map(lambda x: _.pack_start(x, False, False, 0), self.obs)
map(lambda x: x.show(), self.obs)
map(lambda x: x[1].set_text(x[0]), zip(("Filename", "Name in Menu", "Icon", "Command", "Categories (; Delimited)"), self.obs))
def run(self):
r = self.dialog.run()
self.dialog.destroy()
print _quote(str(r))
if (int(r) == 1): i = Item(self.fname.get_text(), self.name.get_text(), self.icon.get_text(), self.exe.get_text(), self.cats.get_text())
print str(i)
tofile(i)
A:
destroy() will among other things cause the widget and its children to be unrealized, which means the entry loses its text. Always read the state of a dialog (or any other widget) before destroying it.
There are some other minor issues with your code:
For clarity, you should replace the maps with simple loops:
map(lambda x: _.pack_start(x, False, False, 0), self.obs)
for x in self.obs: _.pack_start(x, False, False)
map(lambda x: x[1].set_text(x[0]), zip(("Filename", "Name in Menu", "Icon", "Command", "Categories (; Delimited)"), self.obs))
for txt, x in zip(("Filename", "Name in Menu", "Icon", "Command", "Categories (; Delimited)"), self.obs)): x.set_text(txt)
Instead of calling show on all the children, just call show_all on the parent (the dialog in this case).
I don't think you have to cast the dialog result to an int. Also, magic numbers are bad. Define a constant, or use a predefined one.
| pyGTK - gtk.Entry in gtk.Dialog Yields no Text | In pyGTK (2.22 - version is very important), I'm encountering the bug detailed below. I think it's a pyGTK issue, but I could be wrong and don't want to report a non-bug.
Basically, I am extracting text from a gtk.Entry() using .get_text(), and this returns an empty string even with text in the widget. Here is some relevant code (with NOOP definitions to make it runnable):
import gtk
class Item: pass
def tofile(item): pass
# Described issues begin below
class ItemAddDialog:
"A dialog used when adding a menu item"
def __init__(self):
self.dialog = gtk.Dialog(title="Adding menu item...", buttons=btns)
self.fname, self.name, self.icon, self.exe, self.cats = [gtk.Entry() for i in range(5)]
self.obs = (self.fname, self.name, self.icon, self.exe, self.cats)
self._config()
def _config(self):
_ = self.dialog.vbox
map(lambda x: _.pack_start(x, False, False, 0), self.obs)
map(lambda x: x.show(), self.obs)
map(lambda x: x[1].set_text(x[0]), zip(("Filename", "Name in Menu", "Icon", "Command", "Categories (; Delimited)"), self.obs))
def run(self):
r = self.dialog.run()
self.dialog.destroy()
print _quote(str(r))
if (int(r) == 1): i = Item(self.fname.get_text(), self.name.get_text(), self.icon.get_text(), self.exe.get_text(), self.cats.get_text())
print str(i)
tofile(i)
| [
"destroy() will among other things cause the widget and its children to be unrealized, which means the entry loses its text. Always read the state of a dialog (or any other widget) before destroying it.\nThere are some other minor issues with your code:\n\nFor clarity, you should replace the maps with simple loops:... | [
3
] | [] | [] | [
"gtkentry",
"pygtk",
"python"
] | stackoverflow_0004121004_gtkentry_pygtk_python.txt |
Q:
How to run a .py (Python) file in ASP.NET?
I have a GetList.py file which consumes Web Service and saves the output in XML on the server.
How do I invoke GetList.py so it saves the output in XML on the server before displaying the XML output in .ASPX page?
A:
You can create one batch file which contains call to python file and call that batch file from you .net application.
To call batch file, you can use Process class.
For example, suppose you have test.py file containing following code :
print "hello world"
then create one batch file (file having .bat extension) which has following contents :
python C:\test.py
Assuming you are using C#, and ur batchfile is stored in (C:\test.bat) you can use following code to invoke batch file
Process.Start("C:\test.bat");
You can have more details about Process class here
A:
If your server has a Python interpreter installed, use that. (It's usually in /usr/bin/python)
If it doesn't (and it probably doesn't, since you use .NET), use IronPython. It's based on .NET and works very nicely with ASP.NET. Fair warning: if your GetList.py script uses parts of the CPython standard library that haven't been implemented in IronPython, you might have to change the script. See this article to get a basic intro to IronPython and see how it fits in with .NET.
| How to run a .py (Python) file in ASP.NET? | I have a GetList.py file which consumes Web Service and saves the output in XML on the server.
How do I invoke GetList.py so it saves the output in XML on the server before displaying the XML output in .ASPX page?
| [
"You can create one batch file which contains call to python file and call that batch file from you .net application.\nTo call batch file, you can use Process class.\nFor example, suppose you have test.py file containing following code :\nprint \"hello world\"\n\nthen create one batch file (file having .bat extensi... | [
9,
6
] | [] | [] | [
"asp.net",
"python"
] | stackoverflow_0004121993_asp.net_python.txt |
Q:
Python regex help
a = Account(unit = 2, path='/real/os/win/today/axl.xls', realname = 'st')
What I want is escape the ' to html entities, which is '
remember, the string after path can be anything, I need a generic way to do this.
The output of this string is
Account(unit = 2, path='/real/os/win/today/axl.xls', realname = 'st')
A:
re.sub(r"path=\'([^\']*)\'", "path='\1'", str)
A:
If you want to convert '/real/os/win/today/axl.xls' to '/real/os/win/today/axl.xls' you can use "'/real/os/win/today/axl.xls'".replace("'", ''') instead of using regex.
A:
What you have are non-HTML entities. If I remember it right, there are 3 such types of &... entities, e.x.-     all mean U+00A0 NO-BREAK SPACE.
  - (the type you have) is a "numeric character reference" (decimal).
  - is a "numeric character reference" (hexadecimal).
- is an entity.
You could check out Fredrick Luth's Unescape HTML script (for python2.x) & more about HTML entities here
A:
if i understood the question correctly:
>>> a = "Account(unit = 2, path='/real/os/win/today/axl.xls', realname = 'st')"
>>> re.sub("(?<=path=').*", lambda x: '''+x.group(0), a)
"Account(unit = 2, path=''/real/os/win/today/axl.xls', realname = 'st')"
A:
I prefer BeautifulSoup for all this stuff. Check out http://www.crummy.com/software/BeautifulSoup/documentation.html#Entity%20Conversion for more.
| Python regex help | a = Account(unit = 2, path='/real/os/win/today/axl.xls', realname = 'st')
What I want is escape the ' to html entities, which is '
remember, the string after path can be anything, I need a generic way to do this.
The output of this string is
Account(unit = 2, path='/real/os/win/today/axl.xls', realname = 'st')
| [
"re.sub(r\"path=\\'([^\\']*)\\'\", \"path='\\1'\", str)\n\n",
"If you want to convert '/real/os/win/today/axl.xls' to '/real/os/win/today/axl.xls' you can use \"'/real/os/win/today/axl.xls'\".replace(\"'\", ''') instead of using regex.\n",
"What you have are non-HTML entities. If I remember ... | [
0,
0,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004121240_python_regex.txt |
Q:
What type of collection of mutable objects will allow me to quickly remove items in python?
Suppose I have profiled my program, and the vast majority of runtime is spent in method 'remove' of 'list' objects. The program manipulates a collection of collections, and the collections do not need to be ordered. What would be the most straightforward way to implement these collections in python (preferably using standard python collections) so that collection.remove(item) is inexpensive both when collection is the outer collection and item is an inner collection and when collection is an inner collection and item is just an immutable object.
The problem with using sets here is that sets cannot contain mutable collections, so the inner sets would have to be frozensets, but then removing items is no longer so cheap.
The best solution I've come upon so far was suggested by someone as an answer here that apparently was deleted shortly after. They suggested using a dict. This would work, but you would have to generate arbitrary id's for each item then, so it's a bit awkward. Another alternative is to used a linked list, but that would be awkward too, since linked lists aren't part of the standard library.
A:
If you can live with equality defined as identity, you can create a hashable list subtype and use these as set members for fast access/removal:
class hlist(list):
"Hashable list"
def __hash__(self):
return id(self)
def __eq__(self, other):
return self is other
def __ne__{self, other}:
return self is not other
in1 = hlist([1,2,3])
in2 = hlist([4,5,6])
outer = set([in1, in2])
A:
They suggested using a dict. This would work, but you would have to generate arbitrary id's for each item then, so it's a bit awkward.
You delete them by instance? Using a dict approach, you can always use id() as their "arbitrary" ID?
One dict for groups with their id() as key, inner dict for invidual's id(). And another global dict with individuals with their id() as key.
It's not clear if an individual can be in multiple groups... If so, you would need to verify if the invidual is in any group before deleting it.
A:
Dictionary is the collection you want in this case because it has O(1) find and delete. There is a cost you will incur, which is generating a key for each object when you want to add/remove, but it'll be significantly faster than the O(n) approach of scanning a list. Generating a key for your objects is correct in this situation. If you have a primary key (did they come from a DB?) that will negate the hash function to a property lookup, and you'll achieve near perfect performance.
You seem to think that using a dictionary as a data structure in this case is a bad thing - it isn't at all. The purpose of a dictionary is to quickly find items in a collection. This is what you need, use it.
A:
If you are spending a lot of time remove-ing elements from a list, perhaps you should consider filtering it instead? In other words. make a large initial list and then subsequent generators consuming elements in the list.
A:
It's perhaps not exactly what you're asking for, but collections.deque might meet some of your requirements:
Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.
| What type of collection of mutable objects will allow me to quickly remove items in python? | Suppose I have profiled my program, and the vast majority of runtime is spent in method 'remove' of 'list' objects. The program manipulates a collection of collections, and the collections do not need to be ordered. What would be the most straightforward way to implement these collections in python (preferably using standard python collections) so that collection.remove(item) is inexpensive both when collection is the outer collection and item is an inner collection and when collection is an inner collection and item is just an immutable object.
The problem with using sets here is that sets cannot contain mutable collections, so the inner sets would have to be frozensets, but then removing items is no longer so cheap.
The best solution I've come upon so far was suggested by someone as an answer here that apparently was deleted shortly after. They suggested using a dict. This would work, but you would have to generate arbitrary id's for each item then, so it's a bit awkward. Another alternative is to used a linked list, but that would be awkward too, since linked lists aren't part of the standard library.
| [
"If you can live with equality defined as identity, you can create a hashable list subtype and use these as set members for fast access/removal:\nclass hlist(list):\n\"Hashable list\"\n def __hash__(self):\n return id(self)\n def __eq__(self, other):\n return self is other\n def __ne__{self, ... | [
4,
2,
2,
1,
0
] | [
"Why not have something like a master list of sets and then another set that contains the indices to the list for the set you want to keep track of? Sure it might be a little extra work, but you should be able to abstract it out into a class.\n"
] | [
-1
] | [
"linked_list",
"optimization",
"python",
"set"
] | stackoverflow_0004119698_linked_list_optimization_python_set.txt |
Q:
How to print textfield's value in Django and Python?
I'm trying to create a very simple web page with 2 textfields, 1 button and 3 labels to make it look like so:
First Name: [..........] <-- label + textfield
Last Name: [...........] <-- label + textfield
(Submit) <-- button
{Your full name is %FirstName% + %LastName% } <-- label
As you can see it's an extremely simple task. I could have easily done this in ASP.NET in 5 minutes but I am not very familiar with Django or Python, as I am just starting to learn the framework.
Thanks.
A:
zomboid's comment is correct. It looks like you need to learn more about Django. You might want to take a look at this chapter from The Django Book. That text is a bit outdated, but the fundamentals are the same.
Some general guidance: you need to point a URL (e.g., /namegrabber) to a view function. Inside that view function, you decide whether the user's doing a GET or a POST. If it's a GET, then instantiate an unbound form -- i.e., a form with no data -- and pass it to a template to be rendered. If it's a POST, then instantiate your form, populating it with request.POST. Then, take the data in your form's cleaned_data attribute and pass that to a template to be rendered.
Two other comments. First, as I mentioned, the text in The Django Book is a bit outdated. In particular, you'll need to somehow deal with Django's CSRF protection since your view will be handling POST requests, assuming you're using Django 1.2+. A nice overview of how to do that is here. Second, when you're building your form, you'll probably want to use forms.CharField for the data you're talking about.
Good luck! This is a five-minute task in Django once you're accustomed to the framework.
A:
On the python end of it, you can view these values by looking at request.POST["field_name"]. You can then pass these values to the template (different methods depending on which function you are using to call the template). Then the template will look something like
Your full name is {{ first_name }} {{ last_name }}
Let me know if you need more detail / examples.
| How to print textfield's value in Django and Python? | I'm trying to create a very simple web page with 2 textfields, 1 button and 3 labels to make it look like so:
First Name: [..........] <-- label + textfield
Last Name: [...........] <-- label + textfield
(Submit) <-- button
{Your full name is %FirstName% + %LastName% } <-- label
As you can see it's an extremely simple task. I could have easily done this in ASP.NET in 5 minutes but I am not very familiar with Django or Python, as I am just starting to learn the framework.
Thanks.
| [
"zomboid's comment is correct. It looks like you need to learn more about Django. You might want to take a look at this chapter from The Django Book. That text is a bit outdated, but the fundamentals are the same.\nSome general guidance: you need to point a URL (e.g., /namegrabber) to a view function. Inside that v... | [
2,
1
] | [] | [] | [
"django",
"python",
"textbox"
] | stackoverflow_0004121503_django_python_textbox.txt |
Q:
Not need CSRF feature in django 1.2.3
I upgrading from django 1.1.1 to django 1.2.3, I know that CSRF feature have changed. But I don't need this feature for now , How can I make my code run properly.?
A:
You can remove the corresponding middleware from the MIDDLEWARE_CLASSES constant in your settings file.
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
| Not need CSRF feature in django 1.2.3 | I upgrading from django 1.1.1 to django 1.2.3, I know that CSRF feature have changed. But I don't need this feature for now , How can I make my code run properly.?
| [
"You can remove the corresponding middleware from the MIDDLEWARE_CLASSES constant in your settings file.\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n #'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004121486_django_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.