content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to read a structure containing an array using Python's ctypes and readinto? We have some binary files created by a C program. One type of file is created by calling fwrite to write the following C structure to file: typedef struct { unsigned long int foo; unsigned short int bar; unsigned short int ...
How to read a structure containing an array using Python's ctypes and readinto?
We have some binary files created by a C program. One type of file is created by calling fwrite to write the following C structure to file: typedef struct { unsigned long int foo; unsigned short int bar; unsigned short int bow; } easyStruc; In Python, I read the structs of this file as follows: class easy...
[ "According to this documentation page (section: 15.15.1.13. Arrays), it should be something like:\nclass strucWithArrays(Structure):\n _fields_ = [\n (\"foo\", c_ulong),\n (\"barFloat\", c_float * 4),\n (\"bowFloat\", c_float * 17)]\n\nCheck that documentation page for other examples.\n", "There's a section a...
[ 10, 2 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0001444159_ctypes_python.txt
Q: Example code for a python server wrapper I have a command line server for which I want to create a wrapper in python. The idea is that the wrapper receives commands like: my_wrapper start my_wrapper stop my_wrapper restart my_wrapper status And handles the server in background, unlinked to the terminal that launc...
Example code for a python server wrapper
I have a command line server for which I want to create a wrapper in python. The idea is that the wrapper receives commands like: my_wrapper start my_wrapper stop my_wrapper restart my_wrapper status And handles the server in background, unlinked to the terminal that launched it from the wrapper. I was about to start ...
[ "You could use an implementation of PEP 3143 - Standard daemon process library. One existing is python-daemon.\n" ]
[ 1 ]
[]
[]
[ "python", "wrapper" ]
stackoverflow_0001444358_python_wrapper.txt
Q: Django Models internal methods I'm new to Django so I just made up an project to get to know it but I'm having a little problem with this code, I want to be able to as the car obj if it is available so I do a: >>>cars = Car.objects.all() >>>print cars[0].category >>>'A' >>>cars[0].available(fr, to) that results i...
Django Models internal methods
I'm new to Django so I just made up an project to get to know it but I'm having a little problem with this code, I want to be able to as the car obj if it is available so I do a: >>>cars = Car.objects.all() >>>print cars[0].category >>>'A' >>>cars[0].available(fr, to) that results in a: >>>global name 'category' is no...
[ "Although I can't see how the error you are getting relates to it, the filter you are using doesn't look correct.\nYou define category as a string in the Car model:\ncategory = models.CharField(\"Category\",max_length=1,primary_key=True)\n\nAnd define car as a foreignkey in the Rent model:\ncar = models.ForeignKey(...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001444222_django_django_models_python.txt
Q: Werkzeug and SQLAlchemy 0.5x session Updated: Going through the Werkzeug link text tutorial, got stack with creating SQLAlchemy session using sessionmaker() instead of create_session() as recommended. Note: it is not about SA, it is about Werkzeug. Werkzeug tutorial: session = scoped_session(lambda: create_session...
Werkzeug and SQLAlchemy 0.5x session
Updated: Going through the Werkzeug link text tutorial, got stack with creating SQLAlchemy session using sessionmaker() instead of create_session() as recommended. Note: it is not about SA, it is about Werkzeug. Werkzeug tutorial: session = scoped_session(lambda: create_session(bind=application.database_engine, aut...
[ "sessionmaker() returns a session factory, not a session itself. scoped_session() takes a session factory as argument. So just omit the lambda: and pass the result of sessionmaker() directly to scoped_session().\n" ]
[ 4 ]
[]
[]
[ "python", "sqlalchemy", "werkzeug" ]
stackoverflow_0001444735_python_sqlalchemy_werkzeug.txt
Q: What is the best-maintained generic functions implementation for Python? A generic function is dispatched based on the type of all its arguments. The programmer defines several implementations of a function. The correct one is chosen at call time based on the types of its arguments. This is useful for object adapt...
What is the best-maintained generic functions implementation for Python?
A generic function is dispatched based on the type of all its arguments. The programmer defines several implementations of a function. The correct one is chosen at call time based on the types of its arguments. This is useful for object adaptation among other things. Python has a few generic functions including len(). ...
[ "I'd recommend the PEAK-Rules library by P. Eby. By the same author (deprecated though) is the RuleDispatch package (the predecessor of PEAK-Rules). The latter being no longer maintained IIRC. \nPEAK-Rules has a lot of nice features, one being, that it is (well, not easily, but) extensible. Besides \"classic\" disp...
[ 7, 0, 0 ]
[]
[]
[ "generics", "python" ]
stackoverflow_0001445065_generics_python.txt
Q: How can I find out why subprocess.Popen wait() waits forever if stdout=PIPE? I have a program that writes to stdout and possibly stderr. I want to run it from python, capturing the stdout and stderr. My code looks like: from subprocess import * p = Popen( exe, shell=TRUE, stdout=PIPE, stderr=PIPE ) rtrncode = p.w...
How can I find out why subprocess.Popen wait() waits forever if stdout=PIPE?
I have a program that writes to stdout and possibly stderr. I want to run it from python, capturing the stdout and stderr. My code looks like: from subprocess import * p = Popen( exe, shell=TRUE, stdout=PIPE, stderr=PIPE ) rtrncode = p.wait() For a couple of programs, this works fine, but when I added a new one, the ...
[ "When a pipe's buffer fills up (typically 4KB or so), the writing process stops until a reading process has read some of the data in question; but here you're reading nothing until the subprocess is done, hence the deadlock. The docs on wait put it very clearly indeed:\n\nWarning This will deadlock if the\n child...
[ 52, 3 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0001445627_python_subprocess.txt
Q: Introduction to the Python Clutter bindings? I've had a search around but I haven't been able to find decent online tutorials for the recent clutter bindings. There are guides for 0.4 and 0.6 around but 0.8 is supposed to be very different making these guides kind of useless. Links or examples greatly appreciated!...
Introduction to the Python Clutter bindings?
I've had a search around but I haven't been able to find decent online tutorials for the recent clutter bindings. There are guides for 0.4 and 0.6 around but 0.8 is supposed to be very different making these guides kind of useless. Links or examples greatly appreciated!
[ "these docs seem to be pretty up to date.\n" ]
[ 6 ]
[]
[]
[ "binding", "clutter_gui", "python", "user_interface" ]
stackoverflow_0001445633_binding_clutter_gui_python_user_interface.txt
Q: In Django, how to call a subprocess with a slow start-up time Suppose you're running Django on Linux, and you've got a view, and you want that view to return the data from a subprocess called cmd that operates on a file that the view creates, for example likeso: def call_subprocess(request): response = HttpR...
In Django, how to call a subprocess with a slow start-up time
Suppose you're running Django on Linux, and you've got a view, and you want that view to return the data from a subprocess called cmd that operates on a file that the view creates, for example likeso: def call_subprocess(request): response = HttpResponse() with tempfile.NamedTemporaryFile("W") as f: ...
[ "It may seem like i am punting this product as this is the second time i have responded with a recommendation of this.\nBut it seems like you need a Message Queing service, in particular a distributed message queue.\nere is how it will work:\n\nYour Django App requests CMD\nCMD gets added to a queue\nCMD gets pushe...
[ 3, 3, 0 ]
[]
[]
[ "django", "fork", "multithreading", "python", "subprocess" ]
stackoverflow_0001428900_django_fork_multithreading_python_subprocess.txt
Q: Class for pickle- and copy-persistent object? I'm trying to write a class for a read-only object which will not be really copied with the copy module, and when it will be pickled to be transferred between processes each process will maintain no more than one copy of it, no matter how many times it will be passed a...
Class for pickle- and copy-persistent object?
I'm trying to write a class for a read-only object which will not be really copied with the copy module, and when it will be pickled to be transferred between processes each process will maintain no more than one copy of it, no matter how many times it will be passed around as a "new" object. Is there already something...
[ "I made an attempt to implement this. @Alex Martelli and anyone else, please give me comments/improvements. I think this will eventually end up on GitHub.\n\"\"\"\ntodo: need to lock library to avoid thread trouble?\n\ntodo: need to raise an exception if we're getting pickled with\nan old protocol?\n\ntodo: make it...
[ 2, 1, 0 ]
[]
[]
[ "persistence", "pickle", "python" ]
stackoverflow_0001400295_persistence_pickle_python.txt
Q: Pydev code browsing? I've been -trying- to use pydev to do some python (can't say I'm having good times so far). I finally got code completion working for the libraries I'm using, but I'm still wondering about a couple of things... So the library I'm using is called orange. Say I call the function orange.MakeRand...
Pydev code browsing?
I've been -trying- to use pydev to do some python (can't say I'm having good times so far). I finally got code completion working for the libraries I'm using, but I'm still wondering about a couple of things... So the library I'm using is called orange. Say I call the function orange.MakeRandomIndices2, but I'm not su...
[ "When you hover your cursor over a function or class, Pydev should show you the docstring. Click on the function/class, then press F3, and it will take you to the definition of that function/class. If that is not happening, you probably have not configured Pydev correctly. Look over the documentation again, making ...
[ 2 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0001444651_eclipse_pydev_python.txt
Q: Whats the proper idiom for naming django model fields that are python reserved names? I have a model that needs to have a field named complex and another one named type. Those are both python reserved names. According to PEP 8, I should name them complex_ and type_ respectively, but django won't allow me to have f...
Whats the proper idiom for naming django model fields that are python reserved names?
I have a model that needs to have a field named complex and another one named type. Those are both python reserved names. According to PEP 8, I should name them complex_ and type_ respectively, but django won't allow me to have fields named with a trailing underscore. Whats the proper way to handle this?
[ "There's no problem with those examples. Just use complex and type. You are only shadowing in a very limited scope (the class definition itself). After that, you'll be accessing them using dot notation (self.type), so there's no ambiguity:\nPython 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) \n[GCC 4.3.3] on l...
[ 4, 1 ]
[]
[]
[ "django", "idioms", "python" ]
stackoverflow_0001445971_django_idioms_python.txt
Q: Python cmd module command aliases I am making a command line interface in Python 3.1.1 using the cmd module. Is there a way to create a command with more than one name e.g. "quit" and "exit"? Or would it just be a case of making a number of commands that all reference the same function? A: Yes, it would just be ...
Python cmd module command aliases
I am making a command line interface in Python 3.1.1 using the cmd module. Is there a way to create a command with more than one name e.g. "quit" and "exit"? Or would it just be a case of making a number of commands that all reference the same function?
[ "Yes, it would just be a case of making a number of commands that all reference the same function.\nThis is common. It often helps to provide multiple common aliases for a command. It makes the user's life simpler because the odds of them guessing correctly are improved.\n" ]
[ 4 ]
[]
[]
[ "cmd", "command_line_interface", "python" ]
stackoverflow_0001446137_cmd_command_line_interface_python.txt
Q: Python decorator to ensure that kwargs are correct I have done a decorator that I used to ensure that the keyword arguments passed to a constructor are the correct/expected ones. The code is the following: from functools import wraps def keyargs_check(keywords): """ This decorator ensures that the keys passed in...
Python decorator to ensure that kwargs are correct
I have done a decorator that I used to ensure that the keyword arguments passed to a constructor are the correct/expected ones. The code is the following: from functools import wraps def keyargs_check(keywords): """ This decorator ensures that the keys passed in kwargs are the onces that are specified in the passed t...
[ "Your decorator is not necessary. The only thing the decorator does that can't be done with the standard syntax is prevent keyword args from absorbing positional arguments. Thus\nclass Base(object):\n def __init__(name=None,surname=None,age=None):\n #some code\n\nclass Child(Base):\n def __init__(tes...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0001446555_python.txt
Q: What are good names for user defined exceptions? This question covers a broad range of programming languages; however, I am specifically working with Python in this case. I would like to create some user defined exceptions, but I'm not sure how fine-grained they should be. For example, if I have the following clas...
What are good names for user defined exceptions?
This question covers a broad range of programming languages; however, I am specifically working with Python in this case. I would like to create some user defined exceptions, but I'm not sure how fine-grained they should be. For example, if I have the following class: class Race(object): def __init__(self, start_ti...
[ "I think the built-in ValueError may be appropriate in this case. From the Python docs:\n\nexception ValueError\nRaised when a\n built-in operation or function\n receives an argument that has the\n right type but an inappropriate value,\n and the situation is not described by\n a more precise exception such as...
[ 6, 1 ]
[]
[]
[ "exception", "exception_handling", "python" ]
stackoverflow_0001446789_exception_exception_handling_python.txt
Q: How to identify binary and text files using Python? I need identify which file is binary and which is a text in a directory. I tried use mimetypes but it isnt a good idea in my case because it cant identify all files mimes, and I have strangers ones here... I just need know, binary or text. Simple ? But I couldn´...
How to identify binary and text files using Python?
I need identify which file is binary and which is a text in a directory. I tried use mimetypes but it isnt a good idea in my case because it cant identify all files mimes, and I have strangers ones here... I just need know, binary or text. Simple ? But I couldn´t find a solution... Thanks
[ "Thanks everybody, I found a solution that suited my problem. I found this code at http://code.activestate.com/recipes/173220/ and I changed just a little piece to suit me.\nIt works fine. \nfrom __future__ import division\nimport string \n\ndef istext(filename):\n s=open(filename).read(512)\n text_characters...
[ 11, 8, 6, 5 ]
[]
[]
[ "binary", "file_type", "python", "text" ]
stackoverflow_0001446549_binary_file_type_python_text.txt
Q: apt like column output - python library Debian's apt tool outputs results in uniform width columns. For instance, try running "aptitude search svn" .. and all names appear in the first column of the same width. Now if you resize the terminal, the column width is adjusted accordingly. Is there a Python library that...
apt like column output - python library
Debian's apt tool outputs results in uniform width columns. For instance, try running "aptitude search svn" .. and all names appear in the first column of the same width. Now if you resize the terminal, the column width is adjusted accordingly. Is there a Python library that enables one to do this? Note that the librar...
[ "Update: The colprint routine is now available in the applib Python library hosted in GitHub. \nHere's the complete program for those of you interested:\n# This function was written by Alex Martelli\n# http://stackoverflow.com/questions/1396820/\ndef colprint(table, totwidth=None):\n \"\"\"Print the table in ter...
[ 4, 2, 2, 2 ]
[]
[]
[ "apt", "formatting", "python", "terminal" ]
stackoverflow_0001396820_apt_formatting_python_terminal.txt
Q: How to encapsulate python modules? Is it possible to encapsulate python modules 'mechanize' and 'BeautifulSoup' into a single .py file? My problem is the following: I have a python script that requires mechanize and BeautifulSoup. I am calling it from a php page. The webhost server supports python, but doesn't hav...
How to encapsulate python modules?
Is it possible to encapsulate python modules 'mechanize' and 'BeautifulSoup' into a single .py file? My problem is the following: I have a python script that requires mechanize and BeautifulSoup. I am calling it from a php page. The webhost server supports python, but doesn't have the modules installed. That's why I wo...
[ "You don't actually have to combine the files, or install them in a system-wide location. Just make sure the libraries are in a directory readable by your Python script (and therefore, by your PHP app) and added to the Python load path.\nThe Python runtime searches for libraries in the directories in the sys.path a...
[ 4, 2, 0 ]
[]
[]
[ "encapsulation", "python" ]
stackoverflow_0001446852_encapsulation_python.txt
Q: In Django Admin, I want to change how foreign keys are displayed in a Many-Many Relationship admin widget I have a ManyToMany relationship: class Book: title = models.CharField(...) isbn = models.CharField(...) def unicode(self): return self.title def ISBN(self): return self.isbn class Author: ...
In Django Admin, I want to change how foreign keys are displayed in a Many-Many Relationship admin widget
I have a ManyToMany relationship: class Book: title = models.CharField(...) isbn = models.CharField(...) def unicode(self): return self.title def ISBN(self): return self.isbn class Author: name = models.CharField(...) books = models.ManyToManyField(Book...) In the admin interface for Author I g...
[ "To display the ISBN you could make a custom field like this:\n\nclass BooksField(forms.ModelMultipleChoiceField):\n def label_from_instance(self, obj):\n return obj.isbn\n\nThere's a CheckboxSelectMultiple for the ManyToManyField but it doesn't display correctly on the admin, so you could also write some...
[ 3, 2 ]
[]
[]
[ "django", "django_admin", "django_widget", "python" ]
stackoverflow_0001444912_django_django_admin_django_widget_python.txt
Q: How to send a file via HTTP, the good way, using Python? If a would-be-HTTP-server written in Python2.6 has local access to a file, what would be the most correct way for that server to return the file to a client, on request? Let's say this is the current situation: header('Content-Type', file.mimetype) header('C...
How to send a file via HTTP, the good way, using Python?
If a would-be-HTTP-server written in Python2.6 has local access to a file, what would be the most correct way for that server to return the file to a client, on request? Let's say this is the current situation: header('Content-Type', file.mimetype) header('Content-Length', file.size) # file size in bytes header('Conten...
[ "This is how I send ZIP file,\n req.send_response(200)\n req.send_header('Content-Type', 'application/zip')\n req.send_header('Content-Disposition', 'attachment;'\n 'filename=%s' % filename)\n\nMost browsers handle it correctly.\n", "If you don't have to return the response body (that ...
[ 6, 1 ]
[]
[]
[ "http", "http_headers", "python" ]
stackoverflow_0001447353_http_http_headers_python.txt
Q: Installed Python to portable python I have installed python from .msi installer in windows and installed a lot of other modules. i would like to have all these available on a portable thumbdrive, but i don't want to redownload all the extramodules. Is there a way i can convert my C:\python26* to a portable python ...
Installed Python to portable python
I have installed python from .msi installer in windows and installed a lot of other modules. i would like to have all these available on a portable thumbdrive, but i don't want to redownload all the extramodules. Is there a way i can convert my C:\python26* to a portable python installation?
[ "Python is pretty smart about knowing where it is run from. What happens if you just copy the whole directory tree to the thumb drive?\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0001447422_python.txt
Q: Class usage in Python I write a lot of scripts in Python to analyze and plot experimental data as well as write simple simulations to test how theories fit the data. The scripts tend to be very procedural; calculate some property, calculate some other property, plot properties, analyze plot... Rather than just wr...
Class usage in Python
I write a lot of scripts in Python to analyze and plot experimental data as well as write simple simulations to test how theories fit the data. The scripts tend to be very procedural; calculate some property, calculate some other property, plot properties, analyze plot... Rather than just writing a procedure, would th...
[ "By using Object Oriented Programming, you will have objects, that have associated functions, that are (should) be the only way to modify its properties (internal variables).\nIt was common to have functions called trim_string(string), while with a string class you could do string.trim(). The difference is noticeab...
[ 15, 4, 1, 1, 1 ]
[]
[]
[ "class_design", "oop", "procedural_programming", "python" ]
stackoverflow_0001440434_class_design_oop_procedural_programming_python.txt
Q: How do I see the results of my class on a file? I found this class to take a space delimited file and if there are multiple spaces, they will be treated as a single separator. How do I see the effects of this on a file? class FH: def __init__(self, fh): self.fh = fh def close(self): self...
How do I see the results of my class on a file?
I found this class to take a space delimited file and if there are multiple spaces, they will be treated as a single separator. How do I see the effects of this on a file? class FH: def __init__(self, fh): self.fh = fh def close(self): self.fh.close() def seek(self, arg): self.fh...
[ "Looks like this class takes a file (not a file name) in the initializer. Try:\nr = FH(file('classfhtry.csv', 'r'))\nfor line in r:\n print line\n\n", "dcrosta is correct. The class expects a space delimited contents in the file.\nHave a file like:\nsomefile.txt\none two\nthree four\nfive six\n\nAnd follow the...
[ 5, 0 ]
[]
[]
[ "class", "python" ]
stackoverflow_0001447487_class_python.txt
Q: Writing a function to display current day using time_t? I've been writing a time converter to take the systems time_t and convert it into human readable date/time. Oh, and this is my second python script ever. We'll leave that fact aside and move on. The full script is hosted here. Writing converters for the year ...
Writing a function to display current day using time_t?
I've been writing a time converter to take the systems time_t and convert it into human readable date/time. Oh, and this is my second python script ever. We'll leave that fact aside and move on. The full script is hosted here. Writing converters for the year and month were fairly easy, but I've hit a serious brick wall...
[ "Why not use:\nfrom datetime import datetime\nthe_date = datetime.fromtimestamp(the_time)\nprint(the_date.strftime('%Y %B %d'))\n\nThe datetime module handles all the edge cases -- leap years, leap seconds, leap days -- as well as time zone conversion (with optional second argument)\n", "You could do it either wi...
[ 8, 3, 1, 0 ]
[]
[]
[ "python", "time", "time_t" ]
stackoverflow_0001445236_python_time_time_t.txt
Q: Help with Python in the web I've been using Werkzeug to make WSGI compliant applications. I'm trying to modify the code in the front page. Its basic idea is that you go to the /hello URL and you get a "Hello World!" message. You go to /hello/ and you get "hello !". For example, /hello/jeff yields "Hello Jeff!". An...
Help with Python in the web
I've been using Werkzeug to make WSGI compliant applications. I'm trying to modify the code in the front page. Its basic idea is that you go to the /hello URL and you get a "Hello World!" message. You go to /hello/ and you get "hello !". For example, /hello/jeff yields "Hello Jeff!". Anyway, what I'm trying to do is pu...
[ "Do it the right way: go to /hello?name=joe to say hello to joe, and so forth. That's how HTML/HTTP is designed to work! Your code behind the /hello URL just needs to get the name parameter from the request, if present, and respond accordingly.\n", "HTML Forms have a static target address, action=\"/something\",...
[ 1, 0 ]
[ "Directly on the page link to which you provide (http://werkzeug.pocoo.org/) when clicking on 'Click here', you get a code for the hello X example. What you seem to be missing is:\nHello ${url_values['name']|h}!\n\nsomewhere in your html template (assuming it is the template for response as well as for request)\n",...
[ -1, -1 ]
[ "python", "werkzeug", "wsgi" ]
stackoverflow_0001447010_python_werkzeug_wsgi.txt
Q: How do I partition datetime intervals which overlap (Org Mode clocked time)? I have related tasks from two Org files/subtrees where some of the clocked time overlaps. These are a manual worklog and a generated git commit log, see below. One subtree's CLOCK: entries needs to be adjusted to remove overlapping time. ...
How do I partition datetime intervals which overlap (Org Mode clocked time)?
I have related tasks from two Org files/subtrees where some of the clocked time overlaps. These are a manual worklog and a generated git commit log, see below. One subtree's CLOCK: entries needs to be adjusted to remove overlapping time. The other subtree is considered complete, and it's CLOCK: entries should not be ad...
[ "Do you want help parsing the file format? Or just on figuring out the overlapping times?\ndatetime objects are comparable in Python, so you can do something like this:\n>>> (a,b) = (datetime(2009, 9, 15, 8, 30), datetime(2009, 9, 15, 8, 45))\n>>> (c,d) = (datetime(2009, 9, 15, 8, 40), datetime(2009, 9, 15, 8, 50))...
[ 2 ]
[]
[]
[ "datetime", "emacs", "org_mode", "overlap", "python" ]
stackoverflow_0001447257_datetime_emacs_org_mode_overlap_python.txt
Q: Error trying to pass (large) image over socket in python I am trying to pass an image over python socket for smaller images it works fine but for larger images it gives error as socket.error: [Errno 10040] A message sent on a datagram socket was larger than the internal message buffer or some other network limit,...
Error trying to pass (large) image over socket in python
I am trying to pass an image over python socket for smaller images it works fine but for larger images it gives error as socket.error: [Errno 10040] A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram into was smaller than...
[ "Your image is too big to be sent in one UDP packet. You need to split the image data into several packets that are sent individually.\nIf you don't have a special reason to use UDP you could also use TCP by specifying socket.SOCK_STREAM instead of socket.SOCK_DGRAM. There you don't have to worry about packet sizes...
[ 5, 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0001447684_python_sockets.txt
Q: Modifying a GUI started with Glade I am just starting to learn Glade with pyGTK. Since Glade makes XML files instead of actual python code, is there a good way to start a project with Glade and then hand code more or tweak it? Are there times or reasons it would be preferrable to hand code all of it instead of s...
Modifying a GUI started with Glade
I am just starting to learn Glade with pyGTK. Since Glade makes XML files instead of actual python code, is there a good way to start a project with Glade and then hand code more or tweak it? Are there times or reasons it would be preferrable to hand code all of it instead of starting with glade?
[ "GUI's created with glade are accessible in the code in two way: libglade or gtkbuilder. I cannot comment much on the differences between the two, other than that gtkbuilder is newer; there are a lot of pages on google that show how to migrate from libglade to gtkbuilder.\nUsing gtkbuilder, you can create your GUI ...
[ 4, 2 ]
[]
[]
[ "glade", "gtk", "pygtk", "python" ]
stackoverflow_0001412350_glade_gtk_pygtk_python.txt
Q: IDLE and Python have different path in Mac OS X I am running Mac OS X 10.5.8. I have installed Python 2.6 from the site. It's in my application directory. I have edited my .bash_profile to have: # Setting PATH for MacPython 2.6 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Pyt...
IDLE and Python have different path in Mac OS X
I am running Mac OS X 10.5.8. I have installed Python 2.6 from the site. It's in my application directory. I have edited my .bash_profile to have: # Setting PATH for MacPython 2.6 # The orginal version is saved in .bash_profile.pysave PATH="/Library/Frameworks/Python.framework/Versions/2.6/bin:${PATH}" export PATH e...
[ "Like all OS X application bundles, if you launch IDLE.app by double-clicking, a shell is not involved and thus .bash_profile or other shell initialization files are not invoked. There is a way to set user session environment variables through the use of a special property list file (~/.MacOSX/environment.plist) b...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001447961_django_python.txt
Q: Python SOCK_STREAM over internet I have a simple programs for socket client and server its not working over internet # Echo server program import socket import ImageGrab HOST = '' # Symbolic name meaning all available interfaces PORT = 3000 # Arbitrary non-privileged port s = socket....
Python SOCK_STREAM over internet
I have a simple programs for socket client and server its not working over internet # Echo server program import socket import ImageGrab HOST = '' # Symbolic name meaning all available interfaces PORT = 3000 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STRE...
[ "You've got the right approach, but you are probably running into networking or firewall problems. Depending on how your friend's networking is configured, he may be behind NAT or a firewall that prevents you from making a direct connection into his computer.\nTo eliminate half the problem, you can use telnet as a ...
[ 5 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0001448193_python_sockets.txt
Q: Python subprocess.Popen - adding GCC flags results in "no input files" error I'm building a Python script to automate my build process, which invokes GCC using subprocess.Popen. My initial attempt works fine. >>> import subprocess >>> p = Popen(['gcc', 'hello.c'], stdout=subprocess.PIPE, stderr=stderr=subprocess....
Python subprocess.Popen - adding GCC flags results in "no input files" error
I'm building a Python script to automate my build process, which invokes GCC using subprocess.Popen. My initial attempt works fine. >>> import subprocess >>> p = Popen(['gcc', 'hello.c'], stdout=subprocess.PIPE, stderr=stderr=subprocess.STDOUT) >>> p.wait() 0 >>> p.communicate() ('', None) However, once I pass additi...
[ "Shouldn't that be\np = Popen(['gcc', '-o', 'hello', 'hello.c'], stdout=subprocess.PIPE, stderr=stderr=subprocess.STDOUT)\n\n" ]
[ 6 ]
[]
[]
[ "gcc", "popen", "python", "subprocess" ]
stackoverflow_0001448558_gcc_popen_python_subprocess.txt
Q: Python - I can't stop the program running I am completely new to python. I have installed it on windows. I am having a problem, I write: from pylab import* subplot(111,projection="hammer") show() After this it will not let me do anything else and ctrl-c does not work. I have looked at another post here and trie...
Python - I can't stop the program running
I am completely new to python. I have installed it on windows. I am having a problem, I write: from pylab import* subplot(111,projection="hammer") show() After this it will not let me do anything else and ctrl-c does not work. I have looked at another post here and tried ctrl-break, ctrl-z and various other methods ...
[ "I'd recommend to use IPython. It brings a matplotlib/pylab mode that handles all this for you. After you install IPython, you can start it with the pylab flag:\n$ ipython -pylab\n\nThen, in the interactive shell, you type your code:\nIn [1]: from pylab import*\n\nIn [2]: subplot(111,projection=\"hammer\")\nOut[2]:...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001448505_python.txt
Q: Role-based security with Google App Engine and Python I would like to ask what is the common way for handling role-based security with Google App Engine, Python? In the app.yaml, there is the "login" section, but available values are only "admin" and "required". How do you normally handle role-based security? Cre...
Role-based security with Google App Engine and Python
I would like to ask what is the common way for handling role-based security with Google App Engine, Python? In the app.yaml, there is the "login" section, but available values are only "admin" and "required". How do you normally handle role-based security? Create the model with two tables: Roles and UserRoles Import v...
[ "I would do this by adding a ListProperty for roles to the model representing users. The list contains any roles a given user belongs to. This way if you want to know whether a given user belongs to a given role (I expect, the most common operation), it is a fast membership test.\nYou could put the role names direc...
[ 4 ]
[]
[]
[ "google_app_engine", "python", "role_based" ]
stackoverflow_0001448308_google_app_engine_python_role_based.txt
Q: Apache: VirtualHost with [PHP|Python|Ruby] support I am experimenting with several languages (Python, Ruby...), and I would like to know if there is a way to optimize my Apache Server to load certain modules only in certain VirtualHost, for instance: http://myapp1 <- just with Ruby support http://myapp2 <- just...
Apache: VirtualHost with [PHP|Python|Ruby] support
I am experimenting with several languages (Python, Ruby...), and I would like to know if there is a way to optimize my Apache Server to load certain modules only in certain VirtualHost, for instance: http://myapp1 <- just with Ruby support http://myapp2 <- just with Python support http://myapp3 <- just with Php supp...
[ "Each Apache worker loads every module, so it's not possible to do within Apache itself.\nWhat you need to do is move your language modules to processes external to Apache workers.\nThis is done for your languages with the following modules:\n\nPHP: mod_fastcgi. More info: Apache+Chroot+FastCGI.\nPython: mod_wsgi i...
[ 3, 0, 0, 0 ]
[]
[]
[ "apache", "php", "python", "ruby", "virtualhost" ]
stackoverflow_0001082906_apache_php_python_ruby_virtualhost.txt
Q: Decorators should not have side effects? Editing because the initial code was confusing. I would assume these two things to be same, #I would use either of these #Option 1 def bar(*args): pass foo = deco(bar) #Option2 @deco def foo(*args): pass However if the decorators deco has side effects, this is not...
Decorators should not have side effects?
Editing because the initial code was confusing. I would assume these two things to be same, #I would use either of these #Option 1 def bar(*args): pass foo = deco(bar) #Option2 @deco def foo(*args): pass However if the decorators deco has side effects, this is not guaranteed. In particular, this was my expect...
[ "Actually, these both are exactly the same:\ndef foo(*args):\n pass\nfoo = deco(foo)\n\n@deco\ndef foo(*args):\n pass\n\nIf you want to decorate bar and call it foo, foo = deco(bar) is the right way. It says: \"decorate this previously defined thing called bar and call it foo\". The point of the decorator syn...
[ 2, 0 ]
[]
[]
[ "decorator", "django", "python" ]
stackoverflow_0001447996_decorator_django_python.txt
Q: WSGI Authentication: Homegrown, Authkit, OpenID...? I want basic authentication for a very minimal site, all I personally need is a single superuser. While hard-coding a password and username in one of my source files is awfully tempting, especially since I'm hosting the site on my own server, I feel I'm breaking ...
WSGI Authentication: Homegrown, Authkit, OpenID...?
I want basic authentication for a very minimal site, all I personally need is a single superuser. While hard-coding a password and username in one of my source files is awfully tempting, especially since I'm hosting the site on my own server, I feel I'm breaking the law of the internets and I should just use a database...
[ "also look at repose.who\nhttp://static.repoze.org/whodocs/\n", "AuthKit includes a built-in OpenID module, if that helps.\nThe AuthKit cookbook includes a simple example here... http://wiki.pylonshq.com/display/authkitcookbook/OpenID+Passurl \nThat said, if you only need a single login (so there's no complex use...
[ 4, 2, 1, 0 ]
[]
[]
[ "authentication", "python", "wsgi" ]
stackoverflow_0000723856_authentication_python_wsgi.txt
Q: Use Python 2.6 subprocess module in Python 2.5 I would like to use Python 2.6's version of subprocess, because it allows the Popen.terminate() function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? Some sort of from __future__ import subpr...
Use Python 2.6 subprocess module in Python 2.5
I would like to use Python 2.6's version of subprocess, because it allows the Popen.terminate() function, but I'm stuck with Python 2.5. Is there some reasonably clean way to use the newer version of the module in my 2.5 code? Some sort of from __future__ import subprocess_module?
[ "I know this question has already been answered, but for what it's worth, I've used the subprocess.py that ships with Python 2.6 in Python 2.3 and it's worked fine. If you read the comments at the top of the file it says:\n\n# This module should remain compatible with Python 2.2, see PEP 291.\n\n", "There isn't r...
[ 9, 6, 2, 2, 1, 0 ]
[]
[]
[ "python", "python_2.5", "subprocess" ]
stackoverflow_0000552423_python_python_2.5_subprocess.txt
Q: why does this code break out of loop? import math t=raw_input() k=[] a=0 for i in range(0,int(t)): s=raw_input() b=1 c=1 a=int(s) if a==0: continue else: d=math.atan(float(1)/b) + math.atan(float(1)/c) v=math.atan(float(1)/a) print v print d p...
why does this code break out of loop?
import math t=raw_input() k=[] a=0 for i in range(0,int(t)): s=raw_input() b=1 c=1 a=int(s) if a==0: continue else: d=math.atan(float(1)/b) + math.atan(float(1)/c) v=math.atan(float(1)/a) print v print d print float(v) print float(d) ...
[ "Your while loop tests on an empty tuple, which evaluates to False. Thus, the statements within the while loop will never execute:\nIf you want your while loop to run until it encounters a break statement, do this:\nwhile True:\n if (some_condition):\n break\n else:\n # Do stuff...\n\n", "If i...
[ 8, 2, 2, 0 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0000994729_python_syntax_error.txt
Q: How can I omit words in the middle of a regular expression in Python? I have a multi-line string like this: "...Togo...Togo...Togo...ACTIVE..." I want to get everything between the third 'Togo' and 'ACTIVE' and the remainder of the string. I am unable to create a regular expression that can do this. If I try some...
How can I omit words in the middle of a regular expression in Python?
I have a multi-line string like this: "...Togo...Togo...Togo...ACTIVE..." I want to get everything between the third 'Togo' and 'ACTIVE' and the remainder of the string. I am unable to create a regular expression that can do this. If I try something like reg = "(Togo^[Togo]*?)(ACTIVE.*)" nothing is captured (the fir...
[ "reg = \"Togo.*Togo.*Togo(.*)ACTIVE\"\n\nAlternatively, if you want to match the string between the last occurrence of Togo and the following occurence of ACTIVE, and the number of Togo occurences is not necessarily three, try this:\nreg = \"Togo(([^T]|T[^o]|To[^g]|Tog[^o])*T?.?.?)ACTIVE\"\n\n", "This matches jus...
[ 1, 1, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001441866_python_string.txt
Q: PIL not rendering fonts uniformly across machines I wrote some code that spits out an image. The code ran on my local machine yields this image: local http://img32.yfrog.com/img32/9476/local.png and on my webhost, it looks like this: host http://img32.imageshack.us/img32/858/hoste.png As you can see they are diffe...
PIL not rendering fonts uniformly across machines
I wrote some code that spits out an image. The code ran on my local machine yields this image: local http://img32.yfrog.com/img32/9476/local.png and on my webhost, it looks like this: host http://img32.imageshack.us/img32/858/hoste.png As you can see they are different. The top is much nicer. Both are using the same co...
[ "I would guess that the top image was rendered with the TrueType hinting bytecode VM enabled, where the bottom was using only FreeType's auto-hinting. (Personally I prefer the bottom!)\nThere are, unfortunately, software patent issues which mean the hinting bytecode feature is not available on all binary builds. Th...
[ 4 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0001449663_python_python_imaging_library.txt
Q: Python TurtleGraphics - Making a randomly moving turtle? I'm trying to create a randomly moving turtle here by following these steps in a function I've called drunk_turtle(): Repeat the following as many times as you like: Randomly choose an integer, called rand_num, from -1 to 1 (i.e. randomly set rand_num to be...
Python TurtleGraphics - Making a randomly moving turtle?
I'm trying to create a randomly moving turtle here by following these steps in a function I've called drunk_turtle(): Repeat the following as many times as you like: Randomly choose an integer, called rand_num, from -1 to 1 (i.e. randomly set rand_num to be -1, 0, or 1) Make the turtle turn right rand_num * 90 degrees...
[ "You can find all of that information in the Python random manual.\n\nrandom.randint(a, b)\nReturn a random integer N such that a <= N <= b.\n\n\nSo you would do random.randint(-1,1) to get a number from -1, 0, or 1.\nTo get 5, 10, or 15, just do 5 * random.randint(1,3).\nIf you had a more complicated set of number...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0001449826_python.txt
Q: Converting 2.5 byte comparisons to 3 I'm trying to convert a 2.5 program to 3. Is there a way in python 3 to change a byte string, such as b'\x01\x02' to a python 2.5 style string, such as '\x01\x02', so that string and byte-by-byte comparisons work similarly to 2.5? I'm reading the string from a binary file. I ha...
Converting 2.5 byte comparisons to 3
I'm trying to convert a 2.5 program to 3. Is there a way in python 3 to change a byte string, such as b'\x01\x02' to a python 2.5 style string, such as '\x01\x02', so that string and byte-by-byte comparisons work similarly to 2.5? I'm reading the string from a binary file. I have a 2.5 program that reads bytes from a f...
[ "Bytes is an immutable sequence of integers (in the range 0<= to <256), therefore when you're accessing (a+b)[0] you're getting back an integer, exactly the same one you'd get by accessing a[0]. so when you're comparing sequence a to an integer (a+b)[0], they're naturally different.\nusing the slice notation you co...
[ 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001449791_python_python_3.x.txt
Q: How to convert an NSDictionary to a Python dict? I have a plugin written entirely in Python using PyObjC whose core classes I need to convert to Objective-C. One of them basically just loads up a Python module and executes a specific function, passing it keyword arguments. In PyObjC, this was extremely. However,...
How to convert an NSDictionary to a Python dict?
I have a plugin written entirely in Python using PyObjC whose core classes I need to convert to Objective-C. One of them basically just loads up a Python module and executes a specific function, passing it keyword arguments. In PyObjC, this was extremely. However, I'm having difficulty figuring out how to do the same...
[ "Oh, looks like I misunderstood your question. Well, going the other direction isn't terribly different. This should be (as least a start of) the function you're looking for (I haven't tested it thoroughly though, so beware of the bugs):\n// Returns a new reference\nPyObject *ObjcToPyObject(id object)\n{\n if (o...
[ 2 ]
[]
[]
[ "objective_c", "pyobjc", "python" ]
stackoverflow_0001449620_objective_c_pyobjc_python.txt
Q: Which queue is most appropriate? I'm building a mobile photo sharing site in Python similar to TwitPic and have been exploring various queues to handle the image processing. I've looked into RabbitMQ and ActiveMQ but I'm thinking that there is a better solution for my use case. I'm looking for something a little ...
Which queue is most appropriate?
I'm building a mobile photo sharing site in Python similar to TwitPic and have been exploring various queues to handle the image processing. I've looked into RabbitMQ and ActiveMQ but I'm thinking that there is a better solution for my use case. I'm looking for something a little more lightweight. I'm open to any sugg...
[ "You could write a daemon that uses python's built-in multiprocessing library and its Queue.\nAll you should have to do is set up a pool of workers, and have them wait on jobs from the Queue. Your main process can dump new jobs into the Queue, and you're good to go.\n", "Gearman is good in that it optionally allo...
[ 2, 1, 0 ]
[]
[]
[ "python", "queue" ]
stackoverflow_0001450038_python_queue.txt
Q: Python TurtleGraphics - Smoothing out random walks? I need some help with this question relating to TurtleGraphics in Python: A small detail of tipsy_turtle() is that when the turtle turns 90 degrees it immediately "jumps" to the new direction. This makes its movement seem jagged. It might look better if the turtl...
Python TurtleGraphics - Smoothing out random walks?
I need some help with this question relating to TurtleGraphics in Python: A small detail of tipsy_turtle() is that when the turtle turns 90 degrees it immediately "jumps" to the new direction. This makes its movement seem jagged. It might look better if the turtle moved smoothly when turning. So, for this question, wri...
[ "Hopefully this sample clears up what went wrong in your example -- you performed either rand_num*90*rand_num*90 left turns, or rand_num*90 right turns!\nif rand_num < 0: # don't need to multiply by 90 here - it's either +ve or -ve.\n for step in xrange(90): # xrange is preferred over range in situations like th...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001449990_python.txt
Q: Django FormPreview - What is it for? While looking across the Django documentation, I came across the FormPreview. The description says this: Django comes with an optional “form preview” application that helps automate the following workflow: “Display an HTML form, force a preview, then do something with the sub...
Django FormPreview - What is it for?
While looking across the Django documentation, I came across the FormPreview. The description says this: Django comes with an optional “form preview” application that helps automate the following workflow: “Display an HTML form, force a preview, then do something with the submission.” What is meant by "force a previ...
[ "I think they mean (I use django but I didn't know of this until now..) that you can let people write, for example in a textarea box like I'm doing right now. After the user submits it the system would preview it to the user and give him the chance to read and edit what he submitted, before it being submitted again...
[ 2, 2 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0001450295_django_forms_python.txt
Q: How to check form entry for special characters in python? Let's say I have a form field for "Name". I want to display an error message if it contains special characters such as $,#,etc. The only acceptable characters should be any alphanumeric, the hyphen "-", and the apostrophe "'". I am not sure how i should ...
How to check form entry for special characters in python?
Let's say I have a form field for "Name". I want to display an error message if it contains special characters such as $,#,etc. The only acceptable characters should be any alphanumeric, the hyphen "-", and the apostrophe "'". I am not sure how i should search the name for these non-acceptable characters, especially...
[ "You can use regular expressions to validate your string, like this:\nimport re\nif re.search(r\"^[\\w\\d'-]+$\", name):\n # success\n\nAnother way:\nif set(\"#$\").intersection(name):\n print \"bad chars in the name\"\n\n", "import re\np = r\"^[\\w'-]+$\"\nif re.search(p, name):\n # it's okay\nelse:\n ...
[ 3, 1 ]
[]
[]
[ "forms", "python" ]
stackoverflow_0001450522_forms_python.txt
Q: Embed a spreadsheet/table in a PyGTK application? In my application, we want to present the user with a typical spreadsheet/table (OO.O/Excel-style), and then pull out the values and do something with them internally. Is there a preexisting widget for PyGTK that does this? The PyGTK FAQ mentions GtkGrid, but the l...
Embed a spreadsheet/table in a PyGTK application?
In my application, we want to present the user with a typical spreadsheet/table (OO.O/Excel-style), and then pull out the values and do something with them internally. Is there a preexisting widget for PyGTK that does this? The PyGTK FAQ mentions GtkGrid, but the link is dead and I can't find a tarball anywhere.
[ "GtkGrid is deprecated in favor of the more powerful and more customizable GtkTreeView.\nIt can display trees and lists. To make it work like a table, you must define a ListStore where it will take the data from, and TreeViewColumns for each column you want to show, with CellRenderers to define how to show the colu...
[ 12, 3, 0 ]
[]
[]
[ "pygtk", "python", "spreadsheet" ]
stackoverflow_0001447187_pygtk_python_spreadsheet.txt
Q: wx.StaticBitmap or wx.DC: Which is better to use for constantly changing images? I would like to have a python gui that loads different images from files. I've seen many exmples of loading an image with some code like: img = wx.Image("1.jpg", wx.BITMAP_TYPE_ANY, -1) sb = wx.StaticBitmap(rightPanel, -1, wx.BitmapFr...
wx.StaticBitmap or wx.DC: Which is better to use for constantly changing images?
I would like to have a python gui that loads different images from files. I've seen many exmples of loading an image with some code like: img = wx.Image("1.jpg", wx.BITMAP_TYPE_ANY, -1) sb = wx.StaticBitmap(rightPanel, -1, wx.BitmapFromImage(img)) sizer.Add(sb) It seems to be suited for an image that will be there for...
[ "If you have rapidly changing big images, or you would like some custom effect in future, it better to write your own control and doing painting using paintDC, and it is not that hard.\nDoing your own drawing you can correctly scale, avoid flicker and may be do blend of one image into other if you like :)\n", "Yo...
[ 1, 0, 0 ]
[]
[]
[ "image", "python", "user_interface", "wxpython" ]
stackoverflow_0001450639_image_python_user_interface_wxpython.txt
Q: Simple object recognition ===SOLVED=== Thanks for your suggestions and comments. By working on the flood_fill algorithm given in Beginning Python Visualization book (Chapter 9 - Image Processing) I have implemented what I have wanted. I can count the objects, get enclosing rectangles for each object (therefore hei...
Simple object recognition
===SOLVED=== Thanks for your suggestions and comments. By working on the flood_fill algorithm given in Beginning Python Visualization book (Chapter 9 - Image Processing) I have implemented what I have wanted. I can count the objects, get enclosing rectangles for each object (therefore height and widths), and lastly can...
[ "\nScan every square (e.g. from the top-left, left-to-right, top-to-bottom)\nWhen you hit a blue square then:\na. Record this square as a location of a new object\nb. Find all the other contiguous blue squares (e.g. by looking at the neighbours of this square, and the neighbours of those neighbours, etc.) and mark ...
[ 5, 3, 3, 2, 2 ]
[]
[]
[ "computer_vision", "image_processing", "pattern_recognition", "python" ]
stackoverflow_0001449139_computer_vision_image_processing_pattern_recognition_python.txt
Q: How to stream binary data in python I want to stream a binary data using python. I do not have any idea how to achieve it. I did created python socket program using SOCK_DGRAM. Problem with SOCK_STREAM is that it does not work over internet as our isp dont allow tcp server socket. I want to transmit screen shot...
How to stream binary data in python
I want to stream a binary data using python. I do not have any idea how to achieve it. I did created python socket program using SOCK_DGRAM. Problem with SOCK_STREAM is that it does not work over internet as our isp dont allow tcp server socket. I want to transmit screen shots periodically to remote computer. I have ...
[ "SOCK_STREAM is the correct way to stream data.\nWhat you're saying about ISPs makes very little sense; they don't control whether or not your machine listens on a certain port on an interface. Perhaps you're talking about firewall/addressing issues?\nIf you insist on using UDP (and you shouldn't because you'll hav...
[ 3, 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0001451349_python_sockets.txt
Q: Security concerns with a Python PAM module? I'm interested in writing a PAM module that would make use of a popular authentication mechanism for Unix logins. Most of my past programming experience has been in Python, and the system I'm interacting with already has a Python API. I googled around and found pam_pytho...
Security concerns with a Python PAM module?
I'm interested in writing a PAM module that would make use of a popular authentication mechanism for Unix logins. Most of my past programming experience has been in Python, and the system I'm interacting with already has a Python API. I googled around and found pam_python, which allows PAM modules to invoke the python ...
[ "The security concerns that you mention aren't, per se, about \"allowing the user to invoke Python code\" which runs with high access levels, but allowing the user to exercise any form of control over the running of such code -- most obviously by injecting or altering the code itself, but, more subtly, also by cont...
[ 17 ]
[]
[]
[ "pam", "python", "security", "suid" ]
stackoverflow_0001451224_pam_python_security_suid.txt
Q: Paste text to active window on Linux I want to write an application which pastes some text to the active window on some keystroke. How can I do this with Python or C++? I want to write an app which will work like a daemon and on some global keystroke paste some text to the current active application (text editor, ...
Paste text to active window on Linux
I want to write an application which pastes some text to the active window on some keystroke. How can I do this with Python or C++? I want to write an app which will work like a daemon and on some global keystroke paste some text to the current active application (text editor, browser, and jabber client). I think I wil...
[ "Interacting between multiple applications interfaces can be tricky, so it may help to provide more information on specifically what you are trying to do. \nNonetheless, you have a few options if you want to use the clipboard to accomplish this. On Windows, the Windows API provides GetClipboardData and SetClipboar...
[ 1, 0 ]
[]
[]
[ "c++", "linux", "python", "x11" ]
stackoverflow_0001450892_c++_linux_python_x11.txt
Q: Python: How to find presence of every list item in string What is the most pythonic way to find presence of every directory name ['spam', 'eggs'] in path e.g. "/home/user/spam/eggs" Usage example (doesn't work but explains my case): dirs = ['spam', 'eggs'] path = "/home/user/spam/eggs" if path.find(dirs): prin...
Python: How to find presence of every list item in string
What is the most pythonic way to find presence of every directory name ['spam', 'eggs'] in path e.g. "/home/user/spam/eggs" Usage example (doesn't work but explains my case): dirs = ['spam', 'eggs'] path = "/home/user/spam/eggs" if path.find(dirs): print "All dirs are present in the path" Thanks
[ "set.issubset:\n>>> set(['spam', 'eggs']).issubset('/home/user/spam/eggs'.split('/'))\nTrue\n\n", "Looks line you want something like...:\nif all(d in path.split('/') for d in dirs):\n ...\n\nThis one-liner style is inefficient since it keeps splitting path for each d (and split makes a list, while a set is bet...
[ 9, 5, 2, 1, 0 ]
[]
[]
[ "list", "path", "python" ]
stackoverflow_0001451390_list_path_python.txt
Q: Setting a colour scale in ipython I am new to python and am having trouble finding the correct syntax to use. I want to plot some supernovae data onto a hammer projection. The data has coordinates alpha and beta. For each data point there is also a value delta describing a property of the SN. I would like to crea...
Setting a colour scale in ipython
I am new to python and am having trouble finding the correct syntax to use. I want to plot some supernovae data onto a hammer projection. The data has coordinates alpha and beta. For each data point there is also a value delta describing a property of the SN. I would like to create a colour scale that ranges from min....
[ "If you are thinking of a fixed color table, just map your delta values into the index range for that table. For example, you can construct a color table with color names recognized by your plot package:\n>>> colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']\n\nThe range of possible delta va...
[ 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001450874_python.txt
Q: How to add bi-directional manytomanyfields in django admin? In my models.py i have something like: class LocationGroup(models.Model): name = models.CharField(max_length=200) class Report(models.Model): name = models.CharField(max_length=200) locationgroups = models.ManyToManyField(LocationGroup) admi...
How to add bi-directional manytomanyfields in django admin?
In my models.py i have something like: class LocationGroup(models.Model): name = models.CharField(max_length=200) class Report(models.Model): name = models.CharField(max_length=200) locationgroups = models.ManyToManyField(LocationGroup) admin.py (standard): admin.site.register(LocationGroup) admin.site.re...
[ "The workaround I found was to follow the instructions for ManyToManyFields with intermediary models. Even though you're not using the 'through' model feature, just pretend as if you were and create a stub model with the necessary ForeignKey.\n# models: make sure the naming convention matches what ManyToManyField...
[ 8, 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001339409_django_django_models_python.txt
Q: Simple scraping of youtube xml to get a Python list of videos I have an xml feed, say: http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/ I want to get the list of hrefs for the videos: ['http://www.youtube.com/watch?v=aJvVkBcbFFY', 'ht....', ... ] A: from xml.etree import cElementTree as ET import urlli...
Simple scraping of youtube xml to get a Python list of videos
I have an xml feed, say: http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/ I want to get the list of hrefs for the videos: ['http://www.youtube.com/watch?v=aJvVkBcbFFY', 'ht....', ... ]
[ "from xml.etree import cElementTree as ET\nimport urllib\n\ndef get_bass_fishing_URLs():\n results = []\n data = urllib.urlopen(\n 'http://gdata.youtube.com/feeds/api/videos/-/bass/fishing/')\n tree = ET.parse(data)\n ns = '{http://www.w3.org/2005/Atom}'\n for entry in tree.findall(ns + 'entry'):\n for...
[ 7, 3, 3, 1 ]
[]
[]
[ "python", "xml", "youtube" ]
stackoverflow_0001452144_python_xml_youtube.txt
Q: How to write a large amount of data in a tarfile in python without using temporary file I've wrote a small cryptographic module in python whose task is to cipher a file and put the result in a tarfile. The original file to encrypt can be quit large, but that's not a problem because my program only need to work wit...
How to write a large amount of data in a tarfile in python without using temporary file
I've wrote a small cryptographic module in python whose task is to cipher a file and put the result in a tarfile. The original file to encrypt can be quit large, but that's not a problem because my program only need to work with a small block of data at a time, that can be encrypted on the fly and stored. I'm looking f...
[ "You can create an own file-like object and pass to TarFile.addfile. Your file-like object will generate the encrypted contents on the fly in the fileobj.read() method.\n", "Huh? Can't you just use the subprocess module to run a pipe through to tar? That way, no temporary file should be needed. Of course, this wo...
[ 4, 2, 2, 1 ]
[]
[]
[ "python", "tar" ]
stackoverflow_0001389681_python_tar.txt
Q: Python - Writing pseudocode? How would you write pseudocode for drawing an 8-by-8 checkerboard of squares, where none of the squares have to be full? (Can all be empty) I don't quite get the pseudocode concept. A: I would be even more generic eg. Loop with x from 1 to 8 Loop with y from 1 to 8 draw s...
Python - Writing pseudocode?
How would you write pseudocode for drawing an 8-by-8 checkerboard of squares, where none of the squares have to be full? (Can all be empty) I don't quite get the pseudocode concept.
[ "I would be even more generic eg.\nLoop with x from 1 to 8\n Loop with y from 1 to 8\n draw square at x, y\n\n", "Pseudo code is writing out the code in form that is like code but not quite code. So for opening a file and printing printing out its lines of text\nif file exists(path_to_file) then :\n ope...
[ 7, 5, 5, 2, 1 ]
[]
[]
[ "pseudocode", "python" ]
stackoverflow_0001452237_pseudocode_python.txt
Q: Evaluation of boolean expressions in Python What truth value do objects evaluate to in Python? Related Questions Boolean Value of Objects in Python: Discussion about overriding the way it is evaluated A: Any object can be tested for truth value, for use in an if or while condition or as operand of the Boole...
Evaluation of boolean expressions in Python
What truth value do objects evaluate to in Python? Related Questions Boolean Value of Objects in Python: Discussion about overriding the way it is evaluated
[ "\nAny object can be tested for truth\n value, for use in an if or while\n condition or as operand of the Boolean\n operations below. The following values\n are considered false:\n\nNone\nFalse\nzero of any numeric type, for example, 0, 0L, 0.0, 0j.\nany empty sequence, for example, '', (), [].\nany empty mappi...
[ 24, 9 ]
[]
[]
[ "boolean", "object", "python" ]
stackoverflow_0001452489_boolean_object_python.txt
Q: Creating Simultaneous Loops in Python I want to create a loop who has this sense: for i in xrange(0,10): for k in xrange(0,10): z=k+i print z where the output should be 0 2 4 6 8 10 12 14 16 18 A: You can use zip to turn multiple lists (or iterables) into pairwise* tuples: >>> for a,b in zip(xrange(...
Creating Simultaneous Loops in Python
I want to create a loop who has this sense: for i in xrange(0,10): for k in xrange(0,10): z=k+i print z where the output should be 0 2 4 6 8 10 12 14 16 18
[ "You can use zip to turn multiple lists (or iterables) into pairwise* tuples:\n>>> for a,b in zip(xrange(10), xrange(10)):\n... print a+b\n... \n0\n2\n4\n6\n8\n10\n12\n14\n16\n18\n\nBut zip will not scale as well as izip (that sth mentioned) on larger sets. zip's advantage is that it is a built-in and you don'...
[ 21, 11, 2, 2, 0 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0001452694_loops_python.txt
Q: Why can't a Python class definition assign a closure variable to itself? Why doesn't the following work in Python? def make_class(a): class A(object): a=a return A A: works just fine: >>> def make_class(a): class A(object): _a=a return A >>> make_class('df') <class '__main__.A'> ...
Why can't a Python class definition assign a closure variable to itself?
Why doesn't the following work in Python? def make_class(a): class A(object): a=a return A
[ "works just fine:\n>>> def make_class(a):\n class A(object):\n _a=a\n return A\n\n>>> make_class('df')\n<class '__main__.A'>\n>>> make_class('df')._a\n'df'\n\nbtw, function is not a reserved keyword in Python.\n", "Let's use a simpler example for the same problem:\na = 'something'\ndef boo():\n a ...
[ 9, 7, 2, 2 ]
[]
[]
[ "closures", "python" ]
stackoverflow_0001445207_closures_python.txt
Q: RTSP library in Python or C/C++? I am trying to find any RTSP streaming library for Python or C/C++. If not is there any other solutions for real time streaming? How much easy or difficult it is to implement RTSP in Python or C/C++ and where to get started? A: try live555. They have a lots of libraries and modu...
RTSP library in Python or C/C++?
I am trying to find any RTSP streaming library for Python or C/C++. If not is there any other solutions for real time streaming? How much easy or difficult it is to implement RTSP in Python or C/C++ and where to get started?
[ "try live555. They have a lots of libraries and modules for implementing rtp and rtsp (as well as sip) into your c and c++ programs\n", "With Python and Twisted, you could use this module.\n" ]
[ 4, 2 ]
[]
[]
[ "c", "c++", "python", "rtsp" ]
stackoverflow_0001452710_c_c++_python_rtsp.txt
Q: How to filter query in sqlalchemy by year (datetime column) I have table in sqlalchemy 0.4 that with types.DateTime column: Column("dfield", types.DateTime, index=True) I want to select records, that has specific year in this column, using model. How to do this? I though it should be done like this: selected_year...
How to filter query in sqlalchemy by year (datetime column)
I have table in sqlalchemy 0.4 that with types.DateTime column: Column("dfield", types.DateTime, index=True) I want to select records, that has specific year in this column, using model. How to do this? I though it should be done like this: selected_year = 2009 my_session = model.Session() my_query = my_session.query(...
[ "sqlalchemy.extract('year', model.MyRecord.dfield) == selected_year\n\nFor referene: https://docs.sqlalchemy.org/en/13/core/sqlelement.html#sqlalchemy.sql.expression.extract\n" ]
[ 27 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0001453591_python_sqlalchemy.txt
Q: Django: queryset filter for *all* values from a ManyToManyField Hi (sorry for my bad english :p) Imagine these models : class Fruit(models.Model): # ... class Basket(models.Model): fruits = models.ManyToManyField(Fruit) Now I would like to retrieve Basket instances related to all fruits. The problem is t...
Django: queryset filter for *all* values from a ManyToManyField
Hi (sorry for my bad english :p) Imagine these models : class Fruit(models.Model): # ... class Basket(models.Model): fruits = models.ManyToManyField(Fruit) Now I would like to retrieve Basket instances related to all fruits. The problem is that the code bellow returns Basket instances related to any fruits : ...
[ "I don't have a dataset handy to test this, but I think it should work:\nBasket.objects.annotate(num_fruits=Count('fruits')).filter(num_fruits=len(Fruit.objects.all()))\n\nIt annotates every basket object with the count of related fruits and filters out those baskets that have a fruit count that equals the total am...
[ 6 ]
[]
[]
[ "django", "django_models", "django_queryset", "python", "sql" ]
stackoverflow_0001453662_django_django_models_django_queryset_python_sql.txt
Q: ctypes memory management: how and when free the allocated resources? I'm writing a small wrapper for a C library in Python with Ctypes, and I don't know if the structures allocated from Python will be automatically freed when they're out of scope. Example: from ctypes import * mylib = cdll.LoadLibrary("mylib.so") ...
ctypes memory management: how and when free the allocated resources?
I'm writing a small wrapper for a C library in Python with Ctypes, and I don't know if the structures allocated from Python will be automatically freed when they're out of scope. Example: from ctypes import * mylib = cdll.LoadLibrary("mylib.so") class MyPoint(Structure): _fields_ = [("x", c_int), ("y", c_int)] de...
[ "In this case your MyPoint instance is a Python object allocated on the Python heap, so there should be no need to treat it differently from any other Python object. If, on the other hand, you got the MyPoint instance by calling say allocate_point() in mylib.so, then you would need to free it using whatever functio...
[ 5 ]
[]
[]
[ "c", "ctypes", "memory", "python" ]
stackoverflow_0001453776_c_ctypes_memory_python.txt
Q: Python bracket convention What do you think is the convention that is mostly used when writing dictionary literals in the code? I'll write one possible convention as an answer. A: my_dictionary = { 1: 'something', 2: 'some other thing', } A: I'd say there is almost no standard. I've seen two ways of in...
Python bracket convention
What do you think is the convention that is mostly used when writing dictionary literals in the code? I'll write one possible convention as an answer.
[ "my_dictionary = {\n 1: 'something',\n 2: 'some other thing',\n}\n\n", "I'd say there is almost no standard.\nI've seen two ways of indenting:\nIndent 1:\nmy_dictionary = {\n 'uno': 'something',\n 'number two': 'some other thing',\n}\n\nIndent 2:\nmy_dictionary = {'uno': 'something',\n ...
[ 21, 15, 8, 4 ]
[ "I do this, if the dictionary is too large to fit on a single line:\nd = \\\n {\n 'a' : 'b',\n 'c' : 'd'\n }\n\n" ]
[ -3 ]
[ "coding_style", "conventions", "python" ]
stackoverflow_0001431862_coding_style_conventions_python.txt
Q: Flow control in threading.Thread I Have run into a few examples of managing threads with the threading module (using Python 2.6). What I am trying to understand is how is this example calling the "run" method and where. I do not see it anywhere. The ThreadUrl class gets instantiated in the main() function as "t" a...
Flow control in threading.Thread
I Have run into a few examples of managing threads with the threading module (using Python 2.6). What I am trying to understand is how is this example calling the "run" method and where. I do not see it anywhere. The ThreadUrl class gets instantiated in the main() function as "t" and this is where I would normally expe...
[ "Per the pydoc:\n\nThread.start()\nStart the thread’s activity.\nIt must be called at most once per thread object. It arranges for the\n object’s run() method to be invoked in\n a separate thread of control.\nThis method will raise a RuntimeException if called more than\n once on the same thread object.\n\nThe w...
[ 7, 4, 0 ]
[]
[]
[ "control_flow", "multithreading", "python" ]
stackoverflow_0001454941_control_flow_multithreading_python.txt
Q: Allowing user to rollback from db audit trail with SQLAlchemy I'm starting to use SQLAlchemy for a new project where I was planning to implement an audit trail similar to the one proposed on these questions: Implementing Audit Trail for Objects in C#? Audit trails and implementing SOX/HIPAA/etc, best practices fo...
Allowing user to rollback from db audit trail with SQLAlchemy
I'm starting to use SQLAlchemy for a new project where I was planning to implement an audit trail similar to the one proposed on these questions: Implementing Audit Trail for Objects in C#? Audit trails and implementing SOX/HIPAA/etc, best practices for sensitive data Ideas on database design for capturing audit trail...
[ "Although I haven't used SQLAlchemy specifically, I can give you some general tips that can be easily implemented in any ORM:\n\nSeparate out the versioned item into two tables, say Document and DocumentVersion. Document stores information that will never change between versions, and DocumentVersion stores informat...
[ 8 ]
[]
[]
[ "audit", "python", "rollback", "sqlalchemy" ]
stackoverflow_0001454874_audit_python_rollback_sqlalchemy.txt
Q: How to define properties in __init__ I whish to define properties in a class from a member function. Below is some test code showing how I would like this to work. However I don't get the expected behaviour. class Basket(object): def __init__(self): # add all the properties for p in self.PropNames(): ...
How to define properties in __init__
I whish to define properties in a class from a member function. Below is some test code showing how I would like this to work. However I don't get the expected behaviour. class Basket(object): def __init__(self): # add all the properties for p in self.PropNames(): setattr(self, p, property(lambda : p) ...
[ "You need to set the properties on the class (ie: self.__class__), not on the object (ie: self). For example:\nclass Basket(object):\n\n def __init__(self):\n # add all the properties\n setattr(self.__class__, 'Apple', property(lambda s : 'Apple') )\n setattr(self.__class__, 'Pear', property(lambda s : 'P...
[ 13, 3, 0 ]
[]
[]
[ "constructor", "properties", "python" ]
stackoverflow_0001454984_constructor_properties_python.txt
Q: Python-based Gallery web applications? I'm trying to cut my last dependencies on PHP and MySQL. The last stumbling block is a image gallery I set up for a client a while ago. The whole website is built around Django and Zine, except for the image gallery, which is based on plogger. I'd love to replace plogger with...
Python-based Gallery web applications?
I'm trying to cut my last dependencies on PHP and MySQL. The last stumbling block is a image gallery I set up for a client a while ago. The whole website is built around Django and Zine, except for the image gallery, which is based on plogger. I'd love to replace plogger with a Python solution. Requirements include: g...
[ "There is django-photo-gallery, django photo album and another django-photo-gallery (don't know if its the same one.)\nAnything else, and you'll have to make your own.\n" ]
[ 7 ]
[]
[]
[ "gallery", "python", "web_applications" ]
stackoverflow_0001455224_gallery_python_web_applications.txt
Q: What's a Django/Python solution for providing a one-time url for people to download files? I'm looking for a way to sell someone a card at an event that will have a unique code that they will be able to use later in order to download a file (mp3, pdf, etc.) only one time and mask the true file location so a savvy ...
What's a Django/Python solution for providing a one-time url for people to download files?
I'm looking for a way to sell someone a card at an event that will have a unique code that they will be able to use later in order to download a file (mp3, pdf, etc.) only one time and mask the true file location so a savvy person downloading the file won't be able to download the file more than once. It would be nice ...
[ "Neat idea. However, I would warn against the single-download method, because there is no guarantee that their first download attempt will be successful. Perhaps use a time-expiration method instead?\nBut it is certainly possible to do this with Django. Here is an outline of the basic approach:\n\nSet up a django u...
[ 3, 2 ]
[]
[]
[ "django", "download", "proxy", "python", "url" ]
stackoverflow_0001455109_django_download_proxy_python_url.txt
Q: Django: use archive_index with date_field from a related model Hello (please excuse me for my ugly english :p), Imagine these two simple models : from django.contrib.contenttypes import generic from django.db import models class SomeModel(models.Model): content_type = models.ForeignKey(ContentType) object...
Django: use archive_index with date_field from a related model
Hello (please excuse me for my ugly english :p), Imagine these two simple models : from django.contrib.contenttypes import generic from django.db import models class SomeModel(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(_('object id')) content_object...
[ "From digging through the Django source code, the generic view archive_index does not appear to support related fields that are GenericRelations.\nThis is because the queryset method dates does not support generic relations. Consider filing this as a bug / feature request on the Django bug tracker.\n" ]
[ 1 ]
[]
[]
[ "django", "django_generic_views", "django_models", "django_views", "python" ]
stackoverflow_0001453465_django_django_generic_views_django_models_django_views_python.txt
Q: Python code does not work as expected when I run script as a Windows Service Here is the code to get Desktop path on Windows Vista. import pythoncom import win32com.client pythoncom.CoInitialize() shell = win32com.client.Dispatch("WScript.Shell") desktop_path = shell.SpecialFolders("Desktop") Code works fine wh...
Python code does not work as expected when I run script as a Windows Service
Here is the code to get Desktop path on Windows Vista. import pythoncom import win32com.client pythoncom.CoInitialize() shell = win32com.client.Dispatch("WScript.Shell") desktop_path = shell.SpecialFolders("Desktop") Code works fine when I tried on python interpreter but its not working when I execute the same code ...
[ "Most likely, your service is running under an account which doesn't have a user desktop folder. Also note that by default, services have no access to the GUI - if your app has one, you have to mark your service as being allowed to interact with the desktop (user session, not folder).\n" ]
[ 3 ]
[]
[]
[ "python", "service", "windows", "windows_vista" ]
stackoverflow_0001455592_python_service_windows_windows_vista.txt
Q: Could not get out of python loop I want to get out of loop when there is no data but loop seems to be stopping at recvfrom image='' while 1: data,address=self.socket.recvfrom(512) if data is None:break image=image+data count=count+1 print str(count)+' packets received...' ...
Could not get out of python loop
I want to get out of loop when there is no data but loop seems to be stopping at recvfrom image='' while 1: data,address=self.socket.recvfrom(512) if data is None:break image=image+data count=count+1 print str(count)+' packets received...'
[ "Try setting to a non-blocking socket. You would do this before the loop starts. You can also try a socket with a timeout.\n", "recvfrom may indeed stop (waiting for data) unless you've set your socket to non-blocking or timeout mode. Moreover, if the socket gets closed by your counterpart, the indication of \"...
[ 4, 2, 0, 0 ]
[]
[]
[ "loops", "python", "sockets" ]
stackoverflow_0001455630_loops_python_sockets.txt
Q: Can we run google app engine on ubuntu/windows and serve web application I see google provide SDK and utilties to develop and run the web application in development (developer-pc) and port them to google app engine live (at google server). Can we use google app engine to run the local web application without using...
Can we run google app engine on ubuntu/windows and serve web application
I see google provide SDK and utilties to develop and run the web application in development (developer-pc) and port them to google app engine live (at google server). Can we use google app engine to run the local web application without using google infrastructure? Basically I want a decent job scheduler and persisten...
[ "You can run App Engine apps on top of appscale which in turn does run on Eucalyptus, Xen, and other clustering solutions you can deploy on Ubuntu (not sure about there being any Windows support) -- looks like it may require substantial system installation, configuration, and administration work to get started (sor...
[ 8 ]
[ "I don't believe so. According to the App Engine terms of service:\n\n7.1. Google gives you a personal, worldwide, royalty-free,\n non-assignable and non-exclusive\n license to use the software provided\n to you by Google as part of the\n Service as provided to you by Google\n (referred to as the \"Google App ...
[ -1 ]
[ "google_app_engine", "python", "task" ]
stackoverflow_0001455800_google_app_engine_python_task.txt
Q: Given a class type how do I create an instance in Python? Let's say I have this : class whatever(object): def __init__(self): pass and this function: def create_object(type_name): # create an object of type_name I'd like to be able to call the create_object like this: inst = create_object(whatever) ...
Given a class type how do I create an instance in Python?
Let's say I have this : class whatever(object): def __init__(self): pass and this function: def create_object(type_name): # create an object of type_name I'd like to be able to call the create_object like this: inst = create_object(whatever) and get back an instance of whatever. I think this should be do...
[ "The most obvious way:\ndef create_object(type_name):\n return type_name()\n\n", "def create_object(typeobject):\n return typeobject()\n\nAs you so explicitly say that the arg to create_object is NOT meant to be a string, I assume it's meant to be the type object itself, just like in the create_object(whateve...
[ 7, 5, 2, 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0001455835_oop_python.txt
Q: Apache vs Twisted I know Twisted is a framework that allows you to do asynchronous non-blocking i/o but I still do not understand how that is different from what Apache server does. If anyone could explain the need for twisted, I would appreciate it.. A: Twisted is a platform for developing internet applications...
Apache vs Twisted
I know Twisted is a framework that allows you to do asynchronous non-blocking i/o but I still do not understand how that is different from what Apache server does. If anyone could explain the need for twisted, I would appreciate it..
[ "Twisted is a platform for developing internet applications, for handling the underlying communications and such. It doesn't \"do\" anything out of the box--you've got to program it.\nApache is an internet application, of sorts. Upon install, you have a working web server which can serve up static and dynamic web p...
[ 11, 2, 2, 2 ]
[]
[]
[ "apache", "python", "twisted" ]
stackoverflow_0001410967_apache_python_twisted.txt
Q: Python: Does a dict value pointer store its key? I'm wondering if there is a built-in way to do this... Take this simple code for example: D = {'one': objectA(), 'two': objectB(), 'three': objectC()} object_a = D['one'] I believe object_a is just pointing at the objectA() created on the first line, and knows noth...
Python: Does a dict value pointer store its key?
I'm wondering if there is a built-in way to do this... Take this simple code for example: D = {'one': objectA(), 'two': objectB(), 'three': objectC()} object_a = D['one'] I believe object_a is just pointing at the objectA() created on the first line, and knows nothing about the dictionary D, but my question is, does P...
[ "I think no.\nConsider the case of adding a single object to a (large) number of different dictionaries. It would become quite expensive for Python to track that for you, it would cost a lot for a feature not used by most.\n", "The dict mapping is not trivially \"reversible\" as you describe.\n\nThe key must be i...
[ 7, 3, 2, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0001454437_dictionary_python.txt
Q: Can I "embed" a Python back-end in an AIR application? I'm trying to find out if there is a way I could embed a Python back-end into an AIR application? I'm looking to employ an approach similar to the one outlined here to implement the business logic for my application, but additionally, I would like to provide ...
Can I "embed" a Python back-end in an AIR application?
I'm trying to find out if there is a way I could embed a Python back-end into an AIR application? I'm looking to employ an approach similar to the one outlined here to implement the business logic for my application, but additionally, I would like to provide the user with a single binary which they can load. I don't ...
[ "Probably. We are using a J2EE server side which uses SOAP webservices to talk to our AIR application on the frontend. You should be able to do the same because soap doesn't care which technology sits on either side of it.\nYou can always have the application launch from a single binary which first fires up the s...
[ 1, 1, 1 ]
[]
[]
[ "air", "apache_flex", "python" ]
stackoverflow_0001455722_air_apache_flex_python.txt
Q: Python Eval: What's wrong with this code? I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code: import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin...
Python Eval: What's wrong with this code?
I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code: import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin else : handle = open(sys.argv[1]) result =...
[ "Try using exec instead of eval. The difference between the 2 is explained here\n", "try:\nfor line in handle:\n result += 1 if eval(pred) else 0\n\n", "#!/usr/bin/env python\nimport fileinput, sys\n\npred = eval('lambda line: ' + sys.argv[1])\nprint sum(1 for line in fileinput.input(sys.argv[2:]) if pred(lin...
[ 11, 5, 3, 2, 0 ]
[]
[]
[ "eval", "python", "syntax_error" ]
stackoverflow_0001456760_eval_python_syntax_error.txt
Q: Return a random word from a word list in python I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist. import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.R...
Return a random word from a word list in python
I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist. import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file))],
[ "The random module defines choice(), which does what you want:\nimport random\n\nwords = [line.strip() for line in open('/etc/dictionaries-common/words')]\nprint(random.choice(words))\n\nNote also that this assumes that each word is by itself on a line in the file. If the file is very big, or if you perform this op...
[ 17, 9, 9, 3, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001456617_python.txt
Q: Renaming contents of text file using Regular Expressions I have a text file with several lines in the following format: gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate...
Renaming contents of text file using Regular Expressions
I have a text file with several lines in the following format: gatename #outputs #inputs list_of_inputs_separated_by_spaces * gate_id example: nand 3 2 10 11 * G0 (The two inputs to the nand gate are 10 and 11) or 2 1 10 * G1 (The only input to the or gate is gate 10) What I need to do is rename the contents such th...
[ "This is basically what the cut utility is for:\ncut -d \" \" -f 1,3-\n\n(update: I forgot the -f option, sorry.)\nThis takes a file, considers fields delimited by spaces, and outputs the first, third and following fields.\n(If you're on Windows, you should have these unix-style utilities anyway, they can be incred...
[ 4, 2, 1, 1, 0 ]
[]
[]
[ "eclipse", "python", "regex" ]
stackoverflow_0001457100_eclipse_python_regex.txt
Q: Simple file transfer over wifi between computer and mobile phone using python I'd like to be able to transfer files between my mobile phone and computer. The phone is a smartphone that can run python 2.5.4 and the computer is running windows xp (with python 2.5.4 and 3.1.1). I'd like to have a simple python pro...
Simple file transfer over wifi between computer and mobile phone using python
I'd like to be able to transfer files between my mobile phone and computer. The phone is a smartphone that can run python 2.5.4 and the computer is running windows xp (with python 2.5.4 and 3.1.1). I'd like to have a simple python program on the phone that can send files to the computer and get files from the comput...
[ "I would use paramiko. It's secure fast and really simple. How bout this?\nSo we start by importing the module, and specifying the log file:\nimport paramiko\nparamiko.util.log_to_file('/tmp/paramiko.log')\n\nWe open an SSH transport:\nhost = \"example.com\"\nport = 22\ntransport = paramiko.Transport((host, port))...
[ 3, 1, 0 ]
[]
[]
[ "file_transfer", "mobile_phones", "python" ]
stackoverflow_0001451849_file_transfer_mobile_phones_python.txt
Q: Can Python encode a string to match ASP.NET membership provider's EncodePassword I'm working on a Python script to create hashed strings from an existing system similar to that of ASP.NET's MembershipProvider. Using Python, is there a way to take a hexadecimal string and convert it back to a binary and then do a b...
Can Python encode a string to match ASP.NET membership provider's EncodePassword
I'm working on a Python script to create hashed strings from an existing system similar to that of ASP.NET's MembershipProvider. Using Python, is there a way to take a hexadecimal string and convert it back to a binary and then do a base64 encoding, somehow treating the original string as Unicode. Let's try some code....
[ "This is the trick:\n\nEncoding.Unicode\n\n“Unicode” encoding is confusing Microsoft-speak for UTF-16LE (specifically, without any BOM). Encode the string to that before hashing and you get the right answer:\n>>> import hashlib\n>>> p= u'password'\n>>> hashlib.sha1(p.encode('utf-16le')).digest().encode('base64')\n'...
[ 5 ]
[]
[]
[ ".net", "asp.net", "c#", "python", "unicode" ]
stackoverflow_0001456770_.net_asp.net_c#_python_unicode.txt
Q: python shell command - why won't it work? I wonder if anyone has any insights into this. I have a bash script that should put my ssh key onto a remote machine. Adopted from here, the script reads, #!/usr/bin/sh REMOTEHOST=user@remote KEY="$HOME/.ssh/id_rsa.pub" KEYCODE=`cat $KEY` ssh -q $REMOTEHOST "mkdir ~/.ssh 2...
python shell command - why won't it work?
I wonder if anyone has any insights into this. I have a bash script that should put my ssh key onto a remote machine. Adopted from here, the script reads, #!/usr/bin/sh REMOTEHOST=user@remote KEY="$HOME/.ssh/id_rsa.pub" KEYCODE=`cat $KEY` ssh -q $REMOTEHOST "mkdir ~/.ssh 2>/dev/null; chmod 700 ~/.ssh; echo "$KEYCODE" >...
[ "You have a serious question -- in that os.system isn't behaving the way you expect it to -- but also, you should seriously rethink the approach as a whole.\nYou're launching a Python interpreter -- but then, via os.system, telling that Python interpreter to launch a shell! os.system shouldn't be used at all in mod...
[ 5 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0001457757_python_shell.txt
Q: How do I find the name of the file that is the importer, within the imported file? How do I find the name of the file that is the "importer", within the imported file? If a.py and b.py both import c.py, is there anyway that c.py can know the name of the file importing it? A: Use sys.path[0] returns the path of t...
How do I find the name of the file that is the importer, within the imported file?
How do I find the name of the file that is the "importer", within the imported file? If a.py and b.py both import c.py, is there anyway that c.py can know the name of the file importing it?
[ "Use\nsys.path[0]\nreturns the path of the script that launched the python interpreter. If you can this script directly, it will return the path of the script. If the script however, was imported from another script, it will return the path of that script.\nSee Python Path Issues\n", "In the top-level of c.py (i....
[ 3, 2, 2, 1 ]
[]
[]
[ "import", "python" ]
stackoverflow_0001457308_import_python.txt
Q: Get every combination of strings I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings. In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a p...
Get every combination of strings
I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings. In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a program. The only problem is that I ca...
[ "Assuming you DO mean combinations (no repetitions, order does not matter):\nimport itertools\n\nS = [ 'a', 'ab', 'ba' ]\n\nfor i in range(len(S)+1):\n for c in itertools.combinations(S, i):\n cc = ''.join(c)\n if len(cc) <= 6:\n print c\n\nemits all the possibilities:\n()\n('a',)\n('ab',)\n('ba',)\n('a...
[ 10, 8, 4, 1 ]
[]
[]
[ "combinatorics", "python", "string" ]
stackoverflow_0001457814_combinatorics_python_string.txt
Q: TurtleGraphics Python: Bouncing turtle off the walls? So, I am trying to make a realistic bouncing function, where the turtle hits a wall and bounces off at the corresponding angle. My code looks like this: def bounce(num_steps, step_size, initial_heading): turtle.reset() top = turtle.window_height()/2 bo...
TurtleGraphics Python: Bouncing turtle off the walls?
So, I am trying to make a realistic bouncing function, where the turtle hits a wall and bounces off at the corresponding angle. My code looks like this: def bounce(num_steps, step_size, initial_heading): turtle.reset() top = turtle.window_height()/2 bottom = -top right = turtle.window_width()/2 left = -r...
[ "Try something like this:\nif not (left <= x <= right):\n turtle.left(180 - 2 * turtle.heading())\nelif not (bottom <= y <= top):\n turtle.left(-2 * turtle.heading())\nelse:\n pass\n\nMy python syntax is a little rusty, sorry :P. But the math is a little different for a horizontal vs. a vertical flip.\nED...
[ 1, 0 ]
[]
[]
[ "python", "turtle_graphics" ]
stackoverflow_0001457332_python_turtle_graphics.txt
Q: Which process was responsible for an event signalled by inotify? I am using pyinotify to detect access, changes, etc. on files in a given directory. Is there an easier way to find out which process was responsible for that - without having to patch inotify? A: No, you can't, that information isn't in the struct ...
Which process was responsible for an event signalled by inotify?
I am using pyinotify to detect access, changes, etc. on files in a given directory. Is there an easier way to find out which process was responsible for that - without having to patch inotify?
[ "No, you can't, that information isn't in the struct inotify_event sent by the kernel.\nActually there isn't any guarantee that the process responsible is still running when you get the event.\n", "Assuming you are on Linux (pyinotify would tend to indicate this) you could use SELinux (running in permissive mode ...
[ 1, 1 ]
[]
[]
[ "inotify", "pyinotify", "python" ]
stackoverflow_0000922200_inotify_pyinotify_python.txt
Q: Need help installing MySQL for Python Trying to install MySQL for Python. Two problems: 1) Instructions over the net says installation is python setup.py For me, it results with can't open file 'setup.py': [Errno 2] No such file or directory 2) README.txt says: The Z MySQL database adapter uses the MySQLdb package...
Need help installing MySQL for Python
Trying to install MySQL for Python. Two problems: 1) Instructions over the net says installation is python setup.py For me, it results with can't open file 'setup.py': [Errno 2] No such file or directory 2) README.txt says: The Z MySQL database adapter uses the MySQLdb package.This must be installed before you can use ...
[ "You are confusing A Zope product (ZMySQLDA) with the python-mysqldb package.\nTry one of the download files, if it doesn't help, go for the source.\nNote that the source trunk is clearly divided into ZMySQLDA/ and MySQLdb/ .\n", "If you're using a Debian based distro you can :\napt-get install python-mysqldb ( o...
[ 2, 1 ]
[]
[]
[ "adapter", "mysql", "python", "zope" ]
stackoverflow_0001458500_adapter_mysql_python_zope.txt
Q: Find the file with a given SVN URL within a SVN working copy Given a starting point in a Subversion working copy (e.g. current working directory), and a target SVN URL, I'd like to find the file in the working copy that has that SVN URL. For example, given this current directory: c:\Subversion\ProjectA\a\b\c\ whi...
Find the file with a given SVN URL within a SVN working copy
Given a starting point in a Subversion working copy (e.g. current working directory), and a target SVN URL, I'd like to find the file in the working copy that has that SVN URL. For example, given this current directory: c:\Subversion\ProjectA\a\b\c\ which has this SVN URL: https://svnserver/svn/ProjectA/trunk/a/b/c/ ...
[ "Subversion doesn't use this backward mapping from url to working copy location itself. The most stable way to check for the url use would be to perform a recursive 'svn info' call over the working copy.\nThis gives you the url for all files and directories and you can do the matching yourself.\nYou could optimize ...
[ 4 ]
[]
[]
[ "pysvn", "python", "svn" ]
stackoverflow_0001458457_pysvn_python_svn.txt
Q: Python socket programming and ISO-OSI model I am sending packets from one pc to other. I am using python socket socket.socket(socket.AF_INET, socket.SOCK_DGRAM ). Do we need to take care of order in which packets are received ? In ISO-OSI model layers below transport layer handle all packets communication. Do all...
Python socket programming and ISO-OSI model
I am sending packets from one pc to other. I am using python socket socket.socket(socket.AF_INET, socket.SOCK_DGRAM ). Do we need to take care of order in which packets are received ? In ISO-OSI model layers below transport layer handle all packets communication. Do all ISO-OSI layers present in the program ? Or some ...
[ "SOCK_DGRAM means you want to send packets by UDP -- no order guarantee, no guarantee of reception, no guarantee of lack of repetition. SOCK_STREAM would imply TCP -- no packet boundary guarantee, but (unless the connection's dropped;-) guarantee of order, reception, and no duplication. TCP/IP, the networking mode...
[ 5, 4 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0001458087_python_sockets.txt
Q: Python - Is there a way around 'os.listdir()' returning gibberish for bad folder name? I have a simple script written in Python: import os def Path(SourcePath): for Folder in os.listdir(SourcePath): print "TESTING: %s" % Folder Path("\\\\192.168.0.36\\PDFs") When i run this it recurses through a rem...
Python - Is there a way around 'os.listdir()' returning gibberish for bad folder name?
I have a simple script written in Python: import os def Path(SourcePath): for Folder in os.listdir(SourcePath): print "TESTING: %s" % Folder Path("\\\\192.168.0.36\\PDFs") When i run this it recurses through a remote share on the LAN and just simply displays the names of the folders found. This share pri...
[ "Windows uses generated 8.3 \"placeholders\" when a filename over CIFS contains characters which are illegal in a Windows filename.\nIn this case, it's happening because your \"Santas Chocolate \" filename ends with a space. Windows filenames can't end with spaces, so it uses a placeholder to make the file accessi...
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001458847_python.txt
Q: Is there a C# equivalent to Python's unhexlify? Possible Duplicate: How to convert hex to a byte array? I'm searching for a python compatible method in C# to convert hex to binary. I've reversed a hash in Python by doing this: import sha import base64 import binascii hexvalue = "5baa61e4c9b93f3f0682250b6cf8331...
Is there a C# equivalent to Python's unhexlify?
Possible Duplicate: How to convert hex to a byte array? I'm searching for a python compatible method in C# to convert hex to binary. I've reversed a hash in Python by doing this: import sha import base64 import binascii hexvalue = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8" binaryval = binascii.unhexlify(hexvalue) ...
[ "This value is too big for a long (64bits), that's why you get an OverflowException.\nBut it's very easy to convert hex to binary byte by byte (well, nibble by nibble actually) :\nstatic string Hex2Binary(string hexvalue)\n{\n StringBuilder binaryval = new StringBuilder();\n for(int i=0; i < hexvalue.Length; ...
[ 6, 1 ]
[]
[]
[ "binary", "c#", "hex", "python" ]
stackoverflow_0001459006_binary_c#_hex_python.txt
Q: Reading a float from string I have a simple string that I want to read into a float without losing any visible information as illustrated below: s = ' 1.0000\n' When I do f = float(s), I get f=1.0 How to trick this to get f=1.0000 ? Thank you A: Direct answer: You can't. Floats are imprecise, by design. ...
Reading a float from string
I have a simple string that I want to read into a float without losing any visible information as illustrated below: s = ' 1.0000\n' When I do f = float(s), I get f=1.0 How to trick this to get f=1.0000 ? Thank you
[ "Direct answer: You can't. Floats are imprecise, by design. While python's floats have more than enough precision to represent 1.0000, they will never represent a \"1-point-zero-zero-zero-zero\". Chances are, this is as good as you need. You can always use string formatting, if you need to display four decimal d...
[ 9, 5, 1, 1 ]
[]
[]
[ "floating_point", "python", "string" ]
stackoverflow_0001458203_floating_point_python_string.txt
Q: How can I protect myself from a zip bomb? I just read about zip bombs, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...). When opened they fill the server's disk. How can I detect a zip file is a zip bomb before unzipping it? UPDATE Can you tell me how is this done in...
How can I protect myself from a zip bomb?
I just read about zip bombs, i.e. zip files that contain very large amount of highly compressible data (00000000000000000...). When opened they fill the server's disk. How can I detect a zip file is a zip bomb before unzipping it? UPDATE Can you tell me how is this done in Python or Java?
[ "Try this in Python:\nimport zipfile\n\nwith zipfile.ZipFile('a_file.zip') as z\n print(f'total files size={sum(e.file_size for e in z.infolist())}')\n\n", "Zip is, erm, an \"interesting\" format. A robust solution is to stream the data out, and stop when you have had enough. In Java, use ZipInputStream rather...
[ 25, 24, 13, 6, 5, 4, 1 ]
[]
[]
[ "compression", "java", "python", "security", "zip" ]
stackoverflow_0001459080_compression_java_python_security_zip.txt
Q: module reimported if imported from different path In a big application I am working, several people import same modules differently e.g. import x or from y import x the side effects of that is x is imported twice and may introduce very subtle bugs, if someone is relying on global attributes e.g. suppose I have a p...
module reimported if imported from different path
In a big application I am working, several people import same modules differently e.g. import x or from y import x the side effects of that is x is imported twice and may introduce very subtle bugs, if someone is relying on global attributes e.g. suppose I have a package mypakcage with three file mymodule.py, main.py a...
[ "Each module namespace is imported only once. Issue is, you're importing them differently. On the first you're importing from the global package, and on the second you're doing a local, non-packaged import. Python sees modules as different. The first import is internally cached as mypackage.mymodule and the second ...
[ 5, 3 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0001459236_python_python_import.txt
Q: Python ctypes and not enough arguments (4 bytes missing) The function i'm trying to call is: void FormatError (HRESULT hrError,PCHAR pszText); from a custom dll using windll. c_p = c_char_p() windll.thedll.FormatError(errcode, c_p) Results in: ValueError: Procedure probably called with not enough arguments (4 by...
Python ctypes and not enough arguments (4 bytes missing)
The function i'm trying to call is: void FormatError (HRESULT hrError,PCHAR pszText); from a custom dll using windll. c_p = c_char_p() windll.thedll.FormatError(errcode, c_p) Results in: ValueError: Procedure probably called with not enough arguments (4 bytes missing) Using cdll instead increases the bytes missing c...
[ "At the very least, you'll get more descriptive errors if you properly set up the argtypes and the restype.\nTry doing it this way:\nwindll.thedll.FormatError.argtypes = [ctypes.HRESULT, ctypes.c_char_p]\nwindll.thedll.FormatError.restype = None\n\nThere's also a very good chance you are using the wrong calling co...
[ 2, 0, 0 ]
[]
[]
[ "ctypes", "python", "windows" ]
stackoverflow_0001458813_ctypes_python_windows.txt
Q: pyparsing - load ABNF? can pyparsing read ABNF from a file instead of having to define it in terms of python objects? If not, is there something which can do similar (load an ABNF file into a parser object) A: See this example submitted by Seo Sanghyeon, which reads EBNF and parses it (using pyparsing) to creat...
pyparsing - load ABNF?
can pyparsing read ABNF from a file instead of having to define it in terms of python objects? If not, is there something which can do similar (load an ABNF file into a parser object)
[ "See this example submitted by Seo Sanghyeon, which reads EBNF and parses it (using pyparsing) to create a pyparsing parser.\n", "There are lots of Python parsing packages: Python Parsing Tools. ANTLR in particular is very well-respected, and reads a grammar from a dedicated file. \n" ]
[ 9, 2 ]
[]
[]
[ "parsing", "pyparsing", "python" ]
stackoverflow_0001459371_parsing_pyparsing_python.txt
Q: Trying to embed python into tinycc, says python symbols are undefined I've literally spent the past half hour searching for the solution to this, and everything involves GCC. What I do here works absolutely fine with GCC, however I'm using TinyCC, and this is where I'm getting confused. First the code: #include <P...
Trying to embed python into tinycc, says python symbols are undefined
I've literally spent the past half hour searching for the solution to this, and everything involves GCC. What I do here works absolutely fine with GCC, however I'm using TinyCC, and this is where I'm getting confused. First the code: #include <Python.h> #include <stdio.h> int main(int argc, char*argv[]) { Py_Initia...
[ "Did you use tiny_impdef.exe to create a .def file for the Python DLL?\n", "Full solution for Windows:\n\ntiny_impdef as per bk1e's advice\ntiny_impdef.exe c:\\WINDOWS\\system32\\python25.dll\nadd python25.def (or python26.def) to compilation list\ntcc tiny.c python25.def -IC:\\Python25\\include -LC:\\Python25\\l...
[ 3, 2 ]
[]
[]
[ "c", "compilation", "python" ]
stackoverflow_0000743044_c_compilation_python.txt