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: time attendance can help me with iterating with python I have file: Sukirman 2011-07-01 09:53:43 Sukirman 2011-07-01 13:11:45 Sukirman 2011-07-01 16:36:03 Sukirman 2011-07-01 17:14:22 Sukirman 2011-07-04 12:16:40 Sukirman 2011-07-04 14:39:28 Sukirman 2011-07-04 15:32:13 Sukirman 2011-07-04 15:38:2...
time attendance
can help me with iterating with python I have file: Sukirman 2011-07-01 09:53:43 Sukirman 2011-07-01 13:11:45 Sukirman 2011-07-01 16:36:03 Sukirman 2011-07-01 17:14:22 Sukirman 2011-07-04 12:16:40 Sukirman 2011-07-04 14:39:28 Sukirman 2011-07-04 15:32:13 Sukirman 2011-07-04 15:38:23 Sukirman 2011-07-0...
[ "You may want to have a dictionary instead of a list. Otherwise just make d.items() in the code below\n>>> import collections\n>>> d = collections.defaultdict(list)\n>>> for name, date, hour in (line.split() for line in open('the_file.txt')):\n d[date].append(hour)\n>>> print(d)\ndefaultdict(<class 'list'>, \n{'...
[ 4, 1 ]
[]
[]
[ "multidimensional_array", "python", "time_and_attendance" ]
stackoverflow_0007087288_multidimensional_array_python_time_and_attendance.txt
Q: lxml parse xsd file without Schema URL I am using lxml to parse an xsd file and am looking for an easy way to remove the URL namespace attached to each element name. Here's the xsd file: <?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="2.0...
lxml parse xsd file without Schema URL
I am using lxml to parse an xsd file and am looking for an easy way to remove the URL namespace attached to each element name. Here's the xsd file: <?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema...
[ "I'd use:\nprint elem.tag.split('}')[-1]\n\nBut you could also use the xpath function local-name():\nprint elem.xpath('local-name()')\n\nAs for fewer getchildren() calls: just leave them out. getchildren() is a deprecated way of making a list of the direct children (you should just use list(elem) instead if you act...
[ 3, 1, 0, 0 ]
[]
[]
[ "lxml", "python", "xml", "xsd" ]
stackoverflow_0006721096_lxml_python_xml_xsd.txt
Q: python remove duplicate dictionaries from a list I have a list of dictionaries l = [ {'firstname': 'joe', 'surname': 'bloggs'}, {'firstname': 'john', 'surname': 'smith'}, {'firstname': 'joe', 'surname': 'bloggs'}, {'firstname': 'jane', 'surname': 'bloggs'} ] how do i remove duplicates i.e. {'firstname': 'joe', 's...
python remove duplicate dictionaries from a list
I have a list of dictionaries l = [ {'firstname': 'joe', 'surname': 'bloggs'}, {'firstname': 'john', 'surname': 'smith'}, {'firstname': 'joe', 'surname': 'bloggs'}, {'firstname': 'jane', 'surname': 'bloggs'} ] how do i remove duplicates i.e. {'firstname': 'joe', 'surname': 'bloggs'} appears twice so would want it only...
[ "Something like this should do the stuff : \nresult = [dict(tupleized) for tupleized in set(tuple(item.items()) for item in l)]\n\nfirst, I transform the inital dict in a list of tuples, then I put them into a set (that removes duplicates entries), and then back into a dict.\n", "import itertools\n\nimport operat...
[ 65, 14 ]
[]
[]
[ "python" ]
stackoverflow_0007090758_python.txt
Q: Creating a dynamic forum signature generator in python I have searched and searched but I have only found solutions involving php and not python/django. My goal is to make a website (backend coded in python) that will allow a user to input a string. The backend script would then be run and output a dictionary with...
Creating a dynamic forum signature generator in python
I have searched and searched but I have only found solutions involving php and not python/django. My goal is to make a website (backend coded in python) that will allow a user to input a string. The backend script would then be run and output a dictionary with some info. What I want is to use the info from the dictiona...
[ "If I understand you correctly, you want to get an image from one place, get some textual information from another place, draw text on top of the image, and then return the marked-up image. Do I have that right?\nIf so, get PIL, the Python Image Library. Both PIL and BeatifulSoup are capable of reading directly f...
[ 3 ]
[]
[]
[ "django", "forum", "image", "python", "signature" ]
stackoverflow_0007090773_django_forum_image_python_signature.txt
Q: How can I securely pass an arbitrarily deep path to a webapp (Flask, in this case)? I have a form that sends a string to my Flask app when the form is posted. The string is a filepath, so I'd like to make sure it doesn't contain anything nasty, like ../../../etc/passwd. Werkzeug, which Flask uses, has a handy func...
How can I securely pass an arbitrarily deep path to a webapp (Flask, in this case)?
I have a form that sends a string to my Flask app when the form is posted. The string is a filepath, so I'd like to make sure it doesn't contain anything nasty, like ../../../etc/passwd. Werkzeug, which Flask uses, has a handy function called secure_filename that strips nasty stuff out of filenames. Unfortunately, when...
[ "For situations like this Flask has safe_join which raises 404 if a user attempts to leave the path:\n>>> safe_join('/foo/bar', 'test')\n'/foo/bar/test'\n>>> safe_join('/foo/bar', 'test/../other_test')\n'/foo/bar/other_test'\n>>> safe_join('/foo/bar', 'test/../../../etc/htpassw')\nTraceback (most recent call last):...
[ 10, 2 ]
[]
[]
[ "flask", "python", "web_applications", "werkzeug" ]
stackoverflow_0007069753_flask_python_web_applications_werkzeug.txt
Q: Flask blueprints proper usage I have a question regarding blueprints. I have an app which is structured like this app /run.py /APP /__init__.py /VIEWS /__init__.py /general.py /crud.py this is the code http://pastebin.com/bsHsTGAP run.py from overwatch i...
Flask blueprints proper usage
I have a question regarding blueprints. I have an app which is structured like this app /run.py /APP /__init__.py /VIEWS /__init__.py /general.py /crud.py this is the code http://pastebin.com/bsHsTGAP run.py from overwatch import app app.run() __init__.py fr...
[ "To access the current application from your blueprint's views, you should use the flask.current_app object, it is a proxy to the current application (and it's what's used in flask extensions for example).\nRegarding your code, except the unused imports, it's well organised in my opinion, but i can't tell about the...
[ 21 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0007085438_flask_python.txt
Q: Howto parse multiple files (whole packages) with pylint I am working with python 2.7 and installed pylint 0.24, as an IDE i use Eclipse (with pydev) and the OS is windows 7 64 bit. Pylint works so far, but in eclipse i only get the pylint report when i save a python file. So my question is, is it possible to parse...
Howto parse multiple files (whole packages) with pylint
I am working with python 2.7 and installed pylint 0.24, as an IDE i use Eclipse (with pydev) and the OS is windows 7 64 bit. Pylint works so far, but in eclipse i only get the pylint report when i save a python file. So my question is, is it possible to parse multiple files at once, for example all files in a package o...
[ "Yes it is. I'm working with Aptana but it should be the same deal. When u save a file in eclipse the first line in your console should be:\nPyLint: Executing command line:' /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pylint-0.23.0-py2.7.egg/pylint/lint.py --include-ids=y /Users/bo...
[ 1 ]
[]
[]
[ "code_analysis", "pydev", "pylint", "python", "windows" ]
stackoverflow_0007091668_code_analysis_pydev_pylint_python_windows.txt
Q: Python timedelta behaviour on subtraction This question originated when I came upon (another thread) about Python's datetime and timedelta objects. I followed the update by jimgardener and read the comments by eyquem ,and tried out some python code ..I am having a bad time understanding the way things work here(d...
Python timedelta behaviour on subtraction
This question originated when I came upon (another thread) about Python's datetime and timedelta objects. I followed the update by jimgardener and read the comments by eyquem ,and tried out some python code ..I am having a bad time understanding the way things work here(due to my newbie to python status)..I thought it...
[ "The timedeltas don't represent time from a midnight, just an amount of time.\nIf it took me three hours minus four hours to do something, it would take me negative one hour.\nThe difference between the two timedeltas is negative one day plus 45 minutes.\nThis is the same as negative 23 hours and 15 minutes.\n15 mi...
[ 11 ]
[]
[]
[ "datetime", "python", "timedelta" ]
stackoverflow_0007091616_datetime_python_timedelta.txt
Q: Problem with lists' dependence (python) I'm sure this question was answered thousands time before, but English is not my native language and I am really bad at searching so I beg your pardon. I am trying to learn python by writing a database for my job, so I met this issue. Simplified peace of code: x=[[0,0],...
Problem with lists' dependence (python)
I'm sure this question was answered thousands time before, but English is not my native language and I am really bad at searching so I beg your pardon. I am trying to learn python by writing a database for my job, so I met this issue. Simplified peace of code: x=[[0,0],[0,0]] y=x[0:] y[0][0]="1" print ...
[ "Using x[0:] does not create a 'deep copy'; it is essentially copying the references to the inner arrays, or a 'shallow copy', such that setting y[0] or y[1] would not change x, but setting the inner array's items would.\n", "y=x[0:] \n\nThis does copy the list x but the since the elements of x are arrays these w...
[ 3, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007091730_list_python.txt
Q: Eclipse Expressions view with PyDev - expand objects I use Eclipse and PyDev for my work. I have seen elsewhere (http://help.eclipse.org/indigo/topic/org.eclipse.jdt.doc.user/reference/views/expressions/ref-expressions_view.htm) that it is possible to have the expressions view have "expandable" objects, so that on...
Eclipse Expressions view with PyDev - expand objects
I use Eclipse and PyDev for my work. I have seen elsewhere (http://help.eclipse.org/indigo/topic/org.eclipse.jdt.doc.user/reference/views/expressions/ref-expressions_view.htm) that it is possible to have the expressions view have "expandable" objects, so that one can "open" the result of an expression to see the fields...
[ "PyDev does not have that feature. Please create a feature request for that.\n" ]
[ 0 ]
[]
[]
[ "debugging", "eclipse", "pydev", "python" ]
stackoverflow_0007088307_debugging_eclipse_pydev_python.txt
Q: Inconsistent results being returned by mongodb find query I ran the following query on a collection in my mongodb database. db.coll.find({field_name:{$exists:true}}).count() and it returned 2437185. The total records reported by db.coll.find({}).count() is 2437228 . Now when i run the query db.coll.find({field_na...
Inconsistent results being returned by mongodb find query
I ran the following query on a collection in my mongodb database. db.coll.find({field_name:{$exists:true}}).count() and it returned 2437185. The total records reported by db.coll.find({}).count() is 2437228 . Now when i run the query db.coll.find({field_name:{$exists:false}}).count() , instead of returning 43 it retur...
[ "I believe you're running into the issue reported at SERVER-1587. What version of MongoDB are you using? If it is less than 1.9.0, you can use the following as a work-around:\ndb.coll.find({field_name: {$not: {$exists: true}}}).count()\n\nAs for the other question, \"blanking out\" in this case means that an update...
[ 5 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0007091952_mongodb_pymongo_python.txt
Q: Passing wxPython objects as multiprocessor arguments I'm currently writing a program in python with a gui using wxpython. The program has a function which evaluates several pythonscripts and will therefore hang up the gui. I am trying to use a separate process for this function. The problem is that the function ne...
Passing wxPython objects as multiprocessor arguments
I'm currently writing a program in python with a gui using wxpython. The program has a function which evaluates several pythonscripts and will therefore hang up the gui. I am trying to use a separate process for this function. The problem is that the function needs a few things from the ui; a listctrl and a textctrl, t...
[ "Basically, you can't. You need to pass the results back and let the GUI thread update the listctrl and textctrl.\nSee this mailing list thread for information about the pickling error.\n" ]
[ 2 ]
[]
[]
[ "multiprocessing", "python", "wxpython" ]
stackoverflow_0007092175_multiprocessing_python_wxpython.txt
Q: difficulty in understanding numpy array behavior the following is a (very)shorterned vesrion of my program the normvecs vector is not getting overwritten , you woud be able to see for yourself just once you run this code snippet , the parameters are correct geom function takes an n+1 X 2 array and n as input, i ...
difficulty in understanding numpy array behavior
the following is a (very)shorterned vesrion of my program the normvecs vector is not getting overwritten , you woud be able to see for yourself just once you run this code snippet , the parameters are correct geom function takes an n+1 X 2 array and n as input, i guess i'm doing something really stupid (which i think...
[ "I see no problem at all. Running a more concise version of your code:\nimport numpy as np\n\n#geometry calculations\ndef geom(pts,n):\n normvecs = np.zeros((n,2))\n alphap = np.zeros(n)\n alphap[:] = np.arctan2(pts[1:n+1,1]-pts[0:n,1],pts[1:n+1,0]-pts[0:n,0])\n normvecs[:,0] = -np.sin(alphap[:])\n n...
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007091544_numpy_python.txt
Q: Absolute position from relative Provided that I have a Python list of strings of words, how do I get absolute position of a given word in the whole list, as opposed to relative position within the string? l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1'] rel_0word2 = l[0].split().index('1word2'...
Absolute position from relative
Provided that I have a Python list of strings of words, how do I get absolute position of a given word in the whole list, as opposed to relative position within the string? l = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1'] rel_0word2 = l[0].split().index('1word2') # equals 2 abs_0word2 = ??? # equal...
[ "Not sure on what you mean on absolute position, please find below my sample:\nl = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']\n\nprint [x for w in l for x in w.split()].index('1word2')\n\nOr:\ndef get_abs_pos(lVals, word):\n return [i for i,x in enumerate([x for w in l for x in w.split()])...
[ 3, 1, 0, 0 ]
[ "Use string.find, as can be viewed in the docs here.\nl = ['0word0 0word1 0word2', '1word0 1word1 1word2', '2word0 2word1']\nindex = l[0].find('0word2')\n\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0007091460_list_python.txt
Q: Complex server logic and node.js I love node.js, socket.io, the templating engines, etc: as a web framework, it's amazing. A lot of my back-end work is with NLP, Machine Learning, and Data Mining, for which there exist hundreds of rock-solid Python libraries, but no Javascript libraries. If I were using Django, I'...
Complex server logic and node.js
I love node.js, socket.io, the templating engines, etc: as a web framework, it's amazing. A lot of my back-end work is with NLP, Machine Learning, and Data Mining, for which there exist hundreds of rock-solid Python libraries, but no Javascript libraries. If I were using Django, I'd just import the libraries and chug a...
[ "I think you have answered your own question. Python has greater maturity and by your own admission has the libraries you require. Could you narrow down your requirements a bit more?\n" ]
[ 2 ]
[]
[]
[ "node.js", "python" ]
stackoverflow_0007091583_node.js_python.txt
Q: Problems when compiling the Open Kinect drivers for Python on Windows I'm trying to compile the Open Kinect drivers for Python on Windows I made a Make file with CMake (link) and tried compiling it with VC++ Express. Everything seems to compile alright (the viewer sample works), except for the Python wrapper. I ch...
Problems when compiling the Open Kinect drivers for Python on Windows
I'm trying to compile the Open Kinect drivers for Python on Windows I made a Make file with CMake (link) and tried compiling it with VC++ Express. Everything seems to compile alright (the viewer sample works), except for the Python wrapper. I changed the output folder of freenect, which places freenect.lib in another f...
[ "Somehow the linker got a wrong argument: the output file matches one of the input files.\nIs C:/IvoPython/Kinnect/Driver an exisiting path from your download ?\nYou should try to choose a build target outside Kinnect, maybe C:/IvoPython/build\n" ]
[ 2 ]
[]
[]
[ "kinect", "python" ]
stackoverflow_0006870884_kinect_python.txt
Q: How do closures work in runpy? I get unexpected behaviour when I try to run methods defined in a file loaded using the runpy module. The methods do not see any variables (including imported modules) defined outside of that method. Here is how I am doing it: #test.py import runpy env = runpy.run_path('test', {'y':'...
How do closures work in runpy?
I get unexpected behaviour when I try to run methods defined in a file loaded using the runpy module. The methods do not see any variables (including imported modules) defined outside of that method. Here is how I am doing it: #test.py import runpy env = runpy.run_path('test', {'y':'world'}) env['fn']() ~ #test import...
[ "OK, this is a curiosity of the way Python handles modules, which I know about but don't fully understand. I've come across it while working on IPython, where it's explained in a comment.\nWhen Python runs a module, it produces a module object, the attributes of which are the global names in the module. When the mo...
[ 4 ]
[]
[]
[ "closures", "python", "runpy" ]
stackoverflow_0007092000_closures_python_runpy.txt
Q: Python won't run everytime i try to run it, why is this? Firstly, sorry i'm just a beginner. Everytime i try to run/open python an IDLE subprocess error message comes up saying 'socket error: conection refused'. I'm not sure what to do about it, and because of this i can't use python. Could anyone help me please? ...
Python won't run everytime i try to run it, why is this?
Firstly, sorry i'm just a beginner. Everytime i try to run/open python an IDLE subprocess error message comes up saying 'socket error: conection refused'. I'm not sure what to do about it, and because of this i can't use python. Could anyone help me please?
[ "On Windows, you have to create a firewall rule for IDLE, since it uses a network connection for certain tasks. Unfortunately I could not find any documentation on this topic, but I think it can be read in the IDLE README.\n", "You've probably got some kind of firewall in place that prevents IDLE from opening a l...
[ 0, 0 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0007092639_python_python_idle.txt
Q: Concise way to call ifilter with multiple predicates in python I'm streaming a very large collection through a script and am currently using ifilter in a simple call to reject certain values, i.e.: ifilter(lambda x: x in accept_list, read_records(filename)) That's one predicate, but now it's occurred to me I shou...
Concise way to call ifilter with multiple predicates in python
I'm streaming a very large collection through a script and am currently using ifilter in a simple call to reject certain values, i.e.: ifilter(lambda x: x in accept_list, read_records(filename)) That's one predicate, but now it's occurred to me I should add another, and I might want to add others in the future. The st...
[ "You could write the following function:\ndef conjoin(*fns):\n def conjoined(x):\n for fn in fns:\n if not fn(x): return False\n return True\n return conjoined\n\nYou would then call it like so:\nifilter(conjoined(lambda x: x not in block_list, lambda x: x in accept_list),\n re...
[ 5, 1, 0 ]
[]
[]
[ "functional_programming", "iterator", "python" ]
stackoverflow_0003141958_functional_programming_iterator_python.txt
Q: "No module named fcntl" when py script run from c# but works from windows command line I am calling a python script that uses imaplib.py and get the "no module named fcntl" error. From searching I found that this module is only available in unix and so I wonder if the py script is confused about what os it is run...
"No module named fcntl" when py script run from c# but works from windows command line
I am calling a python script that uses imaplib.py and get the "no module named fcntl" error. From searching I found that this module is only available in unix and so I wonder if the py script is confused about what os it is running under. Again, script works fine under windows run directly from the python directory. ...
[ "First of all you're setting sys.platform to a list, it should be a string. .NET/CLI is a different platform than Win32 though, so just setting sys.platform won't help.\nSome Googling suggests IronPython doesn't support the subprocess module (or the module doesn't support IronPython). There is a partial replacement...
[ 3, 0 ]
[]
[]
[ ".net", "c#", "ironpython", "python" ]
stackoverflow_0004027157_.net_c#_ironpython_python.txt
Q: Child function with additional conditions Say I have the following: class Parent(object): [...] def func(self, list): for item in list: if condition1: do something class Child(Parent): [...] def func(self, list): for item in list: if conditio...
Child function with additional conditions
Say I have the following: class Parent(object): [...] def func(self, list): for item in list: if condition1: do something class Child(Parent): [...] def func(self, list): for item in list: if condition1 and condition2: do something...
[ "If you have access to Parent, you could do\nclass Parent(object):\n [...]\n def _condition(self, whatever):\n return condition1\n def func(self, list):\n for item in list:\n if self._condition(...):\n do something\n\nclass Child(Parent):\n [...]\n def _conditi...
[ 6, 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007093009_python.txt
Q: Learn python the hard way, exercise 35 I'm having some problems with exercise 35 in "Learn python the hard way". def bear_room(): print "There is a bear here." print "The bear has a bunch of honey." print "The fat bear is in front of another door." print "How are you going to move the bear?" be...
Learn python the hard way, exercise 35
I'm having some problems with exercise 35 in "Learn python the hard way". def bear_room(): print "There is a bear here." print "The bear has a bunch of honey." print "The fat bear is in front of another door." print "How are you going to move the bear?" bear_moved = False while True: ne...
[ "a) The while loop does not test bear_movedit tests True which is, well, always true.\nb) The difference is, you may only move the bear once - a second time would be fatal. This serves to distinguish. But I don't consider it good style - a better way would be\n elif next == \"taunt bear\":\n if bear_moved...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007093028_python.txt
Q: Getting the two letter language code of the client This is probably a very common question but after a lot of Googling, I'm still yet to find a useful answer. My site is only in English but I like to keep logs of the user's sessions and I need to get the client's language. I've read that I can get the the language...
Getting the two letter language code of the client
This is probably a very common question but after a lot of Googling, I'm still yet to find a useful answer. My site is only in English but I like to keep logs of the user's sessions and I need to get the client's language. I've read that I can get the the language information from the HTTP_ACCEPT_LANGUAGE header which ...
[ "Use translation.get_language_from_request :\nfrom django.utils import translation\n\ndef view(request):\n\n client_lang = translation.get_language_from_request(request)\n\nBy the way why you want this ? did you check django support for i18n and l10n, because\nif you have the LocaleMiddleware enable you can also...
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007092821_django_python.txt
Q: string comprehension in Python I am working with images that have multiple layer which are described in their meta data that looks like this.. print layers Cube1[visible:true, mode:Normal]{r:Cube1.R, g:Cube1.G, b:Cube1.B, a:Cube1.A}, Ground[visible:true, mode:Lighten, opacity:186]{r:Ground.R, g:Ground.G, b:Ground....
string comprehension in Python
I am working with images that have multiple layer which are described in their meta data that looks like this.. print layers Cube1[visible:true, mode:Normal]{r:Cube1.R, g:Cube1.G, b:Cube1.B, a:Cube1.A}, Ground[visible:true, mode:Lighten, opacity:186]{r:Ground.R, g:Ground.G, b:Ground.B, a:Ground.A}, Cube3[visible:true, ...
[ "Parsing (Pyparsing et al) is surely the correct and extensible way to go, but here's a fast-and-dirty object and constructors using regexes and comprehensions to parse properties and bolt them on with setattr(). All constructive criticisms welcome!\nimport re\n#import string\n\nclass Layer(object):\n @classmeth...
[ 0, 0 ]
[]
[]
[ "metadata", "python", "string" ]
stackoverflow_0007084334_metadata_python_string.txt
Q: Python matplotlib plotting an array with different colors I have a file that combines data sets from different sources but preserves the common format. I want to plot these using different colors to indicate the different sources of the data sets. For example, a few lines in the data file look like this: # Source ...
Python matplotlib plotting an array with different colors
I have a file that combines data sets from different sources but preserves the common format. I want to plot these using different colors to indicate the different sources of the data sets. For example, a few lines in the data file look like this: # Source measurement1 measurement2 error color SiteA 543.2 12.3 0.01 bl...
[ "If you don't have too many colours, you should be able to speed things up by plotting in groups of colours, i.e. calling pyplot.errorbar() once for each colour. Use list comprehension to group the data into colour groups, and provide lists or arrays instead of scalars for measurement1, measurement2 etc.\n" ]
[ 2 ]
[]
[]
[ "matplotlib", "plot", "python" ]
stackoverflow_0007092902_matplotlib_plot_python.txt
Q: Given two python lists of same length. How to return the best matches of similar values? Given are two python lists with strings in them (names of persons): list_1 = ['J. Payne', 'George Bush', 'Billy Idol', 'M Stuart', 'Luc van den Bergen'] list_2 = ['John Payne', 'George W. Bush', 'Billy Idol', 'M. Stuart', 'Luc...
Given two python lists of same length. How to return the best matches of similar values?
Given are two python lists with strings in them (names of persons): list_1 = ['J. Payne', 'George Bush', 'Billy Idol', 'M Stuart', 'Luc van den Bergen'] list_2 = ['John Payne', 'George W. Bush', 'Billy Idol', 'M. Stuart', 'Luc Bergen'] I want a mapping of the names, that are most similar. 'J. Payne' -> 'John...
[ "Using the function defined here: http://hetland.org/coding/python/levenshtein.py\n>>> for i in list_1:\n... print i, '==>', min(list_2, key=lambda j:levenshtein(i,j))\n... \n\n\nJ. Payne ==> John Payne\nGeorge Bush ==> George W. Bush\nBilly Idol ==> Billy Idol\nM Stuart ==> M. Stuart\nLuc van den Bergen ==> Lu...
[ 11, 10, 2 ]
[]
[]
[ "list", "mapping", "python", "string" ]
stackoverflow_0007062340_list_mapping_python_string.txt
Q: Conjoin function made in functional style Recently, reading Python "Functional Programming HOWTO", I came across a mentioned there test_generators.py standard module, where I found the following generator: # conjoin is a simple backtracking generator, named in honor of Icon's # "conjunction" control structure. Pa...
Conjoin function made in functional style
Recently, reading Python "Functional Programming HOWTO", I came across a mentioned there test_generators.py standard module, where I found the following generator: # conjoin is a simple backtracking generator, named in honor of Icon's # "conjunction" control structure. Pass a list of no-argument functions # that retur...
[ "This seems to work, and it's still lazy:\ndef conjoin(gs):\n return [()] if not gs else (\n (val,) + suffix for val in gs[0]() for suffix in conjoin(gs[1:])\n )\n\ndef range3():\n return range(3)\n\nprint list(conjoin([range3, range3]))\n\nOutput:\n[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (...
[ 3, 2 ]
[]
[]
[ "functional_programming", "python" ]
stackoverflow_0007093121_functional_programming_python.txt
Q: Python: ServiceDesk PLus Servlet API I am new to programming in Python and am writing a script for my company. We use ServiceDesk Plus which uses Servlet API. I want to write a script that will auto create/close tickets upon alarms from Solarwinds. I cannot figure out the syntax for auto creating a ticket using t...
Python: ServiceDesk PLus Servlet API
I am new to programming in Python and am writing a script for my company. We use ServiceDesk Plus which uses Servlet API. I want to write a script that will auto create/close tickets upon alarms from Solarwinds. I cannot figure out the syntax for auto creating a ticket using the servlet API in python. Here is what I h...
[ "Maybe try creating a request first, then opening the request?\n params = urllib.urlencode({\n 'operation': 'AddRequest',\n })\n request = urllib2.Request('http://localhost:6970/servlets/RequestServlet/' ,params)\n response = urllib2.urlopen(request)\n\n", "You thus got the following error:\n\nurlli...
[ 1, 1 ]
[]
[]
[ "python", "servlets" ]
stackoverflow_0007092867_python_servlets.txt
Q: Django login system I'm looking for a "ready" example of a Login/Register/Authentication system for my site written in Python (so with Django I suppose). EDIT: I've tried the Django-registration, see this tutorial In the tutorials (see STEP 4), I need to update the file urls.py to: from django.conf.urls.defaults i...
Django login system
I'm looking for a "ready" example of a Login/Register/Authentication system for my site written in Python (so with Django I suppose). EDIT: I've tried the Django-registration, see this tutorial In the tutorials (see STEP 4), I need to update the file urls.py to: from django.conf.urls.defaults import * from django.views...
[ "https://github.com/ubernostrum/django-registration\n\nThis is a user-registration application for Django. There are two registration workflows (one-step, and two-step with activation) built in, and it's designed to be extensible and support building additional workflows.\n\n", "Try django-registration or Pinax.\...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007093744_django_python.txt
Q: Python: Seeing all files in Hex I am writing a python script which looks at common computer files and examines them for similar bytes, words, double word's. Though I need/want to see the files in Hex, ande cannot really seem to get python to open a simple file in python. I have tried codecs.open with hex as the ...
Python: Seeing all files in Hex
I am writing a python script which looks at common computer files and examines them for similar bytes, words, double word's. Though I need/want to see the files in Hex, ande cannot really seem to get python to open a simple file in python. I have tried codecs.open with hex as the encoding, but when I operate on the f...
[ "codecs.open(_file, \"rb\", \"hex\") is trying to decode the file's contents as being hex, which is why it's failing on you.\nConsidering your other \"word at a time\" target (I assume you mean \"computer word\", i.e. 32 bits?), you'll be better off encapsulating the open file into a class of your own. E.g.:\nclas...
[ 4, 1, 1 ]
[]
[]
[ "hex", "python" ]
stackoverflow_0002894190_hex_python.txt
Q: Question about safe=True parameter for update operation of mongodb Im working a mongodb database using pymongo python module. I have a function in my code which when called updates the records in the collection as follows. for record in coll.find(<some query here>): #Code here #... #... coll.update({ '...
Question about safe=True parameter for update operation of mongodb
Im working a mongodb database using pymongo python module. I have a function in my code which when called updates the records in the collection as follows. for record in coll.find(<some query here>): #Code here #... #... coll.update({ '_id' : record['_id'] },record) Now, if i modify the code as follows : f...
[ "try and except never cause an exception to be thrown. They simply handle thrown exceptions.\nIf update throws an exception on failure, the except will handle the exception, then the loop will continue (unless you use raise in the except clause).\nIf update doesn't throw an exception on failure, but instead returns...
[ 3, 3 ]
[]
[]
[ "mongodb", "pymongo", "python" ]
stackoverflow_0007092407_mongodb_pymongo_python.txt
Q: Modifiers for HyperlinkEvent? I've got a wxPython application where I'm using an AuiNotebook, and HyperlinkCtrl widgets, to present the user with an interface sort of like tabbed web browsing. Currently I open links in new tabs, or the current one, depending on the kind of link, etc. I'd like to let the users cont...
Modifiers for HyperlinkEvent?
I've got a wxPython application where I'm using an AuiNotebook, and HyperlinkCtrl widgets, to present the user with an interface sort of like tabbed web browsing. Currently I open links in new tabs, or the current one, depending on the kind of link, etc. I'd like to let the users control whether or not they get a new w...
[ "use wx.GetKeyState(int id):\n(docs)\n\nGet the state of a key (true if pressed or toggled on, false if not.)\n This is generally most useful getting the state of the modifier or\n toggle keys. On some platforms those may be the only keys that this\n function is able to detect.\n\nif wx.GetKeyState(wx.WXK_CONTR...
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007088480_python_wxpython.txt
Q: python virtualenv - some python core libraries are missing I'm trying to set-up a virtualenv with Python 2.6.6 on CentOS 5. I've already Python 2.6.6 installed in my home directory, working well. However, when I try to set-up a virtualenv, I got the following error (cf. end for full log): ImportError: No module na...
python virtualenv - some python core libraries are missing
I'm trying to set-up a virtualenv with Python 2.6.6 on CentOS 5. I've already Python 2.6.6 installed in my home directory, working well. However, when I try to set-up a virtualenv, I got the following error (cf. end for full log): ImportError: No module named _md5 By looking at other threads, this errors occurs when c...
[ "AFAIK _md5 depends on some openssl packages. You should install them first.\nYou may also find this thread useful.\n" ]
[ 1 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0007094074_python_virtualenv.txt
Q: monitor stuck python processes I have a python script that performs URL requests using the urllib2. I have a pool of 5 processes that run asynchronously and perform a function. This function is the one that makes the url calls, gets data, parses it into the required format, performs calculations and inserts data. ...
monitor stuck python processes
I have a python script that performs URL requests using the urllib2. I have a pool of 5 processes that run asynchronously and perform a function. This function is the one that makes the url calls, gets data, parses it into the required format, performs calculations and inserts data. The amount of data varies for each u...
[ "Implement a ping mechanism if you are so inclined to use multiprocessing. You're looking for processes that have become stuck because of slow I/O, I assume?\nPersonally I would go with a queue (not necessarily a queue server), say for example ~/jobs is a list of URLs to work on, then have a program that takes the ...
[ 1, 0 ]
[]
[]
[ "multiprocessing", "python", "urllib2" ]
stackoverflow_0007030559_multiprocessing_python_urllib2.txt
Q: efficiently turning a ctypes LP_c_ubyte into a python 'str' I'm having problems with a ctypes binding, and the ctypes docs are making my head hurt a little. I have a remote network client sending binary data and the library I'm using (Mosquitto, for MQTT message brokers) provides a ctypes method for getting the or...
efficiently turning a ctypes LP_c_ubyte into a python 'str'
I'm having problems with a ctypes binding, and the ctypes docs are making my head hurt a little. I have a remote network client sending binary data and the library I'm using (Mosquitto, for MQTT message brokers) provides a ctypes method for getting the original binary data from the network. This is a "LP_c_ubyte" type...
[ "I think this should do what you want:\nimport ctypes\npp = ctypes.string_at(msg.payload, msg.payloadlen)\n\n" ]
[ 5 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0007082788_ctypes_python.txt
Q: how to use Python SaveAs dialog I'm trying to find a python function for presenting a 'save file as' dialog that returns a filename as a string. I quickly found the tkFileDialog module, only to realize that its asksaveasfilename function throws an exception if the file entered doesn't already exist, which is not ...
how to use Python SaveAs dialog
I'm trying to find a python function for presenting a 'save file as' dialog that returns a filename as a string. I quickly found the tkFileDialog module, only to realize that its asksaveasfilename function throws an exception if the file entered doesn't already exist, which is not the behavior I'm looking for. I think...
[ "Here is a small example for the asksaveasfilename() function. I hope you can use it:\nimport Tkinter, Tkconstants, tkFileDialog\n\nclass TkFileDialogExample(Tkinter.Frame):\n\n def __init__(self, root):\n\n Tkinter.Frame.__init__(self, root)\n button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pa...
[ 7 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007094324_python_tkinter.txt
Q: Extract real time data from ajax website in python I would like to extract real time data from a webpage: http://www.fxstreet.com/rates-charts/forex-rates/ I am programming in Python and I did an urlopen to take the htmlcode. Then I used regular expressions to extract the numbers. Problem is that I have to do an u...
Extract real time data from ajax website in python
I would like to extract real time data from a webpage: http://www.fxstreet.com/rates-charts/forex-rates/ I am programming in Python and I did an urlopen to take the htmlcode. Then I used regular expressions to extract the numbers. Problem is that I have to do an urlopen each second to get the latest data, its long not ...
[ "Here's something to get you going. Try the following from the command line:\ncurl -d '[{\"channel\":\"/meta/connect\",\"connectionType\":\"xhr-streaming\",\"id\":\"15\",\"clientId\":\"14799ac3-a0ac-43ab-8bb6-baad56886e11\"}]' \"http://ttpush.fxstreet.com/http_push/connect\"\n\nAs you can see, as long as you keep ...
[ 1 ]
[]
[]
[ "ajax", "python" ]
stackoverflow_0007090997_ajax_python.txt
Q: ExtJS 4.0 Grid Date Column and Form Date Field (browser timezone issues) The Date Column in Grid (also in date form field) is using local browser time zone, but I prefer to use time zone selected in application user profile, rather than using browser timezone. What can I do about it? Can I forse ExtJS to use time...
ExtJS 4.0 Grid Date Column and Form Date Field (browser timezone issues)
The Date Column in Grid (also in date form field) is using local browser time zone, but I prefer to use time zone selected in application user profile, rather than using browser timezone. What can I do about it? Can I forse ExtJS to use timezone without daylight saving time, so all the date/time combinations are valid...
[ "In your EXT code, instead of specifying the date as new Date(), calculate the required date and use: new Date(\"October 13, 2011 11:13:00\") (or whatever your preferred date is). You can do this using convert: in your field definitions.\nEDIT: I would assume that the Date column in your grid gets its value from yo...
[ 1 ]
[]
[]
[ "django", "extjs", "postgresql", "python", "timezone" ]
stackoverflow_0007094617_django_extjs_postgresql_python_timezone.txt
Q: Multiple processes sharing a listening socket: When a new process enters why does the old one stop? These code is the Server part of my proxy program, and its function is creating the socket and fork four process to accept one by one. In my program I use gevent model to dispatch all my function and before I alter...
Multiple processes sharing a listening socket: When a new process enters why does the old one stop?
These code is the Server part of my proxy program, and its function is creating the socket and fork four process to accept one by one. In my program I use gevent model to dispatch all my function and before I alter it to multiple process, my program is all right. but now when I use the second process, the first one s...
[ "accept() is a blocking call. It'll wait indefinitely for a client to connect. Holding a mutex over a blocking operation like that is a Bad IdeaTM since you totally lock all other concurrent processes out.\nAlso, as @Maxim noted in the comments, you don't really need to lock around accept(). Just let the OS arbitra...
[ 1 ]
[]
[]
[ "gevent", "multiprocess", "python", "sockets" ]
stackoverflow_0007091166_gevent_multiprocess_python_sockets.txt
Q: How to wait until stdout has finished writing to file Im trying to wait for stdout to finish writing to file. Does anyone have any ideas on how I can do this? Heres the piece of code: Code: Select all session = open("c:\\sessionID.txt", "w") #Execute previous exe and output session to text file from the current d...
How to wait until stdout has finished writing to file
Im trying to wait for stdout to finish writing to file. Does anyone have any ideas on how I can do this? Heres the piece of code: Code: Select all session = open("c:\\sessionID.txt", "w") #Execute previous exe and output session to text file from the current directory cmd = os.path.realpath(os.getcwd()) +"\\Program.ex...
[ "Use the process.wait() (as explained in the Popen documentation) method after starting it, and it will wait the end of the execution....\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0007095136_python.txt
Q: Defining a color in python I have a question that may be straight forward, or may be impossible to answer, I'm not sure. I'm wondering how I can define a color in python. For example, I would like to simply do this: myColor = #920310 However, using the '#' sign in python automatically comments anything following....
Defining a color in python
I have a question that may be straight forward, or may be impossible to answer, I'm not sure. I'm wondering how I can define a color in python. For example, I would like to simply do this: myColor = #920310 However, using the '#' sign in python automatically comments anything following. Is there a way around this? Tha...
[ "If you want it as a string, do \nmyColor = '#920310'\n\nIf you actually want it to be a Color object, you can do something like\nmyColor = Color('#920310')\n\nand interpret it in Color's constructor.\nIf the question is can you make # not be interpreted as a comment, then the answer is no. If # wasn't a comment, i...
[ 10, 3, 2, 1 ]
[]
[]
[ "colors", "python" ]
stackoverflow_0007095441_colors_python.txt
Q: How to fill array missing elements? I have a simple arrary: a = [1,2,3,6,7,10,11,12,15,16] How to fill array missing elements ? A: range(min(a), max(a) + 1) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
How to fill array missing elements?
I have a simple arrary: a = [1,2,3,6,7,10,11,12,15,16] How to fill array missing elements ?
[ "range(min(a), max(a) + 1)\n# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\n\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0007095558_python.txt
Q: How can I call/run a software by python? I'm trying to make a simple script to run different tasks one by one (one after another) but I don't know how can I run the program by python script! I know that it should be simple! but I couldn't find it any where. my example is this: samtools merge filename.bam file1.sor...
How can I call/run a software by python?
I'm trying to make a simple script to run different tasks one by one (one after another) but I don't know how can I run the program by python script! I know that it should be simple! but I couldn't find it any where. my example is this: samtools merge filename.bam file1.sorted.bam file2.sorted.bam file3.sorted.bam file...
[ "from subprocess import call # call runs an external program and waits for it to quit\n\nfor command in (\"samtools merge filename.bam file1.sorted.bam file2.sorted.bam file3.sorted.bam file4.sorted.bam\", \n \"samtools index filename.bam\", \n \"samtools idxstats filename.bam > filena...
[ 4, 3 ]
[]
[]
[ "call", "file_io", "python" ]
stackoverflow_0007095734_call_file_io_python.txt
Q: Python and libxml2: how to iterate in xml nodes with XPATH I have a problem with retrieving information from a XML tree. My XML has this shape: <?xml version="1.0"?> <records xmlns="http://www.mysyte.com/foo"> <record> <id>first</id> <name>john</name> <papers> <paper>john_1</paper> <paper...
Python and libxml2: how to iterate in xml nodes with XPATH
I have a problem with retrieving information from a XML tree. My XML has this shape: <?xml version="1.0"?> <records xmlns="http://www.mysyte.com/foo"> <record> <id>first</id> <name>john</name> <papers> <paper>john_1</paper> <paper>john_2</paper> </papers> </record> <record> <id>sec...
[ "Here is a suggestion. Note the setContextNode() method:\nimport libxml2\n\nxml = \"test.xml\"\ndoc = libxml2.parseFile(xml) \n\nctxt = doc.xpathNewContext() \nctxt.xpathRegisterNs(\"pre\",\"http://www.mysyte.com/foo\") \n\nret_list = []\nrecord_nodes = ctxt.xpathEval('/pre:records/pre:record') \n\nfor node in reco...
[ 7, 0, 0 ]
[ "libxslt lacks such an important namespace support for some reason, but we can pre-parse the xml file, pre-read namespaces from it and then call xsltproc with those namespaces\ndef xpath(xml, xpathexpression):\n f=open(xml)\n fcontent = f.read()\n f.close()\n\n doc=libxml2.parseFile(xml)\n xp = doc.x...
[ -1 ]
[ "libxml2", "python", "xml", "xpath" ]
stackoverflow_0003366032_libxml2_python_xml_xpath.txt
Q: Forcing compatibility of inherited types (Python) Assume someone gave you an existing pair of classes that work together: class non_unique_collection: def __init__(self): self.all_items = [] def add_new_item(self, item): self.all_items.append(item) def __len__(self): return len(...
Forcing compatibility of inherited types (Python)
Assume someone gave you an existing pair of classes that work together: class non_unique_collection: def __init__(self): self.all_items = [] def add_new_item(self, item): self.all_items.append(item) def __len__(self): return len(self.all_items) ## ... ## there are several oth...
[ "Think twice if you really want to enforce this. Strict type checking is not recommended for Python since it prevents \"duck typing\".\nFurthermore, inheritance in object-oriented programming models an is-a relationship. Since unique_ranked_collection inherits from non_unique_ranked_collection, an instance of th...
[ 1, 0 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0007095042_inheritance_python.txt
Q: Appending to a csv file in Python Hi I have a csv file with names and surnames and empty username and password columns. How can I use python csv to write to the columns 3 and 4 in each row, just appending to it, not overwriting anything. A: The csv module doesn't do that, you'd have to write it out to a separate...
Appending to a csv file in Python
Hi I have a csv file with names and surnames and empty username and password columns. How can I use python csv to write to the columns 3 and 4 in each row, just appending to it, not overwriting anything.
[ "The csv module doesn't do that, you'd have to write it out to a separate file then overwrite the old file with the new one, or read the whole file into memory and then write over it.\nI'd recommend the first option:\nfrom csv import writer as csvwriter, reader as cvsreader\nfrom os import rename # add ', remove' o...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0007096138_python.txt
Q: Add django model manager code-completion to Komodo I have been using ActiveState Komodo for a while and while most of the code-completion is spot on it lacks the code completion from Django's model manager. I have included the Django directory in my PYTHONPATH and get most of the code completion, the notable excep...
Add django model manager code-completion to Komodo
I have been using ActiveState Komodo for a while and while most of the code-completion is spot on it lacks the code completion from Django's model manager. I have included the Django directory in my PYTHONPATH and get most of the code completion, the notable exception being the models. Assuming I have a model users I w...
[ "Probably the easiest way to get this to work seems to be to add the following to the top of models.py:\nfrom django.db.models import manager\n\nand then under each model add\nobjects = manager.Manager()\n\nso that, for example, the following:\nclass Site(models.Model):\n name = models.CharField(max_length=200)\...
[ 0 ]
[]
[]
[ "django", "komodo", "python" ]
stackoverflow_0007096090_django_komodo_python.txt
Q: Why to use Parrot (or other VM) if I have an interpreter? Why should I use VM, like Parrot, for a dynamic language I use (Python, Perl, ...) if I already have an interpreter? What can I potentially gain, for the cost of having different VM between my code and my machine, and by using a separate interpreter? (I am ...
Why to use Parrot (or other VM) if I have an interpreter?
Why should I use VM, like Parrot, for a dynamic language I use (Python, Perl, ...) if I already have an interpreter? What can I potentially gain, for the cost of having different VM between my code and my machine, and by using a separate interpreter? (I am new in VM issue, so maybe the answer is obvious) EDIT What's th...
[ "\nWhy should I use VM, like Parrot, for a dynamic language I use (Python, Perl, ...) if I already have an interpreter?\n\nFirst, if you're starting a project, then you may not already have an interpreter.\nHowever, assuming you have an interpreter and are considering whether to add functionality to it or rewrite i...
[ 5, 4 ]
[]
[]
[ "interpreter", "parrot", "perl", "python", "vm_implementation" ]
stackoverflow_0007093883_interpreter_parrot_perl_python_vm_implementation.txt
Q: Gdal will not import after several installs (Mac OSX) Using Macports, I've tried to install: gdal, py27gdal, and gdal-grass. All so I can import gdal into python 2.7.2. Neither have been successful. When I type: port list installed I see the installed modules: gdal-grass @1.4.3 gis/...
Gdal will not import after several installs (Mac OSX)
Using Macports, I've tried to install: gdal, py27gdal, and gdal-grass. All so I can import gdal into python 2.7.2. Neither have been successful. When I type: port list installed I see the installed modules: gdal-grass @1.4.3 gis/gdal-grass gdbm @1.8.3 ...
[ "Are you using the MacPorts python2.7? Try launching Python this way:\n/opt/local/bin/python2.7\n\n", "I'm not 100% sure if this solves your problem, but gdal is in the osgeo namespace. So you should try importing gdal like this:\nfrom osgeo import gdal\n\nThe gdal namespace itself is deprecated.\n" ]
[ 2, 0 ]
[]
[]
[ "gdal", "import", "macos", "macports", "python" ]
stackoverflow_0007094749_gdal_import_macos_macports_python.txt
Q: In numpy, what is the fastest way to multiply the second dimension of a 3 dimensional array by a 1 dimensional array? You have an array of shape (a,b,c) and you want to multiply the second dimension by an array of shape (b) A for loop would work, but is there a better way? Ex. A = np.array(shape=(a,b,c)) B = np.a...
In numpy, what is the fastest way to multiply the second dimension of a 3 dimensional array by a 1 dimensional array?
You have an array of shape (a,b,c) and you want to multiply the second dimension by an array of shape (b) A for loop would work, but is there a better way? Ex. A = np.array(shape=(a,b,c)) B = np.array(shape=(b)) for i in B.shape[0]: A[:,i,:]=A[:,i,:]*B[i]
[ "Use broadcasting:\nA*B[:,np.newaxis]\n\nFor example:\nIn [47]: A=np.arange(24).reshape(2,3,4)\n\nIn [48]: B=np.arange(3)\n\nIn [49]: A*B[:,np.newaxis]\nOut[49]: \narray([[[ 0, 0, 0, 0],\n [ 4, 5, 6, 7],\n [16, 18, 20, 22]],\n\n [[ 0, 0, 0, 0],\n [16, 17, 18, 19],\n [40, 4...
[ 6 ]
[]
[]
[ "arrays", "multidimensional_array", "numpy", "python" ]
stackoverflow_0007096371_arrays_multidimensional_array_numpy_python.txt
Q: Python - How to raise a value error of multiple items in list If I have a list of items which is going to be in the end a binary number, how do I get the program to say value error (or something similar) when the list is longer than 8 numbers and not a 1 or a 0??? i.e [1,0,2,0,1,0,0,0,1] This should give an error ...
Python - How to raise a value error of multiple items in list
If I have a list of items which is going to be in the end a binary number, how do I get the program to say value error (or something similar) when the list is longer than 8 numbers and not a 1 or a 0??? i.e [1,0,2,0,1,0,0,0,1] This should give an error saying the list has an non 1 or 0 number and its more that 8 number...
[ "This will do it. Whether it's as clean as you want is up to you:\nif len(l1) != 8 or len([n for n in l1 if n not in (1, 0)]) != 0:\n raise ValueError('Invalid entries or incorrect length')\n\n", "if len(my_list) > 8 or any((x is not 0) and (x is not 1) for x in my_list):\n raise ValueError\n\nDoesn't create...
[ 1, 1, 0 ]
[]
[]
[ "binary", "python" ]
stackoverflow_0007096578_binary_python.txt
Q: python/serial broken in OSX lion / launchd I have a launchd entry that worked with OSX 10.6 but that fails with 10.7. It uses python, and it produces an error whilst trying to import serial. I don't quite understand this, because I've re-downloaded pyserial-2.5 and re-installed it with sudo. (In desperation, I ...
python/serial broken in OSX lion / launchd
I have a launchd entry that worked with OSX 10.6 but that fails with 10.7. It uses python, and it produces an error whilst trying to import serial. I don't quite understand this, because I've re-downloaded pyserial-2.5 and re-installed it with sudo. (In desperation, I re-installed it for each of the many flavours of...
[ "The path you are appending:\n/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages\nis the site-packages directory for a third-party, non-system Python, possibly installed using a python.org installer, and not that of the Apple-supplied system Python 2.7, which would be:\n/Library/Python/2....
[ 1, 0 ]
[]
[]
[ "launchd", "macos", "osx_lion", "pyserial", "python" ]
stackoverflow_0007093689_launchd_macos_osx_lion_pyserial_python.txt
Q: How to change a list of strings to integers - Python Possible Duplicate: How to convert strings into integers in python? I need to change a list of strings into a list of integers how do i do this i.e ('1', '1', '1', '1', '2') into (1,1,1,1,2). A: Use list comprehensions: strtuple = ('1', '1', '1', '1', '2') i...
How to change a list of strings to integers - Python
Possible Duplicate: How to convert strings into integers in python? I need to change a list of strings into a list of integers how do i do this i.e ('1', '1', '1', '1', '2') into (1,1,1,1,2).
[ "Use list comprehensions:\nstrtuple = ('1', '1', '1', '1', '2')\nintlist = [int(s) for s in strtuple]\n\nStuff for completeness:\nAs your “list” is in truth a tuple, i.e. a immutable list, you would have to use a generator expression together with a tuple constructor to get another tuple back:\ninttuple = tuple(int...
[ 8, 2, 2, 0 ]
[]
[]
[ "integer", "python", "string" ]
stackoverflow_0007097058_integer_python_string.txt
Q: I keep getting "list index out of range" in Python when the list has the correct index I am new to Python and am getting the list index error, when I shouldn't. I have the following variable: date_array = ['2001','15','1'] I can access the first index. I can only access the last index, if I try something like th...
I keep getting "list index out of range" in Python when the list has the correct index
I am new to Python and am getting the list index error, when I shouldn't. I have the following variable: date_array = ['2001','15','1'] I can access the first index. I can only access the last index, if I try something like this: date_array[-1] I get "list index out of range" error whenever I try: date_array[2] d...
[ "Simple answer is that date_array does not always have 3 elements. If you're going to index the list directly, add a check to make sure that the length is adequate.\nif len(date_array) < 3:\n print('date_array too short')\n # do something else\n\nor alternatively, wrap the index operations in a try block\n", ...
[ 2, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007097049_list_python.txt
Q: cannot import cv on OpenCV2.1 I have downloaded OpenCV2.1 and Python2.6. when i try to import cv using sys.path.append("C:\OpenCV2.1\Python2.6\Lib\site-packages") and then import cv, it tells me ImportError: DLLload failed.. I have tried the solutions given in previous thread to copy the two files in the above pa...
cannot import cv on OpenCV2.1
I have downloaded OpenCV2.1 and Python2.6. when i try to import cv using sys.path.append("C:\OpenCV2.1\Python2.6\Lib\site-packages") and then import cv, it tells me ImportError: DLLload failed.. I have tried the solutions given in previous thread to copy the two files in the above path to C:\Python26\Lib\site-packages...
[ "The OpenCV DLLs seem not to be found. Did you add OpenCV's bin directory to your PATH, \"C:\\OpenCV2.1\\bin\" in your case?\n\nTo use the Python wrappers\nsys.path.append(\"C:\\OpenCV2.1\\Python2.6\\Lib\\site-packages\")\nimport cv\n\nshould work, as well as copying cv.lib and cv.pyd to your C:\\Python26\\Lib\\sit...
[ 1 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0007096064_opencv_python.txt
Q: Why does this __getattr__ function not work? I've got this little class I wrote to try playing with custom __getattr__ methods, and every time I run it, I get an Attribute error: class test: def __init__(self): self.attrs ={'attr':'hello'} def __getattr__(self, name): if name in self.attrs...
Why does this __getattr__ function not work?
I've got this little class I wrote to try playing with custom __getattr__ methods, and every time I run it, I get an Attribute error: class test: def __init__(self): self.attrs ={'attr':'hello'} def __getattr__(self, name): if name in self.attrs: return self.attrs[name] else...
[ "Because the class test doesn't have attr as an attribute, the instance t does:\nclass test:\n def __init__(self):\n self.attrs ={'attr':'hello'}\n def __getattr__(self, name):\n if name in self.attrs:\n return self.attrs[name]\n else:\n raise AttributeError\n\nt = t...
[ 8, 4 ]
[]
[]
[ "getattr", "python" ]
stackoverflow_0007097721_getattr_python.txt
Q: Python Regex MULTILINE option not working correctly? I'm writing a simple version updater in Python, and the regex engine is giving me mighty troubles. In particular, ^ and $ aren't matching correctly even with re.MULTILINE option. The string matches without the ^ and $, but no joy otherwise. I would appreciate yo...
Python Regex MULTILINE option not working correctly?
I'm writing a simple version updater in Python, and the regex engine is giving me mighty troubles. In particular, ^ and $ aren't matching correctly even with re.MULTILINE option. The string matches without the ^ and $, but no joy otherwise. I would appreciate your help if you can spot what I'm doing wrong. Thanks targe...
[ "Change your replace to:\nreplace = r'\\g<1>' + newVersion + r'\\2'\n\nThe problem you're having is your version results in this:\nreplace = \"\\\\101.20.01\\\\2\"\n\nwhich is confusing the sub call as there is no field 101. From the documentation for the Python re module:\n\n\\g<number> uses the corresponding gro...
[ 6, 2 ]
[]
[]
[ "find", "multiline", "python", "regex", "replace" ]
stackoverflow_0007097791_find_multiline_python_regex_replace.txt
Q: What is an attracting component subgraph? What is a attracting component subgraph of a graph? Networkx has an algorithm for this. But I am unable to understand what this is because: >>> g.edges() [(0, 1), (1, 2), (2, 3), (2, 5), (3, 4)] >>> for l in nx.algorithms.components.attracting.attracting_component_subgrap...
What is an attracting component subgraph?
What is a attracting component subgraph of a graph? Networkx has an algorithm for this. But I am unable to understand what this is because: >>> g.edges() [(0, 1), (1, 2), (2, 3), (2, 5), (3, 4)] >>> for l in nx.algorithms.components.attracting.attracting_component_subgraphs(g): ... print l.edges() ... print l....
[ "The definition of an attracting component is provided in the documentation for nx.algorithms.components.attracting_components.\n\nAn attracting component in a directed graph is a strongly connected\n component with the property that a random walker on the graph will\n never leave the component, once it enters t...
[ 7 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0007097627_networkx_python.txt
Q: Remove item in a Python kiwi objectlist I have an generic example from kiwi framework, my question is: How can I remove only a item from kiwi objectlist. Thanks for the time! import gtk from kiwi.ui.objectlist import Column, ObjectList class Fruit: def __init__(self, name, cost): self.name = name ...
Remove item in a Python kiwi objectlist
I have an generic example from kiwi framework, my question is: How can I remove only a item from kiwi objectlist. Thanks for the time! import gtk from kiwi.ui.objectlist import Column, ObjectList class Fruit: def __init__(self, name, cost): self.name = name self.cost = cost fruits = ObjectList([C...
[ "This code:\nfruits.remove(Fruit('Pineapple', 4)) \n\nproduces this error:\nTraceback (most recent call last):\n...\n fruits.remove(Fruit('Pineapple', 4)) #error\n File \"/tmp/kiwi/ui/objectlist.py\", line 1651, in remove\n raise ValueError(\"instance %r is not in the list\" % instance)\nValueError: instan...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007097617_python.txt
Q: Python PIL: best scaling method that preserves lines I have a 2D drawing with a black background and white lines (exported from Autocad) and I want to create a thumbnail preserving lines, using Python PIL library. But what I obtain using the 'thumbnail' method is just a black picture scattered with white dots. Not...
Python PIL: best scaling method that preserves lines
I have a 2D drawing with a black background and white lines (exported from Autocad) and I want to create a thumbnail preserving lines, using Python PIL library. But what I obtain using the 'thumbnail' method is just a black picture scattered with white dots. Note that if I put the image into an IMG tag with fixed width...
[ "The default resizing method used by thumbnail is NEAREST, which is a really bad choice. If you're resizing to 1/5 of the original size for example, it will output one pixel and throw out the next 4 - a one-pixel wide line has only a 1 out of 5 chance of showing up at all in the result!\nThe surprising thing is tha...
[ 14, 3 ]
[]
[]
[ "python", "python_imaging_library", "thumbnails" ]
stackoverflow_0007096323_python_python_imaging_library_thumbnails.txt
Q: How to merge nested tuples I have a set of nested tuples: ('id', ('name', ('name_float_fml',)), ('user', ('email',)), ('user', ('last_login',))) I would like to combine lists with similar prefixes, resulting in: ('id', ('name', ('name_float_fml',)), ('user', ('email','last_login'))) Here is another example: (('b...
How to merge nested tuples
I have a set of nested tuples: ('id', ('name', ('name_float_fml',)), ('user', ('email',)), ('user', ('last_login',))) I would like to combine lists with similar prefixes, resulting in: ('id', ('name', ('name_float_fml',)), ('user', ('email','last_login'))) Here is another example: (('baz', ('bing', ('fizz', 'frozz', ...
[ "Here is a version that works for the examples you posted:\na = ('id', ('name', ('name_float_fml',)), ('user', ('email',)), ('user', ('last_login',)))\nb = (('baz', ('bing', ('fizz', 'frozz',('frazz', ('fry', 'bleep', 'blop'))))), ('baz', ('zap', ('zang',))), 'foo', 'bar')\n\ndef preserve_path(value):\n if len(v...
[ 4, 0, 0 ]
[]
[]
[ "merge", "python", "tree" ]
stackoverflow_0007098802_merge_python_tree.txt
Q: post import hooks in python 2.7 According to PEP 369, post import hooks should be implemented for python 2.6 and 3.0. However, I am unable to register or execute any import hook (according to PEP) in python 2.7. Am I missing something ? A: The PEP is currently in draft stage, hence there's no support for post_im...
post import hooks in python 2.7
According to PEP 369, post import hooks should be implemented for python 2.6 and 3.0. However, I am unable to register or execute any import hook (according to PEP) in python 2.7. Am I missing something ?
[ "The PEP is currently in draft stage, hence there's no support for post_import_hooks for the time being. I missed the part about the status, and I thought it was already approved.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007071372_python.txt
Q: How can I mass rename the all pdfs in Google Docs via API In my Google Docs I have 100s of PDFs but they have underscore separating the words in filename. Now is it possible to rename them on the Google server via API and replace all underscores with space( ). A: These may help http://code.google.com/apis/docume...
How can I mass rename the all pdfs in Google Docs via API
In my Google Docs I have 100s of PDFs but they have underscore separating the words in filename. Now is it possible to rename them on the Google server via API and replace all underscores with space( ).
[ "These may help\nhttp://code.google.com/apis/documents/docs/3.0/developers_guide_python.html#ListDocs\nHere you can find how to go over all documents.\nhttp://code.google.com/apis/documents/docs/3.0/developers_guide_python.html#UpdatingMetadata\nHere you can find how to update the document name.\n" ]
[ 0 ]
[]
[]
[ "google_docs", "google_docs_api", "python" ]
stackoverflow_0006347104_google_docs_google_docs_api_python.txt
Q: Tricky Median Question Given n points, choose a point in the given list such that the sum of distances to this point is minimum ,compared to all others. Distance is measured in the following manner. For a point (x,y) all 8 adjacent points have distance 1. (x+1,y)(x+1,y+1),(x+1,y-1),(x,y+1),(x,y-1),(x-1,y)(x-1,y+1)...
Tricky Median Question
Given n points, choose a point in the given list such that the sum of distances to this point is minimum ,compared to all others. Distance is measured in the following manner. For a point (x,y) all 8 adjacent points have distance 1. (x+1,y)(x+1,y+1),(x+1,y-1),(x,y+1),(x,y-1),(x-1,y)(x-1,y+1),(x-1,y-1) EDIT More cleare...
[ "Update: it sometimes fails to find the optimum, I'll leave this here till I find the problem.\nthis is O(n): nth is O(n) (expected, not worst), iterating over the list is O(n). If you need strict O() then pick the middle element with sorting but then it's going to be O(n*log(n)).\nNote: it's easy to modifiy it to ...
[ 5, 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0007059500_algorithm_python.txt
Q: How to change method defaults in Python? I'm building a class, Child, that inherits from another class, Parent. The Parent class has a loadPage method that the Child will use, except that the Child will need to run its own code near the end of the loadPage function but before the final statements of the function. ...
How to change method defaults in Python?
I'm building a class, Child, that inherits from another class, Parent. The Parent class has a loadPage method that the Child will use, except that the Child will need to run its own code near the end of the loadPage function but before the final statements of the function. I need to somehow insert this function into lo...
[ "For such things, I do it in a different way : \nclass Parent():\n def loadPage(self, pageTitle):\n # do stuff\n self.customFunc()\n # do other stuff\n\n def customFunc(self):\n pass\n\nclass Child(Parent):\n\n def customFunc(self):\n # do the child stuff\n\nthen, a Child instance wou...
[ 4, 2, 2, 0, 0 ]
[]
[]
[ "defaults", "python", "template_method_pattern" ]
stackoverflow_0007100054_defaults_python_template_method_pattern.txt
Q: Reading quicken data files Looking for an open source library, for C++, Java, C# or Python, for reading the data from Quicken .qdf files. @Swati: Quicken .qif format is for transfer only and is not kept up to date by the application like the .qdf file is. A: QDF is proprietary and not really meant for reading ...
Reading quicken data files
Looking for an open source library, for C++, Java, C# or Python, for reading the data from Quicken .qdf files. @Swati: Quicken .qif format is for transfer only and is not kept up to date by the application like the .qdf file is.
[ "QDF is proprietary and not really meant for reading other than my Quicken, probably for a reason as it is messy. \nI would recommend finding a way to export the qdf into an OFX (Open Financial Exchange) or qif file. I have done some financial and quickbooks automation and I did something similar. The problem is...
[ 5, 1, 0 ]
[]
[]
[ "c#", "file_format", "java", "python", "quicken" ]
stackoverflow_0000091890_c#_file_format_java_python_quicken.txt
Q: BeautifulSoup: How to include the encoding on output? I would like to include the encoding tag in an XML document using BeautifulSoup.BeautifulStoneSoup, but I'm not sure how! <?xml version="1.0" encoding="UTF-8"?> <mytag>stuff</mytag> It outputs the encoding tag when I read a document that already has it, but I'...
BeautifulSoup: How to include the encoding on output?
I would like to include the encoding tag in an XML document using BeautifulSoup.BeautifulStoneSoup, but I'm not sure how! <?xml version="1.0" encoding="UTF-8"?> <mytag>stuff</mytag> It outputs the encoding tag when I read a document that already has it, but I'm making a new soup. Thanks! Edit: I'll give an example of ...
[ "Do you mean something like this?\nfrom BeautifulSoup import BeautifulStoneSoup\nsoup = BeautifulStoneSoup('<?xml version=\"1.0\" encoding=\"UTF-8\"?>')\n# make some more soup\n\nOr,\nsoup = BeautifulStoneSoup()\n# make some more soup\nsoup.insert(0, '<?xml version=\"1.0\" encoding=\"UTF-8\"?>')\n\n\nFrom the Beaut...
[ 1 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007100514_beautifulsoup_python.txt
Q: Able to run Python code with Unicode string in Eclipse, but getting UnicodeEncodeError when running via command line or Idle. I've experienced this a lot, where I'll decode/encode some string of Unicode in Eclipse (PyDev), and it runs fine and how I expected, but then when I launch the same script from the command...
Able to run Python code with Unicode string in Eclipse, but getting UnicodeEncodeError when running via command line or Idle.
I've experienced this a lot, where I'll decode/encode some string of Unicode in Eclipse (PyDev), and it runs fine and how I expected, but then when I launch the same script from the command line (for example) instead, I'll get encoding errors. Is there any simple explanation for this? Is Eclipse doing something to the ...
[ "Just wanted to add why it worked on PyDev: it has a special sitecustomize that'll customize python through sys.setdefaultencoding to use the encoding of the PyDev console.\nNote that the response from bobince is correct, if you have a unicode string, you have to use the encode() method to transform it into a prope...
[ 9, 8 ]
[]
[]
[ "eclipse", "pydev", "python", "unicode" ]
stackoverflow_0007096857_eclipse_pydev_python_unicode.txt
Q: How do I stop having carriage returns added to my file output in Python? I'm trying to parse a BMP file, do some changes and then reassemble a new BMP using Python. The carriage return seems to be a huge problem. When I open the bitmap file using Notepad++ and search for "\r', the character does not exist. I rea...
How do I stop having carriage returns added to my file output in Python?
I'm trying to parse a BMP file, do some changes and then reassemble a new BMP using Python. The carriage return seems to be a huge problem. When I open the bitmap file using Notepad++ and search for "\r', the character does not exist. I read the file in Python (readData = fileIn.read()) and try searching using readDa...
[ "You're probably opening the file as text (the default) when you want to open it as binary.\nopen(\"example.bmp\", \"rb\") # to [r]ead as [b]inary\nopen(\"example.bmp\", \"wb\") # to [w]rite as [b]inary\n\nFrom the documentation:\n\nThe default is to use text mode, which may convert '\\n' characters to a platform-s...
[ 8, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0007100698_file_io_python.txt
Q: How execute script from command prompt in python I have mysql dump command that I would like to run from from windows shell or command prompt. I have used shell it does work. d= 'BkSql_'+datetime.datetime.now().strftime("%Y-%m-%d")+".sql" fn = dn+d cmd="""mysqldump -u hapopdy -p > %s""" %fn print c...
How execute script from command prompt in python
I have mysql dump command that I would like to run from from windows shell or command prompt. I have used shell it does work. d= 'BkSql_'+datetime.datetime.now().strftime("%Y-%m-%d")+".sql" fn = dn+d cmd="""mysqldump -u hapopdy -p > %s""" %fn print cmd Edit::::::: The -p needs to be a raw input.
[ "Using the subprocess module\nimport subprocess\nsubprocess.call(cmd)\n\nIf you're running a shell command add shell=True\nsubprocess.call(cmd, shell=True)\n\n", "You should save the password in mysql's local configuration file for the user.(In Unix it's ~/.my.cnf) or you can give it on the command line with --pa...
[ 5, 0 ]
[]
[]
[ "command_line", "python", "shell" ]
stackoverflow_0007100487_command_line_python_shell.txt
Q: Very slow join query on large table (machine = Xeon 2.4 GHz, 16 core, 64 GB RAM) Here is my query : SELECT email_data.id, email_data.source_file, email_data.report_id, email_data.filePath, email_data.fileName, email_data.size, email_data.emailID, email_data.msgID, email_data.cus, email_data.subjec...
Very slow join query on large table (machine = Xeon 2.4 GHz, 16 core, 64 GB RAM)
Here is my query : SELECT email_data.id, email_data.source_file, email_data.report_id, email_data.filePath, email_data.fileName, email_data.size, email_data.emailID, email_data.msgID, email_data.cus, email_data.subject, email_data.sentto, email_data.emailFrom, email_data.hdrs, email_data.cc, ...
[ "It is almost certain that attach_data.emailID is lacking an index. Consider that the query engine must go through every single row of email data, and if the index is missing, it must walk every row of attach_data, even after finding a match.\nYou should run an EXPLAIN on your query to see what MySql is actually d...
[ 3, 1, 1, 1, 0 ]
[]
[]
[ "mysql", "performance", "python", "sql" ]
stackoverflow_0007100228_mysql_performance_python_sql.txt
Q: Idle's Code Context in Eclipse I find the Code Context option of IDLE to be extremely useful when working on big projects. I wanted to know if there is a similar feature for Eclipse? Edit: I would like this feature in CDT and/or PyDev. Example image: http://i38.tinypic.com/95sb39.jpg A: Breadcrump feature can he...
Idle's Code Context in Eclipse
I find the Code Context option of IDLE to be extremely useful when working on big projects. I wanted to know if there is a similar feature for Eclipse? Edit: I would like this feature in CDT and/or PyDev. Example image: http://i38.tinypic.com/95sb39.jpg
[ "Breadcrump feature can help you determine your current context.\n", "That's still not available for PyDev... for now you can either use the outline view and leave it synchronized with the editor or you can use the quick outline (ctrl+O) as it'll focus which method you're in (I know it's not really a substitute, ...
[ 0, 0 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0003500997_eclipse_pydev_python.txt
Q: Flask route with URI encoded component It seems Flask doesn't support routes with a URI encoded component. I'm curious if I'm doing something wrong, or if there is a special flag I need to include. My route looks something like this: @app.route('/foo/<encoded>/bar/') def foo(encoded): # ... pass The URL that...
Flask route with URI encoded component
It seems Flask doesn't support routes with a URI encoded component. I'm curious if I'm doing something wrong, or if there is a special flag I need to include. My route looks something like this: @app.route('/foo/<encoded>/bar/') def foo(encoded): # ... pass The URL that this should match can look like these: http...
[ "Add path to your url rule:\n@app.route('/foo/<path:encoded>/bar/')\nUpdate per comment: The route API docs are here: http://flask.pocoo.org/docs/api/#flask.Flask.route. The underlying classes that implement the path style route converter are here: http://werkzeug.pocoo.org/docs/routing/#custom-converters (this is ...
[ 27 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0007100573_flask_python.txt
Q: get_or_create() takes exactly 1 argument (2 given) Last time I checked, (h) one argument: for entry in f['entries']: h = {'feed':self, 'link': entry['link'],'title':entry['title'], 'summary':entry['summary'], 'updated_at':datetime.fromtimestamp(mktime(entry['updated_parsed']))} en = Entr...
get_or_create() takes exactly 1 argument (2 given)
Last time I checked, (h) one argument: for entry in f['entries']: h = {'feed':self, 'link': entry['link'],'title':entry['title'], 'summary':entry['summary'], 'updated_at':datetime.fromtimestamp(mktime(entry['updated_parsed']))} en = Entry.objects.get_or_create(h) This code is failing with th...
[ "get_or_create takes keyword arguments only. If the arguments are in a dict, you can call it with:\nen = Entry.objects.get_or_create(**h)\n\nOr you can put the keyword arguments directly:\nen = Entry.objects.get_or_create(name=value, ....)\n\nThe reason the error message told you that you supplied two arguments is ...
[ 14 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0007101077_django_django_models_python.txt
Q: How do you make the program auto restart after value error - Python So I have this program to convert a binary to hex. I also have a part that returns a value error if you put in a non 0 or 1 or if the string is more or less than 8 digits. But what I want now with it is if the program does get the value error ho...
How do you make the program auto restart after value error - Python
So I have this program to convert a binary to hex. I also have a part that returns a value error if you put in a non 0 or 1 or if the string is more or less than 8 digits. But what I want now with it is if the program does get the value error how do I code it so that it automatically restarts after the value error.
[ "Put your code into a loop:\nwhile True:\n try:\n # your code here\n # break out of the loop if a ValueError was not raised\n break\n except ValueError:\n pass # or print some error\n\n", "Enclose the code in a while loop.\nwhile True:\n try:\n #your code\n except Va...
[ 2, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007098435_python.txt
Q: Converting Command line argument to standard input in Python How is it possible to convert a script accepting a command-line argument to be able to receive the argument through standard user input? Currently I have a file and to process it I need to run python abc.py query whereas I would like the file to be able ...
Converting Command line argument to standard input in Python
How is it possible to convert a script accepting a command-line argument to be able to receive the argument through standard user input? Currently I have a file and to process it I need to run python abc.py query whereas I would like the file to be able to run through python abc.py and then in the next line it should a...
[ "There is no way to make this happen without changing abc.py itself.\nIf you can change abc.py then a good way is to have it check for the command-line argument, and if it's not there then ask for it... something like this:\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n file_to_process = sys.argv[1...
[ 2 ]
[]
[]
[ "command", "python" ]
stackoverflow_0007100879_command_python.txt
Q: Google App Engine utf-8 coding problem with Python I would appreciate your help with a hopefully trivial issue. Recently I've started learning Python for work with Google App Engine environment. Needlessly to say I began with the simplest Hello World app. The English version of it works just fine However, when I t...
Google App Engine utf-8 coding problem with Python
I would appreciate your help with a hopefully trivial issue. Recently I've started learning Python for work with Google App Engine environment. Needlessly to say I began with the simplest Hello World app. The English version of it works just fine However, when I try to work with the signs in my mother tongue, then the ...
[ "print '<html>'\nprint '<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">'\nprint '<head>'\n\n", "Set the encoding when you set the content type:\nprint 'Content-Type: text/html; charset=UTF-8'\n\nDon't use a meta tag as @bpgergo suggests; it's specific to HTML, and simply overrides the head...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "python", "utf_8" ]
stackoverflow_0007096481_google_app_engine_python_utf_8.txt
Q: Diffing two folders (like the diff tool in Linux) with Python I'm trying to write a project that will have some autonomous components. One of these is the need to diff two folders and spit out the different files into an array of strings. Dircmp does part of this - it spits out the different files. But it would ap...
Diffing two folders (like the diff tool in Linux) with Python
I'm trying to write a project that will have some autonomous components. One of these is the need to diff two folders and spit out the different files into an array of strings. Dircmp does part of this - it spits out the different files. But it would appear it doesn't actually go into the remaining files to see which a...
[ "It seems that filecmp.dircmp does what you want already. If you compare two directories, diff_files will be a list of files which are in both directories, but whose contents differ:\n>>> dc = filecmp.dircmp('dir1', 'dir2')\n>>> dc.diff_files\n<<< ['foo']\n\nAs pointed out by Jonathanb, if you want actual diffs, it...
[ 7 ]
[]
[]
[ "arrays", "diff", "directory", "file_diffs", "python" ]
stackoverflow_0007101373_arrays_diff_directory_file_diffs_python.txt
Q: depth-first algorithm in python does not work I have some project which I decide to do in Python. In brief: I have list of lists. Each of them also have lists, sometimes one-element, sometimes more. It looks like this: rules=[ [[1],[2],[3,4,5],[4],[5],[7]] [[1],[8],[3,7,8],[3],[45],[12]] [[31],[12],[43,24,57],[47]...
depth-first algorithm in python does not work
I have some project which I decide to do in Python. In brief: I have list of lists. Each of them also have lists, sometimes one-element, sometimes more. It looks like this: rules=[ [[1],[2],[3,4,5],[4],[5],[7]] [[1],[8],[3,7,8],[3],[45],[12]] [[31],[12],[43,24,57],[47],[2],[43]] ] The point is to compare values from n...
[ "I am not familiar with Perrier's Loop, but if you code something like famous \"game life\" you would have done simple mistake: store the next generation in the same array thus corrupting it. \nNormally you store the next generation in temporary array and do copy/swap after the sweep, like in this sketch:\ndef do_s...
[ 0 ]
[]
[]
[ "algorithm", "artificial_life", "depth_first_search", "python" ]
stackoverflow_0005506886_algorithm_artificial_life_depth_first_search_python.txt
Q: Scraping elements from a Youtube video I want to take some tags from youtube videos like the title, the number of views etc.I use BeautifulSoup for that but I want to make it faster.Here is my code: #for the title from BeautifulSoup import BeautifulSoup html = re.findall('content=.*>\n\n',urllib2.urlopen(link).rea...
Scraping elements from a Youtube video
I want to take some tags from youtube videos like the title, the number of views etc.I use BeautifulSoup for that but I want to make it faster.Here is my code: #for the title from BeautifulSoup import BeautifulSoup html = re.findall('content=.*>\n\n',urllib2.urlopen(link).read()) soup = BeautifulSoup(html) print soup.p...
[ "Use google's youtube api.\nPart of their example:\ndef PrintEntryDetails(entry):\n print 'Video title: %s' % entry.media.title.text\n print 'Video published on: %s ' % entry.published.text\n print 'Video description: %s' % entry.media.description.text\n print 'Video category: %s' % entry.media.category[0]....
[ 7 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0007101787_beautifulsoup_python.txt
Q: Trouble With Lists of Lists in Python I'm brand new to python, but I have a lot of experience with C++, Java, and .NET. I'm hoping that someone can explain why this sample program works the way it does and how I can change it to work the way I would like it to work. Essentially, I'm trying to create a list of obje...
Trouble With Lists of Lists in Python
I'm brand new to python, but I have a lot of experience with C++, Java, and .NET. I'm hoping that someone can explain why this sample program works the way it does and how I can change it to work the way I would like it to work. Essentially, I'm trying to create a list of objects, and each object in the list contains a...
[ "list_of_obj2 is a class attribute of Obj1, if you want instance attribute:\nclass Obj1(object):\n def __init__(self):\n self.list_of_obj2 = []\n\n" ]
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0007101988_python.txt
Q: Display an image as a splash screen when running Windows batch file, vbscript/wscript or Python console script Any ideas how I can display an image file (bmp or png) centered on the screen as an application splash screen when running a Windows console script based on a batch file, vbscript/wscript or Python consol...
Display an image as a splash screen when running Windows batch file, vbscript/wscript or Python console script
Any ideas how I can display an image file (bmp or png) centered on the screen as an application splash screen when running a Windows console script based on a batch file, vbscript/wscript or Python console script? I'm not interested in a wxPython solution - that's too much overhead just to implement a cosmetic feature ...
[ "A low-tech, ugly approach? How about opening an image viewer with the bitmap and killing it after some time or when the initializations are done? ;-)\nYou certainly have no native way of doing this in a batch file. From VBScript you could use an HTA. PowerShell has no problems of doing this with Windows Forms but ...
[ 1, 0, 0, 0 ]
[]
[]
[ "batch_file", "console_application", "image", "python", "vbscript" ]
stackoverflow_0002502385_batch_file_console_application_image_python_vbscript.txt
Q: How can I get a Python generator to return None rather than StopIteration? I am using generators to perform searches in lists like this simple example: >>> a = [1,2,3,4] >>> (i for i, v in enumerate(a) if v == 4).next() 3 (Just to frame the example a bit, I am using very much longer lists compared to the one abov...
How can I get a Python generator to return None rather than StopIteration?
I am using generators to perform searches in lists like this simple example: >>> a = [1,2,3,4] >>> (i for i, v in enumerate(a) if v == 4).next() 3 (Just to frame the example a bit, I am using very much longer lists compared to the one above, and the entries are a little bit more complicated than int. I do it this way ...
[ "If you are using Python 2.6+ you should use the next built-in function, not the next method (which was replaced with __next__ in 3.x). The next built-in takes an optional default argument to return if the iterator is exhausted, instead of raising StopIteration:\nnext((i for i, v in enumerate(a) if i == 666), None)...
[ 162, 7 ]
[]
[]
[ "exception", "generator", "python", "stopiteration" ]
stackoverflow_0007102050_exception_generator_python_stopiteration.txt
Q: Pagination in django I wanted to implement pagination in my django based app. For that I am using django-pagination module. However the pagination generated by it is not pleasing. I wanted something like the one generated by django's admin view where the page numbers are clickable links rather than something like ...
Pagination in django
I wanted to implement pagination in my django based app. For that I am using django-pagination module. However the pagination generated by it is not pleasing. I wanted something like the one generated by django's admin view where the page numbers are clickable links rather than something like Page 1 of 4 next... Sugges...
[ "Simply change the template. The one as an example here is not the default. You can do anything else with the paginator integrated attributes and functions.\n" ]
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007101942_django_python.txt
Q: Help! Key error in python I keep getting this error: MultiValueDictKeyError at /search/ "Key 'name' not found in <'QueryDict: {}>" I just started learning programming two days ago, so can someone explain in layman's terms why there's a problem and how to solve it. Thanks! Here is the section of programming: def ...
Help! Key error in python
I keep getting this error: MultiValueDictKeyError at /search/ "Key 'name' not found in <'QueryDict: {}>" I just started learning programming two days ago, so can someone explain in layman's terms why there's a problem and how to solve it. Thanks! Here is the section of programming: def NameAndOrCity(request): NoE...
[ "It looks like the only place you could be getting this error is on this line:\nname = request.GET['name']\n\nYou haven't checked if 'name' is in the request.GET dictionary before trying to access it like you did above so you will get a key error if that key doesn't exist in request.GET.\nSo it looks like you need ...
[ 2 ]
[]
[]
[ "dictionary", "django", "python" ]
stackoverflow_0007102226_dictionary_django_python.txt
Q: How can I balance "Pythonic" and "convenient" in this case? I have an "interface" that will be implemented by client code: class Runner: def run(self): pass run should in general return a docutils node but because the far far most common case is plain text, the caller allows run to return a string, wh...
How can I balance "Pythonic" and "convenient" in this case?
I have an "interface" that will be implemented by client code: class Runner: def run(self): pass run should in general return a docutils node but because the far far most common case is plain text, the caller allows run to return a string, which will be checked using type() and turned into a node. However,...
[ "I think this is a slightly deceptive example; there's something you haven't stated. I'm guessing that when you say you \"have an interface,\" what you mean is that you have some code that accepts an object and calls its run method. \nIf you aren't testing for the type of that object before calling its run method, ...
[ 5, 2, 1, 1, 0 ]
[]
[]
[ "duck_typing", "python" ]
stackoverflow_0007102242_duck_typing_python.txt
Q: Is there a way to leave an argument out of the help using python argparse I have an argument that is an internal debug flag and shouldn't be run by users who don't know what they are doing. I realize that hiding it is in essence security by obscurity, but I'm not concerned about malice so much as incompetence. Opt...
Is there a way to leave an argument out of the help using python argparse
I have an argument that is an internal debug flag and shouldn't be run by users who don't know what they are doing. I realize that hiding it is in essence security by obscurity, but I'm not concerned about malice so much as incompetence. Optparse had a SUPPRESS_HELP option, is there and argparse equivalent?
[ "parser.add_argument('--secret', help=argparse.SUPPRESS)\n\nFrom here: http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html\nFirst Google result for argparse suppress_help, by the way.\n" ]
[ 13 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0007102611_argparse_python.txt
Q: Solving an equation in Python i'm trying to solve an equation but I don't know the way to do this. I've got a vector x wich is actually a matrix type and I would like to solve the equation x.transpose()*v=0 where v is another vector Can someone help me? I thank you in advance A: Take any vector at all and projec...
Solving an equation in Python
i'm trying to solve an equation but I don't know the way to do this. I've got a vector x wich is actually a matrix type and I would like to solve the equation x.transpose()*v=0 where v is another vector Can someone help me? I thank you in advance
[ "Take any vector at all and project it into the orthogonal complement of x. \nPython 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) \n[GCC 4.2.1 (Apple Inc. build 5664)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import numpy\n>>> x = numpy.matrix([1, 3.14, 2.73]).T\n...
[ 2, 1 ]
[]
[]
[ "equation_solving", "python" ]
stackoverflow_0007101354_equation_solving_python.txt
Q: Image field related problems while using in django admin I have a following Banner class. Which is editable by admin. class Banner(models.Model): name = models.CharField(max_length = 128) link = models.TextField(max_length = 450) image = models.ImageField(upload_to = 'banner_images'...
Image field related problems while using in django admin
I have a following Banner class. Which is editable by admin. class Banner(models.Model): name = models.CharField(max_length = 128) link = models.TextField(max_length = 450) image = models.ImageField(upload_to = 'banner_images') There are two problems. When saving image it is saved with...
[ "Try something like this:\nfrom os import rename\nclass Banner(models.Model):\n name = models.CharField(max_length = 128)\n link = models.TextField(max_length = 450)\n image = models.ImageField(upload_to = 'banner_images')\n\n def save(self):\n super(Banner, self).save()\n...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0006957079_django_django_admin_python.txt
Q: Syntax error in sqlite statement in python? I have the following code fragment in an object initializer. However, the third line below gives the error sqlite3.OperationalError: near "(": syntax error self._conn = sqlite3.connect('dictionary') cursor = self._conn.cursor() cursor.execute('CREATE TABLE `words` (`word...
Syntax error in sqlite statement in python?
I have the following code fragment in an object initializer. However, the third line below gives the error sqlite3.OperationalError: near "(": syntax error self._conn = sqlite3.connect('dictionary') cursor = self._conn.cursor() cursor.execute('CREATE TABLE `words` (`word` VARCHAR(15) NOT NULL, PRIMARY (`word`));') Any...
[ "You are missing a KEY here.\nCREATE TABLE `words` (`word` VARCHAR(15) NOT NULL, PRIMARY KEY(`word`))\n\n", "PRIMARY word is not valid SQL. Use\nCREATE TABLE words (word VARCHAR(15) NOT NULL PRIMARY KEY);\n\n" ]
[ 4, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0007103416_python_sqlite.txt
Q: Design tips for a program to be run in 25 years If creating an application (that does mostly data processing) that needs to be run now and maybe (maybe not) 10 or 25 years later, what design tips are out there for such applications? The general rules apply: rely on open source software and proven platforms and fai...
Design tips for a program to be run in 25 years
If creating an application (that does mostly data processing) that needs to be run now and maybe (maybe not) 10 or 25 years later, what design tips are out there for such applications? The general rules apply: rely on open source software and proven platforms and failsafe data formats. The language must be a high-level...
[ "Actually, the #1 requirement would be \"use a popular language with an International Standards Organization formal spec\". This is far more important than any of the other things you mention. (\"Open Source\"? Please... There are thousands of public domain programs from the 80s and 90s that it would be nigh-im...
[ 6, 3, 3, 1 ]
[]
[]
[ "future_proof", "programming_languages", "python" ]
stackoverflow_0007103198_future_proof_programming_languages_python.txt
Q: python dictionary sorting oddly (want non-alphabetical) so I am trying to send a packet with some keys that i have put into a dictionary. these need to be printed in a specific order, so I've tried to make a function to reorder them. I assume python is doing something to rearrange in the order I don't want, but i'...
python dictionary sorting oddly (want non-alphabetical)
so I am trying to send a packet with some keys that i have put into a dictionary. these need to be printed in a specific order, so I've tried to make a function to reorder them. I assume python is doing something to rearrange in the order I don't want, but i'm not sure why. I'm currently using this function to try and ...
[ "Since dictionaries in Python are unordered and all that you need is to output results ordered by the specified rule you can do something like this:\norder = \"l5,l4,l3,l2,q,y,k,k3,d1,z,p,c,b,d3,dt,N,n,a,h,v\".split(',')\n\nfor key in order:\n print key, infos.get(key)#if infos is your dictionary\n\nOr you can g...
[ 2, 1, 0 ]
[]
[]
[ "dictionary", "key", "python" ]
stackoverflow_0007101883_dictionary_key_python.txt
Q: Interoperability between OpenCV Python interface and a ctypes library I'm using the Python interface from OpenCV 2.3. I have a library written in C that expects, as arguments, OpenCV objects such as IplImage. Like this: void MyFunction(IplImage* image); I wish, from my Python code, to call this function. I've tri...
Interoperability between OpenCV Python interface and a ctypes library
I'm using the Python interface from OpenCV 2.3. I have a library written in C that expects, as arguments, OpenCV objects such as IplImage. Like this: void MyFunction(IplImage* image); I wish, from my Python code, to call this function. I've tried: library.MyFunction(image) But it gives me an error: ArgumentError: arg...
[ "cv.iplimage is a CPython object defined by iplimage_t. It wraps the IplImage pointer that you need. There are a few ways to get at this pointer. I'll use the fact that CPython id returns the object base address. \nimport cv, cv2\nfrom ctypes import *\n\nYou could use c_void_p instead of defining IplImage. I define...
[ 3 ]
[]
[]
[ "ctypes", "opencv", "python" ]
stackoverflow_0007001835_ctypes_opencv_python.txt
Q: How to change the color of single characters in a cell in excel with python win32com? I have a question regarding the win32com bindings for excel. I set up early bindings and followed some examples from the "Python Programming on Win32" book from O'Reilly. The following code works fine: book2.xlApp.Worksheets('She...
How to change the color of single characters in a cell in excel with python win32com?
I have a question regarding the win32com bindings for excel. I set up early bindings and followed some examples from the "Python Programming on Win32" book from O'Reilly. The following code works fine: book2.xlApp.Worksheets('Sheet1').Cells(1,1).Font.ColorIndex = 1 book2.xlApp.Worksheets('Sheet1').Cells(1,1).Font.Color...
[ "use GetCharacters:\nCells(1,1).GetCharacters(start,length).Font.ColorIndex = 1\n\n" ]
[ 6 ]
[]
[]
[ "excel", "fonts", "python", "win32com" ]
stackoverflow_0007103839_excel_fonts_python_win32com.txt
Q: React on UniqueKeyViolation in SQLAlchemy I have 2 Tables in SQLAlchemy (using declerative_base()) that are joined via a seperate Table relationship # no comment on the wired naming.... site_word = Table('word_site', Base.metadata, Column('site_id', Integer, ForeignKey('sites.site_id'), nullable = False, prima...
React on UniqueKeyViolation in SQLAlchemy
I have 2 Tables in SQLAlchemy (using declerative_base()) that are joined via a seperate Table relationship # no comment on the wired naming.... site_word = Table('word_site', Base.metadata, Column('site_id', Integer, ForeignKey('sites.site_id'), nullable = False, primary_key = True), Column('word_id', Integer, ...
[ "It is difficult to see the problem without an example of how you are working with your objects. I take it you are trying to do something like this:\nsite = Site()\nsite.words.append(Word('Someword'))\nsession.add(site)\nsession.commit()\n\nThis will of course raise an IntegrityError if 'someword' already exists. T...
[ 1, 1 ]
[]
[]
[ "postgresql", "python", "sqlalchemy", "unique_constraint" ]
stackoverflow_0007092396_postgresql_python_sqlalchemy_unique_constraint.txt
Q: Neo4j & JPype Installation Issue I use Ubuntu 10.10 and before continuing with the installation, I installed JPype and openjdk-6-jdk & all its dependencies using synaptic. I proceeded with the install of Neo4j & Python as mentioned on: http://components.neo4j.org/neo4j.py/0.1-SNAPSHOT/ But when I did sudo python ...
Neo4j & JPype Installation Issue
I use Ubuntu 10.10 and before continuing with the installation, I installed JPype and openjdk-6-jdk & all its dependencies using synaptic. I proceeded with the install of Neo4j & Python as mentioned on: http://components.neo4j.org/neo4j.py/0.1-SNAPSHOT/ But when I did sudo python setup.py install in the neo4j-python ...
[ "This solution might work: https://gist.github.com/809425\nFor other ways of using Neo4j with Python see http://www.delicious.com/neo4j/drivers+python and maybe http://www.delicious.com/neo4j/python to get more information.\n" ]
[ 2 ]
[]
[]
[ "neo4j", "python" ]
stackoverflow_0007103024_neo4j_python.txt
Q: Flask - Accessing the config variable in the template I am using Flask version 0.7. I have stored the path of static content in a configuration file and loaded it using app.config.from_envvar(<file_name>) Can I be able to access this config variable in the template without passing the variables through the view...
Flask - Accessing the config variable in the template
I am using Flask version 0.7. I have stored the path of static content in a configuration file and loaded it using app.config.from_envvar(<file_name>) Can I be able to access this config variable in the template without passing the variables through the view?
[ "There are a few global variables that are passed in the templates context by default by flask (here is the complete list), one of them being config, which allows you to access the application configuration from templates. Being a dictionary, it can be accessed using the syntax config['MY_CONFIGURATION'] or config...
[ 125 ]
[]
[]
[ "flask", "jinja2", "python" ]
stackoverflow_0007104198_flask_jinja2_python.txt
Q: How Create RSA Encryption key pairs using python that is comaptible with C# or vice versa? Actually, i have started work on creating a web service in Python and C#(.NET 3.5 framework) as client. All requests are on POST so i decided to send my data in encrypted form using public key on C# side and decrypt data in ...
How Create RSA Encryption key pairs using python that is comaptible with C# or vice versa?
Actually, i have started work on creating a web service in Python and C#(.NET 3.5 framework) as client. All requests are on POST so i decided to send my data in encrypted form using public key on C# side and decrypt data in Python, Again from python Encrypt data using Private Key & decrypt using public key in C# side.....
[ "Please take a look at PyOpenSSL and may be it will be better to use standard HTTPS for your service. You can use self-signed SSL certificates with PyCurl and urllib.urlopen and other python web clients.\nUrllib and validation of server certificate\none of the examples.\n" ]
[ 1 ]
[]
[]
[ "c#", "encryption", "key", "python", "rsa" ]
stackoverflow_0006593820_c#_encryption_key_python_rsa.txt
Q: Setting up EC2 instances as Celery Workers with a local computer as the host Similar to my question here I'm trying to set up multiple amazon EC2 instances to do some multiprocessing. I was thinking of using Celery to manage the workers. Has anyone gotten celery to work on EC2 instances with a local computer as a ...
Setting up EC2 instances as Celery Workers with a local computer as the host
Similar to my question here I'm trying to set up multiple amazon EC2 instances to do some multiprocessing. I was thinking of using Celery to manage the workers. Has anyone gotten celery to work on EC2 instances with a local computer as a host? Does anyone have any good suggestions, tutorials, advice, etc. that may help...
[ "I've used Amazon SQS for tasks management with Amazon EC2. It's very scalable solution. Boto is the best library for managing Amazon services as I found.\nFor storing big amount of small files you can use MongoDB GridFS, it will allow you to store gigs of local files. I used MongoDB and got prefect performance for...
[ 0 ]
[]
[]
[ "amazon_ec2", "celery", "multiprocessing", "python" ]
stackoverflow_0006459459_amazon_ec2_celery_multiprocessing_python.txt
Q: python minidom does not close I'm experiencing a strange behaviour using minidom. I run the following code: import os import sys from xml.dom import minidom def generateReleaseXMLFile(): modelPath = "%./model/" # Create the parser xsydoc = minidom.Document() # Create the element ScriptModelVersio...
python minidom does not close
I'm experiencing a strange behaviour using minidom. I run the following code: import os import sys from xml.dom import minidom def generateReleaseXMLFile(): modelPath = "%./model/" # Create the parser xsydoc = minidom.Document() # Create the element ScriptModelVersion scriptModelVersion = xsydoc.c...
[ "The <?xml ... ?> is not a tag, but the XML Declaration. There is not need to close it, your document is in perfect shape.\n", "Your XML is valid :\nHave a look at : http://en.wikipedia.org/wiki/XML_Schema_%28W3C%29\nYou do not need to close declaration.\n" ]
[ 6, 1 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0007104997_minidom_python_xml.txt