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: problem when zooming pictures in wxpython I need to draw over image (to comment over it) in a scrolled panel. I'm having troubles with it since it doesn't behave right when I zoom it in or out. it stops drawing , and then it shows it after a while in a wrong place. right in the upper left corner of the window. and...
problem when zooming pictures in wxpython
I need to draw over image (to comment over it) in a scrolled panel. I'm having troubles with it since it doesn't behave right when I zoom it in or out. it stops drawing , and then it shows it after a while in a wrong place. right in the upper left corner of the window. and doesn't draw lines correctly . below is the co...
[ "You need to scale mouse co-ordinates so that it is in sync with scaling of drawing, so if you are using userScale=2, mouse at x=10 will end up at 20 .\nso you need to do this\nsx, sy = x/cur_scale, y/cur_scale\n\nYou also need to be do drawing in EVT_PAINT event not on onmotion, on motion you just need to refresh ...
[ 3 ]
[]
[]
[ "drawing", "image", "python", "wxpython", "zooming" ]
stackoverflow_0002041418_drawing_image_python_wxpython_zooming.txt
Q: Django: information leakage problem when using @login_required and setting LOGIN_URL I found a form of information leakage when using the @login_required decorator and setting the LOGIN_URL variable. I have a site that requires a mandatory login for all content. The problem is that you get redirected to the login ...
Django: information leakage problem when using @login_required and setting LOGIN_URL
I found a form of information leakage when using the @login_required decorator and setting the LOGIN_URL variable. I have a site that requires a mandatory login for all content. The problem is that you get redirected to the login page with the next variable set when it's a existing page. So when not logged in and askin...
[ "You can include this line as the last pattern in your urls.py file. It will re-route urls that do not match any other pattern to the login page.\nurlpatterns = patterns('',\n\n ...\n\n (r'^(?P<path>.+)$', 'django.views.generic.simple.redirect_to', {\n 'url': '/login/?next=/%(path)s', \n 'perman...
[ 5 ]
[]
[]
[ "authentication", "django", "django_urls", "python" ]
stackoverflow_0002042201_authentication_django_django_urls_python.txt
Q: How to copy a file from a network share to local disk with variables? If I use the following line: shutil.copyfile(r"\\mynetworkshare\myfile.txt","C:\TEMP\myfile.txt") everything works fine. However, what I can't seem to figure out is how to use a variable with the network share path, because I need the 'r' (rela...
How to copy a file from a network share to local disk with variables?
If I use the following line: shutil.copyfile(r"\\mynetworkshare\myfile.txt","C:\TEMP\myfile.txt") everything works fine. However, what I can't seem to figure out is how to use a variable with the network share path, because I need the 'r' (relative?) flag. The end result I would imagine would be something like: sourc...
[ "The r used in your first code example is making the string a \"raw\" string. In this example, that means the string will see the backslashes and not try to use them to escape \\\\ to just \\.\nTo get your second code sample working, you'd use the r on the strings, and not in the copyfile command:\nsource_path = r\...
[ 28, 5, 3, 1 ]
[]
[]
[ "network_programming", "python", "share" ]
stackoverflow_0002042342_network_programming_python_share.txt
Q: A more pythonic way of iterating a list while excluding an element each iteration I have the following code: items = ["one", "two", "three"] for i in range(0, len(items)): for index, element in enumerate(items): if index != i: # do something with element Basically I want to exclude every ...
A more pythonic way of iterating a list while excluding an element each iteration
I have the following code: items = ["one", "two", "three"] for i in range(0, len(items)): for index, element in enumerate(items): if index != i: # do something with element Basically I want to exclude every element once and iterate the rest. So for the list I have above, I'd like the following...
[ "Although upvoted like crazy, my first solution wasn't what the OP wanted, which is\nN lists, each missing exactly one of the N original elements:\n>>> from itertools import combinations\n>>> L = [\"one\", \"two\", \"three\", \"four\"]\n>>> for R in combinations(L, len(L) - 1):\n... print \" and \".join(R)\n......
[ 17, 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002042363_python.txt
Q: How can I fix ImportError: No module named numpy? I am trying to run a python script which has the following statements: import random as RD import pylab as PL import scipy as SP import networkx as NX Where can I download these packages? I have installed these packages and I get the following error when I run my ...
How can I fix ImportError: No module named numpy?
I am trying to run a python script which has the following statements: import random as RD import pylab as PL import scipy as SP import networkx as NX Where can I download these packages? I have installed these packages and I get the following error when I run my code I am getting the following error when I run the co...
[ "\n'random' is shipped with the standard library\npylab and scipy are part of SciPy\nNetworkx is available here\n\n", "Here's a link to the non standard libraries. random is part of the standard library.\nmatplotlib\nscipy\nnetworkX\nnumpy (reuired by scipy)\n", "random is a standard python library module, no ...
[ 2, 2, 2, 1 ]
[]
[]
[ "matplotlib", "networkx", "python", "random", "scipy" ]
stackoverflow_0002040531_matplotlib_networkx_python_random_scipy.txt
Q: Python Sockets - Creating a message format I have built a Python server to which various clients can connect, and I need to set a predefined series of messages from clients to the server - For example the client passes in a name to the server when it first connects. I was wondering what the best way to approach t...
Python Sockets - Creating a message format
I have built a Python server to which various clients can connect, and I need to set a predefined series of messages from clients to the server - For example the client passes in a name to the server when it first connects. I was wondering what the best way to approach this is? How should I build a simple protocol for...
[ "Depending on the requirements, you might want to consider using JSON: use \"newline\" terminated strings with JSON encoding. The transport protocol could be HTTP: with this, you could have access to all the \"connection related\" facilities (e.g. status codes) and have JSON encoded payload.\nThe advantages of usin...
[ 2, 2, 1, 0 ]
[]
[]
[ "protocols", "python", "sockets" ]
stackoverflow_0002042133_protocols_python_sockets.txt
Q: What to write into log file? My question is simple: what to write into a log. Are there any conventions? What do I have to put in? Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is. I already have some ideas, like a timestamp, a unique ide...
What to write into log file?
My question is simple: what to write into a log. Are there any conventions? What do I have to put in? Since my app has to be released, I'd like to have friendly logs, which could be read by most people without asking what it is. I already have some ideas, like a timestamp, a unique identifier for each function/method, ...
[ "It's quite pleasant, and already implemented.\nRead this: http://docs.python.org/library/logging.html\n\nEdit\n\"easy to parse, read,\" are generally contradictory features. English -- easy to read, hard to parse. XML -- easy to parse, hard to read. There is no format that achieves easy-to-read and easy-to-pars...
[ 18, 9, 1, 1, 1, 0 ]
[ "timeStamp i.e. DateTime YYYY/MM/DD:HH:mm:ss:ms\nUser\nThread ID\nFunction Name\nMessage/Error Message/Success Message/Function Trace\nHave this in XML format and you can then easily write a parser for it.\n<log>\n <logEntry DebugLevel=\"0|1|2|3|4|5....\">\n <TimeStamp format=\"YYYY/MM/DD:HH:mm:ss:ms\" value=\"...
[ -1 ]
[ "logging", "methodology", "python" ]
stackoverflow_0000779989_logging_methodology_python.txt
Q: Py2App Can't find standard modules I've created an app using py2app, which works fine, but if I zip/unzip it, the newly unzipped version can't access standard python modules like traceback, or os. The manpage for zip claims that it preserves resource forks, and I've seen other applications packaged this way (I nee...
Py2App Can't find standard modules
I've created an app using py2app, which works fine, but if I zip/unzip it, the newly unzipped version can't access standard python modules like traceback, or os. The manpage for zip claims that it preserves resource forks, and I've seen other applications packaged this way (I need to be able to put this in a .zip file)...
[ "This is caused by building a semi-standalone version that contains symlinks to the natively installed files and as you say, the links are lost when zipping/unzipping unless the \"-y\" option is used.\nAn alternate solution is to build for standalone instead, which puts (public domain) files inside the application ...
[ 5, 0, 0 ]
[]
[]
[ "macos", "py2app", "python" ]
stackoverflow_0001346297_macos_py2app_python.txt
Q: Could not get cookie from another (parent) domain in Django I need to remove a cookie that was previously set for parent domain while browsing host at subdomain of the parent. I.e., a cookie "xyz" was set for example.com, and I am trying to remove it on subdomain.example.com, using Django backend. The request.COOK...
Could not get cookie from another (parent) domain in Django
I need to remove a cookie that was previously set for parent domain while browsing host at subdomain of the parent. I.e., a cookie "xyz" was set for example.com, and I am trying to remove it on subdomain.example.com, using Django backend. The request.COOKIES given to the view does not contain any cookies except those f...
[ "The cookie was probably set with 'domain' parameter. Set the cookie to be accessible from all the subdomains of the domain the cookie is being set in.\nI'm not the python guy, but my knowledge of http protocol shows that this might be the problem.\n", "You can attempt to call delete_cookie even for a cookie you ...
[ 1, 0 ]
[]
[]
[ "cookies", "django", "javascript", "python" ]
stackoverflow_0002043138_cookies_django_javascript_python.txt
Q: Is there a better library than urlgrabber for fetching remote urls in python? I'm writing a spider that needs a load_url function that performs the following for me: Retry the URL if there is a temporary error, without leaking exceptions. Not leak memory or file handles Use HTTP-KeepAlive for speed (optional) UR...
Is there a better library than urlgrabber for fetching remote urls in python?
I'm writing a spider that needs a load_url function that performs the following for me: Retry the URL if there is a temporary error, without leaking exceptions. Not leak memory or file handles Use HTTP-KeepAlive for speed (optional) URLGrabber looks great on the surface, but it has trouble. The first I hit a problem ...
[ "If you are writing a web-crawler / screen-scraper, you may be interested to look at a dedicated framework such as scrapy. \nYou can write really quite sophisticated web crawlers with very little code: it takes care of all the gory details of scheduling the requests and calling you back with the results for you to...
[ 4, 0, 0, 0, 0 ]
[]
[]
[ "python", "screen_scraping" ]
stackoverflow_0002040628_python_screen_scraping.txt
Q: Traversing an unusual tree in Python I have an unusual tree array like this: [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6], [0, 7], [7, 6], [8, 9], [9, 6]] Each element of the array is a pair, which means second one is a follower of the first, e.g.: [0, 1] - 0 is followed by 1 [1, 2] - 1 is f...
Traversing an unusual tree in Python
I have an unusual tree array like this: [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6], [0, 7], [7, 6], [8, 9], [9, 6]] Each element of the array is a pair, which means second one is a follower of the first, e.g.: [0, 1] - 0 is followed by 1 [1, 2] - 1 is followed by 2 I am trying to extract array...
[ "You could do it using a recursive generator function. I assume that the root node in the tree always comes before all its children in the original list.\ntree = [[0, 1], [1, 2], [2, 3], [2, 4], [2, 5], [5, 6], [4, 6], [3, 6],\n [0, 7], [7, 6], [8, 9], [9, 6]]\n\npaths = {}\nfor t in tree:\n if t[0] not i...
[ 4, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "traversal", "tree" ]
stackoverflow_0002042918_python_traversal_tree.txt
Q: How can I support * in user-defined search strings in python? This question is related to this stack overflow question: How can I support wildcards in user-defined search strings in Python? But I need to only support the wildcards and not the ? or the [seq] functionality that you get with fnmatch. Since there is ...
How can I support * in user-defined search strings in python?
This question is related to this stack overflow question: How can I support wildcards in user-defined search strings in Python? But I need to only support the wildcards and not the ? or the [seq] functionality that you get with fnmatch. Since there is no way to remove that functionality from fnmatch, is there another ...
[ "You could compile a regexp from your search string using split, re.escape, and '^$'.\nimport re\nregex = re.compile('^' + '.*'.join(re.escape(foo) for foo in pattern.split('*')) + '$')\n\n", "If its just one asterisk and you require the search string to be representing the whole matched string, this works:\nsear...
[ 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002043449_python_regex.txt
Q: Compiling a py2app working build for both Leopard and Snow Leopard? I currently am making my PyObjC application work for Snow Leopard and I successfully compiled a standalone app. My question would be, how do I make the build to be also Leopard-compatible, given these errors? dyld: lazy symbol binding failed: Symb...
Compiling a py2app working build for both Leopard and Snow Leopard?
I currently am making my PyObjC application work for Snow Leopard and I successfully compiled a standalone app. My question would be, how do I make the build to be also Leopard-compatible, given these errors? dyld: lazy symbol binding failed: Symbol not found: _fopen$UNIX2003 Referenced from: /Applications/MyApp.app/...
[ "I've done this recently and the trick was to build a standalone version on a Leopard installation.\nBy default, unless you have an open source version of Python installed, py2app creates a semi-standalone application that has symlinks to the OS files.\nIf instead, you create a standalone version of the application...
[ 3, 0, 0 ]
[]
[]
[ "osx_leopard", "osx_snow_leopard", "py2app", "python" ]
stackoverflow_0001351209_osx_leopard_osx_snow_leopard_py2app_python.txt
Q: How to change global variables in Python I am trying to change a variable further down the program. I have a global variable declared at the start of the program and I want to change the variable in different functions down the program. I can do this by declaring the variable inside the function again but I would ...
How to change global variables in Python
I am trying to change a variable further down the program. I have a global variable declared at the start of the program and I want to change the variable in different functions down the program. I can do this by declaring the variable inside the function again but I would like to know is there a better way of doing th...
[ "To update global variables you could use\nglobal ID\nID=\"Yes\"\n\nbefore assigning variable to ID = \"YES\"\nBut changing ID will be no effect on project variable, project = (\"Yep\"+ID), because project is already a string\nyou need to make a function like\ndef getprojectname(ID):\n return project+ID\n\nThe w...
[ 11, 7, 2, 1 ]
[ "You can mutate without reassigning:\nvariables = {}\ndef pro():\n if variables['ID'] == '':\n variables['ID'] = 'default'\n\n", "Why not use a dictionary?\n>>> attr = {'start':'XXX', 'myid':'No'}\n>>> \n>>> def update_and_show(D, value = None):\n... if value: D['myid'] = value\n... print D['st...
[ -1, -1 ]
[ "python" ]
stackoverflow_0002040998_python.txt
Q: Tracking system and real time stats analysis in Python This question is related to an older question: MySQL tracking system. In short: I have to implement a tracking system that will have high loads using Python. For the database part I've settled on mongoDB (which sounds like the right tool for this job). The dev...
Tracking system and real time stats analysis in Python
This question is related to an older question: MySQL tracking system. In short: I have to implement a tracking system that will have high loads using Python. For the database part I've settled on mongoDB (which sounds like the right tool for this job). The development language will be Python. I was thinking of using s...
[ "Have you checked out Graphite? It sounds like exactly the kind of thing that you need (looking at your other question) and was designed for application and server monitoring by the Orbitz team. It's extremely robust and easy to use for this sort of thing.\n\nHere's the project site: http://graphite.wikidot.com/\...
[ 3, 1 ]
[]
[]
[ "cherrypy", "mod_wsgi", "mongodb", "nginx", "python" ]
stackoverflow_0002043879_cherrypy_mod_wsgi_mongodb_nginx_python.txt
Q: NetBeans and Python When I run some python code in NetBeans, which raises an error, the output in NetBeans just gives an error message and no further information, such as line number. Is there any way to fix that? A: If you can, I would run your script outside of NetBeans either with the built-in editor (IDLE) o...
NetBeans and Python
When I run some python code in NetBeans, which raises an error, the output in NetBeans just gives an error message and no further information, such as line number. Is there any way to fix that?
[ "If you can, I would run your script outside of NetBeans either with the built-in editor (IDLE) or just run it from the command line. That should give you a traceback with the error and lineno\nNetBeans has issues with debugging, as other posts suggest.\n", "added solution is debugging if don't have any compilin...
[ 1, 0 ]
[]
[]
[ "netbeans", "python" ]
stackoverflow_0002044364_netbeans_python.txt
Q: SymPy: How to return an expression in terms of other expression(s)? I'm fairly new to SymPy and have what might be a basic question. Or I might simply be misinterpreting how SymPy is supposed to be used. Is there a way to create an expression that is not represented by atoms, but by a combination of other express...
SymPy: How to return an expression in terms of other expression(s)?
I'm fairly new to SymPy and have what might be a basic question. Or I might simply be misinterpreting how SymPy is supposed to be used. Is there a way to create an expression that is not represented by atoms, but by a combination of other expressions? Example: >>> from sympy.physics.units import * >>> expr1 = m/s >>> ...
[ "Checking the source for sympy.physics.units you can see that all units are defined in terms of meters, kilograms, seconds, amperes, kelvins, moles and candelas. These are the base units.\nThen a mile is defined as 5280 feet, and a foot is defined as 0.3048 meters.\nSo all expressions using non-base units will have...
[ 2, 2, 1 ]
[]
[]
[ "python", "sympy" ]
stackoverflow_0002038100_python_sympy.txt
Q: DateTimeProperty has error being set to a datetime in Google App Engine I'm having a weird error with some Google App Engine code I'm writing. My program contains some code like this: import datetime ... class Action(db.Model): visibleDate = db.DateTimeProperty() ... getActionQuery = Action.gql("WHERE user...
DateTimeProperty has error being set to a datetime in Google App Engine
I'm having a weird error with some Google App Engine code I'm writing. My program contains some code like this: import datetime ... class Action(db.Model): visibleDate = db.DateTimeProperty() ... getActionQuery = Action.gql("WHERE user = :user AND __key__ = :key", user = user, key = self.request.get("key")) the...
[ "I think there's something you missed in your traceback.\nI'm seeing:datetime.datetime.strptime(self.request.get(\"visibleDate\"), \"%Y/%m/%d\"),\nNotice the comma at the end of the line.\nThat comma makes that line return a tuple with your date inside it. I'm assuming you accidentally added the comma, so just remo...
[ 5 ]
[]
[]
[ "datetime", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002042913_datetime_google_app_engine_google_cloud_datastore_python.txt
Q: How do I add content before in extended page? (KID templates) I've got master.kid (simplified): <html> <head py:match="item.tag == 'head'"> <title>My Site</title> </head> <body py:match="item.tag == 'body'"> <h1>My Site</h1> <div py:replace="item[:]"></div> <p id="footer">Copyright Blixt 2010</p> </body> ...
How do I add content before in extended page? (KID templates)
I've got master.kid (simplified): <html> <head py:match="item.tag == 'head'"> <title>My Site</title> </head> <body py:match="item.tag == 'body'"> <h1>My Site</h1> <div py:replace="item[:]"></div> <p id="footer">Copyright Blixt 2010</p> </body> </html> And mypage.kid: <html> <head></head> <body> <p>Hello Worl...
[ "The best solution I've found is the following:\nmaster.kid:\n<html>\n<head py:match=\"item.tag == 'head'\">\n <title>My Site</title>\n</head>\n<body py:match=\"item.tag == 'body'\">\n <h1>My Site</h1>\n <div py:replace=\"item[:]\"></div>\n <p id=\"footer\">Copyright Blixt 2010</p>\n <div py:if=\"defined('body...
[ 1 ]
[]
[]
[ "python", "turbogears" ]
stackoverflow_0001999300_python_turbogears.txt
Q: Django: Increment blog entry view count by one. Is this efficient? I have the following code in my index view. latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10] for entry in latest_entry_list: entry.views = entry.views + 1 entry.save() If there are ten (the limit...
Django: Increment blog entry view count by one. Is this efficient?
I have the following code in my index view. latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10] for entry in latest_entry_list: entry.views = entry.views + 1 entry.save() If there are ten (the limit) rows returned from the initial query, will the save issue 10 seperate ...
[ "You can use F() objects for this. \nHere is how you import F: from django.db.models import F\nNew in Django 1.1.\nCalls to update can also use F() objects to update one field based on the value of another field in the model. This is especially useful for incrementing counters based upon their current value.\nEntry...
[ 69, 13, 3, 2, 2 ]
[]
[]
[ "database", "django", "performance", "python" ]
stackoverflow_0000447117_database_django_performance_python.txt
Q: exposing std::vector with boost.python I have written some C++ code that generates a std::vector. I also have a python script that manipulates some data that, for now, I am declaring like this (below). import numpy x = numpy.random.randn(1000) y = numpy.random.randn(1000) I can run the script fine. From my C++ ...
exposing std::vector with boost.python
I have written some C++ code that generates a std::vector. I also have a python script that manipulates some data that, for now, I am declaring like this (below). import numpy x = numpy.random.randn(1000) y = numpy.random.randn(1000) I can run the script fine. From my C++ code: using namespace boost::python; ...
[ "The following code works for me (Python 2.6, Boost 1.39). This is almost the same as your code, except without the BOOST_PYTHON_MODULE line itself (but with the class_ definition for the vector). BOOST_PYTHON_MODULE only needs to be used when creating extension modules.\n#include <iostream>\n#include <boost/python...
[ 12, 3 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0001937135_boost_python_c++_python.txt
Q: Pythonize Me: how to manage caller context variables in Python? (Python/Django) I'm trying to refactor a fairly hefty view function in Django. There are too many variables floating around and it's a huge function. Ideally, I want to modularize the view into logical functions. However, I have to pass the function ...
Pythonize Me: how to manage caller context variables in Python? (Python/Django)
I'm trying to refactor a fairly hefty view function in Django. There are too many variables floating around and it's a huge function. Ideally, I want to modularize the view into logical functions. However, I have to pass the function context around to get easy access to the variables. For example: def complex_view(req...
[ "I like (d) - Create a class for it, and use member functions to do the work.\nIn Django, a view is just a 'callable' that accepts an HTTPRequest object, and whatever other paramaters your URL routing passes to it.\nPython classes can be callable just like functions, if you define a __call__ method on them, like th...
[ 10, 0 ]
[]
[]
[ "django", "django_context", "python" ]
stackoverflow_0002044941_django_django_context_python.txt
Q: Scripting HTTP more effeciently Often times I want to automate http queries. I currently use Java(and commons http client), but would probably prefer a scripting based approach. Something really quick and simple. Where I can set a header, go to a page and not worry about setting up the entire OO lifecycle, setting...
Scripting HTTP more effeciently
Often times I want to automate http queries. I currently use Java(and commons http client), but would probably prefer a scripting based approach. Something really quick and simple. Where I can set a header, go to a page and not worry about setting up the entire OO lifecycle, setting each header, calling up an html pars...
[ "Mechanize for Python seems easy to use: http://wwwsearch.sourceforge.net/mechanize/\n", "Have a look at Selenium. It generates code for C#, Java, Perl, PHP, Python, and Ruby if you need to customize the script.\n", "Watir sounds close to what you want although it (like Selenium linked to in another answer) act...
[ 6, 6, 6, 6, 6, 4, 3, 2, 2, 2, 0, 0 ]
[]
[]
[ "http", "perl", "python", "ruby", "scripting" ]
stackoverflow_0002043058_http_perl_python_ruby_scripting.txt
Q: Pass session information from php to python securely? (in agile) I have a sign up process that is in a legacy framework and we are trying to switch to a new framework...in fact a different language. So let's say that there are 3 steps in the sign up process and each of those 3 steps has it's own file(step1.php, st...
Pass session information from php to python securely? (in agile)
I have a sign up process that is in a legacy framework and we are trying to switch to a new framework...in fact a different language. So let's say that there are 3 steps in the sign up process and each of those 3 steps has it's own file(step1.php, step2.php, step3.php). Now if I want to change page2.php to a python fil...
[ "In PHP, store the session information in a database, encoded in JSON. In Python, pull the session ID from the cookie and look up the session information in the database.\n" ]
[ 2 ]
[]
[]
[ "php", "python", "session" ]
stackoverflow_0002045131_php_python_session.txt
Q: Good backend for downloading nzb files to seperate directories I'm laying out a download management that will segregate each users downloads, separate watched directories each download to their own folders, can't see each others queues, etc. I wanted to use Hellanzb with xml-rpc, however it does not seem to allow...
Good backend for downloading nzb files to seperate directories
I'm laying out a download management that will segregate each users downloads, separate watched directories each download to their own folders, can't see each others queues, etc. I wanted to use Hellanzb with xml-rpc, however it does not seem to allow me to set separate download directories for each file. I want to av...
[ "I'd check out http://github.com/maddox/pyrot. It may do what you need.\n" ]
[ 0 ]
[]
[]
[ "network_programming", "nntp", "python", "usenet", "xml_rpc" ]
stackoverflow_0002045215_network_programming_nntp_python_usenet_xml_rpc.txt
Q: Python XMLRPC: Handling arbitrary exceptions on client-side I'm trying to pass arbitrary exceptions from a XMLRPC server to a client (both Python scripts, exception types are defined on both sides). There's an exemplary client-side implementation at ActiveState Recipes which parses the returned "faultString", comp...
Python XMLRPC: Handling arbitrary exceptions on client-side
I'm trying to pass arbitrary exceptions from a XMLRPC server to a client (both Python scripts, exception types are defined on both sides). There's an exemplary client-side implementation at ActiveState Recipes which parses the returned "faultString", compares it with a list of known exceptions and, if found, raises tha...
[ "You could populate the allowed_errors list from __builtins__:\n[exc for exc in __builtins__ if isinstance(exc, BaseException)]\n\nThis would handle the common case, for built-in exceptions like ValueError, TypeError, OSError, etc. You could probably do something more advanced like PyYAML and pickle, where they aut...
[ 2 ]
[]
[]
[ "python", "xml_rpc", "xmlrpclib" ]
stackoverflow_0002044904_python_xml_rpc_xmlrpclib.txt
Q: What is the proper way to use str.decode and unicode.encode? What is the proper way to use str.decode and unicode.encode? Eg. print str.decode print unicode.encode A: Ignacio's example is correct but depends on your console being able to display Unicode characters, which on Windows it usually can't. Here's the s...
What is the proper way to use str.decode and unicode.encode?
What is the proper way to use str.decode and unicode.encode? Eg. print str.decode print unicode.encode
[ "Ignacio's example is correct but depends on your console being able to display Unicode characters, which on Windows it usually can't. Here's the same thing with only safe string escapes (reprs):\n>>> '\\xe3\\x81\\x82'.decode('utf-8') # three top-bit-set bytes, representing one character\nu'\\u3042' ...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002025969_python.txt
Q: How can I make Python see sqlite? I cannot use sqlite3 (build python package), for the reason that _sqlite3.so file is missing. I found that people had the same problem and they resolved it here. To solve my problem I have to "install sqlite3 and recompile Python". I also found out that the problem can be solved b...
How can I make Python see sqlite?
I cannot use sqlite3 (build python package), for the reason that _sqlite3.so file is missing. I found that people had the same problem and they resolved it here. To solve my problem I have to "install sqlite3 and recompile Python". I also found out that the problem can be solved by "building from source and moving the ...
[ "I don't have exact answer, but few hints here\n\nTo install python from source, you don't need to be root, you can always install at /home/USERNAME/usr, for example when you do configure, do like ./configure --prefix=/home/USERNAME/usr\nInstalling sqlite binaries does not mean its included python extension (instea...
[ 0 ]
[]
[]
[ "pysqlite", "python", "sqlite" ]
stackoverflow_0001481237_pysqlite_python_sqlite.txt
Q: i have '__contains__' ,why error class a(object): def a(self): return True __contains__=a b=a() print 2 in b#why error A: __contains__ is meant to take an argument. a doesn't accept an argument. The following is your example with a working __contains__: >>> class a(object): ... def a(self, i...
i have '__contains__' ,why error
class a(object): def a(self): return True __contains__=a b=a() print 2 in b#why error
[ "__contains__ is meant to take an argument. a doesn't accept an argument.\nThe following is your example with a working __contains__:\n>>> class a(object):\n... def a(self, item):\n... return True\n... __contains__=a\n...\n>>> b=a()\n>>> print 2 in b\nTrue\n\n", "The signature of __contains__ is:\...
[ 7, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002046209_python.txt
Q: Getting String from A TextCtrl Box How to get the strings from a TextCtrl box? Here is the practice code: import wx class citPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) wx.StaticText(self, -1, "Choose put you would like:", (45, 15)) self.quote...
Getting String from A TextCtrl Box
How to get the strings from a TextCtrl box? Here is the practice code: import wx class citPanel(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) wx.StaticText(self, -1, "Choose put you would like:", (45, 15)) self.quote = wx.StaticText(self, -1, "1:", wx.P...
[ "TextCtrlInstance.GetValue()\n\n", "Use GetValue(), not GetString()\nLook at the API:\nhttp://docs.wxwidgets.org/stable/wx_wxtextctrl.html\n" ]
[ 27, 3 ]
[]
[]
[ "python", "textctrl", "wxpython" ]
stackoverflow_0002046338_python_textctrl_wxpython.txt
Q: Compare attributes of a Django Queryset in a template using the `in` Operator I'm trying to use the in operator to determine if a template variable on the current page is also a foreign key in another model. The model is like so: class WishlistItem(models.Model): user = models.ForeignKey(User, related_name='w...
Compare attributes of a Django Queryset in a template using the `in` Operator
I'm trying to use the in operator to determine if a template variable on the current page is also a foreign key in another model. The model is like so: class WishlistItem(models.Model): user = models.ForeignKey(User, related_name='wishlist_items') issue = models.ForeignKey(Issue) On the "Issue" page template,...
[ "I ended up solving this by writing a template filter:\n@register.filter\ndef in_list(obj, arg):\n \"Is the issue in the list?\"\n return obj in (item.issue for item in arg)\n\nThen I could do something like this in a template:\n{% if issue|in_list:user.wishlist_items.all %}\n\nI got the idea from the answer ...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001993064_django_python.txt
Q: Find sequences of digits in long integers efficiently Is it possible to find a defined sequence in an integer without converting it to a string? That is, is it possible to do some form of pattern matching directly on integers. I have not thought of one but I keeping thinking there should be a mathematical way of d...
Find sequences of digits in long integers efficiently
Is it possible to find a defined sequence in an integer without converting it to a string? That is, is it possible to do some form of pattern matching directly on integers. I have not thought of one but I keeping thinking there should be a mathematical way of doing this. That's not to say it is more efficient. (edit) I...
[ "You can use this class to have your generator of digits :-)\nimport math\n\nclass DecimalIndexing:\n def __init__(self, n):\n self.n = n\n def __len__(self):\n return int(math.floor(math.log10(self.n)+1))\n def __getitem__(self, i):\n if isinstance(i, slice):\n return [self...
[ 3, 1, 1, 0, 0 ]
[]
[]
[ "integer", "pattern_matching", "performance", "python", "sequence" ]
stackoverflow_0002042916_integer_pattern_matching_performance_python_sequence.txt
Q: Creating waitable objects in Python I more or less know how to use select() to take a list of sockets, and only return the ones that are ready to read/write something. The project I'm working on now has a class called 'user'. Each 'user' object contains its own socket. What I would like to do is pass a list of ...
Creating waitable objects in Python
I more or less know how to use select() to take a list of sockets, and only return the ones that are ready to read/write something. The project I'm working on now has a class called 'user'. Each 'user' object contains its own socket. What I would like to do is pass a list of users to a select(), and get back a list ...
[ "You should have your User class implement a fileno(self) method which returns self.thesocket.fileno() -- that's the way to make select work on your own classes (sockets only on windows, arbitrary files on Unix-like systems). Not sure what switch is supposed to me -- don't recognize it as a standard library (or bu...
[ 2 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0002046727_python_sockets.txt
Q: Tab Completion in Python Command Line Interface - how to catch Tab events I'm writing a little CLI in Python (as an extension to Mercurial) and would like to support tab-completion. Specifically, I would like catch tabs in the prompt and show a list of matching options (just like bash). Example: Enter section name...
Tab Completion in Python Command Line Interface - how to catch Tab events
I'm writing a little CLI in Python (as an extension to Mercurial) and would like to support tab-completion. Specifically, I would like catch tabs in the prompt and show a list of matching options (just like bash). Example: Enter section name: ext*TAB* extensions extras The problem is I'm not sure how to catch t...
[ "For that you use the readline module.\nSimplest code I can think:\nimport readline\nCOMMANDS = ['extra', 'extension', 'stuff', 'errors',\n 'email', 'foobar', 'foo']\n\ndef complete(text, state):\n for cmd in COMMANDS:\n if cmd.startswith(text):\n if not state:\n retur...
[ 17, 2, 1 ]
[]
[]
[ "mercurial", "python", "raw_input", "tab_completion" ]
stackoverflow_0002046050_mercurial_python_raw_input_tab_completion.txt
Q: Pylons "global name 'c' is not defined" i had setup Pylons v0.9.7, and created a project using genshi. I tried to code an easy test case, but it is not working. code: member.py coding: utf-8 import logging import foo.model from foo.lib.base import * log = logging.getLogger(__name__) class MemberController(Base...
Pylons "global name 'c' is not defined"
i had setup Pylons v0.9.7, and created a project using genshi. I tried to code an easy test case, but it is not working. code: member.py coding: utf-8 import logging import foo.model from foo.lib.base import * log = logging.getLogger(__name__) class MemberController(BaseController): def index(self): c....
[ " c.title=\"title\"\n\nrequires name c to be defined (globally or locally). You never define anything named c.\nSo, define a suitable name c (one where attribute title can be set!) before you assign anything to c.title!\nNext hint: from pylons import tmpl_context as c -- you didn't do that from ... import ... a...
[ 2 ]
[]
[]
[ "genshi", "pylons", "python" ]
stackoverflow_0002046789_genshi_pylons_python.txt
Q: File open: Is this bad Python style? To read contents of a file: data = open(filename, "r").read() The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing. EDIT: Thi...
File open: Is this bad Python style?
To read contents of a file: data = open(filename, "r").read() The open file immediately stops being referenced anywhere, so the file object will eventually close... and it shouldn't affect other programs using it, since the file is only open for reading, not writing. EDIT: This has actually bitten me in a project I wr...
[ "Just for the record:\nThis is only slightly longer, and closes the file immediately:\nfrom __future__ import with_statement\n\nwith open(filename, \"r\") as f:\n data = f.read()\n\n", "It is true that it will close eventually, but eventually might not be soon enough. Especially if you're using this inside a l...
[ 30, 7, 4, 3, 2, 1 ]
[]
[]
[ "coding_style", "file", "file_io", "python" ]
stackoverflow_0001373660_coding_style_file_file_io_python.txt
Q: Stackless Python and PyQt What experiences do you have with Stackless Python and PyQt? Issues i would be happy if people address: Compilation of PyQt for Stackless: does PyQt need to be compiled especially for Stackless? is the compilation smooth? problems with bindings etc. Stability: any unexpected crashes, fre...
Stackless Python and PyQt
What experiences do you have with Stackless Python and PyQt? Issues i would be happy if people address: Compilation of PyQt for Stackless: does PyQt need to be compiled especially for Stackless? is the compilation smooth? problems with bindings etc. Stability: any unexpected crashes, freezes, pauses and other weirditi...
[ "If you're interested in all that because of speed optimization:\nYou may want to check out Unladen Swallow ( Wikipedia here ). Google (because of YouTube being 100% Python) is working on a JIT compiler for Python that will increase its speed by 5-10x (bringing it much closer to Java speeds than the current virtual...
[ 0, 0 ]
[]
[]
[ "pyqt", "pyqt4", "python", "python_stackless", "stackless" ]
stackoverflow_0001749818_pyqt_pyqt4_python_python_stackless_stackless.txt
Q: What is/are the Python equivalent(s) to the Java Collections Framework? The Java Collections Framework is like the C++ Standard Template Library: "a unified architecture for representing and manipulating collections (objects that group multiple elements into a single unit)." http://java.sun.com/docs/books/tutorial...
What is/are the Python equivalent(s) to the Java Collections Framework?
The Java Collections Framework is like the C++ Standard Template Library: "a unified architecture for representing and manipulating collections (objects that group multiple elements into a single unit)." http://java.sun.com/docs/books/tutorial/collections/intro/index.html
[ "As it turns out, the equivalent to the Java Collections Framework in Python is... Python. All of the core collections featured in the Java Collections Framework are already present in core Python.\nGive it a try! Sequences provide lists, queues, stacks, etc. Dictionaries are your hash-tables and maps. Sets are...
[ 15, 12 ]
[]
[]
[ "c++", "collections", "java", "python" ]
stackoverflow_0002047220_c++_collections_java_python.txt
Q: Unit testing file write in Python I am writing a wrapper for the ConfigParser in Python to provide an easy interface for storing and retrieving application settings. The wrapper has two methods, read and write, and a set of properties for the different application settings. The write method is just a wrapper for t...
Unit testing file write in Python
I am writing a wrapper for the ConfigParser in Python to provide an easy interface for storing and retrieving application settings. The wrapper has two methods, read and write, and a set of properties for the different application settings. The write method is just a wrapper for the ConfigParser's write method with the...
[ "First, you don't actually need to unit test open(), since it's pretty reasonable to assume that the standard library is correct.\nNext, you don't want to do file system manipulations to get open() to generate the error you want, because then you're not unit testing, you're doing a functional/integration test by in...
[ 7, 5, 2 ]
[]
[]
[ "file_io", "python", "unit_testing" ]
stackoverflow_0002047459_file_io_python_unit_testing.txt
Q: Sets module deprecated warning When I run my python script I get the following warning DeprecationWarning: the sets module is deprecated How do I fix this? A: Stop using the sets module, or switch to an older version of python where it's not deprecated. According to pep-004, sets is deprecated as of v2.6, repla...
Sets module deprecated warning
When I run my python script I get the following warning DeprecationWarning: the sets module is deprecated How do I fix this?
[ "Stop using the sets module, or switch to an older version of python where it's not deprecated.\nAccording to pep-004, sets is deprecated as of v2.6, replaced by the built-in set and frozenset types.\n", "History:\nBefore Python 2.3: no set functionality\nPython 2.3: sets module arrived\nPython 2.4: set and froze...
[ 35, 27, 5, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002040616_python.txt
Q: Dithering in text using PIL and truetype fonts Consider the following code: from PIL import Image, ImageDraw, ImageFont def addText(img, lTxt): FONT_SIZE = 10 INTERLINE_DISTANCE = FONT_SIZE + 1 font = ImageFont.truetype('arial.ttf', FONT_SIZE) lTxtImageHeight = INTERLINE_DISTANCE * len(lTxt) ...
Dithering in text using PIL and truetype fonts
Consider the following code: from PIL import Image, ImageDraw, ImageFont def addText(img, lTxt): FONT_SIZE = 10 INTERLINE_DISTANCE = FONT_SIZE + 1 font = ImageFont.truetype('arial.ttf', FONT_SIZE) lTxtImageHeight = INTERLINE_DISTANCE * len(lTxt) # create text image lTxtImg = Image.new('RGBA...
[ "I suggest writing the intermediate text images to file (the text, then the rotated text), to isolate where the artefacts first appear.\nOne other possibility could be that the png encoding is using a pallete with no grayscale values, so those reds are the closest available. I checked the encoding of the files on i...
[ 0 ]
[]
[]
[ "dithering", "python", "python_imaging_library", "text" ]
stackoverflow_0002047534_dithering_python_python_imaging_library_text.txt
Q: How to use Python to get local admins from a computer on the Network? I need to get a list of all people in the company who have local admin rights on their computers. We have a group on each machine called "Administrators." I can get a list of all computers from active directory with: import active_directory for...
How to use Python to get local admins from a computer on the Network?
I need to get a list of all people in the company who have local admin rights on their computers. We have a group on each machine called "Administrators." I can get a list of all computers from active directory with: import active_directory for computer in active_directory.search ("objectCategory='Computer'"): print...
[ "Is this the data from this operation going to be manipulated afterwards? If this is a manual scan that is going to be looked at by a human, then you're way overthinking it.\nJust use a network scanner to handle it for you, such as this one.\n", "I'm not sure of the details but it sounds like you may want to take...
[ 0, 0 ]
[]
[]
[ "active_directory", "python", "winreg" ]
stackoverflow_0002047355_active_directory_python_winreg.txt
Q: There's an example on how to use an API with Python and cURL. Is it feasable to just copy the code if I have IronPython installed and have it work? Here's the code in question: #!/usr/bin/python import pycurl c = pycurl.Curl() values = [ ("key", "YOUR_API_KEY"), ("image", (c.FORM_FILE, "file....
There's an example on how to use an API with Python and cURL. Is it feasable to just copy the code if I have IronPython installed and have it work?
Here's the code in question: #!/usr/bin/python import pycurl c = pycurl.Curl() values = [ ("key", "YOUR_API_KEY"), ("image", (c.FORM_FILE, "file.png"))] # OR: ("image", "http://example.com/example.jpg"))] c.setopt(c.URL, "http://imgur.com/api/upload.xml") c.setopt(c.HTTPPOST, values) c.perfo...
[ "In C#, you can use the WebRequest class to accomplish the same. Take a look at the example toward the bottom of the page \"How to: Send Data Using the WebRequest Class\" for a code sample. \n", "The code itself looks straightforward. I don't know if pycurl is available as a .NET module (or whatever it's called...
[ 1, 0, 0, 0 ]
[]
[]
[ "c#", "curl", "ironpython", "python" ]
stackoverflow_0002043848_c#_curl_ironpython_python.txt
Q: Lines do not render on an offscreen frame buffer with a completely black texture If I have a frame buffer which has a textured binded to it which is simply black with full alpha and I try to draw a line to it, even if the line has full alpha it wont render. I'm not stupid, so the lines definitely aren't black. If ...
Lines do not render on an offscreen frame buffer with a completely black texture
If I have a frame buffer which has a textured binded to it which is simply black with full alpha and I try to draw a line to it, even if the line has full alpha it wont render. I'm not stupid, so the lines definitely aren't black. If the texture is white instead the line suddenly render correctly as if the colour of th...
[ "There is at least one thing that looks suspicious: you're turning on Texturing in your init code, and forgetting about it.\nSo your lines are drawn with texturing on (and constant texture coordinates), presumably picking the texture that you're trying to write to.\nThis is likely not what you want (I don't remembe...
[ 1 ]
[]
[]
[ "alphablending", "framebuffer", "opengl", "pyopengl", "python" ]
stackoverflow_0002034775_alphablending_framebuffer_opengl_pyopengl_python.txt
Q: Easy way of getting started programming using python Background I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding wh...
Easy way of getting started programming using python
Background I'm trying to learn to program a little & python seems like a good choice for my purpose. I have no ambition of ever being a serious programmer.I already know bits and pieces of html, css, javascript (mostly how to cut & paste without understanding what I'm doing). The last time I actually "learned programmi...
[ "Lots of great \"Python tutorials for non-programmers\" are listed here!\n", "I recommend biting the bullet and using the command line version to start with.\nLater you'll get onto writing scripts and you'll need a good editor, but not necessarily a python IDE.\nFor learning I found the \"Python Tutorial\" by Gui...
[ 3, 2, 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002047165_python.txt
Q: Why does this Python code print nothing? class a(str): def b(self,*x,**y): print str.decode(self,*x,**y) b=a() b.b('utf-8','aaa') # This prints nothing, why? A: Try initialize your string first, with some value: # classes should have capitalized names ... class a(str): def b(self,*x,**y): ...
Why does this Python code print nothing?
class a(str): def b(self,*x,**y): print str.decode(self,*x,**y) b=a() b.b('utf-8','aaa') # This prints nothing, why?
[ "Try initialize your string first, with some value:\n# classes should have capitalized names ...\nclass a(str):\n def b(self,*x,**y):\n print 'debugging: ', self, x, y\n print str.decode(self, *x,**y)\n\nif __name__ == '__main__':\n b=a('aaa')\n b.b('utf-8')\n\n b=a()\n b.b('utf-8')\n\n...
[ 8, 4, 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002048442_python.txt
Q: Regex match even number of letters I need to match an expression in Python with regular expressions that only matches even number of letter occurrences. For example: AAA # no match AA # match fsfaAAasdf # match sAfA # match sdAAewAsA # match AeAiA # no match An even number of As SHOULD...
Regex match even number of letters
I need to match an expression in Python with regular expressions that only matches even number of letter occurrences. For example: AAA # no match AA # match fsfaAAasdf # match sAfA # match sdAAewAsA # match AeAiA # no match An even number of As SHOULD match.
[ "Try this regular expression:\n^[^A]*((AA)+[^A]*)*$\n\nAnd if the As don’t need to be consecutive:\n^[^A]*(A[^A]*A[^A]*)*$\n\n", "This searches for a block with an odd number of A's. If you found one, the string is bad for you:\n(?<!A)A(AA)*(?!A)\n\nIf I understand correctly, the Python code should look like:\nif...
[ 27, 3, 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002045175_python_regex.txt
Q: Search and sort data from several files I have a set of 1000 text files with names in_s1.txt, in_s2.txt and so. Each file contains millions of rows and each row has 7 columns like: ccc245 1 4 5 5 3 -12.3 For me the most important is the values from the first and seventh columns; the pairs ccc245 , -12.3 What I ne...
Search and sort data from several files
I have a set of 1000 text files with names in_s1.txt, in_s2.txt and so. Each file contains millions of rows and each row has 7 columns like: ccc245 1 4 5 5 3 -12.3 For me the most important is the values from the first and seventh columns; the pairs ccc245 , -12.3 What I need to do is to find between all the in_sXXXX....
[ "In python, use the nsmallest function in the heapq module -- it's designed for exactly this kind of task.\nExample (tested) for Python 2.5 and 2.6:\nimport heapq, glob\n\ndef my_iterable():\n for fname in glob.glob(\"in_s*.txt\"):\n f = open(fname, \"r\")\n for line in f:\n items = line...
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002048779_bash_python.txt
Q: Writing copyright information in python code What is the standard way of writing "copyright information" in python code? Should it be inside docstring or in block comments? I could not find it in PEPs. A: Some projects use module variables like __license__, as in: __author__ = "Software Authors Name" __copyright...
Writing copyright information in python code
What is the standard way of writing "copyright information" in python code? Should it be inside docstring or in block comments? I could not find it in PEPs.
[ "Some projects use module variables like __license__, as in:\n__author__ = \"Software Authors Name\"\n__copyright__ = \"Copyright (C) 2004 Author Name\"\n__license__ = \"Public Domain\"\n__version__ = \"1.0\"\n\nSeems like a pretty clean solution to me (unless you overdo it and dump epic texts into these variables)...
[ 39, 13, 6, 3 ]
[]
[]
[ "coding_style", "copyright_display", "python" ]
stackoverflow_0002048874_coding_style_copyright_display_python.txt
Q: How to get a function to execute I have a function and I want it to execute. Does anyone know how to do this? def a(): a = 'print' print a A: The name of your function is a. It takes no arguments. So call it using a(): >>> def a(): ... a = 'print' ... print a ... >>> a() print Note that you sh...
How to get a function to execute
I have a function and I want it to execute. Does anyone know how to do this? def a(): a = 'print' print a
[ "The name of your function is a. It takes no arguments. So call it using a():\n>>> def a():\n... a = 'print'\n... print a\n... \n>>> a()\nprint\n\nNote that you shadow the definition of a as a function within a itself, by defining a local variable with that same name. You may want to avoid that, as it may c...
[ 14, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002049605_python.txt
Q: Change the events for different parts of the same widget I have created a margin in a gtk.TextView widget. Now I want to make sure that the default event handler for mouse click, which is moving the text cursor to the clicked position, works only when clicked to the right of the margin. Is this possible? A: Try...
Change the events for different parts of the same widget
I have created a margin in a gtk.TextView widget. Now I want to make sure that the default event handler for mouse click, which is moving the text cursor to the clicked position, works only when clicked to the right of the margin. Is this possible?
[ "Try connecting to the button-press-event but doing it before the widget's own connection. If you connect after the view does it, this will be the default (GObject signal handlers are handled in reverse order of connection by default). Then determine if the event should be let through or not, by returning TRUE (to ...
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0002033810_gtk_pygtk_python.txt
Q: architecture of chat website using twisted matrix I am willing to devlop a anonymus chat website.The website pairs 2 random people who are logged into the website and then allows them to chat to each other.Now if any one of them gets disconnected then the other will get connected to any other person who is single....
architecture of chat website using twisted matrix
I am willing to devlop a anonymus chat website.The website pairs 2 random people who are logged into the website and then allows them to chat to each other.Now if any one of them gets disconnected then the other will get connected to any other person who is single. Now i have some doubts regarding archicture. Each tim...
[ "Take a look at Nevow and Athena. These will let you serve web pages to clients and handle messages sent back from them.\n" ]
[ 3 ]
[]
[]
[ "chat", "python", "twisted" ]
stackoverflow_0002046973_chat_python_twisted.txt
Q: Why can't I pickle this object? I have a class (below): class InstrumentChange(object): '''This class acts as the DTO object to send instrument change information from the client to the server. See InstrumentChangeTransport below ''' def __init__(self, **kwargs): self.kwargs = kwargs ...
Why can't I pickle this object?
I have a class (below): class InstrumentChange(object): '''This class acts as the DTO object to send instrument change information from the client to the server. See InstrumentChangeTransport below ''' def __init__(self, **kwargs): self.kwargs = kwargs self._changed = None def _...
[ "Your code has several minor \"side\" issues: the sudden appearance of a 'Transport' in the class name used in the test (it's not the class name that you're defining), the dubious trampling over built-in identifier file as a local variable (don't do that -- it doesn't hurt here, but the habit of trampling over buil...
[ 37, 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002049849_python.txt
Q: python CGI and JQUERY problem I have a simple python CGI script where I query a MySQL database and then prints the result to the screen/webpage. My problem is that the "cursor.execute()" function returns a list of tuples. I use a simple for loop to iterate through this list and extract each tuple. This was working...
python CGI and JQUERY problem
I have a simple python CGI script where I query a MySQL database and then prints the result to the screen/webpage. My problem is that the "cursor.execute()" function returns a list of tuples. I use a simple for loop to iterate through this list and extract each tuple. This was working great until.....I got the bright i...
[ "It looks like you have a syntax error. In Python and Javascript, the code:\n{referer: http://test/index-test.html}\n\nis invalid. In Javascript, you'd have to write it like:\n{referer: \"http://test/index-test.html\"}\n\nand in Python (assuming \"referer\" is a key and not a variable) as:\n{\"referer\": \"http://t...
[ 0 ]
[]
[]
[ "cgi", "jquery", "python" ]
stackoverflow_0002049506_cgi_jquery_python.txt
Q: python to Java checksum calculation I received this python script that generates a file checksum: import sys,os if __name__=="__main__": #filename=os.path.abspath(sys.argv[1]) #filename=r"H:\Javier Ortiz\559-7 From Pump.bin" cksum=0 offset=0 pfi=open(filename,'rb') while 1: icks=0 chunk=pfi.read(256) if not...
python to Java checksum calculation
I received this python script that generates a file checksum: import sys,os if __name__=="__main__": #filename=os.path.abspath(sys.argv[1]) #filename=r"H:\Javier Ortiz\559-7 From Pump.bin" cksum=0 offset=0 pfi=open(filename,'rb') while 1: icks=0 chunk=pfi.read(256) if not chunk: break #if EOF exit loop f...
[ "Your Python version prints the checksum in hex, while your Java version prints it in decimal. You should make your Java version print in hex, too. 0x1c0 == 448.\nTo use the cksum=0x%4.4x format string as you had in your Python version, use this:\nSystem.out.printf(\"cksum=0x%4.4x%n\", ...);\n\nor even better\nSyst...
[ 5, 3, 1 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002050325_java_python.txt
Q: Django/Python - Try/except problem i have code like this: try: var = request.POST['var'] except NameError: var = '' Why always code after "except" is executing? Even if request.POST['var'] exist. A: How do you know it is executing? ...
Django/Python - Try/except problem
i have code like this: try: var = request.POST['var'] except NameError: var = '' Why always code after "except" is executing? Even if request.POST['var'] exist.
[ "How do you know it is executing? Perhaps request.POST['var'] is also '' so you couldn't tell the difference.\nAlso, the only way that \nvar = request.POST['var'] \n\ncould raise a NameError is if request doesn't exist.\nIf request.POST doesn't exist, means POST doesn't exist as an attribute of request thus raising...
[ 8, 2, 1, 1, 0 ]
[]
[]
[ "django", "python", "variables" ]
stackoverflow_0002050568_django_python_variables.txt
Q: Python: fill out a form and confirm with a button click Which do you think is the best method to fill out a form and confirm with clicking a button with Python? Do I have to use django? I want to do it in a simple way. Is there a library? Thanks in advance! A: mechanize A: There are tons. Check out this questi...
Python: fill out a form and confirm with a button click
Which do you think is the best method to fill out a form and confirm with clicking a button with Python? Do I have to use django? I want to do it in a simple way. Is there a library? Thanks in advance!
[ "mechanize\n", "There are tons. Check out this question for some gory details.\n" ]
[ 4, 3 ]
[]
[]
[ "button", "forms", "python" ]
stackoverflow_0002050705_button_forms_python.txt
Q: Standard Regex vs python regex discrepancy I am reading a book and they provide an example of how to match a given string with regular expressions. Here is their example: b*(abb*)*(a|∊) - Strings of a's and b's with no consecutive a's. Now I've tried converting it to python like so: >> p = re.compile(r'b*(abb*)*(...
Standard Regex vs python regex discrepancy
I am reading a book and they provide an example of how to match a given string with regular expressions. Here is their example: b*(abb*)*(a|∊) - Strings of a's and b's with no consecutive a's. Now I've tried converting it to python like so: >> p = re.compile(r'b*(abb*)*(a|)') # OR >> p = re.compile(r'b*(abb*)*(a|\b)')...
[ "Actually, the example works just fine ... to a small details. I would write:\n>>> p = re.compile('b*(abb*)*a?')\n>>> m = p.match('aa')\n>>> print m.group(0)\n'a'\n>>> m = p.match('abbabbabababbabbbbbaaaaa')\n>>> print m.group(0)\nabbabbabababbabbbbba\n\nNote that the group 0 returns the part of the string matched ...
[ 5, 5, 3, 3, 1, 1, 1 ]
[]
[]
[ "python", "regex", "theory" ]
stackoverflow_0002049685_python_regex_theory.txt
Q: Sending stdout as response from CGI spawned program I'm trying to compose a .zip file in a CGI program and send that as the content response. I'm getting stuck in that whenever I spawn a program that prints to stdout, that somehow doesn't get accepted by Apache. It seems to be something to do with spawning a pr...
Sending stdout as response from CGI spawned program
I'm trying to compose a .zip file in a CGI program and send that as the content response. I'm getting stuck in that whenever I spawn a program that prints to stdout, that somehow doesn't get accepted by Apache. It seems to be something to do with spawning a program that writes to stdout. The snippet below reproduce...
[ "Try sys.stdout.flush() before calling external programs.\n" ]
[ 1 ]
[]
[]
[ "apache", "cgi", "python" ]
stackoverflow_0002051030_apache_cgi_python.txt
Q: why is this an infinite loop in python? I can't seem to figure out why this is an infinite loop in python?? for i in range(n): j=1 while((i*j)<n): j+=1 shouldn't the outer loop go n times. incrementing j until its equal to n div i each time? A: i starts at 0, so the while condition stays always t...
why is this an infinite loop in python?
I can't seem to figure out why this is an infinite loop in python?? for i in range(n): j=1 while((i*j)<n): j+=1 shouldn't the outer loop go n times. incrementing j until its equal to n div i each time?
[ "i starts at 0, so the while condition stays always true; see the range docs for details.\n", "You can create a \"trace\" showing the state changes of the variables.\n\nn= 5; i= 0\nn= 5; i= 0; j= 1\ni*j < n -> 0 < 5: n= 5; i= 0; j= 2\ni*j < n -> 0 < 5: n= 5; i= 0; j= 3\ni*j < n -> 0 < 5: n= 5; i= 0; j= 4\ni*j < n...
[ 36, 16, 12, 7, 4, 2, 2, 1, 0 ]
[]
[]
[ "infinite_loop", "loops", "python" ]
stackoverflow_0002051034_infinite_loop_loops_python.txt
Q: Get HTML links within a specified using minidom I'm looking to use Python and xml.dom.minidom to get a list of links within a particular <table> specified by the table id. Based on some excellent advice, I'm trying to use the DOM instead of pattern matching. import urllib import xml.dom.minidom url = 'http://www...
Get HTML links within a specified using minidom
I'm looking to use Python and xml.dom.minidom to get a list of links within a particular <table> specified by the table id. Based on some excellent advice, I'm trying to use the DOM instead of pattern matching. import urllib import xml.dom.minidom url = 'http://www.batstrading.com/market_data/shortsales' page = xml.do...
[ "The problem is that minidom is a non-external-entity-reading XML parser. That means it doesn't even look at the DTD, so it doesn't know that in HTML the attribute with the name id corresponds to an ID schema type.\nA further consequence of this is that minidom won't know about the HTML-specific entities like &eacu...
[ 4, 0 ]
[]
[]
[ "minidom", "python" ]
stackoverflow_0002051270_minidom_python.txt
Q: Accessing samba shares with gio in python I am trying to make a simple command line client for accessing shares via the Python bindings of gio (yes, the main requirement is to use gio). I can see that comparing with it's predecessor gnome-vfs, it provides some means to do authentication stuff (subclassing MountOpe...
Accessing samba shares with gio in python
I am trying to make a simple command line client for accessing shares via the Python bindings of gio (yes, the main requirement is to use gio). I can see that comparing with it's predecessor gnome-vfs, it provides some means to do authentication stuff (subclassing MountOperation), and even some methods which are quite ...
[ "The following appears to be the minimum code needed to mount a volume:\ndef mount(f):\n op = gio.MountOperation()\n op.connect('ask-password', ask_password_cb)\n f.mount_enclosing_volume(op, mount_done_cb)\n\ndef ask_password_cb(op, message, default_user, default_domain, flags):\n op.set_username(USERN...
[ 6 ]
[]
[]
[ "authentication", "gio", "gnome", "python", "samba" ]
stackoverflow_0001991206_authentication_gio_gnome_python_samba.txt
Q: "Optional" backreferences in regular expression I have a regular expression with two groups that are OR'd and I'm wondering if it's possible to have a group be a back reference only if it matched? In all cases, I'm wanting to match spam.eggs.com Example: import re monitorName = re.compile(r"HQ01 : HTTP Service - ...
"Optional" backreferences in regular expression
I have a regular expression with two groups that are OR'd and I'm wondering if it's possible to have a group be a back reference only if it matched? In all cases, I'm wanting to match spam.eggs.com Example: import re monitorName = re.compile(r"HQ01 : HTTP Service - [Ss][Rr][Vv]\d+\.\w+\.com:(\w+\.\w+\.(?:net|com|org))...
[ "The | operator has early precedence so it applies to everything before it (from the beginning of your regex in this case) OR everything after it. In your regex, if there is no \"srv04.example.com\", it isn't checking if the string contains \"HTTP Service\"!\nYour two capturing groups are identical, so there's no p...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002051552_python_regex.txt
Q: django combine models.DecimalField with forms -> error: quantize result has too many digits for current context I want to combine a model decimal field with a forms choice field. The field in the model: sum = models.DecimalField(max_digits=2, decimal_places=2) The field in the form: sum = forms.ChoiceField(choice...
django combine models.DecimalField with forms -> error: quantize result has too many digits for current context
I want to combine a model decimal field with a forms choice field. The field in the model: sum = models.DecimalField(max_digits=2, decimal_places=2) The field in the form: sum = forms.ChoiceField(choices=WORK_HOUR_CHOICES, label='Sum Working Hours', required=True) The choices: WORK_HOUR_CHOICES = ( (0, '0'), ...
[ "It's just a guess, but I bet you need to put Decimals in there: \nWORK_HOUR_CHOICES = (\n (Decimal(\"0\"), '0'),\n (Decimal(\"0.5\"), '0.5'),\n (Decimal(\"1\"), '1'),\n (Decimal(\"1.5\"), '1.5'),\n (Decimal(\"2\"), '2'),\n (Decimal(\"2.5\"), '2.5')\n)\n\nYou can't initialize a Decimal with a floa...
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002051575_django_python.txt
Q: access to gnome configuration information using python Is there a standard way of accessing Gnome configuration information (i.e. ~/.gconf) using Python? Updated: please provide a short example. A: Python GConf, also check out packages like python-gconf and/or gnome-python-gconf in your distros package repo: /u...
access to gnome configuration information using python
Is there a standard way of accessing Gnome configuration information (i.e. ~/.gconf) using Python? Updated: please provide a short example.
[ "Python GConf, also check out packages like python-gconf and/or gnome-python-gconf in your distros package repo:\n\n/usr/share/doc/python-gconf/examples/\n\nOr browse the svn at http://svn.gnome.org/viewvc/gnome-python/trunk/examples/gconf/ for the examples.\nOn Fedora12 (my distro) it is called gnome-python2-gconf...
[ 10 ]
[]
[]
[ "gnome", "python" ]
stackoverflow_0002051905_gnome_python.txt
Q: PyQt4 Drag & Drop Qt4 has support for Drag & Drop actions and I've used them like in the tutorial. Now I want to be able to drag external elements (files) into the GUI form and perform actions based on that (like get the full path and copy it somewhere). I'm not sure whether this is a limitation like something Qt...
PyQt4 Drag & Drop
Qt4 has support for Drag & Drop actions and I've used them like in the tutorial. Now I want to be able to drag external elements (files) into the GUI form and perform actions based on that (like get the full path and copy it somewhere). I'm not sure whether this is a limitation like something Qt cannot do. Does someon...
[ "Most file managers provide drag-and-drop data using the text/uri-list target.\nRegarding the linked tutorial, first you need to set the widget to accept dropping text/uri-list data, then you can retrieve the URIs by calling event.mimeData().urls(). The return value is a list of QUrl objects.\n" ]
[ 3 ]
[]
[]
[ "pyqt4", "python", "qt4" ]
stackoverflow_0002051488_pyqt4_python_qt4.txt
Q: How to use a Django include tag for a separate HTML template? I am trying to use the include Django template tag, and inside it I reference a template which handles the format of the form. When I reference this though inside my template it outputs each of the dynamic parts, each character per new line, it is real...
How to use a Django include tag for a separate HTML template?
I am trying to use the include Django template tag, and inside it I reference a template which handles the format of the form. When I reference this though inside my template it outputs each of the dynamic parts, each character per new line, it is really strange. For example here is a snippet of the output: <form act...
[ "\nspaceless tag\nRemoves whitespace between HTML tags. This includes tab characters and newlines.\n\n", "form is probably a string rather than a Form object, and iterating over a string yields its individual characters.\n" ]
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002052114_django_python.txt
Q: creating 2 foreign keys that relate to one another class Product(models.Model): name = models.CharField(max_length = 127) description = models.TextField() code = models.CharField(max_length = 127) def __unicode__(self): return self.name class ProductLot(models.Model): produc...
creating 2 foreign keys that relate to one another
class Product(models.Model): name = models.CharField(max_length = 127) description = models.TextField() code = models.CharField(max_length = 127) def __unicode__(self): return self.name class ProductLot(models.Model): product = models.ForeignKey(Product) code = models.Foreig...
[ "if you have two FK to one model you need to give different related names:\nproduct = models.ForeignKey(Product, related_name='lot_product')\ncode = models.ForeignKey(Product, related_name='lot_code')\n\nrelated_name comes from django docs:\n\nForeignKey.related_name\nThe name to use for the relation from the relat...
[ 3, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002051895_django_python.txt
Q: Safely executing user-submitted python code on the server I am looking into starting a project which involves executing python code that the user enters via a HTML form. I know this can be potentially lethal (exec), but I have seen it done successfully in at least one instance. I sent an email off to the develope...
Safely executing user-submitted python code on the server
I am looking into starting a project which involves executing python code that the user enters via a HTML form. I know this can be potentially lethal (exec), but I have seen it done successfully in at least one instance. I sent an email off to the developers of the Python Challenge and I was told they are using a solu...
[ "On a modern Linux in addition to chroot(2) you can restrict process further by using clone(2) instead of fork(2). There are several interesting clone(2) flags:\nCLONE_NEWIPC (new namespace for semaphores, shared memory, message queues)\nCLONE_NEWNET (new network namespace - nice one)\nCLONE_NEWNS (new set of mount...
[ 3, 3, 2, 0 ]
[]
[]
[ "python", "user_input" ]
stackoverflow_0001737524_python_user_input.txt
Q: Updating the wx.gauge without while-loop Have been wondering about this for days now: I have a basic wxpython program like this: from MyModule import * class Form(wx.Panel): def __init__(self, parent, id): self.gauge = wx.Gauge(...) ... def ButtonClick(self, event): proc = LongProcess() while ...
Updating the wx.gauge without while-loop
Have been wondering about this for days now: I have a basic wxpython program like this: from MyModule import * class Form(wx.Panel): def __init__(self, parent, id): self.gauge = wx.Gauge(...) ... def ButtonClick(self, event): proc = LongProcess() while (LongProcess): self.gauge.SetValue(LongP...
[ "You can instantiate custom events from the non-GUI thread and wx.PostEvent them back to the GUI-thread. This is a thread-safe action. My use cases typically work like this:\n\nStart worker thread - Custom event 'Starting Action'\nStart processing\nPost events back updating progress 'Line 435 of 15000 is parsed'\n...
[ 8 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0002052369_python_wxpython.txt
Q: Problem assigning input to list I know this is probably an easy question but after reviewing the documentation for python 2.6.4 I cannot seem to find out what is wrong. This is my file, in it's entirety. The problem I am having is in get_phone_number(). After asking for the amount of phone numbers, I get this erro...
Problem assigning input to list
I know this is probably an easy question but after reviewing the documentation for python 2.6.4 I cannot seem to find out what is wrong. This is my file, in it's entirety. The problem I am having is in get_phone_number(). After asking for the amount of phone numbers, I get this error: Traceback (most recent call last):...
[ "replace \nself.phone_number[phone_count]\n\nwith\nself.phone_number = []\n\nThe first statement does nothing (actually, it tries to access the phone_count-th element of a list called phone_number in self, which does not exist, and hence the error).\nThe second statement defines a new list called phone_number.\n", ...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002052452_python.txt
Q: How to submit a form with more than 1 submit button. Sending a POST to a website. (Python) I am creating a script using Python Mechanize that can login to a website and submit a form. However, this form has 3 submit buttons (Preview, Post, and Cancel). I'm used to only one button... This is the form: <TextControl(...
How to submit a form with more than 1 submit button. Sending a POST to a website. (Python)
I am creating a script using Python Mechanize that can login to a website and submit a form. However, this form has 3 submit buttons (Preview, Post, and Cancel). I'm used to only one button... This is the form: <TextControl(subject=Is this good for the holidays? Anyone know about the new tech?)> <IgnoreControl(thread...
[ "I had the same problem as you.\nA form with two submit buttons, first was preview, second was submit.\nAt first, mechanize was using only the first button, I could see the server answer using\nresponse = browser.submit()\nprint response.read()\n\nI put the submit button name as a parameter to the mechanize submit ...
[ 4, 0 ]
[]
[]
[ "http", "mechanize", "python", "url", "urllib2" ]
stackoverflow_0001830413_http_mechanize_python_url_urllib2.txt
Q: Python CGI script IOError Broken Pipe I have an old Python based web form that I am updating to use a GPG for encyption instead of a no longer supported python package. When call the script via the command line it works just fine, but via the web brower and CGI there is a error: IOError: [Errno 32] Broken pipe. Th...
Python CGI script IOError Broken Pipe
I have an old Python based web form that I am updating to use a GPG for encyption instead of a no longer supported python package. When call the script via the command line it works just fine, but via the web brower and CGI there is a error: IOError: [Errno 32] Broken pipe. This error occurs if I use the gnupg package ...
[ "I know my answer might come too late, but I recently had the same problem and I think I could solve it.\nGPG seems to output some stuff (\"You need a passphrase\" blabla) to the terminal regardless of stdout being redirected - don't ask me how :)\nHowever, the Broken Pipe seems to occur because gpg can't output th...
[ 2, 0 ]
[]
[]
[ "cgi", "gnupg", "python" ]
stackoverflow_0001798311_cgi_gnupg_python.txt
Q: Opening different windows in wxPython using strings from a list I have a list of file locations stored as strings. I want to be able to open a separate window for all of the different strings. What would be the best way to do that? Essentially, You click a button, the strings are constructed and they are left in a...
Opening different windows in wxPython using strings from a list
I have a list of file locations stored as strings. I want to be able to open a separate window for all of the different strings. What would be the best way to do that? Essentially, You click a button, the strings are constructed and they are left in a list. When I was prototyping, I built a small program to display the...
[ "for s in mystrings:\n open_window_for_string(s)\n\nI'm sure you can supply a definition for open_window_for_string if you know how to open a window with the contents of a file...\nAlso, it doesn't actually have to be a function of one argument, of course, define it to accept whatever additional arguments are ne...
[ 0 ]
[]
[]
[ "iteration", "list", "python", "wxpython" ]
stackoverflow_0002053009_iteration_list_python_wxpython.txt
Q: Regex replace (in Python) - a simpler way? Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like: "(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)" And then concatenate the start group with the new data for replace and then the end group. Is ther...
Regex replace (in Python) - a simpler way?
Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like: "(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)" And then concatenate the start group with the new data for replace and then the end group. Is there a better method for this?
[ ">>> import re\n>>> s = \"start foo end\"\n>>> s = re.sub(\"foo\", \"replaced\", s)\n>>> s\n'start replaced end'\n>>> s = re.sub(\"(?<= )(.+)(?= )\", lambda m: \"can use a callable for the %s text too\" % m.group(1), s)\n>>> s\n'start can use a callable for the replaced text too end'\n>>> help(re.sub)\nHelp on func...
[ 105, 18, 11, 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000490597_python_regex.txt
Q: Bash or Python for extracting blocks from text files I have a huge text file, which is structured as: SEPARATOR STRING1 (arbitrary number of lines) SEPARATOR ... SEPARATOR STRING2 (arbitrary number of lines) SEPARATOR SEPARATOR STRING3 (arbitrary number of lines) SEPARATOR .... What only changes between the diffe...
Bash or Python for extracting blocks from text files
I have a huge text file, which is structured as: SEPARATOR STRING1 (arbitrary number of lines) SEPARATOR ... SEPARATOR STRING2 (arbitrary number of lines) SEPARATOR SEPARATOR STRING3 (arbitrary number of lines) SEPARATOR .... What only changes between the different "blocks" of the file is the STRING and the content be...
[ "In Python 2.6 or better:\ndef doit(inf, ouf, thestring, separator='SEPARATOR\\n'):\n thestring += '\\n'\n for line in inf:\n # here we're always at the start-of-block separator\n assert line == separator\n blockid = next(inf)\n if blockid == thestring:\n # found block of interest, use enumerate ...
[ 3, 0, 0, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002050411_bash_python.txt
Q: How do I determine if an element is in a list? thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}] How do I say: If "red" is in thelist and time does not equal 2 for that element (that's we just got from the list): A: Using any() to find out if there is an element satisfy...
How do I determine if an element is in a list?
thelist = [{'color':'green', 'time':4}, {'color':'red','time':2},{'color':'blue','time':5}] How do I say: If "red" is in thelist and time does not equal 2 for that element (that's we just got from the list):
[ "Using any() to find out if there is an element satisfying the conditions:\n>>> any(item['color'] == 'red' and item['time'] != 2 for item in thelist)\nFalse\n\n", "def colorRedAndTimeNotEqualTo2(thelist):\n for i in thelist:\n if i[\"color\"] == \"red\" and i[\"time\"] != 2:\n return True\n ...
[ 13, 1, 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002053492_list_python.txt
Q: GQL with two tables Hello i am doing a very small application in google appengine and i use python. My problem is that i have two tables using de db.model ("clients" and "requests"). The table "client" has got the email and name fields and the table "requests" has got the email and issue fields. I want to do a que...
GQL with two tables
Hello i am doing a very small application in google appengine and i use python. My problem is that i have two tables using de db.model ("clients" and "requests"). The table "client" has got the email and name fields and the table "requests" has got the email and issue fields. I want to do a query that returns for each ...
[ "The app engine datastore does not support joins, so you will not be able to solve this problem with GQL. You can use two gets, one for client and one for request, or you can use a ReferenceProperty to establish a relationship between the two entities.\nIf you need to model a one-to-many relationship, you can do i...
[ 3, 0 ]
[]
[]
[ "django", "google_app_engine", "gql", "python" ]
stackoverflow_0002002856_django_google_app_engine_gql_python.txt
Q: Can I ask for screenshot of some great personalized IDE for python? How to setup a Linux/Unix machine for python development? Which Linux/Unix version should I use? What IDE should be used? What development plugins should I have? What code style should would be THE BEST? All above, a great development machine for ...
Can I ask for screenshot of some great personalized IDE for python?
How to setup a Linux/Unix machine for python development? Which Linux/Unix version should I use? What IDE should be used? What development plugins should I have? What code style should would be THE BEST? All above, a great development machine for open source (python developers) development? Can i ask for screenshot of ...
[ "Which Linux/Unix version should I use? Doesn't matter. They all work. Pick one that you're going to be successful with.\nWhat IDE should be used? Duplicate: What IDE to use for Python?\nWhat development plugins should I have? No clue from the vague question.\nWhat code style should would be THE BEST? \"BES...
[ 5, 0, 0, 0 ]
[]
[]
[ "development_environment", "open_source", "python" ]
stackoverflow_0002048345_development_environment_open_source_python.txt
Q: Watch over another process (svn) I have a python script to download source code from a list of repositories, some of them are big. Sometimes, svn hangs in the middle of a check out. Is there a way to watch over svn process, and so I know it is hang or not? A: You can use PySVN, and register a callback for each ...
Watch over another process (svn)
I have a python script to download source code from a list of repositories, some of them are big. Sometimes, svn hangs in the middle of a check out. Is there a way to watch over svn process, and so I know it is hang or not?
[ "You can use PySVN, and register a callback for each \"event\" processes. PySVN can also poll a \"cancel\" callback. The first callback could start a timer, and if the timer expires, you can do tell the \"cancel\" callback to return False, thus cancelling the checkout.\n#!/usr/bin/python\n\nurl = \"svn://server/pat...
[ 1, 0 ]
[]
[]
[ "multiprocessing", "python", "svn" ]
stackoverflow_0002053857_multiprocessing_python_svn.txt
Q: How to get a flat XML so that external entities are merged to the top level I know this is a borderline case whether it really belongs to stackoverflow or superuser, but as it seems there are quite a few 'editing code' questions over here, I am posting it on SO. I have a pile of XML files that someone in their inf...
How to get a flat XML so that external entities are merged to the top level
I know this is a borderline case whether it really belongs to stackoverflow or superuser, but as it seems there are quite a few 'editing code' questions over here, I am posting it on SO. I have a pile of XML files that someone in their infinite wisdom have decided to explode to a multiple files using the tags, which i...
[ "If you have libxml2 installed, then xmllint will probably do this for you. Depending on your setup, you might need more params, but for your example, \nxmllint --noent foobar.xml\n\nwill print your file to stdout with all entities resolved. Should be easy enough to wrap some bash scripting around it to do what you...
[ 5, 1, 0 ]
[]
[]
[ "bash", "editor", "python", "sed", "xml" ]
stackoverflow_0002019317_bash_editor_python_sed_xml.txt
Q: fastest way to compare strings in python I'm writing a script in Python that will allow the user to input a string, which will be a command that instructs the script to perform a specific action. For the sake of argument, I'll say my command list is: lock read write request log Now, I want the user to be able to...
fastest way to compare strings in python
I'm writing a script in Python that will allow the user to input a string, which will be a command that instructs the script to perform a specific action. For the sake of argument, I'll say my command list is: lock read write request log Now, I want the user to be able to enter the word "log" and it will peform a spe...
[ "If you are accepting input from a user, then why are you worried about the speed of comparison? Even the slowest technique will be far faster than the user can perceive. Use the simplest most understandable code you can, and leave efficiency concerns for tight inner loops.\ncmds = [\n \"lock\",\n \"read\",...
[ 16, 5, 3, 2, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0002053937_parsing_python_regex.txt
Q: How to average certain sized subsections of a list in python? I would like to take bites out of a list (or array) of a certain size, return the average for that bite, and then move on to the next bite and do that all over again. Is there some way to do this without writing a for loop? In [1]: import numpy as np In...
How to average certain sized subsections of a list in python?
I would like to take bites out of a list (or array) of a certain size, return the average for that bite, and then move on to the next bite and do that all over again. Is there some way to do this without writing a for loop? In [1]: import numpy as np In [2]: x = range(10) In [3]: np.average(x[:4]) Out[3]: 1.5 In [4]: n...
[ "[np.average(x[i:i+4]) for i in xrange(0, len(x), 4) ]\n", "The grouper itertools recipe can help.\n", "Using numpy, you can use np.average with the axis keyword:\nimport numpy as np\nx=np.arange(12)\ny=x.reshape(3,4)\nprint(y)\n# [[ 0 1 2 3]\n# [ 4 5 6 7]\n# [ 8 9 10 11]]\nprint(np.average(y,axis=1))\...
[ 5, 1, 1 ]
[]
[]
[ "average", "list", "python" ]
stackoverflow_0002054013_average_list_python.txt
Q: how to create 2d array in python if we know number of rows,and number of columns depends on some condition? My array maximum dimension could be 2x27,but number of columns could be lower than 27.Number of columns depends on some condition.Is good solution to initialize array 2x27 and then delete unnecessary columns...
how to create 2d array in python if we know number of rows,and number of columns depends on some condition?
My array maximum dimension could be 2x27,but number of columns could be lower than 27.Number of columns depends on some condition.Is good solution to initialize array 2x27 and then delete unnecessary columns or has more elegant way to do this?
[ "No, it makes no particular sense to build a larger array then remove some part of it -- just build what you need. Assuming that by \"2d array\" you actually mean \"list of lists\":\ndef makarray(value, nrows, ncols):\n return [[value]*ncols for _ in range(nrows)]\n\n", "For so few elements use a dictionary, wit...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002053387_python.txt
Q: Python: Why does my function not display what's being returned in the interpreter? In the Python interactive interpreter: I am importing a module that contains a class. These are the methods of that class (some of them): def do_api_call(self, params): return self.__apicall(params) def __apical...
Python: Why does my function not display what's being returned in the interpreter?
In the Python interactive interpreter: I am importing a module that contains a class. These are the methods of that class (some of them): def do_api_call(self, params): return self.__apicall(params) def __apicall(self, params): return urllib2.urlopen(self.endpoint, params).read() When I im...
[ "Your first version only returns the value that you would like to see as the output. The second version actually prints this value.\nIf I were you, I would consider storing the return value of the call to the first version into a variable and printing that variable. That should solve your issue\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0002054228_python.txt
Q: Asynchronous data through Bloomberg's new data API (COM v3) with Python? Does anyone know how to get asynchronous data through Bloomberg's new data API (COM v3) with Python? I found this code below on wilmott.com and it works just fine, but it's for the old API version. Does anyone know the corresponding code for ...
Asynchronous data through Bloomberg's new data API (COM v3) with Python?
Does anyone know how to get asynchronous data through Bloomberg's new data API (COM v3) with Python? I found this code below on wilmott.com and it works just fine, but it's for the old API version. Does anyone know the corresponding code for the new version? from win32com.client import DispatchWithEvents from pythoncom...
[ "I finally figured it out. I did a fair bit of combrowse.py detective work, and I compared with the JAVA, C, C++, and .NET examples in the BBG API download. Interestingly enough the Bloomberg Helpdesk people knew pretty much null when it came to these things, or perhaps I was just talking to the wrong person.\nHere...
[ 19, 0 ]
[]
[]
[ "asynchronous", "bloomberg", "python", "win32com" ]
stackoverflow_0002005234_asynchronous_bloomberg_python_win32com.txt
Q: creating a numpy vector using 3 components I want to create a vector in numpy using 3 components Vx, Vy, Vz as sown below. Can anyone help? Thank you from numpy import cos, sin Vx = cos(alpha)* cos(beta) Vy = sin(alpha)*cos(beta) Vz = sin(beta) A: With NumPy, vectors (and matrices for that matter) are just Pyth...
creating a numpy vector using 3 components
I want to create a vector in numpy using 3 components Vx, Vy, Vz as sown below. Can anyone help? Thank you from numpy import cos, sin Vx = cos(alpha)* cos(beta) Vy = sin(alpha)*cos(beta) Vz = sin(beta)
[ "With NumPy, vectors (and matrices for that matter) are just Python arrays. As in\nfrom numpy import array\nmyVector = array([Vx, Vy, Vz])\nmyMatrix = array([[Vx, Vy, Vz], [1,2,3]])\n\n" ]
[ 6 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002054360_numpy_python.txt
Q: Getting the first elements per row in an array in Python? Let's say i have an array of Tuples, s, in the form of: s = ((1, 23, 34),(2, 34, 44), (3, 444, 234)) and i want to return another Tuple, t, consisting of the first element per row: t = (1, 2, 3) Which would be the most efficient method to do this? I coul...
Getting the first elements per row in an array in Python?
Let's say i have an array of Tuples, s, in the form of: s = ((1, 23, 34),(2, 34, 44), (3, 444, 234)) and i want to return another Tuple, t, consisting of the first element per row: t = (1, 2, 3) Which would be the most efficient method to do this? I could of course just iterate through s, but is there any slicker wa...
[ "No.\nt = tuple(x[0] for x in s)\n\n", "The list comprehension method given by Ignacio is the cleanest.\nJust for kicks, you could also do:\nzip(*s)[0]\n\n*s expands s into a list of arguments. So it is equivalent to \nzip( (1, 23, 34),(2, 34, 44), (3, 444, 234))\n\nAnd zip returns n tuples where each tuple cont...
[ 23, 5, 1 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0002054416_python_tuples.txt
Q: find corresponding key,values and return? I have a dictionary cities = {1:'Kompong Som', 2: 'Kompong Thom', 3: 'Phnom Penh'} tags = {1: 'school', 2: 'public', 3: 'private'} kwargs = {'city': '2', 'tag': '3'}#should be improve I want to get output like this : kwargs = {'city': 'Kompong Thom', 'tag': 'private'}...
find corresponding key,values and return?
I have a dictionary cities = {1:'Kompong Som', 2: 'Kompong Thom', 3: 'Phnom Penh'} tags = {1: 'school', 2: 'public', 3: 'private'} kwargs = {'city': '2', 'tag': '3'}#should be improve I want to get output like this : kwargs = {'city': 'Kompong Thom', 'tag': 'private'} EDIT passed from URL keyword = customer_typ...
[ "def translate(cities, tags, kwargs):\n return {'city': cities[int(kwargs['city'])],\n 'tag': tags[int(kwargs['tag'])]}\n\nThere's no clear way (from your question) to automate the keyname-to-auxiliary dictionary choice, so I've just hardcoded the keys and aux dict to use for each; if that's not what you ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002054490_python.txt
Q: How to disable shell interception of control characters? I'm writing a curses application in Python under UNIX. I want to enable the user to use C-Y to yank from a kill ring a la Emacs. The trouble is, of course, that C-Y is caught by my shell which then sends SIGTSTP to my process. In addition, C-Z also results i...
How to disable shell interception of control characters?
I'm writing a curses application in Python under UNIX. I want to enable the user to use C-Y to yank from a kill ring a la Emacs. The trouble is, of course, that C-Y is caught by my shell which then sends SIGTSTP to my process. In addition, C-Z also results in SIGTSTP being sent, so catching the signal means that C-Y an...
[ "See the termios module, and the termios(3) man page.\n", "For basic functionality, use tty. For example, calling tty.setraw(sys.stdin) will put standard input's terminal into raw mode.\nFor the more general case, Python comes with a termios library, but you probably need some experience with termios to know how ...
[ 2, 1 ]
[]
[]
[ "curses", "python", "signals", "unix" ]
stackoverflow_0002054626_curses_python_signals_unix.txt
Q: evolution plugin for crm integration via webservices I have built a webservice into my companies self developed CRM system that we are in the process of integrating Outlook to the CRM for calendar sync and recording of emails related to clients. I want to build a plugin for the gnome evolution mail client as I use...
evolution plugin for crm integration via webservices
I have built a webservice into my companies self developed CRM system that we are in the process of integrating Outlook to the CRM for calendar sync and recording of emails related to clients. I want to build a plugin for the gnome evolution mail client as I use it for my work mail/calendar as I primarily run Linux. I ...
[ "I would start with the architecture of Evolution. Then I would look into EPlugins and start off with this. An example for writing a plugin would be this. You will need some familiarity with XML. \nHope this helps.\n" ]
[ 1 ]
[]
[]
[ "c", "email", "linux", "python" ]
stackoverflow_0002027300_c_email_linux_python.txt
Q: How to import models in other projects in Django Is it possible to import models from apps in different Django projects? I hope to move some common models in a base projects from which every child projects can share the same data in these common models. Edit I have to place from baseproject.appname.models import b...
How to import models in other projects in Django
Is it possible to import models from apps in different Django projects? I hope to move some common models in a base projects from which every child projects can share the same data in these common models. Edit I have to place from baseproject.appname.models import basemodel before os.environ['DJANGO_SETTINGS_MODULE'] ...
[ "Yes. You can turn a project-specific app into a standard Python package by moving it to site-packages (or wherever your Python install expects its modules) and breaking any links from it to other apps in the project. You can then import it as you would any Python module, in any project.\n" ]
[ 3 ]
[]
[]
[ "django", "model", "python" ]
stackoverflow_0002054898_django_model_python.txt
Q: How to stop "warnings" when using vim omni-completion with python? I am trying vim's python omni-completion script, it works, but I got problem. After I start vim, the 1st time I press to ask vim to complete python code, many warning shown up. That's because some python libs in my project use md5, which will tri...
How to stop "warnings" when using vim omni-completion with python?
I am trying vim's python omni-completion script, it works, but I got problem. After I start vim, the 1st time I press to ask vim to complete python code, many warning shown up. That's because some python libs in my project use md5, which will trigger a warning message in python 2.6 That's very ignoring, how to stop v...
[ "If you have a top level routine which imports the 3rd party library, you can insert this\nimport warnings\nwarnings.simplefilter(\"ignore\",DeprecationWarning)\n\nto ignore all deprecation warnings (which is what the md5 warning is).\nCheck the warnings module for the details on more sophisticated filtering.\n" ]
[ 1 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0002054942_python_vim.txt
Q: How to provide a default value for base class attribute from subclass in Django? Scenario: class BaseClass(models.Model): base_field = models.CharField(max_length=15, default=None) class SubClass(BaseClass): # TODO set default value if base_field's value is None ... ie. I need to be able to load a fi...
How to provide a default value for base class attribute from subclass in Django?
Scenario: class BaseClass(models.Model): base_field = models.CharField(max_length=15, default=None) class SubClass(BaseClass): # TODO set default value if base_field's value is None ... ie. I need to be able to load a fixture into the database, providing a default value only if the base_field is None. Any...
[ "You could override the save method, check if base_field is set, otherwise set it to the default value.\n" ]
[ 3 ]
[]
[]
[ "django", "django_inheritance", "django_models", "python" ]
stackoverflow_0002054831_django_django_inheritance_django_models_python.txt
Q: How do I send email with django-registration? How do I send email with django-registration? A: django-registration sends an email to the user, e.g. when he or she registers. The process is as follows (if this was your question ...)*: The user has filled out and submitted the registration form ... in views.py:18...
How do I send email with django-registration?
How do I send email with django-registration?
[ "django-registration sends an email to the user, e.g. when he or she registers. The process is as follows (if this was your question ...)*:\n\nThe user has filled out and submitted the registration form ...\nin views.py:187\nnew_user = backend.register(request, **form.cleaned_data)\n\nin e.g. backends/default/__ini...
[ 7 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002054785_django_python.txt
Q: is there a way to view the source of a module from within the python console? if I'm in the python console and I want to see how a particular module works, is there an easy way to dump the source? A: Some of the methods of inspect module are well-suited for this purpose: import module import inspect src = inspec...
is there a way to view the source of a module from within the python console?
if I'm in the python console and I want to see how a particular module works, is there an easy way to dump the source?
[ "Some of the methods of inspect module are well-suited for this purpose:\nimport module\nimport inspect\nsrc = inspect.getsource(module)\n\n", "Using IPython, you can do this:\nIn [1]: import pyparsing\nIn [2]: pyparsing.Word??\n\n...and the source will be displayed, if possible. I guess this must use inspect und...
[ 41, 8, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002055110_python.txt
Q: is there a way to have a python application run invisibly? I have a cherrypy application that I want to control over http with a simple gui. The problem is I don't want both the cherrypy window and the gui running at the same time. Is there a way I can make the cherrypy applications window visible? Its being writ...
is there a way to have a python application run invisibly?
I have a cherrypy application that I want to control over http with a simple gui. The problem is I don't want both the cherrypy window and the gui running at the same time. Is there a way I can make the cherrypy applications window visible? Its being written for windows, which probably makes a difference
[ "Use pythonw.exe rather than python.exe It will start without a console window.\nIf you're using py2exe, you need to change your setup file to not use a console\nfrom distutils.core import setup\nimport py2exe\nsetup(windows=[{\"script\":\"hello.py\"}])\n\n" ]
[ 2 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0002055458_cherrypy_python.txt
Q: Django: Unexpectedly persistent module variables I noticed a strange behaviour today: It seems that, in the following example, the config.CLIENT variable stays persistent accross requests – even if the view gets passed an entirely different client_key, the query that gets the client is only executed once (per many...
Django: Unexpectedly persistent module variables
I noticed a strange behaviour today: It seems that, in the following example, the config.CLIENT variable stays persistent accross requests – even if the view gets passed an entirely different client_key, the query that gets the client is only executed once (per many requests), and then the config.CLIENT variable stays ...
[ "Multiple requests are processed by the same process and global variables like your CLIENT live as long, as process does. You shouldn't rely on global variables, when processing requests - use either local ones, when you need to keep a variable for the time of building response or put data into the database, when s...
[ 6, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002050320_django_python.txt
Q: is there any difference between 'a.b.a' and 'b.b.a' class a(object): class b: a='aaa' print a.b.a#print 'aaa' b=a() print b.b.a#print 'aaa' A: No. To create instance variables, you need to explicitly prefix them with self., in the constructor method __init__(self). In your code, you're simply assi...
is there any difference between 'a.b.a' and 'b.b.a'
class a(object): class b: a='aaa' print a.b.a#print 'aaa' b=a() print b.b.a#print 'aaa'
[ "No.\nTo create instance variables, you need to explicitly prefix them with self., in the constructor method __init__(self).\nIn your code, you're simply assigning in the class scope, and those variables can be reached both ways.\n", "Running your code and then a.b.a is b.b.a gives the result of True, which indi...
[ 5, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002055604_python.txt
Q: python memory del list[:] vs list = [] In python I have noticed that if you do mylist = [] for i in range(0,100000000): mylist.append('something here to take memory') mylist = [] it would seem the second call mylist = [] would remove the reference and it would get collected but, as I watch them memory it ...
python memory del list[:] vs list = []
In python I have noticed that if you do mylist = [] for i in range(0,100000000): mylist.append('something here to take memory') mylist = [] it would seem the second call mylist = [] would remove the reference and it would get collected but, as I watch them memory it does not. when I use del mylist[:] it almos...
[ "How do you measure that?\nI've made a small test that does not confirm your results.\nHere is the source:\nimport meminfo, gc, commands\n\npage_size = int(commands.getoutput(\"getconf PAGESIZE\"))\n\ndef stat(message):\n s = meminfo.proc_stat()\n print \"My memory usage %s: RSS: %dkb, VSIZE: %dkb\" % (\n ...
[ 9 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0002055107_memory_python.txt