content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python not interpreting changed files, using obsolete .pyc Using the Google App Engine to develop in python yesterday it stopped running the current version of the script. Instead of executing the most recent version it seems to run the previously pre-compiled .pyc even if the .py source was changed. Error message...
Python not interpreting changed files, using obsolete .pyc
Using the Google App Engine to develop in python yesterday it stopped running the current version of the script. Instead of executing the most recent version it seems to run the previously pre-compiled .pyc even if the .py source was changed. Error messages actually quotes the correct line from the most current source....
[ "Did you check your system clock? I believe python determine whether to use the .pyc or .py based on timestamps. If your system clock got pushed back, then it would see the .pyc files as newer until the system clock caught up to the last time they were built.\n", "Are you editing the .py files on a different sy...
[ 2, 2, 0 ]
[]
[]
[ "bytecode", "google_app_engine", "pyc", "python" ]
stackoverflow_0005629135_bytecode_google_app_engine_pyc_python.txt
Q: basic question about tkinter buttons I'm new to using tkinter and GUI programming in general so this may be a pretty basic question. Anyway, suppose I have a set of buttons for the user to choose from and what I want is a list of all the button objects that were clicked by the user. Basically, I want to know whi...
basic question about tkinter buttons
I'm new to using tkinter and GUI programming in general so this may be a pretty basic question. Anyway, suppose I have a set of buttons for the user to choose from and what I want is a list of all the button objects that were clicked by the user. Basically, I want to know which buttons the user clicked.
[ "Here's a good website covering Python events that should guide you: \nhttp://effbot.org/tkinterbook/tkinter-events-and-bindings.htm\nIt sounded like you might want something akin to a checkbox, if so:\nCannot understand how to get data from checklistbox in wxpython\n", "On each of the buttons you could set the c...
[ 1, 1, 1 ]
[]
[]
[ "button", "python", "tkinter", "user_interface" ]
stackoverflow_0006192727_button_python_tkinter_user_interface.txt
Q: Alternative for python-mathdom I'd like to convert a MathML expression to an equation string in python, for which the MathDOM module should be good for. An example would be: <math xmlns="http://www.w3.org/1998/Math/MathML"> <lambda> <bvar><ci>A</ci></bvar> <bvar><ci>B</ci></bvar> <apply> ...
Alternative for python-mathdom
I'd like to convert a MathML expression to an equation string in python, for which the MathDOM module should be good for. An example would be: <math xmlns="http://www.w3.org/1998/Math/MathML"> <lambda> <bvar><ci>A</ci></bvar> <bvar><ci>B</ci></bvar> <apply> <plus/> <ci>A</ci> ...
[ "Best solution so far: libsbml\nfrom libsbml import *\nast = readMathMLFromString(xmlString)\nf = FunctionDefinition(2,4)\nf.setMath(ast)\nkl = KineticLaw(2,4)\nkl.setMath(f.getBody())\nkl.getFormula()\n\nOk for me since I'm already working with it but far from a general solution.\n" ]
[ 2 ]
[]
[]
[ "mathml", "python" ]
stackoverflow_0006188082_mathml_python.txt
Q: Call a Function in Another Frame (WxPython) In my wxpython app, I have a parent frame and a child frame. When I click on a button inside the child frame, I want it to send some data (list, string etc.) to the parent frame, close itself, show the parent and finally call a function in the parent frame. How can I do...
Call a Function in Another Frame (WxPython)
In my wxpython app, I have a parent frame and a child frame. When I click on a button inside the child frame, I want it to send some data (list, string etc.) to the parent frame, close itself, show the parent and finally call a function in the parent frame. How can I do that? (especially function calling) Thanks in ad...
[ "You should have the button click generate an event containing the data. Then add an event handler to the parent frame that extracts the data from the event and calls the function. The wxPython wiki has a tutorial that covers events. The wx documentation also has an event handling overview.\n", "You can use pubsu...
[ 2, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006192430_python_wxpython.txt
Q: Python + Selenium - web scraping and counting occurrences of certain text data in HTML Please help. I am trying to fetch data from a website and then count the occurrences of certain text. Unfortunately, I cannot provide the actual website, but the basics are this. The web page is loaded and I am presented with a ...
Python + Selenium - web scraping and counting occurrences of certain text data in HTML
Please help. I am trying to fetch data from a website and then count the occurrences of certain text. Unfortunately, I cannot provide the actual website, but the basics are this. The web page is loaded and I am presented with a list of values, which are located in the table (the code below reflects this). The page woul...
[ "I'm not familiar with the python api so sorry for that, but in java I know using xpath there is a function to get the number of occurrences of your xpath. So you could write an xpath selector to find the element you want then get the number of occurrences of that path. \nThen to click each one you can affix your x...
[ 3 ]
[]
[]
[ "html", "python", "selenium", "web_scraping" ]
stackoverflow_0006193063_html_python_selenium_web_scraping.txt
Q: Scrapy output feed international unicode characters (e.g. Japanese chars) I'm a newbie to python and scrapy and I'm following the dmoz tutorial. As a minor variant to the tutorial's suggested start URL, I chose a Japanese category from the dmoz sample site and noticed that the feed export I eventually get shows th...
Scrapy output feed international unicode characters (e.g. Japanese chars)
I'm a newbie to python and scrapy and I'm following the dmoz tutorial. As a minor variant to the tutorial's suggested start URL, I chose a Japanese category from the dmoz sample site and noticed that the feed export I eventually get shows the unicode numeric values instead of the actual Japanese characters. It seems l...
[ "When you scrape the text from the page it is stored in Unicode.\nWhat you want to do is encode it into something like UTF8.\nunicode_string.encode('utf-8')\n\nAlso, when you extract the text using your selector, it is stored in a list even if there is only one result, so you need to pick the first element.\n" ]
[ 1 ]
[]
[]
[ "python", "scrapy", "unicode" ]
stackoverflow_0006191902_python_scrapy_unicode.txt
Q: Python finding stdin filepath on Linux How can I tell the file (or tty) that is attached to my stdios? Something like: >>> import sys >>> print sys.stdin.__path__ '/dev/tty1' >>> I could look in proc: import os, sys os.readlink('/proc/self/fd/%s' % sys.stdin.fileno()) But seems like there should be a builtin wa...
Python finding stdin filepath on Linux
How can I tell the file (or tty) that is attached to my stdios? Something like: >>> import sys >>> print sys.stdin.__path__ '/dev/tty1' >>> I could look in proc: import os, sys os.readlink('/proc/self/fd/%s' % sys.stdin.fileno()) But seems like there should be a builtin way?
[ "The sys.std* objects are standard Python file objects, so they have a name attribute and a isatty method:\n>>> import sys\n>>> sys.stdout.name\n'<stdout>'\n>>> sys.stdout.isatty()\nTrue\n>>> anotherfile = open('/etc/hosts', 'r')\n>>> anotherfile.name\n'/etc/hosts'\n>>> anotherfile.isatty()\nFalse\n\nShort of telli...
[ 2, 1 ]
[]
[]
[ "filepath", "python", "stdin" ]
stackoverflow_0006191009_filepath_python_stdin.txt
Q: From for loops to numpy dot implementation N=100 reliab=zeros((N,N)) for i in range(N): for j in range(N): if random() < 0.6: reliab[i,j] = 1 else: reliab[i,j] = 0 As in my code this matrix filling is recalled a huge number of times, these for loops should be ch...
From for loops to numpy dot implementation
N=100 reliab=zeros((N,N)) for i in range(N): for j in range(N): if random() < 0.6: reliab[i,j] = 1 else: reliab[i,j] = 0 As in my code this matrix filling is recalled a huge number of times, these for loops should be changed with a dot product...but I dunno how to d...
[ "I'm not sure I understand your problem completely, but the following line should be doing the same thing as your code:\nreliab = numpy.int32(numpy.random.rand(N,N) < 0.6)\n\n", ">>> import numpy as np\n>>> reliab = np.random.random((N,N))\n>>> reliab = reliab < 0.6\n>>> reliab.dtype = np.int8\n>>> reliab\narray(...
[ 4, 1 ]
[]
[]
[ "loops", "numpy", "python" ]
stackoverflow_0006193538_loops_numpy_python.txt
Q: Finding maximum of a list of lists by sum of elements in Python What's the idiomatic way to do maximumBy (higher order function taking a comparison function for the test), on a list of lists, where the comparison we want to make is the sum of the list, in Python? Here's a Haskell implementation and example output:...
Finding maximum of a list of lists by sum of elements in Python
What's the idiomatic way to do maximumBy (higher order function taking a comparison function for the test), on a list of lists, where the comparison we want to make is the sum of the list, in Python? Here's a Haskell implementation and example output: > maximumBy (compare `on` sum) [[1,2,3],[4,5,6],[1,3,5]] > [4,5,6] ...
[ "Since Python 2.5 you can use max with a key parameter:\n>>> max(a, key=sum)\n[4, 5, 6]\n\n", "It isn't terribly efficient, but:\nreduce(lambda x,y: x if sum(x)>sum(y) else y, [[1,2,3],[4,5,6],[1,3,5]])\n\n", "If max didn't have the key parameter you could code the DSU pattern explicitly:\nmax(izip(imap(sum,a),...
[ 41, 1, 1 ]
[]
[]
[ "haskell", "higher_order_functions", "list", "python" ]
stackoverflow_0002763015_haskell_higher_order_functions_list_python.txt
Q: Python Unicode %HH-escaping All, I am working on an application that has a mixture of standard latin-1 characters and other languages. I would like to convert everything to the same "format" so that the Bing translator can understand it. There are two articles that I've looked at. https://dev.laptop.org/ticket/2...
Python Unicode %HH-escaping
All, I am working on an application that has a mixture of standard latin-1 characters and other languages. I would like to convert everything to the same "format" so that the Bing translator can understand it. There are two articles that I've looked at. https://dev.laptop.org/ticket/2327 I actually want to do the rev...
[ "urllib might help. At least this snippet works:\n#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport urllib\n\nw = 'ar.wikipedia.org/wiki/حاسوب'\nprint urllib.quote (w)\n\nOutput is\nar.wikipedia.org/wiki/%D8%AD%D8%A7%D8%B3%D9%88%D8%A8\n\nDepending which encoding your input strings have you might need to cal...
[ 2 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0006193828_python_unicode.txt
Q: Sorting a csv file in Python with sorted() returns values in programmer DESC order, not time DESC order I'm not doing anything overly complex I believe. I'm presorting a large csv data file because it is full of data that arrives in random time order. The index is correct, but the return formatting is off. sor...
Sorting a csv file in Python with sorted() returns values in programmer DESC order, not time DESC order
I'm not doing anything overly complex I believe. I'm presorting a large csv data file because it is full of data that arrives in random time order. The index is correct, but the return formatting is off. sortedList=sorted(reader,key=operator.itemgetter(1)) So instead of sorting like [-100 -10 -1 0 10 100 5000 6000...
[ "Just from the output you see there, it looks like these are being sorted as strings rather than as numbers.\nSo you could do:\nsortedList=sorted(reader, key=lambda t: int( t[1] ))\n\nor\nsortedList=sorted(reader, key=lambda t: float( t[1] ))\n\nOr better, try to ensure that the sequence reader gets populated with ...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "numerical", "python", "sorting" ]
stackoverflow_0006193536_numerical_python_sorting.txt
Q: Connecting to Sql Server with Python 3 in Windows Can someone please point me in the right direction of how I can connect to MS SQL Server with Python? What I want to do is read a text file, extract some values and then insert the values from the text file into a table in my Sql Server database. I am using Python ...
Connecting to Sql Server with Python 3 in Windows
Can someone please point me in the right direction of how I can connect to MS SQL Server with Python? What I want to do is read a text file, extract some values and then insert the values from the text file into a table in my Sql Server database. I am using Python 3.1.3, and it seems some of the modules I have come acr...
[ "There are a bunch more SQL Server libraries listed on the Python wiki. At least mxODBC is fully ready for Python 3.1, but I haven't used it so I can't comment on its appropriateness...\n", "There is a pymssql module. Here you can find installation instructions\n", "I found a module called CEODBC that I was abl...
[ 3, 1, 1 ]
[]
[]
[ "database_connection", "python", "python_3.x", "python_module", "sql" ]
stackoverflow_0006154069_database_connection_python_python_3.x_python_module_sql.txt
Q: How to combine numerous programs into one code? I have a program that opens numerous other programs. How can I combine the code from the other programs into this code so that instead of 10 sets of code i will only have one? Code for app that I want to put all the codes in: import pygtk pygtk.require('2.0') import ...
How to combine numerous programs into one code?
I have a program that opens numerous other programs. How can I combine the code from the other programs into this code so that instead of 10 sets of code i will only have one? Code for app that I want to put all the codes in: import pygtk pygtk.require('2.0') import gtk import subprocess class Example: def __init...
[ "Put the files in the same directory, then use something like:\nfrom Colour import ColorSelectionExample\n\nthen to run it, construct a ColorSelectionExample:\nColorSelectionExample()\n\n" ]
[ 0 ]
[]
[]
[ "combinations", "connect", "modular", "pygtk", "python" ]
stackoverflow_0005938249_combinations_connect_modular_pygtk_python.txt
Q: Simple Django program causing me trouble I've gone through quite a few django tutorials, and I'm finally getting ready to head out on my own. However, my first non-tutorial program is throwing an error, and I've been banging my head for a couple of days. I expect it to be a very noob problem, because, well, I am...
Simple Django program causing me trouble
I've gone through quite a few django tutorials, and I'm finally getting ready to head out on my own. However, my first non-tutorial program is throwing an error, and I've been banging my head for a couple of days. I expect it to be a very noob problem, because, well, I am. When I use this view def todo(request): ...
[ "return render_to_response,('index.html', {\"latest_list\", latest_list})\n\nRemove that comma affer render_to_response and you should be ok. Reason: the comma makes the return value a tuple object, but need to return an HttpResponse object from a view.\n", "You goofed on your return.\ndef todo(request):\n lates...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006194117_django_python.txt
Q: Loop through a bunch of folderish content, which may be itself folderish? Suppose I have a content type, Folder, with 4 items. + MyObject - Child1 - Child2 - Child3 + Child4 - Child5 - Child6 Suppose I have another content type (let's call it Alias). This Alias is mainly a reference to another object but f...
Loop through a bunch of folderish content, which may be itself folderish?
Suppose I have a content type, Folder, with 4 items. + MyObject - Child1 - Child2 - Child3 + Child4 - Child5 - Child6 Suppose I have another content type (let's call it Alias). This Alias is mainly a reference to another object but folderish: it can contain a bunch of other aliases. I'm going to use --> to indi...
[ "The most elegant and Pythonic solution is to write a recursive generator. Assuming this is a method:\ndef iter_preorder(self):\n yield self\n # check for folderishness here if a non-folderish\n # node may have children as well\n for x in self.children:\n for y in x.iter_preorder():\n ...
[ 6, 2, 2, 0 ]
[]
[]
[ "plone", "python", "recursion" ]
stackoverflow_0006192487_plone_python_recursion.txt
Q: Using Python and Beautifulsoup how do I select the desired table in a div? I would like to be able to select the table containing the "Accounts Payable" text but I'm not getting anywhere with what I'm trying and I'm pretty much guessing using findall. Can someone show me how I would do this? For example this is w...
Using Python and Beautifulsoup how do I select the desired table in a div?
I would like to be able to select the table containing the "Accounts Payable" text but I'm not getting anywhere with what I'm trying and I'm pretty much guessing using findall. Can someone show me how I would do this? For example this is what I start with: <div> <tr> <td class="lft lm">Accounts Payable </td> <td class...
[ "You can select the td elements with class lft lm and then examine the element.string to determine if you have the \"Accounts Payable\" td:\nimport sys\nfrom BeautifulSoup import BeautifulSoup\n\n# where so_soup.txt is your html\nf = open (\"so_soup.txt\", \"r\")\ndata = f.readlines ()\nf.close ()\n\nsoup = Beautif...
[ 8 ]
[]
[]
[ "beautifulsoup", "html_parsing", "python" ]
stackoverflow_0006194240_beautifulsoup_html_parsing_python.txt
Q: Cannot find STARTF_USESHOWWINDOW in python I'm trying to do the same thing as this guy right here: Cross-platform subprocess with hidden window But my problem is that subprocess module doesn't contain STARTF_USESHOWWINDOW. If I understand good it was removed from python 2.7 and above. What can I do so I can use it...
Cannot find STARTF_USESHOWWINDOW in python
I'm trying to do the same thing as this guy right here: Cross-platform subprocess with hidden window But my problem is that subprocess module doesn't contain STARTF_USESHOWWINDOW. If I understand good it was removed from python 2.7 and above. What can I do so I can use it in Python 2.7 or is there an alternative to usi...
[ "As mentioned here, you can use subprocess._subprocess.STARTF_USESHOWWINDOW in Python 2.7.\n", "STARTF_USESHOWWINDOW is a Windows specific flag and so you can read it out of win32con. If you don't have that module installed, you can simply define it for yourself.\n" ]
[ 3, 2 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0005485668_python_subprocess.txt
Q: Using UNION in django ORM syntax between different classes in the same hierarchy I need to implement something like (SELECT table1.*, val=2 FROM table1 INNER JOIN table2 ON table1.id = table2.id WHERE some_condition) UNION (SELECT table1.*, val=3 FROM table1 INNER JOIN table3 ON table1.id = table3.id WHERE some...
Using UNION in django ORM syntax between different classes in the same hierarchy
I need to implement something like (SELECT table1.*, val=2 FROM table1 INNER JOIN table2 ON table1.id = table2.id WHERE some_condition) UNION (SELECT table1.*, val=3 FROM table1 INNER JOIN table3 ON table1.id = table3.id WHERE some_condition) or (SELECT val1, val2, val3, val=2 FROM table2 WHERE some_condition) UN...
[ "You'll spend a lot of time fighting the django ORM API if you attempt to write this JOIN/UNION outside of a .execute call. If this is going to be very common, consider using a VIEW and then just do a simple SELECT from your newly created VIEW.\n", "You could rewrite it as a subquery:\nselect val1, val2, val3, va...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_models", "postgresql", "python", "sql" ]
stackoverflow_0006180632_django_django_models_postgresql_python_sql.txt
Q: Develop in python on Linux, test on Windows I'm trying to develop a cross-platform library and want to be able to develop code and then quickly test it on both Windows and Linux. I'm not sure if it's even an option or worthwhile testing under Wine (it uses the multiprocessing module, and COM on Windows) but I do h...
Develop in python on Linux, test on Windows
I'm trying to develop a cross-platform library and want to be able to develop code and then quickly test it on both Windows and Linux. I'm not sure if it's even an option or worthwhile testing under Wine (it uses the multiprocessing module, and COM on Windows) but I do have a VM I've been running it under. It's just be...
[ "Using a DVCS to push the local changes to the server will take you far. You will need a SSH server on the Windows machine, but there are several of those around. You can also use a makefile to direct the pushing and testing, possibly even running the tests remotely depending on what they consist of.\n", "Windows...
[ 2, 1, 1 ]
[]
[]
[ "python", "testing", "virtualization", "windows" ]
stackoverflow_0006194618_python_testing_virtualization_windows.txt
Q: python: how do i know when i am on the last for cycle for i in range(len(results_histogram)): if i!=len(results_histogram)-1: url+=str(results_histogram[i])+',' my if statement is checking whether i am on the last loop, but it is not working. what am i doing wrong? A: To avoid the question slightly, y...
python: how do i know when i am on the last for cycle
for i in range(len(results_histogram)): if i!=len(results_histogram)-1: url+=str(results_histogram[i])+',' my if statement is checking whether i am on the last loop, but it is not working. what am i doing wrong?
[ "To avoid the question slightly, you seem to have rewritten str.join:\n','.join(results_histogram)\n\nIf you get an error like TypeError: sequence item 0: expected string, int found, then you can convert the intermediate results to a string with\n','.join(map(str, results_histogram))\n\n\nstr.join is undoubtedly m...
[ 7, 2, 1, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0003401350_python_syntax.txt
Q: Problem writing unicode utf-8 data to file in python I'm having some issues writing unicode to a file in my Python program. Here is the code that 'saves' the file: def file_save(self): # save changes to existing file if self.filename and isfile(self.filename): self.watcher.removePath(self.filenam...
Problem writing unicode utf-8 data to file in python
I'm having some issues writing unicode to a file in my Python program. Here is the code that 'saves' the file: def file_save(self): # save changes to existing file if self.filename and isfile(self.filename): self.watcher.removePath(self.filename) s = codecs.open(self.filename,'w','utf-8') ...
[ "Unicode support was \"fixed\" in 3.x. Normal string literals are stored as Unicode, and the normal open() function has gained an encoding argument thereby making codecs.open() obsolete.\n s = open(self.filename, 'w', encoding='utf-8')\n s.write(self.ui.editor_window.toPlainText())\n\n" ]
[ 5 ]
[]
[]
[ "python", "unicode", "utf_8" ]
stackoverflow_0006194706_python_unicode_utf_8.txt
Q: How do I translate this to Python? s1 = Selenium::WebDriver::Remote.new :url => "http://localhost:4444/wb/pub" This is Ruby. What's the equivalent in Python? A: This S/O answer should demonstrate the Syntax you need: How do you connect remotely using Python + Webdriver
How do I translate this to Python?
s1 = Selenium::WebDriver::Remote.new :url => "http://localhost:4444/wb/pub" This is Ruby. What's the equivalent in Python?
[ "This S/O answer should demonstrate the Syntax you need:\nHow do you connect remotely using Python + Webdriver\n" ]
[ 1 ]
[]
[]
[ "python", "ruby", "selenium" ]
stackoverflow_0006194736_python_ruby_selenium.txt
Q: python get array parameter I'm comming from php where $_GET [ 'filter' ] on a url such as example.com/?filter[0][field]=username&filter[0][data][type]=string&filter[0][data][value]=someusername will return an array which can be parsed as: foreach ( $_GET [ 'filter' ] as $k => $field ) { $fieldName = $field [$k...
python get array parameter
I'm comming from php where $_GET [ 'filter' ] on a url such as example.com/?filter[0][field]=username&filter[0][data][type]=string&filter[0][data][value]=someusername will return an array which can be parsed as: foreach ( $_GET [ 'filter' ] as $k => $field ) { $fieldName = $field [$k] [ 'data' ] [ 'field' ]; $f...
[ "http://docs.python.org/library/urlparse.html\nurlparse.parse_qs \n", "In case you are using the publisher of apache mod python you can specify the arguments in your index function. Let's assume you call\nhttp://yourserver/script.py?name=John&age=36\n\nThen your script.py should look something like\ndef index (re...
[ 0, 0 ]
[]
[]
[ "get", "python", "request" ]
stackoverflow_0006188924_get_python_request.txt
Q: Django create template filter for nice time I know there's timesince filter. But I want something that returns this: just few seconds ago X minutes ago X hours ago on $day_name X weeks ago X months ago Examples: just few seconds ago 37 minutes ago 2 hours ago yesterday on Thursday 1 week ago 7 months ago How c...
Django create template filter for nice time
I know there's timesince filter. But I want something that returns this: just few seconds ago X minutes ago X hours ago on $day_name X weeks ago X months ago Examples: just few seconds ago 37 minutes ago 2 hours ago yesterday on Thursday 1 week ago 7 months ago How can I implement something like this?
[ "Not sure if it ticks all your boxes, but there's a tag naturaltime in the django.contrib.humanize template tags that should do this:\nhttps://docs.djangoproject.com/en/dev/ref/contrib/humanize/#naturaltime\nsettings.py\nINSTALLED_APPS = {\n ...\n 'django.contrib.humanize',\n}\n\ntemplate.html\n{% load humani...
[ 16, 4 ]
[]
[]
[ "django", "django_template_filters", "python" ]
stackoverflow_0006194589_django_django_template_filters_python.txt
Q: Launching selenium from python (subprocess.Popen vs. os.system) I'm launching the selenium 2 jar file using subprocess.Popen in python when I'm bootstrapping my tests. This works fine with FF but when I try to launch google chrome it fails to load the page (getting a "Aww, snap"-error), it tries to look for it's p...
Launching selenium from python (subprocess.Popen vs. os.system)
I'm launching the selenium 2 jar file using subprocess.Popen in python when I'm bootstrapping my tests. This works fine with FF but when I try to launch google chrome it fails to load the page (getting a "Aww, snap"-error), it tries to look for it's profile in a weird place: $SELENIUM_JAR/"/var/folders/Qg/QgltsVp+FL0PD...
[ "Try to set to_execute to a list instead of a string, like:\nto_execute = [\n 'java', \n '-jar', 'selenium-server.jar',\n '-userExtensions', 'user-extensions.js',\n '-port', '4444']\n\n", "I will simply accept that the problem is not related to python but rather my framework.\n" ]
[ 1, 0 ]
[]
[]
[ "python", "selenium", "subprocess" ]
stackoverflow_0005600445_python_selenium_subprocess.txt
Q: Where can I find documentation/tutorial(s) for Mutagen? (Python) After asking this question: How do I read album artwork using python? I got 'stuck' as it were. I have spent forever looking for documentation online but haven't come across any. I know that a lot of responses suggest reading the internal docstring...
Where can I find documentation/tutorial(s) for Mutagen? (Python)
After asking this question: How do I read album artwork using python? I got 'stuck' as it were. I have spent forever looking for documentation online but haven't come across any. I know that a lot of responses suggest reading the internal docstrings etc. but to be honest this is the first time I've come across a libr...
[ "A couple of things you might try. Pydoc makes it easy to navigate the contents of docstrings for a given project. Assuming you have installed mutagen globally or in a virtualenv, this should start a webserver where you can browse locally:\n% pydoc -p 8080\n# then navigate to http://localhost:8080/mutagen.html to...
[ 2 ]
[]
[]
[ "mp3", "python" ]
stackoverflow_0006194015_mp3_python.txt
Q: Django - how to set blank = False, required = False I've a model like this: class Message(models.Model): msg = models.CharField(max_length = 150) and I have a form for insert the field. Actually django allows empty spaces, for examples if I inset in the field one space it works. But now I want to fix this: th...
Django - how to set blank = False, required = False
I've a model like this: class Message(models.Model): msg = models.CharField(max_length = 150) and I have a form for insert the field. Actually django allows empty spaces, for examples if I inset in the field one space it works. But now I want to fix this: the field is not required, but if a user insert a spaces, t...
[ "Whitespace is not considered to be blank. blank specifically refers to no input (i.e. an empty string ''). You will need to use a model field validator that raises an exception if the value only consists of spaces. See the documentation for details.\nExample:\ndef validate_not_spaces(value):\n if isinstance(val...
[ 13, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006194988_django_python.txt
Q: Configuring a custom scrollbar in PyQt I am building a GUI for image processing in PyQt. One task that I need to be able to do is use a scrollbar to move through a directory of image files. Specifically, if there are 1000 images, say, in /my/dir, then I would like the distance scrolled along a scrollbar to corresp...
Configuring a custom scrollbar in PyQt
I am building a GUI for image processing in PyQt. One task that I need to be able to do is use a scrollbar to move through a directory of image files. Specifically, if there are 1000 images, say, in /my/dir, then I would like the distance scrolled along a scrollbar to correspond to the image number (between 1 and 1000)...
[ "The simplest way would be to use a QListWidget and populate it with your images as the icons of a QListWidgetItem. An example would be something like this\nself.list_widget = QListWidget()\nfiles = glob.glob('YourDirectory/*.jpg') #Get all jpegs in your directory\nfor i in files:\n self.list_widget.addItem(QLi...
[ 1 ]
[]
[]
[ "image_processing", "pyqt", "python", "scrollbar" ]
stackoverflow_0006194659_image_processing_pyqt_python_scrollbar.txt
Q: multidimensional array python I am creating this program. But I can't get it to insert data into the sqlite3 database. class Spider(HTMLParser): def __init__(self, url): HTMLParser.__init__(self) req = urlopen(url) self.feed(req.read()) def handle_starttag(self, tag, attrs): i...
multidimensional array python
I am creating this program. But I can't get it to insert data into the sqlite3 database. class Spider(HTMLParser): def __init__(self, url): HTMLParser.__init__(self) req = urlopen(url) self.feed(req.read()) def handle_starttag(self, tag, attrs): if tag == 'a' and attrs: ...
[ "The VALUES keyword is plural, not singular. You don't have to get rid of the extra parentheses around the question marks, but they're not necessary. Also, you can explicitly tell the SQL server that you want to insert directly into specific columns rather than passing None for an auto-incrementing primary key.\n...
[ 2 ]
[]
[]
[ "data_structures", "multidimensional_array", "python" ]
stackoverflow_0006194936_data_structures_multidimensional_array_python.txt
Q: I am getting an Unexpected Indent error in a nested if block I am using a nested if block to decide the appropriate view. But I am getting an Unexpected Indent error after the if block. I am not able to find out where I am making a mistake in indentation. def logged_home(request): names = request.user.soc...
I am getting an Unexpected Indent error in a nested if block
I am using a nested if block to decide the appropriate view. But I am getting an Unexpected Indent error after the if block. I am not able to find out where I am making a mistake in indentation. def logged_home(request): names = request.user.social_auth.values_list('provider', flat=True) ctx = dict((na...
[ "You might be mixing tabs and spaces, and don't have your tab size set to 8.\n" ]
[ 3 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0006195164_django_django_views_python.txt
Q: Is it possible to subclass the immutable date class and override the __str__ method? I am trying to subclass the immutable date class in Python, but I also need to override the __str__ method. So far, I have the following: from datetime import date class Year(date): def __new__(cls, year): return supe...
Is it possible to subclass the immutable date class and override the __str__ method?
I am trying to subclass the immutable date class in Python, but I also need to override the __str__ method. So far, I have the following: from datetime import date class Year(date): def __new__(cls, year): return super(Year, cls).__new__(cls, year, 1, 1) def __str__(self): return self.strftime(...
[ "Add a return to the __str__ method.\n\nUPDATE:\nI ran your updated code on my machine, and it works fine:\naj@localhost:~/so/python# cat date2.py\nfrom datetime import date\n\nclass Year(date):\n def __new__(cls, year):\n return super(Year, cls).__new__(cls, year, 1, 1)\n def __str__(self):\n r...
[ 2, 1 ]
[]
[]
[ "date", "datetime", "immutability", "python", "subclass" ]
stackoverflow_0006195232_date_datetime_immutability_python_subclass.txt
Q: How to get per-testcase scoping for dependency injected objects in Python? I'm using python-inject, python 2.6 (with unittest2). We have classes to test that use injection, and test-cases which also use the same values. We currently use inject.appscope, to "singletonize" the values. Otherwise they're instantiated ...
How to get per-testcase scoping for dependency injected objects in Python?
I'm using python-inject, python 2.6 (with unittest2). We have classes to test that use injection, and test-cases which also use the same values. We currently use inject.appscope, to "singletonize" the values. Otherwise they're instantiated per user. import inject class A(object): '''shared data between many parts'...
[ "You can use setUp and tearDown to register/unregister the scope, treating each test method invocation as a new \"request\".\nWith the following changes your sample unit tests pass:\nclass TestFoo(unittest2.TestCase):\n\n a = inject.attr('a', A)\n\n def __init__(self, *n, **kw):\n unittest2.TestCase.__...
[ 1 ]
[]
[]
[ "python", "unittest2" ]
stackoverflow_0006151024_python_unittest2.txt
Q: Is there a translation API service for Chinese to English? I have a list of product names in Chinese. I want to translate these into English, I have tried Google AJAX language API, but it seems that translation is not good, it would be great if someone could give me some advice about or point me towards a better c...
Is there a translation API service for Chinese to English?
I have a list of product names in Chinese. I want to translate these into English, I have tried Google AJAX language API, but it seems that translation is not good, it would be great if someone could give me some advice about or point me towards a better choice. Thank you.
[ "Eh, Google is certainly a great translation service, but if you're looking for reliable translations you probably need to go human - machine translation can be sketchy at best. myGengo has an API to facilitate machine translation; your question is tagged with \"python\", so I've thrown some sample code below, but ...
[ 3, 2 ]
[]
[]
[ "python", "translate" ]
stackoverflow_0003979092_python_translate.txt
Q: os.getcwd() throws Exception I have situation when the current directory becomes invalid (ie, when some program deletes it). My Python script calls os.getcwd() which terminates with following exception OSError: [Errno 2] No such file or directory Ideally, it my script would automatically cd into parent directory i...
os.getcwd() throws Exception
I have situation when the current directory becomes invalid (ie, when some program deletes it). My Python script calls os.getcwd() which terminates with following exception OSError: [Errno 2] No such file or directory Ideally, it my script would automatically cd into parent directory in such situation. When is the reco...
[ "Ideally, it my script would automatically cd into parent directory in such situation. When is the recommended strategy for implementing this?\nJust use try/except block for that, that's what for we have them :)\ntry:\n os.getcwd()\nexcept OSError:\n os.chdir(\"..\")\n os.getcwd()\n or something similar.....
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006195301_python.txt
Q: Create copy of list and remove element I would like to write something like this S = [ 0, 1, 2 ] F = [ S.without(i) for i in range(0,len(S)) ] print F and Python putting out [ [0,1], [0,2] ,[1,2] ] and have not found something like this in the online reference. Can you help me? A: Python provides itertools.comb...
Create copy of list and remove element
I would like to write something like this S = [ 0, 1, 2 ] F = [ S.without(i) for i in range(0,len(S)) ] print F and Python putting out [ [0,1], [0,2] ,[1,2] ] and have not found something like this in the online reference. Can you help me?
[ "Python provides itertools.combinations, which does exactly what you want:\n>>> import itertools\n>>> s = [0,1,2]\n>>> list(itertools.combinations(s, len(s) - 1))\n[(0, 1), (0, 2), (1, 2)]\n\nEven better, it returns a generator, so you can easily iterate over all combinations without using much memory.\n", ">>> S...
[ 6, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006195381_list_python.txt
Q: Stubs for local Django unittests with Google App Engine I'd like to run local Django unit tests for a Google App Engine project. GAE recently received some python unit testing utilities that allow one to create stubs for e.g. memcache, the datastore, the task queue, etc. I'd like to be able to use Django's unit te...
Stubs for local Django unittests with Google App Engine
I'd like to run local Django unit tests for a Google App Engine project. GAE recently received some python unit testing utilities that allow one to create stubs for e.g. memcache, the datastore, the task queue, etc. I'd like to be able to use Django's unit testing framework. My first thought is to overload DjangoTestSu...
[ "Just wanted to mention: standard django unit testing worked very nice for me with django-nonrel and GAE Test Bed, including task-queues, memcache, etc. I think it is the same python unit testing code that you mentioned.\n" ]
[ 1 ]
[]
[]
[ "django", "google_app_engine", "python", "unit_testing" ]
stackoverflow_0006177274_django_google_app_engine_python_unit_testing.txt
Q: References to methods C# I'm just wondering if there is a C# equivilent for this python code. I want to store the names of methods in some sort of collection and call them later on. I have searched, but I really don't know what to look for. For example in python I could do: def add_one(x): return x + 1 def doubl...
References to methods C#
I'm just wondering if there is a C# equivilent for this python code. I want to store the names of methods in some sort of collection and call them later on. I have searched, but I really don't know what to look for. For example in python I could do: def add_one(x): return x + 1 def double_it(x): return x*2 maths_r...
[ "You are looking for delegates.\n\nA delegate is a type that defines a method signature. When you instantiate a delegate, you can associate its instance with any method with a compatible signature. You can invoke \n (or call) the method through the delegate instance.\n\nYour example in C#, using the Func<T, TResul...
[ 7, 4 ]
[]
[]
[ "c#", "functional_programming", "python" ]
stackoverflow_0006195549_c#_functional_programming_python.txt
Q: Class decorator with class methods I have written a class decorator that monkey-patches a class overwriting the init and adding a method persist (). So far everything OK. Now I need to add a class method (static method) to the decorated class. What do I have to change in my code to make staticMethod() a static met...
Class decorator with class methods
I have written a class decorator that monkey-patches a class overwriting the init and adding a method persist (). So far everything OK. Now I need to add a class method (static method) to the decorated class. What do I have to change in my code to make staticMethod() a static method of the decorated class? This is my c...
[ " @staticmethod\n def staticMethod (): print \"I am static\"\n\nor\n def staticMethod (): print \"I am static\"\n cls.staticMethod = staticmethod(staticMethod)\n\n", "use the @staticmethod decorator.\n@staticmethod\ndef staticMethod() : ...\n\n" ]
[ 3, 1 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0006195698_decorator_python.txt
Q: Possible to use wide-character members in Python extension objects? It's simple to create a member for an object in a Python C extension with a base type of char *, using the T_STRING define in the PyMemberDef declaration. Why does there not seem to be an equivalent for wchar_t *? And if there actually is one, wha...
Possible to use wide-character members in Python extension objects?
It's simple to create a member for an object in a Python C extension with a base type of char *, using the T_STRING define in the PyMemberDef declaration. Why does there not seem to be an equivalent for wchar_t *? And if there actually is one, what is it? e.g. struct object contains char *text PyMemberDef array has {"t...
[ "Using a wchar_t directly is not portable. Instead, Python defines the Py_UNICODE type as the storage unit for a Unicode character. \nDepending on the platform, Py_UNICODE may be defined as wchar_t if available, or an unsigned short/integer/long, the width of which will vary depending on how Python is configured (U...
[ 2 ]
[]
[]
[ "c", "python", "python_extensions", "unicode" ]
stackoverflow_0006193153_c_python_python_extensions_unicode.txt
Q: Django: How do I update a model after a view has been rendered? I have a view that displays a list of models. Some of the properties of some of the models need to be updated after the view has been rendered: that is, the user is expected to see the original, unchanged values on first visit and the updated values o...
Django: How do I update a model after a view has been rendered?
I have a view that displays a list of models. Some of the properties of some of the models need to be updated after the view has been rendered: that is, the user is expected to see the original, unchanged values on first visit and the updated values on successive visits (or upon page reload). I thought I could achieve ...
[ "There's no need for anything clever here. Rendering a template doesn't need to be the end of the view - that only comes when you actually return that as a response. They don't have to be in the same step.\nSo :\ndef my_view(request, params):\n #...do something...\n response = render_to_response('my_template....
[ 9, 0, 0, 0, 0 ]
[]
[]
[ "django", "django_generic_views", "django_views", "python" ]
stackoverflow_0006193974_django_django_generic_views_django_views_python.txt
Q: Python: exec code object within special environment here is a code that I wanna change LD_LIBRARY_PATH to exec a code: #!/usr/bin/python import os code=''' import os print os.getenv("LD_LIBRARY_PATH"); import wrap ''' os.environ['LD_LIBRARY_PATH'] = '/home/dma/python' os.environ["PYTHONPATH"] = '/home/dma/python...
Python: exec code object within special environment
here is a code that I wanna change LD_LIBRARY_PATH to exec a code: #!/usr/bin/python import os code=''' import os print os.getenv("LD_LIBRARY_PATH"); import wrap ''' os.environ['LD_LIBRARY_PATH'] = '/home/dma/python' os.environ["PYTHONPATH"] = '/home/dma/python' exec code The output is: /home/dma/python Traceback (...
[ "It appears as though example.so isn't in /home/dma/python.\n", "I use popen2 to resolve this problem. It works, anyone has a better way?\n" ]
[ 0, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0006134083_c_python.txt
Q: How to stop Python Crashes on exit After a script runs, the Python instance crashes. Error Signature is: AppName pythonw.exe AppVer 0.0.0.0 ModName:ntdll.dll ModVer 5.2.3790.3959 Offset 00020d8e The script sometimes works fine, then other crashes. It launched from with Spyder. When launched outside of Spyder, st...
How to stop Python Crashes on exit
After a script runs, the Python instance crashes. Error Signature is: AppName pythonw.exe AppVer 0.0.0.0 ModName:ntdll.dll ModVer 5.2.3790.3959 Offset 00020d8e The script sometimes works fine, then other crashes. It launched from with Spyder. When launched outside of Spyder, still crashes. The first run seems to work...
[ "When this kind of thing happens, your first move has to be to STOP using pythonw.exe to run the script. Start the script with python.exe so that you get a console window and you can see the traceback message. That will usually tell you what part of the code is causing the crash.\nDid you install Spyder using the P...
[ 8, 1 ]
[]
[]
[ "crash", "python", "pythonw", "spyder" ]
stackoverflow_0006182859_crash_python_pythonw_spyder.txt
Q: Game Engine Remake - Trouble Choosing a Language /API(Java or Python) The engine I've been wanting to remake is from a PlayStation 1 game called Final Fantasy Tactics, and the game is basically a 2.5D game I guess you could say. Low-resolution sprites and textures, and 3D maps for battlefields. The plan is to main...
Game Engine Remake - Trouble Choosing a Language /API(Java or Python)
The engine I've been wanting to remake is from a PlayStation 1 game called Final Fantasy Tactics, and the game is basically a 2.5D game I guess you could say. Low-resolution sprites and textures, and 3D maps for battlefields. The plan is to mainly load the graphics from a disc, or .iso (I already know the sectors the g...
[ "I'd recommend going with PySFML, and, of course, Python.\nIf you do your Python programming correctly , and if you really are willing to fiddle with C or ASM Python plugins for faster computations, you shouldn't really have too much performace hits.\n", "First thing, I wouldn't worry too much about language perf...
[ 0, 0, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0006195508_java_python.txt
Q: Distributing pre-built libraries with python modules I use the following script to distribute a module containing pure python code. from distutils.core import setup, Extension import os setup (name = 'mtester', version = '0.1', description = 'Python wrapper for libmtester', packages=['mtester'...
Distributing pre-built libraries with python modules
I use the following script to distribute a module containing pure python code. from distutils.core import setup, Extension import os setup (name = 'mtester', version = '0.1', description = 'Python wrapper for libmtester', packages=['mtester'], package_dir={'mtester':'module'}, ) The ...
[ "Unfortunately package_data looks for files relative to the top of the package. One fix is to move the helper library under the module dir with the rest of the code:\n% mv lib64/mhelper.so module/\n\nThen modify the package_data argument accordingly:\npackage_data = {'mtester': ['mhelper.so']}\n...\n\nThen test:\n%...
[ 2 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0006191942_distutils_python.txt
Q: What SOAP client libraries exist for Python, and where is the documentation for them? I've never used SOAP before and I'm sort of new to Python. I'm doing this to get myself acquainted with both technologies. I've installed SOAPlib and I've tried to read their Client documentation, but I don't understand it too ...
What SOAP client libraries exist for Python, and where is the documentation for them?
I've never used SOAP before and I'm sort of new to Python. I'm doing this to get myself acquainted with both technologies. I've installed SOAPlib and I've tried to read their Client documentation, but I don't understand it too well. Is there anything else I can look into which is more suited for being a SOAP Client ...
[ "Update (2016):\nIf you only need SOAP client, there is well maintained library called zeep. It supports both Python 2 and 3 :)\n\nUpdate:\nAdditionally to what is mentioned above, I will refer to Python WebServices page which is always up-to-date with all actively maintained and recommended modules to SOAP and all...
[ 406, 48, 19, 11, 9, 6, 4, 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "soap", "soap_client" ]
stackoverflow_0000206154_python_soap_soap_client.txt
Q: About mysql cursor and iterator Imagine I have a mysql cursor and data read. The amount of data might be very big that I want to deal with one line each time. An easy and straight forward way might be like this: while True: row = cursor.fetchone() if not row: break ..... But this doesn't look good, so...
About mysql cursor and iterator
Imagine I have a mysql cursor and data read. The amount of data might be very big that I want to deal with one line each time. An easy and straight forward way might be like this: while True: row = cursor.fetchone() if not row: break ..... But this doesn't look good, so I wonder whether this way works as i...
[ "The MySQLdb cursor class implements the iterator protocol, so you can simply do this:\ncursor.execute(sql)\nfor row in cursor:\n print row\n ...\n\nRelevant code from MySQLdb.cursors.BaseCursor:\ndef __iter__(self):\n return iter(self.fetchone, None)\n\n" ]
[ 49 ]
[]
[]
[ "database_cursor", "fetchall", "mysql", "python" ]
stackoverflow_0006195988_database_cursor_fetchall_mysql_python.txt
Q: Python ctypes calling reboot() from libc on Linux I'm trying to call the reboot function from libc in Python via ctypes and I just can not get it to work. I've been referencing the man 2 reboot page (http://linux.die.net/man/2/reboot). My kernel version is 2.6.35. Below is the console log from the interactive Pyt...
Python ctypes calling reboot() from libc on Linux
I'm trying to call the reboot function from libc in Python via ctypes and I just can not get it to work. I've been referencing the man 2 reboot page (http://linux.die.net/man/2/reboot). My kernel version is 2.6.35. Below is the console log from the interactive Python prompt where I'm trying to get my machine to reboot...
[ "Try:\n>>> libc = CDLL('libc.so.6', use_errno=True)\n\nThat should allow get_errno() to work.\n[update]\nAlso, the last argument is a void *. If this is a 64-bit system, then the integer 0 is not a valid repesentation for NULL. I would try None or maybe c_void_p(None). (Not sure how that could matter in this con...
[ 4, 3 ]
[]
[]
[ "c", "ctypes", "libc", "linux", "python" ]
stackoverflow_0006195575_c_ctypes_libc_linux_python.txt
Q: Jinja2: Render template inheritance? I'd like to render a fused Jinja2 and Markdown page using a template, which looks like so: {% block title %}{{ title }}{% endblock %} # {{ title[0] }} # {{ title[1] }} ## Introduction I can get that above code to generate HTML fine, but as I am using this script for a custom...
Jinja2: Render template inheritance?
I'd like to render a fused Jinja2 and Markdown page using a template, which looks like so: {% block title %}{{ title }}{% endblock %} # {{ title[0] }} # {{ title[1] }} ## Introduction I can get that above code to generate HTML fine, but as I am using this script for a custom authoring application, I'd like to be abl...
[ "Jinja's renderer needs to know how to load template.html, so you need to give the Environment a template loader instance.\nFor example, assuming the files page.html and template.html are in the current directory:\nfrom jinja import FileSystemLoader\nfrom jinja.environment import Environment\n\nenv = Environment()\...
[ 21 ]
[]
[]
[ "extend", "jinja2", "python" ]
stackoverflow_0006195805_extend_jinja2_python.txt
Q: Python: Implementing a series of functions with each one calling the next programming isn't my field, but I'm trying to learn. I've been writing a program that works something like this: from Tkinter import * root=Tk() def Secondwindow(): firstframe.destroy() secondframe = Frame(root) secondframe.pack...
Python: Implementing a series of functions with each one calling the next
programming isn't my field, but I'm trying to learn. I've been writing a program that works something like this: from Tkinter import * root=Tk() def Secondwindow(): firstframe.destroy() secondframe = Frame(root) secondframe.pack() secondcontent = Label(secondframe, text = 'second window content').pack(...
[ "I un-nested the functions to see what the error was. The problem you have is that the functions try to access variables defined in the scope of another function. That won't work. You either have to nest functions so that their scopes overlap, as you did -- which is awkward -- or you have to use global variables --...
[ 2, 1, 1 ]
[]
[]
[ "function", "nameerror", "python" ]
stackoverflow_0006195790_function_nameerror_python.txt
Q: Content-based routing with RabbitMQ and Python Is it possible with RabbitMQ and Python to do content-based routing? The AMQP standard and RabbitMQ claims to support content-based routing, but are there any libraries for Python which support specifying content-based bindings etc.? The library I am currently using (...
Content-based routing with RabbitMQ and Python
Is it possible with RabbitMQ and Python to do content-based routing? The AMQP standard and RabbitMQ claims to support content-based routing, but are there any libraries for Python which support specifying content-based bindings etc.? The library I am currently using (py-amqplib http://barryp.org/software/py-amqplib/) s...
[ "The answer is \"yes\", but there's more to it... :)\nLet's first agree on what content-based routing means. There are two possible meanings. Some people say that it is based on the header portion of a message. Others say it's based on the data portion of a message.\nIf we take the first definition, these are more ...
[ 20, 6 ]
[]
[]
[ "amqp", "python", "rabbitmq", "routing" ]
stackoverflow_0003280676_amqp_python_rabbitmq_routing.txt
Q: Problems with easy_install --upgrade pytz easy_install was good and very helpful. I have been using it. However, I found it unfunctioning today. error msg: #easy_install --upgrade pytz -bash: /usr/local/bin/easy_install: /usr/bin/python2.6: bad interpreter: No such file or directory I think it is caused by my rei...
Problems with easy_install --upgrade pytz
easy_install was good and very helpful. I have been using it. However, I found it unfunctioning today. error msg: #easy_install --upgrade pytz -bash: /usr/local/bin/easy_install: /usr/bin/python2.6: bad interpreter: No such file or directory I think it is caused by my reinstallation of python and the one I am using is...
[ "Open /usr/local/bin/easy_install in a text editor and examine the first line; you'll probably see something like this:\n #!/usr/bin/python2.6\n\nThis shebang line tells the kernel which command it should execute to evaluate the script body. The error message indicates that /usr/bin/python2.6 is missing. \nTo fix t...
[ 6, 2 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0006196111_easy_install_python.txt
Q: Create a script that runs at 15 minute intervals during working hours of a week From Monday to Friday, 9 am to 4 pm I want to hit a specific URI. If the hit succeeds, I want to create/overwrite a file (this part is done). I am not sure if doing this using a cron job will be better or creating a background service ...
Create a script that runs at 15 minute intervals during working hours of a week
From Monday to Friday, 9 am to 4 pm I want to hit a specific URI. If the hit succeeds, I want to create/overwrite a file (this part is done). I am not sure if doing this using a cron job will be better or creating a background service will be better. I intend to run this on a VPS with 1 GB of RAM. I know it's very litt...
[ "I would vote for the cron job—it's easy enough to add a line to the crontab, or even put a custom file in the /etc/cron.d directory as follows:\n*/15 9-16 * * 1-5 user /your/script/here\n\n[EDIT] from comments:\nIn terms of performance and resources, neither is terribly demanding (assuming your script is well writ...
[ 5 ]
[]
[]
[ "background_process", "cron", "python" ]
stackoverflow_0006196355_background_process_cron_python.txt
Q: Porting the python interpreter to a custom operating system I am looking for resources that I could go through to port the python interpreter to a custom OS (with an implementation similar to DOS but not DOS itself). What are some important points I should keep in mind? Is the complete port of python restricted on...
Porting the python interpreter to a custom operating system
I am looking for resources that I could go through to port the python interpreter to a custom OS (with an implementation similar to DOS but not DOS itself). What are some important points I should keep in mind? Is the complete port of python restricted only by limitations of the OS or could there be more complexities t...
[ "You should probably have a look at Python 2.4.2 for DOS here http://www.caddit.net/pythond/downloads.php\nAnd also check out all the other stuff ported to DOS using the DJGPP port of gcc. In addition Python has been ported to OS\\2 which is DOS-like but not DOS. I believe it may have been done using a relative of ...
[ 3 ]
[]
[]
[ "operating_system", "porting", "python" ]
stackoverflow_0006086082_operating_system_porting_python.txt
Q: Sorting Lists by Repetitions in Python I have a list that contains multiple repeated items. I'm trying to sort the list by giving items with the most repetitions priority. So it would turn this ['a', 'b', 'c', 'a', 'b', 'a', 'd'] into this ['a', 'a', 'a', 'b', 'b', 'c', 'd'] A: d = {} for a in l: d[a] += d...
Sorting Lists by Repetitions in Python
I have a list that contains multiple repeated items. I'm trying to sort the list by giving items with the most repetitions priority. So it would turn this ['a', 'b', 'c', 'a', 'b', 'a', 'd'] into this ['a', 'a', 'a', 'b', 'b', 'c', 'd']
[ "d = {}\nfor a in l:\n d[a] += d.setdefault(a,0)\n\nl.sort(key = lambda k: (d[k],k), reverse = True)\n\n", ">>> from collections import Counter\n>>> [k for k,v in Counter(['a', 'b', 'c', 'a', 'b', 'a', 'd']).most_common() for i in xrange(v)]\n['a', 'a', 'a', 'b', 'b', 'c', 'd']\n\nThis is possibly easier to fo...
[ 5, 5, 2, 1 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0006196416_list_python_sorting.txt
Q: Why do I get this thread error? I have this code: import urllib2 import thread a = 0 def workers(): while 1: a+=1 silva = urllib2.urlopen('http://en.dilandau.eu/download_music/said-the-whale-'+str(a)+'.html') si = silva.read() if 'var playlist' not in si: print a ...
Why do I get this thread error?
I have this code: import urllib2 import thread a = 0 def workers(): while 1: a+=1 silva = urllib2.urlopen('http://en.dilandau.eu/download_music/said-the-whale-'+str(a)+'.html') si = silva.read() if 'var playlist' not in si: print a break thread.start_new_t...
[ "I ran a simpler version of your code and see a stack trace besides the Unhandled Exception message. It should help you to locate the problem.\nThere are a few improvement you should consider. First of all there is a high level library threading that is recommended over thread. Secondly you are doing a busy wait wi...
[ 2, 1, 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0006195745_python_urllib2.txt
Q: Display data in (%) for pie chart using the PyChart library in Python I am creating a pie chart using PyChart library in Python. Here is my code: from pychart import * import sys data = [("foo", 10), ("bar", 20), ("baz", 30), ("ao", 40)] theme.use_color = True theme.get_options() ar = area.T(size = (150, 150), l...
Display data in (%) for pie chart using the PyChart library in Python
I am creating a pie chart using PyChart library in Python. Here is my code: from pychart import * import sys data = [("foo", 10), ("bar", 20), ("baz", 30), ("ao", 40)] theme.use_color = True theme.get_options() ar = area.T(size = (150, 150), legend = legend.T(), x_grid_style = None, y_grid_style = None) ...
[ "Would converting the data to percentages before passing it to the plot function work?\nFor example:\ndef to_percents(data):\n total = float(sum(v for _, v in data))\n data[:] = [(k, v / total) for k, v in data]\n return data\n\ndata = to_percents([(\"foo\", 1), (\"bar\", 3), (\"baz\", 5), (\"ao\", 7)])\np...
[ 2 ]
[]
[]
[ "charts", "pie_chart", "python" ]
stackoverflow_0006196573_charts_pie_chart_python.txt
Q: Editing tree in place while iterating in lxml I am using lxml to parse html and edit it to produce a new document. Essentially, I'm trying to use it somewhat like the javascript DOM - I know this is not really the intended use, but much of it works well so far. Currently, I use iterdescendants() to get a iterable...
Editing tree in place while iterating in lxml
I am using lxml to parse html and edit it to produce a new document. Essentially, I'm trying to use it somewhat like the javascript DOM - I know this is not really the intended use, but much of it works well so far. Currently, I use iterdescendants() to get a iterable list of elements and then deal with each in turn. ...
[ "To simplify things you can use lxml's support for regular expressions within an XPath to find and kill the unwanted nodes without needing to iterate over all descendants. \nThis produces the same result as your script:\nEXSLT_NS = 'http://exslt.org/regular-expressions'\nXPATH = r\"//*[re:test(@class, '\\bunwanted...
[ 5 ]
[]
[]
[ "html_parsing", "lxml", "parsing", "python" ]
stackoverflow_0006152364_html_parsing_lxml_parsing_python.txt
Q: seek a better design suggestion for a trial-and-error mechanism in python? See below data matrix get from sensors, just INT numbers, nothing specical. A B C D E F G H I J K 1 25 0 25 66 41 47 40 12 69 76 1 2 17 23 73 97 99 39 84 26 0 44 45 3 34 15 55 4 77 2...
seek a better design suggestion for a trial-and-error mechanism in python?
See below data matrix get from sensors, just INT numbers, nothing specical. A B C D E F G H I J K 1 25 0 25 66 41 47 40 12 69 76 1 2 17 23 73 97 99 39 84 26 0 44 45 3 34 15 55 4 77 2 96 92 22 18 71 4 85 4 71 99 66 42 28 41 27 39 75 5 65 27 ...
[ "If I understand what you're asking correctly, I probably wouldn't even venture down the Numbpy path as I don't think given your description that it's really required. Here's a sample implementation of how I might go about solving the specific issue that you presented:\nl = [\\\n {'a':25, 'b':0, 'c':25, 'd':...
[ 1, 0 ]
[]
[]
[ "calculus", "functional_programming", "python" ]
stackoverflow_0006196767_calculus_functional_programming_python.txt
Q: How can I do comparison in List of dictionaries for key values? I have this list of dictionary below. What i want is to search for same "alias" and add their score to combine them into a single dictionary and make a cleaner list. d=[{"alias": "2133232", "score": 144}, {"alias": "u234243", "score": 34}, {"alias": "...
How can I do comparison in List of dictionaries for key values?
I have this list of dictionary below. What i want is to search for same "alias" and add their score to combine them into a single dictionary and make a cleaner list. d=[{"alias": "2133232", "score": 144}, {"alias": "u234243", "score": 34}, {"alias": "u234243", "score": 34},{"alias": "2133232", "score": 14}, {"alias": "...
[ "Python 2.5:\nfrom collections import defaultdict \n\nh = defaultdict(int)\nfor i in d:\n h[i['alias']] += i['score']\n\n", "In Python 3.1+:\nimport collections\nres = collections.Counter()\nfor dct in d:\n res[dct['alias']] += dct['score']\nprint(repr(res))\n\nBefore 3.1, you can either use this Counter cla...
[ 2, 1, 1 ]
[]
[]
[ "list", "python", "search" ]
stackoverflow_0006197197_list_python_search.txt
Q: Looping through dictionary to insert value to an object Consider I have the following dictionary: dic={} dic["var1"]=val1 dic["var2"]=val2 Now I have another object which contains two properties: var1 and var2 . I would like to run a loop within the object's method such as (pseudo code): for key, value in dic s...
Looping through dictionary to insert value to an object
Consider I have the following dictionary: dic={} dic["var1"]=val1 dic["var2"]=val2 Now I have another object which contains two properties: var1 and var2 . I would like to run a loop within the object's method such as (pseudo code): for key, value in dic self.key=value so that self.var1=val2 and self.var2=val2 How ...
[ ">>> class Obj(object):\n... pass\n... \n>>> obj = Obj()\n>>> for key, value in {'var1':5, 'var2':6}.iteritems():\n... setattr(obj, key, value)\n... \n>>> obj.var1\n5\n>>> obj.var2\n6\n\nHere I am obligated to say something like \"why not just use a dict?\"\n", "You can use \"setattr\":\nclass Test:\n va...
[ 3, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006197357_python.txt
Q: Creating undirected graphs in Python I need to create a program that analyzes the traveling salesman problem using Python. Does anyone know of a good resource that will help me learn how to create and use undirected graphs in Python? Any info that may help me with the TSP would be greatly appreciated as well. A: ...
Creating undirected graphs in Python
I need to create a program that analyzes the traveling salesman problem using Python. Does anyone know of a good resource that will help me learn how to create and use undirected graphs in Python? Any info that may help me with the TSP would be greatly appreciated as well.
[ "About Python library for directed and undirected graphs, you can take a look at igraph or NetworkX. \nAs for the TSP, a little googling indicates that some Python code and discussion is available here, and some background is given in these slides, A Short History of the Traveling Salesman Problem, and on this page...
[ 2 ]
[]
[]
[ "graph", "python" ]
stackoverflow_0006197339_graph_python.txt
Q: Getting the data for a pie chart Say, I have a model that defines a Car and one of its field is 'manufacturer'. For example: class Car(models.Model): manufacturer = models.CharField(max_length=50) color = models.CharField(max_length=50) licence_plate = models.CharField(max_length=50) . . . ...
Getting the data for a pie chart
Say, I have a model that defines a Car and one of its field is 'manufacturer'. For example: class Car(models.Model): manufacturer = models.CharField(max_length=50) color = models.CharField(max_length=50) licence_plate = models.CharField(max_length=50) . . . To draw a pie chart showing the total...
[ "Not sure this is quite correct, but you need something like:\nfrom django.db.models import Count, Sum\n\nnum_taken = 5 # modify this if you want more/less than 5\nquery = Car.objects.values('manufacturer').annotate(num_cars=Count('manufacturer')).order_by('-num_cars')\ntop_cars = query[:num_taken]\nothers = query...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006197609_django_python.txt
Q: Similar functionality for java to struct for python I have a program that I made in Python to find specific tags in TIFF IFD's and return the values. It was just a proof of concept thing in python, and now I need to move the functionality to java. I think I can just use the String(byteArray[]) constructor for the ...
Similar functionality for java to struct for python
I have a program that I made in Python to find specific tags in TIFF IFD's and return the values. It was just a proof of concept thing in python, and now I need to move the functionality to java. I think I can just use the String(byteArray[]) constructor for the ASCII data types, but I still need to get Unsigned short ...
[ "DataInputStream allows you to read shorts and longs. You should mask them with the appropriate bit mask (0xFFFF for short, 0xFFFFFFFF for 32 bit) in order to account for the difference between signed/unsigned types.\ne.g.\n// omits error handling\nFileInputStream fis = ...;\nDataInputStream stream = new DataInput...
[ 5, 2, 2, 1, 1 ]
[]
[]
[ "image", "java", "python", "tiff" ]
stackoverflow_0006111988_image_java_python_tiff.txt
Q: Converting a Youtube Upload into Podcast There is this youtube channel that uploads one videos per week at exactly the same time every week. Is it somewhat possible to create a python script that creates a podcast out of it. What Library should I be learning to make this thing possible or is it even possible in th...
Converting a Youtube Upload into Podcast
There is this youtube channel that uploads one videos per week at exactly the same time every week. Is it somewhat possible to create a python script that creates a podcast out of it. What Library should I be learning to make this thing possible or is it even possible in the first place? Thanks
[ "Interesting. There are legal blah blah blah rights blah blah blah... but you know that already.\nI would think if you have a link that auto-plays on page open you could use webbrowser with PyAudio as a simple way to rip the audio from a youtube video. This would require you to play the whole thing and doesn't tak...
[ 2, 2 ]
[]
[]
[ "podcast", "python", "youtube" ]
stackoverflow_0006196918_podcast_python_youtube.txt
Q: Python: How to implement a static list in a class referencing all created items and an easy way to delete the items? I have a class that stores all created references in a static list like this: class A: _List = [] def __init__(self): A._List.append(self) def __del__(self): A._List.re...
Python: How to implement a static list in a class referencing all created items and an easy way to delete the items?
I have a class that stores all created references in a static list like this: class A: _List = [] def __init__(self): A._List.append(self) def __del__(self): A._List.remove(self) Now if I do the following: a = A() del a a is not deleted, since it is still referenced to in the list. But t...
[ "You can use weakref.WeakValueDictionary (or weakref.WeakKeyDictionary), it would automatcally remove any elements that do not exist anymore:\nclass A(object):\n _instances = weakref.WeakValueDictionary()\n _next_id = functools.partial(next, itertools.count())\n\n def __init__(self):\n self._instanc...
[ 5, 1 ]
[]
[]
[ "destructor", "list", "python", "static" ]
stackoverflow_0006198230_destructor_list_python_static.txt
Q: how do i get a domain to trigger i18n in django So over the last few weeks I have been preparing a few different languages for our platform and was wondering how you go about getting a domain name to activate a certain language? For instance, if I have site with 5 languages. Swedish, English, Norwegian, Danish and...
how do i get a domain to trigger i18n in django
So over the last few weeks I have been preparing a few different languages for our platform and was wondering how you go about getting a domain name to activate a certain language? For instance, if I have site with 5 languages. Swedish, English, Norwegian, Danish and Finnish and one of my users visit the www.domainname...
[ "With httpd, just use RequestHeader to frob the Accept-Language header for the virtual host, since Django looks at it to discover language preference.\nRequestHeader append Accept-Language sv-se\n\n" ]
[ 0 ]
[]
[]
[ "django", "dns", "internationalization", "python" ]
stackoverflow_0006198691_django_dns_internationalization_python.txt
Q: Python: Closing and removing files I'm trying to unzip a file, and read one of the extracted files, and delete the extracted files. Files extracted (e.g. we got file1 and file2) Read file1, and close it. with open(file1, 'r') as f: data = f.readline() f.close() Do something with the "data". Remove the files ...
Python: Closing and removing files
I'm trying to unzip a file, and read one of the extracted files, and delete the extracted files. Files extracted (e.g. we got file1 and file2) Read file1, and close it. with open(file1, 'r') as f: data = f.readline() f.close() Do something with the "data". Remove the files extracted. os.remove(file1) Everythin...
[ "No need to close a file handle when using with with a file context manager, the handle is automatically closed when the scope have changed, i.e. when readline is done.\nSee python tutorial\n", "The errors you see are not errors as Python would report them. They mean something other than Python tried to open thes...
[ 3, 2 ]
[]
[]
[ "file", "python" ]
stackoverflow_0006198369_file_python.txt
Q: Python sorting a list of strings How would I sort this? >>> list = ["a_0","a_1","a_2","a_3","a_10","a_11","a_23","a_5","a_6","a_5"] >>> sorted(list) ['a_0', 'a_1', 'a_10', 'a_11', 'a_2', 'a_23', 'a_3', 'a_5', 'a_5', 'a_6']> What I need it to be is: ['a_0', 'a_1', 'a_2', 'a_3', 'a_5', 'a_5', 'a_6, 'a_10', 'a_11', ...
Python sorting a list of strings
How would I sort this? >>> list = ["a_0","a_1","a_2","a_3","a_10","a_11","a_23","a_5","a_6","a_5"] >>> sorted(list) ['a_0', 'a_1', 'a_10', 'a_11', 'a_2', 'a_23', 'a_3', 'a_5', 'a_5', 'a_6']> What I need it to be is: ['a_0', 'a_1', 'a_2', 'a_3', 'a_5', 'a_5', 'a_6, 'a_10', 'a_11', 'a_23']> So it's sorted based on the ...
[ "do you mean this: sorted(list, key=lambda d: int(d[2:])) ?\n", "You need to write a \"key function\" that translates your string into a search key that has the ordering you want. For example:\ndef key(k):\n s, sep, i = k.partition('_')\n return (s, int(i))\n\n>>> L = [\"a_0\",\"a_1\",\"b_2\",\"c_2\",\"a_...
[ 10, 6 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0006198836_python_sorting.txt
Q: python html parsing i need do some html parsing use python .if i have a html file like bellow: 《body》 《div class="mydiv"》 《p》i want got it《/p》 《div》 《p》 good 《/p》 《a》 boy 《/a》 《/div》 《/div》 《/body》 how can i get the content of 《div class="mydiv"》 ,say , i want got . ...
python html parsing
i need do some html parsing use python .if i have a html file like bellow: 《body》 《div class="mydiv"》 《p》i want got it《/p》 《div》 《p》 good 《/p》 《a》 boy 《/a》 《/div》 《/div》 《/body》 how can i get the content of 《div class="mydiv"》 ,say , i want got . 《p》i want got it《/p...
[ "With BeautifulSoup it is as simple as:\nfrom BeautifulSoup import BeautifulSoup\n html = \"\"\"\n <body>\n <div class=\"mydiv\">\n <p>i want got it</p>\n <div>\n <p> good </p>\n <a> boy </a>\n </div>\n </div>\n </body>\n \"\"\"\n\n ...
[ 5, 4, 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0006198107_html_python.txt
Q: Modify/replace a line in a python file using another python file I am trying to replace/modify a part of string in a python file from another python file. The line I am trying to replace in other PY is : a.setSystemFile('D:/test/f.xml') I would like to replace the part of this line i.e. the xml path string with ...
Modify/replace a line in a python file using another python file
I am trying to replace/modify a part of string in a python file from another python file. The line I am trying to replace in other PY is : a.setSystemFile('D:/test/f.xml') I would like to replace the part of this line i.e. the xml path string with different xml path: Example: a.setSystemFile('C:/try/X.xml') My code...
[ "You forgot to do something if the line doesn't start with that text.\nfor line in lines:\n if line.startswith('a.setSystemFile'):\n f.write(line.replace('D:/test/f.xml','C:/try/X.xml'))\n else:\n f.write(line)\n\nAlso, might I suggest just using sed for this?\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006199006_python.txt
Q: convert php script to python I try to convert a PHP script to Python $texte = file_get_contents("../test/detail-20110503_10"); preg_match_all("#Acct-Status-Type(.*)Timestamp#Ums", $texte, $blocs); $nbBlocks = count($blocs[0]); for ($i = 0; $i < $nbBlocks; $i++) { preg_match('#Acme-Session-Egress-Realm...
convert php script to python
I try to convert a PHP script to Python $texte = file_get_contents("../test/detail-20110503_10"); preg_match_all("#Acct-Status-Type(.*)Timestamp#Ums", $texte, $blocs); $nbBlocks = count($blocs[0]); for ($i = 0; $i < $nbBlocks; $i++) { preg_match('#Acme-Session-Egress-Realm = "(.*)\"#i', $blocs[0][$i], $Ses...
[ "you can read certain length of content by passing a param to read() function, like read(100)\nor you can use readline() to get a single line at a time\n" ]
[ 0 ]
[]
[]
[ "php", "python", "regex" ]
stackoverflow_0006199001_php_python_regex.txt
Q: Compiling script files Lua or Python I will separate my business code into a script language. it would be Lua or Python. My question is my business code written in script file is viewable by others. Because of script file will not compiled that is open. Anyone can see it. How can I hide it? I think if I use Pytho...
Compiling script files Lua or Python
I will separate my business code into a script language. it would be Lua or Python. My question is my business code written in script file is viewable by others. Because of script file will not compiled that is open. Anyone can see it. How can I hide it? I think if I use Python, it would be compiled (.pyo), but Lua lo...
[ "You can compile Lua scripts with luac:\nluac -s -o yourscript.luc yourscript.lua\n\nUsing the flag -s will also remove debugging information, thus making it also a little bit smaller.\n", "You will not be able to hide this easily. You can encrypt and decipher on the fly. The problem is that people will be able t...
[ 5, 1, 1 ]
[]
[]
[ "compilation", "lua", "obfuscation", "python" ]
stackoverflow_0006197760_compilation_lua_obfuscation_python.txt
Q: Ant simulation: it's better to create a Process/Thread for each Ant or something else? The simple study is: Ant life simulation I'm creating an OO structure that see a Class for the Anthill, a Class for the Ant and a Class for the whole simulator. Now I'm brainstorming on "how to" make Ants 'live'... I know that t...
Ant simulation: it's better to create a Process/Thread for each Ant or something else?
The simple study is: Ant life simulation I'm creating an OO structure that see a Class for the Anthill, a Class for the Ant and a Class for the whole simulator. Now I'm brainstorming on "how to" make Ants 'live'... I know that there are projects like this just started but I'm brainstorming, I'm not looking for a just-r...
[ "I would recommend to have a look at stackless. Stackless introduces tasklets which are akind of microthreads which allows to get the benefits of thread-based programming without the performance and complexity problems associated with conventional threads\nA possible problem with stackless is, that as far as i kn...
[ 4, 3, 2, 1, 1 ]
[]
[]
[ "multiprocess", "multithreading", "python", "resources", "simulation" ]
stackoverflow_0006189398_multiprocess_multithreading_python_resources_simulation.txt
Q: How can keep my libraries , modules or jar files Synced across diff projects I am doing various projects acroos diff computers , servers and diff languages like php python java etc. Now on every computer i have to install / download various supporting libraries like javascript libraries for PHP , Jar files for Jav...
How can keep my libraries , modules or jar files Synced across diff projects
I am doing various projects acroos diff computers , servers and diff languages like php python java etc. Now on every computer i have to install / download various supporting libraries like javascript libraries for PHP , Jar files for Java and many python modules. Is there way so that i can make online folder on server...
[ "Maybe get some version management on the job, which is synced to the server e.g. GitHub or BitBucket.\n", "I would suggest taking planetjones version management idea (GIT or SVN), and pairing that up with scripts to setup the required libraries in your environment. If you've different python environments - I fou...
[ 2, 0, 0 ]
[]
[]
[ "java", "linux", "php", "python", "sync" ]
stackoverflow_0006198941_java_linux_php_python_sync.txt
Q: Best way to document a Python module which is generated by the C API? I have embedded and extended python inside my C application and I now want to document this. I have defined a module using the C API, therefore pydoc tool will not see it (right?). Thus far the best way I can think is to use the 'pydoc' module o...
Best way to document a Python module which is generated by the C API?
I have embedded and extended python inside my C application and I now want to document this. I have defined a module using the C API, therefore pydoc tool will not see it (right?). Thus far the best way I can think is to use the 'pydoc' module on my module at runtime (therefore the extension module I defined will be pr...
[ "I'm not sure exactly how you've use the C-API (since you've just said that you've embedded and extended Python in your C application). \nHowever, pydoc imports a module and uses introspection to generate documentation for the module so if you run it on your compiled module, it will still work. The point is that it...
[ 0 ]
[]
[]
[ "api", "c", "pydoc", "python" ]
stackoverflow_0006199695_api_c_pydoc_python.txt
Q: Deciding which exceptions to catch in Python Suppose that I am using a library X that specifies for example that exception.BaseError is the base class for all exceptions of X. Now, there is another exception, say X.FooError, which of course inherits from exception.BaseError but is more generalized, let's say that ...
Deciding which exceptions to catch in Python
Suppose that I am using a library X that specifies for example that exception.BaseError is the base class for all exceptions of X. Now, there is another exception, say X.FooError, which of course inherits from exception.BaseError but is more generalized, let's say that it handles invalid input. Let's suppose there are ...
[ "Catch only the exceptions you can handle. If you can handle both the base exception and the derived exception then catch both. But make sure to put the derived exception first, since the first exception handler found that matches is the one used.\ntry:\n X.foo()\nexcept X.FooError:\n pass\nexcept X.BaseError:\n ...
[ 10, 3, 2 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0006199884_exception_handling_python.txt
Q: Running C++ code alongside and interacting with Python So my current project is mostly in Python, but I'm looking to rewrite the most computationally expensive portions in C++ to try and boost performance. Much of this I can achieve via simple functions loaded from DLL files, but not everything. I have a multidi...
Running C++ code alongside and interacting with Python
So my current project is mostly in Python, but I'm looking to rewrite the most computationally expensive portions in C++ to try and boost performance. Much of this I can achieve via simple functions loaded from DLL files, but not everything. I have a multidimensional array in Python that I want to perform operations ...
[ "First and foremost, when you are working with multidimensional arrays in Python, you should really be using NumPy. Chances are that your program is already fast enough when you let NumPy do the number crunching (use Array arithmetic instead of Python for loops).\nIf this is not enough, consider writing parts of y...
[ 4, 0 ]
[]
[]
[ "a_star", "c++", "dll", "multidimensional_array", "python" ]
stackoverflow_0006199872_a_star_c++_dll_multidimensional_array_python.txt
Q: Python development - elementtree XML and string operations I am using ElementTree to load up a series of XML files and parse them. As a file is parsed, I am grabbing a few bits of data from it ( a headline and a paragraph of text). I then need to grab some file names that are stored in the XML. They are contained...
Python development - elementtree XML and string operations
I am using ElementTree to load up a series of XML files and parse them. As a file is parsed, I am grabbing a few bits of data from it ( a headline and a paragraph of text). I then need to grab some file names that are stored in the XML. They are contained in an element called ContentItem. My code looks a bit like this...
[ "You get a tuple because you supply a tuple (the parentheses) as the default return value for url.get(). Supply an empty string, and you can use its .endswith() method. Also note that the element itself has a get() method to retrieve attribute values (you do not have to go via .attrib). Example:\nif i.get('Href', '...
[ 2 ]
[]
[]
[ "django", "elementtree", "python" ]
stackoverflow_0006198991_django_elementtree_python.txt
Q: Application based on feedparser Is there an application based on python library feedparser that works under Ubuntu and shows scheduling and storage of feeds? thank you A: Maybe one of these? Planet Venus rawdog
Application based on feedparser
Is there an application based on python library feedparser that works under Ubuntu and shows scheduling and storage of feeds? thank you
[ "Maybe one of these?\n\nPlanet\nVenus \nrawdog\n\n" ]
[ 2 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0006198009_feedparser_python.txt
Q: Determining whether a folder is in a file path I am working on a backup script in Python, and would like it to be able to ignore folders. I therefore have a list of folders to be ignored, ie ['Folder 1', 'Folder3']. I am using os.walk, and am trying to get it to skip any folder in the ignored folders list or that ...
Determining whether a folder is in a file path
I am working on a backup script in Python, and would like it to be able to ignore folders. I therefore have a list of folders to be ignored, ie ['Folder 1', 'Folder3']. I am using os.walk, and am trying to get it to skip any folder in the ignored folders list or that has any of the ignored folders as a parent directory...
[ "From the docs:\n\nWhen topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() ...
[ 2, 0 ]
[]
[]
[ "filepath", "python", "regex" ]
stackoverflow_0006200108_filepath_python_regex.txt
Q: Why can't I do SHOW PROCESSLIST with QtSql (PyQT)? I am a Python and QT newbie. I am trying to do a little app with PyQT4 in order to supervise a home MySQL server of mine, so my first idea was to do the classic SHOW PROCESSLIST, parse it, and show in a pretty UI. Nothing big, really. But for some reason, the QtSq...
Why can't I do SHOW PROCESSLIST with QtSql (PyQT)?
I am a Python and QT newbie. I am trying to do a little app with PyQT4 in order to supervise a home MySQL server of mine, so my first idea was to do the classic SHOW PROCESSLIST, parse it, and show in a pretty UI. Nothing big, really. But for some reason, the QtSql module doesn't return anything when doing this query, ...
[ "I don't know what is wrong, but in recent versions of MySQL you can work it around using information_schema.processlist:\nSELECT * FROM INFORMATION_SCHEMA.PROCESSLIST\n\n", "I don't know if you already tried this, but what about adding an ';'?\nq.exec_(\"SHOW PROCESSLIST;\")\n\nI have never worked with QtSQL but...
[ 1, 0 ]
[]
[]
[ "mysql", "pyqt", "python", "qt" ]
stackoverflow_0001589231_mysql_pyqt_python_qt.txt
Q: lxml only loading a single network entity before raising XMLSyntaxError I am writing code to work with Amazon query based APIs, which return XML which I then wish to parse with lxml. I have written several functions which work perfectly to load the XML and parse it. Each function loads the XML using: variable = lx...
lxml only loading a single network entity before raising XMLSyntaxError
I am writing code to work with Amazon query based APIs, which return XML which I then wish to parse with lxml. I have written several functions which work perfectly to load the XML and parse it. Each function loads the XML using: variable = lxml.etree.parse("http://...") This works perfectly, the FIRST time it is run....
[ "Known unfixed bug.\nUse urllib2.urlopen() to get a file-like object and pass that to lxml.etree.parse()\n" ]
[ 3 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0006199666_lxml_python.txt
Q: Dictionary of dictionaries: print dictionaries that share at least two common keys d = {'g1':{'p1':1,'p2':5,'p3':11,'p4':1}, 'g2':{'p1':7,'p3':1,'p4':2,'p5':8,'p9':11}, 'g3':{'p7':7,'p8':7}, 'g4':{'p8':9,'p9':1,'p10':7,'p11':8,'p12':3}, 'g5':{'p1':4,'p13':1}, 'g6':{'p1':4,'p3':1,'p6':2,'p1...
Dictionary of dictionaries: print dictionaries that share at least two common keys
d = {'g1':{'p1':1,'p2':5,'p3':11,'p4':1}, 'g2':{'p1':7,'p3':1,'p4':2,'p5':8,'p9':11}, 'g3':{'p7':7,'p8':7}, 'g4':{'p8':9,'p9':1,'p10':7,'p11':8,'p12':3}, 'g5':{'p1':4,'p13':1}, 'g6':{'p1':4,'p3':1,'p6':2,'p13':1} } For a given dictionary 'd' I want to return clusters of sub-dictionaries th...
[ "I hope I understood correctly what you want. The approach is clumsy and I fear it is highly inefficient.\nI added a dictionary g6 to d in order to produce a more interesting output:\n#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nd = {'g1':{'p1':1,'p2':5,'p3':11,'p4':1},\n 'g2':{'p1':7,'p3':1,'p4':2,'p5':8...
[ 2, 0, 0, 0 ]
[]
[]
[ "dictionary", "intersection", "key", "python" ]
stackoverflow_0006193489_dictionary_intersection_key_python.txt
Q: Python fromfile returning incorrect values when reading binary file generated with tofile I found several similar questions but none of them described exactly the problem I'm facing. I've an OBJ file which contains lines describing vertex positions: v 0.01214 0.4242 0.82874 I want to transform this data into a mat...
Python fromfile returning incorrect values when reading binary file generated with tofile
I found several similar questions but none of them described exactly the problem I'm facing. I've an OBJ file which contains lines describing vertex positions: v 0.01214 0.4242 0.82874 I want to transform this data into a matlab-friendly format so that I can plot some data with these and other values obtained from othe...
[ "Most probably, the error is in the code you din't show. The out_file parameter to extract_verts() seems to be an open file object, and it is important that you open this file in binary mode:\nout_file = open(\"out.dat\", \"wb\")\n\nFiles are opened in text mode by default. On Windows, this means automatic newlin...
[ 1 ]
[]
[]
[ "binary_data", "numpy", "python" ]
stackoverflow_0006198391_binary_data_numpy_python.txt
Q: Selenium seems to work, but then gets a timeout error? $ java -jar selenium-server-standalone-2.0b3.jar 00:17:03.883 INFO - Java: Sun Microsystems Inc. 19.0-b09 00:17:03.885 INFO - OS: Linux 2.6.32-305-ec2 i386 00:17:03.889 INFO - v2.0 [b3], with Core v2.0 [b3] 00:17:04.501 INFO - RemoteWebDriver instances shoul...
Selenium seems to work, but then gets a timeout error?
$ java -jar selenium-server-standalone-2.0b3.jar 00:17:03.883 INFO - Java: Sun Microsystems Inc. 19.0-b09 00:17:03.885 INFO - OS: Linux 2.6.32-305-ec2 i386 00:17:03.889 INFO - v2.0 [b3], with Core v2.0 [b3] 00:17:04.501 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub 00:17:04.530 INFO...
[ "Looks like you're using Selenium Grid. The grid consists of a hub and nodes which connect to it. When you run a test you send a request to the server which dispatches it accordingly to a host with the appropriate configuration according to what you defined in desired_capabilities. In this case you don't seem to ha...
[ 2 ]
[]
[]
[ "java", "python", "selenium", "selenium_rc" ]
stackoverflow_0006194982_java_python_selenium_selenium_rc.txt
Q: Python desktop app linked to PHP web app? Well, i do want to make a web app in php, where the user could create an account and log in, then download a desktop app made in python, log in there also with the username and the password from the web app and then run in tray. The purpose of this project is none, i want ...
Python desktop app linked to PHP web app?
Well, i do want to make a web app in php, where the user could create an account and log in, then download a desktop app made in python, log in there also with the username and the password from the web app and then run in tray. The purpose of this project is none, i want to do it for fun and practice, but i do have so...
[ "You need a protocol in order for the two to communicate; I recommend JSON-RPC. Modules are available for both PHP and Python.\n", "There are a million ways to do this. I suggest you write the local data gathering first, to know the amount and format of the data (and because getting Windows hardware information v...
[ 2, 1 ]
[]
[]
[ "php", "python" ]
stackoverflow_0006200707_php_python.txt
Q: Packaging a Jython Library I have a Python library I've written that interfaces with a Java application. Note that this is specifically a library for other developers to use, there is no main() involved. I've found plenty of information on packaging Jython web applications into jars to be deployed on application...
Packaging a Jython Library
I have a Python library I've written that interfaces with a Java application. Note that this is specifically a library for other developers to use, there is no main() involved. I've found plenty of information on packaging Jython web applications into jars to be deployed on application servers, but I can't seem to fi...
[ "There is an implementation of disutils in jython but it doesn't work for me. For now you might have to write a script to copy your python files into jython/Lib/site-packages, which I don't think will be too hard if you're just installing python source, see shutil.copytree.\n", "it's strongly recommend to use vi...
[ 0, 0 ]
[]
[]
[ "jython", "packaging", "python" ]
stackoverflow_0006006497_jython_packaging_python.txt
Q: Defining main() in python Often, I see the following code in python programs if __name__ == '__main__': main() I'm following the Python class on Google Code, and it says that it's standard boilerplate code. Do I really need to write such code in all my scripts? What functionality would this add to my programs...
Defining main() in python
Often, I see the following code in python programs if __name__ == '__main__': main() I'm following the Python class on Google Code, and it says that it's standard boilerplate code. Do I really need to write such code in all my scripts? What functionality would this add to my programs?
[ "No, you don't have to, but it's invaluable for things like unit testing.\nYou can create a main in every python file so that, if you run it directly, __name__ will be set to \"__main__\" and it will run a barrage of tests on the code in question.\nIf you just import it normally from another program, that doesn't h...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006200877_python.txt
Q: python twisted INotify without blocking reactor I am using twsited's INotify to monitor the /dev directory to monitor for new serial devices being added. The code I am currently using is similar to below. notifier = INotify() notifier.watch(FilePath("/dev"), IN_CREATE, callbacks=[self.created]) notifier.startRead...
python twisted INotify without blocking reactor
I am using twsited's INotify to monitor the /dev directory to monitor for new serial devices being added. The code I am currently using is similar to below. notifier = INotify() notifier.watch(FilePath("/dev"), IN_CREATE, callbacks=[self.created]) notifier.startReading() def created(self, ignored, path, mask): .....
[ "All event handlers in Twisted run in the \"reactor thread\" - UDP, TCP, and indeed inotify. They all are expected to cooperate with the system by not blocking. So, in this sense, this is just a question about how to write good event handlers in Twisted, not about inotify in particular.\nThere are lots of options...
[ 7, 1 ]
[]
[]
[ "blocking", "inotify", "python", "twisted" ]
stackoverflow_0006200240_blocking_inotify_python_twisted.txt
Q: how to view sparse matrices outside python environment I am working with sparse matrices which are 11685 by 85730 . I am able to store it only as a .pickle file . I want to view the file outside the python environment also . I tried saving as a .txt and .csv files but they are of no help . Can anybody suggest a su...
how to view sparse matrices outside python environment
I am working with sparse matrices which are 11685 by 85730 . I am able to store it only as a .pickle file . I want to view the file outside the python environment also . I tried saving as a .txt and .csv files but they are of no help . Can anybody suggest a suitable format and library so that I can view those matrices ...
[ "Python allows you to write to many formats that are readable outside of python. .csv is one format, but there are also HDF5 and netcdf4 among others (those are meant to store array data though).\nhttp://code.google.com/p/netcdf4-python/\nhttp://code.google.com/p/h5py/\nOr you could save them in a matlab readable f...
[ 2 ]
[]
[]
[ "numpy", "python", "sparse_matrix" ]
stackoverflow_0006200069_numpy_python_sparse_matrix.txt
Q: How can I get the window at a certain X, Y position with Python and PyGTK/PyGDK? So, I develop a small screenshot utility called Lookit, and I'm wanting to have the user be able to screenshot an entire window (currently entire screen and dragged rectangle capture are supported). What I'm wondering is how to get th...
How can I get the window at a certain X, Y position with Python and PyGTK/PyGDK?
So, I develop a small screenshot utility called Lookit, and I'm wanting to have the user be able to screenshot an entire window (currently entire screen and dragged rectangle capture are supported). What I'm wondering is how to get the Window that the user clicks on so that I can find it's geometry and grab that sectio...
[ "Those windows belong to other processes, so you have to go through the windowing system. This is different for each platform, and AFAIK not abstracted by GDK.\nOn X11 you could use the python bindings to libwnck:\nimport wnck\nscreen = wnck.screen_get_default()\nfor window in reversed(screen.get_windows_stacked())...
[ 4 ]
[]
[]
[ "gtk", "linux", "pygtk", "python" ]
stackoverflow_0006196255_gtk_linux_pygtk_python.txt
Q: Why is a part of the output of a subprocess executed by Popen(), lost? This is a strange problem. I started working at it on this thread, and now it has morphed into something slightly different. I am using Popen() to execute a Perl program 'anubadok'. The Perl program writes its output to a file. Here's the snipp...
Why is a part of the output of a subprocess executed by Popen(), lost?
This is a strange problem. I started working at it on this thread, and now it has morphed into something slightly different. I am using Popen() to execute a Perl program 'anubadok'. The Perl program writes its output to a file. Here's the snippet of Perl code that does this. The 4th. print statement (after open OUTFILE...
[ "Both Perl and Python are sensitive to environment variables like LANG. Graphical launchers and terminal windows often hand different values to their children.\nI'd try testing with ASCII input and output, printing STDERR to see if there are warnings, logging the environment of each process.\n" ]
[ 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0006178747_pygtk_python.txt
Q: simple questions about PyGTK, GTKbuilder, GTK+ Okay, I'm just starting to get into creating GUIs with python and I'm a bit confused as how how I should go forward: Should I download PyGTK or the current version of GTK+ if I'm using Python or does it matter? Concerning GUI builders, from what people are saying, ...
simple questions about PyGTK, GTKbuilder, GTK+
Okay, I'm just starting to get into creating GUIs with python and I'm a bit confused as how how I should go forward: Should I download PyGTK or the current version of GTK+ if I'm using Python or does it matter? Concerning GUI builders, from what people are saying, it seems like GTKbuilder is better to use than Glade...
[ "PyGTK bridges GTK+ to Python, so you need all three.\nGlade is an application to edit XML files. You'll definitely want it. To read those files you can use either libglade (separate, deprecated) or GtkBuilder (built into GTK+, and therefore PyGTK).\n" ]
[ 1 ]
[]
[]
[ "glade", "gtkbuilder", "pygtk", "python", "user_interface" ]
stackoverflow_0006158439_glade_gtkbuilder_pygtk_python_user_interface.txt
Q: How to have automated headers for python files A proper header format in python is described here . Using either VIM or a shell script, I would like to have the usual metadata (like __author__, __authors__, __contact__, __copyright__, __license__, __deprecated__, __date__ and __version__) added to the file header...
How to have automated headers for python files
A proper header format in python is described here . Using either VIM or a shell script, I would like to have the usual metadata (like __author__, __authors__, __contact__, __copyright__, __license__, __deprecated__, __date__ and __version__) added to the file header. SVN keywords would also be nice. Adding it to new ...
[ "I highly recommend the snipMate plugin. You can easily add new snips per file type, and they're triggered by just typing a keyword and hitting tab, so for example you could just hit\nheader<TAB>\n\nand all the fields would be added, and you can easily tab through any that require being filled out on a per-file bas...
[ 6, 5, 0 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0006201302_python_vim.txt
Q: Trouble splitting a String with Python I'm desperatly trying to split a string using Python but the text file I need to parse is a little bit tricky: The text file is a comma separated data file I did the following: import fileinput for line in fileinput.input("sample.txt"): data = line.strip().split(',') pass ...
Trouble splitting a String with Python
I'm desperatly trying to split a string using Python but the text file I need to parse is a little bit tricky: The text file is a comma separated data file I did the following: import fileinput for line in fileinput.input("sample.txt"): data = line.strip().split(',') pass This actually should make the job right ? O...
[ "Your data is in a pretty common format -- Comma Separated Values (CSV). Instead of writing yet another parser, consider using the built-in csv module.\n", "CSV files should be handled with csv.\n", "you can use the csv module\nimport csv\n\nwith open('sample.txt', 'rb') as f:\n reader = csv.reader(f)\n ...
[ 10, 5, 4 ]
[]
[]
[ "parsing", "python", "split", "text_processing" ]
stackoverflow_0006201087_parsing_python_split_text_processing.txt
Q: Connecting pys60 bluetooth console I'm trying to program using python (pys60) in my phone. i'm using two way to connect my ubuntu 10.10 to my phone using bluetooth console first is: sdptool add --channel=2 SP mknod /dev/rfcomm0 c 216 0 rfcomm listen 0 2 and the second is: hciconfig reset hcito...
Connecting pys60 bluetooth console
I'm trying to program using python (pys60) in my phone. i'm using two way to connect my ubuntu 10.10 to my phone using bluetooth console first is: sdptool add --channel=2 SP mknod /dev/rfcomm0 c 216 0 rfcomm listen 0 2 and the second is: hciconfig reset hcitool dev sdptool add --channel=2 SP ...
[ "try: \nsudo cu -l /dev/rfcomm2\n\nIf it works you will probably understand what is wrong\n[EDIT]\nsudo chown root:root /dev/rfcomm2\n\nthe line is not in use in my case (try sudo fuser /dev/rfcomm2) cu is a little buggy in error detection see this.\nThe thing i still don't understand is why screen does not work.\...
[ 0 ]
[]
[]
[ "pys60", "python", "symbian" ]
stackoverflow_0005256378_pys60_python_symbian.txt
Q: Where I can find the Python `pwd` module for MS Windows? I use the Python standard library pwd module on GNU+Linux, but now I try to run my application in Microsoft Windows and can not find it. I'm using python 2.6.6. Where can I find the pwd module for use in Python on MS Windows? A: From the docs: Platforms: ...
Where I can find the Python `pwd` module for MS Windows?
I use the Python standard library pwd module on GNU+Linux, but now I try to run my application in Microsoft Windows and can not find it. I'm using python 2.6.6. Where can I find the pwd module for use in Python on MS Windows?
[ "From the docs:\n\nPlatforms: Unix\n\nYou will need to go digging around in PyWin32 and MSDN for the Windows equivalents.\n" ]
[ 3 ]
[]
[]
[ "passwd", "python", "windows" ]
stackoverflow_0006202666_passwd_python_windows.txt
Q: Why is my instance counter display 0 in this Python code? I made a simple code to demonstrate and understand classes - however when I run this, my lists show that they are empty, containing "None" values instead of the strings that the user enters as names. #Static methods do not require the object to be initiated...
Why is my instance counter display 0 in this Python code?
I made a simple code to demonstrate and understand classes - however when I run this, my lists show that they are empty, containing "None" values instead of the strings that the user enters as names. #Static methods do not require the object to be initiated. Can be remotely accessed from outside the function . #Counti...
[ "There are a few errors in your code. First in the way you use lists. Second, in the way you call methods on your objects. The combination of errors explains why you have a list of None at the end.\nList name\nlist = []\n\nDon't name a list list. It is already the name of, well..., the list class, i.e. in Python yo...
[ 6, 5, 3, 1 ]
[]
[]
[ "class", "debugging", "python" ]
stackoverflow_0006202670_class_debugging_python.txt
Q: Extracting beats out of MP3 music with Python What kind of solutions are there to analyze beats out of MP3 music in Python? The purpose of this would be to use rhythm information to time the keyframes of generated animation, export animation as video file and and mix the video and audio together. A: Check this: ...
Extracting beats out of MP3 music with Python
What kind of solutions are there to analyze beats out of MP3 music in Python? The purpose of this would be to use rhythm information to time the keyframes of generated animation, export animation as video file and and mix the video and audio together.
[ "Check this:\nThe Echo Nest Remix API\n# You can manipulate the beats in a song as a native python list\nbeats = audio_file.analysis.beats\nbeats.reverse()\n\n" ]
[ 4 ]
[]
[]
[ "audio", "python", "signal_processing", "video" ]
stackoverflow_0006203007_audio_python_signal_processing_video.txt
Q: Is there a meaningful way to use context managers inside generators? from contextlib import contextmanager @contextmanager def context(): print "entering" yield print "exiting" def test(): with context(): for x in range(10): yield x for x in test(): if x == 5: bre...
Is there a meaningful way to use context managers inside generators?
from contextlib import contextmanager @contextmanager def context(): print "entering" yield print "exiting" def test(): with context(): for x in range(10): yield x for x in test(): if x == 5: break # or raise output: entering Is there a way to make python automatica...
[ "Well, you could wrap the yield in context() function with a try/finally clause:\nfrom contextlib import contextmanager\n\n@contextmanager\ndef context():\n print \"entering\"\n try:\n yield\n finally:\n print \"exiting\"\n\ndef test():\n with context():\n for x in range(10):\n ...
[ 18 ]
[]
[]
[ "contextmanager", "generator", "python" ]
stackoverflow_0006203300_contextmanager_generator_python.txt