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: Creating & Updating UserProfiles in Django Django newbie here stumbling my way around the docs. I'm trying to create a user profile using Django's "UserProfiles", but I'm having a little trouble with figuring out the proper way to set the code based on Django docs. Here's my code, based on the docs. (The create_us...
Creating & Updating UserProfiles in Django
Django newbie here stumbling my way around the docs. I'm trying to create a user profile using Django's "UserProfiles", but I'm having a little trouble with figuring out the proper way to set the code based on Django docs. Here's my code, based on the docs. (The create_user_profile is 100% from the docs). from django.d...
[ "\nhow would I first create, then update all of this, before finally saving\n\nThese aren't separate steps. When you create or update a record in Django, you are saving it to the database.\nFor the registration form, I'd recommend you set it up as a ModelForm on User records, then specify the additional fields you ...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008120678_django_python.txt
Q: Recursion - how do you extract from specific traversals Lets say you have a string: abcde And a set of strings: ab, cde, abcd, a, bcd, cd You want to find all possible concatenations from the set that form the string. You can use recursion to traverse through all possible concatenations from the set, but how woul...
Recursion - how do you extract from specific traversals
Lets say you have a string: abcde And a set of strings: ab, cde, abcd, a, bcd, cd You want to find all possible concatenations from the set that form the string. You can use recursion to traverse through all possible concatenations from the set, but how would you return only those that satisfy the solution? The possi...
[ "Make the recursive function return a list of all concatenations.\nI.e., you make a function concatenations, with a string and a set as input. This function returns a list of all concatenations of items from the set that fit the string.\nThen you can define concatenations recursively in terms of itself:\n\n(end con...
[ 3, 3, 0 ]
[]
[]
[ "algorithm", "python", "recursion" ]
stackoverflow_0008122549_algorithm_python_recursion.txt
Q: SQLAlchemy and Ambiguous Column name Ive had a good search on google but I cant seem to find an answer to this error in my case. Im not making any joins, Im literally just trying to get all from this table. All of the other queries work fine, but this seems to be messing up with this error: InvalidRequestError: Am...
SQLAlchemy and Ambiguous Column name
Ive had a good search on google but I cant seem to find an answer to this error in my case. Im not making any joins, Im literally just trying to get all from this table. All of the other queries work fine, but this seems to be messing up with this error: InvalidRequestError: Ambiguous column name 'INMPTL_WIW_BATAM_STG....
[ "My conjecture would be the case-sensitivity of column names when overriding columns which are reflected by using autoload=True. To verify, comment out all column definition and leave autoload=True. Then do the opposite.\nSee Reflecting Database Objects - Overriding Reflected Columns of SA documentation for more in...
[ 4 ]
[]
[]
[ "ambiguous", "python", "sqlalchemy" ]
stackoverflow_0008120837_ambiguous_python_sqlalchemy.txt
Q: Web helpers in Python I am starting a web project in Python, most likely using Django or Pyramid. I have done some work in ASP.NET MVC and I was wondering if Python (or any of the templating engines) have a concept like 'web helpers'? For those that don't know what that is, it's a callable piece of server-side c...
Web helpers in Python
I am starting a web project in Python, most likely using Django or Pyramid. I have done some work in ASP.NET MVC and I was wondering if Python (or any of the templating engines) have a concept like 'web helpers'? For those that don't know what that is, it's a callable piece of server-side code that will generate a bi...
[ "This is hardly a useful question but here you go: Yes, there is a webhelpers module and the frameworks make your life much easier.\n", "In Django you have template tags and template filter. You include them in your templates and they return some string or unicode value that would be included in the final documen...
[ 1, 0, 0 ]
[]
[]
[ "python", "template_engine" ]
stackoverflow_0008105120_python_template_engine.txt
Q: Django QuerySet with exclude & annotate not returning any results Based off this SO question about counting forgein keys, I have a problem. This is my models: class Type(models.Model): is_bulk = models.BooleanField() class Component(models.Model): parent = models.ForgeinKey(Type, related_name="components") I...
Django QuerySet with exclude & annotate not returning any results
Based off this SO question about counting forgein keys, I have a problem. This is my models: class Type(models.Model): is_bulk = models.BooleanField() class Component(models.Model): parent = models.ForgeinKey(Type, related_name="components") I want to write a queryset that has all types, except those that have is...
[ "I have fixed this by changing the queryset to:\ntypes_qs.annotate(num_components=Count('components')).filter(Q(is_bulk=False) | (Q(is_bulk=True) & Q(num_components__gt=0)))\n\nThat works, but I can't see why my original one didn't. Ah well.\n", "I tried this example and what you need I think is declaring a relat...
[ 1, 0 ]
[]
[]
[ "django", "django_orm", "django_queryset", "python" ]
stackoverflow_0008081106_django_django_orm_django_queryset_python.txt
Q: Web Frameworks with site style inbuilt I hope this isn't knocked for being too general, but... I recently had occasion to learn web2py for a final year university project. In this subject teams of four had 8 weeks to design a web app. Ultimately i found that web2py was quite versatile, with it being very easy to g...
Web Frameworks with site style inbuilt
I hope this isn't knocked for being too general, but... I recently had occasion to learn web2py for a final year university project. In this subject teams of four had 8 weeks to design a web app. Ultimately i found that web2py was quite versatile, with it being very easy to get a site up and running fast, a lot of opti...
[ "I feel your pain. As a developer coming from the desktop world and doing some web development, I'm used to setting up the appearance of my application at the same time I select and arrange my user interface widgets.\nYou will just have to accept that browser based software does not work that way. You must separa...
[ 1, 1, 1, 0 ]
[]
[]
[ "css", "frameworks", "python" ]
stackoverflow_0008077886_css_frameworks_python.txt
Q: matching all characters in any order in regex I'm a regex newbie, but I understand how to match any characters in a regex query in order (ex. [abc] will match any of a, b or c. Also, I believe "abc" will match abc exactly). However, how do I construct a regex query that will match all the characters abc in any or...
matching all characters in any order in regex
I'm a regex newbie, but I understand how to match any characters in a regex query in order (ex. [abc] will match any of a, b or c. Also, I believe "abc" will match abc exactly). However, how do I construct a regex query that will match all the characters abc in any order? So for example, I want it to match "cab" or "...
[ "In Python, I wouldn't use a regualar expression for this purpose, but rather a set:\n>>> chars = set(\"abc\")\n>>> chars.issubset(\"bracket\")\nTrue\n>>> chars.issubset(\"fish\")\nFalse\n>>> chars.issubset(\"bad\")\nFalse\n\nRegular expressions are useful, but there are situations where different tools are more ap...
[ 14, 11, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008123131_python_regex.txt
Q: Execute /bin script from other python script I have a script in my project's bin directory, and I want to execute it from a cron. Both scripts are written in python. Target file : App_directory/bin/script_name Want to execute script_name script with some parameters from App_directory/cron/script_name1.py How do ...
Execute /bin script from other python script
I have a script in my project's bin directory, and I want to execute it from a cron. Both scripts are written in python. Target file : App_directory/bin/script_name Want to execute script_name script with some parameters from App_directory/cron/script_name1.py How do I achieve that ?
[ "Try:\nimport os\nos.system('/path/to/App_directory/bin/script_name')\n\nOr if script_name is not executable and/or doesn't have the shabang (#!/usr/bin/env python):\nimport os\nos.system('python /path/to/App_directory/bin/script_name')\n\n", "The subprocess module is much better than using os.system. Just do:\ni...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008095406_python.txt
Q: I am having trouble with the Hangman program I made I'm having trouble getting the correct output out of my code. I need it to provide the head, body, arms, legs one by one, but it won't. Please check my code. import random max_wrong = len(HANGMAN) -1 WORDS = ("Caleb","Owen","Ben","Adriane","Marley") word = random...
I am having trouble with the Hangman program I made
I'm having trouble getting the correct output out of my code. I need it to provide the head, body, arms, legs one by one, but it won't. Please check my code. import random max_wrong = len(HANGMAN) -1 WORDS = ("Caleb","Owen","Ben","Adriane","Marley") word = random.choice(WORDS) so_far = "-" * len(word) wrong = 0 used = ...
[ "Well, for starters, it looks like you have an undefined variable:\nmax_wrong = len(HANGMAN) -1\n\nDo you mean that to be \nmax_wrong = len(word) -1\n\n?? In that case you'd have to define it after you defined word.\nYou've also got to look at how you're setting up your loops... for example you've got an indented ...
[ 1, 0 ]
[]
[]
[ "pydev", "python" ]
stackoverflow_0008123261_pydev_python.txt
Q: "is" not working in python IDE but working in command line I couldn't understand why this is happening actually.. Take a look at this python code : word = raw_input("Enter Word") length = len(word) if word[length-1:] is "e" : print word + "d" If I give input "love", its output must be "loved...
"is" not working in python IDE but working in command line
I couldn't understand why this is happening actually.. Take a look at this python code : word = raw_input("Enter Word") length = len(word) if word[length-1:] is "e" : print word + "d" If I give input "love", its output must be "loved". So, when I wrote this in PyScripter IDE, its neither showing ...
[ "The is keyword will only work if the strings have exactly the same identity, which is not guaranteed even if the strings have the same value. You should use == instead of is here to compare the values of the strings.\nOr better still, use endswith:\nif word.endswith(\"e\"):\n print word + \"d\"\n\n", "You sh...
[ 9, 6 ]
[]
[]
[ "python" ]
stackoverflow_0008123872_python.txt
Q: Python scikits - Buffer has wrong number of dimensions (expected 1, got 2) I am trying this code snippet. I am using scikits.learn 0.8.1 from scikits.learn import linear_model import numpy as np num_rows = 10000 X = np.zeros([num_rows,2]) y = np.zeros([num_rows,1]) # assume here I have filled in X and y appropriat...
Python scikits - Buffer has wrong number of dimensions (expected 1, got 2)
I am trying this code snippet. I am using scikits.learn 0.8.1 from scikits.learn import linear_model import numpy as np num_rows = 10000 X = np.zeros([num_rows,2]) y = np.zeros([num_rows,1]) # assume here I have filled in X and y appropriately with 0s and 1s from the dataset clf = linear_model.LogisticRegression() clf....
[ "Solved. The error was due to:\ny = np.zeros([num_rows,1])\n\nIt should have been: \ny = np.zeros([num_rows])\n\n" ]
[ 5 ]
[]
[]
[ "numpy", "python", "regression", "scikit_learn", "scikits" ]
stackoverflow_0008123524_numpy_python_regression_scikit_learn_scikits.txt
Q: Could you please explain this code fragment in python I'm brand new to python, and need some help understanding this code fragment: for c in [B, C, D]: try: raise c() except D: print "D" except C: print "C" except B: print "B" Reading python docs, it seems raise() throws an e...
Could you please explain this code fragment in python
I'm brand new to python, and need some help understanding this code fragment: for c in [B, C, D]: try: raise c() except D: print "D" except C: print "C" except B: print "B" Reading python docs, it seems raise() throws an exception, but I can't figure out why raise() is within the ...
[ "raise is how you raise exceptions in the first place. A lone raise in an exception handler only propagates the exception to external handlers.\n", "I presume the raise() was placed directly inside try: just for the purpose of illustration. \nAnd even normally you would put the code causing an exception (i.e one ...
[ 2, 2, 1 ]
[]
[]
[ "exception", "exception_handling", "python" ]
stackoverflow_0008116969_exception_exception_handling_python.txt
Q: Dynamically expanding a scipy array Is there a way to dynamically expand an scipy array from scipy import sci time = sci.zeros((n,1), 'double') Can we increase the size of time array after this? A: It's possible to expand arrays using the resize method, but it can be a slow operation for large arrays, so avoid i...
Dynamically expanding a scipy array
Is there a way to dynamically expand an scipy array from scipy import sci time = sci.zeros((n,1), 'double') Can we increase the size of time array after this?
[ "It's possible to expand arrays using the resize method, but it can be a slow operation for large arrays, so avoid it if possible*.\nFor example:\nimport scipy as sci\nn=3\ntime = sci.zeros((n,1), 'double')\nprint(time)\n# [[ 0.]\n# [ 0.]\n# [ 0.]]\n\ntime.resize((n+1,2))\nprint(time)\n# [[ 0. 0.]\n# [ 0. 0.]\...
[ 5, 4 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0007546080_python_scipy.txt
Q: Filling Livecycle form with Django I am trying to fill a livecycle created form with form data from django. Now I think I have the code done correctly but I am having a hard time with the structure of the livecycle form. Currently I have the ability to populate pdf's created with adobe acrobat but not livecycle....
Filling Livecycle form with Django
I am trying to fill a livecycle created form with form data from django. Now I think I have the code done correctly but I am having a hard time with the structure of the livecycle form. Currently I have the ability to populate pdf's created with adobe acrobat but not livecycle. Is there a certain file structure for ...
[ "Do you have LiveCycle Forms installed? You could then generate the XML data with DJango and sending it to LiveCycle to render the PDF Form\nedit:\nAnd you should notice LiveCycle Designer generates XFA-based forms, which differ from XFDF\n" ]
[ -1 ]
[]
[]
[ "django", "livecycle", "pdf", "pisa", "python" ]
stackoverflow_0008123256_django_livecycle_pdf_pisa_python.txt
Q: String operations on xml nodes in Python I am reading an xml file and want to perform string operations on the node's content. import os import elementtree.ElementTree as ET from xml.etree.ElementTree import ElementTree from xml.etree.ElementTree import tostring xml_file = os.path.abspath(__file__) xml_file = os....
String operations on xml nodes in Python
I am reading an xml file and want to perform string operations on the node's content. import os import elementtree.ElementTree as ET from xml.etree.ElementTree import ElementTree from xml.etree.ElementTree import tostring xml_file = os.path.abspath(__file__) xml_file = os.path.dirname(xml_file) xml_file = os.path.join...
[ "You've written for a in text, but text is a string and you're treating it like an XML node.\nThe tostring method takes an etree.Element, but in this case a is a character of your string text.\nIf you want to iterate over the tree, just treat it as a list\nroot = ET.parse(xml_file).getroot()\nfor child in root:\n ...
[ 2 ]
[]
[]
[ "python", "string", "xml_parsing" ]
stackoverflow_0008124780_python_string_xml_parsing.txt
Q: Download subset of objects in Django I have a site with a search page with a number of forms, and a page to display the results of the search. I want the users to be able to download the results of the search (as a text file or whatever). This is basically what my view looks like: def search_page(request): for...
Download subset of objects in Django
I have a site with a search page with a number of forms, and a page to display the results of the search. I want the users to be able to download the results of the search (as a text file or whatever). This is basically what my view looks like: def search_page(request): form = SearchOptions() if request.method ...
[ "You could define an utility search function that returns the search results based on the search parameters ; and leave it up to the views to call this function and handle how the result should be presented (html or csv download or json or whatever).\nAlternatively, you could add a parameter (in the url or as a get...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008124243_django_python.txt
Q: Python Twisted -- how to control buffered/unbuffered input in Telnet or SSH? I want to write a Python Twisted server that serves text to its clients, and I want the clients to be able to write text back to manipulate the server. I will use Telnet, and the clients will use Putty or some similar terminal...I would a...
Python Twisted -- how to control buffered/unbuffered input in Telnet or SSH?
I want to write a Python Twisted server that serves text to its clients, and I want the clients to be able to write text back to manipulate the server. I will use Telnet, and the clients will use Putty or some similar terminal...I would also be open to using SSH if it is easier to do this. My question is, how do I conf...
[ "twisted.conch.telnet.TelnetBootstrapProtocol is a good example of how to do some option negotiation. It also happens to perform some LINEMODE negotiation. Take a look at the implementation for details, but here's a snippet that shows the server asking the client to enable linemode, naws, and sga:\nfor opt in (LI...
[ 1 ]
[]
[]
[ "python", "ssh", "telnet", "twisted" ]
stackoverflow_0008118397_python_ssh_telnet_twisted.txt
Q: I need to send multiple clients a python file and have them all execute it, then download the result So here's the deal. I have a server that has a ton of clients. I need a way to send them all a python script, and once they receive it they must immediately execute the script. Said script will create a file which...
I need to send multiple clients a python file and have them all execute it, then download the result
So here's the deal. I have a server that has a ton of clients. I need a way to send them all a python script, and once they receive it they must immediately execute the script. Said script will create a file which I then need to download back to the server. The only thing I have to start with is a file with a list of ...
[ "Have a look at Fabric. It is a tool that exactly fits what you need, though I don't know how fast it is.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008086677_python.txt
Q: Parsing .rst files with Sphinx-specific directives programmatically I would like to be able to parse sphinx based rst in Python for further processing and checking. Something like: import sphinx p = sphinx.parse("/path/to/file.rst") do_something_with(p) It seems that something is possible in docutils using the do...
Parsing .rst files with Sphinx-specific directives programmatically
I would like to be able to parse sphinx based rst in Python for further processing and checking. Something like: import sphinx p = sphinx.parse("/path/to/file.rst") do_something_with(p) It seems that something is possible in docutils using the docutils.core.publish_file: publish_file(open("/path/to/file.rst") But tha...
[ "You can use Sphinx Extensions to do custom processing before the final write. There is a very good getting started example project in the documentation that discusses various hooks that allow you to customize Sphinx.\nDepending on what you're trying to do, you may need to supply your do_something function as a cal...
[ 9 ]
[]
[]
[ "docutils", "python", "python_sphinx" ]
stackoverflow_0008125238_docutils_python_python_sphinx.txt
Q: Is it the best way to handle several ComboBoxes in Python GTK+? I am trying to write some configuration GUI, which as many GUIs got two or more ComboBoxes, and other stuff. I don't like copying stuff and making it everywhere the same, long, and hardly readable. I wanna ask you about your own word in that question,...
Is it the best way to handle several ComboBoxes in Python GTK+?
I am trying to write some configuration GUI, which as many GUIs got two or more ComboBoxes, and other stuff. I don't like copying stuff and making it everywhere the same, long, and hardly readable. I wanna ask you about your own word in that question, is it good to create sotcha classes, and if not, how to handle it be...
[ "You're not the only one with this idea; gtk.ComboBoxText was created to solve this problem. It is available from PyGTK 2.24 onwards. If you can't use PyGTK 2.24, then your solution seems quite reasonable.\n" ]
[ 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0008123292_pygtk_python.txt
Q: Hi, I've been trying to do a retrieval in python I've been trying to do a retrieval in python A: the second argument to urlretrieve() is a filename not a directory. you're ignoring docid argument you probably don't want to call download_file() recursively `folder_size` (with backtick) is a syntax error Here's a...
Hi, I've been trying to do a retrieval in python
I've been trying to do a retrieval in python
[ "\nthe second argument to urlretrieve() is a filename not a directory.\nyou're ignoring docid argument\nyou probably don't want to call download_file() recursively\n`folder_size` (with backtick) is a syntax error\n\nHere's a script that downloads documents specified in /tmp/docids to /tmp/Footemp directory (it must...
[ 2, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0008124976_python_python_3.x.txt
Q: Linux more: remove nonprintable characters I am using Python to capture the output of Linux more. However, the file contains the characters: <--- More --->^M ^M How do I use Python to clean the lines? Or use more once more time to cleanit up? A: This isn't guaranteed to work, but you should try ...
Linux more: remove nonprintable characters
I am using Python to capture the output of Linux more. However, the file contains the characters: <--- More --->^M ^M How do I use Python to clean the lines? Or use more once more time to cleanit up?
[ "This isn't guaranteed to work, but you should try setting PAGER to cat in the environment of the child process. You can't do that with subprocess.call but you can do it with subprocess.Popen:\nchildenv = os.environ.copy()\nchildenv['PAGER'] = 'cat'\n\nproc = subprocess.Popen(executable=\"yourprogram\",\n ...
[ 2 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0008125265_linux_python.txt
Q: Calling a python program from an external link and communicating with it I have no idea if this has an official name, nor do I know a better way to really describe what I'm going for here so I'll list the two things I'd like to accomplish. In a nutshell I have a task management program that emails people when they...
Calling a python program from an external link and communicating with it
I have no idea if this has an official name, nor do I know a better way to really describe what I'm going for here so I'll list the two things I'd like to accomplish. In a nutshell I have a task management program that emails people when they've been assigned a task. What I'd like is some way to generate a link (html o...
[ "I use tools like itty and flask to implement this kind of functionality.\nFor example, using itty here's how you could launch a program with some command-line arguments:\nfrom itty import *\n\n@post('/someprogram/(?P<args>\\w+)')\ndef launcher(request, args):\n 'Launch a program with some command-line arguments...
[ 0 ]
[]
[]
[ "external", "python" ]
stackoverflow_0008124424_external_python.txt
Q: Does Coldfusion support dynamic arguments? In python there is the *args convention I am wondering if CF9 supports something similar. Here is the python example >>> def func(*args): for a in args: print a, "is a quality argument" >>> func(1, 2, 3) 1 is a quality argument 2 is a quality argum...
Does Coldfusion support dynamic arguments?
In python there is the *args convention I am wondering if CF9 supports something similar. Here is the python example >>> def func(*args): for a in args: print a, "is a quality argument" >>> func(1, 2, 3) 1 is a quality argument 2 is a quality argument 3 is a quality argument >>>
[ "Yes, CFML has supported dynamic arguments for as long as it has supported user-defined functions.\nAll arguments, whether explicitly defined, or whether passed in without being defined, exist in the Arguments scope.\nThe Arguments scope can be treated as both an array and a structure (key/value).\n\nHere is the cl...
[ 10, 3, 0 ]
[]
[]
[ "coldfusion", "coldfusion_9", "python" ]
stackoverflow_0008124249_coldfusion_coldfusion_9_python.txt
Q: django form submissionr return non "post" page I have a select box and an input box that submits to a view in django. When I submit it adds the value in django then the page reloads and the select box values are updated. However if I press 'refresh' on that page, it tries to resubmit values again. How can I preven...
django form submissionr return non "post" page
I have a select box and an input box that submits to a view in django. When I submit it adds the value in django then the page reloads and the select box values are updated. However if I press 'refresh' on that page, it tries to resubmit values again. How can I prevent this behavior, I would like the refresh after the ...
[ "HttpResponseRedirect only takes one parameter. You need to pass the id parameters to reverse:\nreturn HttpResponseRedirect(reverse(\"myview\", kwargs={\"firstid\": 3, \n \"secondid\": 3}))\n\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008125841_django_python.txt
Q: PostgreSQL COPY command issues In my Postgresql database I have created a table called NAV_DATA with five columns: id (PKEY) ,name (VARCHAR) ,call_type (VARCHAR) ,date_created (date) For these columns I have the csv file which the delimiter TAB \t and Quotechar ". It also has some empty fields in middle column. ...
PostgreSQL COPY command issues
In my Postgresql database I have created a table called NAV_DATA with five columns: id (PKEY) ,name (VARCHAR) ,call_type (VARCHAR) ,date_created (date) For these columns I have the csv file which the delimiter TAB \t and Quotechar ". It also has some empty fields in middle column. How to allow to accept null values i...
[ "copy \"NAV_DATA\" (name,call_type,date_created) from 'c:/test.txt' with delimiter '\\t' csv\n\n", "If you wonder about how NULL values are represented in the CSV file have a look at the manual page @Milen is linking to in his comment. Or write some test data (including NULL values) into your table and export it ...
[ 2, 1 ]
[]
[]
[ "csv", "postgresql", "postgresql_copy", "python" ]
stackoverflow_0008123792_csv_postgresql_postgresql_copy_python.txt
Q: How to read the displayed value of a spreadsheet cell, not the formula? I have a program that reads the value of a cell in a spreadsheet (via COM) by accessing its 'Text' member. When I was using Excel 2003, my program correctly returned the displayed value of the cell. Now I am using OpenOffice Calc, and instead ...
How to read the displayed value of a spreadsheet cell, not the formula?
I have a program that reads the value of a cell in a spreadsheet (via COM) by accessing its 'Text' member. When I was using Excel 2003, my program correctly returned the displayed value of the cell. Now I am using OpenOffice Calc, and instead I am getting back the formula in the cell ('=SUM(F8:F10)'). To complicate mat...
[ "Why not just have the file saved as a CVS in Excel and then use the csv module to pull the data from the file? That will give you the data of the cell rather than the formula.\n" ]
[ 0 ]
[]
[]
[ "excel", "openoffice_calc", "python", "win32com" ]
stackoverflow_0008125553_excel_openoffice_calc_python_win32com.txt
Q: Python Numpy 2-dimensional array iteration Would like to build a list of indices into a 2 dimensional bool_ array, where True. import numpy arr = numpy.zeros((6,6), numpy.bool_) arr[2,3] = True arr[5,1] = True results1 = [[(x,y) for (y,cell) in enumerate(arr[x].flat) if cell] for x in xrange(6)] results2 = [(x,y) ...
Python Numpy 2-dimensional array iteration
Would like to build a list of indices into a 2 dimensional bool_ array, where True. import numpy arr = numpy.zeros((6,6), numpy.bool_) arr[2,3] = True arr[5,1] = True results1 = [[(x,y) for (y,cell) in enumerate(arr[x].flat) if cell] for x in xrange(6)] results2 = [(x,y) for (y,cell) in enumerate(arr[x].flat) if cell f...
[ "I think the function you're looking for is numpy.where. Here's an example:\n>>> import numpy\n>>> arr = numpy.zeros((6,6), numpy.bool_)\n>>> arr[2,3] = True\n>>> arr[5,1] = True\n>>> numpy.where(arr)\n(array([2, 5]), array([3, 1]))\n\nYou can turn this back into an index like this:\n>>> numpy.array(numpy.where(arr...
[ 1, 0 ]
[]
[]
[ "arrays", "iterator", "numpy", "python" ]
stackoverflow_0008125593_arrays_iterator_numpy_python.txt
Q: decreasing time for search from big database in python I have a big database with 10000 id When I search for a name from my database, it takes a long time, and I need a way to decreasing the time for shortest time ?? I am using this way : while (query.next()): line3 = self.lineEdit_4.text() ...
decreasing time for search from big database in python
I have a big database with 10000 id When I search for a name from my database, it takes a long time, and I need a way to decreasing the time for shortest time ?? I am using this way : while (query.next()): line3 = self.lineEdit_4.text() query.exec_("SELECT * FROM test WHERE name LIKE '%s';"...
[ "Oh, wait. Original answer is below, but from looking at your code, it appears you may be re-executing your query for every row in the result.\nYou need to show us the code above your while statement that originally creates and populates query.\nOriginal answer:\nYour search is not optizable using an index because...
[ 4 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0008125938_pyqt4_python.txt
Q: How does Google save changes done on a Google document? I was wondering how does Google save the changes made to a Google document on the fly. Obviously it cannot send all the contents of the document being edited on keyup. I had left Firebug open and it seems like on keyup a text range along with whats changed in...
How does Google save changes done on a Google document?
I was wondering how does Google save the changes made to a Google document on the fly. Obviously it cannot send all the contents of the document being edited on keyup. I had left Firebug open and it seems like on keyup a text range along with whats changed in that range is being sent. Though I m not sure of this. Any i...
[ "Operational Transformation is the core idea behind by many collaborative real-time editors. Google Wave Operational Transformation documents the protocol in Google Wave, and I'd assume that Google Docs is similar.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0008125063_python.txt
Q: What is the differences between container.__iter__() and iterator.__iter__()? I am poor in python so don't beat me please. >>> a = ['a', 'b', 'c'] >>> a.__iter__() <listiterator object at 0x03531750> >>> a.__iter__().__iter__() <listiterator object at 0x03531690> I see that both of listiterator objects lives in ...
What is the differences between container.__iter__() and iterator.__iter__()?
I am poor in python so don't beat me please. >>> a = ['a', 'b', 'c'] >>> a.__iter__() <listiterator object at 0x03531750> >>> a.__iter__().__iter__() <listiterator object at 0x03531690> I see that both of listiterator objects lives in other places (true that 0x03531750 is like place?). I need to know that both of the...
[ "An iterator has an __iter__() method so that you can call iter() on it to get an iterator for it, even though it already is one. Makes it easier to write things that use iterators if you don't have to be constantly checking whether something is already an iterator or not.\nSo you're getting an iterator for the lis...
[ 10, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008125930_python.txt
Q: Proper layout for a large python script Currently I have a python script (proofreader.py) that help me to read a text file, process from several proofreading method, and output the corrected test to a file. But the script is quite lengthy, e.g. > 1000 Line of codes, so I want to better organize it and better reuse...
Proper layout for a large python script
Currently I have a python script (proofreader.py) that help me to read a text file, process from several proofreading method, and output the corrected test to a file. But the script is quite lengthy, e.g. > 1000 Line of codes, so I want to better organize it and better reuse in the future. Current structure: proofreade...
[ "I usually use a similar layout.\nThe only significant difference I'd say is that test module would be under Proofreader instead of under Proofreader/proofreader. The main reason to keep tests separate from the code is that you usually just want to make them available to other developers, but not to the users that ...
[ 1, 1 ]
[]
[]
[ "coding_style", "python" ]
stackoverflow_0008123639_coding_style_python.txt
Q: celery get tasks count I am using python celery+rabbitmq. I can't find a way to get task count in some queue. Some thing like this: celery.queue('myqueue').count() Is it posible to get tasks count from certaint queue? One solution is to run external command from my python scrpit: "rabbitmqctl list_queues -p my_v...
celery get tasks count
I am using python celery+rabbitmq. I can't find a way to get task count in some queue. Some thing like this: celery.queue('myqueue').count() Is it posible to get tasks count from certaint queue? One solution is to run external command from my python scrpit: "rabbitmqctl list_queues -p my_vhost" and parse results, is...
[ "I suppose that using rabbitmqctl command is not good solution, especially on my ubuntu server, where rabbitmqctl can be executed only with root privileges.\nBy playing with pika objects I found working solution:\nimport pika\nfrom django.conf import settings \n\ndef tasks_count(queue_name):\n ''' Connects to me...
[ 5 ]
[]
[]
[ "celery", "python", "rabbitmq" ]
stackoverflow_0007552170_celery_python_rabbitmq.txt
Q: countdown for loop in Python This is my script and I want it to print and subtract 1: for eachNumber in range(counter, 0, -1): print(eachNumber) from counter for each loop it does. When I try to place it in the for loop I currently have it prints all full numbers until it reaches counter I want it to c...
countdown for loop in Python
This is my script and I want it to print and subtract 1: for eachNumber in range(counter, 0, -1): print(eachNumber) from counter for each loop it does. When I try to place it in the for loop I currently have it prints all full numbers until it reaches counter I want it to count down from counter for each fo...
[ "It's hard to tell what you mean, but I think the problem is that you've nested one for loop in another, when you don't actually want to do this. Try adding this inside your ids loop:\nprint counter, \"videos remaining\"\ncounter -= 1\n\nThis just decreases the counter once per Id, rather than running over the full...
[ 2 ]
[]
[]
[ "countdown", "counter", "python", "range" ]
stackoverflow_0008126139_countdown_counter_python_range.txt
Q: Problems when drawing scatter plot I am using matplotlib.pyplot.scatter to draw some simple scatter plot. However, something wrong appears and I cannot find the solution. Here is the code for drawing this scatter plot: # xActA, yActA, xActQ, yActQ are all lists with same dimensions. ax1 = scatter(xActA, yActA, c...
Problems when drawing scatter plot
I am using matplotlib.pyplot.scatter to draw some simple scatter plot. However, something wrong appears and I cannot find the solution. Here is the code for drawing this scatter plot: # xActA, yActA, xActQ, yActQ are all lists with same dimensions. ax1 = scatter(xActA, yActA, color = 'blue',s = 20, label = 'Answers',...
[ "The issue is with linestyle='o'. The 'o' directive is a marker, not a linestyle, so replace linestyle with marker in your first two lines of code.\nYou can see the complete list of markers for scatter here.\n", "If you look closer at your data you will notice that most of your data points fall outside of the plo...
[ 3, 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0008105926_matplotlib_python.txt
Q: XUL Runner Log HTTP Requests Python Looking for some help to log HTTP requests for a given page. Essentially I'm looking at running a Ubuntu instance to log HTTP requests from a given page and parse them out to the user. I'd like to use a Python Web App client side. Workflow is : User types in URL > App takes in R...
XUL Runner Log HTTP Requests Python
Looking for some help to log HTTP requests for a given page. Essentially I'm looking at running a Ubuntu instance to log HTTP requests from a given page and parse them out to the user. I'd like to use a Python Web App client side. Workflow is : User types in URL > App takes in Requests > XULRunner "does something" > Py...
[ "You probably want to use a <browser type=\"content\"> tag in XULRunner and use browser.addProgressListener() to add a web progress listener. With the progress listener you will be able to track all requests (calls to onStateChange with aFlag containing STATE_IS_REQUEST flag). The progress listener can then read ou...
[ 0 ]
[]
[]
[ "http", "python", "xul", "xulrunner" ]
stackoverflow_0008126409_http_python_xul_xulrunner.txt
Q: How do I get a count variable from python handler to javascript function? I am trying to issue a user name to each new user in the form user1, user2, user3 and so on. As the result of my previous question, now I understand that I need to keep track of count in the app and not in the browser. So I created /counthan...
How do I get a count variable from python handler to javascript function?
I am trying to issue a user name to each new user in the form user1, user2, user3 and so on. As the result of my previous question, now I understand that I need to keep track of count in the app and not in the browser. So I created /counthandler (I am working with Google App Engine Python): class CountHandler(webapp.Re...
[ "If you are keeping track of the variable server-side and you want to put it in your web page, then you just output a javascript variable to the web page with the value of count. Thus if your server has a count of 12, then you just output this to the web page from your web server app:\nvar count = 12;\n\nAny clien...
[ 1, 1 ]
[]
[]
[ "javascript", "python", "xmlhttprequest" ]
stackoverflow_0008124588_javascript_python_xmlhttprequest.txt
Q: Cython/Numpy: Float being truncated consider the following: import numpy as np cimport numpy as np DTYPE = np.float ctypedef np.float_t DTYPE_t def do(np.ndarray[DTYPE_t, ndim=2] hlc, int days=2): cdef float dvu = 0.0 cdef Py_ssize_t N = np.shape(hlc)[1]-1, i, j, k cdef np.ndarray[DTYPE_t] h = hlc[0...
Cython/Numpy: Float being truncated
consider the following: import numpy as np cimport numpy as np DTYPE = np.float ctypedef np.float_t DTYPE_t def do(np.ndarray[DTYPE_t, ndim=2] hlc, int days=2): cdef float dvu = 0.0 cdef Py_ssize_t N = np.shape(hlc)[1]-1, i, j, k cdef np.ndarray[DTYPE_t] h = hlc[0] cdef np.ndarray[DTYPE_t] l = hlc[1]...
[ "I'm dumb. I was printing the thing out using the round function in a different module. There's 3 hours of my life I'll never get back ...\n" ]
[ 0 ]
[]
[]
[ "cython", "numpy", "python" ]
stackoverflow_0008126190_cython_numpy_python.txt
Q: How to use Freebase to label a very large unlabeled NLP dataset? Vocabulary that I am using: nounphrase -- A short phrase that refers to a specific person, place, or idea. Examples of different nounphrases include "Barack Obama", "Obama", "Water Bottle", "Yellowstone National Park", "Google Chrome web browser", et...
How to use Freebase to label a very large unlabeled NLP dataset?
Vocabulary that I am using: nounphrase -- A short phrase that refers to a specific person, place, or idea. Examples of different nounphrases include "Barack Obama", "Obama", "Water Bottle", "Yellowstone National Park", "Google Chrome web browser", etc. category -- The semantic concept defining which nounphrases belong ...
[ "The basic form of the query (for a person, for example) is \n[{\n \"type\":\"/people/person\",\n \"name\":None,\n \"/common/topic/alias\":[],\n \"limit\":100\n}]​\n\nThere's documentation available at http://wiki.freebase.com/wiki/MQL_Manual\nUsing freebase.mqlreaditer() from the Python library http://code.goo...
[ 4, 1 ]
[]
[]
[ "freebase", "nlp", "python" ]
stackoverflow_0008100044_freebase_nlp_python.txt
Q: Create a function that opens a file and creates a dictionary I have a file that I'm working with. I want to create a function that reads the files and place the contents into a dictionary. Then that dictionary needs to be passed through the main function. Here is the main program. It cannot be changed. Everythi...
Create a function that opens a file and creates a dictionary
I have a file that I'm working with. I want to create a function that reads the files and place the contents into a dictionary. Then that dictionary needs to be passed through the main function. Here is the main program. It cannot be changed. Everything I do must work with the main program. def main(): sunspot_d...
[ "Given the restriction you give in your reply to Raymond, that you can't modify the init_dictionary() method and that it requires that you pass it a dictionary which it will then populate, I recommend that you make your own class a subclass of dict.\nclass MySunspotDict(dict):\n def __init__(self, file_str):\n ...
[ 1, 1 ]
[]
[]
[ "dictionary", "function", "python" ]
stackoverflow_0008117441_dictionary_function_python.txt
Q: How to set the application name in spynner/PyQt4? I have had searched the web to find the way to put a name in the top of a PyQt4 application border. I saw setCaption() method ( like in http://nullege.com/codes/search/PyQt4.QtGui.QDialog.setCaption ) but I don't know how to use it and if it's the good method ( ...
How to set the application name in spynner/PyQt4?
I have had searched the web to find the way to put a name in the top of a PyQt4 application border. I saw setCaption() method ( like in http://nullege.com/codes/search/PyQt4.QtGui.QDialog.setCaption ) but I don't know how to use it and if it's the good method ( I have had tested browser.setCaption("foobar") ) My app...
[ "browser.webview.setWindowTitle('the title')\n\nhttps://github.com/makinacorpus/spynner/blob/master/src/spynner/browser.py#L885\nhttp://doc.qt.nokia.com/latest/qwebview-members.html\n" ]
[ 2 ]
[]
[]
[ "pyqt4", "python", "qtwebkit", "spynner" ]
stackoverflow_0008127494_pyqt4_python_qtwebkit_spynner.txt
Q: Clip an image using several patches in matplotlib I have a plot in pylab which I want to clip to the borders of a map of the UK. I've also made a series of patches which contain the outlines of each country: one for England, one for Wales etc. Clipping the plot one patch works brilliantly: fig = plt.figure() ax =...
Clip an image using several patches in matplotlib
I have a plot in pylab which I want to clip to the borders of a map of the UK. I've also made a series of patches which contain the outlines of each country: one for England, one for Wales etc. Clipping the plot one patch works brilliantly: fig = plt.figure() ax = fig.add_subplot(111) im = ax.scatter(x,y,c = z) ax.add...
[ "I think you can do this by making multiple scatter plots, clipping each one with a unique patch (eg one has England, one has Ireland, etc). Though this might not be what you asked for, ie \"Does anyone know how I can clip using an 'OR' type statement?\", it should have the same effect:\nimport numpy as np\nimport ...
[ 8 ]
[]
[]
[ "clip", "matplotlib", "patch", "python" ]
stackoverflow_0008126151_clip_matplotlib_patch_python.txt
Q: How do you Edit Video ID3 Tags in Python? I've been slowly writing a little project to create a Movie/TV Show/Music ID3 tag editor that can be used on batches of files from my iTunes library. I started designing the GUI in python after finding a bunch of ID3 tag editors here: http://wiki.python.org/moin/UsefulModu...
How do you Edit Video ID3 Tags in Python?
I've been slowly writing a little project to create a Movie/TV Show/Music ID3 tag editor that can be used on batches of files from my iTunes library. I started designing the GUI in python after finding a bunch of ID3 tag editors here: http://wiki.python.org/moin/UsefulModules#ID3Handling Unfortunately when it came time...
[ "Massively overdue, but if you're on OSX, you can use appscript to alter metadata via iTunes itself, which is very easy if slow.\nThe great thing about this is that it works on any kind of media and you can alter iTunes-specific metadata, too.\nIf not, you can use Atomic Parsley via subprocess or similar.\n", "To...
[ 1, 0 ]
[]
[]
[ "id3", "metadata", "mp4", "python", "video" ]
stackoverflow_0004770597_id3_metadata_mp4_python_video.txt
Q: My Python-Java Interface, good design? And how to wrap JNI Functions? I'm going to write my own Python-Java interface. It is compiled as a DLL and wrapped using ctypes. Yet, it is possible to find Java-classes and allocate Java-objects. But what would be an interface to another language without using those objects...
My Python-Java Interface, good design? And how to wrap JNI Functions?
I'm going to write my own Python-Java interface. It is compiled as a DLL and wrapped using ctypes. Yet, it is possible to find Java-classes and allocate Java-objects. But what would be an interface to another language without using those objects methods? My aim is to make this as natural as possible. Unfortunately, it ...
[ "1. What do I think of this design?\n\nit's not clear what actual problem you're trying to solve.\nwhat about edge cases; error-handling; forward-/backward-compatibility; bugs in Python/Java? Not fun, but essential for robust software.\nmixing two languages is hard enough, mixing three is sure to be much much wors...
[ 11 ]
[]
[]
[ "c++", "java", "java_native_interface", "python", "variadic_functions" ]
stackoverflow_0008071362_c++_java_java_native_interface_python_variadic_functions.txt
Q: Parsing a tab-separated file with missing fields This is an example of a complex tab separated file I'm trying to parse ENTRY map0010\tNAME Glycolysis\tDESCRIPTION Glycolysis is the process of converting glucose into pyruvate\tCLASS Metabolism\tDISEASE H00071 Hereditary fructose intolerance\tH00072 Pyruva...
Parsing a tab-separated file with missing fields
This is an example of a complex tab separated file I'm trying to parse ENTRY map0010\tNAME Glycolysis\tDESCRIPTION Glycolysis is the process of converting glucose into pyruvate\tCLASS Metabolism\tDISEASE H00071 Hereditary fructose intolerance\tH00072 Pyruvate dehydrogenase complex deficiency\tDBLINKS GO: 00...
[ "Use the built in csv library. Your job will be much easier.\nFor some sample code:\nimport csv\nreader = csv.reader(open('myfile.csv', 'rb'), dialect='excel-tab')\nfieldnames = ['Name','Class']\nwriter = csv.DictWriter(open('myfile.csv', 'rb'), fieldnames, restval='', extrasaction='ignore', dialect='excel-tab')\n\...
[ 6, 3, 2 ]
[]
[]
[ "csv", "parsing", "python" ]
stackoverflow_0008127524_csv_parsing_python.txt
Q: python: algorithm - to gather items from mean Not sure whether this is the right place, but I have a question related to algorithm and I cant think of an efficient algorithm. So thought of sharing my problem statement.. :) To ease up what I am trying to explain, let me create a hypothetical example. Suppose, I hav...
python: algorithm - to gather items from mean
Not sure whether this is the right place, but I have a question related to algorithm and I cant think of an efficient algorithm. So thought of sharing my problem statement.. :) To ease up what I am trying to explain, let me create a hypothetical example. Suppose, I have a list which contains an object whcih contains tw...
[ "You are probably looking for selection algorithm.\nFirst find the n1'th smallest element, let it be e1, and the lower bound list is all elements such that element <= e1.\nDo the same for the other ranges.\npseudo code for lower bound list:\ngetLowerRange(list,n):\n e <- select(list,n) \n result <- []\n for each...
[ 2, 2, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0008126807_algorithm_python.txt
Q: Python package without __init__ I pip install-ed the flufl.enum Python package and I noticed that it works despite missing a flufl/__init__.py module as regular Python packages. Even stranger is this: >>> import flufl >>> flufl <module 'flufl' (built-in)> I tried to reproduce this creating foo/bar/__init__.py wit...
Python package without __init__
I pip install-ed the flufl.enum Python package and I noticed that it works despite missing a flufl/__init__.py module as regular Python packages. Even stranger is this: >>> import flufl >>> flufl <module 'flufl' (built-in)> I tried to reproduce this creating foo/bar/__init__.py without foo/__init__.py and (predictably...
[ "the magic is done in the flufl.enum-3.2-py2.7-nspkg.pth file, which is put into site-packages by \"pip install\":\nimport sys,new,os\np = os.path.join(sys._getframe(1).f_locals['sitedir'], *('flufl',))\nie = os.path.exists(os.path.join(p,'__init__.py'))\nm = not ie and sys.modules.setdefault('flufl',new.module('fl...
[ 19, 0, 0 ]
[]
[]
[ "built_in", "python" ]
stackoverflow_0008110951_built_in_python.txt
Q: Making a dictionary from a file Possible Duplicate: Create a function that opens a file and creates a dictionary We are given a main function to use to: Write the following two functions: init_dictionary(file_string, sunspot_dict) This function takes as an argument the name of file to open and an empty dictiona...
Making a dictionary from a file
Possible Duplicate: Create a function that opens a file and creates a dictionary We are given a main function to use to: Write the following two functions: init_dictionary(file_string, sunspot_dict) This function takes as an argument the name of file to open and an empty dictionary. It has no return value but does ...
[ "Read more about IO in Python ....\nYou need to open the file , extract its contents and then populate your dictionary...\nHave a look at Input-Output in Python\nA hint is to look at this example where they try to make a dictionary out of a file .... reading file to dictionary\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008127515_python.txt
Q: Converting tuples to lists and getting rid of inner tuple/list Here's my tuple of tuples: (('dlazarov',), ('ant1',)) I would like to turn this into this: ['dlazarov', 'ant1'] I was trying to use this: userdata = (('dlazarov',), ('ant1',)) userdata = map(list, userdata) userdata = sum(userdata, []) But this doe...
Converting tuples to lists and getting rid of inner tuple/list
Here's my tuple of tuples: (('dlazarov',), ('ant1',)) I would like to turn this into this: ['dlazarov', 'ant1'] I was trying to use this: userdata = (('dlazarov',), ('ant1',)) userdata = map(list, userdata) userdata = sum(userdata, []) But this doesn't seem to work. Nevermind, I had a typo in my end. Also - questio...
[ "You can use a list comprehension:\n>>> userdata = (('dlazarov',), ('ant1',))\n>>> [x[0] for x in userdata]\n['dlazarov', 'ant1']\n\n", "The operation is called \"flattening\".\nYou can use itertools.chain.from_iterable to handle the common case of flattening an iterable of iterables (in your case, a tuple of tup...
[ 2, 2, 1, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0008128403_list_python_tuples.txt
Q: How to get back a valid object from python in C++ while this object has been construct using handle<>? I want to allocate a buffer in C++ and provide it to python as a memoryview object. To do so, I expose this function using boost::python : object* Allocator() { void* buff = my_alloc_function(char, size); ...
How to get back a valid object from python in C++ while this object has been construct using handle<>?
I want to allocate a buffer in C++ and provide it to python as a memoryview object. To do so, I expose this function using boost::python : object* Allocator() { void* buff = my_alloc_function(char, size); Py_buffer pybuffer; int res = PyBuffer_FillInfo(&pybuffer, 0, buff, size, false, PyBUF_CONTIG); if ...
[ "I managed to get it work.\nHere is the code the two functions (without return policy when exposing them):\nPyObject* Allocator()\n{\n void* buff = my_alloc_function(char, size);\n Py_buffer pybuffer;\n int res = PyBuffer_FillInfo(&pybuffer, 0, buff, size, false, PyBUF_CONTIG);\n if (res == -1)\n ...
[ 2, 0 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0008123121_boost_python_c++_python.txt
Q: In Python 3, how can I search for a string in a separate .txt file? I am trying to write a code in Python 3 that will allow the user to enter the name of a .txt file. Then the user enters a keyword or phrase and Python searches that .txt file and returns what line the phrase is on. Also, the program will write som...
In Python 3, how can I search for a string in a separate .txt file?
I am trying to write a code in Python 3 that will allow the user to enter the name of a .txt file. Then the user enters a keyword or phrase and Python searches that .txt file and returns what line the phrase is on. Also, the program will write some things to a .html file, but I can take care of that once I get this par...
[ "It looks like the part you're missing is how to search 'txt' files. This snippet may help you get started:\nimport glob\n\nkeyword = raw_input('Enter a keyword to search for: ')\nfor filename in glob.glob('*.txt'):\n with open(filename) as f:\n for lineno, line in enumerate(f, 1):\n if keywor...
[ 1 ]
[]
[]
[ "database", "python", "search", "string", "text" ]
stackoverflow_0008128591_database_python_search_string_text.txt
Q: Splitting Text File Into Columns and Rows in Python I have a newbie question. I need help on separating a text file into columns and rows. Let's say I have a file like this: 1 2 3 4 2 3 4 5 and I want to put it into a 2d list called values = [[]] i can get it to give me the rows ok and this code works ok: values...
Splitting Text File Into Columns and Rows in Python
I have a newbie question. I need help on separating a text file into columns and rows. Let's say I have a file like this: 1 2 3 4 2 3 4 5 and I want to put it into a 2d list called values = [[]] i can get it to give me the rows ok and this code works ok: values = map(int, line.split(',')) I just don't know how I can...
[ "f = open(filename,'rt')\na = [[int(token) for token in line.split()] for line in f.readlines()[::2]]\n\nIn your sample file above, you have an empty line between each data row - I took this into account, but you can drop the ::2 subscript if you didn't mean to have this extra line in your data.\nEdit: added conver...
[ 6, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005245468_python.txt
Q: Python - Parsing Columns and Rows I am running into some trouble with parsing the contents of a text file into a 2D array/list. I cannot use built-in libraries, so have taken a different approach. This is what my text file looks like, followed by my code 1,0,4,3,6,7,4,8,3,2,1,0 2,3,6,3,2,1,7,4,3,1,1,0 5,2,1,3,4,6...
Python - Parsing Columns and Rows
I am running into some trouble with parsing the contents of a text file into a 2D array/list. I cannot use built-in libraries, so have taken a different approach. This is what my text file looks like, followed by my code 1,0,4,3,6,7,4,8,3,2,1,0 2,3,6,3,2,1,7,4,3,1,1,0 5,2,1,3,4,6,4,8,9,5,2,1 def twoDArray(): netw...
[ "Well, I can explain the error. You're using str.split() and its usage pattern is:\nstr.split(separator, maxsplit)\nYou're using str.split(string, separator) and that isn't a valid call to split. Here is a direct link to the Python docs for this:\nhttp://docs.python.org/library/stdtypes.html#str.split\n", "To d...
[ 4, 2, 2, 0, 0, 0, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0005043815_parsing_python.txt
Q: Properly handling IOError thrown by logging.config.fileConfig? This may be an open ended or awkward question, but I find myself running into more and more exception handling concerns where I do not know the "best" approach in handling them. Python's logging module raises an IOError if you try to configure a FileH...
Properly handling IOError thrown by logging.config.fileConfig?
This may be an open ended or awkward question, but I find myself running into more and more exception handling concerns where I do not know the "best" approach in handling them. Python's logging module raises an IOError if you try to configure a FileHandler with a file that does not exist. The module does not handle t...
[ "This is not something specific to the logging module: in general, Python code does not automatically create intermediate directories for you automatically; you need to do this explicitly using os.makedirs(), typically like this:\nif not os.path.exists(dirname):\n os.makedirs(dirname)\n\nYou can replace the stan...
[ 1, 0 ]
[]
[]
[ "exception", "exception_handling", "ioerror", "logging", "python" ]
stackoverflow_0008128088_exception_exception_handling_ioerror_logging_python.txt
Q: How can I create variables by iterating through a combination of integers and strings? So I want to create variables by looping through some sort of name assigning statement or function. I want to end up having variables titled "t1, t2, t3" etc. How can I accomplish what i = 1 while 1: ("t" + str(i)) = [0,0,0,...
How can I create variables by iterating through a combination of integers and strings?
So I want to create variables by looping through some sort of name assigning statement or function. I want to end up having variables titled "t1, t2, t3" etc. How can I accomplish what i = 1 while 1: ("t" + str(i)) = [0,0,0,0] i = i + 1 looks like it would do. (Keep the str("t") at the front than make the seco...
[ "Don't try.\nInstead, use a single dictionary to keep all the values - your titles can be the keys:\nmy_dict = {}\nfor i in range(1, 4):\n my_dict['t%s' % i] = foo\n\n", "While it is technically possible to do what you want, it's a really bad practice. This is exactly the use case that lists (or arrays) were m...
[ 5, 5, 3 ]
[]
[]
[ "loops", "python", "variables" ]
stackoverflow_0008126720_loops_python_variables.txt
Q: Python: flexible way to declare constructors What is a clean way to declare multiple constructors for one class? For example, let's say I have an Item class. One way to create an Item (for example is) item = Item(product_id, name, description,price) another way to do the same thing might item = Item(otherItem) ...
Python: flexible way to declare constructors
What is a clean way to declare multiple constructors for one class? For example, let's say I have an Item class. One way to create an Item (for example is) item = Item(product_id, name, description,price) another way to do the same thing might item = Item(otherItem) And then another way to do this.. maybe in some c...
[ "The two most common approaches for providing multiple constructors are:\n\nclass methods and\nfactory functions\n\nHere is an example taken from the standard library showing how collections.OrderedDict uses a classmethod to implement fromkeys() as an alternate class constructor:\n@classmethod\ndef fromkeys(cls, it...
[ 4, 1, 1 ]
[]
[]
[ "constructor", "python" ]
stackoverflow_0008129014_constructor_python.txt
Q: Best ways to stream live video to a webpage using Python/C++/Java I want to read in a live video stream, like RTSP, run some basic processing on it, and display it on a website. What are some good ways to do this? I have used OpenCV for Python before but found it to be a hassle. I am also familiar with Java and...
Best ways to stream live video to a webpage using Python/C++/Java
I want to read in a live video stream, like RTSP, run some basic processing on it, and display it on a website. What are some good ways to do this? I have used OpenCV for Python before but found it to be a hassle. I am also familiar with Java and C++ if there are better libraries available. I haven't done a lot of ...
[ "What kind of live video source that you mean? If you don't intend to do this code-wise, you can use the free VLC Player to act as a streaming service in between any kind of media stream source (file, network, capture device, disc) and your web video client.\nBut, if you intend to do this code-wise, you can you VLC...
[ 0 ]
[]
[]
[ "c++", "java", "python", "streaming" ]
stackoverflow_0008127213_c++_java_python_streaming.txt
Q: does Tornado uses WSGI to deal with python files? am sorry for that question, am beginning in Tornado, and because i come from two other frameworks: Flask and Django, Flask uses Werkzeug which is a WSGI webserver, Django uses WSGI too, but, when making an application programmed with Tornado, how it will deal with ...
does Tornado uses WSGI to deal with python files?
am sorry for that question, am beginning in Tornado, and because i come from two other frameworks: Flask and Django, Flask uses Werkzeug which is a WSGI webserver, Django uses WSGI too, but, when making an application programmed with Tornado, how it will deal with HTTP? there is a protocol to deal with python files whe...
[ "Tornado shouldn't use WSGI, because WSGI is not async friendly. It has WSGI support, but it won't support async.\nTornado has its own HTTP server (written in C and Python), and can be used standalone or placed behind another async HTTP server (usually Nginx).\n" ]
[ 3 ]
[]
[]
[ "python", "tornado", "wsgi" ]
stackoverflow_0008128736_python_tornado_wsgi.txt
Q: lxml iterparse mising child nodes I am using lxml iterparse to read huge xml files. For a given mainElement, I check the child elements and process each child. But I notice that, on checking the children within an element, the parser is actually missing some child nodes sometimes. I even printed the length of each...
lxml iterparse mising child nodes
I am using lxml iterparse to read huge xml files. For a given mainElement, I check the child elements and process each child. But I notice that, on checking the children within an element, the parser is actually missing some child nodes sometimes. I even printed the length of each element, which should be a constant nu...
[ "When you define the context, be sure to set the parameter events to ('end',) rather than ('start',). Otherwise, you can get the very behavior you are describing.\ncontext=etree.iterparse(filehandle, events=('end',), tag=mainElement)\n\n\nI think the problem is that lxml is processing the XML in one thread while ru...
[ 4 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0008129329_lxml_python.txt
Q: Factory method in python I'm working to the following little project: https://github.com/AndreaCrotti/project-organizer Which in short aims to manage many different projects much more easily. One of the useful things is a way to detect automatically the kind of project that I'm working on, to set up correctly some...
Factory method in python
I'm working to the following little project: https://github.com/AndreaCrotti/project-organizer Which in short aims to manage many different projects much more easily. One of the useful things is a way to detect automatically the kind of project that I'm working on, to set up correctly some commands. At the moment I'm u...
[ "This was a reasonable use of a factory function as a class method.\nOne possible improvement is to have all the classes inherit from a single parent class which would have a single classmethod that incorporated all the logic in detect_project_type.\nPerhaps something like this would work:\nclass ProjectType(object...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0008129018_python.txt
Q: How do mod_php, mod_python, mod_Language work Some of the Apache modules are related to programming languages, like mod_php and mod_python. The description is basically "enables usage of php within apache" or "enables usage of python within apache". I'm trying to understand an overview of how these types of "langu...
How do mod_php, mod_python, mod_Language work
Some of the Apache modules are related to programming languages, like mod_php and mod_python. The description is basically "enables usage of php within apache" or "enables usage of python within apache". I'm trying to understand an overview of how these types of "language" modules work.
[ "This is relatively simple; When the webserver starts, it will register modules within its core. Language interpreter modules, like mod_php, will register a hook within the page request handler.\nThis means when a user requests a page, the webserver will pass the request to the module, which checks if the requested...
[ 4, 1 ]
[]
[]
[ "apache", "mod_php", "mod_python", "php", "python" ]
stackoverflow_0008129088_apache_mod_php_mod_python_php_python.txt
Q: Python simple regex So I have a pattern: hourPattern = re.compile('\d{2}:\d{2}') And match against the compiled pattern hourStart = hourPattern.match('Sat Jan 28 01:15:00 GMT 2012') When I print hourStart it gives me None. Any help? A: Match expects the found value to be at the beginning of the string. You ...
Python simple regex
So I have a pattern: hourPattern = re.compile('\d{2}:\d{2}') And match against the compiled pattern hourStart = hourPattern.match('Sat Jan 28 01:15:00 GMT 2012') When I print hourStart it gives me None. Any help?
[ "Match expects the found value to be at the beginning of the string. You want search.\n>>> import re\n>>>\n>>> s = re.compile('\\d+')\n>>>\n>>> s2 = 'a123'\n>>>\n>>> s.match(s2)\n>>> s.search(s2)\n<_sre.SRE_Match object at 0x01E29AD8>\n\n", "Switch from the match method to the search method:\n>>> hourPattern = r...
[ 9, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008129648_python_regex.txt
Q: In Python, how to create a large number of variables in a loop? I'm looking for a way, in python 3.2, to create a large number of variables and assign them values. Something like X = 10 Y = 10 A = 0 B = 0 while X >= 0: while Y >= 0: cell[C]X[A] = A cell[C]Y[B] = B B = B + 1 Y = ...
In Python, how to create a large number of variables in a loop?
I'm looking for a way, in python 3.2, to create a large number of variables and assign them values. Something like X = 10 Y = 10 A = 0 B = 0 while X >= 0: while Y >= 0: cell[C]X[A] = A cell[C]Y[B] = B B = B + 1 Y = Y - 1 C = C + 1 A = A + 1 X = X - 1 Which would opti...
[ "Honestly, the only reasonable answer to this question is: Don't do that, and learn how to use dictionaries instead.\nI believe this is also the most helpful answer as well. You have already stated in your question that (1) you are new to Python, (2) you are new to programming in general, and (3) you accept that d...
[ 10, 5, 4 ]
[ "Global scope is not something you want to create variables in, i can offer you couple of ways to create arrays instead:\nThere is a couple of ways you can take.\none would be to multiply like so:\na = [1]*5\n\nThis will actually build you a list of references to the same array which is not what we need - good catc...
[ -1 ]
[ "loops", "python", "python_3.x", "variables" ]
stackoverflow_0008129190_loops_python_python_3.x_variables.txt
Q: Attempt at parsing packets: Is there a Java equivalent to Python's "unpack"? Is there an equivalent function to this Python function in Java? struct.unpack(fmt, string) I'm trying to port a parser written in Python to Java, and I'm looking for a way to implement the following line of code: handle, msgVer, source, ...
Attempt at parsing packets: Is there a Java equivalent to Python's "unpack"?
Is there an equivalent function to this Python function in Java? struct.unpack(fmt, string) I'm trying to port a parser written in Python to Java, and I'm looking for a way to implement the following line of code: handle, msgVer, source, startTime, dataFormat, sampleCount, sampleInterval, physDim, digMin, digMax, phys...
[ "I am not aware of any real equivalent to Python's unpack in Java.\nThe conventional approach would be to read the data from a stream (originating either from a socket, or from a byte array read from the socket, via a ByteArrayInputStream) using a DataInputStream. That class has a set of methods for reading various...
[ 3 ]
[]
[]
[ "java", "python" ]
stackoverflow_0008084836_java_python.txt
Q: How should I resolve my appspot backup failure? I'm trying to make a backup but it won't: 2011-10-01 09:22:43.706 /remote_api 302 5ms 0cpu_ms 0kb 213.89.134.0 - - [01/Oct/2011:05:22:43 -0700] "GET /remote_api HTTP/1.1" 302 0 - - "montaoproject.appspot.com" ms=6 cpu_ms=0 api_cpu_ms=0 cpm_usd=0.000032 $ python ./a...
How should I resolve my appspot backup failure?
I'm trying to make a backup but it won't: 2011-10-01 09:22:43.706 /remote_api 302 5ms 0cpu_ms 0kb 213.89.134.0 - - [01/Oct/2011:05:22:43 -0700] "GET /remote_api HTTP/1.1" 302 0 - - "montaoproject.appspot.com" ms=6 cpu_ms=0 api_cpu_ms=0 cpm_usd=0.000032 $ python ./appcfg.py download_data --application=montaoproject --...
[ "When using this approach to get remote API to work with open ID (from http://blog.notdot.net/2010/06/Using-remote-api-with-OpenID-authentication), I think you need to specify the secret key (ie 'thetopsecret') as the email when prompted (and then just hit enter when prompted for the password).\n", "Use correct c...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007620200_google_app_engine_python.txt
Q: Django - Consuming a RESTful service asynchronously I need to create a django web portal in which users can select and run ad-hoc reports by providing values, via forms, to parameters defined in each specific report. The view that processes the user’s report execution requests needs to make RESTFul service calls ...
Django - Consuming a RESTful service asynchronously
I need to create a django web portal in which users can select and run ad-hoc reports by providing values, via forms, to parameters defined in each specific report. The view that processes the user’s report execution requests needs to make RESTFul service calls to a remote Jasper Reports Server where the actual output...
[ "django-celery is a popular choice for async tasks, i usually use greenlets as im used to them.\nThen to notify the user you can use the notification framework to tell the client that something is done.\n" ]
[ 4 ]
[]
[]
[ "django", "python", "rest" ]
stackoverflow_0008099699_django_python_rest.txt
Q: How to configure Pyramid to find MongoDB Primary replica Is there a way to configure Pyramid so that when MongoDB fails over to a secondary replica, Pyramid starts using it? A: Pyramid should be using the official python MongoDB drivers. The drivers are configured to do this "automatically", but they need the co...
How to configure Pyramid to find MongoDB Primary replica
Is there a way to configure Pyramid so that when MongoDB fails over to a secondary replica, Pyramid starts using it?
[ "Pyramid should be using the official python MongoDB drivers. The drivers are configured to do this \"automatically\", but they need the correct connection string.\nSee here for the connection strings.\nOne thing to keep in mind, the definition of \"automatic fail-over\" is not clear cut.\nIf you create a new conne...
[ 2 ]
[]
[]
[ "mongodb", "pymongo", "pyramid", "python" ]
stackoverflow_0008129532_mongodb_pymongo_pyramid_python.txt
Q: What version of this Python code is faster? Just an academic question. I'm curious what version of this code is better (faster) in Python? var = random.randint(1, 10) # First version if var in [2, 5, 9]: print "First: 2, 5 or 9" # Second version if var == 2 or number == 5 or number == 9: print "Second: 2, 5 o...
What version of this Python code is faster?
Just an academic question. I'm curious what version of this code is better (faster) in Python? var = random.randint(1, 10) # First version if var in [2, 5, 9]: print "First: 2, 5 or 9" # Second version if var == 2 or number == 5 or number == 9: print "Second: 2, 5 or 9" This is very simple example, but what if va...
[ "Timing the code will show which is fastest. Use the timeit module for that:\n~ $ python -m timeit --setup 'var=2' 'var in [2, 5, 9]'\n10000000 loops, best of 3: 0.0629 usec per loop\n~ $ python -m timeit --setup 'var=5' 'var in [2, 5, 9]'\n10000000 loops, best of 3: 0.0946 usec per loop\n~ $ python -m timeit --se...
[ 7 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0008130093_optimization_python.txt
Q: Django using multiple databases I have a model called FieldMap which is used throughout my project. I decided recently that the physical database for this model will exist on another machine (other than the default). So I now have two databases setup in my settings: default and dev. I can use both databases like t...
Django using multiple databases
I have a model called FieldMap which is used throughout my project. I decided recently that the physical database for this model will exist on another machine (other than the default). So I now have two databases setup in my settings: default and dev. I can use both databases like this: FieldMap.objects.using('dev/defa...
[ "Consider writing a custom database router that decides the database to use on the fly.\nhttps://docs.djangoproject.com/en/1.3/topics/db/multi-db/#database-routers\n" ]
[ 3 ]
[]
[]
[ "django", "django_orm", "python" ]
stackoverflow_0008129600_django_django_orm_python.txt
Q: Wildcards in getElementsByTagName (xml.dom.minidom) I'm trying to parse a ODF-document with xml.dom.minidom. I would like to get all elements that are text:p OR text:h. Seems like there would be a way to add a wildcard in the getElementsByTagName method. Or is it? Is there a better way to parse a odf-document with...
Wildcards in getElementsByTagName (xml.dom.minidom)
I'm trying to parse a ODF-document with xml.dom.minidom. I would like to get all elements that are text:p OR text:h. Seems like there would be a way to add a wildcard in the getElementsByTagName method. Or is it? Is there a better way to parse a odf-document without uno?
[ "As getElementsByTagName returns a DOMElement list you could just simply concatenate the two lists.\nAlternatively XPath supports and/or operators, so you could use that. That would require using the elementTree or lxml modules instead.\n", "root_element.getElementsByTagNameNS('text', '*')\n\nmaybe put ? instead ...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007421351_python.txt
Q: How do I cancel action of a form after an alert? When the user submits the form, writeToStorage is fired and it checks if the user is in localStorage and if it is, an alert is run. After this alert I don't want the action to execute. I tried return false; but obviously that does not stop the python script from run...
How do I cancel action of a form after an alert?
When the user submits the form, writeToStorage is fired and it checks if the user is in localStorage and if it is, an alert is run. After this alert I don't want the action to execute. I tried return false; but obviously that does not stop the python script from running. How do I stop the action of the form in case the...
[ "Add your return false back in and also change:\nonsubmit=\"writeToStorage()\"\n\nTo:\nonsubmit=\"return writeToStorage();\"\n\n" ]
[ 4 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0008130380_javascript_python.txt
Q: How to synchronize threads in python? I have two threads in python (2.7). I start them at the beginning of my program. While they execute, my program reaches the end and exits, killing both of my threads before waiting for resolution. I'm trying to figure out how to wait for both threads to finish before exiting. ...
How to synchronize threads in python?
I have two threads in python (2.7). I start them at the beginning of my program. While they execute, my program reaches the end and exits, killing both of my threads before waiting for resolution. I'm trying to figure out how to wait for both threads to finish before exiting. def connect_cam(ip, execute_lock): try:...
[ "Thread is meant as a lower level primitive interface to Python's threading machinery - use threading instead. Then, you can use threading.join() to synchronize threads.\n\nOther threads can call a thread’s join() method. This blocks the\n calling thread until the thread whose join() method is called is\n termina...
[ 4, 4, 2 ]
[]
[]
[ "locking", "multithreading", "python", "synchronization" ]
stackoverflow_0008127648_locking_multithreading_python_synchronization.txt
Q: Python reload with dynamic import (imp.load_source) I am using python2.5. I need to import a module dynamically and then reload on change. How do I achieve this. I tried as in below example - does not work: import imp modfile = 'mymod_info.py' modname = 'mymod' modhandle = imp.load_source (modname, modfile) reload...
Python reload with dynamic import (imp.load_source)
I am using python2.5. I need to import a module dynamically and then reload on change. How do I achieve this. I tried as in below example - does not work: import imp modfile = 'mymod_info.py' modname = 'mymod' modhandle = imp.load_source (modname, modfile) reload (modhandle) Static import and reload works (I am not lo...
[ "If the module was already initialized, imp.load_source will initialize the module again. So instead of reload, just call\nmodhandle = imp.load_source(modname, modfile)\n\n" ]
[ 2 ]
[]
[]
[ "python", "reload" ]
stackoverflow_0008130449_python_reload.txt
Q: pyCairo: How to resize and position an image? Based on the question Create PDF with (resized) PNG images using Pycairo - rescaling Surface issue I have attempted to create code that rescales and places an image at a specific position, as shown in the code below (in this case, for example, the images should appear ...
pyCairo: How to resize and position an image?
Based on the question Create PDF with (resized) PNG images using Pycairo - rescaling Surface issue I have attempted to create code that rescales and places an image at a specific position, as shown in the code below (in this case, for example, the images should appear "over" the underlying rectangles). However, I cann...
[ "Switch the order of scale and translate. Translate first, then scale.\n" ]
[ 6 ]
[]
[]
[ "cairo", "pycairo", "python" ]
stackoverflow_0007145780_cairo_pycairo_python.txt
Q: Is is possible to determine the local path from url? I have access to apache web server. It is a web service application using Python. I would like to access a file (100% sure reside in the local which is the web server itself) but I have only the url. I am thinking of references any setting file of apache web ser...
Is is possible to determine the local path from url?
I have access to apache web server. It is a web service application using Python. I would like to access a file (100% sure reside in the local which is the web server itself) but I have only the url. I am thinking of references any setting file of apache web server to determine the absolute local path of the file. let ...
[ "\nIs is possible to determine the local path from url?\n\nThe short answer: no.\n\nGenerally speaking, there is no concrete association between a URL and a file. In fact, there's nothing to say that the data at a given URL exists in a file on any server anywhere.\n" ]
[ 2 ]
[]
[]
[ "apache", "python", "url_routing" ]
stackoverflow_0008130585_apache_python_url_routing.txt
Q: Why does my flask unit test not use a tempfile database when I had specified so? The test still writes to my MySQL database instead of a sqlite tempfile db. Why does this happen? Thanks! Here's my code: class UserTests(unittest.TestCase): def setUp(self): self.app = get_app() #declare testing ...
Why does my flask unit test not use a tempfile database when I had specified so?
The test still writes to my MySQL database instead of a sqlite tempfile db. Why does this happen? Thanks! Here's my code: class UserTests(unittest.TestCase): def setUp(self): self.app = get_app() #declare testing state self.app.config["TESTING"] = True self.db, self.app.config["DATA...
[ "This line might be the problem:\nself.db, self.app.config[\"DATABASE\"] = tempfile.mkstemp()\n\nprint out the values of self.db and self.app.config[\"DATABASE\"] and makes sure they are what you expect them to be.\n", "You probably want to investigate where your config self.app.config[\"DATABASE\"] is referenced...
[ 1, 0 ]
[]
[]
[ "flask", "python" ]
stackoverflow_0008089276_flask_python.txt
Q: python ElementTree find child with certain text value I've been searching for a while. Is there a way to directly retrieve a child based on the text value of a tag? For example: <a> <b> <c>h</c> </b> <b> <c>j</c> </b> </a> And say I want to retrieve the child be whose "c" text value == ...
python ElementTree find child with certain text value
I've been searching for a while. Is there a way to directly retrieve a child based on the text value of a tag? For example: <a> <b> <c>h</c> </b> <b> <c>j</c> </b> </a> And say I want to retrieve the child be whose "c" text value == j. Is there a way of doing this other than having to get al...
[ "If you use lxml you can use the XPath expression //c[text()='j']\nimport lxml.etree as et\n\ndoc = '''\n<a>\n <b>\n <c>h</c>\n </b>\n <b>\n <c>j</c>\n </b>\n</a>\n'''\n\ntree = et.fromstring(doc)\n\ntree.xpath(\"/a/b/c[text()='j']\")\n\nThis answer is relevant: How do I match contents of an ele...
[ 5 ]
[]
[]
[ "elementtree", "python" ]
stackoverflow_0008130905_elementtree_python.txt
Q: Assigning new variable for each loop in a while loop Im trying to reference a line in which the keyword appears if it appears multiple times i need to be able to reference each line from the while loop. Also i need to bold the key word in the line. Thank you! def main(): print("The Great Search Engine, by Eri...
Assigning new variable for each loop in a while loop
Im trying to reference a line in which the keyword appears if it appears multiple times i need to be able to reference each line from the while loop. Also i need to bold the key word in the line. Thank you! def main(): print("The Great Search Engine, by Eric Santos") # input from user name of database file ...
[ "You say you want to reference each line from the while loop... but you don't have a while loop in your program.\nAlso what's the purpose of your variable hits and the variable i (why the two variables?)\n", "I've made some edits to your code. I'm using python 2.6 so I changed input to raw_input and added from ...
[ 0, 0 ]
[]
[]
[ "loops", "python", "variables", "while_loop" ]
stackoverflow_0008130612_loops_python_variables_while_loop.txt
Q: Python Simple Cookie and Python Stack I made a simple cookie and i want to store a python stack object. C = Cookie.SimpleCookie() arr = [] class Test: num = None for x in range(10): test = Test() test.num = x arr.append(test) C['myCookie'] = arr # i want to do something like this arr = C['myCookie'] can a...
Python Simple Cookie and Python Stack
I made a simple cookie and i want to store a python stack object. C = Cookie.SimpleCookie() arr = [] class Test: num = None for x in range(10): test = Test() test.num = x arr.append(test) C['myCookie'] = arr # i want to do something like this arr = C['myCookie'] can any one tell me a way to do it . to store an...
[ "For general purpose object-to-string-and-back conversions, you could use the pickle module:\nC['myCookie'] = pickle.dumps(arr)\narr_restored = pickle.loads(C['myCookie'].value)\n\nKeep in mind that unpickling untrusted cookies represents a security risk. If that is an issue for you, then you will need to adopt so...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008131126_python.txt
Q: Unable to install zope.interface 3.6.1 in python I am unable to install zope.interface 3.6.1 in Python for Windows. If any one know about this please help me? A: in a command prompt go to install zope.interface 3.6.1 folder write "SETUP.py install" it will install A: You don't need to install it. After you dow...
Unable to install zope.interface 3.6.1 in python
I am unable to install zope.interface 3.6.1 in Python for Windows. If any one know about this please help me?
[ "in a command prompt go to install zope.interface 3.6.1 folder\nwrite \"SETUP.py install\"\nit will install\n", "You don't need to install it. After you download the file zope.interface-3.8.0-py2.7-win32.egg, you unzip it then copy the two directories EGG-INFO and zope into the Python27. It works fine. \n" ]
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004499917_python.txt
Q: How can I shift list elements "down" to corresponding elements of another list recursively in Python? I have a list of 6-element lists. If two particular "columns" of the nested list don't match, I want to recursively "shift" the first 3 elements to the next list for the length of the top list... So: list1 = [ ...
How can I shift list elements "down" to corresponding elements of another list recursively in Python?
I have a list of 6-element lists. If two particular "columns" of the nested list don't match, I want to recursively "shift" the first 3 elements to the next list for the length of the top list... So: list1 = [ ['4', 'and', '3', '4', 'EOS', '15'], ['4', 'what', '3', '0', 'and', '2'], ['4', 'is', '2', '1',...
[ "I don't know about built-in, and certainly not terribly pythonic, but this works (modifies in place):\nlist1 = [\n ['4', 'and', '3', '4', 'EOS', '15'], \n ['4', 'what', '3', '0', 'and', '2'], \n ['4', 'is', '2', '1', 'what', '3'], \n ['4', 'the', '2', '1', 'is', '5']\n]\nprev = ['0','EOS','0']\nfor i i...
[ 0 ]
[]
[]
[ "nested_lists", "python" ]
stackoverflow_0008131209_nested_lists_python.txt
Q: Efficiently parsing a large text file in Python? I have a series of large, flat text files that I need to parse in order insert into a SQL database. Each record spans multiple lines and consists of about a hundred fixed-length fields. I am trying to figure out how to efficiently parse them without loading the en...
Efficiently parsing a large text file in Python?
I have a series of large, flat text files that I need to parse in order insert into a SQL database. Each record spans multiple lines and consists of about a hundred fixed-length fields. I am trying to figure out how to efficiently parse them without loading the entire file into memory. Each record starts with a numer...
[ "def recordsFromFile(inputFile):\n record = ''\n terminator = ' ' * 20\n for line in inputFile:\n if line.startswith('1') and record.endswith(terminator):\n yield record\n record = ''\n record += line\n yield record\n\ninputFile = open('test.txt')\nfor record in recor...
[ 3 ]
[]
[]
[ "file_io", "python", "text_processing" ]
stackoverflow_0008131197_file_io_python_text_processing.txt
Q: reading fortran unformatted file with python I have a fortran program generating unformatted files and I am trying to read them into Python. I have the source code so I know the first "chunk" is a character array of character*1 name(80) and so on. So I start out with f = open(filename,'rb') bytes = 80 name = struc...
reading fortran unformatted file with python
I have a fortran program generating unformatted files and I am trying to read them into Python. I have the source code so I know the first "chunk" is a character array of character*1 name(80) and so on. So I start out with f = open(filename,'rb') bytes = 80 name = struct.unpack('c'*bytes,f.read(bytes)) and name is an ...
[ "Most Fortran unformatted files will contain extra bytes to specify the length of the record. A record is the group of items written with a single Fortran write statement. Typically 4-bytes at the beginning and end of each record. So in another language you will want to read these \"hidden\" values and skip them...
[ 6, 2 ]
[]
[]
[ "ascii", "fortran", "python" ]
stackoverflow_0008131204_ascii_fortran_python.txt
Q: Regex and csv issues in python 2.7 Used the following to fix the problems (for the remaining issues, will change my code around). Sorry for the improper code format in my initial post. import csv, re, mechanize htmlML = br.response().read() #escaping ? fixed the regex match patMemberName = re.compile('<a hr...
Regex and csv issues in python 2.7
Used the following to fix the problems (for the remaining issues, will change my code around). Sorry for the improper code format in my initial post. import csv, re, mechanize htmlML = br.response().read() #escaping ? fixed the regex match patMemberName = re.compile('<a href=/foo.php\?XID=(d+) ><font color=#0000...
[ "Unfortunately, I can't find the proper escape sequence for Python right now. Generally, you would wrap an expression with meta-characters that should not be interpreted in \"\\Q...\\E\".\nTry wrapping your string in re.escape(string). So:\nre.compile(re.escape('<font color=#000000><b>(.*)</b>'))\n\n", "For quest...
[ 0, -1 ]
[]
[]
[ "csv", "python", "regex", "screen_scraping" ]
stackoverflow_0008131297_csv_python_regex_screen_scraping.txt
Q: Alternate error and no-error in python interactive mode With file xx.py: class Foo(object): def __init__(self, x): self.x = x def __long__(self): return long(self.x) def __float__(self): return float(self.x) y = Foo(22) print '%d' % y print '%d' % y Interactive mode: $ pyth...
Alternate error and no-error in python interactive mode
With file xx.py: class Foo(object): def __init__(self, x): self.x = x def __long__(self): return long(self.x) def __float__(self): return float(self.x) y = Foo(22) print '%d' % y print '%d' % y Interactive mode: $ python -V Python 2.6.7 $ python -i xx.py 22 22 >>> TypeError:...
[ "Looks like a bug in python! My guess is it's caused by some leftover cruft from the old string-based exceptions. \nThe hexadecimal stuff is a red herring, you can also get strange behaviour with simply assigning y = Foo(1) and just using '%d' % y will exhibit the funny toggling stuff. \nYou should get an TypeErr...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008130826_python.txt
Q: Django with wsgi sporadically fails with "Premature end of script headers:" I have a site that is running for months now on Apache2 and periodically it will just hiccup with the following: [Sat Nov 12 06:18:34 2011] [error] [client X.Y.Z.158] Premature end of script headers: sleepsoundly_wsgi.py [Sat Nov 12 06:18...
Django with wsgi sporadically fails with "Premature end of script headers:"
I have a site that is running for months now on Apache2 and periodically it will just hiccup with the following: [Sat Nov 12 06:18:34 2011] [error] [client X.Y.Z.158] Premature end of script headers: sleepsoundly_wsgi.py [Sat Nov 12 06:18:49 2011] [error] [client X.Y.Z.158] Premature end of script headers: sleepsoundl...
[ "The problem is likely because you have 'maximum-requests' set to 500. This will cause the mod_wsgi daemon processes to be restarted periodically. Since the mod_wsgi daemon processes are running in multithreaded configuration, if there was a stuck request, or long running request which doesn't finish before the for...
[ 5 ]
[]
[]
[ "django", "mod_wsgi", "python" ]
stackoverflow_0008125980_django_mod_wsgi_python.txt
Q: I have multiple lists within one big list. i need to make all of the values on the inside list besides [0] into a list of floats with open('MONTHLY.txt') as file_string: line_list = [] txt_list = [] key_list = [] value_list = [] for line in file_string: line = line.strip() txt_list.append(line) for num in...
I have multiple lists within one big list. i need to make all of the values on the inside list besides [0] into a list of floats
with open('MONTHLY.txt') as file_string: line_list = [] txt_list = [] key_list = [] value_list = [] for line in file_string: line = line.strip() txt_list.append(line) for num in txt_list: num = num.split() line_list.append(num) for i in line_list[4:267]: i = int(i[0]) key_list.append(i) for i i...
[ "I think Julio has given an answer along the right path, but it's kind of lambda- and map-heavy. Especially the second lambda is unnecessary...lambda y: float(y) is a no-op.\nHere's (I think) a more concise and readable way to do it:\n>>> my_list = [['11.5','4.4'],['5.7','7.6']]\n>>> [map(float, x) for x in my_lis...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008131328_python.txt
Q: character encoding of fortran unformatted files? I am reading in a fortran unformatted file. If I use Python to read them in, import struct f = open(filename,'r') values = struct.unpack('%20s',f.read(20)) I get characters like \xf8, \xbf, \xad, \xe8, \xd8, \xec, \xd5, \x10, \xfd, \xbf and so on. Each of these are...
character encoding of fortran unformatted files?
I am reading in a fortran unformatted file. If I use Python to read them in, import struct f = open(filename,'r') values = struct.unpack('%20s',f.read(20)) I get characters like \xf8, \xbf, \xad, \xe8, \xd8, \xec, \xd5, \x10, \xfd, \xbf and so on. Each of these are of length one and string replacement functions do not...
[ "Do you have any information on how the file was written, i.e. what Fortran write statements were used? If not, you'll just be guessing. Keep in mind that unformatted records normally contain binary data, such as integers or floating point numbers, and normally not encoded character data. My guess is you are loo...
[ 2 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0008131491_character_encoding_python.txt
Q: python - string vs list types and NoneType Why does this evaluate to type string: >>> strng = 'spam' >>> type(strng.replace('a', 'A')) >>> <type 'str'> but this evaluates to type NoneType? >>> list_a = ['spam'] >>> type(list_a.append('eggs')) >>> <type 'NoneType'> A: Because the append method on the list retu...
python - string vs list types and NoneType
Why does this evaluate to type string: >>> strng = 'spam' >>> type(strng.replace('a', 'A')) >>> <type 'str'> but this evaluates to type NoneType? >>> list_a = ['spam'] >>> type(list_a.append('eggs')) >>> <type 'NoneType'>
[ "Because the append method on the list returns a None (or, said another way... doesn't return anything), as it mutates the list.\nMost, if not all, mutating methods in python's standard library act this way.\nreplace on the string, does not mutate, as python strings are immutable. A new string is returned with the...
[ 6, 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008131702_python.txt
Q: Code assist for Python on xCode Is there a way to get code assist (code completion) to work with Python on xCode? In other words, when I start typing eat_food(, I want xCode to tell me what the first argument for the function "eat_food" is so I won't have to search my project for the function signature. A: Pytho...
Code assist for Python on xCode
Is there a way to get code assist (code completion) to work with Python on xCode? In other words, when I start typing eat_food(, I want xCode to tell me what the first argument for the function "eat_food" is so I won't have to search my project for the function signature.
[ "Python and all other dynamic languages are notoriously hard to write comprehensive code completion for. The compiler doesn't even know what types and other things about dynamic code, so the IDE isn't going to either. Komodo does one of the best jobs at code completion for dynamic languages like Python, but even it...
[ 6 ]
[]
[]
[ "python", "xcode" ]
stackoverflow_0008131639_python_xcode.txt
Q: Fetching URL with proxy in between I am using urllib2 to obtain any site. Normally while browsing there is a script that is configured in browser i.e there is a link to the location of that script given in tools->internet options->connections->lan settings How do I incorporate that, without that script the pages...
Fetching URL with proxy in between
I am using urllib2 to obtain any site. Normally while browsing there is a script that is configured in browser i.e there is a link to the location of that script given in tools->internet options->connections->lan settings How do I incorporate that, without that script the pages arent fetched. I also tried this Proxy ...
[ "You need to set the http_proxy variable, syntax of which is:\nHTTP_PROXY=http://user:password@proxy.example.com:port/\nIn Windows, right click on My Computer > Properties > Advanced > Environment Variables\nYou will see user variables and system variables. System variables are universal (will work for any logged i...
[ 0 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0008130385_python_urllib2.txt
Q: How to slice a string in Python using a dictionary containing character positions? I have a dictionary containing the character positions of different fields in a string. I'd like to use that information to slice the string. I'm not really sure how to best explain this, but the example should make it clear: inpu...
How to slice a string in Python using a dictionary containing character positions?
I have a dictionary containing the character positions of different fields in a string. I'd like to use that information to slice the string. I'm not really sure how to best explain this, but the example should make it clear: input: mappings = {'name': (0,4), 'job': (4,11), 'color': (11, 15)} data = "JohnChemistBlue"...
[ ">>> dict((f, data[slice(*p)]) for f, p in mappings.iteritems())\n{'color': 'Blue', 'job': 'Chemist', 'name': 'John'}\n\n", "dict([(name, data[range[0]:range[1]]) for name, range in mappings.iteritems()])\n\n", ">>> dict([(k, data[ mappings[k][0]:mappings[k][1] ]) for k in mappings])\n{'color': 'Blue', 'job': '...
[ 10, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0008132332_python.txt
Q: Zeromq with python hangs if connecting to invalid socket If I connect to an inexistent socket with pyzmq I need to hit CTRL_C to stop the program. Could someone explay why this happens? import zmq INVALID_ADDR = 'ipc:///tmp/idontexist.socket' context = zmq.Context() socket = context.socket(zmq.REQ) socket.conne...
Zeromq with python hangs if connecting to invalid socket
If I connect to an inexistent socket with pyzmq I need to hit CTRL_C to stop the program. Could someone explay why this happens? import zmq INVALID_ADDR = 'ipc:///tmp/idontexist.socket' context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect(INVALID_ADDR) socket.send('hello') poller = zmq.Poller() p...
[ "This question was also posted as a pyzmq Issue on GitHub. I will paraphrase my explanation here (I hope that is appropriate, I am fairly new to SO):\nA general rule: When in doubt, hangs at the end of your zeromq program are due to LINGER.\nThe hang here is caused by the LINGER socket option, and happens in the c...
[ 10, 0 ]
[]
[]
[ "python", "zeromq" ]
stackoverflow_0007939977_python_zeromq.txt
Q: How do you debug win32 com integration from Python? I'm trying to call the text to speech API from Python using win32com.client. The Python interpreter is bundled with Splunk and I'm able to invoke it manually using "splunk cmd python". Here's a sample from win32com.client import constants import win32com.client s...
How do you debug win32 com integration from Python?
I'm trying to call the text to speech API from Python using win32com.client. The Python interpreter is bundled with Splunk and I'm able to invoke it manually using "splunk cmd python". Here's a sample from win32com.client import constants import win32com.client speaker = win32com.client.Dispatch("SAPI.SpVoice") speaker...
[ "The application runs as expected when launched as a normal user. The parent process runs as system, which fails to invoke the TTS.\n" ]
[ 0 ]
[]
[]
[ "python", "pywin32", "win32com" ]
stackoverflow_0007565789_python_pywin32_win32com.txt
Q: "self" in python lambda expression def buildTestCase(xmlfile, description, method, evalString): func = lambda self, xmlfile=xmlfile, method=method, evalString=evalString: \ method(self, evalString, feedparser.parse(xmlfile)) func.__doc__ = description return func Above is a code snippet from feedpa...
"self" in python lambda expression
def buildTestCase(xmlfile, description, method, evalString): func = lambda self, xmlfile=xmlfile, method=method, evalString=evalString: \ method(self, evalString, feedparser.parse(xmlfile)) func.__doc__ = description return func Above is a code snippet from feedparser, why there is a "self" in function ...
[ "selfsimply refers to the first argument of the lambda named self. \nthe name self is not a reserved keyword, it is merely a convention above pythonistas to name the instance of the object on which the function applies. here, the author uses the name self as the first argument to the lambda, because this argument w...
[ 7, 3, 2 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0008132619_lambda_python.txt
Q: Working with different projects in eclipse I program in conjunction Eclipse(4 javascript) & PyDev. For example in one project, I opened 5 tabs with different files. Now I need to work with another project, but I do not want to then return to the previous draft to look over all the necessary files and open them ag...
Working with different projects in eclipse
I program in conjunction Eclipse(4 javascript) & PyDev. For example in one project, I opened 5 tabs with different files. Now I need to work with another project, but I do not want to then return to the previous draft to look over all the necessary files and open them again, with close existing ones. How easy is it to...
[ "What I understand is, that you want to stay focused on the work you are doing at the moment. And you have different contexts you want to switch between. There are at least three options to go with:\n\nUse different workspaces (with the same Eclipse installation). This is useful if there is no overlap between the 2...
[ 2, 1 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0008132559_eclipse_pydev_python.txt
Q: Straight LXML or PyQuery Does anyone have experience scraping with straight lxml vs. PyQuery. I just came across the latter recently and was intrigued. I haven't been able to find many comments about the library just yet, so I'm curious as to how robust it is. I'm familiar with lxml and generally enjoy it. It w...
Straight LXML or PyQuery
Does anyone have experience scraping with straight lxml vs. PyQuery. I just came across the latter recently and was intrigued. I haven't been able to find many comments about the library just yet, so I'm curious as to how robust it is. I'm familiar with lxml and generally enjoy it. It would be nice, however, to use ...
[ "lxml supports XPath, which is similar to CSS selectors. \nWould that meet your needs?\n", "Only you can answer the question of whether it's worth it.\nIt simply depends on whether you want to use an extra dependency in order to get jQuery's custom CSS selectors.\nHere are the things jQuery adds on top of the sta...
[ 4, 3 ]
[]
[]
[ "jquery", "lxml", "pyquery", "python", "screen_scraping" ]
stackoverflow_0008129838_jquery_lxml_pyquery_python_screen_scraping.txt
Q: Translate Window BAT (batch) file into Python script I have a Window .bat file with DOS commands that involve REM, MKDIR, ECHO, run some programs, and especially combining all the output into a log file with time stamps. I want to translate this into Python. I tried os.system but this will not work - it will run ...
Translate Window BAT (batch) file into Python script
I have a Window .bat file with DOS commands that involve REM, MKDIR, ECHO, run some programs, and especially combining all the output into a log file with time stamps. I want to translate this into Python. I tried os.system but this will not work - it will run the programs I need to run, but there is no way to connect...
[ "You should probably be using the subprocess module to invoke your executables. It allows you to specify things like the input and output handles for the process, so you can direct them to where you want.\n" ]
[ 3 ]
[]
[]
[ "batch_file", "dos", "python" ]
stackoverflow_0008132878_batch_file_dos_python.txt
Q: What is an efficient way to erase substrings? I have a long string and a list of [end-index, string] like the following: long_sentence = "This is a long long long long sentence" indices = [[6, "is"], [8, "is a"], [18, "long"], [23, "long"]] An element 6, "is" indicates that 6 is the end index of the word "is" in ...
What is an efficient way to erase substrings?
I have a long string and a list of [end-index, string] like the following: long_sentence = "This is a long long long long sentence" indices = [[6, "is"], [8, "is a"], [18, "long"], [23, "long"]] An element 6, "is" indicates that 6 is the end index of the word "is" in the string. I want to get the following string in t...
[ "Each time you do that temp = temp... assignment, Python has to create a new string (because Python strings are immutable).\nWhat you might want to do instead is turn the string into a list of characters, then operate on the list of characters, and then join that list back together into a string again.\nlong_list =...
[ 3, 3, 3, 3 ]
[]
[]
[ "python", "string", "text" ]
stackoverflow_0008132955_python_string_text.txt
Q: What is the difference between django classonlymethod and python classmethod? Why is there a need for Django to introduce the decorator classonlymethod ? Why can't it reuse python classmethod? A: The best explanation is the source code itself: class classonlymethod(classmethod): def __get__(self, instance, c...
What is the difference between django classonlymethod and python classmethod?
Why is there a need for Django to introduce the decorator classonlymethod ? Why can't it reuse python classmethod?
[ "The best explanation is the source code itself:\nclass classonlymethod(classmethod):\n def __get__(self, instance, cls=None):\n if instance is not None:\n raise AttributeError(\"This method is available only on the class, not on instances.\")\n return super().__get__(instance, cls)\n\nT...
[ 54 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008133312_django_python.txt