content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: Python: import URLs into list I am trying to make a python script that can download subtitles for How I Met Your Mother from subscene.com. I am new to Python and programming. I would like the search result to be put in a list, which is printed afterwards, so that the user can choose the right URL. The problem is t...
Python: import URLs into list
I am trying to make a python script that can download subtitles for How I Met Your Mother from subscene.com. I am new to Python and programming. I would like the search result to be put in a list, which is printed afterwards, so that the user can choose the right URL. The problem is that I don't know how create a list ...
[ "You can use list comprehension:\ndef SubDL(self, SubUrl):\n\n l = [item for item in urllib.urlopen(SubUrl).readlines()\n if self.SearchCriteria[0] in item and self.SearchCriteria[1] in item]\n for item in l:\n print('An item: {}'.format(item))\n\n", "If you don’t want to use list comprehensi...
[ 0, 0 ]
[]
[]
[ "list", "python", "url" ]
stackoverflow_0008286128_list_python_url.txt
Q: Getting output from and giving commands to a python subprocess I am trying to get output from a subprocess and then give commands to that process based on the preceding output. I need to do this a variable number of times, when the program needs further input. (I also need to be able to hide the subprocess command...
Getting output from and giving commands to a python subprocess
I am trying to get output from a subprocess and then give commands to that process based on the preceding output. I need to do this a variable number of times, when the program needs further input. (I also need to be able to hide the subprocess command prompt if possible). I figured this would be an easy task given th...
[ "This demo uses a dedicated thread to read from stdout. If you search around, I'm sure you can find a more complete implementation written up in an object oriented interface. At least I can say this is working for me with your provided batch file in both Python 2.7.2 and 3.2.2. \nshellcomm.bat:\n@echo off\necho Com...
[ 3 ]
[]
[]
[ "asynchronous", "command_line", "python", "shell", "subprocess" ]
stackoverflow_0008285032_asynchronous_command_line_python_shell_subprocess.txt
Q: Outputting to a file code snippet: def after_equals(s): return s.partition(' = ')[-1] for k,s in zip(keyword, score): print after_equals(k) + ',' + after_equals(s) The output of the code prints: NORTH,88466 GUESS,83965 DRESSES,79379 RALPH,74897 MATERIAL,68168 I need to output the into file. Please advice h...
Outputting to a file
code snippet: def after_equals(s): return s.partition(' = ')[-1] for k,s in zip(keyword, score): print after_equals(k) + ',' + after_equals(s) The output of the code prints: NORTH,88466 GUESS,83965 DRESSES,79379 RALPH,74897 MATERIAL,68168 I need to output the into file. Please advice how to write to a file.
[ "with open(filename, 'w') as out:\n for k,s in zip(keyword, score):\n print >> out, after_equals(k) + ',' + after_equals(s)\n # note: ^^^\n\n", "Open a file in write mode and write a string to the file, then close it:\nf = file('myfile.txt','w')\nf.write(s)\nf.close()\n\nFor your case:\ndef afte...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008286166_python.txt
Q: How can I get the Bazaar version of a file on my website? There have been similar questions to this that I've been involved with before. One example: How can I get the svn revision number in PHP? But today I'm tackling a project that is managed with BZR. I need to get the bazaar version for a particular file and p...
How can I get the Bazaar version of a file on my website?
There have been similar questions to this that I've been involved with before. One example: How can I get the svn revision number in PHP? But today I'm tackling a project that is managed with BZR. I need to get the bazaar version for a particular file and publish that figure on our website in a way that it automaticall...
[ "If you need to get the latest revision in which a file was modified, you can doit using the following command:\nbzr log -l1 --line <file> | cut -f1 -d:\n\n", "In Python:\nfrom bzrlib.branch import Branch\nb = Branch.open(location_of_your_branch)\nb.lock_read()\ntry:\n # Retrieve the contents of the last revis...
[ 3, 2, 0 ]
[]
[]
[ "bazaar", "python", "version_control" ]
stackoverflow_0008283685_bazaar_python_version_control.txt
Q: Dictionary of types In Python, what is the more efficient way of using types as dictionary keys? Given a classObject, should I use classObject.__name__ or the object itself directly? A: Since type names don't have to be unique across modules, you must use the type (classObject) itself. Luckily, types will automa...
Dictionary of types
In Python, what is the more efficient way of using types as dictionary keys? Given a classObject, should I use classObject.__name__ or the object itself directly?
[ "Since type names don't have to be unique across modules, you must use the type (classObject) itself.\nLuckily, types will automatically have a non-trivial hash value:\n>>> class A(object): pass\n>>> class B(object): pass\n>>> hash(A)\n2579460\n>>> hash(B)\n2579600\n\n", "It depends on what you mean by \"more eff...
[ 3, 0 ]
[]
[]
[ "dictionary", "python", "types" ]
stackoverflow_0008286344_dictionary_python_types.txt
Q: How to calculating and testing the number of concurrent connections? Twisted server supports more than 10,000 concurrent connections. I want to write a test case to check it using Python. What I know is just using multiprocessing + threading + greenlet. My question is how to confirm Twisted's support for more than...
How to calculating and testing the number of concurrent connections?
Twisted server supports more than 10,000 concurrent connections. I want to write a test case to check it using Python. What I know is just using multiprocessing + threading + greenlet. My question is how to confirm Twisted's support for more than 10,000 concurrent connections? Something I know is using logger, but is ...
[ "It's easy to support more than 10,000 concurrent connections. What can be harder is supporting so many active connections. The kind of activity you expect to find on your connections is more likely to determine how many you can support at once. What do you expect these connections to be doing? Construct a test...
[ 4, 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0008284086_python_twisted.txt
Q: Streaming multiple tweets - from multiple users? - Twitter API I have a big list of Twitter users stored in a database, almost 1000. I would like to use the Streaming API in order to stream tweets from these users, but I cannot find an appropriate way to do this. Help would be very much appreciated. A: Accordin...
Streaming multiple tweets - from multiple users? - Twitter API
I have a big list of Twitter users stored in a database, almost 1000. I would like to use the Streaming API in order to stream tweets from these users, but I cannot find an appropriate way to do this. Help would be very much appreciated.
[ "According to the Twitter API documentation, you can only use the streaming API to follow up to 400 users. For more than that, you'll have to request an increased access level for the account you use to access the API. \n", "You can track 400 filter words and 5000 userids via streaming api. \nFilter words can be ...
[ 5, 2 ]
[]
[]
[ "php", "python", "twitter" ]
stackoverflow_0002123651_php_python_twitter.txt
Q: Python pattern matching with regex, findall and groups I had a script that scanned in piece of text and returned me a group which I would save to an array. The code looks like this: pattern = re.compile(r'<span id="first_name">(.+?)</span>') matches = pattern.findall(str(my_text_file)) This works awesome and I c...
Python pattern matching with regex, findall and groups
I had a script that scanned in piece of text and returned me a group which I would save to an array. The code looks like this: pattern = re.compile(r'<span id="first_name">(.+?)</span>') matches = pattern.findall(str(my_text_file)) This works awesome and I could scan first names in my text file and write them into an ...
[ "for match in matches:\n first_names.append(match[0])\n last_names.append(match[1])\n\n" ]
[ 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008286612_python_regex.txt
Q: Implementation of string functions in Python? Is there any documentation on how Python's string functions are implemented in Python? I understand that str is a built-in module, and so its functions are implemented in C. But isn't there code for it anyways? How about in Pypy? From what I've read so far, they've r...
Implementation of string functions in Python?
Is there any documentation on how Python's string functions are implemented in Python? I understand that str is a built-in module, and so its functions are implemented in C. But isn't there code for it anyways? How about in Pypy? From what I've read so far, they've re-implemented a lot of built-in modules in Python i...
[ "This doesn't really answer the question posed, it's just a bit too long to be a comment.\nSome quick digging through the source shows that PyPy has two implementations of split(), this high-level, readable version and this lower-level version, which appears to be the implementation of split() in rpython itself. \n...
[ 5 ]
[]
[]
[ "implementation", "pypy", "python", "string" ]
stackoverflow_0008286295_implementation_pypy_python_string.txt
Q: Why does my newly installed Django project only display the welcome page? Right up front: I'm pretty new to python and django, but I've done the tutorial and some other basic stuff on a local install. I recently started a django project on a live server (hostgator.com, with fastcgi) to the point where it shows tha...
Why does my newly installed Django project only display the welcome page?
Right up front: I'm pretty new to python and django, but I've done the tutorial and some other basic stuff on a local install. I recently started a django project on a live server (hostgator.com, with fastcgi) to the point where it shows that "It worked! Congratulations on your first Django-powered page." message. Next...
[ "Are you sure you have restarted the server properly? Try putting some text in urls.py to provoke a syntax error to make sure the restart did in fact work.\n" ]
[ 0 ]
[]
[]
[ "django", "python", "subdomain" ]
stackoverflow_0008235601_django_python_subdomain.txt
Q: Adding few values into a single value in a dictionary I have a dictionary with strings as keys, and lists of strings as values. How do I append an additional string to a given key? For example, given: dic = {"i'm": ['the']} I would like to append the string 'boss' to the list of strings stored under "i'm", i.e.: ...
Adding few values into a single value in a dictionary
I have a dictionary with strings as keys, and lists of strings as values. How do I append an additional string to a given key? For example, given: dic = {"i'm": ['the']} I would like to append the string 'boss' to the list of strings stored under "i'm", i.e.: dic = {"i'm": ['the','boss']}
[ "Assuming that the key is in the dictionary, it's the easy solution shown several times already: \ndic[\"i'm\"].append(\"boss\")\n\nIf the key might not be in the dictionary, either check first with if key in dic, use dic.setdefault, or make use of a defaultdict. The defaultdict exists pretty much for the case you'...
[ 4, 2, 1, 1, 0 ]
[]
[]
[ "key", "list", "python", "string" ]
stackoverflow_0008286692_key_list_python_string.txt
Q: Rewriting python arrays manipulation function in haskell So I wanted to try to rewrite my pivot routine in haskell, but I got stuck right away... Here is my original python routine (i've commented it heavily to compensate for the lack of types): def pivot(entering, leaving, B, A, Z): """ @param entering i...
Rewriting python arrays manipulation function in haskell
So I wanted to try to rewrite my pivot routine in haskell, but I got stuck right away... Here is my original python routine (i've commented it heavily to compensate for the lack of types): def pivot(entering, leaving, B, A, Z): """ @param entering integer indicating the entering col # @param leaving intege...
[ "I'm not going to take the time right now to translate your code into Haskell, but I am going to critique the code you have and offer a few tips.\nFirst of all, the type [Foo] means \"list of Foo\". And by \"list\" I mean immutable, singly-linked list. The Matrix type makes perfect sense: a Matrix is a list of \"ro...
[ 2 ]
[]
[]
[ "haskell", "python" ]
stackoverflow_0008284568_haskell_python.txt
Q: "name 'self' is not defined" error message in Python for GAE I have built a web app in Python for Google App Engine. It is mature piece of code that I have run many times without any problems. However, when I was making some changes this morning, mysterious white space errors started popping up all over the plac...
"name 'self' is not defined" error message in Python for GAE
I have built a web app in Python for Google App Engine. It is mature piece of code that I have run many times without any problems. However, when I was making some changes this morning, mysterious white space errors started popping up all over the place. I figured out what was going on and removed a few of them by h...
[ "logging.info(self.current_user) is outside of any scope that defines self (and would run when the class is being created, which is probably not what you want). You need to call it inside a method, e.g.\ndef get(self):\n path = ...\n logging.info(self.current_user)\n\n" ]
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008287149_google_app_engine_python.txt
Q: Python: Generate random number between x and y which is a multiple of 5 I've read the manual for pseudo-randomness in Python, and to my knowledge, you can only generate numbers up to a given maximum value, i.e. 0-1, 0-30, 0-1000, etc. I want to: a) Generate a number between two ints, i.e. 5-55, and b) Only inclu...
Python: Generate random number between x and y which is a multiple of 5
I've read the manual for pseudo-randomness in Python, and to my knowledge, you can only generate numbers up to a given maximum value, i.e. 0-1, 0-30, 0-1000, etc. I want to: a) Generate a number between two ints, i.e. 5-55, and b) Only include multiples of 5 (or those ending in 5 or 0, if that's easier) I've looked ...
[ "Create an integer random between e.g. 1-11 and multiply it by 5. Simple math.\nimport random\nfor x in range(20):\n print random.randint(1,11)*5,\nprint\n\nproduces e.g.\n5 40 50 55 5 15 40 45 15 20 25 40 15 50 25 40 20 15 50 10\n\n", ">>> import random\n>>> random.randrange(5,60,5)\n\nshould work in any Python...
[ 123, 66, 13, 6 ]
[]
[]
[ "python", "random" ]
stackoverflow_0008287167_python_random.txt
Q: Django manage.py localization It is comfortable for somebody to read messages on native language. Is it a good idea to add localization for output of manage.py in Django? A: It depends on who are you working with. Personally I prefer having output of developer's stuff in english, even though it is not my native ...
Django manage.py localization
It is comfortable for somebody to read messages on native language. Is it a good idea to add localization for output of manage.py in Django?
[ "It depends on who are you working with. Personally I prefer having output of developer's stuff in english, even though it is not my native language. I think that anyone who is a professional developer has some grasp of english, and the fact is that it is much easier to find potential errors posted in english than ...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008287017_django_python.txt
Q: IPython won't start I'm running Windows 7 x64. I installed the 32x verson of Python 2.7.2 and IPython 0.11 using the Windows Installers. They installed all right. I added C:\Python27 and C:\Python27\Scripts to the system envorment variables. When I type ipython in the command prompt I get this message: Traceback ...
IPython won't start
I'm running Windows 7 x64. I installed the 32x verson of Python 2.7.2 and IPython 0.11 using the Windows Installers. They installed all right. I added C:\Python27 and C:\Python27\Scripts to the system envorment variables. When I type ipython in the command prompt I get this message: Traceback (most recent call last): ...
[ "Solution. Also need to install setuptools from http://pypi.python.org/pypi/setuptools\n" ]
[ 18 ]
[]
[]
[ "ipython", "python" ]
stackoverflow_0008287422_ipython_python.txt
Q: QWidget showFullScreen produces multiple resizeEvents I have a QT application written in python using PySide and I stumbled across a little problem regarding the showFullScreen method of the QGLWidget (although the problem occurs with every other widget too): The problem is, that the widget doesn't have its 'final...
QWidget showFullScreen produces multiple resizeEvents
I have a QT application written in python using PySide and I stumbled across a little problem regarding the showFullScreen method of the QGLWidget (although the problem occurs with every other widget too): The problem is, that the widget doesn't have its 'final' resolution after the program returns from showFullScreen....
[ "One possibility is to check that if the resize event is spontaneous or not. From limited testing here (using Qt C++ on Linux), the second resize event is spontaneous, while the first one is not.\nYou could do your calculations only when the event is spontaneous.\nNote: I'm not sure how portable this is, it might d...
[ 0 ]
[]
[]
[ "fullscreen", "pyside", "python", "qglwidget", "qt" ]
stackoverflow_0008287118_fullscreen_pyside_python_qglwidget_qt.txt
Q: Library to parse Python 2 and 3 I'm looking for a library that allows parsing and modification of Python 3 source code. There is the built-in ast module, but that doesn't allow parsing Python 3 code from Python 2 and vice versa. Is there such a library, or a way to make the ast module recognize Python 2 code on Py...
Library to parse Python 2 and 3
I'm looking for a library that allows parsing and modification of Python 3 source code. There is the built-in ast module, but that doesn't allow parsing Python 3 code from Python 2 and vice versa. Is there such a library, or a way to make the ast module recognize Python 2 code on Python 3?
[ "Python's lib2to3 library includes a code parser can can parse both Python 2 and Python 3 code. It's not well documented though. This chapter from the porting book provides an introduction. If you want to modify code (refactoring, maybe) then 2to3 could very well be exactly what you are looking for.\n" ]
[ 3 ]
[]
[]
[ "parsing", "python", "python_2to3", "python_3.x" ]
stackoverflow_0008286337_parsing_python_python_2to3_python_3.x.txt
Q: Python Threading With Concurrency I wrote the following code while trying to learn threading in python. import threading import time def printWorker(x,y): t = time.time() while time.time() - t < 10: print "Name:%s Time:%s" %(y,str(time.time() - t)) time.sleep(x...
Python Threading With Concurrency
I wrote the following code while trying to learn threading in python. import threading import time def printWorker(x,y): t = time.time() while time.time() - t < 10: print "Name:%s Time:%s" %(y,str(time.time() - t)) time.sleep(x) t1 = threading.Thread(target = p...
[ "To pass arguments you need to do this:\nt1 = threading.Thread(target=printWorker, args=(2, 'Thread-1'))\nt2 = threading.Thread(target=printWorker, args=(3, 'Thread-2'))\n\nYour code is invoking printWorker on the main thread and starting two threads with target=None (the return value of printWorker).\n" ]
[ 4 ]
[]
[]
[ "asynchronous", "multithreading", "python", "python_multithreading", "worker" ]
stackoverflow_0008287670_asynchronous_multithreading_python_python_multithreading_worker.txt
Q: numpy.ma.cov - pairwise correlations for with missing values? Example dataset (rows were randomly extracted from a much larger matrix) import numpy as np test = [[np.nan, np.nan, 0.217, 0.562], [np.nan, np.nan, 0.217, 0.562], [0.269, 0.0, 0.217, 0.562], [np.nan, np.nan, 0.217, -0.953], ...
numpy.ma.cov - pairwise correlations for with missing values?
Example dataset (rows were randomly extracted from a much larger matrix) import numpy as np test = [[np.nan, np.nan, 0.217, 0.562], [np.nan, np.nan, 0.217, 0.562], [0.269, 0.0, 0.217, 0.562], [np.nan, np.nan, 0.217, -0.953], [np.nan, np.nan, 0.217, -0.788], [0.75, 0.0, 0.217, 0....
[ "Your maskedarr does not have any values masked.\n>>> maskedarr.mask\nFalse\n\nYou need to include the mask argument when initializing the array.\n>>> maskedarr = np.ma.array(test, mask=np.isnan(test))\n\nNow maskedarr.mask is as follows.\n>>> maskedarr.mask\narray([[ True, True, False, False],\n [ True, Tr...
[ 6 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0008287573_numpy_python.txt
Q: Replace String by python i have list http://lincoln.com/picture/2453345/flower.jpg http://lincoln.com/picture/2354345/flower1.jpg replace into: http://lincoln.com/picture/4453345/flower.jpg http://lincoln.com/picture/4354345/flower1.jpg i tried: f=open('fileinput','r') f.replace('2453345/flower.jpg','4453345/f...
Replace String by python
i have list http://lincoln.com/picture/2453345/flower.jpg http://lincoln.com/picture/2354345/flower1.jpg replace into: http://lincoln.com/picture/4453345/flower.jpg http://lincoln.com/picture/4354345/flower1.jpg i tried: f=open('fileinput','r') f.replace('2453345/flower.jpg','4453345/flower.jpg') but i have more l...
[ "Replacing part of the string using regular expressions\nSee the following solution:\nimport re\nregexp_test = re.compile('\\/\\d')\nresult = regexp_test.sub(lambda x: '/'+str(int(x.group()[1])+2), file_content)\n\nIt will increment each digit after slash (\"/\") by 2, so \"/2\" will be replaced with \"/4\" and so ...
[ 2, 1 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0008287357_python_replace.txt
Q: issue in installing SPARQLWrapper in python I installed SPARQLWrapper in python in the installation it shows: Installed c:\python27\lib\site-packages\sparqlwrapper-1.4.2-py2.7.egg egg file are available in sit-packages. When I tried to import SPARQLWrapper , the program cannot it. I am new to python and have no c...
issue in installing SPARQLWrapper in python
I installed SPARQLWrapper in python in the installation it shows: Installed c:\python27\lib\site-packages\sparqlwrapper-1.4.2-py2.7.egg egg file are available in sit-packages. When I tried to import SPARQLWrapper , the program cannot it. I am new to python and have no clue what are these egg files and how to handle it...
[ "An egg folder or zip file needs to exist in your PYTHONPATH. Normally, eggs in site-packages should be automatically installed in the path.\nExecute your python interpreter, eg:\npython2.7\n>>> import sys\n>>> print sys.path\n\nIf you don't see c:\\python27\\lib\\site-packages\\sparqlwrapper-1.4.2-py2.7.egg in sy...
[ 2 ]
[]
[]
[ "python", "rdf", "sparql" ]
stackoverflow_0008287394_python_rdf_sparql.txt
Q: Google App Engine: Redirect to RequestHandler I just started with Google App Engine using python and I was following a tutorial and writing my own little app to get familiar the webapp framework. Now I just noticed the tutorial does the following self.redirect('/'). So that got me wondering: is there a way to redi...
Google App Engine: Redirect to RequestHandler
I just started with Google App Engine using python and I was following a tutorial and writing my own little app to get familiar the webapp framework. Now I just noticed the tutorial does the following self.redirect('/'). So that got me wondering: is there a way to redirect to a handler instead of a hardcoded path? Thou...
[ "One alternative would be to have a map of symbolic names to URLs, that way you could redirect to the mapped URL - you could then update your URLs with impunity.\nOr if you'd rather just execute the code from another handler, I don't know why you couldn't just make a method call - worst case, you could extract a co...
[ 3, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003267830_google_app_engine_python.txt
Q: Python: Combining string and lists I have a list of counters counters = ['76195087', '963301809', '830123644', '60989448', '0', '0', '76195087', '4006066839', '390361581', '101817210', '0', '0'] and I would like to create a string using some of these counters.... cmd = 'my_command' + counters[0:1] But I find th...
Python: Combining string and lists
I have a list of counters counters = ['76195087', '963301809', '830123644', '60989448', '0', '0', '76195087', '4006066839', '390361581', '101817210', '0', '0'] and I would like to create a string using some of these counters.... cmd = 'my_command' + counters[0:1] But I find that I am unable to concatenate strings an...
[ "If you just want a single element of the list, just index that element:\ncmd = 'my_command ' + counters[0]\n\nIf you want to join several elements, use the 'join()' method of strings:\ncmd = 'my_command ' + \" \".join(counters[0:2]) # add spaces between elements\n\n", "You can join strings in a list with, well, ...
[ 4, 4, 3, 1 ]
[]
[]
[ "concatenation", "list", "python", "string" ]
stackoverflow_0008288084_concatenation_list_python_string.txt
Q: Django Tutorial Part 1 'Poll' object has no attribute 'was_published_today' I'm doing this Django tutorial https://docs.djangoproject.com/en/dev/intro/tutorial01/ and was_published_today isn't working. Thanks for your time. Here's the command line: Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 3...
Django Tutorial Part 1 'Poll' object has no attribute 'was_published_today'
I'm doing this Django tutorial https://docs.djangoproject.com/en/dev/intro/tutorial01/ and was_published_today isn't working. Thanks for your time. Here's the command line: Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" ...
[ "I had a similar problem as I was working through the Django tutorial. I found that, in order to pick up custom methods, I had to exit from the Python shell and restart it (and re-import the Poll class).\n" ]
[ 3 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0006641212_django_django_models_python.txt
Q: Unexpected behaviour with Urllib in Python My system is not behind any proxy. params = urllib.urlencode({'search':"August Rush"}) f = urllib.urlopen("http://www.thepiratebay.org/search/query", params) This goes onto an infinite loop(Or just hangs). I can obviously get rid of this and use FancyUrlOpener and creat...
Unexpected behaviour with Urllib in Python
My system is not behind any proxy. params = urllib.urlencode({'search':"August Rush"}) f = urllib.urlopen("http://www.thepiratebay.org/search/query", params) This goes onto an infinite loop(Or just hangs). I can obviously get rid of this and use FancyUrlOpener and create the query myself rather than passing it parame...
[ "The posted code works fine for me, with Python 2.7.2 on Windows.\nHave you tried using a http-debugging tool, like Fiddler2 to see the actual conversation going between your program and the site?\nIf you run Fiddler2 on port 8888 on localhost, you can do this to see the request and response:\nimport urllib\nproxie...
[ 1, 1 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0008288057_python_urllib.txt
Q: Weird behavior of simple tables in Python I am a beginner in Python. The dynamic programming solution to the coin change problem requires an initialized table that basically could, for example, look like this: [ [1,0,0,0], [1,0,0,0], [1,0,0,0] ] Which table I specified this way: table=[[1]+[0]*3]*3 Now, if I wri...
Weird behavior of simple tables in Python
I am a beginner in Python. The dynamic programming solution to the coin change problem requires an initialized table that basically could, for example, look like this: [ [1,0,0,0], [1,0,0,0], [1,0,0,0] ] Which table I specified this way: table=[[1]+[0]*3]*3 Now, if I write table[1][2]=1 for x in table: print x I ge...
[ "The error is in the code you didn't show. Presumably, you initialised your list like\na = [1, 0, 0, 0]\ntable = [a, a, a]\n\nor\ntable = [[1, 0, 0, 0]] * 3\n\nor something equivalent, which leads to a list containing three times the same list object. If you modify this single object, it changes everywhere it is ...
[ 2, 0 ]
[]
[]
[ "matrix", "python" ]
stackoverflow_0008288323_matrix_python.txt
Q: HDF5 for Python: high level vs low level interfaces. h5py I've been working with HDF5 files with C and Matlab, both using the same way for reading from and writing to datasets: open file with h5f open dataset with h5d select space with h5s and so on... But now I'm working with Python, and with its h5py library I...
HDF5 for Python: high level vs low level interfaces. h5py
I've been working with HDF5 files with C and Matlab, both using the same way for reading from and writing to datasets: open file with h5f open dataset with h5d select space with h5s and so on... But now I'm working with Python, and with its h5py library I see that it has two ways to manage HDF5: high-level and low-le...
[ "High-level interfaces are generally going with a performance loss of some sort. After that, whether it is noticeable (worth being investigated) will depend on what you are doing exactly with your code.\nJust start with the high-level interface. If the code is overall too slow, start profiling and move the bottlene...
[ 2 ]
[]
[]
[ "h5py", "hdf5", "performance", "python" ]
stackoverflow_0008096668_h5py_hdf5_performance_python.txt
Q: Python `print` passing extra text to sys.stdout? This is probably something stupid I am missing but it has really got me hung up on a larger project (c extension) that I am writing. Why is print "Hello, World!" passing None and an extra \n to sys.stdout here? >>> import sys >>> class StdOutHook: ... def write(...
Python `print` passing extra text to sys.stdout?
This is probably something stupid I am missing but it has really got me hung up on a larger project (c extension) that I am writing. Why is print "Hello, World!" passing None and an extra \n to sys.stdout here? >>> import sys >>> class StdOutHook: ... def write(self, text): ... sys.__stdout__.write("stdout ...
[ "print x() prints the return value of x() which is implicitly None\nEither replace print \"Hello world\" with return \"Hello world\" or replace print x() with x()\n", "Two things:\nFirst, print automatically adds a new line unless you specify otherwise. If you don't want a new line add a comma:\nprint \"Hello, Wo...
[ 8, 3, 1 ]
[]
[]
[ "python", "stderr", "stdout", "sys" ]
stackoverflow_0008288717_python_stderr_stdout_sys.txt
Q: How to append a "timer" inline with a print statement? I didn't actually able to come up with the best suitable title for this. But the problem is: I have this little function, which prints a count up timer on the screen: def timer(x): for i in range(1,x): sys.stdout.write("\r%d" % i) sys.stdout.flush() ...
How to append a "timer" inline with a print statement?
I didn't actually able to come up with the best suitable title for this. But the problem is: I have this little function, which prints a count up timer on the screen: def timer(x): for i in range(1,x): sys.stdout.write("\r%d" % i) sys.stdout.flush() sleep(1) sys.stdout.write('\r \r') How can I appen...
[ "Why not pass your message to the timer function?\ndef timer(message, x):\n for i in range(1,x):\n sys.stdout.write(\"\\r%s%d\" % (message, i))\n sys.stdout.flush()\n sleep(1)\n sys.stdout.write('\\r \\r')\n...\n\n\ntimer('Now counting..... ', 6)\n\n", "You need to remove the \\r as that moves the c...
[ 5, 4 ]
[]
[]
[ "python" ]
stackoverflow_0008289023_python.txt
Q: Python: Get download link from javascript button I am trying to get my script to download subtitles from www.subscene.com. The problem is that the download button on webpage is made in java, and for some reason i cannot download subtitles even if i extract the URL. I think this is the code for the download button:...
Python: Get download link from javascript button
I am trying to get my script to download subtitles from www.subscene.com. The problem is that the download button on webpage is made in java, and for some reason i cannot download subtitles even if i extract the URL. I think this is the code for the download button: <a id="s_lc_bcr_downloadLink" class="downloadLink rat...
[ "As John said this is not the file but javascript code. So instead of getting that file using urllib.urlretrieve, you can execute the javascript which downloads the files in turn. This can be done using selenium module -\nfrom selenium import webdriver\nbrowser = webdriver.Firefox()\nbrowser.get('http://subscene.co...
[ 4 ]
[]
[]
[ "download", "javascript", "python", "url" ]
stackoverflow_0008288202_download_javascript_python_url.txt
Q: How would you mock a web app in Python (for testing a Django project) My app in Django scraps and imports data from another application's HTML. I tested each parsing function and would like to test the crawler that will go through the other application, too. After this, I'd like to make some integration tests. Fo...
How would you mock a web app in Python (for testing a Django project)
My app in Django scraps and imports data from another application's HTML. I tested each parsing function and would like to test the crawler that will go through the other application, too. After this, I'd like to make some integration tests. For making the tests as easy to run as possible, I want to mock the imported ...
[ "I think you're mocking at the wrong level. Your unit test shouldn't have to depend on an external webserver at all, even if you're running it specifically for the test. You should be replacing the urllib2.Request object (or whatever you're using that does the actual HTTP call) with one that just returns pre-canned...
[ 2, 1, 0, 0 ]
[]
[]
[ "basehttpserver", "django", "mocking", "python", "testing" ]
stackoverflow_0008273452_basehttpserver_django_mocking_python_testing.txt
Q: python re.compile Beautiful soup desc = re.compile('<ul class="descShort bullet">(.*)</ul>', re.DOTALL) findDesc = re.findall(desc, link_source) for i in findDesc: print i ''' <ul class="descShort bullet"> Sleek and distinctive, these eye-catching ornaments will be the star of your holiday decor. Thes...
python re.compile Beautiful soup
desc = re.compile('<ul class="descShort bullet">(.*)</ul>', re.DOTALL) findDesc = re.findall(desc, link_source) for i in findDesc: print i ''' <ul class="descShort bullet"> Sleek and distinctive, these eye-catching ornaments will be the star of your holiday decor. These unique glass icicle ornaments are i...
[ "First of all, parsing HTML/XML with regexes is generally considered a bad idea.\nSo, using some parser like BeautifulSoup is a better idea indeed.\nWhat you want can be done as follows:\nfrom BeautifulSoup import BeautifulSoup\n\ntext = \"\"\"\n<ul class=\"descShort bullet\">text1</ul>\n<a href=\"example.com\">tes...
[ 1 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0008288848_beautifulsoup_python_regex.txt
Q: libedit/readline conflict with ipython 3.2.2 on OS X 10.7 Lion I've been trying to set up ipython 3 (running 2.7 works fine) on a mac running Lion, but can't seem to get rid of the following error: 192:~ mlauria$ /Library/Frameworks/Python.framework/Versions/3.2/bin/ipython3 /Library/Frameworks/Python.framework/Ve...
libedit/readline conflict with ipython 3.2.2 on OS X 10.7 Lion
I've been trying to set up ipython 3 (running 2.7 works fine) on a mac running Lion, but can't seem to get rid of the following error: 192:~ mlauria$ /Library/Frameworks/Python.framework/Versions/3.2/bin/ipython3 /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages\ /IPython/utils/rlineimpl.py:...
[ "This is unfortunate as more and more Python distributions on OS X are being built with the Apple-supplied libedit in OS X rather than the GPL-licensed GNU readline library which Apple does not ship. For instance, current 64-bit/32-bit python.org installers for OS X use libedit while the 32-bit-only installers cur...
[ 6, 0 ]
[]
[]
[ "easy_install", "ipython", "python", "python_3.x", "readline" ]
stackoverflow_0008288789_easy_install_ipython_python_python_3.x_readline.txt
Q: Efficient strings containing each other I have two sets of strings (A and B), and I want to know all pairs of strings a in A and b in B where a is a substring of b. The first step of coding this was the following: for a in A: for b in B: if a in b: print (a,b) However, I wanted to know-- i...
Efficient strings containing each other
I have two sets of strings (A and B), and I want to know all pairs of strings a in A and b in B where a is a substring of b. The first step of coding this was the following: for a in A: for b in B: if a in b: print (a,b) However, I wanted to know-- is there a more efficient way to do this with ...
[ "Of course you can easily write this as a list comprehension:\n[(a, b) for a in A for b in B if a in b]\n\nThis might slightly speed up the loop, but don't expect too much. I doubt using regular expressions will help in any way with this one.\nEdit: Here are some timings:\nimport itertools\nimport timeit\nimport r...
[ 10, 7, 6, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0008288960_python_regex_string.txt
Q: Need help porting C function to Python I'm trying to port a C function which calculates a GPS checksum over to Python. According to the receiving end I am sometimes miscalculating the checksum, so must still have a bug in there. C code is void ComputeAsciiChecksum(unsigned char *data, unsigned int len, ...
Need help porting C function to Python
I'm trying to port a C function which calculates a GPS checksum over to Python. According to the receiving end I am sometimes miscalculating the checksum, so must still have a bug in there. C code is void ComputeAsciiChecksum(unsigned char *data, unsigned int len, unsigned char *p1, unsigned ...
[ "\nHere is how you can set up a testing environment to diagnose your problem.\n\nCopy the above C function to a file, remove the assert() line, and compile it to a shared library with\ngcc -shared -o checksum.so checksum.c\n\n(If you are on Windows or whatever, do the equivalent of the above.)\nCopy this code to a ...
[ 4, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0008288387_c_python.txt
Q: Python on Linux: get host name in /etc/hostname From within a Python script I am trying to get the host name in a Linux box. It is a Debian GNU/Linux Amazon EC2 instance. I have set the correct name in /etc/hostname. The recommended solution socket.gethostname() is not working: it shows the ip- plus the IP tuple. ...
Python on Linux: get host name in /etc/hostname
From within a Python script I am trying to get the host name in a Linux box. It is a Debian GNU/Linux Amazon EC2 instance. I have set the correct name in /etc/hostname. The recommended solution socket.gethostname() is not working: it shows the ip- plus the IP tuple. I have searched on StackOverflow and nothing is comin...
[ "Try os.uname(). According to the doc, it is the second position in the tuple returned.\nBut, as the doc itself states, the \"better way to get the hostname is socket.gethostname() or even socket.gethostbyaddr(socket.gethostname()).\"\n", "The generic source for the hostname is hostname(1). This program calls th...
[ 13, 7, 7, 5 ]
[]
[]
[ "ip", "linux", "python" ]
stackoverflow_0008263192_ip_linux_python.txt
Q: wxpython cut copy and paste throughout the application I'm developing a small application with multiple TextCtrl and ComboBox widgets. I want that when I press the key Ctrl-C Ctrl-V and Ctrl-X I get the usual behaviour of copying, pasting and cutting in the appropriate entry. What I obtain right now is that, while...
wxpython cut copy and paste throughout the application
I'm developing a small application with multiple TextCtrl and ComboBox widgets. I want that when I press the key Ctrl-C Ctrl-V and Ctrl-X I get the usual behaviour of copying, pasting and cutting in the appropriate entry. What I obtain right now is that, while I can right-click and have the text copd/past/cutd, I can't...
[ "Menu keybindings work by default with Alt-first_menu_letter -> submenu_first_letter.\nThe menu event of the selected item should bind the corresponding event handler:\nself.Bind(wx.EVT_MENU, self.on_copy, self.copy)\n\nfor a copy method, you first select the text you want to copy with the mouse. Then you can get t...
[ 2 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0008288120_python_user_interface_wxpython.txt
Q: is the python dict str() function reliably sorting keys? in python, both the dict {1:1,2:2,3:3} and {3:3,2:2,1:1} produces "{1:1,2:2,3:3}" when str()'d? Can I rely on this sorting, or at least on the fact that dicts containing the same key/valuepairs will generate the same string when put through the str() functio...
is the python dict str() function reliably sorting keys?
in python, both the dict {1:1,2:2,3:3} and {3:3,2:2,1:1} produces "{1:1,2:2,3:3}" when str()'d? Can I rely on this sorting, or at least on the fact that dicts containing the same key/valuepairs will generate the same string when put through the str() function?
[ "You can rely on neither of these two properties. The order of a dictionary when converted to a string depends also on the insertion order of the key/value pairs.\nWith a bit of knowledge of the Python source code (watch The Mighty Dictionary from PyCon 2010), or a bit of trial and error, you can easily find count...
[ 7, 4, 2, 2 ]
[]
[]
[ "dictionary", "python", "string" ]
stackoverflow_0008289418_dictionary_python_string.txt
Q: Parse response in python When i sending some data on host: r = urllib2.Request(url, data = data, headers = headers) page = urllib2.urlopen(r) soup = BeautifulSoup(page.read(), fromEncoding="cp-1251") print page.read() i have something like this: [{"command":"settings","settings":{"basePath":"\/","ajaxPageState":...
Parse response in python
When i sending some data on host: r = urllib2.Request(url, data = data, headers = headers) page = urllib2.urlopen(r) soup = BeautifulSoup(page.read(), fromEncoding="cp-1251") print page.read() i have something like this: [{"command":"settings","settings":{"basePath":"\/","ajaxPageState":{"theme":"spsr","theme_token":...
[ "The answer you are getting is very likely encoded in JSON. If this is true then using BeautifulSoup doesn't make any sense (it is a HTML/XML parser). If you have JSON data you will need to use a JSON parser. Calling page.read() twice doesn't make any sense either since it won't return you anything sane after the f...
[ 3 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0008289438_beautifulsoup_python.txt
Q: Type casting with non standard types in python How for example would I convert a type from some external class to another one? I've searched around, and gotten stuff like "int to string" and stuff, but I'm talking about something like class "tile" converting to something else, such as "tile2". A: There's no suc...
Type casting with non standard types in python
How for example would I convert a type from some external class to another one? I've searched around, and gotten stuff like "int to string" and stuff, but I'm talking about something like class "tile" converting to something else, such as "tile2".
[ "There's no such thing as casting in Python. That's because there's no need for it: generally, any function that accepts a 'tile' object shouldn't care that it actually is a tile rather than a tile2, as long as it has the data and/or methods that it is expecting. This is called duck typing, and is a fundamental par...
[ 3, 1 ]
[]
[]
[ "casting", "python", "types" ]
stackoverflow_0008289540_casting_python_types.txt
Q: List of dictConfig configuration options for Python logging handlers? Where can I find a list of configuration options for Python's logging handlers? For example, the docs say that the TimedRotatingFileHandler takes a "when" argument. How can this be defined using dictConfig? Like this?: 'handlers': { 'file': ...
List of dictConfig configuration options for Python logging handlers?
Where can I find a list of configuration options for Python's logging handlers? For example, the docs say that the TimedRotatingFileHandler takes a "when" argument. How can this be defined using dictConfig? Like this?: 'handlers': { 'file': { 'level': 'DEBUG', 'formatter':'default', 'class':...
[ "The idea is for the key names in the configuration dict to be the same as the named args in the corresponding call to construct the handler (or formatter, or filter). This will then work with externally defined handlers, too. Given a dict config which holds the configuration of an object (like a handler), the conf...
[ 4 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0008288002_logging_python.txt
Q: Http header name gets modified I'm using httplib and django. When I do the following: conn.request("PUT", "/udj/users/3/library/songs", headers={"X-Udj-Ticket-Hash" : hash, "content-type" : "text/json"}, body='{"blah": 2}') My server then reports that no header by the name of X-Udj-Ticket-Hash was sent. Instea...
Http header name gets modified
I'm using httplib and django. When I do the following: conn.request("PUT", "/udj/users/3/library/songs", headers={"X-Udj-Ticket-Hash" : hash, "content-type" : "text/json"}, body='{"blah": 2}') My server then reports that no header by the name of X-Udj-Ticket-Hash was sent. Instead, it shows that a header by the nam...
[ "Figured it out, the issue is with django. From the documentation here:\n\nWith the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to...
[ 0 ]
[]
[]
[ "django", "http", "http_headers", "python" ]
stackoverflow_0008289413_django_http_http_headers_python.txt
Q: Python templates This is my views.py: from django.http import HttpResponse from django.template.loader import get_template from django.template import Context def login(request): t = get_template('login.html') return HttpResponse(t.render) In my urls.py I put (r'^login/', include('project.views.login'))...
Python templates
This is my views.py: from django.http import HttpResponse from django.template.loader import get_template from django.template import Context def login(request): t = get_template('login.html') return HttpResponse(t.render) In my urls.py I put (r'^login/', include('project.views.login')), to show my template...
[ "include is used to include other url configs from other apps. It shouldn't be used if you're trying to add a url pattern for one particular view. You should have something like \n(r'^login/', 'project.views.login'),\n\nThe other problem is where you return your response. render is a method that takes a context (se...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008289672_django_python.txt
Q: What are some lightweight alternatives to django-sentry for logging? Are there any lightweight alternatives to django-sentry for error logging in a Django environment? I used django-db-log earlier which now known as django-sentry. Some of the others I found were pretty much dead as they had no commits in the last ...
What are some lightweight alternatives to django-sentry for logging?
Are there any lightweight alternatives to django-sentry for error logging in a Django environment? I used django-db-log earlier which now known as django-sentry. Some of the others I found were pretty much dead as they had no commits in the last two years almost. Thanks.
[ "Sentry being overkill and Djangodblog being deprecated, I rolled my own, cannibalising the necessary parts from both. \nHow it works is by catching the error signal. Then it uses Django's inbuilt exception reporter to generate the fancy 500 error page that Django displays when debugging is enabled. We store this i...
[ 13, 2 ]
[]
[]
[ "django", "python", "sentry" ]
stackoverflow_0007130985_django_python_sentry.txt
Q: Throwing an exception to Main from a Class I am trying to write a stand alone Class that can be imported. As part of this I'd like to throw exceptions in my Class that can be caught and dealt with in the Main. Is it possible to throw specific exceptions to Main for the user/developer to deal with? I'm reasonable ...
Throwing an exception to Main from a Class
I am trying to write a stand alone Class that can be imported. As part of this I'd like to throw exceptions in my Class that can be caught and dealt with in the Main. Is it possible to throw specific exceptions to Main for the user/developer to deal with? I'm reasonable comfortable using the try: and except: in the Cl...
[ "Check out the python tutorial section on user defined exceptions and also the section \"Exceptions are Classes Too\". You can define your own exceptions as subclasses of the Exception class, and then catch them in your main.\nHere's a quick example, although the one in the tutorial is better:\nclass MyModuleExcept...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008289772_python.txt
Q: Python Popen WHOIS OS command fail test Prefacing this with the text 'just another beginner'. when you have the result of a whois command via the Popen command, how do you test if its good ? Normally when Python returns a list of whatever you can test the length of it and that has usually sufficed for me, but thi...
Python Popen WHOIS OS command fail test
Prefacing this with the text 'just another beginner'. when you have the result of a whois command via the Popen command, how do you test if its good ? Normally when Python returns a list of whatever you can test the length of it and that has usually sufficed for me, but this is a little more arbitrary. eg im testing f...
[ "To answer your direct question, look for this string in the output of a whois command to see whether there was a problem...\n\nNo match for \"insert_domain_here\"\n\nTo address other meaningful issues to your task... your Popen command is going at things the hard way... you don't need a PIPE for stdin and you can ...
[ 1 ]
[]
[]
[ "networking", "python", "whois" ]
stackoverflow_0008289780_networking_python_whois.txt
Q: Pygame Game with Notes I'm trying to learn pygame and I was wondering if anyone knew of a game that included notes within the script which explains what each line of code does. Preferably a very simple game that just outlines the basics. A: You should look at PyPong or Doodle-Jump A: have you looked at the pyg...
Pygame Game with Notes
I'm trying to learn pygame and I was wondering if anyone knew of a game that included notes within the script which explains what each line of code does. Preferably a very simple game that just outlines the basics.
[ "You should look at PyPong or Doodle-Jump\n", "have you looked at the pygame.org?\nThere are lots of projects in the right menu, you just select the category and download the source\n" ]
[ 0, 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0008289908_pygame_python.txt
Q: Rpy2 could not find function I've looked around for the error could not find function "someFunction" it appears to be a common error, however I have not found any pertaining to Rpy2. I want to make a heat map from a matrix I made in python. def HeatMap(HeatData): RHeatMap = robjects.FloatVector([HeatData[i] f...
Rpy2 could not find function
I've looked around for the error could not find function "someFunction" it appears to be a common error, however I have not found any pertaining to Rpy2. I want to make a heat map from a matrix I made in python. def HeatMap(HeatData): RHeatMap = robjects.FloatVector([HeatData[i] for i in range(len(HeatData[:,1]))]...
[ "I do not have any problems with your code under Python2.7 and rpy2 2.1.9.\nWhat happens if you call the R functions directly instead of using strings?\nHeatMap = robjects.r['matrix'](RHeatMap, nrow = len(HeatData[:,1]))\nrobjects.r['heatmap'](HeatMap, Rowv = robjects.NA_Integer, Colv = robjects.NA_Integer, col = r...
[ 0 ]
[]
[]
[ "heatmap", "python", "r", "rpy2" ]
stackoverflow_0008289736_heatmap_python_r_rpy2.txt
Q: Web.py | yield data via POST and AJAX (generator function) I am using the web.py framework to set up my website. When I click a button, I want to POST data to the server and then send back data via a generator function / yield. Basically yield data as it's ready, not wait for my data function to fully finish. I ge...
Web.py | yield data via POST and AJAX (generator function)
I am using the web.py framework to set up my website. When I click a button, I want to POST data to the server and then send back data via a generator function / yield. Basically yield data as it's ready, not wait for my data function to fully finish. I get yield to work via GET, but my POST implementations via AJAX is...
[ "Foolish me - AJAX doesn't support streaming. So this is a case when Comet or HTML5 WebSockets will come in handy. \n" ]
[ 2 ]
[]
[]
[ "ajax", "jquery", "post", "python", "web.py" ]
stackoverflow_0008276210_ajax_jquery_post_python_web.py.txt
Q: Python 2.7 32-bit install on Win 7: No registry keys? I have downloaded the Python 2.7.2 Windows x86 32-bit MSI from python.org and installed it on a 64-bit Windows 7 system. Everything works (at least the command-line interpreter starts and runs), but the install process does not create any Python entries under ...
Python 2.7 32-bit install on Win 7: No registry keys?
I have downloaded the Python 2.7.2 Windows x86 32-bit MSI from python.org and installed it on a 64-bit Windows 7 system. Everything works (at least the command-line interpreter starts and runs), but the install process does not create any Python entries under HKEY_LOCAL_MACHINE/SOFTWARE in the Windows registry. Variou...
[ "32-bit applications installed on 64-bit OSes store their registry values in: \nHKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node. If you look there, you should see the settings you are looking for.\n" ]
[ 7 ]
[]
[]
[ "installation", "python", "registry", "windows" ]
stackoverflow_0008289859_installation_python_registry_windows.txt
Q: Appengine Error 400 while deploying bloog Recently i was deploying bloog a python based webblog on appengine but got this error Uploading index definitions. Error 400: --- begin server output --- Creating a composite index failed: This index: entity_type: "Article" ancestor: false Property { name: "published" ...
Appengine Error 400 while deploying bloog
Recently i was deploying bloog a python based webblog on appengine but got this error Uploading index definitions. Error 400: --- begin server output --- Creating a composite index failed: This index: entity_type: "Article" ancestor: false Property { name: "published" direction: 2 } the content of index.yaml is ...
[ "Delete that index - and any other single property indexes - from index.yaml. They're completely unnecessary, as single properties are already indexed by the datastore.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008274954_google_app_engine_python.txt
Q: python subclasses I currently have a class called Polynomial, The initialization looks like this: def __init__(self, *termpairs): self.termdict = dict(termpairs) I'm creating a polynomial by making the keys the exponents and the associated values are the coefficients. To create an instance of this class, you...
python subclasses
I currently have a class called Polynomial, The initialization looks like this: def __init__(self, *termpairs): self.termdict = dict(termpairs) I'm creating a polynomial by making the keys the exponents and the associated values are the coefficients. To create an instance of this class, you enter as follows: d1 =...
[ "You should also use super() instead of using the constructor directly.\nclass Quadratic(Polynomial):\n def __init__(self, quadratic, linear, constant):\n super(Quadratic, self).__init__(quadratic[2], linear[1], constant[0])\n\n", "You probably want\nclass Quadratic(Polynomial):\n def __init__(self, q...
[ 15, 11 ]
[]
[]
[ "inheritance", "python", "quadratic", "subclass" ]
stackoverflow_0008290323_inheritance_python_quadratic_subclass.txt
Q: Python: Iterate dictionary that has set() as its value I have dictionary where values are python sets, When I iterate without properly handling the sets, this is what I get. Press Enter to continue... Kunnskap set([]) Samfunn set([]) Helse set([]) Natur set([]) Geografi set([]) Teknologi set([]) Historie set([]) D...
Python: Iterate dictionary that has set() as its value
I have dictionary where values are python sets, When I iterate without properly handling the sets, this is what I get. Press Enter to continue... Kunnskap set([]) Samfunn set([]) Helse set([]) Natur set([]) Geografi set([]) Teknologi set([]) Historie set([]) Dagligliv set([]) Personer set([]) Kommunikasjon set([]) Kult...
[ "\nBut sets doesn't have index so I cant iterate.\n\nSure you can:\n>>> x = set(range(10))\n>>> x\nset([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n>>> iter(x)\n<setiterator object at 0x0196C128>\n>>> for y in x: print y\n...\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n\nThe problem must be somewhere else.\n" ]
[ 4 ]
[]
[]
[ "dictionary", "python", "set" ]
stackoverflow_0008290621_dictionary_python_set.txt
Q: Automatic GUID key_name in model I want my model to get a GUID as key_name automatically and I'm using the code below. Is that a good approach to solve it? Does it have any drawbacks? class SyncModel(polymodel.PolyModel): def __init__(self, key_name=None, key=None, **kwargs): super(SyncModel, self).__i...
Automatic GUID key_name in model
I want my model to get a GUID as key_name automatically and I'm using the code below. Is that a good approach to solve it? Does it have any drawbacks? class SyncModel(polymodel.PolyModel): def __init__(self, key_name=None, key=None, **kwargs): super(SyncModel, self).__init__(key_name=str(uuid.uuid1()) if no...
[ "There is an article by Nick about pre and post put hooks which and be used to set the key_name, I don't know if your current method is valid or not but at least you should be aware of other options. \n", "Overriding __init__ on a Model subclass is dangerous, because the constructor is used by the framework to re...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0008270999_google_app_engine_google_cloud_datastore_python.txt
Q: How to use Assert in this instance? I'm trying to use assert to check if another function is working correctly. In this case the function I am trying to test is the following: def factorial(n): if type(n) != int or n < 0: raise ValueError, "\nThis error has been raised because the value inputted was ei...
How to use Assert in this instance?
I'm trying to use assert to check if another function is working correctly. In this case the function I am trying to test is the following: def factorial(n): if type(n) != int or n < 0: raise ValueError, "\nThis error has been raised because the value inputted was either not an integer or negative." els...
[ "Your factorial function prints the result, but it does not return it. This is why the assertion fails. Try this:\ndef factorial(n):\n if not isinstance(n, int):\n raise ValueError('value must be an int')\n if n < 0:\n raise ValueError('n must be >= 0')\n\n result = 1\n for x in range(n):\...
[ 3, 1, 1 ]
[]
[]
[ "assert", "function", "python" ]
stackoverflow_0008290624_assert_function_python.txt
Q: SQLite: Select all date-value-pairs where the distance between each date and the first date is a multiple of a specific period I am working with SQLite and Python and try to get these specific dates (and corresponding values). I think an example explainst best what I am looking for. Consider selecting from this da...
SQLite: Select all date-value-pairs where the distance between each date and the first date is a multiple of a specific period
I am working with SQLite and Python and try to get these specific dates (and corresponding values). I think an example explainst best what I am looking for. Consider selecting from this data: -(2011-01-02, 4.0) -(2011-01-14, 5.0) -(2011-02-02, 5.5) -(2011-02-07, 6.5) -(2011-02-12, 7.0) -(2011-02-15, 4.0) -(2011-03-02, ...
[ "It sounds like this won't be a flexible enough solution for your needs, but to answer your question directly, here is a query that gets you what you need.\nAlso, since you didn't specify table/column names, my test table I used is called foo, and has columns created and value.\nselect\n foo.created, foo.value\n...
[ 1 ]
[]
[]
[ "date", "python", "sql", "sqlite" ]
stackoverflow_0007733475_date_python_sql_sqlite.txt
Q: Segfault using matplotlib with PyQt Can anyone hint at why the following code (taken from here) segfaults on exit? """ This demo demonstrates how to embed a matplotlib (mpl) plot into a PyQt4 GUI application, including: * Using the navigation toolbar * Adding data to the plot * Dynamically modifying the plot's p...
Segfault using matplotlib with PyQt
Can anyone hint at why the following code (taken from here) segfaults on exit? """ This demo demonstrates how to embed a matplotlib (mpl) plot into a PyQt4 GUI application, including: * Using the navigation toolbar * Adding data to the plot * Dynamically modifying the plot's properties * Processing mpl events * Savin...
[ "The QApplication object is being garbage collected before the Form during exit. Make this change to your code:\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n form = AppForm()\n form.show()\n app.exec_()\n del form\n\nand the segfault goes away. It appears something in PyQt or matplot...
[ 1 ]
[]
[]
[ "matplotlib", "pyqt", "python" ]
stackoverflow_0005770263_matplotlib_pyqt_python.txt
Q: Django query for many to many relationship I have following two models class Questionnaire(models.model) name = models.CharField(max_length=128, null=True, blank=True) type = models.CharField(max_length=128,choices=questionnaire_choices) class TestPopulation(models.Model) user = models.ForeignKey...
Django query for many to many relationship
I have following two models class Questionnaire(models.model) name = models.CharField(max_length=128, null=True, blank=True) type = models.CharField(max_length=128,choices=questionnaire_choices) class TestPopulation(models.Model) user = models.ForeignKey(User, blank=True, null=True) age = models...
[ "test_population = TestPopulation.objects.get(user=user)\ntest_population.questionnaire.all()\n\n", "questionnaire.objects.filter(test_population__user=user).count()\n\n" ]
[ 11, 4 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0008286486_django_django_models_python.txt
Q: MonkeyRunner::How to install python modules? I am using MonkeyRunner to automate some UI test cases. I need to collect logs from the device using tool like QXDM. I see that win32com python module can be used to launch QXDM and collecting logs. But when i use from win32com.client import Dispatch in python script wh...
MonkeyRunner::How to install python modules?
I am using MonkeyRunner to automate some UI test cases. I need to collect logs from the device using tool like QXDM. I see that win32com python module can be used to launch QXDM and collecting logs. But when i use from win32com.client import Dispatch in python script which is passed as argument to MonkeyRunner, MonkeyR...
[ "Monkeyrunner use Jython as its Python interface (jython.jar under tools\\lib folder).\nIt uses 2.5.0 version. Now the latest Jython version is 2.5.2. \nEither one does not support pywin32 or any other modules. It only supports standard Python modules in version 2.5.\n" ]
[ 1 ]
[]
[]
[ "monkeyrunner", "python" ]
stackoverflow_0007311676_monkeyrunner_python.txt
Q: How to get integers from a text file, using Python? in Python I'm trying to set a variable from info stored in a txt. I can manage to set it, but it does not act as a number. Is it being stored as something else? Here is my .txt file (all info is written on one line, no \ns): 11 14 15 3 Here is my script: def br...
How to get integers from a text file, using Python?
in Python I'm trying to set a variable from info stored in a txt. I can manage to set it, but it does not act as a number. Is it being stored as something else? Here is my .txt file (all info is written on one line, no \ns): 11 14 15 3 Here is my script: def break_words(text): words = text.split(' ') return w...
[ "I think the problem is that you have two different types in your comparison string and int. Assuming you are doing a numerical comparison you may want to explicitly cast your shift_l4 to an int. int(shift_l4).\n", "\"file_name\" is not a good name for a file object. \"words\" is not a good name for a collection ...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008291068_python.txt
Q: colour terminal libraries I'm trying to implement colour cycling on my text in Python... This question has been edited and resubmitted as another question because of a massive change in context. please see here instead. this question was more about what library I should use - termcolor, colorama, curses and an ans...
colour terminal libraries
I'm trying to implement colour cycling on my text in Python... This question has been edited and resubmitted as another question because of a massive change in context. please see here instead. this question was more about what library I should use - termcolor, colorama, curses and an ansi colour recipe, code so far: ...
[ "Here are a few techniques to try:\n\nThis block of code creates lists of the actual escape strings. It uses a list comprehension to iterate over the list of color names and look up the escape codes in your colour dictionary. The .split() is just a lazy way to create a list of strings without typing lots of quote...
[ 1, 0 ]
[]
[]
[ "colors", "python" ]
stackoverflow_0008286043_colors_python.txt
Q: Conditional disabling of widget In the following code, I have been trying to disable the entry1 widget every time I select 1 in the combobox and disable entry2 when i select 2 in combobox. this is my code: from Tkinter import * import ttk def refresh(): if v.get() == 'A': entry1.state(['disabled']) ...
Conditional disabling of widget
In the following code, I have been trying to disable the entry1 widget every time I select 1 in the combobox and disable entry2 when i select 2 in combobox. this is my code: from Tkinter import * import ttk def refresh(): if v.get() == 'A': entry1.state(['disabled']) entry2.state(['!disabled']) ...
[ "The piece you seem to be missing is that you can change the state with the configure method. Also, you can set a trace on a variable to have a function called when the value changes. Since you said you want to change the state based on a combobox, that is the technique you would use. You can do a similar trick wit...
[ 3, -1 ]
[]
[]
[ "python", "tkinter", "ttk", "user_interface" ]
stackoverflow_0008254309_python_tkinter_ttk_user_interface.txt
Q: Model-View-Presenter and Three-Tier? What is the difference between the two architectures: Model-View-Presenter and Three-Tier? I understand the definitions of each when read individually, but I can't readily see how they're different. Is it desktop vs web? I am currently developing a simple desktop application ...
Model-View-Presenter and Three-Tier?
What is the difference between the two architectures: Model-View-Presenter and Three-Tier? I understand the definitions of each when read individually, but I can't readily see how they're different. Is it desktop vs web? I am currently developing a simple desktop application in Python to visualize a complicated data ...
[ "MVC is an UI pattern, three tier is an application architecture pattern. That is you can design your application with 3 tiers - UI, BL, data. And than use MVC in the UI tier.\n", "MVC is a UI implementation pattern that attempts to simplify three tier architecture. MVC is just one of the ways you can implement ...
[ 4, 1, 0 ]
[]
[]
[ "model", "mvp", "python", "three_tier" ]
stackoverflow_0003129633_model_mvp_python_three_tier.txt
Q: EOF error in parser YACC I am trying to parse a string using the yacc parser provided in the PLY library for Python. The parser itself is very long, but the problem that i am having is that it always gives me the same error, no matter what kind of string i put. The error is this: yacc: Parse error in input. EOF A...
EOF error in parser YACC
I am trying to parse a string using the yacc parser provided in the PLY library for Python. The parser itself is very long, but the problem that i am having is that it always gives me the same error, no matter what kind of string i put. The error is this: yacc: Parse error in input. EOF And the lexer is running perfec...
[ "All parsers specified in PLY are expected to have a single top-level rule that gets reduced as a result of parsing the entire input text. For example, if parsing a program, the top level rule might be something like this:\ndef p_program(p):\n '''\n program : declarations\n '''\n\ndef p_declarations(p):\n...
[ 8 ]
[]
[]
[ "parsing", "ply", "python", "yacc" ]
stackoverflow_0008220648_parsing_ply_python_yacc.txt
Q: How to use multiple variables read from file with looping subprocess/popen I am using python to read 2 files from my linux os. One contains a single entry/number 'DATE': 20111125 the other file contains many entries, 'TIME': 042844UTC 044601UTC ... 044601UTC I am able to read the files to assign to proper var...
How to use multiple variables read from file with looping subprocess/popen
I am using python to read 2 files from my linux os. One contains a single entry/number 'DATE': 20111125 the other file contains many entries, 'TIME': 042844UTC 044601UTC ... 044601UTC I am able to read the files to assign to proper variables. I would like to then use the variables to create folder paths, move fil...
[ "I would suggest using os.makedirs (which does the same thing as mkdir -p) instead of subprocess or popen:\nimport sys\nimport os\nDATEFILE = open(os.path.join(r'/Astronomy', 'Sorted', '2-Scratch', 'MAPninox-DATE.txt'), \"r\")\nTIMEFILE = open(os.path.join(r'/Astronomy', 'Sorted', '2-Scratch', 'MAPninox-TIME.txt'),...
[ 2, 1 ]
[]
[]
[ "popen", "python", "subprocess", "variables" ]
stackoverflow_0008290980_popen_python_subprocess_variables.txt
Q: Querying through several models I have a django project with 5 different models in it. All of them has date field. Let's say i want to get all entries from all models with today date. Of course, i could just filter every model, and put results in one big list, but i believe it's bad. What would be efficient way t...
Querying through several models
I have a django project with 5 different models in it. All of them has date field. Let's say i want to get all entries from all models with today date. Of course, i could just filter every model, and put results in one big list, but i believe it's bad. What would be efficient way to do that?
[ "I don't think that it's a bad idea to query each model separately - indeed, from a database perspective, I can't see how you'd be able to do otherwise, as each model will need a separate SQL query. Even if, as @Nagaraj suggests, you set up a common Date model every other model references, you'd still need to query...
[ 4, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008291467_django_python.txt
Q: translating user input in python I would like to translate items in a list (e.g. [1,2,3,4,5,6,7,8,9]) to items in another list (e.g. the names of those numbers). Furthermore, I want to be able to do the translation so that when a user inputs '1', "one" is printed, and similarly for '2', etc. Here's the code I hav...
translating user input in python
I would like to translate items in a list (e.g. [1,2,3,4,5,6,7,8,9]) to items in another list (e.g. the names of those numbers). Furthermore, I want to be able to do the translation so that when a user inputs '1', "one" is printed, and similarly for '2', etc. Here's the code I have so far: numbers = [0, 1, 2, 3, 4, 5,...
[ "Using the input function will allow you to accept input from the user and do the lookup (if I understand what you are asking): \n>>> mydict = {'nom':'singe', 'poids':70, 'taille':1.75}\n>>> myvar = input()\nnom\n>>> print(mydict[myvar])\nsinge\n\n", "It will not print \"nom piods\" because you don't have a key f...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008291359_python.txt
Q: Google App Engine (So "Pure Python"): Convert PDF to Image In Google App Engine, I need to be able to take an uploaded PDF and convert it to an image (or maybe one day a number of tiled images) for storing and serving back out. Is there a library that will read PDF files that is also 100% python (so it can be upl...
Google App Engine (So "Pure Python"): Convert PDF to Image
In Google App Engine, I need to be able to take an uploaded PDF and convert it to an image (or maybe one day a number of tiled images) for storing and serving back out. Is there a library that will read PDF files that is also 100% python (so it can be uploaded with my app)? From what I've gathered so far... PIL does ...
[ "You may want to look into using the GAE Conversion API (not yet fully released). There's a tester signup form here, with a link to further details.\nFrom the doc:\nConversions can be performed in any direction between PDF, HTML, TXT, and image formats, and OCR will be employed if necessary. Note that while PNG, GI...
[ 5 ]
[]
[]
[ "ghostscript", "google_app_engine", "pdf", "python", "python_imaging_library" ]
stackoverflow_0008291321_ghostscript_google_app_engine_pdf_python_python_imaging_library.txt
Q: python subprocess "mount" does not prompt for password I just learned subprocess.check_call() function today. I intend to use it to replace my os.system command. Originally, I have my command as such: os.system("mount -t cifs //source/share /mnt/share -o username=user") The command above will prompt for password ...
python subprocess "mount" does not prompt for password
I just learned subprocess.check_call() function today. I intend to use it to replace my os.system command. Originally, I have my command as such: os.system("mount -t cifs //source/share /mnt/share -o username=user") The command above will prompt for password and it will mount the drive if the password is correct. Howe...
[ "You are invoking mount without parameters. If you specify shell=True, subprocess expects the entire command including arguments is passed to the shell as one big string. If you specify shell=False (the default if not specified), the command and its arguments are passed as a list of strings, as you have done by u...
[ 4 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0008291788_python_subprocess.txt
Q: What's wrong with this nested list comprehension? >>> c = 'A/B,C/D,E/F' >>> [a for b in c.split(',') for (a,_) in b.split('/')] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <listcomp> ValueError: need more than 1 value to unpack The expected result is ['A',...
What's wrong with this nested list comprehension?
>>> c = 'A/B,C/D,E/F' >>> [a for b in c.split(',') for (a,_) in b.split('/')] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <listcomp> ValueError: need more than 1 value to unpack The expected result is ['A', 'C', 'E']. This is how I'd expect to do it, but appare...
[ "The reason you are failing is b.split('/') is not yielding a 2-tuple. A double list comprehension implies you want to treat the cartesian product as a flat stream and not a matrix. That is:\n>>> [x+'/'+y for y in 'ab' for x in '012']\n['0/a', '1/a', '2/a', '0/b', '1/b', '2/b']\n # desire output 0,1,2\n # not...
[ 5, 4 ]
[]
[]
[ "list_comprehension", "python", "python_3.x" ]
stackoverflow_0008291771_list_comprehension_python_python_3.x.txt
Q: creating class instances from a text file in python I have a polynomial class: class Polynomial: def __init__(self, *termpairs): self.termdict = dict(termpairs) To add an instance to this class, you enter the following: P = Polynomial((3,2), (4,5), (9,8)) Now I'm trying to create a function that read...
creating class instances from a text file in python
I have a polynomial class: class Polynomial: def __init__(self, *termpairs): self.termdict = dict(termpairs) To add an instance to this class, you enter the following: P = Polynomial((3,2), (4,5), (9,8)) Now I'm trying to create a function that reads information from a text file, and from that text file, ...
[ "return always exits the function immediately upon calling and can only return one item. So if you want multiple items (in a sense) to be returned, you must pack them in a list, then return that.\nIn place of the for loop:\npolys = []\nfor item in poly1:\n polys.append(Polynomial(item))\nreturn polys\n\nYou wil...
[ 1, 1, 0 ]
[]
[]
[ "file", "instances", "python" ]
stackoverflow_0008291778_file_instances_python.txt
Q: How to implement python's namedtuple in javascript How would I go about implementing python's namedtuple in javascript? Ideally I would also want a function I could "map" over a sequence of sequences to turn it into a sequence of namedtuple-like objects. // with underscore.js included... var points = [[1,2], [3,4]...
How to implement python's namedtuple in javascript
How would I go about implementing python's namedtuple in javascript? Ideally I would also want a function I could "map" over a sequence of sequences to turn it into a sequence of namedtuple-like objects. // with underscore.js included... var points = [[1,2], [3,4], [4,5] var Point = namedlist('Point', 'x y') points = _...
[ "You could just use something like\nvar namedlist = function(fields) {\n return function(arr) {\n var obj = { };\n\n for(var i = 0; i < arr.length; i++) {\n obj[fields[i]] = arr[i]; \n }\n\n return obj;\n };\n};\n\n//use:\nvar points = [[1,2], [3,4], [5,6]];\n...
[ 6 ]
[]
[]
[ "javascript", "namedtuple", "python" ]
stackoverflow_0008291194_javascript_namedtuple_python.txt
Q: Programming in Python; writing a Caesar Cipher using a zip() method I have a homework problem: to encrypt a message using a Caesar cipher. I need to be able to have the user input a number to shift the encryption by. For example, shifting by 4 would change 'A' into 'E'. The user also needs to input the string to b...
Programming in Python; writing a Caesar Cipher using a zip() method
I have a homework problem: to encrypt a message using a Caesar cipher. I need to be able to have the user input a number to shift the encryption by. For example, shifting by 4 would change 'A' into 'E'. The user also needs to input the string to be translated. The book says to use the zip() function to solve the proble...
[ "\"zip\" is a builtin function of Python, not a certain type of method as your question title implies.\n>>> help(zip)\nHelp on built-in function zip in module __builtin__:\n\nzip(...)\n zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\n Return a list of tuples, where each tuple contains the i-th ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008290610_python.txt
Q: python how to convert from string.template object to string This is very simple.I am sure I am missing something silly. fp = open(r'D:\UserManagement\invitationTemplate.html', 'rb') html = Template(fp.read()) fp.close() html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu') print html When i ru...
python how to convert from string.template object to string
This is very simple.I am sure I am missing something silly. fp = open(r'D:\UserManagement\invitationTemplate.html', 'rb') html = Template(fp.read()) fp.close() html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu') print html When i run this code in intepreter directly,I get the proper output. But w...
[ "safe_substitute returns, as a string, the template with the substitutions made. This way, you can reuse the same template for multiple substitutions. So your code has to be\nprint html.safe_substitute(toFirstName='jibin',fromFirstName='Vishnu')\n\n", "According to the docs you should take the return Value of saf...
[ 19, 5, 2 ]
[]
[]
[ "python", "string", "templates" ]
stackoverflow_0008292555_python_string_templates.txt
Q: SSH with Paramiko : failing to read data Below is my driver information where I need to pull the data(Firmware Version) using ssh script as show below. ncmdvstk:~ $ ssh admin@153.88.127.21 Password: MSM760 V. 5.3.6.18-01-9124 (C) 2010 Hewlett-Packard Development Company, L.P. CLI> enable CLI# show system info ...
SSH with Paramiko : failing to read data
Below is my driver information where I need to pull the data(Firmware Version) using ssh script as show below. ncmdvstk:~ $ ssh admin@153.88.127.21 Password: MSM760 V. 5.3.6.18-01-9124 (C) 2010 Hewlett-Packard Development Company, L.P. CLI> enable CLI# show system info [CPU info] [Mem in fo] Firmware Version: 5.3...
[ "You need to add a call to stdin.flush() after the stdin.write() otherwise the input you're sending will stay buffered.\n" ]
[ 0 ]
[]
[]
[ "buffered", "io", "paramiko", "python", "ssh" ]
stackoverflow_0007569050_buffered_io_paramiko_python_ssh.txt
Q: python paste multilines to raw_input in a while loop I have some code looks like this: while line != '' and line != 'STOP ME': line = raw_input("") buf.append(line+'\n') sys.stdin.flush() print raw_input("Input1:") print raw_input("Input2:") The problem is, if the user copy and paste the data like this ...
python paste multilines to raw_input in a while loop
I have some code looks like this: while line != '' and line != 'STOP ME': line = raw_input("") buf.append(line+'\n') sys.stdin.flush() print raw_input("Input1:") print raw_input("Input2:") The problem is, if the user copy and paste the data like this line1 line2 STOP ME "empty line" "empty line" Some junk te...
[ "May be you don't need raw_input here? You can use sys.stdin file-like object. For example sys.stdin.read method.\nOr you can use somthing like this:\nbuf.append(line.split('STOP ME\\n', 1)[0]+'\\n')\n\nto get data before STOP ME line.\n" ]
[ 1 ]
[]
[]
[ "python", "raw_input" ]
stackoverflow_0008292798_python_raw_input.txt
Q: Multiple object instance sharing global variable in Python I want to have a global variable x that can be accessed by multiple object instances: The module Obj should have something like: x = 0 class Obj: def set_x(self): global x x = 2 def print_x(self): print x ...etc. The othe...
Multiple object instance sharing global variable in Python
I want to have a global variable x that can be accessed by multiple object instances: The module Obj should have something like: x = 0 class Obj: def set_x(self): global x x = 2 def print_x(self): print x ...etc. The other module (ex: main) instantiates the object obj: obj1 = Obj.Obj(...
[ "I think you're looking for something like static variables (I'm not sure what they're called in Python). Have you tried something like:\nclass Obj:\n x = 0\n\n def set_x(self):\n Obj.x = Obj.x + 1\n\n def print_x(self):\n print Obj.x\n\nTests:\n>>> obj1 = Obj()\n>>> obj1.set_x()\n>>> obj1.print_x()...
[ 2 ]
[]
[]
[ "global_variables", "multiple_instances", "object", "python" ]
stackoverflow_0008292623_global_variables_multiple_instances_object_python.txt
Q: Backup dirs and subdirs using Python; Use os.walk or filecmp.dircmp, or something else I am a python newbie. My question is what approach I should use to set up a file/directory backup routine, as described below (os.walk or filecmp.dircmp, or something else). I want to set up a backup routine as follows: Eve...
Backup dirs and subdirs using Python; Use os.walk or filecmp.dircmp, or something else
I am a python newbie. My question is what approach I should use to set up a file/directory backup routine, as described below (os.walk or filecmp.dircmp, or something else). I want to set up a backup routine as follows: Every night, I want to make "bakup_dir_a1" (and all its subdirectories) into a mirror of "local...
[ "For the first step, take a look at the shutil module, starting with http://docs.python.org/library/shutil.html#shutil.copytree\nFor the second step, filecmp.dircmp is a reasonable choice. \nFor the fifth step, take a look at the archiving options in the tarfile module and zipfile module.\n" ]
[ 1 ]
[]
[]
[ "backup", "file_comparison", "os.walk", "python" ]
stackoverflow_0008293089_backup_file_comparison_os.walk_python.txt
Q: py2app'ed application runs properly in alias mode but not when bundled I have a pyobjc app running in a 32-bit only python build that makes use of the gevent library. Everything works great in py2app'ed alias mode, but once I build an app bundle, the gevent module can't find the httplib library, even if it was bun...
py2app'ed application runs properly in alias mode but not when bundled
I have a pyobjc app running in a 32-bit only python build that makes use of the gevent library. Everything works great in py2app'ed alias mode, but once I build an app bundle, the gevent module can't find the httplib library, even if it was bundled with the site-packages directory. File "gevent/monkey.pyo", line 182, i...
[ "It is a bit tricky and involves even more patching, but definitely solvable:\ndef main():\n\n # Patch the imp standard library module to fix an incompatibility between\n # py2app and gevent.httplib while running a py2app build on Mac OS-X.\n # This patch must be executed before applying gevent's monkey pa...
[ 2 ]
[]
[]
[ "gevent", "monkeypatching", "py2app", "py2exe", "python" ]
stackoverflow_0008029082_gevent_monkeypatching_py2app_py2exe_python.txt
Q: Django peculiar behavior for model queryset I have a model with the following structure class Lease(models.Model): .... rent_category = models.ForeignKey( Category ) building = models.ForeignKey( Building ) I have a form against this model, and is working fine. But when i go to the shell and and try t...
Django peculiar behavior for model queryset
I have a model with the following structure class Lease(models.Model): .... rent_category = models.ForeignKey( Category ) building = models.ForeignKey( Building ) I have a form against this model, and is working fine. But when i go to the shell and and try to query the model, it doesn't see the building fi...
[ "Thanks DrTyrsa, \nYour last point=True, \ni don't have a building with lease[0].building_id, i did lease[17].building and it returned me the correct result. \nThanks.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008292948_django_python.txt
Q: SQLAlchemy connects to SQLServer using Windows Authenticaton with pymssql driver I can use pymssql to connect to SQLServer using Windows Authentication: conn = pymssql.connect(host='..', database='..', trusted=True) But how could I use SQLAlchemy to connect to SQLServer using Windows Authenticaton with pymssql dr...
SQLAlchemy connects to SQLServer using Windows Authenticaton with pymssql driver
I can use pymssql to connect to SQLServer using Windows Authentication: conn = pymssql.connect(host='..', database='..', trusted=True) But how could I use SQLAlchemy to connect to SQLServer using Windows Authenticaton with pymssql driver? The example given by SQLAlchemy is: mssql+pymssql://<username>:<password>@<freet...
[ "I do not have pymssql to check, but try the version below:\nmssql+pymssql://<freetds_name>?trusted=True\n\n" ]
[ 0 ]
[]
[]
[ "pymssql", "python", "sql_server", "sqlalchemy" ]
stackoverflow_0008284181_pymssql_python_sql_server_sqlalchemy.txt
Q: Google App Engine Help? Thanks for taking time to read my question. I'm trying to embed something like this on my website using google app engine. To accomplish this my understanding is I have to upload a .js file. I currently have this code on my page: <script src='/ytembed.js' type="text/javascript"></script> <...
Google App Engine Help?
Thanks for taking time to read my question. I'm trying to embed something like this on my website using google app engine. To accomplish this my understanding is I have to upload a .js file. I currently have this code on my page: <script src='/ytembed.js' type="text/javascript"></script> <div id="youtubeDiv"></div> <s...
[ "I recommend you to use the static_dir configuration like this:\napplication: ********* \n version: 1\n runtime: python\n api_version: 1\n\n handlers:\n\n - url: /static/\n static_dir: static\n\n - url: .*\n script: main.py\n\nAnd put the ytembed.js in static/js/ytembed.js from the root ...
[ 3 ]
[]
[]
[ "google_app_engine", "javascript", "python" ]
stackoverflow_0008291785_google_app_engine_javascript_python.txt
Q: Python: continue iteration of for loop on exception I have a simple for loop in Python that is exiting on exceptions even though the exception block contains a continue. There are still about 10 lines left to read when it hits an IndexError and exits the for loop. What am I missing here? for row in hkx: ##'hkx' a...
Python: continue iteration of for loop on exception
I have a simple for loop in Python that is exiting on exceptions even though the exception block contains a continue. There are still about 10 lines left to read when it hits an IndexError and exits the for loop. What am I missing here? for row in hkx: ##'hkx' are rows being read in from 'csv.open' try: pr...
[ "It does exactly as it should and continues with the next line. If an exception is terminating your code early then it must either not be IndexError, or it must be being thrown from some code outside the try: block.\n>>> hkx = [ range(5), range(4), range(4), range(5) ]\n>>> for row in hkx: ##'hkx' are rows being r...
[ 12 ]
[]
[]
[ "exception", "for_loop", "python" ]
stackoverflow_0008293086_exception_for_loop_python.txt
Q: Is it bad form to raise ArgumentError by hand? If you want to add an extra check not provided by argparse, such as: if variable a == b then c should be not None ...is it permissible to raise ArgumentError yourself? Or, should you raise Exception instead? Also what is common practice for this kind of situation? S...
Is it bad form to raise ArgumentError by hand?
If you want to add an extra check not provided by argparse, such as: if variable a == b then c should be not None ...is it permissible to raise ArgumentError yourself? Or, should you raise Exception instead? Also what is common practice for this kind of situation? Say that you add a piece of code that's almost like a...
[ "There's nothing inherently wrong with raising an ArgumentError. You can use it anytime the arguments you receive are not what you expected them to be, including checking range of numbers.\nAlso, yes, in general it's alright for you to use the same exceptions provided by a given library if you are writing an extens...
[ 23 ]
[]
[]
[ "argparse", "exception_handling", "python" ]
stackoverflow_0008293325_argparse_exception_handling_python.txt
Q: Cannot change model instance after a ValidationError is thrown in django admin area Imagine a model like this: class CFile(models.Model): filepath = models.FileField(upload_to=...) collection = models.ForeignKey("FileCollection",null=True) ... # other attributes that are not relevant def clean(self)...
Cannot change model instance after a ValidationError is thrown in django admin area
Imagine a model like this: class CFile(models.Model): filepath = models.FileField(upload_to=...) collection = models.ForeignKey("FileCollection",null=True) ... # other attributes that are not relevant def clean(self): bname = os.path.basename if self.collection: cfiles = self.baseline.at...
[ "I think the clearest way is to declare another field in your model for filename and make it unique for every collection. Like this:\nclass CFile(models.Model):\n filepath = models.FileField(upload_to=...)\n collection = models.ForeignKey(\"FileCollection\",null=True, related_name='files')\n filename = mode...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008293333_django_python.txt
Q: Python encode issue with beautifulsoup Hello I`ve got a problem which encoding When I put string to beautifulsoup lost all National char addr = "http://zjazdowa.com.pl/index.php/aktualne-ceny-warzyw-i-owocow-.html" content = urllib2.urlopen(addr) .read() html_pag = BeautifulSoup(co...
Python encode issue with beautifulsoup
Hello I`ve got a problem which encoding When I put string to beautifulsoup lost all National char addr = "http://zjazdowa.com.pl/index.php/aktualne-ceny-warzyw-i-owocow-.html" content = urllib2.urlopen(addr) .read() html_pag = BeautifulSoup(content) #<- there i lost all national letters...
[ "according to the documentation of BeautifulSoup all the input is transformed to UTF8 internally:\nfrom BeautifulSoup import BeautifulSoup\nsoup = BeautifulSoup(\"Hello\")\nsoup.contents[0]\n# u'Hello'\nsoup.originalEncoding\n# 'ascii'\n\nif your input does not specify the encoding (eg, meta-tags), BeautifulSoup gu...
[ 4, 1 ]
[]
[]
[ "ascii", "beautifulsoup", "encoding", "python", "utf_8" ]
stackoverflow_0005088797_ascii_beautifulsoup_encoding_python_utf_8.txt
Q: how to get past keyboard authentication with paramiko I am trying to use Paramiko to connect to a remote host via ssh however I get an error message which states that keyboard authentication is required to access the host. Is there any way I can get around this using Paramiko? If not, is there another ssh module I...
how to get past keyboard authentication with paramiko
I am trying to use Paramiko to connect to a remote host via ssh however I get an error message which states that keyboard authentication is required to access the host. Is there any way I can get around this using Paramiko? If not, is there another ssh module I can use? I'll even use another language if I have to. The ...
[]
[]
[ "You could get username and password from whatever resource you have and use it when calling connect. For example you could save them in a config file.\n", "Either pass the private key directly using pkey= or pass in the name of the file with key_filename= when calling connect() like so:\nclient = SSHClient()\ncl...
[ -1, -1 ]
[ "paramiko", "python", "ssh" ]
stackoverflow_0007380710_paramiko_python_ssh.txt
Q: Why does removing the else slow down my code? Consider the following functions: def fact1(n): if n < 2: return 1 else: return n * fact1(n-1) def fact2(n): if n < 2: return 1 return n * fact2(n-1) They should be equivalent. But there's a performance difference: >>> T(lambda...
Why does removing the else slow down my code?
Consider the following functions: def fact1(n): if n < 2: return 1 else: return n * fact1(n-1) def fact2(n): if n < 2: return 1 return n * fact2(n-1) They should be equivalent. But there's a performance difference: >>> T(lambda : fact1(1)).repeat(number=10000000) [2.57544088363...
[ "What is happening here is that fact2 has a hash conflict with __name__ in your module globals. That makes the lookup of the global fact2 ever so slightly slower.\n>>> [(k, hash(k) % 32) for k in globals().keys() ]\n[('__builtins__', 8), ('__package__', 15), ('fact2', 25), ('__name__', 25), ('fact1', 26), ('__doc__...
[ 12, 11, 9 ]
[]
[]
[ "performance", "python", "recursion" ]
stackoverflow_0008203696_performance_python_recursion.txt
Q: Why does python subprocess.Popen launch a subprocess through cmd.exe? I call subprocess like this: command = 'c:\somepath\myexe.exe' startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(command, shell=False, startupinfo=startupinfo) It appears that i...
Why does python subprocess.Popen launch a subprocess through cmd.exe?
I call subprocess like this: command = 'c:\somepath\myexe.exe' startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(command, shell=False, startupinfo=startupinfo) It appears that instead of launching myexe.exe directly, it goes through cmd.exe. Can I avo...
[ "Iff you're using Python 2.7 - use subprocess._subprocess.STARTF_USESHOWWINDOW instead of subprocess.STARTF_USESHOWWINDOW. I think this would solve it.\n" ]
[ 3 ]
[]
[]
[ "python", "subprocess", "windows" ]
stackoverflow_0008055925_python_subprocess_windows.txt
Q: Python dictionary with variables as keys I'm a Python newbie trying to parse a file to make a table of memory allocations. My input file is in the following format: 48 bytes allocated at 0x8bb970a0 24 bytes allocated at 0x8bb950c0 48 bytes allocated at 0x958bd0e0 48 bytes allocated at 0x8bb9b060 96 bytes allocated...
Python dictionary with variables as keys
I'm a Python newbie trying to parse a file to make a table of memory allocations. My input file is in the following format: 48 bytes allocated at 0x8bb970a0 24 bytes allocated at 0x8bb950c0 48 bytes allocated at 0x958bd0e0 48 bytes allocated at 0x8bb9b060 96 bytes allocated at 0x8bb9afe0 24 bytes allocated at 0x8bb9af6...
[ "Learning a language is as much about the syntax and basic types as it is about the standard library. Python already has a class that makes your task very easy: collections.Counter.\nfrom collections import Counter\n\nwith open(\"allocFile.txt\") as fp:\n counter = Counter(line.split()[0] for line in fp)\n\nfor ...
[ 10, 4, 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008293617_python.txt
Q: Python returns no such file or directory when opening a file it has just found using re.search I am trying to open a specific file in many folders, with the name ending '.alleles.txt'. I search for the file and it is found, but then it returns: IOError: [Errno 2] No such file or directory: 'abca3.alleles.txt' when...
Python returns no such file or directory when opening a file it has just found using re.search
I am trying to open a specific file in many folders, with the name ending '.alleles.txt'. I search for the file and it is found, but then it returns: IOError: [Errno 2] No such file or directory: 'abca3.alleles.txt' when I try and open it. for eachfile in filelisting: if re.search('\.alleles\...
[ "You should be using glob. Try this\nimport glob\n\nfiles = glob.glob('E:\\\\All Data\\\\*\\\\*.alleles.txt')\n\n", "How did you obtain the filelisting? If you used filelisting = os.walk(directoryname) then it resturns a special tuple. Did you look at it?\nAnd, does filelisting contain the full path of the files?...
[ 2, 1, 1, 1 ]
[]
[]
[ "directory", "file", "ioerror", "python" ]
stackoverflow_0008293195_directory_file_ioerror_python.txt
Q: How do I make better use of logging module in my program? I didn't consider logging module when I started with my script, so I just simply code like this: LogMethod(LogFileName, LogMessage): LogRlock.acquire() LogFile = open(LogFileName, "a") LogFile.write(LogMessage) LogFile.close() LogRloc...
How do I make better use of logging module in my program?
I didn't consider logging module when I started with my script, so I just simply code like this: LogMethod(LogFileName, LogMessage): LogRlock.acquire() LogFile = open(LogFileName, "a") LogFile.write(LogMessage) LogFile.close() LogRlock.release() But now since logging module can do way better job...
[ "Using a logger and defining its properties are two different tasks that should be separated in order to separate business logic from configuration logic.\nUsually, in applications, you target a logger by its name. So basically, all you need to log would be a method like this:\ndef logMethod(loggerName, logMessage)...
[ 2, 1 ]
[]
[]
[ "file_io", "logging", "python" ]
stackoverflow_0008292036_file_io_logging_python.txt
Q: Using the filter function in Python I am trying to use Python's built-in filter function in order to extract data from certain columns in a CSV. Is this a good use of the filter function? Would I have to define the data in these columns first, or would Python somehow already know which columns contain what data? ...
Using the filter function in Python
I am trying to use Python's built-in filter function in order to extract data from certain columns in a CSV. Is this a good use of the filter function? Would I have to define the data in these columns first, or would Python somehow already know which columns contain what data?
[ "Since python boasted \"batteries included\", for most the everyday situations, someone might already provided a solution.\nCSV is one of them, there is built-in csv module \nAlso tablib is a very good 3rd-party module especially you're dealing with non-ascii data.\nFor the behaviour you described in the comment, t...
[ 7, 2 ]
[]
[]
[ "csv", "filter", "python" ]
stackoverflow_0008291568_csv_filter_python.txt
Q: Good remote application logging/monitoring software I'm sure this has already been done, but Google isn't helping me - I'm getting swamped with answers for similar but different problems: My boss has asked me to find or build a system that will log uses of our kiosk installations. We build kiosks using java, nati...
Good remote application logging/monitoring software
I'm sure this has already been done, but Google isn't helping me - I'm getting swamped with answers for similar but different problems: My boss has asked me to find or build a system that will log uses of our kiosk installations. We build kiosks using java, native c++, c#, python and using things like Unity. We saw a...
[ "I'm not sure, but I think what you're looking for is SPLUNK. This can parse almost every log and display it in a unified manner. It can listen to ports, read log files via polling and parses and indexes anything you throw at any point of time.\nYou can use this to set up you're own multi-language logging server/sy...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "c#", "c++", "java", "logging", "python" ]
stackoverflow_0008294321_c#_c++_java_logging_python.txt
Q: How to post a list of strings to GAE How to properly POST a list of strings with jQuery to Google App Engine app? I create something like this: $.post("/add", {tags:['first tag','second tag','third tag']} And then in FireBug I see it becomes something like this: tags%5B%5D=first tag&tags%5B%5D=second tag&tags%5B%...
How to post a list of strings to GAE
How to properly POST a list of strings with jQuery to Google App Engine app? I create something like this: $.post("/add", {tags:['first tag','second tag','third tag']} And then in FireBug I see it becomes something like this: tags%5B%5D=first tag&tags%5B%5D=second tag&tags%5B%5D=third tag I am not sure I send a list ...
[ "A straightforward solution would be to cast self.request.get(\"tags\") in a list() however this doesn't work with me when I send a javascript array, but maybe it would work for your case\n", "You could serialize it into a JSON string, and this string will be treated as the post data.\n$.ajax({\n type: \"POST\...
[ 0, 0 ]
[]
[]
[ "ajax", "google_app_engine", "jquery", "python" ]
stackoverflow_0004353916_ajax_google_app_engine_jquery_python.txt
Q: Unexpected end of file error while opening a file via os.system f = urllib.urlopen(url) #Download the file localFile = open(url.split('/')[-1],'w') localFile.write(f.read()) os.system("transmission %s" %localFile) Error I get is this: sh: Syntax error: end of file unexpected 512 A: Your problem might be t...
Unexpected end of file error while opening a file via os.system
f = urllib.urlopen(url) #Download the file localFile = open(url.split('/')[-1],'w') localFile.write(f.read()) os.system("transmission %s" %localFile) Error I get is this: sh: Syntax error: end of file unexpected 512
[ "Your problem might be that localfile contains some confusing characters which make the shell think it should get further information.\nTry out if\nimport subprocess\nsubprocess.call(['transmission', localFile])\n\nchanges the situation.\n\nEDIT: This is, of course, nonsense.\nimport subprocess\nsubprocess.call(['t...
[ 2, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008294842_python.txt
Q: `datetime.strftime` and `datetime.strptime` interprete %Y differently I use a statement as shown below to create a datetime object from a string: t = datetime.strptime("0023-10-10", "%Y-%m-%d") Later, somewhere in my code uses the t object and invoke the strftime method with the same format string: t.strftime("%Y-...
`datetime.strftime` and `datetime.strptime` interprete %Y differently
I use a statement as shown below to create a datetime object from a string: t = datetime.strptime("0023-10-10", "%Y-%m-%d") Later, somewhere in my code uses the t object and invoke the strftime method with the same format string: t.strftime("%Y-%m-%d") This causes a ValueError: year=23 is before 1900; the datetime strf...
[ "I like your idea of using a try..except to validate the input, since in some future version of Python, years < 1000 might be acceptable.\nThis comment in the code suggests this restriction is limited to Python's current implementation of strftime.\n\nIn Python 2.7, the exception occurs for years < 1900, but\nin Py...
[ 4, 2 ]
[]
[]
[ "datetime", "datetime_format", "python" ]
stackoverflow_0008294907_datetime_datetime_format_python.txt
Q: python: Creating a function that receives a global variable as parameter and tests if it is defined I have the following problem: In a Python module, I have a few global variables and instead of the usual try - except for each one of them, I want to test if they are defined using one general function. I thought o...
python: Creating a function that receives a global variable as parameter and tests if it is defined
I have the following problem: In a Python module, I have a few global variables and instead of the usual try - except for each one of them, I want to test if they are defined using one general function. I thought of this: def isDefined(variable): try: variable return True except Nam...
[ "Of course you have to pass your variable in as a string - else it will always \nraise a NameError. \nThe globalsbuilt-in in python returns the module dictionary - \nglobal variables are stored in it.\ndef is_defined(variable):\n return variable in globals()\n\ntomato = 42\n\nis_defined (\"tomato\")\n\n(If for ...
[ 4 ]
[]
[]
[ "function", "global_variables", "python", "try_catch" ]
stackoverflow_0008295101_function_global_variables_python_try_catch.txt
Q: Rolling Average to calculate rainfall intensity I have some real rainfall data recorded as the date and time, and the accumulated number of tips on a tipping bucket rain-gauge. The tipping bucket represents 0.5mm of rainfall. I want to cycle through the file and determine the variation in intensity (rainfall/time)...
Rolling Average to calculate rainfall intensity
I have some real rainfall data recorded as the date and time, and the accumulated number of tips on a tipping bucket rain-gauge. The tipping bucket represents 0.5mm of rainfall. I want to cycle through the file and determine the variation in intensity (rainfall/time) So I need a rolling average over multiple fixed time...
[ "I am not entirely sure what it is that you have a question about.\nDo you know how to read out the file? You can do something like:\ndata = [] # Empty list of counts\n\n# Skip the header\nlines = [line.strip() for line in open('data.txt')][2::]\n\nfor line in lines:\n print line\n date, hour, count = line.sp...
[ 1, 0 ]
[]
[]
[ "average", "python", "rolling_computation" ]
stackoverflow_0008294602_average_python_rolling_computation.txt