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: urllib.urlopen isn't working. Is there a workaround? I'm getting a getaddress error and after doing some sleuthing, it looks like it might be my corporate intranet not allowing the connection (I'm assuming due to security, although it is strange that IE works but won't allow Python to open a url). Is there a safe...
urllib.urlopen isn't working. Is there a workaround?
I'm getting a getaddress error and after doing some sleuthing, it looks like it might be my corporate intranet not allowing the connection (I'm assuming due to security, although it is strange that IE works but won't allow Python to open a url). Is there a safe way to get around this? Here's the exact error: Traceback...
[ "You probably need to fill in proxy information.\nimport urllib2\nproxy_handler = urllib2.ProxyHandler({'http': 'http://yourcorporateproxy:12345/'})\nproxy_auth_handler = urllib2.HTTPBasicAuthHandler()\nproxy_auth_handler.add_password('realm', 'host', 'username', 'password')\n\nopener = urllib2.build_opener(proxy_h...
[ 7, 4, 2, 2, 2 ]
[]
[]
[ "python", "url" ]
stackoverflow_0001076958_python_url.txt
Q: Is it possible to fetch a https page via an authenticating proxy with urllib2 in Python 2.5? I'm trying to add authenticating proxy support to an existing script, as it is the script connects to a https url (with urllib2.Request and urllib2.urlopen), scrapes the page and performs some actions based on what it has ...
Is it possible to fetch a https page via an authenticating proxy with urllib2 in Python 2.5?
I'm trying to add authenticating proxy support to an existing script, as it is the script connects to a https url (with urllib2.Request and urllib2.urlopen), scrapes the page and performs some actions based on what it has found. Initially I had hoped this would be as easy as simply adding a urllib2.ProxyHandler({"http"...
[ "You may want to look into httplib2. One of the examples claims support for SOCKS proxies if the socks module is installed.\n" ]
[ 1 ]
[]
[]
[ "https", "proxy", "python", "urllib2" ]
stackoverflow_0001152980_https_proxy_python_urllib2.txt
Q: Stopping a Long-Running Subprocess I create a subprocess using subprocess.Popen() that runs for a long time. It is called from its own thread, and the thread is blocked until the subprocess completes/returns. I want to be able to interrupt the subprocess so the process terminates when I want. Any ideas? A: I th...
Stopping a Long-Running Subprocess
I create a subprocess using subprocess.Popen() that runs for a long time. It is called from its own thread, and the thread is blocked until the subprocess completes/returns. I want to be able to interrupt the subprocess so the process terminates when I want. Any ideas?
[ "I think you're looking for Popen.terminate or .kill function. They were added in python 2.6.\n" ]
[ 4 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0001153407_python_subprocess.txt
Q: Simple python / Beautiful Soup type question I'm trying to do some simple string manipulation with the href attribute of a hyperlink extracted using Beautiful Soup: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('<a href="http://www.some-site.com/">Some Hyperlink</a>') href = soup.find("a")["href"] p...
Simple python / Beautiful Soup type question
I'm trying to do some simple string manipulation with the href attribute of a hyperlink extracted using Beautiful Soup: from BeautifulSoup import BeautifulSoup soup = BeautifulSoup('<a href="http://www.some-site.com/">Some Hyperlink</a>') href = soup.find("a")["href"] print href print href[href.indexOf('/'):] All I ge...
[ "Python strings do not have an indexOf method.\nUse href.index('/')\nhref.find('/') is similar. But find returns -1 if the string is not found, while index raises a ValueError.\nSo the correct thing is to use index (since '...'[-1] will return the last character of the string).\n", "href is a unicode string. If y...
[ 10, 0, 0 ]
[]
[]
[ "beautifulsoup", "python", "string" ]
stackoverflow_0001153167_beautifulsoup_python_string.txt
Q: Listing builtin functions and methods (Python) I have came up with this: [a for a in dir(__builtins__) if str(type(getattr(__builtins__,a))) == "<type 'builtin_function_or_method'>"] I know its ugly. Can you show me a better/more pythonic way of doing this? A: There is the inspect module: import inspect filter...
Listing builtin functions and methods (Python)
I have came up with this: [a for a in dir(__builtins__) if str(type(getattr(__builtins__,a))) == "<type 'builtin_function_or_method'>"] I know its ugly. Can you show me a better/more pythonic way of doing this?
[ "There is the inspect module:\nimport inspect\n\nfilter(inspect.isbuiltin, (member for name, member in inspect.getmembers(__builtins__)))\n\nEdit: reading the documentation a little more closely, I came up with this variant that doesn't use __getattr__\nimport inspect\n\nmembers = (member for name, member in inspec...
[ 6, 2 ]
[]
[]
[ "inspect", "introspection", "module", "python" ]
stackoverflow_0001153690_inspect_introspection_module_python.txt
Q: How would you inherit from and override the django model classes to create a listOfStringsField? I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following: models.py: from django.db import models class ListOfStringsField(???): ...
How would you inherit from and override the django model classes to create a listOfStringsField?
I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following: models.py: from django.db import models class ListOfStringsField(???): ??? class myDjangoModelClass(): myName = models.CharField(max_length=64) myFriends = ListOfSt...
[ "There's some very good documentation on creating custom fields here. \nHowever, I think you're overthinking this. It sounds like you actually just want a standard foreign key, but with the additional ability to retrieve all the elements as a single list. So the easiest thing would be to just use a ForeignKey, and ...
[ 7, 5, 5, 2 ]
[ "I think what you want is a custom model field.\n" ]
[ -1 ]
[ "django", "django_models", "inheritance", "python" ]
stackoverflow_0001126642_django_django_models_inheritance_python.txt
Q: Change python file in place I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files? Thanks! A: Say you want to split the file into N pieces, then simply start reading from the...
Change python file in place
I have a large xml file (40 Gb) that I need to split into smaller chunks. I am working with limited space, so is there a way to delete lines from the original file as I write them to new files? Thanks!
[ "Say you want to split the file into N pieces, then simply start reading from the back of the file (more or less) and repeatedly call truncate:\n\nTruncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current ...
[ 7, 2, 1, 0, 0, 0 ]
[ "Its a time to buy a new hard drive!\nYou can make backup before trying all other answers and don't get data lost :)\n" ]
[ -1 ]
[ "file", "python" ]
stackoverflow_0001145286_file_python.txt
Q: Python write to line flow Part of my script is taking values and putting them to a text file delimited by tabs. So I have this: for linesplit in fileList: for i in range (0, len(linesplit)): t.write (linesplit[i]+'\t') I get as an output in the file what I expect in the first line but in the following...
Python write to line flow
Part of my script is taking values and putting them to a text file delimited by tabs. So I have this: for linesplit in fileList: for i in range (0, len(linesplit)): t.write (linesplit[i]+'\t') I get as an output in the file what I expect in the first line but in the following lines they all start with a \t...
[ "it doesn't produce what you want because original lines (linesplit) contain end of line character (\\n) that you're not stripping. insert the following before your second for loop:\nlinesplit = linesplit.strip('\\n')\n\nThat should do the job.\n", "I'm sorry... After I hit submit it dawned on me. My last value a...
[ 6, 1, 1, 1, 1, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0001154373_file_io_python.txt
Q: How do I debug a py2exe 'application failed to initialize properly' error? I'm very new to Python in general, but I made an app in Python 2.6 / wxPython 2.8 that works perfectly when I run it through Python. But I wanted to go a step further and be able to deploy it as a Windows executable, so I've been trying out...
How do I debug a py2exe 'application failed to initialize properly' error?
I'm very new to Python in general, but I made an app in Python 2.6 / wxPython 2.8 that works perfectly when I run it through Python. But I wanted to go a step further and be able to deploy it as a Windows executable, so I've been trying out py2exe. But I haven't been able to get it to work. It would always compile an e...
[ "Note that there is a later version of the Visual C++ 2008 Redistributable package: SP1. However, both the SP1 and the earlier release don't install the DLLs into the path. As the download page says (my emphasis):\n\nThis package installs runtime\n components of C Runtime (CRT),\n Standard C++, ATL, MFC, OpenMP a...
[ 10, 0, 0, 0 ]
[]
[]
[ "py2exe", "python", "wxpython" ]
stackoverflow_0001153643_py2exe_python_wxpython.txt
Q: How to run statistics Cumulative Distribution Function and Probability Density Function using SciPy? I am new to Python and new to SciPy libraries. I wanted to take some ques from the experts here on the list before dive into SciPy world. I was wondering if some one could provide a rough guide about how to run two...
How to run statistics Cumulative Distribution Function and Probability Density Function using SciPy?
I am new to Python and new to SciPy libraries. I wanted to take some ques from the experts here on the list before dive into SciPy world. I was wondering if some one could provide a rough guide about how to run two stats functions: Cumulative Distribution Function (CDF) and Probability Distribution Function (PDF). My u...
[ "See this article: Probability distributions in SciPy.\n" ]
[ 8 ]
[]
[]
[ "probability", "python", "scipy", "statistics" ]
stackoverflow_0001154378_probability_python_scipy_statistics.txt
Q: Are there any libraries for generating Python source? I'd like to write a code generation tool that will allow me to create sourcefiles for dynamically generated classes. I can create the class and use it in code, but it would be nice to have a sourcefile both for documentation and to allow something to import. D...
Are there any libraries for generating Python source?
I'd like to write a code generation tool that will allow me to create sourcefiles for dynamically generated classes. I can create the class and use it in code, but it would be nice to have a sourcefile both for documentation and to allow something to import. Does such a thing exist? I've seen sourcecodegen, but I'd r...
[ "I'm not aware of any off-the-shelf library, but have a look at the Python templating engines Mako and Jinja2. They can both generate Python source behind the scenes (they convert text templates to Python code and then to Python bytecode).\n" ]
[ 2 ]
[]
[]
[ "code_generation", "python" ]
stackoverflow_0001155186_code_generation_python.txt
Q: Python: List initialization differences I want a list full of the same thing, where the thing will either be a string or a number. Is there a difference in the way these two list are created? Is there anything hidden that I should probably know about? list_1 = [0] * 10 list_2 = [0 for i in range(10)] Are there...
Python: List initialization differences
I want a list full of the same thing, where the thing will either be a string or a number. Is there a difference in the way these two list are created? Is there anything hidden that I should probably know about? list_1 = [0] * 10 list_2 = [0 for i in range(10)] Are there any better ways to do this same task? Thanks...
[ "It depends on whether your list elements are mutable, if they are, there'll be a difference:\n>>> l = [[]] * 10\n>>> l\n[[], [], [], [], [], [], [], [], [], []]\n>>> l[0].append(1)\n>>> l\n[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]\n>>> l = [[] for i in range(10)]\n>>> l[0].append(1)\n>>> l\n[[1], [], [], ...
[ 16, 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001154494_list_python.txt
Q: python distutils / setuptools: how to exclude a module, or honor svn:ignore flag I have a python project, 'myproject', that contains several packages. one of those packages, 'myproject.settings', contains a module 'myproject.settings.local' that is excluded from version control via 'svn:ignore' property. I would l...
python distutils / setuptools: how to exclude a module, or honor svn:ignore flag
I have a python project, 'myproject', that contains several packages. one of those packages, 'myproject.settings', contains a module 'myproject.settings.local' that is excluded from version control via 'svn:ignore' property. I would like setuptools to ignore this file when making a bdist or bdist_egg target. I have exp...
[ "I don't know if there is a regular way to do that but you you try a workaround like proposed in the How can I make setuptools ignore subversion inventory?\nsvn export your package to a temporary directory, run the setup.py from there\n" ]
[ 2 ]
[]
[]
[ "distutils", "python", "setuptools" ]
stackoverflow_0001154586_distutils_python_setuptools.txt
Q: Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match So what I'm trying to do is replace a string "keyword" with "<b>keyword</b>" in a larger string. Example: myString = "HI there. You should higher that person for the job. Hi hi." keyword = "hi" res...
Python: Replace string with prefixStringSuffix keeping original case, but ignoring case when searching for match
So what I'm trying to do is replace a string "keyword" with "<b>keyword</b>" in a larger string. Example: myString = "HI there. You should higher that person for the job. Hi hi." keyword = "hi" result I would want would be: result = "<b>HI</b> there. You should higher that person for the job. <b>Hi</b> <b>hi</b>....
[ "This ok?\n>>> import re\n>>> myString = \"HI there. You should higher that person for the job. Hi hi.\"\n>>> keyword = \"hi\"\n>>> search = re.compile(r'\\b(%s)\\b' % keyword, re.I)\n>>> search.sub('<b>\\\\1</b>', myString)\n'<b>HI</b> there. You should higher that person for the job. <b>Hi</b> <b>hi</b>.'\n\nThe ...
[ 3, 0, 0 ]
[ "Here's one suggestion, from the nitpicking committee. :-)\nmyString = \"HI there. You should higher that person for the job. Hi hi.\"\n\nmyString.replace('higher','hire')\n\n" ]
[ -1 ]
[ "nltk", "python", "regex", "replace", "search" ]
stackoverflow_0000818691_nltk_python_regex_replace_search.txt
Q: Prevent opening a second instance What's the easiest way to check if my program is already running with WxPython under Windows? Ideally, if the user tries to launch the program a second time, the focus should return to the first instance (even if the window is minimized). This question is similar but the answer is...
Prevent opening a second instance
What's the easiest way to check if my program is already running with WxPython under Windows? Ideally, if the user tries to launch the program a second time, the focus should return to the first instance (even if the window is minimized). This question is similar but the answer is for VB.NET.
[ "You should use wx.SingleInstanceChecker. See here for more information on how to use it, and this post tells about finding the running instance (you have to use pywin32 functions for this, there's nothing built into wxPython AFAIK).\n" ]
[ 3 ]
[]
[]
[ "python", "user_interface", "windows", "wxpython" ]
stackoverflow_0001155315_python_user_interface_windows_wxpython.txt
Q: How do I access an inherited class's inner class and modify it? So I have a class, specifically, this: class ProductVariantForm_PRE(ModelForm): class Meta: model = ProductVariant exclude = ("productowner","status") def clean_meta(self): if len(self.cleaned_data['meta']) == 0: ...
How do I access an inherited class's inner class and modify it?
So I have a class, specifically, this: class ProductVariantForm_PRE(ModelForm): class Meta: model = ProductVariant exclude = ("productowner","status") def clean_meta(self): if len(self.cleaned_data['meta']) == 0: raise forms.ValidationError(_(u'You have to select at least 1 ...
[ "Take a look at the Django documentation for model inheritance here. From that page:\n\nWhen an abstract base class is\n created, Django makes any Meta inner\n class you declared in the base class\n available as an attribute. If a child\n class does not declare its own Meta\n class, it will inherit the parent...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001155351_django_python.txt
Q: Python accessing multiple webpages at once I have a tkinter GUI that downloads data from multiple websites at once. I run a seperate thread for each download (about 28). Is that too much threads for one GUI process? because it's really slow, each individual page should take about 1 to 2 seconds but when all are ru...
Python accessing multiple webpages at once
I have a tkinter GUI that downloads data from multiple websites at once. I run a seperate thread for each download (about 28). Is that too much threads for one GUI process? because it's really slow, each individual page should take about 1 to 2 seconds but when all are run at once it takes over 40 seconds. Is there any...
[ "It's probably the GIL (global interpreter lock) that gets in your way. Python has some performance problems with many threads.\nYou could try twisted.web.getPage (see http://twistedmatrix.com/projects/core/documentation/howto/async.html a bit down the page).\nI don't have benchmarks for that.\nBut taking the examp...
[ 2, 1, 0 ]
[]
[]
[ "download", "multithreading", "python", "tkinter", "user_interface" ]
stackoverflow_0001155404_download_multithreading_python_tkinter_user_interface.txt
Q: Python: Importing pydoc and then using it natively? I know how to use pydoc from the command line. However, because of complicated environmental setup, it would be preferable to run it within a python script as a native API call. That is, my python runner looks a bit like this: import pydoc pydoc.generate_html_d...
Python: Importing pydoc and then using it natively?
I know how to use pydoc from the command line. However, because of complicated environmental setup, it would be preferable to run it within a python script as a native API call. That is, my python runner looks a bit like this: import pydoc pydoc.generate_html_docs_for(someFile) However, it's not clear to me from the ...
[ "Do you mean something like this?\n>>> import pydoc\n>>> pydoc.writedoc('sys')\nwrote sys.html\n>>>\n\n" ]
[ 8 ]
[]
[]
[ "pydoc", "python" ]
stackoverflow_0001155853_pydoc_python.txt
Q: Getting rows from XML using XPath and Python I'd like to get some rows (z:row rows) from XML using: <rs:data> <z:row Attribute1="1" Attribute2="1" /> <z:row Attribute1="2" Attribute2="2" /> <z:row Attribute1="3" Attribute2="3" /> <z:row Attribute1="4" Attribute2="4" /> <z:row Attribute1="5" Att...
Getting rows from XML using XPath and Python
I'd like to get some rows (z:row rows) from XML using: <rs:data> <z:row Attribute1="1" Attribute2="1" /> <z:row Attribute1="2" Attribute2="2" /> <z:row Attribute1="3" Attribute2="3" /> <z:row Attribute1="4" Attribute2="4" /> <z:row Attribute1="5" Attribute2="5" /> <z:row Attribute1="6" Attribute...
[ "If you don't want to figure out setting up namespaces properly, you can ignore them like this:\nXPathGet(\"//*[local-name() = 'row']\")\n\nWhich selects every node whose name (without namespace) is row.\n", "The \"z:\" prefixes represent an XML namespace. you'll need to find out what that namespace is, and do th...
[ 1, 1, 1 ]
[]
[]
[ "python", "xml", "xpath" ]
stackoverflow_0001155566_python_xml_xpath.txt
Q: Algorithm for BFS traveral of an acylic directed graph I'm looking for an elegant Python program that does a BFS traveral of a DAG: Node A is connected to B (A->B) if A "depends on" B (think of python package Foo "depending upon" Bar: Foo->Bar). In a graph of about 7000 such nodes, I want to sort all nodes such t...
Algorithm for BFS traveral of an acylic directed graph
I'm looking for an elegant Python program that does a BFS traveral of a DAG: Node A is connected to B (A->B) if A "depends on" B (think of python package Foo "depending upon" Bar: Foo->Bar). In a graph of about 7000 such nodes, I want to sort all nodes such that for all possible (i, j) where 1>=i<j<=7000 .. depends(Ni...
[ "If I am reading the question correctly, it looks like you want a topological sort. The most efficient algorithm (O(V+E)) for doing this was proposed by Tarjan, and a Python implementation can be found here.\nOff-topic, but it seems as though your package dependency analogy is reversed; I would think that \"A depe...
[ 5 ]
[]
[]
[ "algorithm", "dependencies", "graph", "python", "traversal" ]
stackoverflow_0001156175_algorithm_dependencies_graph_python_traversal.txt
Q: Composable Regexp in Python Often, I would like to build up complex regexps from simpler ones. The only way I'm currently aware of of doing this is through string operations, e.g.: Year = r'[12]\d{3}' Month = r'Jan|Feb|Mar' Day = r'\d{2}' HourMins = r'\d{2}:\d{2}' Date = r'%s %s, %s, %s' % (Month, Day, Year, Hour...
Composable Regexp in Python
Often, I would like to build up complex regexps from simpler ones. The only way I'm currently aware of of doing this is through string operations, e.g.: Year = r'[12]\d{3}' Month = r'Jan|Feb|Mar' Day = r'\d{2}' HourMins = r'\d{2}:\d{2}' Date = r'%s %s, %s, %s' % (Month, Day, Year, HourMins) DateR = re.compile(Date) I...
[ "You can use Python's formatting syntax for this:\ntypes = {\n \"year\": r'[12]\\d{3}',\n \"month\": r'(Jan|Feb|Mar)',\n \"day\": r'\\d{2}',\n \"hourmins\": r'\\d{2}:\\d{2}',\n}\nimport re\nDate = r'%(month)s %(day)s, %(year)s, %(hourmins)s' % types\nDateR = re.compile(Dat...
[ 4, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001156030_python_regex.txt
Q: Latin-1 and the unicode factory in Python I have a Python 2.6 script that is gagging on special characters, encoded in Latin-1, that I am retrieving from a SQL Server database. I would like to print these characters, but I'm somewhat limited because I am using a library that calls the unicode factory, and I don't ...
Latin-1 and the unicode factory in Python
I have a Python 2.6 script that is gagging on special characters, encoded in Latin-1, that I am retrieving from a SQL Server database. I would like to print these characters, but I'm somewhat limited because I am using a library that calls the unicode factory, and I don't know how to make Python use a codec other than ...
[ "Add this at the beginning of the module:\n# coding: latin1\n\nOr decode the string to Unicode yourself.\n[Edit]\nIt's been a while since I played with Unicode, but hopefully this example will show how to convert from Latin1 to Unicode:\n>>> s = u'ééé'.encode('latin1') # a string you may get from the database\n>>> ...
[ 7, 2, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0001155903_python_unicode.txt
Q: Import Dynamically Created Python Files I am creating python files through the course of running a python program. I then want to import these files and run functions that were defined within them. The files I am creating are not stored within my path variables and I'd prefer to keep it that way. Originally I was ...
Import Dynamically Created Python Files
I am creating python files through the course of running a python program. I then want to import these files and run functions that were defined within them. The files I am creating are not stored within my path variables and I'd prefer to keep it that way. Originally I was calling the execFile(<script_path>) function ...
[ "Use\nm = __import__(\"File\")\n\nThis is essentially the same as doing\nimport File\nm = File\n\n", "If I understand correctly your remarks to man that the file isn't in sys.path and you'd rather keep it that way, this would still work:\nimport imp\n\nfileobj, pathname, description = imp.find_module('thefile', '...
[ 5, 3 ]
[]
[]
[ "import", "python" ]
stackoverflow_0001156356_import_python.txt
Q: Python: re.find longest sequence I have a string that is randomly generated: polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine" I'd like to find the longest sequence of "diNCO diol" and the longest of "diNCO diamine". So in the case above the longest "diNCO diol" sequence is ...
Python: re.find longest sequence
I have a string that is randomly generated: polymer_str = "diol diNCO diamine diNCO diamine diNCO diamine diNCO diol diNCO diamine" I'd like to find the longest sequence of "diNCO diol" and the longest of "diNCO diamine". So in the case above the longest "diNCO diol" sequence is 1 and the longest "diNCO diamine" is 3...
[ "Expanding on Ealdwulf's answer:\nDocumentation on re.findall can be found here.\ndef getLongestSequenceSize(search_str, polymer_str):\n matches = re.findall(r'(?:\\b%s\\b\\s?)+' % search_str, polymer_str)\n longest_match = max(matches)\n return longest_match.count(search_str)\n\nThis could be written as o...
[ 10, 3, 3, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001155376_python_regex.txt
Q: Read Block Data in Python? I have a problem reading data file: /// * ABC Names A-06,B-18, * Data 1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01, 1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02, 2.592e-01, 2.513e-01, 2.242e-01, 2.620e...
Read Block Data in Python?
I have a problem reading data file: /// * ABC Names A-06,B-18, * Data 1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01, 1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02, 2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139...
[ "Here's a complete guess at some code that might load the type of file this is an example of, but which should be a little robust: \nf = open(\"mdata.txt\")\n\ndata_dict = {}\nsection = None\ndata_for_section = \"\"\nfor line in f:\n line = line.strip() #remove whitespace at start and end\n\n if section != No...
[ 2, 1, 0, 0 ]
[ "Without any other information...\ndata = [\n1.727e-01, 1.258e-01, 2.724e-01, 2.599e-01,-3.266e-01,-9.425e-02,-6.213e-02, 1.479e-01,\n1.219e-01, 1.174e-01, 2.213e-01, 2.875e-01,-2.306e-01,-3.900e-03,-5.269e-02, 7.420e-02,\n2.592e-01, 2.513e-01, 2.242e-01, 2.620e-01,-1.346e-01,-6.844e-02,-4.139e-02, 9.502e-02,\n1.98...
[ -1 ]
[ "file", "python" ]
stackoverflow_0001141101_file_python.txt
Q: How to a query a set of objects and return a set of object specific attribute in SQLachemy/Elixir? Suppose that I have a table like: class Ticker(Entity): ticker = Field(String(7)) tsdata = OneToMany('TimeSeriesData') staticdata = OneToMany('StaticData') How would I query it so that it returns a set o...
How to a query a set of objects and return a set of object specific attribute in SQLachemy/Elixir?
Suppose that I have a table like: class Ticker(Entity): ticker = Field(String(7)) tsdata = OneToMany('TimeSeriesData') staticdata = OneToMany('StaticData') How would I query it so that it returns a set of Ticker.ticker? I dig into the doc and seems like select() is the way to go. However I am not too famil...
[ "Not sure what you're after exactly but to get an array with all 'Ticker.ticker' values you would do this:\n[instance.ticker for instance in Ticker.query.all()]\n\nWhat you really want is probably the Elixir getting started tutorial - it's good so take a look!\nUPDATE 1: Since you have a database, the best way to f...
[ 0 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0001156962_python_sql_sqlalchemy.txt
Q: cx_Oracle and the data source paradigm There is a Java paradigm for database access implemented in the Java DataSource. This object create a useful abstraction around the creation of database connections. The DataSource object keeps database configuration, but will only create database connections on request. This...
cx_Oracle and the data source paradigm
There is a Java paradigm for database access implemented in the Java DataSource. This object create a useful abstraction around the creation of database connections. The DataSource object keeps database configuration, but will only create database connections on request. This is allows you to keep all database configur...
[ "You'll find relevant information of how to access databases in Python by looking at PEP-249: Python Database API Specification v2.0. cx_Oracle conforms to this specification, as do many database drivers for Python.\nIn this specification a Connection object represents a database connection, but there is no built-i...
[ 3, 1, 0, 0 ]
[]
[]
[ "cx_oracle", "database", "oracle", "python" ]
stackoverflow_0001148472_cx_oracle_database_oracle_python.txt
Q: Python: question about parsing human-readable text I'm parsing human-readable scientific text that is mostly in the field of chemistry. What I'm interested in is breaking the text into a list of words, scientific terms (more on that below), and punctuation marks. So for example, I expect the text "hello, world." t...
Python: question about parsing human-readable text
I'm parsing human-readable scientific text that is mostly in the field of chemistry. What I'm interested in is breaking the text into a list of words, scientific terms (more on that below), and punctuation marks. So for example, I expect the text "hello, world." to break into 4 tokens: 1) "hello"; 2) comma; 3) "world" ...
[ "This will solve your current example. It can be tweaked for a larger data set.\nimport re\nsplitterForIndexing = re.compile(r\"(?:[a-zA-Z0-9\\-,]+[a-zA-Z0-9\\-])|(?:[,.])\")\nsource = \"Hello. 1-methyl-4-phenylpyridinium is ultra-bad. However, 1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine is worse.\"\nprint \"\\n\"...
[ 2, 0, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0001153183_parsing_python.txt
Q: How to update an older C extension for Python 2.x to Python 3.x I'm wanting to use an extension for Python that I found here, but I'm using Python 3.1 and when I attempt to compile the C extension included in the package (_wincon), it does not compile due to all the syntax errors. Unfortunately, it was written for...
How to update an older C extension for Python 2.x to Python 3.x
I'm wanting to use an extension for Python that I found here, but I'm using Python 3.1 and when I attempt to compile the C extension included in the package (_wincon), it does not compile due to all the syntax errors. Unfortunately, it was written for 2.x versions of Python and as such includes methods such as PyMember...
[ "I don't believe there is any magic bullet to make the C sources for a Python extension coded for some old-ish version of Python 2, into valid C sources for one coded for Python 3 -- it takes understanding of C and of how the C API has changed, and of what exactly the extension is doing in each part of its code. Be...
[ 7 ]
[]
[]
[ "c", "console", "python", "windows" ]
stackoverflow_0001157134_c_console_python_windows.txt
Q: Scrolling through a `wx.ScrolledPanel` with the mouse wheel and arrow keys In my wxPython application I've created a wx.ScrolledPanel, in which there is a big wx.StaticBitmap that needs to be scrolled. The scroll bars do appear and I can scroll with them, but I'd also like to be able to scroll with the mouse wheel...
Scrolling through a `wx.ScrolledPanel` with the mouse wheel and arrow keys
In my wxPython application I've created a wx.ScrolledPanel, in which there is a big wx.StaticBitmap that needs to be scrolled. The scroll bars do appear and I can scroll with them, but I'd also like to be able to scroll with the mouse wheel and the arrow keys on the keyboard. It would be nice if the "Home", "Page Up", ...
[ "Problem is on window Frame gets the focus and child panel is not getting the Focus (on ubuntu linux it is working fine). Workaround can be as simple as to redirect Frame focus event to set focus to panel e.g.\nimport wx, wx.lib.scrolledpanel\n\nclass MyFrame(wx.Frame):\n def __init__(self, *args, **kwargs):\n ...
[ 3, 0 ]
[]
[]
[ "python", "scroll", "user_interface", "wxpython" ]
stackoverflow_0001147581_python_scroll_user_interface_wxpython.txt
Q: python function for retrieving key and encryption M2Crypto package is not showing the 'recipient_public_key.pem' file at linux terminal. How do I get/connect with recipient public key. Exactly, I need to check how can I open this file through linux commands. import M2Crypto def encrypt(): recip = M2Crypto.RSA....
python function for retrieving key and encryption
M2Crypto package is not showing the 'recipient_public_key.pem' file at linux terminal. How do I get/connect with recipient public key. Exactly, I need to check how can I open this file through linux commands. import M2Crypto def encrypt(): recip = M2Crypto.RSA.load_pub_key(open('recipient_public_key.pem','rb').read...
[ "I have never used M2Crypto, but according to the API documentation, load_pub_key expects the file name as the argument, not the key itself. Try\nrecip = M2Crypto.RSA.load_pub_key('recipient_public_key.pem')\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0001157442_python.txt
Q: Seeding random in django In a view in django I use random.random(). How often do I have to call random.seed()? One time for every request? One time for every season? One time while the webserver is running? A: Don't set the seed. The only time you want to set the seed is if you want to make sure that the same ev...
Seeding random in django
In a view in django I use random.random(). How often do I have to call random.seed()? One time for every request? One time for every season? One time while the webserver is running?
[ "Don't set the seed.\nThe only time you want to set the seed is if you want to make sure that the same events keep happening. For example, if you don't want to let players cheat in your game you can save the seed, and then set it when they load their game. Then no matter how many times they save + reload, it still ...
[ 4, 3, 0 ]
[]
[]
[ "django", "django_views", "python", "random" ]
stackoverflow_0001156511_django_django_views_python_random.txt
Q: Updated (current) recommendation on Rails versus Django? (Disclaimer: I asked this question yesterday on Hacker News. While responses were good, there was a notable lack of technical discussion and more of a "you should use rails because that's what you know". Since Joel and Jeff state clearly they don't mind repo...
Updated (current) recommendation on Rails versus Django?
(Disclaimer: I asked this question yesterday on Hacker News. While responses were good, there was a notable lack of technical discussion and more of a "you should use rails because that's what you know". Since Joel and Jeff state clearly they don't mind reposts of questions from other sites...and since I really enjoy t...
[ "[Repost from HN, same link as question, as I would like to hear your(you did not reply on HN) and SO response.]\nI am obviously biased, as I run a django development company. That said, Ill start with answering the drawbacks of Django,\n\nLearning curve.:\nNot more than any other framework. Plus the Documentation ...
[ 8, 7, 6, 6 ]
[]
[]
[ "django", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0001153096_django_python_ruby_ruby_on_rails.txt
Q: Forced to use inconsistent file import paths in Python (/Django) I've recently been having some problems with my imports in Django (Python)... It's better to explain using a file diagram: - project/ - application/ - file.py - application2/ - file2.py In project/application/file.py I have t...
Forced to use inconsistent file import paths in Python (/Django)
I've recently been having some problems with my imports in Django (Python)... It's better to explain using a file diagram: - project/ - application/ - file.py - application2/ - file2.py In project/application/file.py I have the following: def test_method(): return "Working" The problem occ...
[ "For import to find a module, it needs to either be in sys.path. Usually, this includes \"\", so it searches the current directory. If you load \"application\" from project, it'll find it, since it's in the current directory.\nOkay, that's the obvious stuff. A confusing bit is that Python remembers which modules...
[ 4, 2, 0 ]
[]
[]
[ "django", "import", "path", "python" ]
stackoverflow_0001156515_django_import_path_python.txt
Q: Syncing Django users with Google Apps without monkeypatching I am writing a Django app, and I would like an account to be created on our Google Apps hosted email using the Provisioning API whenever an account is created locally. I would solely use signals, but since I would like the passwords to be synchronized ac...
Syncing Django users with Google Apps without monkeypatching
I am writing a Django app, and I would like an account to be created on our Google Apps hosted email using the Provisioning API whenever an account is created locally. I would solely use signals, but since I would like the passwords to be synchronized across sites, I have monkeypatched User.objects.create_user and User...
[ "Have you considered subclassing the User model? This may create a different set of problems, and is only available with newer releases (not sure when the change went in, I'm on trunk).\n", "Subclassing seems the best route, as long as you can change all of your code to use the new class. I think that's supported...
[ 1, 0, 0, 0 ]
[]
[]
[ "django", "google_apps", "monkeypatching", "python" ]
stackoverflow_0000429443_django_google_apps_monkeypatching_python.txt
Q: Problem with recursive search of xml document using python I am trying to write a function that will take an xml object, an arbitrary number of tags, defined by tuples containing a tag name, attribute and attribute value (e.g ('tag1', 'id', '1')) and return the most specific node possible. My code is below: from ...
Problem with recursive search of xml document using python
I am trying to write a function that will take an xml object, an arbitrary number of tags, defined by tuples containing a tag name, attribute and attribute value (e.g ('tag1', 'id', '1')) and return the most specific node possible. My code is below: from xml.dom import minidom def _search(object, *pargs): if len(...
[ "Shouldn't you be inserting a return in front of your recursive calls to _search? The way you have it now, some exit paths from _search don't have a return statement, so they will return None - which leads to the exception you're seeing.\n", "I assume you're using http://www.eggheadcafe.com/community/aspnet/17/10...
[ 2, 2 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0001157768_python_xml.txt
Q: Django Double Escaping Quotes etc I'm experiencing what I would consider somewhat strange behavior. Specifically if I have a string like this: 1984: Curriculum Unit by Donald R. Hogue, Center for Learning, George Orwell "A center for learning publication"--Cover. It results in the fo...
Django Double Escaping Quotes etc
I'm experiencing what I would consider somewhat strange behavior. Specifically if I have a string like this: 1984: Curriculum Unit by Donald R. Hogue, Center for Learning, George Orwell "A center for learning publication"--Cover. It results in the following after being auto-escaped by the...
[ "You shouldn't have to think about escaping in 1.0 . If you have a template\n<html>\n <body>\n & == &amp; in HTML\n </body>\n</html>\n\nIt should encode the & to &amp; before printing. \nIf you have a variable\n<html>\n <body>\n {{ msg }}\n </body>\n</html>\n\nand \ndef view(request) :\n msg = \"& == &amp; in HT...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001157725_django_python.txt
Q: Creating DateTime from user inputted date I'm pretty new to Python and App Engine, but what I'm trying to do is store a model which contains a DateProperty, and that DateProperty is populated with a Date entered by the user in a web form. I've got the model of: class Memory(db.Model): author = db.UserProperty(...
Creating DateTime from user inputted date
I'm pretty new to Python and App Engine, but what I'm trying to do is store a model which contains a DateProperty, and that DateProperty is populated with a Date entered by the user in a web form. I've got the model of: class Memory(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=Tru...
[ "You were right with strptime:\n>>> dt = time.strptime('2009-07-21', '%Y-%m-%d')\n>>> dt\n time.struct_time(tm_year=2009, tm_mon=7, tm_mday=21, tm_hour=0, tm_min=0, tm_sec\n =0, tm_wday=1, tm_yday=202, tm_isdst=-1)\n>>>\n\nYou got struct that can be used by other functions. For example display date in M/D/Y c...
[ 0, 0, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0001157794_datetime_python.txt
Q: Qt GraphicsScene constantly redrawing I've written my own implementation of QGraphicsView.drawItems(), to fit the needs of my application. The method as such works fine, however, it is called repeatedly, even if it does not need to be redrawn. This causes the application to max out processor utilization. Do I need...
Qt GraphicsScene constantly redrawing
I've written my own implementation of QGraphicsView.drawItems(), to fit the needs of my application. The method as such works fine, however, it is called repeatedly, even if it does not need to be redrawn. This causes the application to max out processor utilization. Do I need to somehow signal that the drawing is fini...
[ "I think this causes the problem:\nitem.setPen(markupColors[drawable.source])\n\nIf you take a look at the source code:\nvoid QAbstractGraphicsShapeItem::setPen(const QPen &pen)\n{\n Q_D(QAbstractGraphicsShapeItem);\n prepareGeometryChange();\n d->pen = pen;\n d->boundingRect = QRectF();\n update();\...
[ 0 ]
[]
[]
[ "python", "qt" ]
stackoverflow_0001157773_python_qt.txt
Q: Which library should I use to write an XLS from Linux / Python? I'd love a good native Python library to write XLS, but it doesn't seem to exist. Happily, Jython does. So I'm trying to decide between jexcelapi and Apache HSSF: http://www.andykhan.com/jexcelapi/tutorial.html#writing http://poi.apache.org/hssf/quic...
Which library should I use to write an XLS from Linux / Python?
I'd love a good native Python library to write XLS, but it doesn't seem to exist. Happily, Jython does. So I'm trying to decide between jexcelapi and Apache HSSF: http://www.andykhan.com/jexcelapi/tutorial.html#writing http://poi.apache.org/hssf/quick-guide.html (I can't use COM automation because I'm not on Windows, ...
[ "What's wrong with xlwt?\n", "+1 for xlwt. See Matt Harrison's blog for posts on how to use xlwt and how to deal with large spreadsheets. Also, check out the python-excel group on Google \"If you use Python to read, write or otherwise manipulate Excel files\".\n", "I'd use JExcelApi, but only because I've used ...
[ 18, 3, 1, 1, 0 ]
[]
[]
[ "hssf", "java", "jexcelapi", "python", "xls" ]
stackoverflow_0000245225_hssf_java_jexcelapi_python_xls.txt
Q: How can I parse marked up text for further processing? See updated input and output data at Edit-1. What I am trying to accomplish is turning + 1 + 1.1 + 1.1.1 - 1.1.1.1 - 1.1.1.2 + 1.2 - 1.2.1 - 1.2.2 - 1.3 + 2 - 3 into a python data structure such as [{'1': [{'1.1': {'1.1.1': ['1.1.1.1', '1.1.1...
How can I parse marked up text for further processing?
See updated input and output data at Edit-1. What I am trying to accomplish is turning + 1 + 1.1 + 1.1.1 - 1.1.1.1 - 1.1.1.2 + 1.2 - 1.2.1 - 1.2.2 - 1.3 + 2 - 3 into a python data structure such as [{'1': [{'1.1': {'1.1.1': ['1.1.1.1', '1.1.1.2']}, '1.2': ['1.2.1', '1.2.2']}, '1.3'], '2': {}}, ['3',]]...
[ "Edit: thanks to the clarification and change in the spec I've edited my code, still using an explicit Node class as an intermediate step for clarity -- the logic is to turn the list of lines into a list of nodes, then turn that list of nodes into a tree (by using their indent attribute appropriately), then print t...
[ 6, 1, 1, 0 ]
[]
[]
[ "lexer", "markdown", "markup", "parsing", "python" ]
stackoverflow_0001090280_lexer_markdown_markup_parsing_python.txt
Q: django - QuerySet recursive order by method I may have a classic problem, but I didn't find any snippet allowing me to do it. I want to sort this model by its fullname. class ProductType(models.Model): parent = models.ForeignKey('self', related_name='child_set') name = models.CharField(max_length=128...
django - QuerySet recursive order by method
I may have a classic problem, but I didn't find any snippet allowing me to do it. I want to sort this model by its fullname. class ProductType(models.Model): parent = models.ForeignKey('self', related_name='child_set') name = models.CharField(max_length=128) def get_fullname(self): if self.pa...
[ "I would probably create a denomalised field and order on that. Depending on your preferences you might wnat to override .save(), or use a signal to poplate the denormalised field.\nclass ProductType(models.Model):\n parent = models.ForeignKey('self', related_name='child_set')\n name = models.CharField(...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001158267_django_python.txt
Q: backport function modifiers to python2.1 I have some code I developed in python 2.4++ and you bet, I have to backport it to python 2.1! function decorators were so attractive that I have used @classmethod at a few spots, without taking notice of the fact that it is only available starting at version 2.4. the same...
backport function modifiers to python2.1
I have some code I developed in python 2.4++ and you bet, I have to backport it to python 2.1! function decorators were so attractive that I have used @classmethod at a few spots, without taking notice of the fact that it is only available starting at version 2.4. the same functionality is offered by function modifier...
[ "Just like in my old recipe for 2.1 staticmethod:\nclass staticmethod:\n def __init__(self, thefunc): self.f = thefunc\n def __call__(self, *a, **k): return self.f(*a, **k)\n\nyou should be able to do a 2.1 classmethod as:\nclass classmethod:\n def __init__(self, thefunc): self.f = thefunc\n def __call_...
[ 2, 1 ]
[]
[]
[ "backport", "python", "syntax" ]
stackoverflow_0001159023_backport_python_syntax.txt
Q: How to replace a column using Python's built-in .csv writer module? I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I figured I'd try to implement the solution in python. I'm having trouble...
How to replace a column using Python's built-in .csv writer module?
I need to do a find and replace (specific to one column of URLs) in a huge Excel .csv file. Since I'm in the beginning stages of trying to teach myself a scripting language, I figured I'd try to implement the solution in python. I'm having trouble with the "replace" part of the solution. I've read the official csv modu...
[ "The reason you're getting an error is that the writer doesn't have data to iterate over. You're supposed to give it the data - presumably, you'd have some sort of list or generator that produces the rows to write out.\nI'd suggest just combining the two loops, like so:\nfor row in reader:\n row[-1] = row[-1].re...
[ 6, 1, 0 ]
[]
[]
[ "csv", "file_io", "python" ]
stackoverflow_0001019200_csv_file_io_python.txt
Q: How do I disable PythonWin's “Redirecting output to win32trace remote collector” feature without uninstalling PythonWin? When I run a wxPython application, it prints the string “Redirecting output to win32trace remote collector”and I must open PythonWin's trace collector tool to view that trace output. Since I'm n...
How do I disable PythonWin's “Redirecting output to win32trace remote collector” feature without uninstalling PythonWin?
When I run a wxPython application, it prints the string “Redirecting output to win32trace remote collector”and I must open PythonWin's trace collector tool to view that trace output. Since I'm not interested in collecting this output, how should I disable this feature?
[ "You can even pass that when you instantiate your wx.App():\nif __name__ == \"__main__\":\n app = wx.App(redirect=False) #or 0\n app.MainLoop()\n\nwxPython wx.App docs\n", "This message deceived me into thinking win32trace was preventing me from seeing uncaught exceptions in the regular console (of my IDE)....
[ 2, 1, 1 ]
[]
[]
[ "python", "windows", "wxpython" ]
stackoverflow_0000306901_python_windows_wxpython.txt
Q: Where to put message queue consumer in Django? I'm using Carrot for a message queue in a Django project and followed the tutorial, and it works fine. But the example runs in the console, and I'm wondering how I apply this in Django. The publisher class I'm calling from one of my models in models.py, so that's OK. ...
Where to put message queue consumer in Django?
I'm using Carrot for a message queue in a Django project and followed the tutorial, and it works fine. But the example runs in the console, and I'm wondering how I apply this in Django. The publisher class I'm calling from one of my models in models.py, so that's OK. But I have no idea where to put the consumer class. ...
[ "The consumer is simply a long running script in the example you cite from the tutorial. It pops a message from the queue, does something, then calls wait and essentially goes to sleep until another message comes in. \nThis script could just be running at the console under your account or configured as a unix dae...
[ 5, 0 ]
[]
[]
[ "amqp", "django", "message_queue", "python", "rabbitmq" ]
stackoverflow_0001112645_amqp_django_message_queue_python_rabbitmq.txt
Q: Where are Man -pages for the module MySQLdb in Python? I would like to get Python's documentation for MySQLdb in Man -format such that I can read them in terminal. Where are Man -pages for MySQLdb in Python? A: Have you tried using pydoc? Try running the following command. pydoc MySQLdb That should give you so...
Where are Man -pages for the module MySQLdb in Python?
I would like to get Python's documentation for MySQLdb in Man -format such that I can read them in terminal. Where are Man -pages for MySQLdb in Python?
[ "Have you tried using pydoc? Try running the following command.\npydoc MySQLdb\n\nThat should give you something close to what you're looking for.\n", "You may have to convert it yourself. MySQLdb doesn't come with man pages (as far as I know) but the documentation can be accessed e.g. from the project page. The...
[ 2, 1 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001160345_mysql_python.txt
Q: redirect browser in SimpleHTTPServer.py? I am partially through implementing the functionality of SimpleHTTPServer.py in Scheme. I am having some good fun with HTTP request/response mechanism. While going through the above file, I came across this- " # redirect browser - doing basically what apache does" in the co...
redirect browser in SimpleHTTPServer.py?
I am partially through implementing the functionality of SimpleHTTPServer.py in Scheme. I am having some good fun with HTTP request/response mechanism. While going through the above file, I came across this- " # redirect browser - doing basically what apache does" in the code". Why is this redirection necessary in suc...
[ "It simplifies things to treat the trailing / as irrelevant when the user does a GET on a directory, so that (say) http://www.foo.com/bar and http://www.foo.com/bar/ have exactly the same effect. Simplest (though not fastest, see Souders' books;-) is to have the former cause a redirect to the latter.\n", "Imagin...
[ 3, 3 ]
[]
[]
[ "python", "racket", "scheme" ]
stackoverflow_0001160329_python_racket_scheme.txt
Q: How to use a custom site-package using pth-files for Python 2.6? I'm trying to setup a custom site-package directory (Python 2.6 on Windows Vista). For example the directory should be '~\lib\python2.6' ( C:\Users\wierob\lib\python2.6). Hence calling 'setup.py install' should copy packages to C:\Users\wierob\lib\py...
How to use a custom site-package using pth-files for Python 2.6?
I'm trying to setup a custom site-package directory (Python 2.6 on Windows Vista). For example the directory should be '~\lib\python2.6' ( C:\Users\wierob\lib\python2.6). Hence calling 'setup.py install' should copy packages to C:\Users\wierob\lib\python2.6. Following the instructions here: I've created a pth-file in s...
[ "The pth-file seems to be ignored if encoded in UTF-8 with BOM.\nSaving the pth-file in ANSI or UTF-8 without BOM works.\n", "According to documentation you should put paths to .pth file so maybe entering:\nC:\\Users\\wierob\\lib\\python2.6\n\nwill work\n" ]
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001159650_python.txt
Q: Creating a board game simulator (Python?) (Pygame?) I've decided to start working on programming an old favorite of mine. I've never done a game before and also never done a large project in Python. The game is the old Avalon Hill game Russian Campaign I've been playing with PyGame a little bit and was wondering i...
Creating a board game simulator (Python?) (Pygame?)
I've decided to start working on programming an old favorite of mine. I've never done a game before and also never done a large project in Python. The game is the old Avalon Hill game Russian Campaign I've been playing with PyGame a little bit and was wondering if there were reasons not to try to do this with PyGame an...
[ "Separate the \"back-end\" engine (which keeps track of board state, receives move orders from front-ends, generates random numbers to resolve battles, sends updates to front-ends, deals with saving and restoring specific games, ...) from \"front-end\" ones, which basically supply user interfaces for all of this.\n...
[ 25, 2 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0001157245_pygame_python.txt
Q: How to Replace a column in a CSV file in Python? I have 2 csv files. I need to replace a column in one file with a column from the other file but they have to stay sorted according to an ID column. Here's an example: file1: ID, transect, 90mdist ...
How to Replace a column in a CSV file in Python?
I have 2 csv files. I need to replace a column in one file with a column from the other file but they have to stay sorted according to an ID column. Here's an example: file1: ID, transect, 90mdist 1, a, 10, ...
[ "The CSV Module in the Python Library is what you need here.\nIt allows you to read and write CSV files, treating lines a tuples or lists of items.\nJust read in the file with the corrected values, store the in a dictionary keyed with the line's ID.\nThen read in the second file, replacing the relevant column with ...
[ 7, 2, 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0001159524_csv_python.txt
Q: models.py getting huge, what is the best way to break it up? Directions from my supervisor: "I want to avoid putting any logic in the models.py. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes that use the models classes, or wrap them." I feel li...
models.py getting huge, what is the best way to break it up?
Directions from my supervisor: "I want to avoid putting any logic in the models.py. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes that use the models classes, or wrap them." I feel like this is the wrong way to go. I feel that keeping logic out of t...
[ "It's natural for model classes to contain methods to operate on the model. If I have a Book model, with a method book.get_noun_count(), that's where it belongs--I don't want to have to write \"get_noun_count(book)\", unless the method actually intrinsically belongs with some other package. (It might--for example...
[ 115, 64, 6 ]
[]
[]
[ "django", "django_models", "models", "python" ]
stackoverflow_0001160579_django_django_models_models_python.txt
Q: Can you point me to a large Python open-source project? I would like to see how a large (>40 developers) project done with Python looks like: how the code looks like what folder structure they use what tools they use how they set up the collaboration environment what kind of documentation they provide It doesn'...
Can you point me to a large Python open-source project?
I would like to see how a large (>40 developers) project done with Python looks like: how the code looks like what folder structure they use what tools they use how they set up the collaboration environment what kind of documentation they provide It doesn't matter what type of software it is (server, client, applica...
[ "The Django web framework.\nAlso, Twisted Matrix.\nI am not sure about the exact number of developers, though.\n", "Trac - which coincidentally is also usable for the collaboration environment part of your question.\n", "\nRoundup - Issue Tracker\nTwisted - Network Programming Framework\nZenoss - Network Monito...
[ 11, 9, 6, 6, 5, 3, 3, 2, 2, 1 ]
[]
[]
[ "open_source", "python" ]
stackoverflow_0001161339_open_source_python.txt
Q: how do I read everything currently in a subprocess.stdout pipe and then return? I'm using python's subprocess module to interact with a program via the stdin and stdout pipes. If I call the subprocesses readline() on stdout, it hangs because it is waiting for a newline. How can I do a read of all the characters i...
how do I read everything currently in a subprocess.stdout pipe and then return?
I'm using python's subprocess module to interact with a program via the stdin and stdout pipes. If I call the subprocesses readline() on stdout, it hangs because it is waiting for a newline. How can I do a read of all the characters in the stdout pipe of a subprocess instance? If it matters, I'm running in Linux.
[ "Someone else appears to have had the same problem, you can see the related discussion here. \nIf you are running on Linux you can use select to wait for input on the process' stdout. Alternatively you change the mode of the process' stdout to non-blocking using\nimport fcntl, os \nfcntl.fcntl(your_process.stdout, ...
[ 4, 2 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0001161580_linux_python.txt
Q: python docstrings ok so I decided to learn python (perl, c, c++, java, objective-c, ruby and a bit of erlang and scala under my belt). and I keep on getting the following error when I try executing this: Tue Jul 21{stevenhirsch@steven-hirschs-macbook-pro-2}/projects/python:-->./apache_logs.py File "./apache_lo...
python docstrings
ok so I decided to learn python (perl, c, c++, java, objective-c, ruby and a bit of erlang and scala under my belt). and I keep on getting the following error when I try executing this: Tue Jul 21{stevenhirsch@steven-hirschs-macbook-pro-2}/projects/python:-->./apache_logs.py File "./apache_logs.py", line 17 pri...
[ "What version of Python do you have? In Python 3, print was changed to work like a function rather than a statement, i.e. print('Hello World') instead of print 'Hello World'\nI can recommend you to keep using Python 2.6 unless you're doing some brand new production development. Python 3 is still pretty new.\n" ]
[ 5 ]
[]
[]
[ "python", "syntax_error" ]
stackoverflow_0001161810_python_syntax_error.txt
Q: Add data to Django form class using modelformset_factory I have a problem where I need to display a lot of forms for detail data for a hierarchical data set. I want to display some relational fields as labels for the forms and I'm struggling with a way to do this in a more robust way. Here is the code... class C...
Add data to Django form class using modelformset_factory
I have a problem where I need to display a lot of forms for detail data for a hierarchical data set. I want to display some relational fields as labels for the forms and I'm struggling with a way to do this in a more robust way. Here is the code... class Category(models.Model): name = models.CharField(max_length=16...
[ "Well, I figured out the answer to my own question. I've overridden the init class on the form and accessed the instance of the model form. Works exactly as I wanted and it was easy.\nclass BudgetValueForm(forms.ModelForm):\n item = forms.ModelChoiceField(queryset=Item.objects.all(),widget=forms.HiddenInput())\...
[ 3 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0001161618_django_django_forms_python.txt
Q: How to implement a scripting language into a C application? I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application). How does em...
How to implement a scripting language into a C application?
I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application). How does embedding and communication between my app and the scripts actually...
[ "Lua. It has a very small footprint, is rather fast, and I found it (subjectively) to have the most pleasant API to interact with C.\nIf you want to touch the Lua objects from C - it's quite easy using the built-in APIs. If you want to touch C data from Lua - it's a bit more work, typically you'd need to make wrapp...
[ 17, 17, 8, 8, 4, 3, 2, 1 ]
[]
[]
[ "c", "lua", "python", "scripting" ]
stackoverflow_0001158396_c_lua_python_scripting.txt
Q: Retrieving Raw_Input from a system ran script I'm using the OS.System command to call a python script. example: OS.System("call jython script.py") In the script I'm calling, the following command is present: x = raw_input("Waiting for input") If I run script.py from the command line I can input data no problem, ...
Retrieving Raw_Input from a system ran script
I'm using the OS.System command to call a python script. example: OS.System("call jython script.py") In the script I'm calling, the following command is present: x = raw_input("Waiting for input") If I run script.py from the command line I can input data no problem, if I run it via the automated approach I get an EOF...
[ "The problem is the way you run your child script. Since you use os.system() the script's input channel is closed immediately and the raw_input() prompt hits an EOF (end of file). And even if that didn't happen, you wouldn't have a way to actually send some input text to the child as I assume you'd want given that ...
[ 2, 0 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0001161959_jython_python.txt
Q: trac-past-commit-hook on remote repository Trying to set up the svn commit with trac using this script. It is being called without issue, but the problem is this line here: 144 repos = self.env.get_repository() Because I am calling this remotely self.env_get_repository() looks for the repository using the server ...
trac-past-commit-hook on remote repository
Trying to set up the svn commit with trac using this script. It is being called without issue, but the problem is this line here: 144 repos = self.env.get_repository() Because I am calling this remotely self.env_get_repository() looks for the repository using the server drive and not the local drive mapping. That is, ...
[ "This is totally do-able and just requires a couple of small hacks... woo hoo!\nThe problem I was having is that get_repository reads the value of the svn repository from the trac.ini file. This was pointing at E:/ and not at Y:/. The simple fix involves a check to see if the repository is at repository_dir and if ...
[ 0 ]
[]
[]
[ "python", "svn", "trac", "windows" ]
stackoverflow_0001141157_python_svn_trac_windows.txt
Q: Easiest way to pop up interactive Python console? My application has a Python interpreter embedded in it. However there's currently not any way to inspect anything about Python directly. I'd like to be able to pop up an interactive shell at various points to inspect what's going on in Python. I've found several si...
Easiest way to pop up interactive Python console?
My application has a Python interpreter embedded in it. However there's currently not any way to inspect anything about Python directly. I'd like to be able to pop up an interactive shell at various points to inspect what's going on in Python. I've found several similar questions which pointed me to code.InteractiveCon...
[ "What have you tried with IPython? Is it the snippets from the documentation:\n\nEmbedding IPython (IPython docs)\n\nHow about some of the code samples from elsewhere:\n\nEmbedding IPython in GUI apps is trivial\nEmbedding IPython in a PyGTK application\n\nI know I fooled around with this a while back and the samp...
[ 1, 1 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0001162277_debugging_python.txt
Q: win32api.dll Will Not Install I am trying to start a Buildbot Buildslave on a Windows XP virtual machine: python buildbot start . ImportError: No module named win32api. Google tells me that win32api is win32api.dll. I downloaded the file from www.dll-files.com and followed the guide found on that site (http://w...
win32api.dll Will Not Install
I am trying to start a Buildbot Buildslave on a Windows XP virtual machine: python buildbot start . ImportError: No module named win32api. Google tells me that win32api is win32api.dll. I downloaded the file from www.dll-files.com and followed the guide found on that site (http://www.dll-files.com/unzip.php). When ...
[ "win32api belongs Python for Windows extensions, Aka Pywn32.\nhave u installed it?\n", "Install ActivePython (http://www.activestate.com/activepython/) - it's a Python distro that comes bundled with the Windows dlls. It's what everyone else does.\n" ]
[ 5, 0 ]
[]
[]
[ "buildbot", "dll", "python", "twisted", "windows" ]
stackoverflow_0001161178_buildbot_dll_python_twisted_windows.txt
Q: How would you model this database relationship? I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients. The appli...
How would you model this database relationship?
I'm modeling a database relationship in django, and I'd like to have other opinions. The relationship is kind of a two-to-many relationship. For example, a patient can have two physicians: an attending and a primary. A physician obviously has many patients. The application does need to know which one is which; further,...
[ "How about something like this:\nclass Patient(models.Model):\n primary_physician = models.ForeignKey('Physician', related_name='primary_patients')\n attending_physicial = models.ForeignKey('Physician', related_name='attending_patients')\n\nThis allows you to have two foreign keys to the same model; the Physi...
[ 10, 1, 0 ]
[]
[]
[ "database", "database_design", "django", "python" ]
stackoverflow_0001162877_database_database_design_django_python.txt
Q: Python Math Library Independent of C Math Library and Platform Independent? Does the built-in Python math library basically use C's math library or does Python have a C-independent math library? Also, is the Python math library platform independent? A: at the bottom of the page it says: Note: The math module co...
Python Math Library Independent of C Math Library and Platform Independent?
Does the built-in Python math library basically use C's math library or does Python have a C-independent math library? Also, is the Python math library platform independent?
[ "at the bottom of the page it says:\n\nNote: The math module consists mostly of thin wrappers around the platform C math library functions. Behavior in exceptional cases is loosely specified by the C standards, and Python inherits much of its math-function error-reporting behavior from the platform C implementation...
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001160061_python.txt
Q: Connecting C# (frontend) to an apache/php/python (backend) Overview: We are looking to write a C# user interface to select parts of our web applications. This is for a very captive audience (internally, for example). Our web applications are written in PHP and/or Python using Apache as the web server. Why? A wel...
Connecting C# (frontend) to an apache/php/python (backend)
Overview: We are looking to write a C# user interface to select parts of our web applications. This is for a very captive audience (internally, for example). Our web applications are written in PHP and/or Python using Apache as the web server. Why? A well thought out native Windows interface can at times be far more ...
[ "I have no real experience with PHP, but I've done plenty of Python back-end web services consumed by front-end clients in a variety of languages and environment. SOAP is the only technology, out of those I've tried, that has mostly left a sour taste in my mouth -- too much \"ceremony\"/overhead. (Back in the far p...
[ 4, 0, 0, 0 ]
[]
[]
[ "c#", "data_structures", "php", "python", "web_applications" ]
stackoverflow_0001023187_c#_data_structures_php_python_web_applications.txt
Q: How to convert a list of longs into a comma separated string in python I'm new to python, and have a list of longs which I want to join together into a comma separated string. In PHP I'd do something like this: $output = implode(",", $array) In Python, I'm not sure how to do this. I've tried using join, but this ...
How to convert a list of longs into a comma separated string in python
I'm new to python, and have a list of longs which I want to join together into a comma separated string. In PHP I'd do something like this: $output = implode(",", $array) In Python, I'm not sure how to do this. I've tried using join, but this doesn't work since the elements are the wrong type (i.e., not strings). Do I...
[ "You have to convert the ints to strings and then you can join them:\n','.join([str(i) for i in list_of_ints])\n\n", "You can use map to transform a list, then join them up.\n\",\".join( map( str, list_of_things ) )\n\nBTW, this works for any objects (not just longs).\n", "You can omit the square brackets from ...
[ 69, 20, 11, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0000438684_python.txt
Q: Why can't I import this Zope component in a Python 2.4 virtualenv? I'm trying to install Plone 3.3rc4 with plone.app.blob and repoze but nothing I've tried has worked so far. For one attempt I've pip-installed repoze.zope2, Plone, and plone.app.blob into a virtualenv. I have this version of DocumentTemplate in the...
Why can't I import this Zope component in a Python 2.4 virtualenv?
I'm trying to install Plone 3.3rc4 with plone.app.blob and repoze but nothing I've tried has worked so far. For one attempt I've pip-installed repoze.zope2, Plone, and plone.app.blob into a virtualenv. I have this version of DocumentTemplate in the virtualenv's site-packages directory and I'm trying to get it running i...
[ "I must say I doubt DocumentTemplate from Zope will work standalone. You are welcome to try though. :-)\nNote that DT_Util imports C extensions:\nfrom DocumentTemplate.cDocumentTemplate import InstanceDict, TemplateDict\nfrom DocumentTemplate.cDocumentTemplate import render_blocks, safe_callable\nfrom DocumentTempl...
[ 1 ]
[]
[]
[ "python", "virtualenv", "zope" ]
stackoverflow_0001161670_python_virtualenv_zope.txt
Q: Finding the coordinates of tiles that are covered by a rectangle with x,y,w,h pixel coordinates Say I have a tile based system using 16x16 pixels. How would you find out what tiles are covered by a rectangle defined by floating point pixel units? for eg, rect(x=16.0,y=16.0, w=1.0, h=1.0) -> tile(x=1, y=1, w=1, ...
Finding the coordinates of tiles that are covered by a rectangle with x,y,w,h pixel coordinates
Say I have a tile based system using 16x16 pixels. How would you find out what tiles are covered by a rectangle defined by floating point pixel units? for eg, rect(x=16.0,y=16.0, w=1.0, h=1.0) -> tile(x=1, y=1, w=1, h=1) rect(x=16.0,y=16.0, w=16.0, h=16.0) -> tile(x=1, y=1, w=1, h=1) (still within same tile) rect(x=...
[ "Matt's solution with bug-fixes:\nfrom __future__ import division\nimport math\n\nTILE_W = TILE_H = 16\n\ndef get_tile(x,y,w,h):\n x1 = int(math.floor(x/TILE_W))\n x2 = int(math.ceil((x + w)/TILE_W))\n y1 = int(math.floor(y/TILE_H))\n y2 = int(math.ceil((y + h)/TILE_H))\n return x1, y1, x2-x1, y2-y1\...
[ 1, 0, 0, 0 ]
[]
[]
[ "algorithm", "coordinates", "geometry", "math", "python" ]
stackoverflow_0001108929_algorithm_coordinates_geometry_math_python.txt
Q: Python object creation I am pretty new to Python world and trying to learn it. This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :) class Car(): carName = ""...
Python object creation
I am pretty new to Python world and trying to learn it. This is what I am trying to achieve: I want to create a Car class, its constructor checks for the input to set the object carName as the input. I try to do this by using the java logic but I seem to fail :) class Car(): carName = "" #how can I define a non ass...
[ "derived from object for new-style class\nuse __init__ to initialize the new instance, not __self__\n__main__ is helpful too.\nclass Car(object):\n def __init__(self,input):\n self.carName = input\n\n def showName(self):\n print self.carName\ndef main():\n a = Car(\"bmw\")\n a.showName()\n...
[ 14, 2, 1 ]
[]
[]
[ "class", "object", "python" ]
stackoverflow_0001164309_class_object_python.txt
Q: Non-recursive means of printing a list in Python Is there a way to perform the following in a non-recursive fashion: my_list = [ "level 1-1", "level 1-2", "level 1-3", [ "level 2-1", "level 2-2", "level 2-3", [ "level 3-1", ...
Non-recursive means of printing a list in Python
Is there a way to perform the following in a non-recursive fashion: my_list = [ "level 1-1", "level 1-2", "level 1-3", [ "level 2-1", "level 2-2", "level 2-3", [ "level 3-1", "level 3-2" ] ], "lev...
[ "stack = [(my_list, -1)]\nwhile stack:\n item, level = stack.pop()\n\n if isinstance(item, list):\n for i in reversed(item):\n stack.append((i, level+1))\n else:\n print \"\\t\" * level, item\n\n", "def print_list(the_list, indent_level=0):\n stack = [iter(the_list)]\n whil...
[ 4, 2, 2, 0, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0001163429_python_recursion.txt
Q: SQLAlchemy - Models - using dynamic fields - ActiveRecord How close can I get to defining a model in SQLAlchemy like: class Person(Base): pass And just have it dynamically pick up the field names? anyway to get naming conventions to control the relationships between tables? I guess I'm looking for something...
SQLAlchemy - Models - using dynamic fields - ActiveRecord
How close can I get to defining a model in SQLAlchemy like: class Person(Base): pass And just have it dynamically pick up the field names? anyway to get naming conventions to control the relationships between tables? I guess I'm looking for something similar to RoR's ActiveRecord but in Python. Not sure if this ...
[ "It is very simple to automatically pick up the field names:\nfrom sqlalchemy import Table\nfrom sqlalchemy.orm import MetaData, mapper\n\nmetadata = MetaData()\nmetadata.bind = engine\n\nperson_table = Table(metadata, \"tablename\", autoload=True)\n\nclass Person(object):\n pass\n\nmapper(Person, person_table)\...
[ 4, 2 ]
[]
[]
[ "activerecord", "ironpython", "python", "sqlalchemy" ]
stackoverflow_0001165002_activerecord_ironpython_python_sqlalchemy.txt
Q: Python Notation? I've just started using Python and I was thinking about which notation I should use. I've read the PEP 8 guide about notation for Python and I agree with most stuff there except function names (which I prefer in mixedCase style). In C++ I use a modified version of the Hungarian notation where I do...
Python Notation?
I've just started using Python and I was thinking about which notation I should use. I've read the PEP 8 guide about notation for Python and I agree with most stuff there except function names (which I prefer in mixedCase style). In C++ I use a modified version of the Hungarian notation where I don't include informatio...
[ "\n(Almost every Python programmer will say it makes the code less readable, but I've become used to it and code written without these labels is the code that is less readable for me)\n\nFTFY.\nSeriously though, it will help you but confuse and annoy other Python programmers that try to read your code.\nThis also i...
[ 8, 7, 4, 3, 2, 1 ]
[]
[]
[ "naming_conventions", "notation", "python" ]
stackoverflow_0001161658_naming_conventions_notation_python.txt
Q: GQL Query on date equality in Python Ok, you guys were quick and helpful last time so I'm going back to the well ;) Disclaimer: I'm new to python and very new to App Engine. What I'm trying to do is a simple modification of the example from the AppEngine tutorial. I've got my date value being stored in my Memory c...
GQL Query on date equality in Python
Ok, you guys were quick and helpful last time so I'm going back to the well ;) Disclaimer: I'm new to python and very new to App Engine. What I'm trying to do is a simple modification of the example from the AppEngine tutorial. I've got my date value being stored in my Memory class: class Memory(db.Model): author =...
[ "You're trying to use GQL syntax with non-GQL Query objects. Your options are:\n\nUse the Query object and pass in a datetime.date object: q = Memory.all().filter(\"date =\", datetime.date.today())\nUse a GqlQuery and use the DATE syntax: q = db.GqlQuery(\"SELECT * FROM Memory WHERE date = DATE(2007, 07, 20)\")\nUs...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001162644_google_app_engine_python.txt
Q: fast-ish python/jython IPC? All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going. The list of things I'v...
fast-ish python/jython IPC?
All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going. The list of things I've tried: Apache Thrift doesn't h...
[ "Have you considered Hessian? From the blurb:\n\nThe Hessian binary web service\n protocol makes web services usable\n without requiring a large framework,\n and without learning yet another\n alphabet soup of protocols. Because it\n is a binary protocol, it is\n well-suited to sending binary data\n without ...
[ 6, 5, 2, 2, 0 ]
[]
[]
[ "ipc", "jython", "python", "rpc", "twisted" ]
stackoverflow_0001163574_ipc_jython_python_rpc_twisted.txt
Q: Including current date in python logging file I have a process that I run every day. It uses Python logging. How would I configure the python logging module to write to a file containing the current date in the file name? Because I restart the process every morning the TimedRotatingFileHandler won't work. The p...
Including current date in python logging file
I have a process that I run every day. It uses Python logging. How would I configure the python logging module to write to a file containing the current date in the file name? Because I restart the process every morning the TimedRotatingFileHandler won't work. The project is larger, so I would be interested in keepi...
[ "You can use the TimedRotatingFileHandler. For example:\nimport logging\nimport logging.handlers\n\nLOG_FILENAME = '/tmp/log'\n\n# Set up a specific logger with our desired output level\nlog = logging.getLogger(__name__)\nlog.setLevel(logging.DEBUG)\nhandler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME,...
[ 9, 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0001165856_logging_python.txt
Q: Multiple statements in list compherensions in Python? Is it possible to have something like: list1 = ... currentValue = 0 list2 = [currentValue += i, i for i in list1] I tried that but didn't work? What's the proper syntax to write those? EDIT: the print statement was an example. Actually I am incrementing a val...
Multiple statements in list compherensions in Python?
Is it possible to have something like: list1 = ... currentValue = 0 list2 = [currentValue += i, i for i in list1] I tried that but didn't work? What's the proper syntax to write those? EDIT: the print statement was an example. Actually I am incrementing a value outside the loop.
[ "Statements cannot go inside of expressions in Python; it was a complication that was deliberately designed out of the language. For this problem, try using a complication that did make it into the language: generators. Watch:\ndef total_and_item(sequence):\n total = 0\n for i in sequence:\n total +=...
[ 32, 4, 3, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0000774876_list_comprehension_python.txt
Q: Running Python code in different processors In order to do quality assurance in a critical multicore (8) workstation, I want to run the same code in different processors but not in parallel or concurrently. I need to run it 8 times, one run for each processor. What I don't know is how to select the processor I w...
Running Python code in different processors
In order to do quality assurance in a critical multicore (8) workstation, I want to run the same code in different processors but not in parallel or concurrently. I need to run it 8 times, one run for each processor. What I don't know is how to select the processor I want. How can this be accomplished in Python?
[ "In Linux with schedutils, I believe you'd use taskset -c X python foo.py to run that specific Python process on CPU X (exactly how you identify your CPUs may vary, but I believe numbers such as 1, 2, 3, ... should work anywhere). I'm sure Windows, BSD versions, etc, have similar commands to support direct processo...
[ 5, 3 ]
[]
[]
[ "multicore", "python" ]
stackoverflow_0001166392_multicore_python.txt
Q: How do I filter the choices in a ModelForm that has a CharField with the choices attribute (and hence a Select Field) I understand I am able to filter queryset of Foreignkey or Many2ManyFields, however, how do I do that for a simple CharField that is a Select Widget (Select Tag). For example: PRODUCT_STATUS = ( ...
How do I filter the choices in a ModelForm that has a CharField with the choices attribute (and hence a Select Field)
I understand I am able to filter queryset of Foreignkey or Many2ManyFields, however, how do I do that for a simple CharField that is a Select Widget (Select Tag). For example: PRODUCT_STATUS = ( ("unapproved", "Unapproved"), ("approved", "Listed"), #("Backorder","Ba...
[ "class YourModelForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(YourModelForm, self).__init__(*args, **kwargs)\n self.fields['your_field'].choices = (('a', 'A'), ('b', 'B'))\n\n class Meta:\n model = YourModel\n\nI guess this ain't too different from overriding a que...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001166649_django_python.txt
Q: Using Python from within Java Possible Duplicate: Java Python Integration I have a large existing codebase written in 100% Java, but I would like to use Python for some new sections of it. I need to do some text and language processing, and I'd much rather use Python and a library like NLTK to do this. I'm aware ...
Using Python from within Java
Possible Duplicate: Java Python Integration I have a large existing codebase written in 100% Java, but I would like to use Python for some new sections of it. I need to do some text and language processing, and I'd much rather use Python and a library like NLTK to do this. I'm aware of the Jython project, but it look...
[ "\nI'm aware of the Jython project, but\n it looks like this represents a way to\n use Java and its libraries from within\n Python, rather than the other way\n round - am I wrong about this?\n\nYes, you are wrong. You can either call a command line interpreter to run python code using Jyton or use python code f...
[ 34, 6, 4, 2, 2, 0, 0 ]
[]
[]
[ "java", "jython", "python", "rpc" ]
stackoverflow_0001164810_java_jython_python_rpc.txt
Q: Issues with inspect.py when used inside Jython I am using an application developed in Jython. When I try to use the inspect.py in that, it shows error message. My code goes like this import inspect,os,sys,pprint,imp def handle_stackframe_without_leak(getframe): frame = inspect.currentframe() try: f...
Issues with inspect.py when used inside Jython
I am using an application developed in Jython. When I try to use the inspect.py in that, it shows error message. My code goes like this import inspect,os,sys,pprint,imp def handle_stackframe_without_leak(getframe): frame = inspect.currentframe() try: function = inspect.getframeinfo(getframe) pri...
[ "Have you tried running your program on the command line with Jython (so outside of the app)? When I run your program with Jython 2.2.1 or Jython 2.5.0, I get identical output as from Python.\n", "This might help http://grinder.sourceforge.net/faq.html#re-problems.\nFor a quick check, try adding import re in fin...
[ 1, 0 ]
[]
[]
[ "inspect", "jython", "module", "python" ]
stackoverflow_0001108958_inspect_jython_module_python.txt
Q: Executing code for a custom Django 404 page I am getting ready to deploy my first Django application and am hitting a bit of a roadblock. My base template relies on me passing in the session object so that it can read out the currently logged in user's name. This isn't a problem when I control the code that is c...
Executing code for a custom Django 404 page
I am getting ready to deploy my first Django application and am hitting a bit of a roadblock. My base template relies on me passing in the session object so that it can read out the currently logged in user's name. This isn't a problem when I control the code that is calling a template. However, as part of getting th...
[ "You need to override the default view handler for the 404 error. Here is the documentation on how to create your own custom 404 view function:\nhttp://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views\n", "Define your own 404 handler. See Django URLs, specifically the part about handler404...
[ 13, 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001167434_django_python.txt
Q: How to return an alternate column element from the intersect command? I am currently using the following code to get the intersection date column of two sets of financial data. The arrays include date, o,h,l,cl #find intersection of date strings def intersect(seq1, seq2): res = [] # start ...
How to return an alternate column element from the intersect command?
I am currently using the following code to get the intersection date column of two sets of financial data. The arrays include date, o,h,l,cl #find intersection of date strings def intersect(seq1, seq2): res = [] # start empty for x in seq1: # scan seq1 if x in seq2: ...
[ "Okay, here is a complete solution.\nGet a python library to download stocks quotes\nGet some quotes\nstart_date, end_date = '20090309', '20090720'\nibm_data = get_historical_prices('IBM', start_date, end_date)\nmsft_data = get_historical_prices('MSFT', start_date, end_date)\n\nConvert rows into date-keyed dictiona...
[ 0, 0 ]
[]
[]
[ "intersection", "python" ]
stackoverflow_0001167908_intersection_python.txt
Q: Middleware for both Django and Pylons It appears to me that Django and Pylons have different ideas on how middleware should work. I like that Pylons follows the standardized PEP 333, but Django seems to have more widespread adoption. Is it possible to write middleware to be used in both? The project that involves ...
Middleware for both Django and Pylons
It appears to me that Django and Pylons have different ideas on how middleware should work. I like that Pylons follows the standardized PEP 333, but Django seems to have more widespread adoption. Is it possible to write middleware to be used in both? The project that involves said middleware is porting a security toolk...
[ "Pylons uses standard WSGI middleware. If you deploy Django via WSGI, you can also use WSGI middleware at that point. You can't, however, currently use WSGI middleware via the standard Django MIDDLEWARE_CLASSES option in settings.py.\nThat said, there is currently a Google Summer of Code project to enable the use o...
[ 3, 0 ]
[]
[]
[ "django", "middleware", "pylons", "python" ]
stackoverflow_0001167903_django_middleware_pylons_python.txt
Q: Python scripts in /usr/bin I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension? For example, instead of running python htswap.py args from the directory where it currently i...
Python scripts in /usr/bin
I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension? For example, instead of running python htswap.py args from the directory where it currently is, I want to be able to cd to an...
[ "Simply strip off the .py extension by renaming the file. Then, you have to put the following line at the top of your file:\n#!/usr/bin/env python\n\nenv is a little program that sets up the environment so that the right python interpreter is executed.\nYou also have to make your file executable, with the command\n...
[ 47, 14, 2, 1, 0 ]
[]
[]
[ "python", "scripting", "unix" ]
stackoverflow_0001168042_python_scripting_unix.txt
Q: Why does this Python script only read the last RSS post into the file? Im trying to fix a Python script which takes the posts from a specific RSS feed and strips them down and inputs them into a text file. As you can see beneath, there are two main print functions. One prints only to the shell once run, but it sho...
Why does this Python script only read the last RSS post into the file?
Im trying to fix a Python script which takes the posts from a specific RSS feed and strips them down and inputs them into a text file. As you can see beneath, there are two main print functions. One prints only to the shell once run, but it shows all of the posts, which is what I want it to do. Now, the second part is ...
[ "Your print >>f are after the for loop, so they are run once, and operate on the data that you last saved to title, description, and str.\nYou should open the file before the for loop and then put the print >>f lines inside the loop.\nimport urllib\nimport sys\nimport xml.dom.minidom\n\n#The url of the feed\naddres...
[ 2, 1 ]
[]
[]
[ "python", "rss", "xml" ]
stackoverflow_0001168844_python_rss_xml.txt
Q: Autocompletion not working with PyQT4 and PyKDE4 in most of the IDEs I am trying to develop a plasmoid using python. I have tried eclipse with pydev, vim with pythoncomplete, PIDA and also Komodo, but none of them could give me autocmpletion for method names or members for the classes belonging to PyQT4 or PyKDE4...
Autocompletion not working with PyQT4 and PyKDE4 in most of the IDEs
I am trying to develop a plasmoid using python. I have tried eclipse with pydev, vim with pythoncomplete, PIDA and also Komodo, but none of them could give me autocmpletion for method names or members for the classes belonging to PyQT4 or PyKDE4. I added the folders in /usr/share/pyshare in the PYTHONPATH list for the...
[ "There is a number of ways to do it, PyQt4 provides enough information about method names for any object inspecting IDE:\n>>> from PyQt4 import QtGui\n>>> dir(QtGui.QToolBox) \n['Box', ... contextMenuPolicy', 'count', 'create', 'currentChanged'...]\n\nAll those functions are built-in. This means that you have to pu...
[ 4, 0 ]
[]
[]
[ "plasmoid", "pykde", "pyqt4", "python" ]
stackoverflow_0001167065_plasmoid_pykde_pyqt4_python.txt
Q: Smart date interpretation I can't remember which application I was using, but I do recall it having really neat date parsing/interpretation. For example, you could type in 'two days ago' or 'tomorrow' and it would understand. Any libraries to suggest? Bonus points if usable from Python. A: Perhaps you are thinki...
Smart date interpretation
I can't remember which application I was using, but I do recall it having really neat date parsing/interpretation. For example, you could type in 'two days ago' or 'tomorrow' and it would understand. Any libraries to suggest? Bonus points if usable from Python.
[ "Perhaps you are thinking of PHP's strtotime() function, the Swiss Army Knife of date parsing:\n\nMan, what did I do before strtotime(). Oh, I know, I had a 482 line function to parse date formats and return timestamps. And I still could not do really cool stuff. Like tonight I needed to figure out when Thanksgi...
[ 8, 6, 2 ]
[]
[]
[ "date_parsing", "python" ]
stackoverflow_0001169000_date_parsing_python.txt
Q: Boolean evaluation in a lambda Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda? def isodd(number): if (number%2 == 0): return False else: return True Elementary, yes. But I'm interested to know... A: ...
Boolean evaluation in a lambda
Just tooling around for my own amusement, and I want to use a lambda, because I feel like it. Can I replace this function with a lambda? def isodd(number): if (number%2 == 0): return False else: return True Elementary, yes. But I'm interested to know...
[ "And if you don't really need a function you can replace it even without a lambda. :)\n(number % 2 != 0)\n\nby itself is an expression that evaluates to True or False. Or even plainer,\nbool(number % 2)\n\nwhich you can simplify like so:\nif number % 2:\n print \"Odd!\"\nelse:\n print \"Even!\"\n\nBut if that...
[ 16, 11, 11, 8, 6, 5, 3, 2 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0001168236_lambda_python.txt
Q: Find module name of the originating exception in Python Example: >>> try: ... myapp.foo.doSomething() ... except Exception, e: ... print 'Thrown from:', modname(e) Thrown from: myapp.util.url In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the __na...
Find module name of the originating exception in Python
Example: >>> try: ... myapp.foo.doSomething() ... except Exception, e: ... print 'Thrown from:', modname(e) Thrown from: myapp.util.url In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the __name__ of that module? My intention is to use this in logging.g...
[ "This should work:\nimport inspect\n\ntry:\n some_bad_code()\nexcept Exception, e:\n frm = inspect.trace()[-1]\n mod = inspect.getmodule(frm[0])\n print 'Thrown from', mod.__name__\n\nEDIT: Stephan202 mentions a corner case. In this case, I think we could default to the file name.\nimport inspect\n\ntr...
[ 12, 8, 0, 0 ]
[ "I have a story about how CrashKit computes class names and package names from Python stack traces on the company blog: “Python stack trace saga”. Working code included.\n" ]
[ -2 ]
[ "exception", "introspection", "logging", "python", "stack_trace" ]
stackoverflow_0001095601_exception_introspection_logging_python_stack_trace.txt
Q: Python OS X 10.5 development environment I would like to try out the Google App Engine Python environment, which the docs say runs 2.5.2. As I use OS X Leopard, I have Python 2.5.1 installed, but would like the latest 2.5.x version installed (not 2.6 or 3.0). It seems the latest version is 2.5.4 So, I went to he...
Python OS X 10.5 development environment
I would like to try out the Google App Engine Python environment, which the docs say runs 2.5.2. As I use OS X Leopard, I have Python 2.5.1 installed, but would like the latest 2.5.x version installed (not 2.6 or 3.0). It seems the latest version is 2.5.4 So, I went to here: http://wiki.python.org/moin/MacPython/Leop...
[ "You can install python on your Mac, and it won't mess with the default installation. However, I strongly recommend that you use MacPorts to install Python, since that will make it much easier for you to install Python libraries and packages further down the road. Additionally, if you try to install a program or li...
[ 7, 3 ]
[]
[]
[ "development_environment", "google_app_engine", "macos", "python" ]
stackoverflow_0001169025_development_environment_google_app_engine_macos_python.txt
Q: Can I damage the system by running time.sleep() with this newbie code in Python? Im sure there is a better way to do this, but I am quite the newbie so I did it the only way I could figure it out. The thing is, I have a script that updates a textfile with the newest posts from an RSS feed (I got some help from you...
Can I damage the system by running time.sleep() with this newbie code in Python?
Im sure there is a better way to do this, but I am quite the newbie so I did it the only way I could figure it out. The thing is, I have a script that updates a textfile with the newest posts from an RSS feed (I got some help from you guys to figure it out). But I want this script to be automated, so I made this: impor...
[ "To answer your question, no, this won't hurt anything. While the time.sleeps are sleeping, the program will take very little processing power and the rest of the system can run normally.\nNow, as for your looping issue. If you want the code run forever (or until you stop the program) the code you want is\n while T...
[ 9, 1, 1 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0001169185_python_while_loop.txt
Q: Python Unicode Regular Expression I am using python 2.4 and I am having some problems with unicode regular expressions. I have tried to put together a very clear and concise example of my problem. It looks as though there is some problem with how Python is recognizing the different character encodings, or a proble...
Python Unicode Regular Expression
I am using python 2.4 and I am having some problems with unicode regular expressions. I have tried to put together a very clear and concise example of my problem. It looks as though there is some problem with how Python is recognizing the different character encodings, or a problem with my understanding. Thank you very...
[ "You probably want to either enable the DOTALL flag or you want to use the search method instead of the match method. ie:\n# DOTALL makes . match newlines \nre_UNSUB_amsterdam = re.compile(\".*UNSUBSCRIBE.*\", re.UNICODE | re.DOTALL)\n\nor:\n# search will find matches even if they aren't at the start of the string\...
[ 2, 0, 0, 0 ]
[]
[]
[ "character_encoding", "python", "regex" ]
stackoverflow_0001168894_character_encoding_python_regex.txt
Q: Comparing MD5s in Python For a programming exercise I designed for myself, and for use in a pretty non-secure system later on, I'm trying to compare MD5 hashes. The one that is stored in a plain text file and is pulled out by the check_pw() function and the one that is created from the submitted password from a CG...
Comparing MD5s in Python
For a programming exercise I designed for myself, and for use in a pretty non-secure system later on, I'm trying to compare MD5 hashes. The one that is stored in a plain text file and is pulled out by the check_pw() function and the one that is created from the submitted password from a CGI form. md5_pw() is used to cr...
[ "Your pair[1] probably has a trailing newline. Try:\nfor line in f:\n line = line.rstrip()\n pair = line.split(\":\")\n # ...etc\n\n", "My guess is that there's an problem with the file loading/parsing, most likely caused by a newline character. By paring your code down, I was able to find that your logi...
[ 2, 1 ]
[]
[]
[ "md5", "python" ]
stackoverflow_0001169717_md5_python.txt
Q: To build a similar reputation tracker as Jon's by Python Jon Skeet has the following reputation tracker which is built by C#. I am interested in building a similar app by Python such that at least the following modules are used beautiful soup defaultdict We apparently need to parse the reputation from the site...
To build a similar reputation tracker as Jon's by Python
Jon Skeet has the following reputation tracker which is built by C#. I am interested in building a similar app by Python such that at least the following modules are used beautiful soup defaultdict We apparently need to parse the reputation from the site 'https://stackoverflow.com/users/#user-id#' by Bautiful soup ...
[ "The screenscraping is easy, if I understand the SO HTML format correctly, e.g., to get my rep (as I'm user 95810):\nimport urllib\nimport BeautifulSoup\npage = urllib.urlopen('http://stackoverflow.com/users/95810')\nsoup = BeautifulSoup.BeautifulSoup(page)\ntherep = str(soup.find(text='Reputation').parent.previous...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0001168452_python.txt
Q: Publish feeds using Django I'm publishing a feed from a Django application. I subclassed django.contrib.syndication.feeds.Feed, everything works fine, except the date that doesn't get published on the feed. Here's the method I've created on my Feed class def item_pubdate(self, item): return item.date this me...
Publish feeds using Django
I'm publishing a feed from a Django application. I subclassed django.contrib.syndication.feeds.Feed, everything works fine, except the date that doesn't get published on the feed. Here's the method I've created on my Feed class def item_pubdate(self, item): return item.date this method never gets called....
[ "According to the Feed Class Reference in the Django documentation, the item_pubdate field is supposed to return a datetime.datetime object. If item.date is just a DateField and not a DateTimeField, that might be causing the problem. If that is the case you could change the method to make a datetime and then retu...
[ 3, 0, 0 ]
[]
[]
[ "django", "python", "rss" ]
stackoverflow_0000945001_django_python_rss.txt
Q: Python Wiki Style Doc Generator Looking for something like PyDoc that can generate a set of Wiki style pages vs the current HTML ones that export out of PyDoc. I would like to be able to export these in Google Code's Wiki as an extension to the current docs up there now. A: Take a look at pydoc.TextDoc. If this ...
Python Wiki Style Doc Generator
Looking for something like PyDoc that can generate a set of Wiki style pages vs the current HTML ones that export out of PyDoc. I would like to be able to export these in Google Code's Wiki as an extension to the current docs up there now.
[ "Take a look at pydoc.TextDoc. If this contains too little markup, you can inherit from it and make it generate markup according to your wiki's syntax.\n", "Have you taken a look at Sphinx?\n" ]
[ 1, 0 ]
[]
[]
[ "documentation", "pydoc", "python", "wiki" ]
stackoverflow_0001169357_documentation_pydoc_python_wiki.txt
Q: Installing usual libraries inside Google App Engine How should I install (or where should I put and organize) usual python libraries in Google App Engine. Some libraries require to be installed using setuptools. How can I install that libraries. A: You need to unpack the libraries into a subdirectory of your app...
Installing usual libraries inside Google App Engine
How should I install (or where should I put and organize) usual python libraries in Google App Engine. Some libraries require to be installed using setuptools. How can I install that libraries.
[ "You need to unpack the libraries into a subdirectory of your app, and add the library directory to the Python path in your request handler module. Any steps required by setup scripts, you'll have to execute manually, but there generally aren't any unless the library bundles a native module (which aren't supported ...
[ 5, 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001166685_google_app_engine_python.txt
Q: Intercept slice operations in Python I want to imitate a normal python list, except whenever elements are added or removed via slicing, I want to 'save' the list. Is this possible? This was my attempt but it will never print 'saving'. class InterceptedList(list): def addSave(func): def newfunc(self, *...
Intercept slice operations in Python
I want to imitate a normal python list, except whenever elements are added or removed via slicing, I want to 'save' the list. Is this possible? This was my attempt but it will never print 'saving'. class InterceptedList(list): def addSave(func): def newfunc(self, *args): func(self, *args) ...
[ "From the Python 3 docs:\n__getslice__(), __setslice__() and __delslice__() were killed. \nThe syntax a[i:j] now translates to a.__getitem__(slice(i, j)) \n(or __setitem__() or __delitem__(), when used as an assignment \nor deletion target, respectively).\n\n", "\"setslice\" and \"delslice\" are deprecated, if yo...
[ 5, 5, 5, 4 ]
[]
[]
[ "intercept", "jython", "methods", "python", "slice" ]
stackoverflow_0001166839_intercept_jython_methods_python_slice.txt
Q: Bug with Python UTF-16 output and Windows line endings? With this code: test.py import sys import codecs sys.stdout = codecs.getwriter('utf-16')(sys.stdout) print "test1" print "test2" Then I run it as: test.py > test.txt In Python 2.6 on Windows 2000, I'm finding that the newline characters are being output a...
Bug with Python UTF-16 output and Windows line endings?
With this code: test.py import sys import codecs sys.stdout = codecs.getwriter('utf-16')(sys.stdout) print "test1" print "test2" Then I run it as: test.py > test.txt In Python 2.6 on Windows 2000, I'm finding that the newline characters are being output as the byte sequence \x0D\x0A\x00 which of course is wrong for...
[ "The newline translation is happening inside the stdout file. You're writing \"test1\\n\" to sys.stdout (a StreamWriter). StreamWriter translates this to \"t\\x00e\\x00s\\x00t\\x001\\x00\\n\\x00\", and sends it to the real file, the original sys.stderr.\nThat file doesn't know that you've converted the data to UT...
[ 3, 3, 0 ]
[]
[]
[ "python", "utf_16", "windows" ]
stackoverflow_0001169742_python_utf_16_windows.txt
Q: Error when using a Python constructor class fileDetails : def __init__(self,host,usr,pwd,database): self.host=host self.usr.usr self.pwd=pwd self.database=database def __init__(self,connection,sql,path): self.connection=mysql_connection() self.sql=sql ...
Error when using a Python constructor
class fileDetails : def __init__(self,host,usr,pwd,database): self.host=host self.usr.usr self.pwd=pwd self.database=database def __init__(self,connection,sql,path): self.connection=mysql_connection() self.sql=sql self.path=path If I use the constructor...
[ "The overloading of the constructor (or any other function) is not allowed in python. So you cannot define two __init__ functions for your class.\nYou can have a look to this post or this one\nThe main ideas are to use default values or to create 'alternate constructors' or to check the number and the type of your ...
[ 10, 4, 1, 1, 0, 0 ]
[]
[]
[ "constructor", "python" ]
stackoverflow_0001170731_constructor_python.txt
Q: Fit algorithm does not accept my data I'm using the algorithm described here to fit Gaussian bell curves to my data. If I generate my data array with: x=linspace(1.,100.,100) data= 17*exp(-((x-10)/3)**2) everything works fine. But if I read the data from a text file using file = open("d:\\test7.txt") arr=[] data=...
Fit algorithm does not accept my data
I'm using the algorithm described here to fit Gaussian bell curves to my data. If I generate my data array with: x=linspace(1.,100.,100) data= 17*exp(-((x-10)/3)**2) everything works fine. But if I read the data from a text file using file = open("d:\\test7.txt") arr=[] data=[] def column(matrix,i): return [row[...
[ "The fit function expects the data as a numpy Array (which has a shape attribute) and not a list (which does not), hence the AttributeError.\nConvert your data:\ndef column(matrix,i):\n return numpy.asarray([row[i] for row in matrix])\n\n", "The solution of balpha is not correct; the solution is simply to conv...
[ 4, 4 ]
[]
[]
[ "arrays", "file_io", "python" ]
stackoverflow_0001170962_arrays_file_io_python.txt