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: Django Models in Java-style File Structure I'm building a large Django application and would like to split my data models up in a 'class-per-file' structure, but in attempting to do so I'm running into circular dependency issues on some of the more complex models. For example, I have three models, all in separate ...
Django Models in Java-style File Structure
I'm building a large Django application and would like to split my data models up in a 'class-per-file' structure, but in attempting to do so I'm running into circular dependency issues on some of the more complex models. For example, I have three models, all in separate files: class Book(models.Model): title = mod...
[ "You can also specify the model name as a string:\npreferred_genre = models.ForeignKey(\"Genre\")\n\n", "I think that's a design issue rather than a django issue. \nYour Genre should not have a reference to Book. Otherwise you will create circular references whatever the language/framework you are using.\nThe sam...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007390456_django_django_models_python.txt
Q: Is it possible to use different dialects on different fields? I am reading CSV file with python and for some fields I want to remove escape char ('aaa/bb' to aaabb) and for some fields leave it without a change. for example: input:13,0,0,"0",false,"test\\file",-1,-1,1314570610162,13,"1","Danny","name\\Mary" expect...
Is it possible to use different dialects on different fields?
I am reading CSV file with python and for some fields I want to remove escape char ('aaa/bb' to aaabb) and for some fields leave it without a change. for example: input:13,0,0,"0",false,"test\\file",-1,-1,1314570610162,13,"1","Danny","name\\Mary" expected output:13,0,0,"0",false,"testfile",-1,-1,1314570610162,13 ,"1","...
[ "You're overthinking it. You don't need to have multiple dialects, they describe the csv file layout. You want to remove characters within certain fields, which is easily done before writing your output.\nSomething like this should be good:\nreader = csv.reader(yourFileHandle)\nwriter = csv.writer(outputFileHandle)...
[ 1, 0 ]
[]
[]
[ "dialect", "python" ]
stackoverflow_0007388234_dialect_python.txt
Q: Python - how to filter an output in a python shell in a grep-like way? I work in a Python shell. In order to produce a list of all global names I use dir(), but it generates a very long list, which I would like to filter. I am interested only in the names which begin with 'f' and end with digits. Sometimes I also ...
Python - how to filter an output in a python shell in a grep-like way?
I work in a Python shell. In order to produce a list of all global names I use dir(), but it generates a very long list, which I would like to filter. I am interested only in the names which begin with 'f' and end with digits. Sometimes I also need only user-defined names, no __*__ names. Is there any grep-like method ...
[ "[name for name in dir() if name.startswith('f') and name[-1].isdigit()]\n\nExample:\n>>> f0 = 7\n>>> [name for name in dir() if name.startswith('f') and name[-1].isdigit()]\n['f0']\n\n", ">>> import re\n>>> [item for item in dir() if re.match(r'f.*\\d+$',item)]\n\nor\n>>> [item for item in dir() if re.search(r'^...
[ 2, 2, 1 ]
[]
[]
[ "grep", "python" ]
stackoverflow_0007390201_grep_python.txt
Q: Django-Notification - Alternative to Email Backend I'm building a project with Django, and am currently trying to implement django-notification as a means to keep track of user activity. While I managed to install it and create some notifications, they are only sent via email but not stored in the respective datab...
Django-Notification - Alternative to Email Backend
I'm building a project with Django, and am currently trying to implement django-notification as a means to keep track of user activity. While I managed to install it and create some notifications, they are only sent via email but not stored in the respective databases so that I could display them in a feed view. The /n...
[ "It appears that brosner's fork of django-notifications differs from jtauber's in that send_now() does not actually add Notice instances to the database, nor does the default EmailBackend notification backend.\nYou will have to write your own notification backend class that creates a Notice instance when deliver() ...
[ 1 ]
[]
[]
[ "django", "django_notification", "pinax", "python" ]
stackoverflow_0007389205_django_django_notification_pinax_python.txt
Q: Why can't Django find my admin media files once I leave the built-in runserver? When I was using the built-in simple server, everything is OK, the admin interface is beautiful: python manage.py runserver However, when I try to serve my application using a wsgi server with django.core.handlers.wsgi.WSGIHandler, Dja...
Why can't Django find my admin media files once I leave the built-in runserver?
When I was using the built-in simple server, everything is OK, the admin interface is beautiful: python manage.py runserver However, when I try to serve my application using a wsgi server with django.core.handlers.wsgi.WSGIHandler, Django seems to forget where the admin media files is, and the admin page is not styled ...
[ "When I look into the source code of Django, I find out the reason.\nSomewhere in the django.core.management.commands.runserver module, a WSGIHandler object is \nwrapped inside an AdminMediaHandler.\nAccording to the document, AdminMediaHandler is a \n\nWSGI middleware that intercepts calls\n to the admin media di...
[ 2, 1, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003032519_django_django_admin_python.txt
Q: How should I convert a Python tuple of strings into dynamically-specified types? I'm writing a simple Python application using the cmd module to provide a CLI-type interface. The commands provided by my CLI have parameter lists that vary widely. Each command handler receives a string argument containing the portio...
How should I convert a Python tuple of strings into dynamically-specified types?
I'm writing a simple Python application using the cmd module to provide a CLI-type interface. The commands provided by my CLI have parameter lists that vary widely. Each command handler receives a string argument containing the portion of the line that contains arguments; I plan to tokenize them into a tuple using shle...
[ "Depending on whether you are using Python 2.6 or 2.7, you could use the built in optparse or argparse, respectively. \nhttp://docs.python.org/library/argparse.html\nThey may be slightly heavyweight, but they'll do conversion to ints,floats, or whatever type you need as part of the parsing, and it can automatically...
[ 2, 2 ]
[]
[]
[ "parsing", "python", "string" ]
stackoverflow_0007391002_parsing_python_string.txt
Q: Avoid if __name__ == '__main__' in Python subclasses to be run using function from parent I have a generic class (A) which is to be subclassed a lot like this: class A: def run(self): ... self.do_something() ... #abstract function def do_something(self): pass class B(A...
Avoid if __name__ == '__main__' in Python subclasses to be run using function from parent
I have a generic class (A) which is to be subclassed a lot like this: class A: def run(self): ... self.do_something() ... #abstract function def do_something(self): pass class B(A): def do_something(self): ... The subclasses are in separate files that I'm runn...
[ "If your python version is recent enough, you can create a class decorator.\nIn this case, an indirect one.\ndef runifmain(mainname):\n def deco(clas):\n if mainname == '__main__':\n clas().run()\n return clas\n return deco\n\n\n@runifmain(__name__)\nclass B(A):\n [...]\n\nshould d...
[ 8, 2 ]
[]
[]
[ "python", "subclass" ]
stackoverflow_0007386969_python_subclass.txt
Q: lighttpd, mod_rewrite, web.py I've a small issue with lighttpd and web.py. It runs perfectly fine on Apache2 but there's a small issue on lighttpd. Here's my lighttpd config for web.py fastcgi.server = ("/code.py" => (( "socket" => "/tmp/fcgi.socket", "bin-path" => "/home/ivan/www/code.py", ...
lighttpd, mod_rewrite, web.py
I've a small issue with lighttpd and web.py. It runs perfectly fine on Apache2 but there's a small issue on lighttpd. Here's my lighttpd config for web.py fastcgi.server = ("/code.py" => (( "socket" => "/tmp/fcgi.socket", "bin-path" => "/home/ivan/www/code.py", "max-procs" => 1, "check-loc...
[ "Before spawning your script with fastcgi just set\nexport REAL_SCRIPT_NAME=\"\"\n\nthis should work.\n" ]
[ 0 ]
[]
[]
[ "lighttpd", "python", "web.py" ]
stackoverflow_0004802218_lighttpd_python_web.py.txt
Q: Python checking file content with string Hello! I have the following script: import os import stat curDir = os.getcwd() autorun_signature = [ "[Autorun]", "Open=regsvr.exe", "Shellexecute=regsvr.exe", "Shell\Open\command=regsvr.exe", ...
Python checking file content with string
Hello! I have the following script: import os import stat curDir = os.getcwd() autorun_signature = [ "[Autorun]", "Open=regsvr.exe", "Shellexecute=regsvr.exe", "Shell\Open\command=regsvr.exe", "Shell=Open" ] content = [] def rea...
[ "It is probably due to the fact that Windows new lines are \\r\\n instead of \\n.\nAlso, you should escape the \"\\\", so instead use\"\\\\\".\n", "Linebreaks under Windows \\r\\n are different from Linux's \\n.\nSo try replacing \\n with \\r\\n.\n" ]
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007391505_python.txt
Q: What good homework style tutorials are recommended for learning functional programming in Python? I recommended to a friend to learn some functional programming using Python to expand his knowledge and overcome programmer's fatigue. I chose Python because that way there's a good chance he'll be able to use the new...
What good homework style tutorials are recommended for learning functional programming in Python?
I recommended to a friend to learn some functional programming using Python to expand his knowledge and overcome programmer's fatigue. I chose Python because that way there's a good chance he'll be able to use the new knowledge in practical daily work. I tried to find him some tutorials, and found a lot of guides - div...
[ "Maybe http://diveintopython.net/functional_programming/index.html helps.\nSome other useful links are:\n\nFunctional Programming HOWTO\nFunctional Programming with Python (by Pramode C.E.)\nFunctional programming with Python (by CHRISTIAN HARMS)\n\n", "I was told about this website when I first started learning....
[ 7, 1, 0 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0007368119_functional_programming_python.txt
Q: Python regex: how to check if a character in a string is within the span of a regex matched substring? I have a regex pattern, which I used on a large piece of text (a single string). Several discontiguous regions of the original text matches the regexp. Now, I'm attempting to build a state machine, to iterate ove...
Python regex: how to check if a character in a string is within the span of a regex matched substring?
I have a regex pattern, which I used on a large piece of text (a single string). Several discontiguous regions of the original text matches the regexp. Now, I'm attempting to build a state machine, to iterate over the text and do different things based on the char at a position, and whether this position is within the ...
[ "EDIT: It sounds like you want to write your own parser FSM which (among other things) tokenizes comma characters, only when they are not escaped. \nThe following regex works for an identifier, possibly containing escaped commas. You could use this with antlr/lex:\ninput = r'aaaaa,bbbb/,ccccc,dddddd,'\n\npat = re.c...
[ 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007391572_python_regex.txt
Q: Error configuring django with python-mysql in Mac OS 10.6.6 My Setup: Mac OS 10.6.6 - x86_64 MySQL 5.5.8 Python 2.7.1 Django 1.2.5 mysql-python installed via easy_install My situation: I've been struggling to get my setup to work. The problem is with the mysql-python interface. Originally, I was getting a simila...
Error configuring django with python-mysql in Mac OS 10.6.6
My Setup: Mac OS 10.6.6 - x86_64 MySQL 5.5.8 Python 2.7.1 Django 1.2.5 mysql-python installed via easy_install My situation: I've been struggling to get my setup to work. The problem is with the mysql-python interface. Originally, I was getting a similar problem (to the one I'm having with Django) doing an import sta...
[ "export DYLD_LIBRARY_PATH=/usr/local/mysql/lib:$DYLD_LIBRARY_PATH\nor: \npip install MySQL-python\npip install --upgrade MySQL-python\n\nHelped me within a virtualenv\n", "I had a similar problem, which I solved for the development program by including this line in my .bash_profile file (the magic file in my ~ di...
[ 5, 2, 0 ]
[]
[]
[ "django", "mysql", "mysql_python", "osx_snow_leopard", "python" ]
stackoverflow_0005190357_django_mysql_mysql_python_osx_snow_leopard_python.txt
Q: Unity3d - Hosting on Google App Engine I have a problem with hosting my Unity3d web application on GAE. When the application loads and the web player starts to request the ".unity3d" file, i use the following python script to make the HTTP response: class UnityHandler(webapp.RequestHandler): def get (self, q): ...
Unity3d - Hosting on Google App Engine
I have a problem with hosting my Unity3d web application on GAE. When the application loads and the web player starts to request the ".unity3d" file, i use the following python script to make the HTTP response: class UnityHandler(webapp.RequestHandler): def get (self, q): if q is None: q = 'WebPlayer.unity3...
[ "I'm going to assume, first, that you meant to indent the 3 lines starting with path =.\nSecond, I'm guessing your intent was to route the url \"/\" to WebPlayer.unity3d. However, both of your regexes will match the / since everything after the slash is optional; MainHandler will receive the request since it's firs...
[ 4 ]
[]
[]
[ "google_app_engine", "python", "unity3d" ]
stackoverflow_0007390954_google_app_engine_python_unity3d.txt
Q: closing stdout of piped python subprocess Here is what I can read in the python subprocess module documentation: Replacing shell pipeline output=`dmesg | grep hda` ==> p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to ...
closing stdout of piped python subprocess
Here is what I can read in the python subprocess module documentation: Replacing shell pipeline output=`dmesg | grep hda` ==> p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2....
[ "From Wikipedia, SIGPIPE is the signal sent to a process when it attempts to write to a pipe without a process connected to the other end.\nWhen you first create p1 using stdout=PIPE, there is one process connected to the pipe, which is your Python process, and you can read the output using p1.stdout.\nWhen you cre...
[ 15, 1 ]
[]
[]
[ "pipeline", "python", "shell", "subprocess" ]
stackoverflow_0007391689_pipeline_python_shell_subprocess.txt
Q: Django query parameters not returning None I have a few lines of code in my view that get a query param and then filter based on that parameter. search = request.GET.get('search', None) if search: accounts = UserProfile.objects.filter(fullname__icontains=search).order_by('fullname') else: accounts = UserP...
Django query parameters not returning None
I have a few lines of code in my view that get a query param and then filter based on that parameter. search = request.GET.get('search', None) if search: accounts = UserProfile.objects.filter(fullname__icontains=search).order_by('fullname') else: accounts = UserProfile.objects.all().order_by('fullname') For s...
[ "Actually if you pay close attention the search variable is set to a list that contain an empty unicode string [u''] so that why it's evaluated to True:\n>>> search = [u'']\n>>> bool(search)\nTrue\n\nAnd for why you are seeing different behavior between your test and production sadly i'm not sure why !? maybe the d...
[ 2 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0007391884_django_django_queryset_python.txt
Q: What's causing this imaplib error in Python script for AppEngine? This script: import imaplib user = "dave.trindall@gmail.com" pwd = "***" m = imaplib.IMAP4_SSL("imap.gmail.com") m.login(user,pwd) m.select("Inbox") # here you a can choose a mail box like INBOX instead m.search("NEW") ...
What's causing this imaplib error in Python script for AppEngine?
This script: import imaplib user = "dave.trindall@gmail.com" pwd = "***" m = imaplib.IMAP4_SSL("imap.gmail.com") m.login(user,pwd) m.select("Inbox") # here you a can choose a mail box like INBOX instead m.search("NEW") makes this error for me: Traceback (most recent call last): File "c:...
[ "This fails because App-Engine disallows opening sockets in your application. See the 'Pure Python' section in http://code.google.com/appengine/docs/python/runtime.html, also discussion at http://groups.google.com/group/google-appengine/browse_thread/thread/4a8764d266ec17af\n", "Note that while you can't make raw...
[ 4, 0 ]
[]
[]
[ "google_app_engine", "imaplib", "python" ]
stackoverflow_0007376314_google_app_engine_imaplib_python.txt
Q: How to check if remote file exits behind a proxy I writing app that connect to a web server (I am the owner of he server) sends information provided by the user, process that information and send result back to the application. The time needed to process the results depends on the user request (from few seconds to...
How to check if remote file exits behind a proxy
I writing app that connect to a web server (I am the owner of he server) sends information provided by the user, process that information and send result back to the application. The time needed to process the results depends on the user request (from few seconds to a few minutes). I use a infinite loop to check if the...
[ "The simplest solution could be to add a (unused) GET parameter to avoid caching the request. \nie:\ni = 0\nWhile True:\n try:\n result=br.open('http://www.example.com/sample.txt?r=%d' % i).read()\n break\n except:\n i += 1\n time.sleep(10)\n\nThe extra parameter should be ignored by t...
[ 2 ]
[]
[]
[ "file_exists", "mechanize", "proxy", "python" ]
stackoverflow_0007392176_file_exists_mechanize_proxy_python.txt
Q: Python Implementations of Packing Algorithm For an application I'm working on I need something like a packing algorithm implemented in Python see here for more details. The basic idea is that I have n objects of varying sizes that I need to fit into n bins, where the number of bins is limited and the size of both...
Python Implementations of Packing Algorithm
For an application I'm working on I need something like a packing algorithm implemented in Python see here for more details. The basic idea is that I have n objects of varying sizes that I need to fit into n bins, where the number of bins is limited and the size of both objects and bins is fixed. The objects / bins c...
[ "https://bitbucket.org/kent37/python-tutor-samples/src/f657aeba5328/BinPacking.py\n\"\"\" Partition a list into sublists whose sums don't exceed a maximum \n using a First Fit Decreasing algorithm. See\n http://www.ams.org/new-in-math/cover/bins1.html\n for a simple description of the method.\n\"\"\"\n\n\n...
[ 13 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0007392143_algorithm_python.txt
Q: Resizing gtk TreeView in HPaned problem I have a treeview in the left side of an hpaned but when I try to move the bar to the left to make the treeview smaller than its automatic size instead of resizing the treeview it expands the entire program window to the right. Any ideas on how to fix this? The relevant port...
Resizing gtk TreeView in HPaned problem
I have a treeview in the left side of an hpaned but when I try to move the bar to the left to make the treeview smaller than its automatic size instead of resizing the treeview it expands the entire program window to the right. Any ideas on how to fix this? The relevant portions of the source are the following: For the...
[ "I was going to answer this question, and then I realized that my answer was a repeat of the user's answer. But, as he hasn't posted his resolution as an answer, I will anyway. (Below is what I would have posted if he hadn't figured it out.)\nExpand and Fill seem to be causing a bit of a fight for space between the...
[ 2 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0004754437_gtk_pygtk_python.txt
Q: Large temporary database to sanitize data in Python I have a large amount of data that I am pulling from an xml file that all needs to be validated against each other (in excess of 500,000 records). It is location data, so it has information such as: county, street prefix, street suffix, street name, starting hous...
Large temporary database to sanitize data in Python
I have a large amount of data that I am pulling from an xml file that all needs to be validated against each other (in excess of 500,000 records). It is location data, so it has information such as: county, street prefix, street suffix, street name, starting house number, ending number. There are duplicates, house numb...
[ "500,000 is not a large number, why can't you just go thru all record create a dict out of relevant entries and check whatever you need to check e.g.\nimport random\nimport time\n\nclass Data(object):\n ID = 0\n def __init__(self, data):\n Data.ID+=1\n self.id =Data.ID\n self.data = data\...
[ 1, 0 ]
[]
[]
[ "python", "sanitization", "xml" ]
stackoverflow_0007391148_python_sanitization_xml.txt
Q: How do you use __init__.py? I'm trying to learn how the __init__.py file works for packaging and calling modules from different directories. I have a directory structure like this: init_test\ __init__.py a\ aaa.py b\ bbb.py in aaa.py there is a function called test bbb.py looks like this...
How do you use __init__.py?
I'm trying to learn how the __init__.py file works for packaging and calling modules from different directories. I have a directory structure like this: init_test\ __init__.py a\ aaa.py b\ bbb.py in aaa.py there is a function called test bbb.py looks like this: import init_test.a.aaa if __nam...
[ "You also need to have __init__.py in a and b directories\nFor your example to work first you should add your base directory to the path:\nimport sys\nsys.path.append('../..')\n\nimport init_test.a.aaa\n...\n\n", "You have to add an empty __init__.py into a. Then a is recognized as a sub package of init_test and ...
[ 7, 2, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0007392373_module_python.txt
Q: How To : Create Video chat using gst and python and show initiators and accepter's video, in single gtk window I am developing video chat using gst and python. where, I would like to view end user's webcam and also want to view my own webcam in one gtk window (similar to empathy video chat). for that, I have used ...
How To : Create Video chat using gst and python and show initiators and accepter's video, in single gtk window
I am developing video chat using gst and python. where, I would like to view end user's webcam and also want to view my own webcam in one gtk window (similar to empathy video chat). for that, I have used gst.Tee object and created 2 queues, one would link result to local gtk window and second queue would link same vide...
[ "I was holding off on answering, but as no one else has weighed in, I'll take a shot at it.\nI'm not sure if this would tie in with webcam (though it probably would), but you could create two drawing areas (gtk.DrawingArea) in PyGTK for your two screens. Then, you can hook your video up to those.\nI'm doing somethi...
[ 0 ]
[]
[]
[ "audio_video_sync", "gstreamer", "pygtk", "python", "videochat" ]
stackoverflow_0006896623_audio_video_sync_gstreamer_pygtk_python_videochat.txt
Q: Python BeautifulSoup encoding I have a code to read the html and modify some text using Beatiful Soup. It works fine but when I read the output, this part of my html file is changed automatically: Original : <meta http-equiv="Content-Type" content="text/html; charset=**iso-8859-1**" /> Modified by itself: <meta ht...
Python BeautifulSoup encoding
I have a code to read the html and modify some text using Beatiful Soup. It works fine but when I read the output, this part of my html file is changed automatically: Original : <meta http-equiv="Content-Type" content="text/html; charset=**iso-8859-1**" /> Modified by itself: <meta http-equiv="Content-Type" content="te...
[ "Try\nprint soup.__str__(\"ISO-8859-1\")\n\n" ]
[ 1 ]
[]
[]
[ "beautifulsoup", "html", "python" ]
stackoverflow_0007392277_beautifulsoup_html_python.txt
Q: Manually installing python package I'd like to use https://github.com/erikvold/Github-to-Lighthouse-Issue-Migrator/blob/master/migrator.py but in the comments starting on line 8 it says: # pip install lighthouse-python-api (probably have to do this manually) But when I try I get the following error: $ pip install...
Manually installing python package
I'd like to use https://github.com/erikvold/Github-to-Lighthouse-Issue-Migrator/blob/master/migrator.py but in the comments starting on line 8 it says: # pip install lighthouse-python-api (probably have to do this manually) But when I try I get the following error: $ pip install lighthouse-python-api Downloading/unpac...
[ "As @delnan said, the maintainer of Lighthouse API should really create a setup.py script. Anyway, there are two ways to achieve what you want and both require an understand of python modules.\nWhen you import a module in python like so:\nimport lighthouse\n\nthe interpretor searches for a file named lighthouse.py ...
[ 6 ]
[]
[]
[ "package", "pip", "python" ]
stackoverflow_0007391438_package_pip_python.txt
Q: Python+mako Unicode problem I am trying to read a DB table contents and display it as a web page using mako and bottle. The table has some Unicode (utf-8) fields in it. UnicodeDecodeError('ascii', 'MOTOROLA MILESTONE\xe2\x84\xa2 PLUS', 18, 19, 'ordinal not in range(128)') With the following st...
Python+mako Unicode problem
I am trying to read a DB table contents and display it as a web page using mako and bottle. The table has some Unicode (utf-8) fields in it. UnicodeDecodeError('ascii', 'MOTOROLA MILESTONE\xe2\x84\xa2 PLUS', 18, 19, 'ordinal not in range(128)') With the following stack trace: Traceback (most recent...
[ "The problem is not that render_unicode cannot convert a python unicode object into utf8, its that a string object exists, which it assumes is ascii, and that holds non ascii data.\nStart at the beginning - decode all incoming strings into unicode internally. You have a string input that needs fixing.\nI suggest y...
[ 1 ]
[]
[]
[ "bottle", "mako", "python", "unicode" ]
stackoverflow_0007389935_bottle_mako_python_unicode.txt
Q: Python threads - number of arguments Error I am executing a command in a thread for almost 25k times like if threaded is True: thread = Thread(target=threadedCommand, args=(cmd)) thread.start() thread.join() def threadedCommand(command): if command is None: ...
Python threads - number of arguments Error
I am executing a command in a thread for almost 25k times like if threaded is True: thread = Thread(target=threadedCommand, args=(cmd)) thread.start() thread.join() def threadedCommand(command): if command is None: print 'can\'t execute threaded command' ...
[ "args must be a tuple. (cmd) is the same as cmd; you want a one-element tuple instead:\nthread = Thread(target=threadedCommand, args=(cmd,))\n# ^\n\n" ]
[ 22 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0007392636_multithreading_python.txt
Q: Remote procedure call in C# I am basically new to this kind of work.I am programming my application in C# in VS2010.I have a crystal report that is working fine and it basically gets populated with some xml data. That XMl data is coming from other application that is written in Python on another machine. That Pyt...
Remote procedure call in C#
I am basically new to this kind of work.I am programming my application in C# in VS2010.I have a crystal report that is working fine and it basically gets populated with some xml data. That XMl data is coming from other application that is written in Python on another machine. That Python script generates some data an...
[ "As John wrote, you're quite late if it's urgent and your description is quite vague. There are 1001 RPC techniques and the choice depends on details. But taking into account that you seem just to exchange some xml data, you probably don't need a full RPC implementation. You can write a HTTP server in python with j...
[ 0 ]
[]
[]
[ "c#", "python", "rpc", "web_services" ]
stackoverflow_0007392676_c#_python_rpc_web_services.txt
Q: Trying to understand insertion sort algorithm I'm reading some books on Python, data structures, and analysis and design of algorithms. I want to really understand the in's and out's of coding, and become an efficient programmer. It's difficult to ask the book to clarify, hence my question on stackoverflow. I'm re...
Trying to understand insertion sort algorithm
I'm reading some books on Python, data structures, and analysis and design of algorithms. I want to really understand the in's and out's of coding, and become an efficient programmer. It's difficult to ask the book to clarify, hence my question on stackoverflow. I'm really finding Algorithms and recursion challenging ....
[ "Let me try to break this down. \nStart by considering a list. It is \"almost\" sorted. That is, the first few elements are sorted, but the last element is not sorted. So it looks something like this:\n[10, 20, 30, 50, 15]\n\nObviously, the 15 is in the wrong place. So how do we move it? \n key = mylist[4]\n ...
[ 17, 6, 2, 1, 1, 1, 1 ]
[]
[]
[ "algorithm", "insertion_sort", "python", "sorting" ]
stackoverflow_0007392225_algorithm_insertion_sort_python_sorting.txt
Q: Highlight Select Box in Python I am trying to rebuild the functionality of the desktop's "highlight to select" feature so that I can use it in my own app. When I say "highlight to select" I mean the selection box that shows up if you click and drag on your desktop (native to all main-stream OS). I've been working...
Highlight Select Box in Python
I am trying to rebuild the functionality of the desktop's "highlight to select" feature so that I can use it in my own app. When I say "highlight to select" I mean the selection box that shows up if you click and drag on your desktop (native to all main-stream OS). I've been working for hours trying to recreate it, an...
[ "I don't know if this is what you're looking for, but what if you created another window in your module, and have your code show it when you release drag? You could fetch the cursor's current position, and have it draw the window there.\nThis should help you get the mouse position on the root window.\nSo, your code...
[ 0 ]
[]
[]
[ "pygtk", "python", "selection", "xlib" ]
stackoverflow_0007352195_pygtk_python_selection_xlib.txt
Q: How do you use vi (or another editor) as part of another command to edit something and return it to that command? For example, if you have ever used git, when you do a commit it will open vi to add or edit some text, and when you exit it is able to intercept this and use that text. What is this called so I can lo...
How do you use vi (or another editor) as part of another command to edit something and return it to that command?
For example, if you have ever used git, when you do a commit it will open vi to add or edit some text, and when you exit it is able to intercept this and use that text. What is this called so I can lookup some docs on it? Any other information, especially performing this using python, would be very helpful.
[ "Often, the user's $EDITOR environment variable is executed, and instructed to write a temporary file with some random name. The temporary file can then be read back in by your application and discarded when no longer needed.\n# Your application makes a system call like:\n$EDITOR /tmp/randfile1124098weasc9839x.txt...
[ 5, 4, 2 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0007392848_linux_python.txt
Q: Creating a Selection tool using PyGtk Can anyone help or point me in the right direction for figuring out how to create a drag and draw rectangular box to be used as a selection tool in PyGtk? I am presently using an event box with a drawable window and the user can click once in the upper left and once in the low...
Creating a Selection tool using PyGtk
Can anyone help or point me in the right direction for figuring out how to create a drag and draw rectangular box to be used as a selection tool in PyGtk? I am presently using an event box with a drawable window and the user can click once in the upper left and once in the lower right corner of the portion of image the...
[ "Actually, this doesn't seem all that lamebrained at all. It is actually quite specific, and a little challenging. \nI'll give you the steps to start you off, but as you're beginning (and you didn't post any specific code), it would be better for you to create the code yourself based on documentation and my hints.\...
[ 0 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0005464751_gtk_pygtk_python.txt
Q: Where to start with scripting project - searching a log-in only web site from term/cmd I'm attempting to write a script for myself that will log in to a specific website and use the website's search function. The script will then write the list of search results to standard output, where I will then select one of ...
Where to start with scripting project - searching a log-in only web site from term/cmd
I'm attempting to write a script for myself that will log in to a specific website and use the website's search function. The script will then write the list of search results to standard output, where I will then select one of the results and do various actions on the page. I'm very lost as where to start with this. I...
[ "Assuming that website doesn't provide a search API, you need to do automated scraping, in which case curl etc. are way too low-level and error-prone.\nHere are are some widely-used recommendations:\nFor automation, link-following, formfilling etc., I strongly recommend twill API, which is an automation layer which...
[ 3 ]
[]
[]
[ "curl", "python", "search" ]
stackoverflow_0007382916_curl_python_search.txt
Q: Creating dict from all possible combinations of 2 separate lists I found this useful bit of code among the series of tubes that is the internet: x=[1,2,3,4] y=[1,2,3,4] combos=[(`i`+`n`) for i in x for n in y] combos ['11','12','13','14','21','22','23','24','31','32','33','34','41','42','43','44'] What I'm trying...
Creating dict from all possible combinations of 2 separate lists
I found this useful bit of code among the series of tubes that is the internet: x=[1,2,3,4] y=[1,2,3,4] combos=[(`i`+`n`) for i in x for n in y] combos ['11','12','13','14','21','22','23','24','31','32','33','34','41','42','43','44'] What I'm trying to do is something like the following: combinations={(i: `n`+`d`) for...
[ "combos = [str(i) + str(n) for i in x for n in y] # or `i`+`n`, () for a generator\ncombinations = dict((i+1,c) for i,c in enumerate(combos))\n# Only in Python 2.6 and newer:\ncombinations = dict(enumerate(combos, 1))\n# Only in Python 2.7 and newer:\ncombinations = {i+1:c for i,c in enumerate(combos)}\n\n", "Sta...
[ 7, 1, 1, 1 ]
[]
[]
[ "python", "python_2.x" ]
stackoverflow_0007392850_python_python_2.x.txt
Q: izip_longest in itertools: How does rasing IndexError inside the iterator work? In this question @lazyr asks how the following code of izip_longest iterator from here works: def izip_longest_from_docs(*args, **kwds): # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- fillvalue = kwds.get('fillvalu...
izip_longest in itertools: How does rasing IndexError inside the iterator work?
In this question @lazyr asks how the following code of izip_longest iterator from here works: def izip_longest_from_docs(*args, **kwds): # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- fillvalue = kwds.get('fillvalue') def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): yield counte...
[ "in izip_longest_next in the code of izip_longest, no sentinel is used.\nInstead, CPython keeps track of how many of the iterators are still active with a counter, and stops when the number active reaches zero.\nIf an error occurs, it ends iteration as if there are no iterators still active, and allows the error to...
[ 3 ]
[]
[]
[ "iterator", "python", "python_itertools" ]
stackoverflow_0007392902_iterator_python_python_itertools.txt
Q: Flask unresponsive while uploading file or waiting for other server My Flask stops responding when uploading files or when collecting data from another server via GET. I assume, the problem is, that Flask is only running on one thread. How can I change this, so multiple users can use the site? A: Flask's develo...
Flask unresponsive while uploading file or waiting for other server
My Flask stops responding when uploading files or when collecting data from another server via GET. I assume, the problem is, that Flask is only running on one thread. How can I change this, so multiple users can use the site?
[ "Flask's development webserver (invoked when you use app.run) is not a production web server. \nQuoting the docs:\n\nYou can use the builtin server during development, but you should use a full deployment option for production applications. (Do not use the builtin development server in production.)\n\nIf you want ...
[ 6 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0007393345_flask_python.txt
Q: modelformset __iter__ overloading problem I'm writing the custom modelformset. I need that forms to be sorted by value of field "ordering". I overloaded __iter__ method of BaseFormSet in my child formset class. My class inherited from BaseFormSet: class SortedCatForms(BaseFormSet): def __iter__(self): ...
modelformset __iter__ overloading problem
I'm writing the custom modelformset. I need that forms to be sorted by value of field "ordering". I overloaded __iter__ method of BaseFormSet in my child formset class. My class inherited from BaseFormSet: class SortedCatForms(BaseFormSet): def __iter__(self): return iter(self.forms.sort( ...
[ "Not familiar enough with Django to judge whether this is the right way, but here's a simple gotcha:\nreturn iter(self.forms.sort( ...\n\nsort() is a method on a list that sorts it in-place and returns None. You probably meant:\nreturn iter(sorted(self.forms, ...\n\n" ]
[ 7 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0007393615_django_django_forms_python.txt
Q: Getting an error that doesn't seem to make much sense. I keep getting an error that's referencing one of my Dictionaries in the code. But I can't seem to find anything that would be causing the problem. Something is probably slipping past my eyes, but here's the error from command line pdb anyways. To explain what...
Getting an error that doesn't seem to make much sense.
I keep getting an error that's referencing one of my Dictionaries in the code. But I can't seem to find anything that would be causing the problem. Something is probably slipping past my eyes, but here's the error from command line pdb anyways. To explain what's going on, this is a rather large dictionary and it's tell...
[ "Missing comma just before 51.\nIn future, to help trace this kind of error, its helpful not to put everything on one giant line, split it across several lines. That way the arrow will be more helpful.\n", "Element 50 is missing a trailing comma.\nYou can simplify this line to debug such errors. Start by removing...
[ 7, 2, 2 ]
[]
[]
[ "debugging", "dictionary", "pdb", "python" ]
stackoverflow_0007393748_debugging_dictionary_pdb_python.txt
Q: UnicodeDecodeError on import (tweepy) Im trying to use the function "update_profile_background_image" in tweepy and are getting the error: Traceback (most recent call last): File "XXX.py", line 1401, in <module> psn_card.gen_twitter_bg(user_db) File "XXX.py", line 972, in gen_twitter_bg auth_api.update...
UnicodeDecodeError on import (tweepy)
Im trying to use the function "update_profile_background_image" in tweepy and are getting the error: Traceback (most recent call last): File "XXX.py", line 1401, in <module> psn_card.gen_twitter_bg(user_db) File "XXX.py", line 972, in gen_twitter_bg auth_api.update_profile_background_image(file) File "bui...
[ "My guess is that filename is a Unicode string. Unfortunately Tweepy does not support Unicode filenames. Is this a bug? Arguably.\nThe problem is it tries to create the HTTP POST data using the Unicode string verbatim, instead of encoding it down to a byte string:\nbody.append('Content-Disposition: form-data; name=...
[ 4 ]
[]
[]
[ "python", "tweepy", "unicode" ]
stackoverflow_0007392693_python_tweepy_unicode.txt
Q: Regular Expressions Python - Plotting data out of text file I am trying to get some data out of text file with the following format: jvm: 2011-08-29 17:09:54.438864: MemoryStatistics: [290328680, 381288448] moniData: 2011-08-29 17:09:54.438864: Depth: [0] RecordsSent: [1] rdoutData: 2011-08-29 17:09:...
Regular Expressions Python - Plotting data out of text file
I am trying to get some data out of text file with the following format: jvm: 2011-08-29 17:09:54.438864: MemoryStatistics: [290328680, 381288448] moniData: 2011-08-29 17:09:54.438864: Depth: [0] RecordsSent: [1] rdoutData: 2011-08-29 17:09:54.438864: Depth: [0] RecordsSent: [0] rdoutReq: 2011-08...
[ "You can use python's builtin lib re for regular expressions.\nTo get all of the timestamps you can do something like this:\nimport re\n\ndef main():\n file=open(file)\n timestamp=(re.findall(r'\\S+-\\S+-\\d\\d\\s\\d\\d:\\S+:\\S+:',file.read()))\n print timestamp\n\nif __name__=='__main__':\n main()\n\n...
[ 1, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007342716_python_regex.txt
Q: How do you create a PyDev project from existing code? I have created a python project which I began development in TextPad and Command Prompt. http://pydev.org/manual_101_project_conf.html This documentation briefly mentions creating a project with existing code, but I can't make sense of it... Is says: Create the...
How do you create a PyDev project from existing code?
I have created a python project which I began development in TextPad and Command Prompt. http://pydev.org/manual_101_project_conf.html This documentation briefly mentions creating a project with existing code, but I can't make sense of it... Is says: Create the project as if it was a new project, but leave the create d...
[ "From my experience, configuring the PYTHONPATH in PyDev has two main interests :\n\nan obvious one if you have multiple folders containing modules, it allows code running in folder a to import modules in folder b\nanother one, is that PyDev seems to rely on this to enable some parts of code completion, and also co...
[ -1 ]
[]
[]
[ "installation", "project", "pydev", "python" ]
stackoverflow_0007394031_installation_project_pydev_python.txt
Q: Why a Python function copied from class access the class data from outside? How come function x can access the "self" of some object it's not part of??? See the following code: #!/usr/bin/env python class A(object): def __init__(self): self.a = 1 def doit(self): print self.a a = A() x = a.doit x() ...
Why a Python function copied from class access the class data from outside?
How come function x can access the "self" of some object it's not part of??? See the following code: #!/usr/bin/env python class A(object): def __init__(self): self.a = 1 def doit(self): print self.a a = A() x = a.doit x() See: $ ./classes.py 1 $
[ "If you call x(), it simply resolves to calling a.doit(), which is no problem at all to access the contents of A.\n", "It has to do with something call binding. The short and stupid explanation: the method will \"remember\" (it is bound to) where it was created and operate in that context.\nThe longer explanation...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007394075_python.txt
Q: Twisted: disable logging of Twisted-framework classes My Twisted-based client sends UDP packets in a loop. Therefore I'm using the class DatagramProtocol. This is the source: #!/usr/bin/python # -*- coding: utf-8 -*- from twisted.application.service import Service from twisted.internet import reactor from twisted....
Twisted: disable logging of Twisted-framework classes
My Twisted-based client sends UDP packets in a loop. Therefore I'm using the class DatagramProtocol. This is the source: #!/usr/bin/python # -*- coding: utf-8 -*- from twisted.application.service import Service from twisted.internet import reactor from twisted.internet.task import LoopingCall from twisted.internet.prot...
[ "Twisted's logging is all very naive. However, there is no reason this needs to be the case, since twisted.python.log is very featureful, and capable of the kind of selective reporting that you (and others) are interested in.\nA log event is just a dictionary of arbitrary keys and values. The default observer kno...
[ 5 ]
[]
[]
[ "logging", "python", "twistd", "twisted" ]
stackoverflow_0007379712_logging_python_twistd_twisted.txt
Q: python how to make dynamic object name i have a class "karte" i want to know is there a way of dynamic name creation of my new objects normal object creation would be karta=karte() but i am curious in something like this karta[i]=karte() or something like that where i would be the number of for loop. and at th...
python how to make dynamic object name
i have a class "karte" i want to know is there a way of dynamic name creation of my new objects normal object creation would be karta=karte() but i am curious in something like this karta[i]=karte() or something like that where i would be the number of for loop. and at the end i would call object like this karta1....
[ "You can create a list of objects like this:\nkarta = []\nfor i in range(10):\n karta.append(karte())\n\nOr using a list comprehension:\nkarta = [karte() for i in range(10)]\n\nNow you can access the objects like this: karta[i].\nTo accomplish your last example, you have to modify the globals() dictionary. I do ...
[ 14, 6 ]
[]
[]
[ "class", "object", "python", "variables" ]
stackoverflow_0007394301_class_object_python_variables.txt
Q: How to read ASCII data from a serial port into a file in Python I need to read ASCII data including LF and CR from an external device using the serial port of the PC and write it to a file using Python. I just started learning Python but I was able to open up a port but now I'm having trouble with the actual readi...
How to read ASCII data from a serial port into a file in Python
I need to read ASCII data including LF and CR from an external device using the serial port of the PC and write it to a file using Python. I just started learning Python but I was able to open up a port but now I'm having trouble with the actual reading part because I'm not sure how to specify when data is finished and...
[ "Head on over to the pyserial site and start hacking!. Here are examples to get you going.\nIn regards to your question, try the readline() method. You may add the CRLF to the end of the string to write if need be. You can write to the file after each line retrieved. \nWhen the device is finished and the file n...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007394496_python.txt
Q: simplest way to return all of the text between a pair of html tags in BeatifulSoup OK. I have a massive HTML file, and I only want the text that occurs between the tags <center><span style="font-size: 144%;"></span></center> and <dl> <dd><i></i></dd> </dl> I am using Python2.6 and Beautifulsoup, but I have no...
simplest way to return all of the text between a pair of html tags in BeatifulSoup
OK. I have a massive HTML file, and I only want the text that occurs between the tags <center><span style="font-size: 144%;"></span></center> and <dl> <dd><i></i></dd> </dl> I am using Python2.6 and Beautifulsoup, but I have no idea where to begin. I'm assuming it's not difficult?
[ "Try something like:\nsoup = BeautifulSoup.BeautifulSoup(YOUR_HTML)\ntexts = soup.findAll(text=True)\nprint texts\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007394565_python.txt
Q: html in facebook wall posts with graph api? Does anyone know if I can create wall posts with html content using facebook's graph api? And if so, where I could find some documentation/examples? I don't see anything useful here: http://developers.facebook.com/docs/reference/api/post/ It would appear that I can do t...
html in facebook wall posts with graph api?
Does anyone know if I can create wall posts with html content using facebook's graph api? And if so, where I could find some documentation/examples? I don't see anything useful here: http://developers.facebook.com/docs/reference/api/post/ It would appear that I can do this using fbml, but it also appears that they're ...
[ "They're not going to allow you to post HTML to a wall post for two main reasons:-\n\nMalicious users can insert <script>s into the page DOM to do nasty things.\n(rant) Facebook doesn't like formatting in their posts because it makes people look unique.\n\nThe first point is the most important; they won't allow HTM...
[ 5, 2 ]
[]
[]
[ "facebook", "facebook_graph_api", "facebook_wall", "html", "python" ]
stackoverflow_0007394719_facebook_facebook_graph_api_facebook_wall_html_python.txt
Q: Get list based on occurrences in unknown number of sublists I'm looking for a way to make a list containing list (a below) into a single list (b below) with 2 conditions: The order of the new list (b) is based on the number of times the value has occurred in some of the lists in a. A value can only appear once ...
Get list based on occurrences in unknown number of sublists
I'm looking for a way to make a list containing list (a below) into a single list (b below) with 2 conditions: The order of the new list (b) is based on the number of times the value has occurred in some of the lists in a. A value can only appear once Basically turn a into b: a = [[1,2,3,4], [2,3,4], [4,5,6]] # val...
[ "I think this is probably the closest you're going to get:\nfrom collections import defaultdict\n\nd = defaultdict(int)\n\nfor sub in outer:\n for val in sub:\n d[val] += 1\n\nprint sorted(d.keys(), key=lambda k: d[k], reverse = True)\n# Output: [4, 2, 3, 1, 5, 6]\n\nThere is an off chance that the order of ele...
[ 4, 1, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007394474_list_python.txt
Q: What is the best way to share a value by all the generators created by a function? Here I asked a question about izip_longest function from itertools module. The code of it: def izip_longest_from_docs(*args, **kwds): # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- fillvalue = kwds.get('fillvalu...
What is the best way to share a value by all the generators created by a function?
Here I asked a question about izip_longest function from itertools module. The code of it: def izip_longest_from_docs(*args, **kwds): # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- fillvalue = kwds.get('fillvalue') def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): yield counter()...
[ "This has been asked many times in many forms. Read any number of other questions about mutable default arguments and the new Python 3 nonlocal keyword. On Python 2, you could use a function attribute:\ndef sentinel(fillvalue = fillvalue):\n def ret():\n sentinel.counter += 1\n if sentinel.counter ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007394651_python.txt
Q: Painting QTreeViewItem expand buttons and sibling/child lines I am using a QTreeView and a QItemDelegate to reimplement most of the paint routine. However, the expand/collapse buttons and the sibling/child lines are drawn automatically by some other paint routine. What is drawing them, and how can I control it?...
Painting QTreeViewItem expand buttons and sibling/child lines
I am using a QTreeView and a QItemDelegate to reimplement most of the paint routine. However, the expand/collapse buttons and the sibling/child lines are drawn automatically by some other paint routine. What is drawing them, and how can I control it? EDIT: Right now, Qt draws a QTreeView item in this order: [Expand...
[ "You can change those using a style sheet. This is from the Customizing QTreeView example in the style sheet reference:\n QTreeView::branch:has-siblings:!adjoins-item {\n border-image: url(vline.png) 0;\n }\n\n QTreeView::branch:has-siblings:adjoins-item {\n border-image: url(branch-more.png) 0;\n }\n\n QT...
[ 1, 1 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0007288790_pyqt_pyqt4_python_qt_qt4.txt
Q: How to split a CSV row so row[0] is the name and any remaining items are a tuple? I have a csv file in which the first column is the name of a baseball player, and then each subsequent item in the file is a statistic. I'd like to be able to import the file so that the player name was equal to a tuple of the statis...
How to split a CSV row so row[0] is the name and any remaining items are a tuple?
I have a csv file in which the first column is the name of a baseball player, and then each subsequent item in the file is a statistic. I'd like to be able to import the file so that the player name was equal to a tuple of the statistics. Right now when I import the file using this code: Orioles = file("Orioles.csv", "...
[ "Having the player name be it's own variable is not as helpful as you might think: you can't iterate over the collection (because there isn't one), your code is fixed and fragile (you have to add/remove lines when a player name is added or removed from your file, etc.\nIf, however, you have them in a dictionary --...
[ 4, 2 ]
[]
[]
[ "csv", "python", "tuples" ]
stackoverflow_0007394644_csv_python_tuples.txt
Q: How to make multiple web2py apps use the same layout.html? I have three applications, but I want them to use the same layout.html and css. Is there any way to achieve this? EDIT: I put the static folder and layout.html etc in /common/ under the web2py root. Here's what I did in the model: import os global web2py_p...
How to make multiple web2py apps use the same layout.html?
I have three applications, but I want them to use the same layout.html and css. Is there any way to achieve this? EDIT: I put the static folder and layout.html etc in /common/ under the web2py root. Here's what I did in the model: import os global web2py_path web2py_path = os.environ.get('web2py_path', os.getcwd()) ses...
[ "in the root of your web2py folder create a new folder called 'templates'\n/web2py/templates\nput your layout.html there.\nnow in your views do:\n{{extend 'path/to/web2py/templates/layout.html'}}\n\n" ]
[ 5 ]
[]
[]
[ "css", "python", "web2py" ]
stackoverflow_0007395293_css_python_web2py.txt
Q: Python read-file module I have a .zip folder in my current directory. How can I tell python to read the "contents" file in the .zip folder? The contents file has the names of all files in the zip archive. I basically want Python to read the contents file, look for a specific item, such as the word " program logo"...
Python read-file module
I have a .zip folder in my current directory. How can I tell python to read the "contents" file in the .zip folder? The contents file has the names of all files in the zip archive. I basically want Python to read the contents file, look for a specific item, such as the word " program logo" and record to memory the cor...
[ "Zip files are not folders, they are archives. They are files, and you have to open them for reading, like any other files. \nI reckon you should look up the zipfile module. If you actually have a file called \"contents\" in your zip, then\nwith ZipFile('myzipfile.zip', 'r') as z:\n f=z.open(\"contents\",'r')\n ...
[ 1 ]
[]
[]
[ "cmd", "python" ]
stackoverflow_0007395456_cmd_python.txt
Q: Parsing command line arguments in Python: getting a KeyError I am trying execute my Python script as: python series.py supernatural 4 6 Supernatural : TV Series name 4 : season number 6 : episode number Now in my script I am using the above three arguments to fetch the title of the episode: import tvrage.api im...
Parsing command line arguments in Python: getting a KeyError
I am trying execute my Python script as: python series.py supernatural 4 6 Supernatural : TV Series name 4 : season number 6 : episode number Now in my script I am using the above three arguments to fetch the title of the episode: import tvrage.api import sys a = sys.argv[1] b = sys.argv[2] c = sys.argv[3] tem...
[ "The Python TVRage API is expecting integers, not strings (which is what you get from argv):\nname = temp.season(int(b)).episode(int(c))\n\nwill correct the error, if season 4 episode 6 exists.\nYou should take a look at the command line parsing modules that come with Python. For 3.2 / 2.7 or newer, use argparse. F...
[ 3, 3 ]
[]
[]
[ "arguments", "command_line_arguments", "python" ]
stackoverflow_0007395488_arguments_command_line_arguments_python.txt
Q: How do I clear a pygame alpha layer efficiently? I'm trying to write a 2D game using python / pygame that blits several layers on top of one another every screen refresh. My basic setup is (from bottom to top): Background: surface (non-transparent), scrolls at a different rate than rest Midground: SRCALPHA transp...
How do I clear a pygame alpha layer efficiently?
I'm trying to write a 2D game using python / pygame that blits several layers on top of one another every screen refresh. My basic setup is (from bottom to top): Background: surface (non-transparent), scrolls at a different rate than rest Midground: SRCALPHA transparent surface (static) Player / Sprites / Enemies: spr...
[ "I figured out a fast way of clearing a sprites only transparent layer by applying Peter's solution selectively to the layer:\nfor s in self.level.sprites:\n spritelayer.fill((0), s.rect)\n\nThis seems to be working fine (erasing everything each frame) and still runs at 60fps.\n", "The Surface.fill() will clear ...
[ 2, 1 ]
[]
[]
[ "2d", "pygame", "python", "transparency" ]
stackoverflow_0007382246_2d_pygame_python_transparency.txt
Q: How to compile executable for Mac, but from a PC? I need to compile my application for both PC and Mac, but I don't have access to Mac in my area (very rare, mostly PC). My application written in Python with 2 C++ modules, I used pyInstaller for Python and MinGW for C++ in PC, but question is for Mac? What can I d...
How to compile executable for Mac, but from a PC?
I need to compile my application for both PC and Mac, but I don't have access to Mac in my area (very rare, mostly PC). My application written in Python with 2 C++ modules, I used pyInstaller for Python and MinGW for C++ in PC, but question is for Mac? What can I do? is there any OS emulator or something helpful out th...
[ "You can emulate Apple OS and any other OS on VMWare.\n", "You should take a look here, there are a few tools for cross compiling python. I particularly like pyinstaller.\n" ]
[ 2, 0 ]
[]
[]
[ "compilation", "python" ]
stackoverflow_0007393005_compilation_python.txt
Q: Python Module Initialization Is it bad practice to initialize the objects in the module, in the module code? in Module.py: class _Foo(object): def __init__(self): self.x = 'Foo' Foo = _Foo() Than in user code, you could: >>> from Module import Foo >>> print Foo.x 'Foo' >>> ...without having to initi...
Python Module Initialization
Is it bad practice to initialize the objects in the module, in the module code? in Module.py: class _Foo(object): def __init__(self): self.x = 'Foo' Foo = _Foo() Than in user code, you could: >>> from Module import Foo >>> print Foo.x 'Foo' >>> ...without having to initialize the Foo class in the user co...
[ "Typically, you only want to run the minimum necessary to have your module usable. This will have an overall effect on performance (loading time), and can also make debugging easier.\nAlso, usually more than one instance will be created from any given class.\nHaving said that, if you have good reasons (such as onl...
[ 7, 4 ]
[]
[]
[ "object_initialization", "oop", "python" ]
stackoverflow_0007395797_object_initialization_oop_python.txt
Q: How can I specify an AES key in Python? I'm working on converting a Java program into Python and part of its core networking uses AES encryption to handle packets going up and down the line. Java's AES is initialized like so: byte[] key = { 0x13, 0x00, 0x00, 0x00 }; sKeySpec = new SecretKeySpec(key, "AES"); I wan...
How can I specify an AES key in Python?
I'm working on converting a Java program into Python and part of its core networking uses AES encryption to handle packets going up and down the line. Java's AES is initialized like so: byte[] key = { 0x13, 0x00, 0x00, 0x00 }; sKeySpec = new SecretKeySpec(key, "AES"); I want to do the same in Python, and will use PyCr...
[ "Use a string then\nkey = '\\x13\\x00\\x00\\x00'\n\n", "Why Don't you Try using Jython , because You can directly import the .class file without having to re-write it .\n" ]
[ 2, 1 ]
[]
[]
[ "aes", "java", "pycrypto", "python" ]
stackoverflow_0007395874_aes_java_pycrypto_python.txt
Q: Python: Populate or add value to current value in a dictionary I have data in the form of 00 154 01 72 02 93 03 202 04 662 05 1297 00 256 I wish to go through each line and make the value in column 1 the key and the value of column 2 the value also if the current key already exists, mathematically add the new v...
Python: Populate or add value to current value in a dictionary
I have data in the form of 00 154 01 72 02 93 03 202 04 662 05 1297 00 256 I wish to go through each line and make the value in column 1 the key and the value of column 2 the value also if the current key already exists, mathematically add the new value of column 2 to the current value of column 2. Tried this: sea...
[ "This is what collections.defaultdict is for.\nYou can simply do\nd = defaultdict(int)\n\nAnd\nd[a]= d[a] + int(b)\n\nAnd you'll find that it works without any if statement.\n", "d = collections.defaultdict(int)\nfor output in search_results:\n a,b = output.split()\n d[int(a)] += int(b)\n\n" ]
[ 5, 2 ]
[]
[]
[ "add", "dictionary", "python" ]
stackoverflow_0007396007_add_dictionary_python.txt
Q: how to use iterator in recursive function in python? I want to convert my code such that I don't have to use an extra variable (i.e, s in the example below). I know that there is a way to use iterator but I don't know how. Can somebody help? Thanks a bunch. from numbers import Number a = [[[1,2],[3,4]],[[5,6],[7,...
how to use iterator in recursive function in python?
I want to convert my code such that I don't have to use an extra variable (i.e, s in the example below). I know that there is a way to use iterator but I don't know how. Can somebody help? Thanks a bunch. from numbers import Number a = [[[1,2],[3,4]],[[5,6],[7,8]]] def trav(root,s): if isinstance(root,Number): ...
[ "Why not just...\ndef trav(root, s=\"\"):\n\nand then you can omit your s = \"\" line and call it as trav(a)? Also if you were willing to just inline a thing or two, you could do less slicing:\nfrom numbers import Number\n\na = [[[1,2],[3,4]],[[5,6],[7,8]]]\n\n\ndef trav(root, s=\"\"):\n if isinstance(root, Numb...
[ 1 ]
[]
[]
[ "global", "iterator", "python", "recursion", "variables" ]
stackoverflow_0007396073_global_iterator_python_recursion_variables.txt
Q: How to modify group policy object via python ldap? i am trying to link gpos to OUs. Also, i want to add new gpos and modify policy settings/preferences. i am stuck at the latter part. any ideas/tips will be highly appreciated. A: Usually it is just an update to the OU. For instance to set a custom password poli...
How to modify group policy object via python ldap?
i am trying to link gpos to OUs. Also, i want to add new gpos and modify policy settings/preferences. i am stuck at the latter part. any ideas/tips will be highly appreciated.
[ "Usually it is just an update to the OU. For instance to set a custom password policy set the attribute pwdPolicySubentry with the value of a dn that points to the custom policy on the object. This would just be a straight forward modify operation.\n" ]
[ 0 ]
[]
[]
[ "openldap", "python" ]
stackoverflow_0007366065_openldap_python.txt
Q: SQLalchemy issue when extending Pyramid application I have a "Main Application", and in this application I have the following in the init.py file: def main(global_config, **settings): # various config settings config.include(site_configs) def site_configs(config): config.add_route('portfolio', '/portf...
SQLalchemy issue when extending Pyramid application
I have a "Main Application", and in this application I have the following in the init.py file: def main(global_config, **settings): # various config settings config.include(site_configs) def site_configs(config): config.add_route('portfolio', '/portfolio', view='mainapp.views.portfolio', view_r...
[ "Well this really has nothing to do with Pyramid. You have a global variable dbsession that you are attempting to share between different subapps of your application. If the model is the same for all of your applications then you should just have a single initialization function to configure your global in the main...
[ 2 ]
[]
[]
[ "pylons", "pyramid", "python", "sqlalchemy" ]
stackoverflow_0007374612_pylons_pyramid_python_sqlalchemy.txt
Q: Python help ---> random name selection from text file I want to have a list of names such as "john, jack, daniels, whisky, susan, alex" in a .txt file called 'names'. Now, I want to import that file into my 'script' and use the import random module. This is what I have: import random name = ( "jay" , "luis" , "b...
Python help ---> random name selection from text file
I want to have a list of names such as "john, jack, daniels, whisky, susan, alex" in a .txt file called 'names'. Now, I want to import that file into my 'script' and use the import random module. This is what I have: import random name = ( "jay" , "luis" , "bob" , "sofi", "susan" ) x = random.sample(name,input( "pl...
[ "file = open('myFile.txt', 'r')\nnames = file.read().split(',')\nfile.close()\n\nUse that in place of your name = ... line and you should be good to go.\nYou can read more about reading and writing files in Python here.\nNote that I assumed you'll have a comma-delimited list in the file. You can also put each name ...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "generator", "module", "names", "python", "random" ]
stackoverflow_0007396071_generator_module_names_python_random.txt
Q: In which cases can I reuse a django project for multiple applications? I just finished doing the tutorial django app. I now want to build my own app. Should I just create a new app within the tutorial project folder or should I create a new project folder with a new app? I am unsure in which cases it makes sense t...
In which cases can I reuse a django project for multiple applications?
I just finished doing the tutorial django app. I now want to build my own app. Should I just create a new app within the tutorial project folder or should I create a new project folder with a new app? I am unsure in which cases it makes sense to re-use a project and create multiple apps under that project vs. making ne...
[ "You don't need to create a project for each app. When you create a project, you can define new apps inside a project if you want, in fact the manage.py inside the project folder is the same as the django-admin.py outside. So you can startapp directly using django-admin.py:\n$ django-admin.py startproject foo\n$ ...
[ 2, 1 ]
[]
[]
[ "django", "python", "web_applications" ]
stackoverflow_0007396170_django_python_web_applications.txt
Q: Can namespaces enable multiple domains? My gae app serves multiple domains by if..else.. conditions rather than namespaces. I see someone else solved it with namespaces "I have a single app with multiple namespaces defined. I'd like to set up multiple domains a.com b.com c.com and have the app detect the domain a...
Can namespaces enable multiple domains?
My gae app serves multiple domains by if..else.. conditions rather than namespaces. I see someone else solved it with namespaces "I have a single app with multiple namespaces defined. I'd like to set up multiple domains a.com b.com c.com and have the app detect the domain and write the domain's data into its respect...
[ "Yes, namespaces are ideally suited to what you're doing. Simply store configuration data like admin emails in a per-domain configuration record, and store all the records for a given domain in a namespace named after that domain.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "namespaces", "python" ]
stackoverflow_0007395839_google_app_engine_google_cloud_datastore_namespaces_python.txt
Q: Python list object arrives as a text string when sent via CGI I have a list object that I'm sending to a script using CGI. The list is being sent using a hidden field in an HTML form. When I extract the object in the receiving script using my_list = form.getlist['name_of_hidden_field'], the list is stored as a s...
Python list object arrives as a text string when sent via CGI
I have a list object that I'm sending to a script using CGI. The list is being sent using a hidden field in an HTML form. When I extract the object in the receiving script using my_list = form.getlist['name_of_hidden_field'], the list is stored as a single large text string in the first element of my_list rather than...
[ "You need to send the list as a bunch of different inputs with the same name for getlist to get the elements:\nmy_list = ['string1', 'string2', 'string3']\nprint '<form name=\"input\" action=\"my_script.py\">'\nfor element in my_list:\n print '<input type=\"hidden\" name=\"my_list\" value=\"%s\">' % (cgi.escape(...
[ 1, 1 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0007396716_cgi_python.txt
Q: haystack solr search ALL fields I have a solr search engine set up with multiple fields and I want to be able to search ALL fields. I can do a .filter(content='string') but this only searches whatever fields are in the document=True EDIT Also, some of the non document=True fields have different filters/tokenisers ...
haystack solr search ALL fields
I have a solr search engine set up with multiple fields and I want to be able to search ALL fields. I can do a .filter(content='string') but this only searches whatever fields are in the document=True EDIT Also, some of the non document=True fields have different filters/tokenisers applied so im guessing that would not...
[ "Maybe you can make a second field with 'use_template' and a template displaying ALL fields.\nI never tried to do this, but this sound a good way to do it to me.\nEDIT since OP comment:\nThen my best bet is to eaither sublass SearchQueryset to add a method or to create a function that will loop and all fields in yo...
[ 2, 1, 1 ]
[]
[]
[ "django", "django_haystack", "python", "solr" ]
stackoverflow_0006367614_django_django_haystack_python_solr.txt
Q: How do I close the stdout-pipe when killing a process started with python subprocess Popen? I wonder if it is possible to shut down the communication pipe when killing a subprocess started in a different thread. If I do not call communicate() then kill() will work as expected, terminating the process after one sec...
How do I close the stdout-pipe when killing a process started with python subprocess Popen?
I wonder if it is possible to shut down the communication pipe when killing a subprocess started in a different thread. If I do not call communicate() then kill() will work as expected, terminating the process after one second instead of five. I found a discussion of a similar problem here, but I got no real answers. I...
[ "I think the problem is that process.kill() only kills the immediate child process (bash), not the sub-processes of the bash script.\nThe problem and solution are described here:\n\nhttp://www.doughellmann.com/PyMOTW/subprocess/#process-groups-sessions\nHow to terminate a python subprocess launched with shell=True\...
[ 6, 0 ]
[ "It looks like you may be a victim of Python's super coarse grained concurrency. Change your script to this:\n#!/bin/bash\necho \"sleeping five\"\nsleep 5\necho \"sleeping five again\"\nsleep 5\necho \"slept five\"\n\nAnd then the output becomes:\nprocess: sleeping five\n\nreal 0m5.134s\nuser 0m0.000s\nsys ...
[ -1 ]
[ "kill", "pipe", "python", "stdout", "subprocess" ]
stackoverflow_0001624254_kill_pipe_python_stdout_subprocess.txt
Q: django admin permissions - can edit user but can't edit his permissions - how to do it? I gave the editors such permissions: auth | user | can add/change user - ON auth | permissions | can add/change permissions - OFF Still, when editing, they can change their permissions (and allow themselves actions they shoul...
django admin permissions - can edit user but can't edit his permissions - how to do it?
I gave the editors such permissions: auth | user | can add/change user - ON auth | permissions | can add/change permissions - OFF Still, when editing, they can change their permissions (and allow themselves actions they shouldn't do). I've found a ticket from 2yrs ago: http://code.djangoproject.com/ticket/6519 and it...
[ "The code below gives you ability to override the formset, this essentially limits the ability for non-superusers to edit permissions. They can still create users, but they just can't modify permissions. They can even edit users just fine.\n#admin.py\n\nfrom django.utils.translation import gettext_lazy as _\nfrom d...
[ 3, 2 ]
[]
[]
[ "django", "django_admin", "permissions", "python" ]
stackoverflow_0001825771_django_django_admin_permissions_python.txt
Q: javascript to execute a python script on user's computer and retrieve the output Is it possible to write javascript that will execute a python script with a pre-set file location in a user's local hard disk ... and then collect the output for processing ? Something like http://www.jailbreakme.com//# A: No it is ...
javascript to execute a python script on user's computer and retrieve the output
Is it possible to write javascript that will execute a python script with a pre-set file location in a user's local hard disk ... and then collect the output for processing ? Something like http://www.jailbreakme.com//#
[ "No it is not possible. You cannot cause arbitrary programs to be executed on a user's computer without the user installing it, otherwise this would be a grievous security vulnerability.\n", "If you're talking about Javascript run through a browser - no. The browsers will contain javascript execution in a sandbo...
[ 2, 0, 0, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0007396840_javascript_python.txt
Q: Python & GTK3: How to create a Liststore In PyGtk I always used this to create a ListStore with an Image (using it with an IconView for displaying files): store = gtk.ListStore(str, gtk.gdk.Pixbuf, bool) But I can't figure out how to do this with Python 3 and PyGObject. A: Here's how: from gi.repository import ...
Python & GTK3: How to create a Liststore
In PyGtk I always used this to create a ListStore with an Image (using it with an IconView for displaying files): store = gtk.ListStore(str, gtk.gdk.Pixbuf, bool) But I can't figure out how to do this with Python 3 and PyGObject.
[ "Here's how:\nfrom gi.repository import Gtk, GdkPixbuf\nstore = Gtk.ListStore(str, GdkPixbuf.Pixbuf, bool)\n\n" ]
[ 8 ]
[]
[]
[ "gtk3", "pygobject", "python" ]
stackoverflow_0007396723_gtk3_pygobject_python.txt
Q: Connect to MySQL database from Python I have a database set up in MySql Workbench and I want to connect and query the database from my python script. I have no idea how to go about it. A: You want MySQLdb. But do yourself a favour and look into one of the excellent Python wrappers/ORMs: SQLAlchemy, SQLObject, or...
Connect to MySQL database from Python
I have a database set up in MySql Workbench and I want to connect and query the database from my python script. I have no idea how to go about it.
[ "You want MySQLdb.\nBut do yourself a favour and look into one of the excellent Python wrappers/ORMs: SQLAlchemy, SQLObject, or Django.\n", "Look at Connector/Python (written by Geert). It is a pure Python implementation of the MySQL protocol, which means that it installs wherever Python installs.\nYou can find i...
[ 2, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0007393429_mysql_python.txt
Q: Should I extract values from Python dictionaries into object attributes? I have a Python class that is initialized with a dictionary of settings, like this: def __init__(self, settings): self._settings = settings Settings dictionary contains 50-100 different parameters that are used quite a lot in other metho...
Should I extract values from Python dictionaries into object attributes?
I have a Python class that is initialized with a dictionary of settings, like this: def __init__(self, settings): self._settings = settings Settings dictionary contains 50-100 different parameters that are used quite a lot in other methods: def MakeTea(self): tea = Tea() if self._settings['use_sugar']: ...
[ "You're comparing attribute access (self.setting) with attribute access (self.settings) plus a dictionary lookup (settings['setting']). Classes are actually implemented as dictionaries, so the problem reduces to two dictionary lookups vs. one. One lookup will be faster.\nA simpler and faster way to copy an initiali...
[ 4, 0 ]
[]
[]
[ "dictionary", "performance", "python" ]
stackoverflow_0007397599_dictionary_performance_python.txt
Q: Converting string representation of time to date time in app engine In standard python, I can convert a string representation of time into datetime doing this: date_string = u'Tue, 13 Sep 2011 02:38:59 GMT'; date_object = datetime.strptime(date_string, '%a, %d %b %Y %H:%M:%S %Z'); This works fine until I invoke t...
Converting string representation of time to date time in app engine
In standard python, I can convert a string representation of time into datetime doing this: date_string = u'Tue, 13 Sep 2011 02:38:59 GMT'; date_object = datetime.strptime(date_string, '%a, %d %b %Y %H:%M:%S %Z'); This works fine until I invoke the same over app engine where I get the error: time data did not match fo...
[ "Your error message indicates that you're not really passing Tue, 13 Sep 2011 02:38:59 GMT, but 2011-09-13 02:38:59. Are you sure you pass the correct parameters to strptime?\nMy python works just fine for the following:\ndatetime.strptime(u'Tue, 13 Sep 2011 02:38:59 GMT', \"%a, %d %b %Y %H:%M:%S %Z\")\n# returns d...
[ 1 ]
[]
[]
[ "date_formatting", "python" ]
stackoverflow_0007396497_date_formatting_python.txt
Q: Matching case sensitive unicode strings with regular expressions in Python Suppose I want to match a lowercase letter followed by an uppercase letter, I could do something like re.compile(r"[a-z][A-Z]") Now I want to do the same thing for unicode strings, i.e. match something like 'aÅ' or 'yÜ'. Tried re.compile...
Matching case sensitive unicode strings with regular expressions in Python
Suppose I want to match a lowercase letter followed by an uppercase letter, I could do something like re.compile(r"[a-z][A-Z]") Now I want to do the same thing for unicode strings, i.e. match something like 'aÅ' or 'yÜ'. Tried re.compile(r"[a-z][A-Z]", re.UNICODE) but that does not work. Any clues?
[ "This is hard to do with Python regex because the current implementation doesn't support Unicode property shortcuts like \\p{Lu} and \\p{Ll}. \n[A-Za-z] will of course only match ASCII letters, regardless of whether the Unicode option is set or not.\nSo until the re module is updated (or you install the regex packa...
[ 7 ]
[]
[]
[ "case_insensitive", "character_properties", "python", "regex", "unicode" ]
stackoverflow_0007397879_case_insensitive_character_properties_python_regex_unicode.txt
Q: Generate calendar Python webpage Re-phrasing my Question, as suggested by moderator. I need to create a calendar with Python & CSS for a web page, I tried the following in Python: #!/usr/bin/env python import os, re, sys, calendar from datetime import datetime myCal = calendar.monthcalendar(2011,9) html += st...
Generate calendar Python webpage
Re-phrasing my Question, as suggested by moderator. I need to create a calendar with Python & CSS for a web page, I tried the following in Python: #!/usr/bin/env python import os, re, sys, calendar from datetime import datetime myCal = calendar.monthcalendar(2011,9) html += str(myCal) mycal = myCal[:1] cal1 = myCa...
[ "I'm not sure exactly what you are looking for, this produces a table with the 3 rows you describe, but for the entire month (not just the first 15 days). I may be starting point\nimport calendar\nimport itertools\n\nblank = \"&nbsp;\"\n\nmyCal = calendar.monthcalendar(2011,9)\nday_names = itertools.cycle(['mon','t...
[ 3, 1 ]
[]
[]
[ "calendar", "python", "webpage" ]
stackoverflow_0007397031_calendar_python_webpage.txt
Q: Read .plist file data and record to memory with python I have a zip file. In that zip, I have a plist file, "Restore.plist". How can I tell python to read that .plist file and stop when it reaches this part: <key>SupportedProductTypes</key> <array> <string>iPhone3,1</string> </array> I Want to tell Python t...
Read .plist file data and record to memory with python
I have a zip file. In that zip, I have a plist file, "Restore.plist". How can I tell python to read that .plist file and stop when it reaches this part: <key>SupportedProductTypes</key> <array> <string>iPhone3,1</string> </array> I Want to tell Python to stop at the "SupportedProductTypes" key and record its cor...
[ "plistlib in the Python standard library deals with .plist files. Refer to this PyMOTW article for a quick tutorial.\nSee also the ZipFile class in the zipfile module (also in the Python standard library) for reading from ZIP files.\n", "Try with xml :\nimport xml.etree.ElementTree as ET\n\ntree = ET.parse(\"keys...
[ 3, 1 ]
[]
[]
[ "cmd", "python" ]
stackoverflow_0007398395_cmd_python.txt
Q: How to create a status icon in either Notification Area or Indicator Applet? I was wondering that I could not find a tutorial on how to do this. Many of the application on my system has notification area icons and a simple popup menu is attached with most of them. Can anyone tell me how to do this? If some one can...
How to create a status icon in either Notification Area or Indicator Applet?
I was wondering that I could not find a tutorial on how to do this. Many of the application on my system has notification area icons and a simple popup menu is attached with most of them. Can anyone tell me how to do this? If some one can do an example that works with Linux + GTK + Glade + Python, that will be really g...
[ "Try this StatusIcon tutorial.\n" ]
[ 1 ]
[]
[]
[ "glade", "gtk", "linux", "python" ]
stackoverflow_0007397969_glade_gtk_linux_python.txt
Q: Http connect request from multiple IP address to destination in python conn=httlib.HTTPConnection(self.proxy) Self.proxy has destination ip and port. I want to do multiple connection from multiple IP addresses to destination How to specify the source IP while connect request.Please help me out. Thanks in Advance. ...
Http connect request from multiple IP address to destination in python
conn=httlib.HTTPConnection(self.proxy) Self.proxy has destination ip and port. I want to do multiple connection from multiple IP addresses to destination How to specify the source IP while connect request.Please help me out. Thanks in Advance.
[ "I assume that you have multiple network connections on the same computer (i.e. a wired and wireless connection) and you want to make sure that your connect goes over a specific interface.\nIn general you cannot do this. How your traffic is sent to a specific ip address, and therefore what source ip address it show...
[ 0, 0 ]
[]
[]
[ "connect", "http", "python" ]
stackoverflow_0007387190_connect_http_python.txt
Q: What's the difference between using easyintall-2.6 and easy install-2.7 to install ipython I install ipython on Mac OS X Lion following this: How to install iPython on Snow Leopard As I doing this on my Mac sudo /usr/bin/easy_install-2.6 python Turns out I originally have easy_install-2.5, 2.6, 2.7 installed! Then...
What's the difference between using easyintall-2.6 and easy install-2.7 to install ipython
I install ipython on Mac OS X Lion following this: How to install iPython on Snow Leopard As I doing this on my Mac sudo /usr/bin/easy_install-2.6 python Turns out I originally have easy_install-2.5, 2.6, 2.7 installed! Then I choose easy_install-2.7 to install python, it works. But what if I install ipython with 2.5, ...
[ "It will install IPython for the different versions of Python installed on the system. Starting IPython for each version will bring up a shell for the appropriate version of Python.\n" ]
[ 1 ]
[]
[]
[ "easy_install", "ipython", "macos", "python" ]
stackoverflow_0007398818_easy_install_ipython_macos_python.txt
Q: sleep of non-blocking calls I am looking for an optimum sleep value to receive data from a non-blocking socket. E.g: while True: data=s.recv(1024) if not data: time.sleep(10) #10ms else: pass #... No sleep would lead into 100% CPU usage, so any idea how to get the best CPU Usage and b...
sleep of non-blocking calls
I am looking for an optimum sleep value to receive data from a non-blocking socket. E.g: while True: data=s.recv(1024) if not data: time.sleep(10) #10ms else: pass #... No sleep would lead into 100% CPU usage, so any idea how to get the best CPU Usage and bandwith? How long has a sleep to ...
[ "If you plan to use sleep(), why don't you just use blocking sockets?\n", "You shouldn't be doing that yourself. Use the select call, with a timeout if you need your code to wake up every so often even if no data was received. \nBTW, TCP_NODELAY is of the sending side, won't influence your reads.\n", "Use selec...
[ 3, 2, 1 ]
[]
[]
[ "nonblocking", "python", "sockets", "thread_sleep" ]
stackoverflow_0007399374_nonblocking_python_sockets_thread_sleep.txt
Q: Parsing crontab-style lines I need to parse a crontab-like schedule definition in Python (e.g. 00 3 * * *) and get where this should have last run. Is there a good (preferably small) library that parses these strings and translates them to dates? A: Perhaps the python package croniter suits your needs. Usage exa...
Parsing crontab-style lines
I need to parse a crontab-like schedule definition in Python (e.g. 00 3 * * *) and get where this should have last run. Is there a good (preferably small) library that parses these strings and translates them to dates?
[ "Perhaps the python package croniter suits your needs.\nUsage example:\n>>> import croniter\n>>> import datetime\n>>> now = datetime.datetime.now()\n>>> cron = croniter.croniter('45 17 */2 * *', now)\n>>> cron.get_next(datetime.datetime)\ndatetime.datetime(2011, 9, 14, 17, 45)\n>>> cron.get_next(datetime.datetime)...
[ 80, 1 ]
[]
[]
[ "crontab", "python" ]
stackoverflow_0007390170_crontab_python.txt
Q: xpath not operator and multiple select for link in hxs.select("//a[contains(@href,'/women-')]"): if ('.a[notcontains(@href,"/women-shoes")]'): self.log("LINKS2 :: %s" % attribute::href()) The first statement is selecting all the hyperlinks which contain /women- in their url. Basically I want to select...
xpath not operator and multiple select
for link in hxs.select("//a[contains(@href,'/women-')]"): if ('.a[notcontains(@href,"/women-shoes")]'): self.log("LINKS2 :: %s" % attribute::href()) The first statement is selecting all the hyperlinks which contain /women- in their url. Basically I want to select all links which have /women- in their url b...
[ "I think it would be more optimized as it will see first url not contains /women-shoes and then check whether it contains /women- :\nqueryStr = \"//a[not(contains(@href,'/women-shoes')) and contains(@href,'/women-') ]\n\n", "Why not filter within your query?\nqueryStr = \"//a[contains(@href,'/women-') and not(con...
[ 1, 0 ]
[]
[]
[ "python", "xpath" ]
stackoverflow_0007397903_python_xpath.txt
Q: Is this an insane implementation of producer consumer type thing? # file1.py class _Producer(self): def __init__(self): self.chunksize = 6220800 with open('/dev/zero') as f: self.thing = f.read(self.chunksize) self.n = 0 self.start() def start(self): import subprocess import th...
Is this an insane implementation of producer consumer type thing?
# file1.py class _Producer(self): def __init__(self): self.chunksize = 6220800 with open('/dev/zero') as f: self.thing = f.read(self.chunksize) self.n = 0 self.start() def start(self): import subprocess import threading def produce(): self._proc = subprocess.Popen(['produ...
[ "Given your (unusual!) requirements, your implementation seems correct. In particular,\n\nIf you're only updating one attribute, the Python GIL should be sufficient. Single bytecode instructions are atomic.\nIf you do anything more complex, add locking! It's basically harmless anyway - if you cared about performanc...
[ 1 ]
[]
[]
[ "observer_pattern", "producer_consumer", "python" ]
stackoverflow_0007397815_observer_pattern_producer_consumer_python.txt
Q: Pyqt treeview with checkboxes I'm new to PyQt and I'm trying to do some specyfic stuff but without luck :( I'm trying to create a expandable tree of items (treeview) with pyqt, but I want, that on the left of each name there will be a non-exclusive checkbox. I found some codes but for now the best result was tree ...
Pyqt treeview with checkboxes
I'm new to PyQt and I'm trying to do some specyfic stuff but without luck :( I'm trying to create a expandable tree of items (treeview) with pyqt, but I want, that on the left of each name there will be a non-exclusive checkbox. I found some codes but for now the best result was tree with only checkboxes :( Does somebo...
[ "Qt's ItemViews draw checkboxes next to the text, if the ItemIsUserCheckable flag is set for the item in the model. If you write your own model you must implement QAbstractItemModel::flags, if you use QTreeWidget you can set the flags for each QTreeWidgetItem.\n" ]
[ 0 ]
[]
[]
[ "checkbox", "pyqt", "python", "treeview" ]
stackoverflow_0006819763_checkbox_pyqt_python_treeview.txt
Q: Compressing large data arrays as PNG files As output files from a measurement I get large ASCII files, containing a 1000x1000 table of float numbers (~15MB). As those are impractical in large numbers (ie another 1000 measurements per series) I would like to effectively compress them. Exploiting the data structure ...
Compressing large data arrays as PNG files
As output files from a measurement I get large ASCII files, containing a 1000x1000 table of float numbers (~15MB). As those are impractical in large numbers (ie another 1000 measurements per series) I would like to effectively compress them. Exploiting the data structure (basically a 1 MP map -> picture) I tried to use...
[ "The fact that the png is so small is that it uses the zlib library. I think you would rather use that library instead of the png wrapper, it will be less confusing.\nSee http://zlib.net.\nIf you still want to use the png library, the fact that you have 4-tuples is because png images usually have an alpha channel, ...
[ 3, 0 ]
[]
[]
[ "compression", "matplotlib", "png", "python" ]
stackoverflow_0007399471_compression_matplotlib_png_python.txt
Q: converting binary string into float I have an object that I am storing bits in. class Bitset: def __init__(self, bitstring): self.bitlist = [] for char in bitstring: self.bitlist.append(int(char)) def flipBit(self, index): val = self.bitlist[index] val = (val +...
converting binary string into float
I have an object that I am storing bits in. class Bitset: def __init__(self, bitstring): self.bitlist = [] for char in bitstring: self.bitlist.append(int(char)) def flipBit(self, index): val = self.bitlist[index] val = (val + 1) % 2 self.bitlist[index] = val...
[ "Here is a solution that works. as_float32 could be extended to as_float64 by replacing \"I\" with \"L\" and \"f\" with \"d\". See the struct documentation for an explanation.\ndef as_float32(self):\n \"\"\"\n See: http://en.wikipedia.org/wiki/IEEE_754-2008\n \"\"\"\n from struct import pack,unpack\n ...
[ 5, 5 ]
[]
[]
[ "python" ]
stackoverflow_0007395806_python.txt
Q: Unwrapping a list from the inside I am updating a legacy Python script, and was wondering if it is possible to unwrap a list from inside another list, or more generally to unwrap a list into just its elements. My specific problem is that I have a large list, and now am being passed another list to place in the mi...
Unwrapping a list from the inside
I am updating a legacy Python script, and was wondering if it is possible to unwrap a list from inside another list, or more generally to unwrap a list into just its elements. My specific problem is that I have a large list, and now am being passed another list to place in the middle of this list, instead of a single ...
[ "It's not entirely clear what you mean - how are you determining where to place the list? - but you can use slicing to do this.\noriginal_list = [1, 2, 3, 4, 5]\nnew_list = [2, 3, 4]\n\noriginal_list[3:3] = new_list\n\n" ]
[ 2 ]
[]
[]
[ "list", "performance", "python" ]
stackoverflow_0007399823_list_performance_python.txt
Q: Python - Writing a folder and its contents to a ZipFile Is it possible to write a folder and its contents to an existing ZipFile? I've been messing around with this for a while and can only manage to write the folder structure to the archive, anything inside the folder isn't copied. I don't want to point to a sp...
Python - Writing a folder and its contents to a ZipFile
Is it possible to write a folder and its contents to an existing ZipFile? I've been messing around with this for a while and can only manage to write the folder structure to the archive, anything inside the folder isn't copied. I don't want to point to a specific file, because the idea is that the folder contents can...
[ "Use os.walk:\nimport os\nfor dirpath,dirs,files in os.walk('A Folder/Another folder'):\n for f in files:\n fn = os.path.join(dirpath, f)\n myzipfile.write(fn)\n\n" ]
[ 8 ]
[]
[]
[ "copy", "directory", "python", "zip" ]
stackoverflow_0007400165_copy_directory_python_zip.txt
Q: Can a depth-first search using a stack return a path to the goal? I'd like to use a stack and return a path, but I'm thinking it's not possible. A node must be called directly by its parent so that it can receive the path behind it, whereas when this node is pushed onto a stack, it loses the path so far. Using a ...
Can a depth-first search using a stack return a path to the goal?
I'd like to use a stack and return a path, but I'm thinking it's not possible. A node must be called directly by its parent so that it can receive the path behind it, whereas when this node is pushed onto a stack, it loses the path so far. Using a stack would result in a node being evaluated in isolation, and I couldn...
[ "\"A node must be called directly by its parent so that it can receive the path behind it,\" <- This seems okay.\nwhereas when this node is pushed onto a stack, it loses the path so far. <- This isn't anything to worry about I believe.\nWhat you can do is to recursively build up the stack with something like\ndef m...
[ 0, 0 ]
[]
[]
[ "depth_first_search", "python", "stack" ]
stackoverflow_0007396803_depth_first_search_python_stack.txt
Q: How to dynamically create a three-dimensional array If I want to a array, for example: [ [ [6,3,4], [5,2] ], [ [8,5,7], [11,3] ] ] And I just give you a simple example. In fact, the number of array of each dimensional will be changed with different conditions. And I...
How to dynamically create a three-dimensional array
If I want to a array, for example: [ [ [6,3,4], [5,2] ], [ [8,5,7], [11,3] ] ] And I just give you a simple example. In fact, the number of array of each dimensional will be changed with different conditions. And I don't want to use multiplication of list. I want to cre...
[ "Use a mapping from your multi-dimensional index to your values. Don't use a list of lists of lists.\narray_3d = {\n (0,0,0): 6, (0,0,1): 3, (0,0,2): 4,\n (0,1,0): 5, (0,1,1): 2,\n (1,0,0): 8, (1,0,1): 5, (1,0,2): 7,\n (1,1,0): 11,(1,1,1): 3 \n}\n\nNow you don't have to worry about \"pre-allocating\" a...
[ 6, 1 ]
[ "Um, pretty much the way you'd think. In Python they're called lists, not arrays, but you just have a triple-nested list, like,\nthreeDList = [[[]]]\n\nand then you use three indices to identify elements, like\nthreeDList[0][0].append(1)\nthreeDList[0][0].append(2)\n#threeDList == [[[1,2]]]\nthreeDList[0][0][1] = 3...
[ -2 ]
[ "arrays", "multidimensional_array", "python" ]
stackoverflow_0007396199_arrays_multidimensional_array_python.txt
Q: I am trying to sort a linked list in descending order Can you please help me, i am trying to sort the linked lists according to the documentation in the add function but i am getting an error which says: f.add('b', 2) File "", line 69, in add AttributeError: 'NoneType' object has no attribute 'next' how can i avoi...
I am trying to sort a linked list in descending order
Can you please help me, i am trying to sort the linked lists according to the documentation in the add function but i am getting an error which says: f.add('b', 2) File "", line 69, in add AttributeError: 'NoneType' object has no attribute 'next' how can i avoid this? Thankyou. class Frequency(object): """ Sto...
[ "In the lines\ncurrent = current.next\nnext1 = current.next\n\nwhat happens if current.next == None?\n\nI don't know if you are doing this as a Python exercise or because you actually need the functionality; if the latter, there is already a built-in class that does this for you. It's collections.Counter (in Python...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007400334_python.txt
Q: Fastest/most efficient in App Engine, local file read or memcache hit? I have a couple of smaller asset files (text templates typically 100 - a few K bytes) in my app that I'm considering caching using memcached. But does anyone here know if loading a local file or requesting it from memcache is the fastest/most r...
Fastest/most efficient in App Engine, local file read or memcache hit?
I have a couple of smaller asset files (text templates typically 100 - a few K bytes) in my app that I'm considering caching using memcached. But does anyone here know if loading a local file or requesting it from memcache is the fastest/most resource efficient? (I'll be using the Python version of App Engine)
[ "If they are just few kbytes I would load them on the instance memory; amongst the storage choices (Memcache, Datastore, Blobstore and so on) on Google App Engine , instance memory option shoud be the fastest.\n" ]
[ 6 ]
[]
[]
[ "google_app_engine", "performance", "python" ]
stackoverflow_0007399965_google_app_engine_performance_python.txt
Q: Library for Python: How to call C++ functions from Python program? There is a library for Python that enables the calling ability (can call functions in C++ format without extern "C". Please, could you remind me the name of the library? I forgot it's name and can't find it. It's not Boost.Python. Thank you very mu...
Library for Python: How to call C++ functions from Python program?
There is a library for Python that enables the calling ability (can call functions in C++ format without extern "C". Please, could you remind me the name of the library? I forgot it's name and can't find it. It's not Boost.Python. Thank you very much. Your answer will be rewarded.
[ "Are you thinking of Boost.Python?\n", "Perhaps you are thinking of SWIG.\n", "Also, ctypes lets you access dlls and wrap c code\nctypes doc\n", "SWIG, Boost.Python, SIP, Shiboken, PyBindgen, ...\nSWIG and Boost.Python are most popular, i.e. they have the largest user base and the most active development team...
[ 2, 2, 2, 1 ]
[]
[]
[ "c++", "dll", "python", "shared_libraries" ]
stackoverflow_0007393672_c++_dll_python_shared_libraries.txt
Q: Python XML question I have an XML document as a str. Now, in the XSD <foo> is unbounded, and while most of the time there is only 1, there COULD be more. I'm trying to use ElementTree, but am running into an issue: >>> from xml.etree.ElementTree import fromstring >>> >>> xml_str = """<?xml version="1.0"?> ... <fo...
Python XML question
I have an XML document as a str. Now, in the XSD <foo> is unbounded, and while most of the time there is only 1, there COULD be more. I'm trying to use ElementTree, but am running into an issue: >>> from xml.etree.ElementTree import fromstring >>> >>> xml_str = """<?xml version="1.0"?> ... <foo> ... <bar> ... ...
[ "Each XML document is supposed to have exactly one root element. You will need to adjust your XML if you want to support multiple foo elements.\n", "Alas, wrapping the element in an ElementTree with tree = ElementTree(el) and trying tree.findall('//foo') doesn't seem to work either (it seems you can only search \...
[ 3, 2 ]
[]
[]
[ "elementtree", "python", "xml", "xml_parsing" ]
stackoverflow_0007395739_elementtree_python_xml_xml_parsing.txt
Q: Eclipse, PyDev Syntax Coloring In Preferences-PyDev-Editor-"Appearance Color Options" I can edit colors. I can edit the color of "keywords" for instance. Is there a way to edit color of a specific keyword, say "range"? A: There's currently no such feature (i.e.: the keywords are all 'hardcoded' to a single color...
Eclipse, PyDev Syntax Coloring
In Preferences-PyDev-Editor-"Appearance Color Options" I can edit colors. I can edit the color of "keywords" for instance. Is there a way to edit color of a specific keyword, say "range"?
[ "There's currently no such feature (i.e.: the keywords are all 'hardcoded' to a single color).\nIf you fell that this is really needed, please create a feature request explaining your use-case in the pydev tracker. (see: http://pydev.org/about.html)\n" ]
[ 3 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0005425589_eclipse_pydev_python.txt
Q: Creating a matrix I want to my program to take 25 letters as input and put them in some sort of list so that i can make rules for what letter that can connect with another until and get three words from it that is not overlapping. What i did was this: def matris(): matris = [[],[],[],[],[]] counter = 0 ...
Creating a matrix
I want to my program to take 25 letters as input and put them in some sort of list so that i can make rules for what letter that can connect with another until and get three words from it that is not overlapping. What i did was this: def matris(): matris = [[],[],[],[],[]] counter = 0 counter2 = 0 count...
[ "Don't think I get the question. \nHere are however some snippets to get you started.\nJust read 25 letters in one go and use a partitioning generator as described here\nuse split to send it to the generator below.\ndef chunks(l, n):\n \"\"\" Yield successive n-sized chunks from l.\n \"\"\"\n for i in xran...
[ 1 ]
[]
[]
[ "class", "dictionary", "matrix", "python", "vector" ]
stackoverflow_0007400141_class_dictionary_matrix_python_vector.txt
Q: Python swf manipulation I need some info about how to parse(transform), a .swf file to xml, manipulate some data, and reconstructed to a new .swf file. Some python library or ideas? Thanks A: I don't know which data you want to update, but this tool can be usefull http://www.swftools.org
Python swf manipulation
I need some info about how to parse(transform), a .swf file to xml, manipulate some data, and reconstructed to a new .swf file. Some python library or ideas? Thanks
[ "I don't know which data you want to update, but this tool can be usefull\nhttp://www.swftools.org\n" ]
[ 0 ]
[]
[]
[ "flash", "parsing", "python", "xml" ]
stackoverflow_0007399427_flash_parsing_python_xml.txt
Q: Fitting shapes into a given area, finding best fit How would you use python to work out how many blocks of a given size would fit into an area of a given size. Lets say I have a rectangle of X x Y and I have an area of x1 x y1. How would I work out how many of the rectangle would fit into that area and what would ...
Fitting shapes into a given area, finding best fit
How would you use python to work out how many blocks of a given size would fit into an area of a given size. Lets say I have a rectangle of X x Y and I have an area of x1 x y1. How would I work out how many of the rectangle would fit into that area and what would be the best fit?
[ "This is an instance of a Packing problem. A nice algorithm for packing rectangles inside of a rectangle is described here. You'll need to write it in python, obviously.\n" ]
[ 4 ]
[]
[]
[ "geometry", "python" ]
stackoverflow_0007400730_geometry_python.txt
Q: Alternative to compile python for arm-none-linux-gnueabi-g++ in order to get the LIBs I have a C++ wrapper for a Python module. In order to compile my C++ code, I need the libs of Python. Code compiles on my installation Ubuntu, on g++. Now I want to compile $> make CXX=arm-none-linux-gnueabi-g++ Got arm-none-li...
Alternative to compile python for arm-none-linux-gnueabi-g++ in order to get the LIBs
I have a C++ wrapper for a Python module. In order to compile my C++ code, I need the libs of Python. Code compiles on my installation Ubuntu, on g++. Now I want to compile $> make CXX=arm-none-linux-gnueabi-g++ Got arm-none-linux-gnueabi-g++ on my path. Got all the standard libs and includes for ARM, Except python ...
[ "I found a more recent link for cross compiling for ARM (and PPC), but if you're not using something like OpenEmbedded or Buildroot (or whatever else to make a complete embedded distribution) to build all your environment, you'll have to use those tutorials (OpenEmbedded, Buildroot & others are using those methods ...
[ 1 ]
[]
[]
[ "arm", "cross_compiling", "python" ]
stackoverflow_0007401984_arm_cross_compiling_python.txt
Q: What is the most idiomatic way to index a list of objects by coordinates I have a strong python background and a total newbie with Java, so I try to do things in Pythonic way in java and end up struggling. Currently I have a problem to figure out how to do store objects, indexed by coordinates, so that they are it...
What is the most idiomatic way to index a list of objects by coordinates
I have a strong python background and a total newbie with Java, so I try to do things in Pythonic way in java and end up struggling. Currently I have a problem to figure out how to do store objects, indexed by coordinates, so that they are iterable. I could create an 2-dimensional array of the objects, but I'm afraid t...
[ "\nDo not hesitate for memory (not now, maybe later)\nThe Java equivalent \"class\" is a Map. As Map is an interface take a HashMap class for the moment.\nMap has a method values() to get all values of the map.\nAs your key is not scalar you may create your own Coordinates class. Be aware to override equals() and h...
[ 1 ]
[]
[]
[ "java", "python" ]
stackoverflow_0007402260_java_python.txt