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 program running a web site for different inputs This is a general question, and I don't expect any specific solution here. I'm just very curious about the approach. Let us say I have txt-file with many keywords. There are so many keywords that I can't make a seperate google-search for each one of them. That ...
Make program running a web site for different inputs
This is a general question, and I don't expect any specific solution here. I'm just very curious about the approach. Let us say I have txt-file with many keywords. There are so many keywords that I can't make a seperate google-search for each one of them. That would take too long time. My goal is to make a program whi...
[ "Here is one way of doing it. \n\nCreate a java(or any other language) program which will read the file with keywords. \nFor each keyword read from the file, Use Google Search APIs to search (See example here).\nSave the the results returned from API in a file.\n\n", "You are looking for something like bowser aut...
[ 2, 1, 1, 1, 1 ]
[]
[]
[ "html", "java", "php", "python" ]
stackoverflow_0008604672_html_java_php_python.txt
Q: Using strings of decimals in python I'm trying to use a string of a decimal, but I am getting an unwanted "0.". For example: age = .01 print 'test%s'%(age) print 'test' + str(age) These both return 'test0.01', but I want 'test.01'. I know there is a simple solution. Any thoughts? A: age = .01 print 'test' + ...
Using strings of decimals in python
I'm trying to use a string of a decimal, but I am getting an unwanted "0.". For example: age = .01 print 'test%s'%(age) print 'test' + str(age) These both return 'test0.01', but I want 'test.01'. I know there is a simple solution. Any thoughts?
[ "age = .01\nprint 'test' + str(age).lstrip('0')\n\nWorks for age > 1.0 as well.\n", "age = .01\nprint 'test%s' % str(age)[1:] if 0<age<1 else str(age)\n\n", "age = .01\nprint 'test' + (str(age)[1:] if 0 < age < 1 else str(age))\n\n" ]
[ 6, 2, 0 ]
[]
[]
[ "decimal", "python", "string" ]
stackoverflow_0008606228_decimal_python_string.txt
Q: How to get data from SNMP with python? How to get value mac and vlan from fdb table uses python? In bash snmpwalk work fine: snmpwalk -v2c -c pub 192.168.0.100 1.3.6.1.2.1.17.7.1.2.2.1.2 pysnmp: import os, sys import socket import random from struct import pack, unpack from datetime import datetime as dt from...
How to get data from SNMP with python?
How to get value mac and vlan from fdb table uses python? In bash snmpwalk work fine: snmpwalk -v2c -c pub 192.168.0.100 1.3.6.1.2.1.17.7.1.2.2.1.2 pysnmp: import os, sys import socket import random from struct import pack, unpack from datetime import datetime as dt from pysnmp.entity.rfc3413.oneliner import cmdge...
[ "In the pysnmp example you are doing an SNMPGET (snmpget), not a GETNEXT (snmpwalk). If you change,\nreal_fun = getattr(generator, 'getCmd')\n\nto\nreal_fun = getattr(generator, 'nextCmd')\n\nyou will start to see useful results.\nAs for the discrepancy you saw in the results between snmpwalk and the python net-sn...
[ 16 ]
[]
[]
[ "fdb", "net_snmp", "pysnmp", "python", "snmp" ]
stackoverflow_0008601324_fdb_net_snmp_pysnmp_python_snmp.txt
Q: Django urls.py template issue I am new to Django and just playing around with the code and features but I seem to be stuck (yes I have done the entire tutorial). For some reason my mysite/urls.py is not taking me to the right urls, actually it ONLY takes me to one template no matter what I do. Here is my urls.py: ...
Django urls.py template issue
I am new to Django and just playing around with the code and features but I seem to be stuck (yes I have done the entire tutorial). For some reason my mysite/urls.py is not taking me to the right urls, actually it ONLY takes me to one template no matter what I do. Here is my urls.py: from django.conf.urls.defaults impo...
[ "I have checked your code, it works just fine. I cannot replicate such error with your views and urls. Post your templates and directory structure to make sure they are fine too.\ntest result for /app/\n\nHello link 1.\n\ntest result for /app/detail/\n\nYou're looking at detail.\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0008603744_django_django_urls_python.txt
Q: Adding the values of a dictionary to another dictionary I'd like to add the values of a dictionary to another dictionary. For example: adict = {1: {'a': 13, 'b': 19, 'c': 15}, 2: {'a': 7, 'b': 2, 'c': 0}} If we add {1: {'a': 3, 'b': 9, 'c': 23}} to adict Then adict should now be: {1: {'a': 16, 'b': 28, 'c': 38},...
Adding the values of a dictionary to another dictionary
I'd like to add the values of a dictionary to another dictionary. For example: adict = {1: {'a': 13, 'b': 19, 'c': 15}, 2: {'a': 7, 'b': 2, 'c': 0}} If we add {1: {'a': 3, 'b': 9, 'c': 23}} to adict Then adict should now be: {1: {'a': 16, 'b': 28, 'c': 38}, 2: {'a': 7, 'b': 2, 'c': 0}} If we add {3: {'a': 4}} then a...
[ "Simple recursive function:\n>>> adict = {1: {'a': 13, 'b': 19, 'c':15}, 2: {'a': 7, 'b': 2, 'c':0}}\n>>> def dict_add(a,b):\n... a = a.copy()\n... for k,v in b.items():\n... if isinstance(v,(dict,)):\n... a[k] = dict_add(a.get(k,{}),v)\n... else:\n... a[k] = a.get(k,0) + v\n... return a\n...
[ 6, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008606691_python.txt
Q: How to store cumulative output in a list? I am using the following code to get frequency of letters in a text: for s in 'abcdefghijklmnopqrstuvwxyz ': count = 0 for char in rawpunct.lower(): if s == char: count +=1 result = s, '%.3f' % (count*100/len(rawpunct.lower())) f_list.ap...
How to store cumulative output in a list?
I am using the following code to get frequency of letters in a text: for s in 'abcdefghijklmnopqrstuvwxyz ': count = 0 for char in rawpunct.lower(): if s == char: count +=1 result = s, '%.3f' % (count*100/len(rawpunct.lower())) f_list.append(result) And the result is : ['0.061', '0...
[ "You can use import numpy\nand then make result an array results=numpy.array(result)\nand finally 'f_list=numpy.cumsum(results)'\n", "letters = 'abcdefghijklmnopqrstuvwxyz '\ncounts = dict.fromkeys(letters, 0)\nfor char in rawpunct.lower():\n try:\n counts[char] += 1\n except KeyError:\n pa...
[ 3, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0008606130_list_python.txt
Q: How to open an HTML JavaScript page in a wx.Python or other python gui window? Is there any way to open a browser based editor (such as CKEdit, tinymce, or any other HTML + JavaScript editor) in a Python window (perhaps wx.Python) rather than in a browser? Thank you in advance. A: I suggest you try using Webkit ...
How to open an HTML JavaScript page in a wx.Python or other python gui window?
Is there any way to open a browser based editor (such as CKEdit, tinymce, or any other HTML + JavaScript editor) in a Python window (perhaps wx.Python) rather than in a browser? Thank you in advance.
[ "I suggest you try using Webkit python bindings.\nYou can load an arbitrary Webview and put it anywhere as a GTK widget:\nhttp://code.google.com/p/pywebkitgtk/\nI'm not sure about WX.\nOne complexity you will find is how to get the values from JS into Python.\nHere's an article describing a trick to call the sandbo...
[ 2 ]
[]
[]
[ "editor", "html", "python" ]
stackoverflow_0007521925_editor_html_python.txt
Q: Python BeautifulSoup parsing I am trying to scrape some content (am very new to Python) and I have hit a stumbling block. The code I am trying to scrape is: <h2><a href="/best-sellers/sj-b9822.html">Spear & Jackson Predator Universal Hardpoint Saw - 22"</a></h2> <p><span class="productlist_mostwanted_rrp"> ...
Python BeautifulSoup parsing
I am trying to scrape some content (am very new to Python) and I have hit a stumbling block. The code I am trying to scrape is: <h2><a href="/best-sellers/sj-b9822.html">Spear & Jackson Predator Universal Hardpoint Saw - 22"</a></h2> <p><span class="productlist_mostwanted_rrp"> Was: <span class="strikethrough">...
[ "I think what you're looking for is something like this:\nfrom BeautifulSoup import BeautifulSoup\nimport re\n\nsoup = BeautifulSoup(open('prueba.html').read())\nitem = re.sub('\\s+', ' ', soup.h2.a.text)\nprice = soup.find('p', {'class': 'productlist_mostwanted_price'}).text\nprice = re.search('\\d+\\.\\d+', price...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "screen_scraping" ]
stackoverflow_0008606738_beautifulsoup_python_screen_scraping.txt
Q: Python: Compute relative path from one directory to another Possible Duplicate: How to calculate relative path between 2 directory path? I need to compute the relative path from one directory to another (i.e. I set a path relative to the working directory, and want to compute the according relative path from an...
Python: Compute relative path from one directory to another
Possible Duplicate: How to calculate relative path between 2 directory path? I need to compute the relative path from one directory to another (i.e. I set a path relative to the working directory, and want to compute the according relative path from any parent/subdir). What is a good way to do that in Python? I cou...
[ "You should take a look at: os.path.relpath\n", "os.path.relpath() does this for you and is available in Python 2.6 and above. \n" ]
[ 17, 6 ]
[ "You can set the relative path using os.path.dirname(file)\nos.path.join(os.path.dirname(file), \"filename\")\n" ]
[ -1 ]
[ "directory", "path", "python" ]
stackoverflow_0008607264_directory_path_python.txt
Q: access twitter HomeTimeline of user I am trying to develop a gtk3 desktop application using python to perform the basic twitter functions like accessing the home timeline of a user, making tweets etc. I am using python-twitter library, but am unable to find the API call for the purpose. I checked and saw there we...
access twitter HomeTimeline of user
I am trying to develop a gtk3 desktop application using python to perform the basic twitter functions like accessing the home timeline of a user, making tweets etc. I am using python-twitter library, but am unable to find the API call for the purpose. I checked and saw there were a few patches , but they dont seem to ...
[ "Using the python-twitter module from code.google.com, documentation here.\nAccessing user timelines:\nimport twitter\napi = twitter.Api()\nstatuses = api.GetUserTimeline('@gaurav_sood91')\nprint [s.text for s in statuses]\n\nPosting tweets:\nimport twitter\napi = twitter.Api(consumer_key='consumer_key',\n ...
[ 2 ]
[]
[]
[ "python", "python_twitter" ]
stackoverflow_0008605971_python_python_twitter.txt
Q: ImportError: No module named I'm migrating PyVisa from Python 2.6 to Python 3.2. I'm able to install the module. It's listed in C:\Python32\Lib\site-packages\pyvisa The __init__.py file imports a module (vpp43.py) from this folder. At this line I get following error: Traceback (most recent call last): File "D:\Do...
ImportError: No module named
I'm migrating PyVisa from Python 2.6 to Python 3.2. I'm able to install the module. It's listed in C:\Python32\Lib\site-packages\pyvisa The __init__.py file imports a module (vpp43.py) from this folder. At this line I get following error: Traceback (most recent call last): File "D:\Documents and Settings\grknbl16\My D...
[ "In Python 3.x implicit relative imports have gone away. Instead of \nimport configparser, os, sys, vpp43\n\npyvisa\\__init__.py needs to say:\nimport configparser, os, sys\nfrom . import vpp43\n\n" ]
[ 7 ]
[]
[]
[ "import", "migrate", "python", "python_3.x", "visa" ]
stackoverflow_0008605036_import_migrate_python_python_3.x_visa.txt
Q: Show progress of PYTHON CGI script I have a PYTHON CGI script(Content-type: text/plain) which takes about 10 minutes to execute. I want to see the execution status of my script on my browser . Like below: Part 1 of script executed... Part 2 of script executed.. Part 3 of script executed.. Execution Complete I am...
Show progress of PYTHON CGI script
I have a PYTHON CGI script(Content-type: text/plain) which takes about 10 minutes to execute. I want to see the execution status of my script on my browser . Like below: Part 1 of script executed... Part 2 of script executed.. Part 3 of script executed.. Execution Complete I am using print statements, but it is outpu...
[ "I suspect the real blocking point is the gateway (web server), not your CGI application. The gateway technically has to validate the response and make sure it conforms to the HTTP version the gateway is using with the client.\nI'm not sure the gateway is even allowed to forward the headers until all of the reques...
[ 5, 2, 1 ]
[]
[]
[ "cgi", "progress", "python", "show" ]
stackoverflow_0008606798_cgi_progress_python_show.txt
Q: parsedatetime to show a data range? Am I missing something, or does parsedatetime not do date ranges like so: "Next January" - ideally should return something like ('Jan 1st 2012', 'Jan 31st 2012') (sudo code - obviously proper python date objects) Similarly, "Tomorrow" might return something like ('Dec 23rd 2011...
parsedatetime to show a data range?
Am I missing something, or does parsedatetime not do date ranges like so: "Next January" - ideally should return something like ('Jan 1st 2012', 'Jan 31st 2012') (sudo code - obviously proper python date objects) Similarly, "Tomorrow" might return something like ('Dec 23rd 2011 00:00', 'Dec 23rd 2011 23.59') I see it ...
[ "Looking at the source code I see a few regular expressions that pretty much explain what kind of ranges can be parsed (I've removed some lines that deal with locales):\n# \"06/07/06 - 08/09/06\"\nself.DATERNG1 = self.RE_RDATE + r'\\s?%(rangeseperator)s\\s?' + self.RE_RDATE\n\n# \"march 31 - june 1st, 2006\"\nself....
[ 4 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0008607327_datetime_python.txt
Q: error about get data i have a function : def tong_thoigian (self,cr,uid,ids,context={}): obj=self.browse(cr,uid,ids,context=context)[0] cr.execute('''select name,giolam from x_giolam where name=%s'''%(obj.ma_luong)) kq=cr.fetchall() tong=0.00000 ...
error about get data
i have a function : def tong_thoigian (self,cr,uid,ids,context={}): obj=self.browse(cr,uid,ids,context=context)[0] cr.execute('''select name,giolam from x_giolam where name=%s'''%(obj.ma_luong)) kq=cr.fetchall() tong=0.00000 for i in kq: ...
[ "Using my magic crystal ball, I'm guessing that cr.execute is a call to the standard database API. So kr.fetchall() will return a tuple of rows. However, it seems that your SQL is returning only a single row. \nYou probably mean tong += kq[0][1], ie the second column (giolam) of the first row of the result. Alterna...
[ 1 ]
[]
[]
[ "openerp", "python" ]
stackoverflow_0008607391_openerp_python.txt
Q: How to process large files on gae I want my app to download an XML file and process it daily. The XML file comes in a ~100MB zip file - ~1GB when extracted. The processed output is less than 1MB. I noticed the URL fetch (and urllib) response size quota is 32MB: http://code.google.com/appengine/docs/python/urlfetc...
How to process large files on gae
I want my app to download an XML file and process it daily. The XML file comes in a ~100MB zip file - ~1GB when extracted. The processed output is less than 1MB. I noticed the URL fetch (and urllib) response size quota is 32MB: http://code.google.com/appengine/docs/python/urlfetch/overview.html#Quotas_and_Limits Is th...
[ "You will need to use Blobstores\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "large_files", "python", "xml" ]
stackoverflow_0008605148_google_app_engine_large_files_python_xml.txt
Q: Get point IDs after clustering, using python Possible Duplicate: Python k-means algorithm I want to cluster 10000 indexed points based on their feature vectors and get their ids after clustering i.e. cluster1:[p1, p3, p100, ...], cluster2:[...] ... Is there any way to do this in Python? Thx~ P.s. The indexed poi...
Get point IDs after clustering, using python
Possible Duplicate: Python k-means algorithm I want to cluster 10000 indexed points based on their feature vectors and get their ids after clustering i.e. cluster1:[p1, p3, p100, ...], cluster2:[...] ... Is there any way to do this in Python? Thx~ P.s. The indexed points are stored in a 10000*10 matrix, where each r...
[ "Use some clustering algorithm - I've included an implementation of the K-means algorithm that @Cameron linked to in his second comment, but you might want to refer to the link in his first comment. I'm not sure what you mean by get their ID's, could you elaborate?\nfrom math import sqrt\n\ndef k_means(data_pts, k=...
[ 2 ]
[]
[]
[ "cluster_analysis", "k_means", "numpy", "python", "scipy" ]
stackoverflow_0008607670_cluster_analysis_k_means_numpy_python_scipy.txt
Q: How do I get rid of characters like ' that appear instead of apostrophes? Possible Duplicate: Convert XML/HTML Entities into Unicode String in Python I am attempting to scrape a website using Python. I import and use the urllib2, BeautifulSoup and re modules. response = urllib2.urlopen(url) soup = BeautifulSoup(...
How do I get rid of characters like ' that appear instead of apostrophes?
Possible Duplicate: Convert XML/HTML Entities into Unicode String in Python I am attempting to scrape a website using Python. I import and use the urllib2, BeautifulSoup and re modules. response = urllib2.urlopen(url) soup = BeautifulSoup(response) responseString = str(soup) coarseExpression = re.compile('<div clas...
[ "The following BeautifulSoup documentation on entity conversion should be what you're looking for:\nhttp://www.crummy.com/software/BeautifulSoup/documentation.html#Entity%20Conversion\n" ]
[ 4 ]
[]
[]
[ "beautifulsoup", "python", "regex", "screen_scraping", "web_scraping" ]
stackoverflow_0008607912_beautifulsoup_python_regex_screen_scraping_web_scraping.txt
Q: Python HTTPS against Azure service management API fails on Windows I've recently extended a Python API for the Windows Azure storage APIs (PyAzure) to include support for the service management APIs. See https://github.com/bmb/pyazure. I'm using a HTTPSClientAuthHandler like the one suggested in using pyOpenSSL to...
Python HTTPS against Azure service management API fails on Windows
I've recently extended a Python API for the Windows Azure storage APIs (PyAzure) to include support for the service management APIs. See https://github.com/bmb/pyazure. I'm using a HTTPSClientAuthHandler like the one suggested in using pyOpenSSL to create urllib custom opener. On Linux, with various versions of Python ...
[ "I haven't been able to pin down a definitive explanation for this, but after a bit of trial and error I'm confident of where the issue lays...\nShort answer: it's the ssl implementation in the http://www.python.org/ Windows bundle. Use ActiveState Python instead.\nLong Answer:\nThe Windows CPython distributions av...
[ 2, 2, 0 ]
[]
[]
[ "azure", "https", "python", "windows" ]
stackoverflow_0008342714_azure_https_python_windows.txt
Q: Run shell script in python I need to execute a shell script to run the python program in via python command. I should have to execute my python script like this ubuntu@ip-10-32-157-231:~/hg_intcen/lib$ xvfb-run python webpage_scrapper.py http://www.google.ca/search?q=navaspot This script need to be executed in p...
Run shell script in python
I need to execute a shell script to run the python program in via python command. I should have to execute my python script like this ubuntu@ip-10-32-157-231:~/hg_intcen/lib$ xvfb-run python webpage_scrapper.py http://www.google.ca/search?q=navaspot This script need to be executed in python program since there are hu...
[ "Try:\nproc.wait()\n\ninstead of your time.sleep(15) call.\nFrom the docs:\n\nPopen.wait() - Wait for child process to terminate. Set and return returncode attribute.\n\n", "You should use the communicate() method to wait that the external process completes.\nstddata, stderr = proc.communicate()\n\nIf you have to...
[ 7, 2 ]
[]
[]
[ "bash", "python", "shell", "subprocess", "ubuntu_11.04" ]
stackoverflow_0008606709_bash_python_shell_subprocess_ubuntu_11.04.txt
Q: How to specifiy path when using pdb in emacs? I am trying to use pdb in emacs. I need to change path to PYTHONPATH=lib. But when I typed Run pdb (like this): PYTHONPATH=lib pdb ./pychess. Emacs gives me an error saying the file PYTHONPATH=lib isn't found. How do I specify path when running pdb in emacs? In termi...
How to specifiy path when using pdb in emacs?
I am trying to use pdb in emacs. I need to change path to PYTHONPATH=lib. But when I typed Run pdb (like this): PYTHONPATH=lib pdb ./pychess. Emacs gives me an error saying the file PYTHONPATH=lib isn't found. How do I specify path when running pdb in emacs? In terminal PYTHONPATH=lib pdb ./pychess runs fine, but not...
[ "you can try to set the environment variable with in the emacs (say putting in .emacs or using M-:) like this\n(setenv \"PYTHONPATH\" \"lib\")\n\n" ]
[ 4 ]
[]
[]
[ "emacs", "pdb", "python" ]
stackoverflow_0008608661_emacs_pdb_python.txt
Q: Python get character code in different encoding? Given a character code as integer number in one encoding, how can you get the character code in, say, utf-8 and again as integer? A: UTF-8 is a variable-length encoding, so I'll assume you really meant "Unicode code point". Use chr() to convert the character code ...
Python get character code in different encoding?
Given a character code as integer number in one encoding, how can you get the character code in, say, utf-8 and again as integer?
[ "UTF-8 is a variable-length encoding, so I'll assume you really meant \"Unicode code point\". Use chr() to convert the character code to a character, decode it, and use ord() to get the code point.\n>>> ord(chr(145).decode('koi8-r'))\n9618\n\n", "You can only map an \"integer number\" from one encoding to another...
[ 16, 12, 2 ]
[]
[]
[ "character_codes", "encoding", "python", "unicode", "utf_8" ]
stackoverflow_0008600552_character_codes_encoding_python_unicode_utf_8.txt
Q: Modifying DYLD_LIBRARY_PATH for mysql, python, and django I've seen two dozen posts concerning this issue, but I'm so NOOB I'm not sure how to modify everything correctly. I'm attempting to finish the installation, but when I go to Python and "import MySQLdb" I end up getting: ImportError: dlopen(/Users/pccampbell...
Modifying DYLD_LIBRARY_PATH for mysql, python, and django
I've seen two dozen posts concerning this issue, but I'm so NOOB I'm not sure how to modify everything correctly. I'm attempting to finish the installation, but when I go to Python and "import MySQLdb" I end up getting: ImportError: dlopen(/Users/pccampbell/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.5-fat3.egg-tmp...
[ "According to Matt's idea, in mac os x Lion, you should add the following sentence like this to your /etc/profile:\nexport DYLD_LIBRARY_PATH=/usr/local/mysql/lib:$DYLD_LIBRARY_PATH\n\n", "add the export command to /etc/profile as follows:\nexport DYLD_LIBRARY_PATH=/usr/local/mysql/lib\n\nNote:There is no \"/\" af...
[ 14, 8 ]
[]
[]
[ "python" ]
stackoverflow_0005081574_python.txt
Q: How can I determine the current event in Google Calendar using Python? I'm building a thermostat that pulls its target temperatures from a Google Calendar. In doing so, I need to determine the event happening now in said Google Calendar. At present, I'm fetching the .ics file from Google and then parsing it with P...
How can I determine the current event in Google Calendar using Python?
I'm building a thermostat that pulls its target temperatures from a Google Calendar. In doing so, I need to determine the event happening now in said Google Calendar. At present, I'm fetching the .ics file from Google and then parsing it with Python icalendar library. I then iterate through every event in the calendar ...
[ "You should use the Google Calendar API. You can ask it for the events within a certain period of time, and it'll respond with some nice JSON that will give you the information. There's even a Python client that will take care of translating your requests to and from JSON.\nThere isn't a way of querying for the cur...
[ 8 ]
[]
[]
[ "icalendar", "python" ]
stackoverflow_0008609147_icalendar_python.txt
Q: Python regular expressions OR Suppose I want a regular expression that matches both "Sent from my iPhone" and "Sent from my iPod". How do I write such an expression? I tried things like: re.compile("Sent from my [iPhone]|[iPod]") but doesn't seem to work. A: re.compile("Sent from my (iPhone|iPod)") A: re.com...
Python regular expressions OR
Suppose I want a regular expression that matches both "Sent from my iPhone" and "Sent from my iPod". How do I write such an expression? I tried things like: re.compile("Sent from my [iPhone]|[iPod]") but doesn't seem to work.
[ "re.compile(\"Sent from my (iPhone|iPod)\")\n\n", "re.compile(\"Sent from my (?:iPhone|iPod)\")\n\nIf you need to capture matches, remove the ?:.\nFyi, your regex didn't work because you are testing for one character out of i,P,h,o,n,e or one character out of i,P,o,d..\n" ]
[ 95, 33 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008609597_python_regex.txt
Q: Cannot access a value in Django I'm trying to access bc_product.eng_name in the following code but it's not working. The foreign key of the bc_product table is in bc_invoice_product table. Can someone point me in the right direction? View def invoice_pdf(request, inv_no): inv = BC_Invoice.objects.select_relat...
Cannot access a value in Django
I'm trying to access bc_product.eng_name in the following code but it's not working. The foreign key of the bc_product table is in bc_invoice_product table. Can someone point me in the right direction? View def invoice_pdf(request, inv_no): inv = BC_Invoice.objects.select_related().get(invoice_no=inv_no) retur...
[ "It looks to me that inv.bc_invoice_product_set.all returns BC_Invoice_Product models and in this case you should use {{ item.product.eng_name }}. \nFrom your models it is visible that foreign key relationship fied toBC_Product in BC_Invoice_Product is product and not bc_product.\nAlso, convention is to have Foreig...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008600416_django_python.txt
Q: What are the differences between ipython and bpython? What does ipython have that bpython lacks and vice versa? How do the two differ? A: If you just want an interactive interpreter, bpython should be fine. Just use it until you miss some feature you liked about IPython. There are lots of features that IPython ...
What are the differences between ipython and bpython?
What does ipython have that bpython lacks and vice versa? How do the two differ?
[ "If you just want an interactive interpreter, bpython should be fine. Just use it until you miss some feature you liked about IPython.\nThere are lots of features that IPython offers over bpython:\n\nSpecial threading options. I like -gthread for experimenting with PyGTK and -pylab for matplotlib.\ndirect invocat...
[ 73, 38 ]
[]
[]
[ "bpython", "ipython", "python" ]
stackoverflow_0004232923_bpython_ipython_python.txt
Q: PIL Draw.text and Lower Resolution I have the following PIL code to print text in an image import os, sys import PIL from PIL import ImageFont from PIL import Image from PIL import ImageDraw img = Image.open("one.jpg") draw = ImageDraw.Draw(img) font = ImageFont.truetype("/usr/share/fonts/truetype/msttcorefon...
PIL Draw.text and Lower Resolution
I have the following PIL code to print text in an image import os, sys import PIL from PIL import ImageFont from PIL import Image from PIL import ImageDraw img = Image.open("one.jpg") draw = ImageDraw.Draw(img) font = ImageFont.truetype("/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman.ttf",27) draw.text((1...
[ "You need to specify a color for the text:\nimport os\nimport sys\nimport ImageFont\nimport Image\nimport ImageDraw\n\nimg = Image.open(\"two.jpg\")\ndraw = ImageDraw.Draw(img) \nfont = ImageFont.truetype(\"/usr/share/fonts/truetype/msttcorefonts/Times_New_Roman.ttf\",27)\ndraw.text((100, 100), \"test test test\...
[ 2 ]
[]
[]
[ "imaging", "python", "python_imaging_library" ]
stackoverflow_0008609857_imaging_python_python_imaging_library.txt
Q: pygame class structure My goal is to make a module that will make a grid on a pygame canvas and allow you to highlight boxes by their x and y coords. Here is a simple example usage. from grid import Grid g = Grid(100, 100, 10) # width and height in cells, cell width in pixels g.highlightBox(2, 2, (0, 255, 0)) # ...
pygame class structure
My goal is to make a module that will make a grid on a pygame canvas and allow you to highlight boxes by their x and y coords. Here is a simple example usage. from grid import Grid g = Grid(100, 100, 10) # width and height in cells, cell width in pixels g.highlightBox(2, 2, (0, 255, 0)) # cell x and y, rgb color tupl...
[ "For starters, I wouldn't put the game loop inside the initialization function; find some other place for it. To solve this, simply put the code you want to execute in the game loop, next to the code for handling events:\nrunning = True\nwhile running:\n event = pygame.event.poll()\n if event.type == pygame.Q...
[ 1, 1, 0 ]
[]
[]
[ "pygame", "python", "refactoring" ]
stackoverflow_0008607513_pygame_python_refactoring.txt
Q: how to put new line or format in send_mail's plain text in django? how can I put a new line or format in the send_mail's plain message in django? i try this one but it wont work: from django.core.mail import send_mail send_mail('Title!', '<h1>message : message here</h1> <br> message : message', 'myemail@sample.co...
how to put new line or format in send_mail's plain text in django?
how can I put a new line or format in the send_mail's plain message in django? i try this one but it wont work: from django.core.mail import send_mail send_mail('Title!', '<h1>message : message here</h1> <br> message : message', 'myemail@sample.com', ['toemail@sample.com']) do anyone have an idea about my situation? ...
[ "Why not just use Django's template loader to render a text file as a string to insert into your email, and attache the HTML as the alternative content?\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import render_to_string\n\ndef send_message(request):\n context = {'foo' : 'ba...
[ 2 ]
[]
[]
[ "django", "python", "sendmail" ]
stackoverflow_0008601470_django_python_sendmail.txt
Q: Sending commands from one xterm window to another with Python So I have a Python app that starts different xterm windows and in one window after the operation is finished it asks the user "Do you want to use these settings? y/n". How can I send y to that xterm window, so that the user doesn't needs to type anythin...
Sending commands from one xterm window to another with Python
So I have a Python app that starts different xterm windows and in one window after the operation is finished it asks the user "Do you want to use these settings? y/n". How can I send y to that xterm window, so that the user doesn't needs to type anything. Thanks
[ "If you are on linux (kde) and you just want to control the xterms by sending commands between them, you could try using dcop: \n\nhttp://www.linuxjournal.com/content/start-and-control-konsole-dcop\nhttp://www.riverbankcomputing.co.uk/static/Docs/PyKDE3/dcopext.html\n\nOtherwise you would need to actually use an in...
[ 2 ]
[]
[]
[ "python", "xterm" ]
stackoverflow_0008609855_python_xterm.txt
Q: How can you use Python to fill out HTML forms that also have Javascript? I am making a python program that automatically enters information into a form on a website. I looked at a module called mechanize at first but then I realized that it didn't support javascript. Is there any way to take a piece of information...
How can you use Python to fill out HTML forms that also have Javascript?
I am making a python program that automatically enters information into a form on a website. I looked at a module called mechanize at first but then I realized that it didn't support javascript. Is there any way to take a piece of information and insert it into a "form" on a website that uses javascript? The website I ...
[ "I think probably the best way to do this is to use a framework that can operate through a browser. There are several options, but the most pythonic is windmill http://www.getwindmill.com/\nI've found it useful on a number of projects.\n" ]
[ 1 ]
[]
[]
[ "forms", "html", "javascript", "mechanize", "python" ]
stackoverflow_0008610043_forms_html_javascript_mechanize_python.txt
Q: Python GTK+ Canvas I'm currently learning GTK+ via PyGobject and need something like a canvas. I already searched the docs and found two widgets that seem likely to do the job: GtkDrawingArea and GtkLayout. I need a few basic functions like fillrect or drawline ... In fact these functions are available from c but ...
Python GTK+ Canvas
I'm currently learning GTK+ via PyGobject and need something like a canvas. I already searched the docs and found two widgets that seem likely to do the job: GtkDrawingArea and GtkLayout. I need a few basic functions like fillrect or drawline ... In fact these functions are available from c but I couldn't find directio...
[ "In order to illustrate my points made in the comments, let me post a quick'n'dirty PyGtk example that uses a GtkDrawingArea to create a canvas and paints into it using cairo\nCORRECTION: you said PyGObject, that is Gtk+3, so the example is as follows (the main difference is that there is no expose event, instead ...
[ 13 ]
[]
[]
[ "canvas", "gtk", "pygobject", "python", "user_interface" ]
stackoverflow_0008608686_canvas_gtk_pygobject_python_user_interface.txt
Q: Capturing Scapy function output in Python I am trying to capture the output of a scapy function (traceroute) to a string in a python script. I understand I need to pipe this function to stdout (as you do with subproces.call() but unsure how to do this using scapy, is anybody able to provide any assistance? I am ne...
Capturing Scapy function output in Python
I am trying to capture the output of a scapy function (traceroute) to a string in a python script. I understand I need to pipe this function to stdout (as you do with subproces.call() but unsure how to do this using scapy, is anybody able to provide any assistance? I am new to Python. Relevent code below. #!/usr/bin/en...
[ "You can also call traceroute like this:\ntrace, _ = traceroute(\"www.example.org\", verbose=0)\n# trace.get_trace() returns a rather impractical format, so we need\n# to convert it. First, we only want the first trace available\nhosts = trace.get_trace().values()[0]\n\n# hosts will be in the format { 1: (\"1.2.3.4...
[ 2, 0 ]
[]
[]
[ "python", "scapy" ]
stackoverflow_0008610172_python_scapy.txt
Q: Python comparing two massive sets of data in the MOST efficient method possible I have to compare massive database dumps in xls format to parse for changes day-to-day (gross, right?). I'm currently doing this in the most backwards way possible, and using xlrd to turn the xls into csv files, and then I'm running di...
Python comparing two massive sets of data in the MOST efficient method possible
I have to compare massive database dumps in xls format to parse for changes day-to-day (gross, right?). I'm currently doing this in the most backwards way possible, and using xlrd to turn the xls into csv files, and then I'm running diffs to compare them. Since it's a database, and I don't have a means of knowing if th...
[ "\nShould I be using sets? \n\nProbably not. The question is too vague to answer, however.\n\nAnd once I've loaded 75+ thousand lines of this database file into a \"set\", is my ram usage going to be hysterical?\n\nNo. 75000 objects isn't much. This isn't massive. It's not even close to massive.\nPython offers ...
[ 3, 2, 0 ]
[]
[]
[ "compare", "database", "diff", "python", "set" ]
stackoverflow_0008609737_compare_database_diff_python_set.txt
Q: yapsy doesn't load plugin correctly I am using yapsy for a python apps. i wrote a new plugin for my app and put it into the same folder where all the other plugins are my plugins all inherit from a plugin class called doctypes which is in general.interfaces the doctype class inherits from the IPlugin class again a...
yapsy doesn't load plugin correctly
I am using yapsy for a python apps. i wrote a new plugin for my app and put it into the same folder where all the other plugins are my plugins all inherit from a plugin class called doctypes which is in general.interfaces the doctype class inherits from the IPlugin class again all plugins load correctly but for the new...
[ "I'm yapsy's main developer and I've just come across this message...\nThough I guess after 4 months you went for something else but anyway.\nThe first thing I'd like to point to is that it could be best if you filled a bug report on yapsy's tracker at:\nhttps://sourceforge.net/tracker/?group_id=208383\nAnd if you ...
[ 1 ]
[]
[]
[ "plugins", "python" ]
stackoverflow_0006986563_plugins_python.txt
Q: How to see mutual friendships in a facebook group? Given an id of any facebook group, using FQL I can fetch all the members of that group, if I am a member of that group. I can also see who of my friends is in the same group as me, that is also not a problem. Now, I need to see of all of the group members, who of ...
How to see mutual friendships in a facebook group?
Given an id of any facebook group, using FQL I can fetch all the members of that group, if I am a member of that group. I can also see who of my friends is in the same group as me, that is also not a problem. Now, I need to see of all of the group members, who of them is friends, I mean, if there are 2 group members in...
[ "Without each of those friends giving you access to view who their friends are, it's impossible. If Facebook allowed this to happen without a friend granting you that access, then I'm going go scream from the hills about a HUGE security hole.\n" ]
[ 1 ]
[]
[]
[ "facebook", "facebook_fql", "python" ]
stackoverflow_0008608843_facebook_facebook_fql_python.txt
Q: PyQt mimeData to string conversion: How do I eliminate some spaces, but not all of them? I'm converting a mimeData object to a human-readable string when it gets dropped onto another widget. That's all working fine, with the exception of a slight spacing issue. Here's the code: import re event.accept() format = "...
PyQt mimeData to string conversion: How do I eliminate some spaces, but not all of them?
I'm converting a mimeData object to a human-readable string when it gets dropped onto another widget. That's all working fine, with the exception of a slight spacing issue. Here's the code: import re event.accept() format = "application/x-qabstractitemmodeldatalist" data = event.mimeData().data(format) pattern = re.co...
[ "I guess you could use something like this:\n>>> re.sub('\\W+', ' ', 'some space here')\n'some space here'\n\nIt would replace every chunk of whitespace with a single space.\nAlso see here: A simple way to remove multiple spaces in a string in Python\n", "It looks like double spaces are being placed between eve...
[ 0, 0, 0 ]
[]
[]
[ "mime_types", "pyqt", "pyqt4", "python" ]
stackoverflow_0008609794_mime_types_pyqt_pyqt4_python.txt
Q: Python3 plugin system I'm trying to create a plugin framework similar to yapsy (unfortunately yapsy is not python3 compatible). My code looks like this: root main.py plugins/ __init__.py PluginManager.py UI/ __init__.py textui.py In PluginManager.py I defined the f...
Python3 plugin system
I'm trying to create a plugin framework similar to yapsy (unfortunately yapsy is not python3 compatible). My code looks like this: root main.py plugins/ __init__.py PluginManager.py UI/ __init__.py textui.py In PluginManager.py I defined the following class: class Plugi...
[ "Sorry, this is certainly not a direct answer to your question but if you're trying to develop something very close to yapsy for python3, then you may be interested by the new version of yapsy in which I've released a couple of python3-compatible packages:\nhttps://sourceforge.net/projects/yapsy/files/Yapsy-1.9/\n(...
[ 5, 2, 1 ]
[]
[]
[ "plugin_architecture", "python" ]
stackoverflow_0008567425_plugin_architecture_python.txt
Q: How to get SMS sender info using python? I'm using Twilio and Django for an SMS application (I started learning Python yesterday, be gentle). Here's what I need help with: When Twilio sends an incoming SMS message to my URL, I want my app to automatically add the incoming phone number, date/time, and incoming mess...
How to get SMS sender info using python?
I'm using Twilio and Django for an SMS application (I started learning Python yesterday, be gentle). Here's what I need help with: When Twilio sends an incoming SMS message to my URL, I want my app to automatically add the incoming phone number, date/time, and incoming message to some lists. How do I do that? Thanks!
[ "Twilio sends it as the 'From' parameter when it requests your URL. The documentation is at: http://www.twilio.com/docs/api/twiml/sms/message\nIt will be similar to this code, I wrote this in webapp with python (not Django).\nclass MainHandler(webapp.RequestHandler): \n\n def get(self):\n model = Storage()\n ...
[ 2, 0 ]
[]
[]
[ "django", "python", "sms", "twilio" ]
stackoverflow_0006852488_django_python_sms_twilio.txt
Q: Differences in separation of static and stateful code in different languages I've noticed that Java, Python, Perl, and Haskell/Clojure have distinctively different treatment of static functions. In particular, 1) What are the idiomatic differences in the way static functions are implemented and utilized in diffe...
Differences in separation of static and stateful code in different languages
I've noticed that Java, Python, Perl, and Haskell/Clojure have distinctively different treatment of static functions. In particular, 1) What are the idiomatic differences in the way static functions are implemented and utilized in different languages. 2) Do some of these languages have "more complete" separation and ...
[ "The relevant distinction may be the programming paradigm emphasized by language. Functional languages such as Haskell & Clojure aim to eliminate side effects and emphasize determinism; encapsulating mutability or state in thinks like monads. This is in contrast to Imperative languages. Perl & PHP are multi-paradig...
[ 1 ]
[]
[]
[ "java", "perl", "php", "python", "static" ]
stackoverflow_0008611211_java_perl_php_python_static.txt
Q: Importing tkinter in Python2.7 on Mac I recently installed Python2.7 on MacOs 10.6.8. I'm having a problem importing tkinter. I keep gettig this 'no matching architecture in universal wrapper' message which means that the version of Tkinter is incorrect. What I did, I followed the instructions here, downloaded Ac...
Importing tkinter in Python2.7 on Mac
I recently installed Python2.7 on MacOs 10.6.8. I'm having a problem importing tkinter. I keep gettig this 'no matching architecture in universal wrapper' message which means that the version of Tkinter is incorrect. What I did, I followed the instructions here, downloaded ActiveTcl 8.5.11 for 32/64bits MacOs architec...
[ "You can install python which can support both 32bit & 64 bit architecture from\nhttp://python.org/download/releases/2.7.2/\nAlso after installing TCL from the link that you have mentioned. You can try the following to check which architecture is suitable\narch -i386 /path/to/python/executable\nfrom Tkinter import ...
[ 2 ]
[]
[]
[ "eclipse", "python", "python_2.7", "tkinter" ]
stackoverflow_0008611497_eclipse_python_python_2.7_tkinter.txt
Q: LinkedIn API OAuth issue This is my first time using the LinkedIn API. I am using Python. I am exactly following the steps listed here: https://developer.linkedin.com/documents/getting-oauth-token-python Everything goes well until I try to get the PIN for the access token. I type into my browser: "https://www.link...
LinkedIn API OAuth issue
This is my first time using the LinkedIn API. I am using Python. I am exactly following the steps listed here: https://developer.linkedin.com/documents/getting-oauth-token-python Everything goes well until I try to get the PIN for the access token. I type into my browser: "https://www.linkedin.com/uas/oauth/authorize?o...
[ "I apologize for not seeing this sooner. The code on that page has been restored and you can download it now without issue. \nhttps://developer.linkedin.com/documents/getting-oauth-token-python\nIf it's still not working, please let us know (I'll check back here, or you can post in our forums). I use essentially...
[ 1 ]
[]
[]
[ "linkedin", "oauth", "python" ]
stackoverflow_0008015934_linkedin_oauth_python.txt
Q: "None" given when attempting to return the value of dict in Python I'm trying to return the values of a dict when creating an instance of a class in Python, but I keep getting "None" returned instead. I'm very new to Python, so I'm sure there is an easy answer to this one. After running the below: class TestTwo(o...
"None" given when attempting to return the value of dict in Python
I'm trying to return the values of a dict when creating an instance of a class in Python, but I keep getting "None" returned instead. I'm very new to Python, so I'm sure there is an easy answer to this one. After running the below: class TestTwo(object): def __init__(self): self.attributes = { ...
[ "Only results() returns something. You need to pass its return value along the call chain by returning it in the other functions if you want them to return something, too:\ndef your_age(self):\n self.attributes['age'] = raw_input(\"What is your age? > \")\n return self.your_name()\n\ndef your_name(self):\n ...
[ 6, 0 ]
[]
[]
[ "class", "dictionary", "oop", "python", "return" ]
stackoverflow_0008611592_class_dictionary_oop_python_return.txt
Q: Deploying existing Django app on Heroku Following the Heroku tutorial but I have already created a rather complex Django app that I want to upload. I have copied it to a fresh folder and issued git init successfully, along with adding the files to a commit. I do heroku create --stack cedar so I get a site then iss...
Deploying existing Django app on Heroku
Following the Heroku tutorial but I have already created a rather complex Django app that I want to upload. I have copied it to a fresh folder and issued git init successfully, along with adding the files to a commit. I do heroku create --stack cedar so I get a site then issue the git push heroku master. I get the foll...
[ "Chris,\nSpecifically for Django heroku expects you to check in the directory that your Django project lives in (this directory should live at the same level as your requirements.txt). An ls might look something like:\n$ ls\nrequirements.txt appfolder\n$ ls appfolder\n__init__.py manage.py settings.py urls.p...
[ 19, 1 ]
[]
[]
[ "django", "git", "heroku", "python" ]
stackoverflow_0007974902_django_git_heroku_python.txt
Q: beaker cache regions for class methods - use it not as a decorator? I have multiple classes of the following structure: class Thing(Base): id = Column(Integer, primary_key=True) @cache_region('short_term', 'get_children') def get_children(self, childrentype=None): return DBSession.query()... ...
beaker cache regions for class methods - use it not as a decorator?
I have multiple classes of the following structure: class Thing(Base): id = Column(Integer, primary_key=True) @cache_region('short_term', 'get_children') def get_children(self, childrentype=None): return DBSession.query()... The problem however is that beaker will cache get_children() in the same ...
[ "I'm retarded. I should be doing something like:\nclass Thing(Base):\n id = ...\n\n def get_children(self, childrentype, invalidate=False):\n if invalidate:\n region_invalidate(_get_children, None, self.id, childrentype)\n\n @cache_region('short_term', 'get_children')\n def _ge...
[ 3 ]
[]
[]
[ "beaker", "pyramid", "python" ]
stackoverflow_0008611584_beaker_pyramid_python.txt
Q: How can one change the size of SVGFIG plots I'm using the Python SVG wrapper SVGFIG. Here's a code snippet: dots = zip(x,y) dots = svgfig.Dots(dots,0.4,0.4) line = svgfig.Line(0,cs[i,1],250,cs[i,1]+cs[i,0]*250,stroke_width="0.25pt") text = svgfig.Text(200,20,'Band'+str(i+1)) sp = svgfig.Plot(0,250,0,25...
How can one change the size of SVGFIG plots
I'm using the Python SVG wrapper SVGFIG. Here's a code snippet: dots = zip(x,y) dots = svgfig.Dots(dots,0.4,0.4) line = svgfig.Line(0,cs[i,1],250,cs[i,1]+cs[i,0]*250,stroke_width="0.25pt") text = svgfig.Text(200,20,'Band'+str(i+1)) sp = svgfig.Plot(0,250,0,250,dots,line,text,x=15,y=10) The default canvas...
[ "It looks like it's _canvas_defaults, not canvas_defaults:\n>>> svgfig._canvas_defaults\n\n{'font-family': ['Helvetica',\n 'Arial',\n 'FreeSans',\n 'Sans',\n 'sans',\n 'sans-serif'],\n 'height': '400px',\n 'style': {'fill': 'none',\n ...
[ 3 ]
[]
[]
[ "python", "svg" ]
stackoverflow_0008602257_python_svg.txt
Q: Learn Python 2 or 3? I already bought a good book on Python 2.5. Should I return it and get a book on 3.1 instead? that I know this question has already been asked, but I wanted a more up-to-date answer. A: Linky: Python2orPython3 Synopsis: Python 2.5 is old but the general consensus is Python 3 if you don't ha...
Learn Python 2 or 3?
I already bought a good book on Python 2.5. Should I return it and get a book on 3.1 instead? that I know this question has already been asked, but I wanted a more up-to-date answer.
[ "Linky: Python2orPython3\nSynopsis:\nPython 2.5 is old but the general consensus is Python 3 if you don't have any dependencies or a large code base already in production, if this is the case then writing more future ready code might be a better option. On the other hand bigger projects have already started the lon...
[ 4, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008611681_python.txt
Q: How to pass (multiple) regex parsed function parameters to a python function I'm trying to build a python class that parses a string and if it matches a regex that looks like a function call attempt to call that function on the class, passing in any parameters. For example a string like "foo("a", 20")" would trans...
How to pass (multiple) regex parsed function parameters to a python function
I'm trying to build a python class that parses a string and if it matches a regex that looks like a function call attempt to call that function on the class, passing in any parameters. For example a string like "foo("a", 20")" would translate to something like self.foo("a", 20). Here is the code that I have so far.. cl...
[ "You can use the * operator to explode a tuple into separate arguments to a function. For example:\ndef f(a, b, c):\n print a, b, c\n\nIf I call f(...) like this:\nf((1,2,3))\n\nI get an error:\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: f() takes exactly 3 arguments ...
[ 1 ]
[]
[]
[ "eval", "python" ]
stackoverflow_0008611979_eval_python.txt
Q: wxPython: text alignment does not work For some reasons the wx.ALIGN_* does not align anything on Ubuntu, while it works on Mac OS X: self.static_text = wx.StaticText(self, -1, 'hello, world', pos=(0,0), size=(300,30), style=wx.ALIGN_CENTER) Any idea, what could it be? Update: Th...
wxPython: text alignment does not work
For some reasons the wx.ALIGN_* does not align anything on Ubuntu, while it works on Mac OS X: self.static_text = wx.StaticText(self, -1, 'hello, world', pos=(0,0), size=(300,30), style=wx.ALIGN_CENTER) Any idea, what could it be? Update: This was tried with wxPython 2.8.12.1 on Mac O...
[ "I have test this code snippet in Win 7 environment, one error is surfaced about the argument usage: SyntaxError: non-keyword arg after keyword arg\nself.static_text = wx.StaticText(self, -1, 'hello, world', pos=(0,0), size=(300,30), style = wx.ALIGN_CENTER)\n\nCause you have used two keyword args (\"pos\" and \"si...
[ 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0008587060_python_wxpython_wxwidgets.txt
Q: How do range queries work in Python's kd-tree? What is a range query over a kdtree and how is it done by python? A: Assuming you are talking about the k-d tree in scipy.spatial, there are a couple of range queries. Which is to say, there are multiple functions that take as their input one or more points and a ra...
How do range queries work in Python's kd-tree?
What is a range query over a kdtree and how is it done by python?
[ "Assuming you are talking about the k-d tree in scipy.spatial, there are a couple of range queries. Which is to say, there are multiple functions that take as their input one or more points and a radius and query the tree for all points within the radius of the query points. \nThe two most obvious functions are que...
[ 2 ]
[]
[]
[ "kdtree", "python", "range" ]
stackoverflow_0003493061_kdtree_python_range.txt
Q: Where do I begin learning to program bots? I don't know what they're called but I want to learn to program bots that perform tasks within a game or software. But I have no idea how to even make a program that does stuff on other programs/software/games. Are their any good books on the subject? If it makes a differ...
Where do I begin learning to program bots?
I don't know what they're called but I want to learn to program bots that perform tasks within a game or software. But I have no idea how to even make a program that does stuff on other programs/software/games. Are their any good books on the subject? If it makes a difference I'm using a Linux OS. I know Python and I b...
[ "There are many tools for sending artificial input. My favorite one only works on Windows.\nFor the cross platform, including Linux, there is a library called autopy. As you can guess, it's a Python library and it allows you to access your keyboard and mouse through Python objects.\n", "If you want to automate ...
[ 3, 1 ]
[]
[]
[ "automation", "c", "linux", "python", "ubuntu" ]
stackoverflow_0008612254_automation_c_linux_python_ubuntu.txt
Q: How to import Python code from a source file? I was hesitant about asking this because I've seen similar questions with overly complicated answers. The question I actually want answered to was closed on account of being "vague" and "not a real question", so I will be as specific as possible. I have an object calle...
How to import Python code from a source file?
I was hesitant about asking this because I've seen similar questions with overly complicated answers. The question I actually want answered to was closed on account of being "vague" and "not a real question", so I will be as specific as possible. I have an object called "line" in a file called "line.py". I want to crea...
[ "While you could append to the python path for a particular file using:\nimport sys\nsys.path.append('pathtoModule')\n\nIf they are in the same folder, (not a module, as you lack an init.py), you can simply import from the line module by doing:\nfrom line import Line\nclass LineSegment(line):\n\nNaming convention s...
[ 4, 1, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0008612213_import_python.txt
Q: Django Debug "IndexError: list index out of range" I am working on a django project for a while and all over sudden the django's debug stopped working displaying the following exception instead of showing the traceback of the bug in my code. This exception seems to be a problem in the debugger itself and has been ...
Django Debug "IndexError: list index out of range"
I am working on a django project for a while and all over sudden the django's debug stopped working displaying the following exception instead of showing the traceback of the bug in my code. This exception seems to be a problem in the debugger itself and has been discussed in several places indicating that it could be ...
[ "I could not find the solution to the problem but I found a way at least to get more informative tracebacks by just using a different debugger.\nGo here: https://github.com/dcramer/django-devserver\n-do a pip install on the devserver\n-a pip install of werkzeug\n-add dev-server to your apps in settings.py\n-start d...
[ 0 ]
[]
[]
[ "debugging", "django", "exception", "python" ]
stackoverflow_0008601446_debugging_django_exception_python.txt
Q: What does object's __init__() method do in python? While reading the code of OpenStack and I encountered this. A class named 'Service' inherits the base class 'object', and then in Service's __init__() method, object's __init__ is called. The related code looks like this: the class definition: class Service(object...
What does object's __init__() method do in python?
While reading the code of OpenStack and I encountered this. A class named 'Service' inherits the base class 'object', and then in Service's __init__() method, object's __init__ is called. The related code looks like this: the class definition: class Service(object): and Service's init method definition: def __init__(s...
[ "The short answer is that object.__init__() method does nothing except check that no arguments have been passed in. See the source for details. \nWhen called on an instance of Service, the super() call will delegate to object.__init__() and nothing will happen.\nHowever, when called on an instance of a subclass of...
[ 16, 3, 1 ]
[]
[]
[ "init", "object", "python" ]
stackoverflow_0008611712_init_object_python.txt
Q: Is a Django session thread safe? I am storing a dictionary in a Django Session which is accessible by multiple threads. All threads can update that dictionary, threads also get values from dictionary in order to run the process. I want to know does the Django Session is thread safe or I have to use locks or semap...
Is a Django session thread safe?
I am storing a dictionary in a Django Session which is accessible by multiple threads. All threads can update that dictionary, threads also get values from dictionary in order to run the process. I want to know does the Django Session is thread safe or I have to use locks or semaphores? Typical example: Thread1: threa...
[ "The request.session object returned will be a new one for every request, accessing the same storage. Furthermore, they are loaded from the storage at request time and saved back at response time. So if you wish to transfer information from a long-running thread to another request, you need to save it in the long-r...
[ 9, 2, 0 ]
[ "The basic types in Python are generally thread safe thanks to the global interpreter lock. This lock is released in some situations (for example when doing I/O) to allow other threads access. This means that you (the application) will have to maintain a consistant state across calls that could release the GIL. Exa...
[ -1, -1 ]
[ "django", "python", "python_multithreading", "thread_safety" ]
stackoverflow_0008212050_django_python_python_multithreading_thread_safety.txt
Q: How do I know if query is executed correctly or not while executing the cursor.execute()? query = "delete from mytable where id =10" cursor = connection.cursor() cursor.execute(query) It returns None but I want to know the response of the query. How do I get the result? Same as insert statement also. Could anyone...
How do I know if query is executed correctly or not while executing the cursor.execute()?
query = "delete from mytable where id =10" cursor = connection.cursor() cursor.execute(query) It returns None but I want to know the response of the query. How do I get the result? Same as insert statement also. Could anyone give me the solution?
[ "I had a quick look at docs:\nDjango / DB docs: https://docs.djangoproject.com/en/dev/topics/db/sql/\nThe object django.db.connection represents the default database connection, and django.db.transaction represents the default database transaction. To use the database connection, call connection.cursor() to get a c...
[ 1 ]
[]
[]
[ "django", "mysql", "postgresql", "python" ]
stackoverflow_0008613005_django_mysql_postgresql_python.txt
Q: Can an attribute attached to a Django model get information about a given record? I have a class object attached as an attribute to a Django model. For the purposes of the question, let's assume it looks something like: class Foo(object): def bar(self): print "Does things here" class Task(models.Model...
Can an attribute attached to a Django model get information about a given record?
I have a class object attached as an attribute to a Django model. For the purposes of the question, let's assume it looks something like: class Foo(object): def bar(self): print "Does things here" class Task(models.Model): name = models.CharField(max_length=30) user = models.ForeignKey(User, relate...
[ "It sounds like you might want a descriptor. They're classes that implement special methods that are called when getting or setting, and are passed the parent instance.\n", "You would make Foo a custom manager so that it knows about Task inherently.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008612391_django_python.txt
Q: what is the way to connect postgresql with android in ubuntu I am using postgresql in ubuntu, and now i am working on python. I want to connect postgresql with an android application. Is there any way to connect postgresql with an android application? Any reply would be appreciated. A: Better w...
what is the way to connect postgresql with android in ubuntu
I am using postgresql in ubuntu, and now i am working on python. I want to connect postgresql with an android application. Is there any way to connect postgresql with an android application? Any reply would be appreciated.
[ "Better way is to Use RestFUL API or WebService as front end for your Android device to connect to your PostgreSQL backend. I am not sure if it is possible to directly connect your android device to postgre SQL.\n" ]
[ 2 ]
[]
[]
[ "android", "postgresql", "python", "ubuntu_10.04", "web_services" ]
stackoverflow_0008613246_android_postgresql_python_ubuntu_10.04_web_services.txt
Q: Python3 porting: TypeError: unorderable types: dict() < int() I have this piece of code that is working fine in python 2.7. "dist" is a dictionary of number and "min_dist" is just a number. for v in vertices: if dist[v.node_id] < min_dist: min_dist = dist[v.node_id] cur_min = v Now I am trying...
Python3 porting: TypeError: unorderable types: dict() < int()
I have this piece of code that is working fine in python 2.7. "dist" is a dictionary of number and "min_dist" is just a number. for v in vertices: if dist[v.node_id] < min_dist: min_dist = dist[v.node_id] cur_min = v Now I am trying to run it under python 3.2 and it gives me this error: if dist...
[ "Your code is \"wrong\" in Python 2 as well. It makes no sense to compare a dictionary to an integer. It's like asking if a color is bigger than a number, it simply makes no sense.\nPython 2 allows comparisons of different types like this, and will always say that a dictionary is larger than a number, which is arbi...
[ 10, 2 ]
[]
[]
[ "porting", "python", "python_3.x" ]
stackoverflow_0008613515_porting_python_python_3.x.txt
Q: How to load Firefox with javascript disable when running Selenium Webdriver (Python) tests? I heard one can load a custom Firefox profile when starting webdriver, but I've yet to find a way to do that. The Python binding documentation doesn't state it very clearly. I need to start up Firefox without JS because the...
How to load Firefox with javascript disable when running Selenium Webdriver (Python) tests?
I heard one can load a custom Firefox profile when starting webdriver, but I've yet to find a way to do that. The Python binding documentation doesn't state it very clearly. I need to start up Firefox without JS because the site I'm testing has a lot of ads injected by Google and some are very slow to load, making the ...
[ "You can use the -firefoxProfileTemplate command line option when starting the Selenium server. But it seems rather counterproductive to disable javascript when testing how browsers behave on your site (unless your site doesn't have any scripts of its own) - you should rather use adblock, or disable the IP used by ...
[ 0 ]
[]
[]
[ "automated_tests", "javascript", "python", "selenium" ]
stackoverflow_0008613440_automated_tests_javascript_python_selenium.txt
Q: How i can set the increasing of enumerate, that depends on condition? I have got the following loop^ i = 0 for var in vars: if var[ "ID" ] != 0 and var[ "ID" ] & 1: print i, var[ "ID" ] i += 1 Can I use enumerate for this loop instead of counter i ? How i can set the increasing of enum...
How i can set the increasing of enumerate, that depends on condition?
I have got the following loop^ i = 0 for var in vars: if var[ "ID" ] != 0 and var[ "ID" ] & 1: print i, var[ "ID" ] i += 1 Can I use enumerate for this loop instead of counter i ? How i can set the increasing of enumerate, that depends on this condition: if var[ "ID" ] != 0 and var[ "ID" ]...
[ "You may use filter:\n>>> vs = [{'ID': 1}, {'ID': 4}]\n>>> for i, v in enumerate(filter(lambda x: x['ID'] & 1, vs)):\n... print i, v\n...\n0 {'ID': 1}\n\n", "No, I don't think you can use enumerate to simplify this code (not without thinning vars first, so that enumerate would only apply to elements that matc...
[ 3, 2 ]
[]
[]
[ "enumerate", "python" ]
stackoverflow_0008613873_enumerate_python.txt
Q: Get text from a single element of the etree in XML The code below works fine, but isn't there any pythonic way to get the same functionality? I just want to parse XML and get text from several elements (name, name_status, url). from lxml import etree from urllib2 import urlopen def ask_CoL(url): tree = etree....
Get text from a single element of the etree in XML
The code below works fine, but isn't there any pythonic way to get the same functionality? I just want to parse XML and get text from several elements (name, name_status, url). from lxml import etree from urllib2 import urlopen def ask_CoL(url): tree = etree.parse(urlopen(url)) tn=[ el.get('total_number_of_res...
[ "You could simplify both interface and implementation:\nimport urllib2\nfrom xml.etree import cElementTree as etree\n\ndef f(url):\n tree = etree.parse(urllib2.urlopen(url)) \n el = tree.find('results')\n if el is not None:\n lst = [el.findtext(tag) or '' for tag in \"name name_status url\".s...
[ 1 ]
[]
[]
[ "elementtree", "lxml", "python" ]
stackoverflow_0008612469_elementtree_lxml_python.txt
Q: Getting ValueError as response to http request in Django framework When i access this url: http://localhost:8000/ProjectOverview/proj_view/15/ Django tells me that the format is in complete: Request Method: GET Request URL: http://localhost:8000/ProjectOverview/proj_view/15/ Django Version: 1.3.1 Excep...
Getting ValueError as response to http request in Django framework
When i access this url: http://localhost:8000/ProjectOverview/proj_view/15/ Django tells me that the format is in complete: Request Method: GET Request URL: http://localhost:8000/ProjectOverview/proj_view/15/ Django Version: 1.3.1 Exception Type: ValueError Exception Value: incomplete format Excepti...
[ "You need to make your % become %s (if it's an string) or %d (if it's an integer):\ndef proj_view(request, cust):\n return HttpResponse(\"project overview for cust: %s.\" % cust) \n\nSee python string-formatting.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008613967_django_python.txt
Q: In multiprocess module of python , how to find which worker process has executed the job Is there any way to find out , which worker process among the Pool has executed a specific job . For example, def start_exe(): #execute some bunch of statements if __name__ == '__main__': p = Pool(5) result = p.a...
In multiprocess module of python , how to find which worker process has executed the job
Is there any way to find out , which worker process among the Pool has executed a specific job . For example, def start_exe(): #execute some bunch of statements if __name__ == '__main__': p = Pool(5) result = p.apply.async(start_exe) print result.get()
[ "I don't see any API for that, but you can embed the name of the process that did the job in the result:\nfrom multiprocessing import Pool, current_process\n\ndef start_exe():\n return 'done', current_process().name\n\nif __name__ == '__main__':\n p = Pool(5)\n result = p.apply_async(start_exe)\n\n prin...
[ 3 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0008613818_multiprocessing_python.txt
Q: Ways to implement Janrain Engage (RPXNow) on Google App Engine? What a some possible solutions to best implement Janrain Engage (RPX Now) on Google App Engine? A: For a complete solution including sessions, I recommend gae-sessions. The source includes a demo which shows how to integrate the sessions library wi...
Ways to implement Janrain Engage (RPXNow) on Google App Engine?
What a some possible solutions to best implement Janrain Engage (RPX Now) on Google App Engine?
[ "For a complete solution including sessions, I recommend gae-sessions. The source includes a demo which shows how to integrate the sessions library with Janrain/RPX.\nDisclaimer: I wrote gae-sessions, but for an informative comparison of it with alternatives, read this article.\n", "According to this HOWTO, it s...
[ 2, 0, 0 ]
[]
[]
[ "google_app_engine", "janrain", "python", "rpxnow", "session" ]
stackoverflow_0003882610_google_app_engine_janrain_python_rpxnow_session.txt
Q: How to properly log errors/info with Python? I'm building a GUI program that has several a GUI (main) module and 4 different QThread modules. I want to be able to properly log unhandled exceptions and other various information that I specify. So I decided to use the python's built-in logging module. This is what I...
How to properly log errors/info with Python?
I'm building a GUI program that has several a GUI (main) module and 4 different QThread modules. I want to be able to properly log unhandled exceptions and other various information that I specify. So I decided to use the python's built-in logging module. This is what I configured it as: logging.basicConfig(filename="u...
[ "Can you post a full snippet? If I do what you just said, I get a proper log. I'll post my script here (named stackoverflow_8613924.py), for comparison:\nimport logging\n\nlogging.basicConfig(filename=None, format='%(asctime)-6s: %(name)s - %(levelname)s - %(module)s - %(funcName)s - %(lineno)d - %(message)s', leve...
[ 3, 1, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0008613924_logging_python.txt
Q: Automating Review Requests with ReviewBoard and Mercurial using Python hooks Here is my problem: I got a remote mercurial repository where the hook is gonna be setup either incoming or changegroup, and I got a ReviewBoard setup on a different server. The idea is to automate review request tickets generation upon p...
Automating Review Requests with ReviewBoard and Mercurial using Python hooks
Here is my problem: I got a remote mercurial repository where the hook is gonna be setup either incoming or changegroup, and I got a ReviewBoard setup on a different server. The idea is to automate review request tickets generation upon push from devs into the remote repository. Of course, I would need a hook that inv...
[ "Not sure if this is quite what you need, but this is something I use for executing a commit message check in pretty much the same circumstances, it has to check each change and verify information based on the user. In the same way I need to check the user the changelist is for, not the 'pushing' user.\nIt should ...
[ 7 ]
[]
[]
[ "automation", "mercurial", "mercurial_hook", "python", "review_board" ]
stackoverflow_0007675917_automation_mercurial_mercurial_hook_python_review_board.txt
Q: How to pass value to a function I am new to python and doing this homework. I need to create a small program with menu. I was very good 'til now. I am a little bit lost. How can I pass a value to the function? Can you please check if there are any other faults in my code. import turtle as t def how_many(): wh...
How to pass value to a function
I am new to python and doing this homework. I need to create a small program with menu. I was very good 'til now. I am a little bit lost. How can I pass a value to the function? Can you please check if there are any other faults in my code. import turtle as t def how_many(): while True: print " How man...
[ "For how to define and call functions, see the Python tutorial.\nFor code review, try https://codereview.stackexchange.com/\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0008615350_python.txt
Q: Subtract the html Div tags in python How we could subtract the div tags from the Html String in python? For example, My Html DOM is like <html> <div id ="main"> <div id = "child1"> ....(some doms) </div> <div id="child2"> .......(some nested dom) </div> </div> </html> In this structure ...
Subtract the html Div tags in python
How we could subtract the div tags from the Html String in python? For example, My Html DOM is like <html> <div id ="main"> <div id = "child1"> ....(some doms) </div> <div id="child2"> .......(some nested dom) </div> </div> </html> In this structure I need to subtract from "div #main" to "di...
[ "Your question isn't very clear. Are you wanting to get all elements before a certain element?\nimport lxml.html as lh\n\nhtml = \"\"\"\n<div id=\"div1\">\n</div>\n<div id=\"div2\">\n</div>\n\"\"\"\n\ntree = lh.fromstring(html)\n\nfor el in tree.xpath(\"div[@id='div2']/preceding-sibling::div\"):\n print el.attri...
[ 1 ]
[]
[]
[ "beautifulsoup", "dom_manipulation", "html", "lxml", "python" ]
stackoverflow_0008614913_beautifulsoup_dom_manipulation_html_lxml_python.txt
Q: Is it possible to create named functions in Python similar to C macro? Sorry for the confusing title. I would like to do the following: (Similar to defstruct in Lisp) def mkstruct(structname, field_dict): # create a function called "structname" and get/set functions # called "structname_get(s, field_name)"...
Is it possible to create named functions in Python similar to C macro?
Sorry for the confusing title. I would like to do the following: (Similar to defstruct in Lisp) def mkstruct(structname, field_dict): # create a function called "structname" and get/set functions # called "structname_get(s, field_name)" and "structname_set(s, field_name, value)" # Create a struct "lstnode" mks...
[ "This should be a step in the direction of what you want:\ndef mkstruct(name, attrs):\n def init(self):\n self.id = # not sure how you want to get the id\n\n def getattr(self, attr):\n if attr not in attrs:\n raise AttributeError(attr)\n # put your database lookup statement her...
[ 1, 1, 0 ]
[]
[]
[ "function", "macros", "python" ]
stackoverflow_0008576849_function_macros_python.txt
Q: WebApp needs to do something first time only, where to put that logic? Flask or django The web app I am working on needs to perform a first-time setup or initialization, where is a good place to put that logic? I dont want to perform the check if a configuration/setup exists on each request to / or before any req...
WebApp needs to do something first time only, where to put that logic? Flask or django
The web app I am working on needs to perform a first-time setup or initialization, where is a good place to put that logic? I dont want to perform the check if a configuration/setup exists on each request to / or before any request as thats kind of not performant. I was thinking of performing a check if there is a san...
[ "The proper way is creating a CLI script, preferably via Flask-Script if you use Flask (in Django it would be the default manage.py where you can easily add custom commands, too) and defining a function such as init or install:\nfrom flaskext.script import Manager\nfrom ... import app\nmanager = Manager(app)\n@mana...
[ 1 ]
[]
[]
[ "configuration", "django", "flask", "python" ]
stackoverflow_0008614478_configuration_django_flask_python.txt
Q: How to install python module to Nokia Symbian phone? I want to calculate sunrise/sunset times with my Nokia Symbian phone, but the python code for this needs the pytz module. How do i install the pure python module to Nokia Symbian phone? A: Read the "Extending and Embedding PyS60" chapter here: https://garage.m...
How to install python module to Nokia Symbian phone?
I want to calculate sunrise/sunset times with my Nokia Symbian phone, but the python code for this needs the pytz module. How do i install the pure python module to Nokia Symbian phone?
[ "Read the \"Extending and Embedding PyS60\" chapter here: https://garage.maemo.org/frs/download.php/7490/PyS60_2_0_documentation.pdf\nBut I guess you can simply grab all the useful source codes from that pytz module and try to integrate into your mobile project.\n" ]
[ 0 ]
[]
[]
[ "installation", "module", "python", "symbian" ]
stackoverflow_0008551279_installation_module_python_symbian.txt
Q: How to programmatically pair a bluetooth device on Symbian using PyS60? Is there a way to pair up two BT devices using PyS60? Perhaps there is a system API which prompts PIN and communicate with other device so it will appear as Paired device then. Unfortunately can't find this in PyS60 documentation. A: Check o...
How to programmatically pair a bluetooth device on Symbian using PyS60?
Is there a way to pair up two BT devices using PyS60? Perhaps there is a system API which prompts PIN and communicate with other device so it will appear as Paired device then. Unfortunately can't find this in PyS60 documentation.
[ "Check out Bluetooth examples for the \"Mobile Python\" book: http://www.mobilenin.com/mobilepythonbook/examples.html\n" ]
[ 0 ]
[]
[]
[ "bluetooth", "pys60", "python", "symbian" ]
stackoverflow_0006535290_bluetooth_pys60_python_symbian.txt
Q: URL like string parsing in python I need to parse a string which is more or less a url.. for example i have a string which is a URL tempString = "?var1=somevalue1&var2=somevalue2&var3=somevalue3" i need to parse the string tempString and get the value of var1 var2 and var3 from it. What's the best way to get the ...
URL like string parsing in python
I need to parse a string which is more or less a url.. for example i have a string which is a URL tempString = "?var1=somevalue1&var2=somevalue2&var3=somevalue3" i need to parse the string tempString and get the value of var1 var2 and var3 from it. What's the best way to get the value.
[ "Use urlparse.parse_qs.\n", "This is a quick way, but you'd need to prepend a host and path to your example string.\nimport urlparse\n\nscheme, netloc, path, query, fragment = urlparse.urlsplit( url )\nparameters = urlparse.parse_qs( query )\n\n", "Use urlparse. For example, see this.\n", "Well if it were rea...
[ 4, 0, 0, 0 ]
[]
[]
[ "python", "string_parsing" ]
stackoverflow_0008615695_python_string_parsing.txt
Q: Get list of changesets in a changegroup (mercurial python hook) I want a mercurial hook that will run JSLint/PyChecker/etc on all files that are modified. However, I do not have control over all hg clients, and want this to run on push to the master repository (which I have control), so a pretxnchangegroup hook on...
Get list of changesets in a changegroup (mercurial python hook)
I want a mercurial hook that will run JSLint/PyChecker/etc on all files that are modified. However, I do not have control over all hg clients, and want this to run on push to the master repository (which I have control), so a pretxnchangegroup hook on the master seems best. How can I get a list of all changesets that a...
[ "You're right that you want a pretxnchangegroup hook, but you don't want to check all the new revisions -- because people will fix the errors you reject in subsequent changesets but if you're checking all changesets their work will never be accepted!\nInstead either just check all files in all the heads, or use the...
[ 4, 3, 0 ]
[]
[]
[ "hook", "mercurial", "mercurial_hook", "python" ]
stackoverflow_0003621463_hook_mercurial_mercurial_hook_python.txt
Q: Google App Engine + Python - Educational website: Required help of expert Currently I'm running educational website and teaching above 30,000 students. Currently this website is on Google Sites (with Google Apps). Due to few restriction and limitation, I would like to transfer this website to Google App Engine. My...
Google App Engine + Python - Educational website: Required help of expert
Currently I'm running educational website and teaching above 30,000 students. Currently this website is on Google Sites (with Google Apps). Due to few restriction and limitation, I would like to transfer this website to Google App Engine. My requirement is Login system for this website. I've created basic website at ap...
[ "Assuming you don't mind piggybacking on google's app administration functionality, I don't think I can provide a better answer than google themselves. It all looks forgiving enough. Long story short, you need this in your app.yaml:\n- url: <url of restricted page>\nscript: <script to run>\nlogin: admim\n\nHope th...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008615092_google_app_engine_python.txt
Q: error with elif statement This is an example in the Python book I'm reading. When I try to run the program there's an error, and when I check the code for the error elif is highlighted in red. I'm programming in Python 2.5. import random secret = random.randint(1, 99) guess = 0 tries = 0 print "It is a number be...
error with elif statement
This is an example in the Python book I'm reading. When I try to run the program there's an error, and when I check the code for the error elif is highlighted in red. I'm programming in Python 2.5. import random secret = random.randint(1, 99) guess = 0 tries = 0 print "It is a number between 1 and 99. I'll give you s...
[ "Python is indentation sensitive.\nimport random\n\nsecret = random.randint(1, 99)\nguess = 0\ntries = 0\n\nprint \"It is a number between 1 and 99. I'll give you six tries. \"\n\nwhile guess != secret and tries < 6:\n guess = input(\"What's your guess? \")\n if guess < secret:\n print \"Too low!\"\n ...
[ 5, 1, 1 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0008616563_if_statement_python.txt
Q: Remove the Html tags in regex Possible Duplicate: Strip html from strings in python RegEx match open tags except XHTML self-contained tags I have the regex pattern in my python module which removes the html tags from the given string. It doesn't work for this case. Input string: string=<li class=" tal ...
Remove the Html tags in regex
Possible Duplicate: Strip html from strings in python RegEx match open tags except XHTML self-contained tags I have the regex pattern in my python module which removes the html tags from the given string. It doesn't work for this case. Input string: string=<li class=" tal "><h3><a href="/aclk?sa=l&amp;ai=C...
[ "In that case you should use the DOTALL functionality:\np = re.compile(r'<.*?>',re.DOTALL)\n\nshould work.\nBut... you should not use regexes for HTML parsing, see this: https://stackoverflow.com/a/1732454/11621 \nHTH.\n", "Google or search Stackoverflow for HTML and regex - this is a bad idea. You'd be better o...
[ 3, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008616841_python_regex.txt
Q: Can I use Turbogears to develop mobile sites? Is it possible to develop mobile versions of webpages using Turbogears? Can someone please show me an example and how it is done? A: You might want to take a look at tgext.mobilemiddleware it makes available an @expose_mobile decorator that permits to expose a differ...
Can I use Turbogears to develop mobile sites?
Is it possible to develop mobile versions of webpages using Turbogears? Can someone please show me an example and how it is done?
[ "You might want to take a look at tgext.mobilemiddleware it makes available an @expose_mobile decorator that permits to expose a different template engine for mobile devices. It also provides a tg.request.is_mobile attribute that can be used inside controllers to apply different execution paths when a mobile device...
[ 2, 0, 0, 0 ]
[]
[]
[ "mobile_website", "python", "turbogears" ]
stackoverflow_0003493244_mobile_website_python_turbogears.txt
Q: Rendering using OpenSG python bindings Hey!! I'm looking for python bindings for opensg 1.8.. I haven't been able to find it. I have read somethin about pyopengs. Is it still available? I am working on linux platform (ubuntu). If anyone could direct me to it I would be grateful. A: The homepage and source code i...
Rendering using OpenSG python bindings
Hey!! I'm looking for python bindings for opensg 1.8.. I haven't been able to find it. I have read somethin about pyopengs. Is it still available? I am working on linux platform (ubuntu). If anyone could direct me to it I would be grateful.
[ "The homepage and source code is on google code: pyOpenSG Project\nAs one of the creators of pyOpenSG, I can tell you that it is definitely still alive and kicking. We use it in production software all the time. It has become so stable for us though that we don't often update the code base. The python binding g...
[ 1 ]
[]
[]
[ "c++", "python", "rendering" ]
stackoverflow_0005382146_c++_python_rendering.txt
Q: How to install pyclamd with pip pyclamd does not have a setup.py. I want to install it with pip so that I can use pip freeze to create a requirements file. How do you install modules that have no setup.py with pip. A: You can install from source control like this:: pip install svn+http://code.google.com/p/pyclam...
How to install pyclamd with pip
pyclamd does not have a setup.py. I want to install it with pip so that I can use pip freeze to create a requirements file. How do you install modules that have no setup.py with pip.
[ "You can install from source control like this::\npip install svn+http://code.google.com/p/pyclamd/source/browse/#svn%2Ftrunk\n\n" ]
[ 1 ]
[]
[]
[ "pip", "python" ]
stackoverflow_0008617068_pip_python.txt
Q: Django and/or Ladon (exposing methods to several internet service protocols) Is there an easy way to export django project functionality with multiple protocols like REST, SOAP (with wsdl file) and RPC? Or may be it will be beter to use Ladon and write functionality without using Django? A: Absolutely. There is ...
Django and/or Ladon (exposing methods to several internet service protocols)
Is there an easy way to export django project functionality with multiple protocols like REST, SOAP (with wsdl file) and RPC? Or may be it will be beter to use Ladon and write functionality without using Django?
[ "Absolutely. There is at least tastypie and piston but there are also many others.\n" ]
[ 1 ]
[]
[]
[ "django", "python", "rest", "rpc", "soap" ]
stackoverflow_0008617467_django_python_rest_rpc_soap.txt
Q: How to add mysql-python image path to crontab Crontab always try to load mysql-python image from my home directory, while the library image is actually in /Library/Python/2.7/site-packages/MySQL_python... How can I point crontab to the right place? Without reinstall mysql-python as a static library? I work on MAC ...
How to add mysql-python image path to crontab
Crontab always try to load mysql-python image from my home directory, while the library image is actually in /Library/Python/2.7/site-packages/MySQL_python... How can I point crontab to the right place? Without reinstall mysql-python as a static library? I work on MAC OS 10.7. Thanks.
[ "Run env at your command-line and copy its output. Add that to the top of your crontab, as that will set the environment for the cron to run - this should do the trick. You can then remove unwanted environment variables at your own leisure.\nReference for Mac OS X:\ncrontab file\nWhen you add cron jobs (using conrt...
[ 2 ]
[]
[]
[ "crontab", "macos", "mysql", "mysql_python", "python" ]
stackoverflow_0008602527_crontab_macos_mysql_mysql_python_python.txt
Q: "Error: Python not found" when trying to access the android repository It gives me the error on line 23 of the repo file: exec: python: not found. the thing is, I have python installed in C:\Python27 (the default) I'm using the Git Bash when typing in these commands. I've tried to move the python folder into th...
"Error: Python not found" when trying to access the android repository
It gives me the error on line 23 of the repo file: exec: python: not found. the thing is, I have python installed in C:\Python27 (the default) I'm using the Git Bash when typing in these commands. I've tried to move the python folder into the git directory to run the repo file and it still says the same thing. I've ...
[ "It seems to me that you should add python to your path variable.\n" ]
[ 2 ]
[]
[]
[ "android", "git", "python", "repository" ]
stackoverflow_0008617208_android_git_python_repository.txt
Q: A nice way to find all combinations that give a sum of N? Is there a nice way for generating a list of digits (0-9), with repetitions and a length of 6, such that the sum is N, say, 20. For example: 004673 -> 4+6+7+3=20 121673 -> 1+2+1+6+7+3=20 ... Thanks A: ['{0:06}'.format(i) for i in xrange(1000000) if sum(m...
A nice way to find all combinations that give a sum of N?
Is there a nice way for generating a list of digits (0-9), with repetitions and a length of 6, such that the sum is N, say, 20. For example: 004673 -> 4+6+7+3=20 121673 -> 1+2+1+6+7+3=20 ... Thanks
[ "['{0:06}'.format(i) for i in xrange(1000000) if sum(map(int,str(i))) == 20]\n\ndoes the trick and needs about 5 seconds to return all 35127 numbers.\nUPDATE - as a bonus, here comes the ugly-but-much-faster (~40 times faster) version:\nresult = []\nfor a in xrange(10):\n for b in xrange(10):\n for c in x...
[ 12, 7, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008617455_python.txt
Q: Matching user's input with query from sqlite3 db in python I'm writing a script where by a user registers his/her username, but a function checks whether this username is already in the db or not. But I'm stuck on how to match my query with the input. Here is the code: def checker(self, insane): ...
Matching user's input with query from sqlite3 db in python
I'm writing a script where by a user registers his/her username, but a function checks whether this username is already in the db or not. But I'm stuck on how to match my query with the input. Here is the code: def checker(self, insane): t = (insane,) ...
[ "The DB fetch models return a tuple for each row. Since you've only selected a single field, you can simply access namer[0] to get the actual value.\n" ]
[ 1 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0008617837_python_sql_sqlite.txt
Q: Python ast.Print "nl" argument? According to the Python docs, ast.Print takes an optional, boolean nl argument. What is it for? A: It marks the difference between print 'foo' and print 'foo',. The latter omits the trailing linebreak. In [1]: import ast In [2]: ast.dump(ast.parse('print "hi"')) Out[2]: "Module(b...
Python ast.Print "nl" argument?
According to the Python docs, ast.Print takes an optional, boolean nl argument. What is it for?
[ "It marks the difference between print 'foo' and print 'foo',. The latter omits the trailing linebreak.\nIn [1]: import ast\n\nIn [2]: ast.dump(ast.parse('print \"hi\"'))\nOut[2]: \"Module(body=[Print(dest=None, values=[Str(s='hi')], nl=True)])\"\n\nIn [3]: ast.dump(ast.parse('print \"hi\",'))\nOut[3]: \"Module(bod...
[ 4 ]
[]
[]
[ "abstract_syntax_tree", "python" ]
stackoverflow_0008617906_abstract_syntax_tree_python.txt
Q: Error installing MySQL-python on a windows 7 box I'm trying to install django on a windows machine (I swear, it's not my fault). When it comes to the mysqldb module, I keep getting this error: Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved. PS C:\Users\ME> easy_install MySQL-pyth...
Error installing MySQL-python on a windows 7 box
I'm trying to install django on a windows machine (I swear, it's not my fault). When it comes to the mysqldb module, I keep getting this error: Windows PowerShell Copyright (C) 2009 Microsoft Corporation. All rights reserved. PS C:\Users\ME> easy_install MySQL-python Searching for MySQL-python Reading http://pypi.pyth...
[ "install with the exe from here. \nI've been stuck there, done that etc..\n" ]
[ 4 ]
[]
[]
[ "mysql_python", "python", "windows" ]
stackoverflow_0008617720_mysql_python_python_windows.txt
Q: Gstreamer does not produce audio when imported from a homebrew module Just for fun, I've been using python and gstreamer to create simple Linux audio players. The first one was a command-line procedural script that used gst-launch-0.10 playbin to play a webstream. The second version was again procedural but had a ...
Gstreamer does not produce audio when imported from a homebrew module
Just for fun, I've been using python and gstreamer to create simple Linux audio players. The first one was a command-line procedural script that used gst-launch-0.10 playbin to play a webstream. The second version was again procedural but had a GUI and used playbin2 to create the gstreamer pipeline. Now I'm trying to c...
[ "Tested your sample application and they work fine for me, you don't need the glib mainloop invocation in the imported player.py though\n", "I changed the name of the main script and things began to run ok. I have no idea why though. Hope this be eventually of use to anyone.\n" ]
[ 0, 0 ]
[]
[]
[ "gstreamer", "module", "oop", "python" ]
stackoverflow_0008576104_gstreamer_module_oop_python.txt
Q: format from tuple to float in python? def tong_thoigian (self,kr,uid,ids,context={}): obj=self.browse(kr,uid,ids,context=context)[0] kr.execute('''select name,giolam from x_giolam where name=%s'''%(obj.ma_luong)) kq=kr.fetchall() tong=0.00000 for i in kq: tong+=kq[1] ...
format from tuple to float in python?
def tong_thoigian (self,kr,uid,ids,context={}): obj=self.browse(kr,uid,ids,context=context)[0] kr.execute('''select name,giolam from x_giolam where name=%s'''%(obj.ma_luong)) kq=kr.fetchall() tong=0.00000 for i in kq: tong+=kq[1] self.write(kr,uid,ids,{'tonggiolam...
[ "Since the query is \"select name,giolam ...\", kq probably is something like:\n[ ('Thong', 324.34), ('Tran', 543.34), ('Thang', 765.52) ... ]\n\nSo I think you want:\nfor record in kq:\n tong+=record[1]\n\nInstead of tong+=kq[1].\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008618057_python.txt
Q: How to create a Filehandle in memory and pass to an external command in Python I have a small in-house Python script for Linux that creates a /home/user/environ_script.sh file in the users $HOME directory and then loads the environment in their shell via subprocess.call('bash --rcfile /home/user/environ_script....
How to create a Filehandle in memory and pass to an external command in Python
I have a small in-house Python script for Linux that creates a /home/user/environ_script.sh file in the users $HOME directory and then loads the environment in their shell via subprocess.call('bash --rcfile /home/user/environ_script.sh') Script works fine yet I was wondering if this can be done without writing to di...
[ "I think that what you're looking is a named pipe, that is, a mechanism for interprocess communication that can be used as a file, but that isn't written to disk:\nimport subprocess\nimport os\n\nfifo_name = 'my-bash.rc'\nos.mkfifo(fifo_name)\n\ntry:\n process = subprocess.Popen(['bash', '--rcfile', fifo_name])\...
[ 3 ]
[]
[]
[ "file", "python" ]
stackoverflow_0008612189_file_python.txt
Q: Extract All Zipped Files to Same Directory Using Python I have a large amount of zipped files in a single directory that I would like to decompress and save them to the same directory and with the same name as the zipped file. A: Start with something like: import glob import os import zipfile zip_files = glob.g...
Extract All Zipped Files to Same Directory Using Python
I have a large amount of zipped files in a single directory that I would like to decompress and save them to the same directory and with the same name as the zipped file.
[ "Start with something like:\nimport glob\nimport os\nimport zipfile\n\nzip_files = glob.glob('*.zip')\n\nfor zip_filename in zip_files:\n dir_name = os.path.splitext(zip_filename)[0]\n os.mkdir(dir_name)\n zip_handler = zipfile.ZipFile(zip_filename, \"r\")\n zip_handler.extractall(dir_name)\n\nSorry, I ...
[ 3 ]
[]
[]
[ "python", "zip" ]
stackoverflow_0008618251_python_zip.txt
Q: psycopg2 - how to change NULL type to a string 'NA' instead of None psycopg2 converts NULL to None through the NoneAdapter (right?) How do I create another adapter that converts all NULL to a string 'NA' ? Thanks *UPDATE: @thatisbrilliant Here is what i have: After doing this query : SELECT pg_type.oid FROM pg_t...
psycopg2 - how to change NULL type to a string 'NA' instead of None
psycopg2 converts NULL to None through the NoneAdapter (right?) How do I create another adapter that converts all NULL to a string 'NA' ? Thanks *UPDATE: @thatisbrilliant Here is what i have: After doing this query : SELECT pg_type.oid FROM pg_type JOIN pg_namespace ON typnamespace = pg_namespace.oid WHERE typnam...
[ "Actually NoneAdapter does the opposite of what you want, converts python's None type into SQL NULL. For info on casting SQL types into python objects, check out the official psycopg2 documentation.\nBased on that, it looks like you will have to register your adapter function for every type you want it to work on, ...
[ 4, 0 ]
[]
[]
[ "psycopg2", "python" ]
stackoverflow_0008582962_psycopg2_python.txt
Q: How can I add a delay to every method in a Python sub-class when I don't want to replicate every method in the parent class My apologies if this question has already been answered somewhere, but if it has I have not been able to locate the answer. I would like to create a sub-class of a parent class in such a way ...
How can I add a delay to every method in a Python sub-class when I don't want to replicate every method in the parent class
My apologies if this question has already been answered somewhere, but if it has I have not been able to locate the answer. I would like to create a sub-class of a parent class in such a way that there will be a delay (e.g. time.sleep()) before each call to the corresponding parent class method. I would like to do this...
[ "Really, what you have here is a design that involves a Strategy object.\nYour best approach is to fix the parent class to include a call to a \"delay object\". A default delay object does nothing.\nThis violates the \"so that I do not even need to know all the parent class methods\" hoped-for feature set. \nMeth...
[ 4, 4, 3, 1 ]
[]
[]
[ "dynamic", "methods", "python" ]
stackoverflow_0008618157_dynamic_methods_python.txt
Q: Initializing a static variable in Python Context Say, we want to use the Box-Muller algorithm. Starting from a couple of random numbers U1 and U2, we can generate G1 and G2. Now, for any call, we just want to output either G1 or G2. In other languages, we could use static variables to be able to know if we need to...
Initializing a static variable in Python
Context Say, we want to use the Box-Muller algorithm. Starting from a couple of random numbers U1 and U2, we can generate G1 and G2. Now, for any call, we just want to output either G1 or G2. In other languages, we could use static variables to be able to know if we need to generate a new couple. How can it be done in ...
[ "Writing generators is a very good practice! \nimport random \nimport math\ndef BoxMullerFormula(a,b):\n c = math.sqrt(-2 * math.log(a)) * math.cos(2 * math.pi * b)\n d = math.sqrt(-2 * math.log(a)) * math.sin(2 * math.pi * b)\n return (c,d)\ndef BoxM(): \n while 1:\n Rand01 = random.random()\n...
[ 3 ]
[]
[]
[ "generator", "python", "static", "yield" ]
stackoverflow_0008618650_generator_python_static_yield.txt
Q: Formatting a long list to 80 columns try: for key in copy['KnownNetworks'].keys(): if copy['KnownNetworks'][key]['SSID_STR'] == networkDict['name']: networkDict['uuid'] = copy['KnownNetworks'][key]['Unique Password ID'] print 'Found existing reference to wireless password uuid: %s' % ne...
Formatting a long list to 80 columns
try: for key in copy['KnownNetworks'].keys(): if copy['KnownNetworks'][key]['SSID_STR'] == networkDict['name']: networkDict['uuid'] = copy['KnownNetworks'][key]['Unique Password ID'] print 'Found existing reference to wireless password uuid: %s' % networkDict['uuid'] found = True e...
[ "For lines over 80 columns, you can break them into multiple lines. Here it's easy as you've got a list.\narguments = [security,\n 'add-generic-password',\n '-a', networkDict['name'],\n '-l', networkDict['name'],\n '-D', 'Airport network password',\n '-s',...
[ 8 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0008618777_dictionary_list_python.txt
Q: Getting authenticationerror.login_cookie_required error while using Google adwords API with Python I am trying to use python to consume some adwords soap API, I am able to get the auth token but when I try to make a get request I got the authenticationerror.login_cookie_required error. Any ideas? from suds.client ...
Getting authenticationerror.login_cookie_required error while using Google adwords API with Python
I am trying to use python to consume some adwords soap API, I am able to get the auth token but when I try to make a get request I got the authenticationerror.login_cookie_required error. Any ideas? from suds.client import Client auth_data = {'accountType':'GOOGLE', 'Email':'xxx@xxx.com', 'Passwd':'xxxxxxxx', 'service...
[ "Have you tried using the Python client library for the AdWords API?\nhttp://code.google.com/p/google-api-ads-python/\n", "authToken isn't a SOAP header. RequestHeader is the soap header and authToken is a member of that header. See http://code.google.com/apis/adwords/docs/headers.html and http://code.google.com/...
[ 0, 0 ]
[]
[]
[ "google_ads_api", "python", "soap" ]
stackoverflow_0008114830_google_ads_api_python_soap.txt
Q: How do you open a URL with Python without using a browser? I want to open a URL with Python code but I don't want to use the "webbrowser" module. I tried that already and it worked (It opened the URL in my actual default browser, which is what I DON'T want). So then I tried using urllib (urlopen) and mechanize. Bo...
How do you open a URL with Python without using a browser?
I want to open a URL with Python code but I don't want to use the "webbrowser" module. I tried that already and it worked (It opened the URL in my actual default browser, which is what I DON'T want). So then I tried using urllib (urlopen) and mechanize. Both of them ran fine with my program but neither of them actually...
[ "I'm not sure what OS you're working on, but if you use something like httpscoop (mac) or fiddler (pc) or wireshark, you should be able to watch the traffic and see what's happening. It may be that the website does a redirect (which your browser is following) or there's some other subsequent activity.\nStart an HT...
[ 1, 0 ]
[]
[]
[ "mechanize", "python", "urllib" ]
stackoverflow_0008618335_mechanize_python_urllib.txt
Q: python postgis ST_Contains failing query I have been trying the following but always fails, roomTypeSQL = "SELECT spftype FROM cameron_toll_spatialfeatures WHERE ST_Contains(ST_GeomFromText(%s), ST_geomFromWKB(geometry)) = 'True';" roomTypeData = (pointTested) # "POINT(-3.164005 55.926378)" .execute(roomTypeSQL, r...
python postgis ST_Contains failing query
I have been trying the following but always fails, roomTypeSQL = "SELECT spftype FROM cameron_toll_spatialfeatures WHERE ST_Contains(ST_GeomFromText(%s), ST_geomFromWKB(geometry)) = 'True';" roomTypeData = (pointTested) # "POINT(-3.164005 55.926378)" .execute(roomTypeSQL, roomTypeData) I want to get the polygon from m...
[ "might be a simple answer...st_contains returns 't' not 'true'. Postgres is cap sensitive, make sure t not T\n", "This had to do with python operators. I entered all the sql arguments using the python % operator properly and it worked. Like this,\nroomTypeSQL = \"SELECT spftype FROM cameron_toll_spatialfeatures ...
[ 0, 0 ]
[]
[]
[ "postgis", "python" ]
stackoverflow_0008520559_postgis_python.txt
Q: pygame: using pygame.mixer simultaneously from 2 threads fails I am trying to build a little sound generator with pygame and numpy. The following code plays the data out of my numpy arrays correctly, but when I try to use this code in a module and access it either from different threads or from different processes...
pygame: using pygame.mixer simultaneously from 2 threads fails
I am trying to build a little sound generator with pygame and numpy. The following code plays the data out of my numpy arrays correctly, but when I try to use this code in a module and access it either from different threads or from different processes to play two sounds at a time, one of the sounds is played before th...
[ "To completely bypass your problem you could use py audiere to make your sounds. with it you could have two different tones at once.\nUsing your code I don't think you can have two tones at once.\nThis is a snippet from my frequency generator:\nspeakers = audiere.open_device()\n\ntone = speakers.create_square(start...
[ 0, 0 ]
[]
[]
[ "audio", "pygame", "python" ]
stackoverflow_0008610991_audio_pygame_python.txt