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: Make Django Create Foreign Keys for MySQL Backend How do you force Django to create real foreign key constraints when using a MySQL backend? If I'm reading this old bug report correctly, Django should be creating real foreign keys, but my default Django 1.2.3 setup using MySQL only generates indexes for models.For...
Make Django Create Foreign Keys for MySQL Backend
How do you force Django to create real foreign key constraints when using a MySQL backend? If I'm reading this old bug report correctly, Django should be creating real foreign keys, but my default Django 1.2.3 setup using MySQL only generates indexes for models.ForeignKey().
[ "Change your database engine to InnoDB. MyISAM doesn't support foreign keys.\n", "I'm running on Django 1.2.1 with MySQL_python-1.2.3c and can verify that it is indeed creating proper foreign key entries on MySQL.\nI suggest that you check if you are using MySQL_python-1.2.3c or better\n" ]
[ 3, 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0004454278_django_mysql_python.txt
Q: python sort on timedelta I have a bunch of records for which I calculate timedelta (latest - time of creation). I need to sort them so that the latest comes first. I do it like this - results = list() for i in range(100): res.append((name, content, delta, age)) res = sorted(res, key=lambda i:i[2], reverse=Tru...
python sort on timedelta
I have a bunch of records for which I calculate timedelta (latest - time of creation). I need to sort them so that the latest comes first. I do it like this - results = list() for i in range(100): res.append((name, content, delta, age)) res = sorted(res, key=lambda i:i[2], reverse=True) This would work perfect, b...
[ "You want None to compare less than ALL possible timedelta values, even negative ones. So what you do is augment your key with a leading flag:\nkey=lambda i: (i[2] is not None, i[2])\n\nThus None is compared as (False, None) and some_timedelta is compared as (True, some_timedelta) and there's no chance of the non-c...
[ 4, 3, 1, 0 ]
[]
[]
[ "datetime", "python", "sorting" ]
stackoverflow_0004463666_datetime_python_sorting.txt
Q: Don't understand python pop altering multiple variables I'm sure this is something simple that I've overlooked, but I'm hoping someone can explain the following to me: origList = [1, 2, 3, 4, 5, 6, 7, 8] def test(inputList): while range(len(inputList)): inputList.pop() altList = origList test(altList) ...
Don't understand python pop altering multiple variables
I'm sure this is something simple that I've overlooked, but I'm hoping someone can explain the following to me: origList = [1, 2, 3, 4, 5, 6, 7, 8] def test(inputList): while range(len(inputList)): inputList.pop() altList = origList test(altList) print 'origList:', origList # prints origList: [] print 'altL...
[ "Everything in Python is a reference. They're the same list.\naltList = origList[:]\n\n", "It's because the line:\naltList = origList\n\ndoes not create a copy of the origList object. Both names, will refer to the same underlying object. To create a copy, see the copy module.\n", "this is because when you say\n...
[ 7, 3, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004465496_list_python.txt
Q: Declaring a variable as float I get java.lang.IllegalArgumentException: Can not set java.lang.Float field I'm using jython for writing test cases and I need to declare a variable as float. I am declaring this way: width = float(10.0) Height = float(40.0) I'm getting this error: java.lang.IllegalArgumentExceptio...
Declaring a variable as float I get java.lang.IllegalArgumentException: Can not set java.lang.Float field
I'm using jython for writing test cases and I need to declare a variable as float. I am declaring this way: width = float(10.0) Height = float(40.0) I'm getting this error: java.lang.IllegalArgumentException: Can not set java.lang.Float field com.ganz.tt.user.service.client.featurecodemanager.CreateVillagerSvc$Request...
[ "My guess would be to use java double type instead of float. Python uses usually doubles to represent floats.\n" ]
[ 0 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0004465649_jython_python.txt
Q: Does Django have a template tag that can detect URLs and turn them into hyperlinks? When someone writes a post and copies and pastes a url in it, can Django detect it and render it as a hyperlink rather than plain text? A: Django has the urlize template filter which will automatically detect both URLs and email ...
Does Django have a template tag that can detect URLs and turn them into hyperlinks?
When someone writes a post and copies and pastes a url in it, can Django detect it and render it as a hyperlink rather than plain text?
[ "Django has the urlize template filter which will automatically detect both URLs and email addresses and turn them into the appropriate hyperlinks.\nThe docs there are actually a little thin, so I recommend also reading the docstring in the source for the urlize function for more information.\n", "urlize:\nhttp:/...
[ 20, 3, 0 ]
[]
[]
[ "django", "http", "python", "templates", "url" ]
stackoverflow_0004465636_django_http_python_templates_url.txt
Q: Python: Convert '3.5' to integer So far, I would do int(float('3.5')) Any other good way to do? Note: 3.5 is a string. I want to use the the built-in API that specify for this sort of problem. A: You're on the right track, and the best solution is probably as mentioned: >>> int(float("3.5")) This truncates the ...
Python: Convert '3.5' to integer
So far, I would do int(float('3.5')) Any other good way to do? Note: 3.5 is a string. I want to use the the built-in API that specify for this sort of problem.
[ "You're on the right track, and the best solution is probably as mentioned:\n>>> int(float(\"3.5\"))\n\nThis truncates the float.\nIf you want a different type of rounding, you can use the math package:\n>>> import math\n>>> x = \"3.5\"\n>>> math.floor(float(x)) # returns FP; still needs to be wrapped in int()\n3.0...
[ 5, 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004465693_python.txt
Q: How do I check the difference in time of 2 datetime objects? Let's say x and y are datetime objects in Python. How do I check: if y - x is more than 30 seconds: print "ok, 30 seconds have passed" A: The following class can be used for duration expressing the difference between two date, time, or datetime ins...
How do I check the difference in time of 2 datetime objects?
Let's say x and y are datetime objects in Python. How do I check: if y - x is more than 30 seconds: print "ok, 30 seconds have passed"
[ "The following class can be used for duration expressing the difference between two date, time, or datetime instances to microsecond resolution: \nclass datetime.timedelta\nThe following code can be used for your purposes:\nif (y-x) >datetime.timedelta(0,30):\n\n", "For Python 2.7 you can do:\nif (y - x).total_se...
[ 5, 3, 0, 0 ]
[]
[]
[ "datetime", "python", "time", "timestamp" ]
stackoverflow_0004465966_datetime_python_time_timestamp.txt
Q: Using Microsoft SQL through python on a webserver I'm trying to run some queries to a database from a pylons (paster-based) webserver and every time I try to import the pymssql Library I'm using (its this one by the way) I keep getting this error: tds_init_winsock: WSAEnumProtocols failed with 10055(WSAENOBUFS: No...
Using Microsoft SQL through python on a webserver
I'm trying to run some queries to a database from a pylons (paster-based) webserver and every time I try to import the pymssql Library I'm using (its this one by the way) I keep getting this error: tds_init_winsock: WSAEnumProtocols failed with 10055(WSAENOBUFS: No buffer space available.) on the import. I also tried ...
[ "Error code WSAENOBUFS, while translated into \"No buffer space available\", actually means (quoting the MSDN page I just pointed to):\n\nAn operation on a socket could not be\n performed because the system lacked\n sufficient buffer space or because a\n queue was full.\n\nand in practice (as explained e.g. here...
[ 2, 1, 0 ]
[]
[]
[ "paster", "pylons", "pymssql", "python", "sql_server" ]
stackoverflow_0003528243_paster_pylons_pymssql_python_sql_server.txt
Q: How to display a XML file in a folder like system I have searched quite a bit for some help on this but most information about XML and Python is about how to read and parse files, not how to write them. I currently have a script that outputs the file system of a folder as an XML file but I want this file to includ...
How to display a XML file in a folder like system
I have searched quite a bit for some help on this but most information about XML and Python is about how to read and parse files, not how to write them. I currently have a script that outputs the file system of a folder as an XML file but I want this file to include HTML tags that can be read on the web. Also, I am loo...
[ "Generally it's not a good idea to code HTML directly in Python by building strings as you do it. You won't understand what kind of HTML you produce if look at your code in a month or so. I recommend using a templating engine.\nAlternatively, as you are converting from XML to XML, XSLT (an XML transformation langua...
[ 2 ]
[]
[]
[ "html", "python", "xml" ]
stackoverflow_0004465975_html_python_xml.txt
Q: Django testing tips In the spirit of this question, I would like to know if anyone has any tips on creating a useful and "complete" test suite (can a test suite ever be "complete"?) for a Django webapp. My situation: I've knocked out a prototype and am now working on adding some regression testing. I personally us...
Django testing tips
In the spirit of this question, I would like to know if anyone has any tips on creating a useful and "complete" test suite (can a test suite ever be "complete"?) for a Django webapp. My situation: I've knocked out a prototype and am now working on adding some regression testing. I personally use django-webtest for most...
[ "I would recommend reading Django 1.1 Testing and Debugging by Karen M. Tracey. The first five chapters cover testing in Django. Specifically, you should look at Chapter 5 which discusses integrating other test tools. Below is an excerpt of what Chapter 5 covers:\n\nIn this chapter, we:\n\nLearned what hooks Django...
[ 14, 3 ]
[]
[]
[ "django", "django_testing", "python", "testing", "unit_testing" ]
stackoverflow_0004445713_django_django_testing_python_testing_unit_testing.txt
Q: python argparse with dependencies I'm writing a script which has 2 arguments which are mutually exclusive, and an option that only makes sense with one of those arguments. I'm trying to set up argparse to fail if you call it with the argument that makes no sense. To be clear: -m -f makes sense -s makes sense -s -f...
python argparse with dependencies
I'm writing a script which has 2 arguments which are mutually exclusive, and an option that only makes sense with one of those arguments. I'm trying to set up argparse to fail if you call it with the argument that makes no sense. To be clear: -m -f makes sense -s makes sense -s -f should throw errors no arguments are f...
[ "You just have the argument groups mixed up. In your code, you only assign one option to the mutually exclusive group. I think what you want is:\nparser = argparse.ArgumentParser(description='Lookup servers by ip address from host file')\nparser.add_argument('host', nargs=1,\n help=\"ip address to lookup...
[ 8, 2 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0004466197_argparse_python.txt
Q: Make Python access to MS Access faster on Windows I am on a windows server 2003 and accessing a locally stored MS Access 2000 MDB from python 2.5.4 scripts using pyodbc 2.1.5. The db access is very slow this way (I am on fast machine and all other db operations are normal) and I wonder if there is a better way to ...
Make Python access to MS Access faster on Windows
I am on a windows server 2003 and accessing a locally stored MS Access 2000 MDB from python 2.5.4 scripts using pyodbc 2.1.5. The db access is very slow this way (I am on fast machine and all other db operations are normal) and I wonder if there is a better way to access the MDB from python? Maybe a better odbc driver?...
[ "Try setting up your connection once on program startup and then reusing the connection everywhere. Rather than closing it after every Execute or Commit.\n", "Tony's suggestion makes the most sense to me. However, if it's not enough, you could also try a later version of the driver, such as this one that works ...
[ 3, 0 ]
[]
[]
[ "ms_access", "odbc", "pyodbc", "python", "windows" ]
stackoverflow_0004466273_ms_access_odbc_pyodbc_python_windows.txt
Q: I've been using dictionary keys as membership markers. Is this a good idea? For instance, I have a document that has a pile of control codes that I need to manually specify replacements for. I basically write a script that prints out the list of codes. Easy. Now I've been using a dictionary's key to store the mem...
I've been using dictionary keys as membership markers. Is this a good idea?
For instance, I have a document that has a pile of control codes that I need to manually specify replacements for. I basically write a script that prints out the list of codes. Easy. Now I've been using a dictionary's key to store the membership. If the code exists, then I set the dictionary value to something, and th...
[ "You should use a set instead.\n>>> members = set()\n>>> members.add(1)\n>>> 1 in members\nTrue\n>>> 2 in members\nFalse\n\nIf your codes are stored in an iterable then finding the unique codes might be as as simple as:\n>>> set(codes)\n\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0004466473_python.txt
Q: python unix service library I have a command-line python app that is a service - i.e. it waits for connections and does stuff when asked, like webserver. There's python-daemon library for dealing with all the issues of detaching from the terminal, forking, etc. but I'd like to go a bit further - to have the progra...
python unix service library
I have a command-line python app that is a service - i.e. it waits for connections and does stuff when asked, like webserver. There's python-daemon library for dealing with all the issues of detaching from the terminal, forking, etc. but I'd like to go a bit further - to have the program do the following: Know if it's...
[ "I've used this recipe. Works pretty good.\nhttp://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/\n" ]
[ 1 ]
[]
[]
[ "python", "python_module", "service", "unix" ]
stackoverflow_0004466727_python_python_module_service_unix.txt
Q: urllib2 exception handling with couchdb I usually have a hard time nailing down how to handle urllib2 exceptions. So I'm still learning. Here is a scenario that I'd like some advice on. I have a local couch db database. I want to know if the database exists. ie "127.0.0.1:5984/database". If it does not exist, and ...
urllib2 exception handling with couchdb
I usually have a hard time nailing down how to handle urllib2 exceptions. So I'm still learning. Here is a scenario that I'd like some advice on. I have a local couch db database. I want to know if the database exists. ie "127.0.0.1:5984/database". If it does not exist, and I can reach "127.0.0.1:5984", I want to know ...
[ "I would argue that you're attacking this problem at too low a level. Why not use couchdb-python?\nTo answer your questions, 1) no it is not an especially clean way to do this. I would at least factor the code in your except block out into a method that extracts error types suitable for your application out of the ...
[ 1 ]
[]
[]
[ "couchdb", "exception", "python", "urllib2" ]
stackoverflow_0004465231_couchdb_exception_python_urllib2.txt
Q: Why is there a key error in this line of my Django forms code? class RegisterForm(forms.Form): username = forms.CharField(max_length=16, label="Username", required=False) password = forms.CharField(max_length=100,widget=forms.PasswordInput, required=False) password2 = forms.CharField(max_length=100,wid...
Why is there a key error in this line of my Django forms code?
class RegisterForm(forms.Form): username = forms.CharField(max_length=16, label="Username", required=False) password = forms.CharField(max_length=100,widget=forms.PasswordInput, required=False) password2 = forms.CharField(max_length=100,widget=forms.PasswordInput, label="Password Again", required=False) ...
[ "Well the short literal answer is that self.cleaned_data is a dict that has no entry with 'password' as a key. Going to the next stage:\nHave you tried inspecting self.cleaned_data? Is it missing only a password entry or is it empty? Did you type in a password on the form? What do you expect to be in self.cleaned_d...
[ 2, 2 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0004466726_django_django_forms_python.txt
Q: In Django, how do i change "This field is required." to "Name is required"? I'm using the forms framework. And when I set required=True, this error shows. What if I don't want it to say "This field", but instead, say the label? Since i'm not going to be displaying it beneath the form input. I"m going to display a...
In Django, how do i change "This field is required." to "Name is required"?
I'm using the forms framework. And when I set required=True, this error shows. What if I don't want it to say "This field", but instead, say the label? Since i'm not going to be displaying it beneath the form input. I"m going to display all the errors at the top of the page.
[ "An easy way to specify simple \"required\" validation messages is to pass the field the error_messages argument.\nname = forms.CharField(error_messages={'required': 'Your Name is Required'}) \n\nCheck the docs for which keys can be specified per field:\nhttp://docs.djangoproject.com/en/dev/ref/forms/fields/#django...
[ 23, 0 ]
[]
[]
[ "django", "forms", "frameworks", "python" ]
stackoverflow_0004466499_django_forms_frameworks_python.txt
Q: certain output of x numbers i would like to make a program that takes an integer and gives a string of the amount of numbers of that integer. For example, if the integer is 7, it gives 7777777, or if its 3, it give 333. Thank you A: Try this function: def mkstr(n): return n * str(n) print mkstr(3) print mk...
certain output of x numbers
i would like to make a program that takes an integer and gives a string of the amount of numbers of that integer. For example, if the integer is 7, it gives 7777777, or if its 3, it give 333. Thank you
[ "Try this function:\ndef mkstr(n):\n return n * str(n)\n\nprint mkstr(3)\nprint mkstr(7)\n\nIt outputs:\n333\n7777777\n\nas expected. This is the simplest Pythonic way to do it but, if this does turn out to be a homework question, you'll probably be expected to do this as a loop, something like the pseudo-code:\...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004467047_python.txt
Q: Why does "c.execute(...)" break the loop? I am trying to change some data in an sqlite3 file and I my non-existing knowledge in python and google-fu made me end up with this code: #!/usr/bin/python # Filename : hello.py from sqlite3 import * conn = connect('database') c = conn.cursor() c.execute('select * from...
Why does "c.execute(...)" break the loop?
I am trying to change some data in an sqlite3 file and I my non-existing knowledge in python and google-fu made me end up with this code: #!/usr/bin/python # Filename : hello.py from sqlite3 import * conn = connect('database') c = conn.cursor() c.execute('select * from table limit 2') for row in c: newname = r...
[ "It's doing that because as soon as you do c.execute(newdata) the cursor is no longer pointing at the original result set anymore. I would do it this way:\n#!/usr/bin/python\n# Filename : hello.py\n\nfrom sqlite3 import *\n\nconn = connect('database')\n\nc = conn.cursor()\n\nc.execute('select * from table limit 2')...
[ 7, 3, 0, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0004467230_python_sqlite.txt
Q: Fill in program The randint(a,b) function from Python's random module returns a "random" integer in the range from a to b, including both end point. Fill in the blanks in the function below that creates and returns a random string of 0's and 1s of length n. from random import randint: def randString01(n): _...
Fill in program
The randint(a,b) function from Python's random module returns a "random" integer in the range from a to b, including both end point. Fill in the blanks in the function below that creates and returns a random string of 0's and 1s of length n. from random import randint: def randString01(n): _________________ ...
[ "Since this is homework, I won't give you the answer, but here are some leading questions:\n\nHow would you use randint(a,b) to give you either 0 or 1?\nHow do you convert an integer to a string?\nHow can you build up a string with a for loop?\n\nIf you can answer those, you've solved the problem.\n", "Inside the...
[ 5, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004467182_python.txt
Q: Help me fix a program Hello I have gotten a program that gives an output of a random series of 0s and 1s of length n. However, there is a slight problem in my program because I get syntax error. I am using Sage. What should I fix? from random import randint def randString01(num): x = str() count = num...
Help me fix a program
Hello I have gotten a program that gives an output of a random series of 0s and 1s of length n. However, there is a slight problem in my program because I get syntax error. I am using Sage. What should I fix? from random import randint def randString01(num): x = str() count = num while count >0: ...
[ "as others noted, you shouldn't use 'append'\nfrom random import randint\ndef randString01(num):\n x = str() \n count = num \n while count >0: \n if randint(0,1) == 0: \n x += \"0\" \n else: \n x += \"1\" \n count -= 1\n x=str(x) \n return x\n\nSecond, thi...
[ 5, 1, 0 ]
[]
[]
[ "python", "sage" ]
stackoverflow_0004467374_python_sage.txt
Q: Create a graph using Mathematica and Python I was wondering how I would go about using Python to create a Graph with Mathematica. I want to be able to use python code to invoke mathematica to create a new graph, using data from a CSV file. A: You probably need to look at PYML, which provides a Python API for Ma...
Create a graph using Mathematica and Python
I was wondering how I would go about using Python to create a Graph with Mathematica. I want to be able to use python code to invoke mathematica to create a new graph, using data from a CSV file.
[ "You probably need to look at PYML, which provides a Python API for Mathematica.\nDepending on your needs, you might also want to look at matplotlib which would allow you to do the graphing in Python.\n", "You could make a Mathematica shell script and call it from Python using os.system()\n", "The old fashioned...
[ 2, 2, 2 ]
[]
[]
[ "csv", "python", "wolfram_mathematica" ]
stackoverflow_0004466217_csv_python_wolfram_mathematica.txt
Q: Generating 3D noise quickly in python I need a method to generate 3D simplex noise in python rather quickly. What methods are there out there to solve this problem? A: $ pip install noise http://pypi.python.org/pypi/noise/ This package is designed to give you simple to use, fast functions for generating Perl...
Generating 3D noise quickly in python
I need a method to generate 3D simplex noise in python rather quickly. What methods are there out there to solve this problem?
[ "$ pip install noise\n\n\nhttp://pypi.python.org/pypi/noise/\n\n\nThis package is designed to give you simple to use, fast functions for\n generating Perlin noise in your Python programs. Perlin noise is famously\n called the \"salt\" of procedural generation, as it adds considerable flavor in\n its application....
[ 13, 0, 0 ]
[]
[]
[ "noise", "python" ]
stackoverflow_0004467638_noise_python.txt
Q: Do I need to bundle the Python interpreter (in py2exe) when I am distributing my app? I have a small Python app ready that I'd like to distribute around to my friends in the company. I have used wxWidgets for the GUI, with SQLite for the database. I'm planning on using py2exe for packaging the entire thing. I'd l...
Do I need to bundle the Python interpreter (in py2exe) when I am distributing my app?
I have a small Python app ready that I'd like to distribute around to my friends in the company. I have used wxWidgets for the GUI, with SQLite for the database. I'm planning on using py2exe for packaging the entire thing. I'd like to know if bundling the Python interpreter is required ? Does py2exe does it by default...
[ "Last time I did it (which admittedly was some time ago), py2exe bundled everything into the executable.\nThis fairly concise document talks about external dependencies, such MSVC runtime DLLs.\nI also suggest taking a look at the following past questions:\n\npy2exe + sqlalchemy + sqlite problem\nWhen using py2exe,...
[ 2, 0 ]
[]
[]
[ "executable", "installation", "py2exe", "python", "wxwidgets" ]
stackoverflow_0004463097_executable_installation_py2exe_python_wxwidgets.txt
Q: Python - Search for files & ZIP, across multiple directories This is my first time hacking together bits and pieces of code to form a utility that I need (I'm a designer by trade) and, though I feel I'm close, I'm having trouble getting the following to work. I routinely need to zip up files with a .COD extension ...
Python - Search for files & ZIP, across multiple directories
This is my first time hacking together bits and pieces of code to form a utility that I need (I'm a designer by trade) and, though I feel I'm close, I'm having trouble getting the following to work. I routinely need to zip up files with a .COD extension that are inside of a directory structure I've created. As an examp...
[ "For problem #1, I think your problem is probably this section:\ncod = zipfile.ZipFile(\"COD.zip\",\"a\")\ncod.write(currentFile)\n\nYou're creating a new zip (and possibly overwriting the existing one) every time you go to write a new file. Instead you want to create the zip once per directory and then repeatedly...
[ 1, 1 ]
[]
[]
[ "python", "recursion", "search", "zip" ]
stackoverflow_0004272439_python_recursion_search_zip.txt
Q: django datetime.datetime error While following the tutorial here, I get down to where you run poll.was_published_today and I get this error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/myDir/mySite/polls/models.py", line 11, in was_published_today return (self.pub_date()...
django datetime.datetime error
While following the tutorial here, I get down to where you run poll.was_published_today and I get this error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/myDir/mySite/polls/models.py", line 11, in was_published_today return (self.pub_date() == datetime.date.today()) TypeError...
[ "Typo. Should be\ndef was_published_today(self):\n return (self.pub_date.date() == datetime.date.today())\n\n", "I fixed it. For some reason it's treating import datetime like from datetime import * (Anyone know why?) So removing datetime from \nreturn (self.pub_date.date() == datetime.date.today())\ncorrect...
[ 5, 2 ]
[]
[]
[ "datetime", "django", "python" ]
stackoverflow_0004466164_datetime_django_python.txt
Q: Problems with python-oauth2 and Yahoo's Fantasy Sports API I'm trying to build a web app that grabs fantasy sports info from Yahoo's API. I know that it requires the use of OAuth in order to speak to the API. It's being created using Flask and will run on Google App Engine. I've been trying to use python-oauth2 ...
Problems with python-oauth2 and Yahoo's Fantasy Sports API
I'm trying to build a web app that grabs fantasy sports info from Yahoo's API. I know that it requires the use of OAuth in order to speak to the API. It's being created using Flask and will run on Google App Engine. I've been trying to use python-oauth2 from the folks at SimpleGeo and I keep getting the same exact er...
[ "As kanaka pointed out, yahoo's get_access_token call requires the oauth_callback, and simplegeo/oauth2 does not allow you to specify it easily. \nHere are a couple of workarounds:\nInstead of simplegeo/python-oauth2, take zbowling/python-oauth2 (which is a fork of simplegeo, but with some nice new code, and bugfix...
[ 6, 2 ]
[]
[]
[ "flask", "oauth", "python" ]
stackoverflow_0004026759_flask_oauth_python.txt
Q: Python BeautifulSoup equivalent to lxml make_links_absolute So lxml has a very hand feature: make_links_absolute: doc = lxml.html.fromstring(some_html_page) doc.make_links_absolute(url_for_some_html_page) and all the links in doc are absolute now. Is there an easy equivalent in BeautifulSoup or do I simply need t...
Python BeautifulSoup equivalent to lxml make_links_absolute
So lxml has a very hand feature: make_links_absolute: doc = lxml.html.fromstring(some_html_page) doc.make_links_absolute(url_for_some_html_page) and all the links in doc are absolute now. Is there an easy equivalent in BeautifulSoup or do I simply need to pass it through urlparse and normalize it: soup = BeautifulSoup...
[ "In my answer to What is a simple way to extract the list of URLs on a webpage using python? I covered that incidentally as part of the extraction step; you could easily write a method to do it on the soup and not just extract it.\nfrom urllib.parse import urljoin\n\ndef make_links_absolute(soup, url):\n for tag...
[ 15 ]
[]
[]
[ "beautifulsoup", "lxml", "python" ]
stackoverflow_0004468410_beautifulsoup_lxml_python.txt
Q: How to use lxml to grab specific parts of an XML document? I am using Amazon's API to receive information about books. I am trying to use lxml to extract specific parts of the XMl document that are needed for my application. I am not really sure how to use lxml, though. This is as far as I have gotten: root = etre...
How to use lxml to grab specific parts of an XML document?
I am using Amazon's API to receive information about books. I am trying to use lxml to extract specific parts of the XMl document that are needed for my application. I am not really sure how to use lxml, though. This is as far as I have gotten: root = etree.XML(response) To create a etree object for the XML document. ...
[ "This is tested to work with both lxml.etree and xml.etree.cElementTree running Python 2.7.1.\nimport lxml.etree as ET\n# Also works with cElementTree (included in recent standard CPythons).\n# Use this import:\n# import xml.etree.cElementTree as ET\nt = ET.fromstring(xmlstring) # your data -- with 2 missing tags a...
[ 2, 1, 1, 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0004456421_lxml_python.txt
Q: Help me write a function Hello can anyone help me write a function that calculates 1+x+x^2+...+x^n for a given x and a positive integer n and use it to calculate (1+x+x^2+...+x^10)(1+x^2+x^4+...+x^10) for x=100? A: def myfunc(x, n, step): if n > 0: return x**n + myfunc(x, n - step, step) return 1 myfunc...
Help me write a function
Hello can anyone help me write a function that calculates 1+x+x^2+...+x^n for a given x and a positive integer n and use it to calculate (1+x+x^2+...+x^10)(1+x^2+x^4+...+x^10) for x=100?
[ "def myfunc(x, n, step):\n if n > 0:\n return x**n + myfunc(x, n - step, step)\n return 1\n\nmyfunc(100, 10, 1) * myfunc(100, 10, 2)\n\n", "You can use this to calculate 1+x+x^2+...+x^n:\nlambda x, n: sum([x**y for y in range(0, n + 1)])\n\nUse the logic to calculate the second function.\n", "Since you put...
[ 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "sage" ]
stackoverflow_0004467470_python_sage.txt
Q: different wallpaper for each screen for multi-monitor setups in Windows I'm using: ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "picturefile", 0) To change the wallpaper. But I'm wondering if there's any simple way to put different wallpapers on ea...
different wallpaper for each screen for multi-monitor setups in Windows
I'm using: ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "picturefile", 0) To change the wallpaper. But I'm wondering if there's any simple way to put different wallpapers on each screen. This feature isn't standard in windows though, but there are exter...
[ "\nAfter joining the images together into a big image, you have to set the wallpaper mode to tiled to make it so the image spans the desktop (otherwise it will restart on each monitor).\nCouple of ways to do this:\na) Using IActiveDesktop (which does not require Active Desktop to be used, don't worry). This is nice...
[ 7 ]
[]
[]
[ "desktop_wallpaper", "python", "winapi", "windows" ]
stackoverflow_0004467331_desktop_wallpaper_python_winapi_windows.txt
Q: How to programmatically create a new Page in MoinMoin? I want to write a python script that calls some external REST service and then creates MoinMoin pages based on the data that I pull back. I am using Python 2.4.3 on CentOS 5.3 and MoinMoin 1.9.3 in a wiki farm configuration. Note I don't want to embed data in ...
How to programmatically create a new Page in MoinMoin?
I want to write a python script that calls some external REST service and then creates MoinMoin pages based on the data that I pull back. I am using Python 2.4.3 on CentOS 5.3 and MoinMoin 1.9.3 in a wiki farm configuration. Note I don't want to embed data in pages using Macros, as I already know how to do that. I want...
[ "Here is a documentation of the MoinMoin API: http://moinmo.in/MoinAPI/Beispiele\nIt is in german (the main MoinMoin developers are german).\nI think what you want is the PageEditor: http://moinmo.in/MoinAPI/Beispiele#PageEditor\n" ]
[ 1 ]
[]
[]
[ "moinmoin", "python" ]
stackoverflow_0004468588_moinmoin_python.txt
Q: Fast, searchable dict storage for Python Current I use SQLite (w/ SQLAlchemy) to store about 5000 dict objects. Each dict object corresponds to an entry in PyPI with keys - (name, version, summary .. sometimes 'description' can be as big as the project documentation). Writing these entries (from JSON) back to the ...
Fast, searchable dict storage for Python
Current I use SQLite (w/ SQLAlchemy) to store about 5000 dict objects. Each dict object corresponds to an entry in PyPI with keys - (name, version, summary .. sometimes 'description' can be as big as the project documentation). Writing these entries (from JSON) back to the disk (SQLite format) takes several seconds, an...
[ "Did you put indices on name and description? Searching on 5000 indexed entries should be essentially instantaneous (of course ORMs will make your life much harder, as they usually do [even relatively good ones such as SQLAlchemy, but try \"raw sqlite\" and it absolutely should fly).\nWriting just the updated entr...
[ 2, 1, 0, 0 ]
[]
[]
[ "data_storage", "python", "sqlite" ]
stackoverflow_0001156993_data_storage_python_sqlite.txt
Q: Best way to request-scope data in Django? I'm wondering if there's a clever pattern for request-scoping arbitrary information without resorting to either TLS or putting the information in the session. Really, this would be for contextual attributes that I'd like to not look up more than once in a request path, but...
Best way to request-scope data in Django?
I'm wondering if there's a clever pattern for request-scoping arbitrary information without resorting to either TLS or putting the information in the session. Really, this would be for contextual attributes that I'd like to not look up more than once in a request path, but which are tied to a request invocation and the...
[ "Context processors. They are called once for every request and receive the actual request object - so you can add ANY data to the context, also based on the curent request!\n", "Just assign the dictionary directly to the request. You can do that in middleware or in your view, as you like. \n" ]
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004466923_django_python.txt
Q: Preserving the state of show/hide sections in Django with jQuery/Javascript I have a form with some show/hide sections. When I press some buttons in my home form, different forms will be shown. After I edit the information in those forms I'm returning to the first form. But the state of the show/hide sections is r...
Preserving the state of show/hide sections in Django with jQuery/Javascript
I have a form with some show/hide sections. When I press some buttons in my home form, different forms will be shown. After I edit the information in those forms I'm returning to the first form. But the state of the show/hide sections is reseted. The show/hide action is done with jquery toggle. The state of these secti...
[ "You don't really need session storage. In the case you've described, you want the sections' show/hide status to be kept between pages, for a single client. Session would be overkill, as it involves the server for something trivial.\nMy go would be to use something like localStorage (or cookies if you really want) ...
[ 1 ]
[]
[]
[ "django", "django_middleware", "jquery", "python", "session" ]
stackoverflow_0004468963_django_django_middleware_jquery_python_session.txt
Q: import module == from module import *? I had a problem with the Django tutorial so I asked a question here. No-one knew the answer, but I eventually figured it out with help from Robert. Python seems to be treating import datetime the same as from datetime import *. Working code: import datetime from django.db i...
import module == from module import *?
I had a problem with the Django tutorial so I asked a question here. No-one knew the answer, but I eventually figured it out with help from Robert. Python seems to be treating import datetime the same as from datetime import *. Working code: import datetime from django.db import models class Poll(models.Model): ...
[ "The problem in the latter snippet is with this part of your code:\nreturn (self.pub_date() == datetime.date.today())\n\nself.pub_date contains a datetime.datetime instance. It's not callable like that. For example:\n>>> import datetime\n>>> d = datetime.datetime.now()\n>>> d()\nTraceback (most recent call last):\n...
[ 4, 2, 2 ]
[]
[]
[ "django", "django_models", "import", "module", "python" ]
stackoverflow_0004468256_django_django_models_import_module_python.txt
Q: right way to use if else in django template? {% if {{result}} == 'Invalid' %} <span class="error-message-uname">Invalid .</span> {% endif %} A: That depends on what version of Django you're using. Since Django 1.2, this is valid: {% if result == 'Invalid' %} <span class="error-message-uname">Invalid .</span...
right way to use if else in django template?
{% if {{result}} == 'Invalid' %} <span class="error-message-uname">Invalid .</span> {% endif %}
[ "That depends on what version of Django you're using. Since Django 1.2, this is valid:\n{% if result == 'Invalid' %}\n <span class=\"error-message-uname\">Invalid .</span>\n{% endif %}\n\nFor earlier versions, use ifequal:\n{% ifequal result 'Invalid' %}\n <span class=\"error-message-uname\">Invalid .</span>\...
[ 11, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004468969_django_python.txt
Q: wxPython: wx.Panel of AuiManager has empty space of gray I am trying to make a window with 2 panels. One panel is just a notebook panel. The second panel contains a toolbar on top and a text control on the bottom. I want to arrange this panel in my frame using wx.aui.AuiManager. The problem is that I get a big em...
wxPython: wx.Panel of AuiManager has empty space of gray
I am trying to make a window with 2 panels. One panel is just a notebook panel. The second panel contains a toolbar on top and a text control on the bottom. I want to arrange this panel in my frame using wx.aui.AuiManager. The problem is that I get a big empty space of grey in my custom panel. Here is my code: import...
[ "Take out the line:\nself._mgr.GetPane(\"notebook-content\").Show().Top().Layer(0).Row(0).Position(0)\n\nAs for the OnExit() handler, it is firing!\nIf you want to exit the application, replace it with app.Exit()\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0004463187_python_wxpython.txt
Q: What are common homonyms and synonyms between different webplatforms/webproducts? I am ASP.NET developer. Yesterday I started to write website content on and support customers of plugin(s) (for example, captchas, etc.) supporting different web CMSes (Content Management Systems) on different platforms mainly PHP...
What are common homonyms and synonyms between different webplatforms/webproducts?
I am ASP.NET developer. Yesterday I started to write website content on and support customers of plugin(s) (for example, captchas, etc.) supporting different web CMSes (Content Management Systems) on different platforms mainly PHP-based ones (like WordPress, Joomla, Drupal, etc.) though they can be for any (non-PHP...
[ "Plone calls plugins \"Products\", and calls MVC controllers \"views\". That's common confusions.\n", "In order to support different CMSes, your existing knowledge of ASP.NET should cover you on most of the stuff you need to know. As for terminology, it varies from CMS to CMS. It would be helpful to read some tut...
[ 1, 0 ]
[]
[]
[ "asp.net", "c#", "html", "php", "python" ]
stackoverflow_0004467923_asp.net_c#_html_php_python.txt
Q: “Incorrect Signature” Python Twitter I have the following code: import urlparse import oauth2 as oauth PROXY_DOMAIN = "twitter1-ewizardii.apigee.com" consumer_key = '...' consumer_secret = '...' consumer = oauth.Consumer(consumer_key, consumer_secret) oauth_token = '...' oauth_token_secret = '...' token ...
“Incorrect Signature” Python Twitter
I have the following code: import urlparse import oauth2 as oauth PROXY_DOMAIN = "twitter1-ewizardii.apigee.com" consumer_key = '...' consumer_secret = '...' consumer = oauth.Consumer(consumer_key, consumer_secret) oauth_token = '...' oauth_token_secret = '...' token = oauth.Token(oauth_token, oauth_token_sec...
[ "Although I have switched to tweepy for anyone who finds this question this may be of use to you:\nhttp://dev.twitter.com/pages/libraries\nIt could have been a glitch on the day I was testing as I didn't go back to trying out the oauth-python module since tweepy has been working for me. But that link list all the p...
[ 0 ]
[]
[]
[ "oauth", "python", "signature", "twitter" ]
stackoverflow_0004437357_oauth_python_signature_twitter.txt
Q: How can I make cx-oracle bind the results of a query to a dictionary rather than a tuple? Here is my code. I would like to find a way to have results from a query returned as a list of dictionaries rather than list of tuples. It seems like cx_oracle supports this with parts of the documentation talking about 'bind...
How can I make cx-oracle bind the results of a query to a dictionary rather than a tuple?
Here is my code. I would like to find a way to have results from a query returned as a list of dictionaries rather than list of tuples. It seems like cx_oracle supports this with parts of the documentation talking about 'binding'. Though I can't figure out how it works. def connect(): dsn = cx_Oracle.makedsn("hos...
[ "Bindvars are used to execute query such as \n\nBy name(given named parameters)\ncursor = self.db.cursor()\ncursor.execute(\"SELECT bookName, author from books where Id=:bookId\" , bookId=\"155881\")\nprint cursor.bindnames()\n\n\nwill print : ['BOOKID']\n\nby position given a list of values\ncursor = self.db.curso...
[ 16, 0 ]
[]
[]
[ "cx_oracle", "database", "oracle", "python", "sql" ]
stackoverflow_0004468071_cx_oracle_database_oracle_python_sql.txt
Q: Determining how difficult a word is to type on a QWERTY keyboard I'm looking for a reasonably simple algorithm to determine how difficult it is to type a word on the QWERTY layout. The words would not necessarily be dictionary words, so a list of commonly mistyped words or the like is not an option. I'm sure there...
Determining how difficult a word is to type on a QWERTY keyboard
I'm looking for a reasonably simple algorithm to determine how difficult it is to type a word on the QWERTY layout. The words would not necessarily be dictionary words, so a list of commonly mistyped words or the like is not an option. I'm sure there must be an existing, well-tested algorithm, but I can't find anything...
[ "There is this comparison between QWERTY, Colemak and Dvorak layouts, which calculates the distance between the keys typed, the percentage of keys on the same hand, etc. with source code in Java. These metrics in combination should give a very good estimate of the 'typeability' of a word.\n", "I don't have any al...
[ 5, 2, 1, 0 ]
[]
[]
[ "algorithm", "python", "qwerty" ]
stackoverflow_0004459352_algorithm_python_qwerty.txt
Q: Is there something like LINQ to XML in python for appengine? Is there something that I can use to query XML in python like I can do in LINQ2XML? And if it would run on appengine too. Pseudocode: xml = fetch("http://foo/bar.xml") for person : xml.elements("person"): print(person.attribute("name")) for numb...
Is there something like LINQ to XML in python for appengine?
Is there something that I can use to query XML in python like I can do in LINQ2XML? And if it would run on appengine too. Pseudocode: xml = fetch("http://foo/bar.xml") for person : xml.elements("person"): print(person.attribute("name")) for number : person.elements("number") print(" %s %d",(number.attribu...
[ "Yes. Example XML file:\n<?xml version=\"1.1\" encoding=\"iso-8859-1\"?>\n<container>\n <person name=\"Jim\">\n <number type=\"home\" value=\"000-000-0000\"/>\n <number type=\"work\" value=\"111-111-1111\"/>\n </person>\n <person name=\"Fred\">\n <number type=\"home\" value=\"222-222-2222\"/>\n <numb...
[ 4, 2 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0004469441_python_xml.txt
Q: How do I remove lines from a big file in Python, within limited environment Say I have a 10GB HDD Ubuntu VPS in the USA (and I live in some where else), and I have a 9GB text file on the hard drive. I have 512MB of RAM, and about the same amount of swap. Given the fact that I cannot add more HDD space and cannot m...
How do I remove lines from a big file in Python, within limited environment
Say I have a 10GB HDD Ubuntu VPS in the USA (and I live in some where else), and I have a 9GB text file on the hard drive. I have 512MB of RAM, and about the same amount of swap. Given the fact that I cannot add more HDD space and cannot move the file to somewhere else to process, is there an efficient method to remove...
[ "How about this? It edits the file in place. I've tested it on some small text files (in Python 2.6.1), but I'm not sure how well it will perform on massive files because of all the jumping around, but still...\nI've used a indefinite while loop with a manual EOF check, because for line in f: didn't work correctly ...
[ 3, 2, 1, 0, 0 ]
[]
[]
[ "file", "lines", "python" ]
stackoverflow_0004469614_file_lines_python.txt
Q: Which is better? Using inbuilt python functions or os.system commands? Which is better to use in a python automation script for following simple operations To create a zip file and copy it or rename it to a new location. Using python inbuilt functions or terminal commands through os.system modules is better? A: ...
Which is better? Using inbuilt python functions or os.system commands?
Which is better to use in a python automation script for following simple operations To create a zip file and copy it or rename it to a new location. Using python inbuilt functions or terminal commands through os.system modules is better?
[ "The inbuilt Python modules/ stdlib wherever you can, subprocess (os.system) where you must.\nReasons: Portability, maintenance, code readability just to name a few. \n", "I'd use the Python library if possible. The biggest drawbacks of the built-in functions appear to me that they often don't support all the fea...
[ 11, 4, 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004470302_python.txt
Q: Can I use lambda to create a query in SQLAlchemy? I need to implement a function that takes a lambda as the argument and queries the database. I use SQLAlchemy for ORM. Is there a way to pass the lambda, that my function receives, to SQLAlchemy to create a query? Sincerely, Roman Prykhodchenko A: I guess you wan...
Can I use lambda to create a query in SQLAlchemy?
I need to implement a function that takes a lambda as the argument and queries the database. I use SQLAlchemy for ORM. Is there a way to pass the lambda, that my function receives, to SQLAlchemy to create a query? Sincerely, Roman Prykhodchenko
[ "I guess you want to filter the data with the lambda, like a WHERE clause? Well, no, functions nor lambdas cannot be turned into a SQL query. Sure, you could just fetch all the data and filter it in Python, but that completely defeats the purpose of the database.\nYou'll need to recreate the logic you put into the ...
[ 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0004470481_python_sqlalchemy.txt
Q: Python and native GUI I checked some other question and websites, and I've come to the conclusion that Python does allow (correct me if I'm wrong) you to make GUI programs using different cross-platform toolkits like Qt, wxWidgets and some others. But what if I don't want cross-platform portability. Primary, I wan...
Python and native GUI
I checked some other question and websites, and I've come to the conclusion that Python does allow (correct me if I'm wrong) you to make GUI programs using different cross-platform toolkits like Qt, wxWidgets and some others. But what if I don't want cross-platform portability. Primary, I want to develop native applica...
[ "Don't waste your time. Use wxPython, which will use the native toolkit for you.\n", "On Windows, the PyWin32 project has bindings to the Win32 API (and to MFC, if you already know that.)\nOn OS X, you can use PyObjC to write Cocoa programs -- see their examples\nEdit: Note that in general, I agree with @Ignacio'...
[ 8, 3, 0 ]
[]
[]
[ "macos", "python", "qt", "windows", "wxwidgets" ]
stackoverflow_0004471056_macos_python_qt_windows_wxwidgets.txt
Q: Python library for getting information about SVN repository? I'm searching for a library that can extract (at least) the following information from a SVN repository (not a working copy!): Revision numbers and their author & commit message Changes in each revision (added, deleted, modified files) Is there a Pytho...
Python library for getting information about SVN repository?
I'm searching for a library that can extract (at least) the following information from a SVN repository (not a working copy!): Revision numbers and their author & commit message Changes in each revision (added, deleted, modified files) Is there a Python library that can do this? For the authors and commit messages, I...
[ "There are Python bindings to libsvn: http://pysvn.tigris.org/docs/pysvn.html. They facilitate doing pretty much everything the svn command line client can do.\nIn particular, the Client.log() method does what you are looking for.\n", "I think you want something like py-svn.\n" ]
[ 2, 0 ]
[]
[]
[ "python", "svn", "svn_repository" ]
stackoverflow_0004471195_python_svn_svn_repository.txt
Q: Fastest and pythonic way of deletion of objects in this code This is a sample code of what I want to do... class A(): number = 0 List = [] for i in range(5): state = A() state.number = i List.append(state) print List Numbers = [1,2,3] Now I want to delete class objects in List whose number is in Numbe...
Fastest and pythonic way of deletion of objects in this code
This is a sample code of what I want to do... class A(): number = 0 List = [] for i in range(5): state = A() state.number = i List.append(state) print List Numbers = [1,2,3] Now I want to delete class objects in List whose number is in Numbers. What is the fastest way to do it ? Also if someone can suggest...
[ "First of, instead of having a class variable like A.number as in:\nclass A():\n number = 0\n\nyou should generally write a __init__ method that sets the number only on the instance.\nclass A(object):\n def __init__(self, number):\n self.number = number\n\nNow the rest of your code can be written simpl...
[ 8, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004471235_python.txt
Q: Print using for loop - Python I am fairly very new to Python or any programming language for that matter. I am finding it challenging to print arbitrary text along with with iterated values from a list, using for loop. What I need is to print the whole first item of the list with arbitrary text "shutdown" and repe...
Print using for loop - Python
I am fairly very new to Python or any programming language for that matter. I am finding it challenging to print arbitrary text along with with iterated values from a list, using for loop. What I need is to print the whole first item of the list with arbitrary text "shutdown" and repeat the same for new text "no shutdo...
[ "Currently you do this:\nprint \" shut\"\nprint \" no shut\"\n\nThe result of that is:\nshut\nno shut\n\nAs expected. If you want it to print \"shut\" when it shuts down and \"no shut\" when it doesn't, you need a test:\nif shutdown(interface):\n print \"shut\"\nelse:\n print \"no shut\"\n\nOr something simil...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004471174_python.txt
Q: Unable to find modules from pydbgr in emacs I am trying to get a decent python environment using emacs. As part of this process i want to integrate pydbgr with emacs. I have almost done it but with an issue. When i try to start a debugging session pydbgr does not found my modules when i try to import them. If i ch...
Unable to find modules from pydbgr in emacs
I am trying to get a decent python environment using emacs. As part of this process i want to integrate pydbgr with emacs. I have almost done it but with an issue. When i try to start a debugging session pydbgr does not found my modules when i try to import them. If i change PYTHONPATH and then execute pydbgr from comm...
[ "Use Emacs Lisp function setenv as in:\n(setenv \"PYTHONPATH\" \"c:/....\")\n" ]
[ 0 ]
[]
[]
[ "debugging", "emacs", "python" ]
stackoverflow_0004471587_debugging_emacs_python.txt
Q: Determine current Mac Chrome web page using Python (py-appscript) So Chromium has officially added support for Applescript: http://code.google.com/p/chromium/issues/detail?id=27468 I assume that this also means Chromium can be accessed by py-appscript. The question is: how? What syntax in py-appscript can I use to...
Determine current Mac Chrome web page using Python (py-appscript)
So Chromium has officially added support for Applescript: http://code.google.com/p/chromium/issues/detail?id=27468 I assume that this also means Chromium can be accessed by py-appscript. The question is: how? What syntax in py-appscript can I use to get the URL of the front-most tab in Chromium?
[ "Found it. It is:\nappscript.app(\"Google Chrome\").windows.active_tab.URL()\n\nThe way I found it was by calling .help() successively.\nSo, first, I called the appscript.app(\"Google Chrome\").help(), which listed out all of the app's accessible properties and alerted me that I needed to access it's windows proper...
[ 1 ]
[]
[]
[ "chromium", "google_chrome", "python", "sourceforge_appscript" ]
stackoverflow_0004471656_chromium_google_chrome_python_sourceforge_appscript.txt
Q: Python - multiple inserts of large text In Python, what's the fastest way (i.e. a single-pass method) to go about inserting two large sets of text, A and B, into another large set of text, C. Where C is for example: .... .... <<<A goes here>>> .... .... <<<B goes here>>> .... .... and "...." represents quite a lo...
Python - multiple inserts of large text
In Python, what's the fastest way (i.e. a single-pass method) to go about inserting two large sets of text, A and B, into another large set of text, C. Where C is for example: .... .... <<<A goes here>>> .... .... <<<B goes here>>> .... .... and "...." represents quite a lot of text (i.e. up to 20k). What's the best w...
[ "The documentation for str.find says it returns the index of the first occurrence of the searched-for string, which (to me) implies that it doesn't go through the whole string. If you know that \"<<<A goes here>>>\" always occurs first, I'd do:\nAflag = \"<<<A goes here>>>\"\nBflag = \"<<<B goes here>>>\"\nAidx =...
[ 3, 2, 1, 1 ]
[]
[]
[ "python", "string", "templates" ]
stackoverflow_0004471331_python_string_templates.txt
Q: Output all members from a class defines as list Hi I've got a class that essentially is a list object holding a bunch of objects. I try to define a method to return all members, but it fails. My code is: class Stadion: def __init__(self,): self.__Tribuner=[] def setTribuner(self,tribuner): ...
Output all members from a class defines as list
Hi I've got a class that essentially is a list object holding a bunch of objects. I try to define a method to return all members, but it fails. My code is: class Stadion: def __init__(self,): self.__Tribuner=[] def setTribuner(self,tribuner): self.__Tribuner.append(tribuner) def getTribune...
[ "Maybe you want\ndef getTribuner(self):\n return self.__Tribuner\n\nor\ndef getTribuner(self):\n for tr in self.__Tribuner:\n yield tr\n\nI would recommend to expose the standard Python sequence interface instead of your custom method names. In your case it would be easiset to just derive Stadion from...
[ 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "class", "methods", "python" ]
stackoverflow_0004471356_class_methods_python.txt
Q: Getting current logged_in user in Django I'm developping a blog with Django, and I'd like my posts to be related to their author. I've created an author field in my Blog model class, which is a ForeignKey pointing on a User object. Problem is, South database migration django tool asks me for a default value to giv...
Getting current logged_in user in Django
I'm developping a blog with Django, and I'd like my posts to be related to their author. I've created an author field in my Blog model class, which is a ForeignKey pointing on a User object. Problem is, South database migration django tool asks me for a default value to give to it. Actually, I'd like it to be the id of...
[ "If you want the field to be required you will have to set a default value when migrating. For the reason you don't have stored any data anywhere about who created the post, you ca only set it to a specific user, which in this case probably should be your administrator user!\nYou could then edit the posts in the ad...
[ 3, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004470105_django_python.txt
Q: Help with computer math project I need help making a program that would calculate 1+x+x^2+...+x^n for a given x and a positive integer n and use it to calculate (1+x+x^2+...+x^10)(1+x^2+x^2...+x^10) for x=100 so far i have def myfunc(x, n, step): if n > 0: return x**n + myfunc(x, n - step, step) return...
Help with computer math project
I need help making a program that would calculate 1+x+x^2+...+x^n for a given x and a positive integer n and use it to calculate (1+x+x^2+...+x^10)(1+x^2+x^2...+x^10) for x=100 so far i have def myfunc(x, n, step): if n > 0: return x**n + myfunc(x, n - step, step) return 1 #In case n is 0 I would then use ...
[ "Hint, since the \"functional-programming\" tag is present, I assume it is an exercise in recursion:\n1 + x + x**2 + ... + x**n = 1 + x * (1 + x + ... + x**(n-1))\n\nYou only need n multiplications and no exponentiation to evaluate this polynomial. This is called the Horner scheme. Note that this formula can also b...
[ 6, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004472367_python.txt
Q: How do I swap the left hand and right hand sides of a C/C++ assignment statement in gvim? To be honest, I actually have a solution for this, but Google search finds so many great tips for me from this site, that I had to contribute something back. Here is what I came up with. For a single line: s/^\(\s\+\)\(.*\)...
How do I swap the left hand and right hand sides of a C/C++ assignment statement in gvim?
To be honest, I actually have a solution for this, but Google search finds so many great tips for me from this site, that I had to contribute something back. Here is what I came up with. For a single line: s/^\(\s\+\)\(.*\) = \(.*\);/\1\3 = \2;/ For multiple lines starting at the current line, add .,.+<line count>. ...
[ "Use 'very magic': add \\v to the expression. See :help magic. Basically, it mean that all non-alphanumeric characters have special (i.e. regular expression operator meanings) unless escaped, which means that they do not need to be escaped in your usage above.\n", "Using \\v at the start of your regex can help ma...
[ 2, 1 ]
[]
[]
[ "c++", "java", "python", "variable_assignment", "vim" ]
stackoverflow_0004472257_c++_java_python_variable_assignment_vim.txt
Q: Python regex to pull FQDN from syslog server I'm trying to build a regex to parse our syslogs. I was asked to account for each server that uses the service. I wrote a simple regex to pull out the FQDN, but it seems to be consuming too much of the line... >>> string = "2010-12-13T00:00:02-05:00 <local3.info> suba...
Python regex to pull FQDN from syslog server
I'm trying to build a regex to parse our syslogs. I was asked to account for each server that uses the service. I wrote a simple regex to pull out the FQDN, but it seems to be consuming too much of the line... >>> string = "2010-12-13T00:00:02-05:00 <local3.info> suba1.suba2.example.com named[29959]: client 192.168.1...
[ "Replacing \\s with \\b and the .*? with \\S will do it.\n>>> regex = re.compile(r'\\b\\S*\\.example\\.com')\n>>> regex.findall(string)\n[u'suba1.suba2.example.com', u'subb1.subb2.example.com']\n\n", "The regex\nr\"query: ([\\w\\.]+)\"\n\nwould grab the end from [...] query on and then you can use a unnamed group...
[ 0, 0, 0, 0 ]
[]
[]
[ "fqdn", "python", "regex", "syslog" ]
stackoverflow_0004472458_fqdn_python_regex_syslog.txt
Q: Django - Coleman I am a noob in Django and I started a project that is to have a shopping cart/ e-commerce solution. I have been reading into Django 1.2 e-commerce book by Jesse Legg and I am looking for someone who has gone through it to some extent. I apologise that I might not be specific enough in my question....
Django - Coleman
I am a noob in Django and I started a project that is to have a shopping cart/ e-commerce solution. I have been reading into Django 1.2 e-commerce book by Jesse Legg and I am looking for someone who has gone through it to some extent. I apologise that I might not be specific enough in my question. After setting up the ...
[ "Since Item is nested in Cart, you need to provide the proper scope. Change add_item to:\ndef add_item(self, product, quantity=1):\n item = Cart.Item(self.next_item_id, product, quantity)\n self.items.push(item)\n\nAlternatively, self.Item(...) will also work.\n", "I don't know the book. But until s...
[ 1, 0 ]
[]
[]
[ "django", "e_commerce", "python" ]
stackoverflow_0004470617_django_e_commerce_python.txt
Q: Regex match either some pattern or predefined string I have two strings: a = 'B E R L I N IS A CITY' b = 'PARIS IS A CITY, TOO' I want to match the first word in case it is with a single space, or a predefined word. The regular expression I came up with (Python) is regex = re.compile('^(?P<city>([a-z] )*|(paris ...
Regex match either some pattern or predefined string
I have two strings: a = 'B E R L I N IS A CITY' b = 'PARIS IS A CITY, TOO' I want to match the first word in case it is with a single space, or a predefined word. The regular expression I came up with (Python) is regex = re.compile('^(?P<city>([a-z] )*|(paris )).*$', re.IGNORECASE) print regex.match(a).group('city'),...
[ "The “problem” is that ^([a-z] )* matches the begin of the string PARIS … when the [a-z]  is repeated zero times. So there is no need for the regex interpreter to test for the literal paris .\nUse + instead of + and it works as expected:\n^(?P<city>([a-z] )+|(paris )).*$\n\n", "Use of span() often throws light on...
[ 5, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004473078_python_regex.txt
Q: Problems with nested loops… I’m going to explain to you in details of what I want to achieve. I have 2 programs about dictionaries. The code for program 1 is here: import re words = {'i':'jeg','am':'er','happy':'glad'} text = "I am happy.".split() translation = [] for word in text: word_mod = re.sub('[^a-z0-...
Problems with nested loops…
I’m going to explain to you in details of what I want to achieve. I have 2 programs about dictionaries. The code for program 1 is here: import re words = {'i':'jeg','am':'er','happy':'glad'} text = "I am happy.".split() translation = [] for word in text: word_mod = re.sub('[^a-z0-9]', '', word.lower()) punctu...
[ "My solution flow would be something like this:\ndict = ...\nmax_group = len(max(dict))\ninput = ...\ntextWPunc = input.lower().split()\ntextOnly = [re.sub('[^a-z0-9]', '', x) for x in input.lower().split()]\ntranslation = []\n\nwhile textOnly:\n for m in [max_group..0]:\n if textOnly[:m] in words:\n ...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0002356408_python.txt
Q: Global name in self/class? I am having issues calling variables in my class. I have everything set up as self's and what have but i am still getting errors. I think i am having a hard time figuring this out cause i am new to 3.0 scripting. Here is my script: http://pastebin.com/9Lrw399E here is the error: command ...
Global name in self/class?
I am having issues calling variables in my class. I have everything set up as self's and what have but i am still getting errors. I think i am having a hard time figuring this out cause i am new to 3.0 scripting. Here is my script: http://pastebin.com/9Lrw399E here is the error: command = 'tcpdump -c5 -tttt -w {0} host...
[ "command = 'tcpdump -c5 -tttt -w {0} host {1}'.format(raw, input_host)\n\nShould be:\ncommand = 'tcpdump -c5 -tttt -w {0} host {1}'.format(self.raw, self.input_host)\n\nNotice the self.\n", "try\ncommand = 'tcpdump -c5 -tttt -w {0} host {1}'.format(self.raw, self.input_host)\n\nUnless you're passing raw and input...
[ 5, 1 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0004473531_python_subprocess.txt
Q: Python - comparing long/integer values with == and is Possible Duplicate: Python “is” operator behaves unexpectedly with integers Ran into something odd last night where doing if max_urls is 0: max_urls = 10 would always return false... even when max_urls was 0.... it was getting assigned from the database....
Python - comparing long/integer values with == and is
Possible Duplicate: Python “is” operator behaves unexpectedly with integers Ran into something odd last night where doing if max_urls is 0: max_urls = 10 would always return false... even when max_urls was 0.... it was getting assigned from the database. When I did a print type(max_urls) would return <type 'lo...
[ "== is a value comparison, is is an object identity (memory location) comparison. You will often see that comparisons like max_urls is 0 will give the intended result because small values are usually cached in Python, but you always want to be using == instead of is when checking equality because this behavior can...
[ 24, 6 ]
[]
[]
[ "conditional_operator", "python", "variables" ]
stackoverflow_0004473673_conditional_operator_python_variables.txt
Q: C# equivalent to Python's traceback library In this post, python has traceback library to get some detailed error information (line number, file name ...). Does C# have similar functions to know what file/line number that generates the exception? ADDED I came up with the following code based on the answers. using ...
C# equivalent to Python's traceback library
In this post, python has traceback library to get some detailed error information (line number, file name ...). Does C# have similar functions to know what file/line number that generates the exception? ADDED I came up with the following code based on the answers. using System; // https://stackoverflow.com/questions/4...
[ "When you catch an exception you can view its stack trace, which should give similar results:\ncatch(Exception e)\n{\n Console.WriteLine(e.StackTrace);\n}\n\nIf debug data can be loaded (if the .pdb file is in the same directory as the executable/you build in debug mode) this will include file names line numbers...
[ 4, 1, 1 ]
[]
[]
[ "c#", "error_handling", "exception_handling", "python" ]
stackoverflow_0004474326_c#_error_handling_exception_handling_python.txt
Q: Is it possible to connect different Product-objects to one Contract? My problem: I want my Customers to be able to connect many different Products to one Contract, and the code to list all Products attached to a Contract feels dirty. My Models class Contract(models.Model): # The contract, a customer can have...
Is it possible to connect different Product-objects to one Contract?
My problem: I want my Customers to be able to connect many different Products to one Contract, and the code to list all Products attached to a Contract feels dirty. My Models class Contract(models.Model): # The contract, a customer can have many contracts customer = models.ForeignKey(Customer) class Product...
[ "This other stack question looks directly related -- maybe it will help?\n>>> Product.objects.all()\n[<SimpleProduct: ...>, <OtherProduct: ...>, <BlueProduct: ...>, ...]\n\nSubclassed django models with integrated querysets\nSpecifically, the snippet has subclassed models Meal Salad(Meal)\nhttp://djangosnippets.org...
[ 1, 0 ]
[]
[]
[ "application_design", "django", "django_models", "python" ]
stackoverflow_0004463595_application_design_django_django_models_python.txt
Q: How can I get unicode characters from a URL parameter? I need to use a GET request to send JSON to my server via a JavaScript client, so I started echoing responses back to make sure nothing is lost in translation. There doesn't seem to be a problem with normal text, but as soon as I include a Unicode character of...
How can I get unicode characters from a URL parameter?
I need to use a GET request to send JSON to my server via a JavaScript client, so I started echoing responses back to make sure nothing is lost in translation. There doesn't seem to be a problem with normal text, but as soon as I include a Unicode character of any sort (e.g. "ç") the character is encoded somehow (e.g. ...
[ "Everything looks fine to me.\n>>> hex(ord(u'°'))\n'0xb0'\n>>> hex(ord(u'ç'))\n'0xe7'\n\nPerhaps you should decode the JSON before attempting to use it.\n", "Your procedure's fine, you just need 1 more step; that is, encoding from unicode to utf-8 (or any other encoding that supports the 'weird characters'.)\nThi...
[ 3, 3 ]
[]
[]
[ "character_encoding", "encoding", "python", "special_characters", "unicode" ]
stackoverflow_0004474430_character_encoding_encoding_python_special_characters_unicode.txt
Q: implement an object that holds x seats in y rows What is the best way to implement an object that holds x rows with y seats? Would it be to use a dictionary object, such as object={'row1:"2", "row2:"2","row3":"4"} And then reference each row if I where to update number of seats? Or are there any better way of imp...
implement an object that holds x seats in y rows
What is the best way to implement an object that holds x rows with y seats? Would it be to use a dictionary object, such as object={'row1:"2", "row2:"2","row3":"4"} And then reference each row if I where to update number of seats? Or are there any better way of implementing this? /Andy.l
[ "If all you're doing is tracking rows and seats, you could do it with a simple array:\nrows = [2,2,4]\n\nRow 1 is rows[0] with 2 seats, Row 3 is rows[2] with 4 seats, and so on.\n", "Depending on the operations you need to perform on a row, you may find it better to create a Row class and put instances of that in...
[ 6, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0004474690_dictionary_python.txt
Q: how to get checkbox value in django? <tr name="item"> <td><input type="checkbox" ></td> <td>>{{ foo }}</td> <td> {{ bar }} </td> </tr> Now I want that in django views request.POST.getlist('item') returns the value of ie foo and bar. But it is returning null. A: Checkboxes work a little...
how to get checkbox value in django?
<tr name="item"> <td><input type="checkbox" ></td> <td>>{{ foo }}</td> <td> {{ bar }} </td> </tr> Now I want that in django views request.POST.getlist('item') returns the value of ie foo and bar. But it is returning null.
[ "Checkboxes work a little bit different from other form inputs, so if you examine a post sent from a form that includes a checkbox, there are two possibilities...\n<input type=\"checkbox\" name=\"cb1\" />\n\nif the checkbox is checked, your queryset will look like:\nqueryset = {'cb1': 'on'}\n\nİf it is not checked:...
[ 6, 3, 2 ]
[ "As others stated, this is simle html - You have to put your foo and bar values on the \"value\" attribute of the input tag, regardless of what is shown on the page. And that is all you need to do.\n<tr name=\"item\">\n <td><input type=\"checkbox\" name=\"item\" value=\"{{foo}},{{bar}}\"></td>\n <td>>...
[ -1 ]
[ "django", "django_templates", "html", "python" ]
stackoverflow_0004470833_django_django_templates_html_python.txt
Q: Django error trying to delete a file using virtualenv File "/srv/xxxx/venv/lib/python2.6/site-packages/django/core/files/storage.py", line 193, in delete os.remove(name) OSError: [Errno 13] Permission denied: '/srv/notxxxelinq/app/xxx/site_media/xx/xxx/20101217T194905.document.pdf' I've tried chmod ...
Django error trying to delete a file using virtualenv
File "/srv/xxxx/venv/lib/python2.6/site-packages/django/core/files/storage.py", line 193, in delete os.remove(name) OSError: [Errno 13] Permission denied: '/srv/notxxxelinq/app/xxx/site_media/xx/xxx/20101217T194905.document.pdf' I've tried chmod +x on django-admin.py but that didn't do the trick. Any id...
[ "It sounds like the permissions on your site_media directory might be wrong - what are the permissions on that directory?\n" ]
[ 1 ]
[]
[]
[ "django", "python", "virtualenv" ]
stackoverflow_0004474953_django_python_virtualenv.txt
Q: unsupported operand type(s) exception with ThreapPool.map but not map? Why does the built in map work but not multiprocessing's ThreadPool map work? from multiprocessing.pool import ThreadPool def identity(a, b): return (a, b) map(identity, [1, 2, 3], [4, 5, 6]) p = ThreadPool(2) #gives above error: p.map(iden...
unsupported operand type(s) exception with ThreapPool.map but not map?
Why does the built in map work but not multiprocessing's ThreadPool map work? from multiprocessing.pool import ThreadPool def identity(a, b): return (a, b) map(identity, [1, 2, 3], [4, 5, 6]) p = ThreadPool(2) #gives above error: p.map(identity, [1, 2, 3], [4, 5, 6]) edit: After some digging, apparently the thread...
[ "from multiprocessing.pool import ThreadPool\n\ndef identity((a,b)): return a, b\n\nprint map(identity, zip([1, 2, 3], [4, 5, 6]))\n\np = ThreadPool(2)\n\n#gives above error:\nprint p.map(identity, zip([1, 2, 3], [4, 5, 6]))\n\nOutput\n[(1, 4), (2, 5), (3, 6)]\n[(1, 4), (2, 5), (3, 6)]\n\n" ]
[ 1 ]
[]
[]
[ "multithreading", "python", "threadpool" ]
stackoverflow_0004474940_multithreading_python_threadpool.txt
Q: PyDev and Django inside virtual environment I've set my virtual environment through console and than with pip installed Django into it. I'd really like now to open and run this folder/project/virtualenv inside of PyDev, but I don't know how. In PyDev I can only start new Django project, which hasn't isolated envir...
PyDev and Django inside virtual environment
I've set my virtual environment through console and than with pip installed Django into it. I'd really like now to open and run this folder/project/virtualenv inside of PyDev, but I don't know how. In PyDev I can only start new Django project, which hasn't isolated environment... You know what I mean? Thanks everyone!
[ "You need to set the Python interpreter used by the project to the interpreter in the virtualenv. The Pydev manual has more information on how to configure the interpreter.\n", "If this works anything like iPython, you will need to install PyDev inside of your virtual environment. IE:\npip install ipython\n\n" ]
[ 5, 0 ]
[]
[]
[ "django", "eclipse", "pydev", "python", "virtualenv" ]
stackoverflow_0004475012_django_eclipse_pydev_python_virtualenv.txt
Q: Pygtk notes links if any of you are familiar with PyGTK links for beginners to grasp within a week, please let me know. Thanks. A: These are handy links to have open when programming with pygtk: GTK 2 PyGTK 2.x Reference Manual: http://library.gnome.org/devel/pygtk/stable/ PyGTK Tutorial by Andrew Steele: htt...
Pygtk notes links
if any of you are familiar with PyGTK links for beginners to grasp within a week, please let me know. Thanks.
[ "These are handy links to have open when programming with pygtk:\nGTK 2\nPyGTK 2.x Reference Manual: http://library.gnome.org/devel/pygtk/stable/ \nPyGTK Tutorial by Andrew Steele: http://learngtk.org/tutorials/pygtk-tutorial/\nPyGTK FAQ: http://faq.pygtk.org/index.py?req=index\nGTK 3\nPython GI API Reference h...
[ 3, 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0004234215_pygtk_python.txt
Q: Curious about python installation paths, especially on OSX First: I'm running Macports. No problems with that, except: /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin which is the value of sys.exec_prefix, for my macports python even though: /opt/local/lib/python2.6/site-packages/ seems to be ...
Curious about python installation paths, especially on OSX
First: I'm running Macports. No problems with that, except: /opt/local/Library/Frameworks/Python.framework/Versions/2.6/bin which is the value of sys.exec_prefix, for my macports python even though: /opt/local/lib/python2.6/site-packages/ seems to be quite a logical place to put things, /opt/local being the macpor...
[ "So first I'd make the observation that the directory \n/Library/Frameworks/Python.framework/Versions/2.6/...\n\nis where you can find the OS X provided version of Python so I'd guess that what the MacPorts developers want to do is replicate the OS X Python directory structure but keep it as far away from the OS X ...
[ 1 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0002785256_macos_python.txt
Q: calling XQueryKeymap() function in pygtk? How do I call the x XQueryKeymap() function in a pygtk application? A: XQueryKeymap() is very low-level and inherently non-portable, since it returns an array of bytes that identifies which keys are pressed down. Each bit represents one key of the keyboard. Of course, yo...
calling XQueryKeymap() function in pygtk?
How do I call the x XQueryKeymap() function in a pygtk application?
[ "XQueryKeymap() is very low-level and inherently non-portable, since it returns an array of bytes that identifies which keys are pressed down. Each bit represents one key of the keyboard. Of course, you don't get to decide which bit identifies which key on which platform, for it would spoil the fun.\nBoth GTK+ and ...
[ 1 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0004474695_gtk_pygtk_python.txt
Q: How can I store HTML in a DB (SQLITE PYTHON) This is probably quite simple, but I can't get there... How can I store html code in a SQLITE Data Base? I'm using text as the data-type for the field in the DB (should it be blob??) I'm getting weird errors (and changing erros with the same input, so I think it has som...
How can I store HTML in a DB (SQLITE PYTHON)
This is probably quite simple, but I can't get there... How can I store html code in a SQLITE Data Base? I'm using text as the data-type for the field in the DB (should it be blob??) I'm getting weird errors (and changing erros with the same input, so I think it has something to do with escaping) MY CODE: con = sqlite....
[ "Try:\ncur.execute(\n \"UPDATE posts SET html = ? WHERE id = ?\", (html ,temp[i][1]))\n\nUse parameterized arguments to allow sqlite3 to escape the quotes for you. (It also helps prevent SQL injection.)\nRegarding the ProgrammingError: html should be a unicode object, rather than a string object. When you open t...
[ 3 ]
[]
[]
[ "database", "html", "python", "sqlite" ]
stackoverflow_0004475867_database_html_python_sqlite.txt
Q: How to query NATIVE hardware resolution of primary monitor in Windows? I need to find the "best" or native resolution for an attached LCD monitor under Windows (which I'll then set programmatically and know how to do.) Let me repeat that I do not need the Current Windows resolution, nor need to worry about CRTs/p...
How to query NATIVE hardware resolution of primary monitor in Windows?
I need to find the "best" or native resolution for an attached LCD monitor under Windows (which I'll then set programmatically and know how to do.) Let me repeat that I do not need the Current Windows resolution, nor need to worry about CRTs/projectors. I've seen it work with this program, so I know it is possible des...
[ "Decided to give up talking directly to the monitor and instead parsing EDID information cached in the registry. This code isn't perfect, but it works:\nimport win32api as api, win32con as con, pywintypes\nimport win32com.client\n_objWMIService = win32com.client.Dispatch('WbemScripting.SWbemLocator')\n_objSWbemSer...
[ 2 ]
[]
[]
[ "c", "monitor", "python", "resolution", "windows" ]
stackoverflow_0004322153_c_monitor_python_resolution_windows.txt
Q: Using ip address to track visitors, is there a better way? (using Flask micro-framework) I am going to use Flask micro-framework (based on Werkzeug, and I'll be using Python 2.7 or 2.6) to make a games website. I want to allow users to vote (simple 1-5 stars) on games, and also to track how many unique visits the...
Using ip address to track visitors, is there a better way? (using Flask micro-framework)
I am going to use Flask micro-framework (based on Werkzeug, and I'll be using Python 2.7 or 2.6) to make a games website. I want to allow users to vote (simple 1-5 stars) on games, and also to track how many unique visits there have been to each game page - such that I can dynamically order links to the games based on...
[ "In my opinion using the IP address isn't the correct approach.\n\nMany colleges, campuses, hotels, dorms, and offices use a single or small block IP range. This means that only a single person in one of those environments can vote. So if you have a dorm building with 3,000 kids in it who are all behind a single IP...
[ 5, 1 ]
[]
[]
[ "flask", "ip_address", "python", "web", "werkzeug" ]
stackoverflow_0004476127_flask_ip_address_python_web_werkzeug.txt
Q: Bouncing Python Application in Mac Dock when Accessing URLs with py-appscript This has been a recurring, strange issue for me when accessing URLs using py-appscript, first in Safari and now in Chrome. Whenever I run the script command to get the current URL in the terminal, for example, appscript.app("Google Chrom...
Bouncing Python Application in Mac Dock when Accessing URLs with py-appscript
This has been a recurring, strange issue for me when accessing URLs using py-appscript, first in Safari and now in Chrome. Whenever I run the script command to get the current URL in the terminal, for example, appscript.app("Google Chrome").windows.active_tab.URL() a bouncing instance of the "Python" application appea...
[ "The background on this problem is explained here by the author of appscript. Assuming you are on OS X 10.5 or higher, the solution is to use a Python that has been built using a minimum deployment target of 10.5 or higher. From the path you supplied, it appears likely you are using a Python 2.6 from a python.org ...
[ 3 ]
[]
[]
[ "google_chrome", "py_appscript", "python", "safari", "sourceforge_appscript" ]
stackoverflow_0004471951_google_chrome_py_appscript_python_safari_sourceforge_appscript.txt
Q: How would I look for all URLs on a web page and then save them to a individual variables with urllib2 In Python? How would I look for all URLs on a web page and then save them to individual variables with urllib2 In Python? A: Parse the html with an html parser and find all (e.g. using Beutiful Soup's findAll() ...
How would I look for all URLs on a web page and then save them to a individual variables with urllib2 In Python?
How would I look for all URLs on a web page and then save them to individual variables with urllib2 In Python?
[ "Parse the html with an html parser and find all (e.g. using Beutiful Soup's findAll() method) <a> tags and check their href attributes.\nIf, however, you want to find all URLs in the page even if they aren't hyperlinks, then you can use a regular expression which could be anything from simple to ridiculously insan...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004475929_python.txt
Q: Python + Mechanize not working with Delicious I'm using Mechanize and Beautiful soup to scrape some data off Delicious from mechanize import Browser from BeautifulSoup import BeautifulSoup mech = Browser() url = "http://www.delicious.com/varunsrin" page = mech.open(url) html = page.read() soup = BeautifulSoup(ht...
Python + Mechanize not working with Delicious
I'm using Mechanize and Beautiful soup to scrape some data off Delicious from mechanize import Browser from BeautifulSoup import BeautifulSoup mech = Browser() url = "http://www.delicious.com/varunsrin" page = mech.open(url) html = page.read() soup = BeautifulSoup(html) print soup.prettify() This works for most site...
[ "Take some of the tips for emulating a browser with python+mechanize from here. Adding addheaders and set_handle_robots appears to be the minimum required. With the code below, I get output:\nfrom mechanize import Browser, _http\nfrom BeautifulSoup import BeautifulSoup\n\nbr = Browser() \nbr.set_handle_robots(Fa...
[ 9 ]
[]
[]
[ "mechanize", "python", "scraper", "web_crawler" ]
stackoverflow_0004476354_mechanize_python_scraper_web_crawler.txt
Q: Intel Compiler and Python/ctypes/libffi I am having trouble building a working version of Python with ctypes using the Intel Compiler (11.1). The trouble is, that libffi under the ctypes module does not work properly when interfacing with e.g. OpenGL. Originally, libffi did not compile using the Intel Compilers as...
Intel Compiler and Python/ctypes/libffi
I am having trouble building a working version of Python with ctypes using the Intel Compiler (11.1). The trouble is, that libffi under the ctypes module does not work properly when interfacing with e.g. OpenGL. Originally, libffi did not compile using the Intel Compilers as __int128_t is not defined, and I followed th...
[ "I am the author of libffi. I recommend sending a note to libffi-discuss@sourceware.org containing all of this detail. I also recommend running the libffi testsuite on an intel-compiler built libffi. Make sure you send the results to libffi-discuss@sourceware.org and we can help figure out the problem.\n" ]
[ 3 ]
[]
[]
[ "compiler_construction", "ctypes", "libffi", "python" ]
stackoverflow_0003500662_compiler_construction_ctypes_libffi_python.txt
Q: Can `authenticate` use like this in django? this is the code : def openid_done(request, provider=None): """ When the request reaches here, the user has completed the Openid authentication flow. He has authorised us to login via Openid, so request.openid is populated. After coming here, we want ...
Can `authenticate` use like this in django?
this is the code : def openid_done(request, provider=None): """ When the request reaches here, the user has completed the Openid authentication flow. He has authorised us to login via Openid, so request.openid is populated. After coming here, we want to check if we are seeing this openid first time....
[ "No, django does not have an authenticate function that expects openid_key, provider arguments.\ngrep -r \"openid\" django returns nothing for version 1.2.3\nWhat you are looking at is a custom authentication backend, like the one found on github here: https://github.com/agiliq/Django-Socialauth/blob/master/sociala...
[ 0 ]
[]
[]
[ "arguments", "authentication", "django", "python" ]
stackoverflow_0004475987_arguments_authentication_django_python.txt
Q: trying to clone pypy's mercurial repo on windows Trying to clone the pypy repo on my windows machine for some reason. I have mercurial installed, but I do not have svn installed. I know they just did the migration, but I didn't think I would need svn installed too? Here is the output from my terminal. C:\Documen...
trying to clone pypy's mercurial repo on windows
Trying to clone the pypy repo on my windows machine for some reason. I have mercurial installed, but I do not have svn installed. I know they just did the migration, but I didn't think I would need svn installed too? Here is the output from my terminal. C:\Documents and Settings\blahblah\programming>hg clone https://...
[ "This repository uses several SVN subrepositories.\n$ cat .hgsub\ngreenlet = [svn]http://codespeak.net/svn/greenlet/trunk/c\ntestrunner = [svn]http://codespeak.net/svn/pypy/build/testrunner\nlib_pypy/pyrepl = [svn]http://codespeak.net/svn/pyrepl/trunk/pyrepl/pyrepl\nlib_pypy/sqlite3 = [svn]http://codespeak.net/svn/...
[ 4 ]
[]
[]
[ "mercurial", "pypy", "python", "svn" ]
stackoverflow_0004476732_mercurial_pypy_python_svn.txt
Q: pyWin32 support? Trouble while building; syntax error I just downloaded pyWin32 (https://sourceforge.net/projects/pywin32/) and started to install it. My first question: does anybody know, where I can get specific pyWin32-support? I can't see/find anything at sourceforge. 2nd question: Did anybody of you encounter...
pyWin32 support? Trouble while building; syntax error
I just downloaded pyWin32 (https://sourceforge.net/projects/pywin32/) and started to install it. My first question: does anybody know, where I can get specific pyWin32-support? I can't see/find anything at sourceforge. 2nd question: Did anybody of you encounter the problem, that h2py.py ran into an syntax-error during ...
[ "Why do you need to build? Why not just install the pre-built binaries by downloading and executing pywin32-214.win32-py2.6.exe ? It works perfectly for me.\n" ]
[ 3 ]
[]
[]
[ "installation", "python", "pywin32" ]
stackoverflow_0004476764_installation_python_pywin32.txt
Q: Fast-Responding Command Line Scripts I have been writing command-line Python scripts for a while, but recently I felt really frustrated with speed. I'm not necessarily talking about processing speed, dispatching tasks or other command-line tool-specific processes (that is usually a design/implementation problem), ...
Fast-Responding Command Line Scripts
I have been writing command-line Python scripts for a while, but recently I felt really frustrated with speed. I'm not necessarily talking about processing speed, dispatching tasks or other command-line tool-specific processes (that is usually a design/implementation problem), but rather I am talking of simply running ...
[ "In addition to compiling the Python files, Mercurial modifies importing to be on demand which does indeed reduce the start-up time. It sets __builtin__.__import__ to its own import function in the demandimport module.\nIf you look at the hg script in /usr/lib/ (or wherever it is on your machine), you can see this ...
[ 7, 0 ]
[]
[]
[ "command_line", "performance", "python" ]
stackoverflow_0004476125_command_line_performance_python.txt
Q: Django class based generic views: cannot import name TemplateView Django fires exception cannot import name TemplateView how to fix this? view.py : from django.views.generic import TemplateView class Monitor(TemplateView): template_name = 'helo.html' urls.py : from monitor.views import Monitor urlpatterns ...
Django class based generic views: cannot import name TemplateView
Django fires exception cannot import name TemplateView how to fix this? view.py : from django.views.generic import TemplateView class Monitor(TemplateView): template_name = 'helo.html' urls.py : from monitor.views import Monitor urlpatterns = patterns('', (r'^admin/', Monitor.as_view()), )
[ "I don't know what Django version you are using, but only in Django 1.3 a class called TemplateView exists. Its import should be:\nfrom django.views.generic.base import TemplateView\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004476983_django_django_templates_python.txt
Q: Python try except finally It looks like I don't quite have the hang of Exception handling yet. I'm at a loss :( The following code sometimes returns this error: File "applications/pingback/modules/plugin_h_pingback.py", line 190, in ping db(table.id==id_).update(status=status) UnboundLocalError: local variable...
Python try except finally
It looks like I don't quite have the hang of Exception handling yet. I'm at a loss :( The following code sometimes returns this error: File "applications/pingback/modules/plugin_h_pingback.py", line 190, in ping db(table.id==id_).update(status=status) UnboundLocalError: local variable 'status' referenced before ass...
[ "Your code doesn't always assign something to status. I can see a few ways that status might not be assigned and I've highlighted them below:\ntry:\n server_url = self._get_pingback_server(target)\nexcept PingbackClientError, e:\n # If evaluating `e.message` raises an exception then status is not set.\n st...
[ 10, 3 ]
[]
[]
[ "python", "try_catch_finally", "web2py" ]
stackoverflow_0004477332_python_try_catch_finally_web2py.txt
Q: Manipulating another model's data from a model save method I am building a simple application which has questions. Each question will have a binary vote (yes/no). I want to record the vote per user, so each user only gets one vote per question (similar to stack overflow or reddit). I have a votes_no and votes_yes ...
Manipulating another model's data from a model save method
I am building a simple application which has questions. Each question will have a binary vote (yes/no). I want to record the vote per user, so each user only gets one vote per question (similar to stack overflow or reddit). I have a votes_no and votes_yes int field on the question. These need to be updated in a transac...
[ "Would the following answer the question ?\nclass Question(models.Model):\n blablabla #your definition\n\n def count_yes(self):\n return Vote.objects.filter(question__exact = self,\n choice__exact = 'Y').count()\n\n", "I'd rewrite Igautier's method a bit differently:...
[ 1, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004477093_django_django_models_python.txt
Q: prime_factorize(1) -> ? (Pythonic error signalling) I have a prime_factorize function that returns a dictionary mapping from prime divisors to their powers. E.g., 50 = 2^1 * 5^2, so prime_factorize(50) returns {2 : 1, 5 : 2}. Assuming this is the documented behavior, what would be the least surprising way to sign...
prime_factorize(1) -> ? (Pythonic error signalling)
I have a prime_factorize function that returns a dictionary mapping from prime divisors to their powers. E.g., 50 = 2^1 * 5^2, so prime_factorize(50) returns {2 : 1, 5 : 2}. Assuming this is the documented behavior, what would be the least surprising way to signal an error if called 0, 1, or a negative number? Throw V...
[ "In prime_factorize(n):\nif n < 2 or not isinstance(n, numbers.Integral):\n raise ValueError(\"Number to factor can't be less than 2\")\nelse:\n # normal behavior\n\nThat way users a.) get meaningful info about what went wrong and b.) can handle the exception in a try...except block.\nI definitely wouldn't tu...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004476880_python.txt
Q: Creating a Python Distribution: Trouble inlcluding HTML & JS etc files I'm using the following script to create a python distribution, a theme/templates set for Pinax. The files are mostly HTML & JS, with the Python files there more for configuration purposes: import os import sys from fnmatch import fnmatchcase ...
Creating a Python Distribution: Trouble inlcluding HTML & JS etc files
I'm using the following script to create a python distribution, a theme/templates set for Pinax. The files are mostly HTML & JS, with the Python files there more for configuration purposes: import os import sys from fnmatch import fnmatchcase from distutils.util import convert_path from setuptools import setup, find_p...
[ "I believe you have to specify those files in MANIFEST.in. \n" ]
[ 3 ]
[]
[]
[ "django", "python", "sdist" ]
stackoverflow_0004477413_django_python_sdist.txt
Q: how can i convert a string like 123245wkjsvd :/' to list and sort? I want to convert it to a list and sort them alphabetically and then turn the result to a string again. Well i want to do this in python. how can i do that? A: There are shorter one-liners, but here it is statement-by-statement: # initial string ...
how can i convert a string like 123245wkjsvd :/' to list and sort?
I want to convert it to a list and sort them alphabetically and then turn the result to a string again. Well i want to do this in python. how can i do that?
[ "There are shorter one-liners, but here it is statement-by-statement:\n# initial string\ninput_string = \"123245wkjsvd :/'\"\n# Convert string to list of characters\nlist_of_chars = list(input_string)\n# Sort list\nlist_of_chars.sort()\n# Convert to string\noutput_string = ''.join(list_of_chars)\n\nShortest one-lin...
[ 12, 4, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0004477504_list_python_string.txt
Q: Inside Django's models.py, if I am validating a form, how do I get the user's IP? I know how to get it in views.py.... request.META['REMOTE_ADDR'] However, how do I get it in models.py when one of my forms is being validateD? A: You can pass the request object to the form/model code that is being called: this wi...
Inside Django's models.py, if I am validating a form, how do I get the user's IP?
I know how to get it in views.py.... request.META['REMOTE_ADDR'] However, how do I get it in models.py when one of my forms is being validateD?
[ "You can pass the request object to the form/model code that is being called: this will then provide access to request.META['REMOTE_ADDR']. Alternatively, just pass that in.\n", "If you are validating at form level or at model level, both instances know nothing about the HTTP request (where the client IP info is ...
[ 1, 0, 0 ]
[]
[]
[ "django", "forms", "ip", "python", "validation" ]
stackoverflow_0004476430_django_forms_ip_python_validation.txt
Q: any method to mix these urls in django the usl : (r'^account/', include('account.urls')), (r'^account/', include('django_authopenid.urls')), i want to use these url , and i dont want to mix it by my hand one by one , it is not very easy , has a method to do this in django . thanks A: Your own code can wor...
any method to mix these urls in django
the usl : (r'^account/', include('account.urls')), (r'^account/', include('django_authopenid.urls')), i want to use these url , and i dont want to mix it by my hand one by one , it is not very easy , has a method to do this in django . thanks
[ "Your own code can work properly in many cases, but if not you can do\nthis:\nCreate your own urls.py file:\nfrom account.urls import urlpatterns as accounts_urlpatterns\nfrom django_authopenid.urls import urlpatterns as authopenid_urlpatterns\n\nurlpatterns = patterns(\"\")\nurlpatterns += accounts_urlpatterns\nur...
[ 2, 2 ]
[]
[]
[ "django", "python", "url" ]
stackoverflow_0004477006_django_python_url.txt
Q: How do I use this Django app correctly? https://github.com/jtauber/django-notification/tree/555b506a3e225d476d17939d8b43f853fd0226ec/notification OK, so this is what I did so far: Install this via setup.py install put "notification" in INSTALLED_APPS import notification in my views.py After looking at the source...
How do I use this Django app correctly?
https://github.com/jtauber/django-notification/tree/555b506a3e225d476d17939d8b43f853fd0226ec/notification OK, so this is what I did so far: Install this via setup.py install put "notification" in INSTALLED_APPS import notification in my views.py After looking at the source code of that app, it seems like there is URL...
[ "Use setup.py, and install it into your project's virtualenv.\nIf you aren't using virtualenv for development, and probably deployment, then you should be.\nOh, and obligatory docs link for including urls.py: http://docs.djangoproject.com/en/dev/topics/http/urls/#including-other-urlconfs (hat-tip to Ignacio).\n" ]
[ 0 ]
[]
[]
[ "django", "installation", "python" ]
stackoverflow_0004476097_django_installation_python.txt
Q: Django templates: get the list of passed objects and variable How to get the list of objects and variables passed into a template? Sultan A: I usually have django-debug-toolbar installed. It gives you all that information and much more. A: You can modify the dict that you passed to render_to_response so that ...
Django templates: get the list of passed objects and variable
How to get the list of objects and variables passed into a template? Sultan
[ "I usually have django-debug-toolbar installed. It gives you all that information and much more.\n", "You can modify the dict that you passed to render_to_response so that it contains the list of variables.\nIn your views.py:\ndic = {'a':1, 'b':2}\ndic['keys'] = dic.keys()\nreturn render_to_response('your_templa...
[ 4, -2 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0004477316_django_django_templates_python.txt
Q: How to get Django to work on Apache in Windows? I'm creating an internet radio station site on my Apache, and I've decided Django is the CMS which is best suited to the task. http://www.gareth53.co.uk/work.html mentions it being used for radio station sites, and I decided I'd go with this since it seems to be a fa...
How to get Django to work on Apache in Windows?
I'm creating an internet radio station site on my Apache, and I've decided Django is the CMS which is best suited to the task. http://www.gareth53.co.uk/work.html mentions it being used for radio station sites, and I decided I'd go with this since it seems to be a fairly popular choice. These are some examples of it in...
[ "First of all, Django is not a CMS.. it is a web framework. You can find how to deploy django with apache and modwsgi in the following link. \nhttp://docs.djangoproject.com/en/dev/howto/deployment/modwsgi/\n" ]
[ 1 ]
[]
[]
[ "django", "mod_wsgi", "python" ]
stackoverflow_0004477819_django_mod_wsgi_python.txt
Q: Should I use Pylons or Pyramid? I was planning to move from Django to Pylons, but then I bumped into Pyramid. What are the differences between Pylons and Pyramid? I read some text in PylonsBook, which currently covers Pylons 0.9.7, and wonder if it is a to start for Pylons and Pyramid. A: Pylons isn't being "can...
Should I use Pylons or Pyramid?
I was planning to move from Django to Pylons, but then I bumped into Pyramid. What are the differences between Pylons and Pyramid? I read some text in PylonsBook, which currently covers Pylons 0.9.7, and wonder if it is a to start for Pylons and Pyramid.
[ "Pylons isn't being \"cancelled\", and it will continue to receive updates. That said, the \"future\" per se is in Pyramid. On the mailing list is has been referred to as Pylons 2.0. It is fully tested and better documented than Pylons 1.0, so you might as well jump aboard if you're fresh.\nPyramid is essentially t...
[ 36, 19, 10 ]
[]
[]
[ "pylons", "pyramid", "python" ]
stackoverflow_0004313715_pylons_pyramid_python.txt
Q: How does Python handle memory? I've been looking at a in-memory database -- and it got me thinking, how does Python handle IO that's not tied to a connection (and even data that is); for example, hashes, sets, etc.; is this a config somewhere, or is it dynamically managed based on resources; are there "easy" ways ...
How does Python handle memory?
I've been looking at a in-memory database -- and it got me thinking, how does Python handle IO that's not tied to a connection (and even data that is); for example, hashes, sets, etc.; is this a config somewhere, or is it dynamically managed based on resources; are there "easy" ways to view the effect resources are hav...
[ "Python allocates all memory that the application asks for. There is not much room for policy. The only issue is when to release memory. (C)Python immediately releases all memory that is not referenced anymore (this is also not tunable). Memory that is referenced only from itself (ie. cycles) are released by the ga...
[ 7, 1 ]
[]
[]
[ "memory", "performance", "python" ]
stackoverflow_0004478082_memory_performance_python.txt
Q: Reading objects from file after dumping then to file I've made a function to write objects to a file: def StoreToFile(Thefile,objekt): utfil=None utfil=open(Thefile,'wb') pickle.dump(objekt,utfil) return True if utfil is not None: utfil.close() And my code to use this function: for st in S...
Reading objects from file after dumping then to file
I've made a function to write objects to a file: def StoreToFile(Thefile,objekt): utfil=None utfil=open(Thefile,'wb') pickle.dump(objekt,utfil) return True if utfil is not None: utfil.close() And my code to use this function: for st in Stadion: StoreToFile(r'C:\pytest\prod.psr',st) This wo...
[ "for st in Stadion:\n StoreToFile(r'C:\\pytest\\prod.psr',st)\n\n\nThis works like a charm.\n\nIf you mean \"run without errors\", then yes, it does \"work\". This code repeatedly overwrites the file, so it will only contain the last item in the list.\nUse this instead:\nStoreToFile(r'C:\\pytest\\prod.psr', Stad...
[ 2, 2, 1, 0 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0004478138_pickle_python.txt
Q: Processing buffers bigger than 65536 in Clyther/OpenCL I am currently in the process of discovering OpenCL via the Python binding Clyther. So far I am messing with a very simple script to get the sin or cos of a buffer of 65536. Apparently 65536 is the limit for buffers on my card but say I'd have 16 million numb...
Processing buffers bigger than 65536 in Clyther/OpenCL
I am currently in the process of discovering OpenCL via the Python binding Clyther. So far I am messing with a very simple script to get the sin or cos of a buffer of 65536. Apparently 65536 is the limit for buffers on my card but say I'd have 16 million numbers in my buffer how would I go about it without constantly ...
[ "This awfully looks like you are using __constant memory. The solution is to use __global memory instead, but you have to be careful about how you access it for best performance.\n__constant memory is a special address space for often used constant values, but is restricted in size on current GPUs.\n" ]
[ 2 ]
[]
[]
[ "opencl", "python" ]
stackoverflow_0004470246_opencl_python.txt