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: python introspection not showing functions for Lock When I try to use introspection to look at what methods are available on threading.Lock I don't see what I would expect. Specifically I don't see acquire, release or locked. Why is this? Here's what I do see: >>> dir (threading.Lock) ['__call__', '__class__', '_...
python introspection not showing functions for Lock
When I try to use introspection to look at what methods are available on threading.Lock I don't see what I would expect. Specifically I don't see acquire, release or locked. Why is this? Here's what I do see: >>> dir (threading.Lock) ['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__getattribute__', '_...
[ "You're doing it wrong. threading.Lock is not an object.\n>>> import threading\n>>> threading.Lock\n<built-in function allocate_lock>\n>>> type(threading.Lock)\n<type 'builtin_function_or_method'>\n>>> x=threading.Lock()\n>>> type(x)\n<type 'thread.lock'>\n>>> dir(x)\n['__enter__', '__exit__', 'acquire', 'acquire_...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0000394300_python.txt
Q: Finding when the ActiveApplication changes in OSX through Python Is there a way to find when the activeApplication changes in OSX through Python and AppKit? I know how to find out launchedApplication and activeApplication ( please refer to my other question here: Finding the Current Active Window in Mac OS X using...
Finding when the ActiveApplication changes in OSX through Python
Is there a way to find when the activeApplication changes in OSX through Python and AppKit? I know how to find out launchedApplication and activeApplication ( please refer to my other question here: Finding the Current Active Window in Mac OS X using Python )
[ "I've got an OS X app that does this by polling with an NSTimer. I tried searching for distributed notifications to see if I could find a better way to do it, but I couldn't see anything terribly useful.\nI did get notifications when application were launched or quit. which is at least a little helpful. You can s...
[ 1, 0 ]
[]
[]
[ "cocoa_touch", "macos", "python" ]
stackoverflow_0000394372_cocoa_touch_macos_python.txt
Q: Is there a simple way in Python to create a file which can be written to in one thread and read in a different one? In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-l...
Is there a simple way in Python to create a file which can be written to in one thread and read in a different one?
In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first threa...
[ "You should use the Queue module for sharing sequential data across threads. You would have to make a file-like Queue subclass, where .read and .write mutually block each other, with a buffer in-between.\nOTOH, I wonder why the first thread can't write to the real file in the first place.\n", "Use shutil's copyfi...
[ 5, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000394500_python.txt
Q: Python threads stack_size and segfaults A web crawler script that spawns at most 500 threads and each thread basically requests for certain data served from the remote server, which each server's reply is different in content and size from others. i'm setting stack_size as 756K's for threads threading.stack_size(7...
Python threads stack_size and segfaults
A web crawler script that spawns at most 500 threads and each thread basically requests for certain data served from the remote server, which each server's reply is different in content and size from others. i'm setting stack_size as 756K's for threads threading.stack_size(756*1024) which enables me to have the suffic...
[ "Why on earth are you spawning 500 threads? That seems like a terrible idea! \nRemove threading completely, use an event loop to do the crawling. Your program will be faster, simpler, and easier to maintain.\nLots of threads waiting for network won't make your program wait faster. Instead, collect all open sockets ...
[ 10 ]
[]
[]
[ "multithreading", "python", "segmentation_fault", "stack_size" ]
stackoverflow_0000394895_multithreading_python_segmentation_fault_stack_size.txt
Q: Python: Lock directory access under windows I'd like to be able to lock directory access under windows. The following code work greatly with file or directory under POSIX system: def flock(fd, blocking=False, exclusive=False): if exclusive: flags = fcntl.LOCK_EX else: flags = fcntl.LOCK_SH...
Python: Lock directory access under windows
I'd like to be able to lock directory access under windows. The following code work greatly with file or directory under POSIX system: def flock(fd, blocking=False, exclusive=False): if exclusive: flags = fcntl.LOCK_EX else: flags = fcntl.LOCK_SH if not blocking: flags |= fcntl.LOCK...
[ "I don't believe it's possible to use flock() on directories in windows. PHPs docs on flock() indicate that it won't even work on FAT32 filesystems.\nOn the other hand, Windows already tends to not allow you to delete files/directories if any files are still open. This, plus maybe using ACLs intelligently, might ...
[ 1, 0, 0 ]
[]
[]
[ "directory", "locking", "python", "windows" ]
stackoverflow_0000394439_directory_locking_python_windows.txt
Q: Calling Application Methods from a wx Frame Class I'm starting out with wxPython and have been working my way through every tutorial and example I can get my hands on. I've run into a slight problem, however, and it has to do with the wx.App versus the wx.Frame and which should contain specific methods. Just abo...
Calling Application Methods from a wx Frame Class
I'm starting out with wxPython and have been working my way through every tutorial and example I can get my hands on. I've run into a slight problem, however, and it has to do with the wx.App versus the wx.Frame and which should contain specific methods. Just about every example I've seen don't go much beyond layouts...
[ "As Mark stated you should make a new class that handles things like this. \nThe ideal layout of code when using something like wxWidgets is the model view controller where the wxFrame class only has the code needed to display items and all the logic and business rules are handled by other class that interact with ...
[ 2, 2, 2, 0 ]
[]
[]
[ "model_view_controller", "project_organization", "python", "wxpython", "wxwidgets" ]
stackoverflow_0000390867_model_view_controller_project_organization_python_wxpython_wxwidgets.txt
Q: Threads in Python General tutorial or good resource on how to use threads in Python? When to use threads, how they are effective, and some general background on threads [specific to Python]? A: Threads should be used when you want two things to run at once, or want something to run in the background without slow...
Threads in Python
General tutorial or good resource on how to use threads in Python? When to use threads, how they are effective, and some general background on threads [specific to Python]?
[ "Threads should be used when you want two things to run at once, or want something to run in the background without slowing down the main process.\nMy recommendation is to only use threads if you have to. They generally add complexity to a program.\nThe main documentation for threading is here: http://docs.python.o...
[ 13, 8, 3, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0000395704_multithreading_python.txt
Q: Caching compiled regex objects in Python? Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory. a = re.compile("a.*b") b = re.compile("c.*d") ... Question: Is it possible to s...
Caching compiled regex objects in Python?
Each time a python file is imported that contains a large quantity of static regular expressions, cpu cycles are spent compiling the strings into their representative state machines in memory. a = re.compile("a.*b") b = re.compile("c.*d") ... Question: Is it possible to store these regular expressions in a cache on di...
[ "\nIs it possible to store these regular expressions in a cache on disk in a pre-compiled manner to avoid having to execute the regex compilations on each import?\n\nNot easily. You'd have to write a custom serializer that hooks into the C sre implementation of the Python regex engine. Any performance benefits woul...
[ 13, 4, 2 ]
[ "The shelve module appears to work just fine:\n\nimport re\nimport shelve\na_pattern = \"a.*b\"\nb_pattern = \"c.*d\"\na = re.compile(a_pattern)\nb = re.compile(b_pattern)\n\nx = shelve.open('re_cache')\nx[a_pattern] = a\nx[b_pattern] = b\nx.close()\n\n# ...\nx = shelve.open('re_cache')\na = x[a_pattern]\nb = x[b_p...
[ -1, -1, -1 ]
[ "caching", "python", "regex" ]
stackoverflow_0000065266_caching_python_regex.txt
Q: "MetaClass", "__new__", "cls" and "super" - what is the mechanism exactly? I have read posts like these: What is a metaclass in Python? What are your (concrete) use-cases for metaclasses in Python? Python's Super is nifty, but you can't use it But somehow I got confused. Many confusions like: When and why would...
"MetaClass", "__new__", "cls" and "super" - what is the mechanism exactly?
I have read posts like these: What is a metaclass in Python? What are your (concrete) use-cases for metaclasses in Python? Python's Super is nifty, but you can't use it But somehow I got confused. Many confusions like: When and why would I have to do something like the following? # Refer link1 return super(MyType, c...
[ "OK, you've thrown quite a few concepts into the mix here! I'm going to pull out a few of the specific questions you have.\nIn general, understanding super, the MRO and metclasses is made much more complicated because there have been lots of changes in this tricky area over the last few versions of Python.\nPython'...
[ 25, 9 ]
[]
[]
[ "metaclass", "python", "super", "types" ]
stackoverflow_0000395982_metaclass_python_super_types.txt
Q: How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X? I'm new to the Mac OS X, and I'm just about ready to throw my brand new MacBook Pro out the window. Every tutorial on setting up a Django development environment on Mac OS X Leopard is ins...
How do I install MySQL and the Python MySQL package on OS X Leopard? Or how do I learn about being a web developer using OS X?
I'm new to the Mac OS X, and I'm just about ready to throw my brand new MacBook Pro out the window. Every tutorial on setting up a Django development environment on Mac OS X Leopard is insidiously wrong. They are all skipping over one step, or assuming you have setup something one way, or are just assuming that I know ...
[ "Did the MySQL and MySQL-dev installations go smoothly? Can you run MySQL, connect to it and so on? Does /usr/local/mysql/include contain lots of header files? (I've got 46 header files there, for reference).\nIf so, MySQL should be good to go. There are still a few manual steps required to compile MySQL-python, ho...
[ 12, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "django", "macos", "mysql", "python", "sysadmin" ]
stackoverflow_0000395509_django_macos_mysql_python_sysadmin.txt
Q: Desktop graphics - or "skinned" windows I'm looking for a way to draw animations right on the desktop. No window frames and with transparent background. I'm using Python in windows XP for it, but it doesn't have to be cross platform, although it'd be a nice bonus. Does anyone know about a python library that can d...
Desktop graphics - or "skinned" windows
I'm looking for a way to draw animations right on the desktop. No window frames and with transparent background. I'm using Python in windows XP for it, but it doesn't have to be cross platform, although it'd be a nice bonus. Does anyone know about a python library that can do this?
[ "If you want a frameless window, there are several options. For example, pygame can be initialized with the following flag:\npygame.init()\nscreen = pygame.display.set_mode(size=(640,480), pygame.NOFRAME)\n\nYour question doesn't make it clear if you're looking for a transparent surface, though.\n" ]
[ 2 ]
[]
[]
[ "desktop", "graphics", "python", "shaped_window", "skinning" ]
stackoverflow_0000396791_desktop_graphics_python_shaped_window_skinning.txt
Q: commands to send messages in Python via the Poplib module? I've found a number of tutorials online involving downloading messages via Poplib, but haven't been able to find anything explaining how to create new messages. Does this exist? A: As S.Lott rightly says, you will want some smtp, but to create the actua...
commands to send messages in Python via the Poplib module?
I've found a number of tutorials online involving downloading messages via Poplib, but haven't been able to find anything explaining how to create new messages. Does this exist?
[ "As S.Lott rightly says, you will want some smtp, but to create the actual email, use the email package from the standard library, then use an message's as_string method to send it.\nAn example with multipart MIME (how cool is that!)\n", "Send yourself an email to create a message.\nSMTP is the protocol the email...
[ 3, 2 ]
[]
[]
[ "email", "poplib", "python" ]
stackoverflow_0000396991_email_poplib_python.txt
Q: Trouble with encoding in emails I have a little python script that pulls emails from a POP mail address and dumps them into a file (one file one email) Then a PHP script runs through the files and displays them. I am having an issue with ISO-8859-1 (Latin-1) encoded email Here's an example of the text i get: =?iso...
Trouble with encoding in emails
I have a little python script that pulls emails from a POP mail address and dumps them into a file (one file one email) Then a PHP script runs through the files and displays them. I am having an issue with ISO-8859-1 (Latin-1) encoded email Here's an example of the text i get: =?iso-8859-1?Q?G=EDsli_Karlsson?= and Sj=E...
[ "You can use the python email library (python 2.5+) to avoid these problems:\nimport email\nimport poplib\nimport random\nfrom cStringIO import StringIO\nfrom email.generator import Generator\n\npop = poplib.POP3(server)\n\nmail_count = len(pop.list()[1])\n\nfor message_num in xrange(mail_count):\n message = \"\...
[ 3, 2, 2, 1, 0 ]
[]
[]
[ "email", "encoding", "python" ]
stackoverflow_0000389398_email_encoding_python.txt
Q: PHP vs. application server? For those of you who have had the opportunity of writing web applications in PHP and then as an application server (eg. Python-based solutions like CherryPy or Pylons), in what context are application servers a better alternative to PHP? I tend to favor PHP simply because it's available...
PHP vs. application server?
For those of you who have had the opportunity of writing web applications in PHP and then as an application server (eg. Python-based solutions like CherryPy or Pylons), in what context are application servers a better alternative to PHP? I tend to favor PHP simply because it's available on just about any web server (es...
[ "I have a feeling that some of the responses didn't address the initial question directly, so I decided to post my own. I understand that the question was about the difference between the mod_php deployment model and the application server deployment model.\nIn simple words, PHP executes a given script on every req...
[ 5, 4, 1, 1, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0000395960_php_python.txt
Q: django,fastcgi: how to manage a long running process? I have inherited a django+fastcgi application which needs to be modified to perform a lengthy computation (up to half an hour or more). What I want to do is run the computation in the background and return a "your job has been started" -type response. While the...
django,fastcgi: how to manage a long running process?
I have inherited a django+fastcgi application which needs to be modified to perform a lengthy computation (up to half an hour or more). What I want to do is run the computation in the background and return a "your job has been started" -type response. While the process is running, further hits to the url should return ...
[ "I have to solve a similar problem now. It is not going to be a public site, but similarly, an internal server with low traffic.\nTechnical constraints:\n\nall input data to the long running process can be supplied on its start\nlong running process does not require user interaction (except for the initial input to...
[ 4, 3 ]
[]
[]
[ "django", "fastcgi", "python" ]
stackoverflow_0000219329_django_fastcgi_python.txt
Q: Can I call and set the Python gettext module in a library and a module using it at the same time? Im a coding a library including textual feedback that I need to translate. I put the following lines in a _config.py module that I import everywhere in my app : import gettext, os, sys pathname = os.path.dirname(sys.a...
Can I call and set the Python gettext module in a library and a module using it at the same time?
Im a coding a library including textual feedback that I need to translate. I put the following lines in a _config.py module that I import everywhere in my app : import gettext, os, sys pathname = os.path.dirname(sys.argv[0]) localdir = os.path.abspath(pathname) + "/locale" gettext.install("messages", localdir) I have ...
[ "You can use the class based gettext api to isolate message catalogs. This is also what is recommended in the python gettext documentation.\nThe drawback is that you, or the other dev, will have to use the gettext method or define the _() method in the local scope, bound to the specific gettext class. An example of...
[ 4, 2 ]
[]
[]
[ "gettext", "internationalization", "python" ]
stackoverflow_0000246137_gettext_internationalization_python.txt
Q: Python Proxy Script I'm writing a simple python script so I can test my websites from a different ip address. The url of a page is given in the querystring, the script fetches the page and displays it to the user. The code below is used to rewrite the tags that contain urls but I don't think it's complete/totally ...
Python Proxy Script
I'm writing a simple python script so I can test my websites from a different ip address. The url of a page is given in the querystring, the script fetches the page and displays it to the user. The code below is used to rewrite the tags that contain urls but I don't think it's complete/totally correct. def rel2abs(rel_...
[ "Please read other postings here about parsing HTML. For example Python regular expression for HTML parsing (BeautifulSoup) and HTML parser in Python.\nUse Beautiful Soup, not regular expressions.\n" ]
[ 3 ]
[]
[]
[ "proxy", "python" ]
stackoverflow_0000398385_proxy_python.txt
Q: Split by \b when your regex engine doesn't support it How can I split by word boundary in a regex engine that doesn't support it? python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation. example input: "hello, foo" exp...
Split by \b when your regex engine doesn't support it
How can I split by word boundary in a regex engine that doesn't support it? python's re can match on \b but doesn't seem to support splitting on it. I seem to recall dealing with other regex engines that had the same limitation. example input: "hello, foo" expected output: ['hello', ', ', 'foo'] actual python output:...
[ "(\\W+) can give you the expected output:\n>>> re.compile(r'(\\W+)').split('hello, foo')\n['hello', ', ', 'foo']\n\n", "One can also use re.findall() for this:\n>>> re.findall(r'.+?\\b', 'hello, foo')\n['hello', ', ', 'foo']\n\n", "Ok I figured it out:\nPut the split pattern in capturing parens and will be incl...
[ 11, 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000398560_python_regex.txt
Q: Need help on selecting items in simple database in python I'm trying to write a circuit schematic drawing tool in Python. I'm creating a simple database based on dictionaries which holds all the components and their properties. I'm also trying to create a simple query language where you can select, for example, ...
Need help on selecting items in simple database in python
I'm trying to write a circuit schematic drawing tool in Python. I'm creating a simple database based on dictionaries which holds all the components and their properties. I'm also trying to create a simple query language where you can select, for example, all resistors with value>100ohms or footprint='0402' So far, ...
[ "You'll be a lot happier with a proper database.\nYou have SQLite with your Python distribution. Simply define tables instead of dictionaries and use SQL. \nIf you need more power and sophistication, you can add SQLAlchemy (or SQLObject) and you won't struggle with these problems.\n", "It really depends on how ...
[ 5, 3, 1 ]
[]
[]
[ "circuit", "eda", "python", "sql" ]
stackoverflow_0000399957_circuit_eda_python_sql.txt
Q: How do you get Python to write down the code of a function it has in memory? When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 Then I exe...
How do you get Python to write down the code of a function it has in memory?
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 Then I execute the file and get the data. Since the program is all on my machine and no one ...
[ "\nvinko@mithril$ more a.py\n\ndef foo(a):\n print a\n\nvinko@mithril$ more b.py\n\nimport a\nimport inspect\n\na.foo(89)\nprint inspect.getsource(a.foo)\n\nvinko@mithril$ python b.py\n89\ndef foo(a):\n print a\n\n\n", "You might also consider some other means of data persistence. In my own (astronomy) researc...
[ 15, 2, 0, 0, 0 ]
[]
[]
[ "artificial_intelligence", "python" ]
stackoverflow_0000399991_artificial_intelligence_python.txt
Q: Ignoring XML errors in Python I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser. Is it possible to ignore them, like a browser for example? I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible. A: There is a ...
Ignoring XML errors in Python
I am using XML minidom (xml.dom.minidom) in Python, but any error in the XML will kill the parser. Is it possible to ignore them, like a browser for example? I am trying to write a browser in Python, but it just throws an exception if the tags aren't fully compatible.
[ "There is a library called BeautifulSoup, I think it's what you're looking for.\nAs you're trying to parse a invalid XML, the normal XML parser won't work. BeautifulSoup is more fail-tolerant, it can still extract information from invalid XML.\n\nBeautiful Soup is a Python HTML/XML\n parser designed for quick turn...
[ 12, 3, 0 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0000399980_minidom_python_xml.txt
Q: Regex that only matches text that's not part of HTML markup? (python) How can I make a pattern match so long as it's not inside of an HTML tag? Here's my attempt below. Anyone have a better/different approach? import re inputstr = 'mary had a <b class="foo"> little loomb</b>' rx = re.compile('[aob]') repl = 'x' ...
Regex that only matches text that's not part of HTML markup? (python)
How can I make a pattern match so long as it's not inside of an HTML tag? Here's my attempt below. Anyone have a better/different approach? import re inputstr = 'mary had a <b class="foo"> little loomb</b>' rx = re.compile('[aob]') repl = 'x' outputstr = '' i = 0 for astr in re.compile(r'(<[^>]*>)').split(inputstr)...
[ "Since you are using Python anyway, if I were you, I would have a look at Beautiful Soup, which is a Python HTML/XML parser. Really, there are so many special cases and headaches with writing your own parser, it just doesn't worth the effort. Your regular expression will get unmanageably large and will still not yi...
[ 12 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000401726_python_regex.txt
Q: Why can't I subclass datetime.date? Why doesn't the following work (Python 2.5.2)? >>> import datetime >>> class D(datetime.date): def __init__(self, year): datetime.date.__init__(self, year, 1, 1) >>> D(2008) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: f...
Why can't I subclass datetime.date?
Why doesn't the following work (Python 2.5.2)? >>> import datetime >>> class D(datetime.date): def __init__(self, year): datetime.date.__init__(self, year, 1, 1) >>> D(2008) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: function takes exactly 3 arguments (1 give...
[ "Regarding several other answers, this doesn't have anything to do with dates being implemented in C per se. The __init__ method does nothing because they are immutable objects, therefore the constructor (__new__) should do all the work. You would see the same behavior subclassing int, str, etc.\n>>> import datet...
[ 40, 12, 4, 2, 1, 0 ]
[]
[]
[ "datetime", "oop", "python", "subclass" ]
stackoverflow_0000399022_datetime_oop_python_subclass.txt
Q: Help--Function Pointers in Python My idea of program: I have a dictionary: options = { 'string' : select_fun(function pointer), 'float' : select_fun(function pointer), 'double' : select_fun(function pointer) } whatever type comes single function select_fun(function pointer) gets called. Inside select_fun(function...
Help--Function Pointers in Python
My idea of program: I have a dictionary: options = { 'string' : select_fun(function pointer), 'float' : select_fun(function pointer), 'double' : select_fun(function pointer) } whatever type comes single function select_fun(function pointer) gets called. Inside select_fun(function pointer),I will have diff functions fo...
[ "Could you be more specific on what you're trying to do? You don't have to do anything special to get function pointers in Python -- you can pass around functions like regular objects:\ndef plus_1(x):\n return x + 1\n\ndef minus_1(x):\n return x - 1\n\nfunc_map = {'+' : plus_1, '-' : minus_1}\n\nfunc_map['+'...
[ 20, 6, 4, 4, 3 ]
[]
[]
[ "function", "pointers", "python" ]
stackoverflow_0000402364_function_pointers_python.txt
Q: Best way to organize the folders containing the SQLAlchemy models I use SQLAlchemy at work and it does the job really fine. Now I am thinking about best practices. For now, I create a module holding all the SQLA stuff : my_model |__ __init__.py |__ _config.py <<<<< contains LOGIN, HOST, and a Me...
Best way to organize the folders containing the SQLAlchemy models
I use SQLAlchemy at work and it does the job really fine. Now I am thinking about best practices. For now, I create a module holding all the SQLA stuff : my_model |__ __init__.py |__ _config.py <<<<< contains LOGIN, HOST, and a MetaData instance |__ table1.py <<<<< contains the class, the mo...
[ "Personally I like to keep the database / ORM logic out of the model classes. It makes them easier to test. I typically have something like a types.py which defines the types used in my application, but independent of the database.\nThen typically there is a db.py or something similar which has the Session class an...
[ 3 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0000362998_orm_python_sqlalchemy.txt
Q: Making the value of a table equal to another value in a different table I have a small problem with a program that im writing. I have a table - stocks which contains information(products, barcodes etc.) about items stored in a fridge. I then have another table - shop which acts like a shop,containing loads of prod...
Making the value of a table equal to another value in a different table
I have a small problem with a program that im writing. I have a table - stocks which contains information(products, barcodes etc.) about items stored in a fridge. I then have another table - shop which acts like a shop,containing loads of products and their barcodes.some of the products in the shop table are in the sto...
[ "So, if I got that right you have the following tables:\nStock with at least a barcode, amount and quantity column\nShop with at least a barcode and a stock column\nI don't understand why you need that stock column in the shop table, because you could easily get the products which are in stock by using a join like ...
[ 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0000403433_mysql_python.txt
Q: Calling from a parent file in python I have a file called main.py and a file called classes.py main.py contains the application and what's happening while class.py contains some classes. main.py has the following code main.py import classes def addItem(text): print text myClass = classes.ExampleClass() And ...
Calling from a parent file in python
I have a file called main.py and a file called classes.py main.py contains the application and what's happening while class.py contains some classes. main.py has the following code main.py import classes def addItem(text): print text myClass = classes.ExampleClass() And then we have classes.py classes.py class E...
[ "I couldn't answer this any better than this post by Alex Martelli. Basically any way you try to do this will lead to trouble and you are much better off refactoring the code to avoid mutual dependencies between two modules... \nIf you have two modules A and B which depend on each other, the easiest way is to isola...
[ 9, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000403822_python.txt
Q: Making a SQL Query in two tables I'm wondering, is it possible to make an sql query that does the same function as 'select products where barcode in table1 = barcode in table2'. I am writing this function in a python program. Once that function is called will the table be joined permanently or just while that fun...
Making a SQL Query in two tables
I'm wondering, is it possible to make an sql query that does the same function as 'select products where barcode in table1 = barcode in table2'. I am writing this function in a python program. Once that function is called will the table be joined permanently or just while that function is running? thanks.
[ "SELECT t1.products\nFROM [Table1] t1\nINNER JOIN [Table2] t2 ON t2.barcode = t1.barcode\n\n", "I think you want to join two tables:\nhttp://www.w3schools.com/Sql/sql_join.asp\n", "Something like:\nSELECT * FROM table1 WHERE barcode IN (SELECT barcode FROM table2)\n\nIs that what you're looking for?\n", "SELE...
[ 10, 7, 1, 0, 0, 0 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0000403527_python_sql.txt
Q: using results from a sql query in a python program in another sql query sorry for my previous question which was very ambiguous, but i think if i get the answer to this question I can work it out. In the program below i have selected the barcodes of products where the amount is less than the quantity. I want to sa...
using results from a sql query in a python program in another sql query
sorry for my previous question which was very ambiguous, but i think if i get the answer to this question I can work it out. In the program below i have selected the barcodes of products where the amount is less than the quantity. I want to say, that if the barcodes(in the fridge table) match barcodes in another table(...
[ "UPDATE products SET stock = 0 WHERE barcode IN ( \n SELECT fridge.barcode FROM fridge WHERE fridge.amount < fridge.quantity );\n\nI know this doesn't answer the question exactly but two SQL statements are not required.\nTo do it in python:\nimport MySQLdb\n\ndef order():\n db = MySQLdb.connect(host='localhos...
[ 5, 4 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0000403897_python_sql.txt
Q: All code in one file After asking organising my Python project and then calling from a parent file in Python it's occurring to me that it'll be so much easier to put all my code in one file (data will be read in externally). I've always thought that this was bad project organisation but it seems to be the easiest ...
All code in one file
After asking organising my Python project and then calling from a parent file in Python it's occurring to me that it'll be so much easier to put all my code in one file (data will be read in externally). I've always thought that this was bad project organisation but it seems to be the easiest way to deal with the probl...
[ "If you are planning to use any kind of SCM then you are going to be screwed. Having one file is a guaranteed way to have lots of collisions and merges that will be painstaking to deal with over time.\nStick to conventions and break apart your files. If nothing more than to save the guy who will one day have to mai...
[ 14, 4, 2, 2, 2, 2 ]
[]
[]
[ "project_management", "python", "version_control" ]
stackoverflow_0000403934_project_management_python_version_control.txt
Q: I need help--lists and Python How to return a list in Python??? When I tried returning a list,I got an empty list.What's the reason??? A: As Andrew commented, you will receive better answers if you show us the code you are currently using. Also if you could state what version of Python you are using that would b...
I need help--lists and Python
How to return a list in Python??? When I tried returning a list,I got an empty list.What's the reason???
[ "As Andrew commented, you will receive better answers if you show us the code you are currently using. Also if you could state what version of Python you are using that would be great.\nThere are a few ways you can return a list. Say for example we have a function called retlist.\ndef retlist():\n return []\n\nw...
[ 2, 0 ]
[]
[]
[ "list", "python", "return" ]
stackoverflow_0000404825_list_python_return.txt
Q: Scaling the y-axis with Matplotlib in Python How to scale the y-axis with Matplotlib? I don't want to change the y-limit, I just want to extend the physical space. ^ ^ | | | | +----> | Before +----> After A: Just use a larger height value when you instantiate the figure: from pylab import *...
Scaling the y-axis with Matplotlib in Python
How to scale the y-axis with Matplotlib? I don't want to change the y-limit, I just want to extend the physical space. ^ ^ | | | | +----> | Before +----> After
[ "Just use a larger height value when you instantiate the figure:\nfrom pylab import *\nx = linspace(0, 10*pi, 2**10)\ny = sin(x)\nfigure(figsize=(5, 10))\nplot(x, y)\nshow()\n\nWhere figsize=(width, height) and defaults to (8, 6). Values are in inches (the dpi keyword arg can be used to define the DPI for the figu...
[ 8, 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0000401787_matplotlib_python.txt
Q: Line reading chokes on 0x1A I have the following file: abcde kwakwa <0x1A> line3 linllll Where <0x1A> represents a byte with the hex value of 0x1A. When attempting to read this file in Python as: for line in open('t.txt'): print line, It only reads the first two lines, and exits the loop. The solution seems ...
Line reading chokes on 0x1A
I have the following file: abcde kwakwa <0x1A> line3 linllll Where <0x1A> represents a byte with the hex value of 0x1A. When attempting to read this file in Python as: for line in open('t.txt'): print line, It only reads the first two lines, and exits the loop. The solution seems to be to open the file in binary ...
[ "0x1A is Ctrl-Z, and DOS historically used that as an end-of-file marker. For example, try using a command prompt, and \"type\"ing your file. It will only display the content up the Ctrl-Z. \nPython uses the Windows CRT function _wfopen, which implements the \"Ctrl-Z is EOF\" semantics.\n", "Ned is of course c...
[ 28, 9 ]
[]
[]
[ "binary_data", "python", "windows" ]
stackoverflow_0000405058_binary_data_python_windows.txt
Q: I can't but help get the idea I'm doing it all wrong (Python, again) All of the questions that I've asked recently about Python have been for this project. I have realised that the reason I'm asking so many questions may not be because I'm so new to Python (but I know a good bit of PHP) and is probably not because...
I can't but help get the idea I'm doing it all wrong (Python, again)
All of the questions that I've asked recently about Python have been for this project. I have realised that the reason I'm asking so many questions may not be because I'm so new to Python (but I know a good bit of PHP) and is probably not because Python has some inherent flaw. Thus I will now say what the project is an...
[ "\nWith Python I have to remake that\n array each time I import the relevant\n data file\n\nYou're missing a subtle point of Python semantics here. When you import a module for a second time, you aren't re-executing the code in that module. The name is found in a list of all modules imported, and the same modul...
[ 5, 3, 3, 1 ]
[]
[]
[ "php", "project", "project_planning", "python" ]
stackoverflow_0000405106_php_project_project_planning_python.txt
Q: Accepting File Argument in Python (from Send To context menu) I'm going to start of by noting that I have next to no python experience. alt text http://www.aquate.us/u/9986423875612301299.jpg As you may know, by simply dropping a shortcut in the Send To folder on your Windows PC, you can allow a program to take a ...
Accepting File Argument in Python (from Send To context menu)
I'm going to start of by noting that I have next to no python experience. alt text http://www.aquate.us/u/9986423875612301299.jpg As you may know, by simply dropping a shortcut in the Send To folder on your Windows PC, you can allow a program to take a file as an argument. How would I write a python program that takes ...
[ "\nFind out what the dragged file was: http://docs.python.org/library/sys.html#sys.argv\nOpen it: http://docs.python.org/library/functions.html#open\nRead it in: http://docs.python.org/library/stdtypes.html#file.read\nPost it: http://docs.python.org/library/urllib2.html#urllib2.urlopen\n\n", "import sys\n\nfor ar...
[ 7, 2 ]
[]
[]
[ "contextmenu", "python", "sendto", "urllib2" ]
stackoverflow_0000405612_contextmenu_python_sendto_urllib2.txt
Q: insert two values from an mysql table into another table using a python program I'm having a small problem with a Python program (below) that I'm writing. I want to insert two values from a MySQL table into another table from a Python program. The two fields are priority and product and I have selected them from ...
insert two values from an mysql table into another table using a python program
I'm having a small problem with a Python program (below) that I'm writing. I want to insert two values from a MySQL table into another table from a Python program. The two fields are priority and product and I have selected them from the shop table and I want to insert them into the products table. Can anyone help? T...
[ "Well, the same thing again:\nimport MySQLdb\n\ndef checkOut():\n db = MySQLdb.connect(host='localhost', user = 'root', passwd = '$$', db = 'fillmyfridge')\n cursor = db.cursor(MySQLdb.cursors.DictCursor)\n user_input = raw_input('please enter the product barcode that you are taking out of the fridge: \\n'...
[ 1, 1 ]
[]
[]
[ "database", "mysql", "python" ]
stackoverflow_0000405617_database_mysql_python.txt
Q: Modifying Microsoft Outlook contacts from Python I have written a few Python tools in the past to extract data from my Outlook contacts. Now, I am trying to modify my Outlook Contacts. I am finding that my changes are being noted by Outlook, but they aren't sticking. I seem to be updating some cache, but not the r...
Modifying Microsoft Outlook contacts from Python
I have written a few Python tools in the past to extract data from my Outlook contacts. Now, I am trying to modify my Outlook Contacts. I am finding that my changes are being noted by Outlook, but they aren't sticking. I seem to be updating some cache, but not the real record. The code is straightforward. import win32c...
[ "I believe there is a .Save() method on the contact, so you need to add:\ncontact.Save()\n" ]
[ 6 ]
[]
[]
[ "mapi", "outlook", "python", "winapi" ]
stackoverflow_0000405724_mapi_outlook_python_winapi.txt
Q: Many instances of a class I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be. So, my question: How can I automatically give a name to an object? I was thinking of...
Many instances of a class
I am trying to write a life simulation in python with a variety of animals. It is impossible to name each instance of the classes I am going to use because I have no way of knowing how many there will be. So, my question: How can I automatically give a name to an object? I was thinking of creating a "Herd" class which ...
[ "Hm, well you normally just stuff all those instances in a list and then iterate over that list if you want to do something with them. If you want to automatically keep track of each instance created you can also make the adding to the list implicit in the class' constructor or create a factory method that keeps tr...
[ 8, 5, 4, 2, 1 ]
[]
[]
[ "class", "multiple_instances", "object", "python" ]
stackoverflow_0000405282_class_multiple_instances_object_python.txt
Q: Assigning a 'for loop' to a variable in a python program Im writing a program at the moment that interacts with a MySQL database and im having a problem. As you can see I've written a query that will look for products in the products table that corresponds to the barcode that the user has inputted. If the barcode...
Assigning a 'for loop' to a variable in a python program
Im writing a program at the moment that interacts with a MySQL database and im having a problem. As you can see I've written a query that will look for products in the products table that corresponds to the barcode that the user has inputted. If the barcode that is input by the user is found in the products table, I w...
[ "The answer depends on what you mean by \"assign a variable to a for loop.\" This wording is confusing because a for loop is a tool for controlling the flow of execution -- it's not normally thought of as having a value. But I think I know what you mean. Every time the loop runs, it will execute print \"%s\" % (row...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "database", "input", "mysql", "python" ]
stackoverflow_0000399032_database_input_mysql_python.txt
Q: opengl set texture color with vertex color Because I need to display a huge number of labels that move independently, I need to render a label in pyglet to a texture (otherwise updating the vertex list for each glyph is too slow). I have a solution to do this, but my problem is that the texture that contains the g...
opengl set texture color with vertex color
Because I need to display a huge number of labels that move independently, I need to render a label in pyglet to a texture (otherwise updating the vertex list for each glyph is too slow). I have a solution to do this, but my problem is that the texture that contains the glyphs is black, but I'd like it to be red. See t...
[ "You want to set glEnable(GL_COLOR_MATERIAL). This makes the texture color mix with the current OpenGL color. You can also use the glColorMaterial function to specify whether the front/back/both of each polygon should be affected. Docs here.\n", "Isn't that when you use decaling, through glTexEnv()?\n" ]
[ 2, 0 ]
[]
[]
[ "opengl", "pyglet", "python" ]
stackoverflow_0000244720_opengl_pyglet_python.txt
Q: How do you fix a Trac installation that begins giving errors relating to PYTHON_EGG_CACHE? We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in: PythonHandler tr...
How do you fix a Trac installation that begins giving errors relating to PYTHON_EGG_CACHE?
We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in: PythonHandler trac.web.modpython_frontend: ExtractionError: Can't extract file(s) to egg cache The following ...
[ "That should be fixed in 0.11 according to their bug tracking system. \nIf that's not the case you should try to pass the environment var to apache, since doing a SetEnv in the configuration file doesn't work. Adding something like \nexport PYTHON_EGG_CACHE=/tmp/python_eggs\n\nto the script you use to start apache ...
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "configuration", "python", "python_egg_cache", "trac" ]
stackoverflow_0000215267_configuration_python_python_egg_cache_trac.txt
Q: What does asterisk * mean in Python? Does * have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook: def get(self, *a, **kw) Would you please explain it to me or point out where I can find an answer (Google interprets the * as wild card character and thus I cannot find ...
What does asterisk * mean in Python?
Does * have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook: def get(self, *a, **kw) Would you please explain it to me or point out where I can find an answer (Google interprets the * as wild card character and thus I cannot find a satisfactory answer).
[ "See Function Definitions in the Language Reference.\n\nIf the form *identifier is\n present, it is initialized to a tuple\n receiving any excess positional\n parameters, defaulting to the empty\n tuple. If the form **identifier is\n present, it is initialized to a new\n dictionary receiving any excess\n key...
[ 345, 201, 93, 41, 30 ]
[]
[]
[ "python" ]
stackoverflow_0000400739_python.txt
Q: ForeignKey form restrictions in Django I'm using Django to write a blog app, and I'm trying to implement a hierarchical category structure. Each category has a "parent" ForeignKey pointing back to the same Category model. I want to allow admins to add categories, and I want the interface to allow them to select ...
ForeignKey form restrictions in Django
I'm using Django to write a blog app, and I'm trying to implement a hierarchical category structure. Each category has a "parent" ForeignKey pointing back to the same Category model. I want to allow admins to add categories, and I want the interface to allow them to select a category's parent category. However, I wa...
[ "I have had to deal with arbitrary-depth categories on SQL and it seems not well suited for storing data of this type in a normal form, as nested queries and/or multiple JOINs tend to get ugly extremely quickly.\nThis is almost the only case where I would go with a sort of improper solution, namely to store categor...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000401118_django_django_forms_python.txt
Q: Hiding implementation details on an email templating system written in Python I am writing an application where one of the features is to allow the user to write an email template using Markdown syntax. Besides formatting, the user must be able to use placeholders for a couple of variables that would get replaced ...
Hiding implementation details on an email templating system written in Python
I am writing an application where one of the features is to allow the user to write an email template using Markdown syntax. Besides formatting, the user must be able to use placeholders for a couple of variables that would get replaced at runtime. The way this is currently working is very simple: the templates have t...
[ "Use a real template tool: mako or jinja. Don't roll your own. Not worth it.\n", "Have a light templating system ... I am not sure if you can use some of the ones TurboGears provides (Kid or Genshi)\n", "I would recommend jinja2.\nIt shouldn't create runtime performance issue since it compiles templates to py...
[ 6, 2, 1, 0 ]
[]
[]
[ "email", "formatting", "python", "templates" ]
stackoverflow_0000405509_email_formatting_python_templates.txt
Q: Most pythonic form for mapping a series of statements? This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic vers...
Most pythonic form for mapping a series of statements?
This is something that has bugged me for some time. I learnt Haskell before I learnt Python, so I've always been fond of thinking of many computations as a mapping onto a list. This is beautifully expressed by a list comprehension (I'm giving the pythonic version here): result = [ f(x) for x in list ] In many cases th...
[ "You can easily do function composition in Python. \nHere's a demonstrates of a way to create a new function which is a composition of existing functions.\n>>> def comp( a, b ):\n def compose( args ):\n return a( b( args ) )\n return compose\n\n>>> def times2(x): return x*2\n\n>>> def plus1(x): return...
[ 5, 3, 2, 1, 1, 1, 0 ]
[]
[]
[ "coding_style", "idioms", "python" ]
stackoverflow_0000352076_coding_style_idioms_python.txt
Q: How to intercept special (alt / ctrl) key press? How can I catch key combinations like ALT+K or CTRL+ALT+H in python curses? A: A terminal converts the control key in combination with a letter key to a normal ASCII code. This can be read from the getch() function like any other key press. CTRL-A: getch() returns...
How to intercept special (alt / ctrl) key press?
How can I catch key combinations like ALT+K or CTRL+ALT+H in python curses?
[ "A terminal converts the control key in combination with a letter key to a normal ASCII code. This can be read from the getch() function like any other key press.\nCTRL-A: getch() returns 1\nCTRL-B: getch() returns 2\n...\nCTRL-Z: getch() returns 26\n\nAlso, the keypad() function must be called to enable other spec...
[ 12 ]
[]
[]
[ "curses", "python" ]
stackoverflow_0000406933_curses_python.txt
Q: Floating Point Limitations My code: a = '2.3' I wanted to display a as a floating point value. Since a is a string, I tried: float(a) The result I got was : 2.2999999999999998 I want a solution for this problem. Please, kindly help me. I was following this tutorial. A: I think it reflects more on your underst...
Floating Point Limitations
My code: a = '2.3' I wanted to display a as a floating point value. Since a is a string, I tried: float(a) The result I got was : 2.2999999999999998 I want a solution for this problem. Please, kindly help me. I was following this tutorial.
[ "I think it reflects more on your understanding of floating point types than on Python. See my article about floating point numbers (.NET-based, but still relevant) for the reasons behind this \"inaccuracy\". If you need to keep the exact decimal representation, you should use the decimal module.\n", "This is not...
[ 19, 6, 5 ]
[]
[]
[ "floating_accuracy", "floating_point", "precision", "python" ]
stackoverflow_0000406361_floating_accuracy_floating_point_precision_python.txt
Q: How to synchronize the same object on client and server side in client-server application? Is small messages framework good for this job? I'm making a game engine in c++ and python. I'm using OGRE for 3D rendering, OpenAL for sound, ODE for physics, OIS for input, HawkNL for networking and boost.python for embedde...
How to synchronize the same object on client and server side in client-server application? Is small messages framework good for this job?
I'm making a game engine in c++ and python. I'm using OGRE for 3D rendering, OpenAL for sound, ODE for physics, OIS for input, HawkNL for networking and boost.python for embedded python interpreter. Every subsystem (library) is wrapped by a class - manager and every manager is singleton. Now, I have a class - Object - ...
[ "It sounds like you would be sending a lot of tiny messages. The UDP and IP headers will add 28 bytes of overhead (20 bytes for the IPv4 header or 40 for IPv6 plus 8 bytes for the UDP header). So, I would suggest combining multiple messages to be dispatched together at a perioidic rate.\nYou may also want to read t...
[ 7 ]
[]
[]
[ "c++", "oop", "python" ]
stackoverflow_0000407464_c++_oop_python.txt
Q: Prevent Python subprocess from passing fds on Windows? Python's subprocess module by default passes all open file descriptors to any child processes it spawns. This means that if the parent process is listening on a port, and is killed, it cannot restart and begin listening again (even using SO_REUSEADDR) because...
Prevent Python subprocess from passing fds on Windows?
Python's subprocess module by default passes all open file descriptors to any child processes it spawns. This means that if the parent process is listening on a port, and is killed, it cannot restart and begin listening again (even using SO_REUSEADDR) because the child is still in possession of that descriptor. I hav...
[ "What seems to be the most relevant information that I can find: SetHandleInformation, referenced in this article, should give you pointers.\nYou'll probably need to use pywin32 and/or ctypes to accomplish what you want.\n" ]
[ 2 ]
[ "I don't have a windows box around, so this is untested, but I'd be tempted to try the os.dup and os.dup2 methods; duplicate the file descriptors and use those instead of the parent ones.\n" ]
[ -2 ]
[ "popen", "python", "subprocess", "windows" ]
stackoverflow_0000408039_popen_python_subprocess_windows.txt
Q: Iterate over subclasses of a given class in a given module In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X? A: Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more p...
Iterate over subclasses of a given class in a given module
In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?
[ "Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more pythonic. They rely on using the inspect module from the standard library.\n\nYou can avoid the getattr call by using inspect.getmembers()\nThe try/catch can be avoided by using inspect.isclas...
[ 21, 14, 4, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0000044352_oop_python.txt
Q: How to produce a 303 Http Response in Django? Last couple of days we were discussing at another question the best to manage randomness in a RESTful way; today I went to play a little bit with some ideas in Django only to find that there is no easy standard way of returning a 303 response (nor a 300 one, btw), that...
How to produce a 303 Http Response in Django?
Last couple of days we were discussing at another question the best to manage randomness in a RESTful way; today I went to play a little bit with some ideas in Django only to find that there is no easy standard way of returning a 303 response (nor a 300 one, btw), that is, there doesn't seem to exist an HttpResponseSee...
[ "You could just override HttpResponse, like the other Responses do:\nclass HttpResponseSeeOther(HttpResponseRedirect):\n status_code = 303\n\nreturn HttpResponseSeeOther('/other-url/')\n\n", "The generic HttpResponse object lets you specify any status code you want:\nresponse = HttpResponse(content=\"\", statu...
[ 31, 21 ]
[]
[]
[ "django", "http", "python", "rest" ]
stackoverflow_0000408541_django_http_python_rest.txt
Q: In Windows, how can I enumerate and get text from another window's controls? More particularly - I have a window handle of another running application. This application contains a TListControl.UnicodeClass control somewhere (I know this from Winspector). How can I, using the Windows API and that window handle, go ...
In Windows, how can I enumerate and get text from another window's controls?
More particularly - I have a window handle of another running application. This application contains a TListControl.UnicodeClass control somewhere (I know this from Winspector). How can I, using the Windows API and that window handle, go through all the items in that list control and get the text from all of the items?...
[ "You want EnumWindows and EnumChildWindows for the enumeration. See here for examples and usage info/warnings.\nFor window text, once you have the appropriate HWND, you want GetWindowText in general, and control-specific API's if the text is stored in a different place (eg: list controls). For the specific control,...
[ 5, 2 ]
[]
[]
[ "controls", "python", "winapi", "windows" ]
stackoverflow_0000408334_controls_python_winapi_windows.txt
Q: Python mailbox encoding errors First, let me say that I'm a complete beginner at Python. I've never learned the language, I just thought "how hard can it be" when Google turned up nothing but Python snippets to solve my problem. :) I have a bunch of mailboxes in Maildir format (a backup from the mail server on my ...
Python mailbox encoding errors
First, let me say that I'm a complete beginner at Python. I've never learned the language, I just thought "how hard can it be" when Google turned up nothing but Python snippets to solve my problem. :) I have a bunch of mailboxes in Maildir format (a backup from the mail server on my old web host), and I need to extract...
[ "Try it in Python 2.5 or 2.6 instead of 3.0. 3.0 has completely different Unicode handling and this module may not have been updated for 3.0. \n", "Note \n\n@Jimmy2Times could be very True in saying that this module may not be updated for 3.0.\nThis is not an answer particularly rather a probable explanation of ...
[ 4, 4 ]
[]
[]
[ "email_formats", "encoding", "python" ]
stackoverflow_0000409217_email_formats_encoding_python.txt
Q: Loop function parameters for sanity check I have a Python function in which I am doing some sanitisation of the input parameters: def func(param1, param2, param3): param1 = param1 or '' param2 = param2 or '' param3 = param3 or '' This caters for the arguments being passed as None rather than empty str...
Loop function parameters for sanity check
I have a Python function in which I am doing some sanitisation of the input parameters: def func(param1, param2, param3): param1 = param1 or '' param2 = param2 or '' param3 = param3 or '' This caters for the arguments being passed as None rather than empty strings. Is there an easier/more concise way to lo...
[ "This looks like a good job for a decorator. How about this:\ndef sanitized(func):\n def sfunc(*args, **kwds):\n return func(*[arg or '' for arg in args],\n **dict((k, v or '') for k,v in kwds.iteritems()))\n sfunc.func_name = func.func_name\n sfunc.func_doc = func.func_doc\n r...
[ 7, 2 ]
[ "def func(x='', y='', z='hooray!'):\n print x, y, z\n\nIn [2]: f('test')\ntest hooray!\n\nIn [3]: f('test', 'and')\ntest and hooray!\n\nIn [4]: f('test', 'and', 'done!')\ntest and done!\n\n" ]
[ -2 ]
[ "arguments", "function", "parameters", "python", "sanitization" ]
stackoverflow_0000409449_arguments_function_parameters_python_sanitization.txt
Q: What versions of Python and wxPython correspond to each version of OSX? I'd like to know what versions of Python and wxPython correspond to each version of OSX. I'm interested to know exactly how far back some of my apps will remain compatible on a mac before having to install newer versions of Python and wxPytho...
What versions of Python and wxPython correspond to each version of OSX?
I'd like to know what versions of Python and wxPython correspond to each version of OSX. I'm interested to know exactly how far back some of my apps will remain compatible on a mac before having to install newer versions of Python and wxPython.
[ "Tiger shipped with Python 2.3.5 and wxPython 2.5.3, Leopard ships with python 2.5.1 and wxPython 2.8.4.\nwxPython was not shipped with previous versions.\n\nOSX Lion has 2.7.1\n" ]
[ 3 ]
[]
[]
[ "compatibility", "macos", "python", "wxpython" ]
stackoverflow_0000409677_compatibility_macos_python_wxpython.txt
Q: Alter elements of a list I have a list of booleans where occasionally I reset them all to false. After first writing the reset as: for b in bool_list: b = False I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the...
Alter elements of a list
I have a list of booleans where occasionally I reset them all to false. After first writing the reset as: for b in bool_list: b = False I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rew...
[ "If you only have one reference to the list, the following may be easier:\nbool_list = [False] * len(bool_list)\n\nThis creates a new list populated with False elements.\nSee my answer to Python dictionary clear for a similar example.\n", "Here's another version:\nbool_list = [False for item in bool_list]\n\n", ...
[ 13, 13, 12, 11, 4, 3, 0, 0 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0000409732_coding_style_python.txt
Q: How to compare and search list of integers efficiently? I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers. For example: object1: tags(1,3,4) object2: tags(2) object3: tags(3,4) object4: tags(5) and so on. Query parameter is a set on integers, lets try q(3,4,5) ob...
How to compare and search list of integers efficiently?
I have a database populated with 1 million objects. Each object has a 'tags' field - set of integers. For example: object1: tags(1,3,4) object2: tags(2) object3: tags(3,4) object4: tags(5) and so on. Query parameter is a set on integers, lets try q(3,4,5) object1 does not match ('1' not in '3,4,5') object2 does not ma...
[ "Given that you are using PostgreSQL, you could use its array datatype and its contains/overlaps operators.\nOf course this would tie your app to PostgreSQL tightly, which may not be desired. On the other hand, it may save you coding for when it's really needed (ie, when you finally have to port it to another datab...
[ 3, 3, 1, 0, 0, 0, 0 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0000408855_postgresql_python.txt
Q: What's the best way to upgrade from Django 0.96 to 1.0? Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can? A: Although this depends on what you're doing, most applications should be able to just upgrade and then fix everything that...
What's the best way to upgrade from Django 0.96 to 1.0?
Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can?
[ "Although this depends on what you're doing, most applications should be able to just upgrade and then fix everything that breaks. In my experience, the main things that I've had to fix after an upgrade are\n\nChanges to some of the funky stuff with models, such as the syntax for following foreign keys.\nA small s...
[ 7, 3, 2, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000128466_django_python.txt
Q: Avoid exceptions? This particular example relates to Django in Python, but should apply to any language supporting exceptions: try: object = ModelClass.objects.get(search=value) except DoesNotExist: pass if object: # do stuff The Django model class provides a simple method get which allows me to sear...
Avoid exceptions?
This particular example relates to Django in Python, but should apply to any language supporting exceptions: try: object = ModelClass.objects.get(search=value) except DoesNotExist: pass if object: # do stuff The Django model class provides a simple method get which allows me to search for one and only one...
[ "Believe it or not, this actually is an issue that is a bit different in each language. In Python, exceptions are regularly thrown for events that aren't exceptional by the language itself. Thus I think that the \"you should only throw exceptions under exceptional circumstances\" rule doesn't quite apply. I thin...
[ 11, 8, 5, 3, 2, 2, 2 ]
[]
[]
[ "django", "exception", "python" ]
stackoverflow_0000409529_django_exception_python.txt
Q: Best modules to develop a simple windowed 3D modeling application? I want to create a very basic 3D modeling tool. The application is supposed to be windowed and will need to respond to mouse click and drag events in the 3D viewport. I've decided on wxPython for the actual window since I'm fairly familiar with it...
Best modules to develop a simple windowed 3D modeling application?
I want to create a very basic 3D modeling tool. The application is supposed to be windowed and will need to respond to mouse click and drag events in the 3D viewport. I've decided on wxPython for the actual window since I'm fairly familiar with it already. However, I need to produce an OpenGL viewport that can respon...
[ "Any reason you wouldn't use wx's GLCanvas? Here's an example that draws a sphere.\n", "As a very basic 3D modelling tool I'd recommend VPython.\n", "I'm not aware of any boxed up modules which provide that functionality, but you can take some inspiration from Blender 3D, which has all of the features you descr...
[ 3, 2, 1 ]
[]
[]
[ "3d", "opengl", "python", "wxpython" ]
stackoverflow_0000410941_3d_opengl_python_wxpython.txt
Q: gtk.Builder, container subclass and binding child widgets I'm trying to use custom container widgets in gtk.Builder definition files. As far as instantiating those widgets, it works great: #!/usr/bin/env python import sys import gtk class MyDialog(gtk.Dialog): __gtype_name__ = "MyDialog" if __name__ == "_...
gtk.Builder, container subclass and binding child widgets
I'm trying to use custom container widgets in gtk.Builder definition files. As far as instantiating those widgets, it works great: #!/usr/bin/env python import sys import gtk class MyDialog(gtk.Dialog): __gtype_name__ = "MyDialog" if __name__ == "__main__": builder = gtk.Builder() builder.add_from_fil...
[ "Alright, I guess I answered my own question.\nOne way to do the above is to override gtk.Buildable's parser_finished(), which gives access to the builder object that created the class instance itself. The method is called after entire .xml file has been loaded, so all of the additional widgets we may want to get h...
[ 5 ]
[]
[]
[ "bind", "gtk", "gtkbuilder", "python", "subclass" ]
stackoverflow_0000411708_bind_gtk_gtkbuilder_python_subclass.txt
Q: Variable number of inputs with Django forms possible? Is it possible to have a variable number of fields using django forms? The specific application is this: A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pi...
Variable number of inputs with Django forms possible?
Is it possible to have a variable number of fields using django forms? The specific application is this: A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures will ...
[ "Yes, it's possible to create forms dynamically in Django. You can even mix and match dynamic fields with normal fields.\nclass EligibilityForm(forms.Form):\n def __init__(self, *args, **kwargs):\n super(EligibilityForm, self).__init__(*args, **kwargs)\n # dynamic fields here ...\n self.fie...
[ 20, 7, 7 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000411761_django_django_forms_python.txt
Q: How to access to the root path in a mod_python directory? In my Apache webserver I put this: <Directory /var/www/MYDOMAIN.com/htdocs> SetHandler mod_python PythonHandler mod_python.publisher PythonDebug On </Directory> Then I have a handler.py file with an index function. When I go to MYDOMAIN.com/han...
How to access to the root path in a mod_python directory?
In my Apache webserver I put this: <Directory /var/www/MYDOMAIN.com/htdocs> SetHandler mod_python PythonHandler mod_python.publisher PythonDebug On </Directory> Then I have a handler.py file with an index function. When I go to MYDOMAIN.com/handler.py, I see a web page produced by the index function (just ...
[ "Yes, but you need to create your own handler. You currently use publisher, it just checks the URI and loads given python module.\nTo create your own handler you need to create a module like this (just a minimalistic example):\nfrom mod_python import apache\n\ndef requesthandler(req):\n req.content_type = \"text...
[ 2, 0 ]
[]
[]
[ "mod_python", "publisher", "python" ]
stackoverflow_0000412498_mod_python_publisher_python.txt
Q: Algorithm to keep a list of percentages to add up to 100% (code examples are python) Lets assume we have a list of percentages that add up to 100: mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] Some values of mylist may be changed, others must stay fixed. Lets assume the first 3 (2.0, 7.0, 12.0) must stay fixed an...
Algorithm to keep a list of percentages to add up to 100%
(code examples are python) Lets assume we have a list of percentages that add up to 100: mylist = [2.0, 7.0, 12.0, 35.0, 21.0, 23.0] Some values of mylist may be changed, others must stay fixed. Lets assume the first 3 (2.0, 7.0, 12.0) must stay fixed and the last three (35.0, 21.0, 23.0) may be changed. fix = mylis...
[ "How's this?\ndef adjustAppend( v, n ):\n weight= -n/sum(v)\n return [ i+i*weight for i in v ] + [n]\n\nGiven a list of numbers v, append a new number, n.\nWeight the existing number to keep the sum the same.\n sum(v) == sum( v + [n] )\n\nEach element of v, i, must be reduced by some function of i, r(i) such ...
[ 9, 3, 3, 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0000412943_algorithm_python.txt
Q: Apps Similar to Nodebox? I'm looking for apps/environments similar to Nodebox. Nodebox is so cool and I want to know if there were other similar apps out there. They don't have to be graphics-related; I'm interested in software that uses programming languages in a new way. A: http://processing.org/ is a languag...
Apps Similar to Nodebox?
I'm looking for apps/environments similar to Nodebox. Nodebox is so cool and I want to know if there were other similar apps out there. They don't have to be graphics-related; I'm interested in software that uses programming languages in a new way.
[ "http://processing.org/ is a language for creating graphics and animations similar to Nodebox.\n", "it was referenced on @Jonas processing.org, but alice.org is interesting.\n" ]
[ 5, 0 ]
[]
[]
[ "nodebox", "python" ]
stackoverflow_0000412775_nodebox_python.txt
Q: Django and units conversion I need to store some values in the database, distance, weight etc. In my model, I have field that contains quantity of something and IntegerField with choices option, that determines what this quantity means (length, time duration etc). Should I create a model for units and physical qu...
Django and units conversion
I need to store some values in the database, distance, weight etc. In my model, I have field that contains quantity of something and IntegerField with choices option, that determines what this quantity means (length, time duration etc). Should I create a model for units and physical quantity or should I use IntegerFie...
[ "By field(enum)\" do you mean you are using the choices option on a field? \nA simple set of choices works out reasonably well for small lists of conversions. It allows you to make simplifying assumptions that helps your users (and you) get something that works.\nCreating a formal model for units should only be d...
[ 4, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000413446_django_python.txt
Q: Is there a Python library than can simulate network traffic from different addresses Is there a python library out there than can allow me to send UDP packets to a machine (sending to localhost is ok) from different source addresses and ports? I remember that one existed, but can't find it anymore. A: You can s...
Is there a Python library than can simulate network traffic from different addresses
Is there a python library out there than can allow me to send UDP packets to a machine (sending to localhost is ok) from different source addresses and ports? I remember that one existed, but can't find it anymore.
[ "You can spoof an IP address using Scapy library.\nHere's an example from Packet Wizardry: Ruling the Network with Python:\n#!/usr/bin/env python\nimport sys\nfrom scapy import *\nconf.verb=0\n\nif len(sys.argv) != 4:\n print \"Usage: ./spoof.py <target> <spoofed_ip> <port>\"\n sys.exit(1)\n\ntarget = sys.arg...
[ 20 ]
[]
[]
[ "networking", "python" ]
stackoverflow_0000414025_networking_python.txt
Q: python "'NoneType' object has no attribute 'encode'" I wrote this tiny Python snippet that scrapes a feed and prints it out. When I run the code, something in the feed triggers the error message you see here as my question. Here's the complete console output on error: > Traceback (most recent call last): > File ...
python "'NoneType' object has no attribute 'encode'"
I wrote this tiny Python snippet that scrapes a feed and prints it out. When I run the code, something in the feed triggers the error message you see here as my question. Here's the complete console output on error: > Traceback (most recent call last): > File "/home/vijay/ffour/ffour5.py", > line 20, in <module> > ...
[ "\n> sys.stdout.write(entry[\"title\"]).encode('utf-8')\n\n\nThis is the culprit. You probably mean:\nsys.stdout.write(entry[\"title\"].encode('utf-8'))\n\n(Notice the position of the last closing bracket.)\n", "Lets try to clear up some of the confusion in the exception message.\nThe function call\nsys.stdout.wr...
[ 12, 5 ]
[]
[]
[ "python", "urlencode" ]
stackoverflow_0000414230_python_urlencode.txt
Q: How to bring program to front using python I would like to force my python app to the front if a condition occurs. I'm using Kubuntu & QT3.1 I've tried setActiveWindow(), but it only flashes the task bar in KDE. I think Windows has a function bringwindowtofront() for VB. Is there something similar for KDE? A: Ch...
How to bring program to front using python
I would like to force my python app to the front if a condition occurs. I'm using Kubuntu & QT3.1 I've tried setActiveWindow(), but it only flashes the task bar in KDE. I think Windows has a function bringwindowtofront() for VB. Is there something similar for KDE?
[ "Check if KWin is configured to prevent focus stealing.\nThere might be nothing wrong with your code -- but we linux people don't like applications bugging us when we work, so stealing focus is kinda frowned upon, and difficult under some window managers.\n", "Have you tried using those 3 (in this order) on your ...
[ 4, 1, 1 ]
[]
[]
[ "python", "qt" ]
stackoverflow_0000412214_python_qt.txt
Q: How to (simply) connect Python to my web site? I've been playing with Python for a while and wrote a little program to make a database to keep track of some info (its really basic, and hand written). I want to add the ability to create a website from the data that I will then pass to my special little place on the...
How to (simply) connect Python to my web site?
I've been playing with Python for a while and wrote a little program to make a database to keep track of some info (its really basic, and hand written). I want to add the ability to create a website from the data that I will then pass to my special little place on the internet. What should I use to build up the website...
[ "I would generate a page or two of HTML using a template engine (Jinja is my personal choice) and just stick them in your public_html directory or wherever the webserver's root is.\n", "Generating static HTML is great, if that works for you go for it. \nIf you want a dynamic website and the ability to update, web...
[ 12, 0 ]
[]
[]
[ "python", "web" ]
stackoverflow_0000412368_python_web.txt
Q: URLs: Binary Blob, Unicode or Encoded Unicode String? I wish to store URLs in a database (MySQL in this case) and process it in Python. Though the database and programming language are probably not this relevant to my question. In my setup I receive unicode strings when querying a text field in the database. But ...
URLs: Binary Blob, Unicode or Encoded Unicode String?
I wish to store URLs in a database (MySQL in this case) and process it in Python. Though the database and programming language are probably not this relevant to my question. In my setup I receive unicode strings when querying a text field in the database. But is a URL actually text? Is encoding from and decoding to un...
[ "The relevant answer is found in RFC 2396, section \n2.1 URI and non-ASCII characters\n\nThe relationship between URI and characters has been a source of\nconfusion for characters that are not part of US-ASCII. To describe\nthe relationship, it is useful to distinguish between a \"character\"\n(as a distinguishable...
[ 3, 1, 1 ]
[]
[]
[ "database", "mysql", "python", "url" ]
stackoverflow_0000416315_database_mysql_python_url.txt
Q: Filtering away nearby points from a list I half-answered a question about finding clusters of mass in a bitmap. I say half-answered because I left it in a condition where I had all the points in the bitmap sorted by mass and left it to the reader to filter the list removing points from the same cluster. Then when...
Filtering away nearby points from a list
I half-answered a question about finding clusters of mass in a bitmap. I say half-answered because I left it in a condition where I had all the points in the bitmap sorted by mass and left it to the reader to filter the list removing points from the same cluster. Then when thinking about that step I found that the sol...
[ "Just so you know, you are asking for a solution to an ill-posed problem: no definitive solution exists. That's fine...it just makes it more fun. Your problem is ill-posed mostly because you don't know how many clusters you want. Clustering is one of the key areas of machine learning and there a quite a few appr...
[ 5, 4, 3, 1, 1, 1 ]
[]
[]
[ "algorithm", "bitmap", "filtering", "language_agnostic", "python" ]
stackoverflow_0000416406_algorithm_bitmap_filtering_language_agnostic_python.txt
Q: Implementing a buffer-like structure in Python I'm trying to write a small wsgi application which will put some objects to an external queue after each request. I want to make this in batch, ie. make the webserver put the object to a buffer-like structure in memory, and another thread and/or process for sending th...
Implementing a buffer-like structure in Python
I'm trying to write a small wsgi application which will put some objects to an external queue after each request. I want to make this in batch, ie. make the webserver put the object to a buffer-like structure in memory, and another thread and/or process for sending these objects to the queue in batch, when buffer is bi...
[ "Examine https://docs.python.org/library/queue.html to see if it meets your needs.\n", "Since you write \"thread and/or process\", see also multiprocessing.Queue and multiprocessing.JoinableQueue from 2.6. Those are interprocess variants of Queue.\n", "Use a buffered stream if you are using python 3.0.\n" ]
[ 8, 3, 1 ]
[]
[]
[ "data_structures", "message_queue", "multithreading", "python" ]
stackoverflow_0000410273_data_structures_message_queue_multithreading_python.txt
Q: What does "|" sign mean in a Django template? I often see something like that: something.property|escape something is an object, property is it's string property. escape - i don't know :) What does this mean? And what min python version it is used in? EDIT: The question was asked wrongly, it said "What does | m...
What does "|" sign mean in a Django template?
I often see something like that: something.property|escape something is an object, property is it's string property. escape - i don't know :) What does this mean? And what min python version it is used in? EDIT: The question was asked wrongly, it said "What does | mean in Python", so the bitwise or answers are corre...
[ "The pipe character indicates that you want to send the results of the left hand side to the filter defined on the right side. The filter will modify the value in some way. \nThe 'escape' filter is just one of many.\nThe list of built in filters can be found here: \nDjango Documentation - Built-in filters referen...
[ 14, 10 ]
[ "It's a bitwise \"or\". It means escape if the property doesn't exist/is null.\n" ]
[ -3 ]
[ "django", "django_templates", "python" ]
stackoverflow_0000417265_django_django_templates_python.txt
Q: What are "first-class" objects? When are objects or something else said to be "first-class" in a given programming language, and why? In what way do they differ from languages where they are not? When one says "everything is an object" (like in Python), do they indeed mean that "everything is first-class"? A: In...
What are "first-class" objects?
When are objects or something else said to be "first-class" in a given programming language, and why? In what way do they differ from languages where they are not? When one says "everything is an object" (like in Python), do they indeed mean that "everything is first-class"?
[ "In short, it means there are no restrictions on the object's use. It's the same as\nany other object.\nA first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. \n\nDepending...
[ 227, 28, 20, 18, 3 ]
[]
[]
[ "language_agnostic", "python" ]
stackoverflow_0000245192_language_agnostic_python.txt
Q: Best way to create a simple python web service I've been using python for years, but I have little experience with python web programming. I'd like to create a very simple web service that exposes some functionality from an existing python script for use within my company. It will likely return the results in csv....
Best way to create a simple python web service
I've been using python for years, but I have little experience with python web programming. I'd like to create a very simple web service that exposes some functionality from an existing python script for use within my company. It will likely return the results in csv. What's the quickest way to get something up? If it ...
[ "Have a look at werkzeug. Werkzeug started as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP da...
[ 55, 26, 17, 12, 9, 4, 2, 2, 1 ]
[]
[]
[ "python", "web_services" ]
stackoverflow_0000415192_python_web_services.txt
Q: How to check that a path has a sticky bit in python? How to check with python if a path has the sticky bit set? A: import os def is_sticky(path): return os.stat(path).st_mode & 01000 == 01000 A: os.stat() will return a tupple of information about the file. The first item will be the mode. You would then ...
How to check that a path has a sticky bit in python?
How to check with python if a path has the sticky bit set?
[ "import os\ndef is_sticky(path):\n return os.stat(path).st_mode & 01000 == 01000\n\n", "os.stat() will return a tupple of information about the file. The first item will be the mode. You would then be able to use some bit arithmetic to get for the sticky bit. The sticky bit has an octal value of 1000.\n" ]
[ 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000418204_python.txt
Q: Python: C++-like stream input Is there a pythonic way of reading - say - mixed integer and char input without reading the whole input at once and without worrying about linebreaks? For example I have a file with whitespace-separated data of which I only know that there are x integers, then y chars and then z more ...
Python: C++-like stream input
Is there a pythonic way of reading - say - mixed integer and char input without reading the whole input at once and without worrying about linebreaks? For example I have a file with whitespace-separated data of which I only know that there are x integers, then y chars and then z more integers. I don't want to assume an...
[ "How about a small generator function that returns a stream of tokens and behaves like cin:\ndef read_tokens(f):\n for line in f:\n for token in line.split():\n yield token\n\nx = y = z = 5 # for simplicity: 5 ints, 5 char tokens, 5 ints\nf = open('data.txt', 'r')\ntokens = read_tokens(f)\nX = []...
[ 7, 3, 2, 0 ]
[]
[]
[ "c++", "input", "python", "stream" ]
stackoverflow_0000417703_c++_input_python_stream.txt
Q: Why does Python's string.printable contains unprintable characters? I have two String.printable mysteries in the one question. First, in Python 2.6: >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' Look at the end of the string,...
Why does Python's string.printable contains unprintable characters?
I have two String.printable mysteries in the one question. First, in Python 2.6: >>> string.printable '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' Look at the end of the string, and you'll find '\x0b\x0c' sticking out like a sore-thumb. Why are they ...
[ "There is a difference in \"printable\" for \"can be displayed on your screen\". Your terminal displays the low ascii printer control codes 0x0B and 0x0C as the male and female symbols because that is what those indices in your font contain. Those characters are more accurately described as the Vertical Tabulator...
[ 27, 6 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0000418176_character_encoding_python.txt
Q: py2exe setup.py with icons How do I make icons for my exe file when compiling my Python program? A: I was searching for this a while ago, and found this: http://www.mail-archive.com/pygame-users@seul.org/msg05619.html Quote from above link: The setup.py File: PY_PROG = 'trek10.py' APP_NAME = 'Trek_Game' cfg = {...
py2exe setup.py with icons
How do I make icons for my exe file when compiling my Python program?
[ "I was searching for this a while ago, and found this: http://www.mail-archive.com/pygame-users@seul.org/msg05619.html\nQuote from above link:\n\nThe setup.py File: PY_PROG =\n'trek10.py' APP_NAME = 'Trek_Game'\ncfg = {\n'name':APP_NAME,\n'version':'1.0',\n'description':'',\n'author':'',\n'author_email':'',\n'url':...
[ 2, 2, 2 ]
[ "I have no experience with py2exe but a quick google search found this, if embedding icons in exe files was what you asked for. \nIf you want to create .ico files, I'd really suggest you search for a icon designer or finished icons. Sure you can create a Win 3.x style icon fairly easy by creating a 16x16, 32x32, o...
[ -1 ]
[ "icons", "py2exe", "python" ]
stackoverflow_0000289518_icons_py2exe_python.txt
Q: Python Threads - Critical Section What is the "critical section" of a thread (in Python)? A thread enters the critical section by calling the acquire() method, which can either be blocking or non-blocking. A thread exits the critical section, by calling the release() method. - Understanding Threading i...
Python Threads - Critical Section
What is the "critical section" of a thread (in Python)? A thread enters the critical section by calling the acquire() method, which can either be blocking or non-blocking. A thread exits the critical section, by calling the release() method. - Understanding Threading in Python, Linux Gazette Also, what is t...
[ "Other people have given very nice definitions. Here's the classic example:\nimport threading\naccount_balance = 0 # The \"resource\" that zenazn mentions.\naccount_balance_lock = threading.Lock()\n\ndef change_account_balance(delta):\n global account_balance\n with account_balance_lock:\n # Critical s...
[ 24, 18, 0 ]
[]
[]
[ "language_agnostic", "multithreading", "python" ]
stackoverflow_0000419145_language_agnostic_multithreading_python.txt
Q: How can I convert XML into a Python object? I need to load an XML file and convert the contents into an object-oriented Python structure. I want to take this: <main> <object1 attr="name">content</object> </main> And turn it into something like this: main main.object1 = "content" main.object1.attr = "name" Th...
How can I convert XML into a Python object?
I need to load an XML file and convert the contents into an object-oriented Python structure. I want to take this: <main> <object1 attr="name">content</object> </main> And turn it into something like this: main main.object1 = "content" main.object1.attr = "name" The XML data will have a more complicated structure...
[ "It's worth looking at lxml.objectify.\nxml = \"\"\"<main>\n<object1 attr=\"name\">content</object1>\n<object1 attr=\"foo\">contenbar</object1>\n<test>me</test>\n</main>\"\"\"\n\nfrom lxml import objectify\n\nmain = objectify.fromstring(xml)\nmain.object1[0] # content\nmain.object1[1] # cont...
[ 59, 9, 4, 1, 1, 0 ]
[ "If googling around for a code-generator doesn't work, you could write your own that uses XML as input and outputs objects in your language of choice.\nIt's not terribly difficult, however the three step process of Parse XML, Generate Code, Compile/Execute Script does making debugging a bit harder.\n" ]
[ -1 ]
[ "python", "xml" ]
stackoverflow_0000418497_python_xml.txt
Q: Grabbing text from a webpage I would like to write a program that will find bus stop times and update my personal webpage accordingly. If I were to do this manually I would Visit www.calgarytransit.com Enter a stop number. ie) 9510 Click the button "next bus" The results may look like the following: 10:16p ...
Grabbing text from a webpage
I would like to write a program that will find bus stop times and update my personal webpage accordingly. If I were to do this manually I would Visit www.calgarytransit.com Enter a stop number. ie) 9510 Click the button "next bus" The results may look like the following: 10:16p Route 154 10:46p Route 154 11:...
[ "Beautiful Soup is a Python library designed for parsing web pages. Between it and urllib2 (urllib.request in Python 3) you should be able to figure out what you need.\n", "What you're asking about is called \"web scraping.\" I'm sure if you google around you'll find some stuff, but the core notion is that you w...
[ 13, 5, 3, 2, 2, 1, 1, 0 ]
[]
[]
[ "c", "python", "text", "webpage" ]
stackoverflow_0000419260_c_python_text_webpage.txt
Q: How would a system tray application be accomplished on other platforms? Windows has the "system tray" that houses the clock and alway-running services like MSN, Steam, etc. I'd like to develop a wxPython tray application but I'm wondering how well this will port to other platforms. What is the tray equivalent on ...
How would a system tray application be accomplished on other platforms?
Windows has the "system tray" that houses the clock and alway-running services like MSN, Steam, etc. I'd like to develop a wxPython tray application but I'm wondering how well this will port to other platforms. What is the tray equivalent on each platform, and how much manual work would be required to support Windows,...
[ "wx is a cross-platform GUI and tools library that supports Win32, Mac OS X, GTK+, X11, Motif, WinCE, and more. And if you use it's classes then your application should work on all these platforms.\nFor system tray look at wxTaskBarIcon (http://docs.wxwidgets.org/stable/wx_wxtaskbaricon.html#wxtaskbaricon).\n", "...
[ 6, 3, 2, 1, 1 ]
[]
[]
[ "cross_platform", "operating_system", "python", "system_tray", "wxpython" ]
stackoverflow_0000419334_cross_platform_operating_system_python_system_tray_wxpython.txt
Q: How to raise an exception on the version number of a module How can you raise an exception when you import a module that is less or greater than a given value for its __version__? There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. I...
How to raise an exception on the version number of a module
How can you raise an exception when you import a module that is less or greater than a given value for its __version__? There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. In this case the version number is of the format x.x.x
[ "Python comes with this inbuilt as part of distutils. The module is called distutils.version and is able to compare several different version number formats.\nfrom distutils.version import StrictVersion\n\nprint StrictVersion('1.2.2') > StrictVersion('1.2.1')\n\nFor way more information than you need, see the docum...
[ 6, 2, 1, 0 ]
[ "If you know the exact formatting of the version string a plain comparison will work:\n>>> \"1.2.2\" > \"1.2.1\"\nTrue\n\nThis will only work if each part of the version is in the single digits, though:\n>>> \"1.2.2\" > \"1.2.10\" # Bug!\nTrue\n\n" ]
[ -2 ]
[ "python", "versioning" ]
stackoverflow_0000419010_python_versioning.txt
Q: Automated Class timetable optimize crawler? Overall Plan Get my class information to automatically optimize and select my uni class timetable Overall Algorithm Logon to the website using its Enterprise Sign On Engine login Find my current semester and its related subjects (pre setup) Navigate to the right page an...
Automated Class timetable optimize crawler?
Overall Plan Get my class information to automatically optimize and select my uni class timetable Overall Algorithm Logon to the website using its Enterprise Sign On Engine login Find my current semester and its related subjects (pre setup) Navigate to the right page and get the data from each related subject (lecture...
[ "Depending on how far you plan on taking #6, and how big the dataset is, it may be non-trivial; it certainly smacks of NP-hard global optimisation to me...\nStill, if you're talking about tens (rather than hundreds) of nodes, a fairly dumb algorithm should give good enough performance.\nSo, you have two constraints...
[ 2, 0, 0 ]
[]
[]
[ "python", "scheduling", "screen_scraping" ]
stackoverflow_0000419698_python_scheduling_screen_scraping.txt
Q: python install on leopard I'll admit I'm completely dumbed by python install. Can someone help me on how to install module I want to play with PyGame, PyOpenGL etc. So I install them, but I everytime I type "import pygame" error message shows up. here's my environment so far. In .bash_profile PATH=${PATH}:/System/...
python install on leopard
I'll admit I'm completely dumbed by python install. Can someone help me on how to install module I want to play with PyGame, PyOpenGL etc. So I install them, but I everytime I type "import pygame" error message shows up. here's my environment so far. In .bash_profile PATH=${PATH}:/System/Library/Frameworks/Python.frame...
[ "I'm not a huge fan of the default python install on OS X in the first place, mostly because it's usually a pretty old version. I find everything works better if I use the macports package.\neasy_install seems to work better with the macports package, but maybe that's just because I'm too lazy to figure out all the...
[ 1, 0 ]
[]
[]
[ "easy_install", "macos", "osx_leopard", "python" ]
stackoverflow_0000420515_easy_install_macos_osx_leopard_python.txt
Q: What are the best prebuilt libraries for doing Web Crawling in Python I need to crawl and store locally for future analysis the contents of a finite list of websites. I basically want to slurp in all pages and follow all internal links to get the entire publicly available site. Are there existing free libraries t...
What are the best prebuilt libraries for doing Web Crawling in Python
I need to crawl and store locally for future analysis the contents of a finite list of websites. I basically want to slurp in all pages and follow all internal links to get the entire publicly available site. Are there existing free libraries to get me there? I've seen Chilkat, but it's for pay. I'm just looking for...
[ "Use Scrapy.\nIt is a twisted-based web crawler framework. Still under heavy development but it works already. Has many goodies:\n\nBuilt-in support for parsing HTML, XML, CSV, and Javascript\nA media pipeline for scraping items with images (or any other media) and download the image files as well\nSupport for exte...
[ 7, 0 ]
[]
[]
[ "python", "web_crawler" ]
stackoverflow_0000421283_python_web_crawler.txt
Q: In Python, how I do use subprocess instead of os.system? I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"): import os sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\P...
In Python, how I do use subprocess instead of os.system?
I have a Python script that calls an executable program with various arguments (in this example, it is 'sqlpubwiz.exe' which is the "Microsoft SQL Server Database Publishing Wizard"): import os sqlpubwiz = r'"C:\Program Files\Microsoft SQL Server\90\Tools\Publishing\sqlpubwiz.exe"' server = 'myLocalServer' database = ...
[ "import subprocess\np=subprocess.Popen(args, stdout=subprocess.PIPE)\nprint p.communicate()[0]\n\nIt would look pretty much the same. But the path should not be r'\"whatever the path is\"'. Because that gives me an error. You want \"the path with escaped backslashes\" or r'the path without escaping'.\nAlso args ...
[ 5, 4, 4, 4, 0, 0, 0 ]
[]
[]
[ "process", "python", "scripting", "syntax" ]
stackoverflow_0000421206_process_python_scripting_syntax.txt
Q: Drawing with Webdings in PIL I've got a Python program using PIL to render text, and it works great with all kinds of fonts. But it only draws "missing glyph" rectangles with wingdings or webdings. Here's a sample that tries to draw every unicode character: # Run this with .ttf file path as an argument, and also ...
Drawing with Webdings in PIL
I've got a Python program using PIL to render text, and it works great with all kinds of fonts. But it only draws "missing glyph" rectangles with wingdings or webdings. Here's a sample that tries to draw every unicode character: # Run this with .ttf file path as an argument, and also an encoding if you like. # It will...
[ "I must have done something wrong before. \"symb\" as the encoding works for wingdings too! Sorry for the noise...\n", "Not all of wingdings is mapped to unicode: see http://www.alanwood.net/demos/wingdings.html\nAlso you're only covering the Basic Multilingual Plane (wikipedia)\n" ]
[ 2, 1 ]
[]
[]
[ "fonts", "python", "python_imaging_library" ]
stackoverflow_0000422555_fonts_python_python_imaging_library.txt
Q: How can the user communicate with my python script using the shell? How can I implement the following in python? #include <iostream> int main() { std::string a; std::cout << "What is your name? "; std::cin >> a; std::cout << std::endl << "You said: " << a << std::endl; } Output: What is your name...
How can the user communicate with my python script using the shell?
How can I implement the following in python? #include <iostream> int main() { std::string a; std::cout << "What is your name? "; std::cin >> a; std::cout << std::endl << "You said: " << a << std::endl; } Output: What is your name? Nick You said: Nick
[ "Call \nname = raw_input('What is your name?')\n\nand \nprint 'You said', name\n\n", "Look at the print statement and the raw_input() function.\nOr look at sys.stdin.read() and sys.stdout.write(). \nWhen using sys.stdout, don't forget to flush.\n", "print \"You said:\", raw_input(\"What is your name? \")\n\nEDI...
[ 7, 3, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000422091_python.txt
Q: How to maintain lists and dictionaries between function calls in Python? I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls Suppose the dic is : a = {'a':1,'b':2,'c':3} At first call,say,I changed a[a] to 100 Dict become...
How to maintain lists and dictionaries between function calls in Python?
I have a function. Inside that I'm maintainfing a dictionary of values. I want that dictionary to be maintained between different function calls Suppose the dic is : a = {'a':1,'b':2,'c':3} At first call,say,I changed a[a] to 100 Dict becomes a = {'a':100,'b':2,'c':3} At another call,i changed a[b] to 200 I want that ...
[ "You might be talking about a callable object.\nclass MyFunction( object ):\n def __init__( self ):\n self.rememberThis= dict()\n def __call__( self, arg1, arg2 ):\n # do something\n rememberThis['a'] = arg1\n return someValue\n\nmyFunction= MyFunction()\n\nFrom then on, use myFunc...
[ 18, 15, 8, 6, 4, 3, 3 ]
[]
[]
[ "function_calls", "python", "variables" ]
stackoverflow_0000419379_function_calls_python_variables.txt
Q: can cherrypy receive multipart/mixed POSTs out of the box? We're receiving some POST data of xml + arbitrary binary files (like images and audio) from a device that only gives us multipart/mixed encoding. I've setup a cherrypy upload/POST handler for our receiver end. I've managed to allow it to do arbitrary numb...
can cherrypy receive multipart/mixed POSTs out of the box?
We're receiving some POST data of xml + arbitrary binary files (like images and audio) from a device that only gives us multipart/mixed encoding. I've setup a cherrypy upload/POST handler for our receiver end. I've managed to allow it to do arbitrary number of parameters using multipart/form-data. However when we try...
[ "My bad. Whenever the Content-Type is of type \"multipart/*\", then CP tries to stick the contents into request.params (if any other Content-Type, it goes into request.body).\nUnfortunately, CP has assumed that any multipart message is form-data, and made no provision for other subtypes. I've just fixed this in tru...
[ 4 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0000415019_cherrypy_python.txt
Q: How to return more than one value from a function in Python? How to return more than one variable from a function in Python? A: You separate the values you want to return by commas: def get_name(): # you code return first_name, last_name The commas indicate it's a tuple, so you could wrap your values by p...
How to return more than one value from a function in Python?
How to return more than one variable from a function in Python?
[ "You separate the values you want to return by commas:\ndef get_name():\n # you code\n return first_name, last_name\n\nThe commas indicate it's a tuple, so you could wrap your values by parentheses:\nreturn (first_name, last_name)\n\nThen when you call the function you a) save all values to one variable as a tu...
[ 156, 14, 6 ]
[]
[]
[ "function", "multiple_variable_return", "python" ]
stackoverflow_0000423710_function_multiple_variable_return_python.txt
Q: How to save inline formset models in Django? Formsets have a .save() method, and the documentation says to save in views like this: if request.method == "POST": formset = BookInlineFormSet(request.POST, request.FILES, instance=author) if formset.is_valid(): formset.save() # Do something. el...
How to save inline formset models in Django?
Formsets have a .save() method, and the documentation says to save in views like this: if request.method == "POST": formset = BookInlineFormSet(request.POST, request.FILES, instance=author) if formset.is_valid(): formset.save() # Do something. else: formset = BookInlineFormSet(instance=autho...
[ "I discovered my problem, and it's embarrassing.\nIn the parent model form I had exclude = ('...',) in the Meta class, and one of the excluded fields was critical for the relations in the inline_formsets. So, I've removed the excludes and ignoring those fields in the template.\n" ]
[ 4 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0000423437_django_django_forms_python.txt
Q: Python and different Operating Systems I am about to start a personal project using python and I will be using it on both Linux(Fedora) and Windows(Vista), Although I might as well make it work on a mac while im at it. I have found an API for the GUI that will work on all 3. The reason I am asking is because I hav...
Python and different Operating Systems
I am about to start a personal project using python and I will be using it on both Linux(Fedora) and Windows(Vista), Although I might as well make it work on a mac while im at it. I have found an API for the GUI that will work on all 3. The reason I am asking is because I have always heard of small differences that are...
[ "In general:\n\nBe careful with paths. Use os.path wherever possible.\nDon't assume that HOME points to the user's home/profile directory.\nAvoid using things like unix-domain sockets, fifos, and other POSIX-specific stuff.\n\nMore specific stuff:\n\nIf you're using wxPython, note that there may be differences in t...
[ 4, 3, 1, 0 ]
[]
[]
[ "cross_platform", "python" ]
stackoverflow_0000425343_cross_platform_python.txt
Q: Correct way to detect sequence parameter? I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I don't want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or somethin...
Correct way to detect sequence parameter?
I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I don't want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid spec...
[ "As of 2.6, use abstract base classes.\n>>> import collections\n>>> isinstance([], collections.Sequence)\nTrue\n>>> isinstance(0, collections.Sequence)\nFalse\n\nFurthermore ABC's can be customized to account for exceptions, such as not considering strings to be sequences. Here an example:\nimport abc\nimport coll...
[ 19, 5, 4, 4, 3, 3, 2, 1, 1, 0, 0 ]
[ "You could pass your parameter in the built-in len() function and check whether this causes an error. As others said, the string type requires special handling.\nAccording to the documentation the len function can accept a sequence (string, list, tuple) or a dictionary.\nYou could check that an object is a string w...
[ -1 ]
[ "python", "sequences", "types" ]
stackoverflow_0000305359_python_sequences_types.txt
Q: Drag button between panels in wxPython Does anyone know of an example where it is shown how to drag a button from one panel to another in wxPython? I have created a bitmap button in a panel, and I would like to be able to drag it to a different panel and drop I there. I haven't found any examples using buttons, j...
Drag button between panels in wxPython
Does anyone know of an example where it is shown how to drag a button from one panel to another in wxPython? I have created a bitmap button in a panel, and I would like to be able to drag it to a different panel and drop I there. I haven't found any examples using buttons, just text and files. I am using the latest ve...
[ "If you want to graphically represent the drag, one good way to do this is to create a borderless Frame that follows the mouse during a drag. You remove the button from your source Frame, temporarily put it in this \"drag Frame\", and then, when the user drops, add it to your destination Frame.\n" ]
[ 4 ]
[]
[]
[ "drag_and_drop", "python", "wxpython" ]
stackoverflow_0000425722_drag_and_drop_python_wxpython.txt
Q: Most Pythonic way equivalent for: while ((x = next()) != END) What's the best Python idiom for this C construct? while ((x = next()) != END) { .... } I don't have the ability to recode next(). update: and the answer from seems to be: for x in iter(next, END): .... A: @Mark Harrison's answer: for x in i...
Most Pythonic way equivalent for: while ((x = next()) != END)
What's the best Python idiom for this C construct? while ((x = next()) != END) { .... } I don't have the ability to recode next(). update: and the answer from seems to be: for x in iter(next, END): ....
[ "@Mark Harrison's answer:\nfor x in iter(next_, END):\n ....\n\nHere's an excerpt from Python's documentation:\niter(o[, sentinel])\n\n\nReturn an iterator object.\n ...(snip)... If the second argument, sentinel, is given, then o must be\n a callable object. The iterator\n created in this case will call o\n ...
[ 14, 5, 4, 2, 1, 1, 1 ]
[]
[]
[ "c", "python" ]
stackoverflow_0000028559_c_python.txt
Q: Cross Platform SWF Playback with Python? I'm looking for different solutions to playing back SWF files on Windows, OSX and Linux using Python. Ideally I'd like to embed the player inside a wxPython frame/window. One possibility I'm investigating is the Mozilla XPCOM framework since its used by FireFox to load the...
Cross Platform SWF Playback with Python?
I'm looking for different solutions to playing back SWF files on Windows, OSX and Linux using Python. Ideally I'd like to embed the player inside a wxPython frame/window. One possibility I'm investigating is the Mozilla XPCOM framework since its used by FireFox to load the Flash plugin within the browser.
[ "Have you considered Adobe AIR? \nBruce Eckel said: Try combining the power of Python with the polish of Adobe Flash to create a desktop application.\n", "Though I don't know how to embed a browser within a wxPython window, the following code might serve in a pinch (and will work cross-platform, assuming you're w...
[ 3, 2 ]
[]
[]
[ "cross_platform", "flash", "python", "wxpython" ]
stackoverflow_0000417159_cross_platform_flash_python_wxpython.txt