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: Is there any python web app framework that provides database abstraction layer for SQL and NoSQL? Is it even possible to create an abstraction layer that can accommodate relational and non-relational databases? The purpose of this layer is to minimize repetition and allows a web application to use any kind of data...
Is there any python web app framework that provides database abstraction layer for SQL and NoSQL?
Is it even possible to create an abstraction layer that can accommodate relational and non-relational databases? The purpose of this layer is to minimize repetition and allows a web application to use any kind of database by just changing/modifying the code in one place (ie, the abstraction layer). The part that sits o...
[ "There's a Summer of Code project going on right now to add non-relational support to Django's ORM. It seems to be going well and chances are good that it will be merged into core in time for Django 1.3.\n", "You could use stock Django and Django-nonrel ( http://www.allbuttonspressed.com/projects/django-nonrel ) ...
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "database", "google_app_engine", "nosql", "python", "sql" ]
stackoverflow_0003606215_database_google_app_engine_nosql_python_sql.txt
Q: how to go to the next page using django paginator? I have something like this: myobj = paginator_method(request, myresult) return render_to_response(' ', myobj, context) And when I am going to page 2 and onward its giving MultiValueDictKeyError: Key 'name' not found in <QueryDict: {u'page': [u'2']} A: return r...
how to go to the next page using django paginator?
I have something like this: myobj = paginator_method(request, myresult) return render_to_response(' ', myobj, context) And when I am going to page 2 and onward its giving MultiValueDictKeyError: Key 'name' not found in <QueryDict: {u'page': [u'2']}
[ "return render_to_response(' ', dict(pagination=myobj, data=myresult), context)\n\n.\n{{ pagination.somevar }}\n{{ data.somevar }}\n\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003649765_django_python.txt
Q: What are differences between List, Dictionary and Tuple in Python? What is the difference between list, dictionary and tuple in Python exactly? A: A list can store a sequence of objects in a certain order such that you can index into the list, or iterate over the list. List is a mutable type meaning that lists c...
What are differences between List, Dictionary and Tuple in Python?
What is the difference between list, dictionary and tuple in Python exactly?
[ "A list can store a sequence of objects in a certain order such that you can index into the list, or iterate over the list. List is a mutable type meaning that lists can be modified after they have been created.\nA tuple is similar to a list except it is immutable. There is also a semantic difference between a list...
[ 53 ]
[]
[]
[ "python" ]
stackoverflow_0003649841_python.txt
Q: Using the ttk (tk 8.5) Notebook widget effectively (scrolling of tabs) I'm working on a project using Tkinter and Python. In order to have native theming and to take advantage of the new widgets I'm using ttk in Python 2.6. My problem is how to allow the user to scroll through the tabs in the notebook widget (a la...
Using the ttk (tk 8.5) Notebook widget effectively (scrolling of tabs)
I'm working on a project using Tkinter and Python. In order to have native theming and to take advantage of the new widgets I'm using ttk in Python 2.6. My problem is how to allow the user to scroll through the tabs in the notebook widget (a la firefox). Plus, I need a part in the right edge of the tabs for a close but...
[ "The notebook widget doesn't do scrolling of tabs (or multiple layers of them either) because the developer doesn't believe that they make for a good GUI. I can see his point; such GUIs tend to suck. The best workaround I've seen is to have a panel on the side that allows the selection of which pane to display. You...
[ 3, 0 ]
[]
[]
[ "python", "tkinter", "ttk", "user_interface" ]
stackoverflow_0003386098_python_tkinter_ttk_user_interface.txt
Q: Why isn't web2py more readily adopted? I have been playing with python and different web frameworks. I started with Django, but am not in so deep that I am entrenched. I really quite like python but have not found that "perfect" web solution. My qualifications of perfect would be: simple to learn/code simple to...
Why isn't web2py more readily adopted?
I have been playing with python and different web frameworks. I started with Django, but am not in so deep that I am entrenched. I really quite like python but have not found that "perfect" web solution. My qualifications of perfect would be: simple to learn/code simple to host (my webhost, Site5, isn't exactly pyth...
[ "Django is more widely used, because Django is (already) more widely used. \n" ]
[ 1 ]
[]
[]
[ "django", "python", "web2py" ]
stackoverflow_0003649079_django_python_web2py.txt
Q: How to understand makefiles and python I'm trying to understand how a makefile works for compiling some .ui files to .py (PyQt -> Python). This is the makefile that I am using that was autogenerated: # Makefile for a PyQGIS plugin UI_FILES = Ui_UrbanAnalysis.py RESOURCE_FILES = resources.py default: compile ...
How to understand makefiles and python
I'm trying to understand how a makefile works for compiling some .ui files to .py (PyQt -> Python). This is the makefile that I am using that was autogenerated: # Makefile for a PyQGIS plugin UI_FILES = Ui_UrbanAnalysis.py RESOURCE_FILES = resources.py default: compile compile: $(UI_FILES) $(RESOURCE_FILES) %.p...
[ "Not that I know the build steps you are trying to achieve, but both of these lines:\ndefault: compile\n compile: $(UI_FILES) $(RESOURCE_FILES)\n\nlook like target lines, so they should probably be:\ndefault: compile\n\ncompile: $(UI_FILES) $(RESOURCE_FILES)\n\nAs it was make is probably trying to interpret the ...
[ 2 ]
[]
[]
[ "makefile", "python" ]
stackoverflow_0003650625_makefile_python.txt
Q: Jump into a Python Interactive Session mid-program? Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering: Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution? I think that wo...
Jump into a Python Interactive Session mid-program?
Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering: Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution? I think that would be pretty handy ;) edit: I want to emphasize that my ...
[ "So roughly a year on from the OP's question, PyDev has this capability built in. I am not sure when this feature was introduced, but all I know is I've spent the last ~2hrs Googling... configuring iPython and whatever (which was looking like it would have done the job), but only to realise Eclipse/PyDev has what I...
[ 9, 6, 3, 2 ]
[ "If you are already running in debug mode you can set an additional breakpoint if the program execution is currently paused (e.g. because you are already at a breakpoint). I just tried it out now with the latest Pydev - it works just fine. \nIf you are running normally (i.e. not in debug mode) all breakpoints will ...
[ -2 ]
[ "breakpoints", "debugging", "eclipse", "pydev", "python" ]
stackoverflow_0000925832_breakpoints_debugging_eclipse_pydev_python.txt
Q: Django - Ajax HttpResponse delay I have a django view function that calls another function if a condition is true, the function is called as a separate process, the view returns a status variable which shows if the function was called or not, the status is returned to a ajax click event assigned to a button. The p...
Django - Ajax HttpResponse delay
I have a django view function that calls another function if a condition is true, the function is called as a separate process, the view returns a status variable which shows if the function was called or not, the status is returned to a ajax click event assigned to a button. The problem is that when the function 'do_w...
[ "Although you see the printed message before you return HttpResponse(success), that return statement in itself can't asynchronously finish the response.\nPresumably after that function returns, your web server is still waiting for something else to happen (such as for all child processes to terminate) before it fin...
[ 1 ]
[]
[]
[ "ajax", "django", "jquery", "process", "python" ]
stackoverflow_0003650465_ajax_django_jquery_process_python.txt
Q: Nicest, efficient way to get result tuple of sequence items fulfilling and not fulfilling condition (This is professional best practise/ pattern interest, not home work request) INPUT: any unordered sequence or generator items, function myfilter(item) returns True if filter condition is fulfilled OUTPUT: (filter_...
Nicest, efficient way to get result tuple of sequence items fulfilling and not fulfilling condition
(This is professional best practise/ pattern interest, not home work request) INPUT: any unordered sequence or generator items, function myfilter(item) returns True if filter condition is fulfilled OUTPUT: (filter_true, filter_false) tuple of sequences of original type which contain the elements partitioned according ...
[ "Here is a way to do it which only calls myfilter once for each item and will also work if mylist is a generator\nimport itertools as it\nleft,right = it.tee((myfilter(x), x) for x in mylist)\nfilter_true = (x for p,x in left if p)\nfilter_false = (x for p,x in right if not p)\n\n", "Let's suppose that your probl...
[ 5, 2, 0 ]
[ "I think your best bet will be constructing two separate generators:\nfilter_true = (x for x in mylist if myfilter(x))\nfilter_false = (x for x in mylist if not myfilter(x))\n\n" ]
[ -1 ]
[ "data_partitioning", "filter", "generator", "python" ]
stackoverflow_0003650305_data_partitioning_filter_generator_python.txt
Q: General network MVC framework for Python I have been using Django for web-development, and have become quite fond of that framework. However, I would like to use a similar framework but for more general network applications. Is there such a framework? Or is it possible to modify Django to be able to have a more ge...
General network MVC framework for Python
I have been using Django for web-development, and have become quite fond of that framework. However, I would like to use a similar framework but for more general network applications. Is there such a framework? Or is it possible to modify Django to be able to have a more general network/protocol backend?
[ "Twisted should be able to help you. Take a look at Twisted projects and decide on the protocol which you are going to use.\n" ]
[ 3 ]
[]
[]
[ "django", "network_programming", "python" ]
stackoverflow_0003650818_django_network_programming_python.txt
Q: python threadpool problem (wait for something) I wrote simple web site crowler with threadpool. The problem is: then crawler is get all over site it must finish, but in real it wait for something in the end,and script dont finished, why this happend? from Queue import Queue from threading import Thread import sys...
python threadpool problem (wait for something)
I wrote simple web site crowler with threadpool. The problem is: then crawler is get all over site it must finish, but in real it wait for something in the end,and script dont finished, why this happend? from Queue import Queue from threading import Thread import sys from urllib import urlopen from BeautifulSoup impor...
[ "The problem I see is that you never quit the while in run. So, it will block forever. You need to break that loop when the jobs are done.\nYou could try to :\n1) insert \nif not func: break \n\nafter task.get(...) in run. \n2) append \npool.add_task(None, None, None) \n\nat the end of process. \nThis is a wa...
[ 1 ]
[]
[]
[ "multithreading", "pool", "python" ]
stackoverflow_0003648781_multithreading_pool_python.txt
Q: adding python packages to uClinux I have distribution of uClinux, throught "menu config" I check python and compile("make"). I have python on my chip now. There is a binary executable file /bin/python. But what about python packages? There are only some basic packages as sys, time etc. I want to add for example pa...
adding python packages to uClinux
I have distribution of uClinux, throught "menu config" I check python and compile("make"). I have python on my chip now. There is a binary executable file /bin/python. But what about python packages? There are only some basic packages as sys, time etc. I want to add for example package pyserial for serial port. Before ...
[ "Did you take a look at this page : http://bytes.com/topic/python/answers/782203-python-board-os-uclinux ?\nI'm not sure it will fulfill your needs, but it could :)\n" ]
[ 0 ]
[]
[]
[ "linux", "package", "python", "uclinux" ]
stackoverflow_0003650780_linux_package_python_uclinux.txt
Q: going to next page using django paginator sends request again. My google search application making a request each time while i am using paginator. Suppose i have a 100 records. Each page have to show 10 records so ten pages. When i click 2nd page it again sending a request. Ideally it should not send the request. ...
going to next page using django paginator sends request again.
My google search application making a request each time while i am using paginator. Suppose i have a 100 records. Each page have to show 10 records so ten pages. When i click 2nd page it again sending a request. Ideally it should not send the request.
[ "\nWhen i click 2nd page it again sending a request. Ideally it should not send the request.\n\nWhat do you mean by request? Is it a request to Google? \nYour application apparently does not cache the results. If your request to Google returns 100 pages then you should cache those hundred. When you request the seco...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003651125_django_python.txt
Q: Sending large file to PIPE input in python I have the following code: sourcefile = open(filein, "r") targetfile = open(pathout, "w") content= sourcefile.read(): p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE) p.communicate(content) sourcefile.close() targetfile.close() The data in sourcefile is quite large,...
Sending large file to PIPE input in python
I have the following code: sourcefile = open(filein, "r") targetfile = open(pathout, "w") content= sourcefile.read(): p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE) p.communicate(content) sourcefile.close() targetfile.close() The data in sourcefile is quite large, so it takes a lot of memory/swap to store it in...
[ "Replace the p.communicate(content) with a loop which reads from the sourcefile, and writes to p.stdin in blocks. When sourcefile is EOF, make sure to close p.stdin.\nsourcefile = open(filein, \"r\")\ntargetfile = open(pathout, \"w\")\n\np = Popen([SCRIPT], stdout=targetfile, stdin=PIPE)\nwhile True:\n data = so...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003651275_python.txt
Q: regexp python with parsing html page Good day. Little problem with regexp. I have a regexp that look like rexp2 = re.findall(r'<p>(.*?)</p>', data) And i need to grab all in <div id="header"> <h1></h1> <p> localhost OpenWrt Backfire<br /> Load: 0.00 0.00 0.00<br /> Hostname: localhost </p> </div> But my code do...
regexp python with parsing html page
Good day. Little problem with regexp. I have a regexp that look like rexp2 = re.findall(r'<p>(.*?)</p>', data) And i need to grab all in <div id="header"> <h1></h1> <p> localhost OpenWrt Backfire<br /> Load: 0.00 0.00 0.00<br /> Hostname: localhost </p> </div> But my code doesnt work :( What im doing wrong?
[ "Statutory Warning: It is a Bad Idea to parse (X)HTML using regular expression. \nFortunately there is a better way. To get going, first install the BeautifulSoup module. Next, read up on the documentation. Third, code!\nHere is one way to do what you are trying to do:\nfrom BeautifulSoup import BeautifulSoup\nhtml...
[ 4, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003651589_python_regex.txt
Q: Python: Do relative imports mean you can't execute a subpackage by itself? I've recently ported my Python project to run on Python 3.1. For that I had to adopt the policy of relative imports within the submodules and subpackages of my project. I've don’t that and now the project itself works, but I noticed I can't...
Python: Do relative imports mean you can't execute a subpackage by itself?
I've recently ported my Python project to run on Python 3.1. For that I had to adopt the policy of relative imports within the submodules and subpackages of my project. I've don’t that and now the project itself works, but I noticed I can't execute any of the subpackages or submodules in it. If I try, I get "builtins.V...
[ "Yes, it's normal. If you want to execute a module that is also a part of a package (in itself a strange thing to do) you need to have absolute imports. When you execute the module it is not, from the interpreters point of view, a part of a package, but the __main__ module. So it wouldn't know where the relative pa...
[ 4, 3 ]
[ "I had the same problem and I considered the -m switch too hard. \nInstead I use this:\ntry:\n from . import bar\nexcept ValueError:\n import bar\n\nif __name__ == \"__main__\":\n pass\n\n" ]
[ -1 ]
[ "import", "python", "python_3.x" ]
stackoverflow_0001585756_import_python_python_3.x.txt
Q: How can I call a particular base class method in Python? Let's say, I have the following two classes: class A(object): def __init__(self, i): self.i = i class B(object): def __init__(self, j): self.j = j class C(A, B): def __init__(self): super(C, self).__init__(self, 4) c = C(...
How can I call a particular base class method in Python?
Let's say, I have the following two classes: class A(object): def __init__(self, i): self.i = i class B(object): def __init__(self, j): self.j = j class C(A, B): def __init__(self): super(C, self).__init__(self, 4) c = C() c will only have the i attribute set, not the j. What shoul...
[ "If you want to set only the j attribute, then only call B.__init__:\nclass C(A, B):\n def __init__(self):\n B.__init__(self,4)\n\nIf you want to manually call both A and B's __init__ methods, then\nof course you could do this:\nclass C(A, B):\n def __init__(self):\n A.__init__(self,4)\n ...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0003651902_python.txt
Q: python - strange behavior question >>> class S(object): ... def __init__(self): ... self.x = 1 ... def x(self): ... return self.x ... >>> s = S() >>> s.x 1 >>> s.x() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable Why...
python - strange behavior question
>>> class S(object): ... def __init__(self): ... self.x = 1 ... def x(self): ... return self.x ... >>> s = S() >>> s.x 1 >>> s.x() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not callable Why, in this example, is s.x a method, but ...
[ "Python doesn't use separate spaces for callable and non-callable objects: a name is a name is a name. s.x, by Python rules, must refer to exactly the same object, whether you're going to call it or not. Another way of putting it: assuming that _aux is a name not otherwise used,\n_aux = self.x\n_aux()\n\nand\nsel...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "instantiation", "python", "scope" ]
stackoverflow_0003648890_instantiation_python_scope.txt
Q: How do I use an anonymous function within a class method in Python (closure)? class Test: def somemethod(self): def write(): print 'hello' write() x = Test() x.somemethod() write() is a function that will be used several times through somemethod(). somemethod() is the only funct...
How do I use an anonymous function within a class method in Python (closure)?
class Test: def somemethod(self): def write(): print 'hello' write() x = Test() x.somemethod() write() is a function that will be used several times through somemethod(). somemethod() is the only function within the class that will require it's use so it seems silly to define it outs...
[ "I find it impossible to reproduce the problem you report:\n>>> class Test(object):\n... def somemethod(self):\n... def write():\n... print 'hello'\n... write()\n... \n>>> x = Test()\n>>> x.somemethod()\nhello\n>>> \n\nso I believe you must have done some transcription error, or something. What do ...
[ 3, 0 ]
[]
[]
[ "anonymous_function", "closures", "python" ]
stackoverflow_0003649250_anonymous_function_closures_python.txt
Q: ping a server thru a specific port (fsockopen) in php function checkServer($domain, $port=80) { global $checkTimeout, $testServer; $status = 0; $starttime = microtime(true); $file = @fsockopen ($domain, $port, $errno, $errstr, $checkTimeout); $stoptime = microtime(true); if($file) { fclose($file); $s...
ping a server thru a specific port (fsockopen) in php
function checkServer($domain, $port=80) { global $checkTimeout, $testServer; $status = 0; $starttime = microtime(true); $file = @fsockopen ($domain, $port, $errno, $errstr, $checkTimeout); $stoptime = microtime(true); if($file) { fclose($file); $status = ($stoptime - $starttime) * 1000; $status = floo...
[ "Use CURL\nthis is an example how to conversion fsockopen to CURL \nPHP fsockopen to curl conversion\nGood luck\n" ]
[ 0 ]
[]
[]
[ "bash", "fsockopen", "php", "python", "sockets" ]
stackoverflow_0003652111_bash_fsockopen_php_python_sockets.txt
Q: Sortable tables in Django I read some of the other posts about this and some recommendations involved javascript and using other libraries. I did something quick by hand, but I'm new to Django and Python for that matter so I'm curious if this isn't a good way to do it. HTML <table> <tr> <td><...
Sortable tables in Django
I read some of the other posts about this and some recommendations involved javascript and using other libraries. I did something quick by hand, but I'm new to Django and Python for that matter so I'm curious if this isn't a good way to do it. HTML <table> <tr> <td><a href="?sort=to">To</a></td> ...
[ "Looks good to me. I'd suggest one minor refactoring in the view code:\nheaders = {'to':'asc',\n 'date':'asc',\n 'type':'asc',}\n\ndef table_view(request):\n sort = request.GET.get('sort')\n records = Record.objects.all()\n\n if sort is not None:\n records = records.order_by(sort)\n\...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003648512_django_python.txt
Q: Open Source Queue that works with Java, PHP and Python I'm currently in the market for a new queue system for jobs we have in our system. I've tried beanstalk but it's been unable to keep up with the load. I'm looking for a simple system to get up and running that I can put pieces of data in from producers and hav...
Open Source Queue that works with Java, PHP and Python
I'm currently in the market for a new queue system for jobs we have in our system. I've tried beanstalk but it's been unable to keep up with the load. I'm looking for a simple system to get up and running that I can put pieces of data in from producers and have consumers in Java, PHP and Python pull data off and proces...
[ "How about Apache ActiveMQ.\nAccessible from Java, PHP, Python.\nSupports all the features you requested.\n", "RabbitMQ is good messaging system and there are bindings for Java, PHP, Python and many other languages.\n", "The Berkeley database can be used to build a priority queue with bindings to most relevant ...
[ 3, 3, 0 ]
[]
[]
[ "java", "message_queue", "php", "python", "queue" ]
stackoverflow_0003652765_java_message_queue_php_python_queue.txt
Q: Why to copy a dictonairy from WSGI environment? In the following example from wsgi.org is cur_named copied: def __call__(self, environ, start_response): script_name = environ.get('SCRIPT_NAME', '') path_info = environ.get('PATH_INFO', '') for regex, application in self.patterns: match = regex.m...
Why to copy a dictonairy from WSGI environment?
In the following example from wsgi.org is cur_named copied: def __call__(self, environ, start_response): script_name = environ.get('SCRIPT_NAME', '') path_info = environ.get('PATH_INFO', '') for regex, application in self.patterns: match = regex.match(path_info) if not match: con...
[ "Do you know where cur_named dict came from? Just imaging something like the following:\nSOME_CONFIG = {\n 'some_key': ((..., ...), {...}),\n ...\n}\n\nenviron['wsgiorg.routing_args'] = SOME_CONFIG['some_key']\n\nNow when you update new_named in-place you are actually updating inner dictionary inside SOME_CON...
[ 1 ]
[]
[]
[ "dictionary", "python", "wsgi" ]
stackoverflow_0003651339_dictionary_python_wsgi.txt
Q: difficulty in installing SciPy and Numpy in Ubuntu(9.04)? HI folks. I have difficulty in installing these items in Ubuntu.......plz help me as soon as possible.iam experiencing errors such as no module name found......sometimes certain libraries are not found.......plz folks can all of u state the basic librar...
difficulty in installing SciPy and Numpy in Ubuntu(9.04)?
HI folks. I have difficulty in installing these items in Ubuntu.......plz help me as soon as possible.iam experiencing errors such as no module name found......sometimes certain libraries are not found.......plz folks can all of u state the basic libraries required for installing these items and where to find them
[ "Let's start at the beginning - do you have Python installed and running on Ubuntu? If not, you won't have NumPy or SciPy, either.\nDid you download NumPy and SciPy and unpack them to your hard drive? Do you see directories that contain setup.py somewhere?\nUsually it's python setup.py install in a command shell ...
[ 2, 1, 0 ]
[]
[]
[ "numpy", "python", "scipy", "ubuntu" ]
stackoverflow_0003652866_numpy_python_scipy_ubuntu.txt
Q: Simple Django form / model save question I want to set the BooleanField inuse to True when I save the ModelForm (I'm using a form outside of the admin area) and I'm unsure how to do it. Models: class Location(models.Model): place = models.CharField(max_length=100) inuse = models.BooleanField() class Booki...
Simple Django form / model save question
I want to set the BooleanField inuse to True when I save the ModelForm (I'm using a form outside of the admin area) and I'm unsure how to do it. Models: class Location(models.Model): place = models.CharField(max_length=100) inuse = models.BooleanField() class Booking(models.Model): name = models.CharField(...
[ "class BookingForm(ModelForm):\n\n class Meta:\n model = Booking\n\n def save(self, commit=True):\n booking = super(BookingForm, self).save(commit=False)\n booking.inuse = True\n if commit:\n booking.save()\n\n", "Here is my stab at it:\nclass BookingForm(ModelForm):\n...
[ 3, 2 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0003652585_django_django_forms_django_models_python.txt
Q: Is code interpreted at every call in Web2Py? If so, What is the advantage ? (sure it will avoid restarting webserver). But isn't it a perfomance bottleneck? For production, is it possible to make web2py run directly from bytecode skipping interpreting stage (Caching) (except for the first request) ? A: In web2py...
Is code interpreted at every call in Web2Py?
If so, What is the advantage ? (sure it will avoid restarting webserver). But isn't it a perfomance bottleneck? For production, is it possible to make web2py run directly from bytecode skipping interpreting stage (Caching) (except for the first request) ?
[ "In web2py, by default, all code in models, views and controllers (not web2py code, not code in modules imported by your models, views, controllers) is interpreted at every request. This allows to use a third party web server (for example apache) and still be able to see changes in your code reflected immediately w...
[ 6, 2 ]
[]
[]
[ "bytecode", "caching", "performance", "python", "web2py" ]
stackoverflow_0003649607_bytecode_caching_performance_python_web2py.txt
Q: What's the difference between "browser posting" and "program posting"? I've asked one question about this a month ago, it's here: "post" method to communicate directly with a server. And I still didn't get the reason why sometimes I get 404 error and sometimes everything works fine, I mean I've tried those codes ...
What's the difference between "browser posting" and "program posting"?
I've asked one question about this a month ago, it's here: "post" method to communicate directly with a server. And I still didn't get the reason why sometimes I get 404 error and sometimes everything works fine, I mean I've tried those codes with several different wordpress blogs. Using firefox or IE, you can post th...
[ "You should use somthing like mechanize.\n", "The blog may have some spam protection against this kind of posting. ( Using programmatic post without accessing/reading the page can be easily detected using javascript protection ).\nBut if it's the case, I'm surprised you receive a 404...\nAnyway, if you wanna simu...
[ 0, 0 ]
[]
[]
[ "comments", "post", "python", "wordpress" ]
stackoverflow_0003653086_comments_post_python_wordpress.txt
Q: Subdomains vs folders/directories I'm currently building a web application and I would like my users to have their own URLs to identify them. I could either do this using subdomains or using folders and am wondering what are the advantages and disadvantages of either one. I really like the folder solution because ...
Subdomains vs folders/directories
I'm currently building a web application and I would like my users to have their own URLs to identify them. I could either do this using subdomains or using folders and am wondering what are the advantages and disadvantages of either one. I really like the folder solution because my URL mapping would be fairly easy. I ...
[ "I think directories are the way to go. I believe it would be easier to adapt Django to the directories way much easier than to subdomains. And as one user commented you can avoid restarting your server each time.\nI prefer to keep subdomains reserved for system use. Users should get their own directories instead. ...
[ 1, 0 ]
[]
[]
[ "django", "nginx", "python", "subdomain" ]
stackoverflow_0003653239_django_nginx_python_subdomain.txt
Q: python failed to call flash loaded html page I tried to render html page which contains flash content. But it not responding. Loads endless. Text and image contents are OK. Here is my code. self.response.out.write(template.render('ieerror.html', dict())) html file contains: <head> <meta http-equiv="Content-Type" ...
python failed to call flash loaded html page
I tried to render html page which contains flash content. But it not responding. Loads endless. Text and image contents are OK. Here is my code. self.response.out.write(template.render('ieerror.html', dict())) html file contains: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>flash...
[ "Use http://code.google.com/p/swfobject/ instead\nlike from:\n<script type=\"text/javascript\">\n\nvar flashvars = false;\nvar params = {\n menu: \"false\",\n flashvars: \"name1=hello&name2=world&name3=foobar\"\n};\nvar attributes = {\n id: \"myDynamicContent\",\n name: \"myDynamicContent\"\n};\n\nswfobject.emb...
[ 0 ]
[]
[]
[ "flash", "html", "javascript", "python" ]
stackoverflow_0003651979_flash_html_javascript_python.txt
Q: Cleaning data which is of type URLField I have a simple URLField in my model link = models.URLField(verify_exists = False, max_length = 225) I would like to strip the leading and trailing spaces from the field. I don't think I can do this in "clean_fieldname" or in the "clean" method. Do I need to sub-class the ...
Cleaning data which is of type URLField
I have a simple URLField in my model link = models.URLField(verify_exists = False, max_length = 225) I would like to strip the leading and trailing spaces from the field. I don't think I can do this in "clean_fieldname" or in the "clean" method. Do I need to sub-class the "URLField" and remove the spaces in to_python...
[ "I did a quick experiment and found out that you can indeed use a clean_ method to remove leading/trailing spaces. Something like this:\n# models.py\nclass UrlModel(models.Model):\n link = models.URLField(verify_exists = False, max_length = 225)\n\n def __unicode__(self):\n return self.link\n\n# forms....
[ 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0003653423_django_django_forms_django_models_python.txt
Q: Python: int to binary stream element? If you have a int and you wish to convert it to a single char string you can use the function chr() Is there a way to convert an int to a single char binary stream? e.g: >>> something(97) b'a' What is the something? A: You can do: bytes(chr(97)) A: In Python 3.x: >>> byte...
Python: int to binary stream element?
If you have a int and you wish to convert it to a single char string you can use the function chr() Is there a way to convert an int to a single char binary stream? e.g: >>> something(97) b'a' What is the something?
[ "You can do:\nbytes(chr(97))\n\n", "In Python 3.x:\n>>> bytes([97])\nb'a'\n\n" ]
[ 0, 0 ]
[]
[]
[ "binary", "python" ]
stackoverflow_0003653664_binary_python.txt
Q: criticism this python code (crawler with threadpool) how good this python code ? need criticism) there is a error in this code, some times script do print "ALL WAIT - CAN FINISH!" and freeze (no more actions are happend..) but i can't find reason why this happend? site crawler with threadpool: import sys from urll...
criticism this python code (crawler with threadpool)
how good this python code ? need criticism) there is a error in this code, some times script do print "ALL WAIT - CAN FINISH!" and freeze (no more actions are happend..) but i can't find reason why this happend? site crawler with threadpool: import sys from urllib import urlopen from BeautifulSoup import BeautifulSoup,...
[ "You are sharing state between threads (i.e., in is_all_wait) without synchronization. Plus, the fact that all threads are \"waiting\" is not a reliable indicator that the queue is empty (for instance, they could all be in the process of getting a task). I suspect that, occasionally, threads are exiting before th...
[ 1, 0 ]
[]
[]
[ "multithreading", "pool", "python", "web_crawler" ]
stackoverflow_0003653675_multithreading_pool_python_web_crawler.txt
Q: Simple python Tkinter questions about buttons Can someone provide me with some example code. I am fairly fluent with python but can't figure this out. So i will be generating a list with say "x" elements from other code. I need Tkinter to display a "x" buttons that can be checked on or off. Then once the user has ...
Simple python Tkinter questions about buttons
Can someone provide me with some example code. I am fairly fluent with python but can't figure this out. So i will be generating a list with say "x" elements from other code. I need Tkinter to display a "x" buttons that can be checked on or off. Then once the user has selected whichever ones they want, they will press ...
[ "import Tkinter as tk\n\ndef printVar():\n print 'var is', var.get()\n\nroot = tk.Tk()\nvar = tk.IntVar()\nc = tk.Checkbutton(root, text='Check me', variable=var, command=printVar)\nc.pack()\nroot.mainloop()\n\nTake a look at Tkinter page at the python wiki.\nEdit\nimport Tkinter as tk\n\ndef printOpts():\n f...
[ 2, 0 ]
[]
[]
[ "function", "python", "tkinter" ]
stackoverflow_0003614781_function_python_tkinter.txt
Q: "python manage.py runserver" = cannot execute binary file error (django) new one to me commend I'm running ubuntu 10.04 relatively fresh install on my laptop manually installed django 1.2.1 when I try to run inside of a virtualenv python manage.py **any command** I get the error "bash: /home/alvin/workspace/storm...
"python manage.py runserver" = cannot execute binary file error (django)
new one to me commend I'm running ubuntu 10.04 relatively fresh install on my laptop manually installed django 1.2.1 when I try to run inside of a virtualenv python manage.py **any command** I get the error "bash: /home/alvin/workspace/storm-guard/virtual_damage_restoration/bin/python: cannot execute binary file " I h...
[ "the virtualenv I was attempting to use was copied from another computer\nfor whatever reason when I created a new virtualenv and copied the bin directory over the existing everything started working\n" ]
[ 0 ]
[]
[]
[ "django", "python", "virtualenv" ]
stackoverflow_0003654036_django_python_virtualenv.txt
Q: How do you get the last arrow key pressed using curses? I'm writing a Python snake game using curses, but am having some trouble controlling the snake, my current code for controlling the snake is placed inside the main loop and looks like this: while True: char = screen.getch() if char == 113: exit() # q...
How do you get the last arrow key pressed using curses?
I'm writing a Python snake game using curses, but am having some trouble controlling the snake, my current code for controlling the snake is placed inside the main loop and looks like this: while True: char = screen.getch() if char == 113: exit() # q elif char == curses.KEY_RIGHT: snake.update(RIGHT) e...
[ "Set screen.nodelay(1):\nscreen.nodelay(1)\nwhile True:\n char = screen.getch()\n if char == 113: break # q\n elif char == curses.KEY_RIGHT: snake.update(RIGHT)\n elif char == curses.KEY_LEFT: snake.update(LEFT)\n elif char == curses.KEY_UP: snake.update(UP)\n elif char == curses.KEY_DOWN: snake....
[ 4 ]
[]
[]
[ "curses", "keypress", "python" ]
stackoverflow_0003651709_curses_keypress_python.txt
Q: python mysql configuration problem I'm trying to make django work on snow leopard. So far I've installed mysql 64 bit installed python 2.7 64 bit and installed django 1.2.1. Now I'm trying to install mysql-python-1.2.3; at the beginning I had problems because I hadn't installed the setup tool, having done that whe...
python mysql configuration problem
I'm trying to make django work on snow leopard. So far I've installed mysql 64 bit installed python 2.7 64 bit and installed django 1.2.1. Now I'm trying to install mysql-python-1.2.3; at the beginning I had problems because I hadn't installed the setup tool, having done that when try to install it by executing these c...
[ "You need to use sudo\nsudo setup.py build\nsudo setup.py install\n\nYou might just want to use sqlite.\n", "At the risk of pointing out the obvious, you do not have permission to write to the build directory. Check and change the directory permissions (with the chmod command) or do the setup as an admin user.\n...
[ 2, 0 ]
[]
[]
[ "django", "macos", "mysql", "python" ]
stackoverflow_0003654479_django_macos_mysql_python.txt
Q: Matplotlib: multiple y axes, grid lines applied to both? I've got a Matplotlib graph with two y axes, created like: ax1 = fig.add_subplot(111) ax1.grid(True, color='gray') ax1.plot(xdata, ydata1, 'b', linewidth=0.5) ax2 = ax1.twinx() ax2.plot(xdata, ydata2, 'g', linewidth=0.5) I need grid lines but I want them to...
Matplotlib: multiple y axes, grid lines applied to both?
I've got a Matplotlib graph with two y axes, created like: ax1 = fig.add_subplot(111) ax1.grid(True, color='gray') ax1.plot(xdata, ydata1, 'b', linewidth=0.5) ax2 = ax1.twinx() ax2.plot(xdata, ydata2, 'g', linewidth=0.5) I need grid lines but I want them to apply to both y axes not just the left one. The scales of eac...
[ "EDIT\nConsider this simple example:\nfrom pylab import *\n\n# some random values\nxdata = arange(0.0, 2.0, 0.01)\nydata1 = sin(2*pi*xdata)\nydata2 = 5*cos(2*pi*xdata) + randn(len(xdata))\n\n# number of ticks on the y-axis\nnumSteps = 9;\n\n# plot\nfigure()\n\nsubplot(121)\nplot(xdata, ydata1, 'b')\nyticks( linspac...
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0003654619_matplotlib_python.txt
Q: Why can't I assign to undeclared attributes of an object() instance but I can with custom classes? Basically I want to know why this works: class MyClass: pass myObj = MyClass() myObj.foo = 'a' But this returns an AttributeError: myObj = object() myObj.foo = 'a' How can I tell which classes I can use undefine...
Why can't I assign to undeclared attributes of an object() instance but I can with custom classes?
Basically I want to know why this works: class MyClass: pass myObj = MyClass() myObj.foo = 'a' But this returns an AttributeError: myObj = object() myObj.foo = 'a' How can I tell which classes I can use undefined attributes with and which I can't? Thanks.
[ "You can set attributes on any class with a __dict__, because that is where they are stored. object instances (which are weird) and any class that defines __slots__ do not have one:\n>>> class Foo(object): pass\n...\n>>> foo = Foo()\n>>> hasattr(foo, \"__dict__\")\nTrue\n>>> foo.bar = \"baz\"\n>>>\n>>> class Spam(o...
[ 2 ]
[]
[]
[ "class_structure", "python" ]
stackoverflow_0003654669_class_structure_python.txt
Q: SVN/python library I need to manipulate a subversion client from python. I need to: check the most recent revision to change something under a given path. update a client to a given (head or non head) revision get logs for a given path (revisions that changed it and when). A quick search didn't turn up what I'm ...
SVN/python library
I need to manipulate a subversion client from python. I need to: check the most recent revision to change something under a given path. update a client to a given (head or non head) revision get logs for a given path (revisions that changed it and when). A quick search didn't turn up what I'm looking for and I'd rath...
[ "Check out the pysvn library. Or skim the pysvn Programmer's Guide to see if it meets most of your use cases.\n" ]
[ 6 ]
[]
[]
[ "python", "svn" ]
stackoverflow_0003654812_python_svn.txt
Q: Rounding up with pennies in Python? I am making a change program in python. The user must input a dollar amount and then the program will calculate the change in twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. I was instructed to use the round function for the pennies because If I input an amo...
Rounding up with pennies in Python?
I am making a change program in python. The user must input a dollar amount and then the program will calculate the change in twenties, tens, fives, ones, quarters, dimes, nickels, and pennies. I was instructed to use the round function for the pennies because If I input an amount of $58.79, the program tells me to gi...
[ "Multiply the user's inputed dollar value by 100, convert to int, and work in units of pennies.\nInteger arithmetic is dead simple (and exact). Floating point arithmetic is tricky and forces you to use more brain cells :) . Save brain cells and work entirely in ints. \n", "The problem is that 0.01 cannot be accur...
[ 4, 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003654331_python.txt
Q: How could you swap out a particular database implementation in python? If I have a seperate class for my db calls, and I create another implementation of the db layer but say with a different data store. Is there a way for me to completly swap out the implementation without having to change allot of code? i.e. I a...
How could you swap out a particular database implementation in python?
If I have a seperate class for my db calls, and I create another implementation of the db layer but say with a different data store. Is there a way for me to completly swap out the implementation without having to change allot of code? i.e. I am starting a project, so I can design things properly to achieve this from t...
[ "As long as two modules implement exactly the same interface (classes with the same names, methods, and other attributes, functions with the same names and signatures, ...) you can pick one or the other at the time your application is starting up, for example on the basis of some configuration file, and import the ...
[ 2 ]
[]
[]
[ "ioc_container", "python" ]
stackoverflow_0003654873_ioc_container_python.txt
Q: Django, save data from form without having to manually set each field to save? I can't seem to figure out a good way to do this, I have a bunch of form input fields and rather than having to do like below where I have to type out each fieldname = "" and such, is there a way to code this so it would automatically s...
Django, save data from form without having to manually set each field to save?
I can't seem to figure out a good way to do this, I have a bunch of form input fields and rather than having to do like below where I have to type out each fieldname = "" and such, is there a way to code this so it would automatically save each field from within the form? b = Modelname(fieldname=request.POST['fieldname...
[ "Sure, request.POST.items() and request.POST.iteritems() work just like the methods of the same name in a dict, returning resp. a list and an iterator of all (name, value) pairs (2-items tuple) in that dict-like object. If there are multiple values for a name, that only gives you the last one; if you want all of t...
[ 3 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0003655018_django_forms_python.txt
Q: Python routes - I'm trying to set the format extension but it's failing I'm trying to setup my Routes and enable an optional 'format' extension to specify whether the page should load as a standard HTML page or within a lightbox. Following this http://routes.groovie.org/setting_up.html#format-extensions, I've come...
Python routes - I'm trying to set the format extension but it's failing
I'm trying to setup my Routes and enable an optional 'format' extension to specify whether the page should load as a standard HTML page or within a lightbox. Following this http://routes.groovie.org/setting_up.html#format-extensions, I've come up with: map.connect('/info/test{.format:lightbox}', controller='front', act...
[ "Generally:\nhttp://pylonsbook.com/en/1.1/urls-routing-and-dispatch.html#pylons-routing-in-detail\n\nRoutes then searches each of the routes in the route map from top to bottom until it finds a route that matches the URL. Because matching is done from top to bottom, you are always advised to put your custom routes ...
[ 1, 0 ]
[]
[]
[ "pylons", "python", "routes" ]
stackoverflow_0003655142_pylons_python_routes.txt
Q: Python: Shorten ugly code? I have a ridiculous code segment in one of my programs right now: str(len(str(len(var_text)**255))) Is there an easy way to shorten that? 'Cause, frankly, that's ridiculous. A option to convert a number >500 digits to scientific notation would also be helpful (that's what I'm trying to ...
Python: Shorten ugly code?
I have a ridiculous code segment in one of my programs right now: str(len(str(len(var_text)**255))) Is there an easy way to shorten that? 'Cause, frankly, that's ridiculous. A option to convert a number >500 digits to scientific notation would also be helpful (that's what I'm trying to do) Full code: print("Useless co...
[ "TL;DR: y = 2.408 * len(var_text)\nLets assume that your passkey is a string of characters with 256 characters available (0-255). Then just as a 16bit number holds 65536 numbers (2**16) the permutations of a string of equal length would be\nn_perms = 256**len(passkey)\n\nIf you want the number of (decimal) digits i...
[ 6, 0, 0, 0 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0003654706_coding_style_python.txt
Q: Python: Listen on two ports import socket backlog = 1 #Number of queues sk_1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk_2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) local = {"port":1433} internet = {"port":9999} sk_1.bind (('', internet["port"])) sk_1.listen(backlog) sk_2.bind (('', local[...
Python: Listen on two ports
import socket backlog = 1 #Number of queues sk_1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk_2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) local = {"port":1433} internet = {"port":9999} sk_1.bind (('', internet["port"])) sk_1.listen(backlog) sk_2.bind (('', local["port"])) sk_2.listen(backlog) B...
[ "The fancy-pants way to do this if you want to use Python std-lib would be to use SocketServer with the ThreadingMixin -- although the 'select' suggestion is probably the more efficient. \nEven though we only define one ThreadedTCPRequestHandler you can easily repurpose it such that each listener has it's own uniqu...
[ 11, 4 ]
[]
[]
[ "listen", "python", "sockets" ]
stackoverflow_0003655053_listen_python_sockets.txt
Q: object factory that generates an object or list of objects I have the following code: def f(cls, value): # cls is a class # value is a string value if cls == str: pass # value is already the right type elif cls == int: value = int(value) elif cls == C1: value = C1(value) elif cls == C2: ...
object factory that generates an object or list of objects
I have the following code: def f(cls, value): # cls is a class # value is a string value if cls == str: pass # value is already the right type elif cls == int: value = int(value) elif cls == C1: value = C1(value) elif cls == C2: value = C2(value) elif cls == C3 # in this case, we conve...
[ "If most cases are best handled by calling cls, and a few are best handled otherwise, simplest is to single out the latter:\nthemap = {C3: C3.parse}\nfor C in (str, C1, C2):\n themap[C] = C\n\ndef f(cls, value):\n wot = themap.get(cls)\n if wot is None:\n raise UnknownClass(repr(cls))\n return wo...
[ 2, 0 ]
[]
[]
[ "factory", "object", "python" ]
stackoverflow_0003655544_factory_object_python.txt
Q: How do I print a list of strings, when I can't know the char encoding in advance? I am retrieving a list of names from a webservice using a client I've written in Python. Upon retrieving the list, I encode each name to unicode and then print each of them to stdout. When I get to the name "Ólafur Jóhann Ólafsson", ...
How do I print a list of strings, when I can't know the char encoding in advance?
I am retrieving a list of names from a webservice using a client I've written in Python. Upon retrieving the list, I encode each name to unicode and then print each of them to stdout. When I get to the name "Ólafur Jóhann Ólafsson", I get the following error: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in ...
[ "The UnicodeDammit module from BeautifulSoup can automagically detect the encoding.\nfrom BeautifulSoup import UnicodeDammit\n\nu = UnicodeDammit(\"Ólafur Jóhann Ólafsson\")\n\nprint u.unicode\nprint u.originalEncoding\n\n", "This page may help you http://wiki.python.org/moin/PrintFails \nThe problem, I guess, is...
[ 1, 1, 1 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0003652774_encoding_python.txt
Q: SWIG - running python code upon import I have a C++ module that I'm wrapping with SWIG that uses dynamic linking. Because of the way that python deals with scope of imported functions I've had to run the command dl.open(library, dl.RLTD_NOW, dl.RTLD_GLOBAL) directly after import. This is to make sure that the C++ ...
SWIG - running python code upon import
I have a C++ module that I'm wrapping with SWIG that uses dynamic linking. Because of the way that python deals with scope of imported functions I've had to run the command dl.open(library, dl.RLTD_NOW, dl.RTLD_GLOBAL) directly after import. This is to make sure that the C++ libraries functions are available to the oth...
[ "Try wrapping your module. Build your C++ code into a \"private\" module, and call it module_ or something, to make it clear that you shouldn't import it. Then, in module.py (the wrapper module):\nimport dl\nfrom module_ import *\ndl.open(library, dl.RTLD_NOW, dl.RTLD_GLOBAL)\n\n" ]
[ 2 ]
[]
[]
[ "python", "swig" ]
stackoverflow_0003650059_python_swig.txt
Q: Write a script to do content filtering with postfix How can i write in python or ruby a script to do content filtering in postfix via smtp or uucp (not pipe)? There is some examples? A: If you don't need the whole mail body to process it, you could simply write a policy server for Postfix, see Access policy dele...
Write a script to do content filtering with postfix
How can i write in python or ruby a script to do content filtering in postfix via smtp or uucp (not pipe)? There is some examples?
[ "If you don't need the whole mail body to process it, you could simply write a policy server for Postfix, see Access policy delegation.\nIf you need to process the whole mail, you have several possibilities, see Postfix Content Inspection.\nYou could either implement a content filter (see FILTER_README) which gets ...
[ 4 ]
[]
[]
[ "postfix_mta", "python", "ruby" ]
stackoverflow_0003652161_postfix_mta_python_ruby.txt
Q: Binary Search Trees This is some code found on wikipedia regarding BST : # 'node' refers to the parent-node in this case def search_binary_tree(node, key): if node is None: return None # key not found if key < node.key: return search_binary_tree(node.leftChild, key) elif key ...
Binary Search Trees
This is some code found on wikipedia regarding BST : # 'node' refers to the parent-node in this case def search_binary_tree(node, key): if node is None: return None # key not found if key < node.key: return search_binary_tree(node.leftChild, key) elif key > node.key: retu...
[ "It's just because your tree is not a binary search tree: it is not ordered correctly. The BST is build as described in the algorithm actually. For instance in your tree: the node '9' is not at the right position because as 9 < 10 it should be under the left branch of your root node '10'. Same for '14' and '11' whi...
[ 10, 3, 3, 1, 1 ]
[]
[]
[ "algorithm", "binary_search_tree", "binary_tree", "python" ]
stackoverflow_0003656008_algorithm_binary_search_tree_binary_tree_python.txt
Q: manage.py syncdb error while Django model using non-ascii verbose_name I am pretty new to Django. I want the name of my models to be displayed in Chinese, so i used verbose_name in my meta class of my model, codes below: #this models.py file is encoded in unicode class TS_zone(models.Model): index = models.In...
manage.py syncdb error while Django model using non-ascii verbose_name
I am pretty new to Django. I want the name of my models to be displayed in Chinese, so i used verbose_name in my meta class of my model, codes below: #this models.py file is encoded in unicode class TS_zone(models.Model): index = models.IntegerField() zone_name = models.CharField(max_length=50); zone_icon ...
[ "You have to specify an encoding. Add the following line as the first line of your models.py file.\n# encoding: utf-8\n\nUpdate\nThe OP has edited his question to say that the \"models.py is encoded in Unicode\". Then the error is strange. It works for me using Django 1.2.1, Python 2.6.2 on Ubuntu Jaunty. \nUpdate ...
[ 5 ]
[]
[]
[ "django", "manage.py", "python", "syncdb" ]
stackoverflow_0003656119_django_manage.py_python_syncdb.txt
Q: Mac OS X: Trouble with Local Django + PyDev install working with remote MySQL I've got PyDev installed in Eclipse. I'm trying to play with Django. I'm got a remote MySQL database set up. I would really like to not install MySQL on my MacBook. Trying to set up the MySQL plugin for python, I get (djangotest)jeebus:...
Mac OS X: Trouble with Local Django + PyDev install working with remote MySQL
I've got PyDev installed in Eclipse. I'm trying to play with Django. I'm got a remote MySQL database set up. I would really like to not install MySQL on my MacBook. Trying to set up the MySQL plugin for python, I get (djangotest)jeebus:MySQL-python-1.2.3 blah$ python setup.py clean sh: mysql_config: command not found ...
[ "In a word, no. You need the client side libraries of MySQL but you don't need the server components. Most package managers provide each as separate packages.\nMySQL-python, AKA MySQLdb, is not a client module per se. It is a wrapper or interface between Python programs and the standard MySQL client libraries. M...
[ 1, 0, 0 ]
[]
[]
[ "django", "mysql", "pydev", "python" ]
stackoverflow_0003654350_django_mysql_pydev_python.txt
Q: Django / Python, using iteritems() to update database gives strange error: "dictionary update sequence element #0 has length 4; 2 is required" I'm trying to do a Django database save from a form where I don't have to manually specify the fieldnames (as I do in the 2nd code block), the way I am trying to do this is...
Django / Python, using iteritems() to update database gives strange error: "dictionary update sequence element #0 has length 4; 2 is required"
I'm trying to do a Django database save from a form where I don't have to manually specify the fieldnames (as I do in the 2nd code block), the way I am trying to do this is as below (1st code block) as I got the tip from another S.O. post. However, when I try this I get the error "dictionary update sequence element #0 ...
[ "Not sure what you are trying to do, but maybe you want something like this\nb = Twitter(**{name: value})\n\nBut to get the equivalent to Twitter(account_username='vvvvvv') you would need something like this\nTwitter(**{testdict['name'], testdict['value']})\n\nwhere testdict would only contain a single entity to se...
[ 1, 0, 0 ]
[]
[]
[ "dictionary", "django", "loops", "python" ]
stackoverflow_0003655700_dictionary_django_loops_python.txt
Q: Django + IIS +? I need to run a django app on windows under either IIS6 or IIS7 (yes, I don't know the exact requirements right now). What I did: I've tried to set up a working environment on my windows 7 (so its IIS7 for now) machine. I've followed the instructions at django trac using PyISAPIe. What came out of ...
Django + IIS +?
I need to run a django app on windows under either IIS6 or IIS7 (yes, I don't know the exact requirements right now). What I did: I've tried to set up a working environment on my windows 7 (so its IIS7 for now) machine. I've followed the instructions at django trac using PyISAPIe. What came out of it: Apparently, eithe...
[ "This is a cut and paste from my response on the mailing list. I suppose either here or there would be fine for further questions.\nhttp://groups.google.com/group/pyisapie/browse_thread/thread/af7dac9398336e67?hl=en_US\n\nThe module isn't supported at all and the Django folks didn't get around to including it in th...
[ 2 ]
[]
[]
[ "django", "iis_6", "iis_7", "python", "windows" ]
stackoverflow_0003651648_django_iis_6_iis_7_python_windows.txt
Q: reading .bash_history file through python script I want to write a python script which reads the '.bash_history' file and prints the statistics. Also, I would like to print the command which was used the most. I was able to read the bash history through the terminal but I'm not able to do it through python program...
reading .bash_history file through python script
I want to write a python script which reads the '.bash_history' file and prints the statistics. Also, I would like to print the command which was used the most. I was able to read the bash history through the terminal but I'm not able to do it through python programming. Can someone please help me with how to start wit...
[ "http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files\n", "Something beginning with...\n#!/usr/bin/env python\n\nimport os\n\nhomedir = os.path.expanduser('~')\nbash_history = open(homedir+\"/.bash_history\", 'r')\n\nNow we have the file open... what operations do you want to do now?\nPrint ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003656500_python.txt
Q: How to reset global variable in python? SOME_VARIABLE = [] def some_fun: append in SOME_VARIABLE s = [] s = SOME_VARIABLE SOME_VARIABLE = [] // Not setting to empty list. return s How to reset SOME_VARIABLE to empty. A: If you read a variable, Python looks for it in the entire scope chain....
How to reset global variable in python?
SOME_VARIABLE = [] def some_fun: append in SOME_VARIABLE s = [] s = SOME_VARIABLE SOME_VARIABLE = [] // Not setting to empty list. return s How to reset SOME_VARIABLE to empty.
[ "If you read a variable, Python looks for it in the entire scope chain. This mean that:\nGLOB_VAR = \"Some string\"\n\ndef some_fun():\n print GLOB_VAR\n\nwill print Some string\nNow, if you write to a variable, Python looks for it in the local scope, and if it cannot find a variable with the name you gave at th...
[ 11, 8, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003657163_django_python.txt
Q: python - edit a text file I am using python and i want to delete some characters from the end of a text file. The file is big a and i dont want to read all of it and duplicate the interesting part. My best guess is that i need to change the file size.... can anyone help me please thanks A: I guess that you need ...
python - edit a text file
I am using python and i want to delete some characters from the end of a text file. The file is big a and i dont want to read all of it and duplicate the interesting part. My best guess is that i need to change the file size.... can anyone help me please thanks
[ "I guess that you need to open the file, seek to the end, delete characters and save it.\nseek ( http://docs.python.org/library/stdtypes.html#file.seek ) accepts negative values (e.g. f.seek(-3, os.SEEK_END) sets the position to the third to last), so that you can easily go to the end of your file.\nhttp://docs.pyt...
[ 2 ]
[]
[]
[ "python", "text", "text_files" ]
stackoverflow_0003657109_python_text_text_files.txt
Q: Python: Reading Excel 2007 files under Linux environment I want to read excel 2007 files via python on my Ubuntu server. I have already checked http://www.python-excel.org/ xlwt and xlrd but it seems like none of them can read excel 2007 files. What would be your recommendation? Regards A: Try pyXLSX. There is a...
Python: Reading Excel 2007 files under Linux environment
I want to read excel 2007 files via python on my Ubuntu server. I have already checked http://www.python-excel.org/ xlwt and xlrd but it seems like none of them can read excel 2007 files. What would be your recommendation? Regards
[ "Try pyXLSX. There is also openpyxl which can also read / write .xlsx files.\n" ]
[ 3 ]
[]
[]
[ "excel", "excel_2007", "openpyxl", "python" ]
stackoverflow_0003656911_excel_excel_2007_openpyxl_python.txt
Q: Best way to know that my Python Code base is using PyXML or not? I have a python code base and want to know whether pyxml is really used in the code any where. The python version i have is 2.6. pyxml's last binary distribution ended with 2.4 python version. Any clues or ideas to judge the code whether it is free o...
Best way to know that my Python Code base is using PyXML or not?
I have a python code base and want to know whether pyxml is really used in the code any where. The python version i have is 2.6. pyxml's last binary distribution ended with 2.4 python version. Any clues or ideas to judge the code whether it is free of pyxml 0.8.4 on python 2.6 ? Thanks in Advance.
[ "When you run \npython -v script.py\n\nPython prints all the modules imported to stderr. You can then inspect that output for the string \"import pyxml\":\npython -v script.py 2>&1 | grep \"import pyxml\"\n\nThis works even if script.py imported pyxml in an unconventional way, such as __import__('pyxml').\nIt even ...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003657165_python.txt
Q: Django / Python, Make database save function re-usable (so that it takes modelname and appname from strings), using contenttypes or some other method? I want to make some functions that are re-usable by any model so that I can specify the appname and model in string format and then use this to import that model an...
Django / Python, Make database save function re-usable (so that it takes modelname and appname from strings), using contenttypes or some other method?
I want to make some functions that are re-usable by any model so that I can specify the appname and model in string format and then use this to import that model and make calls to it such as creating database fields, updating, deleting, etc... I had thought I could do this using contenttypes in Django but am trying thi...
[ "The following code will work:\ninstancemodelname = ContentType.objects.get(app_label=\"myappname\", model=\"mymodelname\")\nb = instancemodelname.model_class()(account_username='testtestest')\nb.save()\n\nThat said I am not entirely convinced that contenttypes is the best way to achieve what you want. \n", "Don'...
[ 2, 1 ]
[]
[]
[ "code_reuse", "content_type", "django", "python" ]
stackoverflow_0003657076_code_reuse_content_type_django_python.txt
Q: inverted comma and string in python I'm kinda' new to python, but I have already written many programs including some like download-managers, games and text-editors which require a lot of string manipulation. For representing a string literal I use either single or double inverted commas.. whichever comes to my mi...
inverted comma and string in python
I'm kinda' new to python, but I have already written many programs including some like download-managers, games and text-editors which require a lot of string manipulation. For representing a string literal I use either single or double inverted commas.. whichever comes to my mind first at that time. Although I haven't...
[ "There is no difference between \"string\" and 'string' in Python, so, as you suggest, it's just for usability.\n>>> 'string' == \"string\"\nTrue\n\nYou can also use triple quotes for multiline strings:\n>>> mystring = \"\"\"Hello\n... World!\"\"\"\n>>> mystring\n'Hello\\nWorld!'\n\nAnother trick is that adjacent s...
[ 5, 4, 1 ]
[]
[]
[ "literals", "python", "string" ]
stackoverflow_0003657792_literals_python_string.txt
Q: Does "Find-Replace whole word only" exist in python? Does "Find-Replace whole word only" exist in python? e.g. "old string oldstring boldstring bold" if i want to replace 'old' with 'new', new string should look like, "new string oldstring boldstring bold" can somebody help me? A: >>> import re >>> s = "old stri...
Does "Find-Replace whole word only" exist in python?
Does "Find-Replace whole word only" exist in python? e.g. "old string oldstring boldstring bold" if i want to replace 'old' with 'new', new string should look like, "new string oldstring boldstring bold" can somebody help me?
[ ">>> import re\n>>> s = \"old string oldstring boldstring bold\"\n>>> re.sub(r'\\bold\\b', 'new', s)\n'new string oldstring boldstring bold'\n\nThis is done by using word boundaries. Needless to say, this regex is not Python-specific and is implemented in most regex engines.\n", "you need the following regex:\n\\...
[ 44, 5 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003658215_python_regex.txt
Q: Automation of Open Zoom How would I automate the process of deploying a gigantic jpeg on a web server and then generate the necessary files to load the image up on the frontend site in OpenZoom? I'm working in php but any shell/bash/python scripts are welcome A: http://github.com/stinie/deepzoom.php/blob/master/...
Automation of Open Zoom
How would I automate the process of deploying a gigantic jpeg on a web server and then generate the necessary files to load the image up on the frontend site in OpenZoom? I'm working in php but any shell/bash/python scripts are welcome
[ "http://github.com/stinie/deepzoom.php/blob/master/php5.2/tests/index.php\nUsing this library one can generate and display Deep Zoom Images using purely php on the fly =]\n" ]
[ 0 ]
[]
[]
[ "bash", "deepzoom", "python" ]
stackoverflow_0003658023_bash_deepzoom_python.txt
Q: How Do You Predict A Non-Linear Script's Run Time? I wrote this simple code in python to calculate a given number of primes. The question I want to ask is whether or not it's possible for me to write a script that calculates how long it will take, in terms of processor cycles, to execute this? If yes then how? pri...
How Do You Predict A Non-Linear Script's Run Time?
I wrote this simple code in python to calculate a given number of primes. The question I want to ask is whether or not it's possible for me to write a script that calculates how long it will take, in terms of processor cycles, to execute this? If yes then how? primes = [2] pstep = 3 count = 1 def ifprime (a): """ Che...
[ "I think you would have to use an approximation of the distribution of primes, a la PNT which (I think) states that between 1 and x you'll have approximately x/ln(x) primes (ln being natural log). So given rough estimates of the time taken for a single iteration, you should be able to create an estimate.\nYou have ...
[ 2, 2, 0, 0, 0 ]
[]
[]
[ "math", "python", "recursion" ]
stackoverflow_0003657495_math_python_recursion.txt
Q: Django model per table vs model per select I am working with Django for a while and now that my "tree" and whole DB is filled with data (note: existing database), I was wondering if the "one model per table" is really better at this point than "one model per select". I have got one table - objtree. This is the pl...
Django model per table vs model per select
I am working with Django for a while and now that my "tree" and whole DB is filled with data (note: existing database), I was wondering if the "one model per table" is really better at this point than "one model per select". I have got one table - objtree. This is the place where I have all nodes (brands, categories, ...
[ "\nI was wondering if the \"one model per table\" is really better at this point than \"one model per select\".\n\nWhat is \"model per select\"? It sounds like your model is wrong.\n\nThe problem is that I use this model for almost everything, BUT the foreign keys are used rarely, not to mention the third one that ...
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003658944_django_django_models_python.txt
Q: Adding objects to queue without interruption I would like to put two objects into a queue, but I've got to be sure the objects are in both queues at the same time, therefore it should not be interrupted in between - something like an atomic block. Does some one have a solution? Many thanks... queue_01.put(car) que...
Adding objects to queue without interruption
I would like to put two objects into a queue, but I've got to be sure the objects are in both queues at the same time, therefore it should not be interrupted in between - something like an atomic block. Does some one have a solution? Many thanks... queue_01.put(car) queue_02.put(bike)
[ "You could use a Condition object. You can tell the threads to wait with cond.wait(), and signal when the queues are ready with cond.notify_all(). See, for example, Doug Hellman's wonderful Python Module of the Week blog. His code uses multiprocessing; here I've adapted it for threading:\nimport threading\nimport Q...
[ 1, 0 ]
[]
[]
[ "atomic", "locking", "python", "queue" ]
stackoverflow_0003658511_atomic_locking_python_queue.txt
Q: Numpy matrix operations I want to compute the following values for all i and j: M_ki = Sum[A_ij - A_ik - A_kj + A_kk, 1 <= j <= n] How can I do it using Numpy (Python) without an explicit loop? Thanks! A: Here is a general strategy for solving this kind of problem. First, write a small script, with the loop wri...
Numpy matrix operations
I want to compute the following values for all i and j: M_ki = Sum[A_ij - A_ik - A_kj + A_kk, 1 <= j <= n] How can I do it using Numpy (Python) without an explicit loop? Thanks!
[ "Here is a general strategy for solving this kind of problem.\nFirst, write a small script, with the loop written explicitly in two different functions, and a test at the end making sure that the two functions are exactly the same:\nimport numpy as np\nfrom numpy import newaxis\n\ndef explicit(a):\n n = a.shape[...
[ 14 ]
[]
[]
[ "matrix", "numpy", "python" ]
stackoverflow_0003657884_matrix_numpy_python.txt
Q: How to have gantt chart using python or pyqt I'm working on a (asset management) system to handle assets , resources and progress of tasks I want to have a gantt chart in my system I'm using python 2.6 and pyqt . Is there any (already made charts python library)? that can work well with pyqt. or should i make a c...
How to have gantt chart using python or pyqt
I'm working on a (asset management) system to handle assets , resources and progress of tasks I want to have a gantt chart in my system I'm using python 2.6 and pyqt . Is there any (already made charts python library)? that can work well with pyqt. or should i make a custom widgets for this ? Please advice.
[ "These are not pyQt related but you can have a look at http://pypi.python.org/pypi/GanttPV/0.1\nor maybe http://pypi.python.org/pypi/xm.charting/0.3\nI have not used any of them though so I can not give you more specific info.\n", "Check out the faces project. It uses little Python scripts to define tasks and de...
[ 1, 0 ]
[]
[]
[ "gantt_chart", "pyqt", "python", "qt" ]
stackoverflow_0003657504_gantt_chart_pyqt_python_qt.txt
Q: How to test a web API throttle limit in Python I would like to test a web API throttle limit of a given site using Python. This API throttle limit allows X requests MAX over Y seconds per IP. I would like to be able to test the reliability of this throttle limit, in particular on border cases (X-1 requests, X+1 re...
How to test a web API throttle limit in Python
I would like to test a web API throttle limit of a given site using Python. This API throttle limit allows X requests MAX over Y seconds per IP. I would like to be able to test the reliability of this throttle limit, in particular on border cases (X-1 requests, X+1 requests) Could you suggest a good way to do it?
[ "I would write a script to do the following:\n\nMake a burst of X requests, timing each request (I would use time.time()). There should be no evidence of throttling in the timing results. You may need to parallelize to hit the limit if latency is significant. \nMake another request and time it. It should be throttl...
[ 3 ]
[]
[]
[ "api", "python", "throttling" ]
stackoverflow_0003657894_api_python_throttling.txt
Q: Python Plugin-System - HOWTO I'm writing a Python application which stores some data. For storing the data i've wrote a Connection class with abstract methods (using Python's abc module). This class is the super class all storage back-ends derive from. Each storage back-end has only one purpose, e.g. storing the d...
Python Plugin-System - HOWTO
I'm writing a Python application which stores some data. For storing the data i've wrote a Connection class with abstract methods (using Python's abc module). This class is the super class all storage back-ends derive from. Each storage back-end has only one purpose, e.g. storing the data in plain text files or in a XM...
[ "Do not walk the filesystem (!) and scan the Python source code of the backends! That's an ugly hack at the best of times, and even worse here because you don't need anything like it at all! Registering all the classes on import is perfectly OK. \n\nStore the backends in a class attribute instead of an instance att...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003659773_python.txt
Q: How to By pass WP super cache using python? I'm trying to collecting data from a frequently updating blog, so I simply use a while loop which includes urllib2.urlopen("http:\example.com") to refresh the page every 5 minutes to collect the data I wanted. But I notice that I'm not getting the most recent content by...
How to By pass WP super cache using python?
I'm trying to collecting data from a frequently updating blog, so I simply use a while loop which includes urllib2.urlopen("http:\example.com") to refresh the page every 5 minutes to collect the data I wanted. But I notice that I'm not getting the most recent content by doing this, it's different from what I see via b...
[ "Have you tried changing the URL with some harmless data? Something like this:\nimport time\nurllib2.urlopen(\"http:\\example.com?time=%s\" % int(time.time()))\n\nIt will actually call http:\\example.com?time=1283872559. Most caching systems will bypass the cache if there's a querystring or it's something that isn'...
[ 2 ]
[]
[]
[ "php", "python", "urllib2", "urlopen", "wordpress" ]
stackoverflow_0003659429_php_python_urllib2_urlopen_wordpress.txt
Q: Django Celery AbortableTask usage I'm trying to use the AbortableTask feature of Celery but the documentation example doesn't seem to be working for me. The example given is: from celery.contrib.abortable import AbortableTask def MyLongRunningTask(AbortableTask): def run(self, **kwargs): logger = se...
Django Celery AbortableTask usage
I'm trying to use the AbortableTask feature of Celery but the documentation example doesn't seem to be working for me. The example given is: from celery.contrib.abortable import AbortableTask def MyLongRunningTask(AbortableTask): def run(self, **kwargs): logger = self.get_logger(**kwargs) results...
[ "Just a guess but I think it should be \nclass MyLongRunningTask(AbortableTask)\n\nand not\ndef MyLongRunningTask(AbortableTask)\n\n" ]
[ 2 ]
[]
[]
[ "celery", "celery_task", "django", "python" ]
stackoverflow_0003659561_celery_celery_task_django_python.txt
Q: how to shift a datetime object by 12 hours in python Datetime objects hurt my head for some reason. I am writing to figure out how to shift a date time object by 12 hours. I also need to know how to figure out if two date time object's differ by say 1 minute or more. A: The datetime library has a timedelta objec...
how to shift a datetime object by 12 hours in python
Datetime objects hurt my head for some reason. I am writing to figure out how to shift a date time object by 12 hours. I also need to know how to figure out if two date time object's differ by say 1 minute or more.
[ "The datetime library has a timedelta object specifically for this kind of thing:\nimport datetime\n\nmydatetime = datetime.now() # or whatever value you want\ntwelvelater = mydatetime + datetime.timedelta(hours=12)\ntwelveearlier = mydatetime - datetime.timedelta(hours=12)\n\ndifference = abs(some_datetime_A - som...
[ 32, 5 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0003660210_datetime_python.txt
Q: When a Web framework isn't convenient to use? When a Web framework ( like django, ruby on rails, zend, etc ) isn't convenient to use ? And so... When a Web programming language ( like PHP, Asp, Python, etc ) is better than a Web Framework ? A: You don't need frameworks when you don't plan to use their features. ...
When a Web framework isn't convenient to use?
When a Web framework ( like django, ruby on rails, zend, etc ) isn't convenient to use ? And so... When a Web programming language ( like PHP, Asp, Python, etc ) is better than a Web Framework ?
[ "You don't need frameworks when you don't plan to use their features.\n", "I like the wikipedia description:\n\nThe framework aims to alleviate the\n overhead associated with common\n activities performed in Web\n development. For example, many\n frameworks provide libraries for\n database access, templating...
[ 3, 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "django", "php", "python", "ruby_on_rails", "zend_framework" ]
stackoverflow_0003659687_django_php_python_ruby_on_rails_zend_framework.txt
Q: Query CPU ID from Python? How I can find processor id with py2.6, windows OS? I know that there is pycpuid, but I can't compile this under 2.6. A: Have you tried wmi? (It may require elevated privilege level) Here's a solution (it works for Python 2 and 3): >>> import wmi >>> c = wmi.WMI() >>> for s in c.Win32_P...
Query CPU ID from Python?
How I can find processor id with py2.6, windows OS? I know that there is pycpuid, but I can't compile this under 2.6.
[ "Have you tried wmi? (It may require elevated privilege level)\nHere's a solution (it works for Python 2 and 3):\n>>> import wmi\n>>> c = wmi.WMI()\n>>> for s in c.Win32_Processor():\n print (s)\n\n\n\ninstance of Win32_Processor\n{\n AddressWidth = 64;\n Architecture = 9;\n Availability = 3;\n Capti...
[ 6, 3, 1, 0 ]
[]
[]
[ "cpu", "python", "windows" ]
stackoverflow_0003056674_cpu_python_windows.txt
Q: python error checking I am using code below. How Do add error checking. If anything is error, replace continue reading Ex: if volume is N\a or missing , replace with 'a value.' Don't skip line, don't stop. reader = csv.reader(idata.split("\r\n")) stocks = [] for line in reader: if line == '': continu...
python error checking
I am using code below. How Do add error checking. If anything is error, replace continue reading Ex: if volume is N\a or missing , replace with 'a value.' Don't skip line, don't stop. reader = csv.reader(idata.split("\r\n")) stocks = [] for line in reader: if line == '': continue stock, price, volume...
[ "Do something like the following:\ndef isRecordValid(stock,price,volume,stime):\n #do input validation here, return True if record is fine, False if not. Optionally raise an Error here and catch it in your loop\n return True\n\nreader = csv.reader(idata.split(\"\\r\\n\"))\n\nstocks = []\nfor line in reader:\...
[ 2 ]
[]
[]
[ "error_handling", "python" ]
stackoverflow_0003660370_error_handling_python.txt
Q: Top 3 questions to test someones Python level, what would they be? If you had to judge someones level of Python understand in just 3 questions, what would you ask? A: This is pretty much the same as for any language. What projects have you done with Python? What is your favorite Python reference? Have you worke...
Top 3 questions to test someones Python level, what would they be?
If you had to judge someones level of Python understand in just 3 questions, what would you ask?
[ "This is pretty much the same as for any language.\n\nWhat projects have you done with Python?\nWhat is your favorite Python reference?\nHave you worked with other people on code written in Python?\n\nThat's how I would judge. If I wanted to test, it would depend on whether I were looking for someone to write in 2....
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003660503_python.txt
Q: Building a Python extension with bjam (Boost.Build) on Mac OS X So far as I can tell what happens is this: In python.jam, it works out which version of Python I am using and which library directories to look in; It adds -Wl-R arguments to the g++ command line to include those directories; The ld command complains...
Building a Python extension with bjam (Boost.Build) on Mac OS X
So far as I can tell what happens is this: In python.jam, it works out which version of Python I am using and which library directories to look in; It adds -Wl-R arguments to the g++ command line to include those directories; The ld command complains that it does not have a -R option. So either (a) I have a defective...
[ "I can't tell which version of Boost you have.. BUt the most likely reason for the problem is that you are using the generic \"gcc\" toolset to build. There's a special toolset for building with the GCC variant that Apple uses in Xcode. Try building with bjam toolset=darwin instead.\n" ]
[ 3 ]
[]
[]
[ "boost", "macos", "python" ]
stackoverflow_0003610286_boost_macos_python.txt
Q: Figure out nested submenu selections in wxPython? Let's say in a larger submenu structure with a depth of 3 levels, I have selected 'car' in the first level, 'type' in the second, and 'suv' in the third and last level. Is there any way I can figure all these three selections in my def OnPopupItemSelected(self, eve...
Figure out nested submenu selections in wxPython?
Let's say in a larger submenu structure with a depth of 3 levels, I have selected 'car' in the first level, 'type' in the second, and 'suv' in the third and last level. Is there any way I can figure all these three selections in my def OnPopupItemSelected(self, event) method? I hope I have made myself clear enough, if ...
[ "It looks like in the wxPython demo that they \"code\" the ids in a child parent fashion:\n# top level menu\nmenu1 = wx.Menu()\nmenu1.Append(11,\"11\")\nmenu1.Append(12, \"12\") \n\n# sub menu 1\nmenu2 = wx.Menu()\nmenu2.Append(131, \"131\")\nmenu2.Append(132, \"132\")\nmenu1.AppendMenu(13,\"13\",menu2)\n\n#...
[ 3 ]
[]
[]
[ "nested", "python", "submenu" ]
stackoverflow_0003658747_nested_python_submenu.txt
Q: returning xml documents from cherrypy I am new to web programming and am trying to return an xml document from the cherrypy web server. But, what I see in the browser is a string value stripped off all the xml tags. i.e. <Foo> <Val1> </Foo> <Bar> <Val2> </Bar> shows up in the browser as Val1 Val2 I am sure ...
returning xml documents from cherrypy
I am new to web programming and am trying to return an xml document from the cherrypy web server. But, what I see in the browser is a string value stripped off all the xml tags. i.e. <Foo> <Val1> </Foo> <Bar> <Val2> </Bar> shows up in the browser as Val1 Val2 I am sure that I am generating the document correctly...
[ "WebKit-based browsers like Safari and Chrome hide XML markup from the rendered text. You should ask the browser to show you the source (Tools->View Source(CTRL+U) in Chrome). Firefox shows XML markup by default.\nAnyhow, if you're doing webservice development I'd recommend you to use curl. It will save you a lot o...
[ 1 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0003660521_cherrypy_python.txt
Q: apropos / find context related information On unix-like systems we have apropos to search the manual page names and descriptions so we can find context related information. For example apropos delete would give me a list of all kinds of software related to "deleting" stuff. Does anybody know if that already exist ...
apropos / find context related information
On unix-like systems we have apropos to search the manual page names and descriptions so we can find context related information. For example apropos delete would give me a list of all kinds of software related to "deleting" stuff. Does anybody know if that already exist for Python or do I have to code it? What I basic...
[ "\n\nI am not talking about doing a search on PyPI!\n\n\nwhy not ? that should be the first thing you do if you want to look for Python modules. Otherwise simple search on google/yahoo may yield some results, such as this\n", "$ apt-cache search <keyword> | grep python\n\n" ]
[ 1, 1 ]
[]
[]
[ "find", "python" ]
stackoverflow_0003660395_find_python.txt
Q: I get OSError: [Errno 13] Permission denied: , and os.walk exits I have a script to report me about all files, in a directory, so that users will be required to erase them (it's a really badly managed cluster, w/o real superuser). When I run the script I get: OSError: [Errno 13] Permission denied: ' ls: : Permissi...
I get OSError: [Errno 13] Permission denied: , and os.walk exits
I have a script to report me about all files, in a directory, so that users will be required to erase them (it's a really badly managed cluster, w/o real superuser). When I run the script I get: OSError: [Errno 13] Permission denied: ' ls: : Permission denied I can't write the dir name (company policy) The code is: #!/...
[ "It sounds like your script is running as a normal user, and does not have permission to read a directory.\nIt would help to see the full error message (even if path names are changed), since it would tell us on which line the error was occurring.\nBut basically the solution is to trap the exception in a try...exce...
[ 2 ]
[]
[]
[ "os.walk", "python" ]
stackoverflow_0003660706_os.walk_python.txt
Q: same line behaves correctly or gives me an error message depending on file position gives me an error message: class logger: session = web.ctx.session #this line doesn't give me an error message: class create: def GET(self): # loggedout() session = web.ctx.session #this line form =...
same line behaves correctly or gives me an error message depending on file position
gives me an error message: class logger: session = web.ctx.session #this line doesn't give me an error message: class create: def GET(self): # loggedout() session = web.ctx.session #this line form = self.createform() return render.create(form) Why?
[ "web.ctx can't be used in that scope. It's a thread-local object that web.py initializes before it calls GET/POST/etc. and gets discarded afterwards.\n", "class logger:\n print('Hi')\n\nprints Hi. Statements under a class definition gets run at definition time. \nA function definition like this one:\ndef GET(s...
[ 1, 0 ]
[]
[]
[ "python", "web.py" ]
stackoverflow_0003647939_python_web.py.txt
Q: Python 2.7 or 3.1.2? Possible Duplicate: python 2.6 or python 3.1? Hi, I'm new to the python world and it seems that there are currently two parallel versions in development, which would be the 2.7 versus the 3.1.2. I'm wondering what version should I use to start, and why? A: Stay with 3.1.2 if you want to be...
Python 2.7 or 3.1.2?
Possible Duplicate: python 2.6 or python 3.1? Hi, I'm new to the python world and it seems that there are currently two parallel versions in development, which would be the 2.7 versus the 3.1.2. I'm wondering what version should I use to start, and why?
[ "Stay with 3.1.2 if you want to be on the bleeding edge.\nStay with 2.7 if you want to leverage any 3rd party libraries that haven't been ported to 3.1.2 yet or can't be backward compatible.\n", "I'd suggest Python 3 as it has incorporated several fixes to remove some of Python's previous \"warts\". The primary r...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0003661186_python.txt
Q: Testing workflows in Django I really love testing and building unit tests, but I find it quite annoying having to build tests for a website's workflow. e.g. Register -> Check email -> Activate account -> Login or Login -> Edit details -> Submit and view profile manual testing = loads of time + tireing even when u...
Testing workflows in Django
I really love testing and building unit tests, but I find it quite annoying having to build tests for a website's workflow. e.g. Register -> Check email -> Activate account -> Login or Login -> Edit details -> Submit and view profile manual testing = loads of time + tireing even when using app such as Selenium, going ...
[ "I write \"functional unit\" tests for individual views using Django's test framework. I have found that integration tests are best done using something like Robot Framework. In one of my projects I came up with a minimal, custom implementation of Ward Cunningham's FIT mechanism.\n", "You probably want a function...
[ 3, 3, 2 ]
[]
[]
[ "django", "python", "testing", "unit_testing", "workflow" ]
stackoverflow_0003657934_django_python_testing_unit_testing_workflow.txt
Q: how do matlab do the sort? How is the sort() working in matlab? Code in pure matlab: q is an array: q = -0.2461 2.9531 -15.8867 49.8750 -99.1172 125.8438 -99.1172 49.8750 -15.8867 2.9531 -0.2461 After q = sort(roots(q)), I got: q = 0.3525 0.3371 - 0.1564i 0.3371 + 0.1564i ...
how do matlab do the sort?
How is the sort() working in matlab? Code in pure matlab: q is an array: q = -0.2461 2.9531 -15.8867 49.8750 -99.1172 125.8438 -99.1172 49.8750 -15.8867 2.9531 -0.2461 After q = sort(roots(q)), I got: q = 0.3525 0.3371 - 0.1564i 0.3371 + 0.1564i 0.2694 - 0.3547i 0....
[ "From the MATLAB documentation for SORT:\n\nIf A has complex entries r and s,\n sort orders them according to the\n following rule: r appears before s in\n sort(A) if either of the following\n hold:\n\nabs(r) < abs(s)\nabs(r) = abs(s) and angle(r) < angle(s)\n\n\nIn other words, an array that has complex entrie...
[ 4 ]
[]
[]
[ "matlab", "numpy", "python" ]
stackoverflow_0003662203_matlab_numpy_python.txt
Q: Design question in Python: should this be one generic function or two specific ones? I'm creating a basic database utility class in Python. I'm refactoring an old module into a class. I'm now working on an executeQuery() function, and I'm unsure of whether to keep the old design or change it. Here are the 2 option...
Design question in Python: should this be one generic function or two specific ones?
I'm creating a basic database utility class in Python. I'm refactoring an old module into a class. I'm now working on an executeQuery() function, and I'm unsure of whether to keep the old design or change it. Here are the 2 options: (The old design:) Have one generic executeQuery method that takes the query to execute...
[ "It's propably just me and my FP fetish, but I think a function executed solely for side effects is very different from a non-destructive function that fetches some data, and therefore have different names. Especially if the generic function would do something different depending on exactly that (the part on the co...
[ 4, 2, 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003662134_oop_python.txt
Q: Suspending function calls in Python for passing later (functional paradigm) I'm writing a python command line program which has some interdependent options, I would like for the user to be able to enter the options in whichever order they please. Currently I am using the getopts library to parse the command line ...
Suspending function calls in Python for passing later (functional paradigm)
I'm writing a python command line program which has some interdependent options, I would like for the user to be able to enter the options in whichever order they please. Currently I am using the getopts library to parse the command line options, unfortunately that parses them in-order. I've thrown together a system o...
[ "If you heappush like this:\nmyFun = obj.parseFile\nheapq.heappush(commandQ, (1, myFun, path))\n\nthen to later call the function, you could do this:\nwhile commandQ:\n x=heapq.heappop(commandQ)\n func=x[1]\n args=x[2:]\n func(*args)\n\n\nUse\nhelp = obj.PrintHelp\n\nwithout the parentheses. This makes ...
[ 2, 1, 0 ]
[]
[]
[ "functional_programming", "python", "suspend" ]
stackoverflow_0003662115_functional_programming_python_suspend.txt
Q: Making HTTP POST request I'm trying to make a POST request to retrieve information about a book. Here is the code that returns HTTP code: 302, Moved import httplib, urllib params = urllib.urlencode({ 'isbn' : '9780131185838', 'catalogId' : '10001', 'schoolStoreId' : '15828', 'search' : 'Search' ...
Making HTTP POST request
I'm trying to make a POST request to retrieve information about a book. Here is the code that returns HTTP code: 302, Moved import httplib, urllib params = urllib.urlencode({ 'isbn' : '9780131185838', 'catalogId' : '10001', 'schoolStoreId' : '15828', 'search' : 'Search' }) headers = {"Content-type":...
[ "Their server seems to want you to acquire the proper cookie. This works:\nimport urllib, urllib2, cookielib\n\ncookie_jar = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))\nurllib2.install_opener(opener)\n\n# acquire cookie\nurl_1 = 'http://www.bkstr.com/webapp/wcs/st...
[ 26, 4, 0 ]
[]
[]
[ "http", "post", "python", "urllib" ]
stackoverflow_0003659595_http_post_python_urllib.txt
Q: Python Tkinter Text Widget .get method error I'm very new to Python, sort of following Dive into Python 2 and wanted to dabble with some Tkinter programming. I've tried to make a little program that takes 3 sets of words and makes combinations of each word in the 3 sets to make keywords for websites. When I run th...
Python Tkinter Text Widget .get method error
I'm very new to Python, sort of following Dive into Python 2 and wanted to dabble with some Tkinter programming. I've tried to make a little program that takes 3 sets of words and makes combinations of each word in the 3 sets to make keywords for websites. When I run the script, the GUI appears as expected, but I get t...
[ "You're trying to access\nprimaryKeyWordsBox\n\noutside the class Application in the (free) function makeCombinations(..).\nYou could make makeCombinations(..) a member of Application by indenting it like the other member functions and add the self argument:\n def makeCombinations(self):\n\nYou should modify the bi...
[ 1 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0003662902_python_tkinter_user_interface.txt
Q: python comparing dictionaries level: beginner word= 'even' dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2} i want to know if word is entirely composed of letters in dict2 my approach: step 1 : convert word to dictionary(dict1) step2: for k in dict1.keys(): if k in dict2: if dict1[...
python comparing dictionaries
level: beginner word= 'even' dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2} i want to know if word is entirely composed of letters in dict2 my approach: step 1 : convert word to dictionary(dict1) step2: for k in dict1.keys(): if k in dict2: if dict1[k] != dict2[k]: ...
[ ">>> word= 'even'\n>>> dict2 = {'i': 1, 'n': 1, 'e': 1, 'l': 2, 'v': 2}\n>>> set(word).issubset(set(dict2.keys()))\nTrue\n\n", "Unless you need it for something else, don't bother constructing dict1. Just do this:\nfor c in word:\n if c not in dict2:\n return False\nreturn True\n\nOf course, you could ...
[ 4, 1, 0, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0003662297_dictionary_python.txt
Q: Why does my PyQt application open in the background on Mac OS X? I've got a PyQt app which I'm developing in Mac OS X, and whenever I try launching the app, it always is the very bottom application on the stack. So after launching, I always need to command+tab all the way to the end of the application list to swi...
Why does my PyQt application open in the background on Mac OS X?
I've got a PyQt app which I'm developing in Mac OS X, and whenever I try launching the app, it always is the very bottom application on the stack. So after launching, I always need to command+tab all the way to the end of the application list to switch focus to it. I read that this behavior can be fixed by launching t...
[ "Based on this article http://diotavelli.net/PyQtWiki/PyInstallerOnMacOSX, you need to call app.raise_() after app.show()\nui = MainWindow()\nui.show()\nui.raise_()\n\nref: http://www.mail-archive.com/pyqt@riverbankcomputing.com/msg18945.html\n" ]
[ 14 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0003662559_pyqt_python.txt
Q: Can i control PSFTP from a Python script? i want to run and control PSFTP from a Python script in order to get log files from a UNIX box onto my Windows machine. I can start up PSFTP and log in but when i try to run a command remotely such as 'cd' it isn't recognised by PSFTP and is just run in the terminal when i...
Can i control PSFTP from a Python script?
i want to run and control PSFTP from a Python script in order to get log files from a UNIX box onto my Windows machine. I can start up PSFTP and log in but when i try to run a command remotely such as 'cd' it isn't recognised by PSFTP and is just run in the terminal when i close PSFTP. The code which i am trying to run...
[ "You'll need to run PSFTP as a subprocess and speak directly with the process. os.system spawns a separate subshell each time it's invoked so it doesn't work like typing commands sequentially into a command prompt window. Take a look at the documentation for the standard Python subprocess module. You should be able...
[ 2, 1 ]
[]
[]
[ "ftp", "python", "scripting", "sftp", "unix" ]
stackoverflow_0003659395_ftp_python_scripting_sftp_unix.txt
Q: Customize the output of forms in Django I have multiple forms in a Django project. I was trying to use the Django provided as_p for form displaying due to its simplicity but client wants the error list below the field. Django's as_p prints it above the field label. I rather not add a field printing loop in every t...
Customize the output of forms in Django
I have multiple forms in a Django project. I was trying to use the Django provided as_p for form displaying due to its simplicity but client wants the error list below the field. Django's as_p prints it above the field label. I rather not add a field printing loop in every template just for this small change. It seems ...
[ "\nIncluding a template which just\n handles form displaying. The problem\n is, this template must assume that the\n form is named a certain name. How\n about if I have multiple forms being\n passed with different names? Does\n anyone know how to address this issue?\n\nYou could include your form template ins...
[ 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003663713_django_django_forms_python.txt
Q: do i need 32bit libxml2 for python on snow leopard? i'm having a hell of a time installing scrapy on my sl mbp. it requires libxml2, so i set about installing that. installing it from macports doesn't seem to pull down the python binding. installing it from source through scrapy's instructions (here) does install ...
do i need 32bit libxml2 for python on snow leopard?
i'm having a hell of a time installing scrapy on my sl mbp. it requires libxml2, so i set about installing that. installing it from macports doesn't seem to pull down the python binding. installing it from source through scrapy's instructions (here) does install the python bindings, but when i run 'python -c "import li...
[ "From the paths in your traceback, it appears you have installed and are trying to use the python.org python 2.6.4 (installed to /Library/Frameworks/Python.frameworks ...). That python is 32-bit only. By default on 10.6, MacPorts tries to install 64-bit versions of packages. You can change that for most MacPort...
[ 5, 1, 0, 0 ]
[]
[]
[ "libxml2", "macos", "osx_snow_leopard", "python" ]
stackoverflow_0002353957_libxml2_macos_osx_snow_leopard_python.txt
Q: Python: why does my list change after I've retrieved it from an object Simple question, I've scaled down a problem I'm having where a list which I've retrieve from an object is changing when I append more data to the object. Not to the list. Can anyone help my understand the behavior of python? class a(): de...
Python: why does my list change after I've retrieved it from an object
Simple question, I've scaled down a problem I'm having where a list which I've retrieve from an object is changing when I append more data to the object. Not to the list. Can anyone help my understand the behavior of python? class a(): def __init__(self): self.log = [] def clearLog(self): del ...
[ "When you code\n`list = obj.getLog()`\n\n(ignoring -- just for a second -- what a terrible idea it is to use identifiers that shadow builtins!!!) you're saying: \"make name list refer to exactly the same object that obj.getLog() returns\" -- which as we know from the code for class a is obj.log. So of course since...
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003663760_python.txt
Q: replace an item in a html tag spanning multiple lines I have a text file with html: Blah, blah, blah some text is here. <div> something here something else </body></html> so far, if the tags are on one line this works: textfile = open("htmlfile.txt", "r+") text = textfile.read() a = re.search('<div.+?<\/html...
replace an item in a html tag spanning multiple lines
I have a text file with html: Blah, blah, blah some text is here. <div> something here something else </body></html> so far, if the tags are on one line this works: textfile = open("htmlfile.txt", "r+") text = textfile.read() a = re.search('<div.+?<\/html>', text) repstr = c.group(0) text = text.replace(repstr,...
[ "By default, the dot doesn't match new lines. To make it match new lines, you need to compile the regex with the flag re.DOTALL, eg:\na = re.search('<div.+?<\\/html>', text, re.DOTALL)\n\n\nThat being said, you really shouldn't use regex to parse HTML.\nDo yourself a favor and use an XML parser like BeautifulSoup.\...
[ 0 ]
[]
[]
[ "python", "regex", "replace" ]
stackoverflow_0003664090_python_regex_replace.txt
Q: Calling a function with variable number of arguments with an array in C++ (like python's * operator) I'm trying to write a v8 module in C++; there, the functions receive a variable number of arguments in an array. I want to take that array and call a function like gettext and printf that receives a formatted strin...
Calling a function with variable number of arguments with an array in C++ (like python's * operator)
I'm trying to write a v8 module in C++; there, the functions receive a variable number of arguments in an array. I want to take that array and call a function like gettext and printf that receives a formatted string and it's necessary args. The thing is, how can one take an array and send the elements as arguments to o...
[ "Here's one way:\nvoid foo(const char *firstArg, ...) {\n va_list argList;\n va_start(argList, firstArg);\n\n vprintf(firstArg, argList);\n\n va_end(argList);\n}\n\nAssuming that you're trying to do a printf. Basically, va_list is the key, and you can use it to either examine the arguments, or pass them...
[ 2 ]
[]
[]
[ "c++", "gettext", "node.js", "python", "v8" ]
stackoverflow_0003664348_c++_gettext_node.js_python_v8.txt
Q: XML parser syntax error So I'm working with a block of code which communicates with the Flickr API. I'm getting a 'syntax error' in xml.parsers.expat.ExpatError (below). Now I can't figure out how it'd be a syntax error in a Python module. I saw another similar question on SO regarding the Wikipedia API which see...
XML parser syntax error
So I'm working with a block of code which communicates with the Flickr API. I'm getting a 'syntax error' in xml.parsers.expat.ExpatError (below). Now I can't figure out how it'd be a syntax error in a Python module. I saw another similar question on SO regarding the Wikipedia API which seemed to return HTML intead of ...
[ "SyntaxError normally means an error in Python syntax, but I think here that expatbuilder is overloading it to mean an XML syntax error. Put a try:except block around it, and print out the contents of payload and to work out what's wrong with the first line of it. \nMy guess would be that flickr is rejecting your...
[ 6, 2 ]
[]
[]
[ "api", "python", "xml", "xml_parsing" ]
stackoverflow_0003664084_api_python_xml_xml_parsing.txt
Q: django comment system: How to make it more like YouTube's? I like the comment box at the top with the posts going in reverse order. Comment rating, highest rated comments, all great features, remaining character count, spam flag. My question is, is there a open commenting system available for Django that already h...
django comment system: How to make it more like YouTube's?
I like the comment box at the top with the posts going in reverse order. Comment rating, highest rated comments, all great features, remaining character count, spam flag. My question is, is there a open commenting system available for Django that already has these features?
[ "I suggest Disqus plus django-disqus (http://github.com/arthurk/django-disqus)\n" ]
[ -1 ]
[]
[]
[ "comments", "django", "python", "youtube" ]
stackoverflow_0003662809_comments_django_python_youtube.txt