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: Is it possible to create a completely new instance of the members of a parent class? Python version 2.7. Scenario class A(object): x = 0 class B(A): pass ai = A() bi = B() #Then: id(ai.x) == id(bi.x) >>> True What I'd like to know is if there is a way, other than having all the class member definitions...
Is it possible to create a completely new instance of the members of a parent class?
Python version 2.7. Scenario class A(object): x = 0 class B(A): pass ai = A() bi = B() #Then: id(ai.x) == id(bi.x) >>> True What I'd like to know is if there is a way, other than having all the class member definitions in __init__ to have instances of class B have their own copies of x without having to red...
[ "For your example, it doesn't matter with immutable objects. bi references a new object if it is ever assigned.\nclass A(object):\n x = 0\n\nclass B(A):\n pass\n\nai = A()\nbi = B()\n\nprint id(ai.x) == id(bi.x)\nai.x=3\nprint id(ai.x) == id(bi.x)\n\nResult:\nTrue\nFalse\n\nNote also, that even if you initia...
[ 2 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0008555167_python_python_2.7.txt
Q: Python pywin32 Access Denied So, I'm trying to write a simple time tracker in python using the pywin32 module. It works fine most of the time, but in some cases it shows one of the following errors: (5, 'OpenProcess', 'Access is Denied.') (87, 'OpenProcess', 'The Parameter is incorrect.)' The problems usually oc...
Python pywin32 Access Denied
So, I'm trying to write a simple time tracker in python using the pywin32 module. It works fine most of the time, but in some cases it shows one of the following errors: (5, 'OpenProcess', 'Access is Denied.') (87, 'OpenProcess', 'The Parameter is incorrect.)' The problems usually occur when minimizing a window or ru...
[ "First of all do you need 0x0410 permissions (PROCESS_VM_READ+PROCESS_QUERY_INFORMATION)? Maybe obtaining PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION is enough for your needs? Check this MSDN page for permissions description http://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85...
[ 1 ]
[]
[]
[ "python", "pywin32", "windows" ]
stackoverflow_0008543716_python_pywin32_windows.txt
Q: Fast String within List Searching Using Python 3, I have a list containing over 100,000 strings (list1), each 300 characters long at most. I also have a list of over 9 million substrings (list2)--I want to count how many elements a substring in list2 appears in. For instance, list1 = ['cat', 'caa', 'doa', 'oat'] l...
Fast String within List Searching
Using Python 3, I have a list containing over 100,000 strings (list1), each 300 characters long at most. I also have a list of over 9 million substrings (list2)--I want to count how many elements a substring in list2 appears in. For instance, list1 = ['cat', 'caa', 'doa', 'oat'] list2 = ['at', 'ca', 'do'] I want the f...
[ "set M = len(list1) and N = len(list2)\nFor each of the N entries in list2 you're going to have to do M comparisons against the entries in list1. That's a worst case running time of O(M x N). If you take it further, lets take each entry in list2 to be of length 1 and each entry in list1 to be of length 300, then yo...
[ 2, 2, 0 ]
[]
[]
[ "list", "performance", "python", "string" ]
stackoverflow_0008549788_list_performance_python_string.txt
Q: Only include enabled objects in dict() - Python I am current converting a list of Objects to a dict using this command: MODULES = dict([(s.key, s) for s in ALL_MODULES]) Each module in ALL_MODULES is enabled=True or enabled=False How would I change the above code to only include the modules with enabled=True? A:...
Only include enabled objects in dict() - Python
I am current converting a list of Objects to a dict using this command: MODULES = dict([(s.key, s) for s in ALL_MODULES]) Each module in ALL_MODULES is enabled=True or enabled=False How would I change the above code to only include the modules with enabled=True?
[ "try this:\nMODULES = dict([(s.key, s) for s in ALL_MODULES if s.enabled])\n\nor \nMODULES = dict([(s.key, s) for s in ALL_MODULES if s['enabled']])\n\nDepends on module data type.\n", "MODULES = dict([(s.key, s) for s in ALL_MODULES if MODULES['enabled'] == True])\n\n", "dict([(s.key, s) for s in ALL_MODULES i...
[ 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008555423_python.txt
Q: Periodic Python Threads with on demand trigger I have simple PyGTK app. Since I have to run multiple periodic tasks to fetch some data and refresh GUI, I extended Thread like this: class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.setDaemon(True)...
Periodic Python Threads with on demand trigger
I have simple PyGTK app. Since I have to run multiple periodic tasks to fetch some data and refresh GUI, I extended Thread like this: class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.setDaemon(True) self.event = threading.Event() self...
[ "Instead of using a Timer, use another Event object in combination with a timeout. You can then set that event from within your button callback. The following code illustrates this (I've stripped your cancelling code to keep it short):\nimport threading\n\nclass MyThread(threading.Thread):\n\n def __init__(self)...
[ 4 ]
[]
[]
[ "multithreading", "pygtk", "python", "python_multithreading", "task" ]
stackoverflow_0008531993_multithreading_pygtk_python_python_multithreading_task.txt
Q: Python leave() takes exactly 1 argument (0 given) Ok so my problem is that when calling a method inside of my class from outside(top level), it takes the self parameter as if it would be an argument that it wants a value for, my class: class Client: def __init__(self, host='localhost', port=5000): try:...
Python leave() takes exactly 1 argument (0 given)
Ok so my problem is that when calling a method inside of my class from outside(top level), it takes the self parameter as if it would be an argument that it wants a value for, my class: class Client: def __init__(self, host='localhost', port=5000): try: self.server_socket = socket.socket(socket....
[ "The client instance is supposed to be created when the user presses the \"Connect\" button, so let it call a method GUI.connect, which creates self.client=Client().\nThen use a second method GUI.leave, which when called, delegates to self.client.leave():\nclass GUI():\n def __init__(self):\n self.client ...
[ 3 ]
[]
[]
[ "class", "methods", "python", "python_3.x", "self" ]
stackoverflow_0008555491_class_methods_python_python_3.x_self.txt
Q: write list of word from web site to txt file I want to make text file contain many Arabic word so I think to open website in python by: urlopen function and save the word in list then export it to text file . I'm new in python any help I will be thankful A: to save a file from the web: import urllib2 u = urll...
write list of word from web site to txt file
I want to make text file contain many Arabic word so I think to open website in python by: urlopen function and save the word in list then export it to text file . I'm new in python any help I will be thankful
[ "to save a file from the web:\nimport urllib2\n\nu = urllib2.urlopen('http://www.your-url-here.com/filename.txt')\nf = open('myfile.txt', 'w')\nf.write(u.read())\nf.close()\n\n", "Do the following:\n\nExtract the html from the website that contains the text\nclear it of html tags and symbols\nextract words.\nfilt...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008555187_python.txt
Q: Change 64bit Registry from 32bit Python I am having difficulty do understand this. If I'm correct, A 32bit Python can't run a code and change registry values in 64bit. Do I get it right? Or is there a switch to turn on in which enables this functionality? There is this: http://msdn.microsoft.com/en-us/library/aa38...
Change 64bit Registry from 32bit Python
I am having difficulty do understand this. If I'm correct, A 32bit Python can't run a code and change registry values in 64bit. Do I get it right? Or is there a switch to turn on in which enables this functionality? There is this: http://msdn.microsoft.com/en-us/library/aa384129%28v=VS.85%29.aspx But how do I use it wi...
[ "As the MSDN article you linked to explains, 64bit Windows has two registry views, one for 32bit and one for 64bit. By default a 32bit application (e.g. your Python script being executed by a 32bit Python interpreter) will access the 32bit view. You can force it to access the 64bit view using the flags mentioned in...
[ 6 ]
[]
[]
[ "32bit_64bit", "python", "registry", "window" ]
stackoverflow_0008506646_32bit_64bit_python_registry_window.txt
Q: Instantiating and using StanfordTagger within NLTK I apologize for the newbie-nature of this question - I have been trying to figure out Python packaging and namespaces, but the finer points seem to elude me. To wit, I would like to use the Python wrapper to Stanford part-of-speech tagger. I had no trouble finding...
Instantiating and using StanfordTagger within NLTK
I apologize for the newbie-nature of this question - I have been trying to figure out Python packaging and namespaces, but the finer points seem to elude me. To wit, I would like to use the Python wrapper to Stanford part-of-speech tagger. I had no trouble finding the documentation here, which provides a use sample: s...
[]
[]
[ "Suggestions:\na. Look on the nltk directory installed on your PC. I checked mine and stanford.py is not there (i.e. is missing in nltk/tag/ directory). You can find quickly where to look for running this:\nimport distutils.sysconfig\nprint distutils.sysconfig.get_python_lib()+'/nltk/tag/'\n\nb. If it's not there, ...
[ -1 ]
[ "nltk", "python" ]
stackoverflow_0008555312_nltk_python.txt
Q: single linked list reverse in python i'm trying to create a simple single linked list in python. (i know there is no need to implement list in python, but that's not the point) here is my code: class Node: def __init__(self,data): self.data = data self.next= None class List: def __init__(s...
single linked list reverse in python
i'm trying to create a simple single linked list in python. (i know there is no need to implement list in python, but that's not the point) here is my code: class Node: def __init__(self,data): self.data = data self.next= None class List: def __init__(self): self.firstNode = Node(None...
[ "def __show(self,start):\n if start.next:\n print start.data\n self.__show(start.next)\n\nthat only prints the current node if it has a next node, thats why the last node is never printed.\nshould be:\ndef __show(self,start):\n if start:\n print start.data\n self.__show(start.next)\n\nyo...
[ 3 ]
[]
[]
[ "linked_list", "python" ]
stackoverflow_0008555661_linked_list_python.txt
Q: Difference between xreadlines and for-looping a file Having a file object in Python 2.7: f = open('my_file', 'r') What would be the difference between for-looping the file (most common way) and using the xreadlines() function: for line in f: # Do something with line and for line in f.xreadlines(): # Do s...
Difference between xreadlines and for-looping a file
Having a file object in Python 2.7: f = open('my_file', 'r') What would be the difference between for-looping the file (most common way) and using the xreadlines() function: for line in f: # Do something with line and for line in f.xreadlines(): # Do something with line I mean, both options define a generato...
[ "From docs.python.org\nfile.xreadlines()\nThis method returns the same thing as iter(f).\n\nNew in version 2.1.\n\nDeprecated since version 2.3: Use for line in file instead.\n\n... and it's better to use the with keyword when working with files; again see the docs page.\nwith open('my_file', 'r') as f:\n for li...
[ 21 ]
[]
[]
[ "file", "python" ]
stackoverflow_0008555722_file_python.txt
Q: removing leading 0 from matplotlib tick label formatting How can I change the ticklabels of numeric decimal data (say between 0 and 1) to be "0", ".1", ".2" rather than "0.0", "0.1", "0.2" in matplotlib? For example, hist(rand(100)) xticks([0, .2, .4, .6, .8]) will format the labels as "0.0", "0.2", etc. I know t...
removing leading 0 from matplotlib tick label formatting
How can I change the ticklabels of numeric decimal data (say between 0 and 1) to be "0", ".1", ".2" rather than "0.0", "0.1", "0.2" in matplotlib? For example, hist(rand(100)) xticks([0, .2, .4, .6, .8]) will format the labels as "0.0", "0.2", etc. I know that this gets rid of the leading "0" from "0.0" and the traili...
[ "Although I am not sure it is the best way, you can use a matplotlib.ticker.FuncFormatter to do this. For example, define the following function.\ndef my_formatter(x, pos):\n \"\"\"Format 1 as 1, 0 as 0, and all values whose absolute values is between\n 0 and 1 without the leading \"0.\" (e.g., 0.7 is formatt...
[ 13 ]
[ "Multiple all your values by 10.\n" ]
[ -3 ]
[ "matplotlib", "plot", "python" ]
stackoverflow_0008555652_matplotlib_plot_python.txt
Q: PyUSB AttributeError: 'int' object has no attribute 'enumerate_devices' First time using PyUSB, trying to reverse engineer an eye-toy (Play Station) for OS X. Though I get the following error, when attempting to establish a testing collection. Traceback (most recent call last): File "eye.py", line 5, in <module> d...
PyUSB AttributeError: 'int' object has no attribute 'enumerate_devices'
First time using PyUSB, trying to reverse engineer an eye-toy (Play Station) for OS X. Though I get the following error, when attempting to establish a testing collection. Traceback (most recent call last): File "eye.py", line 5, in <module> dev = usb.core.find(0x054C,0x0155) File "/Library/Python/2.7/site-packages/usb...
[ "usb.core.find isn't used with positional arguments like that.\nI'm guessing that you have a vendor ID and a product ID.\nIf so, you should be doing this:\nusb.core.find(idVendor= 0x054C, idProduct= 0x0155)\n\nIf you try to provide positional parameters, you're settings the values of find_all and backend.\n" ]
[ 2 ]
[]
[]
[ "python", "pyusb" ]
stackoverflow_0008555642_python_pyusb.txt
Q: Python Searching and removing an item plus the following two from a text file I am just starting out with programming and am learning Python. I am having some troubles searching and removing from a text file. The text file contains a list of single spaced names. I need to have the user input a name and have it and...
Python Searching and removing an item plus the following two from a text file
I am just starting out with programming and am learning Python. I am having some troubles searching and removing from a text file. The text file contains a list of single spaced names. I need to have the user input a name and have it and the two following items removed from list. Right now I am able to find and remove...
[ "Assuming the contacts file is three lines per contact, an example file might look like this:\nFred\n58993884\nAnyTown\nMary\n61963888\nSomeCity\nBill\n78493883\nOtherTown\nAnne\n58273854\nAnyCity\n\nScript:\nx = raw_input('Enter Name of Contact to Delete: ')\n\n# do a case-insensitive match for names\ntarget = x.s...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008554832_python.txt
Q: Python - How to extract the last x elements from a list If the length of a python list is greater than a given value (say 10), then I want to extract the last 10 elements in that list into a new list. How can I do this? I tried getting the difference between len(my_list) - 10 and use it as: new_list = [(len(my_li...
Python - How to extract the last x elements from a list
If the length of a python list is greater than a given value (say 10), then I want to extract the last 10 elements in that list into a new list. How can I do this? I tried getting the difference between len(my_list) - 10 and use it as: new_list = [(len(my_list) - 10):] which does not work Any suggestions? Thanks in ad...
[ "it's just as simple as:\nmy_list[-10:]\n\nAdditional Comment: (from the comments section)\nIf the initial list is less than 10 elements, then this solution will still work yielding the whole list. E.g. if my_list = [1,2,3], then my_list[-10:] is equal to [1,2,3]\n", "This shows how to chop a long list into a max...
[ 140, 24, 16, 6 ]
[]
[]
[ "python" ]
stackoverflow_0008556076_python.txt
Q: How do I send an xml request and receive an xml response in Python? I'm currently using a WS where I send an XML Request to a url and then receive an XML Response. The request might look like the following: <RequestColour> ... </RequestColour> The response looks like: <ResponseColourOutput> ... </ResponseColourO...
How do I send an xml request and receive an xml response in Python?
I'm currently using a WS where I send an XML Request to a url and then receive an XML Response. The request might look like the following: <RequestColour> ... </RequestColour> The response looks like: <ResponseColourOutput> ... </ResponseColourOutput> Which libraries should I use in Python to send those xml requests...
[ "You can use the urllib2 module that comes with Python to make requests to a URL that can consume this.\nThe Python website has a decent tutorial on how to use this module to fetch internet resources. The next step is learning how to generate/consume XML.\nRelated SO answers for those steps:\n\nGenerating XML\nCon...
[ 5, 1, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0004660191_python_xml.txt
Q: Best way to process line at a time data from hdfs file from within CPython (without using stdin)? I would like to use CPython in a hadoop streaming job that needs access to supplementary information from a line-oriented file kept in a hadoop file system. By "supplementary" I mean that this file is in addition to t...
Best way to process line at a time data from hdfs file from within CPython (without using stdin)?
I would like to use CPython in a hadoop streaming job that needs access to supplementary information from a line-oriented file kept in a hadoop file system. By "supplementary" I mean that this file is in addition to the information delivered via stdin. The supplementary file is large enough that I can't just slurp it ...
[ "Check out this documentation for Streaming for using the Hadoop Distributed Cache in Hadoop Streaming jobs. You first upload the file to hdfs, then you tell Hadoop to replicate it everywhere before running the job, then it conveniently places a symlink in the working directory of the job. You can then just use pyt...
[ 3, 1 ]
[]
[]
[ "hadoop", "hdfs", "line", "python" ]
stackoverflow_0008556503_hadoop_hdfs_line_python.txt
Q: Brain stuck on overloading, How can I do this like a pythonista? I know that I can't overload functions in python, and I can't seem to get my head around using python to get the behavior I'm after. An Example: class Hop(object): def __init__(self, variety, aa, qty, time): self.variety = variety sel...
Brain stuck on overloading, How can I do this like a pythonista?
I know that I can't overload functions in python, and I can't seem to get my head around using python to get the behavior I'm after. An Example: class Hop(object): def __init__(self, variety, aa, qty, time): self.variety = variety self.aa = aa self.qty = qty self.time = time class HopBill(o...
[ "Just make two methods. Init hop_list in __init__ or the instances of HopBill will share the list:\nclass HopBill(object):\n def __init__(self):\n self.hop_list = []\n def add(self, hop):\n self.hop_list.append(hop)\n def addnew(self, variety, aa, qty, time):\n hop = Hop(variety, aa, qty, tim...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008554844_python.txt
Q: Prevent xml.etree.ElementTree.xml( ) from including website name in Element tags I'm using python and trying to take some XML and turn it into a dict. The code works fine except that some weird text is being added to the element tags which is then being added to the dict property names. This text seems to be the...
Prevent xml.etree.ElementTree.xml( ) from including website name in Element tags
I'm using python and trying to take some XML and turn it into a dict. The code works fine except that some weird text is being added to the element tags which is then being added to the dict property names. This text seems to be the value of the "WebServiceGeocodeQueryResult" attribute: "xmlns". My code looks somethi...
[ "That \"weird text\" is the namespace of the element. ElementTree expands element names to universal names.\nYou can preprocess your element names like this:\ntree = ET.XML(thexml)\net = ET.ElementTree(tree) # this is to include root node\nfor elem in et.getiterator(): #in python 2.7 or greater, getiterator() is un...
[ 5 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0008556501_python_xml.txt
Q: nested for loop for spliting string based on multiple delimiters I'm working on a Python assignment which requires a text to be delimited, sorted and printed as: sentences are delimited by . phrases by , then printed What I've done so far: text = "what time of the day is it. i'm heading out to the ball park, wi...
nested for loop for spliting string based on multiple delimiters
I'm working on a Python assignment which requires a text to be delimited, sorted and printed as: sentences are delimited by . phrases by , then printed What I've done so far: text = "what time of the day is it. i'm heading out to the ball park, with the kids, on this nice evening. are you willing to join me, on the ...
[ "You probably want:\n'sentence #%d:\\nphrase #%d: %d %s\\n' %(s+1,p+1,len(sentence),phrase)\n\nAnd in the inner loop, you certainly want to split sentence, not text again\n", "TypeError: not all arguments converted during string formatting\nIs a hint.\nYour loops are fine. \n'sentence #%d:','phrase #%d: %s' %(s+1...
[ 2, 2, 1, 0 ]
[]
[]
[ "for_loop", "list", "python", "string" ]
stackoverflow_0008556846_for_loop_list_python_string.txt
Q: Python Pyramid Learning Resource I have trid learning the framework with the help of the book, The Pyramid Web Application Development Framework. I have somewhat managed to understand up-to URL Dispatch. But I still find it difficult to grab some concepts. Can you lead me to some easy-for-newbie tutorials? Do I ne...
Python Pyramid Learning Resource
I have trid learning the framework with the help of the book, The Pyramid Web Application Development Framework. I have somewhat managed to understand up-to URL Dispatch. But I still find it difficult to grab some concepts. Can you lead me to some easy-for-newbie tutorials? Do I need previous experience of other web fr...
[ "I've been doing web dev for > 15 years, and > 10 with Python, and I found some of the concepts in Pyramid hard to understand, too.\nI'd suggest just pushing through; copy-n-paste if you have to, and keep on working. I'm noticing that concepts are 'gelling' for me after the fact, and what I used to find confusing I...
[ 14, 8, 6, 5, 2 ]
[]
[]
[ "pyramid", "python" ]
stackoverflow_0006858987_pyramid_python.txt
Q: Is 'dict', False. Yet gives ? >>> flob = {u'': [u''], u'DL': [u'DL'], u'Gender': [u'Both Sexes'], u'SQ': [u'SQ'], u'BP': [u'BP'], u'Location': [u'World Wide']} >>> flob is dict False >>> flob == dict False >>> type(flob) <type 'dict'> I ask it if its type dict, it says false. I ask it what type it is, it sa...
Is 'dict', False. Yet gives ?
>>> flob = {u'': [u''], u'DL': [u'DL'], u'Gender': [u'Both Sexes'], u'SQ': [u'SQ'], u'BP': [u'BP'], u'Location': [u'World Wide']} >>> flob is dict False >>> flob == dict False >>> type(flob) <type 'dict'> I ask it if its type dict, it says false. I ask it what type it is, it says dict. Why?
[ "Because you are comparing the object itself, the instance of dict, with dict... these two things are different entities. is is used to determine if two variable names are pointing at the same object.\n type({}) is dict # returns true.\n\n a = {}\n b = a\n a is b # returns true\n\n", "is is used or identity com...
[ 8, 3, 3 ]
[]
[]
[ "python", "types" ]
stackoverflow_0008557029_python_types.txt
Q: How to include a variable in REGEX in python? I am fairly new to python, and really new to regex! I am using the re module in python and trying to insert a variable into a re.compile statement. I have a file that includes these words as test - linux windows mac - So if I do re.compile('...u.', re.IGNORECASE) it wi...
How to include a variable in REGEX in python?
I am fairly new to python, and really new to regex! I am using the re module in python and trying to insert a variable into a re.compile statement. I have a file that includes these words as test - linux windows mac - So if I do re.compile('...u.', re.IGNORECASE) it will find linux. But how to I put ...u. into a variab...
[ "Could you show your code snippet for \"assigning '...u.' to a variable\"?\nIt works for me:\nimport re\nstr = 'linux windows mac'\na = re.compile('...u.',re.IGNORECASE)\na.match(str).group(0) # returns 'linux'\n\nregex = '...u.'\nb = re.compile(regex,re.IGNORECASE)\nb.match(str).group(0) # returns 'linux'\n\n" ]
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008557353_python_regex.txt
Q: Displaying multiple substring indices within a string by using recursion def subStringMatchExact(target, key): if (target.find(key) == -1): return [] else: foundStringAt = [target.find(key)] target = target[foundStringAt[0] + len(key):] return foundStringAt + subStringMatch...
Displaying multiple substring indices within a string by using recursion
def subStringMatchExact(target, key): if (target.find(key) == -1): return [] else: foundStringAt = [target.find(key)] target = target[foundStringAt[0] + len(key):] return foundStringAt + subStringMatchExact(target, key) string = subStringMatchExact("your code works with wrongly...
[ "The fast way\nYou don't have to implement your own solution, its already done! Use the finditer function from the re module:\n>>> import re\n>>> s = 'your code works with wrongly correlated coefficients which incorporates more costs'\n>>> matches = re.finditer('co', s)\n>>> positions = [ match.start() for match in...
[ 5, 4, 2, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0008557292_python_recursion.txt
Q: Recommend a library for testing the 'closedness' of '.stl' geometries? Some clarification is necessary, I am not referring to the Standard Template Library. I am referring to the '.stl file format'. < my eventual goal > A little background, my end goal is to use the Kinect and 'point cloud' type scanning to create...
Recommend a library for testing the 'closedness' of '.stl' geometries?
Some clarification is necessary, I am not referring to the Standard Template Library. I am referring to the '.stl file format'. < my eventual goal > A little background, my end goal is to use the Kinect and 'point cloud' type scanning to create .stl files. These .stl representations will be provided to 3D printing serv...
[ "You might have a look at Meshlab which by itself is an application, but it is based on the freely available VCG library. It contains dozens of algorithms related to your problem description: automatic vs semi-automatic hole-filling, boundary edge detection and input/output for the STL ASCII and binary format.\nHop...
[ 2 ]
[]
[]
[ "3d_modelling", "c++", "python" ]
stackoverflow_0008420630_3d_modelling_c++_python.txt
Q: python mp3 meta-tag I try to write a script than scan recursive a given directory and if found mp3 get and just print meta tag for it. What ever I passed to getEyeD3Tag I got an exception. Here is my code that i have written so far def getEyeD3Tags(path): try: trackInfo = eyeD3.Mp3AudioFile(path) ...
python mp3 meta-tag
I try to write a script than scan recursive a given directory and if found mp3 get and just print meta tag for it. What ever I passed to getEyeD3Tag I got an exception. Here is my code that i have written so far def getEyeD3Tags(path): try: trackInfo = eyeD3.Mp3AudioFile(path) tag = trackInfo.getT...
[ "To check if the file being parsed is a valid mp3, call the eyeD3.isMp3File(filename) method.\nThe following is from a short script I made to auto-sort my music folder.\ndef parseIDETag(self, path):\n if eyeD3.isMp3File(path):\n\nThat way, if the file isn't an mp3, it'll just skip over it.\nAlso, str(tag.get...
[ 2 ]
[]
[]
[ "meta_tags", "python" ]
stackoverflow_0003885309_meta_tags_python.txt
Q: ValidationError while using ModelForm Django I am very new to Django. I am working on a small project in which I am using ModelForm. For the date field, I want to do custom validation i.e. whenever a user enters a date before today's date it should display an error message near the date field. I have written code ...
ValidationError while using ModelForm Django
I am very new to Django. I am working on a small project in which I am using ModelForm. For the date field, I want to do custom validation i.e. whenever a user enters a date before today's date it should display an error message near the date field. I have written code as per Django's documentation, but it gives Valida...
[ "Your validation method needs to be called clean_due_date. In Django < 3 it should raise forms.ValidationError, but in Django 3 it should use core.exceptions.ValidationError.\nI have no idea what the get_summary and get_description methods are for, they aren't called and don't do anything useful.\nSee the Django 3 ...
[ 24 ]
[]
[]
[ "django", "django_forms", "python", "python_3.x" ]
stackoverflow_0008557885_django_django_forms_python_python_3.x.txt
Q: Change Django model column default using South I'm using South with a Postgresql DB for a Django project. There is a model field that I'd like to change the default value for going forward. I dont need previous records effected. Just new records. Do I need to do a migration for this, or just change the model? OLD ...
Change Django model column default using South
I'm using South with a Postgresql DB for a Django project. There is a model field that I'd like to change the default value for going forward. I dont need previous records effected. Just new records. Do I need to do a migration for this, or just change the model? OLD FIELD DETAIL: background_style = models.CharField(ma...
[ "You should run a migration. Any time you make a change to a model, no matter how insignificant, you should create a schema migration so that you can move backwards and forwards to any point in time without any \"magic\" edits.\n" ]
[ 0 ]
[]
[]
[ "django", "django_south", "python" ]
stackoverflow_0008558148_django_django_south_python.txt
Q: Python library issue I have a very peculiar issue with Python library. I downloaded the a python library source, changed some code and used python setup.py install to install the library. The original library was already installed with easy_install. Later on I further changed some source code and called the comman...
Python library issue
I have a very peculiar issue with Python library. I downloaded the a python library source, changed some code and used python setup.py install to install the library. The original library was already installed with easy_install. Later on I further changed some source code and called the command python setup.py install ...
[ "An installer typically loads a third-party library code in the site-packages directory. You can go to that directory and delete the library (that will include new and old versions). Then you can do a fresh install (using setup.py on your edited source).\nIf the library is somewhere else on the path, you can find...
[ 1 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0008558165_easy_install_python.txt
Q: Parallel queueing - Multiprocessing pool, python My goal is to go iterate through a directory and compute the MD5 of all the files within. I used code for a solution to a similar problem Parallel file matching, Python import os import re import sys import time import md5 from stat import S_ISREG import multipro...
Parallel queueing - Multiprocessing pool, python
My goal is to go iterate through a directory and compute the MD5 of all the files within. I used code for a solution to a similar problem Parallel file matching, Python import os import re import sys import time import md5 from stat import S_ISREG import multiprocessing global queue size_limit = 500000 target = sy...
[ "It is unclear whether your program is I/O or CPU bound i.e., a single process could perform better than several processes if the task is I/O bound e.g., by minimizing number of disk seeks. You could check this by specifying different nprocesses values (below) and see what provides better results in your case.\nYou...
[ 3, 1 ]
[]
[]
[ "multiprocessing", "multithreading", "parallel_processing", "python" ]
stackoverflow_0008557436_multiprocessing_multithreading_parallel_processing_python.txt
Q: How to use cache-control with python in GAE? I'm choosing whether to enable cache header and what difference it will make. The current code is this and I wonder whether I should enable the caching and what it will do? #seconds_valid = 8600 #self.response.headers['Cache-Control'] = "public, max-age=%d" % seconds_va...
How to use cache-control with python in GAE?
I'm choosing whether to enable cache header and what difference it will make. The current code is this and I wonder whether I should enable the caching and what it will do? #seconds_valid = 8600 #self.response.headers['Cache-Control'] = "public, max-age=%d" % seconds_valid self.response.headers['Cache-Control'] = 'no-...
[ "There is also AppEngine's caching reverse proxy / edge cache which may pick up your Cache-Control header if given a max-age and set to public like in your example. The edge cache is \"best effort\", meaning it is not 100% certain it will cache your response. \nMore information can be found here and here.\n", "Se...
[ 4, 0 ]
[]
[]
[ "caching", "google_app_engine", "html", "http", "python" ]
stackoverflow_0008550066_caching_google_app_engine_html_http_python.txt
Q: Python imports being overridden by the standard library (Python 2.4) I have a python package that I'm writing and I'm having an issue where the standard library is being imported instead of my files because of name clashes. For example, a file structure like below: package/__init__.py # No data in this file packa...
Python imports being overridden by the standard library (Python 2.4)
I have a python package that I'm writing and I'm having an issue where the standard library is being imported instead of my files because of name clashes. For example, a file structure like below: package/__init__.py # No data in this file package/module.py #!/usr/bin/env python print 'Loading module.py' import signal...
[ "The problem in this case is that the built-in signal module is imported as part of the interpreter's startup process. So by the time your code in module.py runs, there is already an entry in sys.modules under the name signal, with the built-in module as its value. Since sys.modules is the first place the import st...
[ 6, 0 ]
[ "File Hierarchy\n.\n|-- package\n| |-- __init__.py\n| |-- module.py\n| `-- signal.py\n`-- script\n`-- __init__.py\n\nscript.py\n#!/usr/bin/env python\nfrom package import module\n\npackage/module.py\n#!/usr/bin/env python\nprint 'Loading module.py'\nfrom package import signal\n\npackage/signal.py\n#!/usr/bin/...
[ -1 ]
[ "python", "python_2.4" ]
stackoverflow_0008556514_python_python_2.4.txt
Q: import webkit2png Python Quite a simple question here. I want to import webkit2png into another script, but I can't get it to work. import feedparser, webkit2png d = feedparser.parse('http://example.com/rss') link = d.entries[0].link title = d.entries[0].title webkit2png link This gives me a syntax error on line ...
import webkit2png Python
Quite a simple question here. I want to import webkit2png into another script, but I can't get it to work. import feedparser, webkit2png d = feedparser.parse('http://example.com/rss') link = d.entries[0].link title = d.entries[0].title webkit2png link This gives me a syntax error on line 5. What do I do wrong? File "...
[ "webkit2png seems to only have a command line interface, so importing the module won't help much, unless you try to replicate the code that is issued in the main function in webkit2png.\nI'd suggest to use the subprocess module to call the file directly, e.g.\nimport feedparser\nimport subprocess\n\nd = feedparser....
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004923054_python.txt
Q: statistic print in python I have a list of tuples, [(falseName, realName, positionOfMistake)] e.g.: [('Milter', 'Miller', 4), ('Manton','Manson',4), ('Moller', 'Miller', 2)] and I need to write a function that returns: Miller: Milter: 0.50 Moller: 0.50 Manson: Manton: 1.00 I was thinking: def nam...
statistic print in python
I have a list of tuples, [(falseName, realName, positionOfMistake)] e.g.: [('Milter', 'Miller', 4), ('Manton','Manson',4), ('Moller', 'Miller', 2)] and I need to write a function that returns: Miller: Milter: 0.50 Moller: 0.50 Manson: Manton: 1.00 I was thinking: def nameStatistics(nameList): D={}...
[ "You are not building your dictionary correctly, because your indentation is wrong in several places. Also, your print-statement does not refer to the dictionary you build. Try this:\ndef nameStatistics(nameList):\n D={}\n for firstName, lastName, unused in nameList:\n if lastName not in D:\n ...
[ 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0008558649_dictionary_python.txt
Q: Check if file is a named pipe (fifo) in python? I communicate with a named pipe, but I would like to check if it really is a named pipe BEFORE opening it. I check in Google but there is nothing, os.path.isfile() returns False, and I really need to check it. A: You can try: import stat, os stat.S_ISFIFO(os.sta...
Check if file is a named pipe (fifo) in python?
I communicate with a named pipe, but I would like to check if it really is a named pipe BEFORE opening it. I check in Google but there is nothing, os.path.isfile() returns False, and I really need to check it.
[ "You can try:\n import stat, os\n\n stat.S_ISFIFO(os.stat(path).st_mode)\n\ndocs\n" ]
[ 37 ]
[]
[]
[ "pipe", "python" ]
stackoverflow_0008558884_pipe_python.txt
Q: Python parse date format, ignore parts of string I want' to parse dates in this format, but ignore parts of the string. 'Wed, 27 Oct 1770 22:17:00 GMT' From what I have gathered, datetime does not support time zones very well. Which is fine, I really just want to ignore the timezone part of the string, without hav...
Python parse date format, ignore parts of string
I want' to parse dates in this format, but ignore parts of the string. 'Wed, 27 Oct 1770 22:17:00 GMT' From what I have gathered, datetime does not support time zones very well. Which is fine, I really just want to ignore the timezone part of the string, without having to do string manipulation on it. Is there somethin...
[ "Have you actually looked at the docs for dateutil?\ndateutil.parser.parse() does have arguments which let you control the precedence in its format guesser and it also has an ignoretz=True argument.\nIf that's not enough, there's probably some class you can override to implement your own precedence rules.\nOf cours...
[ 3, 3, 2, 0 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0004053924_datetime_python.txt
Q: making index with python the following is my question: data = ['a1_1 00000001\n', 'a1_2 00000002\n', 'a1_3 00000003\n', 'b1_1 00000004\n', 'b1_2 00000005\n', 'b1_3 00000006'] candidate = ['a', 'b'] for i in candidate: for j in data: if i in j.split()[0]: print i, j.split()[1] a 0...
making index with python
the following is my question: data = ['a1_1 00000001\n', 'a1_2 00000002\n', 'a1_3 00000003\n', 'b1_1 00000004\n', 'b1_2 00000005\n', 'b1_3 00000006'] candidate = ['a', 'b'] for i in candidate: for j in data: if i in j.split()[0]: print i, j.split()[1] a 00000001 a 00000002 a 00000003 ...
[ "data = ['a1_1 00000001\\n', 'a1_2 00000002\\n', 'a1_3 00000003\\n', 'b1_1 00000004\\n', 'b1_2 00000005\\n', 'b1_3 00000006']\n\ncandidate = ['a', 'b']\n\n\nfor i in candidate:\n print i, ', '.join(v for k,v in (a.split() for a in data) if k.startswith(i))\n\nprints:\na 00000001, 00000002, 00000003\nb 00000004, ...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008559148_python.txt
Q: Python - Update a value in a list of tuples What is the best way to update a value in a list of tuples? I currently do it like in the code below, but I suppose there is a cleaner and concise way. >>> foo = [('a', 'hello'), ('b', 'world')] >>> bar = dict(foo) >>> bar['b'] = 'friend' >>> foo = bar.items() >>> foo [(...
Python - Update a value in a list of tuples
What is the best way to update a value in a list of tuples? I currently do it like in the code below, but I suppose there is a cleaner and concise way. >>> foo = [('a', 'hello'), ('b', 'world')] >>> bar = dict(foo) >>> bar['b'] = 'friend' >>> foo = bar.items() >>> foo [('a', 'hello'), ('b', 'friend')] Edit: The reason...
[ "Your data structure (a list of tuple) is best referred as an associative list. As other pointed out, it is probably better to use a dictionary as you'll get better amortized cost on operation (insertion, deletion, and lookup are O(1) for a dictionary, but deletion and lookup are O(n) for associative list).\nConcer...
[ 13, 11, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008559217_python.txt
Q: Django : static files not loading My django project contains a folder STATIC in which there are it's child folders css, images, js and swf. My web-site can not locate these files raising a 404 in the development server running on the terminal. I have a settings_local.py file in which I have set the path such as (r...
Django : static files not loading
My django project contains a folder STATIC in which there are it's child folders css, images, js and swf. My web-site can not locate these files raising a 404 in the development server running on the terminal. I have a settings_local.py file in which I have set the path such as (running on ubuntu 11.04) STATIC_ROOT = '...
[ "If you are indeed using django 1.2 then you must install django-staticfiles. If you do not see it in the included requirements.txt from your client then he either did not freeze it out into the file, or was not using that feature and instead was just pointing at it via apache or another production server. \nFollow...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_1.2", "python" ]
stackoverflow_0008530868_django_django_1.2_python.txt
Q: python string parsing using regular expression Given a string #abcde#jfdkjfd, how can I get the string between two # ? And I also want that if no # pair(means no # or only one #), the function will return None. A: >>> import re >>> s = "abc#def#ghi#jkl" >>> re.findall(r"(?<=#)[^#]+(?=#)", s) ['def', 'ghi'] Expl...
python string parsing using regular expression
Given a string #abcde#jfdkjfd, how can I get the string between two # ? And I also want that if no # pair(means no # or only one #), the function will return None.
[ ">>> import re\n>>> s = \"abc#def#ghi#jkl\"\n>>> re.findall(r\"(?<=#)[^#]+(?=#)\", s)\n['def', 'ghi']\n\nExplanation:\n(?<=#) # Assert that the previous character is a #\n[^#]+ # Match 1 or more non-# characters\n(?=#) # Assert that the next character is a #\n\n", "Use (?<=#)(\\w+)(?=#) and capture the first...
[ 8, 2, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008559398_python_regex.txt
Q: Installing Shogun toolbox with MacPorts for Python 2.7 I am having a hard time trying to install the Shogun machine-learning toolbox via MacPorts. It seems that the only version MacPorts has declares Python 2.6 as a dependency and as a result MacPorts downloads and installs Python 2.6, numPy for Python 2.6 etc. Th...
Installing Shogun toolbox with MacPorts for Python 2.7
I am having a hard time trying to install the Shogun machine-learning toolbox via MacPorts. It seems that the only version MacPorts has declares Python 2.6 as a dependency and as a result MacPorts downloads and installs Python 2.6, numPy for Python 2.6 etc. The problem is I have Python 2.7 already installed and a host ...
[ "It looks like it needs to be converted to a python Portgroup port where the python version is implied from the current python see py-scipy for an example depending on py-numpy. \nAlso see the current threads on the macports mailing list for octave.\n" ]
[ 2 ]
[]
[]
[ "machine_learning", "macports", "python", "python_2.7", "shogun" ]
stackoverflow_0008556724_machine_learning_macports_python_python_2.7_shogun.txt
Q: Remote ssh in fabric without using fabfile I am writing a program to remotely execute a bunch of commands using fabric and gearman. The following is the Client code for Gearman import sys , os , json from fabric.api import * import gearman from gearman import GearmanClient def check_request_status(job_request): ...
Remote ssh in fabric without using fabfile
I am writing a program to remotely execute a bunch of commands using fabric and gearman. The following is the Client code for Gearman import sys , os , json from fabric.api import * import gearman from gearman import GearmanClient def check_request_status(job_request): if job_request.complete: print "Job ...
[ "Fixed it ,\n\njson was returning data in unicode format so used simplejson. \nIts env.host_string was the variable to hold hostname. \n\n:)\n" ]
[ 0 ]
[]
[]
[ "fabric", "gearman", "python" ]
stackoverflow_0008559349_fabric_gearman_python.txt
Q: python sum function forloop I am just wondering.. How can I sum over different elements in a for loop? for element in [(2,7),(9,11)] : g=sum(element[1]-element[0]+1) print g If I remove 'sum', I get: 6 3 A: I'm not sure what you do want to get. Is it this? >>> print sum(element[1]-element[0]+...
python sum function forloop
I am just wondering.. How can I sum over different elements in a for loop? for element in [(2,7),(9,11)] : g=sum(element[1]-element[0]+1) print g If I remove 'sum', I get: 6 3
[ "I'm not sure what you do want to get. Is it this?\n>>> print sum(element[1]-element[0]+1 for element in [(2,7), (9,11)])\n9\n\nThis generator expression is equivalent to\ntemp = []\nfor element in [(2,7), (9,11)]:\n temp.append(element[1]-element[0]+1)\nprint sum(temp)\n\nbut it avoids building a list in memory...
[ 11, 3, 2, 1, 1, 0 ]
[]
[]
[ "python", "sum" ]
stackoverflow_0008559495_python_sum.txt
Q: Twisted client connection lost I have a very simple client program: class EchoClient(Int32StringReceiver): def connectionMade(self): print 'connection made.' str = "<request><commands><dbtest /></commands></request>" self.sendString(str) print 'message sent' def stringRece...
Twisted client connection lost
I have a very simple client program: class EchoClient(Int32StringReceiver): def connectionMade(self): print 'connection made.' str = "<request><commands><dbtest /></commands></request>" self.sendString(str) print 'message sent' def stringReceived(self, line): print "rec...
[ "I'm onto something here:\ndef lengthLimitExceeded(self, length):\n print('length limit exceeded: {}'.format(length))\n\nprints:\nlength limit exceeded: 2147483793\nlength limit exceeded: 2147483793\n\nwhich is 0x80000091, so it seems that our propietary API is implementing the NString protocol in a strange way ...
[ 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0008560102_python_twisted.txt
Q: Python: os.walk() maintain hierarchy I am trying to use pythons os.walk to glob files from an arbitrary directory structure: matches = [] for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, name): matches.append(os.path.join(root, filename)) print matches this ni...
Python: os.walk() maintain hierarchy
I am trying to use pythons os.walk to glob files from an arbitrary directory structure: matches = [] for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, name): matches.append(os.path.join(root, filename)) print matches this nicely globs all the files, but I'd like to ...
[ "You already have this info, you're just not using it:\nfor root, dirnames, filenames in os.walk(path):\n # current folder: root\n # list of filenames in that folder: filenames\n # list of subdirectories in that folder: dirnames\n for filename in fnmatch.filter(filenames, name):\n matches.append(...
[ 0, 0 ]
[]
[]
[ "directory", "python", "recursion" ]
stackoverflow_0008560296_directory_python_recursion.txt
Q: subprocess running python getting import error I'm trying to run a python script from a python program by kicking it off from subprocess (The reason is that the main program has to have exited when the script runs, with a combination of wx.CallAfter and Close). However when the script runs I get an error on line 1...
subprocess running python getting import error
I'm trying to run a python script from a python program by kicking it off from subprocess (The reason is that the main program has to have exited when the script runs, with a combination of wx.CallAfter and Close). However when the script runs I get an error on line 1 with ImportError: No module named os which makes me...
[ "subprocess is there because os.exec* has been deprecated so I wouldn't suggest using that in place of Popen as someone suggested.\nI've seen this issue crop up when running from a frozen process. If that is the case then you're most likely inheriting a weird environment for the new python process.\nMost frozen scr...
[ 1, 0 ]
[]
[]
[ "python", "pythonpath", "subprocess" ]
stackoverflow_0008377745_python_pythonpath_subprocess.txt
Q: Trying to get Tor to work with Python, but keep getting connection refused.? I've been trying to get Tor to work with Python, but I've been hitting a brick wall. I simply can't get any of the examples to work. Here is one from Stackoverflow import urllib2 proxy = urllib2.ProxyHandler({'http':'127.0.0.1:8118'}) op...
Trying to get Tor to work with Python, but keep getting connection refused.?
I've been trying to get Tor to work with Python, but I've been hitting a brick wall. I simply can't get any of the examples to work. Here is one from Stackoverflow import urllib2 proxy = urllib2.ProxyHandler({'http':'127.0.0.1:8118'}) opener = urllib2.build_opener(proxy) print opener.open('http://check.torproject.org/...
[ "I've written an article showing how to use Tor with Python (using SOCKS) on http://blog.databigbang.com/distributed-scraping-with-multiple-tor-circuits/\nHope it helps.\n", "I have the same problem but can not find a solution!\nI am running Ubuntu, I can open TOR (latest version) with Vidalia, and surf the web c...
[ 3, 0, 0 ]
[]
[]
[ "proxy", "python", "tor", "urllib2" ]
stackoverflow_0007492531_proxy_python_tor_urllib2.txt
Q: Overriding FieldFile object in django How to add custom property or method to ImageFieldFile object with minimal pain? For instance i have this model: class SomeModelWithImage(models.Model): image = models.ImageField() and a class: class Custom(object): def __repr__(self): return "<Custom object>...
Overriding FieldFile object in django
How to add custom property or method to ImageFieldFile object with minimal pain? For instance i have this model: class SomeModelWithImage(models.Model): image = models.ImageField() and a class: class Custom(object): def __repr__(self): return "<Custom object>" I want to somehow override ImageFiel...
[ "In Django, one model field always corresponds to one database column, so what you want isn't possible. Also, your class names should always be singular, because an object of class 'Image' should just be a single image. I think you might want something more like the following:\nclass ImageSet(models.Model):\n im...
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0008560647_django_django_models_python.txt
Q: Mail inbox analyzer I need a tool to access my email inbox via some convenient interface. For example, I need to get the timestamps of letters from some address. I need that data to build some mailing statistics. What can I use to do that? Maybe there is an API in Thunderbird or something like that. I work under W...
Mail inbox analyzer
I need a tool to access my email inbox via some convenient interface. For example, I need to get the timestamps of letters from some address. I need that data to build some mailing statistics. What can I use to do that? Maybe there is an API in Thunderbird or something like that. I work under Windows. Thank you in adva...
[ "Your best bet is to use a programming language that has a simple IMAP library which you can use to connect to your account. Then you will have to write a script that can do your statistics. \nSince you asked for an API I assume that you know how to use a scripting language like PHP, Python or Ruby which all have a...
[ 2, 1 ]
[]
[]
[ "api", "email", "python", "statistics" ]
stackoverflow_0008560684_api_email_python_statistics.txt
Q: Chat application using django If i devlop a chat application using django will it have some performance problem? Can i do server push in django? I want to have PM and room discussions as well. A: How about using tornado? I tried demo chat application of Tornado. And also Tornado claims to have a better performan...
Chat application using django
If i devlop a chat application using django will it have some performance problem? Can i do server push in django? I want to have PM and room discussions as well.
[ "How about using tornado? I tried demo chat application of Tornado.\nAnd also Tornado claims to have a better performance than django.\nLet me know your thoughts.\n", "I released a Django app on Pypi and Github that provides a multi-user web chat.\nIt's based on Gevent: works well in multithreaded environments, b...
[ 6, 6, 1, 1, 1, 1 ]
[]
[]
[ "chat", "django", "performance", "private_messaging", "python" ]
stackoverflow_0002093822_chat_django_performance_private_messaging_python.txt
Q: Python "in" does not check for type? >>> False in [0] True >>> type(False) == type(0) False The reason I stumbled upon this: For my unit-testing I created lists of valid and invalid example values for each of my types. (with 'my types' I mean, they are not 100% equal to the python types) So I want to iterate the ...
Python "in" does not check for type?
>>> False in [0] True >>> type(False) == type(0) False The reason I stumbled upon this: For my unit-testing I created lists of valid and invalid example values for each of my types. (with 'my types' I mean, they are not 100% equal to the python types) So I want to iterate the list of all values and expect them to pass...
[ "The problem is not the missing type checking, but because in Python bool is a subclass of int. Try this:\n>>> False == 0\nTrue\n>>> isinstance(False, int)\nTrue\n\n", "According to the documentation, __contains__ is done by iterating over the collection and testing elements by ==. Hence the actual problem is cau...
[ 15, 6, 4, 3 ]
[]
[]
[ "boolean", "identity", "python", "types", "unit_testing" ]
stackoverflow_0008560320_boolean_identity_python_types_unit_testing.txt
Q: How can you define a variable that will never be matched in Python? Part of my code relies on a comparison between two items, and it may end up comparing against a variable that doesn't exist. As such I will go through and put in filler variable values for the sets to make sure they both are defined and can be com...
How can you define a variable that will never be matched in Python?
Part of my code relies on a comparison between two items, and it may end up comparing against a variable that doesn't exist. As such I will go through and put in filler variable values for the sets to make sure they both are defined and can be compared. However, if I add a filler value I don't want it to be possible to...
[ "How about simply:\nmissing = object()\n\nand then use missing in comparisons (it won't compare equal to any other object, including None).\n", "Seems like you could define a custom class to compare against. For example:\nclass NoValue:\n pass\n\nif someValue is NoValue:\n doSomething()\n\nThe comparison s...
[ 8, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008561277_python.txt
Q: Django: filter foreign keys I have the following code: query = Entry.objects.all() print 'authors ' + repr([x.id for x in authors]) print 'query ' + repr(query) print 'query ids ' + repr([x.author.id for x in query]) query.filter(author__in=authors) print 'filtered i...
Django: filter foreign keys
I have the following code: query = Entry.objects.all() print 'authors ' + repr([x.id for x in authors]) print 'query ' + repr(query) print 'query ids ' + repr([x.author.id for x in query]) query.filter(author__in=authors) print 'filtered ids ' + repr([x.author.id for x in...
[ "When you call query.filter(author__in=authors), it returns a new queryset. It does not modify the existing queryset. \nIf you assign the new queryset to query, then you will get the result you were expecting. \nquery = query.filter(author__in=authors)\nprint 'filtered ids ' + repr([x.author.id for x in query])\n\n...
[ 3, 1 ]
[]
[]
[ "django", "django_queryset", "filter", "model", "python" ]
stackoverflow_0008561440_django_django_queryset_filter_model_python.txt
Q: Computing time tables I am designing a program to allocate faculty to subjects based on their preferences; and then allocate hours for each student; based on preferences of each teacher and characteristics of each subject (dont schedule a tough subject for friday afternoon). It leads to 100k-ish combinations. An...
Computing time tables
I am designing a program to allocate faculty to subjects based on their preferences; and then allocate hours for each student; based on preferences of each teacher and characteristics of each subject (dont schedule a tough subject for friday afternoon). It leads to 100k-ish combinations. And there are lots of special...
[ "You may try setting the possibilities up as a weighted graph or tree. Both are very 'traditional' data structures as far as I can tell, and should play nicely with different libraries. Like Martin Stam mentioned, you could search through them using Dijkstra's or any other type of search algorithm.\nI'm not sure I ...
[ 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0008561261_algorithm_python.txt
Q: Python templates and function execution I have a question, which is basically a question on Python template engine capability. Suppose I have the following code: import string as st def foo(bar): if bar: t = 'world' else: t = 'not happening' return t temp = st.Template("hello $bar") ...
Python templates and function execution
I have a question, which is basically a question on Python template engine capability. Suppose I have the following code: import string as st def foo(bar): if bar: t = 'world' else: t = 'not happening' return t temp = st.Template("hello $bar") final = temp.some_substitute_magic() and the...
[ "Quite easy actually :)\nJust emulate the workings of a dict and you're done.\nclass Scope(object):\n def __getitem__(self, key):\n return 'call for %s' % key\n\nprint final.substitute(Scope())\n\n" ]
[ 0 ]
[]
[]
[ "function", "python", "templates" ]
stackoverflow_0008561434_function_python_templates.txt
Q: keeping data in a raw mode while passing to re.match In the source file, I have within the line the following data item (as is, len=11): (?i:\'sa\') When I pass it to a re.match, the matching (.groupdict()) value, written into a file, appears to be: (?i:\sa\) (len=9) Question is, how to I preserve value raw (as ...
keeping data in a raw mode while passing to re.match
In the source file, I have within the line the following data item (as is, len=11): (?i:\'sa\') When I pass it to a re.match, the matching (.groupdict()) value, written into a file, appears to be: (?i:\sa\) (len=9) Question is, how to I preserve value raw (as in the following b example), between re.match and file.wri...
[ "Probably string_escape is what you need:\n>>> s = raw_input()\n(?i:\\'sa\\')\n>>> s\n\"(?i:\\\\'sa\\\\')\"\n>>> len(s)\n11\n>>> s.decode('string_escape')\n\"(?i:'sa')\"\n>>> len(s.decode('string_escape'))\n9\n\n" ]
[ 2 ]
[]
[]
[ "python", "string", "text" ]
stackoverflow_0008561600_python_string_text.txt
Q: Comparing string differences to a list of strings I have a method, that computes the number of differences in two strings, and outputs where the differences are. def method(a): count=0 s1="ABC" for i in range (len(a)): if not a[i]==s1[i]: count=count+1 else: coun...
Comparing string differences to a list of strings
I have a method, that computes the number of differences in two strings, and outputs where the differences are. def method(a): count=0 s1="ABC" for i in range (len(a)): if not a[i]==s1[i]: count=count+1 else: count=count+0 return a,count,difference(a, s1) On inpu...
[ "Ok, after clarification, instead of hardcoding s1, make your method take it as argument:\ndef method(a, s1):\n count=0\n for i in range (len(a)):\n if not a[i]==s1[i]:\n count=count+1\n else:\n count=count+0\n return a,count,difference(a, s1)\n\nThen use list compherens...
[ 2, 1 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0008561586_list_python_string.txt
Q: How can I remove backup files, I don't need backup files The original file name is view.py, forms.py but python automatically adds/saves some file named view.pyc, forms.pyc I want to delete those extra view.pyc and forms.pyc files. Why do I get those .pyc files? Or how can I tell python not to create those extra f...
How can I remove backup files, I don't need backup files
The original file name is view.py, forms.py but python automatically adds/saves some file named view.pyc, forms.pyc I want to delete those extra view.pyc and forms.pyc files. Why do I get those .pyc files? Or how can I tell python not to create those extra files with .pyc extension?
[ "pyc files are compiled bytecode files, not backup files\n\n6.1.2 ``Compiled'' Python files http://docs.python.org/release/1.5.1p1/tut/node43.html\n\nAs an important speed-up of the start-up time for short programs that use a lot of standard modules, if a file called \"spam.pyc\" exists in the directory where \"spa...
[ 5, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008562144_python.txt
Q: Python: counting specific words in file of corpus I would like to count specific words in each file of my corpus.. here is my code.. it works fine. num= nltk.FreqDist( (target,fileid) for fileid in reader.fileids() for w in reader.words(fileid) for target in ['have']) but results is l...
Python: counting specific words in file of corpus
I would like to count specific words in each file of my corpus.. here is my code.. it works fine. num= nltk.FreqDist( (target,fileid) for fileid in reader.fileids() for w in reader.words(fileid) for target in ['have']) but results is like this.. FreqDist: '2009.txt': 141205, '20.txt': 4320...
[ "I'm not familiar with NLTK, but it seems you are traversing a dict-like object.\nWhat about this?\nfor file, n in num.iteritems():\n print file, n\n\n" ]
[ 2 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0008562079_nltk_python.txt
Q: Get url parameters for using in a dynamic filter in django Consider this url: www.anysite.com/get_count/?sex=5&sex=6&city=5&city=7&job=7&job=8...... For using in dynamic query in view: model = anyModel.objects.filter(sex=5).filter(sex=6).filter(city=5).... How can I insert url parameters in this query? A: What...
Get url parameters for using in a dynamic filter in django
Consider this url: www.anysite.com/get_count/?sex=5&sex=6&city=5&city=7&job=7&job=8...... For using in dynamic query in view: model = anyModel.objects.filter(sex=5).filter(sex=6).filter(city=5).... How can I insert url parameters in this query?
[ "What about something like this?\nmodel = anyModel.objects\nfor k,vals in request.GET.lists():\n for v in vals:\n model = model.filter(**{k: v})\n\nOr, if you want to change the type of filter, (to, for example, __contains), you can replace last line with something like:\n model = model.filter(**{\...
[ 7, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008561559_django_python.txt
Q: fsolve always returning the guess/estimate I'm using scipy's optimize.fsolve function for the first time to find the roots to an equation. The problem is that whatever number I use as the guess/estimate value is what I get back as my answer (to within about 8 decimal places). When using full_output=True, I get the...
fsolve always returning the guess/estimate
I'm using scipy's optimize.fsolve function for the first time to find the roots to an equation. The problem is that whatever number I use as the guess/estimate value is what I get back as my answer (to within about 8 decimal places). When using full_output=True, I get the exitflag to be '1', which is supposed to mean t...
[ "I think your equation doesn't do what you think it does. For one thing, when I try it, it doesn't return the guess; it returns a number close to the guess. It's very unstable and that seems to be confusing fsolve. For example:\n>>> V_0 = 100\n>>> c_sqr = 3e8 ** 2\n>>> guess = 5\n>>> fsolve(func, guess)\narray([ 5....
[ 6, 1 ]
[]
[]
[ "equation_solving", "python", "scipy" ]
stackoverflow_0008562080_equation_solving_python_scipy.txt
Q: Suds Error: BadStatusLine in httplib I am using suds 0.3.6. When creating a suds client, I randomly get an error: httplib.py, _read_status(), line 355, class httplib.BadStatusLine' Here is the code used to create the client: imp = Import('http://www.w3.org/2001/XMLSchema') imp.filter.add('http://tempuri.org/enc...
Suds Error: BadStatusLine in httplib
I am using suds 0.3.6. When creating a suds client, I randomly get an error: httplib.py, _read_status(), line 355, class httplib.BadStatusLine' Here is the code used to create the client: imp = Import('http://www.w3.org/2001/XMLSchema') imp.filter.add('http://tempuri.org/encodedTypes') imp.filter.add('http://tempuri...
[ "I had the same problem. To troubleshoot the problem, I turned on full suds logging:\nlogging.basicConfig(level=logging.INFO)\nlogging.getLogger(\"suds.client\").setLevel(logging.DEBUG)\nlogging.getLogger(\"suds.transport\").setLevel(logging.DEBUG)\nlogging.getLogger(\"suds.xsd.schema\").setLevel(logging.DEBUG)\nlo...
[ 8, 1, -2 ]
[]
[]
[ "httplib", "python", "soap", "suds" ]
stackoverflow_0007725693_httplib_python_soap_suds.txt
Q: better for-loop syntax for detecting empty sequences? Is there a better way to write the following: row_counter = 0 for item in iterable_sequence: # do stuff with the item counter += 1 if not row_counter: # handle the empty-sequence-case Please keep in mind that I can't use len(iterab...
better for-loop syntax for detecting empty sequences?
Is there a better way to write the following: row_counter = 0 for item in iterable_sequence: # do stuff with the item counter += 1 if not row_counter: # handle the empty-sequence-case Please keep in mind that I can't use len(iterable_sequence) because 1) not all sequences have known length...
[ "for item in iterable:\n break\nelse:\n # handle the empty-sequence-case here\n\nOr \nitem = next(iterator, sentinel)\nif item is sentinel:\n # handle the empty-sequence-case here \n\nIn each case one item is consumed if it is present.\n\nAn example of empty_adapter()'s implementation mentioned in the com...
[ 8, 3, 2, 2, 0 ]
[]
[]
[ "for_loop", "python", "syntax" ]
stackoverflow_0004557255_for_loop_python_syntax.txt
Q: Compilng python3.2 C module, linker asks for 'python26.lib' I'm trying to compile the example visual studio solution that comes with the 3.2 source. I copied the directory up one level as it says to do. I am not using the same visual studio as they used. For some reason I get this: 1>LINK : fatal error LNK1181: ca...
Compilng python3.2 C module, linker asks for 'python26.lib'
I'm trying to compile the example visual studio solution that comes with the 3.2 source. I copied the directory up one level as it says to do. I am not using the same visual studio as they used. For some reason I get this: 1>LINK : fatal error LNK1181: cannot open input file 'python26.lib' I don't understand how the l...
[ "I wouldn't use the example code that comes with the source, your project settings must have Python26.lib in the input list. It is much easier to use distutils instead, this is a setup.py for a Simple module:\nfrom distutils.core import setup, Extension\n\nmodule1 = Extension('Simple',\n sources...
[ 1 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0008562587_c++_python.txt
Q: UnicodeDecodeError: 'ascii' codec can't decode byte XX with urllib2 urlopen() I'm trying to post some data to a url, but I'm running int a python error that doesn't make any sense to me. Here is the error: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/pytho...
UnicodeDecodeError: 'ascii' codec can't decode byte XX with urllib2 urlopen()
I'm trying to post some data to a url, but I'm running int a python error that doesn't make any sense to me. Here is the error: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/logging/__init__.py", line 765, in emit UnicodeDecodeError: 'ascii' codec can'...
[ "I was able to get my problem to go away by just using urllib and not urllib2. I still don't know what caused the problem, but this workout was fine.\nurl = 'http://google.com/'\nf = urllib.urlopen(url, params)\n\n" ]
[ 1 ]
[]
[]
[ "django_nonrel", "python", "urllib2" ]
stackoverflow_0008452285_django_nonrel_python_urllib2.txt
Q: questions about implementing pyinotify instance to monitor directory I have some basic questions about pyinotify that I can't seem to find the answers to elsewhere. 1) For a continuous directory monitor (and event processor) is it necessary to have a while( True ) loop or is the continuous event 'loop' handled b...
questions about implementing pyinotify instance to monitor directory
I have some basic questions about pyinotify that I can't seem to find the answers to elsewhere. 1) For a continuous directory monitor (and event processor) is it necessary to have a while( True ) loop or is the continuous event 'loop' handled by the notify watch and ended when I remove the watch? 2) What happens if f...
[ "\nis it necessary to have a while( True ) loop\n\nYou'll need a while-loop, but it can be set up implicitly by calling the notifier.loop method:\n wm = pyinotify.WatchManager()\n mask = pyinotify.IN_CREATE\n notifier = pyinotify.Notifier(wm, MyProcessEvent(path))\n wdd = wm.add_watch(path, mask, rec=Tr...
[ 2 ]
[]
[]
[ "events", "inotify", "linux", "loops", "python" ]
stackoverflow_0008562376_events_inotify_linux_loops_python.txt
Q: Mongodb data statistics visualization using matplotlib I want to get visualized statistics from my data in mongodb using matplotlib, but the way I'm using now is really weird. I queried the mongodb 30 times for getting day-by-day data, which is already slow and dirty, especially when I'm getting the result from so...
Mongodb data statistics visualization using matplotlib
I want to get visualized statistics from my data in mongodb using matplotlib, but the way I'm using now is really weird. I queried the mongodb 30 times for getting day-by-day data, which is already slow and dirty, especially when I'm getting the result from somewhere else instead of on the server. I wonder if there is ...
[ "UPDATE:\nI fundamentally misunderstood the problem. Felix was querying mongoDB to figure out how many items fell into each range; therefore, my approach didn't work, because I was trying to ask mongoDB for the items. Felix has a lot of data, so this is completely unreasonable.\nFelix, here's an updated function wh...
[ 2, 0 ]
[]
[]
[ "matplotlib", "mongodb", "python" ]
stackoverflow_0008559080_matplotlib_mongodb_python.txt
Q: How do identify a USB modem /dev on LINUX with Python If I have a USB modem that I am accessing using Python pyserial module, it requires the device to be identified '/dev/ttyACM0 for example. If the modem is attached to a USB hub it no longer appears in /dev/tty... How do identify it programmatically from my Pyt...
How do identify a USB modem /dev on LINUX with Python
If I have a USB modem that I am accessing using Python pyserial module, it requires the device to be identified '/dev/ttyACM0 for example. If the modem is attached to a USB hub it no longer appears in /dev/tty... How do identify it programmatically from my Python code so regardless of whether it has been changed or no...
[ "This sounds like a bug in the linux kernel. If you can, try a more recent version.\nIf that fails, check the last few lines of the output of dmesg or in the file /var/log/messages (the latter depends on your distribution; if that file doesn't exist or doesn't contain what you're looking for, then check the other f...
[ 1, 1 ]
[]
[]
[ "linux", "python", "usb" ]
stackoverflow_0008561577_linux_python_usb.txt
Q: Python logging to different destination using a configuration file I want to use a configuration file to create two loggers which will log in two distinct files. My configuration file looks like: [loggers] keys=root,main,zipper [handlers] keys=main,zip [formatters] keys=fmt [logger_root] level=DEBUG handlers=ma...
Python logging to different destination using a configuration file
I want to use a configuration file to create two loggers which will log in two distinct files. My configuration file looks like: [loggers] keys=root,main,zipper [handlers] keys=main,zip [formatters] keys=fmt [logger_root] level=DEBUG handlers=main [logger_main] level=DEBUG handlers=main qualname=MAIN [logger_zippe...
[ "The problem is that the qualified name used in the configuration file:\n[logger_zipper]\nlevel=DEBUG\nqualname=UPLOAD\nhandlers=zip\n\ndoesn't match the one used in the code:\nlog_z = logging.getLogger(\"zipper\")\n\nUse any of these combinations:\n\nqualname=zipper and logging.getLogger(\"zipper\")\nqualname=UPLO...
[ 7 ]
[]
[]
[ "config", "logging", "python" ]
stackoverflow_0008562954_config_logging_python.txt
Q: Python singleton class I'm writing a test suite for firefox 5.1 and selenium webdrive v.2 on os x 10.6 with Python 2.7. Everything is working fine except the creation of a singleton class, which should guarantee only one instance of firefox: def singleton(cls): instances = {} def getinstance(): if ...
Python singleton class
I'm writing a test suite for firefox 5.1 and selenium webdrive v.2 on os x 10.6 with Python 2.7. Everything is working fine except the creation of a singleton class, which should guarantee only one instance of firefox: def singleton(cls): instances = {} def getinstance(): if cls not in instances: ...
[ "Your decorator seems to work OK for me as far as creating a single instance of a class, so I don't see your issue #1. It isn't doing quite what you think it is: each time you use the decorator there's a fresh instances dictionary, and there's only ever one item in it, so there's not actually any reason to use a di...
[ 7, 2 ]
[]
[]
[ "firefox", "python", "selenium_rc", "singleton" ]
stackoverflow_0008563130_firefox_python_selenium_rc_singleton.txt
Q: How to hide everything after .cgi? in the address bar I have a html file with a form: <form method="get" enctype="multipart/form-data" action="bin/a_python_script.cgi"> (I 'have to' use method="get", because when I use method="post" I get weird 'Page expired' problems with the 'back' button in Internet Explorer 8...
How to hide everything after .cgi? in the address bar
I have a html file with a form: <form method="get" enctype="multipart/form-data" action="bin/a_python_script.cgi"> (I 'have to' use method="get", because when I use method="post" I get weird 'Page expired' problems with the 'back' button in Internet Explorer 8) The resulting page shows this in the address bar: http://...
[ "Unfortunately, there are no options other than changing the form method from 'get' to 'post'.\nGET encodes all of the form fields into the URL. There's no way to hide anything without removing the data.\nA quick Google search for \"prevent page expired message\" turns up quite a few results (the examples are mostl...
[ 4, 2, 1, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0008563503_cgi_python.txt
Q: more then one expression in list comprehension? i want to use a list comprehension to split elements of a list. line = [x.split(", ") for x in lineList] At same time I'd like to remove tailing and leading characters of the elements (.rstrip('"')/.lstrip('"'). But a 'list' object has no attribute 'rstrip'. Is ther...
more then one expression in list comprehension?
i want to use a list comprehension to split elements of a list. line = [x.split(", ") for x in lineList] At same time I'd like to remove tailing and leading characters of the elements (.rstrip('"')/.lstrip('"'). But a 'list' object has no attribute 'rstrip'. Is there a way to achieve this within a comprehension or do ...
[ "Try something like this : \nline = [[y.rstrip('\"') for y in x.split(\", \")] for x in lineList]\n\nwith two list comprehensions inside.\n", "If you want to remove both leading and trailing quotes, why not using strip() directly? Also, if you want to flatten the list of lists:\nline = sum([[y.strip('\"') for y i...
[ 4, 3, 1 ]
[]
[]
[ "list", "list_comprehension", "python", "strip" ]
stackoverflow_0008562203_list_list_comprehension_python_strip.txt
Q: Printing different types of attributes and listing all App elements for the selected type in Group Element by Python Sorry for misunderstanding title, but I couldn't explained my issue in a small title. It's not a big problem but confusing anyway. Current output: 1) Deployment 2) Service Status 3) List Servers 4) ...
Printing different types of attributes and listing all App elements for the selected type in Group Element by Python
Sorry for misunderstanding title, but I couldn't explained my issue in a small title. It's not a big problem but confusing anyway. Current output: 1) Deployment 2) Service Status 3) List Servers 4) Restart Service 5) Restart Server 6) Execute Commands on Servers Make your choice: 4 1) Group 2) Single Machine Group or ...
[ "I'm a bit confused about what you're asking. I'm also confused by your XML schema.\nHowever, I would recommend that you familiarise yourself with XPATH. My preferred XML lib is lxml.\nYou can use xpath expressions to query your XML data. The biggest caveat is that your XML may not comply with your desired data mod...
[ 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0008563428_python_xml.txt
Q: Most pythonic way to handle dialogboxes? I made a function in my wxpython app that pop up a passwordbox. The code, that's present in dialogs.py, looks like this: def password_dialog(self, password): # Only ask for password if it actually exist if password == 'False': return True question = 'Pu...
Most pythonic way to handle dialogboxes?
I made a function in my wxpython app that pop up a passwordbox. The code, that's present in dialogs.py, looks like this: def password_dialog(self, password): # Only ask for password if it actually exist if password == 'False': return True question = 'Put in password:' dialog = wx.PasswordEntryD...
[ "I dont think your dialog function should be raising exceptions in this case. Just have it return True or False depending on whether the validation passes or not. Then all you need to do is:\nvalidated = dialogs.password_dialog(self, opts.generic['password'])\nif validated:\n print \"Yay\"\nelse:\n print \"Bo...
[ 1 ]
[]
[]
[ "exception", "python", "wxpython" ]
stackoverflow_0008562868_exception_python_wxpython.txt
Q: Default array parameters unexpectedly not empty Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument def stackdemo(stack=[]): stack.append('q') return stack stackdemo() print stackdemo() returns ['q','q'], whereas stackdemo([]) print stackdemo([]) with the same function returns...
Default array parameters unexpectedly not empty
Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument def stackdemo(stack=[]): stack.append('q') return stack stackdemo() print stackdemo() returns ['q','q'], whereas stackdemo([]) print stackdemo([]) with the same function returns just ['q'], as expected. Why does Python appear to ...
[ "A list is a mutable object. From doc:\nThe default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.\nDo it with None:\ndef stackdemo(stack=None):\n if stack is None:\n stack = []\n stack.append('q')\n ...
[ 3, 1 ]
[]
[]
[ "arrays", "optional_parameters", "python" ]
stackoverflow_0008564264_arrays_optional_parameters_python.txt
Q: In python, how to check the function form of an imported module method For example, I imported Tkinter, and want to check how Tkinter.Frame.__init__ parameter list was defined, and possibly, what is inside the function. I am expecting something like Tkinter.Frame.__init__.__doc__. (I am not using Python IDE, so t...
In python, how to check the function form of an imported module method
For example, I imported Tkinter, and want to check how Tkinter.Frame.__init__ parameter list was defined, and possibly, what is inside the function. I am expecting something like Tkinter.Frame.__init__.__doc__. (I am not using Python IDE, so the parameter list won't pop up)
[ "I suggest you have a look at inspect.getargspec and inspect.getsource:\n>>> import inspect\n\n>>> inspect.getargspec(inspect.getargspec)\nArgSpec(args=['func'], varargs=None, keywords=None, defaults=None)\n>>> print inspect.getsource(inspect.getsource)\ndef getsource(object):\n \"\"\"Return the text of the sour...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0008564218_python.txt
Q: Can't open python programs from command prompt When attempting to run .py files from the command prompt I get this, C:\users\ocean>python helloworld.py python: can't open file 'helloworld.py': [Errno 2] No such file or directory The environment variables are already set to ;C\python27 and ;C\python32 (yes, I'm ru...
Can't open python programs from command prompt
When attempting to run .py files from the command prompt I get this, C:\users\ocean>python helloworld.py python: can't open file 'helloworld.py': [Errno 2] No such file or directory The environment variables are already set to ;C\python27 and ;C\python32 (yes, I'm running both releases of python.) Do I have to set a n...
[ "You have to either do:\npython c:\\path\\to\\the\\file.py\n\nor\ncd c:\\path\\to\\the\npython file.py\n\n" ]
[ 2 ]
[]
[]
[ "cmd", "command_prompt", "python", "windows_7" ]
stackoverflow_0008564430_cmd_command_prompt_python_windows_7.txt
Q: psycopg2 - how to always cast non-string value to string psycopg2's doc has an instruction on how to cast a specific type to a different type: Psycopg converts decimal/numeric database types into Python Decimal objects. Can I have float instead? You can register a customized adapter for PostgreSQL decimal type:...
psycopg2 - how to always cast non-string value to string
psycopg2's doc has an instruction on how to cast a specific type to a different type: Psycopg converts decimal/numeric database types into Python Decimal objects. Can I have float instead? You can register a customized adapter for PostgreSQL decimal type: DEC2FLOAT = psycopg2.extensions.new_type( psycop...
[ "You could delete all the typecasters and receive everything in the postgres string representation:\nimport psycopg2\n\nfor k in psycopg2.extensions.string_types.keys():\n del psycopg2.extensions.string_types[k]\n\ncnn = psycopg2.connect('')\ncur = cnn.cursor()\ncur.execute(\"select 1::int, now()::timestamp, 'he...
[ 4, 0 ]
[]
[]
[ "psycopg2", "python" ]
stackoverflow_0008538413_psycopg2_python.txt
Q: UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 126: ordinal not in range(128) Okay, I have read through many similar questions, and I believe I am following the advice correctly, but somehow my code is still not working. I have parsed an xml file. I have read on here that the output...
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 126: ordinal not in range(128)
Okay, I have read through many similar questions, and I believe I am following the advice correctly, but somehow my code is still not working. I have parsed an xml file. I have read on here that the output is now unicode. I am using the csv writer to write output to a file. So, in my code I have tried to encode in utf...
[ "When you call mystring.encode(..., it's not changing the string in-place; it returns a new string.\n" ]
[ 9 ]
[]
[]
[ "csv", "encode", "python", "xml" ]
stackoverflow_0008564668_csv_encode_python_xml.txt
Q: Issue Python code matching files Recently with help of stackoverflow i came to know how to match text files using python now im facing some small problem with same code...it performs following task Input to program is two text files File 1 C1orf159 FAM79A IGFBP2 RNF25 . . . . File 2 ACVR2B CACNA1A RNF25 ...
Issue Python code matching files
Recently with help of stackoverflow i came to know how to match text files using python now im facing some small problem with same code...it performs following task Input to program is two text files File 1 C1orf159 FAM79A IGFBP2 RNF25 . . . . File 2 ACVR2B CACNA1A RNF25 IGF2 . . . I wrote one python scri...
[ "Are you looking for the intersection of the two files? That's\ns1 = set(open(\"f1.txt\", \"r\"))\ns2 = set(open(\"f2.txt\", \"r\"))\n\nfor ln in s1 & s2:\n file3.write(ln)\n\n", "You want line1.strip() == line2.strip(). in in this case will match substrings. You are after exact matches it sounds like.\n" ]
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0008564705_python.txt
Q: search array of dictionaries and extract value I got the following data: [{'name': 'SqueezePlay', 'power': '1', 'playerid': '91:e2:b5:24:49:63', 'ip': '192.168.1.144:51346', 'canpoweroff': 1, 'displaytype': 'none', 'seq_no': '10', 'connected': 1, 'isplayer': 1, 'model': 'squeezeplay', 'uuid': 'fgh79fg7h98789798978...
search array of dictionaries and extract value
I got the following data: [{'name': 'SqueezePlay', 'power': '1', 'playerid': '91:e2:b5:24:49:63', 'ip': '192.168.1.144:51346', 'canpoweroff': 1, 'displaytype': 'none', 'seq_no': '10', 'connected': 1, 'isplayer': 1, 'model': 'squeezeplay', 'uuid': 'fgh79fg7h98789798978'}, {'name': "FLX's iPhone", 'power': '1', 'playerid...
[ "If your list of dicts is data, then you can try this:\nnext(d for d in data if d['name'] == 'SqueezePlay')['playerid']\n\nThis returns '91:e2:b5:24:49:63' (for the first occurence of the given name).\nYou have to define what to do if given name is not in your data.\n", "Define a function to find a player based o...
[ 9, 1, 1 ]
[]
[]
[ "arrays", "multidimensional_array", "python" ]
stackoverflow_0008564086_arrays_multidimensional_array_python.txt
Q: import rpy quietly My question is analogous to this one but in the context of importing R to Python via RPy. Specifically, when I run from rpy import * at the beginning of my python script, there is a chunk of message dumped to the screen (or output device), starting with Parsing output: R version 2.13.2 (2011-...
import rpy quietly
My question is analogous to this one but in the context of importing R to Python via RPy. Specifically, when I run from rpy import * at the beginning of my python script, there is a chunk of message dumped to the screen (or output device), starting with Parsing output: R version 2.13.2 (2011-09-30) Copyright (C) 201...
[ "Here is simple but not beatiful hack:\n# define somewhere following:\nimport sys\nimport os\nfrom contextlib import contextmanager\n\n@contextmanager\ndef quiet():\n sys.stdout = sys.stderr = open(os.devnull, \"w\")\n try:\n yield\n finally:\n sys.stdout = sys.__stdout__\n sys.stderr ...
[ 8 ]
[]
[]
[ "python", "r", "rpy2" ]
stackoverflow_0008564741_python_r_rpy2.txt
Q: django: generic class view + POST = HTTP 405 (Method not allowed) Recently I've started converting some of the view functions to Generic Views. Converting the function which was expected to handle POST request (via AJAX form) results in "405 Method not allowed" HTTP exception. I'm sure is not about CSRF: Ajax sen...
django: generic class view + POST = HTTP 405 (Method not allowed)
Recently I've started converting some of the view functions to Generic Views. Converting the function which was expected to handle POST request (via AJAX form) results in "405 Method not allowed" HTTP exception. I'm sure is not about CSRF: Ajax sends valid token, changing the generic view back to view function (in the...
[ "I suppose you are using class-based views. If so then you need to define post method in your view or use mixin which does it (django.views.generic.edit.ProcessFormView for example). If you want to fully understand why this is necessary then look at dispatch method of django.views.generic.base.View.\n" ]
[ 17 ]
[]
[]
[ "django", "http", "http_status_code_405", "python" ]
stackoverflow_0008563482_django_http_http_status_code_405_python.txt
Q: Rendering requested type in Tornado In Tornado, how do you tell apart the different request types? Also, what is the proper way to split out the requests? In the end if I go to /item/1.xml, I want xml, /item/1.html to be a proper html view etc. Something like: def getXML(): return self.render('somexmlresult.xm...
Rendering requested type in Tornado
In Tornado, how do you tell apart the different request types? Also, what is the proper way to split out the requests? In the end if I go to /item/1.xml, I want xml, /item/1.html to be a proper html view etc. Something like: def getXML(): return self.render('somexmlresult.xml') def getHTML(): return self.rende...
[ "I would prefer a self describing url like a RESTful application. An url part need not be required to represent the format of the resource. http://www.enterprise.com/customer/abc/order/123 must represent the resource irrespective of whether it is xml/html/json. A way to send the requested format is to send it as on...
[ 2, 1, 1 ]
[]
[]
[ "python", "render", "request", "tornado" ]
stackoverflow_0008405977_python_render_request_tornado.txt
Q: How to combine a pyside frame with a button layout I came across a pyside script demonstrating a frame, and pyside script demonstrating buttons and box layout. I made a primitive attempt to combine the two scripts, but I can't get both of the following functions to work at the same time: run_button_app(True) an...
How to combine a pyside frame with a button layout
I came across a pyside script demonstrating a frame, and pyside script demonstrating buttons and box layout. I made a primitive attempt to combine the two scripts, but I can't get both of the following functions to work at the same time: run_button_app(True) and run_frame_app(True) One of the functions uses this sta...
[ "You can't run two QAplication instances at once, \nhere some information in this tutorial.\nI dont fully understand what are you trying to do, but if you want to add Example widget (with buttons) to FrameTester, you need to create some layout in FrameTester and add Example instance to this layout (there are many t...
[ 1 ]
[]
[]
[ "button", "layout", "pyqt", "pyside", "python" ]
stackoverflow_0008564928_button_layout_pyqt_pyside_python.txt
Q: Fullscreen Python TKinter or wxPython window, but 'stay at the bottom' of all windows? I want to create a fullscreen panel that visually blocks access to everything on the screen (desktop, menu, Unity Panel, etc in Ubuntu (11.10)), but stays below other applications' opened windows. This is mainly to make the lapt...
Fullscreen Python TKinter or wxPython window, but 'stay at the bottom' of all windows?
I want to create a fullscreen panel that visually blocks access to everything on the screen (desktop, menu, Unity Panel, etc in Ubuntu (11.10)), but stays below other applications' opened windows. This is mainly to make the laptop child proof. I want the kid (4 years old) to have access to some selected apps ie. gcompr...
[ "This is how I set the window position in pygame on windows.\nWith this, it will cover all other windows, if you change the -1 to a 1 it will be behind other windows, I only know it works in windows. \nimport pygame, time, datetime, ctypes\nfrom pygame.locals import *\nfrom ctypes import windll\n\npygame.init()\nse...
[ 2 ]
[]
[]
[ "fullscreen", "python", "tkinter", "ubuntu", "wxpython" ]
stackoverflow_0008553418_fullscreen_python_tkinter_ubuntu_wxpython.txt
Q: Numpy array conditional matching I need to match two very large Numpy arrays (one is 20000 rows, another about 100000 rows) and I am trying to build a script to do it efficiently. Simple looping over the arrays is incredibly slow, can someone suggest a better way? Here is what I am trying to do: array datesSecondD...
Numpy array conditional matching
I need to match two very large Numpy arrays (one is 20000 rows, another about 100000 rows) and I am trying to build a script to do it efficiently. Simple looping over the arrays is incredibly slow, can someone suggest a better way? Here is what I am trying to do: array datesSecondDict and array pwfs2Dates contain datet...
[ "Are the array dates sorted ? \n\nIf yes, you can speed up your comparisons by breaking from the inner\nloop comparison once its dates are bigger than the date given by the\nouter loop. In this way you will made a one-pass comparison instead of\nlooping dimVals items len(pwfs2Vals) times\nIf no, maybe you should t...
[ 6, 4, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0008565104_arrays_numpy_python.txt
Q: Longest substring (for sequences of triplets) I am trying to compare strings of the format: AAA-ABC-LAP-ASZ-ASK; basically, triplets of letters separated by dashes. I'm trying to find between 2 such sequences of arbitrary length (from 1 to 30 triplets) the longest sequence of common triplets. For example, AAA-BBB-...
Longest substring (for sequences of triplets)
I am trying to compare strings of the format: AAA-ABC-LAP-ASZ-ASK; basically, triplets of letters separated by dashes. I'm trying to find between 2 such sequences of arbitrary length (from 1 to 30 triplets) the longest sequence of common triplets. For example, AAA-BBB-CCC-AAA-DDD-EEE-BBB and BBB-AAA-DDD-EEE-BBB, you ca...
[ "I think that you're looking for the Longest Common Subsequence algorithm, which can find this sequence extremely quickly (in O(n2) time). The algorithm is based on a simple dynamic programming recurrence, and there are many examples online of how you might implement the algorithm.\nIntuitively, the algorithm work...
[ 5, 1, 0 ]
[]
[]
[ "algorithm", "comparison", "python", "string" ]
stackoverflow_0008566124_algorithm_comparison_python_string.txt
Q: Python XPath / libxml2 namespace query I have been trying to parse the London Underground Linestatus XML "feed" - with little success. I would have expected this to ne "easy" using XPath, but I am getting empty nodes. I am fairly sure sure that I am not dealing with the uk namespace correctly. Here is my (rather ...
Python XPath / libxml2 namespace query
I have been trying to parse the London Underground Linestatus XML "feed" - with little success. I would have expected this to ne "easy" using XPath, but I am getting empty nodes. I am fairly sure sure that I am not dealing with the uk namespace correctly. Here is my (rather simple code): import libxml2 from urllib2 im...
[ "You need to add a forward slash at the end of the namespace URI. The correct URI is http://webservices.lul.co.uk/.\n" ]
[ 6 ]
[]
[]
[ "contextpath", "libxml2", "namespaces", "python", "xpath" ]
stackoverflow_0008566111_contextpath_libxml2_namespaces_python_xpath.txt
Q: get safari and chrome opened tabs on mac with Appcelerator I need to read opened tabs URL in Safari, Chrome and Firefox (optionally) and turn them into an array. I'm using Titanium Appcelerator to develop a Dektop Application, and it support Python. It can be also done by calling an AppleScript that return what I'...
get safari and chrome opened tabs on mac with Appcelerator
I need to read opened tabs URL in Safari, Chrome and Firefox (optionally) and turn them into an array. I'm using Titanium Appcelerator to develop a Dektop Application, and it support Python. It can be also done by calling an AppleScript that return what I'm looking for. For example this simple AppleScript show what I'm...
[ "There are two ways you can do this via python...\n1.(My preference) Install appscript: pip install appscript\nimport appscript\nurls = appscript.app('Safari').windows.tabs.URL()\n\n2.Shell out to the commandline and call osascript:\nfrom subprocess import Popen, PIPE \ncmd = \"/usr/bin/osascript -e 'tell applicat...
[ 4, 4 ]
[]
[]
[ "appcelerator", "applescript", "python", "safari", "titanium" ]
stackoverflow_0008552823_appcelerator_applescript_python_safari_titanium.txt
Q: Padding an image for use in wxpython I'm looking for the most efficient way to 'square' an image for use as an icon. For example, I've got a .png file whose dimensions are 24x20.I don't want to change the 'image' part of the image in any way, I just want to add transparent pixels to the edge of the image so it bec...
Padding an image for use in wxpython
I'm looking for the most efficient way to 'square' an image for use as an icon. For example, I've got a .png file whose dimensions are 24x20.I don't want to change the 'image' part of the image in any way, I just want to add transparent pixels to the edge of the image so it becomes 24x24. My research suggests that I ne...
[ "Use image.paste to paste the image on a transparent background:\nimport Image\nFNAME = '/tmp/test.png'\ntop = Image.open(FNAME).convert('RGBA')\nnew_w = new_h = max(top.size)\nbackground = Image.new('RGBA', size = (new_w,new_h), color = (0, 0, 0, 0))\nbackground.paste(top, (0, 0))\nbackground.save('/tmp/result.png...
[ 3, 3, 1 ]
[]
[]
[ "icons", "padding", "python", "python_imaging_library", "wxpython" ]
stackoverflow_0008561896_icons_padding_python_python_imaging_library_wxpython.txt
Q: Modifying SQL table schema with web2py I'm having problems modifying SQL table schema in web2py. If I change the field type of an existing field in db.define_table, the SQL column's new type seems to register in web2py, but doesn't actually change anything in the database, which leads to errors. If I drop a field...
Modifying SQL table schema with web2py
I'm having problems modifying SQL table schema in web2py. If I change the field type of an existing field in db.define_table, the SQL column's new type seems to register in web2py, but doesn't actually change anything in the database, which leads to errors. If I drop a field from db.define_table, it doesn't go away in...
[ "SQLite is a special case -- read here about fixing broken migrations.\n" ]
[ 4 ]
[]
[]
[ "data_access_layer", "python", "sql", "web2py" ]
stackoverflow_0008565024_data_access_layer_python_sql_web2py.txt
Q: Creating recursive connection threads I create a new connection thread each time a connection with a client is made. However on the second time I run a client script, I get an error, how come? The Client from multiprocessing.connection import Client conn = Client(('localhost', 5555), authkey='secret_password') con...
Creating recursive connection threads
I create a new connection thread each time a connection with a client is made. However on the second time I run a client script, I get an error, how come? The Client from multiprocessing.connection import Client conn = Client(('localhost', 5555), authkey='secret_password') conn.send('Hello World!') conn.close() The Se...
[ "Some errors spotted:\n\nYou probably want your threaded_server to have an infinite loop and accept more than one connection. Right now it accepts only the first one and exists.\nYou're closing the listener after the processing is over, which probably isn't what you want. You can accept more connections using the s...
[ 2, 2, 0 ]
[]
[]
[ "listener", "multiprocessing", "python" ]
stackoverflow_0008565576_listener_multiprocessing_python.txt
Q: using python, how to remove whole line in csv file if specific character is present in this line? I have large csv file, 216961 lines: 9808,54,43,59,999,17,10,59,999,-1,0,0 9809,54,43,59,999,17,12,0,-1,0,0 9810,54,43,59,999,17,13,0,001,-1,0,0 9811,54,43,59,999,17,13,59,999,-1,0,0 9812,54,43,59,999,17,15,0,-1,0,0 9...
using python, how to remove whole line in csv file if specific character is present in this line?
I have large csv file, 216961 lines: 9808,54,43,59,999,17,10,59,999,-1,0,0 9809,54,43,59,999,17,12,0,-1,0,0 9810,54,43,59,999,17,13,0,001,-1,0,0 9811,54,43,59,999,17,13,59,999,-1,0,0 9812,54,43,59,999,17,15,0,-1,0,0 9813,54,43,59,999,17,16,0,001,0,0,0 9814,54,43,59,999,17,16,59,999,0,0,0 9815,54,43,59,999,17,18,0,0,0,0...
[ "Try this approach.\nimport csv\nreader = csv.reader(open(\"file.csv\", \"rb\"), delimiter=',')\nfor line in reader:\n if \"-1\" not in line:\n print line\n\n" ]
[ 5 ]
[ "If you have only one file, why not use vim?\n:g/,-1,/d\n\nIf you have multiple files, you can try\n\nSearch for a line with ,-1,\nDelete that line\n\nHints: look at fileinput \n" ]
[ -2 ]
[ "csv", "python" ]
stackoverflow_0008566342_csv_python.txt
Q: How to change the object that is referenced by a variable? I have an array of objects. I am interested in writing a function that will find a specific object in a list and return a reference to it. Imagine the following code snippet was possible: list1 = [1,2,3] def find(q): return q[0] a = find(list1) a = 0...
How to change the object that is referenced by a variable?
I have an array of objects. I am interested in writing a function that will find a specific object in a list and return a reference to it. Imagine the following code snippet was possible: list1 = [1,2,3] def find(q): return q[0] a = find(list1) a = 0 # This should change the object that "a" is referencing to. pri...
[ "To achieve exact same semantics may not be possible but something similar can be achieved by a proxy with get/set methods, though I am not clear exactly what and why you needed this, so final solution could be much more complex or simple, anyway here is my solution\ndef find(q):\n return Pointer(q, 0)\n\nclass ...
[ 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008566905_python.txt
Q: Django models definition ordering For example, I have 2 models: Model1 and Model2. Model1 has field ForeignKey(Model2). Model2 has method, that returns all instances of Model1 which has this instance of Model2 as ForeignKey. But it doesn't work, because Model2 is defined after Model1 and it knows nothing about Mo...
Django models definition ordering
For example, I have 2 models: Model1 and Model2. Model1 has field ForeignKey(Model2). Model2 has method, that returns all instances of Model1 which has this instance of Model2 as ForeignKey. But it doesn't work, because Model2 is defined after Model1 and it knows nothing about Model2. How to solve this problem?
[ "Take a look at the django docs. You can specify the model using a string so it evaluates later: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey\nclass Car(models.Model):\n manufacturer = models.ForeignKey('Manufacturer')\n # ...\n\nclass Manufacturer(models.Model):\n #...
[ 13, 2, 1 ]
[]
[]
[ "django", "models", "python" ]
stackoverflow_0008566559_django_models_python.txt
Q: Checking RSS feeds for new content with feedparser I'm using python to build an application which functions in a similar way to an RSS aggregator. I'm using the feedparser library to do this. However, I'm struggling to get the program to correctly detect if there is new content. I'm mainly concerned with news-rela...
Checking RSS feeds for new content with feedparser
I'm using python to build an application which functions in a similar way to an RSS aggregator. I'm using the feedparser library to do this. However, I'm struggling to get the program to correctly detect if there is new content. I'm mainly concerned with news-related feeds. Besides seeing if a new item has been added t...
[ "Hashing in this context means to calculate a shorter value to represent each combination of url and title. This approach works when you use a hash function that ensures the odds of a collision (two different items generate the same value) are low.\nTraditionally, MD5 has been a good function for this (but be caref...
[ 4 ]
[]
[]
[ "feedparser", "python", "rss" ]
stackoverflow_0008567052_feedparser_python_rss.txt
Q: Calling a Python function from a shell script I am trying to figure out how to call a Python function from a shell script. I have a Python file with multiple functions and I need to use the values returned by them in my shell script. Is there a way to do it. I am doing this in order to read a config file using Pyt...
Calling a Python function from a shell script
I am trying to figure out how to call a Python function from a shell script. I have a Python file with multiple functions and I need to use the values returned by them in my shell script. Is there a way to do it. I am doing this in order to read a config file using Python and getting the values in shell. Is there any o...
[ "You can send the result of your functions to the standard output by asking the Python interpreter to print the result:\npython -c 'import test; print test.get_foo()'\n\nThe -c option simply asks Python to execute some Python commands.\nIn order to store the result in a variable, you can therefore do:\nRESULT_FOO=`...
[ 42 ]
[]
[]
[ "bash", "configuration_files", "python", "shell" ]
stackoverflow_0008567526_bash_configuration_files_python_shell.txt
Q: payload of an email in string format, python I got payload as a string instance using get_payload() method. But I want my payload in a way where I could access it word by word I tried several things like as_string() method, flatten() method, get_charset() method , but every time there is some problem. I got my pay...
payload of an email in string format, python
I got payload as a string instance using get_payload() method. But I want my payload in a way where I could access it word by word I tried several things like as_string() method, flatten() method, get_charset() method , but every time there is some problem. I got my payload using the following code import email from em...
[ "Just tested your snippet with a couple of my own raw emails. Works fine...\nget_payload() returns either a list or string, so you need to check that first\nif isinstance(payload, list):\n for m in payload:\n print str(m).split()\n\nelse:\n print str(m).split()\n\nEdit\nPer our discussion, your issue w...
[ 3, 0 ]
[]
[]
[ "email", "payload", "python", "string" ]
stackoverflow_0008553650_email_payload_python_string.txt
Q: How to retrieve the storyline paragraph with imdbpy? So far, I haven't figured out how to retrieve the short description paragraph from imdb with imdbpy. I can retrieve a very (very) long plot this way though : ia = IMDb() movie = ia.search_movie("brazil") movie = movie[0] movie = ia.get_movie(movie.movieID) plot...
How to retrieve the storyline paragraph with imdbpy?
So far, I haven't figured out how to retrieve the short description paragraph from imdb with imdbpy. I can retrieve a very (very) long plot this way though : ia = IMDb() movie = ia.search_movie("brazil") movie = movie[0] movie = ia.get_movie(movie.movieID) plot = movie.get('plot', [''])[0] plot = plot.split('::')[0] ...
[ "description = movie.get('plot outline')\n\nThis code will get a list of the type of information available for a movie:\nmovie.keys()\n\n" ]
[ 3 ]
[]
[]
[ "imdb", "imdbpy", "python" ]
stackoverflow_0008567630_imdb_imdbpy_python.txt