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: Changing python interpreter windows I have two python installations, 2.5 and 2.6 I want to change the default python interpreter from 2.5 to 2.6. Anyone know how? A: PYTHONPATH is NOT what you are looking for. That is for varying where Python's "import" looks for packages and modules. You need to change the PATH...
Changing python interpreter windows
I have two python installations, 2.5 and 2.6 I want to change the default python interpreter from 2.5 to 2.6. Anyone know how?
[ "PYTHONPATH is NOT what you are looking for. That is for varying where Python's \"import\" looks for packages and modules.\nYou need to change the PATH variable in your environment so that it contains e.g. \"....;c:\\python26;....\" instead of \"....;c:\\python25;....\". Click on start > control panel > system > ad...
[ 10, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0001053794_python_windows.txt
Q: Regex and a sequences of patterns? Is there a way to match a pattern (e\d\d) several times, capturing each one into a group? For example, given the string.. blah.s01e24e25 ..I wish to get four groups: 1 -> blah 2 -> 01 3 -> 24 4 -> 25 The obvious regex to use is (in Python regex: import re re.match("(\w+).s(\d+)...
Regex and a sequences of patterns?
Is there a way to match a pattern (e\d\d) several times, capturing each one into a group? For example, given the string.. blah.s01e24e25 ..I wish to get four groups: 1 -> blah 2 -> 01 3 -> 24 4 -> 25 The obvious regex to use is (in Python regex: import re re.match("(\w+).s(\d+)e(\d+)e(\d+)", "blah.s01e24e25").groups(...
[ "Do it in two steps, one to find all the numbers, then one to split them:\nimport re\n\ndef get_pieces(s):\n # Error checking omitted!\n whole_match = re.search(r'\\w+\\.(s\\d+(?:e\\d+)+)', s)\n return re.findall(r'\\d+', whole_match.group(1))\n\nprint get_pieces(r\"blah.s01e01\")\nprint get_pieces(r\"blah...
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "python", "regex", "sequences" ]
stackoverflow_0001053481_python_regex_sequences.txt
Q: Why print statement is not pythonic? This question was bugging me for quite a while (as evidenced by my previous question): why exactly is print(x) better (which is defined as being more pythonic) than print x? For those who don't know, the print statement was changed into function in Python 3.0. The formal docume...
Why print statement is not pythonic?
This question was bugging me for quite a while (as evidenced by my previous question): why exactly is print(x) better (which is defined as being more pythonic) than print x? For those who don't know, the print statement was changed into function in Python 3.0. The formal documentation is in PEP 3105 and motivation is i...
[ "Looks to me like yours is a debate, not a question -- are you really going to accept an answer that shows how deeply and badly wrong you were in your assertions?!\nOn to your debating points:\n\nThere are other operators, such as\n import which we write as a statement,\n though their functionality is actually\n ...
[ 58, 11, 8, 6, 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0001053849_python_python_3.x.txt
Q: formencode invalid return type if an exception occurs in form encode then what will be the return type?? suppose if(request.POST): formvalidate = ValidationRule() try: new = formvalidate.to_python(request.POST) data = Users1( n_date = new['n_date'], heading = new['heading'],...
formencode invalid return type
if an exception occurs in form encode then what will be the return type?? suppose if(request.POST): formvalidate = ValidationRule() try: new = formvalidate.to_python(request.POST) data = Users1( n_date = new['n_date'], heading = new['heading'], desc = ...
[ "I assume you are using formencode(http://formencode.org)\nyou can use unpack_errors to get per field error e.g.\nimport formencode\nfrom formencode import validators\n\nclass UserForm(formencode.Schema):\n first_name = validators.String(not_empty=True)\n last_name = validators.String(not_empty=True)\n\nform ...
[ 3 ]
[]
[]
[ "error_handling", "formencode", "python", "webforms" ]
stackoverflow_0001054210_error_handling_formencode_python_webforms.txt
Q: compound sorting in python I have a python script which outputs lots of data, sample is as below. the first of the 4 fields always consists of two letters, one digit, a slash and one or two digits Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020...
compound sorting in python
I have a python script which outputs lots of data, sample is as below. the first of the 4 fields always consists of two letters, one digit, a slash and one or two digits Gi3/2 --.--.--.-- 0024.e89b.c10e Dell Inc. Gi5/4 --.--.--.-- 0030.c1cd.f038 HEWLETTPACKARD Gi4/3 --.--.--.-- 0020.ac00.6703 INTERFLEX DATENSYSTEM...
[ "def lineKey (line):\n keyStr, rest = line.split(' ', 1)\n a, b = keyStr.split('/', 1)\n return (a, int(b))\n\nsorted(lines, key=lineKey)\n\n", "to sort split each line such that you have two tuple, part before / and integer part after that, so each line should be sorted on something like ('Gi6', 12), se...
[ 5, 4, 1, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0001054454_python_sorting.txt
Q: Django official tutorial for the absolute beginner, absolutely failed! Not that level of failure indeed. I just completed the 4 part tutorial from djangoproject.com, my administration app works fine and my entry point url (/polls/) works well, with the exception that I get this http response: No polls are availab...
Django official tutorial for the absolute beginner, absolutely failed!
Not that level of failure indeed. I just completed the 4 part tutorial from djangoproject.com, my administration app works fine and my entry point url (/polls/) works well, with the exception that I get this http response: No polls are available. Even if the database has one registry. Entering with the admin app, the ...
[ "You overlooked this paragraph in the 4. part of the tutorial:\n\nIn previous parts of the tutorial, the templates have been provided with a context that contains the poll and latest_poll_list context variables. However, the generic views provide the variables object and object_list as context. Therefore, you need ...
[ 14 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001054494_django_python.txt
Q: Weighted slope one algorithm? (porting from Python to R) I was reading about the Weighted slope one algorithm ( and more formally here (PDF)) which is supposed to take item ratings from different users and, given a user vector containing at least 1 rating and 1 missing value, predict the missing ratings. I found a...
Weighted slope one algorithm? (porting from Python to R)
I was reading about the Weighted slope one algorithm ( and more formally here (PDF)) which is supposed to take item ratings from different users and, given a user vector containing at least 1 rating and 1 missing value, predict the missing ratings. I found a Python implementation of the algorithm, but I'm having a hard...
[ "I used the same reference (Bryan O'Sullivan's python code) to write an R version of Slope One a while back. I'm pasting the code below in case it helps.\npredict <- function(userprefs, data.freqs, data.diffs) {\n seen <- names(userprefs)\n\n preds <- sweep(data.diffs[ , seen, drop=FALSE], 2, userprefs, '+')...
[ 9 ]
[]
[]
[ "prediction", "python", "r", "recommendation_engine" ]
stackoverflow_0001022649_prediction_python_r_recommendation_engine.txt
Q: How frequently should Python decorators be used? I recently started experimenting with Python decorators (and higher-order functions) because it looked like they might make my Django unit tests more concise. e.g., instead of writing: def visit1(): login() do_stuff() logout() I could instead do @handle...
How frequently should Python decorators be used?
I recently started experimenting with Python decorators (and higher-order functions) because it looked like they might make my Django unit tests more concise. e.g., instead of writing: def visit1(): login() do_stuff() logout() I could instead do @handle_login def visit1(): do_stuff() However, after so...
[ "Decorators are fine in their place and definitely not to be avoided -- when appropriate;-). I see your question as meaning essentially \"OK so when are they appropriate\"?\nAdding some prefix and/or postfix code around some but not all methods of some classes is a good example. Were it all methods, a class decorat...
[ 12, 3, 3, 0 ]
[]
[]
[ "decorator", "django", "python" ]
stackoverflow_0001054249_decorator_django_python.txt
Q: Django and Python 2.6 I'm just starting to get into Django, and of course as of last night one of the two new Python versions went final (2.6 obviously ;)) so I'm wondering if 2.6 plus Django is ready for actual use or do the Django team need more time to finish with tweaks/cleanup? All the google searches I did...
Django and Python 2.6
I'm just starting to get into Django, and of course as of last night one of the two new Python versions went final (2.6 obviously ;)) so I'm wondering if 2.6 plus Django is ready for actual use or do the Django team need more time to finish with tweaks/cleanup? All the google searches I did were inconclusive, I saw b...
[ "The impression I get is that 2.6 should work fine with Django 1.0. As found here: http://simonwillison.net/2008/Oct/2/whatus/ \n", "Note that there is currently no python-mysql adapter for python2.6. If you need MySQL, stick with 2.5 for now.\n", "There is an unofficial build for mysqldb 1.2.2 win32 python 2.6...
[ 7, 5, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0000162808_django_python.txt
Q: Consuming Python COM Server from .NET I wanted to implement python com server using win32com extensions. Then consume the server from within the .NET. I used the following example to implement the com server and it runs without a problem but when I try to consume it using C# I got FileNotFoundException with the fo...
Consuming Python COM Server from .NET
I wanted to implement python com server using win32com extensions. Then consume the server from within the .NET. I used the following example to implement the com server and it runs without a problem but when I try to consume it using C# I got FileNotFoundException with the following message "Retrieving the COM class f...
[ "A COM server is just a piece of software (a DLL or an executable) that will accept remote procedure calls (RPC) through a defined protocol. Part of the protocol says that the server must have a unique ID, stored in the Windows' registry.\nIn our case, this means that you have \"registered\" a server that is not ex...
[ 11, 0 ]
[]
[]
[ ".net", "com", "python" ]
stackoverflow_0001054849_.net_com_python.txt
Q: Unable to make a MySQL database of SO questions by Python Brent's answer suggests me that has made a database of SO questions such that he can fast analyze the questions. I am interested in making a similar database by MySQL such that I can practice MySQL with similar queries as Brent. The database should include ...
Unable to make a MySQL database of SO questions by Python
Brent's answer suggests me that has made a database of SO questions such that he can fast analyze the questions. I am interested in making a similar database by MySQL such that I can practice MySQL with similar queries as Brent. The database should include at the least the following fields (I am guessing here, since th...
[ "I don't know the details of how to import the data into MySQL, but the raw data of Stack Overflow is freely available: https://blog.stackoverflow.com/2009/06/stack-overflow-creative-commons-data-dump/\nThere's no secret API, nor any need to use Beautiful Soup.\n", "I'm sure it's possible to work directly with th...
[ 1, 1 ]
[]
[]
[ "database", "mysql", "python" ]
stackoverflow_0001054964_database_mysql_python.txt
Q: fast and easy way to template xml files in python Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. What is the easiest and quickest way to setup templating so that I can just give the varia...
fast and easy way to template xml files in python
Right now I've hard coded the whole xml file in my python script and just doing out.write(), but now it's getting harder to manage because i have multiple types of xml file. What is the easiest and quickest way to setup templating so that I can just give the variable names amd filename?
[ "Short answer is: You should be focusing, and dealing with, the data (i.e., python object) and not the raw XML\nBasic story:\nXML is supposed to be a representation of some data, or data set.\nYou don't have a lot of detail in your question about the type of data, what it represents, etc, etc -- so I'll give you so...
[ 6, 4, 4, 1, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001055108_python_xml.txt
Q: Unicode friendly alphabetic pattern for python regex? I'm looking for a pattern equivalent to \w, and which doesn't match numeric pattern. I cannot use [a-zA-Z] because I would like it to match japanese kanjis as well. Is there a way to write something like [\w^[0-9]] ? Is there an equivalent of [:alpha:] in pytho...
Unicode friendly alphabetic pattern for python regex?
I'm looking for a pattern equivalent to \w, and which doesn't match numeric pattern. I cannot use [a-zA-Z] because I would like it to match japanese kanjis as well. Is there a way to write something like [\w^[0-9]] ? Is there an equivalent of [:alpha:] in python regex?
[ "[^\\W\\d]\n\nThrow out non-word characters and throw out digits. Keep the rest.\n" ]
[ 11 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001055160_python_regex.txt
Q: How to modify a NumPy.recarray using its two views I am new to Python and Numpy, and I am facing a problem, that I can not modify a numpy.recarray, when applying to masked views. I read recarray from a file, then create two masked views, then try to modify the values in for loop. Here is an example code. import nu...
How to modify a NumPy.recarray using its two views
I am new to Python and Numpy, and I am facing a problem, that I can not modify a numpy.recarray, when applying to masked views. I read recarray from a file, then create two masked views, then try to modify the values in for loop. Here is an example code. import numpy as np import matplotlib.mlab as mlab dat = mlab.cs...
[ "I think you have a misconception in this term \"masked views\" and should (re-)read The Book (now freely downloadable) to clarify your understanding.\nI quote from section 3.4.2:\n\nAdvanced selection is triggered when\n the selection object, obj, is a\n non-tuple sequence object, an ndarray\n (of data type int...
[ 3 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0001055131_matplotlib_numpy_python.txt
Q: What does `@` mean in Python? What does @ mean in Python? Example: @login_required, etc. A: It is decorator syntax. A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. Th...
What does `@` mean in Python?
What does @ mean in Python? Example: @login_required, etc.
[ "It is decorator syntax.\n\nA function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. ...
[ 31, 1, 1, 1, 1, 0 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0001053732_python_syntax.txt
Q: item frequency in a python list of dictionaries Ok, so I have a list of dicts: [{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': '...
item frequency in a python list of dictionaries
Ok, so I have a list of dicts: [{'name': 'johnny', 'surname': 'smith', 'age': 53}, {'name': 'johnny', 'surname': 'ryan', 'age': 13}, {'name': 'jakob', 'surname': 'smith', 'age': 27}, {'name': 'aaron', 'surname': 'specter', 'age': 22}, {'name': 'max', 'surname': 'headroom', 'age': 108}, ] and I want the 'frequency'...
[ "collections.defaultdict from the standard library to the rescue:\nfrom collections import defaultdict\n\nLofD = [{'name': 'johnny', 'surname': 'smith', 'age': 53},\n {'name': 'johnny', 'surname': 'ryan', 'age': 13},\n {'name': 'jakob', 'surname': 'smith', 'age': 27},\n {'name': 'aaron', 'surname': 'specter', 'age'...
[ 14, 2, 2, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0001055646_dictionary_python.txt
Q: Can two versions of the same library coexist in the same Python install? The C libraries have a nice form of late binding, where the exact version of the library that was used during linking is recorded, and thus an executable can find the correct file, even when several versions of the same library are installed....
Can two versions of the same library coexist in the same Python install?
The C libraries have a nice form of late binding, where the exact version of the library that was used during linking is recorded, and thus an executable can find the correct file, even when several versions of the same library are installed. Can the same be done in Python? To be more specific, I work on a Python proje...
[ "You may want to take a look at virtualenv\n" ]
[ 8 ]
[]
[]
[ "python", "shared_libraries" ]
stackoverflow_0001055926_python_shared_libraries.txt
Q: Ruby on Rails vs. Django Possible Duplicate: Rails or Django? (or something else?) These are two web frameworks that are becoming (or have been in many circles) popular. I was wondering what are the advantages and disadvantages of each? Feel free to comment on Ruby and Python pros and cons also. Two disadvantage...
Ruby on Rails vs. Django
Possible Duplicate: Rails or Django? (or something else?) These are two web frameworks that are becoming (or have been in many circles) popular. I was wondering what are the advantages and disadvantages of each? Feel free to comment on Ruby and Python pros and cons also. Two disadvantages I am speculative about for ...
[ "Watch Google Talk \"Snakes and Rubies\" on video.google.com. Core developers from Django and Ruby on Rails comparing these two frameworks. In better quality here\n" ]
[ 9 ]
[]
[]
[ "django", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0001056278_django_python_ruby_ruby_on_rails.txt
Q: Python 2.4 plistlib on Linux According to http://docs.python.org/dev/library/plistlib.html, plistlib is available to non-Mac platforms only since 2.6, but I'm wondering if there's a way to get it work on 2.4 on Linux. A: Download it and give it a try: http://svn.python.org/projects/python/trunk/Lib/plistlib.py (...
Python 2.4 plistlib on Linux
According to http://docs.python.org/dev/library/plistlib.html, plistlib is available to non-Mac platforms only since 2.6, but I'm wondering if there's a way to get it work on 2.4 on Linux.
[ "Download it and give it a try:\nhttp://svn.python.org/projects/python/trunk/Lib/plistlib.py\n(If that doesn't work, you may have more luck with the 2.4 version.)\n" ]
[ 3 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0001056593_linux_python.txt
Q: JSON serialization in Spidermonkey I'm using python-spidermonkey to run JavaScript code. In order to pass objects (instead of just strings) to Python, I'm thinking of returning a JSON string. This seems like a common issue, so I wonder whether there are any facilities for this built into either Spidermonkey or pyt...
JSON serialization in Spidermonkey
I'm using python-spidermonkey to run JavaScript code. In order to pass objects (instead of just strings) to Python, I'm thinking of returning a JSON string. This seems like a common issue, so I wonder whether there are any facilities for this built into either Spidermonkey or python-spidermonkey. (I do know about uneva...
[ "I would use JSON.stringify. It's part of the ECMAScript 5 standard, and it's implemented in the current version of spidermonkey. I don't know if it's in the version used by python-spidermonkey, but if it isn't, you can get a JavaScript implementation from http://www.json.org/js.html.\n" ]
[ 7 ]
[]
[]
[ "javascript", "json", "python", "spidermonkey" ]
stackoverflow_0001055805_javascript_json_python_spidermonkey.txt
Q: How to use dict in python? 10 5 -1 -1 -1 1 1 0 2 ... If I want to count the number of occurrences of each number in a file, how do I use python to do it? A: This is almost the exact same algorithm described in Anurag Uniyal's answer, except using the file as an iterator instead of readline(): from collections i...
How to use dict in python?
10 5 -1 -1 -1 1 1 0 2 ... If I want to count the number of occurrences of each number in a file, how do I use python to do it?
[ "This is almost the exact same algorithm described in Anurag Uniyal's answer, except using the file as an iterator instead of readline():\nfrom collections import defaultdict\ntry:\n from io import StringIO # 2.6+, 3.x\nexcept ImportError:\n from StringIO import StringIO # 2.5\n\ndata = defaultdict(int)\n\n#with ...
[ 7, 5, 2, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001047614_python.txt
Q: How to analyze IE activity when opening a specific web page I'd like to retrieve data from a specific webpage by using urllib library. The problem is that in order to open this page some data should be sent to the server before. If I do it with IE, i need to update first some checkboxes and then press "display d...
How to analyze IE activity when opening a specific web page
I'd like to retrieve data from a specific webpage by using urllib library. The problem is that in order to open this page some data should be sent to the server before. If I do it with IE, i need to update first some checkboxes and then press "display data" button, which opens the desired page. Looking into the sourc...
[ "An HTML debugging proxy would be the best tool to use in this situation. As you're using IE, I recommend Fiddler, as it is developed by Microsoft and automatically integrates with Internet Explorer through a plugin. I personally use Fiddler all the time, and it is a really helpful tool, as I'm building an app that...
[ 3, 0 ]
[]
[]
[ "html", "information_retrieval", "internet_explorer", "python" ]
stackoverflow_0001056739_html_information_retrieval_internet_explorer_python.txt
Q: Python, Django, datetime In my model, I have 2 datetime properties: start_date end_date I would like to count the end date as a one week after the start_date. How can I accomplish this? A: If you always want your end_date to be one week after the start_date, what you could do, is to make a custom save method f...
Python, Django, datetime
In my model, I have 2 datetime properties: start_date end_date I would like to count the end date as a one week after the start_date. How can I accomplish this?
[ "If you always want your end_date to be one week after the start_date, what you could do, is to make a custom save method for your model.\nAnother option would be to use signals instead. The result would be the same, but since you are dealing with the models data, I would suggest that you go for the custom save met...
[ 8, 5 ]
[]
[]
[ "datetime", "django", "python" ]
stackoverflow_0001056934_datetime_django_python.txt
Q: Django failing to find apps I have been working on a django app on my local computer for some time now and i am trying to move it to a mediatemple container and im having a problem when i try to start up django. it gives me this traceback: application failed to start, starting manage.py fastcgi failed:Traceback (m...
Django failing to find apps
I have been working on a django app on my local computer for some time now and i am trying to move it to a mediatemple container and im having a problem when i try to start up django. it gives me this traceback: application failed to start, starting manage.py fastcgi failed:Traceback (most recent call last): File "mana...
[ "Steps I would take would be \n\nRun the dev server on your Media Template instance. If that runs successfully, it obviously is an error with your apache/nginx/whaever setup.\nI dont have experience running apps as FCGI, which it looks to em you are trying to do. It looks to me that somehow when Fcgi runs, it is un...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001056675_django_python.txt
Q: Browser automation: Python + Firefox using PyXPCOM I have tried Pamie a browser automation library for internet explorer. It interfaces IE using COM, pretty neat: import PAM30 ie = PAM30.PAMIE("http://user-agent-string.info/") ie.clickButton("Analyze my UA") Now I would like to do the same thing using PyXPCOM wit...
Browser automation: Python + Firefox using PyXPCOM
I have tried Pamie a browser automation library for internet explorer. It interfaces IE using COM, pretty neat: import PAM30 ie = PAM30.PAMIE("http://user-agent-string.info/") ie.clickButton("Analyze my UA") Now I would like to do the same thing using PyXPCOM with similar flexibility on Firefox. How can I do this? Can...
[ "I've used webdriver with firefox. I was very pleased with it.\nAs for the code examples, this will get you started.\n", "My understanding of PyXPCOM is that it's meant to let you create and access XPCOM components, not control existing ones. You may not be able to do this using PyXPCOM at all, per Mark Hammond,...
[ 10, 4, 2 ]
[]
[]
[ "automation", "firefox", "python" ]
stackoverflow_0001020524_automation_firefox_python.txt
Q: Django/Python: How do i transfer a class's attributes to another via a for loop? (Form->Model Instance) I wish to update a model instance from a form I have. The form is a ModelForm, so it has the same attributes as the model instance, how do I transfer the attributes from the form instance to the model instance i...
Django/Python: How do i transfer a class's attributes to another via a for loop? (Form->Model Instance)
I wish to update a model instance from a form I have. The form is a ModelForm, so it has the same attributes as the model instance, how do I transfer the attributes from the form instance to the model instance instead of doing this: modelinstance.name = form.name . . . . A for loop perhaps? :) Thanks!
[ "Call the save() method of the form.\nSpecifically instantiate the form with keyword argument instance like this:\n>>> a = Article.objects.get(pk=1)\n>>> f = ArticleForm(instance=a)\n>>> f.save()\n\nTaken from here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method\n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001057477_django_python.txt
Q: Using pipes to communicate data between two anonymous python scripts Consider this at the windows commandline. scriptA.py | scriptB.py I want to send a dictionary object from scriptA.py to scriptB.py by pickle:ing it and sending it over a pipe. But I don't know how to accomplish this. I've read some posts about t...
Using pipes to communicate data between two anonymous python scripts
Consider this at the windows commandline. scriptA.py | scriptB.py I want to send a dictionary object from scriptA.py to scriptB.py by pickle:ing it and sending it over a pipe. But I don't know how to accomplish this. I've read some posts about this subject here, but usually there's answers along these line: Popen( "sc...
[ "When you say this to a shell\nscriptA.py | scriptB.py\n\nThe shell connects them with a pipe. You do NOTHING and it works perfectly.\nEverything that scriptA.py writes to sys.stdout goes to scriptB.py\nEverything that scriptB.py reads from sys.stdin came from scriptA.py\nThey're already connected. \nSo, how do y...
[ 7, 2, 0 ]
[]
[]
[ "pipe", "python", "windows" ]
stackoverflow_0001057576_pipe_python_windows.txt
Q: Bad pipe filedescriptor when reading from stdin in python Duplicate of this question. Vote to close. Consider this at the windows commandline. scriptA.py | scriptB.py In scriptA.py: sys.stdout.write( "hello" ) In scriptB.py: print sys.stdin.read() This generates the following error: c:\> scriptA.py | scriptB.py...
Bad pipe filedescriptor when reading from stdin in python
Duplicate of this question. Vote to close. Consider this at the windows commandline. scriptA.py | scriptB.py In scriptA.py: sys.stdout.write( "hello" ) In scriptB.py: print sys.stdin.read() This generates the following error: c:\> scriptA.py | scriptB.py close failed: [Errno 22] Invalid argument Traceback (most rece...
[ "It seems that stdin/stdout redirect does not work when starting from a file association.\nThis is not specific to python, but a problem caused by win32 cmd.exe.\nSee: http://mail.python.org/pipermail/python-bugs-list/2004-August/024920.html\n" ]
[ 7 ]
[]
[]
[ "pipe", "python", "windows" ]
stackoverflow_0001057638_pipe_python_windows.txt
Q: How to do windows API calls in Python 3.1? Has anyone found a version of pywin32 for python 3.x? The latest available appears to be for 2.6. Alternatively, how would I "roll my own" windows API calls in Python 3.1? A: You should be able to do everything with ctypes, if a bit cumbersomely. Here's an example of ge...
How to do windows API calls in Python 3.1?
Has anyone found a version of pywin32 for python 3.x? The latest available appears to be for 2.6. Alternatively, how would I "roll my own" windows API calls in Python 3.1?
[ "You should be able to do everything with ctypes, if a bit cumbersomely.\nHere's an example of getting the \"common application data\" folder:\nfrom ctypes import windll, wintypes\n\n_SHGetFolderPath = windll.shell32.SHGetFolderPathW\npath_buf = wintypes.create_unicode_buffer(255)\ncsidl = 35\n_SHGetFolderPath(0, c...
[ 10, 6 ]
[]
[]
[ "python", "python_3.x", "winapi" ]
stackoverflow_0001057496_python_python_3.x_winapi.txt
Q: Execute a prepared statement in sqlalchemy I have to run 40K requests against a username: SELECT * from user WHERE login = :login It's slow, so I figured I would just use a prepared statement. So I do e = sqlalchemy.create_engine(...) c = e.connect() c.execute("PREPARE userinfo(text) AS SELECT * from user WHERE l...
Execute a prepared statement in sqlalchemy
I have to run 40K requests against a username: SELECT * from user WHERE login = :login It's slow, so I figured I would just use a prepared statement. So I do e = sqlalchemy.create_engine(...) c = e.connect() c.execute("PREPARE userinfo(text) AS SELECT * from user WHERE login = $1") r = c.execute("EXECUTE userinfo('bob...
[ "Not sure how to solve your cursor related error message, but I dont think a prepared staement will solve your performance issue - as long as your using SQL server 2005 or later the execution plan for SELECT * from user WHERE login = $login will already be re-used and there will be no performance gain from the prep...
[ 2, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0001058037_python_sqlalchemy.txt
Q: Flags in Python I'm working with a large matrix (250x250x30 = 1,875,000 cells), and I'd like a way to set an arbitrary number of flags for each cell in this matrix, in some manner that's easy to use and reasonably space efficient. My original plan was a 250x250x30 list array, where each element was something like:...
Flags in Python
I'm working with a large matrix (250x250x30 = 1,875,000 cells), and I'd like a way to set an arbitrary number of flags for each cell in this matrix, in some manner that's easy to use and reasonably space efficient. My original plan was a 250x250x30 list array, where each element was something like: ["FLAG1","FLAG8","FL...
[ "Your solution is fine if every single cell is going to have a flag. However if you are working with a sparse dataset where only a small subsection of your cells will have flags what you really want is a dictionary. You would want to set up the dictonary so the key is a tuple for the location of the cell and the ...
[ 7, 5, 5, 3, 1, 1 ]
[]
[]
[ "flags", "matrix", "numpy", "python" ]
stackoverflow_0001058434_flags_matrix_numpy_python.txt
Q: Coding a coroutine in Python to display "odd" and "even" numbers inifinitely I have scratchy ideas of Generators, Iterators and Coroutines. (from PEPs and other tutorials). I want to implement a coroutine- in which routine1 will print odd and routine2 will print even numbers infinitely in a fashion such as: routin...
Coding a coroutine in Python to display "odd" and "even" numbers inifinitely
I have scratchy ideas of Generators, Iterators and Coroutines. (from PEPs and other tutorials). I want to implement a coroutine- in which routine1 will print odd and routine2 will print even numbers infinitely in a fashion such as: routine1: print odd yield to routine2 routune2: print even yield to rou...
[ "PEP 342, \"Coroutines via Enhanced Generators\", gives as its example 3 'A simple co-routine scheduler or \"trampoline\" that lets coroutines \"call\" other coroutines by yielding the coroutine they wish to invoke.' -- you don't need that much generality (or any of the generality aspects PEP 342 first introduced),...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001058383_python.txt
Q: How to get a nested element in beautiful soup I am struggling with the syntax required to grab some hrefs in a td. The table, tr and td elements dont have any class's or id's. If I wanted to grab the anchor in this example, what would I need? < tr > < td > < a >... Thanks A: As per the docs, you first make ...
How to get a nested element in beautiful soup
I am struggling with the syntax required to grab some hrefs in a td. The table, tr and td elements dont have any class's or id's. If I wanted to grab the anchor in this example, what would I need? < tr > < td > < a >... Thanks
[ "As per the docs, you first make a parse tree:\nimport BeautifulSoup\nhtml = \"<html><body><tr><td><a href='foo'/></td></tr></body></html>\"\nsoup = BeautifulSoup.BeautifulSoup(html)\n\nand then you search in it, for example for <a> tags whose immediate parent is a <td>:\nfor ana in soup.findAll('a'):\n if ana.par...
[ 34, 30 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0001058599_beautifulsoup_python.txt
Q: How do I select a random element from an array in Python? The first examples that I googled didn't work. This should be trivial, right? A: import random random.choice (mylist) A: import random random.choice([1, 2, 3])
How do I select a random element from an array in Python?
The first examples that I googled didn't work. This should be trivial, right?
[ "import random\nrandom.choice (mylist)\n\n", "import random\nrandom.choice([1, 2, 3])\n\n" ]
[ 234, 58 ]
[]
[]
[ "arrays", "python", "random" ]
stackoverflow_0001058712_arrays_python_random.txt
Q: Unicode problems with web pages in Python's urllib I seem to have the all-familiar problem of correctly reading and viewing a web page. It looks like Python reads the page in UTF-8 but when I try to convert it to something more viewable (iso-8859-1) I get this error: UnicodeEncodeError: 'ascii' codec can't encode ...
Unicode problems with web pages in Python's urllib
I seem to have the all-familiar problem of correctly reading and viewing a web page. It looks like Python reads the page in UTF-8 but when I try to convert it to something more viewable (iso-8859-1) I get this error: UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 2: ordinal not in range(12...
[ "As noted by Lennart, your problem is not the decoding. It is trying to encode into \"ascii\", which is often a problem with print statements. I suspect the line\nprint str\n\nis your problem. You need to encode the str into whatever your console is using to have that line work.\n", "It doesn't look like Python...
[ 3, 2, 1 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0001058302_python_unicode.txt
Q: How to append two strings in Python? I have done this operation millions of times, just using the + operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run t...
How to append two strings in Python?
I have done this operation millions of times, just using the + operator! I have no idea why it is not working this time, it is overwriting the first part of the string with the new one! I have a list of strings and just want to concatenate them in one single string! If I run the program from Eclipse it works, from the...
[ "While the two answers are correct (use \" \".join()), your problem (besides very ugly python code) is this:\nYour strings end in \"\\r\", which is a carriage return. Everything is fine, but when you print to the console, \"\\r\" will make printing continue from the start of the same line, hence overwrite what was ...
[ 32, 21, 11, 8, 7, 5 ]
[]
[]
[ "python", "string" ]
stackoverflow_0001058902_python_string.txt
Q: Drawing a Dragons curve in Python I am trying to work out how to draw the dragons curve, with pythons turtle using the An L-System or Lindenmayer system. I no the code is something like the Dragon curve; initial state = ‘F’, replacement rule – replace ‘F’ with ‘F+F-F’, number of replacements = 8, length = 5, ang...
Drawing a Dragons curve in Python
I am trying to work out how to draw the dragons curve, with pythons turtle using the An L-System or Lindenmayer system. I no the code is something like the Dragon curve; initial state = ‘F’, replacement rule – replace ‘F’ with ‘F+F-F’, number of replacements = 8, length = 5, angle = 60 But have no idea how to put tha...
[ "First hit on Google for \"dragons curve python\": \nhttp://www.pynokio.org/dragon.py.htm\nYou can probably modify that to work with your plotting program of choice. I'd try matplotlib. \n", "Draw the dragon curve using turtle module (suggested by @John Fouhy):\n#!/usr/bin/env python\nimport turtle\nfrom functool...
[ 3, 3, 0 ]
[]
[]
[ "fractals", "python" ]
stackoverflow_0000765048_fractals_python.txt
Q: Mule vs ActiveMQ for Python I need to manged several servers, network services, appalication server (Apache, Tomcat) and manage them (start stop, install software). I would like to use Python, since C++ seems to complex and less productive for thing task. In am not sure which middleware to use. ActiveMQ and Mule s...
Mule vs ActiveMQ for Python
I need to manged several servers, network services, appalication server (Apache, Tomcat) and manage them (start stop, install software). I would like to use Python, since C++ seems to complex and less productive for thing task. In am not sure which middleware to use. ActiveMQ and Mule seem to be a good choice, although...
[ "An example python \"script\" that manages various services on multiple remote servers:\nWhat follows is a hacked together script that can be used to manage various services on servers that you have SSH access to.\nYou will ideally want to have an ssh-agent running, or you will be typing your passphrase a lot of ti...
[ 1 ]
[]
[]
[ "messaging", "python" ]
stackoverflow_0001058986_messaging_python.txt
Q: Importing methods for a Python class I wonder if it's possible to keep methods for a Python class in a different file from the class definition, something like this: main_module.py: class Instrument(Object): # Some import statement? def __init__(self): self.flag = True def direct_method(self,ar...
Importing methods for a Python class
I wonder if it's possible to keep methods for a Python class in a different file from the class definition, something like this: main_module.py: class Instrument(Object): # Some import statement? def __init__(self): self.flag = True def direct_method(self,arg1): self.external_method(arg1, ar...
[ "People seem to be overthinking this. Methods are just function valued local variables in class construction scope. So the following works fine:\nclass Instrument(Object):\n # load external methods\n from to_import_from import *\n\n def __init__(self):\n self.flag = True\n def direct_method(self,...
[ 17, 7, 7, 4, 4, 2, 0, 0 ]
[]
[]
[ "import", "methods", "python" ]
stackoverflow_0001057934_import_methods_python.txt
Q: Searching across multiple tables (best practices) I have property management application consisting of tables: tenants landlords units properties vendors-contacts Basically I want one search field to search them all rather than having to select which category I am searching. Would this be an acceptable solution ...
Searching across multiple tables (best practices)
I have property management application consisting of tables: tenants landlords units properties vendors-contacts Basically I want one search field to search them all rather than having to select which category I am searching. Would this be an acceptable solution (technology wise?) Will searching across 5 tables be OK...
[ "Why not create a view which is a union of the tables which aggregates the columns you want to search on into one, and then search on that aggregated column?\nYou could do something like this:\nselect 'tenants:' + ltrim(str(t.Id)), <shared fields> from Tenants as t union\nselect 'landlords:' + ltrim(str(l.Id)), <sh...
[ 7, 4, 3, 1 ]
[]
[]
[ "mysql", "postgresql", "pylons", "python", "sql" ]
stackoverflow_0001059253_mysql_postgresql_pylons_python_sql.txt
Q: Cherrypy server does not accept incoming http request on MS Windows if output (stdout) is not redirected It is a rather strange 'bug'. I have written a cherrypy based server. If I run it this way: python simple_server.py > out.txt It works as expected. Without the the redirection at the end, however, the server...
Cherrypy server does not accept incoming http request on MS Windows if output (stdout) is not redirected
It is a rather strange 'bug'. I have written a cherrypy based server. If I run it this way: python simple_server.py > out.txt It works as expected. Without the the redirection at the end, however, the server will not accept any connection at all. Anyone has any idea? I am using python 2.4 on a Win XP professional ma...
[ "Are you running the script in an XP \"command window\"? Otherwise (if there's neither redirection nor command window available), standard output might simply be closed, which might inhibit the script (or rather its underlying framework).\n", "CherryPy runs in a \"development\" mode by default, which includes log...
[ 1, 0 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0001056642_cherrypy_python.txt
Q: Python Memory Model I have a very large list Suppose I do that (yeah, I know the code is very unpythonic, but for the example's sake..): n = (2**32)**2 for i in xrange(10**7) li[i] = n works fine. however: for i in xrange(10**7) li[i] = i**2 consumes a significantly larger amount of memory. I don't understan...
Python Memory Model
I have a very large list Suppose I do that (yeah, I know the code is very unpythonic, but for the example's sake..): n = (2**32)**2 for i in xrange(10**7) li[i] = n works fine. however: for i in xrange(10**7) li[i] = i**2 consumes a significantly larger amount of memory. I don't understand why that is - storing t...
[ "Java special-cases a few value types (including integers) so that they're stored by value (instead of, by object reference like everything else). Python doesn't special-case such types, so that assigning n to many entries in a list (or other normal Python container) doesn't have to make copies.\nEdit: note that th...
[ 18, 6, 3, 0 ]
[]
[]
[ "arrays", "memory", "model", "python" ]
stackoverflow_0001059674_arrays_memory_model_python.txt
Q: Strange behavior with ModelForm and saving This problem is very strange and I'm hoping someone can help me. For the sake of argument, I have a Author model with ForeignKey relationship to the Book model. When I display an author, I would like to have a ChoiceField that ONLY displays the books associated with tha...
Strange behavior with ModelForm and saving
This problem is very strange and I'm hoping someone can help me. For the sake of argument, I have a Author model with ForeignKey relationship to the Book model. When I display an author, I would like to have a ChoiceField that ONLY displays the books associated with that author. As such, I override the AuthorForm.in...
[ "Not quite sure what you are doing wrong, but it is best to just modify the queryset:\nclass ClientForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n self.affiliate = kwargs.pop('affiliate')\n super(ClientForm, self).__init__(*args, **kwargs)\n self.fields[\"referral\"].querys...
[ 2 ]
[]
[]
[ "django", "modelform", "python" ]
stackoverflow_0001059831_django_modelform_python.txt
Q: How to delete all the items of a specific key in a list of dicts? I'm trying to remove some items of a dict based on their key, here is my code: d1 = {'a': 1, 'b': 2} d2 = {'a': 1} l = [d1, d2, d1, d2, d1, d2] for i in range(len(l)): if l[i].has_key('b'): del l[i]['b'] print l The output will be: [...
How to delete all the items of a specific key in a list of dicts?
I'm trying to remove some items of a dict based on their key, here is my code: d1 = {'a': 1, 'b': 2} d2 = {'a': 1} l = [d1, d2, d1, d2, d1, d2] for i in range(len(l)): if l[i].has_key('b'): del l[i]['b'] print l The output will be: [{'a': 1}, {'a': 1}, {'a': 1}, {'a': 1}, {'a': 1}, {'a': 1}] Is there a...
[ "d1 = {'a': 1, 'b': 2}\nd2 = {'a': 1}\nl = [d1, d2, d1, d2, d1, d2]\nfor d in l:\n d.pop('b',None)\nprint l\n\n", "A slight simplification:\n for d in l:\n if d.has_key('b'):\n del d['b']\n\nSome people might also do\n for d in l:\n try:\n del d['b']\n except KeyError:\n ...
[ 16, 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001059924_python.txt
Q: How do i output a dynamically generated web page to a .html page instead of .py cgi page? So ive just started learning python on WAMP, ive got the results of a html form using cgi, and successfully performed a database search with mysqldb. I can return the results to a page that ends with .py by using print state...
How do i output a dynamically generated web page to a .html page instead of .py cgi page?
So ive just started learning python on WAMP, ive got the results of a html form using cgi, and successfully performed a database search with mysqldb. I can return the results to a page that ends with .py by using print statements in the python cgi code, but i want to create a webpage that's .html and have that returne...
[ "First, I'd suggest that you remember that URLs are URLs and that file extensions don't matter, and that you should just leave it.\nIf that isn't enough, then remember that URLs are URLs and that file extensions don't matter — and configure Apache to use a different rule to determine that is a CGI program rather th...
[ 3 ]
[]
[]
[ "html", "python", "webpage" ]
stackoverflow_0001060289_html_python_webpage.txt
Q: HTML Agility Pack or HTML Screen Scraping libraries for Java, Ruby, Python? I found the HTML Agility Pack useful and easy to use for screen scraping web sites. What's the equivalent library for HTML screen scraping in Java, Ruby, Python? A: Found what I was looking for: Options for HTML scraping? A: Beautiful...
HTML Agility Pack or HTML Screen Scraping libraries for Java, Ruby, Python?
I found the HTML Agility Pack useful and easy to use for screen scraping web sites. What's the equivalent library for HTML screen scraping in Java, Ruby, Python?
[ "Found what I was looking for:\nOptions for HTML scraping?\n", "BeautifulSoup is the standard Python screen scraping tool.\nRecently, however, I used the (incomplete at the moment) pyQuery, which is more or less a rewrite of jQuery into python, and found it to be very useful.\n" ]
[ 5, 3 ]
[]
[]
[ "html", "java", "python", "ruby", "screen_scraping" ]
stackoverflow_0001060484_html_java_python_ruby_screen_scraping.txt
Q: Modeling a complex relationship in Django I'm working on a Web service in Django, and I need to model a very specific, complex relationship which I just can't be able to solve. Imagine three general models, let's call them Site, Category and Item. Each Site contains one or several Categories, but it can relate to ...
Modeling a complex relationship in Django
I'm working on a Web service in Django, and I need to model a very specific, complex relationship which I just can't be able to solve. Imagine three general models, let's call them Site, Category and Item. Each Site contains one or several Categories, but it can relate to them in one of two possible ways: one are "comm...
[ "Why not just have both types of category in one model, so you just have 3 models?\nSite\n\nCategory\n Sites = models.ManyToManyField(Site)\n IsCommon = models.BooleanField()\n\nItem\n Category = models.ForeignKey(Category)\n\nYou say \"Internally, those two type of Categories are completely identical\". So in...
[ 4, 1, 0 ]
[]
[]
[ "django", "django_models", "entity_relationship", "python" ]
stackoverflow_0001053344_django_django_models_entity_relationship_python.txt
Q: How to call a data member of the base class if it is being overwritten as a property in the derived class? This question is similar to this other one, with the difference that the data member in the base class is not wrapped by the descriptor protocol. In other words, how can I access a member of the base class if...
How to call a data member of the base class if it is being overwritten as a property in the derived class?
This question is similar to this other one, with the difference that the data member in the base class is not wrapped by the descriptor protocol. In other words, how can I access a member of the base class if I am overriding its name with a property in the derived class? class Base(object): def __init__(self): ...
[ "Life is simpler if you use delegation instead of inheritance. This is Python. You aren't obligated to inherit from Base.\nclass LooksLikeDerived( object ):\n def __init__( self ):\n self.base= Base()\n\n @property\n def foo(self):\n return 1 + self.base.foo # always works\n\n @foo.sette...
[ 9, 3, 1, 0, 0 ]
[]
[]
[ "descriptor", "inheritance", "overloading", "python" ]
stackoverflow_0001057518_descriptor_inheritance_overloading_python.txt
Q: print statement in for loop only executes once I am teaching myself python. I was thinking of small programs, and came up with an idea to do a keno number generator. For any who don't know, you can pick 4-12 numbers, ranged 1-80, to match. So the first is part asks how many numbers, the second generates them. I ca...
print statement in for loop only executes once
I am teaching myself python. I was thinking of small programs, and came up with an idea to do a keno number generator. For any who don't know, you can pick 4-12 numbers, ranged 1-80, to match. So the first is part asks how many numbers, the second generates them. I came up with x = raw_input('How many numbers do you wa...
[ "This should do what you want:\nx = raw_input('How many numbers do you want to play?')\nfor i in xrange(int(x)):\n print random.randrange(1,81)\n\nIn Python indentation matters. It is the way it knows when you're in a specific block of code. So basically we use the xrange function to create a range to loop throug...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0001061534_python.txt
Q: How can I make sure all my Python code "compiles"? My background is C and C++. I like Python a lot, but there's one aspect of it (and other interpreted languages I guess) that is really hard to work with when you're used to compiled languages. When I've written something in Python and come to the point where I can...
How can I make sure all my Python code "compiles"?
My background is C and C++. I like Python a lot, but there's one aspect of it (and other interpreted languages I guess) that is really hard to work with when you're used to compiled languages. When I've written something in Python and come to the point where I can run it, there's still no guarantee that no language-spe...
[ "Look at PyChecker and PyLint.\nHere's example output from pylint, resulting from the trivial program:\nprint a\n\nAs you can see, it detects the undefined variable, which py_compile won't (deliberately).\nin foo.py:\n\n************* Module foo\nC: 1: Black listed name \"foo\"\nC: 1: Missing docstring\nE: 1: Und...
[ 21, 2, 1, 1, 0 ]
[]
[]
[ "code_analysis", "parsing", "python" ]
stackoverflow_0001026966_code_analysis_parsing_python.txt
Q: python decimal comparison python decimal comparison >>> from decimal import Decimal >>> Decimal('1.0') > 2.0 True I was expecting it to convert 2.0 correctly, but after reading thru PEP 327 I understand there were some reason for not implictly converting float to Decimal, but shouldn't in that case it should rais...
python decimal comparison
python decimal comparison >>> from decimal import Decimal >>> Decimal('1.0') > 2.0 True I was expecting it to convert 2.0 correctly, but after reading thru PEP 327 I understand there were some reason for not implictly converting float to Decimal, but shouldn't in that case it should raise TypeError as it does in this ...
[ "Re 1, it's indeed the behavior we designed -- right or wrong as it may be (sorry if that trips your use case up, but we were trying to be general!).\nSpecifically, it's long been the case that every Python object could be subject to inequality comparison with every other -- objects of types that aren't really comp...
[ 26, 3, 1 ]
[]
[]
[ "comparison", "decimal", "python" ]
stackoverflow_0001062008_comparison_decimal_python.txt
Q: Modifying list contents in Python I have a list like: list = [[1,2,3],[4,5,6],[7,8,9]] I want to append a number at the start of every value in the list programmatically, say the number is 9. I want the new list to be like: list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]] How do I go about doing this in Python? I know it ...
Modifying list contents in Python
I have a list like: list = [[1,2,3],[4,5,6],[7,8,9]] I want to append a number at the start of every value in the list programmatically, say the number is 9. I want the new list to be like: list = [[9,1,2,3],[9,4,5,6],[9,7,8,9]] How do I go about doing this in Python? I know it is a very trivial question but I couldn...
[ "for sublist in thelist:\n sublist.insert(0, 9)\n\ndon't use built-in names such as list for your own stuff, that's just a stupid accident in the making -- call YOUR stuff mylist or thelist or the like, not list.\nEdit: as the OP aks how to insert > 1 item at the start of each sublist, let me point out that the mo...
[ 16, 12, 2, 2, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001061937_list_python.txt
Q: Python NotImplemented constant Looking through decimal.py, it uses NotImplemented in many special methods. e.g. class A(object): def __lt__(self, a): return NotImplemented def __add__(self, a): return NotImplemented The Python docs say: NotImplemented Special value which can be returned ...
Python NotImplemented constant
Looking through decimal.py, it uses NotImplemented in many special methods. e.g. class A(object): def __lt__(self, a): return NotImplemented def __add__(self, a): return NotImplemented The Python docs say: NotImplemented Special value which can be returned by the “rich comparison” special m...
[ "NotImplemented allows you to indicate that a comparison between the two given operands has not been implemented (rather than indicating that the comparison is valid, but yields False, for the two operands).\nFrom the Python Language Reference:\n\nFor objects x and y, first x.__op__(y)\nis tried. If this is not imp...
[ 35, 7, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001062096_python.txt
Q: obtain collection_name from parent's key in GAE is it possible to ask parent for its refered collection_name based on one of its keys, lets say i have a parent db model and its key, can i know ths children who refer to this parent through collection name or otherwise class Parent(db.Model): user = db.UserProper...
obtain collection_name from parent's key in GAE
is it possible to ask parent for its refered collection_name based on one of its keys, lets say i have a parent db model and its key, can i know ths children who refer to this parent through collection name or otherwise class Parent(db.Model): user = db.UserProperty() class Childs(db.Model): refer = db.ReferenceP...
[ "I think you're asking \"can I get the set of all the children that refer to a given parent\".\nIn which case, yes you can, it's a property of the Parent class.\nAssuming you have a Parent object p then the children that reference it will be in p.children\nIf you hadn't specified the collection_name on the Referenc...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001062108_google_app_engine_python.txt
Q: Python 3.0 smtplib I have a very simple piece of code that I used in previous versions of Python without issues (version 2.5 and prior). Now with 3.0, the following code give the error on the login line "argument 1 must be string or buffer, not str". import smtplib smtpserver = 'mail.somedomain.com' AUTHRE...
Python 3.0 smtplib
I have a very simple piece of code that I used in previous versions of Python without issues (version 2.5 and prior). Now with 3.0, the following code give the error on the login line "argument 1 must be string or buffer, not str". import smtplib smtpserver = 'mail.somedomain.com' AUTHREQUIRED = 1 ...
[ "UPDATE: just noticed from a look at the bug tracker there's a suggested fix also: \nEdit smtplib.py and replace the existing encode_plain() definition with this: \ndef encode_plain(user, password):\n s = \"\\0%s\\0%s\" % (user, password)\n return encode_base64(s.encode('ascii'), eol='')\n\nTested here on my ...
[ 4, 3, 2, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0000549391_python_python_3.x.txt
Q: Python - Reading multiple lines into list OK guys/gals stuck again on something simple I have a text file which has multiple lines per entry, the data is in the following format firstword word word word wordx word word word interesting1 word word word word wordy word word word wordz word word word interesting2 w...
Python - Reading multiple lines into list
OK guys/gals stuck again on something simple I have a text file which has multiple lines per entry, the data is in the following format firstword word word word wordx word word word interesting1 word word word word wordy word word word wordz word word word interesting2 word word word lastword this sequence repeats ...
[ "from itertools import izip, tee, islice\n\ni1, i2 = tee(open(\"foo.txt\"))\n\nfor line2, line4 in izip(islice(i1,1, None, 4), islice(i2, 3, None, 4)) :\n print line2.split(\" \")[4], \"=\", line4.split(\" \")[4]\n\n", "In that case, make a regexp that matches the repeating text, and has groups for the interes...
[ 6, 0, 0 ]
[]
[]
[ "line", "parsing", "python", "text" ]
stackoverflow_0001062171_line_parsing_python_text.txt
Q: Python Script Executed with Makefile I am writing python scripts and execute them in a Makefile. The python script is used to process data in a pipeline. I would like Makefile to execute the script every time I make a change to my python scripts. Does anyone have an idea of how to do this? A: That's not a lot of...
Python Script Executed with Makefile
I am writing python scripts and execute them in a Makefile. The python script is used to process data in a pipeline. I would like Makefile to execute the script every time I make a change to my python scripts. Does anyone have an idea of how to do this?
[ "That's not a lot of information, so this answer is a bit vague. The basic principle of Makefiles is to list dependencies for each target; in this case, your target (let's call it foo) depends on your python script (let's call it do-foo.py):\nfoo: do-foo.py\n python do-foo.py > foo\n\nNow foo will be rerun whene...
[ 21, 4, 0 ]
[]
[]
[ "makefile", "python" ]
stackoverflow_0001062436_makefile_python.txt
Q: Python win32 com : how to handle 'out' parameter? I need to access a third-party COM server with following interface definition (idl): interface IDisplay : IDispatch { HRESULT getFramebuffer ( [in] ULONG aScreenId, [out] IFramebuffer * * aFramebuffer, [out] LONG * aXOrigin, [out] LONG * aYOrigin ...
Python win32 com : how to handle 'out' parameter?
I need to access a third-party COM server with following interface definition (idl): interface IDisplay : IDispatch { HRESULT getFramebuffer ( [in] ULONG aScreenId, [out] IFramebuffer * * aFramebuffer, [out] LONG * aXOrigin, [out] LONG * aYOrigin ); }; As you can see, it returns 3 values via [out] pa...
[ "Since those are out parameters, can't you simply do the following?\nFramebuffer, XOrigin, YOrigin = display.getFrameBuffer(ScreenId)\n\nThere is some good references in Python Programming on Win32 Chapter 12 Advanced Python and COM\nAnd they indicate that the syntax should be like above. They also mention using \n...
[ 8, 3 ]
[]
[]
[ "com", "python" ]
stackoverflow_0001062129_com_python.txt
Q: Is registered atexit handler inherited by spawned child processes? I am writing a daemon program using python 2.5. In the main process an exit handler is registered with atexit module, it seems that the handler gets called when each child process ends, which is not I expected. I noticed this behavior isn't menti...
Is registered atexit handler inherited by spawned child processes?
I am writing a daemon program using python 2.5. In the main process an exit handler is registered with atexit module, it seems that the handler gets called when each child process ends, which is not I expected. I noticed this behavior isn't mentioned in python atexit doc, anybody knows the issue? If this is how it sh...
[ "When you fork to make a child process, that child is an exact copy of the parent -- including of course registered exit functions as well as all other code and data structures. I believe that's the issue you're observing -- of course it's not mentioned in each and every module, because it necessarily applies to ev...
[ 4, 3, 1 ]
[]
[]
[ "atexit", "multiprocessing", "python" ]
stackoverflow_0001052716_atexit_multiprocessing_python.txt
Q: Calling a non-returning python function from a python script I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want ...
Calling a non-returning python function from a python script
I want to call a wrapped C++ function from a python script which is not returning immediately (in detail: it is a function which starts a QApplication window and the last line in that function is QApplication->exec()). So after that function call I want to move on to my next line in the python script but on executing t...
[ "Use a thread (longer example here):\nfrom threading import Thread\n\nclass WindowThread(Thread):\n def run(self):\n callCppFunctionHere()\n\nWindowThread().start()\n\n", "QApplication::exec() starts the main loop of the application and will only return after the application quits. If you want to run co...
[ 2, 1, 0 ]
[]
[]
[ "c++", "function", "python", "scripting" ]
stackoverflow_0001062562_c++_function_python_scripting.txt
Q: Python Encryption: Encrypting password using PGP public key I have the key pair generated by the GPG. Now I want to use the public key for encrypting the password. I need to make a function in Python. Can somebody guide me on how to do this? I studied the Crypto package but was unable to find out how to encrypt th...
Python Encryption: Encrypting password using PGP public key
I have the key pair generated by the GPG. Now I want to use the public key for encrypting the password. I need to make a function in Python. Can somebody guide me on how to do this? I studied the Crypto package but was unable to find out how to encrypt the password using the public key. I also read about the chilkat Py...
[ "Have a look at PyGPGME\n", "See also the answers provided to the following questions found in this search Python Encryption questions at Stack Overflow :\n\nPython and PGP/encryption\nEncrypt a string using a public key\nHow to do PGP in Python (generate keys, encrypt/decrypt)\n\n" ]
[ 2, 0 ]
[]
[]
[ "cryptography", "encryption", "gnupg", "python" ]
stackoverflow_0001063014_cryptography_encryption_gnupg_python.txt
Q: How to code a Download/Upload Speed Monitor in PHP,Python, or Java? I have to code a up/download speed monitor. It will obtain the current download and upload transfer speed of the computer which it has been installed and post it to another server periodically. c But I don't have an idea about how to catch instant...
How to code a Download/Upload Speed Monitor in PHP,Python, or Java?
I have to code a up/download speed monitor. It will obtain the current download and upload transfer speed of the computer which it has been installed and post it to another server periodically. c But I don't have an idea about how to catch instant transfer rates of a computer. As you know some of network monitoring pro...
[ "You don't say which operating system you're interested in.\nA quick google turned up this: http://excess.org/speedometer/\n\"Measure and display the rate of data across a network connection or data being stored in a file\"\nOpensource, written in Python\n", "JPCAP (a java packet capture library-sniffer) is suita...
[ 3, 1 ]
[]
[]
[ "java", "networking", "php", "python" ]
stackoverflow_0001057449_java_networking_php_python.txt
Q: How can I make a list of files, modification dates and paths? I have directory with subdirectories and I have to make a list like: file_name1 modification_date1 path1 file_name2 modification_date2 path2 and write the list into text file how can i do it in python? A: For traversing the subdirectories, use os.w...
How can I make a list of files, modification dates and paths?
I have directory with subdirectories and I have to make a list like: file_name1 modification_date1 path1 file_name2 modification_date2 path2 and write the list into text file how can i do it in python?
[ "For traversing the subdirectories, use os.walk().\nFor getting modification date, use os.stat()\nThe modification time will be a timestamp counting seconds from epoch, there are various methods in the time module that help you convert those to something easier to use.\n", "import os\nimport time\n\nfor root, dir...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0001063037_python.txt
Q: Custom Python exception with different include paths Update: This is, as I was told, no principle Python related problem, but seems to be more specific. See below for more explanations to my problem. I have a custom exception (let's call it CustomException), that lives in a file named exceptions.py. Now imagine, t...
Custom Python exception with different include paths
Update: This is, as I was told, no principle Python related problem, but seems to be more specific. See below for more explanations to my problem. I have a custom exception (let's call it CustomException), that lives in a file named exceptions.py. Now imagine, that I can import this file via two paths: import applicati...
[ "Why that would be a problem? exception would me matched based on class type and it would be same however it is imported e.g.\nimport exceptions\nl=[]\ntry:\n l[1]\nexcept exceptions.IndexError,e:\n print e\n\ntry:\n l[1]\nexcept IndexError,e:\n print e\n\nboth catch the same exception\nyou can even ass...
[ 1, 1, 0, 0 ]
[]
[]
[ "django", "exception", "python" ]
stackoverflow_0001063228_django_exception_python.txt
Q: KenKen puzzle addends: REDUX A (corrected) non-recursive algorithm This question relates to those parts of the KenKen Latin Square puzzles which ask you to find all possible combinations of ncells numbers with values x such that 1 <= x <= maxval and x(1) + ... + x(ncells) = targetsum. Having tested several of the...
KenKen puzzle addends: REDUX A (corrected) non-recursive algorithm
This question relates to those parts of the KenKen Latin Square puzzles which ask you to find all possible combinations of ncells numbers with values x such that 1 <= x <= maxval and x(1) + ... + x(ncells) = targetsum. Having tested several of the more promising answers, I'm going to award the answer-prize to Lennart ...
[ "Your algorithm seems pretty good at first blush, and I don't think OO or another language would improve the code. I can't say if recursion would have helped but I admire the non-recursive approach. I bet it was harder to get working and it's harder to read but it likely is more efficient and it's definitely quite ...
[ 3, 2, 2, 1, 1, 1, 1, 1, 1 ]
[]
[]
[ "algorithm", "combinations", "puzzle", "python", "statistics" ]
stackoverflow_0001061590_algorithm_combinations_puzzle_python_statistics.txt
Q: how to use french letters in a django template? I have some french letters (é, è, à...) in a django template but when it is loaded by django, an UnicodeDecodeError exception is raised. If I don't load the template but directly use a python string. It works ok. Is there something to do to use unicode with django te...
how to use french letters in a django template?
I have some french letters (é, è, à...) in a django template but when it is loaded by django, an UnicodeDecodeError exception is raised. If I don't load the template but directly use a python string. It works ok. Is there something to do to use unicode with django template?
[ "You are probably storing the template in a non-unicode encoding, such as latin-1. I believe Django assumes that templates are in UTF-8 by default (though there is a setting to override this).\nYour editor should be capable of saving the template file in the UTF-8 encoding (probably via a dropdown on the save as p...
[ 7, 3 ]
[]
[]
[ "django", "python", "unicode" ]
stackoverflow_0001063626_django_python_unicode.txt
Q: payment processing - pylons/python I'm building an application that eventually needs to process cc #s. I'd like to handle it completely in my app, and then hand off the information securely to my payment gateway. Ideally the user would have no interaction with the payment gateway directly. Any thoughts? Is ther...
payment processing - pylons/python
I'm building an application that eventually needs to process cc #s. I'd like to handle it completely in my app, and then hand off the information securely to my payment gateway. Ideally the user would have no interaction with the payment gateway directly. Any thoughts? Is there an easier way?
[ "Most payment gateways offer a few mechanisms for submitting CC payments:\n1) A simple HTTPS POST where your application collects the customer's payment details (card number, expiry date, amount, optional CVV) and then submits this to the gateway. The payment parameters are sent through in the POST variables, and t...
[ 3, 1, 1 ]
[]
[]
[ "payment", "payment_gateway", "pylons", "python" ]
stackoverflow_0001060334_payment_payment_gateway_pylons_python.txt
Q: Can I use Win32 COM to replace text inside a word document? I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read s...
Can I use Win32 COM to replace text inside a word document?
I have to perform a large number of replacements in some documents, and the thing is, I would like to be able to automate that task. Some of the documents contain common strings, and this would be pretty useful if it could be automated. From what I read so far, COM could be one way of doing this, but I don't know if te...
[ "I like the answers so far; \nhere's a tested example (slightly modified from here) \nthat replaces all occurrences of a string in a Word document:\nimport win32com.client\n\ndef search_replace_all(word_file, find_str, replace_str):\n ''' replace all occurrences of `find_str` w/ `replace_str` in `word_file` '''\...
[ 13, 9, 3, 2, 2 ]
[]
[]
[ "com", "ms_word", "python", "replace", "winapi" ]
stackoverflow_0001045628_com_ms_word_python_replace_winapi.txt
Q: Why isn't this a valid schema for Rx? I'm using YAML as a configuration file format for a Python project. Recently I found Rx to be the only schema validator available for Python and YAML. :-/ Kwalify works with YAML, but it's only for Ruby and Java. :( I've been reading their lacking documentation all day and jus...
Why isn't this a valid schema for Rx?
I'm using YAML as a configuration file format for a Python project. Recently I found Rx to be the only schema validator available for Python and YAML. :-/ Kwalify works with YAML, but it's only for Ruby and Java. :( I've been reading their lacking documentation all day and just can't seem to write a valid schema to rep...
[ "Try this:\ntype: //map\nvalues:\n type: //rec\n required:\n exec: //str\n optional:\n aliases:\n type: //arr\n contents: //str\n length: {min: 1, max: 10}\n filter:\n type: //rec\n optional:\n sms: //str\n email: //str\n all: //str\n\nA map can contain any ...
[ 4 ]
[]
[]
[ "python", "schema", "yaml" ]
stackoverflow_0001061482_python_schema_yaml.txt
Q: Hex data from socket, process and response Lets put it in parts. I got a socket receiving data OK and I got it in the \x31\x31\x31 format. I know that I can get the same number, ripping the \x with something like for i in data: print hex(ord(i)) so I got 31 in each case. But if I want to add 1 to the data (so it...
Hex data from socket, process and response
Lets put it in parts. I got a socket receiving data OK and I got it in the \x31\x31\x31 format. I know that I can get the same number, ripping the \x with something like for i in data: print hex(ord(i)) so I got 31 in each case. But if I want to add 1 to the data (so it shall be "32 32 32")to send it as response, how...
[ "use the struct module\nunpack and get the 3 values in abc\n(a, b, c) = struct.unpack(\">BBB\", your_string)\nthen \na, b, c = a+1, b+1, c+1\nand pack into the response\nresponse = struct.pack(\">BBB\", a, b, c)\nsee the struct module in python documentation for more details\n", "The \"\\x31\" is not a format but...
[ 4, 4, 0, 0 ]
[]
[]
[ "hex", "python", "sockets" ]
stackoverflow_0001063775_hex_python_sockets.txt
Q: PyQt: Consolidating signals to a single slot I am attempting to reduce the amount of signals I have to use in my contextmenus. The menu consists of actions which switches the operation mode of the program, so the operation carried out by the slots is very simple. Quoting the documentation on QMenu::triggered, Nor...
PyQt: Consolidating signals to a single slot
I am attempting to reduce the amount of signals I have to use in my contextmenus. The menu consists of actions which switches the operation mode of the program, so the operation carried out by the slots is very simple. Quoting the documentation on QMenu::triggered, Normally, you connect each menu action's triggered() ...
[ "Using QObject.Sender is one of the solution, although not the cleanest one.\nUse QSignalMapper to associate cleanly a value with the object that emitted the signal.\n", "I use this approach:\nfrom functools import partial\n\ndef bind(self, action, *params):\n self.connect(action, QtCore.SIGNAL('triggered()'),...
[ 4, 2, 1 ]
[]
[]
[ "python", "qt" ]
stackoverflow_0001063734_python_qt.txt
Q: In Python, Using pyodbc, How Do You Perform Transactions? I have a username which I must change in numerous (up to ~25) tables. (Yeah, I know.) An atomic transaction seems to be the way to go for this sort of thing. However, I do not know how to do this with pyodbc. I've seen various tutorials on atomic transa...
In Python, Using pyodbc, How Do You Perform Transactions?
I have a username which I must change in numerous (up to ~25) tables. (Yeah, I know.) An atomic transaction seems to be the way to go for this sort of thing. However, I do not know how to do this with pyodbc. I've seen various tutorials on atomic transactions before, but have never used them. The setup: Windows pla...
[ "By its documentation, pyodbc does support transactions, but only if the odbc driver support it. Furthermore, as pyodbc is compliant with PEP 249, data is stored only when a manual commit is done.\nThis means that you have to explicitely commit() the transaction, or rollback() the entire transaction.\nNote that pyo...
[ 25 ]
[ "I don't think pyodbc has any specific support for transactions. You need to send the SQL command to start/commit/rollback transactions.\n" ]
[ -10 ]
[ "pyodbc", "python", "transactions" ]
stackoverflow_0001063770_pyodbc_python_transactions.txt
Q: How to debug the MySQL error message: Caught an exception while rendering I am building Django +MySQL on dreamhost, but met the error messages: Caught an exception while rendering: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to ...
How to debug the MySQL error message: Caught an exception while rendering
I am building Django +MySQL on dreamhost, but met the error messages: Caught an exception while rendering: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ORDER BY tag.used_count DESC, tag.name ASC' at line 1") I traced h...
[ "Is it possible that there are no questions, in which case the SQL will contain something like \"WHERE question_id IN ()\" which wouldn't be valid SQL.\n" ]
[ 2 ]
[]
[]
[ "django", "dreamhost", "mysql", "python" ]
stackoverflow_0001064152_django_dreamhost_mysql_python.txt
Q: error while uploading project to Google App Engine(python) 2009-06-30 23:36:28,483 ERROR appcfg.py:1272 An unexpected error occurred. Aborting. Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.py", line 1250, in DoUpload missing_files = self.Begi...
error while uploading project to Google App Engine(python)
2009-06-30 23:36:28,483 ERROR appcfg.py:1272 An unexpected error occurred. Aborting. Traceback (most recent call last): File "C:\Program Files\Google\google_appengine\google\appengine\tools\appcfg.py", line 1250, in DoUpload missing_files = self.Begin() File "C:\Program Files\Google\google_appengine\google\appe...
[ "You're trying to upload to a URL to which you lack access -- are you sure you're spelling your app name right, own its name on appspot, etc, etc?\n", "I see a HTTP 403 Forbidden in there, which says to me that your authentications is probably not sorted out correctly.\n", "HTTP Error 403: Forbidden... bad user...
[ 1, 0, 0 ]
[]
[]
[ "google_app_engine", "python", "uploading" ]
stackoverflow_0001064422_google_app_engine_python_uploading.txt
Q: Are Python commands suitable in Vim's visual mode? I have found the following command in AWK useful in Vim :'<,'>!awk '{ print $2 }' Python may also be useful in Vim. However, I have not found an useful command in Python for Vim's visual mode. Which Python commands do you use in Vim? A: It's hard to make useful...
Are Python commands suitable in Vim's visual mode?
I have found the following command in AWK useful in Vim :'<,'>!awk '{ print $2 }' Python may also be useful in Vim. However, I have not found an useful command in Python for Vim's visual mode. Which Python commands do you use in Vim?
[ "It's hard to make useful one-liner filters in Python. You need to import sys to get stdin, and already you're starting to push it. This isn't to say anything bad about Python. My feeling is that Python is optimized for multi-line scripts, while the languages that do well at one-liners (awk, sed, bash, I could name...
[ 4, 4 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0001064644_python_vim.txt
Q: Formatting a variable in Django and autofields I have this problem I've been trying to tackle for a while. I have a variable that is 17 characters long, and when displaying the variable on my form, I want it to display the last seven characters of this variable in bold...how do I go about this...I'd really apprec...
Formatting a variable in Django and autofields
I have this problem I've been trying to tackle for a while. I have a variable that is 17 characters long, and when displaying the variable on my form, I want it to display the last seven characters of this variable in bold...how do I go about this...I'd really appreciate anybody's insight on this.
[ "{{ thevar|slice:\":-7\" }}<b>{{ thevar|slice:\"-7:\" }}</b>\n\nThe slice built-in filter in Django templates acts like slicing does in Python, so that for example s[:-7] is the string excluding its last 7 characters and s[-7:] is the substring formed by just the last 7 characters.\n" ]
[ 2 ]
[]
[]
[ "django", "python", "string_formatting" ]
stackoverflow_0001064953_django_python_string_formatting.txt
Q: How do I include a PHP script in Python? I have a PHP script (news-generator.php) which, when I include it, grabs a bunch of news items and prints them. Right now, I'm using Python for my website (CGI). When I was using PHP, I used something like this on the "News" page: <?php print("<h1>News and Updates</h1>"); i...
How do I include a PHP script in Python?
I have a PHP script (news-generator.php) which, when I include it, grabs a bunch of news items and prints them. Right now, I'm using Python for my website (CGI). When I was using PHP, I used something like this on the "News" page: <?php print("<h1>News and Updates</h1>"); include("news-generator.php"); print("</body>")...
[ "import subprocess\n\ndef php(script_path):\n p = subprocess.Popen(['php', script_path], stdout=subprocess.PIPE)\n result = p.communicate()[0]\n return result\n\n# YOUR CODE BELOW:\npage_html = \"<h1>News and Updates</h1>\"\nnews_script_output = php(\"news-generator.php\") \nprint page_html + news_script_o...
[ 11, 7, 1, 0, 0 ]
[]
[]
[ "execution", "integration", "php", "python", "scripting" ]
stackoverflow_0001060436_execution_integration_php_python_scripting.txt
Q: for statement in python When an exe file is run it prints out some stuff. I'm trying to run this on some numbers below and print out line 54 ( = blah ). It says process isn't defined and I'm really unsure how to fix this and get what I want printed to the screen. If anyone could post some code or ways to fix this ...
for statement in python
When an exe file is run it prints out some stuff. I'm trying to run this on some numbers below and print out line 54 ( = blah ). It says process isn't defined and I'm really unsure how to fix this and get what I want printed to the screen. If anyone could post some code or ways to fix this thank you so very much! for j...
[ "I can't help but clean that up a little.\n# aesthetically (so YMMV), I think the code would be better if it were ...\n# (and I've asked some questions throughout)\n\nj_map = {\n 90: [0], # prefer lists [] to tuples (), I say...\n 52.62263: [0, 72, 144, 216, 288],\n 26.5651: [324, 36, 108, 180, 252],\n 10.8123...
[ 6, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001065133_python.txt
Q: Unable to understand a statement about customizing Python's Macro Syntax Cody has been building a Pythonic Macro Syntax. He says These macros allow you to define completely custom syntax, from new constructs to new operators. There's no facility for doing this in Python as it stands. I am not sure what h...
Unable to understand a statement about customizing Python's Macro Syntax
Cody has been building a Pythonic Macro Syntax. He says These macros allow you to define completely custom syntax, from new constructs to new operators. There's no facility for doing this in Python as it stands. I am not sure what he means by new constructs to new operators: Does he refer to binary operators...
[ "No doubt Cody refers to completely new operators that are not currently in Python, such as (I dunno) ^^ or ++ or +* and so on, whatever they might mean. And he's explicitly saying that the macro system lets you define a completely new syntax for Python (his question was about the syntax of the macro definitions th...
[ 6 ]
[]
[]
[ "macros", "python", "syntax" ]
stackoverflow_0001065966_macros_python_syntax.txt
Q: Object Attribute in Random List Not Accessible in Python I'm working on my first object oriented bit of python and I have the following: #!/usr/bin/python import random class triangle: # Angle A To Angle C Connects Side F # Angle C to Angle B Connects Side D # Angle B to Angle A Connects Side E def __init...
Object Attribute in Random List Not Accessible in Python
I'm working on my first object oriented bit of python and I have the following: #!/usr/bin/python import random class triangle: # Angle A To Angle C Connects Side F # Angle C to Angle B Connects Side D # Angle B to Angle A Connects Side E def __init__(self, a, b, c, d, e, f): self.a = a self.b ...
[ "When you say [myTri.a, myTri.b, ...] you are not getting a list of the variables themselves, or references to them. Instead you are getting just their values. Since you know they were initialized to 0, it is as if you had written [0, 0, 0, 0, 0, 0]. There's no difference.\nThen later when you try to assign to sam...
[ 5, 2, 0 ]
[]
[]
[ "object", "oop", "python", "random" ]
stackoverflow_0001066827_object_oop_python_random.txt
Q: Export set of data in different formats I want to be able to display set of data differently according to url parameters. My URL looks like /page/{limit}/{offset}/{format}/. For example: /page/20/0/xml/ - subset [0:20) in xml /page/100/20/json/ - subset [20:100) in json Also I want to be able to do the same for ...
Export set of data in different formats
I want to be able to display set of data differently according to url parameters. My URL looks like /page/{limit}/{offset}/{format}/. For example: /page/20/0/xml/ - subset [0:20) in xml /page/100/20/json/ - subset [20:100) in json Also I want to be able to do the same for csv, text, excel, pdf, html, etc... I have to...
[ "I suggest having the renderer also know about the mimetype rather than hardcoding the latter in the code that calls the renderer -- better to concentrate format-specific knowledge in one place, so the calling code would be\ncontent, mimetype = renderer().render(data=dataset)\nreturn HttpResponse(content, mimetype=...
[ 1, 0 ]
[]
[]
[ "django", "python", "rendering" ]
stackoverflow_0001066516_django_python_rendering.txt
Q: Get rid of toplevel tk panewindow while usong tkMessageBox link text When I do : tkMessageBox.askquestion(title="Symbol Display",message="Is the symbol visible on the console") along with Symbol Display window tk window is also coming. If i press "Yes"...the child window return yes,whereas tk window remains ther...
Get rid of toplevel tk panewindow while usong tkMessageBox
link text When I do : tkMessageBox.askquestion(title="Symbol Display",message="Is the symbol visible on the console") along with Symbol Display window tk window is also coming. If i press "Yes"...the child window return yes,whereas tk window remains there. Whenever I am tryng to close tk window, End Program - tk come...
[ "The trick is to invoke withdraw on the Tk root top-level:\n>>> import tkMessageBox, Tkinter\n>>> Tkinter.Tk().withdraw()\n>>> tkMessageBox.askquestion(\n... title=\"Symbol Display\",\n... message=\"Is the symbol visible on the console\")\n\n" ]
[ 5 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0001067900_python_tkinter.txt
Q: Programmatically detect system-proxy settings on Windows XP with Python I develop a critical application used by a multi-national company. Users in offices all around the globe need to be able to install this application. The application is actually a plugin to Excel and we have an automatic installer based on Set...
Programmatically detect system-proxy settings on Windows XP with Python
I develop a critical application used by a multi-national company. Users in offices all around the globe need to be able to install this application. The application is actually a plugin to Excel and we have an automatic installer based on Setuptools' easy_install that ensures that all a project's dependancies are auto...
[ "Here's a sample that should create a bullet green (proxy enable) or red (proxy disable) in your systray\nIt shows how to read and write in windows registry\nit uses gtk\n#!/usr/bin/env python\nimport gobject\nimport gtk\nfrom _winreg import *\n\nclass ProxyNotifier:\n def __init__(self): \n self.t...
[ 4, 3 ]
[]
[]
[ "networking", "proxy", "python", "setuptools", "windows" ]
stackoverflow_0001068212_networking_proxy_python_setuptools_windows.txt
Q: Has anyone tried NetBeans 6.5 Python IDE? Has anyone tried the NetBeans 6.5 Python IDE? What are your opinions? Is it better/worse than PyDev? Do you like it? How does it integrate with source control tools (especially Mercurial)? A: I will share some of the feelings from using it for quite a while now. Things t...
Has anyone tried NetBeans 6.5 Python IDE?
Has anyone tried the NetBeans 6.5 Python IDE? What are your opinions? Is it better/worse than PyDev? Do you like it? How does it integrate with source control tools (especially Mercurial)?
[ "I will share some of the feelings from using it for quite a while now. Things that are roughly the same quality as in Eclipse+Pydev+mercurial:\n\neditor, code-completion\ndebugger features\n\nThings that are better:\n\nautoimport\ncolor schemes (Norway today rocks)\nMercurial support (though it is getting better a...
[ 5, 4, 2, 2, 2, 1, 0, 0 ]
[]
[]
[ "ide", "netbeans", "python" ]
stackoverflow_0000371037_ide_netbeans_python.txt
Q: Multiprocessing in python with more then 2 levels I want to do a program and want make a the spawn like this process -> n process -> n process can the second level spawn process with multiprocessing ? using multiprocessinf module of python 2.6 thnx A: @vilalian's answer is correct, but terse. Of course, it's har...
Multiprocessing in python with more then 2 levels
I want to do a program and want make a the spawn like this process -> n process -> n process can the second level spawn process with multiprocessing ? using multiprocessinf module of python 2.6 thnx
[ "@vilalian's answer is correct, but terse. Of course, it's hard to supply more information when your original question was vague.\nTo expand a little, you'd have your original program spawn its n processes, but they'd be slightly different than the original in that you'd want them (each, if I understand your questi...
[ 3, 1, 1, 0 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0001066710_multiprocessing_python.txt
Q: Making a wxPython application multilingual I have a application written in wxPython which I want to make multilingual. Our options are using gettext http://docs.python.org/library/gettext.html seprating out all UI text to a messages.py file, and using it to translate text I am very much inclined towards 2nd an...
Making a wxPython application multilingual
I have a application written in wxPython which I want to make multilingual. Our options are using gettext http://docs.python.org/library/gettext.html seprating out all UI text to a messages.py file, and using it to translate text I am very much inclined towards 2nd and I see no benefit in going gettext way, using 2n...
[ "There are some advantages of gettext:\n\nOne of the biggest advantages is: when using poedit to do the translations you can benefit from the translation database. Basically poedit ca scan your harddisk and find already translated files and will make suggestions when you translate your file.\nWhen you give the code...
[ 1, 1 ]
[ "For the web (this is PHP but the idea's the same), I always create multiple language files in a specific directory. en.php, fr.php, et cetera. Those files contain definitions of all output text, in the given language. The user preference for language determines which of those files get included, thus, which lan...
[ -1 ]
[ "gettext", "internationalization", "multilingual", "python" ]
stackoverflow_0001043708_gettext_internationalization_multilingual_python.txt
Q: Open-Source Forum with API Does anyone have suggestions for a PHP, Python, or J2EE-based web forum that has a good API for programmatically creating users and forum topics? A: phpBB would be the first that comes to mind as open-source, simply because it's free. In reality almost all forum platforms have some so...
Open-Source Forum with API
Does anyone have suggestions for a PHP, Python, or J2EE-based web forum that has a good API for programmatically creating users and forum topics?
[ "phpBB would be the first that comes to mind as open-source, simply because it's free. \nIn reality almost all forum platforms have some sort of 'api' in that you can do whatever you need programatically, it just may not be as simple as 'add_user(bob)'. A few lines of code and a SQL query or two and you can usually...
[ 4 ]
[]
[]
[ "forum", "php", "python", "web" ]
stackoverflow_0001069246_forum_php_python_web.txt
Q: How should I setup the Wing IDE for use with IronPython Here is a screen where I should point the Wing IDE to my python files. I am using IronPython. Am I assuming correctly that textbox one gets filled with ipy.exe ? (proper path provided) What should be in the rest of the boxes ? A: I do not know about your q...
How should I setup the Wing IDE for use with IronPython
Here is a screen where I should point the Wing IDE to my python files. I am using IronPython. Am I assuming correctly that textbox one gets filled with ipy.exe ? (proper path provided) What should be in the rest of the boxes ?
[ "I do not know about your question in particular; however few weeks ago, Michael Foord published a guide for using WingIde with IronPython.\nYou can find it here: http://www.voidspace.org.uk/ironpython/wing-how-to.shtml\n", "\nWing IDE at the moment doesn't allow the debug mode with IronPython. You need to link t...
[ 2, 0 ]
[]
[]
[ "ironpython", "python", "wing_ide" ]
stackoverflow_0001038695_ironpython_python_wing_ide.txt
Q: how to integrate ZSH and (i)python? I have been in love with zsh for a long time, and more recently I have been discovering the advantages of the ipython interactive interpreter over python itself. Being able to cd, to ls, to run or to ! is indeed very handy. But now it feels weird to have such a clumsy shell when...
how to integrate ZSH and (i)python?
I have been in love with zsh for a long time, and more recently I have been discovering the advantages of the ipython interactive interpreter over python itself. Being able to cd, to ls, to run or to ! is indeed very handy. But now it feels weird to have such a clumsy shell when in ipython, and I wonder how I could int...
[ "I asked this question on the zsh list and this answer worked for me. YMMV.\nIn genutils.py after the line \n\nif not debug:\n\nRemove the line:\n\nstat = os.system(cmd)\n\nReplace it with:\n\nstat =\n subprocess.call(cmd,shell=True,executable='/bin/zsh')\n\nyou see, the problem is that that \"!\" call uses os.sys...
[ 12, 7 ]
[]
[]
[ "ipython", "python", "shell", "zsh" ]
stackoverflow_0000973520_ipython_python_shell_zsh.txt
Q: Python-Hotshot error trying to profile a simple program I was trying to learn how to profile a simple python program using hotshot, but am facing a weird error, import sys import hotshot def main(argv): for i in range(1,1000): print i if __name__ == "__main__": prof = hotshot.Profile("hotshot_edi_stats") ...
Python-Hotshot error trying to profile a simple program
I was trying to learn how to profile a simple python program using hotshot, but am facing a weird error, import sys import hotshot def main(argv): for i in range(1,1000): print i if __name__ == "__main__": prof = hotshot.Profile("hotshot_edi_stats") b,c = prof.runcall(main(sys.argv)) prof.close() and the ...
[ "And I think I've figured out something I missed for over 2 hours.. \nTurns out, runcall() should be called as,\nruncall(main, self.argv)\n\nand this makes things work!\n", "In general, if you have a way to randomly pause or interrupt the program and see the call stack, this method always works.\n" ]
[ 3, 1 ]
[]
[]
[ "profiler", "profiling", "python" ]
stackoverflow_0001061361_profiler_profiling_python.txt
Q: How To: View MFC Doc File in Python I want to use Python to access MFC document files generically? Can CArchive be used to query a file and view the structure, or does Python, in opening the document, need to know more about the document structure in order to view the contents? A: I think that the Python code ne...
How To: View MFC Doc File in Python
I want to use Python to access MFC document files generically? Can CArchive be used to query a file and view the structure, or does Python, in opening the document, need to know more about the document structure in order to view the contents?
[ "I think that the Python code needs to know the document structure. \nMaybe you should make a python wrapper of your c++ code. \nIn this case, I would recommend to use http://sourceforge.net/projects/pycpp/>pycpp which is my opinion a great library for making python extensions in c++.\n" ]
[ 0 ]
[]
[]
[ "file", "mfc", "python", "windows" ]
stackoverflow_0001070932_file_mfc_python_windows.txt
Q: Equivalent for inject() in Python? In Ruby, I'm used to using Enumerable#inject for going through a list or other structure and coming back with some conclusion about it. For example, [1,3,5,7].inject(true) {|allOdd, n| allOdd && n % 2 == 1} to determine if every element in the array is odd. What would be the app...
Equivalent for inject() in Python?
In Ruby, I'm used to using Enumerable#inject for going through a list or other structure and coming back with some conclusion about it. For example, [1,3,5,7].inject(true) {|allOdd, n| allOdd && n % 2 == 1} to determine if every element in the array is odd. What would be the appropriate way to accomplish the same thin...
[ "To determine if every element is odd, I'd use all()\ndef is_odd(x): \n return x%2==1\n\nresult = all(is_odd(x) for x in [1,3,5,7])\n\nIn general, however, Ruby's inject is most like Python's reduce():\nresult = reduce(lambda x,y: x and y%2==1, [1,3,5,7], True)\n\nall() is preferred in this case because it will ...
[ 25, 8, 4 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0001070926_functional_programming_python.txt
Q: Why does list comprehension using a zip object results in an empty list? f = lambda x : 2*x g = lambda x : x ** 2 h = lambda x : x ** x funcTriple = ( f, g, h ) myZip = ( zip ( funcTriple, (1, 3, 5) ) ) k = lambda pair : pair[0](pair[1]) # Why do Output # 1 (2, 9, 3125) and Output # 2 ( [ ] ) differ? print ("\n\...
Why does list comprehension using a zip object results in an empty list?
f = lambda x : 2*x g = lambda x : x ** 2 h = lambda x : x ** x funcTriple = ( f, g, h ) myZip = ( zip ( funcTriple, (1, 3, 5) ) ) k = lambda pair : pair[0](pair[1]) # Why do Output # 1 (2, 9, 3125) and Output # 2 ( [ ] ) differ? print ("\n\nOutput # 1: for pair in myZip: k(pair) ...") for pair in myZip : print (...
[ "Works perfectly in Python 2.6 but fails in Python 3.0 because zip returns a generator-style object and the first loop exhausts it. Make a list instead:\nmyZip = list( zip ( funcTriple, (1, 3, 5) ) )\n\nand it works in Python 3.0\n" ]
[ 18 ]
[]
[]
[ "list_comprehension", "python", "zip" ]
stackoverflow_0001071201_list_comprehension_python_zip.txt
Q: Detect URLs in a string and wrap with "<a href..." tag I am looking to write something that seems like it should be easy enough, but for whatever reason I'm having a tough time getting my head around it. I am looking to write a python function that, when passed a string, will pass that string back with HTML encodi...
Detect URLs in a string and wrap with "<a href..." tag
I am looking to write something that seems like it should be easy enough, but for whatever reason I'm having a tough time getting my head around it. I am looking to write a python function that, when passed a string, will pass that string back with HTML encoding around URLs. unencoded_string = "This is a link - http://...
[ "Googled solutions:\n#---------- find_urls.py----------#\n# Functions to identify and extract URLs and email addresses\n\nimport re\n\ndef fix_urls(text):\n pat_url = re.compile( r'''\n (?x)( # verbose identify URLs within text\n (http|ftp|gopher) # make sure we find a resource type\...
[ 11, 11 ]
[]
[]
[ "html", "python", "regex" ]
stackoverflow_0001071191_html_python_regex.txt
Q: Where can i get free GSM libraries/components for delphi or python? Where can i get good free GSM libraries for Delphi or Python? Libraries i can use to send and receive sms's on my application? Gath A: For free and open source AsyncPro> Not free but the components has active development nrComm Lib Another solut...
Where can i get free GSM libraries/components for delphi or python?
Where can i get good free GSM libraries for Delphi or Python? Libraries i can use to send and receive sms's on my application? Gath
[ "For free and open source AsyncPro>\nNot free but the components has active development nrComm Lib\nAnother solution to use SMS gateway, such as ClickAtell, with solution you can send sms using a simple post command to the gateway url or webservices.\n", "Get it here - completely free (previously commercial compo...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "delphi", "gsm", "python" ]
stackoverflow_0000657100_delphi_gsm_python.txt
Q: Some help understanding async USB operations with libusb-1.0 and ctypes Alright. I figured it out. transfer.flags needed to be a byte instead of an int. Silly me. Now I'm getting an error code from ioctl, errno 16, which I think means the device is busy. What a workaholic. I've asked on the libusb mailing list. Be...
Some help understanding async USB operations with libusb-1.0 and ctypes
Alright. I figured it out. transfer.flags needed to be a byte instead of an int. Silly me. Now I'm getting an error code from ioctl, errno 16, which I think means the device is busy. What a workaholic. I've asked on the libusb mailing list. Below is what I have so far. This isn't really that much code. Most of it is ct...
[ "\nHave you checked to make sure the return values of libusb_alloc_transfer and libusb_open_device_with_vid_pid are valid?\nHave you tried annotating the library functions with the appropriate argtypes?\nYou may run in to trouble with transfer[0].callback = LIBUSB_TRANSFER_CB_FN(callback)—you're not keeping any ref...
[ 2, 0 ]
[ "where is the initial declaration of transfer? I am not familiar with python, but is this ok to assign values to fields in your struct without defining what data type it should be?\n" ]
[ -1 ]
[ "ctypes", "libusb", "python", "usb" ]
stackoverflow_0001052135_ctypes_libusb_python_usb.txt
Q: python class variable not visible in __init__? This code produces an error message, which I found surprising: class Foo(object): custom = 1 def __init__(self, custom=Foo.custom): self._custom = custom x = Foo() Can anyone provide enlightenment? A: It's Foo that isn't visible, because you're in ...
python class variable not visible in __init__?
This code produces an error message, which I found surprising: class Foo(object): custom = 1 def __init__(self, custom=Foo.custom): self._custom = custom x = Foo() Can anyone provide enlightenment?
[ "It's Foo that isn't visible, because you're in the middle of building it. But since you're in the same scope as custom, you can just say custom rather than Foo.custom:\nclass Foo(object):\n custom = 1\n def __init__(self, mycustom=custom):\n self._custom = mycustom\n\nBut note that changing Foo.custo...
[ 16, 7, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001071469_python.txt
Q: how to convert a python dict object to a java equivalent object? I need to convert a python code into an equivalent java code. Python makes life very easy for the developers by providing lots of shortcut functionalities. But now I need to migrate the same to Java. I was wondering what will the equivalent of dict o...
how to convert a python dict object to a java equivalent object?
I need to convert a python code into an equivalent java code. Python makes life very easy for the developers by providing lots of shortcut functionalities. But now I need to migrate the same to Java. I was wondering what will the equivalent of dict objects in java? I have tried using HashMap but life is hell. For start...
[ "It's probably easiest to just create a class for the (Name, Strength) tuple:\nclass NameStrength {\n public String name;\n public String strength;\n}\n\nAdd getters, setters and a constructor if appropriate.\nThen you can use the new class in your map:\nMap<Integer, NameStrength> nodesMap = new HashMap<Integ...
[ 4, 3, 1 ]
[]
[]
[ "dictionary", "hashmap", "java", "python" ]
stackoverflow_0001071793_dictionary_hashmap_java_python.txt
Q: Problem using os.system() with sed command I'm writing a small method to replace some text in a file. The only argument I need is the new text, as it is always the same file and text to be replaced. I'm having a problem using the os.system() call, when I try to use the argument of the method If I use a string like...
Problem using os.system() with sed command
I'm writing a small method to replace some text in a file. The only argument I need is the new text, as it is always the same file and text to be replaced. I'm having a problem using the os.system() call, when I try to use the argument of the method If I use a string like below, everything runs ok: stringId = "GRRRRRRR...
[ "Obligatory: don't use os.system - use the subprocess module:\nimport subprocess\n\ndef updateExportConfigId(m_id, source='path/file.old', \n destination='path/file.new'):\n if isinstance(m_id, unicode):\n m_id = m_id.encode('utf-8')\n cmd= [\n \"sed\",\n \...
[ 5, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001068812_python.txt
Q: Is this a correct way to return JSON in Python/GAE for parsing in JavaScript? I am making an API for some AJAX related things in my web app on GAE in Python. After setting the content-type to 'application/json' and accessing my url directly- http://mysite.com/api?method=theMethod&param=firstParam -I am being prom...
Is this a correct way to return JSON in Python/GAE for parsing in JavaScript?
I am making an API for some AJAX related things in my web app on GAE in Python. After setting the content-type to 'application/json' and accessing my url directly- http://mysite.com/api?method=theMethod&param=firstParam -I am being prompted with a 'save file' dialog box instead of seeing the JSON object displayed. The...
[ "This is the right way, mime type for json is application/json not text/json and NEVER text/html.\nhttps://www.rfc-editor.org/rfc/rfc4627 starts with \"The application/json Media Type for JavaScript Object Notation (JSON)\"\nread this for more details/options\n", "I think the Flickr API returns the json as type '...
[ 4, 1 ]
[]
[]
[ "ajax", "api", "google_app_engine", "json", "python" ]
stackoverflow_0001072281_ajax_api_google_app_engine_json_python.txt