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: Optimize PDF conversion in Django / Python I have a webapp that export reports in PDF. Everything is fine when the query returns less than 100 values. When the number of records raise above 100 the server raise a 502 Proxy Error. The report outputs fine in HTML. The process that hangs up the server is the conversion from html to PDF. I'm using xhtml2pdf (AKA pisa 3.0) to generate the PDF. The algorythm is something like this: def view1(request, **someargs): queryset = someModel.objects.get(someargs) if request.GET['pdf']: return pdfWrapper('template.html',queryset,'filename') else: return render_to_response('template.html',queryset) def pdfWrapper(template_src, context_dict, filename): ################################################ # # The code comented below is an older version # I updated the code according the comment recived # The function still works for short HTML documents # and produce the 502 for larger onese # ################################################ ##import cStringIO as StringIO import ho.pisa as pisa from django.template.loader import get_template from django.template import Context from django.http import HttpResponse ##from cgi import escape template = get_template(template_src) context = Context(context_dict) html = template.render(context) response = HttpResponse() response['Content-Type'] ='application/pdf' response['Content-Disposition']='attachment; filename=%s.pdf'%(filename) pisa.CreatePDF( src=html, dest=response, show_error_as_pdf=True) return response ##result = StringIO.StringIO() ##pdf = pisa.pisaDocument( ## StringIO.StringIO(html.encode("ISO-8859-1")), ## result) ##if not pdf.err: ## response = HttpResponse( ## result.getvalue(), ## mimetype='application/pdf') ## response['Content-Disposition']='attachement; filename=%s.pdf'%(filename) ## return response ##return HttpResponse('Hubo un error<pre>%s</pre>' % escape(html)) I've put some thought about creating a buffer so the server can free some memory but I didn't find anything yet. Anyone could help? please? A: I can't tell you exactly what causes your problem - it could be caused by buffering problems in StringIO. However, you are wrong if you assume that this code would actually stream the generated PDF data: StringIO.getvalue() returns the content of the string buffer at the time this method is called, not an output stream (see http://docs.python.org/library/stringio.html#StringIO.StringIO.getvalue). If you want to stream the output, you can treat the HttpResponse instance as a file-like object (see http://docs.djangoproject.com/en/1.2/ref/request-response/#usage). Secondly, I don't see any reason to make use of StringIO here. According to the documentation of Pisa I found (which calls this function CreatePDF, by the way) the source can be a string or a unicode object. Personally, I would try the following: Create the HTML as unicode string Create and configure the HttpResponse object Call the PDF generator with the string as input and the response as output In outline, this could look like this: html = template.render(context) response = HttpResponse() response['Content-Type'] ='application/pdf' response['Content-Disposition']='attachment; filename=%s.pdf'%(filename) pisa.CreatePDF( src=html, dest=response, show_error_as_pdf=True) #response.flush() return response However, I did not try if this actually works. (I did this sort of PDF streaming only in Java, so far.) Update: I just looked at the implementation of HttpResponse. It implements the file interface by collecting the chunks of strings written to it in a list. Calling response.flush() is pointless, because it does nothing. Also, you can set response parameters like Content-Type even after the response has been accessed as file-object. Your original problem may also be related to the fact you never closed the StringIO objects. The underlying buffer of a StringIO object is not released before close() is called.
Optimize PDF conversion in Django / Python
I have a webapp that export reports in PDF. Everything is fine when the query returns less than 100 values. When the number of records raise above 100 the server raise a 502 Proxy Error. The report outputs fine in HTML. The process that hangs up the server is the conversion from html to PDF. I'm using xhtml2pdf (AKA pisa 3.0) to generate the PDF. The algorythm is something like this: def view1(request, **someargs): queryset = someModel.objects.get(someargs) if request.GET['pdf']: return pdfWrapper('template.html',queryset,'filename') else: return render_to_response('template.html',queryset) def pdfWrapper(template_src, context_dict, filename): ################################################ # # The code comented below is an older version # I updated the code according the comment recived # The function still works for short HTML documents # and produce the 502 for larger onese # ################################################ ##import cStringIO as StringIO import ho.pisa as pisa from django.template.loader import get_template from django.template import Context from django.http import HttpResponse ##from cgi import escape template = get_template(template_src) context = Context(context_dict) html = template.render(context) response = HttpResponse() response['Content-Type'] ='application/pdf' response['Content-Disposition']='attachment; filename=%s.pdf'%(filename) pisa.CreatePDF( src=html, dest=response, show_error_as_pdf=True) return response ##result = StringIO.StringIO() ##pdf = pisa.pisaDocument( ## StringIO.StringIO(html.encode("ISO-8859-1")), ## result) ##if not pdf.err: ## response = HttpResponse( ## result.getvalue(), ## mimetype='application/pdf') ## response['Content-Disposition']='attachement; filename=%s.pdf'%(filename) ## return response ##return HttpResponse('Hubo un error<pre>%s</pre>' % escape(html)) I've put some thought about creating a buffer so the server can free some memory but I didn't find anything yet. Anyone could help? please?
[ "I can't tell you exactly what causes your problem - it could be caused by buffering problems in StringIO. \nHowever, you are wrong if you assume that this code would actually stream the generated PDF data: StringIO.getvalue() returns the content of the string buffer at the time this method is called, not an output...
[ 3 ]
[]
[]
[ "django", "pdf", "pisa", "python" ]
stackoverflow_0003397965_django_pdf_pisa_python.txt
Q: How should I write very long lines of code? if i have a very long line of a code, is it possible to continue it on the next line for example: url='http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|' + '100,000|1,000,000&chxp=1,0&chxr=0,0,' + max(freq) + '300|1,0,3&chxs=0,676767,13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1,0&chs=640x465&cht=bvs&chco=A2C180&chds=0,300&chd=t:' A: I would write it like this url=('http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|' '100,000|1,000,000&chxp=1,0&chxr=0,0,%(max_freq)s300|1,0,3&chxs=0,676767' ',13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1,0&chs=640x465' '&cht=bvs&chco=A2C180&chds=0,300&chd=t:'%{'max_freq': max(freq)}) Note that the + are not required to join the strings. It is better this way because the strings are joined at compile time instead of runtime. I've also embedded %(max_freq)s in your string, this is substituted in from the dict at the end Also check out urllib.urlencode() if you want to make your url handling simpler A: Where to look for help in future Most syntax problems like this are dealt with in PEP 8. For the answer to this question, you can refer to the section "Code Layout". Preferred way : Use (), {} & [] From PEP-8: The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression... This means your example would like like this: url= ('http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|' + '100,000|1,000,000&chxp=1,0&chxr=0,0,' + max(freq) + '300|1,0,3&...chco=A2C180&chds=0,300&chd=t:') The alternate way: Use \ From PEP-8: ...but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. url = 'http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|' + \ '100,000|1,000,000&chxp=1,0&chxr=0,0,' + \ max(freq) + \ '300|1,0,3&...chco=A2C180&chds=0,300&chd=t:' Avoiding concatenation String formatting In this case, we only have a single thing that we would like to be changed in the URL: max(freq). In order to efficiently insert this into a new string, we can use the format method with numerical or named arguments: url = "http://...{0}.../".format(max(freq)) url = "http://...{max_freq}.../".format(max_freq=max(freq)) A: Python combines two strings literal together, so >>> s = "abc" "def" >>> s 'abcdef' but that wouldn't work if they are on two lines because Python doesn't know that the next line is part of the command. To solve that you can use backslash or brackets. >>> s = ("hello, world" "!") >>> s 'hello, world!' and you wouldn't need + to attach the strings together. You will still need it for adding nonliterals like max(freq), as explained in String Literal Concatenation. This is marginally more efficient, but more importantly clearer and enables commenting parts of a string as shown in the Python documentation linked. A: Yes, use a backslash \, like so: url='http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|' + \ '100,000|1,000,000&chxp=1,0&chxr=0,0,' + \ max(freq) + '300|1,0,3&chxs=0,676767,13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1,0&chs=640x465&cht=bvs&chco=A2C180&chds=0,300&chd=t:' Or you can wrap your expression with parentheses (): url=('http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|' + '100,000|1,000,000&chxp=1,0&chxr=0,0,' + max(freq) + '300|1,0,3&chxs=0,676767,13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1,0&chs=640x465&cht=bvs&chco=A2C180&chds=0,300&chd=t:')
How should I write very long lines of code?
if i have a very long line of a code, is it possible to continue it on the next line for example: url='http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|' + '100,000|1,000,000&chxp=1,0&chxr=0,0,' + max(freq) + '300|1,0,3&chxs=0,676767,13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1,0&chs=640x465&cht=bvs&chco=A2C180&chds=0,300&chd=t:'
[ "I would write it like this\nurl=('http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|'\n '100,000|1,000,000&chxp=1,0&chxr=0,0,%(max_freq)s300|1,0,3&chxs=0,676767'\n ',13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1,0&chs=640x465'\n '&cht=bvs&chco=A2C180&chds=0,300&chd=t:'%{'max...
[ 21, 17, 2, 1 ]
[]
[]
[ "pep8", "python" ]
stackoverflow_0003401468_pep8_python.txt
Q: wrapping boost::ublas with swig I am trying to pass data around the numpy and boost::ublas layers. I have written an ultra thin wrapper because swig cannot parse ublas' header correctly. The code is shown below #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/lexical_cast.hpp> #include <algorithm> #include <sstream> #include <string> using std::copy; using namespace boost; typedef boost::numeric::ublas::matrix<double> dm; typedef boost::numeric::ublas::vector<double> dv; class dvector : public dv{ public: dvector(const int rhs):dv(rhs){;}; dvector(); dvector(const int size, double* ptr):dv(size){ copy(ptr, ptr+sizeof(double)*size, &(dv::data()[0])); } ~dvector(){} }; with the SWIG interface that looks something like %apply(int DIM1, double* INPLACE_ARRAY1) {(const int size, double* ptr)} class dvector{ public: dvector(const int rhs); dvector(); dvector(const int size, double* ptr); %newobject toString; char* toString(); ~dvector(); }; I have compiled them successfully via gcc 4.3 and vc++9.0. However when I simply run a = dvector(array([1.,2.,3.])) it gives me a segfault. This is the first time I use swigh with numpy and not have fully understanding between the data conversion and memory buffer passing. Does anyone see something obvious I have missed? I have tried to trace through with a debugger but it crashed within the assmeblys of python.exe. I have no clue if this is a swig problem or of my simple wrapper. Anything is appreciated. A: You may be interested in looking at the pyublas module. It does the conversion between numpy arrays and ublas data types seamlessly and without copying. A: You may want to replace copy(ptr, ptr+sizeof(double)*size, &(dv::data()[0])); by copy(ptr, ptr+size, &(dv::data()[0])); Remember that in C/C++ adding or subtracting from a pointer moves it by a multiple of the size of the datatype it points to. Best,
wrapping boost::ublas with swig
I am trying to pass data around the numpy and boost::ublas layers. I have written an ultra thin wrapper because swig cannot parse ublas' header correctly. The code is shown below #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/lexical_cast.hpp> #include <algorithm> #include <sstream> #include <string> using std::copy; using namespace boost; typedef boost::numeric::ublas::matrix<double> dm; typedef boost::numeric::ublas::vector<double> dv; class dvector : public dv{ public: dvector(const int rhs):dv(rhs){;}; dvector(); dvector(const int size, double* ptr):dv(size){ copy(ptr, ptr+sizeof(double)*size, &(dv::data()[0])); } ~dvector(){} }; with the SWIG interface that looks something like %apply(int DIM1, double* INPLACE_ARRAY1) {(const int size, double* ptr)} class dvector{ public: dvector(const int rhs); dvector(); dvector(const int size, double* ptr); %newobject toString; char* toString(); ~dvector(); }; I have compiled them successfully via gcc 4.3 and vc++9.0. However when I simply run a = dvector(array([1.,2.,3.])) it gives me a segfault. This is the first time I use swigh with numpy and not have fully understanding between the data conversion and memory buffer passing. Does anyone see something obvious I have missed? I have tried to trace through with a debugger but it crashed within the assmeblys of python.exe. I have no clue if this is a swig problem or of my simple wrapper. Anything is appreciated.
[ "You may be interested in looking at the pyublas module. It does the conversion between numpy arrays and ublas data types seamlessly and without copying. \n", "You may want to replace \ncopy(ptr, ptr+sizeof(double)*size, &(dv::data()[0])); \nby \ncopy(ptr, ptr+size, &(dv::data()[0])); \nRemember that in C/C++...
[ 3, 1 ]
[]
[]
[ "boost", "c++", "python", "swig" ]
stackoverflow_0002755352_boost_c++_python_swig.txt
Q: Decorating a method In my Python app, I'm using events to communicate between different plugins. Now, instead of registering the methods to the events manually, I thought I might use decorators to do that for me. I would like to have it look like this: @events.listento('event.name') def myClassMethod(self, event): ... I have first tried to do it like this: def listento(to): def listen_(func): myEventManager.listen(to, func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return func return listen_ When I callmyEventManger.listen('event', self.method)from within the instance, everything is running fine. However, if I use the decorator approach, theselfargument is never passed. The other approach that I have tried, after searching for a solution on the Internet, is to use a class as a decorator: class listen(object): def __init__(self, method): myEventManager.listen('frontend.route.register', self) self._method = method self._name = method.__name__ self._self = None def __get__(self, instance, owner): self._self = instance return self def __call__(self, *args, **kwargs): return self._method(self._self, *args, **kwargs) The problem with this approach is that I don't really understand the concept of__get__, and that I don't know how I'd incorporate the parameters. Just for testing I have tried using a fixed event to listen to, but with this approach, nothing happens. When I add print statements, I can see that__init__is called. If I add an additional, "old style" event registration, both__get__and__call__get executed, and the event works, despite the new decorator. What would be the best way to achieve what I'm looking for, or am I just missing some important concept with decorators? A: The decorator approach isn't working because the decorator is being called when the class is constructed, not when the instance is constructed. When you say class Foo(object): @some_decorator def bar(self, *args, **kwargs): # etc etc then some_decorator will be called when the class Foo is constructed, and it will be passed an unbound method, not the bound method of an instance. That's why self isn't getting passed. The second method, on the other hand, could work as long as you only ever create one object of each class you use the decorator on, and if you're a bit clever. If you define listen as above and then define class Foo(object): def __init__(self, *args, **kwargs): self.some_method = self.some_method # SEE BELOW FOR EXPLANATION # etc etc @listen def some_method(self, *args, **kwargs): # etc etc Then listen.__get__ would be called when someone tried to call f.some_method directly for some f...but the whole point of your scheme is that no-one's doing that! The event call back mechanism is calling the listen instance directly 'cause that's what it gets passed and the listen instance is calling the unbound method it squirrelled away when it was created. listen.__get__ won't ever get called and the _self parameter is never getting set properly...unless you explicitly access self.some_method yourself, as I did in the __init__ method above. Then listen.__get__ will be called upon instance creation and _self will be set properly. Problem is (a) this is a horrible, horrible hack and (b) if you try to create two instances of Foo then the second one will overwrite the _self set by the first, because there's still only one listen object being created, and that's associated to the class, not the instance. If you only ever use one Foo instance then you're fine, but if you have to have the event trigger two different Foo's then you'll just have to use your "old style" event registration. The TL,DR version: decorating a method decorates the unbound method of the class, whereas you want your event manager to get passed the bound method of an instance. A: Part of your code is: def wrapper(*args, **kwargs): return func(*args, **kwargs) return func which defines wrapper then completely ignores it and returns func instead. Hard to say whether this is a real problem in your real code because obviously you're not posting that (as proven by typoes such as myEventManagre, myEvnetManager, &c), but if that's what you're doing in your actual code it is obviously part of your problem.
Decorating a method
In my Python app, I'm using events to communicate between different plugins. Now, instead of registering the methods to the events manually, I thought I might use decorators to do that for me. I would like to have it look like this: @events.listento('event.name') def myClassMethod(self, event): ... I have first tried to do it like this: def listento(to): def listen_(func): myEventManager.listen(to, func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return func return listen_ When I callmyEventManger.listen('event', self.method)from within the instance, everything is running fine. However, if I use the decorator approach, theselfargument is never passed. The other approach that I have tried, after searching for a solution on the Internet, is to use a class as a decorator: class listen(object): def __init__(self, method): myEventManager.listen('frontend.route.register', self) self._method = method self._name = method.__name__ self._self = None def __get__(self, instance, owner): self._self = instance return self def __call__(self, *args, **kwargs): return self._method(self._self, *args, **kwargs) The problem with this approach is that I don't really understand the concept of__get__, and that I don't know how I'd incorporate the parameters. Just for testing I have tried using a fixed event to listen to, but with this approach, nothing happens. When I add print statements, I can see that__init__is called. If I add an additional, "old style" event registration, both__get__and__call__get executed, and the event works, despite the new decorator. What would be the best way to achieve what I'm looking for, or am I just missing some important concept with decorators?
[ "The decorator approach isn't working because the decorator is being called when the class is constructed, not when the instance is constructed. When you say\nclass Foo(object):\n @some_decorator\n def bar(self, *args, **kwargs):\n # etc etc\n\nthen some_decorator will be called when the class Foo is construct...
[ 4, 3 ]
[]
[]
[ "decorator", "methods", "python" ]
stackoverflow_0003401421_decorator_methods_python.txt
Q: python c extension for standard deviation I'm writing a c extension to calculate he standard deviation. Performance is important because it will be performed over large data sets. I'm having a hard time figuring out how to get the value of pyobject once I get the item from a list. This is my first time writing a c extension for python and any help is appreciated. Apparently I don't know how to use the code sample button correctly :( This is what I have so far: #include <Python.h> static PyObject* func(PyObject *self, PyObject *args) { PyObject *list, *item; Py_ssize_t i, len; if (!PyArg_UnpackTuple(args, "func", 1, 1, &list)){ return NULL; } printf("hello world\n"); Py_INCREF(list); len = PyList_GET_SIZE(list); for (i=0;i<len;i++){ item = PyList_GET_ITEM(list, i); PyObject_Print(item,stdout,0); } return list; } static char func_doc[] = "This function calculates standard deviation."; static PyMethodDef std_methods[] = { {"func", func, METH_VARARGS, func_doc}, {NULL, NULL} }; PyMODINIT_FUNC initstd(void) { Py_InitModule3("std", std_methods, "This is a sample docstring."); } A: You may be reinventing the wheel. There are several scientific computing libraries for Python, such as SciPy and Numpy, which are mostly wrappers around C libraries, that implement functions such as standard deviation. A: Once you have item, you can get its float value with PyNumber_Float: PyObject* floatitem = PyNumber_Float(item); Now you need to check and exit on error (if(!floatitem) return 0 -- or a goto to a location where you decref anything you may have incref'd in the previous part of your code, e.g. in your case list). If no error, PyFloat_AsDouble gives you the required double value for use in the rest of your C-coded loop: double ditem = PyFloat_AsDouble(floatitem); after which you can decref floatitem and go your merry way. Don't worry overmuch about conversion overhead in PyNumber_Float -- there won't be any if you're passed a list of floats in the first place;-). If you do still worry (would rather give an error if somebody does pass a non-float requiring conversion) you can use PyFloat_Check if you insist (but I'd suggest at least special-casing int and long items unless you want truly perplexed and unhappy users;-). In a similar vein, I'd also strongly recommend studying and using PySequence_Fast and friends, rather than astonishing users by specifically requiring lists rather than other types of sequences!-). A: Just to mention that there is almost certainly a better way than writing a C extension. First option is to use NumPy. In the comment you have on the other answer you mention that it is expensive to convert the list to an array. This may be true if the standard deviation calculation is the only bit you are doing with the data which is highly unlikely. Barring that, I would go for Cython. Here is a comparison of Cython and NumPy. Cython underperforms NumPy in this case, but more importantly the code implemented for csum can trivially be changed to compute the standard deviation. A: Have you considered using cython to write your extension. It is perfect for this type of thing A: This method will be limited by the number of items in the list. Another design would keep a running total and let you add points until you overflowed the double. A: If you want simple statistics over large datasets, you can randomly sample a subset of the data and take the average and standard deviation of that. That will have a "standard error" of approximation, and the more samples you take, the smaller that will be. If you don't need high precision of the statistics, you don't need to read all the data.
python c extension for standard deviation
I'm writing a c extension to calculate he standard deviation. Performance is important because it will be performed over large data sets. I'm having a hard time figuring out how to get the value of pyobject once I get the item from a list. This is my first time writing a c extension for python and any help is appreciated. Apparently I don't know how to use the code sample button correctly :( This is what I have so far: #include <Python.h> static PyObject* func(PyObject *self, PyObject *args) { PyObject *list, *item; Py_ssize_t i, len; if (!PyArg_UnpackTuple(args, "func", 1, 1, &list)){ return NULL; } printf("hello world\n"); Py_INCREF(list); len = PyList_GET_SIZE(list); for (i=0;i<len;i++){ item = PyList_GET_ITEM(list, i); PyObject_Print(item,stdout,0); } return list; } static char func_doc[] = "This function calculates standard deviation."; static PyMethodDef std_methods[] = { {"func", func, METH_VARARGS, func_doc}, {NULL, NULL} }; PyMODINIT_FUNC initstd(void) { Py_InitModule3("std", std_methods, "This is a sample docstring."); }
[ "You may be reinventing the wheel. There are several scientific computing libraries for Python, such as SciPy and Numpy, which are mostly wrappers around C libraries, that implement functions such as standard deviation.\n", "Once you have item, you can get its float value with PyNumber_Float:\nPyObject* floatite...
[ 4, 1, 1, 1, 0, 0 ]
[]
[]
[ "c", "performance", "python", "standard_deviation" ]
stackoverflow_0003401521_c_performance_python_standard_deviation.txt
Q: need help with splitting a string in python I am trying to tokenize a string using the pattern as below. >>> splitter = re.compile(r'((\w*)(\d*)\-\s?(\w*)(\d*)|(?x)\$?\d+(\.\d+)?(\,\d+)?|([A-Z]\.)+|(Mr)\.|(Sen)\.|(Miss)\.|.$|\w+|[^\w\s])') >>> splitter.split("Hello! Hi, I am debating this predicament called life. Can you help me?") I get the following output. Could someone point out what I'd need to correct please? I'm confused about the whole bunch of "None"'s. Also if there is a better way to tokenize a string I'd really appreciate the additional help. ['', 'Hello', None, None, None, None, None, None, None, None, None, None, '', '!', None, None, None, None, None, None, None, None, None, None, ' ', 'Hi', None,None, None, None, None, None, None, None, None, None, '', ',', None, None, None, None, None, None, None, None, None, None, ' ', 'I', None, None, None, None, None, None, None, None, None, None, ' ', 'am', None, None, None, None, None, None,None, None, None, None, ' ', 'debating', None, None, None, None, None, None, None, None, None, None, ' ', 'this', None, None, None, None, None, None, None, None, None, None, ' ', 'predicament', None, None, None, None, None, None, None, None, None, None, ' ', 'called', None, None, None, None, None, None, None, None, None, None, ' ', 'life', None, None, None, None, None, None, None, None, None, None, '', '.', None, None, None, None, None, None, None, None, None, None, ' ', 'Can', None, None, None, None, None, None, None, None, None, None, ' ', 'you', None, None, None, None, None, None, None, None, None, None, ' ', 'help', None, None,None, None, None, None, None, None, None, None, ' ', 'me', None, None, None, None, None, None, None, None, None, None, '', '?', None, None, None, None, None, None, None, None, None, None, ''] The output that I'd like is:- ['Hello', '!', 'Hi', ',', 'I', 'am', 'debating', 'this', 'predicament', 'called', 'life', '.', 'Can', 'you', 'help', 'me', '?'] Thank you. A: re.split rapidly runs out of puff when used as a tokeniser. Preferable is findall (or match in a loop) with a pattern of alternatives this|that|another|more >>> s = "Hello! Hi, I am debating this predicament called life. Can you help me?" >>> import re >>> re.findall(r"\w+|\S", s) ['Hello', '!', 'Hi', ',', 'I', 'am', 'debating', 'this', 'predicament', 'called', 'life', '.', 'Can', 'you', 'help', 'me', '?'] >>> This defines tokens as either one or more "word" characters, or a single character that's not whitespace. You may prefer [A-Za-z] or [A-Za-z0-9] or something else instead of \w (which allows underscores). You may even want something like r"[A-Za-z]+|[0-9]+|\S" If things like Sen., Mr. and Miss (what happened to Mrs and Ms?) are significant to you, your regex should not list them out, it should just define a token that ends in ., and you should have a dictionary or set of probable abbreviations. Splitting text into sentences is complicated. You may like to look at the nltk package instead of trying to reinvent the wheel. Update: if you need/want to distinguish between the types of tokens, you can get an index or a name like this without a (possibly long) chain of if/elif/elif/.../else: >>> s = "Hello! Hi, I we 0 1 987?" >>> pattern = r"([A-Za-z]+)|([0-9]+)|(\S)" >>> list((m.lastindex, m.group()) for m in re.finditer(pattern, s)) [(1, 'Hello'), (3, '!'), (1, 'Hi'), (3, ','), (1, 'I'), (1, 'we'), (2, '0'), (2, '1'), (2, '987'), (3, '?')] >>> pattern = r"(?P<word>[A-Za-z]+)|(?P<number>[0-9]+)|(?P<other>\S)" >>> list((m.lastgroup, m.group()) for m in re.finditer(pattern, s)) [('word', 'Hello'), ('other', '!'), ('word', 'Hi'), ('other', ','), ('word', 'I'), ('word', 'we'), ('number', '0'), ('number', '1'), ('number', '987'), ('other' , '?')] >>> A: I recommend NLTK's tokenizers. Then you don't need to worry about tedious regular expressions yourself: >>> import nltk >>> nltk.word_tokenize("Hello! Hi, I am debating this predicament called life. Can you help me?") ['Hello', '!', 'Hi', ',', 'I', 'am', 'debating', 'this', 'predicament', 'called', 'life.', 'Can', 'you', 'help', 'me', '?'] A: Could be missing something but I beleive something like the following would work: s = "Hello! Hi, I am debating this predicament called life. Can you help me?" s.split(" ") This is assuming you want spaces. You should get something along the lines of: ['Hello!', 'Hi,', 'I', 'am', 'debating', 'this', 'predicament', 'called', 'life.', 'Can', 'you', 'help', 'me?'] With this, if you needed a specific piece, you could probably loop though it to get what you need. Hopefully this helps.... A: The reason you're getting all of those None's is because you have lots of parenthesized groups in your regular expression separated by |'s. Every time your regular expression finds a match, it's only matching one of the alternatives given by the |'s. The parenthesized groups in the other, unused alternatives get set to None. And re.split by definition reports the values of all parenthesized groups every time it gets a match, hence lots of None's in your result. You could filter those out pretty easily (e.g. tokens = [t for t in tokens if t] or something similar) but I think split isn't really the tool you want for tokenizing. split is meant for just throwing away whitespace. If you want really want to use regular expressions to tokenize something, here's a toy example of another method (I'm not going to even try to unpack that monster r.e. you're using...use the re.VERBOSE option for the love of Ned...but hopefully this toy example will give you the idea): tokenpattern = re.compile(r""" (?P<words>\w+) # Things with just letters and underscores |(?P<numbers>\d+) # Things with just digits |(?P<other>.+?) # Anything else """, re.VERBOSE) The (?P<something>... business lets you identify the type of token you're looking for by name in the code below: for match in tokenpattern.finditer("99 bottles of beer"): if match.group('words'): # This token is a word word = match.group('words') #... elif match.group('numbers'): number = int(match.group('numbers')): else: other = match.group('other'): Note that this is still a r.e. using a bunch of parenthesized groups separated by |'s, so the same thing is going to happen as in your code: for each match, one group will be defined and the others will be set to None. This method checks for that explicitly. A: Perhaps he didn't mean it as such, but John Machin's comment "str.split is NOT a place to get started" (as part of the exchange after Frank V's answer) came as a bit of a challenge. So ... the_string = "Hello! Hi, I am debating this predicament called life. Can you help me?" tokens = the_string.split() punctuation = ['!', ',', '.', '?'] output_list = [] for token in tokens: if token[-1] in punctuation: output_list.append(token[:-1]) output_list.append(token[-1]) else: output_list.append(token) print output_list This seems to provide the requested output. Granted, John's answer is simpler in terms of number of lines of code. However, I have a couple points to make supporting this sort of solution. I don't completely agree with Jamie Zawinski's 'Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.' (Neither did he from what I've read.) My point in quoting this is that regular expressions can be a pain to get working if you're not accustomed to them. Also, while it won't normally be an issue, the performance of the above solution was consistently better than the regex solution, when measured with timeit. The above solution (with the print statement removed) came in at about 8.9 seconds; John's regular expression solution came in at about 11.8 seconds. This involved 10 tries each of 1 million iterations on a quad core dual processor system running at 2.4 GHz.
need help with splitting a string in python
I am trying to tokenize a string using the pattern as below. >>> splitter = re.compile(r'((\w*)(\d*)\-\s?(\w*)(\d*)|(?x)\$?\d+(\.\d+)?(\,\d+)?|([A-Z]\.)+|(Mr)\.|(Sen)\.|(Miss)\.|.$|\w+|[^\w\s])') >>> splitter.split("Hello! Hi, I am debating this predicament called life. Can you help me?") I get the following output. Could someone point out what I'd need to correct please? I'm confused about the whole bunch of "None"'s. Also if there is a better way to tokenize a string I'd really appreciate the additional help. ['', 'Hello', None, None, None, None, None, None, None, None, None, None, '', '!', None, None, None, None, None, None, None, None, None, None, ' ', 'Hi', None,None, None, None, None, None, None, None, None, None, '', ',', None, None, None, None, None, None, None, None, None, None, ' ', 'I', None, None, None, None, None, None, None, None, None, None, ' ', 'am', None, None, None, None, None, None,None, None, None, None, ' ', 'debating', None, None, None, None, None, None, None, None, None, None, ' ', 'this', None, None, None, None, None, None, None, None, None, None, ' ', 'predicament', None, None, None, None, None, None, None, None, None, None, ' ', 'called', None, None, None, None, None, None, None, None, None, None, ' ', 'life', None, None, None, None, None, None, None, None, None, None, '', '.', None, None, None, None, None, None, None, None, None, None, ' ', 'Can', None, None, None, None, None, None, None, None, None, None, ' ', 'you', None, None, None, None, None, None, None, None, None, None, ' ', 'help', None, None,None, None, None, None, None, None, None, None, ' ', 'me', None, None, None, None, None, None, None, None, None, None, '', '?', None, None, None, None, None, None, None, None, None, None, ''] The output that I'd like is:- ['Hello', '!', 'Hi', ',', 'I', 'am', 'debating', 'this', 'predicament', 'called', 'life', '.', 'Can', 'you', 'help', 'me', '?'] Thank you.
[ "re.split rapidly runs out of puff when used as a tokeniser. Preferable is findall (or match in a loop) with a pattern of alternatives this|that|another|more\n>>> s = \"Hello! Hi, I am debating this predicament called life. Can you help me?\"\n>>> import re\n>>> re.findall(r\"\\w+|\\S\", s)\n['Hello', '!', 'Hi', ',...
[ 4, 4, 2, 1, 0 ]
[]
[]
[ "python", "regex", "string_split" ]
stackoverflow_0003392947_python_regex_string_split.txt
Q: having to run multiple instances of a web service for ruby/python seems like a hack to me Is it just me or is having to run multiple instances of a web server to scale a hack? Am I wrong in this? Clarification I am referring to how I read people run multiple instances of a web service on a single server. I am not talking about a cluster of servers. A: Not really, people were running multiple frontends across a cluster of servers before multicore cpus became widespread So there has been all the infrastructure for supporting sessions properly across multiple frontends for quite some time before it became really advantageous to run a bunch of threads on one machine. Infact using asynchronous style frontends gives better performance on the same hardware than a multithreaded approach, so I would say that not running multiple instances in favour of a multithreaded monster is a hack A: Since we are now moving towards more cores, rather than faster processors - in order to scale more and more, you will need to be running more instances. So yes, I reckon you are wrong. This does not by any means condone brain-dead programming with the excuse that you can just scale it horizontally, that just seems retarded. A: With no details, it is very difficult to see what you are getting at. That being said, it is quite possible that you are simply not using the right approach for your problem. Sometimes multiple separate instances are better. Sometimes, your Python services are actually better deployed behind a single Apache instance (using mod_wsgi) which may elect to use more than a single process. I don't know about Ruby to opinionate there. In short, if you want to make your service scalable then the way to do so depends heavily on additional details. Is it scaling up or scaling out? What is the operating system and available or possibly installable server software? Is the service itself easily parallelized and how much is it database dependent? How is the database deployed? A: Even if Ruby/Python interpreters were perfect, and could utilize all avail CPU with single process, you would still reach maximal capability of single server sooner or later and have to scale across several machines, going back to running several instances of your app. A: I would hesitate to say that the issue is a "hack". Or indeed that threaded solutions are necessarily superior. The situation is a result of design decisions used in the interpreters of languages like Ruby and Python. I work with Ruby, so the details may be different for other languages. BUT ... essentially, Ruby uses a Global Interpreter Lock to prevent threading issues: http://en.wikipedia.org/wiki/Global_Interpreter_Lock The side-effect of this is that to achieve concurrency with frameworks like Rails, rather than relying on multiple threads within the VM, we use multiple processes, each with its own interpreter and instance of your framework and application code Each instance of the app handles a single request at a time. To achieve concurrency we have to spin up multiple instances. In the olden days (2-3 years ago) we would run multiple mongrel (or similar) instances behind a proxy (generally apache). Passenger changed some of this because it is smart enough to manage the processes itself, rather than requiring manual setup. You tell Passenger how many processes it can use and off it goes. The whole structure is actually not as bad as the thread-orthodoxy would have you believe. For a start, it's pretty easy to make this type of architecture work in a multicore environment. Any modern database is designed to handle highly concurrent loads, so having multiple processes has very little if any effect at that level. If you use a language like JRuby you can deploy into a threaded app server like Tomcat and have a deployment that looks much more "java-like". However, this is not as big a win as you might think, because now your application needs to be much more thread-aware and you can see side effects and strangeness from threading issues. A: Your assumption that Tomcat's and IIS's single process per server is superior is flawed. The choice of a multi-threaded server and a multi-process server depends on a lot of variables. One main thing is the underlying operating system. Unix systems have always had great support for multi-processing because of the copy-on-write nature of the fork system call. This makes multi-processes a really attractive option because web-serving is usually very shared-nothing and you don't have to worry about locking. Windows on the other hand had much heavier processes and lighter threads so programs like IIS would gravitate to a multi-threading model. As for the question to wether it's a hack to run multiple servers really depends on your perspective. If you look at Apache, it comes with a variety of pluggable engines to choose from. The MPM-prefork one is the default because it allows the programmer to easily use non-thread-safe C/Perl/database libraries without having to throw locks and semaphores all over the place. To some that might be a hack to work around poorly implemented libraries. To me it's a brilliant way of leaving it to the OS to handle the problems and letting me get back to work. Also a multi-process model comes with a few features that would be very difficult to implement in a multi-threaded server. Because they are just processes, zero-downtime rolling-updates are trivial. You can do it with a bash script. It also has it's short-comings. In a single-server model setting up a singleton that holds some global state is trivial, while on a multi-process model you have to serialize that state to a database or Redis server. (Of course if your single-process server outgrows a single server you'll have to do that anyway.) Is it a hack? Yes and no. Both original implementations (MRI, and CPython) have Global Interpreter Locks that will prevent a multi-core server from operating at it's 100% potential. On the other hand multi-process has it's advantages (especially on the Unix-side of the fence). There's also nothing inherent in the languages themselves that makes them require a GIL, so you can run your application with Jython, JRuby, IronPython or IronRuby if you really want to share state inside a single process.
having to run multiple instances of a web service for ruby/python seems like a hack to me
Is it just me or is having to run multiple instances of a web server to scale a hack? Am I wrong in this? Clarification I am referring to how I read people run multiple instances of a web service on a single server. I am not talking about a cluster of servers.
[ "Not really, people were running multiple frontends across a cluster of servers before multicore cpus became widespread\nSo there has been all the infrastructure for supporting sessions properly across multiple frontends for quite some time before it became really advantageous to run a bunch of threads on one machi...
[ 4, 4, 1, 1, 1, 0 ]
[]
[]
[ "python", "ruby_on_rails" ]
stackoverflow_0003399367_python_ruby_on_rails.txt
Q: best way to download large files with python Which library/module is the best to use for downloading large 500mb+ files in terms of speed, memory, cpu? I was also contemplating using pycurl. A: At sizes of 500MB+ one has to worry about data integrity, and HTTP is not designed with data integrity in mind. I'd rather use python bindings for rsync (if they exist) or even bittorrent, which was initially implemented in python. Both rsync and bittorrent address the data integrity issue.
best way to download large files with python
Which library/module is the best to use for downloading large 500mb+ files in terms of speed, memory, cpu? I was also contemplating using pycurl.
[ "At sizes of 500MB+ one has to worry about data integrity, and HTTP is not designed with data integrity in mind.\nI'd rather use python bindings for rsync (if they exist) or even bittorrent, which was initially implemented in python. Both rsync and bittorrent address the data integrity issue.\n" ]
[ 0 ]
[]
[]
[ "curl", "python", "urllib2" ]
stackoverflow_0003402271_curl_python_urllib2.txt
Q: python dict remove duplicate values by key's value? A dict dic = { 1: 'a', 2: 'a', 3: 'b', 4: 'a', 5: 'c', 6: 'd', 7: 'd', 8: 'a', 9: 'a'} I want to remove duplicate values just keep one K/V pair, Regarding the "key" selection of those duplicated values, it may be max or min or by random select one of those duplicated item's key. I do not want to use a k/v swap since that can not control the key selection. Take value "a" for example 1: 'a', 2: 'a', 4: 'a', 8: 'a', 9: 'a' the max key will be {9: 'a'} and the min will be {1: 'a'}, and the random will choise any one of it. And, if the key is other kind of hashable value, for example, string, then how to do such a selection? Can anyone share me an idea? Thanks! A: You could build a reverse dictionary where the values are lists of all the keys from your initial dictionary. Using this you could then do what you want, min, max, random, alternate min and max, or whatever. from collections import defaultdict d = defaultdict(list) for k,v in dic.iteritems(): d[v].append(k) print d # {'a': [1, 2, 4, 8, 9], 'c': [5], 'b': [3], 'd': [6, 7]} A: import itertools as it newdic = {} for v, grp in it.groupby(sorted((v, k) for k, v in dic.items)): newdic[min(k for _, k in grp)] = v Or other "selection" functions in lieu of min (which, of course, does work fine even if keys are strings -- will give you the "lexically first" key in that case). The one case in which the selection function needs some care is when the keys corresponding to the same value may be non-comparable (e.g., complex numbers, or, in Python 3, objects of different not-all-numeric types). Nothing a key= in the min won't cure;-). A: This will give you a randomly selected unique key: In [29]: dic Out[29]: {1: 'a', 2: 'a', 3: 'b', 4: 'a', 5: 'c', 6: 'd', 7: 'd', 8: 'a', 9: 'a'} In [30]: dict((v,k) for k,v in dic.iteritems()) Out[30]: {'a': 9, 'b': 3, 'c': 5, 'd': 7} In [31]: dict((v,k) for k,v in dict((v,k) for k,v in dic.iteritems()).iteritems()) Out[31]: {3: 'b', 5: 'c', 7: 'd', 9: 'a'}
python dict remove duplicate values by key's value?
A dict dic = { 1: 'a', 2: 'a', 3: 'b', 4: 'a', 5: 'c', 6: 'd', 7: 'd', 8: 'a', 9: 'a'} I want to remove duplicate values just keep one K/V pair, Regarding the "key" selection of those duplicated values, it may be max or min or by random select one of those duplicated item's key. I do not want to use a k/v swap since that can not control the key selection. Take value "a" for example 1: 'a', 2: 'a', 4: 'a', 8: 'a', 9: 'a' the max key will be {9: 'a'} and the min will be {1: 'a'}, and the random will choise any one of it. And, if the key is other kind of hashable value, for example, string, then how to do such a selection? Can anyone share me an idea? Thanks!
[ "You could build a reverse dictionary where the values are lists of all the keys from your initial dictionary. Using this you could then do what you want, min, max, random, alternate min and max, or whatever.\nfrom collections import defaultdict\n\nd = defaultdict(list)\nfor k,v in dic.iteritems():\n d[v].appen...
[ 5, 2, 1 ]
[]
[]
[ "dictionary", "duplicates", "python" ]
stackoverflow_0003402346_dictionary_duplicates_python.txt
Q: How to reverse django feed url? I've been searching for hours to try and figure this out, and it seems like no one has ever put an example online - I've just created a Django 1.2 rss feed view object and attached it to a url. When I visit the url, everything works great, so I know my implementation of the feed class is OK. The hitch is, I can't figure out how to link to the url in my template. I could just hard code it, but I would much rather use {% url %} I've tried passing the full path like so: {% url app_name.lib.feeds.LatestPosts blog_name=name %} And I get nothing. I've been searching and it seems like everyone else has a solution so obvious it's not worth posting online. Have I just been up too long? Here is the relevent url pattern: from app.lib.feeds import LatestPosts urlpatterns = patterns('app.blog.views', (r'^rss/(?P<blog_name>[A-Za-z0-9]+)/$', LatestPosts()), #snip... ) Thanks for your help. A: You can name your url pattern, which requires the use of the url helper function: from django.conf.urls.defaults import url, patterns urlpatterns = patterns('app.blog.views', url(r'^rss/(?P<blog_name>[A-Za-z0-9]+)/$', LatestPosts(), name='latest-posts'), #snip... ) Then, you can simply use {% url latest-posts blog_name="myblog" %} in your template.
How to reverse django feed url?
I've been searching for hours to try and figure this out, and it seems like no one has ever put an example online - I've just created a Django 1.2 rss feed view object and attached it to a url. When I visit the url, everything works great, so I know my implementation of the feed class is OK. The hitch is, I can't figure out how to link to the url in my template. I could just hard code it, but I would much rather use {% url %} I've tried passing the full path like so: {% url app_name.lib.feeds.LatestPosts blog_name=name %} And I get nothing. I've been searching and it seems like everyone else has a solution so obvious it's not worth posting online. Have I just been up too long? Here is the relevent url pattern: from app.lib.feeds import LatestPosts urlpatterns = patterns('app.blog.views', (r'^rss/(?P<blog_name>[A-Za-z0-9]+)/$', LatestPosts()), #snip... ) Thanks for your help.
[ "You can name your url pattern, which requires the use of the url helper function:\nfrom django.conf.urls.defaults import url, patterns\n\nurlpatterns = patterns('app.blog.views',\n url(r'^rss/(?P<blog_name>[A-Za-z0-9]+)/$', LatestPosts(), name='latest-posts'),\n #snip...\n)\n\nThen, you can simply use {% url...
[ 6 ]
[]
[]
[ "django", "django_syndication", "python", "rss" ]
stackoverflow_0003402362_django_django_syndication_python_rss.txt
Q: Fibonacci sequence Possible Duplicate: How to write the Fibonacci Sequence in Python Hi. I'm also a learning programmer and I've been asked the same question you were asked for Fibonacci numbers and I can't figure it out. Can you please show me the code you used to generate these numbers asking the user to give numbers and find only the numbers in the range specified? Thank you A: I'm not going to give you the code - you should be able to write it yourself. Here are some things you may need to know when writing it however (Not using recursion): Create 3 variables equal to -1 (n1), 1 (n2), and n1 + n2 sumn. Create a loop using for i in range(amount_of_numbers), where amount_of_numbers is how many numbers you want to generate In this loop, reassign n1 to n2, n2 to sumn, and, once again, sumn to n1 + n2. Print out sumn (Inside the loop). That should be all you need to know if you are really lost on where to go with this. If you need help with specific syntax, you can check out the python docs. Your output should look like this: 1 1 2 3 5 8 13 21 A: A good google should save the day http://en.literateprograms.org/Fibonacci_numbers_(Python) How to write the Fibonacci Sequence in Python A: This question and answers provides you everything you need, I think: How to write the Fibonacci Sequence in Python
Fibonacci sequence
Possible Duplicate: How to write the Fibonacci Sequence in Python Hi. I'm also a learning programmer and I've been asked the same question you were asked for Fibonacci numbers and I can't figure it out. Can you please show me the code you used to generate these numbers asking the user to give numbers and find only the numbers in the range specified? Thank you
[ "I'm not going to give you the code - you should be able to write it yourself. Here are some things you may need to know when writing it however (Not using recursion):\n\nCreate 3 variables equal to -1 (n1), 1 (n2), and n1 + n2 sumn.\nCreate a loop using for i in range(amount_of_numbers), where amount_of_numbers i...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003402584_python.txt
Q: How can I select and delete all (ctrl + shift + left arrow + del) with shell.SendKeys? Hey, I'm having some trouble here... How can I delete an entire text from a field with the sendkeys ? How can I send the ctrl+shift pressed with the left arrow and delete key after? edit: for example, I have this part of the code ctypes.windll.user32.SetCursorPos(910,475) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0) time.sleep(0.1) shell.SendKeys(inf_firstname) This part select a field and paste the firstname information (just like a macro), but I want to do something before paste the information that deletes the content of the field, if it has one... capiche? A: I don't know with Sendkeys but I know that you can send keystrokes with ctypes. Here is how to remove a text by sending CTRL+A and BACK: ctypes.windll.user32.keybd_event(0x11, 0, 0, 0) #CTRL is down ctypes.windll.user32.keybd_event(ord("A"), 0, 0, 0) #A is down ctypes.windll.user32.keybd_event(ord("A"), 0, 0x0002, 0) #A is up ctypes.windll.user32.keybd_event(0x11, 0, 0x0002, 0) #CTRL is up ctypes.windll.user32.keybd_event(0x08, 0, 0, 0) #BACK is down ctypes.windll.user32.keybd_event(0x08, 0, 0x0002, 0) #BACK is up You need to send the windows virtual key code. See here for the full list. It may be similar with SendKeys I hope it helps A: Might want to do Ctrl+A instead? Can you give a short example of the code that isn't working for you? Depending on the implementation of SendKeys, it might not accept all those at once. It might require multiple SendKeys invocations. You could try doing one at a time, in separate calls to SendKeys. Edit: http://msdn.microsoft.com/en-us/library/8c6yea83.aspx It seems to me you should be able to do this: shell.SendKeys("^a") shell.SendKeys("{DELETE}")
How can I select and delete all (ctrl + shift + left arrow + del) with shell.SendKeys?
Hey, I'm having some trouble here... How can I delete an entire text from a field with the sendkeys ? How can I send the ctrl+shift pressed with the left arrow and delete key after? edit: for example, I have this part of the code ctypes.windll.user32.SetCursorPos(910,475) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0) time.sleep(0.1) shell.SendKeys(inf_firstname) This part select a field and paste the firstname information (just like a macro), but I want to do something before paste the information that deletes the content of the field, if it has one... capiche?
[ "I don't know with Sendkeys but I know that you can send keystrokes with ctypes.\nHere is how to remove a text by sending CTRL+A and BACK:\nctypes.windll.user32.keybd_event(0x11, 0, 0, 0) #CTRL is down\nctypes.windll.user32.keybd_event(ord(\"A\"), 0, 0, 0) #A is down\nctypes.windll.user32.keybd_event(ord(\"A\"), 0,...
[ 4, 3 ]
[]
[]
[ "python", "sendkeys" ]
stackoverflow_0003401149_python_sendkeys.txt
Q: Multi choice form field in Django I'am developing application on app-engine-path. I would like to make form with multichoice (acceptably languages for user). Code look like this: Language settings: settings.LANGUAGES = ((u"cs", u"Čeština"), (u"en", u"English")) Form model: class UserForm(forms.ModelForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) languages = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=settings.LANGUAGES) The form is rendered o.k. (all languages have checkbox. IDs, NAMEs is ok.) But if I save some languages for user, those languages don't check checkboxes. User model look like this class User(User): #... languages = db.StringListProperty() #... and view: def edit_profile(request): user = request.user if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): # ... else: form = UserForm(instance=user) data = {"user":user, "form": form} return render_to_response(request, 'user_profile/user_profile.html', data) A: I solved it this way: some_view(request): ... form = UserForm(instance=user, initial={"languages":user.languages}) ...
Multi choice form field in Django
I'am developing application on app-engine-path. I would like to make form with multichoice (acceptably languages for user). Code look like this: Language settings: settings.LANGUAGES = ((u"cs", u"Čeština"), (u"en", u"English")) Form model: class UserForm(forms.ModelForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) languages = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=settings.LANGUAGES) The form is rendered o.k. (all languages have checkbox. IDs, NAMEs is ok.) But if I save some languages for user, those languages don't check checkboxes. User model look like this class User(User): #... languages = db.StringListProperty() #... and view: def edit_profile(request): user = request.user if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): # ... else: form = UserForm(instance=user) data = {"user":user, "form": form} return render_to_response(request, 'user_profile/user_profile.html', data)
[ "I solved it this way:\nsome_view(request):\n ...\n form = UserForm(instance=user, initial={\"languages\":user.languages}) \n ...\n\n" ]
[ 0 ]
[]
[]
[ "app_engine_patch", "django_forms", "python" ]
stackoverflow_0002522332_app_engine_patch_django_forms_python.txt
Q: Find max length word from arbitrary letters I have 10 arbitrary letters and need to check the max length match from words file I started to learn RE just some time ago, and can't seem to find suitable pattern first idea that came was using set: [10 chars] but it also repeats included chars and I don't know how to avoid that I stared to learn Python recently but before RE and maybe RE is not needed and this can be solved without it using "for this in that:" iterator seems inappropriate, but maybe itertools can do it easily (with which I'm not familiar) I guess solution is known even to novice programmers/scripters, but not to me Thanks A: I'm guessing this is something like finding possible words given a set of Scrabble tiles, so that a character can be repeated only as many times as it is repeated in the original list. The trick is to efficiently test each character of each word in your word file against a set containing your source letters. For each character, if found in the test set, remove it from the test set and proceed; otherwise, the word is not a match, and go on to the next word. Python has a nice function all for testing a set of conditions based on elements in a sequence. all has the added feature that it will "short-circuit", that is, as soon as one item fails the condition, then no more tests are done. So if your first letter of your candidate word is 'z', and there is no 'z' in your source letters, then there is no point in testing any more letters in the candidate word. My first shot at writing this was simply: matches = [] for word in wordlist: testset = set(letters) if all(c in testset for c in word): matches.append(word) Unfortunately, the bug here is that if the source letters contained a single 'm', a word with several 'm's would erroneously match, since each 'm' would separately match the given 'm' in the source testset. So I needed to remove each letter as it was matched. I took advantage of the fact that set.remove(item) returns None, which Python treats as a Boolean False, and expanded my generator expression used in calling all. For each c in word, if it is found in testset, I want to additionally remove it from testset, something like (pseudo-code, not valid Python): all(c in testset and "remove c from testset" for c in word) Since set.remove returns a None, I can replace the quoted bit above with "not testset.remove(c)", and now I have a valid Python expression: all(c in testset and not testset.remove(c) for c in word) Now we just need to wrap that in a loop that checks each word in the list (be sure to build a fresh testset before checking each word, since our all test has now become a destructive test): for word in wordlist: testset = set(letters) if all(c in testset and not testset.remove(c) for c in word): matches.append(word) The final step is to sort the matches by descending length. We can pass a key function to sort. The builtin len would be good, but that would sort by ascending length. To change it to a descending sort, we use a lambda to give us not len, but -1 * len: matches.sort(key=lambda wd: -len(wd)) Now you can just print out the longest word, at matches[0], or iterate over all matches and print them out. (I was surprised that this brute force approach runs so well. I used the 2of12inf.txt word list, containing over 80,000 words, and for a list of 10 characters, I get back the list of matches in about 0.8 seconds on my little 1.99GHz laptop.) A: I think this code will do what you are looking for: >>> words = open('file.txt') >>> max(len(word) for word in set(words.split())) If you require more sophisticated tokenising, for example if you're not using Latin text, would should use NLTK: >>> import nltk >>> words = open('file.txt') >>> max(len(word) for word in set(nltk.word_tokenize(words))) A: I assume you are trying to find out what is the longest word that can be made from your 10 arbitrary letters. You can keep your 10 arbitrary letters in a dict along with the frequency they occur. e.g., your 4 (using 4 instead of 10 for simplicity) arbitrary letters are: e, w, l, l. This would be in a dict as: {'e':1, 'w':1, 'l':2} Then for each word in the text file, see if all of the letters for that word can be found in your dict of arbitrary letters. If so, then that is one of your candidate words. So: we wall well all of the letters in well would be found in your dict of arbitrary letters so save it and its length for comparison against other words.
Find max length word from arbitrary letters
I have 10 arbitrary letters and need to check the max length match from words file I started to learn RE just some time ago, and can't seem to find suitable pattern first idea that came was using set: [10 chars] but it also repeats included chars and I don't know how to avoid that I stared to learn Python recently but before RE and maybe RE is not needed and this can be solved without it using "for this in that:" iterator seems inappropriate, but maybe itertools can do it easily (with which I'm not familiar) I guess solution is known even to novice programmers/scripters, but not to me Thanks
[ "I'm guessing this is something like finding possible words given a set of Scrabble tiles, so that a character can be repeated only as many times as it is repeated in the original list.\nThe trick is to efficiently test each character of each word in your word file against a set containing your source letters. For...
[ 2, 0, 0 ]
[]
[]
[ "iterator", "puzzle", "python" ]
stackoverflow_0003402574_iterator_puzzle_python.txt
Q: Creating Instances of IronPython Classes From C# I want to create an instance of an IronPython class from C#, but my current attempts all seem to have failed. This is my current code: ConstructorInfo[] ci = type.GetConstructors(); foreach (ConstructorInfo t in from t in ci where t.GetParameters().Length == 1 select t) { PythonType pytype = DynamicHelpers.GetPythonTypeFromType(type); object[] consparams = new object[1]; consparams[0] = pytype; _objects[type] = t.Invoke(consparams); pytype.__init__(_objects[type]); break; } I am able to get the created instance of the object from calling t.Invoke(consparams), but the __init__ method doesn't seem to be called, and thus all the properties that I set from my Python script aren't used. Even with the explicit pytype.__init__ call, the constructed object still doesn't seem to be initialised. Using ScriptEngine.Operations.CreateInstance doesn't seem to work, either. I'm using .NET 4.0 with IronPython 2.6 for .NET 4.0. EDIT: Small clarification on how I'm intending to do this: In C#, I have a class as follows: public static class Foo { public static object Instantiate(Type type) { // do the instantiation here } } And in Python, the following code: class MyClass(object): def __init__(self): print "this should be called" Foo.Instantiate(MyClass) The __init__ method never seems to be called. A: This code works with IronPython 2.6.1 static void Main(string[] args) { const string script = @" class A(object) : def __init__(self) : self.a = 100 class B(object) : def __init__(self, a, v) : self.a = a self.v = v def run(self) : return self.a.a + self.v "; var engine = Python.CreateEngine(); var scope = engine.CreateScope(); engine.Execute(script, scope); var typeA = scope.GetVariable("A"); var typeB = scope.GetVariable("B"); var a = engine.Operations.CreateInstance(typeA); var b = engine.Operations.CreateInstance(typeB, a, 20); Console.WriteLine(b.run()); // 120 } EDITED according to clarified question class Program { static void Main(string[] args) { var engine = Python.CreateEngine(); var scriptScope = engine.CreateScope(); var foo = new Foo(engine); scriptScope.SetVariable("Foo", foo); const string script = @" class MyClass(object): def __init__(self): print ""this should be called"" Foo.Create(MyClass) "; var v = engine.Execute(script, scriptScope); } } public class Foo { private readonly ScriptEngine engine; public Foo(ScriptEngine engine) { this.engine = engine; } public object Create(object t) { return engine.Operations.CreateInstance(t); } } A: I think I solved my own question -- using the .NET Type class seems to have discarded Python type information. Replacing it with IronPython.Runtime.Types.PythonType works quite well. A: Looks like you're looking for the answer given to this SO question.
Creating Instances of IronPython Classes From C#
I want to create an instance of an IronPython class from C#, but my current attempts all seem to have failed. This is my current code: ConstructorInfo[] ci = type.GetConstructors(); foreach (ConstructorInfo t in from t in ci where t.GetParameters().Length == 1 select t) { PythonType pytype = DynamicHelpers.GetPythonTypeFromType(type); object[] consparams = new object[1]; consparams[0] = pytype; _objects[type] = t.Invoke(consparams); pytype.__init__(_objects[type]); break; } I am able to get the created instance of the object from calling t.Invoke(consparams), but the __init__ method doesn't seem to be called, and thus all the properties that I set from my Python script aren't used. Even with the explicit pytype.__init__ call, the constructed object still doesn't seem to be initialised. Using ScriptEngine.Operations.CreateInstance doesn't seem to work, either. I'm using .NET 4.0 with IronPython 2.6 for .NET 4.0. EDIT: Small clarification on how I'm intending to do this: In C#, I have a class as follows: public static class Foo { public static object Instantiate(Type type) { // do the instantiation here } } And in Python, the following code: class MyClass(object): def __init__(self): print "this should be called" Foo.Instantiate(MyClass) The __init__ method never seems to be called.
[ "This code works with IronPython 2.6.1\n static void Main(string[] args)\n {\n const string script = @\"\nclass A(object) :\n def __init__(self) :\n self.a = 100\n\nclass B(object) : \n def __init__(self, a, v) : \n self.a = a\n self.v = v\n def run(self) :\n return...
[ 10, 2, 0 ]
[]
[]
[ ".net", "c#", "dynamic_language_runtime", "ironpython", "python" ]
stackoverflow_0003402713_.net_c#_dynamic_language_runtime_ironpython_python.txt
Q: Comparing strings using '==' and 'is' Possible Duplicates: Types for which “is” keyword may be equivalent to equality operator in Python Python “is” operator behaves unexpectedly with integers Hi. I have a question which perhaps might enlighten me on more than what I am asking. Consider this: >>> x = 'Hello' >>> y = 'Hello' >>> x == y True >>> x is y True I have always used the comparison operator. Also I read that is compares the memory address and hence in this case, returns True So my question is, is this another way to compare variables in Python? If yes, then why is this not used? Also I noticed that in C++, if the variables have the same value, their memory addresses are different. { int x = 40; int y = 40; cout << &x, &y; } 0xbfe89638, 0xbfe89634 What is the reason for Python having the same memory addresses? A: This is an implementation detail and absolutely not to be relied upon. is compares identities, not values. Short strings are interned, so they map to the same memory address, but this doesn't mean you should compare them with is. Stick to ==. A: There are two ways to check for equality in Python: == and is. == will check the value, while is will check the identity. In almost every case, if is is true, then == must be true. Sometimes, Python (specifically, CPython) will optimize values together so that they have the same identity. This is especially true for short strings. Python realizes that 'Hello' is the same as 'Hello' and since strings are immutable, they become the same through string interning / string pooling. See a related question: Python: Why does ("hello" is "hello") evaluate as True? A: This is because of a Python feature called String interning which is a method of storing only one copy of each distinct string value. A: In Python both strings and integers are immutable therefore you can cache them. Integers in the range of ´-5´ to ´256´ and small strings(don't know the exact size atm) get cached, therefore they are the same object. x and y are only names that refer to these objects. Also == compares for equals values, while is compares for object identity. None True and False are global objects, for example you can rebind False to True. The following shows that not every thing is being cached: x = 'Test' * 2000 y = 'Test' * 2000 >>> x == y True >>> x is y False >>> x = 10000000000000 >>> y = 10000000000000 >>> x == y True >>> x is y False A: In Python, variables are just names that point to some object (and they can point to the same object). In C++, variables also define the actual memory that is reserved for them; this is why they have distinct memory addresses. About Python string interning and differences between the two comparison operators, see carl's response.
Comparing strings using '==' and 'is'
Possible Duplicates: Types for which “is” keyword may be equivalent to equality operator in Python Python “is” operator behaves unexpectedly with integers Hi. I have a question which perhaps might enlighten me on more than what I am asking. Consider this: >>> x = 'Hello' >>> y = 'Hello' >>> x == y True >>> x is y True I have always used the comparison operator. Also I read that is compares the memory address and hence in this case, returns True So my question is, is this another way to compare variables in Python? If yes, then why is this not used? Also I noticed that in C++, if the variables have the same value, their memory addresses are different. { int x = 40; int y = 40; cout << &x, &y; } 0xbfe89638, 0xbfe89634 What is the reason for Python having the same memory addresses?
[ "This is an implementation detail and absolutely not to be relied upon. is compares identities, not values. Short strings are interned, so they map to the same memory address, but this doesn't mean you should compare them with is. Stick to ==.\n", "There are two ways to check for equality in Python: == and is. ==...
[ 12, 10, 8, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003403964_python.txt
Q: djangoproject access fields of object dynamically Can anyone help me? I have list of fields called 'allowed_fields' and I have object called 'individual'. allowed_fields is sub set of individual. Now I want to run loop like this for field in allowed_fields: obj.field = individual.field obj have same fields like individual. Do you have solution of my problem? I will thankful to you. A: If each field is actually a string, you could try the following. I renamed field to fieldname to better indicate that it is a string. for fieldname in allowed_fields: setattr(obj, fieldname, getattr(individual, fieldname)) A: setattr(obj, fieldname, fieldvalue) (see also getattr to retrieve at runtime)
djangoproject access fields of object dynamically
Can anyone help me? I have list of fields called 'allowed_fields' and I have object called 'individual'. allowed_fields is sub set of individual. Now I want to run loop like this for field in allowed_fields: obj.field = individual.field obj have same fields like individual. Do you have solution of my problem? I will thankful to you.
[ "If each field is actually a string, you could try the following.\nI renamed field to fieldname to better indicate that it is a string.\nfor fieldname in allowed_fields:\n setattr(obj, fieldname, getattr(individual, fieldname))\n\n", "setattr(obj, fieldname, fieldvalue)\n(see also getattr to retrieve at runtim...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003404055_django_python.txt
Q: Updating an object in a for loop using SqlAlchemy, should this work in theory? So first I am fetching the rows: q = session.query(products) for p in q: p.someproperty = 23 session.commit() Should the above work in theory? Or is that the wrong pattern? I am getting an error saying can't modify the property, which is strange so I figured I was doing something fundamentally wrong. A: 2 things: Number one, you shouldn't have to commit() after every change. You should be able to: for p in session.query (query): p.someproperty = somevalue session.commit() and number two, see this thread here: Efficiently updating database using SQLAlchemy ORM. This gives another example of the syntax, and also the accepted answer suggests a better, more efficient way to perform this mass update. A: You have to fetch the objects explicitly to be able to modify them; you have to iterate over session.query(query_string).all() . And, of course, a single commit after the loop is finished would be more efficient.
Updating an object in a for loop using SqlAlchemy, should this work in theory?
So first I am fetching the rows: q = session.query(products) for p in q: p.someproperty = 23 session.commit() Should the above work in theory? Or is that the wrong pattern? I am getting an error saying can't modify the property, which is strange so I figured I was doing something fundamentally wrong.
[ "2 things:\nNumber one, you shouldn't have to commit() after every change. You should be able to:\nfor p in session.query (query):\n p.someproperty = somevalue\nsession.commit()\n\nand number two, see this thread here: Efficiently updating database using SQLAlchemy ORM. This gives another example of the syntax...
[ 3, 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003393102_python_sqlalchemy.txt
Q: urllib.urlopen to open page on same port just hangs I am trying to use urllib.urlopen to open a web page running on the same host and port as the page I am loading it from and it is just hanging. For example I have a page at: "http://mydevserver.com:8001/readpage.html" and I have the following code in it: data = urllib.urlopen("http://mydevserver.com:8001/testpage.html") When I try and load the page it just hangs. However if I move the testpage.html script to a different port on the same host it works fine. e.g. data = urllib.urlopen("http://mydevserver.com:8002/testpage.html") Does anyone know why this might be and how I can solve the problem? A: A firewall perhaps? Try opening the page from the command line with wget/curl (assuming you're on Linux) or on the browser, with both ports on settings. Furthermore, you could try a packet sniffer to find out what's going on and where the connection gets stuck. Also, if testpage.html is dynamically generated, see if it is hit, check webserver logs if the request shows up there. A: Maybe something is already running on port 8001. Does the page open properly with a browser? A: You seem to be implying that you are accessing a web page that is scripted in Python. That implies that the Python script is handling the incoming connections, which could mean that since it's already handling the urllib call, it is not available to handle the connection that results from it as well. Show the code (or tell us what software) you're using to serve these Python scripts.
urllib.urlopen to open page on same port just hangs
I am trying to use urllib.urlopen to open a web page running on the same host and port as the page I am loading it from and it is just hanging. For example I have a page at: "http://mydevserver.com:8001/readpage.html" and I have the following code in it: data = urllib.urlopen("http://mydevserver.com:8001/testpage.html") When I try and load the page it just hangs. However if I move the testpage.html script to a different port on the same host it works fine. e.g. data = urllib.urlopen("http://mydevserver.com:8002/testpage.html") Does anyone know why this might be and how I can solve the problem?
[ "A firewall perhaps? Try opening the page from the command line with wget/curl (assuming you're on Linux) or on the browser, with both ports on settings. Furthermore, you could try a packet sniffer to find out what's going on and where the connection gets stuck. Also, if testpage.html is dynamically generated, see ...
[ 0, 0, 0 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0003404003_python_urllib.txt
Q: How to tell if item in list contains certain characters I have a script that creates a list of numbers, and i want to remove all numbers from the list that are not whole numbers (i.e have anything other than zero after the decimal point) however python creates lists where even whole numbers get .0 put on the end, and as a result i cant tell them apart from numbers with anything else. I can't use the int() function as it would apply to all of them and make them all integers, and then i'd lose the ones that originally were. Here is my code: z = 300 mylist = [] while(z > 1): z = z - 1 x = 600851475143 / z mylist.append(x) print(mylist) [y for y in mylist if y #insert rule to tell if it contains .0 here] the first bit just divides 600851475143 by every number between 300 and 1 in turn. I then need to filter this list to get only the ones that are whole numbers. I have a filter in place, but where the comment is i need a rule that will tell if the particular value in the list has .0 Any way this can be achieved? A: You're performing an integer division, so your results will all be integers anyway. Even if you'd divide by float(z) instead, you'd run the risk of getting rounding errors, so checking for .0 wouldn't be a good idea anyway. Maybe what you want is if 600851475143 % z == 0: mylist.append(600851475143/z) It's called the "modulo operator", cf. http://docs.python.org/reference/expressions.html#binary-arithmetic-operations EDIT: Ralph is right, I didn't put the division result into the list. Now it looks ugly, due to the repetition of the division ... :) gnibbler's answer is probably preferable, or Ralph's. A: You can use divmod() and only put the result of an "even divide" in to your list: z = 300 mylist = [] while(z > 1): z = z - 1 x,y = divmod(600851475143, z) if y==0: mylist.append(x) print(mylist) A: You can use int() - just not the way you were thinking of perhaps z = 300 mylist = [] while(z > 1): z = z - 1 x = 600851475143 / z mylist.append(x) print(mylist) [y for y in mylist if y==int(y)] A: Use regular expressions to match what you need. In your case, it should be check for ".0" at the end of the string, thus re.search("\.0$", y). Please be aware that you should use re.search, because re.match checks only for match at the beginning of the string. Edit: sorry, I was disappointed with however python creates lists where even whole numbers get .0 and thought that you are making it list of strings. jellybean gave you the answer. A: jellybean's answer is quite good, so I'd summarise: magic_num = 600851475143 filtered_list = [magic_num/i for i in range(300,0,-1) if magic_num%i == 0] (the division operator should be integer //, but the code coloriser interprets it as a comment, so I've left the single slash)
How to tell if item in list contains certain characters
I have a script that creates a list of numbers, and i want to remove all numbers from the list that are not whole numbers (i.e have anything other than zero after the decimal point) however python creates lists where even whole numbers get .0 put on the end, and as a result i cant tell them apart from numbers with anything else. I can't use the int() function as it would apply to all of them and make them all integers, and then i'd lose the ones that originally were. Here is my code: z = 300 mylist = [] while(z > 1): z = z - 1 x = 600851475143 / z mylist.append(x) print(mylist) [y for y in mylist if y #insert rule to tell if it contains .0 here] the first bit just divides 600851475143 by every number between 300 and 1 in turn. I then need to filter this list to get only the ones that are whole numbers. I have a filter in place, but where the comment is i need a rule that will tell if the particular value in the list has .0 Any way this can be achieved?
[ "You're performing an integer division, so your results will all be integers anyway.\nEven if you'd divide by float(z) instead, you'd run the risk of getting rounding errors, so checking for .0 wouldn't be a good idea anyway.\nMaybe what you want is\nif 600851475143 % z == 0:\n mylist.append(600851475143/z)\n\nI...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003404382_python.txt
Q: Hyperlink in Tkinter Text widget? I am re designing a portion of my current software project, and want to use hyperlinks instead of Buttons. I really didn't want to use a Text widget, but that is all I could find when I googled the subject. Anyway, I found an example of this, but keep getting this error: TclError: bitmap "blue" not defined When I add this line of code (using the IDLE) hyperlink = tkHyperlinkManager.HyperlinkManager(text) The code for the module is located here and the code for the script is located here Anyone have any ideas? The part that is giving problems says foreground="blue", which is known as a color in Tkinter, isn't it? A: If you don't want to use a text widget, you don't need to. An alternative is to use a label and bind mouse clicks to it. Even though it's a label it still responds to events. For example: import tkinter as tk class App: def __init__(self, root): self.root = root for text in ("link1", "link2", "link3"): link = tk.Label(text=text, foreground="#0000ff") link.bind("<1>", lambda event, text=text: self.click_link(event, text)) link.pack() def click_link(self, event, text): print("You clicked '%s'" % text) root = tk.Tk() app = App(root) root.mainloop() If you want, you can get fancy and add additional bindings for <Enter> and <Leave> events so you can alter the look when the user hovers. And, of course, you can change the font so that the text is underlined if you so choose. Tk is a wonderful toolkit that gives you the building blocks to do just about whatever you want. You just need to look at the widgets not as a set of pre-made walls and doors but more like a pile of lumbar, bricks and mortar. A: "blue" should indeed be acceptable (since you're on Windows, Tkinter should use its built-in color names table -- it might be a system misconfiguration on X11, but not on Windows); therefore, this is a puzzling problem (maybe a Tkinter misconfig...?). What happen if you use foreground="#00F" instead, for example? This doesn't explain the problem but might let you work around it, at least...
Hyperlink in Tkinter Text widget?
I am re designing a portion of my current software project, and want to use hyperlinks instead of Buttons. I really didn't want to use a Text widget, but that is all I could find when I googled the subject. Anyway, I found an example of this, but keep getting this error: TclError: bitmap "blue" not defined When I add this line of code (using the IDLE) hyperlink = tkHyperlinkManager.HyperlinkManager(text) The code for the module is located here and the code for the script is located here Anyone have any ideas? The part that is giving problems says foreground="blue", which is known as a color in Tkinter, isn't it?
[ "If you don't want to use a text widget, you don't need to. An alternative is to use a label and bind mouse clicks to it. Even though it's a label it still responds to events.\nFor example:\nimport tkinter as tk\n\nclass App:\n def __init__(self, root):\n self.root = root\n for text in (\"link1\", ...
[ 13, 1 ]
[]
[]
[ "hyperlink", "python", "tkinter", "windows" ]
stackoverflow_0003402110_hyperlink_python_tkinter_windows.txt
Q: Finding the user who uses my django web application I have developed a small django web application. It still runs in the django development web server. It has been decided that if more than 'n' number of users like the application, it will be approved. I want to find out all the users who view my application. How can find the user who views my application? Since I was the user who ran the application, all python ways of getting the username returns my name only. Please help. A: You can look in the admin to see how many usernames are there, assuming everyone who likes it creates one. Or you can look at your server logs and count the unique IPs. A: You can keep track of your visitors by adding a call to google analytics in your web pages. Or, if you do not wish to use a Google product, there are plenty of other analytics packages to keep track of visitors locally. These packages tell you a lot more than just the number of unique visitors. An open source alternative can be found at http://piwik.org/ . Also, see http://forge.2metz.fr/p/python-piwik/ A: Step 1. Add a model -- connected users. Include an FK to username and a datetime stamp. Step 2. Write a function to log each user's activity. Step 3. Write your own version of login that will call the Django built-in login and also call your function to log each user's activity. Step 4. Write a small application -- outside Django -- that uses the ORM to query the connected users table and write summaries and counts and what-not. You have a database. Use it.
Finding the user who uses my django web application
I have developed a small django web application. It still runs in the django development web server. It has been decided that if more than 'n' number of users like the application, it will be approved. I want to find out all the users who view my application. How can find the user who views my application? Since I was the user who ran the application, all python ways of getting the username returns my name only. Please help.
[ "You can look in the admin to see how many usernames are there, assuming everyone who likes it creates one. Or you can look at your server logs and count the unique IPs.\n", "You can keep track of your visitors by adding a call to google analytics in your web pages. Or, if you do not wish to use a Google product,...
[ 1, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003404759_django_python.txt
Q: Changing the encoding of a table with django+south migrations Django and south newbie here I need to change the encoding of a table I created, does anyone know a way to do so using a migration? A: I think the solution will be database-specific. For example, for a MySQL database: from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): db.execute('alter table appname_modelname charset=utf8') db.execute('alter table appname_modelname alter column fieldname charset=utf8') # et cetera for any other char or text columns def backwards(self, orm): db.execute('alter table appname_modelname charset=latin1') db.execute('alter table appname_modelname alter column fieldname charset=latin1') # et cetera for any other char or text columns complete_apps = ['appname']
Changing the encoding of a table with django+south migrations
Django and south newbie here I need to change the encoding of a table I created, does anyone know a way to do so using a migration?
[ "I think the solution will be database-specific. For example, for a MySQL database:\nfrom south.db import db\nfrom south.v2 import SchemaMigration\n\nclass Migration(SchemaMigration):\n def forwards(self, orm):\n db.execute('alter table appname_modelname charset=utf8')\n db.execute('alter table app...
[ 8 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0003404737_django_django_south_python.txt
Q: Generating dictionary keys on the fly Working with deeply nested python dicts, I would like to be able to assign values in such a data structure like this: mydict[key][subkey][subkey2]="value" without having to check that mydict[key] etc. are actually set to be a dict, e.g. using if not key in mydict: mydict[key]={} The creation of subdictionaries should happen on the fly. What is the most elegant way to allow something equivalent - maybe using decorators on the standard <type 'dict'>? A: class D(dict): def __missing__(self, key): self[key] = D() return self[key] d = D() d['a']['b']['c'] = 3 A: You could use a tuple as the key for the dict and then you don't have to worry about subdictionaries at all: mydict[(key,subkey,subkey2)] = "value" Alternatively, if you really need to have subdictionaries for some reason you could use collections.defaultdict. For two levels this is straightforward: >>> from collections import defaultdict >>> d = defaultdict(dict) >>> d['key']['subkey'] = 'value' >>> d['key']['subkey'] 'value' For three it's slightly more complex: >>> d = defaultdict(lambda: defaultdict(dict)) >>> d['key']['subkey']['subkey2'] = 'value' >>> d['key']['subkey']['subkey2'] 'value' Four and more levels are left as an exercise for the reader. :-) A: I like Dave's answer better, but here's an alternative. from collections import defaultdict d = defaultdict(lambda : defaultdict(int)) >>> d['a']['b'] += 1 >>> d defaultdict(<function <lambda> at 0x652f0>, {'a': defaultdict(<type 'int'>, {'b': 1})}) >>> d['a']['b'] 1 http://tumble.philadams.net/post/85269428/python-nested-defaultdicts It's definitely not pretty to have to use lambdas to implements the inner defaulted collections, but apparently necessary.
Generating dictionary keys on the fly
Working with deeply nested python dicts, I would like to be able to assign values in such a data structure like this: mydict[key][subkey][subkey2]="value" without having to check that mydict[key] etc. are actually set to be a dict, e.g. using if not key in mydict: mydict[key]={} The creation of subdictionaries should happen on the fly. What is the most elegant way to allow something equivalent - maybe using decorators on the standard <type 'dict'>?
[ "class D(dict):\n def __missing__(self, key):\n self[key] = D()\n return self[key]\n\nd = D()\nd['a']['b']['c'] = 3\n\n", "You could use a tuple as the key for the dict and then you don't have to worry about subdictionaries at all:\nmydict[(key,subkey,subkey2)] = \"value\"\n\nAlternatively, if yo...
[ 28, 14, 3 ]
[]
[]
[ "decorator", "dictionary", "python" ]
stackoverflow_0003405073_decorator_dictionary_python.txt
Q: Execute raw SQL after connect to database How can I execute raw SQL after connect to database? I need to run script once, after connect to DB. Thanks. UPD: question is not how to run raw SQL. A: Just visit the docs here. It was I think the second match on google with "Django ORM". EDIT See comments If you look at this Django page you see that MySQLdb (the underlying layer) also accepts an init_command option which is run immediately after a connection is established. That's a feature of MySQLdb, and not so much of Django itself. A: If you are using django >= 1.2: from django.db import connection, transaction query = "SELECT foo FROM bar;" connection.cursor().execute(query) transaction.commit_unless_managed()
Execute raw SQL after connect to database
How can I execute raw SQL after connect to database? I need to run script once, after connect to DB. Thanks. UPD: question is not how to run raw SQL.
[ "Just visit the docs here.\nIt was I think the second match on google with \"Django ORM\".\nEDIT See comments\nIf you look at this Django page you see that MySQLdb (the underlying layer) also accepts an init_command option which is run immediately after a connection is established. That's a feature of MySQLdb, and ...
[ 1, 1 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0003405166_database_django_python.txt
Q: How can I run gtk.main() asynchronsly in pygtk? The basic code that I have so far is below. How do I thread gtk.main() so that the code after Display is initialized runs asynchronously? import pygtk pygtk.require("2.0") import gtk class Display(): def __init__(self): self.fail = "This will fail to display" window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("destroy", lambda w: gtk.main_quit()) window.show() self.main() def main(self): gtk.main() class Test(): def __init__(self, display): print display.fail d = Display() t = Test(d) A: Just put the gtk.main call after everything else. If you need to have the controller in a separate thread, make sure you do all gtk related function/methods by doing gobject.idle_add(widget.method). import pygtk pygtk.require("2.0") import gtk class Display(object): def __init__(self): self.fail = "This will fail to display" window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("destroy", lambda w: gtk.main_quit()) window.show() class Test(object): def __init__(self, display): print display.fail d = Display() t = Test(d) gtk.main() A: You could use Twisted with the gtk2reactor. http://twistedmatrix.com/documents/current/core/howto/choosing-reactor.html
How can I run gtk.main() asynchronsly in pygtk?
The basic code that I have so far is below. How do I thread gtk.main() so that the code after Display is initialized runs asynchronously? import pygtk pygtk.require("2.0") import gtk class Display(): def __init__(self): self.fail = "This will fail to display" window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("destroy", lambda w: gtk.main_quit()) window.show() self.main() def main(self): gtk.main() class Test(): def __init__(self, display): print display.fail d = Display() t = Test(d)
[ "Just put the gtk.main call after everything else.\nIf you need to have the controller in a separate thread, make sure you do all gtk related function/methods by doing gobject.idle_add(widget.method).\nimport pygtk\npygtk.require(\"2.0\")\nimport gtk\n\nclass Display(object):\n\n def __init__(self):\n sel...
[ 0, 0 ]
[]
[]
[ "multithreading", "pygtk", "python" ]
stackoverflow_0001391680_multithreading_pygtk_python.txt
Q: Python multiprocessing continuously spawns pythonw.exe processes without doing any actual work I don't understand why this simple code # file: mp.py from multiprocessing import Process import sys def func(x): print 'works ', x + 2 sys.stdout.flush() p = Process(target= func, args= (2, )) p.start() p.join() p.terminate() print 'done' sys.stdout.flush() creates "pythonw.exe" processes continuously and it doesn't print anything, even though I run it from the command line: python mp.py I am running the latest of Python 2.6 on Windows 7 both 32 and 64 bits A: You need to protect then entry point of the program by using if __name__ == '__main__':. This is a Windows specific problem. On Windows your module has to be imported into a new Python interpreter in order for it to access your target code. If you don't stop this new interpreter running the start up code it will spawn another child, which will then spawn another child, until it's pythonw.exe processes as far as the eye can see. Other platforms use os.fork() to launch the subprocesses so don't have the problem of reimporting the module. So your code will need to look like this: from multiprocessing import Process import sys def func(x): print 'works ', x + 2 sys.stdout.flush() if __name__ == '__main__': p = Process(target= func, args= (2, )) p.start() p.join() p.terminate() print 'done' sys.stdout.flush() A: According to the programming guidelines for multiprocessing, on windows you need to use an if __name__ == '__main__': A: Funny, works on my Linux machine: $ python mp.py works 4 done $ Is the multiprocessing thing supposed to work on Windows? A lot of programs originated in the Unix world don't handle Windows so well, because Unix uses fork(2) to clone processes quite cheaply, but (it is my understanding) that Windows does not support fork(2) gracefully, if at all.
Python multiprocessing continuously spawns pythonw.exe processes without doing any actual work
I don't understand why this simple code # file: mp.py from multiprocessing import Process import sys def func(x): print 'works ', x + 2 sys.stdout.flush() p = Process(target= func, args= (2, )) p.start() p.join() p.terminate() print 'done' sys.stdout.flush() creates "pythonw.exe" processes continuously and it doesn't print anything, even though I run it from the command line: python mp.py I am running the latest of Python 2.6 on Windows 7 both 32 and 64 bits
[ "You need to protect then entry point of the program by using if __name__ == '__main__':.\nThis is a Windows specific problem. On Windows your module has to be imported into a new Python interpreter in order for it to access your target code. If you don't stop this new interpreter running the start up code it wil...
[ 32, 2, 1 ]
[]
[]
[ "multiprocessing", "process", "python", "windows" ]
stackoverflow_0003405397_multiprocessing_process_python_windows.txt
Q: need to selectively escape html entities (&) I'm scraping a html page, then using xml.dom.minidom.parseString() to create a dom object. however, the html page has a '&'. I can use cgi.escape to convert this into &amp; but it also converts all my html <> tags into &lt;&gt; which makes parseString() unhappy. how do i go about this? i would rather not just hack it and straight replace the "&"s thanks A: i would rather not just hack it and straight replace the "&"s Er, why? That's what cgi.escape is doing - effectively just a search and replace operation for certain characters that have to be escaped. If you only want to replace a single character, just replace the single character: yourstring.replace('&', '&amp;') Don't beat around the bush. A: For scraping, try to use a library that can handle such html "tag soup", like lxml, which has a html parser (as well as a dedicated html package in lxml.html), or BeautifulSoup (you will also find that these libraries also contain other stuff that makes scraping/working with html easier, aside from being able to handle ill-formed documents: getting information out of forms, making hyperlinks absolute, using css selectors...) A: If you want to make sure that you don't accidentally re-escape an already escaped & (i. e. not transform &amp; into &amp;amp; or &szlig; into &amp;szlig;), you could import re newstring = re.sub(r"&(?![A-Za-z])", "&amp;", oldstring) This will leave &s alone when they are followed by a letter. A: You shouldn't use an XML parser to parse data that isn't XML. Find an HTML parser instead, you'll be happier in the long run. The standard library has a few (HTMLParser and htmllib), and BeautifulSoup is a well-loved third-party package.
need to selectively escape html entities (&)
I'm scraping a html page, then using xml.dom.minidom.parseString() to create a dom object. however, the html page has a '&'. I can use cgi.escape to convert this into &amp; but it also converts all my html <> tags into &lt;&gt; which makes parseString() unhappy. how do i go about this? i would rather not just hack it and straight replace the "&"s thanks
[ "\ni would rather not just hack it and\n straight replace the \"&\"s\n\nEr, why? That's what cgi.escape is doing - effectively just a search and replace operation for certain characters that have to be escaped.\nIf you only want to replace a single character, just replace the single character:\nyourstring.replace(...
[ 1, 1, 0, 0 ]
[]
[]
[ "escaping", "html_entities", "python" ]
stackoverflow_0003403168_escaping_html_entities_python.txt
Q: remove everything between 2 tags that span branches of an xml tree I'm trying to remove everything in an XML Document between 2 tags, using python & lxml. the problem is that the tags can be in different branches of the tree (but always at the same depth) an example document might look like this. <root> <p> Hello world <start />this is a paragraph </p> <p> Goodbye world. <end />I'm leaving now </p> </root> i'd like to remove everything between the start and end tags. which would result in a single p tag: <root> <p> Hello world I'm leaving now </p> </root> does anyone have any idea how this might be accomplished using lxml & python? A: You've got a mess on your hands and should slap the person who wrote an intentional perversion of the XML nesting rule. You are probably best of using something like SAX to recognize the <start/> tag and begin discarding input until you hit an <end/>. SAX has the advantage over lxml here because it allows you to take arbitrary actions per lexeme while lxml will have already divorced start and end before you get to touch them. While you're at it, you might want to convert those documents to usable XML. A: I know there are some people who'll want to stone me for this, but you could just use regex: import re new_string = re.sub(r'<start />(.*?)<end />', '', your_string, re.S) You can't use an XML parser when it's not valid XML. A: You could try using the SAX-like target parser interface: from lxml import etree class SkipStartEndTarget: def __init__(self, *args, **kwargs): self.builder = etree.TreeBuilder() self.skip = False def start(self, tag, attrib, nsmap=None): if tag == 'start': self.skip = True if not self.skip: self.builder.start(tag, attrib, nsmap) def data(self, data): if not self.skip: self.builder.data(data) def comment(self, comment): if not self.skip: self.builder.comment(self) def pi(self, target, data): if not self.skip: self.builder.pi(target, data) def end(self, tag): if not self.skip: self.builder.end(tag) if tag == 'end': self.skip = False def close(self): self.skip = False return self.builder.close() You can then use the SkipStartEndTarget class to make a parser target, and create a custom XMLParser with that target, like this: parser = etree.XMLParser(target=SkipStartEndTarget()) You can still provide other parser options to the parser if you need them. Then you can provide this parser to the parser function you are using, for example: elem = etree.fromstring(xml_str, parser=parser) This also works with etree.XML() and etree.parse(), and you can even set the parser as the default parser with etree.setdefaultparser() (which is probably not a good idea). One thing that might trip you: even with etree.parse(), this will not return an elementtree, but always an element (as etree.XML() and etree.fromstring() do). I don't think this can be done (yet), so if this is an issue to you, you will have to work around it somehow. Note that it is also possible to use create an elementtree from sax events, with lxml.sax, which is probably somewhat more difficult and slower. Contrary to the above example, it will return an elementtree, but I think it doesn't provide the .docinfo you would get when using etree.parse() normally. I also believe it (currently) doesn't support comments and pi's. (haven't used it yet, so I can't be more precise at the moment) Also note that any SAX-like approach to parsing the document requires that skipping everything between <start/> and <end/> will still result in a well-formed document, which is the case in your example, but would not be the case if the second <p> was a <p2> for example, as you'd end up with <p>....</p2>.
remove everything between 2 tags that span branches of an xml tree
I'm trying to remove everything in an XML Document between 2 tags, using python & lxml. the problem is that the tags can be in different branches of the tree (but always at the same depth) an example document might look like this. <root> <p> Hello world <start />this is a paragraph </p> <p> Goodbye world. <end />I'm leaving now </p> </root> i'd like to remove everything between the start and end tags. which would result in a single p tag: <root> <p> Hello world I'm leaving now </p> </root> does anyone have any idea how this might be accomplished using lxml & python?
[ "You've got a mess on your hands and should slap the person who wrote an intentional perversion of the XML nesting rule. \nYou are probably best of using something like SAX to recognize the <start/> tag and begin discarding input until you hit an <end/>. SAX has the advantage over lxml here because it allows you to...
[ 1, 1, 0 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0003401922_lxml_python_xml.txt
Q: fuse & gstreamer transcoding I'm trying to create a FUSE fs which transcodes all sound files to mp3. My first idea is to use gstreamer as the backend for transcoding. I thought about using this pipeline: gst-launch -v filesrc location=01\ New\ Born.flac ! decodebin ! audioconvert ! lame vbr=4 vbr-quality=9 ! id3v2mux ! appsink The python bindings of fuse expect calls this function when a file is being read: def read(self, length, offset): How would I transfer the buffer from gstreamer to the fuse fs? I don't how to handle this. I've never used appsink before. I hope it's clear what I mean. A: I don't think you need to bother with appsink. My gut feeling is that the further you can separate the transcoding part from the filesystem part the better. Transcode in a separate thread or process into a filesink and pass messages to tell the FUSE daemon how far transcoding has progressed. Instead of appsink, I'd use filesink, transcode in a number of worker threads/processes that write .mp3s to a size-controlled cache directory, and have read() block until the transcoded file in progress is long enough to fulfill the request. Here's the source for filesink. In the absence of seeks, it appears to just append the contents of each buffer to the file. http://mediatools.cs.ucl.ac.uk/nets/newvideo/browser/gst-cvs/gstreamer/plugins/elements/gstfilesink.c#L436 You could also save yourself a lot of time and trouble by just downloading mp3fs or gstfs which already accomplish pretty much exactly what you mention. A: Have you tried: giosink Write to any GIO-supported location giosrc Read from any GIO-supported location With Gio you should be able to treat FUSE as any file system.
fuse & gstreamer transcoding
I'm trying to create a FUSE fs which transcodes all sound files to mp3. My first idea is to use gstreamer as the backend for transcoding. I thought about using this pipeline: gst-launch -v filesrc location=01\ New\ Born.flac ! decodebin ! audioconvert ! lame vbr=4 vbr-quality=9 ! id3v2mux ! appsink The python bindings of fuse expect calls this function when a file is being read: def read(self, length, offset): How would I transfer the buffer from gstreamer to the fuse fs? I don't how to handle this. I've never used appsink before. I hope it's clear what I mean.
[ "I don't think you need to bother with appsink. My gut feeling is that the further you can separate the transcoding part from the filesystem part the better. Transcode in a separate thread or process into a filesink and pass messages to tell the FUSE daemon how far transcoding has progressed.\nInstead of appsink, I...
[ 0, 0 ]
[]
[]
[ "fuse", "gstreamer", "python" ]
stackoverflow_0003387506_fuse_gstreamer_python.txt
Q: Is there a Python idiom for evaluating a list of functions/expressions with short-circuiting? I wrote a simple script to solve a "logic puzzle", the type of puzzle from school where you are given a number of rules and then must be able to find the solution for problems like "There are five musicians named A, B, C, D, and E playing in a concert, each plays one after the other... if A goes before B, and D is not last ... what is the order of who plays when?" etc. To evaluate possible solutions, I wrote each "rule" as a separate function which would evaluate if a possible solution (represented simply as a list of strings) is valid, for example #Fifth slot must be B or D def rule1(solution): return solution[4] == 'B' or solution[4] == 'D' #There must be at least two spots between A and B def rule2(solution): returns abs(solution.index('A') - solution.index('B')) >= 2 #etc... I'm interested in finding the Pythonic way to test if a possible solution passes all such rules, with the ability to stop evaluating rules after the first has failed. At first I wrote the simplest possible thing: def is_valid(solution): return rule1(solution) and rule2(solution) and rule3(solution) and ... But this seemed rather ugly. I thought perhaps I could make this read a bit more elegant with something like a list comprehension... def is_valid(solution) rules = [rule1, rule2, rule3, rule4, ... ] return all([r(solution) for f in rules]) ... but then I realized that since the list comprehension is generated before the all() function is evaluated, that this has the side effect of not being short-circuited at all - every rule will be evaluated even if the first returns False. So my question is: is there a more Pythonic/functional way to be able to evaluate a list of True/False expressions, with short-circuiting, without the need to write out a long list of return f1(s) and f2(s) and f3(s) ... ? A: Use a generator expression: rules = [ rule1, rule2, rule3, rule4, ... ] rules_generator = ( r( solution ) for r in rules ) return all( rules_generator ) Syntactic sugar: you can omit the extra parentheses: rules = [ rule1, rule2, rule3, rule4, ... ] return all( r( solution ) for r in rules ) A generator is (basically) an object with a .next() method, which returns the next item in some iterable. This means they can do useful things like read a file in chunks without loading it all into memory, or iterate up to huge integers. You can iterate over them with for loops transparently; Python handles it behind-the-scenes. For instance, range is a generator in Py3k. You can roll your own custom generator expressions by using the yield statement instead of return in a function definition: def integers(): i = 0 while True: yield i and Python will handle saving the function's state and so on. They're awesome!
Is there a Python idiom for evaluating a list of functions/expressions with short-circuiting?
I wrote a simple script to solve a "logic puzzle", the type of puzzle from school where you are given a number of rules and then must be able to find the solution for problems like "There are five musicians named A, B, C, D, and E playing in a concert, each plays one after the other... if A goes before B, and D is not last ... what is the order of who plays when?" etc. To evaluate possible solutions, I wrote each "rule" as a separate function which would evaluate if a possible solution (represented simply as a list of strings) is valid, for example #Fifth slot must be B or D def rule1(solution): return solution[4] == 'B' or solution[4] == 'D' #There must be at least two spots between A and B def rule2(solution): returns abs(solution.index('A') - solution.index('B')) >= 2 #etc... I'm interested in finding the Pythonic way to test if a possible solution passes all such rules, with the ability to stop evaluating rules after the first has failed. At first I wrote the simplest possible thing: def is_valid(solution): return rule1(solution) and rule2(solution) and rule3(solution) and ... But this seemed rather ugly. I thought perhaps I could make this read a bit more elegant with something like a list comprehension... def is_valid(solution) rules = [rule1, rule2, rule3, rule4, ... ] return all([r(solution) for f in rules]) ... but then I realized that since the list comprehension is generated before the all() function is evaluated, that this has the side effect of not being short-circuited at all - every rule will be evaluated even if the first returns False. So my question is: is there a more Pythonic/functional way to be able to evaluate a list of True/False expressions, with short-circuiting, without the need to write out a long list of return f1(s) and f2(s) and f3(s) ... ?
[ "Use a generator expression:\nrules = [ rule1, rule2, rule3, rule4, ... ]\nrules_generator = ( r( solution ) for r in rules )\nreturn all( rules_generator )\n\nSyntactic sugar: you can omit the extra parentheses: \nrules = [ rule1, rule2, rule3, rule4, ... ]\nreturn all( r( solution ) for r in rules )\n\nA generato...
[ 13 ]
[]
[]
[ "functional_programming", "list_comprehension", "python", "short_circuiting" ]
stackoverflow_0003405794_functional_programming_list_comprehension_python_short_circuiting.txt
Q: Django - Limit users who view the items My Models: class PromoNotification(models.Model): title = models.CharField(_('Title'), max_length=200) content = models.TextField(_('Content')) users = models.ManyToManyField(User, blank=True, null=True) groups = models.ManyToManyField(Group, blank=True, null=True) I want to publish there items to templates with some permissions. The template is only show the notifications for users who are in list (users or/and group). What should I do? Thank you for any help. Please show me some codes if you can. A: You might use a custom manager, which makes it easier to do this user filtering in multiple views. class PromoNotificationManager(models.Manager): def get_for_user(self, user) """Retrieve the notifications that are visible to the specified user""" # untested, but should be close to what you need notifications = super(PromoNotificationManager, self).get_query_set() user_filter = Q(groups__in=user.groups.all()) group_filter = Q(users__in=user.groups.all()) return notifications.filter(user_filter | group_filter) Hook up the manager to your PromoNotification model: class PromoNotification(models.Model): ... objects = PromoNotificationManager() Then in your view: def some_view(self): user_notifications = PromoNotification.objects.get_for_user(request.user) You can read more about custom managers in the docs: http://www.djangoproject.com/documentation/models/custom_managers/
Django - Limit users who view the items
My Models: class PromoNotification(models.Model): title = models.CharField(_('Title'), max_length=200) content = models.TextField(_('Content')) users = models.ManyToManyField(User, blank=True, null=True) groups = models.ManyToManyField(Group, blank=True, null=True) I want to publish there items to templates with some permissions. The template is only show the notifications for users who are in list (users or/and group). What should I do? Thank you for any help. Please show me some codes if you can.
[ "You might use a custom manager, which makes it easier to do this user filtering in multiple views.\nclass PromoNotificationManager(models.Manager):\n def get_for_user(self, user)\n \"\"\"Retrieve the notifications that are visible to the specified user\"\"\"\n # untested, but should be close to wh...
[ 4 ]
[]
[]
[ "django", "django_models", "django_templates", "python" ]
stackoverflow_0003404843_django_django_models_django_templates_python.txt
Q: Django from Java developer perspective I'm a long time Java programmer and I'm digging into Django recently to see what it offers. It looks to me that Django doesn't fit Java web developers taste. I mean in MVC Java web frameworks we have usually a controller class that receives the request, do the logic and then forwards the request to another destination. Rails also follows this paradigm. Django on the other hand looks a little bit procedural, you map requests in a file, write your handlers in another, write your domain classes in another ... So, I think Rails suits Java web developers taste and Django suits PHP folks. If you are a Java web developer, how do you see Django? Are you a Java programmer that is happy using Django? (I'm not underestimating Django, Django framework is unquestionable). A: Django on the other hand looks a little bit procedural, you map requests in a file, write your handlers in another, write your domain classes in another ... As a Java developer, how is this any different than a traditional Java MVC pattern? It's just different names: Django uses "view" for what is traditionally (in Java-land) called a Controller, "template" for View, etc. Don't you have domain classes in your Java application as well? In Java-land, when you have an MVC webapp, you have the same sort of splitting of logic: You write the request-handling logic in your Controller You represent the "domain" in your Model/domain classes You write the display logic in your view templates/classes I'm having a hard time understanding what you think is different about Django beyond the names.
Django from Java developer perspective
I'm a long time Java programmer and I'm digging into Django recently to see what it offers. It looks to me that Django doesn't fit Java web developers taste. I mean in MVC Java web frameworks we have usually a controller class that receives the request, do the logic and then forwards the request to another destination. Rails also follows this paradigm. Django on the other hand looks a little bit procedural, you map requests in a file, write your handlers in another, write your domain classes in another ... So, I think Rails suits Java web developers taste and Django suits PHP folks. If you are a Java web developer, how do you see Django? Are you a Java programmer that is happy using Django? (I'm not underestimating Django, Django framework is unquestionable).
[ "\nDjango on the other hand looks a little bit procedural, you map requests in a file, write your handlers in another, write your domain classes in another ...\n\nAs a Java developer, how is this any different than a traditional Java MVC pattern? It's just different names: Django uses \"view\" for what is tradition...
[ 4 ]
[]
[]
[ "django", "java", "python" ]
stackoverflow_0003405626_django_java_python.txt
Q: wx.TextCtrl and wx.Validator I need to validate the textboxes with wx.Textvalidator. Any please help me to do this? How can i use wx.FILTER_ALPHA with validators and if the user is giving a wrong input how can i give them a message? i need to validate all the inputs when clicking on the save button? can any one provide me a sample code for this? A: This is a feature of wxWidgets, and is not implemented in wxPython. http://www.wxpython.org/docs/api/wx.TextValidator-class.html - not found while: http://docs.wxwidgets.org/trunk/classwx_text_validator.html http://docs.wxwidgets.org/stable/wx_wxtextvalidator.html There is a demo of the Validators in the wxPython demo: import wx class TextObjectValidator(wx.PyValidator): """ This validator is used to ensure that the user has entered something into the text object editor dialog's text field. """ def __init__(self): """ Standard constructor. """ wx.PyValidator.__init__(self) def Clone(self): """ Standard cloner. Note that every validator must implement the Clone() method. """ return TextObjectValidator() def Validate(self, win): """ Validate the contents of the given text control. """ textCtrl = self.GetWindow() text = textCtrl.GetValue() if len(text) == 0: wx.MessageBox("A text object must contain some text!", "Error") textCtrl.SetBackgroundColour("pink") textCtrl.SetFocus() textCtrl.Refresh() return False else: textCtrl.SetBackgroundColour( wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)) textCtrl.Refresh() return True def TransferToWindow(self): """ Transfer data from validator to window. The default implementation returns False, indicating that an error occurred. We simply return True, as we don't do any data transfer. """ return True # Prevent wxDialog from complaining. def TransferFromWindow(self): """ Transfer data from window to validator. The default implementation returns False, indicating that an error occurred. We simply return True, as we don't do any data transfer. """ return True # Prevent wxDialog from complaining. #---------------------------------------------------------------------- class TestValidateDialog(wx.Dialog): def __init__(self, parent): wx.Dialog.__init__(self, parent, -1, "Validated Dialog") self.SetAutoLayout(True) VSPACE = 10 fgs = wx.FlexGridSizer(0, 2) fgs.Add((1,1)); fgs.Add(wx.StaticText(self, -1, "These controls must have text entered into them. Each\n" "one has a validator that is checked when the Okay\n" "button is clicked.")) fgs.Add((1,VSPACE)); fgs.Add((1,VSPACE)) label = wx.StaticText(self, -1, "First: ") fgs.Add(label, 0, wx.ALIGN_RIGHT|wx.CENTER) fgs.Add(wx.TextCtrl(self, -1, "", validator = TextObjectValidator())) fgs.Add((1,VSPACE)); fgs.Add((1,VSPACE)) label = wx.StaticText(self, -1, "Second: ") fgs.Add(label, 0, wx.ALIGN_RIGHT|wx.CENTER) fgs.Add(wx.TextCtrl(self, -1, "", validator = TextObjectValidator())) buttons = wx.StdDialogButtonSizer() #wx.BoxSizer(wx.HORIZONTAL) b = wx.Button(self, wx.ID_OK, "OK") b.SetDefault() buttons.AddButton(b) buttons.AddButton(wx.Button(self, wx.ID_CANCEL, "Cancel")) buttons.Realize() border = wx.BoxSizer(wx.VERTICAL) border.Add(fgs, 1, wx.GROW|wx.ALL, 25) border.Add(buttons) self.SetSizer(border) border.Fit(self) self.Layout() app = wx.App(redirect=False) f = wx.Frame(parent=None) f.Show() dlg = TestValidateDialog(f) dlg.ShowModal() dlg.Destroy() app.MainLoop() A: There are lots of ways to do this. The wxPython demo actually shows how to allow only digits or only alpha. Here's an example based on that: import wx import string ######################################################################## class CharValidator(wx.PyValidator): ''' Validates data as it is entered into the text controls. ''' #---------------------------------------------------------------------- def __init__(self, flag): wx.PyValidator.__init__(self) self.flag = flag self.Bind(wx.EVT_CHAR, self.OnChar) #---------------------------------------------------------------------- def Clone(self): '''Required Validator method''' return CharValidator(self.flag) #---------------------------------------------------------------------- def Validate(self, win): return True #---------------------------------------------------------------------- def TransferToWindow(self): return True #---------------------------------------------------------------------- def TransferFromWindow(self): return True #---------------------------------------------------------------------- def OnChar(self, event): keycode = int(event.GetKeyCode()) if keycode < 256: #print keycode key = chr(keycode) #print key if self.flag == 'no-alpha' and key in string.letters: return if self.flag == 'no-digit' and key in string.digits: return event.Skip() ######################################################################## class ValidationDemo(wx.Frame): """""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" wx.Frame.__init__(self, None, wx.ID_ANY, "Text Validation Tutorial") panel = wx.Panel(self) textOne = wx.TextCtrl(panel, validator=CharValidator('no-alpha')) textTwo = wx.TextCtrl(panel, validator=CharValidator('no-digit')) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(textOne, 0, wx.ALL, 5) sizer.Add(textTwo, 0, wx.ALL, 5) panel.SetSizer(sizer) # Run the program if __name__ == "__main__": app = wx.App(False) frame = ValidationDemo() frame.Show() app.MainLoop() An alternative approach would be to use Masked controls using wx.lib.masked. The wxPython demo has examples of this as well. A: The problem is probably thast you have the ctrl in a panel within the dialog. Set the recursive flag on the dialog to enable validation code to look for controls with validators recursively: self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY) A: I was unable to make the sample code work properly within my code (not using a dialog at all but a txtctrl within a panel), even though it works correctly in the demo (go figure). I ended up using a snippet from another site and feel obligated to document it here: self.tc.GetValidator().Validate(self.tc) This was the only way that I could get my custom validator code to be called. Calling self.tc.Validate() did not work at all nor did self.Validate(), nor either representation passing the window in as a parameter. reference: link text
wx.TextCtrl and wx.Validator
I need to validate the textboxes with wx.Textvalidator. Any please help me to do this? How can i use wx.FILTER_ALPHA with validators and if the user is giving a wrong input how can i give them a message? i need to validate all the inputs when clicking on the save button? can any one provide me a sample code for this?
[ "This is a feature of wxWidgets, and is not implemented in wxPython.\nhttp://www.wxpython.org/docs/api/wx.TextValidator-class.html - not found\nwhile:\nhttp://docs.wxwidgets.org/trunk/classwx_text_validator.html\nhttp://docs.wxwidgets.org/stable/wx_wxtextvalidator.html\nThere is a demo of the Validators in the wxPy...
[ 5, 4, 2, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002198903_python_wxpython.txt
Q: List web url dir contents I wanna list a external webpage's ulr's content. like i wanna list the content of this website example.com/dir/dir/images/ currently i can download an image from a page with: urllib.urlretrieve(page_url,save_url ) But I want to list all images in a directory, or anything ells for that matter I wanna use python A: Unfortunately this can only work if the web server in question will serve you a directory listing when you navigate to that directory's URI. If it does, typical directory listings have very simple markup, making them a prime candidate for various forms of web scraping. Otherwise, you're out of luck.
List web url dir contents
I wanna list a external webpage's ulr's content. like i wanna list the content of this website example.com/dir/dir/images/ currently i can download an image from a page with: urllib.urlretrieve(page_url,save_url ) But I want to list all images in a directory, or anything ells for that matter I wanna use python
[ "Unfortunately this can only work if the web server in question will serve you a directory listing when you navigate to that directory's URI.\nIf it does, typical directory listings have very simple markup, making them a prime candidate for various forms of web scraping. Otherwise, you're out of luck.\n" ]
[ 2 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0003405953_python_urllib.txt
Q: A thread pool that lets me know when at least 1 has finished? I need to use a thread pool in python, and I want to be able to know when at least 1 thead out or "maximum threads allowed" has finished, so I can start it again if I still need to do something. I has been using something like this: def doSomethingWith(dataforthread): dostuff() i = i-1 #thread has finished i = 0 poolSize = 5 threads = [] data = #array of data while len(data): while True: if i<poolSize: #if started threads is < poolSize start new thread dataforthread = data.pop(0) i = i+1 thread = doSomethingWith(dataforthread) thread.start() threads.append(thread) else: break for t in threads: #wait for ALL threads (I ONLY WANT TO WAIT FOR 1 [any]) t.join() As I understand, my code opens 5 threads, and then waits for all the threads to finish before starting new threads, until data is consumed. But what I really want to do is start a new thread as soon as one of the threads finish and the pool has an "available spot" for a new thread. I have been reading this, but I think that would have the same issue than my code (not sure, im new to python but by looking at joinAll() it looks like that). Does someone has an example to do what I am trying to achieve? I mean detecting as soon as i is < than poolSize, launching new threads until i=poolSize and do that until data is consumed. A: As the article author mentions, and @getekha highlights, thread pools in Python don't accomplish exactly the same thing as they do in other languages. If you need parallelism, you should look into the multiprocessing module. Among other things, it has these handy Queue and Pool constructs. Also, there's an accepted PEP for "futures" that you'll probably want to monitor. A: The problem is that Python has a Global Interpreter Lock, which must be held to run any Python code. This means that only one thread can execute Python code at any time, so thread pools in Python are not the same as in other languages. This is mainly for arcane reasons known only to a select few (i.e. it's complicated). If you really want to run code asynchronously, you should spawn new Processes; the multiprocesssing module has a Pool class which you could look into.
A thread pool that lets me know when at least 1 has finished?
I need to use a thread pool in python, and I want to be able to know when at least 1 thead out or "maximum threads allowed" has finished, so I can start it again if I still need to do something. I has been using something like this: def doSomethingWith(dataforthread): dostuff() i = i-1 #thread has finished i = 0 poolSize = 5 threads = [] data = #array of data while len(data): while True: if i<poolSize: #if started threads is < poolSize start new thread dataforthread = data.pop(0) i = i+1 thread = doSomethingWith(dataforthread) thread.start() threads.append(thread) else: break for t in threads: #wait for ALL threads (I ONLY WANT TO WAIT FOR 1 [any]) t.join() As I understand, my code opens 5 threads, and then waits for all the threads to finish before starting new threads, until data is consumed. But what I really want to do is start a new thread as soon as one of the threads finish and the pool has an "available spot" for a new thread. I have been reading this, but I think that would have the same issue than my code (not sure, im new to python but by looking at joinAll() it looks like that). Does someone has an example to do what I am trying to achieve? I mean detecting as soon as i is < than poolSize, launching new threads until i=poolSize and do that until data is consumed.
[ "As the article author mentions, and @getekha highlights, thread pools in Python don't accomplish exactly the same thing as they do in other languages. If you need parallelism, you should look into the multiprocessing module. Among other things, it has these handy Queue and Pool constructs. Also, there's an accepte...
[ 2, 1 ]
[]
[]
[ "multithreading", "python", "threadpool" ]
stackoverflow_0003405840_multithreading_python_threadpool.txt
Q: Twisted Web Proxy I have been running this code (from: http://blog.somethingaboutcode.com/?p=155 ): from twisted.internet import reactor from twisted.web import http from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient from ImageFile import Parser from StringIO import StringIO class InterceptingProxyClient(ProxyClient): def __init__(self, *args, **kwargs): ProxyClient.__init__(self, *args, **kwargs) self.image_parser = None def handleHeader(self, key, value): if key == "Content-Type" and value in ["image/jpeg", "image/gif", "image/png"]: self.image_parser = Parser() if key == "Content-Length" and self.image_parser: pass else: ProxyClient.handleHeader(self, key, value) def handleEndHeaders(self): if self.image_parser: pass #Need to calculate and send Content-Length first else: ProxyClient.handleEndHeaders(self) def handleResponsePart(self, buffer): print buffer if self.image_parser: self.image_parser.feed(buffer) else: ProxyClient.handleResponsePart(self, buffer) def handleResponseEnd(self): if self.image_parser: image = self.image_parser.close() try: format = image.format image = image.rotate(180) s = StringIO() image.save(s, format) buffer = s.getvalue() except: buffer = "" ProxyClient.handleHeader(self, "Content-Length", len(buffer)) ProxyClient.handleEndHeaders(self) ProxyClient.handleResponsePart(self, buffer) ProxyClient.handleResponseEnd(self) class InterceptingProxyClientFactory(ProxyClientFactory): protocol = InterceptingProxyClient class InterceptingProxyRequest(ProxyRequest): protocols = {'http': InterceptingProxyClientFactory} ports = {"http" : 80} class InterceptingProxy(Proxy): requestFactory = InterceptingProxyRequest factory = http.HTTPFactory() factory.protocol = InterceptingProxy reactor.listenTCP(8000, factory) reactor.run() Whenever I get this and go to 127.0.0.1:8000 I get this: Traceback (most recent call last): File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 84, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 69, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.p y", line 59, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.p y", line 37, in callWithContext return func(*args,**kw) --- <exception caught here> --- File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\selectr eactor.py", line 146, in _doReadOrWrite why = getattr(selectable, method)() File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\tcp.py" , line 460, in doRead return self.protocol.dataReceived(data) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\protocols\basic. py", line 251, in dataReceived why = self.lineReceived(line) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", li ne 1573, in lineReceived self.allContentReceived() File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", li ne 1641, in allContentReceived req.requestReceived(command, path, version) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", li ne 807, in requestReceived self.process() File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\proxy.py", l ine 147, in process port = self.ports[protocol] exceptions.KeyError: '' Whenever I setup firefox or chrome or opera to use the proxy on localhost:8000 there are no connections made to the proxy (and I can no longer connect to any page, though that is probably because it isn't connection to the proxy). Ok it still fails and with logging I get this output when I set firefox to use the proxy at localhost:8000 and don't visit the proxy directly from the web browser (such as by typing localhost:8000 in firefox's address bar) 2010-08-04 12:31:18-0400 [-] Log opened. 2010-08-04 12:31:29-0400 [-] twisted.web.http.HTTPFactory starting on 8000 2010-08-04 12:31:29-0400 [-] Starting factory <twisted.web.http.HTTPFactory inst ance at 0x010B3EE0> 2010-08-04 12:33:55-0400 [-] Received SIGINT, shutting down. 2010-08-04 12:33:55-0400 [twisted.web.http.HTTPFactory] (Port 8000 Closed) 2010-08-04 12:33:55-0400 [twisted.web.http.HTTPFactory] Stopping factory <twiste d.web.http.HTTPFactory instance at 0x010B3EE0> 2010-08-04 12:33:55-0400 [-] Main loop terminated. However when I do visit the proxy directly I get the key error. Also for sniffing I can't; Wireshark doesn't seem to sniff the localhost traffic and if I use fiddler 2 it sets itself as the proxy (and so I am no longer using my proxy server) and then works (because it uses fiddler 2's proxy). A: The KeyError exception you see when you connect directly is caused by the fact that requests to a proxy must include an absolute URL, not a relative one. If your browser doesn't know it's talking to a proxy, it will request a URL like /foo/bar. If it does know it is talking to a proxy, it will instead request something like http://example.com/foo/bar. The http://example.com/ part is important because it's the only way the proxy knows what it's supposed to go off and retrieve. As for why none of Firefox, Chrome, nor Opera will connect to the proxy once you configure them to do so, that's a little bit harder to explain. Make sure you're configuring an "HTTP Proxy", not any of the other kinds of proxy supported. Once you've double checked that, you might want to use a tool like Wireshark to get a better look at what's happening on the network layer. It's possible that the connections are really being made to the proxy but something else is going wrong that prevents them from completing. In this case, without logging enabled, you might not be able to tell that the proxy is receiving connections simply by looking at its output. To enable logging, try: from sys import stdout from twisted.python.log import startLogging startLogging(stdout)
Twisted Web Proxy
I have been running this code (from: http://blog.somethingaboutcode.com/?p=155 ): from twisted.internet import reactor from twisted.web import http from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient from ImageFile import Parser from StringIO import StringIO class InterceptingProxyClient(ProxyClient): def __init__(self, *args, **kwargs): ProxyClient.__init__(self, *args, **kwargs) self.image_parser = None def handleHeader(self, key, value): if key == "Content-Type" and value in ["image/jpeg", "image/gif", "image/png"]: self.image_parser = Parser() if key == "Content-Length" and self.image_parser: pass else: ProxyClient.handleHeader(self, key, value) def handleEndHeaders(self): if self.image_parser: pass #Need to calculate and send Content-Length first else: ProxyClient.handleEndHeaders(self) def handleResponsePart(self, buffer): print buffer if self.image_parser: self.image_parser.feed(buffer) else: ProxyClient.handleResponsePart(self, buffer) def handleResponseEnd(self): if self.image_parser: image = self.image_parser.close() try: format = image.format image = image.rotate(180) s = StringIO() image.save(s, format) buffer = s.getvalue() except: buffer = "" ProxyClient.handleHeader(self, "Content-Length", len(buffer)) ProxyClient.handleEndHeaders(self) ProxyClient.handleResponsePart(self, buffer) ProxyClient.handleResponseEnd(self) class InterceptingProxyClientFactory(ProxyClientFactory): protocol = InterceptingProxyClient class InterceptingProxyRequest(ProxyRequest): protocols = {'http': InterceptingProxyClientFactory} ports = {"http" : 80} class InterceptingProxy(Proxy): requestFactory = InterceptingProxyRequest factory = http.HTTPFactory() factory.protocol = InterceptingProxy reactor.listenTCP(8000, factory) reactor.run() Whenever I get this and go to 127.0.0.1:8000 I get this: Traceback (most recent call last): File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 84, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\log.py", line 69, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.p y", line 59, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\python\context.p y", line 37, in callWithContext return func(*args,**kw) --- <exception caught here> --- File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\selectr eactor.py", line 146, in _doReadOrWrite why = getattr(selectable, method)() File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\internet\tcp.py" , line 460, in doRead return self.protocol.dataReceived(data) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\protocols\basic. py", line 251, in dataReceived why = self.lineReceived(line) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", li ne 1573, in lineReceived self.allContentReceived() File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", li ne 1641, in allContentReceived req.requestReceived(command, path, version) File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\http.py", li ne 807, in requestReceived self.process() File "C:\Program Files\Python 2.6.2\lib\site-packages\twisted\web\proxy.py", l ine 147, in process port = self.ports[protocol] exceptions.KeyError: '' Whenever I setup firefox or chrome or opera to use the proxy on localhost:8000 there are no connections made to the proxy (and I can no longer connect to any page, though that is probably because it isn't connection to the proxy). Ok it still fails and with logging I get this output when I set firefox to use the proxy at localhost:8000 and don't visit the proxy directly from the web browser (such as by typing localhost:8000 in firefox's address bar) 2010-08-04 12:31:18-0400 [-] Log opened. 2010-08-04 12:31:29-0400 [-] twisted.web.http.HTTPFactory starting on 8000 2010-08-04 12:31:29-0400 [-] Starting factory <twisted.web.http.HTTPFactory inst ance at 0x010B3EE0> 2010-08-04 12:33:55-0400 [-] Received SIGINT, shutting down. 2010-08-04 12:33:55-0400 [twisted.web.http.HTTPFactory] (Port 8000 Closed) 2010-08-04 12:33:55-0400 [twisted.web.http.HTTPFactory] Stopping factory <twiste d.web.http.HTTPFactory instance at 0x010B3EE0> 2010-08-04 12:33:55-0400 [-] Main loop terminated. However when I do visit the proxy directly I get the key error. Also for sniffing I can't; Wireshark doesn't seem to sniff the localhost traffic and if I use fiddler 2 it sets itself as the proxy (and so I am no longer using my proxy server) and then works (because it uses fiddler 2's proxy).
[ "The KeyError exception you see when you connect directly is caused by the fact that requests to a proxy must include an absolute URL, not a relative one. If your browser doesn't know it's talking to a proxy, it will request a URL like /foo/bar. If it does know it is talking to a proxy, it will instead request so...
[ 1 ]
[]
[]
[ "python", "twisted", "twisted.web" ]
stackoverflow_0003402694_python_twisted_twisted.web.txt
Q: Pattern matching using python In the code below how match the pattern after "answer" and "nonanswer" in the dictionary opt_dict=( {'answer1':1, 'answer14':1, 'answer13':12, 'answer11':6, 'answer5':5, 'nonanswer12':1, 'nonanswer11':1, 'nonanswer4':1, 'nonanswer5':1,}) And if opt_dict: for ii in opt_dict: logging.debug(ii) logging.debug(opt_dict[ii]) if ii in "nonanswer": logging.debug(opt_dict[ii]) elif ii in "answer": logging.debug("answer founddddddddddddddddddddddddddddddd") logging.debug(opt_dict[ii]) else: logging.debug("empty dict") A: I didn't keep all your logging, but this should work: if opt_dict: for key, value in opt_dict.items(): if "nonanswer" in key: print "nonanswer", value elif "answer" in key: print "answer", value else: raise Exception( "invalid key" ) else: print "empty dict" A: I'm pretty sure you have your in tests reversed. The data has the form answer1, which will never be in the literal answer. Try "answer" in ii instead. To be more specific, you can use the startswith method, since all your data (at least in this example) actually starts with answer or nonanswer, and you might not want to match something of the form 34argleanswer.
Pattern matching using python
In the code below how match the pattern after "answer" and "nonanswer" in the dictionary opt_dict=( {'answer1':1, 'answer14':1, 'answer13':12, 'answer11':6, 'answer5':5, 'nonanswer12':1, 'nonanswer11':1, 'nonanswer4':1, 'nonanswer5':1,}) And if opt_dict: for ii in opt_dict: logging.debug(ii) logging.debug(opt_dict[ii]) if ii in "nonanswer": logging.debug(opt_dict[ii]) elif ii in "answer": logging.debug("answer founddddddddddddddddddddddddddddddd") logging.debug(opt_dict[ii]) else: logging.debug("empty dict")
[ "I didn't keep all your logging, but this should work:\nif opt_dict:\n for key, value in opt_dict.items():\n if \"nonanswer\" in key:\n print \"nonanswer\", value\n elif \"answer\" in key:\n print \"answer\", value\n else:\n raise Exception( \"invalid key\" )...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003406034_python.txt
Q: How to understand the sample from python minimock? How to understand this line? >>> smtplib.SMTP.mock_returns = Mock('smtp_connection')? What is smtp_connection? It seems I can modify it to any name. following is from minimock Here's an example of something we might test, a simple email sender:: >>> import smtplib >>> def send_email(from_addr, to_addr, subject, body): ... conn = smtplib.SMTP('localhost') ... msg = 'To: %s\nFrom: %s\nSubject: %s\n\n%s' % ( ... to_addr, from_addr, subject, body) ... conn.sendmail(from_addr, [to_addr], msg) ... conn.quit() Now we want to make a mock smtplib.SMTP object. We'll have to inject our mock into the smtplib module:: >>> smtplib.SMTP = Mock('smtplib.SMTP') >>> smtplib.SMTP.mock_returns = Mock('smtp_connection') Now we do the test:: >>> send_email('ianb@colorstudy.com', 'joe@example.com', ... 'Hi there!', 'How is it going?') Called smtplib.SMTP('localhost') Called smtp_connection.sendmail( 'ianb@colorstudy.com', ['joe@example.com'], 'To: joe@example.com\nFrom: ianb@colorstudy.com\nSubject: Hi there!\n\nHow is it going?') Called smtp_connection.quit() A: If you read the rest of the docs you'll see the following: Mock objects have several attributes, all of which you can set when instantiating the object. To avoid name collision, all the attributes start with mock_, while the constructor arguments don't. name: The name of the object, used when printing out messages. In the example about it was 'smtplib.SMTP'. It's the name of the connection, used e.g. in: Called smtp_connection.sendmail( 'ianb@colorstudy.com', ['joe@example.com'], 'To: joe@example.com\nFrom: ianb@colorstudy.com\nSubject: Hi there!\n\nHow is it going?') Called smtp_connection.quit()
How to understand the sample from python minimock?
How to understand this line? >>> smtplib.SMTP.mock_returns = Mock('smtp_connection')? What is smtp_connection? It seems I can modify it to any name. following is from minimock Here's an example of something we might test, a simple email sender:: >>> import smtplib >>> def send_email(from_addr, to_addr, subject, body): ... conn = smtplib.SMTP('localhost') ... msg = 'To: %s\nFrom: %s\nSubject: %s\n\n%s' % ( ... to_addr, from_addr, subject, body) ... conn.sendmail(from_addr, [to_addr], msg) ... conn.quit() Now we want to make a mock smtplib.SMTP object. We'll have to inject our mock into the smtplib module:: >>> smtplib.SMTP = Mock('smtplib.SMTP') >>> smtplib.SMTP.mock_returns = Mock('smtp_connection') Now we do the test:: >>> send_email('ianb@colorstudy.com', 'joe@example.com', ... 'Hi there!', 'How is it going?') Called smtplib.SMTP('localhost') Called smtp_connection.sendmail( 'ianb@colorstudy.com', ['joe@example.com'], 'To: joe@example.com\nFrom: ianb@colorstudy.com\nSubject: Hi there!\n\nHow is it going?') Called smtp_connection.quit()
[ "If you read the rest of the docs you'll see the following:\n\nMock objects have several attributes,\n all of which you can set when\n instantiating the object. To avoid\n name collision, all the attributes\n start with mock_, while the\n constructor arguments don't.\nname:\n The name of the object, used ...
[ 2 ]
[]
[]
[ "mocking", "python" ]
stackoverflow_0003406068_mocking_python.txt
Q: Iteration order of sets in Python If I have two identical sets, meaning a == b gives me True, will they have the same iteration order? I tried it, and it works: >>> foo = set("abc") >>> bar = set("abc") >>> zip(foo, bar) [('a', 'a'), ('c', 'c'), ('b', 'b')] My question is, was I lucky, or is this behavior guaranteed? A: It wasn't just a coincidence that they came out the same: the implementation happens to be deterministic, so creating the same set twice produces the same ordering. But Python does not guarantee that. If you create the same set in two different ways: n = set("abc") print n m = set("kabc") m.remove("k") print m ...you can get different ordering: set(['a', 'c', 'b']) set(['a', 'b', 'c']) A: You were lucky, the order is not guaranteed. The only thing that's guaranteed is that the sets will have the same elements. If you need some sort of predictability, you could sort them like this: zip(sorted(foo), sorted(bar)). A: No.: >>> class MyStr( str ): ... def __hash__( self ): ... return 0 ... >>> a = MyStr( "a" ) >>> b = MyStr( "b" ) >>> c = MyStr( "c" ) >>> foo = { a, b, c } >>> foo {'c', 'b', 'a'} >>> bar = { b, a, c } >>> foo is bar False >>> foo == bar True >>> list( zip( foo, bar ) ) [('c', 'c'), ('b', 'a'), ('a', 'b')] P.S. I have no idea if the __hash__ override is necessary. I just tried something I thought would break this, and it did. A: Yes, you were lucky. See for example: import random r = [random.randint(1,10000) for i in range(20)] foo = set(r) r.sort(key=lambda _: random.randint(1,10000)) bar = set(r) print foo==bar print zip(foo, bar) Which gave me the result: True [(3234, 3234), (9393, 9393), (9361, 1097), (1097, 5994), (5994, 2044), (1614, 1614), (6074, 4377), (4377, 9361), (5202, 5202), (2355, 2355), (1012, 1012), (7349, 7349), (6198, 6198), (8489, 8489), (7929, 7929), (6556, 6074), (6971, 6971), (2044, 6556), (7133, 7133), (383, 383)] A: I'd say you got lucky. Though, it might also be that, since the elements in the set were the same, they were stored in the same order. This behavior is not something you'd want to rely on.
Iteration order of sets in Python
If I have two identical sets, meaning a == b gives me True, will they have the same iteration order? I tried it, and it works: >>> foo = set("abc") >>> bar = set("abc") >>> zip(foo, bar) [('a', 'a'), ('c', 'c'), ('b', 'b')] My question is, was I lucky, or is this behavior guaranteed?
[ "It wasn't just a coincidence that they came out the same: the implementation happens to be deterministic, so creating the same set twice produces the same ordering. But Python does not guarantee that.\nIf you create the same set in two different ways:\nn = set(\"abc\")\nprint n\n\nm = set(\"kabc\")\nm.remove(\"k\"...
[ 21, 4, 4, 1, 0 ]
[]
[]
[ "iteration", "python", "set" ]
stackoverflow_0003406341_iteration_python_set.txt
Q: How to make python window run as "Always On Top"? I am running a little program in python that launches a small window that needs to stay on top of all the other windows. I believe this is OS specific, how is it done in GNU-Linux with GNOME? [Update - Solution for Windows] Lovely, I think I got it working. I am using Python 2.5.4 with Pygame 1.9.1 in Eclipse on Vista 64-bit. Thus, this is for windows systems. The SetWindowPos function is documented Here. I will refer to this in my explanation. Imports: from ctypes import windll Then I set up a variable that calls the "SetWindowPos" in user32: SetWindowPos = windll.user32.SetWindowPos Now, let's say I just made a window: screen = pygame.display.set_mode((100,100), pygame.NOFRAME) The next line is the key. This sets the window to be on top of other windows. SetWindowPos(pygame.display.get_wm_info()['window'], -1, x, y, 0, 0, 0x0001) Basically, You supply the hWnd(Window Handle) with the window ID returned from a call to display.get_wm_info(). Now the function can edit the window you just initialized. The -1 is our hWndInsertAfter. The MSDN site says: A window can be made a topmost window either by setting the hWndInsertAfter parameter to HWND_TOPMOST and ensuring that the SWP_NOZORDER flag is not set, or by setting a window's position in the Z order so that it is above any existing topmost windows. When a non-topmost window is made topmost, its owned windows are also made topmost. Its owners, however, are not changed. So, the -1 makes sure the window is above any other existing topmost windows, but this may not work in all cases. Maybe a -2 beats a -1? It currently works for me. :) The x and y specify the new coordinates for the window being set. I wanted the window to stay at its current position when the SetWindowPos function was called on it. Alas, I couldn't find a way to easily pass the current window (x,y) position into the function. I was able to find a work around, but assume I shouldn't introduce a new topic into this question. The 0, 0, are supposed to specify the new width and height of the window, in pixels. Well, that functionality is already in your pygame.display.set_mode() function, so I left them at 0. The 0x0001 ignores these parameters. 0x0001 corresponds to SWP_NOSIZE and is my only uFlag. A list of all the available uFlags are on the provided documentation page. Some of their Hex representations are as follows: SWP_NOSIZE = 0x0001 SWP_NOMOVE = 0x0002 SWP_NOZORDER = 0x0004 SWP_NOREDRAW = 0x0008 SWP_NOACTIVATE = 0x0010 SWP_FRAMECHANGED = 0x0020 SWP_SHOWWINDOW = 0x0040 SWP_HIDEWINDOW = 0x0080 SWP_NOCOPYBITS = 0x0100 SWP_NOOWNERZORDER = 0x0200 SWP_NOSENDCHANGING = 0x0400 That should be it! Hope it works for you! Credit to John Popplewell at john@johnnypops.demon.co.uk for his help. A: The question is more like which windowing toolkit are you using ? PyGTK and similar educated googling gave me this: gtk.Window.set_keep_above As mentioned previously it is upto the window manager to respect this setting or not. Edited to include SDL specific stuff Pygame uses SDL to do display work and apprently does not play nice with Windowing toolkits. SDL Window can be put on top is discussed here. A: I really don't know much Python at all, but Googling "pygtk always on top" gave me this: http://www.mail-archive.com/pygtk@daa.com.au/msg01370.html The solution posted there was: transient.set_transient_for(main_window) You might also want to search things like "x11 always on top". The underlying concept seems to be that you're giving the window manager a "hint" that it should keep the window above the others. The window manager, however, has free reign and can do whatever it wants. I've also seen the concept of layers when using window managers like Fluxbox, so maybe there's a way to change the layer on which the window appears. A: I was trying to figure out a similar issue and found this solution using the Pmw module http://www.java2s.com/Code/Python/GUI-Pmw/Showglobalmodaldialog.htm
How to make python window run as "Always On Top"?
I am running a little program in python that launches a small window that needs to stay on top of all the other windows. I believe this is OS specific, how is it done in GNU-Linux with GNOME? [Update - Solution for Windows] Lovely, I think I got it working. I am using Python 2.5.4 with Pygame 1.9.1 in Eclipse on Vista 64-bit. Thus, this is for windows systems. The SetWindowPos function is documented Here. I will refer to this in my explanation. Imports: from ctypes import windll Then I set up a variable that calls the "SetWindowPos" in user32: SetWindowPos = windll.user32.SetWindowPos Now, let's say I just made a window: screen = pygame.display.set_mode((100,100), pygame.NOFRAME) The next line is the key. This sets the window to be on top of other windows. SetWindowPos(pygame.display.get_wm_info()['window'], -1, x, y, 0, 0, 0x0001) Basically, You supply the hWnd(Window Handle) with the window ID returned from a call to display.get_wm_info(). Now the function can edit the window you just initialized. The -1 is our hWndInsertAfter. The MSDN site says: A window can be made a topmost window either by setting the hWndInsertAfter parameter to HWND_TOPMOST and ensuring that the SWP_NOZORDER flag is not set, or by setting a window's position in the Z order so that it is above any existing topmost windows. When a non-topmost window is made topmost, its owned windows are also made topmost. Its owners, however, are not changed. So, the -1 makes sure the window is above any other existing topmost windows, but this may not work in all cases. Maybe a -2 beats a -1? It currently works for me. :) The x and y specify the new coordinates for the window being set. I wanted the window to stay at its current position when the SetWindowPos function was called on it. Alas, I couldn't find a way to easily pass the current window (x,y) position into the function. I was able to find a work around, but assume I shouldn't introduce a new topic into this question. The 0, 0, are supposed to specify the new width and height of the window, in pixels. Well, that functionality is already in your pygame.display.set_mode() function, so I left them at 0. The 0x0001 ignores these parameters. 0x0001 corresponds to SWP_NOSIZE and is my only uFlag. A list of all the available uFlags are on the provided documentation page. Some of their Hex representations are as follows: SWP_NOSIZE = 0x0001 SWP_NOMOVE = 0x0002 SWP_NOZORDER = 0x0004 SWP_NOREDRAW = 0x0008 SWP_NOACTIVATE = 0x0010 SWP_FRAMECHANGED = 0x0020 SWP_SHOWWINDOW = 0x0040 SWP_HIDEWINDOW = 0x0080 SWP_NOCOPYBITS = 0x0100 SWP_NOOWNERZORDER = 0x0200 SWP_NOSENDCHANGING = 0x0400 That should be it! Hope it works for you! Credit to John Popplewell at john@johnnypops.demon.co.uk for his help.
[ "The question is more like which windowing toolkit are you using ? PyGTK and similar educated googling gave me this:\n\ngtk.Window.set_keep_above\n\nAs mentioned previously it is upto the window manager to respect this setting or not.\nEdited to include SDL specific stuff\nPygame uses SDL to do display work and app...
[ 8, 0, 0 ]
[]
[]
[ "always_on_top", "gnome", "linux", "pygame", "python" ]
stackoverflow_0001482565_always_on_top_gnome_linux_pygame_python.txt
Q: How to write a server using existing version and wireshark? I decided to improve my knowledge about python network programming and here is the deal: I have a simple server for Windows, which interacts with a client from a mobile device using wi-fi. Also I have a packet sniffer (Wireshark). Now I want to ask, what do I need to write the Linux version of this server? How to determine the structure of packets, establish the connection? What do I need to use - sockets, Twisted, maybe Tornado? A: Start with the SocketServer module and build from there. Note that this will take a lot of guesswork if there is no documentation about the protocol. If you're lucky, they are using XML or HTML. If not, you will have to make the existing server send a lot of test data which you have to manipulate in some way (by changing fields and see what changes in the data stream). Good luck!
How to write a server using existing version and wireshark?
I decided to improve my knowledge about python network programming and here is the deal: I have a simple server for Windows, which interacts with a client from a mobile device using wi-fi. Also I have a packet sniffer (Wireshark). Now I want to ask, what do I need to write the Linux version of this server? How to determine the structure of packets, establish the connection? What do I need to use - sockets, Twisted, maybe Tornado?
[ "Start with the SocketServer module and build from there.\nNote that this will take a lot of guesswork if there is no documentation about the protocol. If you're lucky, they are using XML or HTML. If not, you will have to make the existing server send a lot of test data which you have to manipulate in some way (by ...
[ 1 ]
[]
[]
[ "networking", "python", "tcp", "wireshark" ]
stackoverflow_0003406665_networking_python_tcp_wireshark.txt
Q: Python modules for visualization of C++ code I'm looking for python modules that can help with grepping C++ code. I have a large code base that I would like to do some analysis on. Ultimately I would like to come up with a graphical map of the software. There is lots of message passing going on amongst apps so I would like to be able to capture that information and present it visually. I have been looking around at some of the data visualization packages but have only stumbled on math and plotting related ones. What are the best tools for this job, preferably in python? A: Your best tool for the job is Graphviz. If you look at their gallery you'll find the sort of thing that you're interested in along with links to projects. Under the language bindings section here there are a few python entries. Personally I don't use them as the dot language format is simple enough that you can build up fairly complex graphs from Python just using print statements. A: You ca look at doxygen and see if it does (at least some part of) what you want. It generates call graph and class diagrams directly in html or xml format (I believe you need to have dot installed for fancy graphs).
Python modules for visualization of C++ code
I'm looking for python modules that can help with grepping C++ code. I have a large code base that I would like to do some analysis on. Ultimately I would like to come up with a graphical map of the software. There is lots of message passing going on amongst apps so I would like to be able to capture that information and present it visually. I have been looking around at some of the data visualization packages but have only stumbled on math and plotting related ones. What are the best tools for this job, preferably in python?
[ "Your best tool for the job is Graphviz. If you look at their gallery you'll find the sort of thing that you're interested in along with links to projects.\nUnder the language bindings section here there are a few python entries. Personally I don't use them as the dot language format is simple enough that you can b...
[ 1, 1 ]
[]
[]
[ "c++", "data_visualization", "grep", "python" ]
stackoverflow_0003405177_c++_data_visualization_grep_python.txt
Q: How to make a Django passthrough view? I want to make a Django view that does the following: Receive an HttpRequest on api/some/url/or/other Passes this through to another server at some/url/or/other (rewrite the URL, basically) Adding a cookie based on session data in Django Using the same method, data, params, et al, that were in the original request Returns verbatim the response to the API call Must store the cookies that came back from the call in the session Must include the Django session cookie in the returned HttpResponse What tools already exist in Django to do this? A: None. You'll have to code your own wrapper utility, using one of httplib / urllib / urllib2 libs to connect to the other server. Most likely you will have to extract all the relevant info from the HttpRequest object and use that to manually construct your own request in said util function. Regarding receiving the response from that other server, it will depend a little bit on wether you need that response only asynchronously or quasi-synchronously.
How to make a Django passthrough view?
I want to make a Django view that does the following: Receive an HttpRequest on api/some/url/or/other Passes this through to another server at some/url/or/other (rewrite the URL, basically) Adding a cookie based on session data in Django Using the same method, data, params, et al, that were in the original request Returns verbatim the response to the API call Must store the cookies that came back from the call in the session Must include the Django session cookie in the returned HttpResponse What tools already exist in Django to do this?
[ "None.\nYou'll have to code your own wrapper utility, using one of httplib / urllib / urllib2 libs to connect to the other server.\nMost likely you will have to extract all the relevant info from the HttpRequest object and use that to manually construct your own request in said util function.\nRegarding receiving t...
[ 1 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0003406800_ajax_django_python.txt
Q: Removing things from Python list during for loop Here is my code: toBe =[] #Check if there is any get request if request.GET.items() != []: for x in DB: try: #This is removing the PMT that is spcific to the name if request.GET['pmtName'] != "None": if not request.GET['pmtName'] in x['tags']: print x['title'], x['tags'] toBe.append(x) continue #This is removing the peak stuff if int(request.GET['peakMin']): if int(request.GET['peakMin']) < int(x['charge_peak']): toBe.append(x) continue if int(request.GET['peakMax']): if int(request.GET['peakMax']) > int(x['charge_peak']): toBe.append(x) continue if int(request.GET['widthMin']): if int(request.GET['widthMin']) < int(x['charge_width']): toBe.append(x) continue if int(request.GET['widthMax']): if int(request.GET['widthMax']) > int(x['charge_width']): toBe.append(x) continue except: pass #TODO: Stupid hack, this needs to be fixed for x in toBe: DB.remove(x) del toBe Essentially I want to remove the item and then skip to the next one. The problem with this is that when that happens, it messes up the order of the list and skips some. Anyone know a work around for this? Or maybe just a different way of doing this? thanks A: for x in DB[:]: makes a copy of the list DB, so you can iterate over it while modifying the original. Care -- memory-intensive and slow. A nicer way would be to make another layer over the list which yields only some of the values, and then iterate over that when you need it later. You can do that with a generator: def db_view( DB ): for x in DB: #This is removing the PMT that is spcific to the name if request.GET.get( 'pmtName', None ) not in x['tags']: print x['title'], x['tags'] continue #This is removing the peak stuff if int(request.GET['peakMin']): if int(request.GET['peakMin']) < int(x['charge_peak']): continue if int(request.GET['peakMax']): if int(request.GET['peakMax']) > int(x['charge_peak']): continue if int(request.GET['widthMin']): if int(request.GET['widthMin']) < int(x['charge_width']): continue if int(request.GET['widthMax']): if int(request.GET['widthMax']) > int(x['charge_width']): continue yield x which you would use like for x in db_view( DB ): # Do stuff A: The answer I usually see for questions of this sort if to loop over the list backwards. Here's how I do it in one of my programs: for i in range(len(my_list)-1,-1,-1): # do something This works even if I add items to the list. On http://desk.stinkpot.org:8080/tricks/index.php/2006/08/read-a-list-backwards-in-python/ they say you can use the syntax "for i in list[::-1]:" instead. I have not tried doing it that way. A: You're running over the same interpolation of request.GET for each value of x. Instead you could build a reusable list of filtering functions once. For example something like: if request.GET: filters = [] if 'pmtName' in request.GET: n = request.GET['pmtName'] filters.append(lambda x: n not in x['tags']) if 'peakMin' in request.GET and request.GET['peakMin'].isdigit(): n = int(request.GET['peakMin']) filters.append(lambda x: n < int(x['charge_peak'])) if 'peakMax' in request.GET and request.GET['peakMax'].isdigit(): n = int(request.GET['peakMax']) filters.append(lambda x: n > int(x['charge_peak'])) if 'widthMin' in request.GET and request.GET['widthMin'].isdigit(): n = int(request.GET['widthMin']) filters.append(lambda x: n < int(x['charge_width'])) if 'widthMax' in request.GET and request.GET['widthMax'].isdigit(): n = int(request.GET['widthMax']) filters.append(lambda x: n > int(x['charge_width'])) Then you can apply this list of functions to select the members of DB to remove: remove_these = [ x for x in DB if any(f(x) for f in filters)] for item in remove_these: DB.remove(item) Or create a generator that will return the values of DB that all of the filters fail on: filtered_DB = ( x for x in DB if all(not f(x) for f in filters))
Removing things from Python list during for loop
Here is my code: toBe =[] #Check if there is any get request if request.GET.items() != []: for x in DB: try: #This is removing the PMT that is spcific to the name if request.GET['pmtName'] != "None": if not request.GET['pmtName'] in x['tags']: print x['title'], x['tags'] toBe.append(x) continue #This is removing the peak stuff if int(request.GET['peakMin']): if int(request.GET['peakMin']) < int(x['charge_peak']): toBe.append(x) continue if int(request.GET['peakMax']): if int(request.GET['peakMax']) > int(x['charge_peak']): toBe.append(x) continue if int(request.GET['widthMin']): if int(request.GET['widthMin']) < int(x['charge_width']): toBe.append(x) continue if int(request.GET['widthMax']): if int(request.GET['widthMax']) > int(x['charge_width']): toBe.append(x) continue except: pass #TODO: Stupid hack, this needs to be fixed for x in toBe: DB.remove(x) del toBe Essentially I want to remove the item and then skip to the next one. The problem with this is that when that happens, it messes up the order of the list and skips some. Anyone know a work around for this? Or maybe just a different way of doing this? thanks
[ "for x in DB[:]: makes a copy of the list DB, so you can iterate over it while modifying the original. Care -- memory-intensive and slow.\nA nicer way would be to make another layer over the list which yields only some of the values, and then iterate over that when you need it later. You can do that with a generato...
[ 1, 0, 0 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0003406783_list_loops_python.txt
Q: Parsing Snort Logs with PyParsing Having a problem with parsing Snort logs using the pyparsing module. The problem is with separating the Snort log (which has multiline entries, separated by a blank line) and getting pyparsing to parse each entry as a whole chunk, rather than read in line by line and expecting the grammar to work with each line (obviously, it does not.) I have tried converting each chunk to a temporary string, stripping out the newlines inside each chunk, but it refuses to process correctly. I may be wholly on the wrong track, but I don't think so (a similar form works perfectly for syslog-type logs, but those are one-line entries and so lend themselves to your basic file iterator / line processing) Here's a sample of the log and the code I have so far: [**] [1:486:4] ICMP Destination Unreachable Communication with Destination Host is Administratively Prohibited [**] [Classification: Misc activity] [Priority: 3] 08/03-07:30:02.233350 172.143.241.86 -> 63.44.2.33 ICMP TTL:61 TOS:0xC0 ID:49461 IpLen:20 DgmLen:88 Type:3 Code:10 DESTINATION UNREACHABLE: ADMINISTRATIVELY PROHIBITED HOST FILTERED ** ORIGINAL DATAGRAM DUMP: 63.44.2.33:41235 -> 172.143.241.86:4949 TCP TTL:61 TOS:0x0 ID:36212 IpLen:20 DgmLen:60 DF Seq: 0xF74E606 (32 more bytes of original packet) ** END OF DUMP [**] ...more like this [**] And the updated code: def snort_parse(logfile): header = Suppress("[**] [") + Combine(integer + ":" + integer + ":" + integer) + Suppress("]") + Regex(".*") + Suppress("[**]") cls = Optional(Suppress("[Classification:") + Regex(".*") + Suppress("]")) pri = Suppress("[Priority:") + integer + Suppress("]") date = integer + "/" + integer + "-" + integer + ":" + integer + "." + Suppress(integer) src_ip = ip_addr + Suppress("->") dest_ip = ip_addr extra = Regex(".*") bnf = header + cls + pri + date + src_ip + dest_ip + extra def logreader(logfile): chunk = [] with open(logfile) as snort_logfile: for line in snort_logfile: if line !='\n': line = line[:-1] chunk.append(line) continue else: print chunk yield " ".join(chunk) chunk = [] string_to_parse = "".join(logreader(logfile).next()) fields = bnf.parseString(string_to_parse) print fields Any help, pointers, RTFMs, You're Doing It Wrongs, etc., greatly appreciated. A: import pyparsing as pyp import itertools integer = pyp.Word(pyp.nums) ip_addr = pyp.Combine(integer+'.'+integer+'.'+integer+'.'+integer) def snort_parse(logfile): header = (pyp.Suppress("[**] [") + pyp.Combine(integer + ":" + integer + ":" + integer) + pyp.Suppress(pyp.SkipTo("[**]", include = True))) cls = ( pyp.Suppress(pyp.Optional(pyp.Literal("[Classification:"))) + pyp.Regex("[^]]*") + pyp.Suppress(']')) pri = pyp.Suppress("[Priority:") + integer + pyp.Suppress("]") date = pyp.Combine( integer+"/"+integer+'-'+integer+':'+integer+':'+integer+'.'+integer) src_ip = ip_addr + pyp.Suppress("->") dest_ip = ip_addr bnf = header+cls+pri+date+src_ip+dest_ip with open(logfile) as snort_logfile: for has_content, grp in itertools.groupby( snort_logfile, key = lambda x: bool(x.strip())): if has_content: tmpStr = ''.join(grp) fields = bnf.searchString(tmpStr) print(fields) snort_parse('snort_file') yields [['1:486:4', 'Misc activity', '3', '08/03-07:30:02.233350', '172.143.241.86', '63.44.2.33']] A: You have some regex unlearning to do, but hopefully this won't be too painful. The biggest culprit in your thinking is the use of this construct: some_stuff + Regex(".*") + Suppress(string_representing_where_you_want_the_regex_to_stop) Each subparser within a pyparsing parser is pretty much standalone, and works sequentially through the incoming text. So the Regex term has no way to look ahead to the next expression to see where the '*' repetition should stop. In other words, the expression Regex(".*") is going to just read until the end of the line, since that is where ".*" stops without specifying multiline. In pyparsing, this concept is implemented using SkipTo. Here is how your header line is written: header = Suppress("[**] [") + Combine(integer + ":" + integer + ":" + integer) + Suppress("]") + Regex(".*") + Suppress("[**]") Your ".*" problem gets resolved by changing it to: header = Suppress("[**] [") + Combine(integer + ":" + integer + ":" + integer) + Suppress("]") + SkipTo("[**]") + Suppress("[**]") Same thing for cls. One last bug, your definition of date is short by one ':' + integer: date = integer + "/" + integer + "-" + integer + ":" + integer + "." + Suppress(integer) should be: date = integer + "/" + integer + "-" + integer + ":" + integer + ":" + integer + "." + Suppress(integer) I think those changes will be sufficient to start parsing your log data. Here are some other style suggestions: You have a lot of repeated Suppress("]") expressions. I've started defining all my suppressable punctuation in a very compact and easy to maintain statement like this: LBRACK,RBRACK,LBRACE,RBRACE = map(Suppress,"[]{}") (expand to add whatever other punctuation characters you like). Now I can use these characters by their symbolic names, and I find the resulting code a little easier to read. You start off header with header = Suppress("[**] [") + .... I never like seeing spaces embedded in literals this way, as it bypasses some of the parsing robustness pyparsing gives you with its automatic whitespace skipping. If for some reason the space between "[**]" and "[" was changed to use 2 or 3 spaces, or a tab, then your suppressed literal would fail. Combine this with the previous suggestion, and header would begin with header = Suppress("[**]") + LBRACK + ... I know this is generated text, so variation in this format is unlikely, but it plays better to pyparsing's strengths. Once you have your fields parsed out, start assigning results names to different elements within your parser. This will make it a lot easier to get the data out afterward. For instance, change cls to: cls = Optional(Suppress("[Classification:") + SkipTo(RBRACK)("classification") + RBRACK) Will allow you to access the classification data using fields.classification. A: Well, I don't know Snort or pyparsing, so apologies in advance if I say something stupid. I'm unclear as to whether the problem is with pyparsing being unable to handle the entries, or with you being unable to send them to pyparsing in the right format. If the latter, why not do something like this? def logreader( path_to_file ): chunk = [ ] with open( path_to_file ) as theFile: for line in theFile: if line: chunk.append( line ) continue else: yield "".join( *chunk ) chunk = [ ] Of course, if you need to modify each chunk before sending it to pyparsing, you can do so before yielding it.
Parsing Snort Logs with PyParsing
Having a problem with parsing Snort logs using the pyparsing module. The problem is with separating the Snort log (which has multiline entries, separated by a blank line) and getting pyparsing to parse each entry as a whole chunk, rather than read in line by line and expecting the grammar to work with each line (obviously, it does not.) I have tried converting each chunk to a temporary string, stripping out the newlines inside each chunk, but it refuses to process correctly. I may be wholly on the wrong track, but I don't think so (a similar form works perfectly for syslog-type logs, but those are one-line entries and so lend themselves to your basic file iterator / line processing) Here's a sample of the log and the code I have so far: [**] [1:486:4] ICMP Destination Unreachable Communication with Destination Host is Administratively Prohibited [**] [Classification: Misc activity] [Priority: 3] 08/03-07:30:02.233350 172.143.241.86 -> 63.44.2.33 ICMP TTL:61 TOS:0xC0 ID:49461 IpLen:20 DgmLen:88 Type:3 Code:10 DESTINATION UNREACHABLE: ADMINISTRATIVELY PROHIBITED HOST FILTERED ** ORIGINAL DATAGRAM DUMP: 63.44.2.33:41235 -> 172.143.241.86:4949 TCP TTL:61 TOS:0x0 ID:36212 IpLen:20 DgmLen:60 DF Seq: 0xF74E606 (32 more bytes of original packet) ** END OF DUMP [**] ...more like this [**] And the updated code: def snort_parse(logfile): header = Suppress("[**] [") + Combine(integer + ":" + integer + ":" + integer) + Suppress("]") + Regex(".*") + Suppress("[**]") cls = Optional(Suppress("[Classification:") + Regex(".*") + Suppress("]")) pri = Suppress("[Priority:") + integer + Suppress("]") date = integer + "/" + integer + "-" + integer + ":" + integer + "." + Suppress(integer) src_ip = ip_addr + Suppress("->") dest_ip = ip_addr extra = Regex(".*") bnf = header + cls + pri + date + src_ip + dest_ip + extra def logreader(logfile): chunk = [] with open(logfile) as snort_logfile: for line in snort_logfile: if line !='\n': line = line[:-1] chunk.append(line) continue else: print chunk yield " ".join(chunk) chunk = [] string_to_parse = "".join(logreader(logfile).next()) fields = bnf.parseString(string_to_parse) print fields Any help, pointers, RTFMs, You're Doing It Wrongs, etc., greatly appreciated.
[ "import pyparsing as pyp\nimport itertools\n\ninteger = pyp.Word(pyp.nums)\nip_addr = pyp.Combine(integer+'.'+integer+'.'+integer+'.'+integer)\n\ndef snort_parse(logfile):\n header = (pyp.Suppress(\"[**] [\")\n + pyp.Combine(integer + \":\" + integer + \":\" + integer)\n + pyp.Suppress(...
[ 14, 4, 0 ]
[]
[]
[ "pyparsing", "python", "snort" ]
stackoverflow_0003406544_pyparsing_python_snort.txt
Q: Paranoia, excessive logging and exception handling on simple scripts dealing with files. Is this normal? I find myself using python for a lot of file management scripts as the one below. While looking for examples on the net I am surprised about how little logging and exception handling is featured on the examples. Every time I write a new script my intention is not to end up as the one below but if it deals with files then no matter what my paranoia takes over and the end result is nothing like the examples I see on the net. As I am a newbie I would like to known if this is normal or not. If not then how do you deal with the unknowns and the fears of deleting valuable info? def flatten_dir(dirname): '''Flattens a given root directory by moving all files from its sub-directories and nested sub-directories into the root directory and then deletes all sub-directories and nested sub-directories. Creates a backup directory preserving the original structure of the root directory and restores this in case of errors. ''' RESTORE_BACKUP = False log.info('processing directory "%s"' % dirname) backup_dirname = str(uuid.uuid4()) try: shutil.copytree(dirname, backup_dirname) log.debug('directory "%s" backed up as directory "%s"' % (dirname,backup_dirname)) except shutil.Error: log.error('shutil.Error: Error while trying to back up the directory') sys.stderr.write('the program is terminating with an error\n') sys.stderr.write('press consult the log file\n') sys.stderr.flush() time.sleep(0.25) print 'Press any key to quit this program.' msvcrt.getch() sys.exit() for root, dirs, files in os.walk(dirname, topdown=False): log.debug('os.walk passing: (%s, %s, %s)' % (root, dirs, files)) if root != dirname: for file in files: full_filename = os.path.join(root, file) try: shutil.move(full_filename, dirname) log.debug('"%s" copied to directory "%s"' % (file,dirname)) except shutil.Error: RESTORE_BACKUP = True log.error('file "%s" could not be copied to directory "%s"' % (file,dirname)) log.error('flagging directory "%s" for reset' % dirname) if not RESTORE_BACKUP: try: shutil.rmtree(root) log.debug('directory "%s" deleted' % root) except shutil.Error: RESTORE_BACKUP = True log.error('directory "%s" could not be deleted' % root) log.error('flagging directory "%s" for reset' % dirname) if RESTORE_BACKUP: break if RESTORE_BACKUP: RESTORE_FAIL = False try: shutil.rmtree(dirname) except shutil.Error: log.error('modified directory "%s" could not be deleted' % dirname) log.error('manual restoration from backup directory "%s" necessary' % backup_dirname) RESTORE_FAIL = True if not RESTORE_FAIL: try: os.renames(backup_dirname, dirname) log.debug('back up of directory "%s" restored' % dirname) print '>' print '>******WARNING******' print '>There was an error while trying to flatten directory "%s"' % dirname print '>back up of directory "%s" restored' % dirname print '>******WARNING******' print '>' except WindowsError: log.error('backup directory "%s" could not be renamed to original directory name' % backup_dirname) log.error('manual renaming of backup directory "%s" to original directory name "%s" necessary' % (backup_dirname,dirname)) print '>' print '>******WARNING******' print '>There was an error while trying to flatten directory "%s"' % dirname print '>back up of directory "%s" was NOT restored successfully' % dirname print '>no information is lost' print '>check the log file for information on manually restoring the directory' print '>******WARNING******' print '>' else: try: shutil.rmtree(backup_dirname) log.debug('back up of directory "%s" deleted' % dirname) log.info('directory "%s" successfully processed' % dirname) print '>directory "%s" successfully processed' % dirname except shutil.Error: log.error('backup directory "%s" could not be deleted' % backup_dirname) log.error('manual deletion of backup directory "%s" necessary' % backup_dirname) print '>' print '>******WARNING******' print '>directory "%s" successfully processed' % dirname print '>cleanup of backup directory "%s" failed' % backup_dirname print '>manual cleanup necessary' print '>******WARNING******' print '>' A: Learning to let go (or how I learned to live with the bomb)... Ask yourself this: what exactly are you afraid of, and how will you handle it if it happens? In the example that you provide you want to avoid data-loss. The way that you've handled it is by looking for every combination of conditions that you think is an error and placing huge amounts of logging over it. Things will still go wrong and it's not clear that having a large amount of logging will be a good way to deal with it. Sketching out what you are trying to achieve: for each file in a tree if file is below the root move it into the root if nothing went wrong delete empty subtrees So what kind of things could go wrong in this process? Well, there are many ways in which the move file operations could barf due to the underlying file-system. Can we list them all and provide nice ways to deal with them? No... but in general you are going to deal with them all the same way. Sometimes an error is just an error regardless of what it is. So in this case if any error occurs then you want to abort and undo any changes. The way that you've decided to do that is by creating a backup copy and restoring it when something goes wrong. But your most likely error is the file-system being full in which case these steps are likely to fail.... Ok, so it is a common enough problem - if you are worried about unknown errors at any point how do you stop your restoration path from going wrong? The general answer is make sure that you do any intermediate work first, and then take a single troublesome (hopefully atomic) step. In your case you need to flip your recovery around. Instead of building a copy as a backup, build a copy of the result. If everything succeeds you can then swap the new result in for the old original tree. Or, if you are really paranoid you can leave that step for a human. The advantage here is that if something goes wrong you can just abort and throw away the partial state that you have constructed. Your structure then becomes : make empty result directory for every file in the tree copy file into new result on failure abort otherwise move result over old source directory By the way, there is a bug in your current script that this psuedo-code makes more obvious: if you have files with identical names in different branches they will overwrite each other in the new flattened version. The second point about this psuedo code is that all of the error handling is in the same place (ie wrap the make new directory and recursive copy inside a single try block and catch all the errors after it), this solves your original issue about the large ratio of logging / error-checking to actual work code. backup_dirname = str(uuid.uuid4()) try: shutil.mkdir(backup_dirname) for root, dirs, files in os.walk(dirname, topdown=False): for file in files: full_filename = os.path.join(root, file) target_filename = os.path.join(backup_dirname,file) shutil.copy(full_filename, target_filename) catch Exception, e: print >>sys.stderr, "Something went wrong %s" % e exit(-1) shutil.move(back_dirname,root) # I would do this bit by hand really A: It's ok to be a little paranoid. But there are different kinds of paranoia :). During the development phase, I use a lot of debug statements so I can see where I am going wrong (if I do go wrong). Sometimes I will leave these statements in, but use a flag to control whether they need to be displayed or not (pretty much a debug flag). You could also have a "verbosity" flag to control how much logging you do. The other type of paranoia comes with sanity checks. This paranoia comes into play when you rely on external data or tools - pretty much anything that doesn't come out of your program. In this case, it never hurts to be paranoid (especially with data that you receive - never trust it). It's also ok to be paranoid if you're checking to see if a particular operation completed successfully. This is just part of normal error-handling. I notice that you're performing functions like deleting directories and files. These are operations that could potentially fail, and so you must deal with the scenario where they fail. If you simply ignore it, your code could end up in an indeterminate/undefined state and could potentially do bad (or at the least, undesirable) things. As far as the log files and debug files are concerned, you can leave them in if you wish. I usually perform a decent amount of logging; just enough to tell me what's going on. Of course, that is subjective. The key is to make sure you don't drown yourself in logging; where there is so much information that you can't pick it out easily. Logging in general helps you figure out what when wrong when a script you wrote suddenly stops working. Instead of stepping through the program to figure it out, you can get a rough idea of where the problem is by going through your logs. A: Paranoia can definitely obscure what your code is trying to do. That is a very bad thing, for several reasons. It hides bugs. It makes the program harder to modify when you need it to do something else. It makes it harder to debug. Assuming Amoss can't cure you of your paranoia, here is how I might rewrite the program. Note that: Each block of code that contains a lot of paranoia is split out into its own function. Each time an exception is caught, it is re-raised, until it is finally caught in the main function. This eliminates the need for variables like RESTORE_BACKUP and RESTORE_FAIL. The heart of the program (in flatten_dir) is now just 17 lines long and paranoia-free. def backup_tree(dirname, backup_dirname): try: shutil.copytree(dirname, backup_dirname) log.debug('directory "%s" backed up as directory "%s"' % (dirname,backup_dirname)) except: log.error('Error trying to back up the directory') raise def move_file(full_filename, dirname): try: shutil.move(full_filename, dirname) log.debug('"%s" copied to directory "%s"' % (file,dirname)) except: log.error('file "%s" could not be moved to directory "%s"' % (file,dirname)) raise def remove_empty_dir(dirname): try: os.rmdir(dirname) log.debug('directory "%s" deleted' % dirname) except: log.error('directory "%s" could not be deleted' % dirname) raise def remove_tree_for_restore(dirname): try: shutil.rmtree(dirname) except: log.error('modified directory "%s" could not be deleted' % dirname) log.error('manual restoration from backup directory "%s" necessary' % backup_dirname) raise def restore_backup(backup_dirname, dirname): try: os.renames(backup_dirname, dirname) log.debug('back up of directory "%s" restored' % dirname) print '>' print '>******WARNING******' print '>There was an error while trying to flatten directory "%s"' % dirname print '>back up of directory "%s" restored' % dirname print '>******WARNING******' print '>' except: log.error('backup directory "%s" could not be renamed to original directory name' % backup_dirname) log.error('manual renaming of backup directory "%s" to original directory name "%s" necessary' % (backup_dirname,dirname)) print '>' print '>******WARNING******' print '>There was an error while trying to flatten directory "%s"' % dirname print '>back up of directory "%s" was NOT restored successfully' % dirname print '>no information is lost' print '>check the log file for information on manually restoring the directory' print '>******WARNING******' print '>' raise def remove_backup_tree(backup_dirname): try: shutil.rmtree(backup_dirname) log.debug('back up of directory "%s" deleted' % dirname) log.info('directory "%s" successfully processed' % dirname) print '>directory "%s" successfully processed' % dirname except shutil.Error: log.error('backup directory "%s" could not be deleted' % backup_dirname) log.error('manual deletion of backup directory "%s" necessary' % backup_dirname) print '>' print '>******WARNING******' print '>directory "%s" successfully processed' % dirname print '>cleanup of backup directory "%s" failed' % backup_dirname print '>manual cleanup necessary' print '>******WARNING******' print '>' raise def flatten_dir(dirname): '''Flattens a given root directory by moving all files from its sub-directories and nested sub-directories into the root directory and then deletes all sub-directories and nested sub-directories. Creates a backup directory preserving the original structure of the root directory and restores this in case of errors. ''' log.info('processing directory "%s"' % dirname) backup_dirname = str(uuid.uuid4()) backup_tree(dirname, backup_dirname) try: for root, dirs, files in os.walk(dirname, topdown=False): log.debug('os.walk passing: (%s, %s, %s)' % (root, dirs, files)) if root != dirname: for file in files: full_filename = os.path.join(root, file) move_file(full_filename, dirname) remove_empty_dir(dirname) except: remove_tree_for_restore(dirname) restore_backup(backup_dirname, dirname) raise else: remove_backup_tree(backup_dirname) def main(dirname): try: flatten_dir(dirname) except: import exceptions logging.exception('error flattening directory "%s"' % dirname) exceptions.print_exc() sys.stderr.write('the program is terminating with an error\n') sys.stderr.write('press consult the log file\n') sys.stderr.flush() time.sleep(0.25) print 'Press any key to quit this program.' msvcrt.getch() sys.exit() A: That seems reasonable to me. It depends how important your data is. I often start out like that, and have the logging be optional, with a flag set at the top of the file (or by the caller) setting the logging on or off. You could also have a verbosity. Generally, after something has been working for a while and is no longer in development, I stop reading the logs, and build up giant log files which I never read. However, if something does go wrong, it's good to know that they're there. A: If it's OK to leave the job half-done on error (only some files moved), as long as no files are lost, then the backup directory is unnecessary. So you can write dramatically simpler code: import os, logging def flatten_dir(dirname): for root, dirs, files in os.walk(dirname, topdown=False): assert len(dirs) == 0 if root != dirname: for file in files: full_filename = os.path.join(root, file) target_filename = os.path.join(dirname, file) if os.path.exists(target_filename): raise Exception('Unable to move file "%s" because "%s" already exists' % (full_filename, target_filename)) os.rename(full_filename, target_filename) os.rmdir(root) def main(): try: flatten_dir(somedir) except: logging.exception('Failed to flatten directory "%s".' % somedir) print "ERROR: Failed to flatten directory. Check log files for details." Each individual system call here makes progress without destroying data that you wanted to keep. There's no need for a backup directory because there's never anything you need to "recover".
Paranoia, excessive logging and exception handling on simple scripts dealing with files. Is this normal?
I find myself using python for a lot of file management scripts as the one below. While looking for examples on the net I am surprised about how little logging and exception handling is featured on the examples. Every time I write a new script my intention is not to end up as the one below but if it deals with files then no matter what my paranoia takes over and the end result is nothing like the examples I see on the net. As I am a newbie I would like to known if this is normal or not. If not then how do you deal with the unknowns and the fears of deleting valuable info? def flatten_dir(dirname): '''Flattens a given root directory by moving all files from its sub-directories and nested sub-directories into the root directory and then deletes all sub-directories and nested sub-directories. Creates a backup directory preserving the original structure of the root directory and restores this in case of errors. ''' RESTORE_BACKUP = False log.info('processing directory "%s"' % dirname) backup_dirname = str(uuid.uuid4()) try: shutil.copytree(dirname, backup_dirname) log.debug('directory "%s" backed up as directory "%s"' % (dirname,backup_dirname)) except shutil.Error: log.error('shutil.Error: Error while trying to back up the directory') sys.stderr.write('the program is terminating with an error\n') sys.stderr.write('press consult the log file\n') sys.stderr.flush() time.sleep(0.25) print 'Press any key to quit this program.' msvcrt.getch() sys.exit() for root, dirs, files in os.walk(dirname, topdown=False): log.debug('os.walk passing: (%s, %s, %s)' % (root, dirs, files)) if root != dirname: for file in files: full_filename = os.path.join(root, file) try: shutil.move(full_filename, dirname) log.debug('"%s" copied to directory "%s"' % (file,dirname)) except shutil.Error: RESTORE_BACKUP = True log.error('file "%s" could not be copied to directory "%s"' % (file,dirname)) log.error('flagging directory "%s" for reset' % dirname) if not RESTORE_BACKUP: try: shutil.rmtree(root) log.debug('directory "%s" deleted' % root) except shutil.Error: RESTORE_BACKUP = True log.error('directory "%s" could not be deleted' % root) log.error('flagging directory "%s" for reset' % dirname) if RESTORE_BACKUP: break if RESTORE_BACKUP: RESTORE_FAIL = False try: shutil.rmtree(dirname) except shutil.Error: log.error('modified directory "%s" could not be deleted' % dirname) log.error('manual restoration from backup directory "%s" necessary' % backup_dirname) RESTORE_FAIL = True if not RESTORE_FAIL: try: os.renames(backup_dirname, dirname) log.debug('back up of directory "%s" restored' % dirname) print '>' print '>******WARNING******' print '>There was an error while trying to flatten directory "%s"' % dirname print '>back up of directory "%s" restored' % dirname print '>******WARNING******' print '>' except WindowsError: log.error('backup directory "%s" could not be renamed to original directory name' % backup_dirname) log.error('manual renaming of backup directory "%s" to original directory name "%s" necessary' % (backup_dirname,dirname)) print '>' print '>******WARNING******' print '>There was an error while trying to flatten directory "%s"' % dirname print '>back up of directory "%s" was NOT restored successfully' % dirname print '>no information is lost' print '>check the log file for information on manually restoring the directory' print '>******WARNING******' print '>' else: try: shutil.rmtree(backup_dirname) log.debug('back up of directory "%s" deleted' % dirname) log.info('directory "%s" successfully processed' % dirname) print '>directory "%s" successfully processed' % dirname except shutil.Error: log.error('backup directory "%s" could not be deleted' % backup_dirname) log.error('manual deletion of backup directory "%s" necessary' % backup_dirname) print '>' print '>******WARNING******' print '>directory "%s" successfully processed' % dirname print '>cleanup of backup directory "%s" failed' % backup_dirname print '>manual cleanup necessary' print '>******WARNING******' print '>'
[ "Learning to let go (or how I learned to live with the bomb)...\nAsk yourself this: what exactly are you afraid of, and how will you handle it if it happens? In the example that you provide you want to avoid data-loss. The way that you've handled it is by looking for every combination of conditions that you think i...
[ 8, 3, 2, 1, 0 ]
[]
[]
[ "exception", "logging", "python" ]
stackoverflow_0003406627_exception_logging_python.txt
Q: Android app uploading data to a python server via post I have successfully implemented this from android to a java httpservlet on google app engine, but I'd like to use python instead for the server side. I'm new to python. Has anyone done this? I have the guestbook example up and running, but I can't seem to send posts from my android app to the server. I'd also like to issue a string response back to the client like "success". A guiding hand would be much appreciated. Thanks ***Client side java: URL url = new URL(Const.SERVER_NAME); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream() ); out.write("content=12345"); out.close(); ***Server side Python: class Upload(webapp.RequestHandler): def post(self): greeting.content = self.request.get('content') greeting.put() ***Server side Java (working) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String instring = request.getParameter("content") // set the response code and write the response data response.setStatus(HttpServletResponse.SC_OK); OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream()); writer.write("Success"); writer.flush(); writer.close(); } catch (IOException e) { try{ response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().print(e.getMessage()); response.getWriter().close(); } catch (IOException ioe) { } } A: I know it's been a long time. But I did solve this so I'll post the solution. Android code: url = new URL(SERVER_URL); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream()); String post_string; post_string = "deviceID="+tm.getDeviceId().toString(); // send post string to server out.write(post_string); out.close(); //grab a return string from server BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); Toast.makeText(context, in.readLine(), Toast.LENGTH_SHORT).show(); And here's the python server side, using Django with GAE: def upload(request): if request.method == 'POST': deviceID = measurement.deviceID = str(request.POST['deviceID']) return HttpResponse('Success!') else: return HttpResponse('Invalid Data')
Android app uploading data to a python server via post
I have successfully implemented this from android to a java httpservlet on google app engine, but I'd like to use python instead for the server side. I'm new to python. Has anyone done this? I have the guestbook example up and running, but I can't seem to send posts from my android app to the server. I'd also like to issue a string response back to the client like "success". A guiding hand would be much appreciated. Thanks ***Client side java: URL url = new URL(Const.SERVER_NAME); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream() ); out.write("content=12345"); out.close(); ***Server side Python: class Upload(webapp.RequestHandler): def post(self): greeting.content = self.request.get('content') greeting.put() ***Server side Java (working) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String instring = request.getParameter("content") // set the response code and write the response data response.setStatus(HttpServletResponse.SC_OK); OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream()); writer.write("Success"); writer.flush(); writer.close(); } catch (IOException e) { try{ response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().print(e.getMessage()); response.getWriter().close(); } catch (IOException ioe) { } }
[ "I know it's been a long time. But I did solve this so I'll post the solution. \nAndroid code:\n url = new URL(SERVER_URL);\n URLConnection connection = url.openConnection();\n connection.setDoOutput(true);\n\n OutputStreamWriter out = new OutputStreamWriter(\n ...
[ 4 ]
[]
[]
[ "google_app_engine", "http", "java", "post", "python" ]
stackoverflow_0002331862_google_app_engine_http_java_post_python.txt
Q: SPSS Python Error Getting the following error when trying to run SPSS from an external Python IDE. import spss yields the following error Traceback (most recent call last): File "C:\Documents and Settings\USER\workspace\SPSS\src\NE ASQ 2010.py", line 6, in <module> import spss File "C:\Python26\Lib\site-packages\spss180\spss\spss.py", line 16, in <module> error = errCode() File "C:\Python26\Lib\site-packages\spss180\spss\errMsg.py", line 24, in __init__ self.errMsg = errTable['okay'][str(0)] KeyError: 'okay' Ran the Python essentials plug-in with no errors. Funny thing is that I dont get an error when I run this in a syntax BEGIN PROGRAM PYTHON. import spss num = spss.GetVariableCount() print num END PROGRAM. Any help will be much appreciated. Brock A: I believe I figured out the issue. I needed to configure Eclipse to see the external python modules that are created when you install the SPSS/Python plugin. I had to set a reference to the modules when configuring the project. Once I did that, it looks like I am up and running!
SPSS Python Error
Getting the following error when trying to run SPSS from an external Python IDE. import spss yields the following error Traceback (most recent call last): File "C:\Documents and Settings\USER\workspace\SPSS\src\NE ASQ 2010.py", line 6, in <module> import spss File "C:\Python26\Lib\site-packages\spss180\spss\spss.py", line 16, in <module> error = errCode() File "C:\Python26\Lib\site-packages\spss180\spss\errMsg.py", line 24, in __init__ self.errMsg = errTable['okay'][str(0)] KeyError: 'okay' Ran the Python essentials plug-in with no errors. Funny thing is that I dont get an error when I run this in a syntax BEGIN PROGRAM PYTHON. import spss num = spss.GetVariableCount() print num END PROGRAM. Any help will be much appreciated. Brock
[ "I believe I figured out the issue. I needed to configure Eclipse to see the external python modules that are created when you install the SPSS/Python plugin. I had to set a reference to the modules when configuring the project. \nOnce I did that, it looks like I am up and running!\n" ]
[ 1 ]
[]
[]
[ "python", "spss" ]
stackoverflow_0003259753_python_spss.txt
Q: python: what happens to opened file if i quit before it is closed? i am opening a csv file: def get_file(start_file): #opens original file, reads it to array with open(start_file,'rb') as f: data=list(csv.reader(f)) header=data[0] counter=collections.defaultdict(int) for row in data: counter[row[10]]+=1 return (data,counter,header) does the file stay in memory if i quit the program inside the WITH loop? what happens to the variables in general inside the program when i quit the program without setting all variables to NULL? A: The operating system will automatically close any open file descriptors when your process terminates. File data stored in memory (e.g. variables, Python buffers) will be lost. Data buffered in the operating system may be flushed to disk when the file is implicitly closed (checking the exact semantics of in-kernel dirty-buffers here would be educational, though you should not rely on it). Your variables cease to exist when your process terminates. A: My understanding of the with statement is that, no matter what, it will take care of closing your file handles for you when you exit it's scope. That should still happen if your program exits inside the with block. As far as other variables are concerned, they're deleted from memory when your program exits automatically. If you are interested in finding ways to make something persistent between runs you can look at the pickle (http://docs.python.org/library/pickle.html) or shelve (http://docs.python.org/library/shelve.html) modules. Personally, I prefer shelve to pickle, but they both work well for that. @gotgenes - Thanks for the suggestion. It's important to note that shelve uses pickle in its underlying implementation. When I say I prefer shelve to pickle, I mean that for the ways that persistence is important in what I'm currently designing using shelve is easier because it's not doing anything more than serving as a dictionary that persists between runs. A: you never have to set variables to NULL, as soon as your program terminates the memory is freed. the same holds true for the file - it stays in memory no more or less whether you quit in the with loop or anywhere else. however, it is good practice to manually close the file so you can be sure that any pending operations are performed before the program is exited. in general, this should happen anyway, but especially when writing, I generally prefer the close.
python: what happens to opened file if i quit before it is closed?
i am opening a csv file: def get_file(start_file): #opens original file, reads it to array with open(start_file,'rb') as f: data=list(csv.reader(f)) header=data[0] counter=collections.defaultdict(int) for row in data: counter[row[10]]+=1 return (data,counter,header) does the file stay in memory if i quit the program inside the WITH loop? what happens to the variables in general inside the program when i quit the program without setting all variables to NULL?
[ "The operating system will automatically close any open file descriptors when your process terminates.\nFile data stored in memory (e.g. variables, Python buffers) will be lost. Data buffered in the operating system may be flushed to disk when the file is implicitly closed (checking the exact semantics of in-kernel...
[ 9, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003407522_python.txt
Q: using xpath to tell selenium where to click? I'm new to all of this but I've learned a few things about python not long time ago, could you help me specify the correct the XPath for selenium to click? I've tried this way, but didn't work, obviously :( self.selenium.click("xpath=//html/body/div/div/div/div[4]/ul/li[3]/a") If you're wandering where did i get that ugly XPath, it's from Firebug's copy XPath option. I think that the HTML snippet is as long as hell so i couldn't do more than this: <html> <body> <div id="outer_wrapper"> <div id="container"> <div id="header"> <div id="menunav"> <ul> <li><a title="Login page" href="[dest]">Login</a></li> <li><a title="" href="[dest]">Sitemap</a></li> **<li><a title="" href="[dest]">Administration</a></li>** </ul> </div> </div> </div> </div> </body> </html> A: Below are a few example locators you could use to click the Administration link (based on your XPath and HTML snippet). The correct Selenium command is click. link=Administration css=a:contains(Administration) css=#menunav a:nth-child(3) xpath=id('menunav')/descendant::a[3] //a[text()='Administration'] //a[contains(text(), 'Administration')] I hope this points you in the right direction.
using xpath to tell selenium where to click?
I'm new to all of this but I've learned a few things about python not long time ago, could you help me specify the correct the XPath for selenium to click? I've tried this way, but didn't work, obviously :( self.selenium.click("xpath=//html/body/div/div/div/div[4]/ul/li[3]/a") If you're wandering where did i get that ugly XPath, it's from Firebug's copy XPath option. I think that the HTML snippet is as long as hell so i couldn't do more than this: <html> <body> <div id="outer_wrapper"> <div id="container"> <div id="header"> <div id="menunav"> <ul> <li><a title="Login page" href="[dest]">Login</a></li> <li><a title="" href="[dest]">Sitemap</a></li> **<li><a title="" href="[dest]">Administration</a></li>** </ul> </div> </div> </div> </div> </body> </html>
[ "Below are a few example locators you could use to click the Administration link (based on your XPath and HTML snippet). The correct Selenium command is click.\n\nlink=Administration\ncss=a:contains(Administration)\ncss=#menunav a:nth-child(3)\nxpath=id('menunav')/descendant::a[3]\n//a[text()='Administration']\n//a...
[ 6 ]
[]
[]
[ "python", "selenium", "xpath" ]
stackoverflow_0003406103_python_selenium_xpath.txt
Q: python sort without lambda expressions I often do sorts in Python using lambda expressions, and although it works fine, I find it not very readable, and was hoping there might be a better way. Here is a typical use case for me. I have a list of numbers, e.g., x = [12, 101, 4, 56, ...] I have a separate list of indices: y = range(len(x)) I want to sort y based on the values in x, and I do this: y.sort(key=lambda a: x[a]) Is there a good way to do this without using lambda? A: You can use the __getitem__ method of the list x. This behaves the same as your lambda and will be much faster since it is implemented as a C function instead of a python function: >>> x = [12, 101, 4, 56] >>> y = range(len(x)) >>> sorted(y, key=x.__getitem__) [2, 0, 3, 1] A: Not elegantly, but: [a for (v, a) in sorted((x[a], a) for a in y)] BTW, you can do this without creating a separate list of indices: [i for (v, i) in sorted((v, i) for (i, v) in enumerate(x))] A: I'm not sure if this is the kind of alternative you meant, but you could define the key function with a def: def sort_key(value): return x[value] y.sort(key = sort_key) Personally, I think this is worse than the lambda as it moves the sort criteria away from the line of code doing the sort and it needlessly adds the sort_key function into your namespace. A: I suppose if I wanted to create another function, I could do it something like this (not tested): def sortUsingList(indices, values): return indices[:].sort(key=lambda a: values[a]) Though I think I prefer to use lambda instead to avoid having to create an extra function.
python sort without lambda expressions
I often do sorts in Python using lambda expressions, and although it works fine, I find it not very readable, and was hoping there might be a better way. Here is a typical use case for me. I have a list of numbers, e.g., x = [12, 101, 4, 56, ...] I have a separate list of indices: y = range(len(x)) I want to sort y based on the values in x, and I do this: y.sort(key=lambda a: x[a]) Is there a good way to do this without using lambda?
[ "You can use the __getitem__ method of the list x. This behaves the same as your lambda and will be much faster since it is implemented as a C function instead of a python function:\n>>> x = [12, 101, 4, 56]\n>>> y = range(len(x))\n>>> sorted(y, key=x.__getitem__)\n[2, 0, 3, 1]\n\n", "Not elegantly, but:\n[a for...
[ 12, 7, 4, 0 ]
[]
[]
[ "lambda", "python", "sorting" ]
stackoverflow_0003407414_lambda_python_sorting.txt
Q: Python subprocess + mencoder not working, same command works in terminal I am having a problem using mencoder (SVN-r30531-4.2.1) through a python (2.6.1) subprocess. I am trying to join two mp4 files which are exactly the same size, codec, etc. Both have no audio. The code I am using to test is: import subprocess mp4merge = [ "mencoder", "in1.mp4", "in2.mp4", "-ovc", "copy", "-oac", "copy", "-of", "lavf", "-o", "out.mp4" ] try: pMerge = subprocess.Popen(mp4merge, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while pMerge.poll() == None: for l in pMerge.stderr.readlines(): print l if pMerge.poll() is not None: print "Complete" except subprocess.CalledProcessError: print "fail" And it doesn't work, it just hangs indefinitely. However, when I run the exact same command through Terminal (OS X 10.6.4) it works. The command is: mencoder in1.mp4 in2.mp4 -ovc copy -oac copy -of lavf -o out.mp4 You can download the videos from here. I am quite confident the videos aren't the probelm because of the fact that it works from Terminal. A: The problem here is that pMerge.stderr.readlines() blocks forever until the process is over. It reads all lines before continuing. Since mencoder writes a lot to the stdout, the stdout buffer is filled and mencoder is waiting for it to empty before it can continue. So the process never ends. Here's a way to do the same, that won't hang: pMerge = subprocess.Popen(mp4merge, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = pMerge.communicate() print stdout print stderr Another option that allows you to read the output line-by-line is to redirect stderr to stdout, and then read only stdout, (don't use readlines() since it blocks until all lines are read): pMerge = subprocess.Popen(mp4merge, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in pMerge.stdout: print line, This redirects stderr to stdout so your buffer won't fill.
Python subprocess + mencoder not working, same command works in terminal
I am having a problem using mencoder (SVN-r30531-4.2.1) through a python (2.6.1) subprocess. I am trying to join two mp4 files which are exactly the same size, codec, etc. Both have no audio. The code I am using to test is: import subprocess mp4merge = [ "mencoder", "in1.mp4", "in2.mp4", "-ovc", "copy", "-oac", "copy", "-of", "lavf", "-o", "out.mp4" ] try: pMerge = subprocess.Popen(mp4merge, stdout=subprocess.PIPE, stderr=subprocess.PIPE) while pMerge.poll() == None: for l in pMerge.stderr.readlines(): print l if pMerge.poll() is not None: print "Complete" except subprocess.CalledProcessError: print "fail" And it doesn't work, it just hangs indefinitely. However, when I run the exact same command through Terminal (OS X 10.6.4) it works. The command is: mencoder in1.mp4 in2.mp4 -ovc copy -oac copy -of lavf -o out.mp4 You can download the videos from here. I am quite confident the videos aren't the probelm because of the fact that it works from Terminal.
[ "The problem here is that pMerge.stderr.readlines() blocks forever until the process is over. It reads all lines before continuing.\nSince mencoder writes a lot to the stdout, the stdout buffer is filled and mencoder is waiting for it to empty before it can continue. So the process never ends.\nHere's a way to do t...
[ 2 ]
[]
[]
[ "mencoder", "mp4", "python", "subprocess", "video" ]
stackoverflow_0003407742_mencoder_mp4_python_subprocess_video.txt
Q: Python Pickle Help I'm not sure why this Pickle example is not showing both of the dictionary definitions. As I understand it, "ab+" should mean that the pickle.dat file is being appended to and can be read from. I'm new to the whole pickle concept, but the tutorials on the net don't seem to go beyond just the initial storage. import cPickle as pickle def append_object(d, fname): """appends a pickle dump of d to fname""" print "append_hash", d, fname with open(fname, 'ab') as pickler: pickle.dump(d, pickler) db_file = 'pickle.dat' cartoon = {} cartoon['Mouse'] = 'Mickey' append_object(cartoon, db_file) cartoon = {} cartoon['Bird'] = 'Tweety' append_object(cartoon, db_file) print 'loading from pickler' with open(db_file, 'rb') as pickler: cartoon = pickle.load(pickler) print 'loaded', cartoon Ideally, I was hoping to build up a dictionary using a for loop and then add the key:value pair to the pickle.dat file, then clear the dictionary to save some RAM. What's going on here? A: Don't use pickle for that. Use a database. Python dbm module seems to fit what you want perfectly. It presents you with a dictionary-like interface, but data is saved to disk. Example usage: >>> import dbm >>> x = dbm.open('/tmp/foo.dat', 'c') >>> x['Mouse'] = 'Mickey' >>> x['Bird'] = 'Tweety' Tomorrow you can load the data: >>> import dbm >>> x = dbm.open('/tmp/foo.dat', 'c') >>> print x['Mouse'] Mickey >>> print x['Bird'] Tweety A: I started to edit your code for readability and factored out append_object in the process. There are multiple confusions here. The first, is that pickle.dump writes a Python object in its entirety. You can put multiple objects in a pickle file, but each needs its own load. The code did what you asked of it and loaded the first dictionary you wrote to the file. The second dictionary was there waiting to be read but it isn't a concatenation to the first, it is its own loadable. Don't underestimate the importance of names. append_object isn't a great name, but it is different than append_to_object. If you are opening a file for reading, just open it for reading and the same for writing or appending. Not only does it make your intentions more clear but it prevents silly errors.
Python Pickle Help
I'm not sure why this Pickle example is not showing both of the dictionary definitions. As I understand it, "ab+" should mean that the pickle.dat file is being appended to and can be read from. I'm new to the whole pickle concept, but the tutorials on the net don't seem to go beyond just the initial storage. import cPickle as pickle def append_object(d, fname): """appends a pickle dump of d to fname""" print "append_hash", d, fname with open(fname, 'ab') as pickler: pickle.dump(d, pickler) db_file = 'pickle.dat' cartoon = {} cartoon['Mouse'] = 'Mickey' append_object(cartoon, db_file) cartoon = {} cartoon['Bird'] = 'Tweety' append_object(cartoon, db_file) print 'loading from pickler' with open(db_file, 'rb') as pickler: cartoon = pickle.load(pickler) print 'loaded', cartoon Ideally, I was hoping to build up a dictionary using a for loop and then add the key:value pair to the pickle.dat file, then clear the dictionary to save some RAM. What's going on here?
[ "Don't use pickle for that. Use a database.\nPython dbm module seems to fit what you want perfectly. It presents you with a dictionary-like interface, but data is saved to disk.\nExample usage:\n>>> import dbm\n>>> x = dbm.open('/tmp/foo.dat', 'c')\n>>> x['Mouse'] = 'Mickey'\n>>> x['Bird'] = 'Tweety'\n\nTomorrow yo...
[ 5, 3 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0003407646_pickle_python.txt
Q: Genshi: TemplateSyntaxError: not well-formed (invalid token) with ampersands in I'm using Pylons/Genshi, and trying to show 'all recent comments' on my site with a Disqus javascript widget (Disqus is installed on the site, and I can post comments OK). However, the code below produces a nasty 500 error: TemplateSyntaxError: not well-formed (invalid token): line 25, column 121 (line 25 is the <script> line). <div py:def="content"> <div id="recentcomments" class="dsq-widget"> <h2 class="dsq-widget-title">Recent Comments</h2> <script type="text/javascript" src="http://disqus.com/forums/wdmmg/recent_comments_widget.js num_items=5&hide_avatars=0&avatar_size=32&excerpt_length=200"></script> </div> </div> Weirdly, I think it might be something to do with the & symbols in the GET request, because using <script type="text/javascript" src="http://disqus.com/forums/wdmmg/recent_comments_widget.js ?num_items=5"></script> in the same line works fine. Does Genshi dislike & symbols, or is something else going on? A: In XML, you should encode your ampersands, since they have special meaning. Correct way to use them in urls is recent_comments_widget.js?num_items=5&amp;hide_avatars=0&amp;avatar_size=32&amp;excerpt_length=200 A: In the first snippet you don't have ? before num_items and in the second you do. Try adding it to the first one and check, if it works.
Genshi: TemplateSyntaxError: not well-formed (invalid token) with ampersands in
I'm using Pylons/Genshi, and trying to show 'all recent comments' on my site with a Disqus javascript widget (Disqus is installed on the site, and I can post comments OK). However, the code below produces a nasty 500 error: TemplateSyntaxError: not well-formed (invalid token): line 25, column 121 (line 25 is the <script> line). <div py:def="content"> <div id="recentcomments" class="dsq-widget"> <h2 class="dsq-widget-title">Recent Comments</h2> <script type="text/javascript" src="http://disqus.com/forums/wdmmg/recent_comments_widget.js num_items=5&hide_avatars=0&avatar_size=32&excerpt_length=200"></script> </div> </div> Weirdly, I think it might be something to do with the & symbols in the GET request, because using <script type="text/javascript" src="http://disqus.com/forums/wdmmg/recent_comments_widget.js ?num_items=5"></script> in the same line works fine. Does Genshi dislike & symbols, or is something else going on?
[ "In XML, you should encode your ampersands, since they have special meaning.\nCorrect way to use them in urls is recent_comments_widget.js?num_items=5&amp;hide_avatars=0&amp;avatar_size=32&amp;excerpt_length=200\n", "In the first snippet you don't have ? before num_items and in the second you do. Try adding it to...
[ 4, 1 ]
[]
[]
[ "genshi", "pylons", "python" ]
stackoverflow_0003408248_genshi_pylons_python.txt
Q: How to assert that zero or only one of N given arguments is passed I have a definition like this def bar(self, foo=None, bar=None, baz=None): pass I want to make sure a maximum of one of foo, bar, baz is passed. I can do if foo and bar: raise Ex() if foo and baz: raise Ex() .... But there got be something simpler. A: How about: initialisers = [foo, bar, baz] if initialisers.count(None) < len(initialisers) - 1: raise Ex() It simply counts how many None are present. If they're all None or only one isn't then fine, otherwise it raises the exception. A: x!=None returns True (whose numeric value is 1!) for non-Nones, False (whose numeric value is 0) for Nones. So, sum(x!=None for x in (foo, bar, baz)) is the simplest way to count how many of those identifiers are bound to non-None values (and you can check that count against 1 just like other answers do for their ways of obtaining the count). This is a very general approach in that instead of x!=None you could be using any strictly-bool predicate of interest; for example if you have a bunch of integers and want to know how many of them have 3 as the first digit of their decimal representation, sum(str(abs(x)).startswith('3') for x in (a, b, c, d, e)) works fine too. Don't be queasy about "summing bools": Python bools are sharply defined as a subclass of int with exactly two instances which have peculiar str/repr but otherwise behave exactly like the plain ints 0 and 1. There are good pragmatical reasons for this design and the ability to do arithmetic on bools is one of them, so feel free to use that ability!-) A: Try count = sum(map(lambda x: 0 if x is None else 1, (foo, bar, baz))) if count > 1: raise Ex() That turns None into 0 and everything into 1 and then sums everything up. A: I have even shorter answer, with my favorite python feature - decorators: def single_keyword(func): def single_keyword_dec(*args, **kw): if len(kw) > 1: raise Exception("More than one initializer passed: {0}".format(kw.keys())) return func(*args, **kw) return single_keyword_dec @single_keyword def some_func(self, foo=None, bar=None, baz=None): print foo, bar, baz some_func(object, foo=0) some_func(object, foo=0, bar=0) #result 0 None None Traceback (most recent call last): File "dec2.py", line 13, in <module> some_func(object, foo=0, bar=0) File "dec2.py", line 4, in single_keyword_dec raise Exception("More than one initializer passed: {0}".format(kw.keys())) Exception: More than one initializer passed: ['foo', 'bar'] If you need distinguish between 'foo', 'bar', 'baz' and some other keywords, you could make similiar decorator which would accept list of keywords to restrict, and use it like this: @single_keyword('foo', 'bar', 'baz') This way its 100% code reuse, no typing same thing over and over, and you get proper keywords in your function, not some obscure dict. A: if len(filter(lambda x: x != None, locals().values())) > 1: raise Exception() Edited to address Alex's point.
How to assert that zero or only one of N given arguments is passed
I have a definition like this def bar(self, foo=None, bar=None, baz=None): pass I want to make sure a maximum of one of foo, bar, baz is passed. I can do if foo and bar: raise Ex() if foo and baz: raise Ex() .... But there got be something simpler.
[ "How about:\n initialisers = [foo, bar, baz]\n if initialisers.count(None) < len(initialisers) - 1:\n raise Ex()\n\nIt simply counts how many None are present. If they're all None or only one isn't then fine, otherwise it raises the exception.\n", "x!=None returns True (whose numeric value is 1!) for non-None...
[ 9, 6, 4, 2, 1 ]
[ "Like this.\ndef func( self, **kw ):\n assert len(kw) == 1, \"Too Many Arguments\"\n assert kw.keys[0] in ( 'foo', 'bar', 'baz' ), \"Argument not foo, bar or baz\"\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0001648956_python.txt
Q: Writing binary data to middle of a sparse file I need to compile a binary file in pieces with pieces arriving in random order (yes, its a P2P project) def write(filename, offset, data) file.open(filename, "ab") file.seek(offset) file.write(data) file.close() Say I have a 32KB write(f, o, d) at offset 1MB into file and then another 32KB write(f, o, d) at offset 0 I end up with a file 65KB in length (i.e. the gap consisting of 0s between 32KB - 1MB is truncated/disappears) I am aware this may appear an incredibly stupid question, but I cannot seem to figure it out from the file.open(..) modes Advice gratefully received. *** UPDATE My method to write P2P pieces ended up as follows (for those who may glean some value from it) def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts): file = open(filename,"r+b") if not self.piecemap[ipdst].has_key(pieceindex): little = struct.pack('<'+'B'*len(bytes), *bytes) # Seek to offset based on piece index file.seek(pieceindex * self.piecesize) file.write(little) file.flush() self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename)) # Remember we have this piece now in case duplicates arrive self.piecemap[ipdst][pieceindex] = True file.close() Note: I also addressed some endian issues using struct.pack which plagued me for a while. For anyone wondering, the project I am working on is to analyse BT messages captured directly off the wire. A: >>> import os >>> filename = 'tempfile' >>> def write(filename,data,offset): ... try: ... f = open(filename,'r+b') ... except IOError: ... f = open(filename,'wb') ... f.seek(offset) ... f.write(data) ... f.close() ... >>> write(filename,'1' * (1024*32),1024*1024) >>> write(filename,'1' * (1024*32),0) >>> os.path.getsize(filename) 1081344 A: You opened the file in append ("a") mode. All writes are going to the end of the file, irrespective of the calls to seek(). A: Try using 'r+b' rather than 'ab'. A: It seems to me like there's not a lot of point in trying to assemble the file until all the pieces of it are there. Why not keep the pieces separate until all are present, then write them to the final file in order? That's what most P2P apps do, AFAIK.
Writing binary data to middle of a sparse file
I need to compile a binary file in pieces with pieces arriving in random order (yes, its a P2P project) def write(filename, offset, data) file.open(filename, "ab") file.seek(offset) file.write(data) file.close() Say I have a 32KB write(f, o, d) at offset 1MB into file and then another 32KB write(f, o, d) at offset 0 I end up with a file 65KB in length (i.e. the gap consisting of 0s between 32KB - 1MB is truncated/disappears) I am aware this may appear an incredibly stupid question, but I cannot seem to figure it out from the file.open(..) modes Advice gratefully received. *** UPDATE My method to write P2P pieces ended up as follows (for those who may glean some value from it) def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts): file = open(filename,"r+b") if not self.piecemap[ipdst].has_key(pieceindex): little = struct.pack('<'+'B'*len(bytes), *bytes) # Seek to offset based on piece index file.seek(pieceindex * self.piecesize) file.write(little) file.flush() self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename)) # Remember we have this piece now in case duplicates arrive self.piecemap[ipdst][pieceindex] = True file.close() Note: I also addressed some endian issues using struct.pack which plagued me for a while. For anyone wondering, the project I am working on is to analyse BT messages captured directly off the wire.
[ ">>> import os\n>>> filename = 'tempfile'\n>>> def write(filename,data,offset):\n... try:\n... f = open(filename,'r+b')\n... except IOError:\n... f = open(filename,'wb')\n... f.seek(offset)\n... f.write(data)\n... f.close()\n...\n>>> write(filename,'1' * (1024*32),1024*1024)\n>>>...
[ 7, 4, 0, 0 ]
[]
[]
[ "binary", "file_io", "p2p", "python", "sparse_matrix" ]
stackoverflow_0003407505_binary_file_io_p2p_python_sparse_matrix.txt
Q: How to rewrite this Dictionary For Loop in Python? I have a Dictionary of Classes where the classes hold attributes that are lists of strings. I made this function to find out the max number of items are in one of those lists for a particular person. def find_max_var_amt(some_person) #pass in a patient id number, get back their max number of variables for a type of variable max_vars=0 for key, value in patients[some_person].__dict__.items(): challenger=len(value) if max_vars < challenger: max_vars= challenger return max_vars What I want to do is rewrite it so that I do not have to use the .iteritems() function. This find_max_var_amt function works fine as is, but I am converting my code from using a dictionary to be a database using the dbm module, so typical dictionary functions will no longer work for me even though the syntax for assigning and accessing the key:value pairs will be the same. Thanks for your help! A: Since dbm doesn't let you iterate over the values directly, you can iterate over the keys. To do so, you could modify your for loop to look like for key in patients[some_person].__dict__: value = patients[some_person].__dict__[key] # then continue as before I think a bigger issue, though, will be the fact that dbm only stores strings. So you won't be able to store the list directly in the database; you'll have to store a string representation of it. And that means that when you try to compute the length of the list, it won't be as simple as len(value); you'll have to develop some code to figure out the length of the list based on whatever string representation you use. It could just be as simple as len(the_string.split(',')), just be aware that you have to do it. By the way, your existing function could be rewritten using a generator, like so: def find_max_var_amt(some_person): return max(len(value) for value in patients[some_person].__dict__.itervalues()) and if you did it that way, the change to iterating over keys would look like def find_max_var_amt(some_person): dct = patients[some_person].__dict__ return max(len(dct[key]) for key in dct)
How to rewrite this Dictionary For Loop in Python?
I have a Dictionary of Classes where the classes hold attributes that are lists of strings. I made this function to find out the max number of items are in one of those lists for a particular person. def find_max_var_amt(some_person) #pass in a patient id number, get back their max number of variables for a type of variable max_vars=0 for key, value in patients[some_person].__dict__.items(): challenger=len(value) if max_vars < challenger: max_vars= challenger return max_vars What I want to do is rewrite it so that I do not have to use the .iteritems() function. This find_max_var_amt function works fine as is, but I am converting my code from using a dictionary to be a database using the dbm module, so typical dictionary functions will no longer work for me even though the syntax for assigning and accessing the key:value pairs will be the same. Thanks for your help!
[ "Since dbm doesn't let you iterate over the values directly, you can iterate over the keys. To do so, you could modify your for loop to look like\nfor key in patients[some_person].__dict__:\n value = patients[some_person].__dict__[key]\n # then continue as before\n\nI think a bigger issue, though, will be the...
[ 2 ]
[]
[]
[ "dictionary", "for_loop", "python" ]
stackoverflow_0003408725_dictionary_for_loop_python.txt
Q: Grid of clickable images in wxPython So I need to be able to open several images in a grid layout and click on the images to perform various actions. Right now I am adding the images to a grid sizer. How do I capture mouse events from a sizer? Or should I display the images in another way to make it easy to respond to mouse events? A: Bind one of the mouse events to your images eg. your_staticBitmap_object.bind(wx.EVT_LEFT_UP, self.onImageClick, your_staticBitmap_object)
Grid of clickable images in wxPython
So I need to be able to open several images in a grid layout and click on the images to perform various actions. Right now I am adding the images to a grid sizer. How do I capture mouse events from a sizer? Or should I display the images in another way to make it easy to respond to mouse events?
[ "Bind one of the mouse events to your images\neg. \nyour_staticBitmap_object.bind(wx.EVT_LEFT_UP, self.onImageClick, your_staticBitmap_object)\n\n" ]
[ 3 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003408759_python_wxpython.txt
Q: Python UTF-8 comparison a = {"a":"çö"} b = "çö" a['a'] >>> '\xc3\xa7\xc3\xb6' b.decode('utf-8') == a['a'] >>> False What is going in there? edit= I'm sorry, it was my mistake. It is still False. I'm using Python 2.6 on Ubuntu 10.04. A: Possible solutions Either write like this: a = {"a": u"çö"} b = "çö" b.decode('utf-8') == a['a'] Or like this (you may also skip the .decode('utf-8') on both sides): a = {"a": "çö"} b = "çö" b.decode('utf-8') == a['a'].decode('utf-8') Or like this (my recommendation): a = {"a": u"çö"} b = u"çö" b == a['a'] Explanation Updated based on Tim's comment. In your original code, b.decode('utf-8') == u'çö' and a['a'] == 'çö', so you're actually making the following comparison: u'çö' == 'çö' One of the objects is of type unicode, the other is of type str, so in order to execute the comparison, the str is converted to unicode and then the two unicode objects are compared. It works fine in the case of purely ASCII strings, for example: u'a' == 'a', since unicode('a') == u'a'. However, it fails in case of u'çö' == 'çö', since unicode('çö') returns the following error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128), and therefore the whole comparison returns False and issues the following warning: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal. A: b is a string, a is a dict You want (I believe): b == a['a'] A: UTF-8 is an encoding used to record Unicode text in files. However, in Python you are working with objects that have a fixed way to represent Unicode text, and that way is not UTF-8. You can still compare Unicode strings in Python, but this is unrelated to UTF-8, except that if you want to put constants into these Unicode strings, then you will need to encode the text of the file containing your source code, in UTF-8. As soon as the assignment operator is executed, the string is no longer UTF-8, but is now the Python internal representation. By the way, if you are doing comparisons with Unicode, you probably will want to use the unicodedata module and normalize the strings before comparisons are done. A: Try b == a['a'] A: You are comparing a string to a dict. >>> a = {"a":"çö"} >>> b = "çö" >>> a == b False >>> a['a'] == b True If you compare the string (b) to the member of a (a['a']), then you get the desired result. A: Make sure your code is in UTF-8 (NOT Latin-1) and/or use a coding line as so: #! /usr/bin/python # -*- coding: utf-8 -*- a = {"a": u"çö"} b = "çö" assert b == a['a'] assert b.decode('utf-8') == a['a'].decode('utf-8') If you're using unicode across the board, you can import unicode_literals from the future and cut back on encoding heartaches: #! /usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals a = {"a": u"çö"} b = "çö" assert b == a['a'] assert b == a['a'] assert b.encode('utf-8') != a['a'] assert b.encode('utf-8') == a['a'].encode('utf-8') If a file uses unicode_literals, all "strings" are now u"unicode" objects (per the coding of the file) if they're not b"prepended" with a b (to emulate the string/bytes split in Python 3.X). A: NullUserException is right that this should be correct: b == a['a'] You're still getting "False" because you're decoding one side as utf-8 (creating a Unicode string) while the other side remains a utf-8 encoded byte string.
Python UTF-8 comparison
a = {"a":"çö"} b = "çö" a['a'] >>> '\xc3\xa7\xc3\xb6' b.decode('utf-8') == a['a'] >>> False What is going in there? edit= I'm sorry, it was my mistake. It is still False. I'm using Python 2.6 on Ubuntu 10.04.
[ "Possible solutions\nEither write like this:\na = {\"a\": u\"çö\"}\nb = \"çö\"\nb.decode('utf-8') == a['a']\n\nOr like this (you may also skip the .decode('utf-8') on both sides):\na = {\"a\": \"çö\"}\nb = \"çö\"\nb.decode('utf-8') == a['a'].decode('utf-8')\n\nOr like this (my recommendation):\na = {\"a\": u\"çö\"}...
[ 30, 5, 4, 2, 2, 0, 0 ]
[]
[]
[ "python", "python_2.x", "unicode", "utf_8" ]
stackoverflow_0003400171_python_python_2.x_unicode_utf_8.txt
Q: How do I edit the url in python and open a new page without having a new window or tab opened? I am trying to create a python script that opens a single page at a time, however python + mozilla make it so everytime I do this, it opens up a new tab. I want it to keep just a single window open so that it can loop forever without crashing due to too many windows or tabs. It will be going to about 6-7 websites and the current code imports time and webbrowser. webbrowser.open('url') time.sleep(100) webbrowser.open('next url') //but here it will open a new tab, when I just want it to change the page. Any information would be greatful, Thank you. A: In firefox, if you go to about:config and set browser.link.open_newwindow to "1", that will cause a clicked link that would open in a new window or tab to stay in the current tab. I'm not sure if this applies to calls from 3rd-party apps, but it might be worth a try. Of course, this will now apply to everything you do in firefox (though ctrl + click will still open links in a new tab)
How do I edit the url in python and open a new page without having a new window or tab opened?
I am trying to create a python script that opens a single page at a time, however python + mozilla make it so everytime I do this, it opens up a new tab. I want it to keep just a single window open so that it can loop forever without crashing due to too many windows or tabs. It will be going to about 6-7 websites and the current code imports time and webbrowser. webbrowser.open('url') time.sleep(100) webbrowser.open('next url') //but here it will open a new tab, when I just want it to change the page. Any information would be greatful, Thank you.
[ "In firefox, if you go to about:config and set browser.link.open_newwindow to \"1\", that will cause a clicked link that would open in a new window or tab to stay in the current tab. I'm not sure if this applies to calls from 3rd-party apps, but it might be worth a try.\nOf course, this will now apply to everything...
[ 1 ]
[]
[]
[ "browser", "python" ]
stackoverflow_0003408891_browser_python.txt
Q: How to rotate a polygon on a Tkinter Canvas? I am working to create a version of asteroids using Python and Tkinter. When the left or right arrow key is pressed the ship needs to rotate. The ship is a triangle on the Tkinter canvas. I am having trouble coming up with formula to adjust the coordinates for the triangle. I believe it has something to do with sin and cos, though I am not exactly sure. So far I have two classes one for the ship and the other for the game. In the ship class I have callback methods for the key presses. Any help would be greatly appreciated. Thanks. Ship Class import math class Ship: def __init__(self,canvas,x,y,width,height): self.canvas = canvas self.x = x - width/2 self.y = y + height/2 self.width = width self.height = height self.x0 = self.x self.y0 = self.y self.x1 = self.x0 + self.width/2 self.y1 = self.y0-self.height self.x2 = self.x0 + self.width self.y2 = self.y0 self.ship = self.canvas.create_polygon((self.x0, self.y0, self.x1, self.y1, self.x2, self.y2), outline="white", width=3) def changeCoords(self): self.canvas.coords(self.ship,self.x0, self.y0, self.x1, self.y1, self.x2, self.y2) def rotateLeft(self, event=None): # Should rotate one degree left. pass def rotateRight(self, event=None): # Should rotate one degree right. self.x0 = self.x0 -1 self.y0 = self.y0 - 1 self.x1 = self.x1 + 1 self.y1 = self.y1 + 1 self.x2 = self.x2 - 1 self.y2 = self.y2 + 1 self.changeCoords() Game Class from Tkinter import * from ship import * class Game: def __init__(self, gameWidth, gameHeight): self.root = Tk() self.gameWidth = gameWidth self.gameHeight = gameHeight self.gameWindow() self.ship = Ship(self.canvas, x=self.gameWidth/2,y=self.gameHeight/2, width=50, height=50) self.root.bind('<Left>', self.ship.rotateLeft) self.root.bind('<Right>', self.ship.rotateRight) self.root.mainloop() def gameWindow(self): self.frame = Frame(self.root) self.frame.pack(fill=BOTH, expand=YES) self.canvas = Canvas(self.frame,width=self.gameWidth, height=self.gameHeight, bg="black", takefocus=1) self.canvas.pack(fill=BOTH, expand=YES) asteroids = Game(600,600) A: First of all, you need to rotate around a center of the triangle. The centroid would probably work best for that. To find that, you can use the formula C = (1/3*(x0 + x1 + x2), 1/3*(y0 + y1 + y2)), as it's the average of all points in the triangle. Then you have to apply the rotation with that point as the center. So it'd be something like this... import math class Ship: def centroid(self): return 1 / 3 * (self.x0 + self.x1 + self.x2), 1 / 3 * (self.y0 + self.y1 + self.y2) def __init__(self, canvas, x, y, width, height, turnspeed, acceleration=1): self._d = {'Up':1, 'Down':-1, 'Left':1, 'Right':-1} self.canvas = canvas self.width = width self.height = height self.speed = 0 self.turnspeed = turnspeed self.acceleration = acceleration self.x0, self.y0 = x, y self.bearing = -math.pi / 2 self.x1 = self.x0 + self.width / 2 self.y1 = self.y0 - self.height self.x2 = self.x0 + self.width self.y2 = self.y0 self.x, self.y = self.centroid() self.ship = self.canvas.create_polygon((self.x0, self.y0, self.x1, self.y1, self.x2, self.y2), outline="white", width=3) def changeCoords(self): self.canvas.coords(self.ship,self.x0, self.y0, self.x1, self.y1, self.x2, self.y2) def rotate(self, event=None): t = self._d[event.keysym] * self.turnspeed * math.pi / 180 # the trig functions generally take radians as their arguments rather than degrees; pi/180 radians is equal to 1 degree self.bearing -= t def _rot(x, y): #note: the rotation is done in the opposite fashion from for a right-handed coordinate system due to the left-handedness of computer coordinates x -= self.x y -= self.y _x = x * math.cos(t) + y * math.sin(t) _y = -x * math.sin(t) + y * math.cos(t) return _x + self.x, _y + self.y self.x0, self.y0 = _rot(self.x0, self.y0) self.x1, self.y1 = _rot(self.x1, self.y1) self.x2, self.y2 = _rot(self.x2, self.y2) self.x, self.y = self.centroid() self.changeCoords() def accel(self, event=None): mh = int(self.canvas['height']) mw = int(self.canvas['width']) self.speed += self.acceleration * self._d[event.keysym] self.x0 += self.speed * math.cos(self.bearing) self.x1 += self.speed * math.cos(self.bearing) self.x2 += self.speed * math.cos(self.bearing) self.y0 += self.speed * math.sin(self.bearing) self.y1 += self.speed * math.sin(self.bearing) self.y2 += self.speed * math.sin(self.bearing) self.x, self.y = self.centroid() if self.y < - self.height / 2: self.y0 += mh self.y1 += mh self.y2 += mh elif self.y > mh + self.height / 2: self.y0 += mh self.y1 += mh self.y2 += mh if self.x < -self.width / 2: self.x0 += mw self.x1 += mw self.x2 += mw elif self.x > mw + self.width / 2: self.x0 -= mw self.x1 -= mw self.x2 -= mw self.x, self.y = self.centroid() self.changeCoords() I made some changes to the controls that make the game a bit more like Asteroids, by the way. (Didn't implement firing, though. I may have gotten more into this than I expected, but I'm not going to do everything. Also, there's a bit of a problem when you try to use multiple movement keys at once, but that's due to the way Tk does event handling. It wasn't designed for gaming, so you'd have to fiddle around a fair bit to get that working properly with Tk/Tkinter.) from tkinter import * from ship import * class Game: def __init__(self, gameWidth, gameHeight): self.root = Tk() self.gameWidth = gameWidth self.gameHeight = gameHeight self.gameWindow() self.ship = Ship(self.canvas, x=self.gameWidth / 2,y=self.gameHeight / 2, width=50, height=50, turnspeed=10, acceleration=5) self.root.bind('<Left>', self.ship.rotate) self.root.bind('<Right>', self.ship.rotate) self.root.bind('<Up>', self.ship.accel) self.root.bind('<Down>', self.ship.accel) self.root.mainloop() def gameWindow(self): self.frame = Frame(self.root) self.frame.pack(fill=BOTH, expand=YES) self.canvas = Canvas(self.frame,width=self.gameWidth, height=self.gameHeight, bg="black", takefocus=1) self.canvas.pack(fill=BOTH, expand=YES) asteroids = Game(600,600) As an aside, you might want to use properties to allow for easier handling of the points and such.
How to rotate a polygon on a Tkinter Canvas?
I am working to create a version of asteroids using Python and Tkinter. When the left or right arrow key is pressed the ship needs to rotate. The ship is a triangle on the Tkinter canvas. I am having trouble coming up with formula to adjust the coordinates for the triangle. I believe it has something to do with sin and cos, though I am not exactly sure. So far I have two classes one for the ship and the other for the game. In the ship class I have callback methods for the key presses. Any help would be greatly appreciated. Thanks. Ship Class import math class Ship: def __init__(self,canvas,x,y,width,height): self.canvas = canvas self.x = x - width/2 self.y = y + height/2 self.width = width self.height = height self.x0 = self.x self.y0 = self.y self.x1 = self.x0 + self.width/2 self.y1 = self.y0-self.height self.x2 = self.x0 + self.width self.y2 = self.y0 self.ship = self.canvas.create_polygon((self.x0, self.y0, self.x1, self.y1, self.x2, self.y2), outline="white", width=3) def changeCoords(self): self.canvas.coords(self.ship,self.x0, self.y0, self.x1, self.y1, self.x2, self.y2) def rotateLeft(self, event=None): # Should rotate one degree left. pass def rotateRight(self, event=None): # Should rotate one degree right. self.x0 = self.x0 -1 self.y0 = self.y0 - 1 self.x1 = self.x1 + 1 self.y1 = self.y1 + 1 self.x2 = self.x2 - 1 self.y2 = self.y2 + 1 self.changeCoords() Game Class from Tkinter import * from ship import * class Game: def __init__(self, gameWidth, gameHeight): self.root = Tk() self.gameWidth = gameWidth self.gameHeight = gameHeight self.gameWindow() self.ship = Ship(self.canvas, x=self.gameWidth/2,y=self.gameHeight/2, width=50, height=50) self.root.bind('<Left>', self.ship.rotateLeft) self.root.bind('<Right>', self.ship.rotateRight) self.root.mainloop() def gameWindow(self): self.frame = Frame(self.root) self.frame.pack(fill=BOTH, expand=YES) self.canvas = Canvas(self.frame,width=self.gameWidth, height=self.gameHeight, bg="black", takefocus=1) self.canvas.pack(fill=BOTH, expand=YES) asteroids = Game(600,600)
[ "First of all, you need to rotate around a center of the triangle. The centroid would probably work best for that. To find that, you can use the formula C = (1/3*(x0 + x1 + x2), 1/3*(y0 + y1 + y2)), as it's the average of all points in the triangle. Then you have to apply the rotation with that point as the center....
[ 12 ]
[]
[]
[ "python", "tkinter", "vector" ]
stackoverflow_0003408779_python_tkinter_vector.txt
Q: Python regex string to list of words (including words with hyphens) I would like to parse a string to obtain a list including all words (hyphenated words, too). Current code is: s = '-this is. A - sentence;one-word' re.compile("\W+",re.UNICODE).split(s) returns: ['', 'this', 'is', 'A', 'sentence', 'one', 'word'] and I would like it to return: ['', 'this', 'is', 'A', 'sentence', 'one-word'] A: If you don't need the leading empty string, you could use the pattern \w(?:[-\w]*\w)? for matching: >>> import re >>> s = '-this is. A - sentence;one-word' >>> rx = re.compile(r'\w(?:[-\w]*\w)?') >>> rx.findall(s) ['this', 'is', 'A', 'sentence', 'one-word'] Note that it won't match words with apostrophes like won't. A: Here my traditional "why to use regexp language when you can use Python" alternative: import string s = "-this is. A - sentence;one-word what's" s = filter(None,[word.strip(string.punctuation) for word in s.replace(';','; ').split() ]) print s """ Output: ['this', 'is', 'A', 'sentence', 'one-word', "what's"] """ A: You could use "[^\w-]+" instead. A: s = "-this is. A - sentence;one-word what's" re.findall("\w+-\w+|[\w']+",s) result: ['this', 'is', 'A', 'sentence', 'one-word', "what's"] make sure you notice that the correct ordering is to look for hyypenated words first! A: Yo can try with the NLTK library: >>> import nltk >>> s = '-this is a - sentence;one-word' >>> hyphen = r'(\w+\-\s?\w+)' >>> wordr = r'(\w+)' >>> r = "|".join([ hyphen, wordr]) >>> tokens = nltk.tokenize.regexp_tokenize(s,r) >>> print tokens ['this', 'is', 'a', 'sentence', 'one-word'] I found it here: http://www.cs.oberlin.edu/~jdonalds/333/lecture03.html Hope it helps
Python regex string to list of words (including words with hyphens)
I would like to parse a string to obtain a list including all words (hyphenated words, too). Current code is: s = '-this is. A - sentence;one-word' re.compile("\W+",re.UNICODE).split(s) returns: ['', 'this', 'is', 'A', 'sentence', 'one', 'word'] and I would like it to return: ['', 'this', 'is', 'A', 'sentence', 'one-word']
[ "If you don't need the leading empty string, you could use the pattern \\w(?:[-\\w]*\\w)? for matching:\n>>> import re\n>>> s = '-this is. A - sentence;one-word'\n>>> rx = re.compile(r'\\w(?:[-\\w]*\\w)?')\n>>> rx.findall(s)\n['this', 'is', 'A', 'sentence', 'one-word']\n\nNote that it won't match words with apostro...
[ 4, 2, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003406771_python_regex.txt
Q: Python: saving image from web to disk Can I save images to disk using python? An example of an image would be: A: Easiest is to use urllib.urlretrieve. Python 2: import urllib urllib.urlretrieve('http://chart.apis.google.com/...', 'outfile.png') Python 3: import urllib.request urllib.request.urlretrieve('http://chart.apis.google.com/...', 'outfile.png') A: If your goal is to download a png to disk, you can do so with urllib: import urllib urladdy = "http://chart.apis.google.com/chart?chxl=1:|0|10|100|1%2C000|10%2C000|100%2C000|1%2C000%2C000|2:||Excretion+in+Nanograms+per+gram+creatinine+milliliter+(logarithmic+scale)|&chxp=1,0|2,0&chxr=0,0,12.1|1,0,3&chxs=0,676767,13.5,0,lt,676767|1,676767,13.5,0,l,676767&chxtc=0,-1000&chxt=y,x,x&chbh=a,1,0&chs=640x465&cht=bvs&chco=A2C180&chds=0,12.1&chd=t:0,0,0,0,0,0,0,0,0,1,0,0,3,2,4,6,6,9,3,6,5,11,9,10,6,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0&chdl=n=87&chtt=William+MD+-+Buprenorphine+Graph" filename = r"c:\tmp\toto\file.png" urllib.urlretrieve(urladdy, filename) In python 3, you will need to use urllib.request.urlretrieve instead of urllib.urlretrieve. A: The Google chart API produces PNG files. Just retrieve them with urllib.urlopen(url).read() or something along these lines and safe to a file the usual way. Full example: >>> import urllib >>> url = 'http://chart.apis.google.com/chart?chxl=1:|0|10|100|1%2C000|10%2C000|100%2C000|1%2C000%2C000|2:||Excretion+in+Nanograms+per+gram+creatinine+milliliter+(logarithmic+scale)|&chxp=1,0|2,0&chxr=0,0,12.1|1,0,3&chxs=0,676767,13.5,0,lt,676767|1,676767,13.5,0,l,676767&chxtc=0,-1000&chxt=y,x,x&chbh=a,1,0&chs=640x465&cht=bvs&chco=A2C180&chds=0,12.1&chd=t:0,0,0,0,0,0,0,0,0,1,0,0,3,2,4,6,6,9,3,6,5,11,9,10,6,2,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0&chdl=n=87&chtt=William+MD+-+Buprenorphine+Graph' >>> image = urllib.urlopen(url).read() >>> outfile = open('chart01.png','wb') >>> outfile.write(image) >>> outfile.close() As noted in other examples, 'urllib.urlretrieve(url, outfilename)` is even more straightforward, but playing with urllib and urllib2 will surely be instructive for you.
Python: saving image from web to disk
Can I save images to disk using python? An example of an image would be:
[ "Easiest is to use urllib.urlretrieve.\nPython 2:\nimport urllib\nurllib.urlretrieve('http://chart.apis.google.com/...', 'outfile.png')\n\nPython 3:\nimport urllib.request\nurllib.request.urlretrieve('http://chart.apis.google.com/...', 'outfile.png')\n\n", "If your goal is to download a png to disk, you can do so...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003409104_python.txt
Q: Replacing a blank i am building a URL and replacing all the spaces with + url.replace(' ','+') for some reason it is not replacing any of the white spaces! anyone know what is wrong? A: The replace function doesn't replace anything in-place - you need to assign it: url = url.replace(' ','+') A: You are probbly still looking at the old url. replace returns new string with replaced values. Try: url = url.replace(' ', '+') A: Aside: If you are encoding a query or path component for inclusion in a URL, you will need to do more than simply replacing the space character. There are many other characters which won't fit unencoded into a URL component, and which may break the URL if you try. These have to be replaced by %nn hexadecimal escape sequences. Use urllib to take care of URL-encoding rather than trying to do it yourself with string methods. For example: >>> import urllib >>> param= 'Hello world!' >>> url= 'http://www.example.com/script.py?a='+urllib.quote_plus(param) >>> url 'http://www.example.com/script.py?a=Hello+world%21' (urllib.quote_plus() is designed explicitly for form parameters in the query string, so it'll use + for spaces, as opposed to %20 which urllib.quote() produces. %20 works in path components as well as query components, so it's a bit safer than +, but slightly more messy visually.) If you have more than one parameter, use urlencode() on a dictionary. This is generally easier to read than trying to stick strings together: >>> params= {'foo': 'bar', 'bof': 'Hello world!'} >>> url= 'http://www.example.com/script.py?'+urllib.urlencode(params) >>> url 'http://www.example.com/script.py?foo=bar&bof=Hello+world%21'
Replacing a blank
i am building a URL and replacing all the spaces with + url.replace(' ','+') for some reason it is not replacing any of the white spaces! anyone know what is wrong?
[ "The replace function doesn't replace anything in-place - you need to assign it:\nurl = url.replace(' ','+')\n\n", "You are probbly still looking at the old url. replace returns new string with replaced values. Try:\nurl = url.replace(' ', '+')\n\n", "Aside:\nIf you are encoding a query or path component for in...
[ 5, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003408772_python.txt
Q: Pythonistas, please help convert this to utilize Python Threading concepts Update : For anyone wondering what I went with at the end - I divided the result-set into 4 and ran 4 instances of the same program with one argument each indicating what set to process. It did the trick for me. I also consider PP module. Though it worked, it prefer the same program. Please pitch in if this is a horrible implementation! Thanks.. Following is what my program does. Nothing memory intensive. It is serial processing and boring. Could you help me convert this to more efficient and exciting process? Say, I process 1000 records this way and with 4 threads, I can get it to run in 25% time! I read articles on how python threading can be inefficient if done wrong. Even python creator says the same. So I am scared and while I am reading more about them, want to see if bright folks on here can steer me in the right direction. Muchos gracias! def startProcessing(sernum, name): ''' Bunch of statements depending on result, will write to database (one update statement) Try Catch blocks which upon failing, will call this function until the request succeeds. ''' for record in result: startProc = startProcessing(str(record[0]), str(record[1])) A: Python threads can't run at the same time due to the Global Interpreter Lock; you want new processes instead. Look at the multiprocessing module. (I was instructed to post this as an answer =p.)
Pythonistas, please help convert this to utilize Python Threading concepts
Update : For anyone wondering what I went with at the end - I divided the result-set into 4 and ran 4 instances of the same program with one argument each indicating what set to process. It did the trick for me. I also consider PP module. Though it worked, it prefer the same program. Please pitch in if this is a horrible implementation! Thanks.. Following is what my program does. Nothing memory intensive. It is serial processing and boring. Could you help me convert this to more efficient and exciting process? Say, I process 1000 records this way and with 4 threads, I can get it to run in 25% time! I read articles on how python threading can be inefficient if done wrong. Even python creator says the same. So I am scared and while I am reading more about them, want to see if bright folks on here can steer me in the right direction. Muchos gracias! def startProcessing(sernum, name): ''' Bunch of statements depending on result, will write to database (one update statement) Try Catch blocks which upon failing, will call this function until the request succeeds. ''' for record in result: startProc = startProcessing(str(record[0]), str(record[1]))
[ "Python threads can't run at the same time due to the Global Interpreter Lock; you want new processes instead. Look at the multiprocessing module.\n(I was instructed to post this as an answer =p.)\n" ]
[ 1 ]
[]
[]
[ "multithreading", "parallel_processing", "python" ]
stackoverflow_0003406654_multithreading_parallel_processing_python.txt
Q: Why am I getting this simplejson exception? Why does Django give me this exception [(7, u'Acura'), (18, u'Alfa Romeo'), ...] is not JSON serializable When I try data = VehicleMake.objects.filter(model__start_year__gte=request.GET.get('year',0)).values_list('id','name') return HttpResponse(simplejson.dumps(data, ensure_ascii=False), mimetype='application/json') ? It's just a simple list of tuples. It works with my other hard-coded list that's in almost exactly the same format. Is it because the strings are unicode? How do I handle that? It works fine when I encode it as a dict: def get_makes(request): year = request.GET.get('year',0) data = VehicleMake.objects.filter(model__start_year__lte=year, model__stop_year__gte=year).order_by('name').distinct().values_list('id','name') return HttpResponse(simplejson.dumps(odict(data), ensure_ascii=False), mimetype='application/json') Some makes have accented characters... could that be it? Yes, the list is big (~900 makes total). A: This seems to work fine: In [28]: a = [(7, u'Acura'), (18, u'Alfa Romeo'),] In [29]: simplejson.dumps(a, ensure_ascii=False) Out[29]: u'[[7, "Acura"], [18, "Alfa Romeo"]]' So it's not the first couple of tuples. You'll need to dig deeper in the records list to narrow down the issue. If it's large, perhaps take some slices of the data list and try encoding those, to see if the error occurs in any particular segment. UPDATE: OK, it's probably because your data object is a QuerySet and simplejson doesn't handle that. Try using django's serialize instead. (Or coerce the data to a list.) from django.core import serializers json_serializer = serializers.get_serializer("json")() json_serializer.serialize(data, ensure_ascii=False, stream=response) A: Ticket #6234 claims that leaving out ensure_ascii=False will resolve the problem (but I am not sure if the problem is really understood): Simply omitting ensure_ascii parameter resolves the issue even though it makes no sense. A: Instead of return HttpResponse(simplejson.dumps(data, ensure_ascii=False), mimetype='application/json') Use list(data) and modify your Javascript to work with it. for(i in values) { $select.append('<option value="'+values[i][0]+'">'+values[i][1]+'</option>'); }
Why am I getting this simplejson exception?
Why does Django give me this exception [(7, u'Acura'), (18, u'Alfa Romeo'), ...] is not JSON serializable When I try data = VehicleMake.objects.filter(model__start_year__gte=request.GET.get('year',0)).values_list('id','name') return HttpResponse(simplejson.dumps(data, ensure_ascii=False), mimetype='application/json') ? It's just a simple list of tuples. It works with my other hard-coded list that's in almost exactly the same format. Is it because the strings are unicode? How do I handle that? It works fine when I encode it as a dict: def get_makes(request): year = request.GET.get('year',0) data = VehicleMake.objects.filter(model__start_year__lte=year, model__stop_year__gte=year).order_by('name').distinct().values_list('id','name') return HttpResponse(simplejson.dumps(odict(data), ensure_ascii=False), mimetype='application/json') Some makes have accented characters... could that be it? Yes, the list is big (~900 makes total).
[ "This seems to work fine:\nIn [28]: a = [(7, u'Acura'), (18, u'Alfa Romeo'),]\n\nIn [29]: simplejson.dumps(a, ensure_ascii=False)\nOut[29]: u'[[7, \"Acura\"], [18, \"Alfa Romeo\"]]'\n\nSo it's not the first couple of tuples. You'll need to dig deeper in the records list to narrow down the issue. If it's large, pe...
[ 2, 1, 0 ]
[]
[]
[ "django", "exception", "python", "simplejson" ]
stackoverflow_0003269541_django_exception_python_simplejson.txt
Q: Appengine Blobstore - Video Streaming I'm trying to setup a video streaming app via the Google Appengine Blobstore. Just wanted to know if this was possible, as there isn't too much regarding this in the Appengine Documentation. Basically I want to serve these videos through a flash player. Thanks A: I would say the blobstore is suitable for this. While datastore entities are limited to 1MB and standard HTTP responses are limited to 10MB, with the blobstore you can upload, store, and serve files up to 2GB. The 30 second limit refers to how long your handler can execute; time spent downloading (or uploading) doesn't count towards this limit. The blobstore also supports byte ranges, so if your flash component supports it, you can seek to random positions in the video without downloading everything first.
Appengine Blobstore - Video Streaming
I'm trying to setup a video streaming app via the Google Appengine Blobstore. Just wanted to know if this was possible, as there isn't too much regarding this in the Appengine Documentation. Basically I want to serve these videos through a flash player. Thanks
[ "I would say the blobstore is suitable for this. While datastore entities are limited to 1MB and standard HTTP responses are limited to 10MB, with the blobstore you can upload, store, and serve files up to 2GB. The 30 second limit refers to how long your handler can execute; time spent downloading (or uploading) do...
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003409549_google_app_engine_python.txt
Q: Limiting the searching of a large file So here is my program with some new modifications: datafile = open('C:\\text2.txt', 'r') completedataset = open('C:\\bigfile.txt', 'r') smallerdataset = open('C:\\smallerdataset.txt', 'w') matchedLines = [] for line in datafile: splitline = line.split() for item in splitline: if not item.endswith("NOVA"): if item.startswith("JJJ") or item.startswith("KOS"): matchedLines.append( item ) counter = 1 for line in completedataset: print counter counter +=1 for t in matchedLines: if t in line: smallerdataset.write(line) datafile.close() completedataset.close() smallerdataset.close() The problem that I have now is that I want to search through the "bigfile" but at a faster rate. I would like to limit the searching of each line in bigfile to the string that occurs before the first ',' I want to use something like index = aString.find(',') I beleive but I'm not having much luck limiting the search of the big file to the string that occurs before the first comma. A: For your splitting issue you can just limit the number of times it splits the line: first_item = str.split(",",maxsplit=1)[0] A: You could change if t in line: to if t in line[:line.find(',')]: This may make the program faster if line is very very long and the comma appears near the beginning. Or it may make the program slower if , appears near the end of the line. PS. Is every line guaranteed to have a comma in it? The above code acts a bit funky if there is no comma. For example, In [21]: line='a line of text' In [22]: line[:line.find(',')] Out[22]: 'a line of tex' If you want to ignore lines without a comma, this might be better: In [23]: line[:line.find(',')+1] Out[23]: '' A: this may help speed it up...sorry about the lack of tabbing datafile = open('C:\\text2.txt', 'r') completedataset = open('C:\\bigfile.txt', 'r') smallerdataset = open('C:\\smallerdataset.txt', 'w') matchedLines = [] counter = 1 for line in datafile.readlines(): if line[-4:] == "NOVA": if (line[:3] == "JJJ") or (line[:3] =="KOS"): counter += 1 for compline in completedataset: if line in compline: smallerdataset.write(line) datafile.close() completedataset.close() smallerdataset.close()
Limiting the searching of a large file
So here is my program with some new modifications: datafile = open('C:\\text2.txt', 'r') completedataset = open('C:\\bigfile.txt', 'r') smallerdataset = open('C:\\smallerdataset.txt', 'w') matchedLines = [] for line in datafile: splitline = line.split() for item in splitline: if not item.endswith("NOVA"): if item.startswith("JJJ") or item.startswith("KOS"): matchedLines.append( item ) counter = 1 for line in completedataset: print counter counter +=1 for t in matchedLines: if t in line: smallerdataset.write(line) datafile.close() completedataset.close() smallerdataset.close() The problem that I have now is that I want to search through the "bigfile" but at a faster rate. I would like to limit the searching of each line in bigfile to the string that occurs before the first ',' I want to use something like index = aString.find(',') I beleive but I'm not having much luck limiting the search of the big file to the string that occurs before the first comma.
[ "For your splitting issue you can just limit the number of times it splits the line:\nfirst_item = str.split(\",\",maxsplit=1)[0]\n\n", "You could change\nif t in line:\n\nto\nif t in line[:line.find(',')]:\n\nThis may make the program faster if line is very very long and the comma appears near the beginning. Or ...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003408871_python.txt
Q: Accessing Dictionaries VS Accessing Shelves Currently, I have a dictionary that has a number as the key and a Class as a value. I can access the attributes of that Class like so: dictionary[str(instantiated_class_id_number)].attribute1 Due to memory issues, I want to use the shelve module. I am wondering if doing so is plausible. Does a shelve dictionary act the exact same as a standard dictionary? If not, how does it differ? A: Shelve doesn't act extactly the same as dictionary, notably when modifying objects that are already in the dictionary. The difference is that when you add a class to a dictionary a reference is stored, but shelve keeps a pickled (serialized) copy of the object. If you then modify the object you will modify the in-memory copy, but not the pickled version. That can be handled (mostly) transparently by shelf.sync() and shelf.close(), which write out entries. Making all that work does require tracking all retrieved objects which haven't been written back yet so you do have to call shelf.sync() to clear the cache. The problem with shelf.sync() clearing the cache is that you can keep a reference to the object and modify it again. This code doesn't work as expected with a shelf, but will work with a dictionary: s["foo"] = MyClass() s["foo"].X = 8 p = s["foo"] # store a reference to the object p.X = 9 # update the reference s.sync() # flushes the cache p.X = 0 print "value in memory: %d" % p.X # prints 0 print "value in shelf: %d" % s["foo"].X # prints 9 Sync flushes the cache so the modified 'p' object is lost from the cache so it isn't written back. A: Yes, it is plausible: Shelf objects support all methods supported by dictionaries. This eases the transition from dictionary based scripts to those requiring persistent storage. You need to call shelf.sync() every so often to clear the cache. EDIT Take care, it's not exactly a dict. See e.g. Laurion's answer. Oh, and you can only have str keys.
Accessing Dictionaries VS Accessing Shelves
Currently, I have a dictionary that has a number as the key and a Class as a value. I can access the attributes of that Class like so: dictionary[str(instantiated_class_id_number)].attribute1 Due to memory issues, I want to use the shelve module. I am wondering if doing so is plausible. Does a shelve dictionary act the exact same as a standard dictionary? If not, how does it differ?
[ "Shelve doesn't act extactly the same as dictionary, notably when modifying objects that are already in the dictionary.\nThe difference is that when you add a class to a dictionary a reference is stored, but shelve keeps a pickled (serialized) copy of the object. If you then modify the object you will\nmodify the i...
[ 3, 0 ]
[]
[]
[ "dictionary", "python", "shelve" ]
stackoverflow_0003409856_dictionary_python_shelve.txt
Q: Getting started with Pylons and MVC - Need some guidance on design I've been getting more and more interested in using Pylons as my Python web framework and I like the idea of MVC but, coming from a background of never using 'frameworks/design patterns/ what ever it\'s called', I don't really know how to approach it. From what I've read in the Pylons Book, so far, it seems I do the following: Create my routes in ./config/routes.py This is where I map URLs to controllers. Create a controller for the URL This is where the main body of the code lies. It does all the work and prepares it for viewing Create my template I create a template and assign the data from the controller to it Models... I have no idea what they're for :/ So my question is, can you recommend any reading materials for someone who clearly has no idea what they're doing? I really want to start using Pylons but I think in a few months time I'll come back to my code and think "...what the F was I thinking :/" EDIT: A better, summarized, question came to mind: What code should be placed in the Controller? What code should I put in the Model? The view is just the templating, right? And, in terms of Pylons, the 'lib' folder will contain code shared among Controllers or misc code that doesn't fit anywhere else - Right? A: there is a book about pylons 0.9.7 [http://pylonsbook.com/]. and after that see the updated docs to understand pylons 1 at [http://bitbucket.org/bbangert/quickwiki] and [http://bitbucket.org/bbangert/pylons]. if you have a question go to the google groups for pylons [http://groups.google.com/group/pylons-discuss] A: Model is for your db-related code. All queries go there, including adding new records/updating existing ones. Controllers are somewhat ambigous, different projects use different approaches to it. Reddit for example does fair bit of what should be View in controllers. I, for one, prefer to limit my controllers to request processing and generation of some result object collections, which are then delivered to XHTML/XML/JSON views, depending on the type of request (so each controller should be used for both static page generation and AJAX handling). I really want to start using Pylons but I think in a few months time I'll come back to my code and think "...what the F was I thinking :/" Well, thats inevitable, you should try different approaches to find the one which suits you best.
Getting started with Pylons and MVC - Need some guidance on design
I've been getting more and more interested in using Pylons as my Python web framework and I like the idea of MVC but, coming from a background of never using 'frameworks/design patterns/ what ever it\'s called', I don't really know how to approach it. From what I've read in the Pylons Book, so far, it seems I do the following: Create my routes in ./config/routes.py This is where I map URLs to controllers. Create a controller for the URL This is where the main body of the code lies. It does all the work and prepares it for viewing Create my template I create a template and assign the data from the controller to it Models... I have no idea what they're for :/ So my question is, can you recommend any reading materials for someone who clearly has no idea what they're doing? I really want to start using Pylons but I think in a few months time I'll come back to my code and think "...what the F was I thinking :/" EDIT: A better, summarized, question came to mind: What code should be placed in the Controller? What code should I put in the Model? The view is just the templating, right? And, in terms of Pylons, the 'lib' folder will contain code shared among Controllers or misc code that doesn't fit anywhere else - Right?
[ "there is a book about pylons 0.9.7 [http://pylonsbook.com/].\nand after that see the updated docs to understand pylons 1 at [http://bitbucket.org/bbangert/quickwiki]\nand [http://bitbucket.org/bbangert/pylons].\nif you have a question go to the google groups for pylons [http://groups.google.com/group/pylons-discus...
[ 0, 0 ]
[]
[]
[ "design_patterns", "model_view_controller", "pylons", "python" ]
stackoverflow_0003350972_design_patterns_model_view_controller_pylons_python.txt
Q: python, svn, deploy applications with shared code I have a few related applications that I want to deploy to different computers. They each share a large body of common code, and have some things unique to them. For example, I have a server and a client which use a lot of common classes to communicate to each other. I have yet more servers and clients which use some of the same classes, but are unrelated from each other. The easy solution is to just leave them all in the same directory structure so they can all use whichever modules they need, and whenever I deploy a server or a client I put in the entire codebase. However the codebase is quite large, and some of the components use datafiles which are a few megabytes in size. Ideally I'd be able to have them all share the same code, but be able to deploy just exactly which files each component needs... and they'd all be connected to the same version control. So it'd be something like: On one computer: svn checkout client1. On another: svn checkout server1. On another: svn checkout client2. Then if I modify some client2 code that is shared between client2 and client1, both will be updated when I do svn update. Also ideally, I wouldn't have to pick out the files I need manually, since that can be annoying, but I can deal with that. Have other people had this problem? Does it have a better-defined name? What solutions can I use to solve it? A: When it can be broken up in modules, go for a repo / branch with all the 'base' code, and in the actual project, include them as svn:externals (same repository or another one doesn't matter). That way you can independently update / work on modules, pin certain projects to certain revisions of that module or keep them to HEAD. A new project would either require a branching of a base project with most externals already set, or manual adding of the needed externals. A simple shell script setting the exact externals you need is easily made.
python, svn, deploy applications with shared code
I have a few related applications that I want to deploy to different computers. They each share a large body of common code, and have some things unique to them. For example, I have a server and a client which use a lot of common classes to communicate to each other. I have yet more servers and clients which use some of the same classes, but are unrelated from each other. The easy solution is to just leave them all in the same directory structure so they can all use whichever modules they need, and whenever I deploy a server or a client I put in the entire codebase. However the codebase is quite large, and some of the components use datafiles which are a few megabytes in size. Ideally I'd be able to have them all share the same code, but be able to deploy just exactly which files each component needs... and they'd all be connected to the same version control. So it'd be something like: On one computer: svn checkout client1. On another: svn checkout server1. On another: svn checkout client2. Then if I modify some client2 code that is shared between client2 and client1, both will be updated when I do svn update. Also ideally, I wouldn't have to pick out the files I need manually, since that can be annoying, but I can deal with that. Have other people had this problem? Does it have a better-defined name? What solutions can I use to solve it?
[ "When it can be broken up in modules, go for a repo / branch with all the 'base' code, and in the actual project, include them as svn:externals (same repository or another one doesn't matter). That way you can independently update / work on modules, pin certain projects to certain revisions of that module or keep t...
[ 2 ]
[]
[]
[ "deployment", "python", "svn", "version_control" ]
stackoverflow_0003410228_deployment_python_svn_version_control.txt
Q: Subversion python bindings could not be loaded This is a but of a part 2 in trying to convert an SVN repository to a Mercurial one command is: hg convert file://c:/svnrepository but, the output I get is: assuming destination svnrepository-hg initializing destination svnrepository-hg repository file://c:/svnrepository does not look like a CVS checkout file://c:/svnrepository does not look like a Git repo Subversion python bindings could not be loaded file://c:/svnrepository is not a local Mercurial repo file://c:/svnrepository does not look like a darcs repo file://c:/svnrepository does not look like a monotone repo file://c:/svnrepository does not look like a GNU Arch repo file://c:/svnrepository does not look like a Bazaar repo file://c:/svnrepository does not look like a P4 repo abort: file://c:/svnrepository: missing or unsupported repository The line I'm interested in is: Subversion python bindings could not be loaded I have installed python 2.5, and I have installed the python subversion bindings from the subversion website. But still getting this error A: I just wanted to bring the actual solution out of the comments to Alex Martelli's answer: According to https://www.mercurial-scm.org/pipermail/mercurial/2009-May/026015.html the subversion bindings are included in tortoisehg. So you just need to enable the convert extension in tortoisehg. – tonfa Ah ha! Another step forward. I changed my path to point at hg in TortoiseHG instead of Mercurial and this got over that hurdle. Now it just doesn't think the repository is an SVN one, ahh! – Paul This worked for me as well. If you're currently using the standard command line version of HG on Windows, the specific steps are: Install TortoiseHG Right click a file / TortoiseHG / Global Settings... / Extensions / {Check "convert"} Make sure TortoiseHG is the path for your hg command: WinKey+Pause / Advanced / Environment Variables / System Variables / Path REMOVE C:\Program Files\Mercurial from the path Make sure C:\Program Files\TortoiseHG is there A: The problem's explained here at heading "Converting from Subversion": Subversion's Python bindings are a prerequisite. The bindings (generated with SWIG) are installed separately on Windows, and can be found on http://subversion.tigris.org/ . Note that you can't do this with the Win32 Mercurial binaries -- there's no way to install the Subversion bindings into its built-in Python library. So you'll need to use a Mercurial installed on top of a stand-alone Python, and you may also need to do something like "set HG=python c:\Python25\Scripts\hg" to override the default Win32 binaries if you have those installed also. For Mac OS X, the easiest way is to install the CollabNet Subversion build, and then copy the content of /opt/subversion/lib/svn-python to the site-package directory of the python installation. Unfortunately hg + svn + win doesn't apparently get any easier with hgsubversion, at least judging from this post and this discussion thereof (I have no Windows installed to try and help out, sigh). A: sudo apt-get install python-subversion did the trick for me on Ubuntu.
Subversion python bindings could not be loaded
This is a but of a part 2 in trying to convert an SVN repository to a Mercurial one command is: hg convert file://c:/svnrepository but, the output I get is: assuming destination svnrepository-hg initializing destination svnrepository-hg repository file://c:/svnrepository does not look like a CVS checkout file://c:/svnrepository does not look like a Git repo Subversion python bindings could not be loaded file://c:/svnrepository is not a local Mercurial repo file://c:/svnrepository does not look like a darcs repo file://c:/svnrepository does not look like a monotone repo file://c:/svnrepository does not look like a GNU Arch repo file://c:/svnrepository does not look like a Bazaar repo file://c:/svnrepository does not look like a P4 repo abort: file://c:/svnrepository: missing or unsupported repository The line I'm interested in is: Subversion python bindings could not be loaded I have installed python 2.5, and I have installed the python subversion bindings from the subversion website. But still getting this error
[ "I just wanted to bring the actual solution out of the comments to Alex Martelli's answer:\n\nAccording to https://www.mercurial-scm.org/pipermail/mercurial/2009-May/026015.html the subversion bindings are included in tortoisehg. So you just need to enable the convert extension in tortoisehg. – tonfa\nAh ha! Anoth...
[ 21, 14, 5 ]
[]
[]
[ "mercurial", "python", "svn", "windows" ]
stackoverflow_0001657918_mercurial_python_svn_windows.txt
Q: python: unhashable type error Traceback (most recent call last): File "<pyshell#80>", line 1, in <module> do_work() File "C:\pythonwork\readthefile080410.py", line 14, in do_work populate_frequency5(e,data) File "C:\pythonwork\readthefile080410.py", line 157, in populate_frequency5 data=medications_minimum3(data,[drug.upper()],1) File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3 counter[row[11]]+=1 TypeError: unhashable type: 'list' I am getting the above error on this line: data=medications_minimum3(data,[drug.upper()],1) (I have also tried drug.upper() without brackets) Here is a preview of this function: def medications_minimum3(c,drug_input,sample_cutoff): #return sample cut off for # medications/physician d=[] counter=collections.defaultdict(int) for row in c: counter[row[11]]+=1 for row in c: if counter[row[11]]>=sample_cutoff: d.append(row) write_file(d,'/pythonwork/medications_minimum3.csv') return d Does anyone know what I am doing wrong here? I know that what must be wrong is the way I am calling this function, because I call this function from a different location and it works fine: d=medications_minimum3(c,drug_input,50) Thank you very much for your help! A: counter[row[11]]+=1 You don't show what data is, but apparently when you loop through its rows, row[11] is turning out to be a list. Lists are mutable objects which means they cannot be used as dictionary keys. Trying to use row[11] as a key causes the defaultdict to complain that it is a mutable, i.e. unhashable, object. The easiest fix is to change row[11] from a list to a tuple. Either by doing counter[tuple(row[11])] += 1 or by fixing it in the caller before data is passed to medications_minimum3. A tuple simply an immutable list, so it behaves exactly like a list does except you cannot change it once it is created. A: I don't think converting to a tuple is the right answer. You need go and look at where you are calling the function and make sure that c is a list of list of strings, or whatever you designed this function to work with For example you might get this error if you passed [c] to the function instead of c A: As Jim Garrison said in the comment, no obvious reason why you'd make a one-element list out of drug.upper() (which implies drug is a string). But that's not your error, as your function medications_minimum3() doesn't even use the second argument (something you should fix). TypeError: unhashable type: 'list' usually means that you are trying to use a list as a hash argument (like for accessing a dictionary). I'd look for the error in counter[row[11]]+=1 -- are you sure that row[11] is of the right type? Sounds to me it might be a list. A: File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3 counter[row[11]]+=1 TypeError: unhashable type: 'list' row[11] is unhashable. It's a list. That is precisely (and only) what the error message means. You might not like it, but that is the error message. Do this counter[tuple(row[11])]+=1 Also, simplify. d= [ row for row in c if counter[tuple(row[11])]>=sample_cutoff ]
python: unhashable type error
Traceback (most recent call last): File "<pyshell#80>", line 1, in <module> do_work() File "C:\pythonwork\readthefile080410.py", line 14, in do_work populate_frequency5(e,data) File "C:\pythonwork\readthefile080410.py", line 157, in populate_frequency5 data=medications_minimum3(data,[drug.upper()],1) File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3 counter[row[11]]+=1 TypeError: unhashable type: 'list' I am getting the above error on this line: data=medications_minimum3(data,[drug.upper()],1) (I have also tried drug.upper() without brackets) Here is a preview of this function: def medications_minimum3(c,drug_input,sample_cutoff): #return sample cut off for # medications/physician d=[] counter=collections.defaultdict(int) for row in c: counter[row[11]]+=1 for row in c: if counter[row[11]]>=sample_cutoff: d.append(row) write_file(d,'/pythonwork/medications_minimum3.csv') return d Does anyone know what I am doing wrong here? I know that what must be wrong is the way I am calling this function, because I call this function from a different location and it works fine: d=medications_minimum3(c,drug_input,50) Thank you very much for your help!
[ "counter[row[11]]+=1\n\nYou don't show what data is, but apparently when you loop through its rows, row[11] is turning out to be a list. Lists are mutable objects which means they cannot be used as dictionary keys. Trying to use row[11] as a key causes the defaultdict to complain that it is a mutable, i.e. unhashab...
[ 16, 10, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003410206_python.txt
Q: Approaches to embedded vector images/charts into PDF How have people from the Linux world embedded vector images into PDF? I am attempting to create automated reports from data that I currently render as SVG images. Ideally, I would like to use the same XML in PostScript, PDF or DjVu format. To what degree are those formats able to handle SVG natively? More broadly, what have people's experiences been? Should I reuse the native SVG XML? rasterise SVGs that have already been created? or use another format? I'm restricted to formats that are accessible from Ubuntu 10.04 & Python. This will probably exclude me from utilising Adobe Illustrator files. A: Investigate Apache FOP, its main purpose is to convert XML to PDF. Upsides (for this project): full Apache project (=> reliable) Downsides (for this project): Will need to learn XSL-FO Not Python A: Batik is a nice Java SVG library. It has a utility library called batik-rasterizer.jar which can convert SVG into a some useful formats: PDF, TIFF, PNG, and GIF. You could use Jython to link to this library with python.
Approaches to embedded vector images/charts into PDF
How have people from the Linux world embedded vector images into PDF? I am attempting to create automated reports from data that I currently render as SVG images. Ideally, I would like to use the same XML in PostScript, PDF or DjVu format. To what degree are those formats able to handle SVG natively? More broadly, what have people's experiences been? Should I reuse the native SVG XML? rasterise SVGs that have already been created? or use another format? I'm restricted to formats that are accessible from Ubuntu 10.04 & Python. This will probably exclude me from utilising Adobe Illustrator files.
[ "Investigate Apache FOP, its main purpose is to convert XML to PDF.\nUpsides (for this project):\n\nfull Apache project (=> reliable)\n\nDownsides (for this project):\n\nWill need to learn XSL-FO\nNot Python\n\n", "Batik is a nice Java SVG library. It has a utility library called batik-rasterizer.jar which can co...
[ 0, 0 ]
[]
[]
[ "linux", "pdf_generation", "python" ]
stackoverflow_0003402576_linux_pdf_generation_python.txt
Q: Working on Dictionary of Classes in Python For this example, I have a dictionary, that when I call on it, "Ember Attack" is displayed. #import shelve class Pokemon(): """Each pokemon's attributes""" def __init__(self): self.id=[] self.var1=[] self.var2=[] self.var3=[] self.var4=[] self.var5=[] def __str__(self): showList=['id','var1', 'var2', 'var3', 'var4', 'var5'] #dict1=shelve.open("shelve.dat") dict1={} dict1["Charmander"]=Pokemon() dict1["Charmander"].var1="Ember Attack" #dict1.sync() print dict1["Charmander"].var1 #dict1.close() However when I start using shelves instead of the dictionary, I get a blank when I call on var1. import shelve class Pokemon(): """Each patient's attributes""" def __init__(self): self.id=[] self.var1=[] self.var2=[] self.var3=[] self.var4=[] self.var5=[] def __str__(self): showList=['id','var1', 'var2', 'var3', 'var4', 'var5'] dict1=shelve.open("shelve.dat") #dict1={} dict1["Charmander"]=Pokemon() dict1["Charmander"].var1="Ember Attack" dict1.sync() print dict1["Charmander"].var1 dict1.close() The only difference is that I made dict1 a shelve dictionary instead of a regular dictionary. It probably has to do with memory scope or something. Anyway, can someone help me revise my code so that it will work with shelves? Thanks! A: dict1=shelve.open("shelve.dat", writeback=True) you can also specify the protocol which should improve performance dict1=shelve.open("shelve.dat", protocol=2, writeback=True) Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example). If the optional writeback parameter is set to True, all entries accessed are also cached in memory, and written back on sync() and close(); this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated).
Working on Dictionary of Classes in Python
For this example, I have a dictionary, that when I call on it, "Ember Attack" is displayed. #import shelve class Pokemon(): """Each pokemon's attributes""" def __init__(self): self.id=[] self.var1=[] self.var2=[] self.var3=[] self.var4=[] self.var5=[] def __str__(self): showList=['id','var1', 'var2', 'var3', 'var4', 'var5'] #dict1=shelve.open("shelve.dat") dict1={} dict1["Charmander"]=Pokemon() dict1["Charmander"].var1="Ember Attack" #dict1.sync() print dict1["Charmander"].var1 #dict1.close() However when I start using shelves instead of the dictionary, I get a blank when I call on var1. import shelve class Pokemon(): """Each patient's attributes""" def __init__(self): self.id=[] self.var1=[] self.var2=[] self.var3=[] self.var4=[] self.var5=[] def __str__(self): showList=['id','var1', 'var2', 'var3', 'var4', 'var5'] dict1=shelve.open("shelve.dat") #dict1={} dict1["Charmander"]=Pokemon() dict1["Charmander"].var1="Ember Attack" dict1.sync() print dict1["Charmander"].var1 dict1.close() The only difference is that I made dict1 a shelve dictionary instead of a regular dictionary. It probably has to do with memory scope or something. Anyway, can someone help me revise my code so that it will work with shelves? Thanks!
[ "dict1=shelve.open(\"shelve.dat\", writeback=True)\n\nyou can also specify the protocol which should improve performance\ndict1=shelve.open(\"shelve.dat\", protocol=2, writeback=True)\n\n\nBecause of Python semantics, a shelf\n cannot know when a mutable\n persistent-dictionary entry is\n modified. By default mo...
[ 1 ]
[]
[]
[ "dictionary", "python", "shelve" ]
stackoverflow_0003410452_dictionary_python_shelve.txt
Q: Unit Testing / Eclipse / Command Line I have project with the following layout (Python 2.4.3) root +--- src +--- xyz +--- __init__.py +--- C1.py +--- C2.py +--- test +--- xyz +--- __init__.py +--- CXMock.py +--- C1Test.py +--- C2Test.py So i'm writing a unit test (C1Test.py for example) and trying to use CXMock.py there which is only for testing purposes so only in the test area. But if i try to run that unit test via Eclipse Plugin (PyDev 1.5.4) (python unit-test) i got a message like this: Finding files... ['/home/.../test/xyz /C1Test.py.py'] ... done Importing test modules ... Traceback (most recent call last): File "/opt/eclipse-plugins/pydev/plugins/org.python.pydev.debug_1.5.4.2010011921/pysrc/runfiles.py", line 342, in __get_module_from_str mod = __import__(modname) File "/home/../test/xyz/C1Test.py", line 4, in ? from xyz.CXMock.py import CXMock.py ImportError: No module named CXMock.py ERROR: Module: C1Test could not be imported. done. Does someone has an idea/hint ? Thanks in advance. A: You don't include the ".py" on your imports. Try: from xyz.CXMock import CXMock
Unit Testing / Eclipse / Command Line
I have project with the following layout (Python 2.4.3) root +--- src +--- xyz +--- __init__.py +--- C1.py +--- C2.py +--- test +--- xyz +--- __init__.py +--- CXMock.py +--- C1Test.py +--- C2Test.py So i'm writing a unit test (C1Test.py for example) and trying to use CXMock.py there which is only for testing purposes so only in the test area. But if i try to run that unit test via Eclipse Plugin (PyDev 1.5.4) (python unit-test) i got a message like this: Finding files... ['/home/.../test/xyz /C1Test.py.py'] ... done Importing test modules ... Traceback (most recent call last): File "/opt/eclipse-plugins/pydev/plugins/org.python.pydev.debug_1.5.4.2010011921/pysrc/runfiles.py", line 342, in __get_module_from_str mod = __import__(modname) File "/home/../test/xyz/C1Test.py", line 4, in ? from xyz.CXMock.py import CXMock.py ImportError: No module named CXMock.py ERROR: Module: C1Test could not be imported. done. Does someone has an idea/hint ? Thanks in advance.
[ "You don't include the \".py\" on your imports. Try:\nfrom xyz.CXMock import CXMock\n\n" ]
[ 2 ]
[]
[]
[ "eclipse", "pydev", "python", "unit_testing" ]
stackoverflow_0003203082_eclipse_pydev_python_unit_testing.txt
Q: urllib2 connection timed out error I am trying to open a page using urllib2 but i keep getting connection timed out errors. The line which i am using is: f = urllib2.urlopen(url) exact error is: URLError: <urlopen error [Errno 110] Connection timed out> A: urllib2 respects robots.txt. Many sites block the default User-Agent. Try adding a new User-Agent, by creating Request objects & using them as arguments for urlopen: import urllib2 request = urllib2.Request('http://www.example.com/') request.add_header('User-agent', 'Mozilla/5.0 (Linux i686)') response = urllib2.urlopen(request) Several detailed walk-throughs are available, such as http://www.doughellmann.com/PyMOTW/urllib2/ A: As a general strategy, open wireshark and watch the traffic generated by urllib2.urlopen(url). You may be able to see where the error is coming from.
urllib2 connection timed out error
I am trying to open a page using urllib2 but i keep getting connection timed out errors. The line which i am using is: f = urllib2.urlopen(url) exact error is: URLError: <urlopen error [Errno 110] Connection timed out>
[ "urllib2 respects robots.txt. Many sites block the default User-Agent.\nTry adding a new User-Agent, by creating Request objects & using them as arguments for urlopen:\nimport urllib2\n\nrequest = urllib2.Request('http://www.example.com/')\nrequest.add_header('User-agent', 'Mozilla/5.0 (Linux i686)')\n\nresponse = ...
[ 4, 1 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0003197299_python_urllib2.txt
Q: how to calculate timedelta python What I am trying to do is to subtract 7 hours from a date. I searched stack overflow and found the answer on how to do it here. I then went to go read the documentation on timedelta because I was unable to understand what that line in the accepted answer does, rewritten here for ease: from datetime import datetime dt = datetime.strptime( date, '%Y-%m-%d %H:%M' ) dt_plus_25 = dt + datetime.timedelta( 0, 2*60*60 + 30*60 ) Unfortunately, even after reading the documentation I still do not understand how that line works. What is the timedelta line doing? How does it work? Additionally, before I found this stackoverflow post, I was working with time.struct_time tuples. I had a variable tm: tm = time.strptime(...) I was simply accessing the hour through tm.tm_hour and subtracting seven from it but this, for obvious reasons, does not work. This is why I am now trying to use datetime. tm now has the value tm = datetime.strptime(...) I'm assuming using datetime is the best way to subtract seven hours? Note: subtracting seven hours because I want to go from UTC to US/Pacific timezone. Is there a built-in way to do this? A: What is the timedelta line doing? How does it work? It creates a timedelta object. There are two meanings of "time". "Point in Time" (i.e, date or datetime) "Duration" or interval or "time delta" A time delta is an interval, a duration, a span of time. You provided 3 values. 0 days. 2*60*60 + 30*60 seconds. A: timedelta() generates an object representing an amount of time—the Greek letter delta is used in math to represent "difference". So to compute an addition or a subtraction of an amount of time, you take the starting time and add the change, or delta, that you want. The specific call you've quoted is for generating the timedelta for 2.5 hours. The first parameter is days, and the second is seconds, so you have (0 days, 2.5 hours), and 2.5 hours in seconds is (2 hours * 60 minutes/hour * 60 seconds/minute) + (30 minutes * 60 seconds / minute). For your case, you have a negative time delta of 0 days, 7 hours, so you'd write: timedelta(0, -7 * 60 * 60) ... or timedelta(0, -7 * 3600) or whatever makes it clear to you what you're doing. A: Note: subtracting seven hours because I want to go from UTC to US/Pacific timezone. Is there a built-in way to do this? Yes there is: datetime has built-in timezone conversion capabilities. If you get your datetime object using something like this: tm = datetime.strptime(date_string, '%Y-%m-%d %H:%M') it will not have any particular timezone "attached" to it at first, but you can give it a timezone using tm_utc = tm.replace(tzinfo=pytz.UTC) Then you can convert it to US/Pacific with tm_pacific = tm_utc.astimezone(pytz.all_timezones('US/Pacific')) I'd suggest doing this instead of subtracting seven hours manually because it makes it clear that you're keeping the actual time the same, just converting it to a different timezone, whereas if you manually subtracted seven hours, it looks more like you're actually trying to get a time seven hours in the past. Besides, the timezone conversion properly handles oddities like daylight savings time. To do this you will need to install the pytz package, which is not included in the Python standard library.
how to calculate timedelta python
What I am trying to do is to subtract 7 hours from a date. I searched stack overflow and found the answer on how to do it here. I then went to go read the documentation on timedelta because I was unable to understand what that line in the accepted answer does, rewritten here for ease: from datetime import datetime dt = datetime.strptime( date, '%Y-%m-%d %H:%M' ) dt_plus_25 = dt + datetime.timedelta( 0, 2*60*60 + 30*60 ) Unfortunately, even after reading the documentation I still do not understand how that line works. What is the timedelta line doing? How does it work? Additionally, before I found this stackoverflow post, I was working with time.struct_time tuples. I had a variable tm: tm = time.strptime(...) I was simply accessing the hour through tm.tm_hour and subtracting seven from it but this, for obvious reasons, does not work. This is why I am now trying to use datetime. tm now has the value tm = datetime.strptime(...) I'm assuming using datetime is the best way to subtract seven hours? Note: subtracting seven hours because I want to go from UTC to US/Pacific timezone. Is there a built-in way to do this?
[ "\nWhat is the timedelta line doing? How does it work?\n\nIt creates a timedelta object.\nThere are two meanings of \"time\". \n\n\"Point in Time\" (i.e, date or datetime)\n\"Duration\" or interval or \"time delta\"\n\nA time delta is an interval, a duration, a span of time. You provided 3 values.\n\n0 days.\n2...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003410439_python.txt
Q: Python's join() won't join the string representation (__str__) of my object I'm not sure what I'm doing wrong here: >>> class Stringy(object): ... def __str__(self): ... return "taco" ... def __repr__(self): ... return "taco" ... >>> lunch = Stringy() >>> lunch taco >>> str(lunch) 'taco' >>> '-'.join(('carnitas',lunch)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 1: expected string, Stringy found Given my inclusion of the __str__() method in the Stringy object, shouldn't join() see lunch as a string? A: no you have to convert it to str yourself '-'.join(('carnitas',str(lunch))) if you have to do it for a whole sequence of items '-'.join(str(x) for x in seq) or '-'.join(map(str, seq)) for your particular case you can just write 'carnitas-'+str(lunch) A: ''.join does not call __str__ on the items of the sequence it's joining. Every object has a __str__, after all (be it only inherited from object), therefore if join worked that way it would join up any sequence whatsoever (after stringification) -- often to weird effects. Better to have the the user call up str explicitly when warranted ("explicit is better than implicit" being one of the mottos in "The Zen of Python", after all). You could subclass str or unicode if you want to "be" a string. Otherwise, an explicit str call will be needed to make instances of your type "become" strings. A: The call signature for str.join is: S.join(sequence) -> string Return a string which is the concatenation of the strings in the sequence. The separator between elements is S. Notice that sequence is expected to be a sequence of strings. Lots of objects have __str__ methods, but not all of them (like Stringy) is an instance of str. The fix, of course, is simple: '-'.join(('carnitas',str(lunch)))
Python's join() won't join the string representation (__str__) of my object
I'm not sure what I'm doing wrong here: >>> class Stringy(object): ... def __str__(self): ... return "taco" ... def __repr__(self): ... return "taco" ... >>> lunch = Stringy() >>> lunch taco >>> str(lunch) 'taco' >>> '-'.join(('carnitas',lunch)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 1: expected string, Stringy found Given my inclusion of the __str__() method in the Stringy object, shouldn't join() see lunch as a string?
[ "no you have to convert it to str yourself\n'-'.join(('carnitas',str(lunch)))\n\nif you have to do it for a whole sequence of items\n'-'.join(str(x) for x in seq)\n\nor \n'-'.join(map(str, seq))\n\nfor your particular case you can just write \n'carnitas-'+str(lunch)\n\n", "''.join does not call __str__ on the ite...
[ 14, 8, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003410647_python.txt
Q: Calling cgi.FieldStorage for an arbitrary url I'd like to get field values corresponding to an arbitrary URL. I.e. given "http://example.com/hello?q=1&b=1" I want a dictionary {'q':1, 'b':1}. How do I use cgi.FieldStorage for that? Thanks! A: You can use urlparse to do that from urlparse import urlparse, parse_qs qs = urlparse("http://example.com/hello?q=1&b=1").query parse_qs(qs) if you must use FieldStorage cgi.FieldStorage(environ={'REQUEST_METHOD':'GET', 'QUERY_STRING':qs}) A: You don't -- you use cgi.parse_qs in 2.5 or earlier, urlparse.parse_qs in 2.6 or later. E.g.: >>> import urlparse >>> pr = urlparse.urlparse("http://example.com/hello?q=1&b=1") >>> urlparse.parse_qs(pr.query) {'q': ['1'], 'b': ['1']} Note that the values are always going to be lists of strings -- you appear to want them to be ("scalar") integers, but that really makes no sense (how would you expect ?q=bah to be parsed?!) -- if you "know" there's only one instance of each parameters and those instances' values are always strings of digits, then it's easy enough to transform what the parsing return into the form you want, of course (better, this "known" property can be checked, raising an exception if it doesn't actually hold;-).
Calling cgi.FieldStorage for an arbitrary url
I'd like to get field values corresponding to an arbitrary URL. I.e. given "http://example.com/hello?q=1&b=1" I want a dictionary {'q':1, 'b':1}. How do I use cgi.FieldStorage for that? Thanks!
[ "You can use urlparse to do that\nfrom urlparse import urlparse, parse_qs\nqs = urlparse(\"http://example.com/hello?q=1&b=1\").query\nparse_qs(qs)\n\nif you must use FieldStorage\ncgi.FieldStorage(environ={'REQUEST_METHOD':'GET', 'QUERY_STRING':qs})\n\n", "You don't -- you use cgi.parse_qs in 2.5 or earlier, urlp...
[ 3, 2 ]
[]
[]
[ "html", "http", "python", "url" ]
stackoverflow_0003410713_html_http_python_url.txt
Q: objective C and python - pyobjc Is it possible for an objective c application to run python files and read their data, etc? If so, can someone post code? or lead me in the right direction? Thanks, Elijah A: Sure, see the tutorial -- it's very dated but should still apply today. (Apple's tutorial is good, but it only shows how to call ObjC from Python, while pyobjc's own tutorial, while extremely short, focuses on the opposite direction -- calling Python from ObjC -- which appears to be what you want).
objective C and python - pyobjc
Is it possible for an objective c application to run python files and read their data, etc? If so, can someone post code? or lead me in the right direction? Thanks, Elijah
[ "Sure, see the tutorial -- it's very dated but should still apply today. (Apple's tutorial is good, but it only shows how to call ObjC from Python, while pyobjc's own tutorial, while extremely short, focuses on the opposite direction -- calling Python from ObjC -- which appears to be what you want).\n" ]
[ 1 ]
[]
[]
[ "objective_c", "pyobjc", "python" ]
stackoverflow_0003410480_objective_c_pyobjc_python.txt
Q: How do I use SQL parameters with python? I am using python 2.7 and pymssql 1.9.908. In .net to query the database I would do something like this: using (SqlCommand com = new SqlCommand("select * from Customer where CustomerId = @CustomerId", connection)) { com.Parameters.AddWithValue("@CustomerID", CustomerID); //Do something with the command } I am trying to figure out what the equivalent is for python and more particularly pymssql. I realize that I could just do string formatting, however that doesn't seem handle escaping properly like a parameter does (I could be wrong on that). How do I do this in python? A: After creating a connection object db: cursor = db.execute('SELECT * FROM Customer WHERE CustomerID = %s', [customer_id]) then use any of the fetch... methods of the resulting cursor object. Don't be fooled by the %s part: this is NOT string formatting, it's parameter substitution (different DB API modules use different syntax for parameter substitution -- pymssql just happens to use the unfortunate %s!-).
How do I use SQL parameters with python?
I am using python 2.7 and pymssql 1.9.908. In .net to query the database I would do something like this: using (SqlCommand com = new SqlCommand("select * from Customer where CustomerId = @CustomerId", connection)) { com.Parameters.AddWithValue("@CustomerID", CustomerID); //Do something with the command } I am trying to figure out what the equivalent is for python and more particularly pymssql. I realize that I could just do string formatting, however that doesn't seem handle escaping properly like a parameter does (I could be wrong on that). How do I do this in python?
[ "After creating a connection object db:\ncursor = db.execute('SELECT * FROM Customer WHERE CustomerID = %s', [customer_id])\n\nthen use any of the fetch... methods of the resulting cursor object.\nDon't be fooled by the %s part: this is NOT string formatting, it's parameter substitution (different DB API modules us...
[ 24 ]
[]
[]
[ "pymssql", "python" ]
stackoverflow_0003410455_pymssql_python.txt
Q: How to upload pdf and pptx files to google docs via the gdata python client? I'm using the gdata python client for the google docs api for a project. I use oauth authentication and all the dance, and have successfully uploaded .doc, .xls and every file type in Their FAQ. but I cannot seem to upload pdf files, even though is right there, listed on the supported filetypes. I tried with the latest version of gdata (released last week) to no avail. Also, I'd like to be able to upload .pptx files, though I realize that that extension is not supported. Has anybody out there succesfully uploaded a pdf file to google docs via their gdata python client?
How to upload pdf and pptx files to google docs via the gdata python client?
I'm using the gdata python client for the google docs api for a project. I use oauth authentication and all the dance, and have successfully uploaded .doc, .xls and every file type in Their FAQ. but I cannot seem to upload pdf files, even though is right there, listed on the supported filetypes. I tried with the latest version of gdata (released last week) to no avail. Also, I'd like to be able to upload .pptx files, though I realize that that extension is not supported. Has anybody out there succesfully uploaded a pdf file to google docs via their gdata python client?
[]
[]
[ "Done.\nFirst did this\nhttp://code.google.com/p/gdata-issues/issues/detail?id=591#c77\nbut now I was getting a bad request error \"invalid request uri\". So I then discovered in another google thread that the uri for the v3.0 apis was no longer http://docs.google.com/feeds/folders/private/full/<resource-id> but ht...
[ -1 ]
[ "gdata", "gdata_python_client", "google_docs", "python" ]
stackoverflow_0003401623_gdata_gdata_python_client_google_docs_python.txt
Q: Define dtypes in NumPy using a list? I just am having a problem with NumPy dtypes. Essentially I'm trying to create a table that looks like the following (and then save it using rec2csv): name1 name2 name3 . . . name1 # # # name2 # # # name2 # # # . . . The matrix (numerical array in the center), is already computed before I attempt to add the name tags. I've tried to use the following code: dt = dtype({'names' : tuple(blah), 'formats' : tuple(fmt)}) ReadArray = array(tuplelist, dtype=dt) where tuplelist is a list of rows (i.e. the row [name1, #, #, #...]), blah is a list of strings (i.e. the names, blah = ['name1', 'name2', ...]) and fmt is the list of format,s (i.e. fmt = [str, float, float, ...]). The error I'm getting is the following: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "table_calc_try2.py", line 152, in table_calc_try2 dt = dtype({'names' : tuple(blah), 'formats' : tuple(fmt)}) TypeError: data type not understood Can anyone help? Thanks! A: The following code might help: import numpy as np dt = np.dtype([('name1', '|S10'), ('name2', '<f8')]) tuplelist=[ ('n1', 1.2), ('n2', 3.4), ] arr = np.array(tuplelist, dtype=dt) print(arr['name1']) # ['n1' 'n2'] print(arr['name2']) # [ 1.2 3.4] Your immediate problem was that np.dtype expects the format specifiers to be numpy types, such as '|S10' or '<f8' and not Python types, such as str or float. If you type help(np.dtype) you'll see many examples of how np.dtypes can be specified. (I've only mentioned a few.) Note that np.array expects a list of tuples. It's rather particular about that. A list of lists raises TypeError: expected a readable buffer object. A (tuple of tuples) or a (tuple of lists) raises ValueError: setting an array element with a sequence.
Define dtypes in NumPy using a list?
I just am having a problem with NumPy dtypes. Essentially I'm trying to create a table that looks like the following (and then save it using rec2csv): name1 name2 name3 . . . name1 # # # name2 # # # name2 # # # . . . The matrix (numerical array in the center), is already computed before I attempt to add the name tags. I've tried to use the following code: dt = dtype({'names' : tuple(blah), 'formats' : tuple(fmt)}) ReadArray = array(tuplelist, dtype=dt) where tuplelist is a list of rows (i.e. the row [name1, #, #, #...]), blah is a list of strings (i.e. the names, blah = ['name1', 'name2', ...]) and fmt is the list of format,s (i.e. fmt = [str, float, float, ...]). The error I'm getting is the following: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "table_calc_try2.py", line 152, in table_calc_try2 dt = dtype({'names' : tuple(blah), 'formats' : tuple(fmt)}) TypeError: data type not understood Can anyone help? Thanks!
[ "The following code might help:\nimport numpy as np\n\ndt = np.dtype([('name1', '|S10'), ('name2', '<f8')])\ntuplelist=[\n ('n1', 1.2),\n ('n2', 3.4), \n ]\narr = np.array(tuplelist, dtype=dt)\n\nprint(arr['name1'])\n# ['n1' 'n2']\nprint(arr['name2'])\n# [ 1.2 3.4]\n\nYour immediate problem was that n...
[ 12 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003410147_numpy_python.txt
Q: Summarizing a dictionary of arrays in Python I got the following dictionary: mydict = { 'foo': [1,19,2,3,24,52,2,6], # sum: 109 'bar': [50,5,9,7,66,3,2,44], # sum: 186 'another': [1,2,3,4,5,6,7,8], # sum: 36 'entry': [0,0,0,2,99,4,33,55], # sum: 193 'onemore': [21,22,23,24,25,26,27,28] # sum: 196 } I need to efficiently filter out and sort the top x entries by the sum of the array. For example, the Top 3 sorted and filtered list for the example above would be sorted_filtered_dict = { 'onemore': [21,22,23,24,25,26,27,28], # sum: 196 'entry': [0,0,0,2,99,4,33,55], # sum: 193 'bar': [50,5,9,7,66,3,2,44] # sum: 186 } I'm fairly new to Python, and tried it myself with chaining a sum and filter function on a lambda function, but struggled with the actual syntax. A: It's easy to do with a sort: sorted(mydict.iteritems(), key=lambda tup: sum(tup[1]), reverse=True)[:3] This is reasonable if the ratio is similar to this one (3 / 5). If it's larger, you'll want to avoid the sort (O(n log n)), since top 3 can be done in O(n). For instance, using heapq, the heap module: heapq.nlargest(3, mydict.iteritems(), key=lambda tup: sum(tup[1])) This is O(n + 3 log n), since assembly the initial heap is O(n) and re-heapifying is O(log n). EDIT: If you're using Python 2.7 or later, you can easily convert to a OrderedDict (equivalent version for Python 2.4+): OrderedDict(heapq.nlargest(3, mydict.iteritems(), key=lambda tup: sum(tup[1]))) OrderedDict has the same API as dict, but remembers insertion order. A: For such a small slice it's not worth using islice sorted(mydict.iteritems(), key=lambda (k,v): sum(v), reverse=True)[:3]
Summarizing a dictionary of arrays in Python
I got the following dictionary: mydict = { 'foo': [1,19,2,3,24,52,2,6], # sum: 109 'bar': [50,5,9,7,66,3,2,44], # sum: 186 'another': [1,2,3,4,5,6,7,8], # sum: 36 'entry': [0,0,0,2,99,4,33,55], # sum: 193 'onemore': [21,22,23,24,25,26,27,28] # sum: 196 } I need to efficiently filter out and sort the top x entries by the sum of the array. For example, the Top 3 sorted and filtered list for the example above would be sorted_filtered_dict = { 'onemore': [21,22,23,24,25,26,27,28], # sum: 196 'entry': [0,0,0,2,99,4,33,55], # sum: 193 'bar': [50,5,9,7,66,3,2,44] # sum: 186 } I'm fairly new to Python, and tried it myself with chaining a sum and filter function on a lambda function, but struggled with the actual syntax.
[ "It's easy to do with a sort:\nsorted(mydict.iteritems(), key=lambda tup: sum(tup[1]), reverse=True)[:3]\n\nThis is reasonable if the ratio is similar to this one (3 / 5). If it's larger, you'll want to avoid the sort (O(n log n)), since top 3 can be done in O(n). For instance, using heapq, the heap module:\nheap...
[ 7, 2 ]
[]
[]
[ "algorithm", "arrays", "dictionary", "python" ]
stackoverflow_0003411025_algorithm_arrays_dictionary_python.txt
Q: Why does the Python 2.7 AMD 64 installer seem to run Python in 32 bit mode? I've installed Python 2.7 from the python-2.7.amd64.msi package from python.org. It installs and runs correctly, but seems to be in 32-bit mode, despite the fact that the installer was a 64 bit installer. Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys, platform >>> platform.architecture() ('64bit', 'WindowsPE') >>> sys.maxint 2147483647 What can I do to install Python so that it actually runs in 64-bit mode? A: See the discussion here. It's from 2.6.1, but it seems to still apply. I haven't seen evidence to the contrary anywhere, at least. The gist of the matter (quoted from that link) is: This is by design. In their infinitive wisdom Microsoft has decided to make the 'long' C type always a 32 bit signed integer - even on 64bit systems. On most Unix systems a long is at least 32 bit but usually sizeof(ptr). A: On my x86-64 Linux: $ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys, platform >>> platform.architecture() ('64bit', 'ELF') >>> sys.maxint 9223372036854775807 Of course, what matters more than integer size is how much memory you can allocate. Maybe your smaller ints won't really matter much, since Python will just promote to a long any way, but if you can allocate more than three gigs of memory, you'll still be enjoying the benefits of 64 bit execution.
Why does the Python 2.7 AMD 64 installer seem to run Python in 32 bit mode?
I've installed Python 2.7 from the python-2.7.amd64.msi package from python.org. It installs and runs correctly, but seems to be in 32-bit mode, despite the fact that the installer was a 64 bit installer. Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys, platform >>> platform.architecture() ('64bit', 'WindowsPE') >>> sys.maxint 2147483647 What can I do to install Python so that it actually runs in 64-bit mode?
[ "See the discussion here. It's from 2.6.1, but it seems to still apply. I haven't seen evidence to the contrary anywhere, at least. The gist of the matter (quoted from that link) is:\n\nThis is by design. In their infinitive wisdom Microsoft has decided to\n make the 'long' C type always a 32 bit signed integer - ...
[ 14, 3 ]
[]
[]
[ "64_bit", "python", "windows" ]
stackoverflow_0003411079_64_bit_python_windows.txt
Q: Things to consider when creating a web framework I am not trying to create yet another web framework. For one of the applications I am working on, I want to create a custom framework. I don't want to use any already available framework. What are the common things to consider? What should be the architecture? Thanks :) A: If the point of a framework is to make tedious things easy, a good start would be to consider what is tedious. A: What are the common things to consider? Purpose. Usually, when you start building a piece of software, you have a purpose in mind. What will it do that other programs can't? If you can't answer that question, then take any existing open source framework, change its name and your job is done. Now you have your own framework. A: Well if you are going to write a custom framework then I assume the framework needs to be tailored to your needs, otherwise you would use one that is already available. So figure out what your needs are and go from there ;) What are the most often repeated operations in your application? Is there a division of labor that a framework could make more apparent?
Things to consider when creating a web framework
I am not trying to create yet another web framework. For one of the applications I am working on, I want to create a custom framework. I don't want to use any already available framework. What are the common things to consider? What should be the architecture? Thanks :)
[ "If the point of a framework is to make tedious things easy, a good start would be to consider what is tedious.\n", "What are the common things to consider?\nPurpose. Usually, when you start building a piece of software, you have a purpose in mind. What will it do that other programs can't?\nIf you can't answer t...
[ 2, 1, 0 ]
[]
[]
[ "frameworks", "php", "python", "ruby" ]
stackoverflow_0003411176_frameworks_php_python_ruby.txt
Q: wxPython: Window and Event Id's I have a Panel on which I display a StaticBitmap initialised with an id of 2. When I bind a mouse event to the image and call GetId() on the event, it returns -202. Why? import wx class MyFrame(wx.Frame): def __init__(self, parent, id=-1): wx.Frame.__init__(self,parent,id) self.panel = wx.Panel(self,wx.ID_ANY) img = wx.Image("img1.png",wx.BITMAP_TYPE_ANY) img2 = wx.StaticBitmap(self.panel,2,wx.BitmapFromImage(img)) print img2.GetId() # prints 2 img2.Bind(wx.EVT_LEFT_DOWN,self.OnDClick) def OnDClick(self, event): print event.GetId() # prints -202 if __name__ == "__main__": app = wx.PySimpleApp() frame = MyFrame(None) frame.Show() app.MainLoop() A: You're printing the event's ID, not the bitmap's ID. Try print event.GetEventObject().GetId() GetEventObject returns the widget associated with the event, in this case, the StaticBitmap. FWIW, I've never needed to assign ID's to any widgets, and you probably shouldn't need to either. Edit: I saw some other questions you asked and this is what I would recommend, especially if GetEventObject is returning the parent instead (I'm very surprised if that's true, you should double check): import functools widget1.Bind(wx.EVT_LEFT_DOWN, functools.partial(self.on_left_down, widget=widget1)) widget2.Bind(wx.EVT_LEFT_DOWN, functools.partial(self.on_left_down, widget=widget2)) # or the above could be in a loop, creating lots of widgets def on_left_down(self, event, widget): # widget is the one that was clicked # event is still the wx event # handle the event here...
wxPython: Window and Event Id's
I have a Panel on which I display a StaticBitmap initialised with an id of 2. When I bind a mouse event to the image and call GetId() on the event, it returns -202. Why? import wx class MyFrame(wx.Frame): def __init__(self, parent, id=-1): wx.Frame.__init__(self,parent,id) self.panel = wx.Panel(self,wx.ID_ANY) img = wx.Image("img1.png",wx.BITMAP_TYPE_ANY) img2 = wx.StaticBitmap(self.panel,2,wx.BitmapFromImage(img)) print img2.GetId() # prints 2 img2.Bind(wx.EVT_LEFT_DOWN,self.OnDClick) def OnDClick(self, event): print event.GetId() # prints -202 if __name__ == "__main__": app = wx.PySimpleApp() frame = MyFrame(None) frame.Show() app.MainLoop()
[ "You're printing the event's ID, not the bitmap's ID.\nTry print event.GetEventObject().GetId()\nGetEventObject returns the widget associated with the event, in this case, the StaticBitmap.\nFWIW, I've never needed to assign ID's to any widgets, and you probably shouldn't need to either.\nEdit: I saw some other que...
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003411361_python_wxpython.txt
Q: How to use simplejson to decode following data? I grab some data from a URL, and search online to find out the data is in in Jason data format, but when I tried to use simplejson.loads(data), it will raise exception. First time deal with jason data, any suggestion how to decode the data? Thanks ================= result = simplejson.loads(data, encoding="utf-8") File "F:\My Documents\My Dropbox\StockDataDownloader\simplejson__init__.py", line 401, in loads return cls(encoding=encoding, **kw).decode(s) File "F:\My Documents\My Dropbox\StockDataDownloader\simplejson\decoder.py", line 402, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "F:\My Documents\My Dropbox\StockDataDownloader\simplejson\decoder.py", line 420, in raw_decode raise JSONDecodeError("No JSON object could be decoded", s, idx) simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0) ============================ data = "{identifier:'ID', label:'As at Wed 4 Aug 2010 05:05 PM',items:[{ID:0,N:'2ndChance',NC:'528',R:'NONE',I:'NONE',M:'-',LT:0.335,C:0.015,VL:51.000,BV:20.000,B:0.330,S:0.345,SV:20.000,O:0.335,H:0.335,L:0.335,V:17085.000,SC:'4',PV:0.320,P:4.6875,P_:'X',V_:''},{ID:1,N:'8Telecom',NC:'E25',R:'NONE',I:'NONE',M:'-',LT:0.190,C:0.000,VL:965.000,BV:1305.000,B:0.185,S:0.190,SV:641.000,O:0.185,H:0.190,L:0.185,V:179525.000,SC:'2',PV:0.190,P:0.0,P_:'X',V_:''},{ID:2,N:'A-Sonic',NC:'A53',R:'NONE',I:'NONE',M:'-',LT:0.090,C:0.005,VL:1278.000,BV:17.000,B:0.090,S:0.095,SV:346.000,O:0.090,H:0.090,L:0.090,V:115020.000,SC:'A',PV:0.085,P:5.882352734375,P_:'X',V_:''},{ID:3,N:'AA Grp',NC:'5GZ',R:'NONE',I:'NONE',M:'t',LT:0.000,C:0.000,VL:0.000,BV:100.000,B:0.050,S:0.060,SV:50.000,O:0.000,H:0.000,L:0.000,V:0.000,SC:'2',PV:0.050,P:0.0,P_:'X',V_:''}]}" A: You're using simplejson correctly, but the site that gave you that data isn't using JSON format properly. Look at json.org, which uses simple syntax diagrams to show what is JSON: in the object diagram, after { (unless the object is empty, in which case a } immediately follows), JSON always has a string -- and as you see in that diagram, this means something that starts with a double quote. So, the very start of the string: {identifier: tells you that's incorrect JSON -- no double quotes around the word identifier. Working around this problem is not as easy as recognizing it's there, but I wanted to reassure you, at least, about your code. Sigh it does seem that broken websites, such a great tradition in old HTML days, are with us to stay no matter how modern the technology they break is...:-(
How to use simplejson to decode following data?
I grab some data from a URL, and search online to find out the data is in in Jason data format, but when I tried to use simplejson.loads(data), it will raise exception. First time deal with jason data, any suggestion how to decode the data? Thanks ================= result = simplejson.loads(data, encoding="utf-8") File "F:\My Documents\My Dropbox\StockDataDownloader\simplejson__init__.py", line 401, in loads return cls(encoding=encoding, **kw).decode(s) File "F:\My Documents\My Dropbox\StockDataDownloader\simplejson\decoder.py", line 402, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "F:\My Documents\My Dropbox\StockDataDownloader\simplejson\decoder.py", line 420, in raw_decode raise JSONDecodeError("No JSON object could be decoded", s, idx) simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0) ============================ data = "{identifier:'ID', label:'As at Wed 4 Aug 2010 05:05 PM',items:[{ID:0,N:'2ndChance',NC:'528',R:'NONE',I:'NONE',M:'-',LT:0.335,C:0.015,VL:51.000,BV:20.000,B:0.330,S:0.345,SV:20.000,O:0.335,H:0.335,L:0.335,V:17085.000,SC:'4',PV:0.320,P:4.6875,P_:'X',V_:''},{ID:1,N:'8Telecom',NC:'E25',R:'NONE',I:'NONE',M:'-',LT:0.190,C:0.000,VL:965.000,BV:1305.000,B:0.185,S:0.190,SV:641.000,O:0.185,H:0.190,L:0.185,V:179525.000,SC:'2',PV:0.190,P:0.0,P_:'X',V_:''},{ID:2,N:'A-Sonic',NC:'A53',R:'NONE',I:'NONE',M:'-',LT:0.090,C:0.005,VL:1278.000,BV:17.000,B:0.090,S:0.095,SV:346.000,O:0.090,H:0.090,L:0.090,V:115020.000,SC:'A',PV:0.085,P:5.882352734375,P_:'X',V_:''},{ID:3,N:'AA Grp',NC:'5GZ',R:'NONE',I:'NONE',M:'t',LT:0.000,C:0.000,VL:0.000,BV:100.000,B:0.050,S:0.060,SV:50.000,O:0.000,H:0.000,L:0.000,V:0.000,SC:'2',PV:0.050,P:0.0,P_:'X',V_:''}]}"
[ "You're using simplejson correctly, but the site that gave you that data isn't using JSON format properly. Look at json.org, which uses simple syntax diagrams to show what is JSON: in the object diagram, after { (unless the object is empty, in which case a } immediately follows), JSON always has a string -- and as...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003411469_python.txt
Q: Python permutation generator puzzle I am writing a permutation function that generate all permutations of a list in Python. My question is why this works: def permute(inputData, outputSoFar): for elem in inputData: if elem not in outputSoFar: outputSoFar.append(elem) if len(outputSoFar) == len(inputData): print outputSoFar else: permute(inputData, outputSoFar) # --- Recursion outputSoFar.pop() permute([1,2,3],[]) But this does not: def permute(inputData, outputSoFar): for elem in inputData: if elem not in outputSoFar: outputSoFar.append(elem) if len(outputSoFar) == len(inputData): yield outputSoFar else: permute(inputData, outputSoFar) # --- Recursion outputSoFar.pop() for i in permute([1,2,3], []): print i This does not work either (yield a copy of the list): def permute(inputData, outputSoFar): for elem in inputData: if elem not in outputSoFar: outputSoFar.append(elem) if len(outputSoFar) == len(inputData): yield outputSoFar[:] # --- Copy of the list else: permute(inputData, outputSoFar) # --- Recursion outputSoFar.pop() for i in permute([1,2,3], []): print i A: You must also yield the results of the recursive call(s): def permute(inputData, outputSoFar): for a in inputData: if a not in outputSoFar: if len(outputSoFar) == len(inputData) - 1: yield outputSoFar + [a] else: for b in permute(inputData, outputSoFar + [a]): # --- Recursion yield b for i in permute([1,2,3], []): print i ... Or (closer to the OP code): def permute(inputData, outputSoFar): for elem in inputData: if elem not in outputSoFar: outputSoFar.append(elem) if len(outputSoFar) == len(inputData): yield outputSoFar else: for permutation in permute(inputData, outputSoFar): yield permutation # --- Recursion outputSoFar.pop() for i in permute([1,2,3], []): print i A: You're destructively losing items when you do the pop. Use copies of the list instead of mutating it in-place. Alternately, use itertools.permutations or itertools.combinations instead.
Python permutation generator puzzle
I am writing a permutation function that generate all permutations of a list in Python. My question is why this works: def permute(inputData, outputSoFar): for elem in inputData: if elem not in outputSoFar: outputSoFar.append(elem) if len(outputSoFar) == len(inputData): print outputSoFar else: permute(inputData, outputSoFar) # --- Recursion outputSoFar.pop() permute([1,2,3],[]) But this does not: def permute(inputData, outputSoFar): for elem in inputData: if elem not in outputSoFar: outputSoFar.append(elem) if len(outputSoFar) == len(inputData): yield outputSoFar else: permute(inputData, outputSoFar) # --- Recursion outputSoFar.pop() for i in permute([1,2,3], []): print i This does not work either (yield a copy of the list): def permute(inputData, outputSoFar): for elem in inputData: if elem not in outputSoFar: outputSoFar.append(elem) if len(outputSoFar) == len(inputData): yield outputSoFar[:] # --- Copy of the list else: permute(inputData, outputSoFar) # --- Recursion outputSoFar.pop() for i in permute([1,2,3], []): print i
[ "You must also yield the results of the recursive call(s):\ndef permute(inputData, outputSoFar):\n for a in inputData:\n if a not in outputSoFar:\n if len(outputSoFar) == len(inputData) - 1:\n yield outputSoFar + [a]\n else:\n for b in permute(inputData,...
[ 3, 0 ]
[]
[]
[ "generator", "permutation", "puzzle", "python", "recursion" ]
stackoverflow_0003411612_generator_permutation_puzzle_python_recursion.txt
Q: Python logging for non-trivial uses? I'm attempting to use the python logging module to do complex things. I'll leave the motivation for this design out because it would greatly lengthen the post, but I need to have a root logger that spams a regular log file for our code and libraries that use logging -- and a collection of other loggers that go to different log files. The overall setup should look like this. I will do everything to stdout in this example to simplify the code. import logging, sys root = logging.getLogger('') top = logging.getLogger('top') bottom = logging.getLogger('top.bottom') class KillFilter(object): def filter(self, msg): return 0 root_handler = logging.StreamHandler(sys.stdout) top_handler = logging.StreamHandler(sys.stdout) bottom_handler = logging.StreamHandler(sys.stdout) root_handler.setFormatter(logging.Formatter('ROOT')) top_handler.setFormatter(logging.Formatter('TOP HANDLER')) bottom_handler.setFormatter(logging.Formatter("BOTTOM HANDLER")) msg_killer = KillFilter() root.addHandler(root_handler) top.addHandler(top_handler) bottom.addHandler(bottom_handler) top.addFilter(msg_killer) root.error('hi') top.error('hi') bottom.error('hi') This outputs ROOT BOTTOM HANDLER ROOT The second root handler call should not because according to logging documentation the msg_killer will stop the message from going up to the root logger. Obviously the documentation could use improvement. Edit: removed my "in the moment" harsh words for python logging. A: First off, I get a different output on my machine (running Python 2.6): ROOT BOTTOM HANDLER TOP HANDLER ROOT Filtering is only applied on the logger that the message is issued to, and if it passes the filters, it's then propagated to all the handlers of the parent loggers (and not the loggers themselves) - I don't know the rationale for this decision. If you want to stop propagation at say the "top" Logger instance, set: top.propagation = False A: Source is messed with different case identifiers, more useful version: import logging, sys root = logging.getLogger('') level1 = logging.getLogger('level1') level2 = logging.getLogger('level1.level2') class KillFilter(object): def filter(self, msg): return 0 root_handler = logging.StreamHandler(sys.stdout) top_handler = logging.StreamHandler(sys.stdout) bottom_handler = logging.StreamHandler(sys.stdout) root_handler.setFormatter(logging.Formatter('ROOT HANDLER - %(msg)s')) top_handler.setFormatter(logging.Formatter('level1 HANDLER - %(msg)s')) bottom_handler.setFormatter(logging.Formatter('level2 HANDLER - %(msg)s')) msg_killer = KillFilter() root.addHandler(root_handler) level1.addHandler(top_handler) level2.addHandler(bottom_handler) level1.addFilter(msg_killer) level1.propagate = False root.error('root_message') level1.error('level1_message') level2.error('level2_message')
Python logging for non-trivial uses?
I'm attempting to use the python logging module to do complex things. I'll leave the motivation for this design out because it would greatly lengthen the post, but I need to have a root logger that spams a regular log file for our code and libraries that use logging -- and a collection of other loggers that go to different log files. The overall setup should look like this. I will do everything to stdout in this example to simplify the code. import logging, sys root = logging.getLogger('') top = logging.getLogger('top') bottom = logging.getLogger('top.bottom') class KillFilter(object): def filter(self, msg): return 0 root_handler = logging.StreamHandler(sys.stdout) top_handler = logging.StreamHandler(sys.stdout) bottom_handler = logging.StreamHandler(sys.stdout) root_handler.setFormatter(logging.Formatter('ROOT')) top_handler.setFormatter(logging.Formatter('TOP HANDLER')) bottom_handler.setFormatter(logging.Formatter("BOTTOM HANDLER")) msg_killer = KillFilter() root.addHandler(root_handler) top.addHandler(top_handler) bottom.addHandler(bottom_handler) top.addFilter(msg_killer) root.error('hi') top.error('hi') bottom.error('hi') This outputs ROOT BOTTOM HANDLER ROOT The second root handler call should not because according to logging documentation the msg_killer will stop the message from going up to the root logger. Obviously the documentation could use improvement. Edit: removed my "in the moment" harsh words for python logging.
[ "First off, I get a different output on my machine (running Python 2.6):\nROOT\nBOTTOM HANDLER\nTOP HANDLER\nROOT\n\nFiltering is only applied on the logger that the message is issued to, and if it passes the filters, it's then propagated to all the handlers of the parent loggers (and not the loggers themselves) - ...
[ 7, 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0001580828_logging_python.txt
Q: Simple Twisted server won't write with Timer I'm just learning Python and Twisted and I can't figure out for the life of me why this simple server won't work. The self.transport.write doesn't work when called from a timer. I get no error at all. Any help appreciated. Thank you very much! from twisted.internet.protocol import Factory, Protocol from twisted.internet import reactor from threading import Timer class proto(Protocol): def saySomething(self): self.transport.write('hello there\r\n') def connectionMade(self): Timer(5, self.saySomething).start() class theFactory(Factory): protocol = proto reactor.listenTCP(8007, theFactory()) reactor.run() A: I figured it out myself. From http://twistedmatrix.com/documents/current/core/howto/threading.html: Most code in Twisted is not thread-safe. For example, writing data to a transport from a protocol is not thread-safe. Thanks anyways folks!
Simple Twisted server won't write with Timer
I'm just learning Python and Twisted and I can't figure out for the life of me why this simple server won't work. The self.transport.write doesn't work when called from a timer. I get no error at all. Any help appreciated. Thank you very much! from twisted.internet.protocol import Factory, Protocol from twisted.internet import reactor from threading import Timer class proto(Protocol): def saySomething(self): self.transport.write('hello there\r\n') def connectionMade(self): Timer(5, self.saySomething).start() class theFactory(Factory): protocol = proto reactor.listenTCP(8007, theFactory()) reactor.run()
[ "I figured it out myself.\nFrom http://twistedmatrix.com/documents/current/core/howto/threading.html:\n\nMost code in Twisted is not thread-safe. For example, writing data to a transport from a protocol is not thread-safe.\n\nThanks anyways folks!\n" ]
[ 2 ]
[]
[]
[ "python", "timer", "twisted" ]
stackoverflow_0003411511_python_timer_twisted.txt
Q: How can I get the installed GDAL/OGR version from python? How can I get the installed GDAL/OGR version from python? I aware of the gdal-config program and are currently using the following: In [3]: import commands In [4]: commands.getoutput('gdal-config --version') Out[4]: '1.7.2' However, I suspect there is a way to do this using the python API itself. Any dice? A: gdal.VersionInfo() does what I want: >>> osgeo.gdal.VersionInfo() '1604' This works on both my Windows box and Ubuntu install. gdal.__version__ gives an error on my Windows installation, although it works on my Ubuntu installation: >>> import osgeo.gdal >>> print osgeo.gdal.__version__ Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute '__version__' A: The __version__ property in the osgeo.gdal module is a string that contains the version number import osgeo.gdal print osgeo.gdal.__version__ On my ubuntu machine gives: >> '1.6.3'
How can I get the installed GDAL/OGR version from python?
How can I get the installed GDAL/OGR version from python? I aware of the gdal-config program and are currently using the following: In [3]: import commands In [4]: commands.getoutput('gdal-config --version') Out[4]: '1.7.2' However, I suspect there is a way to do this using the python API itself. Any dice?
[ "gdal.VersionInfo() does what I want:\n>>> osgeo.gdal.VersionInfo()\n'1604'\n\nThis works on both my Windows box and Ubuntu install. gdal.__version__ gives an error on my Windows installation, although it works on my Ubuntu installation:\n>>> import osgeo.gdal\n>>> print osgeo.gdal.__version__\nTraceback (most rec...
[ 25, 16 ]
[]
[]
[ "gdal", "geospatial", "gis", "ogr", "python" ]
stackoverflow_0003233674_gdal_geospatial_gis_ogr_python.txt
Q: Simple "Hello-World" program for python-evince I'm trying to write a simple "hello-world"-type program using the python-evince package for lucid-lynx gnome, that embeds Evince in a python-gtk window. The samples I've found on the web go like this: import evince import gtk w = gtk.Window() w.show() e = evince.View() w.add(e) e.show() document = evince.document_factory_get_document('my pdf file') e.set_document(document) gtk.main() The problem is that "evince.set_document" no longer exists: The forums seem to indicate that there have been recent changes, but I have been unable to figure out the (probably very simple) modifications necessary to get this working. Can anyone help? A: The API has changed, with an extra step added. These instructions should help: >>> e = evince.View() >>> docmodel = evince.DocumentModel() >>> doc = evince.document_factory_get_document('file:///path/to/file/example.pdf') >>> docmodel.set_document(doc) >>> e.set_model(model)
Simple "Hello-World" program for python-evince
I'm trying to write a simple "hello-world"-type program using the python-evince package for lucid-lynx gnome, that embeds Evince in a python-gtk window. The samples I've found on the web go like this: import evince import gtk w = gtk.Window() w.show() e = evince.View() w.add(e) e.show() document = evince.document_factory_get_document('my pdf file') e.set_document(document) gtk.main() The problem is that "evince.set_document" no longer exists: The forums seem to indicate that there have been recent changes, but I have been unable to figure out the (probably very simple) modifications necessary to get this working. Can anyone help?
[ "The API has changed, with an extra step added. These instructions should help:\n>>> e = evince.View()\n>>> docmodel = evince.DocumentModel()\n>>> doc = evince.document_factory_get_document('file:///path/to/file/example.pdf')\n>>> docmodel.set_document(doc)\n>>> e.set_model(model)\n\n" ]
[ 1 ]
[]
[]
[ "gnome", "gtk", "python" ]
stackoverflow_0003411929_gnome_gtk_python.txt
Q: Pattern matching in dictionary using python In the following dictionary,can the elements be sorted according the last prefix in the key opt_dict=( {'option1':1, 'nonoption2':1, 'nonoption3':12, 'option4':6, 'nonoption5':5, 'option6':1, 'option7':1, }) for key,val in opt_dict.items(): if "answer" in key: //match keys last prefix and print output print "found option 1,4,6,7" //in ascending order elif "nonanswer" in key: //match keys last prefix and print output print "found option 2,3,5 " //in ascending order Thanks.. A: for k,v in sorted(opt_dict.items(), key = lambda item: int(item[0][len("option"):]) if item[0].startswith("option") else int(item[0][len("nonoption"):]) ): print k,v Prints: option1 1 nonoption2 1 nonoption3 12 option4 6 nonoption5 5 option6 1 option7 1
Pattern matching in dictionary using python
In the following dictionary,can the elements be sorted according the last prefix in the key opt_dict=( {'option1':1, 'nonoption2':1, 'nonoption3':12, 'option4':6, 'nonoption5':5, 'option6':1, 'option7':1, }) for key,val in opt_dict.items(): if "answer" in key: //match keys last prefix and print output print "found option 1,4,6,7" //in ascending order elif "nonanswer" in key: //match keys last prefix and print output print "found option 2,3,5 " //in ascending order Thanks..
[ "for k,v in sorted(opt_dict.items(),\n key = lambda item: int(item[0][len(\"option\"):])\n if item[0].startswith(\"option\")\n else int(item[0][len(\"nonoption\"):])\n ):\n print k,v\n\nPrints:\noption1 1\nnonoption2 1\nnon...
[ -2 ]
[]
[]
[ "python" ]
stackoverflow_0003412310_python.txt
Q: Printing the values of a tuple Accessing tuple values How to access the value of a and b in the following >> t=[] >> t.append(("a" , 1)) >> t.append(("b" , 2)) >> print t[0][0] a >> print t[1][0] b How to print the values of a and b A: Just do print t[0][1] print t[1][1] But of course if you really want to look up for a or b, this is not the best construct, then you need a dict: t = {} t["a"] = 1 t["b"] = 2 print t["a"] print t["b"] A: It's simpler than expected: >> t=[] >> t.append(("a" , 1)) >> t.append(("b" , 2)) >> dict(t).get('a') # 1 Happy Coding. A: >>> t [('a', 1), ('b', 2)] >>> t[0][1] 1 >>> t[1][1] 2
Printing the values of a tuple
Accessing tuple values How to access the value of a and b in the following >> t=[] >> t.append(("a" , 1)) >> t.append(("b" , 2)) >> print t[0][0] a >> print t[1][0] b How to print the values of a and b
[ "Just do\nprint t[0][1]\nprint t[1][1]\n\nBut of course if you really want to look up for a or b, this is not the best construct, then you need a dict:\nt = {}\nt[\"a\"] = 1\nt[\"b\"] = 2\nprint t[\"a\"]\nprint t[\"b\"]\n\n", "It's simpler than expected: \n>> t=[]\n>> t.append((\"a\" , 1))\n>> t.append((\"b\" , 2...
[ 5, 2, 1 ]
[ "print t[0][1]\nprint t[1][1]\n\n??\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0003412576_python.txt
Q: Python cut a string after Xth sentence I have to cut a unicode string which is actually an article (contains sentences) I want to cut this article string after Xth sentence in python. A good indicator of a sentence ending is that it ends with full stop (".") and the word after start with capital name. Such as myarticle == "Hi, this is my first sentence. And this is my second. Yet this is my third." How can this be achieved ? Thanks A: Consider downloading the Natural Language Toolkit (NLTK). Then you can create sentences that will not break for things like "U.S.A." or fail to split sentences that end in "?!". >>> import nltk >>> paragraph = u"Hi, this is my first sentence. And this is my second. Yet this is my third." >>> sentences = nltk.sent_tokenize(paragraph) [u"Hi, this is my first sentence.", u"And this is my second.", u"Yet this is my third."] Your code becomes much more readable. To access the second sentence, you use notation you're used to. >>> sentences[1] u"And this is my second." A: Here is a more robust solution: myarticle = """This is a sentence. And another one. And a 3rd one.""" N = 3 # 3 sentences print ''.join(sentence+'.' for sentence in re.split('\.(?=\s*(?:[A-Z]|$))', myarticle, maxsplit=N)[:-1]) This solution has a few advantages over some of the other possibilities mentioned before: It works even when there are exactly N sentences in your text. Some other answers yield a double . at the end. This is avoided here by taking into account the fact that the last sentence is not followed by an uppercase letter, but by an end-of-text ($). This works even when there are fewer than N sentences in the text. The number of splits is limited by the maxsplit argument to re.split(), which limits the number of splittings and is therefore quite efficient. Hope this helps! A: If there can be other punctuation marks than the usual '.', you should probably try this: re.split('\W(?=[A-Z])',ss) This returns the list of the sentences. Of course, it does not treat correctly the cases mentioned by Paul. A: Try this: '.'.join(re.split('\.(?=\s*[A-Z])', myarticle)[:2]) + '.' It cuts your string after the second sentence ([:2]). However there are some problems (as always if you deal with natural language): Most notably it will only recognize a sentence that starts with 'A-Z'. That might be true for English but not for other languages.
Python cut a string after Xth sentence
I have to cut a unicode string which is actually an article (contains sentences) I want to cut this article string after Xth sentence in python. A good indicator of a sentence ending is that it ends with full stop (".") and the word after start with capital name. Such as myarticle == "Hi, this is my first sentence. And this is my second. Yet this is my third." How can this be achieved ? Thanks
[ "Consider downloading the Natural Language Toolkit (NLTK). Then you can create sentences that will not break for things like \"U.S.A.\" or fail to split sentences that end in \"?!\". \n>>> import nltk\n>>> paragraph = u\"Hi, this is my first sentence. And this is my second. Yet this is my third.\"\n>>> sentences = ...
[ 15, 2, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003412316_python_string.txt
Q: Threading in Python I have two definitions or methods in python. I'd like to run them at the same exact time. Originally I tried to use forking but since the child retained the memory from the parent, it's writing multiple things that I don't need in a file. So I switched to threading. I have something similar to import threading class test(threading.Thread) def __init__(self,numA, list): self.__numA=numA # (random number) self.__list=list #(list) def run(self): makelist(self) makelist2(self) makelist() and makelist2() use numA and list. So in those definitions/methods instead of saying print list I say print self.__list. In the main() I made a new class object: x = test() x.start() When I run my program I get an attribute error saying it cannot recognize the __list or __numA. I've been stuck on this for a while. If there's another better way to run two methods at the same time (the methods are not connected at all) please inform me of so and explain how. Thank you. A: The __list and __numA won't be visible from makelist and makelist2 if they are not also members of the same class. The double underscore will make things like this fail: >>> class A(object): ... def __init__(self): ... self.__a = 2 ... >>> def f(x): ... print x.__a ... >>> a = A() >>> f(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f AttributeError: 'A' object has no attribute '__a' But, naming the __a something without two leading underscores would work. Is that what you are seeing? You can read more about private variables in the python documentation. A: Firstly, don't name your variable the same as built-in types or functions, i.e. list. Secondly. as well as the problems that others have pointed out (__ name mangling, initialising Thread etc), if your intention is to run makelist and makelist2 at the same time then you are doing it wrong, since your run method will still execute them one after the other. You need to run them in separate threads, not sequentially in the same thread. Thirdly how exact do you mean by "same exact time"? Using threads in (C)Python this is physically impossible, since the execution will be interleaved at the bytecode level. Other versions of Python (Jython, IronPython etc) may run them at exactly the same time on a multi-core system, but even then you have no control over when the OS scheduler will start each one. Finally it is a bad idea to share mutable objects between threads, since if both threads change the data at the same time then unpredictable things can (and will) happen. You need to protect against this by either using locks or only passing round immutable data or copies of the data. Using locks can also cause its own problems if you are not careful, such as deadlocks. A: I'd like to run them at the same exact time. You can't do this with threading: the Global Interpreter Lock in Python ensures that only one thread can execute Python code at any time (threads are switched every sys.getcheckinterval() bytecodes). Use multiprocessing instead: from multiprocessing import Process import os def info(title): print title print 'module name:', __name__ print 'parent process:', os.getppid() print 'process id:', os.getpid() def f(name): info('function f') print 'hello', name if __name__ == '__main__': info('main line') p = Process(target=f, args=('bob',)) p.start() p.join() A: A Couple of things: A) When you override the __init__ method of the threading.Thread object you need to initialize threading.Thread yourself which can be accomplished by putting "threading.Thread.__init__(self)" at the end of the __init__ function B) As msw pointed out those calls to "makelist" and "makelist2" seem to be to global functions which kinda defeats the purpose of the threading. I recommend making them functions of test.
Threading in Python
I have two definitions or methods in python. I'd like to run them at the same exact time. Originally I tried to use forking but since the child retained the memory from the parent, it's writing multiple things that I don't need in a file. So I switched to threading. I have something similar to import threading class test(threading.Thread) def __init__(self,numA, list): self.__numA=numA # (random number) self.__list=list #(list) def run(self): makelist(self) makelist2(self) makelist() and makelist2() use numA and list. So in those definitions/methods instead of saying print list I say print self.__list. In the main() I made a new class object: x = test() x.start() When I run my program I get an attribute error saying it cannot recognize the __list or __numA. I've been stuck on this for a while. If there's another better way to run two methods at the same time (the methods are not connected at all) please inform me of so and explain how. Thank you.
[ "The __list and __numA won't be visible from makelist and makelist2 if they are not also members of the same class. The double underscore will make things like this fail:\n>>> class A(object):\n... def __init__(self):\n... self.__a = 2\n...\n>>> def f(x):\n... print x.__a\n...\n>>> a = A()\n>>> f(a)\nT...
[ 1, 1, 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0003412283_multithreading_python.txt
Q: Monitor Global keyboard input on a Mac with python Trying to write a program that allows users to control a program via global shortcuts. I already have a working version on windows using pyHook but can't figure out how to capture global input on a Mac. The other questions I have read here so far mostly seemed to be about Linux not Mac. (which is why I'm asking) Is there any way to do this? A: I believe you could use PyObjC to handle the API hooks; look at this explanation for what to do.
Monitor Global keyboard input on a Mac with python
Trying to write a program that allows users to control a program via global shortcuts. I already have a working version on windows using pyHook but can't figure out how to capture global input on a Mac. The other questions I have read here so far mostly seemed to be about Linux not Mac. (which is why I'm asking) Is there any way to do this?
[ "I believe you could use PyObjC to handle the API hooks; look at this explanation for what to do.\n" ]
[ 0 ]
[]
[]
[ "input", "keyboard", "macos", "python" ]
stackoverflow_0003412329_input_keyboard_macos_python.txt