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: executing a python script from another python script I have a script a.py : #!/usr/bin/env python def foo(arg1, arg2): return int(arg1) + int(arg2) if __name__ == "__main__": import sys print foo(sys.argv[1], sys.argv[2])` I now want to make a script that can run the first script and write the output ...
executing a python script from another python script
I have a script a.py : #!/usr/bin/env python def foo(arg1, arg2): return int(arg1) + int(arg2) if __name__ == "__main__": import sys print foo(sys.argv[1], sys.argv[2])` I now want to make a script that can run the first script and write the output of a.py to a file with some arguments as well. I want to m...
[ "This is not a function, it's an if statement:\nif __name__ == \"__main__\":\n ...\n\nIf you want a main function, define one:\nimport sys\n\ndef main():\n print foo(sys.argv[1], sys.argv[2])`\n\nThen just call it if you need to:\nif __name__ == \"__main__\":\n main()\n\n", "a.main() has nothing to do wit...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007762692_python.txt
Q: Django Passing data between views I was wondering what is the 'best' way of passing data between views. Is it better to create invisible fields and pass it using POST or should I encode it in my URLS? Or is there a better/easier way of doing this? Sorry if this question is stupid, I'm pretty new to web programming...
Django Passing data between views
I was wondering what is the 'best' way of passing data between views. Is it better to create invisible fields and pass it using POST or should I encode it in my URLS? Or is there a better/easier way of doing this? Sorry if this question is stupid, I'm pretty new to web programming :) Thanks
[ "There are different ways to pass data between views. Actually this is not much different that the problem of passing data between 2 different scripts & of course some concepts of inter-process communication come in as well. Some things that come to mind are - \n\nGET request - First request hits view1->send data t...
[ 58 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0007763115_django_django_views_python.txt
Q: Converting strings into another data type, Python I have the string "(0, 0, 0)". I'd like to be able to convert this to a tuple. The built in tuple function doesn't work for my purposes because it treats each character as an individual item. I want to be able to convert "(0, 0, 0)" to (0, 0, 0) programmatically. ...
Converting strings into another data type, Python
I have the string "(0, 0, 0)". I'd like to be able to convert this to a tuple. The built in tuple function doesn't work for my purposes because it treats each character as an individual item. I want to be able to convert "(0, 0, 0)" to (0, 0, 0) programmatically.
[ "You can use ast.literal_eval\n>>> import ast\n>>> ast.literal_eval('(0,0,0)')\n(0, 0, 0)\n\n" ]
[ 5 ]
[]
[]
[ "python", "string", "tuples", "types" ]
stackoverflow_0007763300_python_string_tuples_types.txt
Q: How to update a particular column of a row in a csv using python I am having a csv file with the following contents 1,2,3,4 a,b,c,d w,x,y,z And i want to update this csv file contents to 1,2,3,4 a,b,c,d,k w,x,y,z Can someone please share Python code for this update process?? A: Using the csv library, we read i...
How to update a particular column of a row in a csv using python
I am having a csv file with the following contents 1,2,3,4 a,b,c,d w,x,y,z And i want to update this csv file contents to 1,2,3,4 a,b,c,d,k w,x,y,z Can someone please share Python code for this update process??
[ "Using the csv library, we read in the data, convert it to a list of lists, append the k to the relevant list, then write it out again.\nimport csv\n\ndata = csv.reader(open(\"input.csv\"))\n\nl = list(data) \nl[1].append(\"k\")\n\nour_writer = csv.writer(open(\"output.csv\", \"wb\"))\n\nour_writer.writerows(l)\...
[ 1, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007763491_csv_python.txt
Q: Open a Python port from Erlang: no reply messages Based on Chapter 12 of the OTP in Action book and Cesarini's book I wrote this Erlang code: Erlang: p(Param) -> ?DBG("Starting~n", []), Cmd = "python test.py", Port = open_port({spawn,Cmd}, [stream,{line, 1024}, exit_status]), ?DBG("Opened the p...
Open a Python port from Erlang: no reply messages
Based on Chapter 12 of the OTP in Action book and Cesarini's book I wrote this Erlang code: Erlang: p(Param) -> ?DBG("Starting~n", []), Cmd = "python test.py", Port = open_port({spawn,Cmd}, [stream,{line, 1024}, exit_status]), ?DBG("Opened the port: ~w~n", [Port]), Payload = term_to_binary(list...
[ "Does your Param contain the command limiter for Python? (in this case I assume newline, \"\\n\"). Also, list_to_binary/1 and then a term_to_binary/1 feels kinda wrong. term_to_binary/1 directly (including the newline) should be sufficient.\n", "There are two points:\n\nmake sure that Python does not buffer your...
[ 1, 1 ]
[]
[]
[ "erlang", "erlang_ports", "python" ]
stackoverflow_0007756743_erlang_erlang_ports_python.txt
Q: retrieve inheritance relationship information in python Say I have the following inheritance relationship. object->Car->SUV object is the father of Car and Car is the father of the SUV. How can I use Python programs to get such relationship information,like use dir to get the attributes of a class A: Use __bas...
retrieve inheritance relationship information in python
Say I have the following inheritance relationship. object->Car->SUV object is the father of Car and Car is the father of the SUV. How can I use Python programs to get such relationship information,like use dir to get the attributes of a class
[ "Use __bases__:\nIn [11]: SUV.__bases__\nOut[11]: (<class '__main__.Car'>,)\n\nIn [12]: Car.__bases__\nOut[12]: (<type 'object'>,)\n\nIf the purpose is to call the parent method from a child method, use super() instead.\n", "In addition to __bases__ which aix mentioned, there is also __mro__ which will tell you a...
[ 2, 2 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0007763801_inheritance_python.txt
Q: Best style for maintaining long equation What do you think is the best way of writing this method for calculating an ackermann function value? This function incorporates several 'short cuts' to the simplest method of calculating the value that speeds the calculation up considerably by reducing the amount of recurs...
Best style for maintaining long equation
What do you think is the best way of writing this method for calculating an ackermann function value? This function incorporates several 'short cuts' to the simplest method of calculating the value that speeds the calculation up considerably by reducing the amount of recursive calls, but you end up with a long expressi...
[ "What's wrong with just nesting in a simple elif chain?\ndef ack5(m, n):\n if m == 0:\n return (n + 1)\n elif m == 1:\n return (n + 2)\n elif m == 2:\n return (2 * n + 3)\n elif m == 3:\n return (8 * ( 2 ** n - 1) + 5)\n elif n == 0:\n return ack5(m - 1, 1)\n els...
[ 4, 3, 0 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0007763597_coding_style_python.txt
Q: How to convert Array in C++ to Python? How can I convert this C++ code for(int i=0; i<3; ++i){ array[i][0]=i*4+0; array[i][1]=i*4+1; array[i][2]=i*4+2; array[i][3]=i*4+3;} to Python ? When your IDE says xrange is an undefined function,please look at @ThiefMaste'comments : Just because your IDE says...
How to convert Array in C++ to Python?
How can I convert this C++ code for(int i=0; i<3; ++i){ array[i][0]=i*4+0; array[i][1]=i*4+1; array[i][2]=i*4+2; array[i][3]=i*4+3;} to Python ? When your IDE says xrange is an undefined function,please look at @ThiefMaste'comments : Just because your IDE says something is not defined, it doesn't mean i...
[ "How about this:\nIn [3]: [[i*4+j for j in xrange(4)] for i in xrange(3)]\nOut[3]: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]\n\n", "array = []\nfor i in range(3):\n list.append([i*4, i*4+1, i*4+2, i*4+3])\n\nor to be more exact (in case the list is not empty before):\nfor i in range(3):\n list[i] = [i*4,...
[ 3, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0007763909_python_python_3.x.txt
Q: How to set the sharing rights of a folder in Plone? I want to set sharing rights of many folders by using a Python script in a Plone site. A: You need to look at the AccessControl/rolemanager.py module for details; the sharing tab in Plone is a friendly wrapper around that API. To add roles for a given userid, c...
How to set the sharing rights of a folder in Plone?
I want to set sharing rights of many folders by using a Python script in a Plone site.
[ "You need to look at the AccessControl/rolemanager.py module for details; the sharing tab in Plone is a friendly wrapper around that API.\nTo add roles for a given userid, call manage_addLocalRoles:\ncontext.manage_addLocalRoles('userid', ('Role1', 'Role2',))\n\nThe other two important methods are manage_setLocalRo...
[ 8 ]
[]
[]
[ "permissions", "plone", "python", "zope" ]
stackoverflow_0007763150_permissions_plone_python_zope.txt
Q: Communicate with parent's children I'm trying to write a GUI with the following structure (only relevant parts): Window -> VBox -> HBox -> Frame: Input -> ScrolledWindow -> TreeView -> ListStore: Output As soon as the input is received, a list will we computed that is the output. How do I send th...
Communicate with parent's children
I'm trying to write a GUI with the following structure (only relevant parts): Window -> VBox -> HBox -> Frame: Input -> ScrolledWindow -> TreeView -> ListStore: Output As soon as the input is received, a list will we computed that is the output. How do I send this list to the ListStore so that it wil...
[ "You can just keep references of your input and your output, then do the following:\n\nbind a method to your input, that will be called on update or validation,\nin this method, do the treatment needed,\nat the end of this method, update your output, directly using its reference and its internal functions (configur...
[ 3 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0007763952_gtk_pygtk_python.txt
Q: How to Write Method to Verify Reflection Method Names and Parameters We were writing a Selenium test core by using Python webdriver. The main idea is to read from a CSV file with the format: method_name,parameter 1,parameter 2, parameter 3, ..., parameter n And then by using reflection, the test core will call th...
How to Write Method to Verify Reflection Method Names and Parameters
We were writing a Selenium test core by using Python webdriver. The main idea is to read from a CSV file with the format: method_name,parameter 1,parameter 2, parameter 3, ..., parameter n And then by using reflection, the test core will call the method based on the "method name" and parameters. def runTest(self): ...
[ "For the method, you can easily call hasattr to see if it exists. In your case, it's just :\nfor row in test_case_reader:\n method_name = get_method_name() # Your code here\n if not hasattr(self, method_name):\n self.logger.error(\"No method name %s\", method_name)\n\nFor the parameter, it's a little m...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007764096_python.txt
Q: Printing certain HTML Python Mechanize Im making a small python script for auto logon to a website. But i'm stuck. I'm looking to print into terminal a small part of the html, located within this tag in the html file on the site: <td class=h3 align='right'>&nbsp;&nbsp;John Appleseed</td><td>&nbsp;<a href="members_...
Printing certain HTML Python Mechanize
Im making a small python script for auto logon to a website. But i'm stuck. I'm looking to print into terminal a small part of the html, located within this tag in the html file on the site: <td class=h3 align='right'>&nbsp;&nbsp;John Appleseed</td><td>&nbsp;<a href="members_myaccount.php"><img border=0 src="../tbs_v7_...
[ "Mechanize is only good for fetching the html. Once you want to extract information from the html, you could use for example BeautifulSoup. (See also my answer to a similar question: Web mining or scraping or crawling? What tool/library should I use?)\nDepending on where the <td> is located in the html (it's unclea...
[ 7, 1, 1 ]
[]
[]
[ "mechanize", "printing", "python" ]
stackoverflow_0007763691_mechanize_printing_python.txt
Q: Is there analog in C++ for Python's file.read(2)? I'm currently trying to make analog of Python's function: def read_two_symbols(fdescr): return(file.read(2)) myfile = open('mytext.txt', 'rb') two_symbols = read_two_symbols(myfile) print(two_symbols) Is there any way to do it in C++? That's what I've tried: #in...
Is there analog in C++ for Python's file.read(2)?
I'm currently trying to make analog of Python's function: def read_two_symbols(fdescr): return(file.read(2)) myfile = open('mytext.txt', 'rb') two_symbols = read_two_symbols(myfile) print(two_symbols) Is there any way to do it in C++? That's what I've tried: #include <iostream> #include <string> #include <fstream> ...
[ "use the read or readsome function in istream. e.g\nstd::vector<char> buffer(2, 0);\n\nif (myfile.read(&buffer[0], 2))\n std::copy(buffer.begin(), buffer.end(), std::ostream_iterator<int>(std::cout, \"\"));\n\n", "Change the function definition to this ( notice the & sign):\nstring read_two_bytes(fstream & file)...
[ 1, 1, 1 ]
[]
[]
[ "c++", "file", "file_io", "python" ]
stackoverflow_0007764546_c++_file_file_io_python.txt
Q: Mixin Field into Existing and uneditable django model I would like to mix a field into an existing model which I would rather not edit (it comes from a third party project and I would rather leave the project untouched). I have created a simple example which illustrates what I am trying but unable to do: In an em...
Mixin Field into Existing and uneditable django model
I would like to mix a field into an existing model which I would rather not edit (it comes from a third party project and I would rather leave the project untouched). I have created a simple example which illustrates what I am trying but unable to do: In an empty Django project I have created apps app1 and app2 (they ...
[ "Mixins work great with adding attributes and methods, but not fields.\nIn app1.models.py, do this instead:\nfrom django.db import models\nfrom app2.models import BlogPost\n\ncustom_field_name = models.CharField(max_length=200)\ncustom_field_name.contribute_to_class(BlogPost, \"custom_field_name\")\n\nI think also ...
[ 0 ]
[]
[]
[ "django", "mixins", "python" ]
stackoverflow_0007759218_django_mixins_python.txt
Q: Python beginner question - trying to understand return statement Basically I want to return the contents of create_user in the register function to use to save to my database. I am a complete beginner. What am I misunderstanding? def register(): form = SignupForm(request.form) if request.method == 'POST' a...
Python beginner question - trying to understand return statement
Basically I want to return the contents of create_user in the register function to use to save to my database. I am a complete beginner. What am I misunderstanding? def register(): form = SignupForm(request.form) if request.method == 'POST' and form.validate(): create_user = ({'username' : form.username.dat...
[ "I think you've lost some formatting somewhere. The first return statement should be indented far enough that it's inside the if block and the second return statement should line up with the if block. If validation succeeds then it returns the tuple create_user, redirect(url_for('loggedin.html')), otherwise it re...
[ 4, 3, 1 ]
[]
[]
[ "flask", "python", "return" ]
stackoverflow_0003496321_flask_python_return.txt
Q: Extract javascript variable value from html document with python I need to parse an HTML document that contains javascript code with json object. Something like this: <html> <head> </head> <body> <script type="text/javascript"> myJSONObject = {"name": "steve", "city": "new york"} </script> ...
Extract javascript variable value from html document with python
I need to parse an HTML document that contains javascript code with json object. Something like this: <html> <head> </head> <body> <script type="text/javascript"> myJSONObject = {"name": "steve", "city": "new york"} </script> <p>Hello World.</p> </body> </html> How can I extract the myJSONObj...
[ "You can use lxml to parse the HTML, and then extract the JSON:\n>>> import lxml.etree,json\n>>> s = '''<html><body><script type=\"text/javascript\">\n myJSONObject = {\"name\": \"steve\", \"city\": \"new york\"}\n </script></body></html>'''\n>>> js = lxml.etree.HTML(s).find('.//body/script')....
[ 7 ]
[]
[]
[ "javascript", "json", "python" ]
stackoverflow_0007765175_javascript_json_python.txt
Q: Python Reportlab Area under multiple lines graph So I have started a project for the web utilizing Reportlab. The website needs to generate PDFs that have embedded charts. So far I've been extremely happy with Reportlab's capabilities (i've done a bunch of pie and bar charts), however its documentation is kinda la...
Python Reportlab Area under multiple lines graph
So I have started a project for the web utilizing Reportlab. The website needs to generate PDFs that have embedded charts. So far I've been extremely happy with Reportlab's capabilities (i've done a bunch of pie and bar charts), however its documentation is kinda lacking. I have looked all over the internet, and have b...
[ "I have built a collection of galleries under http://www.reportlab.com/chartgallery/ to serve as examples. I think what you need is the inFills property under the line, look at http://www.reportlab.com/chartsgallery/financial/AreaChart01/ for an example (also read the description there). You could browse the proper...
[ 2 ]
[]
[]
[ "charts", "graph", "linegraph", "python", "reportlab" ]
stackoverflow_0007718133_charts_graph_linegraph_python_reportlab.txt
Q: Sort words by their usage I have a list of english words (approx 10000) and I'd like to sort them by their usage as they occur in literature, newspaper, blogs etc. Can I sort them in Python or other language? I heard about NLTK which is the closest library I know that could help. Or is this task for other tool? th...
Sort words by their usage
I have a list of english words (approx 10000) and I'd like to sort them by their usage as they occur in literature, newspaper, blogs etc. Can I sort them in Python or other language? I heard about NLTK which is the closest library I know that could help. Or is this task for other tool? thank you
[ "Python and NLTK are the perfect tools to sort your wordlist, as the NLTK comes with some corpora of the english language, from which you can extract frequency information.\nThe following code will print a given wordlist in the order of word frequency in the brown corpus: \nimport nltk\nfrom nltk.corpus import brow...
[ 12, 0, 0 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0007764229_nltk_python.txt
Q: Apply tags in a text widget I need some help tag-related! I am writing a simple editor, supporting basic formatting. By using a Text widget (named text), I put a tag 'b' to set the text where this tag applies to bold. This is not a problem when I apply the bold to a selection: text.tag_add('b', SEL_FIRST,SEL_LAST...
Apply tags in a text widget
I need some help tag-related! I am writing a simple editor, supporting basic formatting. By using a Text widget (named text), I put a tag 'b' to set the text where this tag applies to bold. This is not a problem when I apply the bold to a selection: text.tag_add('b', SEL_FIRST,SEL_LAST) I have instead two problems wh...
[ "You may not realize it, but you're trying to do something that's very hard in Tkinter. While the text widget tags are a powerful concept, they have some weaknesses when it comes to creating something like a wysywig editor. \nYou need to change your approach a bit. Instead of inserting spaces, I think the better so...
[ 3 ]
[ "Thank you Bryan, but your approach seems to me too much complicated, and I'm not so eager to start writing bindings for what's missing - paste as an example!\nI simply wrote down the following, and it seems to work\n l=text.tag_names('insert')\n if l==() or l[0]!='b': # select bold\n text....
[ -1 ]
[ "python", "tkinter" ]
stackoverflow_0007659069_python_tkinter.txt
Q: Is it worth using a multithreaded blas implementation along with multiprocessing in Python? Suppose I have a 16 core machine, and an embarrassingly parallel program. I use lots of numpy dot products and addition of numpy arrays, and if I did not use multiprocessing it would be a no-brainer: Make sure numpy is bu...
Is it worth using a multithreaded blas implementation along with multiprocessing in Python?
Suppose I have a 16 core machine, and an embarrassingly parallel program. I use lots of numpy dot products and addition of numpy arrays, and if I did not use multiprocessing it would be a no-brainer: Make sure numpy is built against a version of blas that uses multithreading. However, I am using multiprocessing, and...
[ "You might need to be a little careful about the assumption that your code is actually used multithreaded BLAS calls. Relatively few numpy operators actually use the underlying BLAS, and relatively few BLAS calls are actually multithreaded. numpy.dot uses either BLAS dot, gemv or gemm, depending on the operation, b...
[ 6, 2 ]
[]
[]
[ "blas", "multiprocessing", "multithreading", "numpy", "python" ]
stackoverflow_0007761859_blas_multiprocessing_multithreading_numpy_python.txt
Q: Python Mechanize: Session has expired Trying out mechanize to scrape some content off an https asp site, it looks as if the login page submission works as I get returned a 200. But when I try and open a url presumably using the cookie captured after the login, I get re-directed back to the login page with the err...
Python Mechanize: Session has expired
Trying out mechanize to scrape some content off an https asp site, it looks as if the login page submission works as I get returned a 200. But when I try and open a url presumably using the cookie captured after the login, I get re-directed back to the login page with the error that my session has expired. The last p...
[ "Your code looks good to me however I don't see any check that login was successful\nresponse = mech.submit()\n\nLook at the content of response to make sure your login was successful.\nAre you sure this site works without javascript? There could be hidden field that are set by javascript.\n" ]
[ 1 ]
[]
[]
[ "mechanize", "mechanize_python", "python" ]
stackoverflow_0007720828_mechanize_mechanize_python_python.txt
Q: error on using exec() to call python script I am trying to call a simple python script #!/usr/local/python25/bin/python print "hello world" from the following php script <?php echo exec("/usr/local/python25/bin/python myfile.py"); ?> But nothing was happened. Please tell me what is wrong here? (I also...
error on using exec() to call python script
I am trying to call a simple python script #!/usr/local/python25/bin/python print "hello world" from the following php script <?php echo exec("/usr/local/python25/bin/python myfile.py"); ?> But nothing was happened. Please tell me what is wrong here? (I also checked other thread but I could not solve my pr...
[ "1.The exec function just return the last line from the result of the command.\n2. The print statement in python (except python 3) automatically adds a newline at the end.\nThis is the reason you feel nothing was happened.\nYou can catch the whole output by this way.\nexec(\"/usr/local/python25/bin/python myfile.py...
[ 3, 1, 0 ]
[]
[]
[ "exec", "php", "python" ]
stackoverflow_0007765473_exec_php_python.txt
Q: in python, how do i iterate a nested dict with a dynamic number of nests? OK by dynamic I mean unknown at runtime. here is a dict: aDict[1]=[1,2,3] aDict[2]=[7,8,9,10] aDict[n]=[x,y] I don't know how many n will be but I want to loop as follows: for l1 in aDict[1]: for l2 in aDict[2]: for ln in aDict[n]: ...
in python, how do i iterate a nested dict with a dynamic number of nests?
OK by dynamic I mean unknown at runtime. here is a dict: aDict[1]=[1,2,3] aDict[2]=[7,8,9,10] aDict[n]=[x,y] I don't know how many n will be but I want to loop as follows: for l1 in aDict[1]: for l2 in aDict[2]: for ln in aDict[n]: # do stuff with l1, l2, ln combination. Any suggestions on how to do this?...
[ "You need itertools.product.\nfrom itertools import product\n\nfor vals in product(*list(aDict.values())):\n # vals will be (l1, l2, ..., ln) tuple\n\n", "Same idea as DrTyrsa, but making sure order is right.\nfrom itertools import product\n\nfor vals in product( *[aDict[i] for i in sorted(aDict.keys())]):\n ...
[ 12, 11 ]
[]
[]
[ "nested", "python" ]
stackoverflow_0007764892_nested_python.txt
Q: Django 1.3 post login/logout signals in relation with authentication First of all both methods below return True. I'd expect the second one to return False using the django standard admin authentication procedure or am I wrong? def post_login(sender, **kwargs): """ Django 1.3 post login signal handler ...
Django 1.3 post login/logout signals in relation with authentication
First of all both methods below return True. I'd expect the second one to return False using the django standard admin authentication procedure or am I wrong? def post_login(sender, **kwargs): """ Django 1.3 post login signal handler """ # do stuff user = kwargs['user'] print user.is_authenticat...
[ "\nIf user is an instance of User model, user.is_authenticated() will always return True. Models instance can't know what's going on on request level. This method is for views.\nIf you want to deal with failed login attempts, take a look at django-axes. You can just use it, or look at the code and reimplement some ...
[ 4 ]
[]
[]
[ "django", "python", "security" ]
stackoverflow_0007765113_django_python_security.txt
Q: Looking for a good book for Google App Engine Python Can you recommend me book to Google App Engine in Python? English/French books are both accepted. A: Programming Google App Engine: Build and Run Scalable Web Apps on Google's Infrastructure is a pretty good book that talks about both the Java and Python APIs....
Looking for a good book for Google App Engine Python
Can you recommend me book to Google App Engine in Python? English/French books are both accepted.
[ "Programming Google App Engine: Build and Run Scalable Web Apps on Google's Infrastructure is a pretty good book that talks about both the Java and Python APIs. Google also has good Getting Started tutorial that I thought was pretty good.\nGood luck.\n", "I come back to this question after sereval searches.\nI ro...
[ 6, 2, 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005257456_google_app_engine_python.txt
Q: how can I make an if loop in python to say " if something (in this case 1/1) exist in one of my column (in my case 10)? I have a file like this: Chr10 31 . T C 35.1 . DP=7;AF1=1;CI95=1,1;DP4=0,0,7,0;MQ=23;FQ=-48 GT:PL:GQ 1/1:68,21,0:39** Chr10 445 . G ...
how can I make an if loop in python to say " if something (in this case 1/1) exist in one of my column (in my case 10)?
I have a file like this: Chr10 31 . T C 35.1 . DP=7;AF1=1;CI95=1,1;DP4=0,0,7,0;MQ=23;FQ=-48 GT:PL:GQ 1/1:68,21,0:39** Chr10 445 . G T 34 . DP=23;AF1=0.5;CI95=0.5,0.5;DP4=7,5,6,3;MQ=19;FQ=12.3;PV4=1,6.2e-08,1,0.27 GT:PL:GQ 0/1:...
[ "If it can appear anywhere in the column:\nif \"1/1\" in e[9]:\n ...\n\nIf it must appear at the start of the column as in your example:\nif e[9].startswith(\"1/1\"):\n ...\n\nAlternatively, if the column always contains colon-separated values:\nif e[9].split(':')[0] == \"1/1\":\n ...\n\nThe last one is the stri...
[ 5, 2, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0007766152_if_statement_python.txt
Q: Hidden features of PyCharm I know PyCharm is young IDE but id like to know if you guys have found some candy while using it. I know from experience that JetBrains IDE's are filled with candy and can't wait to find it all. Please list your tips, perhaps something you did not first expected to be there. A: As the ...
Hidden features of PyCharm
I know PyCharm is young IDE but id like to know if you guys have found some candy while using it. I know from experience that JetBrains IDE's are filled with candy and can't wait to find it all. Please list your tips, perhaps something you did not first expected to be there.
[ "As the lead developer of PyCharm, I can tell you that we don't usually hide features in random places, and there are a few reliable ways to discover most of them.\n\nTry Ctrl-clicking on everything (methods, functions, template tag names and parameters, etc.)\nIf Ctrl-clicking works, usually so does completion (Ct...
[ 120, 33, 26, 11, 6, 5, 5 ]
[]
[]
[ "pycharm", "python" ]
stackoverflow_0002555726_pycharm_python.txt
Q: Python: Uploading an XML file to a MySQL database I want to use Python to upload a large xml file to MySQL database. I can use lxml to parse it and then upload the records to MySQL one by one. But I just wanted to find out if there is some library that can make it easier. A: There is xml2sql, which I haven't tes...
Python: Uploading an XML file to a MySQL database
I want to use Python to upload a large xml file to MySQL database. I can use lxml to parse it and then upload the records to MySQL one by one. But I just wanted to find out if there is some library that can make it easier.
[ "There is xml2sql, which I haven't tested for myself. You can give it a try. But I'd prefer to write a custom importer/exporter using lxml (for speed), and considering the fact that your xml is large, maybe storing it as a blob is a good idea..\n" ]
[ 0 ]
[]
[]
[ "lxml", "mysql", "python" ]
stackoverflow_0007764923_lxml_mysql_python.txt
Q: Keep python module in memory I'm using the Natural Language Toolkit for python and in it there is a useful function called pos_tag. You can run nltk.pos_tag() on any a list of words that were tokenized from a sentence and it will return a list of tuples with each word in the sentence and its part of speech (POS). ...
Keep python module in memory
I'm using the Natural Language Toolkit for python and in it there is a useful function called pos_tag. You can run nltk.pos_tag() on any a list of words that were tokenized from a sentence and it will return a list of tuples with each word in the sentence and its part of speech (POS). Well thats great, but I need to r...
[ "I believe that the most efficient and quick way to accomplish that is to have a separate server or process which receives text and replies with the results of post_tag() function, or whatever function you want. \n" ]
[ 2 ]
[]
[]
[ "nltk", "persistence", "python" ]
stackoverflow_0007760513_nltk_persistence_python.txt
Q: Creating a Celery task that is only executed once at a time I already read the respective article in Celery docs (Cookbook :: Creating Tasks), however I didn't completely like the solution suggested. I have very long running tasks (from 15 minutes to 1 hour or possibly even more) and thus choosing some LOCK_EXPIRE...
Creating a Celery task that is only executed once at a time
I already read the respective article in Celery docs (Cookbook :: Creating Tasks), however I didn't completely like the solution suggested. I have very long running tasks (from 15 minutes to 1 hour or possibly even more) and thus choosing some LOCK_EXPIRE setting doesn't seem reliable: if it turns out too small, I get ...
[ "Just use one lock without expiration, and create a periodic \"investigator\" Task that checks whether everything is ok, that is, if another Task died unexpectedly, it fixes the lock issue. As a plus, take a look here.\n" ]
[ 2 ]
[]
[]
[ "celery", "locking", "python" ]
stackoverflow_0007766365_celery_locking_python.txt
Q: How to run python unittests for multiple implementations in one go I'm having trouble figuring out the proper way of using pythons unittest framework I currently have 3 different implementations for a data structure class and unittests to test various things in the class as follows: import fooHorse import fooSnake...
How to run python unittests for multiple implementations in one go
I'm having trouble figuring out the proper way of using pythons unittest framework I currently have 3 different implementations for a data structure class and unittests to test various things in the class as follows: import fooHorse import fooSnake import fooMoose import unittest foo = fooHorse.foo() #foo = fooSnake.f...
[ "Just factor all the testing into a function and call it from the three tests :\nclass testFoo(unittest.TestCase):\n def _doTest(self, foo):\n foo.do_something()\n # ...\n\n def testFoorHorse(self):\n foo = fooHorse.foo()\n self._doTest(foo)\n # and so on.\n\nI wouldn't try to...
[ 2, 0 ]
[]
[]
[ "python", "testing", "unit_testing" ]
stackoverflow_0007764344_python_testing_unit_testing.txt
Q: PyQt4: Interrupted system call while calling commands.getoutput() in timer The problem appeared to be very simple, but I can not find any solution after a day of googling and looking at stackoverflow. Originally I am developing a simple plasmoid which will send a specific request to local web-server every 30 minut...
PyQt4: Interrupted system call while calling commands.getoutput() in timer
The problem appeared to be very simple, but I can not find any solution after a day of googling and looking at stackoverflow. Originally I am developing a simple plasmoid which will send a specific request to local web-server every 30 minutes, parse output and display in a label on panel. I took an example of plasmoid ...
[ "It appears that a signal is being delivered whilst the pipe is still reading.\nSo try stopping the timer before calling setLabelText(), and then restart it again afterwards.\nEDIT\nYou should also try rewriting your code to use subprocess instead of the deprecated commands module. For example:\npipe = subprocess.P...
[ 1 ]
[]
[]
[ "pipe", "pyqt", "pyqt4", "python" ]
stackoverflow_0007763740_pipe_pyqt_pyqt4_python.txt
Q: Close server socket on quit/crash I'm learning how to use sockets in python, and quite often when my program crashes or I Ctrl+C the server socket somehow stays listening on the port. This obviously stops the program from listening on that port when it starts back up again, so I have to keep changing it. I'm guess...
Close server socket on quit/crash
I'm learning how to use sockets in python, and quite often when my program crashes or I Ctrl+C the server socket somehow stays listening on the port. This obviously stops the program from listening on that port when it starts back up again, so I have to keep changing it. I'm guessing I need to do socket.close() somewhe...
[ "You could try the atexit module.\nimport atexit\n\nfunction close_socket:\n s.close()\n\natexit.register(close_socket)\n\nIf the issue is delays in the port becoming available during testing, I would suggest setting SO_REUSEADDR which will allow the port to be bound again immediately instead of waiting for time...
[ 10, 1 ]
[]
[]
[ "python", "sockets", "socketserver" ]
stackoverflow_0007766776_python_sockets_socketserver.txt
Q: how to output log info in a python cgi file? I am using cgi (python) as a proxy to solve cross-domain issue of ajax request. i want to log some key info of each request, such as url, and save these info to a file on server. what should I do? I tried python logging module or File I/O module, neither seems work in t...
how to output log info in a python cgi file?
I am using cgi (python) as a proxy to solve cross-domain issue of ajax request. i want to log some key info of each request, such as url, and save these info to a file on server. what should I do? I tried python logging module or File I/O module, neither seems work in this environment. #!C:/Python25/python.exe -u impo...
[ "It's probably a combination of using a relative path and file permissions...\nTry changing this line:\nf = open(\"./proxy.txt\",\"a\")\n\nto an absolute path, e.g.\nf = open(\"C:\\Users\\foo\\Desktop\\proxy.txt\",\"a\")\n\nMake sure that the effective user running the cgi script has permission to write to the abso...
[ 1 ]
[]
[]
[ "cgi", "logging", "proxy", "python" ]
stackoverflow_0007761832_cgi_logging_proxy_python.txt
Q: python intersect of dict items Suppose I have a dict like: aDict[1] = '3,4,5,6,7,8' aDict[5] = '5,6,7,8,9,10,11,12' aDict[n] = '5,6,77,88' The keys are arbitrary, and there could be any number of them. I want to consider every value in the dictionary. I want to treat each string as comma-separated values, and fin...
python intersect of dict items
Suppose I have a dict like: aDict[1] = '3,4,5,6,7,8' aDict[5] = '5,6,7,8,9,10,11,12' aDict[n] = '5,6,77,88' The keys are arbitrary, and there could be any number of them. I want to consider every value in the dictionary. I want to treat each string as comma-separated values, and find the intersection across the entire...
[ "from functools import reduce # if Python 3\n\nreduce(lambda x, y: x.intersection(y), (set(x.split(',')) for x in aDict.values()))\n\n", "First of all, you need to convert these to real lists.\nl1 = '3,4,5,6,7,8'.split(',')\n\nThen you can use sets to do the intersection.\nresult = set(l1) & set(l2) & set(l3)\n\n...
[ 4, 3, 1, 0, 0 ]
[]
[]
[ "intersect", "python" ]
stackoverflow_0007765583_intersect_python.txt
Q: Print two random, different names from a set of names import random mylist = ['anthony', 'kris', 'james', 'vinny', 'joe'] randomList1 = random.randrange(0,len(mylist)) randomList2 = random.randrange(0,len(mylist)) name2 = mylist[randomList1] name3 = mylist[randomList2] print 'The group will consist of'...
Print two random, different names from a set of names
import random mylist = ['anthony', 'kris', 'james', 'vinny', 'joe'] randomList1 = random.randrange(0,len(mylist)) randomList2 = random.randrange(0,len(mylist)) name2 = mylist[randomList1] name3 = mylist[randomList2] print 'The group will consist of', name2, 'and', name3,'. ' Is the code in question, this i...
[ "Use random.sample:\n>>> import random \n>>> mylist = ['anthony', 'kris', 'james', 'vinny', 'joe']\n>>> random.sample(mylist, 2)\n['james', 'vinny']\n\n", ">>> from random import sample\n>>> mylist = ['anthony', 'kris', 'james', 'vinny', 'joe']\n>>> sample(mylist,2)\n['kris', 'vinny']\n\n", "You can use random...
[ 8, 2, 2, 0, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0007767185_python_random.txt
Q: How to declare a form field in Django, if it has the same name as a Python keyword? I've got a simple form in Django, that looks something like this: class SearchForm(forms.Form): text = forms.CharField() from = forms.DateField() until = forms.DateField() Which fails with a SyntaxError, because from i...
How to declare a form field in Django, if it has the same name as a Python keyword?
I've got a simple form in Django, that looks something like this: class SearchForm(forms.Form): text = forms.CharField() from = forms.DateField() until = forms.DateField() Which fails with a SyntaxError, because from is a Python keyword. I rather not change the name of the field; It fits better than any of...
[ "Don't name things after keywords, even if you find a work around, it will probably end up biting you later.\nUse a synonym or add a prefix/suffix instead.\nE.g.\nstart -> finish\nbegin -> end\ndate_from -> date_to\n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007767317_django_python.txt
Q: Importing java class in python module I have created one package in Java and one publis class inside it. package GX1164; public class Test { public int add(int a) { return (a+a); } } Now I have to import this package and class in python module to call the function "add". But somehow I am not able ...
Importing java class in python module
I have created one package in Java and one publis class inside it. package GX1164; public class Test { public int add(int a) { return (a+a); } } Now I have to import this package and class in python module to call the function "add". But somehow I am not able to import the class Test. I keep getting th...
[ "Build your java class into a .jar file then do the following\nAppending the jar to sys.path is the same as setting a class path.\nimport sys\nsys.path.append(\"GX1164.jar\")\n\nimport GX1164\n\ntest = GX1146.Test()\nprint test.add(42)\n\n", "Well, your module is called GX1164 and the class is called Test:\nimpor...
[ 3, 2 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0007766356_jython_python.txt
Q: Why isn't 0-padding allowed in Python? I've just noticed 0-padding is not allowed in Python and I was wondering why this choice was made? For example: a = 09 doesn't work while a = 9 does How's that?! Thank you very much for your answers! A: Python, as many other languages, treat numbers starting with 0 as bei...
Why isn't 0-padding allowed in Python?
I've just noticed 0-padding is not allowed in Python and I was wondering why this choice was made? For example: a = 09 doesn't work while a = 9 does How's that?! Thank you very much for your answers!
[ "Python, as many other languages, treat numbers starting with 0 as being in octal notation. 09 is not valid as octal\nSee chapter 2.4.4 in the python language reference.\n", "To expand on what @nos said:\n>>> a = 01\n>>> a\n1\n>>> a = 07\n>>> a\n7\n>>> a = 010\n>>> a\n8\n>>> a = 08\n File \"<stdin>\", line 1\n ...
[ 8, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007767856_python.txt
Q: file comparision using python I have two text files file1: 1234 13454 93837 82739 file2: comp i 93837 -4.52 82739 -2.2 1234 -2.36 13454 -2.25 I tried a python script to compare files and it should ideally do following search CID from file1 in file2 and append i value to file1. But unfortunately it is not working...
file comparision using python
I have two text files file1: 1234 13454 93837 82739 file2: comp i 93837 -4.52 82739 -2.2 1234 -2.36 13454 -2.25 I tried a python script to compare files and it should ideally do following search CID from file1 in file2 and append i value to file1. But unfortunately it is not working. file1=open("f1.txt","r") file2=op...
[ "Here's a working solution that modifies your original as little as possible:\nfile1=open(\"f1.txt\",\"r\")\nfile2=open(\"f2.txt\",\"r\")\n\nlist1 = file1.readlines()\nlist2 = file2.readlines()\nfor line1 in list1:\n for line2 in list2:\n if line1.strip() in line2.strip().split(' '):\n print line2\n\n", ...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007767801_python.txt
Q: XML Encoding error while writing it in to file I think I am following the right approach but I am still getting an encoding error: from xml.dom.minidom import Document import codecs doc = Document() wml = doc.createElement("wml") doc.appendChild(wml) property = doc.createElement("property") wml.appendChild(prope...
XML Encoding error while writing it in to file
I think I am following the right approach but I am still getting an encoding error: from xml.dom.minidom import Document import codecs doc = Document() wml = doc.createElement("wml") doc.appendChild(wml) property = doc.createElement("property") wml.appendChild(property) descriptionNode = doc.createElement("descripti...
[ "Ok i have found a solution. When ever data is in other foriegn language you just need to defined the proper encoding in xml header. You do not need to describe encoding in file.write(doc.toprettyxml(encoding='ISO-8859-1')) not even when you are opening a file for writing file = codecs.open('contentFinal.xml', 'w',...
[ 1 ]
[]
[]
[ "character_encoding", "python", "xml" ]
stackoverflow_0007589827_character_encoding_python_xml.txt
Q: Unable to write to AppEngine DataStore using web2py's DAL I've just started using web2py with Google AppEngine for an app of mine. For some reason, I'm unable to save/retrieve data using the DAL. Here's the code I'm using: At the end of db.py: from aeoid import middleware from aeoid import users import json db.de...
Unable to write to AppEngine DataStore using web2py's DAL
I've just started using web2py with Google AppEngine for an app of mine. For some reason, I'm unable to save/retrieve data using the DAL. Here's the code I'm using: At the end of db.py: from aeoid import middleware from aeoid import users import json db.define_table('files', db.Field('name', 'tex...
[ "When using the shortcut syntax db.table[id], id refers to the record ID. db.table[0] doesn't actually refer to an existing record -- it is just used to insert a new record. \nAlso, on GAE, the record IDs do not start at 1 and get incremented by 1, so your first inserted record will not have ID=1. You can either do...
[ 1 ]
[]
[]
[ "database", "google_app_engine", "python", "web2py" ]
stackoverflow_0007767808_database_google_app_engine_python_web2py.txt
Q: Cannot find data from string using regex while string.find() works just fine import re import urllib p = urllib.urlopen("http://sprunge.us/QZhU") page = p.read() pos = page.find("<h2><span>") print page[pos:pos+48] c = re.compile(r'<h2><span>(.*)</span>') print c.match(page).group(1) When I run it: shadyabhi@arc...
Cannot find data from string using regex while string.find() works just fine
import re import urllib p = urllib.urlopen("http://sprunge.us/QZhU") page = p.read() pos = page.find("<h2><span>") print page[pos:pos+48] c = re.compile(r'<h2><span>(.*)</span>') print c.match(page).group(1) When I run it: shadyabhi@archlinux $ python2 temp.py <h2><span>House.S08E02.HDTV.XviD-LOL.avi</span> Traceba...
[ "match only matches at the beginning of the string. Use search, finditer or findall.\nAlso note that * is greedy. You might want to change your regex to r'<h2><span>(.*?)</span>'.\nIn summary, the following works for me:\nimport re\nimport urllib\np = urllib.urlopen(\"http://sprunge.us/QZhU\")\npage = p.read()\npos...
[ 6 ]
[]
[]
[ "python", "regex", "urllib", "web_scraping" ]
stackoverflow_0007768157_python_regex_urllib_web_scraping.txt
Q: How to apply a function to each 3rd axis element in a numpy array? If I have a numpy array like so: [[[137 153 135] [138 154 136] [138 153 138] ..., [134 159 153] [136 159 153] [135 158 152]] ..., [ 57 44 34] [ 55 47 37] [ 55 47 37]]] How can I apply a function to each [000 000 000] en...
How to apply a function to each 3rd axis element in a numpy array?
If I have a numpy array like so: [[[137 153 135] [138 154 136] [138 153 138] ..., [134 159 153] [136 159 153] [135 158 152]] ..., [ 57 44 34] [ 55 47 37] [ 55 47 37]]] How can I apply a function to each [000 000 000] entry, modifying it? # a = numpy array for x in a: for y in x: ...
[ "A simple answer to your question is\nfor row in a:\n for item in row:\n item[:] = modify(item)\n\nThis won't be very efficient, though. An efficient solution should avoid Python loops over all pixels. (That's somehow what NumPy is all about -- vectorise your code!) A vectorised version for the case at ...
[ 5, 0 ]
[]
[]
[ "numpy", "python", "python_imaging_library" ]
stackoverflow_0007767886_numpy_python_python_imaging_library.txt
Q: Django CMS "No module named html5lib" I have a basic Django CMS site installed with all the default and recommended modules however I recieve and error saying... Updated Request Method: GET Request URL: http://teamdjango.lnukapps.co.uk/admin/cms/page/21/ Django Version: 1.3.1 Exception Type: ImportError Excepti...
Django CMS "No module named html5lib"
I have a basic Django CMS site installed with all the default and recommended modules however I recieve and error saying... Updated Request Method: GET Request URL: http://teamdjango.lnukapps.co.uk/admin/cms/page/21/ Django Version: 1.3.1 Exception Type: ImportError Exception Value: No module named html5lib Exce...
[ "Either you have two versions of python installed or you need to set your python path.\nGet the path the module is installed to\n>>> import html5lib\n>>> html5lib.__file__\n\n'/Library/Python/2.7/site-packages/html5lib-0.90-py2.7.egg/html5lib/init.pyc'\n\n\n\n^D\n\n\n\nSet the PYTHONPATH environment variabled.\nexp...
[ 0 ]
[]
[]
[ "django", "html5lib", "python" ]
stackoverflow_0007768443_django_html5lib_python.txt
Q: json[more levels] to dict python i'm having trouble with a simple question. a = { "apiVersion": "2.1", "data": { "startIndex": 1, "items": [{ "id": "YVA3UoZM0zU", "title": "Trailer - Lisbela eo Prisioneiro" ...
json[more levels] to dict python
i'm having trouble with a simple question. a = { "apiVersion": "2.1", "data": { "startIndex": 1, "items": [{ "id": "YVA3UoZM0zU", "title": "Trailer - Lisbela eo Prisioneiro" }] ...
[ "Try:\njs['data']['items'][0]['id']\n\nIt would appear that there may be multiple items in this structure. If you'd like to extract all item ids as a list, the following will do it:\n[item['id'] for item in js['data']['items']]\n\n" ]
[ 11 ]
[]
[]
[ "dictionary", "json", "python" ]
stackoverflow_0007768633_dictionary_json_python.txt
Q: Python: how to do basic data manipulation like in R? I have been working with R for several years. R is very strong in data manipulation. I'm learning python and I would like to know how to manipulate data using python. Basically my data sets are organized as data frames (e.g excel sheet). I would like to know (by...
Python: how to do basic data manipulation like in R?
I have been working with R for several years. R is very strong in data manipulation. I'm learning python and I would like to know how to manipulate data using python. Basically my data sets are organized as data frames (e.g excel sheet). I would like to know (by example) how this kind of basic data manipulation task ca...
[ "I disagree with Cpfohl's comment - perhaps because I've been through this same transition myself, and it's not obvious how a naive user would be able to formulate the problem more precisely. It is actually an active development problem right now with a number of projects that have all come up with non-overlapping ...
[ 23, 14, 11, 3 ]
[]
[]
[ "python", "r" ]
stackoverflow_0004899851_python_r.txt
Q: WSGI, Werkzeug and form based authentication I would like to implement a WSGI/Werzeug based web application and need help implementing the form based authentication. I found repoze.who and think it solves most of my problems. It works fine with SqlAlchemy which I will use for my database code. What I'm looking for...
WSGI, Werkzeug and form based authentication
I would like to implement a WSGI/Werzeug based web application and need help implementing the form based authentication. I found repoze.who and think it solves most of my problems. It works fine with SqlAlchemy which I will use for my database code. What I'm looking for is code to have salted passwords, protection from...
[ "Flask is a good microframework to get you started. You can use WTForms to handle the forms, SQLAlchemy as the ORM and Jinja2 to handle the templates. It's a good match. \nEDIT: Flask has some extensions that might help with what you need (Login extension?)\n" ]
[ 0 ]
[]
[]
[ "python", "security", "sqlalchemy", "werkzeug", "wsgi" ]
stackoverflow_0007767903_python_security_sqlalchemy_werkzeug_wsgi.txt
Q: Python + Django ImportError: cannot import name signals from Python2.5 to Python2.7 I have django-registration installed. I just updated my Python installation from 2.5 to 2.7. Everything works okay but when I try to run my Django app, I get the error below. C:\django\pley>python manage.py runserver Validating mod...
Python + Django ImportError: cannot import name signals from Python2.5 to Python2.7
I have django-registration installed. I just updated my Python installation from 2.5 to 2.7. Everything works okay but when I try to run my Django app, I get the error below. C:\django\pley>python manage.py runserver Validating models... Unhandled exception in thread started by <function inner_run at 0x02FA6830> Traceb...
[ "Seems ok to me. When you unpack django-registration you get 2 folders doc and registration. In registration folder you have a file called signals.py. This is precisely the file that your django app is trying to import.\nEither see if you have added django-registration as INSTALLED_APPS in your project settings.py....
[ 1, 0 ]
[]
[]
[ "django", "django_registration", "python" ]
stackoverflow_0003893396_django_django_registration_python.txt
Q: Python: for loop in index assignment While working through the awesome book "Programming Collective Intelligence", by Toby Segaran, I've encountered some techniques in index assignments I'm not entirely familiar with. Take this for example: createkey='_'.join(sorted([str(wi) for wi in wordids])) or: normalizedsco...
Python: for loop in index assignment
While working through the awesome book "Programming Collective Intelligence", by Toby Segaran, I've encountered some techniques in index assignments I'm not entirely familiar with. Take this for example: createkey='_'.join(sorted([str(wi) for wi in wordids])) or: normalizedscores = dict([(u,float(l)/maxscore) for (u,l...
[ "[str(wi) for wi in wordids]\n\nis a list comprehension.\na = [str(wi) for wi in wordids]\n\nis the same as\na = []\nfor wi in wordids:\n a.append(str(wi))\n\nSo \ncreatekey='_'.join(sorted([str(wi) for wi in wordids]))\n\ncreates a list of strings from each item in wordids, then sorts that list and joins it int...
[ 15, 3, 1, 1, 1, 1 ]
[]
[]
[ "dictionary", "indexing", "python", "variable_assignment" ]
stackoverflow_0007768859_dictionary_indexing_python_variable_assignment.txt
Q: Django - how to get the contents of a {% block %} tag from a template I got this far: >>> some_template = get_template_from_string( ... load_template_source( ... 'some_template.html', ... settings.TEMPLATE_DIRS)) ... >>> blocks = some_template.nodelist.get_nodes_by_type(BlockNode) >>> blocks[0...
Django - how to get the contents of a {% block %} tag from a template
I got this far: >>> some_template = get_template_from_string( ... load_template_source( ... 'some_template.html', ... settings.TEMPLATE_DIRS)) ... >>> blocks = some_template.nodelist.get_nodes_by_type(BlockNode) >>> blocks[0] <Block Node: another_block. Contents: [<Text Node: '\nThis one is really ...
[ "This seems like you're working hard against the Django grain. Put the content into an include file, then {% include %} it in your block, and also read the file directly. If you could tell us more about what you're trying to accomplish, there's probably a better way to do it.\n", "The solution I created:\nimpor...
[ 2, 0 ]
[]
[]
[ "django", "django_templates", "python", "regex" ]
stackoverflow_0007758443_django_django_templates_python_regex.txt
Q: Pyramid, Chameleon and template rendering I started a project with the Python web framwork 'Pyramid', using the template engine 'chameleon'. I'm a beginner of this frameworks, but I have to use it for a customer. I follow the steps in order to install the framework, then I started coding, just for training purpose...
Pyramid, Chameleon and template rendering
I started a project with the Python web framwork 'Pyramid', using the template engine 'chameleon'. I'm a beginner of this frameworks, but I have to use it for a customer. I follow the steps in order to install the framework, then I started coding, just for training purpose! My first application was a stupid, simple CRU...
[ "Using the ${} syntax escapes the included text by default (to help defend against XSS injection attacks).\nInstead, use the structure: prefix to tell the rendering engine to not escape your text:\n<div>${structure: body}</div>\n\n" ]
[ 6 ]
[]
[]
[ "chameleon", "pyramid", "python", "template_tal" ]
stackoverflow_0007769062_chameleon_pyramid_python_template_tal.txt
Q: How to convert all arguments to string in string formatting Starting with this from Corey Goldberg: #!/usr/bin/env python import json import pprint import urllib2 def get_stock_quote(ticker_symbol): url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol lines = urllib2.urlopen(url).read()...
How to convert all arguments to string in string formatting
Starting with this from Corey Goldberg: #!/usr/bin/env python import json import pprint import urllib2 def get_stock_quote(ticker_symbol): url = 'http://finance.google.com/finance/info?q=%s' % ticker_symbol lines = urllib2.urlopen(url).read().splitlines() return json.loads(''.join([x for x in lines if...
[ "Your problem is that %s can't handle a tuple with 2 elements, see that example below:\n>>> \"=%s\" % ('Goog',)\n'=Goog'\n>>> \"=%s\" % ('Goog','MSFT')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: not all arguments converted during string formatting\n\nAnyway, use format(...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "string", "urllib2" ]
stackoverflow_0007769419_python_string_urllib2.txt
Q: matplotlib: adding second axes() with transparent background? Define data x = np.linspace(0,2*np.pi,100) y = 2*np.sin(x) Plot fig = plt.figure() ax = plt.axes() fig.add_subplot(ax) ax.plot(x,y) Add second axis newax = plt.axes(axisbg='none') Gives me ValueError: Unknown element o, even though it does the same t...
matplotlib: adding second axes() with transparent background?
Define data x = np.linspace(0,2*np.pi,100) y = 2*np.sin(x) Plot fig = plt.figure() ax = plt.axes() fig.add_subplot(ax) ax.plot(x,y) Add second axis newax = plt.axes(axisbg='none') Gives me ValueError: Unknown element o, even though it does the same thing as what I am about to describe. I can also see that this works...
[ "You're not actually adding a new axes.\nMatplotlib is detecting that there's already a plot in that position and returning it instead of a new axes object.\n(Check it for yourself. ax and newax will be the same object.)\nThere's probably not a reason why you'd want to, but here's how you'd do it.\n(Also, don't cal...
[ 49 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007761778_matplotlib_python.txt
Q: Python regex negative lookbehind We parse logs created by automated scripts. A typical thing that we'd care about is the string: '1.10.07-SNAPSHOT (1.10.07-20110303.024749-7)' from the following line: 15:28:02.115 - INFO - TestLib: Successfully retrieved build version: '1.11.11-SNAPSHOT (1.11.11-20110303.024749...
Python regex negative lookbehind
We parse logs created by automated scripts. A typical thing that we'd care about is the string: '1.10.07-SNAPSHOT (1.10.07-20110303.024749-7)' from the following line: 15:28:02.115 - INFO - TestLib: Successfully retrieved build version: '1.11.11-SNAPSHOT (1.11.11-20110303.024749-7)' The trouble is, some logs are ma...
[ "You are close, but it is still matching because it can find a string that satisfies .* without being preceded by Step Dialog. Positive and negative assertions only affect the pattern immediately surrounding them. Thus, you have to force it to check every character you don't want matching Step Dialog.\nTry this:\n`...
[ 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007769144_python_regex.txt
Q: Extracting Lotus Notes NSF files under Linux I want to extract NSF Lotus Notes files under linux. are there any opensource tools without the need of installing Lotus Note server ? I do not have any experience with lotus notes my only task is to extract everything from NSF archive. What i have found over web only s...
Extracting Lotus Notes NSF files under Linux
I want to extract NSF Lotus Notes files under linux. are there any opensource tools without the need of installing Lotus Note server ? I do not have any experience with lotus notes my only task is to extract everything from NSF archive. What i have found over web only said to install Domino server and use it via MAPI o...
[ "You can't extract data from Lotus Notes without at least having the Lotus Notes client installed. \nThere are a number of ways to extract data from Notes. You can write Java or LotusScript agents to export to file formats. You can access Lotus Notes via the Lotus Notes SQL driver and use SQL queries or MS Acces...
[ 6, 3 ]
[]
[]
[ "java", "linux", "lotus_domino", "lotus_notes", "python" ]
stackoverflow_0007687021_java_linux_lotus_domino_lotus_notes_python.txt
Q: Trouble with parsing HTML with unicodes through Beautiful Soup Beautiful Soup doesn't seem to work properly(for me) in case HTML contains unicodes whose ascii exceeds 128. What suitable decoding-encoding should be used for this ? raw = open('index.html').read() BeautifulSoup.BeautifulSoup(raw) Error ...stacktrace...
Trouble with parsing HTML with unicodes through Beautiful Soup
Beautiful Soup doesn't seem to work properly(for me) in case HTML contains unicodes whose ascii exceeds 128. What suitable decoding-encoding should be used for this ? raw = open('index.html').read() BeautifulSoup.BeautifulSoup(raw) Error ...stacktrace... UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9'...
[ "The problem is not with parsing the file. Using the link you gave in your comment to Marco, doing soup = BeautifulSoup(urllib.urlopen(your_link)) works absolutely fine.\nIt's just when you try and print that parsed data to the console that you get a problem, because it's now been converted to Unicode, and Python w...
[ 1 ]
[]
[]
[ "beautifulsoup", "html_parsing", "python", "regex" ]
stackoverflow_0007769322_beautifulsoup_html_parsing_python_regex.txt
Q: C++-classes with SWIG I try to create a python interface (with swig) from C++-code. With the code below. When I remove the line: aClass z = aClass(1); from the .cpp-file i get the following error: Traceback (most recent call last): File "./testit.py", line 3, in <module> import testlib File "(...)/testlib...
C++-classes with SWIG
I try to create a python interface (with swig) from C++-code. With the code below. When I remove the line: aClass z = aClass(1); from the .cpp-file i get the following error: Traceback (most recent call last): File "./testit.py", line 3, in <module> import testlib File "(...)/testlib.py", line 26, in <module> ...
[ "vines@Aspire-5755G:~$ c++filt _ZN6aClassC1Ei\naClass::aClass(int)\n\nIt's a linker error. Try:\ng++ -shared $1_wrap.o $1.o -o _$1.so\n\ni.e. swap the object files. It's because the order they are given matters, and it's reasonable to suppose that $1_wrap.o wants to pull some methods from $1.o.\n" ]
[ 0 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0007770180_c++_python_swig.txt
Q: in Python and linux how to get given user's id There is os.getuid() which "Returns the current process’s user id.". But how do I find out any given user's id? A: You could use pwd.getpwnam(): In [5]: pwd.getpwnam('aix').pw_uid Out[5]: 1004 A: Assuming what you want is the username string associated with the us...
in Python and linux how to get given user's id
There is os.getuid() which "Returns the current process’s user id.". But how do I find out any given user's id?
[ "You could use pwd.getpwnam():\nIn [5]: pwd.getpwnam('aix').pw_uid\nOut[5]: 1004\n\n", "Assuming what you want is the username string associated with the userid for your program, try:\nimport os\nimport pwd\npwd.getpwuid( os.getuid() ).pw_name\n\nUse os.geteuid() to get the effective uid instead, if that differen...
[ 40, 36, 6 ]
[ "You could just parse /etc/passwd, it's stored there.\n" ]
[ -5 ]
[ "linux", "python" ]
stackoverflow_0007770034_linux_python.txt
Q: How to implement a standard logger and argparser for a package I am trying to implement a python build package and functional testing package for our internal software development processes. My primary goal is to implement a global/standard logger (similar to the reference here) and argparser that all modules wil...
How to implement a standard logger and argparser for a package
I am trying to implement a python build package and functional testing package for our internal software development processes. My primary goal is to implement a global/standard logger (similar to the reference here) and argparser that all modules will use from within their perspective packages (i.e. the build logger ...
[ "For logging look no further than the python logging documentation. It is a very easy to implement logging system that is very flexible.\nAs to your question about __init__.py, if you come from other programming languages, think of it as a constructor. If you want some default values assigned on load, then they s...
[ 0 ]
[]
[]
[ "argparse", "build", "package", "python" ]
stackoverflow_0007770427_argparse_build_package_python.txt
Q: os.walk but with pre and post actions per directory? Python's os.walk function is almost what I want, but I need to do a pre- and post-traversal action for each directory. e.g. if the tree is foo/ foo/bar/ foo/bar/baz/ foo/quux/ then I want to do this sequence: pre-action on foo/ pre-action on foo/bar/ pre...
os.walk but with pre and post actions per directory?
Python's os.walk function is almost what I want, but I need to do a pre- and post-traversal action for each directory. e.g. if the tree is foo/ foo/bar/ foo/bar/baz/ foo/quux/ then I want to do this sequence: pre-action on foo/ pre-action on foo/bar/ pre-action on foo/bar/baz/ post-action on foo/bar/baz/ post...
[ "If you don't want to write a simple recursive function yourself, you can use your own stack:\nstack = []\nfor root, dirs, files in os.walk(\"foo\"):\n while stack and not root.startswith(stack[-1]):\n print \"post-action on\", stack.pop()\n print \"pre-action on\", root\n stack.append(root)\nwhile ...
[ 2, 0 ]
[]
[]
[ "filesystems", "python" ]
stackoverflow_0007770488_filesystems_python.txt
Q: Merge/append lists that share a common item The title may be misleading, so feel free to change the wording when the terminology for the real problem arises. =) In this case, I am aware that the lists can probably be interchanged with tuples, for the most part. The end result can be any iterable as far as I'm conc...
Merge/append lists that share a common item
The title may be misleading, so feel free to change the wording when the terminology for the real problem arises. =) In this case, I am aware that the lists can probably be interchanged with tuples, for the most part. The end result can be any iterable as far as I'm concerned. I have two lists-of-lists. Suppose they ar...
[ "from collections import defaultdict\nfrom itertools import chain\n\nfinal = defaultdict(list)\n\nfor idx, value in chain(l1, l2):\n final[idx].append(value)\n\n# and if you have to have a list of lists at the end\nfinalList = [[k] + v for k, v in final.iteritems()]\n\n", "Your input lists should be dictionaries...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007771046_python.txt
Q: Need to ask user if he wants to try again (Python) #Ask the user what option he wants mode = input("Would you like to count Vowel's or Consonant's ? (Vowel or Consonant): ") mode = mode.strip() mode = mode.lower() # Tell the user the input he entered wasn't valid while mode != 'consonant' and mode...
Need to ask user if he wants to try again (Python)
#Ask the user what option he wants mode = input("Would you like to count Vowel's or Consonant's ? (Vowel or Consonant): ") mode = mode.strip() mode = mode.lower() # Tell the user the input he entered wasn't valid while mode != 'consonant' and mode != 'vowel': mode = input("That's not correct. W...
[ "while c:\n do_stuff()\n c = raw_input('Do you want to contine y/n')\n if c.lower().startswith('y'):\n c = True\n else:\n c = False\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007771522_python.txt
Q: How to create a class attribute and class property within Elixir/SqlAlchemy I have a class: from sys import stderr from elixir import * from types import * class User(Entity): using_options(tablename="users") first_name = Field(String(50)) middle_name = Field(String(50)) last_name = Field(String(5...
How to create a class attribute and class property within Elixir/SqlAlchemy
I have a class: from sys import stderr from elixir import * from types import * class User(Entity): using_options(tablename="users") first_name = Field(String(50)) middle_name = Field(String(50)) last_name = Field(String(50)) def __get_name__ (self): first_name = self.first_name if self.fi...
[ "You are define the property and that will be available after object will be assign. \nNote : I change your code for my convenience\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, DateTime, String\nfrom datetime import datetime\n\nBase = declarative_base()\nclass Us...
[ 2, 2 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0007758276_python_python_elixir_sqlalchemy.txt
Q: Add more than one line to a QTextEdit PyQt I am experiencing a rather strange issue with my PyQT QTextEdit. When I enter a string from my QLineEdit it adds it but say I enter another the first string disappears I assume that's because I am not appending the text. Any idea how I can do this? Here is the relevant co...
Add more than one line to a QTextEdit PyQt
I am experiencing a rather strange issue with my PyQT QTextEdit. When I enter a string from my QLineEdit it adds it but say I enter another the first string disappears I assume that's because I am not appending the text. Any idea how I can do this? Here is the relevant code: self.mytext.setText(str(self.user) + ": " + ...
[ "The setText() method replaces all the current text, so you just need to use the append() method instead. (Note that both these methods automatically add a trailing newline).\nimport sys\nfrom PyQt4 import QtGui\n\nclass Window(QtGui.QWidget):\n def __init__(self):\n QtGui.QWidget.__init__(self)\n ...
[ 20 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0007771164_pyqt_python.txt
Q: How to right align level field in Python logging.Formatter I'm currently trying to right align the logging level field in my Python logger so that output such as: [2011-10-14 13:47:51] [DEBUG] --- starting... (smtphandlers.py:96) [2011-10-14 13:47:51] [INFO] --- first things first... (smtphandlers.py:97) [2011-10-...
How to right align level field in Python logging.Formatter
I'm currently trying to right align the logging level field in my Python logger so that output such as: [2011-10-14 13:47:51] [DEBUG] --- starting... (smtphandlers.py:96) [2011-10-14 13:47:51] [INFO] --- first things first... (smtphandlers.py:97) [2011-10-14 13:47:51] [WARNING] --- about to end... (smtphandlers.py:98) ...
[ "Like this:\nlogging.Formatter(\"[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)s)\", \"%Y-%m-%d %H:%M:%S\")\n\n", "Try with this format line : \nlogging.Formatter(\"[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)s)\", \"%Y-%m-%d %H:%M:%S\")\n\npython logger formatter...
[ 102, 15 ]
[]
[]
[ "formatting", "logging", "python" ]
stackoverflow_0007771912_formatting_logging_python.txt
Q: PyGTK: CellRendererPixbuf and transparency I'm using PyGTK and I want to draw something inside a CellRenderer, so I'm using a CellRendererPixbuff, and it's working. The only problem is that if that drawing has transparency, the output will be bad and mixed up. Screenshot: http://postimage.org/image/f839ijd0/ My co...
PyGTK: CellRendererPixbuf and transparency
I'm using PyGTK and I want to draw something inside a CellRenderer, so I'm using a CellRendererPixbuff, and it's working. The only problem is that if that drawing has transparency, the output will be bad and mixed up. Screenshot: http://postimage.org/image/f839ijd0/ My code: def pixbufSqFromColor(color, size, roundR=0)...
[ "I've a similar problem and it seems to stem from gdk.Pixmap but I have no solution yet.\nEdit :\nI've solved my problem by using gtk.gdk.pixbuf_new_from_xpm_data() to generate the pixbuf, instead of gdk.Pixmap and Cairo operations. I know you can't use it because you have size and roundR parameters.\nMaybe you can...
[ 1 ]
[]
[]
[ "colors", "gtk", "pygtk", "python", "transparency" ]
stackoverflow_0007703087_colors_gtk_pygtk_python_transparency.txt
Q: Plotting Histogram With Pylab Working in Python 2.7. I'm trying to plot a histogram for the numbers generated by 50 run-throughs of my random walk. But when I use pylab.hist(batting_average, bins = 10), I get a weird multi-colored histogram that goes up close to 500, but with only 50 runs of the walk, the maximum ...
Plotting Histogram With Pylab
Working in Python 2.7. I'm trying to plot a histogram for the numbers generated by 50 run-throughs of my random walk. But when I use pylab.hist(batting_average, bins = 10), I get a weird multi-colored histogram that goes up close to 500, but with only 50 runs of the walk, the maximum it should be able to go on the y-ax...
[ "The argument passed to battingAverage is 501... and is the number of at-bats. You're doing 50 histograms with 500 at-bats per histogram.\n(Oh, and you need to fix the formatting of your code... the indentation is messed up.)\nYour code doesn't do what you think it does.\nI think you're wanting battingAverage to r...
[ 1 ]
[]
[]
[ "histogram", "matplotlib", "python" ]
stackoverflow_0007772253_histogram_matplotlib_python.txt
Q: Are Decimal 'dtypes' available in NumPy? Are Decimal data type objects (dtypes) available in NumPy? >>> import decimal, numpy >>> d = decimal.Decimal('1.1') >>> s = [['123.123','23'],['2323.212','123123.21312']] >>> ss = numpy.array(s, dtype=numpy.dtype(decimal.Decimal)) >>> a = numpy.array(s, dtype=float) >>> typ...
Are Decimal 'dtypes' available in NumPy?
Are Decimal data type objects (dtypes) available in NumPy? >>> import decimal, numpy >>> d = decimal.Decimal('1.1') >>> s = [['123.123','23'],['2323.212','123123.21312']] >>> ss = numpy.array(s, dtype=numpy.dtype(decimal.Decimal)) >>> a = numpy.array(s, dtype=float) >>> type(d) <class 'decimal.Decimal'> >>> type(ss[1,1...
[ "NumPy doesn't recognize decimal.Decimal as a specific type. The closest it can get is the most general dtype, object. So when converting the elements to the desired dtype, the conversion is a no operation.\n>>> ss.dtype\ndtype('object')\n\nKeep in mind that because the elements of the array are Python objects, y...
[ 30, 13, 5 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007770870_numpy_python.txt
Q: notepad++ run selected code in python console seamlessly I often use R to analyze data, and really enjoy Notepad++ along with NppToR. Especially, NppToR enables to run a part of code without much hassle. I just highlight a snippet of R code to run and press F8. Then the code magically runs in R console. Now, I am ...
notepad++ run selected code in python console seamlessly
I often use R to analyze data, and really enjoy Notepad++ along with NppToR. Especially, NppToR enables to run a part of code without much hassle. I just highlight a snippet of R code to run and press F8. Then the code magically runs in R console. Now, I am required to use python to analyze data. I know that ipython is...
[ "You can customize the editor IPython uses for the edit command, and configure IPython to use Notepad++. IPython 0.11 creates a .ipython/profile_default folder in your user folder (in my case C:/Users/zk/.ipython/profile_default). To configure IPython to use Notepad++ create .ipython/profile_default/ipython_config....
[ 5 ]
[]
[]
[ "ipython", "notepad++", "python", "r" ]
stackoverflow_0007771899_ipython_notepad++_python_r.txt
Q: Syntax Error in Python Request Library when Using on My Test server I'm using Python Request Library in one of my projects. Everything works fine on my local system where I have Python 2.6 and Django 1.2.3. I have created the same environment for my Test server(Python 2.6 and Django 1.2.3 and is using WSGI 3.2). N...
Syntax Error in Python Request Library when Using on My Test server
I'm using Python Request Library in one of my projects. Everything works fine on my local system where I have Python 2.6 and Django 1.2.3. I have created the same environment for my Test server(Python 2.6 and Django 1.2.3 and is using WSGI 3.2). Now I get some weird syntax errors. For example: line 266 result.appen...
[ "This errors mean that actually you are not using Python 2.6. Probably Python 2.4 is also installed on you environment and it is used to execute your code.\n", "I'm guessing your webserver (such as apache) is using an older version of python, rather than the python 2.6 environment you setup.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "django_wsgi", "mod_wsgi", "python", "python_requests" ]
stackoverflow_0007772592_django_django_wsgi_mod_wsgi_python_python_requests.txt
Q: Python convert and save unicode string to a list I need to insert a series of names (like 'Alam\xc3\xa9') into a list, and than I have to save them into a SQLite database. I know that I can render these names correctly by tiping: print eval(repr(NAME)).decode("utf-8") But I have to insert them into a list, so I c...
Python convert and save unicode string to a list
I need to insert a series of names (like 'Alam\xc3\xa9') into a list, and than I have to save them into a SQLite database. I know that I can render these names correctly by tiping: print eval(repr(NAME)).decode("utf-8") But I have to insert them into a list, so I can't use the print Other way for doing this without th...
[ "Lots and lots of misconceptions here.\nThe string you quote is not Unicode. It is a byte string, encoded in UTF-8.\nYou can convert it to Unicode by decoding it:\nunicode_name = name.decode('utf-8')\n\nWhen you print the value of unicode_name to the console, you will see one of two things:\n>>> unicode_name\nu'Ala...
[ 6, 0 ]
[]
[]
[ "python", "unicode", "utf_8" ]
stackoverflow_0007769745_python_unicode_utf_8.txt
Q: Is it possible to test exception conditions using Ludibrio? I've recently started using Ludibrio for mocking objects in unit testing. So far it seems to be pretty streamlined, but I seem to have hit a snag when testing some failure scenarios and can't seem to find a solution online. Some of the method calls I'm w...
Is it possible to test exception conditions using Ludibrio?
I've recently started using Ludibrio for mocking objects in unit testing. So far it seems to be pretty streamlined, but I seem to have hit a snag when testing some failure scenarios and can't seem to find a solution online. Some of the method calls I'm working with raise exceptions which I want to trap. So I want my ...
[ "Further Googling has eventually yielded the answer. Simply tell the mock object to pass back an exception. This appears to then be raised on the outside:\nmyMock.test() >> Exception('blah')\n\n" ]
[ 2 ]
[]
[]
[ "mocking", "python" ]
stackoverflow_0007766403_mocking_python.txt
Q: Run an OS X universal binary in 32-bit mode I have a third-party library (the interface to Xerox's Finite State tools) which come as universal binaries with two variants internally: a PPC and an i386 variant. I also have a Python interface to the library (which uses ctypes). But when I try to run the example code ...
Run an OS X universal binary in 32-bit mode
I have a third-party library (the interface to Xerox's Finite State tools) which come as universal binaries with two variants internally: a PPC and an i386 variant. I also have a Python interface to the library (which uses ctypes). But when I try to run the example code provided with the Python interface I get an error...
[ "If you are using the apple system python (on snow leopard) you can execute it with\narch -i386 python\n\neg:\nrobin-mbp:~ $ arch -i386 /usr/bin/python2.6 -c \"import sys; print sys.maxint\"\n2147483647\n\nto start the interpreter in 32 bit mode. There is also an environment variable you can set for the system pyth...
[ 18, 3 ]
[]
[]
[ "macos", "python", "universal_binary" ]
stackoverflow_0001654837_macos_python_universal_binary.txt
Q: main color detection in Python I have about 3000 images and 13 different colors (the background of the majority of these images is white). If the main color of an image is one of those 13 different colors, I'd like them to be associated. I've seen similar questions like Image color detection using python that ask ...
main color detection in Python
I have about 3000 images and 13 different colors (the background of the majority of these images is white). If the main color of an image is one of those 13 different colors, I'd like them to be associated. I've seen similar questions like Image color detection using python that ask for an average color algorithm. I've...
[ "You can use the getcolors function to get a list of all colors in the image. It returns a list of tuples in the form:\n(N, COLOR)\n\nwhere N is the number of times the color COLOR occurs in the image. To get the maximum occurring color, you can pass the list to the max function:\n>>> from PIL import Image\n>>> im ...
[ 10, 2, 1 ]
[]
[]
[ "colors", "detection", "python" ]
stackoverflow_0007772510_colors_detection_python.txt
Q: Caught UnicodeDecodeError while rendering: 'utf8' codec can't decode byte 0xd0 in position 0: unexpected end of data Some day, when i wanted to enter django admin, i couldn't do this, because of this error. I dont remember what i've done, and dont notice, when this error start to appear.. here' full traceback: ht...
Caught UnicodeDecodeError while rendering: 'utf8' codec can't decode byte 0xd0 in position 0: unexpected end of data
Some day, when i wanted to enter django admin, i couldn't do this, because of this error. I dont remember what i've done, and dont notice, when this error start to appear.. here' full traceback: http://dpaste.com/418718/ Sorry for my english
[ "The database field is too small for the data in it, and silently truncated it on insertion. You'll need to repair the data by hand, and make the field larger as well.\n", "I got this error when reading data from a Mysql table. The database had some fields in latin1 format. Converting them to utf8 format helped....
[ 2, 0 ]
[]
[]
[ "django", "django_admin", "python", "syntax_error", "unicode" ]
stackoverflow_0005002807_django_django_admin_python_syntax_error_unicode.txt
Q: How to use Posterous API to 'scrape' my own site for contributor info, date info, and response info As a college teacher in STEM, I like it when I can use technology to enhance the learning experience of my students, and I doubly like it when it allows me to introduce them to cool tech, too. During the last year, ...
How to use Posterous API to 'scrape' my own site for contributor info, date info, and response info
As a college teacher in STEM, I like it when I can use technology to enhance the learning experience of my students, and I doubly like it when it allows me to introduce them to cool tech, too. During the last year, I've had a couple classes make posts to a Posterous site (http://spectrawiki.posterous.com) and post comm...
[ "Follow-up, 5 December 2012: It looks like pyposterous no longer works. My scripts fail and pyposterous fails its own unit tests. Bummer.\n====\nPyposterous did, indeed, give me the tools to answer my question, so I thought I'd share it here for others. Here's the script I wrote:\nimport datetime\nimport pypost...
[ 2 ]
[]
[]
[ "api", "posterous", "python" ]
stackoverflow_0007604569_api_posterous_python.txt
Q: How to ignore the time while converting string to date? I want to convert '2011-10-13' to a date object representing the same. I use strptime but it includes the time, which I dont need. How to best avoid this? d = datetime.datetime.strptime("2011-10-13", "%Y-%m-%d") print d 2011-10-13 00:00:00 A: You can use t...
How to ignore the time while converting string to date?
I want to convert '2011-10-13' to a date object representing the same. I use strptime but it includes the time, which I dont need. How to best avoid this? d = datetime.datetime.strptime("2011-10-13", "%Y-%m-%d") print d 2011-10-13 00:00:00
[ "You can use the .date() method:\nd = datetime.datetime.strptime(\"2011-10-13\", \"%Y-%m-%d\")\nprint d.date()\n>> 2011-10-13\n\n", "If you don't want a time component, use date, not datetime.\n" ]
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007773600_python.txt
Q: Web Scraper: Limit to Requests Per Minute/Hour on Single Domain? I'm working with a librarian to re-structure his organization's digital photography archive. I've built a Python robot with Mechanize and BeautifulSoup to pull about 7000 poorly structured and mildy incorrect/incomplete documents from a collection. ...
Web Scraper: Limit to Requests Per Minute/Hour on Single Domain?
I'm working with a librarian to re-structure his organization's digital photography archive. I've built a Python robot with Mechanize and BeautifulSoup to pull about 7000 poorly structured and mildy incorrect/incomplete documents from a collection. The data will be formatted for a spreadsheet he can use to correct it....
[ "There's no built-in rate limit for HTTP. Most common web servers are not configured out of the box to rate limit. If rate limiting is in place, it will almost certainly have been put there by the administrators of the website and you'd have to ask them what they've configured.\nSome search engines respect a non-...
[ 4 ]
[]
[]
[ "http", "mechanize", "mechanize_python", "python" ]
stackoverflow_0007773567_http_mechanize_mechanize_python_python.txt
Q: Which way to append dict to list is more efficient # Method one array_a = [] a = {} for i in range(5): a = {} a[str(i)] = i array_a.append(a) print(array_a) # [{'0': 0}, {'1': 1}, {'2': 2}, {'3': 3}, {'4': 4}] # Method two from copy import deepcopy array_b = [] b = {} for i in range(5): b.clea...
Which way to append dict to list is more efficient
# Method one array_a = [] a = {} for i in range(5): a = {} a[str(i)] = i array_a.append(a) print(array_a) # [{'0': 0}, {'1': 1}, {'2': 2}, {'3': 3}, {'4': 4}] # Method two from copy import deepcopy array_b = [] b = {} for i in range(5): b.clear() b[str(i)] = i array_b.append(deepcopy(b)) pr...
[ "The difference is not relevant. Both need to create a new dict each time. Since the first is clearer, it is preferable over the second method.\nMy suggestion would be a list comprehension:\narray_c = [{str(i): i} for i in range(5)]\n\n", "Here's a one-liner that should also be more efficient:\narray_a.extend([{s...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007771609_python.txt
Q: Get a list of variables using regexp I have a string expression like param1=123,param2=bbb I would like to get a list of similar {'param1':'123','param2':'bb'} Or at least ['param1=123','param2=bbb'] Unfortunately, the design gives the re.match('^(\w+?=\w+?,?)+$','param1=123,param2=bbb').groups() does not produc...
Get a list of variables using regexp
I have a string expression like param1=123,param2=bbb I would like to get a list of similar {'param1':'123','param2':'bb'} Or at least ['param1=123','param2=bbb'] Unfortunately, the design gives the re.match('^(\w+?=\w+?,?)+$','param1=123,param2=bbb').groups() does not produce the desired result of course - this is p...
[ ">>> dict(re.findall(r'(\\w+)=(\\w+)','param1=123,param2=bbb'))\n{'param2': 'bbb', 'param1': '123'}\n\n", "I'd suggest avoiding regexps and splitting on the delimiters. E.g. :\n>>> sample = 'param1=123,param2=bbb'\n>>> [ x.split('=',1) for x in sample.split(',') ]\n[['param1', '123'], ['param2', 'bbb']]\n>>> dict...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007773067_python_regex.txt
Q: What part of python.socket could conceivably freeze my script for ever even though timeout is set? The oauth library (Linked from the Justin.tv Python library page) locks up my Python processes indefinitely at random times. This happens randomly, but OFTEN on one of my servers. I'm positive this is not due to anyt...
What part of python.socket could conceivably freeze my script for ever even though timeout is set?
The oauth library (Linked from the Justin.tv Python library page) locks up my Python processes indefinitely at random times. This happens randomly, but OFTEN on one of my servers. I'm positive this is not due to anything in my code, so I'm pasting the part of the stack dump related to the Justin.tv python library and o...
[ "These lines from the Justin.tv Python Client Library are relevant:\ndef _send_request(self, request, token=None):\n request.sign_request(OAuthSignatureMethod_HMAC_SHA1(), self.consumer, token)\n conn = self._get_conn() # connection was requested here\n if request.http_method == 'POST':\n conn.reque...
[ 2 ]
[]
[]
[ "python", "python_sockets" ]
stackoverflow_0007773733_python_python_sockets.txt
Q: Optimal (broadcasted) matrix division in numpy. Avoiding temporary arrays or not? Numpy allows matrices of different sizes to be added/multiplied/divided provided certain broadcasting rules are followed. Also, creation of temporary arrays is a major speed impediment to numpy. The following timit results surpris...
Optimal (broadcasted) matrix division in numpy. Avoiding temporary arrays or not?
Numpy allows matrices of different sizes to be added/multiplied/divided provided certain broadcasting rules are followed. Also, creation of temporary arrays is a major speed impediment to numpy. The following timit results surprise me...what is going on? In [41]: def f_no_dot(mat,arr): ....: return mat/arr I...
[ "\nI thought that f_dot would be slower since it had to create the temporary array denominator, and I assumed that this step was skipped by f_no_dot.\n\nFor what it's worth, creating the temporary array is skipped, which is why f_no_dot is slower (but uses less memory).\nElement-wise operations on arrays of the sam...
[ 5, 2 ]
[]
[]
[ "numpy", "performance", "python" ]
stackoverflow_0007769525_numpy_performance_python.txt
Q: Reading raw imagery with PIL and Python I have a 7GB image I got from NASA and I wanted to write a decoder using Python and PIL. The page from where I got the image states the following: The data are formatted as a single-channel 16-bit integer (two byte, long) signed raw binary file, with big-endian byte o...
Reading raw imagery with PIL and Python
I have a 7GB image I got from NASA and I wanted to write a decoder using Python and PIL. The page from where I got the image states the following: The data are formatted as a single-channel 16-bit integer (two byte, long) signed raw binary file, with big-endian byte order and no header. Here's the documentati...
[ "I deal a lot with raw images, some in 16bit and some in 8bit grayscale.\nI have found that loading the raw image into a numpy array, then converting it to an image usually works.\nIf there is a problem with the byte order, then the numpy array.byteswap() command should take care of it before conversion to the PIL ...
[ 2, 0, 0 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0004516365_image_processing_python_python_imaging_library.txt
Q: Normalize numpy arrays from various "image" objects please consider this reproducible example: from PIL import Image import numpy as np import scipy.misc as sm import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.cbook as cbook import urllib datafile = cbook.get_sample_data('lena.jpg...
Normalize numpy arrays from various "image" objects
please consider this reproducible example: from PIL import Image import numpy as np import scipy.misc as sm import matplotlib.pyplot as plt import matplotlib.image as mpimg import matplotlib.cbook as cbook import urllib datafile = cbook.get_sample_data('lena.jpg') lena_pil = Image.open(datafile) lena_pil_np = np.asarr...
[ "def normalize(arr):\n arr=arr.astype('float32')\n if arr.max() > 1.0:\n arr/=255.0\n return arr\n\n" ]
[ 5 ]
[]
[]
[ "matplotlib", "numpy", "python", "python_imaging_library", "scipy" ]
stackoverflow_0007773925_matplotlib_numpy_python_python_imaging_library_scipy.txt
Q: Measuring various aspects of code Is there a tool that is able to measure the frequency of function calls in a project and counts other aspects (for statistics purposes) of Python code? thank you A: The Python profiler should provide you with quite a bit of information: python -m cProfile -o fooprof myscript.py ...
Measuring various aspects of code
Is there a tool that is able to measure the frequency of function calls in a project and counts other aspects (for statistics purposes) of Python code? thank you
[ "The Python profiler should provide you with quite a bit of information:\npython -m cProfile -o fooprof myscript.py\n\nYou load the results using a simple script:\n#!/usr/bin/env python\nimport pstats\np = pstats.Stats('fooprof')\np.strip_dirs().sort_stats(-1).print_stats()\n\nAlternatively, if you do not specify -...
[ 2, 1, 0 ]
[]
[]
[ "code_analysis", "code_metrics", "python" ]
stackoverflow_0007689807_code_analysis_code_metrics_python.txt
Q: How can I track sessions (session duration, where user logs in from, etc) using Google's default authentication on Appengine? I would like to keep track of my users - who logs in, how long they are logged in for, where they log in from, etc. - from my GAE app. I'm wondering what is a good way to do this using the ...
How can I track sessions (session duration, where user logs in from, etc) using Google's default authentication on Appengine?
I would like to keep track of my users - who logs in, how long they are logged in for, where they log in from, etc. - from my GAE app. I'm wondering what is a good way to do this using the authentication mechanisms provided by Google. I can easily add decorators and constraints in app.yaml to ensure that specific endpo...
[ "When a user logs in, flag that user as active within the datastore, use memcache to store whatever session info you want, then run a regular job that checks the active users and saves the data from inactive sessions (ie older than 20 mins or so) to the datastore.\nHere's an example that tracks a user's start and e...
[ 0 ]
[]
[]
[ "authentication", "google_app_engine", "python", "session_management" ]
stackoverflow_0007765235_authentication_google_app_engine_python_session_management.txt
Q: While function python Hello is use eclipse and pydev, I was wondering why my sample code won't work trying to use the while function. print("Welcome to the annoying program") response = "" while response != "Because.": response = input("why\n") print("Oh,ok") the output is the following: Welcome to the annoyi...
While function python
Hello is use eclipse and pydev, I was wondering why my sample code won't work trying to use the while function. print("Welcome to the annoying program") response = "" while response != "Because.": response = input("why\n") print("Oh,ok") the output is the following: Welcome to the annoying program why Because. Tra...
[ "The input function in 2.x evaluates the input as Python code! Use the raw_input function instead.\nWith input, your text \"Because.\" is being evaluated, and it's a syntax error because the dot isn't followed by anything.\n" ]
[ 6 ]
[]
[]
[ "eclipse", "pydev", "python", "while_loop" ]
stackoverflow_0007774183_eclipse_pydev_python_while_loop.txt
Q: Executing a python script line-by-line using the C++ Python API My goal is ultimately to execute a python script that manipulates values in my C++ program, one line at a time, returning execution to my C++ program between statements in the python script. Right now, I'm been attempting to feed the python interprete...
Executing a python script line-by-line using the C++ Python API
My goal is ultimately to execute a python script that manipulates values in my C++ program, one line at a time, returning execution to my C++ program between statements in the python script. Right now, I'm been attempting to feed the python interpreter my script one line at a time. But it wants a context, and I have no...
[ "I think it will be difficult to feed a script one line at a time. Look into sys.settrace() to set a function that is invoked at each line of execution. You can also set it in the C API using PyEval_SetTrace, in a slightly different form.\n", "I am not 100% sure that I fully understand your goal, but some 8 mon...
[ 4, 1, 0 ]
[]
[]
[ "api", "c++", "interpreter", "python" ]
stackoverflow_0007773301_api_c++_interpreter_python.txt
Q: Python - Identify Common Values I am currently using Python 2.7. I currently have three columns in an Excel document all with different integer values in. The amount of values can vary ranging from 10 through to thousands. Basically, what I am looking to do is scan through the column one and compare each value to ...
Python - Identify Common Values
I am currently using Python 2.7. I currently have three columns in an Excel document all with different integer values in. The amount of values can vary ranging from 10 through to thousands. Basically, what I am looking to do is scan through the column one and compare each value to see if any appear in column two and t...
[ "What about using set intersection?\nset(column_1_vals) & set(column_2_vals) & set(column_3_vals)\n\nThat will give you those values which appear in all three columns.\n" ]
[ 2 ]
[]
[]
[ "comparison", "list", "loops", "performance", "python" ]
stackoverflow_0007774216_comparison_list_loops_performance_python.txt
Q: Updating CSV files automatically I started learning Python recently (5 hrs ago). Here's my scenario. I get mails every 4 hours from a remote measurement site with measurement values. The files are in *.csv format and the filenames are XX-2011-00001.csv and YY-2011-00001.csv. These are data of two instruments conti...
Updating CSV files automatically
I started learning Python recently (5 hrs ago). Here's my scenario. I get mails every 4 hours from a remote measurement site with measurement values. The files are in *.csv format and the filenames are XX-2011-00001.csv and YY-2011-00001.csv. These are data of two instruments continuously running with different samplin...
[ "As others have said, the csv package contains great objects to handle the file I/O without writing a lot of low-level code. \nHowever, I would implement the time requirement using a cron job rather than sleeping your application, if it's available. It'll be more flexible, and it won't be susceptible to to a single...
[ 1, 1, 0, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007772966_csv_python.txt
Q: Python Telnet Port 23 vs 223 with Different Results When I run this Python 3.1 code to access a device using telnetlib, it works as expected: import telnetlib tn = telnetlib.Telnet("15.39.100.126", "23") tn.write(b"menu\n") tn.write(b"0\n") print(tn.read_all().decode('ascii')) Then, I run this code (very similar...
Python Telnet Port 23 vs 223 with Different Results
When I run this Python 3.1 code to access a device using telnetlib, it works as expected: import telnetlib tn = telnetlib.Telnet("15.39.100.126", "23") tn.write(b"menu\n") tn.write(b"0\n") print(tn.read_all().decode('ascii')) Then, I run this code (very similar to above, but this port presents different menus) to por...
[ "The telnet command itself does different things for port 23 vs other ports: Primarily it implements telnet option negotiation. The purpose of telnetlib is to implement the Telnet protocol (option negotiation etc) for you so that you can interact with a service on port 23 that expects telnet on the other end. Si...
[ 3 ]
[]
[]
[ "python", "python_3.x", "telnetlib", "windows_ce" ]
stackoverflow_0007774139_python_python_3.x_telnetlib_windows_ce.txt
Q: Editing the URL with user data Python Mechanize I have an URL in Mechanize in Python that reads: members_booking.php?operation=member_day&amp;course_id=1&amp;d_date=2011-10-5&amp;comp=1 But I want to change that url depending on the data that the user inputs to the console, eg: year = raw_input("Enter the YEAR") ...
Editing the URL with user data Python Mechanize
I have an URL in Mechanize in Python that reads: members_booking.php?operation=member_day&amp;course_id=1&amp;d_date=2011-10-5&amp;comp=1 But I want to change that url depending on the data that the user inputs to the console, eg: year = raw_input("Enter the YEAR") month = raw_input("Enter the MONTH") day = raw_input(...
[ "urlstring = \"members_booking.php?operation=member_day&course_id=1&d_date=%s-%s-%s&comp=1\"\n\nyear = raw_input(\"Enter the YEAR: \")\nmonth = raw_input(\"Enter the MONTH: \")\nday = raw_input(\"Enter the DAY: \")\n\nprint urlstring % (year, month, day)\n\n" ]
[ 1 ]
[]
[]
[ "mechanize", "parsing", "printing", "python", "string" ]
stackoverflow_0007774388_mechanize_parsing_printing_python_string.txt
Q: how to find a string in a text file and print the lines right before and after I am trying to convert my shell scripts into python code, but I am stuck while trying this operation. I have a process that outputs a text file, the file has sections like this: Running Operation kdasdakdnaskdaksdma (error if present)...
how to find a string in a text file and print the lines right before and after
I am trying to convert my shell scripts into python code, but I am stuck while trying this operation. I have a process that outputs a text file, the file has sections like this: Running Operation kdasdakdnaskdaksdma (error if present) error: kdmakmdasmdaksom This file could have multiple lines for the operation and ...
[ "import re\n\n\nss = '''qhvfgbhgozr\nyytuuuyuyuuuyuyuuyy\njhfg tryy error jjfkhdjhfjh ttrtr\naaaeeedddeedaeaeeaeeea\njhzdgcoiua zfaozifh cohfgdyg fuo'''\n\nregx = re.compile('^(.*)\\r?\\n(.*?error.*)\\r?\\n(.*)', re.MULTILINE)\n\nprint regx.search(ss).groups()\n\nresult\n('yytuuuyuyuuuyuyuuyy', 'jhfg tryy error j...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007774626_python.txt
Q: package for statistics in Python i am writing a program in Python 3, and at this point i am looking for a package that handles statistics. Is there anything available? Thanks in advance. A: It's a pretty open-ended question, but Numpy and SciPy are the gold standard for numerical computation in Python.
package for statistics in Python
i am writing a program in Python 3, and at this point i am looking for a package that handles statistics. Is there anything available? Thanks in advance.
[ "It's a pretty open-ended question, but Numpy and SciPy are the gold standard for numerical computation in Python.\n" ]
[ 5 ]
[]
[]
[ "python", "statistics" ]
stackoverflow_0007774651_python_statistics.txt
Q: Using Django/Python to CONSUME existing web services I have an existing REST application serving either JSON or XML. I can use the framework (Play) to render templates directly, but I'm not allowed to (arbitrary homework requirement they just invented), and forced to use a second layer to consume, process and rend...
Using Django/Python to CONSUME existing web services
I have an existing REST application serving either JSON or XML. I can use the framework (Play) to render templates directly, but I'm not allowed to (arbitrary homework requirement they just invented), and forced to use a second layer to consume, process and render the REST objects. I want to use Django/Python if possib...
[ "Inside your Django app, you can easily use the urllib and json modules in the Python standard library to pull data from URLs, and then parse them as JSON. \n" ]
[ 2 ]
[]
[]
[ "django", "python", "rest", "web_services" ]
stackoverflow_0007774930_django_python_rest_web_services.txt
Q: Python create list from smallest number of repeating values in a nested list I have a Dict whs = { 'ID1' : ['code1', 'code2', 'code3'], 'ID2' : ['code2', 'code5', 'code3'], 'ID3' : ['code6', 'code7', 'code8'], 'ID4' : ['code3', 'code5', 'code6'], } What I need to do is build a new list that will l...
Python create list from smallest number of repeating values in a nested list
I have a Dict whs = { 'ID1' : ['code1', 'code2', 'code3'], 'ID2' : ['code2', 'code5', 'code3'], 'ID3' : ['code6', 'code7', 'code8'], 'ID4' : ['code3', 'code5', 'code6'], } What I need to do is build a new list that will look like submit = [ { 'codes' : ['code3', ], 'ids' : ['ID1', '...
[ "I attacked it by building a tree of all the potential additions, and then finding the cheapest option among those. Here is a working (albeit ugly and unoptimized) example:\nhttps://gist.github.com/1288835\nThe tree will end up with p*w nodes, where p is the number of products and w(p) is the average number of war...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007774719_python.txt
Q: How to Create a Mutex for a Single Instance Python Application I have been using the following recipe to only allow a single instance of my application: http://code.activestate.com/recipes/474070-creating-a-single-instance-application/ The recipe uses a "mutexname" variable which is filled with some mutex value. I...
How to Create a Mutex for a Single Instance Python Application
I have been using the following recipe to only allow a single instance of my application: http://code.activestate.com/recipes/474070-creating-a-single-instance-application/ The recipe uses a "mutexname" variable which is filled with some mutex value. If I want to create my own unique "mutex", how do I do it? Also, how ...
[ "The recipe uses the win32 api function CreateMutex to create a named mutex. A mutex is a system object and exists outside your app's process. GetLastError returns ERROR_ALREADY_EXISTS when CreateMutex is called with a name that already exists. The recipe checks for this return value and exits if so. You should cha...
[ 2 ]
[]
[]
[ "instance", "mutex", "python" ]
stackoverflow_0007775163_instance_mutex_python.txt
Q: parse HTML in python wxWidgets TextCtrl Is it possible, or is there a library that will allow me to parse HTML code inside the wx.TextCtrl widget? A: Sure, just use myTextCtrl.GetValue(), then parse the string with something like BeautifulSoup, xml.dom.minidom, HTMLParser, etc: from BeautifulSoup import Beautifu...
parse HTML in python wxWidgets TextCtrl
Is it possible, or is there a library that will allow me to parse HTML code inside the wx.TextCtrl widget?
[ "Sure, just use myTextCtrl.GetValue(), then parse the string with something like BeautifulSoup, xml.dom.minidom, HTMLParser, etc:\nfrom BeautifulSoup import BeautifulSoup\n\n# lets say this is the text inside the TextCtrl:\n# '<html><head><title>Page title</title></head><body><p id=\"firstpara\" align=\"center\">Th...
[ 1, 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0007761089_python_wxpython_wxwidgets.txt
Q: porting Python 2 program to Python 3, random line generator I have a random line generator program written in Python2, but I need to port it to Python3. You give the program the option -n [number] and a file argument to tell it to randomly output [number] number of lines from the file. Here is the source for the p...
porting Python 2 program to Python 3, random line generator
I have a random line generator program written in Python2, but I need to port it to Python3. You give the program the option -n [number] and a file argument to tell it to randomly output [number] number of lines from the file. Here is the source for the program: #!/usr/bin/python import random, sys from optparse impor...
[ "The line \"except IOError as (errno, strerror)\" relies on a the little used obscure fact that exceptions in Python 2 are iterable, and that you can iterate over the parameters given to the exception by iterating over the exception itself.\nThis of course breaks the \"Explicit is better than implicit\" rule of Pyt...
[ 14, 8 ]
[ "In order to convert your program from python 2 to python 3, use the 2to3 tool. \nhttp://docs.python.org/library/2to3.html\n" ]
[ -1 ]
[ "python", "python_2.x", "python_3.x" ]
stackoverflow_0007775062_python_python_2.x_python_3.x.txt