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: Check substring match of a word in a list of words I want to check if a word is in a list of words. word = "with" word_list = ["without", "bla", "foo", "bar"] I tried if word in set(list), but it is not yielding the wanted result due to the fact in is matching string rather than item. That is to say, "with" is a ...
Check substring match of a word in a list of words
I want to check if a word is in a list of words. word = "with" word_list = ["without", "bla", "foo", "bar"] I tried if word in set(list), but it is not yielding the wanted result due to the fact in is matching string rather than item. That is to say, "with" is a match in any of the words in the word_list but still if ...
[ "You could do:\nfound = any(word in item for item in wordlist)\n\nIt checks each word for a match and returns true if any are matches\n", "in is working as expected for an exact match:\n>>> word = \"with\"\n>>> mylist = [\"without\", \"bla\", \"foo\", \"bar\"]\n>>> word in mylist\nFalse\n>>> \n\nYou can also use:...
[ 9, 3, 0 ]
[]
[]
[ "python", "string_matching", "substring" ]
stackoverflow_0008275417_python_string_matching_substring.txt
Q: I don't see the error here: python Possible Duplicate: IndentationError: unindent does not match any outer indentation level This is my code that I have looked through for a couple of hours. It may be a python bug for Lion. I am using python 2.7. import os, pygame from pygame.locals import * import spritesheet i...
I don't see the error here: python
Possible Duplicate: IndentationError: unindent does not match any outer indentation level This is my code that I have looked through for a couple of hours. It may be a python bug for Lion. I am using python 2.7. import os, pygame from pygame.locals import * import spritesheet import sound from map import Level level...
[ "Make sure you are not mixing tabs and spaces for indentation. It is possible that your editor may think your tab stop is one value (4?), and the python interpreter some other value; if some of your lines are then indented with spaces, and other lines with tabs, your editor will show things as lining up when the py...
[ 5, 1 ]
[]
[]
[ "indentation", "python" ]
stackoverflow_0008275654_indentation_python.txt
Q: Warnings from caller's perspective (aka Python-equivalent of Perl's carp)? Short version: Is there way to achieve in Python the same effect achieved by Perl's Carp::carp utility? Long version (for those unfamiliar with Carp::carp): Suppose we are implementing some library API function (i.e., it is meant to be us...
Warnings from caller's perspective (aka Python-equivalent of Perl's carp)?
Short version: Is there way to achieve in Python the same effect achieved by Perl's Carp::carp utility? Long version (for those unfamiliar with Carp::carp): Suppose we are implementing some library API function (i.e., it is meant to be used by other programmers in their code), say spam, and suppose that spam includes...
[ "This is really just a matter of convention, exception handling in python is designed to be used heavily (beg forgiveness rather than ask permission). And given that you're working in a different language space, you want to follow those conventions - ie/ you really do want to let developers know where the site of t...
[ 2, 1, 1 ]
[]
[]
[ "callstack", "python", "stack_trace" ]
stackoverflow_0008275745_callstack_python_stack_trace.txt
Q: Qt menu shortcuts preempt child widget KeyPressEvents I have a main window in which I establish the standard Edit > Cut/Copy/Paste actions, with the menu actions linked to the relevant slots of a QTextEdit which is a child of the main window. The main window has a different child (on the other side of a splitter) ...
Qt menu shortcuts preempt child widget KeyPressEvents
I have a main window in which I establish the standard Edit > Cut/Copy/Paste actions, with the menu actions linked to the relevant slots of a QTextEdit which is a child of the main window. The main window has a different child (on the other side of a splitter) which displays a TableView. This widget has focus policy of...
[ "When the edit actions are created, give them a WidgetShortcut context and add them to the widget(s) they are to be associated with:\ncopyAction.setShortcutContext(Qt.WidgetShortcut)\neditor.addAction(copyAction)\n\nNote that the shortcuts of actions configured in this way won't override any of the built-in shortcu...
[ 1 ]
[]
[]
[ "keyboard_shortcuts", "pyqt", "python" ]
stackoverflow_0008275276_keyboard_shortcuts_pyqt_python.txt
Q: building a matrix composed of alternative object in python I'm fairly new to python and I am currently making use of the numPy library along with pyinterval library. I want to build a matrix that isn't composed of floats, but intervals. however if I do the following: A = [[interval([2,3]), interval([0,1]), interva...
building a matrix composed of alternative object in python
I'm fairly new to python and I am currently making use of the numPy library along with pyinterval library. I want to build a matrix that isn't composed of floats, but intervals. however if I do the following: A = [[interval([2,3]), interval([0,1]), interval([1,2]), interval([2,3])]] m = np.matrix(A,interval) it gives ...
[ "From the docs regarding dtype syntax:\n\neach type specifier can be prefixed with a repetition number, or a\n shape. In these cases an array element is created, i.e., an array\n within a record. That array is still referred to as a single field.\n\nSo to specify it as one item in the array, you might try setting...
[ 3 ]
[]
[]
[ "arrays", "matrix", "numpy", "python" ]
stackoverflow_0008275746_arrays_matrix_numpy_python.txt
Q: Writing variable from list individually in table with corresponding value from other variable Ok, the code I have is the following: for shidx in xrange(0, book.nsheets): print shidx sheet = book.sheet_by_index(shidx) d = sheet.col_values(0,2) D = sheet.col_values(1,2) dim = sheet.row_values(0,2) if shidx == 0: ...
Writing variable from list individually in table with corresponding value from other variable
Ok, the code I have is the following: for shidx in xrange(0, book.nsheets): print shidx sheet = book.sheet_by_index(shidx) d = sheet.col_values(0,2) D = sheet.col_values(1,2) dim = sheet.row_values(0,2) if shidx == 0: #numLine = sheet.row_values(2) rs = sheet.col_values(6,2) for i in range(4): BB = ...
[ "Your requirement is eventually ascertainable after multiple readings. However your code has several problems:\nThe indentation as displayed is botched. Presumably you are using tabs in your editor. Don't do that with Python source files. Set it up to use 4 spaces per indent level.\nYou are iterating over sheets bu...
[ 0 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0008270524_python_xlrd.txt
Q: Inverted fancy indexing Having an array and a mask for this array, using fancy indexing, it is easy to select only the data of the array corresponding to the mask. import numpy as np a = np.arange(20).reshape(4, 5) mask = [0, 2] data = a[:, mask] But is there a rapid way to select all the data of the array that ...
Inverted fancy indexing
Having an array and a mask for this array, using fancy indexing, it is easy to select only the data of the array corresponding to the mask. import numpy as np a = np.arange(20).reshape(4, 5) mask = [0, 2] data = a[:, mask] But is there a rapid way to select all the data of the array that does not belong to the mask (...
[ "Have a look at numpy.invert, numpy.bitwise_not, numpy.logical_not, or more concisely ~mask. (They all do the same thing, in this case.)\nAs a quick example:\nimport numpy as np\n\nx = np.arange(10)\nmask = x > 5\n\nprint x[mask]\nprint x[~mask]\n\n" ]
[ 9 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0008275857_numpy_python_scipy.txt
Q: Create a list (of tuples?) from two lists of different sizes I am stuck trying to perform this task and while trying I can't help thinking there will be a nicer way to code it than the way I have been trying. I have a line of text and a keyword. I want to make a new list going down each character in each list. The...
Create a list (of tuples?) from two lists of different sizes
I am stuck trying to perform this task and while trying I can't help thinking there will be a nicer way to code it than the way I have been trying. I have a line of text and a keyword. I want to make a new list going down each character in each list. The keyword will just repeat itself until the end of the list. If the...
[ "You've got two questions mashed into one. The first is: how do you remove non-alphanumeric chars from a string? You can do it a few ways, but regular expression substitution is a nice way.\nimport re\n\ndef removeWhitespace( s ):\n return re.sub( '\\s', '', s )\n\nThe second part of the question is about how to...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008275650_python.txt
Q: What's the right way to pass a var to a Python unittest TestCase and/or TestSuite? I need to run a Python unittest test suite against multiple REST backend resources so I need to pass in a Resource object to the test suite and individual testcases. Is setting a global var the right way to do this, or is there a be...
What's the right way to pass a var to a Python unittest TestCase and/or TestSuite?
I need to run a Python unittest test suite against multiple REST backend resources so I need to pass in a Resource object to the test suite and individual testcases. Is setting a global var the right way to do this, or is there a better way? resource = Resource('http://example.com') class RestTestCase(unittest.TestCase...
[ "Follow the example of the how the standard library writes its own unittests. Put the resource in a class variable and use inheritance to test the various resources:\nclass RestTestCase(unittest.TestCase):\n resource = Resource('http://example.com')\n\n def sometest(self):\n r = self.resource\n ...
[ 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0008276310_python_unit_testing.txt
Q: Vim failing to compile with python on OS X I've been trying to compile vim 7.3 with python 2.7 support on mac OS X 10.6. Vim itself compiles fine, but the embedded python not so much. The steps I've taken: hg clone https:/vim.googlecode.com/hg/ vim cd vim/src ./configure --without-x --disable-gui --disable-darwi...
Vim failing to compile with python on OS X
I've been trying to compile vim 7.3 with python 2.7 support on mac OS X 10.6. Vim itself compiles fine, but the embedded python not so much. The steps I've taken: hg clone https:/vim.googlecode.com/hg/ vim cd vim/src ./configure --without-x --disable-gui --disable-darwin \ --enable-pythoninterp --with-fea...
[ "Turns out the bug is actually in the Python Makefile, believe it or not.\nOpen the file\n/usr/local/Cellar/python/2.7.2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config\n\nor whatever the appropriate path is for you, and search for PyMac_Error. It should be on the line defining LINKFORSHARED, and on t...
[ 7, 2, 0 ]
[]
[]
[ "compilation", "macos", "python", "vim" ]
stackoverflow_0006490513_compilation_macos_python_vim.txt
Q: Year Out Of Range In Python? I have an Open Source application installed on my system, designed in python, now I am trying to insert a date older then 1900, it results in an error **Year Out Of Range** Now I am thinking to resolve it so that it will allow me to store any date from 1000 - 9999 years. Is this error ...
Year Out Of Range In Python?
I have an Open Source application installed on my system, designed in python, now I am trying to insert a date older then 1900, it results in an error **Year Out Of Range** Now I am thinking to resolve it so that it will allow me to store any date from 1000 - 9999 years. Is this error due to python or because of my app...
[ "This is a reported python bug. A patch is available at that address. \n" ]
[ 4 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0008276578_cherrypy_python.txt
Q: python: functions in class scope I am just playing around with the language, but wonder if it is possible to use functions defined within a scope of the class without explicitly defining self as the first argument. I understand the "proper" way to implement a class might be class minimal: variable = 1 ...
python: functions in class scope
I am just playing around with the language, but wonder if it is possible to use functions defined within a scope of the class without explicitly defining self as the first argument. I understand the "proper" way to implement a class might be class minimal: variable = 1 def add(self,x,y): return x+y ...
[ "Yes, but don't.\n", "The name of the first argument is arbitrary. The object is always passed as the first argument. When you declare add, the object will be passed as x. When you call self.add(x,self.variable), self is bound to x in add, x in __init__ is bound to y in add and self.variable is passed as a third...
[ 4, 4, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0008276610_oop_python.txt
Q: how to consult the base class of a class Recently i am learning something about unicode in python2.7, and i want to know something about the base class of str, unicode, basestring, etc. and the relations of them, but i can't find a proper way to look up the base class of them expect read the source code. e.g. clas...
how to consult the base class of a class
Recently i am learning something about unicode in python2.7, and i want to know something about the base class of str, unicode, basestring, etc. and the relations of them, but i can't find a proper way to look up the base class of them expect read the source code. e.g. class child(A): pass How can i know the base ...
[ "You're looking for child.__bases__. A Python class can have multiple base classes.\n>>> child.__bases__\n(<class __main__.A at 0x10052f0b8>,)\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008276751_python.txt
Q: How to run a module developed in Eclipse in a Python interactive prompt? Complete noob here wanting to learn Python. I installed Python, then Eclipse, then PyDev. Works great. I created a couple of simple programs in Eclipse and they run fine there. Now at the command prompt, I run python.exe and an interact...
How to run a module developed in Eclipse in a Python interactive prompt?
Complete noob here wanting to learn Python. I installed Python, then Eclipse, then PyDev. Works great. I created a couple of simple programs in Eclipse and they run fine there. Now at the command prompt, I run python.exe and an interactive prompt opens. How do I now run the foo.py module I developed earlier in E...
[ "tu run this you have to run \npython foo.py\n\nor as matijun said. if you want to import it:\n>>> import foo \n\nor \n>>>from foo import *\n\nPlease note that your file path shuold be in PYTHONPATH.\nTo do this \nimport sys\nsys.path.add(\"ur file path\")\nimport foo\n\n", "You have to run\npython.exe foo.py\n\...
[ 3, 1 ]
[]
[]
[ "eclipse", "pydev", "python", "python_3.x" ]
stackoverflow_0008276788_eclipse_pydev_python_python_3.x.txt
Q: escaping the double quotes in python string I've a question about double quotes escaping in python string formatting. for example, print "How tall are you?", height = raw_input() print "So you are %r tall" % height when I put 5" 6' , it returns ' 5\'6" ' and i don't get why there is a backslash. A...
escaping the double quotes in python string
I've a question about double quotes escaping in python string formatting. for example, print "How tall are you?", height = raw_input() print "So you are %r tall" % height when I put 5" 6' , it returns ' 5\'6" ' and i don't get why there is a backslash.
[ "You're asking for the representation of the string. Since the string contains both types of quotes, one type must be escaped in order for it to be a proper representation. If you only want what was typed then use %s instead.\n" ]
[ 5 ]
[]
[]
[ "escaping", "python" ]
stackoverflow_0008276820_escaping_python.txt
Q: python: Fatal IO error 11 (Resource temporarily unavailable) on X server :0.0 I am trying to read some Images(and later intend to do some task on them), and while Images are being read into memory. I want to display a animated '.gif' Image. For that purpose I had to use Threads. Now it is giving Error : python: Fa...
python: Fatal IO error 11 (Resource temporarily unavailable) on X server :0.0
I am trying to read some Images(and later intend to do some task on them), and while Images are being read into memory. I want to display a animated '.gif' Image. For that purpose I had to use Threads. Now it is giving Error : python: Fatal IO error 11 (Resource temporarily unavailable) on X server :0.0. And some time...
[ "Your code works perfect for me in win7 with wxpython 2.8.12.1 and python 2.6.7 runing on Spe version 0.8.4.i when the images are located in the script directory (I used my own animated gif and a png). \nThe only change I needed was to import animate (from wx import animate) in addition to wx and use\nshowclock = a...
[ 3, 3 ]
[]
[]
[ "animated_gif", "multithreading", "python", "wxpython" ]
stackoverflow_0008275187_animated_gif_multithreading_python_wxpython.txt
Q: Windows XP to Ubuntu Linux point-to-point communication using Python or C/C++ I need to know if I can connect 2 PCs over Ethernet connection (point to point connection). I have 2 machines (one of them runs on Windows XP and the other runs on Ubuntu Linux 10.10) and I need to have connection between them. Will be p...
Windows XP to Ubuntu Linux point-to-point communication using Python or C/C++
I need to know if I can connect 2 PCs over Ethernet connection (point to point connection). I have 2 machines (one of them runs on Windows XP and the other runs on Ubuntu Linux 10.10) and I need to have connection between them. Will be possible to have connection between them ? The suggested language is either Python o...
[ "On the Linux side, you want to learn more about networking system calls like socket, connect, listen, accept, recv, send, poll, etc. Read also about tcp. \nI strongly suggest reading a good book like e.g. advanced unix programming here. There are a lot of good material on the web, e.g. this tutorial\nI know nothin...
[ 1, 0 ]
[]
[]
[ "c++", "labview", "linux", "python", "windows_xp" ]
stackoverflow_0008261046_c++_labview_linux_python_windows_xp.txt
Q: Analyze a video, look for a colored pixel or logo I want to sift through a collection of video files looking for a certain logo, and then record the 10-15 seconds leading up to it. I can recognize the logo by checking a certain pixel color. How would you do it? Is there software or a python package that allows me ...
Analyze a video, look for a colored pixel or logo
I want to sift through a collection of video files looking for a certain logo, and then record the 10-15 seconds leading up to it. I can recognize the logo by checking a certain pixel color. How would you do it? Is there software or a python package that allows me to extract those chunks of files and write those into a...
[ "Using perhaps OpenCV or another package -- essentially, you want to train a classifier to identify your logo and then feed it the bitmaps from your video. When it identifies the logo, then you trigger the code which captures the previous 15s of video.\nThis is a very detailed answer about how one might do this in ...
[ 1 ]
[]
[]
[ "python", "video_processing" ]
stackoverflow_0008258981_python_video_processing.txt
Q: python multiprocessing lock issue I want to add a list of dicts together with python multiprocessing module. Here is a simplified version of my code: #!/usr/bin/python2.7 # -*- coding: utf-8 -*- import multiprocessing import functools import time def merge(lock, d1, d2): time.sleep(5) # some time consuming s...
python multiprocessing lock issue
I want to add a list of dicts together with python multiprocessing module. Here is a simplified version of my code: #!/usr/bin/python2.7 # -*- coding: utf-8 -*- import multiprocessing import functools import time def merge(lock, d1, d2): time.sleep(5) # some time consuming stuffs with lock: for key in...
[ "The following should run cross-platform (i.e. on Windows, too) in both Python 2 and 3. It uses a process pool initializer to set the manager dict as a global in each child process. \nFYI:\n\nUsing a lock is unnecessary with a manager dict. \nThe number of processes in a Pool defaults to the CPU count. \nIf you're ...
[ 12 ]
[]
[]
[ "locking", "multiprocessing", "python" ]
stackoverflow_0008276933_locking_multiprocessing_python.txt
Q: Processing multiple checkbox in HTML I am not an expert with HTML and JavaScript. But here is what I am trying to do. I have creating an HTML/jQuery/JS/CSS script. The HTML file lists the number of files in the tabular form ( The number is not fixed) and I have checkboxes for each of the file. The user can select ...
Processing multiple checkbox in HTML
I am not an expert with HTML and JavaScript. But here is what I am trying to do. I have creating an HTML/jQuery/JS/CSS script. The HTML file lists the number of files in the tabular form ( The number is not fixed) and I have checkboxes for each of the file. The user can select one or more files to be deleted and click ...
[ "In jQuery you can get the input checkbox checked list by using the following code:\n$('input:checked').each(function(i){\nval[i] = $(this).val();\n}\n\nHere val[i] contains the array i.e., checked checkbox list so pass this array data to server-side code to delete from server.Hope this helps you :-)\nEDIT:\nOnce c...
[ 1, 0 ]
[]
[]
[ "checkbox", "html", "javascript", "jquery", "python" ]
stackoverflow_0008277127_checkbox_html_javascript_jquery_python.txt
Q: how does python2.7 deal with unicode? I am more and more confused in linux, I opened terminal and input python2.7 and then input the codes as follows: >>> s = u'\u0561' >>> print s ա >>> len(s) 1 the length of u'\u0561' is only 1? Why?I learned that every non-alphabet character's length is 2~4 byte in unicode, wh...
how does python2.7 deal with unicode? I am more and more confused
in linux, I opened terminal and input python2.7 and then input the codes as follows: >>> s = u'\u0561' >>> print s ա >>> len(s) 1 the length of u'\u0561' is only 1? Why?I learned that every non-alphabet character's length is 2~4 byte in unicode, why does it use only 1 byte? and i test other unicode characters, i found...
[ "The len function doesn't count the number of bytes - it count the number of items in any sequence (in this case, the number of characters in the string).\n", "\nthe length of u'\\u0561' is only 1? Why?\n\nBecause ա is one character.\nIn other words, for the same reason that the len() of ['hi mom this is an incre...
[ 7, 1, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0008277114_python_unicode.txt
Q: Unicode in Python In Python 2.7's documentation, three rules about Unicode are described as follows: If the code point is <128, it’s represented by the corresponding byte value. If the code point is between 128 and 0x7ff, it’s turned into two byte values between 128 and 255. Code points >0x7ff are turned into thr...
Unicode in Python
In Python 2.7's documentation, three rules about Unicode are described as follows: If the code point is <128, it’s represented by the corresponding byte value. If the code point is between 128 and 0x7ff, it’s turned into two byte values between 128 and 255. Code points >0x7ff are turned into three- or four-byte sequen...
[ "\nin python2.7's documentation, three rules about unicodes are described as follows:\n\nThat is a description of the UTF-8 encoding.\n\nThen I made some tests about it:\n\n\\ua000 is an escape sequence representing a Unicode character. The a000 is a hexadecimal representation of the numerical code point value. It ...
[ 5, 3, 2 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0008277277_python_unicode.txt
Q: Dynamically add methods to a class in Python 3.0 I'm trying to write a Database Abstraction Layer in Python which lets you construct SQL statments using chained function calls such as: results = db.search("book") .author("J. K. Rowling") .price("<40.00") .title("Harry") .exe...
Dynamically add methods to a class in Python 3.0
I'm trying to write a Database Abstraction Layer in Python which lets you construct SQL statments using chained function calls such as: results = db.search("book") .author("J. K. Rowling") .price("<40.00") .title("Harry") .execute() but I am running into problems when I try to d...
[ "You can simply add the search functions (methods) after the class is created:\nclass Search: # The class does not include the search methods, at first\n def __init__(self):\n self.conditions = {}\n\ndef make_set_condition(option): # Factory function that generates a \"condition setter\" for \"option\"\...
[ 12, 5, 5 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0008276733_python_python_3.x.txt
Q: (permutation/Anagrm) words find in python 2.72 (need help to find what's wrong with my code) i hope this request is legit. i'm taking a programming course in python for engineers, so i'm kinda new at this business. anyway, in my homework i was requested to write a function with receive two strings and check if one...
(permutation/Anagrm) words find in python 2.72 (need help to find what's wrong with my code)
i hope this request is legit. i'm taking a programming course in python for engineers, so i'm kinda new at this business. anyway, in my homework i was requested to write a function with receive two strings and check if one is a (permutation/Anagrm) of the other. (which means if they both have exactly the same letters a...
[ "It looks like you have a typo with a2_list. That section should read:\ns1_list = [string1[i] for i in range(len(string1))] #creates a list of string 1 letters\ns2_list = [string2[k] for k in range(len(string2))]\ns1_list.sort() #sorting the list\ns2_list.sort()\n\nFWIW, here is an interactive prompt example of h...
[ 5, 0, 0 ]
[]
[]
[ "anagram", "permutation", "python", "word" ]
stackoverflow_0008277144_anagram_permutation_python_word.txt
Q: How to handle a Button click event I'm just learning Python and I have the base concept down, and already a few command line programs. I'm now learning how to create GUIs with Tkinter. I created a simple GUI to accept some user information from a Entry widget, and then, when the user clicks submit, it should pop ...
How to handle a Button click event
I'm just learning Python and I have the base concept down, and already a few command line programs. I'm now learning how to create GUIs with Tkinter. I created a simple GUI to accept some user information from a Entry widget, and then, when the user clicks submit, it should pop up a dialog. The dialog should ask for t...
[ "You already had your event function. Just correct your code to:\n \"\"\"Create Submit Button\"\"\"\n self.submitButton = Button(master, command=self.buttonClick, text=\"Submit\")\n self.submitButton.grid()\n\ndef buttonClick(self):\n \"\"\" handle button click event and output text from entry area\"\"\"...
[ 10, 4, 3 ]
[]
[]
[ "button", "events", "python", "tkinter" ]
stackoverflow_0006874525_button_events_python_tkinter.txt
Q: Globals across modules Wow, this seems so basic, but I can't get it to work. All I need to do is store a global dict which can be accessed and modified from other modules & threads. What's the "best practices" way of achieving this? test.py import testmodule class MyClassA(): def __init__(self, id): s...
Globals across modules
Wow, this seems so basic, but I can't get it to work. All I need to do is store a global dict which can be accessed and modified from other modules & threads. What's the "best practices" way of achieving this? test.py import testmodule class MyClassA(): def __init__(self, id): self.id = id if __name__ == ...
[ "The best practice is not to do this at all.\nThe global keyword is really misnamed - it just means module scope, rather than local. There's no way to have a variable that's in every scope automatically. Instead, define it at the module level in one module and import it wherever you need it.\n", "You can in fact ...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008277516_python.txt
Q: Python code to create link based on the title Can someone please post a python snippet to create a link based on the title, like in stackoverflow (or wordpress)... e.g. title : Global across "Modules" ? corresponding link : http://example.com/8277516/globals-across-modules I do not need any chars other than alpha...
Python code to create link based on the title
Can someone please post a python snippet to create a link based on the title, like in stackoverflow (or wordpress)... e.g. title : Global across "Modules" ? corresponding link : http://example.com/8277516/globals-across-modules I do not need any chars other than alphabets or numbers or '-'. Also i don't need the start...
[ "How about this:\n>>> import re\n>>> s = 'Global across \"Modules\" ?'\n>>> '-'.join(item.lower() for item in re.findall(r'\\w+', s))\n'global-across-modules'\n\nThis works on Python 2; there it will keep only ASCII alphanumeric characters. Under Python 3, it will also keep Unicode alphanumerics, which might not be...
[ 2, 1, 0 ]
[]
[]
[ "python", "web_applications" ]
stackoverflow_0008277736_python_web_applications.txt
Q: django template tag instance hard to word the question so ill go right to the point, i wrote the following template tag def do_simple_tag(parser, token): try: tag_name, name = token.split_contents() except ValueError: raise template.TemplateSyntaxError("%r tag requires exactly one argument"...
django template tag instance
hard to word the question so ill go right to the point, i wrote the following template tag def do_simple_tag(parser, token): try: tag_name, name = token.split_contents() except ValueError: raise template.TemplateSyntaxError("%r tag requires exactly one argument" % token.contents.split()[0]) ...
[ "So i finally solved it, basically in the module that contained the _scan_tag function at the top of the file i was importing the SimpleTagNode class like so \nfrom simple_tag.templatetags.simple_tag import SimpleTagNode\n\nsimple_tag being the name of my app, and also the name of the template file, for some reason...
[ 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0008276937_django_django_templates_python.txt
Q: python's scrapy doesn't seem to get data from all available URLs I'm trying to scrape thesession.org to create a table of how many times each tune has been added to memeber's tunebooks so I can find some popular pieces to learn. I've started with the scrapy tutorial here and am trying to modify it to suit my purpo...
python's scrapy doesn't seem to get data from all available URLs
I'm trying to scrape thesession.org to create a table of how many times each tune has been added to memeber's tunebooks so I can find some popular pieces to learn. I've started with the scrapy tutorial here and am trying to modify it to suit my purposes. The problem is that although the thesession.org website appears t...
[ "You need to add Rule, which will extract links to all pages, and spider will follow it:\nrules = [\n ..., #your existing parse_tune rule\n Rule(\n SgmlLinkExtractor(\n allow=('/index/new\\?new_start=\\d+',)\n ),\n follow=True,\n ),\n]\n\nedit:\nfollow=True is not necessary...
[ 6, 0 ]
[]
[]
[ "python", "scrapy", "screen_scraping", "web_scraping" ]
stackoverflow_0008276845_python_scrapy_screen_scraping_web_scraping.txt
Q: altering the print statement and getting rid of long decimal points I have a print statement in my code which generates the following list. The line is, grp = itertools.groupby(phonemeList, lambda i: i[1] is None) phList = [tuple(i[1]) for i in grp if not i[0]] print "\nsyllable groups separated" print '\n\n'.jo...
altering the print statement and getting rid of long decimal points
I have a print statement in my code which generates the following list. The line is, grp = itertools.groupby(phonemeList, lambda i: i[1] is None) phList = [tuple(i[1]) for i in grp if not i[0]] print "\nsyllable groups separated" print '\n\n'.join(str(l) for l in phList) The output is, syllable groups separated (('p...
[ "Use format strings.\n>>> print \"%.1f\" % 1.234\n1.2\n\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0008278369_python.txt
Q: Creating inmutable types in Python using __new__() My question is pretty simple, I have: class upperstr(str): def __new__(cls, arg): return str.__new__(cls, str(arg).upper()) Why, if my __new__() method is directly using an instance of an inmutable type (str), instances of my new type (upperstr) are m...
Creating inmutable types in Python using __new__()
My question is pretty simple, I have: class upperstr(str): def __new__(cls, arg): return str.__new__(cls, str(arg).upper()) Why, if my __new__() method is directly using an instance of an inmutable type (str), instances of my new type (upperstr) are mutable? >>> s = str("text") >>> "__dict__" in dir(s) Fal...
[ "All user-defined classes in Python have a __dict__() attribute by default, even if you don't overwrite anything at all:\n>>> x = object()\n>>> x.__dict__\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'object' object has no attribute '__dict__'\n>>> class MyObject(obj...
[ 7 ]
[]
[]
[ "datamodel", "python" ]
stackoverflow_0008278425_datamodel_python.txt
Q: simple recursive string replace in python? I'm trying to recursively replace a string with another string in Python. I'm aware of this thread, but coming from other languages I'm amazed — is it really that hard? Is there no way of using a one liner to do this? astring="<li><a href="#Quick Start">Quick Start*</li><...
simple recursive string replace in python?
I'm trying to recursively replace a string with another string in Python. I'm aware of this thread, but coming from other languages I'm amazed — is it really that hard? Is there no way of using a one liner to do this? astring="<li><a href="#Quick Start">Quick Start*</li></li> <li><a href="#Parsing a Document">Parsing a...
[ "There are a few things to note:\n\nThe string is not valid python syntax. It is defined with single double-quotes, yet there are double-quotes within it. Either define the string with single quotes str = 'blah blah' or use triple quotes str = \"\"\"blah blah\"\"\"\nstr is the name of a built-in function. It is goo...
[ 2, 1, 1 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0008278422_python_regex_string.txt
Q: Adding words from a text file to a list (python 2.7) Assuming I have a text file. My goal is to write a function which receives a number of line to go over in the text file and returns a list, each cell in the list containing one word exactly from that line. Any idea of how doing this ? thanks A: If you are work...
Adding words from a text file to a list (python 2.7)
Assuming I have a text file. My goal is to write a function which receives a number of line to go over in the text file and returns a list, each cell in the list containing one word exactly from that line. Any idea of how doing this ? thanks
[ "If you are working with small files:\ndef get_words(mifile, my_line_number):\n with open(mifile) as f:\n lines = f.readlines()\n myline = lines[my_line_number] #first line is 0\n return myline.split()\n\nyou get all the file lines in the list lines. This is not very efficient for VERY bi...
[ 2, 1 ]
[]
[]
[ "lines", "python", "text" ]
stackoverflow_0008279271_lines_python_text.txt
Q: How can I get the default gateway IP with Python? I want to get the IP of the default gateway (internal router IP) using Python. I'm really new to Python so not sure how this works. I know you can get the IP of your machine with: import socket internal_ip = socket.gethostbyname(socket.gethostname()) print interna...
How can I get the default gateway IP with Python?
I want to get the IP of the default gateway (internal router IP) using Python. I'm really new to Python so not sure how this works. I know you can get the IP of your machine with: import socket internal_ip = socket.gethostbyname(socket.gethostname()) print internal_ip So I'm thinking it must be something similar?
[ "On Windows, you should use WMI along with proper query to lookup properties of an object (e.g. network devices). The following Python code prints IPv4 and default gateway addresses on my Windows 7 machine:\nCode:\nimport wmi\n\nwmi_obj = wmi.WMI()\nwmi_sql = \"select IPAddress,DefaultIPGateway from Win32_NetworkAd...
[ 4 ]
[]
[]
[ "ip", "python" ]
stackoverflow_0004904047_ip_python.txt
Q: Why is the http request hanging in my python script? One of my script runs perfectly on an XP system, but the exact script hangs on a 2003 system. I always use mechanize to send the http request, here's an example: import socket, mechanize, urllib, urllib2 socket.setdefaulttimeout(60) #### No idea why it's not wo...
Why is the http request hanging in my python script?
One of my script runs perfectly on an XP system, but the exact script hangs on a 2003 system. I always use mechanize to send the http request, here's an example: import socket, mechanize, urllib, urllib2 socket.setdefaulttimeout(60) #### No idea why it's not working MechBrowser = mechanize.Browser() Header = {'User-A...
[ "You could use Fiddler or Wire Shark to see what is happening at the HTTP-level. \nIt is also worth checking out if the machine has been blocked from making requests to the machine you are trying to access. Use a regular browser (with your own HTML form), and the HTTP library used by Mechanize and see if you can ma...
[ 2 ]
[]
[]
[ "http", "mechanize", "mechanize_python", "python", "urllib2" ]
stackoverflow_0008279380_http_mechanize_mechanize_python_python_urllib2.txt
Q: How to install the pydelicious Python del.icio.us API? I am running Python 2.4 on Windows XP and installed pydelicious API version 0.6. Upon running the install script I get ImportError: No module named etree.ElementTree. How to install it? Which version of the API works with Python 2.4? Where is the documentati...
How to install the pydelicious Python del.icio.us API?
I am running Python 2.4 on Windows XP and installed pydelicious API version 0.6. Upon running the install script I get ImportError: No module named etree.ElementTree. How to install it? Which version of the API works with Python 2.4? Where is the documentation? There is none on the download site http://code.google.co...
[ "ElementTree was not available in the standard Python library until 2.5. It is available, though, as a separate install for 2.4.\nIt looks like the pydelicious authors have even accounted for this. From their sources:\ntry:\n from elementtree.ElementTree import parse as parse_xml\nexcept ImportError:\n # Py...
[ 1 ]
[]
[]
[ "api", "delicious_api", "python", "windows_xp" ]
stackoverflow_0008279707_api_delicious_api_python_windows_xp.txt
Q: setting multiple keys/values into a dictionary (python 2.72) I have a list of strings. I am willing to create a dictionary which its keys are all the strings in the list (each string is a key of course). Now for the values: The value corresponding to each key will be the string which comes next after the key strin...
setting multiple keys/values into a dictionary (python 2.72)
I have a list of strings. I am willing to create a dictionary which its keys are all the strings in the list (each string is a key of course). Now for the values: The value corresponding to each key will be the string which comes next after the key string on the list. The values will be from list type. Remarks: The las...
[ "l = ['today','is','worm','and','dry']\n\nd = {}\nfor w1, w2 in zip(l, l[1:]):\n d.setdefault(w1, []).append(w2)\n\n# d == {'and': ['dry'], 'is': ['worm'], 'today': ['is'], 'worm': ['and']}\n\n", "Try this:\nlst = ['today','is','worm','and','dry']\ndic = {}\n\nfor k in xrange(len(lst) - 1):\n dic[lst[k]] = ...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "key", "list", "python" ]
stackoverflow_0008278954_dictionary_key_list_python.txt
Q: python script written with pygame, accept user input? I made a script with python and pygame. However, I found there are no method in pygame which can provide button or text for giving user input. I just want to make a start, stop, reset button, and with text field floating along the pygame windows to hold user in...
python script written with pygame, accept user input?
I made a script with python and pygame. However, I found there are no method in pygame which can provide button or text for giving user input. I just want to make a start, stop, reset button, and with text field floating along the pygame windows to hold user input before the start of the program. What can I use to take...
[ "I guess that's what you need:\nhttp://www.pygame.org/ftp/contrib/input.html\n" ]
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0008279933_pygame_python.txt
Q: Why is my radix sort python implementation slower than quick sort? I rewrote the original radix sort algorithm for Python from Wikipedia using arrays from SciPy to gain performance and to reduce code length, which I managed to accomplish. Then I took the classic (in-memory, pivot based) quick sort algorithm from L...
Why is my radix sort python implementation slower than quick sort?
I rewrote the original radix sort algorithm for Python from Wikipedia using arrays from SciPy to gain performance and to reduce code length, which I managed to accomplish. Then I took the classic (in-memory, pivot based) quick sort algorithm from Literate Programming and compared their performance. I had the expectatio...
[ "You have several problems here.\nFirst of all, as pointed out in the comments, your data set is far too small for the theoretical complexity to overcome the overheads in the code.\nNext your implementation with all those unnecessary function calls and copying lists around is very inefficient. Writing the code in a...
[ 3, 0 ]
[]
[]
[ "python", "quicksort", "radix_sort" ]
stackoverflow_0008279618_python_quicksort_radix_sort.txt
Q: Python 3 - From list to exact string (like list) I have: list = [1, 2, 3, 4, 5] And I want the exact string: string = "[1, 2, 3, 4, 5]" Any help? A: Represent it: >>> repr([1, 2, 3, 4, 5]) '[1, 2, 3, 4, 5]'
Python 3 - From list to exact string (like list)
I have: list = [1, 2, 3, 4, 5] And I want the exact string: string = "[1, 2, 3, 4, 5]" Any help?
[ "Represent it:\n>>> repr([1, 2, 3, 4, 5])\n'[1, 2, 3, 4, 5]'\n\n" ]
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0008280061_python.txt
Q: Python internal database use Say I have a database of recipes that I have online, and I want to use this database in a program, but I want to store the information from the database internally to the program and only have to connect to the online database when I want to update, however I don't want my end-users to...
Python internal database use
Say I have a database of recipes that I have online, and I want to use this database in a program, but I want to store the information from the database internally to the program and only have to connect to the online database when I want to update, however I don't want my end-users to have to have a database(MySql, MS...
[ "sqlite is the most common way to use databases without a database server.\n" ]
[ 2 ]
[]
[]
[ "database", "mysql", "python", "sql_server" ]
stackoverflow_0008280114_database_mysql_python_sql_server.txt
Q: Creating a Draft message in Gmail using the imaplib in Python I want to write a python module that sends data to a draft message in a G-mail account. I have written a script about two weeks ago that worked perfectly using imaplib. A simplified example of my module is below. (I have created a test email address for...
Creating a Draft message in Gmail using the imaplib in Python
I want to write a python module that sends data to a draft message in a G-mail account. I have written a script about two weeks ago that worked perfectly using imaplib. A simplified example of my module is below. (I have created a test email address for anyone to test this script on.) import imaplib import time conn = ...
[ "Before the conn.append, add the following:\nimport email\n\nThen change the conn.append line to read:\nconn.append(\"[Gmail]/Drafts\",\n '',\n imaplib.Time2Internaldate(time.time()),\n str(email.message_from_string('TEST')))\n\n" ]
[ 6 ]
[]
[]
[ "gmail_imap", "imaplib", "python" ]
stackoverflow_0007519135_gmail_imap_imaplib_python.txt
Q: How to open files given as command line arguments in python? I want my .py file to accept file I give as input in command line. I used the sys.argv[] and also fileinput but I am not getting the output. A: If you will write the following script: #!/usr/bin/env python import sys with open(sys.argv[1], 'r') as m...
How to open files given as command line arguments in python?
I want my .py file to accept file I give as input in command line. I used the sys.argv[] and also fileinput but I am not getting the output.
[ "If you will write the following script:\n#!/usr/bin/env python\n\nimport sys\n\nwith open(sys.argv[1], 'r') as my_file:\n print(my_file.read())\n\nand run it, it will display the content of the file whose name you pass in the first argument like that:\n./my_script.py test.txt\n\n(in the above example this file ...
[ 40 ]
[]
[]
[ "command", "python", "sys" ]
stackoverflow_0008280250_command_python_sys.txt
Q: Can't lauch selenium with a python script I am trying to lauch a Selenium scrit from a Python script and it gets stuck at "11:16:32.144 INFO - Launching Firefox..." The Selenium server is running well, I also tried the Selenium IDE and it works. I am using Ubuntu lynx, Firefox 3.6.23, Selenium server 2.11.0 What d...
Can't lauch selenium with a python script
I am trying to lauch a Selenium scrit from a Python script and it gets stuck at "11:16:32.144 INFO - Launching Firefox..." The Selenium server is running well, I also tried the Selenium IDE and it works. I am using Ubuntu lynx, Firefox 3.6.23, Selenium server 2.11.0 What do you think it could be ? Thank you very much. ...
[ "It could be that Selenium can't find firefox somehow?\nIs the process ending? or just hanging?\nTry starting selenium runner manually, say from ipython, something like:\nfrom selenium import selenium\nsr = selenium(host, port, \"*firefox*\", url)\nsr.start()\n\nand see if you get an exception?\n" ]
[ 1 ]
[]
[]
[ "firefox", "launching", "python", "selenium" ]
stackoverflow_0008180959_firefox_launching_python_selenium.txt
Q: Python - Arabic conversion not proper I am working on a project where Arabic language is used and I am using pyqt for the same. There is a text box in which I enters in Arabic then take that Arabic in a variable and read it using python. I have tried using UTF-8 as well but didn't worked. For example I am enterin...
Python - Arabic conversion not proper
I am working on a project where Arabic language is used and I am using pyqt for the same. There is a text box in which I enters in Arabic then take that Arabic in a variable and read it using python. I have tried using UTF-8 as well but didn't worked. For example I am entering بسم الله الرحمن الرحيم in the text box...
[ "Use the appropriate email package classes to ensure the encoding is done properly:\nfrom email.mime.text import MIMEText\nfrom email.header import Header\n...\n\nLOGIN = ''\nPASSWORD = ''\nSUBJECT = u'Invitation'\nFROMADDR = u''\nTOADDRS = unicode(self.listWidget.currentItem().text())\nCONTENT = unicode(self.textE...
[ 1, 1 ]
[]
[]
[ "arabic", "email", "pyqt", "python", "unicode" ]
stackoverflow_0008279027_arabic_email_pyqt_python_unicode.txt
Q: Something wrong without any error - Includes Tkinter I'm not getting any error but the code doesn't do what I want so there must be somewhere in the code where I have made a mistake. What I want to do is if the words match then the words must be a pair and the two chosen cells should remain "self.hidden = False" a...
Something wrong without any error - Includes Tkinter
I'm not getting any error but the code doesn't do what I want so there must be somewhere in the code where I have made a mistake. What I want to do is if the words match then the words must be a pair and the two chosen cells should remain "self.hidden = False" and therefore the cells should still show the words behind ...
[ "The immediate problem is that you're not calling self.show_word on line 136 in Cell.check. \ndef check(self, choice1, choice2):\n \"\"\" Checks if the chosen words are a pair \"\"\"\n tries = 0\n if choice1 == choice2:\n pass\n else:\n self.show_word\n\n tries += 1\n\n(You should also...
[ 1 ]
[]
[]
[ "python", "python_3.x", "tkinter" ]
stackoverflow_0008279514_python_python_3.x_tkinter.txt
Q: unittest in python: ignore an import from the code I want to test I have a python program that imports pythoncom (and uses pythoncom.CoCreateInstance from it). I want to create a unittest for the program logic without it importing pythoncom (so I can run the test on Linux as well). What options are there? Can I do...
unittest in python: ignore an import from the code I want to test
I have a python program that imports pythoncom (and uses pythoncom.CoCreateInstance from it). I want to create a unittest for the program logic without it importing pythoncom (so I can run the test on Linux as well). What options are there? Can I do it without modifying the system under test? What I found so far: sys.m...
[ "If you need to run tests and they actually are OS-dependent, you might want to use these decorators for example:\ndef run_only(func, predicate):\n if predicate():\n return func\n else:\n def f(*args, **kwargs): pass\n return f\n\n\ndef run_only_for_linux(func):\n pred = lambda: sys.pl...
[ 1, 0, 0 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0003045657_python_unit_testing.txt
Q: Python Twisted deferToThread function is not working as expected My goal here is to make a simple server handling TCP message like "process My String" that send "My String" to be processed by a quite time taking operation called (here slowFunction). Here I'm calling this function through deferToThread but nothing ...
Python Twisted deferToThread function is not working as expected
My goal here is to make a simple server handling TCP message like "process My String" that send "My String" to be processed by a quite time taking operation called (here slowFunction). Here I'm calling this function through deferToThread but nothing seems to happened : the defered's callback messages doesn't show up an...
[ "I've got some help by the guys of twisted irc\nThe points are : the callback (onProcessDone and onError) are supposed to take a result argument, and the function called by deferToThread will receive self as an argument (it should one of the MySimpleServer class' method).\nThe final code is now :\nfrom twisted impo...
[ 3, 3 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0008279867_python_twisted.txt
Q: Migrating to nginx/uWSGI/django settings not found Been having ongoing issues with an Apache / Mod_wsgi stack and finally decided to cut my losses and start fresh on the server side of things Have gotten Nginx setup to proxy requests to uwsgi. With the uwsgi protocol was fairly easy. However uwsgi has been plain s...
Migrating to nginx/uWSGI/django settings not found
Been having ongoing issues with an Apache / Mod_wsgi stack and finally decided to cut my losses and start fresh on the server side of things Have gotten Nginx setup to proxy requests to uwsgi. With the uwsgi protocol was fairly easy. However uwsgi has been plain stubborn, tried reading docs / tutorials / asking in IRC....
[ "My guess is you run the django app in python virtualenv. If so, you need to activate virtualenv in upstart script as well: \nexect /path/to/virtualenv/activate && /usr/local/sbin/uwsgi\n", "First of all you do not need all of those sys.path mess, your nginx vars already set the virtualenv for you.\nI suggest you...
[ 1, 1 ]
[]
[]
[ "django", "nginx", "python", "uwsgi" ]
stackoverflow_0008279957_django_nginx_python_uwsgi.txt
Q: ftplib callbacks not working - Python 3 I have looked everywhere and cannot find a fix for this problem, ftplib storbinary callbacks. This is my first time using callbacks so it could be something stupid, I have some code which should call my function everytime 8192 bytes are uploaded I assume (that's how I think ...
ftplib callbacks not working - Python 3
I have looked everywhere and cannot find a fix for this problem, ftplib storbinary callbacks. This is my first time using callbacks so it could be something stupid, I have some code which should call my function everytime 8192 bytes are uploaded I assume (that's how I think callbacks work after research). #In main thre...
[ "A callback, as it name suggests is when you tell some piece of code (ftplib) to call you back. What you did was to call the ftpcallback function yourself and pass it's return value (which is None because it doesn't return anything) to the storbinary method.\nInstead, you want to only pass the function object when ...
[ 1 ]
[]
[]
[ "callback", "ftp", "ftplib", "python", "upload" ]
stackoverflow_0008280868_callback_ftp_ftplib_python_upload.txt
Q: curve fitting with python I'm trying to fit some data and stuff, I know there is a simple command to do this with python/numpy/matplotlib, but I can't find it. I think it is something like popt,popc = numpy.curvefit(f,x) where popt is the paramters of f, popc is the fit quality and f is a predefined function of ...
curve fitting with python
I'm trying to fit some data and stuff, I know there is a simple command to do this with python/numpy/matplotlib, but I can't find it. I think it is something like popt,popc = numpy.curvefit(f,x) where popt is the paramters of f, popc is the fit quality and f is a predefined function of f. Does any of you know it?
[ "Take a look at scipy.optimize.curve_fit:\n\nscipy.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, **kw)\nUse non-linear least squares to fit a function, f, to data.\n\n" ]
[ 29 ]
[ "Found it. Curve_fit from optimize in scipy\n" ]
[ -1 ]
[ "curve_fitting", "numpy", "python" ]
stackoverflow_0008280871_curve_fitting_numpy_python.txt
Q: Migrate a legacy DB to Django, with image files I have a SQL dump of a legacy DB, and a folder with images, and those are referenced by some rows of certain tables, and I need to migrate that data to the new Django models. The specific problem is how to "perform" the upload, but in a management command. When the t...
Migrate a legacy DB to Django, with image files
I have a SQL dump of a legacy DB, and a folder with images, and those are referenced by some rows of certain tables, and I need to migrate that data to the new Django models. The specific problem is how to "perform" the upload, but in a management command. When the table with the field referenced is migrated to it's co...
[ "One approach would be to create a utility django project specifying your legacy database in settings.py. Then use the inspectdb management command to create a django model representation of your legacy database. And finally use dumpdata to get you data in JSON format.\nYou could then finally make your own JSON scr...
[ 0 ]
[]
[]
[ "data_migration", "django", "filefield", "python" ]
stackoverflow_0008280859_data_migration_django_filefield_python.txt
Q: Check validity of datetime? I would like to create a setter method for a datetime object so that I can customize the replace method. Is this possible? For example: datetime = datetime.replace(day = 34) This throws an error because 34 is not a valid number of days for any month, but what I would like to do is incr...
Check validity of datetime?
I would like to create a setter method for a datetime object so that I can customize the replace method. Is this possible? For example: datetime = datetime.replace(day = 34) This throws an error because 34 is not a valid number of days for any month, but what I would like to do is increase the month by 1 and then subt...
[ "this doesn't answer your question directly, but if you're just trying to increment the datetime object, you can use timedelta. For example:\nfrom datetime import datetime\nfrom datetime import timedelta\n\ndatetime(2011, 1, 1) + timedelta(days=34)\n\n", "You can subclass datetime and provide your own implementa...
[ 1, 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0008280650_datetime_python.txt
Q: A python script that automatically input some text in a website and get its source code I am doing biomedical named extraction using Python. Now I have to cross check the results from inputting the text to http://text0.mib.man.ac.uk/software/geniatagger/ and parse the source code of the HTML text that I get after...
A python script that automatically input some text in a website and get its source code
I am doing biomedical named extraction using Python. Now I have to cross check the results from inputting the text to http://text0.mib.man.ac.uk/software/geniatagger/ and parse the source code of the HTML text that I get after submitting text into it. I want that the same thing to be done in my GUI itself i.e. it inpu...
[ "Actually, this is a great question!\nFirst thing you have to do is to explore a source code of the website a little bit.\nIf you look at the source code of the website you see this block of code\n<form method=\"POST\" action=\"a.cgi\">\n<p>\nPlease enter a text that you want to analyze.\n</p>\n<p>\n<textarea name=...
[ 5 ]
[]
[]
[ "automated_tests", "python", "urllib", "user_interface" ]
stackoverflow_0008280157_automated_tests_python_urllib_user_interface.txt
Q: How to retain an "import" capability after py2exe compile I wrote a wxPython GUI where I currently configure some of the widgets and some default values by using "import data" for a module file containing several lists. But I need to compile the whole program using py2exe for a user without a python installation. ...
How to retain an "import" capability after py2exe compile
I wrote a wxPython GUI where I currently configure some of the widgets and some default values by using "import data" for a module file containing several lists. But I need to compile the whole program using py2exe for a user without a python installation. In so doing, I lose the capability of letting the user edit the...
[ "files that are imported are bundled in the executable by py2exe. The way to go is to use a configuration file that you package with your executable in a zip or with Inno Setup. Configuration files are files made to be changed at some moment, contrarily a user should not be modifying a python script. I tell you bec...
[ 0 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0008281067_py2exe_python.txt
Q: How do I make my implementation of greedy set cover faster? I came up with the following implementation for the Greedy Set Cover after much discussion regarding my original question here. From the help I received, I encoded the problem into a "Greedy Set Cover" and after receiving some more help here, I came up wi...
How do I make my implementation of greedy set cover faster?
I came up with the following implementation for the Greedy Set Cover after much discussion regarding my original question here. From the help I received, I encoded the problem into a "Greedy Set Cover" and after receiving some more help here, I came up with the following implementation. I am thankful to everyone for he...
[ "I use a trick when I implemented the famous greedy algorithm for set cover (no weights) in Matlab. It is possible that you could extend this trick to the weighted case somehow, using set cardinality / set weight instead of set cardinality. Moreover, if you use NumPy library, exporting Matlab code to Python should...
[ 6, 3 ]
[]
[]
[ "algorithm", "optimization", "performance", "python", "scalability" ]
stackoverflow_0007942312_algorithm_optimization_performance_python_scalability.txt
Q: 10*10 fold cross validation in scikit-learn? Is class sklearn.cross_validation.ShuffleSplit( n, n_iterations=10, test_fraction=0.10000000000000001, indices=True, random_state=None ) the right way for 10*10fold CV in scikit-learn? (By changing the random_state to 10 different numbers) Beca...
10*10 fold cross validation in scikit-learn?
Is class sklearn.cross_validation.ShuffleSplit( n, n_iterations=10, test_fraction=0.10000000000000001, indices=True, random_state=None ) the right way for 10*10fold CV in scikit-learn? (By changing the random_state to 10 different numbers) Because I didn't find any random_state parameter in St...
[ "I am not sure what you mean by 10*10 cross validation. The ShuffleSplit configuration you give will make you call the fit method of the estimator 10 times. If you call this 10 times by explicitly using an outer loop or directly call it 100 times with 10% of the data reserved for testing in a single loop if you use...
[ 10 ]
[]
[]
[ "machine_learning", "python", "scikit_learn", "scikits" ]
stackoverflow_0008281034_machine_learning_python_scikit_learn_scikits.txt
Q: finding frequent string patterns using python So I am trying to do this problem where I have to find the most frequent 6-letter string within some lines in python, so I realize one could do something like this: >>> from collections import Counter >>> x = Counter("ACGTGCA") >>> x Counter({'A': 2, 'C': 2, 'G': 2, '...
finding frequent string patterns using python
So I am trying to do this problem where I have to find the most frequent 6-letter string within some lines in python, so I realize one could do something like this: >>> from collections import Counter >>> x = Counter("ACGTGCA") >>> x Counter({'A': 2, 'C': 2, 'G': 2, 'T': 1}) Now then, the data I'm using is DNA files ...
[ "I think the simplest way is just do this:\n>>> from collections import Counter\n>>> protein = \"AGTTTCAGGAC\"\n>>> Counter(protein[i:i+6] for i in range(len(protein)-5))\nCounter({'TTCAGG': 1, 'AGTTTC': 1, 'CAGGAC': 1, 'TCAGGA': 1, 'GTTTCA': 1, 'TTTCAG': 1})\n\n", "The old itertools docs (via this answer) provid...
[ 4, 4 ]
[]
[]
[ "bioinformatics", "python", "string" ]
stackoverflow_0008281119_bioinformatics_python_string.txt
Q: Python twisted: Functions are not called properly? I've got a problem with setting up a client which connects to a "distributor" server to send certain data. The server's purpose is to get data from the client and then send that data to it's all connected clients. The server works without any issues. The main clie...
Python twisted: Functions are not called properly?
I've got a problem with setting up a client which connects to a "distributor" server to send certain data. The server's purpose is to get data from the client and then send that data to it's all connected clients. The server works without any issues. The main client is also supposed to work as an IRC bot. Here's a text...
[ "You should avoid writing blocking code like this:\ndef signedOn(self):\n self.msg(\"NickServ\", \"id <password_removed>\") # Identify the bot\n time.sleep(0.1) # Wait a little...\n self.join(self.factory.channel) # Join channel #chantest\n print \"Signed on as %s.\" % (self.nickname,)\n\nFor details, s...
[ 4, 0 ]
[]
[]
[ "client", "irc", "python", "twisted" ]
stackoverflow_0008263272_client_irc_python_twisted.txt
Q: Mixing colors in PyQt? Is there a way to make a new QColor in PyQt by combining 2 different colors? Something like: QColor([30, QColor(123,0,45, 100)], [70, QColor(12, 34, 56, 100)]) where the 30 and 70 represent the percentage of the new color to take. What I need is the equivalent color of layering a semi-trans...
Mixing colors in PyQt?
Is there a way to make a new QColor in PyQt by combining 2 different colors? Something like: QColor([30, QColor(123,0,45, 100)], [70, QColor(12, 34, 56, 100)]) where the 30 and 70 represent the percentage of the new color to take. What I need is the equivalent color of layering a semi-transparent color on top of a opa...
[ "It's been a while since you asked, but ofcourse there is a way to 'blend' these colors together; it may not be trivial, but it is certainly possible.\nCombining two colors can be quite easily done by doing (assuming color1 and color2 are both QColors):\nQColor(.3* color1.red() + .7 * color2.red(),\n .3* co...
[ 3 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0007371984_pyqt_python_qt.txt
Q: How to start Django up programmatically Suppose I have a Django app (for example, myapp) and a Python script (let us say, myscript.py) both in the same directory. How could I start (and stop) the Django app from the script? Is there an object or function for this? Or should I use the subprocess trick? A: Use dja...
How to start Django up programmatically
Suppose I have a Django app (for example, myapp) and a Python script (let us say, myscript.py) both in the same directory. How could I start (and stop) the Django app from the script? Is there an object or function for this? Or should I use the subprocess trick?
[ "Use django.core.management.call_command.\nFor example:\nfrom django.core import management\nmanagement.call_command('runserver')\n\n" ]
[ 10 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008281423_django_python.txt
Q: python: pandas install errors I have the academic distribution of EPD 7.1 for MacOS 10.6.x, which has pandas 0.3 version. The latest official version is 0.5.0 so I though I would upgrade to the latest. Here is what I did: saved the zip file of the source from here executed sudo python setup.py install ran tests ...
python: pandas install errors
I have the academic distribution of EPD 7.1 for MacOS 10.6.x, which has pandas 0.3 version. The latest official version is 0.5.0 so I though I would upgrade to the latest. Here is what I did: saved the zip file of the source from here executed sudo python setup.py install ran tests by executing nosetests pandas Plea...
[ "Best place to ask this question would be on the mailing list (luckily Google Alerts let me know about this right away!). It looks like your install failed and it's still using pandas 0.3.0. Were there any errors when you ran python setup.py install? You may have to upgrade your Cython installation if you're buildi...
[ 1, 1 ]
[]
[]
[ "compiler_errors", "installation", "pandas", "python" ]
stackoverflow_0008273092_compiler_errors_installation_pandas_python.txt
Q: My unittest reports a failure (AssertionError: List differ) but they don't appear to differ, why? This is my unittest code: def testExtractObject(self): self.maxDiff = None objects = Script("compare.py").extractObjects() self.assertListEqual([Object('ClassA',2,5,None), Object('Class...
My unittest reports a failure (AssertionError: List differ) but they don't appear to differ, why?
This is my unittest code: def testExtractObject(self): self.maxDiff = None objects = Script("compare.py").extractObjects() self.assertListEqual([Object('ClassA',2,5,None), Object('ClassB',1,3,None), Object('ClassC',0,2,None)], objects) This is the failure message: As...
[ "You have to tell python how to determine whether or not two objects are equal. You do this by adding an __eq__ function to your class\nclass SomeObject(object):\n def __eq__(self, other):\n return self.a == other.a and self.b == other.b\n\nThen objects which pass this test will be considered equal. By de...
[ 5 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0008281732_python_unit_testing.txt
Q: Python: how to use variables as a string? Supose I have such variables: var1, var2, var3, var4, var 5, ..., var100 (lists and dictionaries are not suitable in my case, because all these vars are class objects). I must process all them in similar way, for example: if var1: print 'var1 is not None' if var2: ...
Python: how to use variables as a string?
Supose I have such variables: var1, var2, var3, var4, var 5, ..., var100 (lists and dictionaries are not suitable in my case, because all these vars are class objects). I must process all them in similar way, for example: if var1: print 'var1 is not None' if var2: print 'var2 is not None' if var3: print 'va...
[ "locals() returns a dictionary of local variables. Similarly, globals() returns a dictionary of global variables. You can find the variable and its value in one of those, depending on where it was defined.\nfor i in range(1,101):\n if ('var%s' % i) in locals():\n print 'var%s is not None' % i\n pri...
[ 8, 5, 2, 2, 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008281455_django_python.txt
Q: Dynamically set self.x from a dictionary key/value pair I have a slice of code where I want to transform thirty or forty ever-changing key/value pairs into variables under a class. So for instance: for i in dict: self.i = dict[i] But of course that would just reset self.i each time. I've tried eval, but you c...
Dynamically set self.x from a dictionary key/value pair
I have a slice of code where I want to transform thirty or forty ever-changing key/value pairs into variables under a class. So for instance: for i in dict: self.i = dict[i] But of course that would just reset self.i each time. I've tried eval, but you cannot set variables with it, as it reports 'x=1' as invalid s...
[ "To update a class instance, you could just use\nvars(self).update(my_dict)\n\nI doubt though this is the best solution for your problem. Could you provide more details why you think you need this?\n", "Here's a way. Sven Marnach is right though -- you should say more about why you want to do this. \n>>> class F...
[ 3, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008281830_python.txt
Q: Weird unicode issue I've got following problem. If I'll run my app in eclipse it works OK, but when I'll run it in standalone debuger - I got following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\u0144' in position 7: ordinal not in range(128) How can I fix it? My code fragment: x = x.repl...
Weird unicode issue
I've got following problem. If I'll run my app in eclipse it works OK, but when I'll run it in standalone debuger - I got following error: UnicodeEncodeError: 'ascii' codec can't encode character u'\u0144' in position 7: ordinal not in range(128) How can I fix it? My code fragment: x = x.replace("Ł", "L")
[ "Guess, based on (insufficient) information provided:\nYou are running Python 2.x.\n[Guess] x is a str object.\n[Guess] Eclipse sets the default encoding to UTF-8.\nThe \"standard debugger\" sets the default encoding to ascii.\nResult: splat.\nSolution (standard operating procedure for working with Unicode):\n\nOn ...
[ 3, 2 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0008281020_python_unicode.txt
Q: Extracting parts of HTML from website using python I'm currently working on a project that involves a program to inspect a web page's HTML using Python. My program has to monitor a web page, and when a change is made to the HTML, it will complete a set of actions. My question is how do you extract just part of a w...
Extracting parts of HTML from website using python
I'm currently working on a project that involves a program to inspect a web page's HTML using Python. My program has to monitor a web page, and when a change is made to the HTML, it will complete a set of actions. My question is how do you extract just part of a web page, and how do you monitor a web page's HTML and re...
[ "In the past I wrote my own parsers. Nowadays HTML is HTML 5, more statements,more Javascript, a lot of crappiness done by developers and their editors, like \ndocument.write('<SCR' + 'IPT\n\nAnd some web frameworks / developers bad coding change the Last-Modified in the HTTP header on every request, even if for a ...
[ 2, 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0008281851_html_python.txt
Q: sorting text files with python Say I have a text file with recipes fomatted like this: TITLE: Michigan Pie: INGREDIENTS: 8 oz cream cheese 1 can sweetened, condensed milk ¼ c lemon juice 15 oz crushed pineapple 8 oz whipped cream DIRECTIONS: Drain the pineapple very well. Beat the cream cheese until it’s very...
sorting text files with python
Say I have a text file with recipes fomatted like this: TITLE: Michigan Pie: INGREDIENTS: 8 oz cream cheese 1 can sweetened, condensed milk ¼ c lemon juice 15 oz crushed pineapple 8 oz whipped cream DIRECTIONS: Drain the pineapple very well. Beat the cream cheese until it’s very smooth. Add the sweetened, condense...
[ "Initialize a dictionary with three keys: TITLE, INGREDIENTS, DIRECTIONS. \nParse the text file. Whenever you find one of the keys, add the text below it to the appropriate key value pair in the dictionary. Stop when you see another bold faced key and continue parsing.\nIf you would prefer a list of the TITLES, for...
[ 1, 0, 0 ]
[]
[]
[ "filesort", "python" ]
stackoverflow_0008280806_filesort_python.txt
Q: displaying a data in a plot label of matplot lib Is there a way to display a variable (specificaly, a linear fit paramter) in a plot I drow? Also, is there a way to control the number of figures displayed? I'm using matplotlib to generate the figures and optimize.curve_fit to do the curve fitting. A: Sure, just...
displaying a data in a plot label of matplot lib
Is there a way to display a variable (specificaly, a linear fit paramter) in a plot I drow? Also, is there a way to control the number of figures displayed? I'm using matplotlib to generate the figures and optimize.curve_fit to do the curve fitting.
[ "Sure, just use text or annotate.\nAs a quick example:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# Generate data...\nx = np.linspace(0, 30, 15)\ny = 0.4 * x + 9 + np.random.random(x.size)\n\n# Linear fit...\nmodel = np.polyfit(x, y, deg=1)\n\nplt.plot(x, y, 'bo', label='Observations')\nplt.plot(x, mod...
[ 3 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0008281391_matplotlib_python.txt
Q: Can't connect to gtalk with python and xmpppy When try connect to gtalk I get this error: An error occurred while looking up _xmpp-client._tcp.talk.google.com The code is here: https://gist.github.com/1396074 A: Do not pass the (incorrect) server name into cl.connect() on line 11. The SRV lookup will go to _x...
Can't connect to gtalk with python and xmpppy
When try connect to gtalk I get this error: An error occurred while looking up _xmpp-client._tcp.talk.google.com The code is here: https://gist.github.com/1396074
[ "Do not pass the (incorrect) server name into cl.connect() on line 11. The SRV lookup will go to _xmpp-client._tcp.gmail.com then (taken from the JID), which should work. Passing in a server is only used for incorrectly configured XMPP servers.\n" ]
[ 1 ]
[]
[]
[ "google_talk", "python", "xmpp" ]
stackoverflow_0008280727_google_talk_python_xmpp.txt
Q: In laymans terms, what does the Python string format "g" actually mean? I feel a bit silly for asking what I'm sure is a rather basic question, but I've been learning Python and I'm having difficulty understanding what exactly the "g" and "G" string formats actually do. The documentation has this to say: Floating...
In laymans terms, what does the Python string format "g" actually mean?
I feel a bit silly for asking what I'm sure is a rather basic question, but I've been learning Python and I'm having difficulty understanding what exactly the "g" and "G" string formats actually do. The documentation has this to say: Floating point format. Uses lowercase exponential format if exponent is less than -4 ...
[ "These examples are probably illustrative:\n>>> numbers = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001]\n>>> for number in numbers:\n... print \"%%e=%e, %%f=%f, %%g=%g\" % (number, number, number)\n... \n%e=1.000000e+02, %f=100.000000, %g=100\n%e=1.000000e+01, %f=10.000000, %g=10\n%e=1.000000e+00, %f=1.000000...
[ 13, 5 ]
[]
[]
[ "exponent", "floating_point", "number_formatting", "python" ]
stackoverflow_0008282130_exponent_floating_point_number_formatting_python.txt
Q: Having problems with importing a module I use os.chdir() to change the current directory where my recommendations.py file is. Then I type Import recommendations and I get error: ImportError: No module named recommendations. What could be the problem? A: Python only looks in the initial working directory (and a...
Having problems with importing a module
I use os.chdir() to change the current directory where my recommendations.py file is. Then I type Import recommendations and I get error: ImportError: No module named recommendations. What could be the problem?
[ "Python only looks in the initial working directory (and a few other places) by default. If you change the current directory, insert the new working directory into the search path:\nsys.path.insert(0, os.getcwd())\n\n", "Python doesn't use the current working directory to import modules, except insofar as it adds...
[ 5, 2 ]
[]
[]
[ "python", "python_import", "pythonpath" ]
stackoverflow_0008282193_python_python_import_pythonpath.txt
Q: How to do kerberos authentication with a python suds client I have a Windows-based web service that does certificate revocation. It supplies a WSDL file that I want the python suds package to use to allow me to revoke certificates. The service is protected via Kerberos/GSSAPI, so there is a keytab file in order to...
How to do kerberos authentication with a python suds client
I have a Windows-based web service that does certificate revocation. It supplies a WSDL file that I want the python suds package to use to allow me to revoke certificates. The service is protected via Kerberos/GSSAPI, so there is a keytab file in order to provide the credentials. How do I tell the suds client to use th...
[ "You will require PyKerberos. If your client does not, you have to patch it. Otherwise there will be not SPNEGO/Kerberos support for your web services.\n" ]
[ 0 ]
[]
[]
[ "gssapi", "kerberos", "python", "suds" ]
stackoverflow_0008247985_gssapi_kerberos_python_suds.txt
Q: Google App Engine handling parallel requests I am using Google App Engine for the first time, whenever I make requests using two instances of the application, the responses come sequentially.. For example, I opened two pages of the app's main page, made an AJAX request from one then refreshed the other, the page ...
Google App Engine handling parallel requests
I am using Google App Engine for the first time, whenever I make requests using two instances of the application, the responses come sequentially.. For example, I opened two pages of the app's main page, made an AJAX request from one then refreshed the other, the page doesn't load until the first page gets its respons...
[ "The Python dev_appserver is single-threaded and only serves one request at a time. The production environment, naturally, has no such restriction.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "parallel_processing", "python", "webserver" ]
stackoverflow_0008281565_google_app_engine_parallel_processing_python_webserver.txt
Q: Is there any function in twisted python similar to 'select' in socket programming? I am doing a muticlient chat server program in twisted python. Is there any function in twisted python similar to 'select' in in socket programming? Can anybody give me the answer please?.. If yes, please tell me the implementation,...
Is there any function in twisted python similar to 'select' in socket programming?
I am doing a muticlient chat server program in twisted python. Is there any function in twisted python similar to 'select' in in socket programming? Can anybody give me the answer please?.. If yes, please tell me the implementation, please.
[ "No, there isn't.\nTwisted calls select (or something like it) for you.\nYou don't ever need to call a function like select; just let the reactor run, and do its work for you.\n" ]
[ 1 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0008280373_python_twisted.txt
Q: How can I set window type hints on a ClutterStage? Is there any way to make a standalone ClutterStage use TYPE_HINT_DOCK (and be borderless), with python? Perhaps by manipulating the window with Xlib? A: I also strongly suggest to use clutter-gtk. It's python bindings have not been removed from Ubuntu. However, ...
How can I set window type hints on a ClutterStage?
Is there any way to make a standalone ClutterStage use TYPE_HINT_DOCK (and be borderless), with python? Perhaps by manipulating the window with Xlib?
[ "I also strongly suggest to use clutter-gtk. It's python bindings have not been removed from Ubuntu.\nHowever, clutter is now using gobject introspection for it's python bindings instead of generating them (simple example). \nThe new package name in Ubuntu is now gir1.2-clutter-gtk-0.10 instead of python-clutter-so...
[ 1, 0 ]
[]
[]
[ "clutter", "python", "xorg" ]
stackoverflow_0008107745_clutter_python_xorg.txt
Q: Combining two sets and splitting them in pairs I need to take two sets of data and produce one set of pairs(tuples) from both sets. This result set will only have one possible pair, i.e. for two sets: 1,2 and 3, 4 the result should be: ((1, 3), (2, 4)). Full exercise text can be found here:http://pastebin.com/mUaK...
Combining two sets and splitting them in pairs
I need to take two sets of data and produce one set of pairs(tuples) from both sets. This result set will only have one possible pair, i.e. for two sets: 1,2 and 3, 4 the result should be: ((1, 3), (2, 4)). Full exercise text can be found here:http://pastebin.com/mUaKV4G7 I need to do this using pop. Here's what I hav...
[ "The error tells you what is going on: pairs is a set and the expression pairs[::2] means \"every 2nd element of the set\". The problem is that sets have no defined order, so \"every 2nd element of the set\" makes no sense. As the order of element is undefined, Python raises a exception instead of making up a rando...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "set", "tuples" ]
stackoverflow_0008282558_python_set_tuples.txt
Q: Python "import django" not finding module; what's it looking for? Very basic, newbie question on setting up Django for Google App Engine in a Windows 7 development environment. I have a Django folder under the google_appengine folder, with all the Django distribution folders (as described in an All Buttons Pressed...
Python "import django" not finding module; what's it looking for?
Very basic, newbie question on setting up Django for Google App Engine in a Windows 7 development environment. I have a Django folder under the google_appengine folder, with all the Django distribution folders (as described in an All Buttons Pressed djangoappengine doc) under the Django folder. Using the App Engine Lau...
[ "I don't think Python looks for its modules via the PATH environment variable. You can add the relevant directory to PYTHON_PATH though and it should pick that up. \nAnother (probably better) solution would be to move the appropriate directory into your Python site-packages directory and making sure it is appropr...
[ 0 ]
[]
[]
[ "django", "google_app_engine", "path", "python", "windows" ]
stackoverflow_0008282852_django_google_app_engine_path_python_windows.txt
Q: Sync django-piston models when using egg module I'm using django-piston and running into the following problem when running the manage.py syncdb command: Traceback (most recent call last): File "./manage.py", line 13, in <module> execute_manager(settings) File "/home/appfirst/django/django/core/management/...
Sync django-piston models when using egg module
I'm using django-piston and running into the following problem when running the manage.py syncdb command: Traceback (most recent call last): File "./manage.py", line 13, in <module> execute_manager(settings) File "/home/appfirst/django/django/core/management/__init__.py", line 438, in execute_manager utilit...
[ "Looks like this is a known issue with Piston 0.2.3. You could apply this patch or just use version 0.2.2 by installing it as so:\npip install django-piston==0.2.2\n\n", "I had the same issue, not sure what caused it, but to fix it, I uncommented the piston app out of my INSTALLED_APPS in settings, and it started...
[ 8, 1 ]
[]
[]
[ "django", "django_piston", "python" ]
stackoverflow_0005735237_django_django_piston_python.txt
Q: How to disable googlebot in Google App Engine? Yesterday googlebot caused my app to exceed read quotas. How do I disable googlebot? Thanks. Update I added - url: /robots.txt static_dir: robots to my app.yaml as explained here and created the robots.txt file the directory "robots", but the url http://www.example...
How to disable googlebot in Google App Engine?
Yesterday googlebot caused my app to exceed read quotas. How do I disable googlebot? Thanks. Update I added - url: /robots.txt static_dir: robots to my app.yaml as explained here and created the robots.txt file the directory "robots", but the url http://www.example.com/robots.txt does not work. What am I doing wrong...
[ "Add a robots.txt file. Here is a simple one which blocks all robots that heed it:\nUser-agent: *\nDisallow: /\n\n", "Move the robot route above the /.* catch all route and modify your app.yaml with:\n- url: /robots.txt\n static_files: robots/robots.txt\n upload: robots/robots.txt\n\nBear in mind that this act...
[ 5, 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008282648_google_app_engine_python.txt
Q: How do I prompt for user input in bash? Please fix my python/bash Spanglish Sorry. I am very new to this and can't find a straight forward answer. In python I can say: from sys import argv script, user_name = argv prompt'> ' print "Hi %s, I'm the %s script" % (user_name, script) print "I'd like to ask you a few qu...
How do I prompt for user input in bash? Please fix my python/bash Spanglish
Sorry. I am very new to this and can't find a straight forward answer. In python I can say: from sys import argv script, user_name = argv prompt'> ' print "Hi %s, I'm the %s script" % (user_name, script) print "I'd like to ask you a few questions" print "What channel is that on?" channel = raw_input(prompt) blah blah -...
[ "I guess you are looking for read internal command\necho -n \"What channel is that on? \";\nread channel;\n\nOr more concisely\nread -p \"What channel is that on? \" channel\n\n", "Look at the subprocess module if you want to launch other programs from python. As for manipulating other programs -- you'd have to b...
[ 4, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0008279795_bash_python.txt
Q: Understanding global object persistence in Python WSGI apps Consider the following code in my WebApp2 application in Google App Engine: count = 0 class MyHandler(webapp2.RequestHandler): def get(self): global count count = count + 1 print count With each refresh of the page, the cou...
Understanding global object persistence in Python WSGI apps
Consider the following code in my WebApp2 application in Google App Engine: count = 0 class MyHandler(webapp2.RequestHandler): def get(self): global count count = count + 1 print count With each refresh of the page, the count increments higher. I'm coming from the PHP world where every r...
[ "Your understanding is correct. If you want variables that persist for the duration of the request, you shouldn't make them globals at all - make them instance variables on your RequestHandler class, accessed as self.var. Since a new RequestHandler is instantiated for each request, your variables will stick around ...
[ 17, 5, 2 ]
[]
[]
[ "google_app_engine", "python", "webapp2", "wsgi" ]
stackoverflow_0008170973_google_app_engine_python_webapp2_wsgi.txt
Q: Multiple threaded socket connections/queues SocketClientThread Reference: http://eli.thegreenplace.net/2011/05/18/code-sample-socket-client-thread-in-python/ Eli provided this generic example of how to manage a socket client inside a thread, and communicate to the main scope with the Queue module. (thanks again El...
Multiple threaded socket connections/queues
SocketClientThread Reference: http://eli.thegreenplace.net/2011/05/18/code-sample-socket-client-thread-in-python/ Eli provided this generic example of how to manage a socket client inside a thread, and communicate to the main scope with the Queue module. (thanks again Eli!) One thread works great, but I'm trying to do ...
[ "Look like you've found a bug in the sample code :-) The bug happens only when more than one thread is created at the same time, as you noted. It's because the Queue.Queue() default argument is only constructed once when the class is defined - quite a common bug in Python actually, but usually happens with lists.\n...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008282216_python.txt
Q: Python interprocess communication advice I have 2 python servers running independently of one another but sharing the same database. They need to communicate with each other about when certain changes have been made to the database so the other server (if running) can reload cached data. What would be my best opti...
Python interprocess communication advice
I have 2 python servers running independently of one another but sharing the same database. They need to communicate with each other about when certain changes have been made to the database so the other server (if running) can reload cached data. What would be my best options for communicating between two such program...
[ "You could have each one implement a simple XMLRPC server. Each one can then execute code in the other, such as telling the other one it needs to update. \n", "The easiest way is to use the database itself as a means of communication. Add a table for logging updates. Then, either machine can periodically query ...
[ 5, 3, 1 ]
[]
[]
[ "ipc", "python" ]
stackoverflow_0008283359_ipc_python.txt
Q: list indices must be integer not str python sqlite3 my code the error points to looks like this for i in array1: cursor.execute("insert into Recipe values (?,?,?)",(array1[i], array2[i], array3[i])) db.commit() the contents of the arrays are strings, so how would I put the arrays into the sqlite3 table? A:...
list indices must be integer not str python sqlite3
my code the error points to looks like this for i in array1: cursor.execute("insert into Recipe values (?,?,?)",(array1[i], array2[i], array3[i])) db.commit() the contents of the arrays are strings, so how would I put the arrays into the sqlite3 table?
[ "Use zip() to iterate over all three arrays together:\nfor row in zip(array1, array2, array3):\n cursor.execute(\"insert into Recipe values (?,?,?)\", row)\ndb.commit()\n\n", "You want to use something like this:\nfor i in range(len(array1)):\n\n...but that's not quite as idiomatic as it should be.\n" ]
[ 2, 0 ]
[]
[]
[ "compiler_errors", "python", "sqlite" ]
stackoverflow_0008283536_compiler_errors_python_sqlite.txt
Q: Need to read data from text file within brackets in Python My text file has line as below. This type of line is present many times in the file. [Nov 22 22:27:13] INFO -[com.macys.seo.business.impl.LinkBusinessImpl]- Executing Search(WS) Gateway request : KeywordVO ( keyword = GUESS score = 83965 normal...
Need to read data from text file within brackets in Python
My text file has line as below. This type of line is present many times in the file. [Nov 22 22:27:13] INFO -[com.macys.seo.business.impl.LinkBusinessImpl]- Executing Search(WS) Gateway request : KeywordVO ( keyword = GUESS score = 83965 normalizedKeyword = GUESS productIds = [] categoryIds = [] ho...
[ "Regular expressions may help do the parsing in a single pass:\nimport re, pprint\n\nwith open('d:\\log.log') as f:\n s = f.read()\nresults = re.findall(r'KeywordVO \\((.*?)\\)', s)\npprint.pprint(results)\n\nThe regex above uses KeywordVO to recognize which parentheses are relevant (I'm guessing that you didn't ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008283638_python.txt
Q: argparse combine with optional parameter If the user use the optional parameter -o then the user has to use parameter -b as well. However, the -b parameter you have to use only if the user set the parameter -o. import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argum...
argparse combine with optional parameter
If the user use the optional parameter -o then the user has to use parameter -b as well. However, the -b parameter you have to use only if the user set the parameter -o. import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-f', nargs='?', required=True) parser...
[ "Add a test after args = parser.parse_args():\nif args.o and not args.b:\n print >> sys.stderr, 'The -b option is required whenever -o is specified'\n sys.exit(1)\n\n" ]
[ 2 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0008283810_argparse_python.txt
Q: Is there any method to remove javascript code from an HTML document? I want to remove all the javascript code from an HTML document, and leave the actual text. Is there any regex or python script to do this? Thanks. A: Using BeautifulSoup: #!/usr/bin/env python from BeautifulSoup import BeautifulSoup with open(...
Is there any method to remove javascript code from an HTML document?
I want to remove all the javascript code from an HTML document, and leave the actual text. Is there any regex or python script to do this? Thanks.
[ "Using BeautifulSoup:\n#!/usr/bin/env python\nfrom BeautifulSoup import BeautifulSoup\n\nwith open(\"with-scripts.html\", \"r\") as f:\n soup = BeautifulSoup(f.read())\n\nfor script in soup(\"script\"):\n script.extract()\n\nwith open(\"without-scripts.html\", \"w\") as f:\n f.write(soup.prettify())\n\n", ...
[ 5, 1, 0 ]
[]
[]
[ "html", "javascript", "python" ]
stackoverflow_0008283907_html_javascript_python.txt
Q: Why does this code only work half the time? I have the following test def test_employees_not_arround_for_more_than_3_rounds(self): self.game_object.generate_workers() people_in_list_turn_1 = self.game_object.employees[:] self.game_object.next_turn() self.game_object.generate_workers() self.gam...
Why does this code only work half the time?
I have the following test def test_employees_not_arround_for_more_than_3_rounds(self): self.game_object.generate_workers() people_in_list_turn_1 = self.game_object.employees[:] self.game_object.next_turn() self.game_object.generate_workers() self.game_object.next_turn() self.game_object.generat...
[ "You are removing items from a list while iterating over it in __remove_workers_unemployed_for_3_rounds, so the loop skips items you would want it to remove. You need to iterate over a copy of the list.\ndef __remove_workers_unemployed_for_3_rounds(self):\n for employee in self.employees[:]:\n if employee...
[ 4, 3, 3 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0008283519_python_python_3.x.txt
Q: How well do Python machine learning algorithms scale? How well do Python machine learning algorithms scale for web applications? So far, I am impressed with the Mahout library but as a Python programmer I was hoping there are also libraries catered towards scaling really well. A: Pure Python code tends to run s...
How well do Python machine learning algorithms scale?
How well do Python machine learning algorithms scale for web applications? So far, I am impressed with the Mahout library but as a Python programmer I was hoping there are also libraries catered towards scaling really well.
[ "Pure Python code tends to run slower than compiled languages. Instead, it favors rapid development.\nWhen Python coders need speed-ups, they tend to use C/C++ libraries with Python wrappers, use NumPy, run pypy, or construct fast extensions using Cython.\nThese alternatives could each be applied to a machine lear...
[ 5 ]
[]
[]
[ "algorithm", "machine_learning", "python" ]
stackoverflow_0008284373_algorithm_machine_learning_python.txt
Q: draw an image to gtk.DrawingArea? I'm writing a PyGtk paint program based on the basic tutorial found here. Is there any way to add an image to the drawing area so that you can still draw over the image? Like a stamp, or an imported photo for example. I've tried adding a gtk.Image() but gtk.DrawingArea object has ...
draw an image to gtk.DrawingArea?
I'm writing a PyGtk paint program based on the basic tutorial found here. Is there any way to add an image to the drawing area so that you can still draw over the image? Like a stamp, or an imported photo for example. I've tried adding a gtk.Image() but gtk.DrawingArea object has no attribute add. self.window = gtk.Win...
[ "You have to draw the image (as a gtk.gdk.Pixbuf, not gtk.Image) onto the backing pixmap yourself using gtk.gdk.Drawable.draw_pixbuf(). Only container widgets (widgets that can contain other widgets) have an add() method, and gtk.DrawingArea is not one.\npixbuf = gtk.gdk.pixbuf_new_from_file(image_filename) #one wa...
[ 4 ]
[]
[]
[ "drawable", "drawing", "paint", "pygtk", "python" ]
stackoverflow_0008283788_drawable_drawing_paint_pygtk_python.txt
Q: Open source tool to generate UML behavioral models from python code? I want to generate UML behavioral models (state machines and/or sequence diagrams) from python code. Is there any open source tool that can do that? A: Here you have a list of UML tools with code-generation or reverse engineering capabilities f...
Open source tool to generate UML behavioral models from python code?
I want to generate UML behavioral models (state machines and/or sequence diagrams) from python code. Is there any open source tool that can do that?
[ "Here you have a list of UML tools with code-generation or reverse engineering capabilities for python but I don't think any support sequence diagrams\n" ]
[ 1 ]
[]
[]
[ "python", "reverse_engineering", "sequence_diagram", "state_machine", "uml" ]
stackoverflow_0008281403_python_reverse_engineering_sequence_diagram_state_machine_uml.txt
Q: Print in single line in Python Given some code: keyword=re.findall(r'ke\w+ = \S+',s) score=re.findall(r'sc\w+ = \S+',s) print '%s,%s' %(keyword,score) The output of above code is: ['keyword = NORTH', 'keyword = GUESS', 'keyword = DRESSES', 'keyword = RALPH', 'keyword = MATERIAL'],['score = 88466', 'score = 83965...
Print in single line in Python
Given some code: keyword=re.findall(r'ke\w+ = \S+',s) score=re.findall(r'sc\w+ = \S+',s) print '%s,%s' %(keyword,score) The output of above code is: ['keyword = NORTH', 'keyword = GUESS', 'keyword = DRESSES', 'keyword = RALPH', 'keyword = MATERIAL'],['score = 88466', 'score = 83965', 'score = 79379', 'score = 74897',...
[ "Instead of the last line, do this instead:\n>>> for k, s in zip(keyword, score):\n kw = k.partition('=')[2].strip()\n sc = s.partition('=')[2].strip()\n print '%s,%s' % (kw, sc)\n\n\nNORTH,88466\nGUESS,83965\nDRESSES,79379\nRALPH,74897\nMATERIAL,68168\n\nHere is how it works:\n\nThe zip brings...
[ 8, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008284489_python.txt
Q: Arbitrary ordering of tuple nested in a list in Python I have a list of tuples like the following that I'm getting back from Solr: [('Second Circuit', 34), ('Ninth Circuit', 24), ('Third Circuit', 4), ('Eleventh Circuit', 2)] Note that not only the second, third, ninth and eleventh circuits were returned. I nee...
Arbitrary ordering of tuple nested in a list in Python
I have a list of tuples like the following that I'm getting back from Solr: [('Second Circuit', 34), ('Ninth Circuit', 24), ('Third Circuit', 4), ('Eleventh Circuit', 2)] Note that not only the second, third, ninth and eleventh circuits were returned. I need to order this according to an ordering tuple I have that l...
[ "Build a dictionary that maps the court name to the desired ranking. Then sort with a key function that looks up the court name to find the ranking:\n>>> COURT_ORDER = (\n 'Supreme Court',\n 'First Circuit',\n 'Second Circuit',\n 'Third Circuit',\n 'Fourth Circuit',\n 'Ninth Circuit',\n 'Eleve...
[ 4, 2 ]
[]
[]
[ "faceted_search", "python", "solr", "sorting" ]
stackoverflow_0008284326_faceted_search_python_solr_sorting.txt
Q: What information identifies the file data at a path as being unchanged? I want to memoize the result of a function that operates on the file data at a given path. How can I determine if the file data has changed since I last processed it? I'm considering mapping a key containing st_dev, st_ino, and st_mtime to the...
What information identifies the file data at a path as being unchanged?
I want to memoize the result of a function that operates on the file data at a given path. How can I determine if the file data has changed since I last processed it? I'm considering mapping a key containing st_dev, st_ino, and st_mtime to the results. Is this sufficient?
[ "The file size and a checksum of the file contents would go much further in determining uniqueness.\n", "Most application only looks at m_time, assuming that if it's unchanged so is the file. So that is clearly sufficient for most applications.\n" ]
[ 0, 0 ]
[]
[]
[ "caching", "memoization", "python", "python_3.x", "stat" ]
stackoverflow_0008284305_caching_memoization_python_python_3.x_stat.txt
Q: F1 smaller than both precision and recall in Scikit-learn I am doing multi-class classification, with unbalanced categories. I noticed f1 is always smaller than the direct harmonic mean of precision and recall, and in some cases, f1 is even smaller than both precision and recall. FYI, I called metrics.precision_sc...
F1 smaller than both precision and recall in Scikit-learn
I am doing multi-class classification, with unbalanced categories. I noticed f1 is always smaller than the direct harmonic mean of precision and recall, and in some cases, f1 is even smaller than both precision and recall. FYI, I called metrics.precision_score(y,pred) for precision and so on. I am aware of the differen...
[ "Can you please update your question with the output of:\n>>> from sklearn.metrics import classification_report\n>>> print classification_report(y_true, y_predicted)\n\nThat will display the precisions and recalls for each individual category along with the support and hence help us make sense of how the averaging ...
[ 2 ]
[]
[]
[ "machine_learning", "python", "scikit_learn", "scikits" ]
stackoverflow_0008284456_machine_learning_python_scikit_learn_scikits.txt
Q: Real-time identification of non-speech, non-music sound from a continuous microphone stream I'm looking to log events corresponding to a specific sound, such as a car door slamming, or perhaps a toaster ejecting toast. The system needs to be more sophisticated than a "loud noise detector"; it needs to be able to d...
Real-time identification of non-speech, non-music sound from a continuous microphone stream
I'm looking to log events corresponding to a specific sound, such as a car door slamming, or perhaps a toaster ejecting toast. The system needs to be more sophisticated than a "loud noise detector"; it needs to be able to distinguish that specific sound from other loud noises. The identification need not be zero-latenc...
[ "This doctoral thesis, Non-Speech Environmental Sound Classification System for Autonomous Surveillance, by Cowling (2004), has experimental results on different techniques for audio feature extraction, as well as classification. He uses environmental sounds such as jangling keys and footsteps, and was able to achi...
[ 3, 3 ]
[]
[]
[ "audio_fingerprinting", "java", "pattern_recognition", "python", "real_time" ]
stackoverflow_0008284725_audio_fingerprinting_java_pattern_recognition_python_real_time.txt
Q: Python Clutter: Set display? How does one set the X11 display in Python-Clutter? I am trying to set it to XSCREENSAVER_WINDOW. I have tried importing clutter.x11 and using set_display(), but this doesn't seem to be the correct command. Does anyone know the right way of doing this? A: While searching around I fou...
Python Clutter: Set display?
How does one set the X11 display in Python-Clutter? I am trying to set it to XSCREENSAVER_WINDOW. I have tried importing clutter.x11 and using set_display(), but this doesn't seem to be the correct command. Does anyone know the right way of doing this?
[ "While searching around I found this thread, and by looking at the avatar picture, I assume it's your thread ;) I'll re post the code given by LemursDontExist so you have it all in one.\n\nShort explanation: to make a program a screensaver in X Windows, the program checks if it is running as a screensaver, that mea...
[ 0 ]
[]
[]
[ "clutter", "python" ]
stackoverflow_0004598581_clutter_python.txt
Q: How to mount/unmount flash disk with using hal,dbus in python? i need to mount and unmount flash drive in my code -written with python- without using command line or os module. how can i mount/unmount flash drive with using dbus ( also hal)? A: Check here for hal(in maintenance mode) or here for udisks
How to mount/unmount flash disk with using hal,dbus in python?
i need to mount and unmount flash drive in my code -written with python- without using command line or os module. how can i mount/unmount flash drive with using dbus ( also hal)?
[ "Check here for hal(in maintenance mode) or here for udisks\n" ]
[ 2 ]
[]
[]
[ "dbus", "python" ]
stackoverflow_0003512352_dbus_python.txt
Q: Maxima and Minima Point of a Curve in Python I have a captured a data from a displacement sensor, the delta values for one iteration look like this. 0, 1, 2, 4, 7, 9, 14, 24, 14, 10, 9, 7, 3 2, 1, 0, 0, 0, 0, -1, -3, -5, -7, -9, -14, -24, -14, -9, -8, -6, -4, -3, -1, 0, 0, 0. (other iterations are also have same p...
Maxima and Minima Point of a Curve in Python
I have a captured a data from a displacement sensor, the delta values for one iteration look like this. 0, 1, 2, 4, 7, 9, 14, 24, 14, 10, 9, 7, 3 2, 1, 0, 0, 0, 0, -1, -3, -5, -7, -9, -14, -24, -14, -9, -8, -6, -4, -3, -1, 0, 0, 0. (other iterations are also have same pattern.) I am interested in the maxima and minima ...
[ "You can use this function for getting the absolute extrema:\ndef extrema(value, deltas):\n max_value = min_value = value\n for delta in deltas:\n value += delta\n if value < min_value:\n min_value = value\n elif value > max_value:\n max_value = value\n return min...
[ 2 ]
[]
[]
[ "curves", "minima", "points", "python" ]
stackoverflow_0008285838_curves_minima_points_python.txt