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: Statement: with and tarfile I try to use with statement and tarfile module... with tarfile.open('/dir/dir/dir.tar.gz', 'w:gz') as fl: fl.add('/dir/dir/dir/', arcname = '/') So it shows the next: Traceback (most recent call last): File "", line 1, in AttributeError: 'TarFile' object has no attribute '__exit__...
Statement: with and tarfile
I try to use with statement and tarfile module... with tarfile.open('/dir/dir/dir.tar.gz', 'w:gz') as fl: fl.add('/dir/dir/dir/', arcname = '/') So it shows the next: Traceback (most recent call last): File "", line 1, in AttributeError: 'TarFile' object has no attribute '__exit__' I try to create tar.gz file an...
[ "You can use contextlib.closing, e.g.:\nfrom contextlib import closing\nwith closing(tarfile.open('/dir/dir/dir.tar.gz', 'w:gz')) as fl:\n fl.add('/dir/dir/dir/', arcname = '/')\n\nFrom docs:\n\nEven if an error occurs, page.close() will be called when the with block is exited.\n\ncontextlib.closing is available...
[ 15, 7, 2 ]
[ "Because the tarfile module obviously does not implement the context manager API\nhttp://docs.python.org/release/2.5.2/lib/typecontextmanager.html\nSo the conclusion is trivial: you can't use tarfile with 'with'.\n" ]
[ -3 ]
[ "python" ]
stackoverflow_0006086603_python.txt
Q: Backward propagation - Character Recognizing - Seeking an example i looking for a example of character recognizing (just one - for example X or A) using MLP, Backward propagation. I want a simple example, and not the entire library. Language does not matter, preferably one of those Java, Python, PHP A: Support V...
Backward propagation - Character Recognizing - Seeking an example
i looking for a example of character recognizing (just one - for example X or A) using MLP, Backward propagation. I want a simple example, and not the entire library. Language does not matter, preferably one of those Java, Python, PHP
[ "Support Vector Machines tend to work much better for character recognition with error rates around 2% generally reported. I suggest that as an alternative if you're just using the character recognition as a module in a larger project.\n" ]
[ 1 ]
[]
[]
[ "java", "neural_network", "php", "python" ]
stackoverflow_0006086560_java_neural_network_php_python.txt
Q: Import urllib or urllib 2 in Python 2.7 failing with ImportError: cannot import name iskeyword I can't import urllib or urllib2 on my Python 2.6 or Python 2.7 installs. Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >...
Import urllib or urllib 2 in Python 2.7 failing with ImportError: cannot import name iskeyword
I can't import urllib or urllib2 on my Python 2.6 or Python 2.7 installs. Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/u...
[ "There must be some importing conflicts. Do you have any modules named keyword in you workspace? Try next:\n>>> import keyword\n>>> dir(keyword)\n\n" ]
[ 5 ]
[]
[]
[ "python", "python_2.7", "python_import", "urllib" ]
stackoverflow_0006086634_python_python_2.7_python_import_urllib.txt
Q: Is there a Python equivalent to Ruby's respond_to? Is a way to see if a class responds to a method in Python? like in ruby: class Fun def hello puts 'Hello' end end fun = Fun.new puts fun.respond_to? 'hello' # true Also is there a way to see how many arguments the method requires? A: Hmmm .... I'd thin...
Is there a Python equivalent to Ruby's respond_to?
Is a way to see if a class responds to a method in Python? like in ruby: class Fun def hello puts 'Hello' end end fun = Fun.new puts fun.respond_to? 'hello' # true Also is there a way to see how many arguments the method requires?
[ "Hmmm .... I'd think that hasattr and callable would be the easiest way to accomplish the same goal:\nclass Fun:\n def hello(self):\n print 'Hello'\n\nhasattr(Fun, 'hello') # -> True\ncallable(Fun.hello) # -> True\n\nYou could, of course, call callable(Fun.hello) from within an exception handling su...
[ 17, 8, 2, 0 ]
[]
[]
[ "class", "python", "ruby" ]
stackoverflow_0006086820_class_python_ruby.txt
Q: Dbus connection through mod_wsgi in python I'm trying to write small application which allows to send dbus commands (to Amarok) through web page. I'm using python + mod_wsgi, because I need to run the script with the same user as Amarok. When I connect to the Amarok through normal shell, it works. But after conn...
Dbus connection through mod_wsgi in python
I'm trying to write small application which allows to send dbus commands (to Amarok) through web page. I'm using python + mod_wsgi, because I need to run the script with the same user as Amarok. When I connect to the Amarok through normal shell, it works. But after connecting through the script, I get the following ...
[ "The problem was that I didn't set the DISPLAY variable, which is required for connecting with dbus.\nYou can check the small tutorial on this webpage:\nhttp://blog.wojtass.pl/tutorial-control-amarok-remotely-through-web-browser/\n" ]
[ 0 ]
[]
[]
[ "apache2", "mod_wsgi", "python" ]
stackoverflow_0004059058_apache2_mod_wsgi_python.txt
Q: VPS setup with fabric Is fabric suitable for a new VPS setup like Linode or SliceHost? The setup is explained in this slicehost article The required actions are basically: changing root password creating a new user and group add the group to the list of sudoers set hostname generate local ssh keys and upload secu...
VPS setup with fabric
Is fabric suitable for a new VPS setup like Linode or SliceHost? The setup is explained in this slicehost article The required actions are basically: changing root password creating a new user and group add the group to the list of sudoers set hostname generate local ssh keys and upload securely the public key set ipt...
[ "Fabric would work very well for these tasks. Essentially anything you do over SSH can be automated with Fabric. It also allows you to upload and download files.\nYou would probably generate your local keys by invoking shell commands locally; but everything else is in fabric's domain.\n" ]
[ 2 ]
[]
[]
[ "fabric", "python", "ssh", "vps" ]
stackoverflow_0006087021_fabric_python_ssh_vps.txt
Q: Quick Sending of 4[GB] To Be Processed From 100 Machines? I have 100 servers in my cluster. At time 17:35:00, all 100 servers are provided with data (of size 1[MB]). Each server processes the data, and produces an output of about 40[MB]. The processing time for each server is 5[sec]. At time 17:35:05 (5[sec] later...
Quick Sending of 4[GB] To Be Processed From 100 Machines?
I have 100 servers in my cluster. At time 17:35:00, all 100 servers are provided with data (of size 1[MB]). Each server processes the data, and produces an output of about 40[MB]. The processing time for each server is 5[sec]. At time 17:35:05 (5[sec] later), there's a need for a central machine to read all the output ...
[ "Look at the flow of data in your application, and then look at the data rates that your (I assume shared) disk system provides and the rate your GigE interconnect provides, and the topology of your cluster. Which of these is a bottleneck?\nGigE provides theoretical maximum 125 MB/s transmission rate between nodes ...
[ 5, 3, 2, 2, 1 ]
[]
[]
[ "distributed_computing", "nosql", "python" ]
stackoverflow_0006062396_distributed_computing_nosql_python.txt
Q: Matching a variable with members of a list in Python? I want to check if a value of a variable matches (==) with a value of any member of a given list, on a single line A: use in: > lst = [1,'r'] > v = 1 > v in lst True A: EDIT: I'll leave this answer cos generator expressions are useful beasts (especially tog...
Matching a variable with members of a list in Python?
I want to check if a value of a variable matches (==) with a value of any member of a given list, on a single line
[ "use in:\n> lst = [1,'r']\n> v = 1\n> v in lst\nTrue\n\n", "EDIT: I'll leave this answer cos generator expressions are useful beasts (especially together with any and all) but if you are just testing for membership in the list then you should use in.\n\nany(var == i for i in my_list)\n\nExplanation:\nany is a fun...
[ 6, 1 ]
[]
[]
[ "list", "match", "python", "variables" ]
stackoverflow_0006087192_list_match_python_variables.txt
Q: Simple counter example using mapreduce in Google App Engine I'm somewhat confused with the current state of mapreduce support in GAE. According to the docs http://code.google.com/p/appengine-mapreduce/ reduce phase isn't supported yet, but in the description of the session from I/O 2011 ( http://www.youtube.com/wa...
Simple counter example using mapreduce in Google App Engine
I'm somewhat confused with the current state of mapreduce support in GAE. According to the docs http://code.google.com/p/appengine-mapreduce/ reduce phase isn't supported yet, but in the description of the session from I/O 2011 ( http://www.youtube.com/watch?v=EIxelKcyCC0 ) it's written "It is now possible to run full ...
[ "You don't really need a reduce phase. You can accomplish this with a linear task chain, more or less as follows:\ndef count_colors(limit=100, totals={}, cursor=None):\n query = Car.all()\n if cursor:\n query.with_cursor(cursor)\n cars = query.fetch(limit)\n for car in cars:\n try:\n totals[car.color...
[ 9, 6 ]
[]
[]
[ "google_app_engine", "mapreduce", "python" ]
stackoverflow_0006060095_google_app_engine_mapreduce_python.txt
Q: Multiple parameters in Django URLconf Say I want my URLs to have alphanumeric string parameters, where each parameter is separated by a '+' and we have more than 1 parameter. That is, blah.com/1a+2b would be valid, but blah.com/1a or blah.com/1a_2b would not be valid. So far, in my urls.py, I have: (r'^((\w+)\+)+(...
Multiple parameters in Django URLconf
Say I want my URLs to have alphanumeric string parameters, where each parameter is separated by a '+' and we have more than 1 parameter. That is, blah.com/1a+2b would be valid, but blah.com/1a or blah.com/1a_2b would not be valid. So far, in my urls.py, I have: (r'^((\w+)\+)+(\w+)$', 'XXX.views.YYY') and in views.py: ...
[ "Take the string in your URLConf and validate in your view.\nurl(r'^(?P<params_list>(\\w+)\\+?)+)/$');\n\nIn your view:\ndef my_view(request, params):\n if not validate_params(params): # validate as you wish\n raise Http404()\n\n # continue with your view\n\nOr, if your view already expects a list, you could w...
[ 1 ]
[]
[]
[ "django", "parameters", "python", "urlconf" ]
stackoverflow_0006085829_django_parameters_python_urlconf.txt
Q: BeautifulSoup Cannot Extract Metadata I am trying to create a function which will extract meta keywords from a given URL and return it. However no matter what URLs I pass to it, it will always fail. def GetKeywords(url): soup = BeautifulSoup(url) keywords = soup.findAll('meta', attrs={'name':re.compile("^keywo...
BeautifulSoup Cannot Extract Metadata
I am trying to create a function which will extract meta keywords from a given URL and return it. However no matter what URLs I pass to it, it will always fail. def GetKeywords(url): soup = BeautifulSoup(url) keywords = soup.findAll('meta', attrs={'name':re.compile("^keywords$", re.I)}) #Find all meta keywords on t...
[ "Where does the BeautifulSoup state that it would accept and fetch an URL?\nsoup = BeautifulSoup(url)\n\nSorry but read the BeautifulSoup documentation first yourself instead trying and guessing API methods..\nhttp://www.crummy.com/software/BeautifulSoup/documentation.html#Parsing a Document\nWhat you want is likel...
[ 3 ]
[]
[]
[ "beautifulsoup", "metadata", "python", "web_scraping" ]
stackoverflow_0006087291_beautifulsoup_metadata_python_web_scraping.txt
Q: What is the name of the developer package or Python runtime package in SuSE LES 11 SP1? _I had problem with installing the mod_wsgi.I have found the solution as below (I am quite sure this is the solution to my problem) in its website. However, I don't know the name of the developer package or Python runtime packa...
What is the name of the developer package or Python runtime package in SuSE LES 11 SP1?
_I had problem with installing the mod_wsgi.I have found the solution as below (I am quite sure this is the solution to my problem) in its website. However, I don't know the name of the developer package or Python runtime package in SuSE LES 11 SP1. Can any one tell me? Thank you_. In order to compile mod_wsgi from sou...
[ "See:\nhttp://software.opensuse.org/search?q=%22python-dev%22&baseproject=openSUSE%3A11.4&lang=en\nLooks like it might be called 'python-devel'.\n" ]
[ 1 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0006086734_apache_django_mod_wsgi_python.txt
Q: Python: changing IDLE's path in WIN7 Windows 7 As I'm learning Python (3.2) I prefer using IDLE than CMD. In order to change the path where I can import scripts of my own, I use a little trick that I found in this site: I go FILE>OPEN>directory>myscript and then run it and from then on I'm on this directory. Never...
Python: changing IDLE's path in WIN7
Windows 7 As I'm learning Python (3.2) I prefer using IDLE than CMD. In order to change the path where I can import scripts of my own, I use a little trick that I found in this site: I go FILE>OPEN>directory>myscript and then run it and from then on I'm on this directory. Nevertheless, I wonder whether there is a simpl...
[ "http://www.skylit.com/python/Appendix-A.html\nCheck section A.2, just before section A.3:\n>>> from os import chdir\n>>> chdir(\"C:/myOtherWork\")\n\nAnd also to check the working directory:\n>>> from os.path import abspath\n>>> abspath('.')\n\nIf the current directory is not already in the path you need to add it...
[ 6 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0006087405_python_python_idle.txt
Q: import C++ module, if fail: import Python version? I have a Python pyd module written in C++. I also have a Python version of the module (which is much slower). My question is, as I want the program to run on multiple OSs, can I try to import the C++ version in the program and import the slower Python version if t...
import C++ module, if fail: import Python version?
I have a Python pyd module written in C++. I also have a Python version of the module (which is much slower). My question is, as I want the program to run on multiple OSs, can I try to import the C++ version in the program and import the slower Python version if that one fails (other OS, architecture)?
[ "Yes, you can import some thing like this: \ntry:\n import CppModule as Module\nexcept ImportError:\n import PurePythonModule as Module\n\n", "Yes you can:\ntry:\n import CppModule\nexcept ImportError:\n import PythonModule\n\nEdit: This answer, while not incorrect, is not really useful. As @Best Game...
[ 7, 1 ]
[]
[]
[ "c++", "import", "module", "pyd", "python" ]
stackoverflow_0006087530_c++_import_module_pyd_python.txt
Q: Is there any method in selenium to get that text is a "Link" or simple text Is there any method in selenium to get that text is a Link or simple text A: I assume that you get innerText of element and now want to validate whether it is under node. Consider following HTML snippet for this - "<a title=\"Junior TSG...
Is there any method in selenium to get that text is a "Link" or simple text
Is there any method in selenium to get that text is a Link or simple text
[ "I assume that you get innerText of element and now want to validate whether it is under node.\nConsider following HTML snippet for this -\n\"<a title=\\\"Junior TSG Application Engineer at Two Sigma Investments. Click to learn more.\\\" target=\\\"_blank\\\" \" +\n \"href=\\\"http://careers.stackoverfl...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0006067613_python_selenium.txt
Q: Python bug when creating matrices I have written a code in Python to create a transition probability matrix from the data, but I keep getting wrong values for two specific data points. I have spent several days on trying to figure out the problem, but with no success. About the code: The input is 4 columns in csv ...
Python bug when creating matrices
I have written a code in Python to create a transition probability matrix from the data, but I keep getting wrong values for two specific data points. I have spent several days on trying to figure out the problem, but with no success. About the code: The input is 4 columns in csv file. After preparation of the data, th...
[ "This sound very much like a rounding issue. I'd suppose that e.g. 100*0.29 (as a floating point number) is rounded downwards (i.e. truncated) and thus yields 28 instead of 29. Try rounding the numbers by yourself (i.e. a up/down rounding) before using them as an array index.\nUpdate: Verified my conjecture by test...
[ 4, 4 ]
[]
[]
[ "matrix", "python" ]
stackoverflow_0006087597_matrix_python.txt
Q: PyQt - creating buttons from dictionary I have a dictionary. I need to create buttons with keys name, and clicked slot based on value: dic = {'a':'111', 'b':'222', 'c':'333'} for key in dic: btn = QPushButton(key, self) btn.clicked.connect(lambda: doit(dic[key])) vbox.addWidget(btn) I have all button...
PyQt - creating buttons from dictionary
I have a dictionary. I need to create buttons with keys name, and clicked slot based on value: dic = {'a':'111', 'b':'222', 'c':'333'} for key in dic: btn = QPushButton(key, self) btn.clicked.connect(lambda: doit(dic[key])) vbox.addWidget(btn) I have all buttons with right name. And last created button b...
[ "The anonymous function lambda: doit(dic[key]) does not evaluate key until the function is called. By that time, the for-loop has completed, and the for-loop variable key references the last key in dic.\nWhen the anonymous function is called (when you press a button), key is looked up in the global namespace, and t...
[ 3, 1, 1 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0006084331_pyqt_python.txt
Q: Plotting a sum in python I'm trying to plot a function in python that has infinite sum in it. Now, since there are no infinities in computing, for my upper bound I can choose a really big number, and that's fine. So I tried to plot it: from scitools.std import * from math import * import numpy as np def f1(t): ...
Plotting a sum in python
I'm trying to plot a function in python that has infinite sum in it. Now, since there are no infinities in computing, for my upper bound I can choose a really big number, and that's fine. So I tried to plot it: from scitools.std import * from math import * import numpy as np def f1(t): return 0.5*(1+sum((4**(2*n)*...
[ "That loop can't possibly end during your lifetime. 10 ** 100 is a really really enormous number. It's bigger than the number of particles in the universe, it's bigger than the number of the tiniest time periods that have passed since the creation of the universe. On an impossibly fast computer - 3 * 10 ** 46 mille...
[ 6, 0 ]
[]
[]
[ "numpy", "python", "sum" ]
stackoverflow_0006087874_numpy_python_sum.txt
Q: Can i reassign the values to same variables in python I have this variable in python DATE_FILENAME = datetime.datetime.now().strftime("%b-%d-%Y-%I%M%p") Now this is supposed to have diff value every time . But i have heard that strings are immutable does it mean that it will hold only one value This is the resul...
Can i reassign the values to same variables in python
I have this variable in python DATE_FILENAME = datetime.datetime.now().strftime("%b-%d-%Y-%I%M%p") Now this is supposed to have diff value every time . But i have heard that strings are immutable does it mean that it will hold only one value This is the result _May-22-2011-1002PM.tar.gz my script took 3 minutes for ...
[ "EDIT: Let me clarify: you define this constant once in your module? In that case it will not change; you have to update the name binding every time you want to write a file. An easy way to do this is to write a little function get_name which will generate the new name every time you call it.\nThe reason the string...
[ 7, 1, 0, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0006088019_python_string.txt
Q: How to make function "make_archive" to include the parent directory in python I am using shutil.make_archive function to make archive But it only archive the contents of directory. i have the folder to backup like root_dir = /home/john/public_html I use that then my archive contains the contents of public_html bu...
How to make function "make_archive" to include the parent directory in python
I am using shutil.make_archive function to make archive But it only archive the contents of directory. i have the folder to backup like root_dir = /home/john/public_html I use that then my archive contains the contents of public_html but i want to include public_html itself in archive. Now in my john folder i have man...
[ "You want to pass the base_dir argument, as mentioned in the docs:\nshutil.make_archive('public_html_backup', 'zip', '/home/john', '/home/john/public_html')\n\n" ]
[ 4 ]
[]
[]
[ "archive", "linux", "python" ]
stackoverflow_0006088271_archive_linux_python.txt
Q: Does monocle use a bad example for event driven programming? https://github.com/saucelabs/monocle The following code is given as an example of standard event driven programming: def get_cmd(conn): conn.read_until("\n", callback=handle_cmd) def handle_cmd(conn, cmd): if cmd.type == "get-address": ...
Does monocle use a bad example for event driven programming?
https://github.com/saucelabs/monocle The following code is given as an example of standard event driven programming: def get_cmd(conn): conn.read_until("\n", callback=handle_cmd) def handle_cmd(conn, cmd): if cmd.type == "get-address": # keep track of the conn so we can write the response back! ...
[ "I'd say it's a poor example because it doesn't show just how bad callback-based event programming can be. The closure isn't necessary, but it (presumably) is used to keep things logically organized, making the code easier to read/reason about. It's quite common to write your callback as a closure. The whole point ...
[ 2 ]
[]
[]
[ "event_handling", "python", "yield" ]
stackoverflow_0006086926_event_handling_python_yield.txt
Q: Python 3- How to retrieve an image from the web and display in a GUI using TKINTER? I want a function that, when a button is clicked, it will take an image from the web using URLLIB and display it in a GUI using TKINTER. I'm new to both URLLIB and TKINTER, so I'm having an incredibly difficult time doing this. Tri...
Python 3- How to retrieve an image from the web and display in a GUI using TKINTER?
I want a function that, when a button is clicked, it will take an image from the web using URLLIB and display it in a GUI using TKINTER. I'm new to both URLLIB and TKINTER, so I'm having an incredibly difficult time doing this. Tried this, but it obviously doesn't work because it uses a textbox and only will display te...
[ "I don't use python 3, but I can give an answer that works in python 2.5+. I assume the code will work nearly identically on python 3.\nBefore we get started, we need to import Tkinter and create the root window:\nimport Tkinter as tk\nroot = tk.Tk()\n\nNext, to download the image using urllib:\nimport urllib\nURL ...
[ 10 ]
[]
[]
[ "python", "tkinter", "urllib", "user_interface" ]
stackoverflow_0006086262_python_tkinter_urllib_user_interface.txt
Q: Django forms not accepting custom dict based label --- AttributeError unicode object has no attribute get I'm trying to edit the form label in Django using a class that looks like this: from django import forms class Form(forms.Form): e = {} gender = forms.ChoiceField(choices = ()) #_remaining variable...
Django forms not accepting custom dict based label --- AttributeError unicode object has no attribute get
I'm trying to edit the form label in Django using a class that looks like this: from django import forms class Form(forms.Form): e = {} gender = forms.ChoiceField(choices = ()) #_remaining variables_ def __init__(self, lang): t = Translation.objects.get(template_file = 'VirasatForm') s...
[ "You can create a form dynamically like this:\nclass Form(forms.Form):\n def __init__(self, gender_choices, *args, **kwargs):\n super(Form, self).__init__(*args, **kwargs)\n self.fields['gender'] = forms.ChoiceField(choices=gender_choices)\n\nExample usage:\n>>> choices = (('m', 'Male'), ('f', 'Fem...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006088275_django_python.txt
Q: how to send data with twisted protocol via factory I'm writing a client implementing a custom protocol, and have a factory for it. My problem is the following: my client has bi-dir communication, and sometimes I want to tell it "send this data". But all I have is the factory object: class MyFactory(ClientFactory):...
how to send data with twisted protocol via factory
I'm writing a client implementing a custom protocol, and have a factory for it. My problem is the following: my client has bi-dir communication, and sometimes I want to tell it "send this data". But all I have is the factory object: class MyFactory(ClientFactory): protocol = MyProtocol def __init__(self, recv_...
[ "You have access to all of the objects you want. The factory is responsible for creating protocol instances, so if you want to keep the protocol instance around where the factory can use it, override buildProtocol and save the instance:\nclass MyFactory(ClientFactory):\n protocol = MyProtocol\n\n ...\n\n ...
[ 10 ]
[]
[]
[ "network_programming", "python", "twisted" ]
stackoverflow_0006088280_network_programming_python_twisted.txt
Q: how to parse human input datetime ranges I want to parse strings like this into a consistent structured date range: Monday through Wednesday, 10 - 6 Monday - Saturday, 10 AM - 8 PM Monday and Tuesday 10AM-7PM Monday-Wednesday: 10am to 7pm Any existing API's or libraries you can recommend? A: You can use parse...
how to parse human input datetime ranges
I want to parse strings like this into a consistent structured date range: Monday through Wednesday, 10 - 6 Monday - Saturday, 10 AM - 8 PM Monday and Tuesday 10AM-7PM Monday-Wednesday: 10am to 7pm Any existing API's or libraries you can recommend?
[ "You can use parsedatetime library. This does exactly what you said.\n" ]
[ 2 ]
[]
[]
[ "api", "datetime", "parsing", "python" ]
stackoverflow_0006088765_api_datetime_parsing_python.txt
Q: Fix invalid XML with ampersands in Python I am using Python to manipulate an XML file I receive from another system. That system produces invalid XML. Mainly, it doesn't escape some of the & in the XML. So, for example, I have some lines like that: <IceCream>Ben&Jerry</IceCream> Of course, when parsed with SAX o...
Fix invalid XML with ampersands in Python
I am using Python to manipulate an XML file I receive from another system. That system produces invalid XML. Mainly, it doesn't escape some of the & in the XML. So, for example, I have some lines like that: <IceCream>Ben&Jerry</IceCream> Of course, when parsed with SAX or DOM it throws invalid token error. For some...
[ "Use the Python bindings for tidylib:\n>>> import tidylib\n>>> print tidylib.tidy_document(\"<IceCream>Ben&Jerry</IceCream>\", {\"input_xml\": True})[0]\n<IceCream>Ben&amp;Jerry</IceCream>\n\nSee the official tidy documentation for a list of parser options.\n" ]
[ 6 ]
[]
[]
[ "dom", "python", "regex", "sax", "xml" ]
stackoverflow_0006088760_dom_python_regex_sax_xml.txt
Q: Can anyone please explain how this python code works line by line? I am working in image processing right now in python using numpy and scipy all the time. I have one piece of code that can enlarge an image, but not sure how this works. So please some expert in scipy/numpy in python can explain to me line by line....
Can anyone please explain how this python code works line by line?
I am working in image processing right now in python using numpy and scipy all the time. I have one piece of code that can enlarge an image, but not sure how this works. So please some expert in scipy/numpy in python can explain to me line by line. I am always eager to learn. import numpy as N import os.path import sci...
[ "First, a grid of empty points is created with point per pixel.\nx, y = N.meshgrid(N.arange(img.shape[1]), N.arange(img.shape[0]))\n\nThe actual image pixels are placed into the variable pts which will be needed later.\npts = N.column_stack((x.ravel(), y.ravel()))\n\nAfter that, it creates a mesh grid with one poin...
[ 5 ]
[]
[]
[ "image_processing", "numpy", "python", "scipy" ]
stackoverflow_0006086289_image_processing_numpy_python_scipy.txt
Q: Python file parsing: Build tree from text file I have an indented text file that will be used to build a tree. Each line represents a node, and indents represent depth as well as node the current node is a child of. For example, a file might look like ROOT Node1 Node2 Node3 Node4 ...
Python file parsing: Build tree from text file
I have an indented text file that will be used to build a tree. Each line represents a node, and indents represent depth as well as node the current node is a child of. For example, a file might look like ROOT Node1 Node2 Node3 Node4 Node5 Node6 Which indicates that ROOT contains t...
[ "If you don't insist on recursion, this works too:\nfrom itertools import takewhile\n\nis_tab = '\\t'.__eq__\n\ndef build_tree(lines):\n lines = iter(lines)\n stack = []\n for line in lines:\n indent = len(list(takewhile(is_tab, line)))\n stack[indent:] = [line.lstrip()]\n print stack\...
[ 20, 13, 11 ]
[]
[]
[ "algorithm", "python", "recursion", "tree" ]
stackoverflow_0006075974_algorithm_python_recursion_tree.txt
Q: What's the easiest/cleanest way to get the MessageID of a sent email? I want to save the MessageID of a sent email, so I can later use it in a References: header to facilitate threading. I see in root/django/trunk/django/core/mail.py (line ~55) where the MessageID is created. I'm trying to think of the best way to...
What's the easiest/cleanest way to get the MessageID of a sent email?
I want to save the MessageID of a sent email, so I can later use it in a References: header to facilitate threading. I see in root/django/trunk/django/core/mail.py (line ~55) where the MessageID is created. I'm trying to think of the best way to collect this value, other than just copy/pasting into a new backend module...
[ "Ok, I see I was browsing tragically old code. I should be able to call django.core.mail.message.make_msgid() and populate the header myself before calling send.\n", "Not all backends actually support asserting a message id (for e.g. SES sets it's own message ID and returns it in it's send response). You can actu...
[ 12, 1 ]
[]
[]
[ "django", "email_headers", "python" ]
stackoverflow_0003470989_django_email_headers_python.txt
Q: python recursion problem Possible Duplicate: Flatten (an irregular) list of lists in Python hello I build a small program using recursion in Python, but am stuck in a place to solve the problem at least I do not know how to row, waiting for your help thank you in advance intertwined with a list following the gi...
python recursion problem
Possible Duplicate: Flatten (an irregular) list of lists in Python hello I build a small program using recursion in Python, but am stuck in a place to solve the problem at least I do not know how to row, waiting for your help thank you in advance intertwined with a list following the given problem using recursion I...
[ "Like this:\nstartlist=[[[13, 7], 90], 2, [1, 100], 8, 6]\nendlist=[]\n\ndef flatten(l):\n for item in l:\n if type(item) in (type([]),type(())):\n flatten(item)\n else:\n endlist.append(item)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006089436_python.txt
Q: Is there such a thing as "too many yield statements" in python? If doing a directory listing and reading the files within, at what point does the performance of yield start to deteriorate, compared to returning a list of all the files in the directory? Here I'm assuming one has enough RAM to return the (potentiall...
Is there such a thing as "too many yield statements" in python?
If doing a directory listing and reading the files within, at what point does the performance of yield start to deteriorate, compared to returning a list of all the files in the directory? Here I'm assuming one has enough RAM to return the (potentially huge) list. PS I'm having problems inlining code in a comment, so I...
[ "There is no point at which further use of yield results in decreased performance. In fact, as compared to assembling things in a list, yield actually improves by comparison the more elements there are.\n", "It depends on how you're doing the directory listing. Most mechanisms in Python pull the entire directory...
[ 5, 2, 1, 0 ]
[]
[]
[ "python", "yield" ]
stackoverflow_0002330546_python_yield.txt
Q: Is there a way to prevent a python window from being seen when opened? So I want to make a Python file that runs all the code within, but the window is invisible. So the user won't see the window in the task bar, or really anywhere on his screen. How would I do something like that? A: To make a script not open t...
Is there a way to prevent a python window from being seen when opened?
So I want to make a Python file that runs all the code within, but the window is invisible. So the user won't see the window in the task bar, or really anywhere on his screen. How would I do something like that?
[ "To make a script not open the terminal window change the extension of your script to .pyw which will cause the script to be executed by pythonw.exe by default. This suppresses the terminal window on startup.\nIf you would like all scripts to open like this you should read up on Executing Scripts.\n", "Maybe you...
[ 4, 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0006089457_python_windows.txt
Q: Problem with inserting into MySQL database from Python I am having trouble inserting a record into a MySQL database from python. This is what I am doing. def testMain2(): conn = MySQLdb.connect(charset='utf8', host="localhost", user="root", passwd="root", db="epf") cursor = conn.cursor() t...
Problem with inserting into MySQL database from Python
I am having trouble inserting a record into a MySQL database from python. This is what I am doing. def testMain2(): conn = MySQLdb.connect(charset='utf8', host="localhost", user="root", passwd="root", db="epf") cursor = conn.cursor() tableName = "test_table" columnsDef = "(export_date ...
[ "You haven't committed the transaction.\nconn.commit()\n\n(The MySQLdb library sets autocommit to False when connecting to MySQL. This means that you need to manually call commit or your changes will never make it into the database.)\n" ]
[ 9 ]
[]
[]
[ "macos", "mysql", "python", "terminal" ]
stackoverflow_0006089743_macos_mysql_python_terminal.txt
Q: selective printing from a list Say for an example, I've a list like this: q_list = [('94.vmtest2', 'sgmops', 'Andy Hays', '27/04 00:27:26', 'C', '27/04 00:28:31', 'vmtest1.hep', 'express', '00:00:10', '00:01:04'), ('96.vmtest2', 'sgmops', 'John Dee', '27/04 01:27:26', 'C', '27/04 01:28:33', 'vmtest1.hep...
selective printing from a list
Say for an example, I've a list like this: q_list = [('94.vmtest2', 'sgmops', 'Andy Hays', '27/04 00:27:26', 'C', '27/04 00:28:31', 'vmtest1.hep', 'express', '00:00:10', '00:01:04'), ('96.vmtest2', 'sgmops', 'John Dee', '27/04 01:27:26', 'C', '27/04 01:28:33', 'vmtest1.hep', 'short', '00:00:09', '00:01:06'),...
[ "Firstly, I would suggest that you store your data in namedtuples or a custom class, instead of just raw tuples. This way you can access the attributes by name (e.g. by using operator.attrgetter). The other option is to use a dict.\nThen, you can simply do the following (assuming your items are dicts):\n[item for i...
[ 2, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006088698_python.txt
Q: How can I route HTTP requests through a python script? I've thoroughly searched for the answer for my question, but I don't think I know the correct terminology to make my searches effective. Anyway, I'm looking to set up my web server to route a request for a static page through a Python "PageBuilder" program whi...
How can I route HTTP requests through a python script?
I've thoroughly searched for the answer for my question, but I don't think I know the correct terminology to make my searches effective. Anyway, I'm looking to set up my web server to route a request for a static page through a Python "PageBuilder" program which will dynamically implant content into templates. In other...
[ "This isn't really static content any more. You want to dynamically generate content using a script.\nIn Python, this is generally done using the WSGI interface (in olden days, the de facto standard was CGI), which defines a standard way for your Python code to get input (information about the HTTP request), and se...
[ 4 ]
[ "This is called CGI.\nhttp://en.wikipedia.org/wiki/Common_Gateway_Interface\n" ]
[ -2 ]
[ "apache", "http", "python", "static_pages" ]
stackoverflow_0006090275_apache_http_python_static_pages.txt
Q: python numpy array slicing I have an 2d array, A that is 6x6. I would like to take the first 2 values (index 0,0 and 0,1) and take the average of the two and insert the average into a new array that is half the column size of A (6x3) at index 0,0. Then i would get the next two indexes at A, take average and put ...
python numpy array slicing
I have an 2d array, A that is 6x6. I would like to take the first 2 values (index 0,0 and 0,1) and take the average of the two and insert the average into a new array that is half the column size of A (6x3) at index 0,0. Then i would get the next two indexes at A, take average and put into the new array at 0,1. The o...
[ "A very useful feature of numpy arrays is that they can be reshaped and viewed in many different ways, and by doing so, you can make certain operations very easy. \nSince you want to pair every two items, it makes sense to reshape the 6x6 array into a 18x2 array:\nimport numpy as np\n\narr=np.arange(36).reshape(6,6...
[ 10, 1 ]
[]
[]
[ "arrays", "indexing", "numpy", "python", "slice" ]
stackoverflow_0006090288_arrays_indexing_numpy_python_slice.txt
Q: App Engine (Python) Datastore Precall API Hooks Background So let's say I'm making app for GAE, and I want to use API Hooks. BIG EDIT: In the original version of this question, I described my use case, but some folks correctly pointed out that it was not really suited for API Hooks. Granted! Consider me helped. ...
App Engine (Python) Datastore Precall API Hooks
Background So let's say I'm making app for GAE, and I want to use API Hooks. BIG EDIT: In the original version of this question, I described my use case, but some folks correctly pointed out that it was not really suited for API Hooks. Granted! Consider me helped. But now my issue is academic: I still don't know how...
[ "Hooks are a little low level for the task at hand. What you probably want is a custom property class. DerivedProperty, from aetycoon, is just the ticket.\nBear in mind, however, that the 'nickname' field of the user object is probably not what you want - per the docs, it's simply the user part of the email field i...
[ 2, 2, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002351752_google_app_engine_google_cloud_datastore_python.txt
Q: Dynamically parsing research data in python The long (winded) version: I'm gathering research data using Python. My initial parsing is ugly (but functional) code which gives me some basic information and turns my raw data into a format suitable for heavy duty statistical analysis using SPSS. However, every time I ...
Dynamically parsing research data in python
The long (winded) version: I'm gathering research data using Python. My initial parsing is ugly (but functional) code which gives me some basic information and turns my raw data into a format suitable for heavy duty statistical analysis using SPSS. However, every time I modify the experiment, I have to dive into the an...
[ "Not sure if I understand your question, but here are a few thoughts:\nFor parsing the data files, you usually use the Python csv module. \nFor categorizing the data you could use a defaultdict with the non-float fields joined as a key for the dict. Example:\nfrom collections import defaultdict\nimport csv\n\nreade...
[ 2, 0, 0, 0 ]
[]
[]
[ "list_comprehension", "parsing", "python" ]
stackoverflow_0006089772_list_comprehension_parsing_python.txt
Q: ImportError: No module named writers.SeqRecord.fasta # File Name RandonProteinSequences.py # standard library import os import random # biopython from Bio.Seq import Seq from Bio.Alphabet import IUPAC from Bio.SeqRecord import SeqRecord import Bio.writers.SeqRecord.fasta from Bio import SeqIO from sys import * r...
ImportError: No module named writers.SeqRecord.fasta
# File Name RandonProteinSequences.py # standard library import os import random # biopython from Bio.Seq import Seq from Bio.Alphabet import IUPAC from Bio.SeqRecord import SeqRecord import Bio.writers.SeqRecord.fasta from Bio import SeqIO from sys import * residueList1 = ["C","D","E","F","G","H","I"] residueList2 =...
[ "I've already mentioned this in your other question and I'll say it here again:\nThis code is in need of an update, since Bio.writers.SeqRecord.fasta is deprecated.\nI took a quick look at Biopython's documentation trying to figure out how you can write a FASTA file.\nTry this:\n# File Name RandonProteinSequences.p...
[ 2, 0 ]
[]
[]
[ "biopython", "python" ]
stackoverflow_0006062423_biopython_python.txt
Q: problems importing a class from a another file I am trying to run a program with two files. file1 contains two classes and one line of code. When I run file1.pyfrom the command line the single line of code runs and calls one of the classes from this file. For file2.py to work it needs to use just one of the classe...
problems importing a class from a another file
I am trying to run a program with two files. file1 contains two classes and one line of code. When I run file1.pyfrom the command line the single line of code runs and calls one of the classes from this file. For file2.py to work it needs to use just one of the classes from file1.py. However no matter what method I use...
[ "if __name__ == '__main__':\n # put your line of code here\n # add this to file1.py\n\nThis code will be executed only if your file was run, but not if your file was imported.\n" ]
[ 3 ]
[]
[]
[ "import", "python" ]
stackoverflow_0006091002_import_python.txt
Q: ctags info for built-in functions in PHP/Python/Etc Is there any way I can get ctags to somehow support the built-in functions provided by PHP/Python (Or whatever I'm working with at that moment), so that I can also use those in Source Explorer in vim and alike? Update: Okay so with python I can just run ctags on ...
ctags info for built-in functions in PHP/Python/Etc
Is there any way I can get ctags to somehow support the built-in functions provided by PHP/Python (Or whatever I'm working with at that moment), so that I can also use those in Source Explorer in vim and alike? Update: Okay so with python I can just run ctags on the source folder to get a tags file with the built in fu...
[ "ctags lets you build your tags database incrementally with the --append option; if you want the C definition for the Python routines (much? some? a little bit? is implemented directly in C, some in Python itself) you can run:\nctags -R\nctags --append -R /path/to/python-source\n\nIf you want just a portion of the ...
[ 2, 1 ]
[]
[]
[ "ctags", "function", "php", "python", "vim" ]
stackoverflow_0006084816_ctags_function_php_python_vim.txt
Q: Create Gtk.Atom with PyGobject Introspection and Gtk+3 Context: There was once a post on preventing window overlap with Gtk+2.x Recent changes in Gtk+3 have however affected the gdk_property_change() function, which has the PyGobject Introspection (hereafter referred to as PyGI) equivalent of Gdk.property_change()...
Create Gtk.Atom with PyGobject Introspection and Gtk+3
Context: There was once a post on preventing window overlap with Gtk+2.x Recent changes in Gtk+3 have however affected the gdk_property_change() function, which has the PyGobject Introspection (hereafter referred to as PyGI) equivalent of Gdk.property_change(). In the previous SO answer the property_change arguments we...
[ "It might be that Gobject-Introspection picks up Gdk from Gtk+-2.0 version, so you have to force the version:\nIn [1]: import gi \nIn [2]: gi.require_version(\"Gdk\", \"3.0\") \nIn [3]: from gi.repository import Gdk \nIn [4]: Gdk.__path__\nOut[4]: '/usr/lib64/girepository-1.0/Gdk-3.0.typelib' \nIn [5]: Gdk...
[ 0 ]
[]
[]
[ "gdk", "gtk", "pygobject", "python", "window" ]
stackoverflow_0006088569_gdk_gtk_pygobject_python_window.txt
Q: Swig, Python, C++: TypeError: in method 'Geodatabase_Open', argument 2 of type 'std::string' I am new to C++ and SWIG. This is my first project. I am able to successfully build my Python extension using distutils. However, when I try my object, I keep getting this error. It seems that there is a conversion problem...
Swig, Python, C++: TypeError: in method 'Geodatabase_Open', argument 2 of type 'std::string'
I am new to C++ and SWIG. This is my first project. I am able to successfully build my Python extension using distutils. However, when I try my object, I keep getting this error. It seems that there is a conversion problem from getting the python string and transforming it into a std::string. I am working on Windows 7...
[ "According to the swig documentation, using std::string requires %include \"std_string.i\".\n%module example\n%include \"std_string.i\"\n\nstd::string foo();\nvoid bar(const std::string &x);\n\n" ]
[ 4 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0006090976_c++_python_swig.txt
Q: Casting to other class in Python I have a code (simplified): class A(object): attrib1 = "a" attrib2 = "b" class B(A): flag = True in some place in my code, I have an instance of A, but I need to create an instance of class B, which will have all the data from instance of A... I feel myself stupid, bu...
Casting to other class in Python
I have a code (simplified): class A(object): attrib1 = "a" attrib2 = "b" class B(A): flag = True in some place in my code, I have an instance of A, but I need to create an instance of class B, which will have all the data from instance of A... I feel myself stupid, but I don't want to do something like: c...
[ "class B(A):\n def __init__(self, obj):\n self.__dict__.update(obj.__dict__)\n\n", "Another option is to change the __class__ variable on your instance of A.\na = A()\na.__class__ = B\n\n" ]
[ 4, 1 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0006091003_inheritance_python.txt
Q: Python WSGI: Reading env['wsgi.input'] more than once I am building a simple web service that requires all requests to be signed. The signature hash is generated using request data including the request body. My desire is to have a middleware component that validates the request signature, responding with an error...
Python WSGI: Reading env['wsgi.input'] more than once
I am building a simple web service that requires all requests to be signed. The signature hash is generated using request data including the request body. My desire is to have a middleware component that validates the request signature, responding with an error if the signature is invalid. The problem is the middleware...
[ "You can try seeking back to the beginning, but you may find that you'll have to replace it with a StringIO containing what you just read out.\n", "The following specification deals with that exact problem, providing explanation of the problem as well as the solution including source code and special cases to tak...
[ 3, 1 ]
[]
[]
[ "middleware", "pylons", "python", "wsgi" ]
stackoverflow_0006090377_middleware_pylons_python_wsgi.txt
Q: How do you compare pixels? I am using the PIL to take an image with a black background and make a mask out of it. What I want the program to do is iterate through all the pixels in the image and if the pixel is black make it white and if it is any other color make it black, but I am not sure how to appropriately c...
How do you compare pixels?
I am using the PIL to take an image with a black background and make a mask out of it. What I want the program to do is iterate through all the pixels in the image and if the pixel is black make it white and if it is any other color make it black, but I am not sure how to appropriately compare pixel values to determine...
[ "The pixel data comparison is correct. But there are two problems with the logic:\n\nWhen you are finished with a row, you should reset j to 0.\nYou are modifying the object \"im\", but writing \"mask\". \n\nThis should work (as long as you have no alpha channel - as andrewdski pointed out):\nimg = Image.open(file...
[ 4, 2, 1 ]
[]
[]
[ "python", "python_imaging_library" ]
stackoverflow_0006088664_python_python_imaging_library.txt
Q: The concept behind scipy.signal.medfilt2d in python I am trying to understand how scipy.signal.medfilt2d works. After I looked at the scipy documentation, its format is: scipy.signal.medfilt2d(input, kernel_size=3) So like if I have a matrix like 1 2 3 7 2 4 3 4 2 2 6 7 1 7 3 1 2 6 3 2 3 4 3 1 2 6 7 8 2 5 3 4 2 2 ...
The concept behind scipy.signal.medfilt2d in python
I am trying to understand how scipy.signal.medfilt2d works. After I looked at the scipy documentation, its format is: scipy.signal.medfilt2d(input, kernel_size=3) So like if I have a matrix like 1 2 3 7 2 4 3 4 2 2 6 7 1 7 3 1 2 6 3 2 3 4 3 1 2 6 7 8 2 5 3 4 2 2 1 8 Since the kernel size is set to 3 in default. If I a...
[ "As explained in the Scipy documentation, medfilt2 is a median filter. Quoting from the documentation,\nThe sample median is the middle array value in a sorted list of neighborhood values\n\nSo for your example, the submatrix at position 1,1\n1 2 3\n3 4 2\n1 7 3\n\nwould be sorted into\n1 1 2 2 3 3 3 4 7\n\nThe mid...
[ 2 ]
[]
[]
[ "matrix", "numpy", "python", "scipy" ]
stackoverflow_0006091378_matrix_numpy_python_scipy.txt
Q: What's your folder layout for a Flask app divided in modules? I am experimenting with Flask coming from Django and I really like it. There is just one problem that I ran into. I read the flask docs and the part about big applications or something like that and it explains a way to divide your project in packages, ...
What's your folder layout for a Flask app divided in modules?
I am experimenting with Flask coming from Django and I really like it. There is just one problem that I ran into. I read the flask docs and the part about big applications or something like that and it explains a way to divide your project in packages, each one with its own static and templates folder as well as its ow...
[ "While I'm not ready to announce because I'm still actively working on refining the samples, you would probably benefit from the flask-skeleton project that I'm developing. I got tired of reinventing the wheel with regards to bootstrapping Flask websites so I started to a complete sample project that uses my best p...
[ 13, 5 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python" ]
stackoverflow_0006089020_flask_flask_sqlalchemy_python.txt
Q: Is it possible to do HTML scraping , data mining through Python? Can I gather intelligent data , HTML scraping using python? I have no knowledge of it , so I would like to get some idea. A: Look at the module scrapy: http://scrapy.org/ A: You certainly can - I developed this library in Python for my web scrapi...
Is it possible to do HTML scraping , data mining through Python?
Can I gather intelligent data , HTML scraping using python? I have no knowledge of it , so I would like to get some idea.
[ "Look at the module scrapy:\nhttp://scrapy.org/\n", "You certainly can - I developed this library in Python for my web scraping work.\nA good parsing library is lxml.\nIf you are new to Python you may want to work through this ebook first.\n", "Try using urllib2 and Beautiful Soup.\nurllib2 is useful for reques...
[ 3, 3, 1, 0 ]
[]
[]
[ "data_mining", "python", "screen_scraping" ]
stackoverflow_0005843062_data_mining_python_screen_scraping.txt
Q: Python Sockets: Enabling Promiscuous Mode in Linux We know that Python Allows enabling promiscuous mode under Windows through s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) However, The RCVALL_* and SIO_* is only available in windows. Using C socket api, in Linux, one can use : ethreq.ifr_flags |= IFF_PROMISC; io...
Python Sockets: Enabling Promiscuous Mode in Linux
We know that Python Allows enabling promiscuous mode under Windows through s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) However, The RCVALL_* and SIO_* is only available in windows. Using C socket api, in Linux, one can use : ethreq.ifr_flags |= IFF_PROMISC; ioctl(sock, SIOCSIFFLAGS, &ethreq); or through, setsockop...
[ "Use an AF_NETLINK socket to issue a request to turn on IFF_PROMISC. Python can construct AF_NETLINK sockets on Linux:\n>>> from socket import AF_NETLINK, SOCK_DGRAM, socket \n>>> s = socket(AF_NETLINK, SOCK_DGRAM)\n>>>\n\nSee the example at the end of the netlink(7) manual page for an example of how to issue a ne...
[ 19, 4 ]
[]
[]
[ "networking", "python", "sockets" ]
stackoverflow_0006067405_networking_python_sockets.txt
Q: Python 2: Thread stops running and I don't know why I am trying to have a thread run in the background that loops that I can turn off with a gui button that sets the go property of the Thread object to false. However the thread only runs for a split second. class MyThread(threading.Thread): def __...
Python 2: Thread stops running and I don't know why
I am trying to have a thread run in the background that loops that I can turn off with a gui button that sets the go property of the Thread object to false. However the thread only runs for a split second. class MyThread(threading.Thread): def __init__(self): threading.Thread.__init...
[ "Remember that in python all threads (that use the interpreter) are subject to the GIL, and so there is only ever one thread running python code at any time. This means that if you have a busy loop in python land holding the GIL in one thread, it will stop execution of another thread. To read more about the GIL, ha...
[ 1 ]
[]
[]
[ "multithreading", "python", "ubuntu" ]
stackoverflow_0006091653_multithreading_python_ubuntu.txt
Q: Preferred Python way of getting the item of a set with a length(/cardinality) of one without removing it? Given set s, which of the segments below looks better? if len(s) == 1: v = s.copy().pop() # important stuff using variable v takes place here or if len(s) == 1: v = s.pop() s.add(v) # impo...
Preferred Python way of getting the item of a set with a length(/cardinality) of one without removing it?
Given set s, which of the segments below looks better? if len(s) == 1: v = s.copy().pop() # important stuff using variable v takes place here or if len(s) == 1: v = s.pop() s.add(v) # important stuff using variable v takes place here or if len(s) == 1: for v in s: # important stuff usi...
[ "\nWhy don't python sets have an alternative method to pop that doesn't remove the item?\n\nIf you want to access the first (and only) item without changing the set structure, use an iterator:\nv = iter(s).next()\n\nThis works prior to Python 3. In Python 3, you need to use the built-in next function:\nv = next(ite...
[ 5, 3 ]
[]
[]
[ "cardinality", "member", "python", "set" ]
stackoverflow_0006091922_cardinality_member_python_set.txt
Q: Looping a set of if/else statements until a list variable has three unique values in Python 3 Trying to make this section of python code repeat until it gets three different results. This isn't the actual code, just a simplified version that does the same thing. roll = random.randint(1,100) if roll < 10: name ...
Looping a set of if/else statements until a list variable has three unique values in Python 3
Trying to make this section of python code repeat until it gets three different results. This isn't the actual code, just a simplified version that does the same thing. roll = random.randint(1,100) if roll < 10: name += "alpha" elif roll < 37: name += "bravo" elif roll < 50: name += "charlie" elif roll < 89...
[ "For this example, I'd do this:\nimport random\nname = [\"alpha\", \"bravo\", \"charlie\", \"delta\", \"echo\"]\nname = \"\\n\".join(random.sample(name, 3))\n\n", "Make a list and then loop until you have three unique items in it.\nvalues = []\nwhile len(values) != 3:\n index = random.randrange(100)\n value =...
[ 2, 1, 1, 0 ]
[]
[]
[ "loops", "python", "random" ]
stackoverflow_0006091165_loops_python_random.txt
Q: Negative lookbehind problem Here is sample text(simplified from original): <start1> <name="4654"> bla bla bla bla <tags="bla" model="c"> bla bla bla bla <start2> <name="12346"> bla bla bla bla <tags="bla" model="d"> bla bla bla bla <start3> <name="73535"> bla bla bla bla <tags="bla" model="c"> <start4> <name="5468...
Negative lookbehind problem
Here is sample text(simplified from original): <start1> <name="4654"> bla bla bla bla <tags="bla" model="c"> bla bla bla bla <start2> <name="12346"> bla bla bla bla <tags="bla" model="d"> bla bla bla bla <start3> <name="73535"> bla bla bla bla <tags="bla" model="c"> <start4> <name="546875"> bla bla bla bla <tags="bla" ...
[ "Is it always in this format of (start, name, tags), (start, name, tags), and so on? If so, you can even do without the lookaround.\n/<name=\"(\\d+)\"[^<]+?<tags=\"([^\"]+?)\" model=\"c\">/s\n\nThat works because you know the next < you encounter will be for the immediately following tags label. Can we guarantee th...
[ 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006091631_python_regex.txt
Q: Converting a text file to list and then reading list to determine if an entry is within the list I'm having a little trouble with converting a text file to a list. the text file is presented like this: 5658845 4520125 7895122 8777541 8451277 1302850 8080152 I have written code that takes user input and tries to ...
Converting a text file to list and then reading list to determine if an entry is within the list
I'm having a little trouble with converting a text file to a list. the text file is presented like this: 5658845 4520125 7895122 8777541 8451277 1302850 8080152 I have written code that takes user input and tries to determine if the user input is in the list. I am however having some trouble in searching the list as ...
[ "i would read the list like this\nchargeAccount = open('charge_accounts.txt', 'r')\naccts = [line.strip() for line in chareAccount]\n\nif chareInput in accts:\n #do something\nelse:\n #do something else\n\nat the very least .strip() off the readline(), your line likely looks like '5658845\\n'\nUPDATE\nso after te...
[ 2, 2 ]
[]
[]
[ "list", "python", "text" ]
stackoverflow_0006092077_list_python_text.txt
Q: Moving characters and applying move to board Hey everyone, I previously asked a question on how to create a 2-D grid for a board game in Python and have now encountered another problem with making this board game. What i'm trying to do is move pieces (numbers or letters) on my board and apply that move to the boar...
Moving characters and applying move to board
Hey everyone, I previously asked a question on how to create a 2-D grid for a board game in Python and have now encountered another problem with making this board game. What i'm trying to do is move pieces (numbers or letters) on my board and apply that move to the board for when it's that same players turn next. Basic...
[ "I believe you are missing a key feature of classes in python: internal state. Here's a simple example:\nclass Counter():\n def __init__(self):\n self.internalCount = 0;\n return\n def addToInternalCount(self, val):\n self.internalCount = self.internalCount + val\n return self.internalCount\n\nNote th...
[ 1 ]
[]
[]
[ "function", "python" ]
stackoverflow_0006092010_function_python.txt
Q: In Python why does a tuple of integers take up less space than distinct integers? Here's an example with random integers: a, b, c, d = 79412623, 56529819571, 10431, 30461 t = (79412623, 56529819571, 10431, 30461) And their sizes: import sys sys.getsizeof(t) # 88 aa, bb, cc, dd = sys.getsizeof(a), sys.getsizeof(b)...
In Python why does a tuple of integers take up less space than distinct integers?
Here's an example with random integers: a, b, c, d = 79412623, 56529819571, 10431, 30461 t = (79412623, 56529819571, 10431, 30461) And their sizes: import sys sys.getsizeof(t) # 88 aa, bb, cc, dd = sys.getsizeof(a), sys.getsizeof(b), sys.getsizeof(c), sys.getsizeof(d) sum([aa,bb,cc,dd]) # 96 Why does the tuple take u...
[ "The number returned by sys.getsizeof doesn't include the size of the objects contained by a container. \n>>> sys.getsizeof({1:2})\n280\n>>> sys.getsizeof({'a_really_long_string_that_takes_up_lots_of_space':'foo'})\n280\n\n", "I'm working on a 32-bit Windows XP, with Python 2.6.2, and I tried your code, which loo...
[ 13, 3 ]
[]
[]
[ "python", "sizeof", "tuples" ]
stackoverflow_0006091992_python_sizeof_tuples.txt
Q: Adding 2 matrix and Multiplying 2 matrix in python by using scipy/numpy I am trying to use scipy and numpy to perform matrix addition and multiplication. I have 2 matrix "a" and "b". my goal is to add "a" and "b" together and store the result into a matrix "c" Also I want to multiply "a" and "b" and store into a m...
Adding 2 matrix and Multiplying 2 matrix in python by using scipy/numpy
I am trying to use scipy and numpy to perform matrix addition and multiplication. I have 2 matrix "a" and "b". my goal is to add "a" and "b" together and store the result into a matrix "c" Also I want to multiply "a" and "b" and store into a matrix "d". Are there any function perform like that in Scipy/Numpy? Thanks ...
[ "Matrix multiplication:\na = numpy.matrix(a)\nb = numpy.matrix(b)\nc = a+b\nd = a*b\n\nArray multiplication (map operator.mul):\na = numpy.array(a)\nb = numpy.array(b)\nc = a+b\nd = a*b\n\n" ]
[ 14 ]
[]
[]
[ "math", "matrix", "numpy", "python", "scipy" ]
stackoverflow_0006092388_math_matrix_numpy_python_scipy.txt
Q: django haystack inheritance problems I am using django and haystack for a search (obviously) and I dont want it including inherited objects. For example: lets say I have model Person and model Employee(which inherits from Person). When an Employee object is added, it also creates a Person object. Person's dont hav...
django haystack inheritance problems
I am using django and haystack for a search (obviously) and I dont want it including inherited objects. For example: lets say I have model Person and model Employee(which inherits from Person). When an Employee object is added, it also creates a Person object. Person's dont have to be Employees though. So I want to sea...
[ "You can add a is_employee field to your SearchIndex class for Person model.\nclass Person(models.Model):\n # your existing code goes here\n\n @property\n def is_employee(self):\n try:\n self.employee # try to get the associated Employee object\n return True\n exce...
[ 2 ]
[]
[]
[ "django", "django_haystack", "python" ]
stackoverflow_0006091950_django_django_haystack_python.txt
Q: Stringing together C and Python code in Go? Update I'm trying to create a simple Go function which will simply take in a string of reddit-style Markdown and return the appropriate HTML. Right now, I know that having Discount installed is a prerequisite and that at least the following three files are used by reddi...
Stringing together C and Python code in Go?
Update I'm trying to create a simple Go function which will simply take in a string of reddit-style Markdown and return the appropriate HTML. Right now, I know that having Discount installed is a prerequisite and that at least the following three files are used by reddit as wrappers around Discount: https://github.co...
[ "If all you want is Markdown, I don't see how Python fits into this. Maybe there's more to it, but if at all possible you should leave Python out of this. If there's a reason to use Python that wasn't in the question, I can edit this answer and address that.\nFirst, try this native Go Markdown package: https://gith...
[ 3 ]
[]
[]
[ "c", "go", "markdown", "python", "reddit" ]
stackoverflow_0006089041_c_go_markdown_python_reddit.txt
Q: How to make this python script memory efficient This snippet pulls all of the docs out of my database, and dumps them into a gzip-compressed file. docs_to_dump is a django object containing all of the text documents to be dumped. os.chdir(dump_dir) filename = 'latest-' + court_id + '.xml.gz.part' with myGzipFile(...
How to make this python script memory efficient
This snippet pulls all of the docs out of my database, and dumps them into a gzip-compressed file. docs_to_dump is a django object containing all of the text documents to be dumped. os.chdir(dump_dir) filename = 'latest-' + court_id + '.xml.gz.part' with myGzipFile(filename, mode='wb') as z_file: z_file.write('<?x...
[ "I think andrewski might be right. If you are crashing, try adjusting your Query's to use the iterator method\nSomething like.\ndocs_to_dump = Document.objects.all().order_by('court').iterator()\n\nShould keep from loading your entire Queryset into memory.\n" ]
[ 2 ]
[]
[]
[ "data_dump", "django", "gzip", "memory_optimization", "python" ]
stackoverflow_0006092417_data_dump_django_gzip_memory_optimization_python.txt
Q: IndexErrors in Tic-Tac-Toe program I'm having issues with I've pasted the code here: X = "X" O = "O" board = [] EMPTY = "" def instructions_prompt (): print "\t\t\tNoughts and Crosses" print \ """Foolish human. Now that you've entered this Python program, there is no exit. None! (At any po...
IndexErrors in Tic-Tac-Toe program I'm having issues with
I've pasted the code here: X = "X" O = "O" board = [] EMPTY = "" def instructions_prompt (): print "\t\t\tNoughts and Crosses" print \ """Foolish human. Now that you've entered this Python program, there is no exit. None! (At any point in the game if you feel like you are intimidated by ...
[ "You have your arguments mixed up for the function computer_move. On line 113, the arguments are in the order computer, board, human. However, on line 147, where computer_move is called, the order is board, computer, human.\nPython gave you the confusing index error because Python strings are really just lists of ...
[ 5 ]
[]
[]
[ "debugging", "indexing", "python", "tic_tac_toe" ]
stackoverflow_0006092711_debugging_indexing_python_tic_tac_toe.txt
Q: storing list/tuples in sqlite database with sqlalchemy I have a class that holds the size and position of something I draw to the screen. I am using sqlalchemy with a sqlite database to persist these objects. However, the position is a 2D value (x and y) and I'd like to have a convienent way to access this as My...
storing list/tuples in sqlite database with sqlalchemy
I have a class that holds the size and position of something I draw to the screen. I am using sqlalchemy with a sqlite database to persist these objects. However, the position is a 2D value (x and y) and I'd like to have a convienent way to access this as MyObject.pos # preferred, simpler interface # instead of: My...
[ "If you are using PostGIS (Geometry extended version of postgres), you can take advantage of that using GeoAlchemy, which allows you to define Column types in terms of geometric primitives available in PostGIS. One such data type is Point, which is just what it sounds like. \nPostGIS is a bit more difficult to se...
[ 4, 0 ]
[]
[]
[ "python", "sqlalchemy", "sqlite" ]
stackoverflow_0006092616_python_sqlalchemy_sqlite.txt
Q: How can one plot time-related information with python in a natural human-readable way? Often, you have a set of events (visits to a website, price information, whatever) that's related to a time value, let's say a timestamp (though a datetime object is just fine). How can they be plotted so that the time axis gets...
How can one plot time-related information with python in a natural human-readable way?
Often, you have a set of events (visits to a website, price information, whatever) that's related to a time value, let's say a timestamp (though a datetime object is just fine). How can they be plotted so that the time axis gets human-readable, meaningful values instead of just number of seconds? I've been looking arou...
[ "FWIW here's a simple example of plotting some values against times using the excellent and well-documented matplotlib:\n\ndata.csv:\n VISIT_TIME TOTAL_VISITS\n 06:00:00 290\n 06:30:00 306\n 07:00:00 364\n 07:30:00 363\n 08:00:00 469\n 08:30:00 436\n 09:00:00 449\n 0...
[ 2 ]
[]
[]
[ "plot", "python", "time" ]
stackoverflow_0006092561_plot_python_time.txt
Q: find a repetitive expression using python regular expression Hello I am trying to retrieve the following string from a file neighbors= {5 7 9 11 13 14 15 16 17 } The pattern {number1 number2... } varies, some are short some are too long. I want to find such a pattern. My logic is to retrieve the statement "neighb...
find a repetitive expression using python regular expression
Hello I am trying to retrieve the following string from a file neighbors= {5 7 9 11 13 14 15 16 17 } The pattern {number1 number2... } varies, some are short some are too long. I want to find such a pattern. My logic is to retrieve the statement "neighbors= {" which is followed by a number and a space as a repetition ...
[ "I think you're looking for this:\nimport re\nFOO = \"\"\"neighbors= {5 7 9 11 13 14 15 16 17 }\"\"\"\nmatch = re.search('(neighbors\\s*=\\s*\\{\\s*(\\d+\\s*)+\\})', FOO)\nprint match.group(1)\n\nThe regex is portable, of-course to many different languages.\nRunning that yields...\nneighbors= {5 7 9 11 13 14 15 16 ...
[ 2, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006092863_python_regex.txt
Q: HTML output using Python 3/sqlite3 Newbie to Python and SQLLite: @ http://www.sqlite.org/sqlite.html - "Command Line Shell For SQLite" I found this: Changing Output Formats: The sqlite3 program is able to show the results of a query in eight different formats: "csv", "column", "html", "insert", "line", "list", "ta...
HTML output using Python 3/sqlite3
Newbie to Python and SQLLite: @ http://www.sqlite.org/sqlite.html - "Command Line Shell For SQLite" I found this: Changing Output Formats: The sqlite3 program is able to show the results of a query in eight different formats: "csv", "column", "html", "insert", "line", "list", "tabs", and "tcl". You can use the ".mode" ...
[ "sqlite's html mode is part of a wrapper that is not included in python, but you can use the aspw module to access it...\nimport apsw\nimport StringIO as io\noutput=io.StringIO()\nconn = apsw.Connection('dbTest.dat')\nshell=apsw.Shell(stdout=output, db=conn)\n# How to execute a dot command\nshell.process_command(\"...
[ 1 ]
[]
[]
[ "html", "python", "sqlite" ]
stackoverflow_0006092988_html_python_sqlite.txt
Q: Anyway to bring up suggestion box when typing python code I'm learning wxpython right now and one thing that helps me ALOT is when I'm typing in the text editor I sometimes press the tab key to give me a hint on what I'm looking for...This is great when it works but I notice sometimes it doesn't work and I get los...
Anyway to bring up suggestion box when typing python code
I'm learning wxpython right now and one thing that helps me ALOT is when I'm typing in the text editor I sometimes press the tab key to give me a hint on what I'm looking for...This is great when it works but I notice sometimes it doesn't work and I get lost looking for a syntax I can't remember... Question is how can ...
[ "What editor do you use??\nWithout knowing that there's no way we can possibly help you.\nFWIW in vim I use C-x [onp]\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006093313_python.txt
Q: python dependency + deployment tool? Does anybody know of a tool to handle module dependencies + deployment in Python? Details: By handle, I mean: list, keep track of and bundle up a zip/installable file for me. Make it trivial to redeploy on another system (ie: includes all modules at the correct versio...
python dependency + deployment tool?
Does anybody know of a tool to handle module dependencies + deployment in Python? Details: By handle, I mean: list, keep track of and bundle up a zip/installable file for me. Make it trivial to redeploy on another system (ie: includes all modules at the correct version in a deploy file, and does not have to g...
[ "Setuptools plus pypi is made for that. The setuptools is an enhanced distutils, with which you can specify dependencies. For example, in the setup function:\ninstall_requires = ['simplejson>=2.0,==dev'],\n\nWill pull in that dependency when you use easy_install.\n", "Since you are on windows take a look at py2ex...
[ 5, 2 ]
[]
[]
[ "dependencies", "dependency_management", "deployment", "python", "web_deployment" ]
stackoverflow_0006092072_dependencies_dependency_management_deployment_python_web_deployment.txt
Q: reporting end of seed or leeching to tracker Libtorrent From what I know, when seeding or leeching torrent, your IP is on tracker and it remains there for some few hours or days How do I manually tell my the tracker using Libtorrent I am no longer going to be connected to the tracker and it should forget my IP as ...
reporting end of seed or leeching to tracker Libtorrent
From what I know, when seeding or leeching torrent, your IP is on tracker and it remains there for some few hours or days How do I manually tell my the tracker using Libtorrent I am no longer going to be connected to the tracker and it should forget my IP as I am neither seeding nore leeching. Any code bits or advices ...
[ "Trackers are just HTTP services (although poorly designed). See BitTorrent Tracker Protocol, in particular, the event query parameter. In Python, you can use urllib.\n", "libtorrent automatically does this when stopping a torrent, or stopping the session. If it seems to fail, you might want to increase the tra...
[ 2, 1 ]
[]
[]
[ "bittorrent", "c++", "python", "tracker" ]
stackoverflow_0006081815_bittorrent_c++_python_tracker.txt
Q: help with python inheritance Given an arbitrary object: class Val(object): def __init__(self): this_val = 123 I want to create an abstract base class which has an attribute that is a Val(): class A(object): foo = Val() I would expect that when my children inherit from that class, they would get c...
help with python inheritance
Given an arbitrary object: class Val(object): def __init__(self): this_val = 123 I want to create an abstract base class which has an attribute that is a Val(): class A(object): foo = Val() I would expect that when my children inherit from that class, they would get copies of Val(). For example: class...
[ "The attribute foo only exists on A. You will have to use a metaclass to add a new Val to each class.\nclass Val(object):\n def __init__(self):\n self.this_val = 123\n\nclass MC(type):\n def __init__(self, name, bases, d):\n super(MC, self).__init__(name, bases, d)\n self.foo = Val()\n\nclass A(obj...
[ 4, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006093656_django_python.txt
Q: django-registration can't set the "from" email address for authentication email i've got django-registration setup and working with my application. I'm on django 1.1 and using the latest django-registration, 0.8 alpha. in case it is relevant, i'm using the fcgi method to deploy and the django-registration app is d...
django-registration can't set the "from" email address for authentication email
i've got django-registration setup and working with my application. I'm on django 1.1 and using the latest django-registration, 0.8 alpha. in case it is relevant, i'm using the fcgi method to deploy and the django-registration app is deployed in a separate folder. I simply add the containing folder to python path. i.e....
[ "A typo, you set DEFAULT_FROM_USER in your settings, but it should be DEFAULT_FROM_EMAIL.\n", "The snippet from settings.py is DEFAULT_FROM_USER instead of DEFAULT_FROM_EMAIL\n" ]
[ 6, 0 ]
[]
[]
[ "default", "django", "django_registration", "python" ]
stackoverflow_0006093919_default_django_django_registration_python.txt
Q: Capturing groups and lookarounds I want to know how capturing groups (or non capturing) are affecting lookarounds in Regex. Here are 2 example: test (?:(?!<start).)+ test (?!<start).+ I would appreciate if anybody can explain how regex engine is interpreting both cases in details. A: Look-arounds are zero-widt...
Capturing groups and lookarounds
I want to know how capturing groups (or non capturing) are affecting lookarounds in Regex. Here are 2 example: test (?:(?!<start).)+ test (?!<start).+ I would appreciate if anybody can explain how regex engine is interpreting both cases in details.
[ "\nLook-arounds are zero-width. In that respect, it doesn't make much sense to place them on their own inside a capturing group, they don't capture anything more interesting than an empty string (much like \\b vs. (\\b). Edge cases involve back-referencing an optional group, but that isn't very interesting.\nPositi...
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006093844_python_regex.txt
Q: Recursively copying files with progress I've seen questions asked here before about Python and copying files, but I have a different scenario to deal with. I'm almost done with a Linux distro installer I've been working on, and now all it needs to do is copy the files over to the destination partition. As most dis...
Recursively copying files with progress
I've seen questions asked here before about Python and copying files, but I have a different scenario to deal with. I'm almost done with a Linux distro installer I've been working on, and now all it needs to do is copy the files over to the destination partition. As most distro installers have a progress bar, I was hop...
[ "You could try using shutil.copy to copy files instead of calling out to the OS using os.system (which creates a separate process). You can also use os.mkdir to create new directories. However, are you sure that it is slow because of the progress bar and not something else?\n" ]
[ 1 ]
[]
[]
[ "copy", "file_io", "progress_bar", "pyqt4", "python" ]
stackoverflow_0006094534_copy_file_io_progress_bar_pyqt4_python.txt
Q: Can I call python script or function from php I have the php page which lists the backups with filename and username. the backups are done with python script but for web interface I used php. Now I want to put the facility on webpage where there will be button called restore next to backup file name and all the ho...
Can I call python script or function from php
I have the php page which lists the backups with filename and username. the backups are done with python script but for web interface I used php. Now I want to put the facility on webpage where there will be button called restore next to backup file name and all the home dir contents are replaced. I can make the python...
[ "Yes you can call exec(\"python pythonscript.py someparams\"); or if you need to save the output to a variable use this code\nexec(\"python mypythonscript.py someparams\",$output);\nvar_dump($output);\n\nMore informaiton: call python script by php and solve errors\n", "You can call the shell from PHP:\n\nshell_ex...
[ 7, 1 ]
[]
[]
[ "linux", "php", "python" ]
stackoverflow_0006094643_linux_php_python.txt
Q: Why this strange behaviour of 'round' built in.(python 2.6) Why So ? >>> round(2/3) 0.0 >>> round(0.66666666666666666666666666666667) 1.0 >>> round(2.0/3) 1.0 A: That's not strange behaviour from round(): Try this: >>> 2/3 0 Using / with two integer values will do an integer division. So the argument to roun...
Why this strange behaviour of 'round' built in.(python 2.6)
Why So ? >>> round(2/3) 0.0 >>> round(0.66666666666666666666666666666667) 1.0 >>> round(2.0/3) 1.0
[ "That's not strange behaviour from round():\nTry this:\n>>> 2/3\n0\n\nUsing / with two integer values will do an integer division. So the argument to round() is already 0, which makes round() return 0.\nUpdate: as @Mark noted in the comment, this behaviour changed in Python 3: 2/3 will do a floating point division ...
[ 16 ]
[]
[]
[ "python", "rounding" ]
stackoverflow_0006094843_python_rounding.txt
Q: how to store key-value as well as value-key in Python? I have this somewhat big data structure that stores pairs of data. The individual data is tiny and readily hashable, and there are something like a few hundred thousand data points in there. At first, this was a simple dict that was accessed only by keys. Late...
how to store key-value as well as value-key in Python?
I have this somewhat big data structure that stores pairs of data. The individual data is tiny and readily hashable, and there are something like a few hundred thousand data points in there. At first, this was a simple dict that was accessed only by keys. Later on however, I discovered that I also needed to access it b...
[ "You could try bidict.\n" ]
[ 4 ]
[]
[]
[ "data_structures", "key_value", "python" ]
stackoverflow_0006094929_data_structures_key_value_python.txt
Q: Understanding unicode in Python and UnicodeDecodeError In Python 2.7 on a Mac I'm printing file names retrieved with nltk's PlaintextCorpusReader: infobasecorpus = PlaintextCorpusReader(corpus_root, '.*\.txt') for fileid in infobasecorpus.fileids(): print fileid and get UnicodeDecodeError: 'ascii', '100316-N1...
Understanding unicode in Python and UnicodeDecodeError
In Python 2.7 on a Mac I'm printing file names retrieved with nltk's PlaintextCorpusReader: infobasecorpus = PlaintextCorpusReader(corpus_root, '.*\.txt') for fileid in infobasecorpus.fileids(): print fileid and get UnicodeDecodeError: 'ascii', '100316-N1-The \xc2\xa3250bn cost of developing.txt', 14, 15, 'ordinal...
[ "Check the type of the fileid object. I suspect it is not a unicode object as you suggest. The UnicodeDecodeError is being raised because of an implicit decode prior to python encoding the string for output (by print).\nOnce the string is successfully decoded (to unicode), you can then print it by explicitly encodi...
[ 2 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0006094812_python_unicode.txt
Q: Running a long running process via Python Popen So, I thought it would be cool if i could get my dev env up and running in a single fell swoop with some python magic. Various DBs, webserver etc. However, every variation on the below that i have tried on the following seems to fail with 'file not found'. p2 = Popen...
Running a long running process via Python Popen
So, I thought it would be cool if i could get my dev env up and running in a single fell swoop with some python magic. Various DBs, webserver etc. However, every variation on the below that i have tried on the following seems to fail with 'file not found'. p2 = Popen(["exec", "/path/to/redis/server"], stdin=p1.stdout, ...
[ "exec is a builtin command in bash, not an executable. The file not found error probably comes from exec not being found in the $PATH.\nI would try ommitting \"exec\" in the Popen call.\n" ]
[ 2 ]
[]
[]
[ "development_environment", "multiprocessing", "python", "unix" ]
stackoverflow_0006094990_development_environment_multiprocessing_python_unix.txt
Q: Patching render_to_response using Mock I am using Mock and I am not able to patch django's render_to_response function properly. For e.g., the following test never fails: from django.test.client import Client from mock import patch import nose.tools as nt @patch('django.shortcuts.render_to_respons...
Patching render_to_response using Mock
I am using Mock and I am not able to patch django's render_to_response function properly. For e.g., the following test never fails: from django.test.client import Client from mock import patch import nose.tools as nt @patch('django.shortcuts.render_to_response') def test_should_fail(self, render_to...
[ "Firstly, why do you want to do this?\nSecondly, the place you should patch a function is the place you are calling it - ie in the views module that handles the relevant URL. For example:\n@patch('myapp.views.render_to_response')\n\n" ]
[ 4 ]
[]
[]
[ "django", "mocking", "python" ]
stackoverflow_0006095019_django_mocking_python.txt
Q: Enigmatic Naming of Lists in Python I am writing a program in python and I am using a dictionary. I need to create an empty list for each key in the dictionary, and each list needs to have the same name as the key. The keys are user entered, which is why I can't just make a list in the conventional way. This was t...
Enigmatic Naming of Lists in Python
I am writing a program in python and I am using a dictionary. I need to create an empty list for each key in the dictionary, and each list needs to have the same name as the key. The keys are user entered, which is why I can't just make a list in the conventional way. This was the first thing I tried a = {"x":1, "y":2,...
[ "This really doesn't make much sense. Why do your lists need 'names'? For that matter, what do you mean by 'names'?\nSecondly, your code doesn't do anything. a.keys() is already a list. Calling list on it doesn't do anything else. But in any case, whatever the result of that line is, it is immediately thrown away, ...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006094983_python.txt
Q: Python - Get class of type from imported module I am trying to import a class from a file with a dynamic name. Here is my file importer: def get_channel_module(app, method): mod_name = 'channel.%s.%s' % (app, method) module = __import__(mod_name, globals(), locals(), [method]) return module This impor...
Python - Get class of type from imported module
I am trying to import a class from a file with a dynamic name. Here is my file importer: def get_channel_module(app, method): mod_name = 'channel.%s.%s' % (app, method) module = __import__(mod_name, globals(), locals(), [method]) return module This imports the specific python file, for example, some_file.p...
[ "You can do this by inspecting the symbols in your module with issubclass:\ndef get_subclass(module, base_class):\n for name in dir(module):\n obj = getattr(module, name)\n try:\n if issubclass(obj, base_class):\n return obj\n except TypeError: # If 'obj' is not a ...
[ 8, 4 ]
[]
[]
[ "python" ]
stackoverflow_0006095131_python.txt
Q: Filter related set in a related set I have the following structure of models : parent Park child Warehouse(foreign key with Park, related_name = park_warehouses) child child Issue(foreign key with Warehouse, related_name = warehouse_issues) now I'd like to filter and get amount of Issues for Park by getting issue...
Filter related set in a related set
I have the following structure of models : parent Park child Warehouse(foreign key with Park, related_name = park_warehouses) child child Issue(foreign key with Warehouse, related_name = warehouse_issues) now I'd like to filter and get amount of Issues for Park by getting issues of each park's building. I've tried th...
[ "Issue.objects.filter(warehouse__park=park)\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "django_queryset", "filtering", "python" ]
stackoverflow_0006095264_django_django_models_django_queryset_filtering_python.txt
Q: Python: One Try Multiple Except In Python, is it possible to have multiple except statements for one try statement? Such as : try: #something1 #something2 except ExceptionType1: #return xyz except ExceptionType2: #return abc A: Yes, it is possible. try: ... except FirstException: handle_first_one() ex...
Python: One Try Multiple Except
In Python, is it possible to have multiple except statements for one try statement? Such as : try: #something1 #something2 except ExceptionType1: #return xyz except ExceptionType2: #return abc
[ "Yes, it is possible.\ntry:\n ...\nexcept FirstException:\n handle_first_one()\n\nexcept SecondException:\n handle_second_one()\n\nexcept (ThirdException, FourthException, FifthException) as e:\n handle_either_of_3rd_4th_or_5th()\n\nexcept Exception:\n handle_all_other_exceptions()\n\nSee: http://docs.py...
[ 523 ]
[]
[]
[ "exception_handling", "python", "syntax" ]
stackoverflow_0006095717_exception_handling_python_syntax.txt
Q: similar to docutils in PHP Just curious to know is there any document utility available in PHP which can perform something like docutils in python ? A libary which can be very user friendly in terms of converting restructured text into HTML ? A: phpDocumentor is quite outdated. Have a look at DocBlox (Github Rep...
similar to docutils in PHP
Just curious to know is there any document utility available in PHP which can perform something like docutils in python ? A libary which can be very user friendly in terms of converting restructured text into HTML ?
[ "phpDocumentor is quite outdated. Have a look at DocBlox (Github Repository) or DocBlox-project.org\nedit:\ndocblox merged with phpdocumentor and they now maintain phpdocumentor 2.\nlinks that take you directly to the project:\nphpdoc.org\ngithub repo\n", "Try phpDocumentor.\n" ]
[ 3, 1 ]
[]
[]
[ "documentation", "php", "python" ]
stackoverflow_0006095818_documentation_php_python.txt
Q: Django Want to count different item types Previously I had a client summary list in a table. In one column I had a list of object types and in another, I had the quantity of that object type. @login_required def client_summary(request, client_id): client = models.Client.objects.get(pk = client_id) items = ...
Django Want to count different item types
Previously I had a client summary list in a table. In one column I had a list of object types and in another, I had the quantity of that object type. @login_required def client_summary(request, client_id): client = models.Client.objects.get(pk = client_id) items = client.storageitem_set.all() tape_and_film_...
[ "If you need to display some info of items for every tag, you can use regroup tag. If you want only quantity, use Count aggregation function.\n" ]
[ 1 ]
[]
[]
[ "count", "django", "html", "python", "tags" ]
stackoverflow_0006095888_count_django_html_python_tags.txt
Q: Problem syncdb-ing new BeautifulSoup package in django This was the traceback, please help. Traceback (most recent call last): File "C:\Documents and Settings\EC.32-SAMUEL\workspace\ec\ec\manage.py", line 11, in <module> execute_manager(settings) File "C:\Python26\lib\site-packages\django\co...
Problem syncdb-ing new BeautifulSoup package in django
This was the traceback, please help. Traceback (most recent call last): File "C:\Documents and Settings\EC.32-SAMUEL\workspace\ec\ec\manage.py", line 11, in <module> execute_manager(settings) File "C:\Python26\lib\site-packages\django\core\management\__init__.py", line 438, in execute_manager ...
[ "BeautifulSoup is not a Django-app. Its a python package/module. You don't have to add to INSTALLED_APPS. It just need to be available in your PYTHONPATH to use it.\nYour traceback doesn't give clue what is actually wrong with your Django project.\n", "The only time you ever need to do a syncdb is when you have t...
[ 3, 0 ]
[]
[]
[ "beautifulsoup", "django", "python" ]
stackoverflow_0006093693_beautifulsoup_django_python.txt
Q: Failing to capture stdout from application I have the following script: import subprocess arguments = ["d:\\simulator","2332.txt","2332.log", "-c"] output=subprocess.Popen(arguments, stdout=subprocess.PIPE).communicate()[0] print(output) which gives me b'' as output. I also tried this script: import subprocess...
Failing to capture stdout from application
I have the following script: import subprocess arguments = ["d:\\simulator","2332.txt","2332.log", "-c"] output=subprocess.Popen(arguments, stdout=subprocess.PIPE).communicate()[0] print(output) which gives me b'' as output. I also tried this script: import subprocess arguments = ["d:\\simulator","2332.txt","atp23...
[ "If possible (not endless stream of data) you should use communicate() as noted on the page.\nTry this:\nimport subprocess\n\narguments = [\"d:\\\\simulator\",\"2332.txt\",\"atp2332.log\", \"-c\"]\nprocess = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nsout, serr = process.communicat...
[ 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0006094618_python_python_3.x.txt
Q: How to transpose a 2 Element Vector In python, I have a 2x1 array a=array([[ 0, 4, 8, 12, 16], [ 0, 8, 16, 24, 32]]) When I extract a column vector c=a[:,1] C becomes a 1x2 array, and I wish it to be a 2x1 array. Applying transpose does not seems to do the trick. Any suggestions? Thanks A: After c=a[:,...
How to transpose a 2 Element Vector
In python, I have a 2x1 array a=array([[ 0, 4, 8, 12, 16], [ 0, 8, 16, 24, 32]]) When I extract a column vector c=a[:,1] C becomes a 1x2 array, and I wish it to be a 2x1 array. Applying transpose does not seems to do the trick. Any suggestions? Thanks
[ "After\nc=a[:,1]\n\nc is now:\narray([4, 8])\n\ni.e. a 1D array (so even not 1x2).\nIf you want it a 2x1 array, try this:\nc = a[:,1:2]\n\nit will become:\narray([[4],\n [8]])\n\n", "Have you tried c.reshape(2,1) ?\n", "Other options include:\nimport numpy as np\nc = a[:,1]\n\nand then access the data wit...
[ 8, 1, 1 ]
[]
[]
[ "numpy", "python", "transpose" ]
stackoverflow_0006096084_numpy_python_transpose.txt
Q: Django/Python sorting after getting cached results Greetings, A few quick things (django 1.2.3, python 2.6, memcached). I have a function where I first do a somewhat expensive query, when I do this query I do an oder_by. I then update some values which may change the order of the results. I then put all of the v...
Django/Python sorting after getting cached results
Greetings, A few quick things (django 1.2.3, python 2.6, memcached). I have a function where I first do a somewhat expensive query, when I do this query I do an oder_by. I then update some values which may change the order of the results. I then put all of the values in the cache. Then in another function I get the c...
[ "The Python function sorted() works with Mutable List Types, which a Django queryset is not: this is what the error you're getting is basically telling you. Technically, subscripting is the act of accessing a list element by its index, like this:\nlist = ['a', 'b', 'c']\nlist[0] # This is a subscript\n\nIf you try ...
[ 4, 1 ]
[ "try to pickle your list before you set it in cache:\nimport cPickle as pickle\n\ncache.set(pickle.dumps(mylist))\n\n\nfunction(2):\n my_cache_list = cache.get(cache_key)\n newlist = sorted(pickle.loads(my_cache_list),key=operator.itemgetter('score'), reverse=True )\n\n" ]
[ -1 ]
[ "django", "memcached", "python", "sorting" ]
stackoverflow_0006094171_django_memcached_python_sorting.txt
Q: Create ctypes binding to C function with variable length arg list Assuming I have C function with variable length argument list: int some_func(int arg1 , ... ); Is it possible (easy?) to call this function from python using ctypes? Update: Implemented suggestion from cedric and that worked like charm: libc =...
Create ctypes binding to C function with variable length arg list
Assuming I have C function with variable length argument list: int some_func(int arg1 , ... ); Is it possible (easy?) to call this function from python using ctypes? Update: Implemented suggestion from cedric and that worked like charm: libc = ctypes.CDLL( "/lib64/libc.so.6" , ctypes.RTLD_GLOBAL ) printf = getatt...
[ "Assuming you can bind the libc printf function, that is a really good example of va_args using, I think you'll be able to create a binding with any function.\n" ]
[ 2 ]
[]
[]
[ "c", "ctypes", "python" ]
stackoverflow_0006096173_c_ctypes_python.txt
Q: How can I get a list of windows with Wnck, using PyGI? I just started using PyGI (on Ubuntu Natty), although I have never used pygtk before. I have used wnck in a wxPython program though, and it was easy enough to get a list of currently opened windows. From PyGI, the window list is always empty. relevant code bit...
How can I get a list of windows with Wnck, using PyGI?
I just started using PyGI (on Ubuntu Natty), although I have never used pygtk before. I have used wnck in a wxPython program though, and it was easy enough to get a list of currently opened windows. From PyGI, the window list is always empty. relevant code bits: from gi.repository import Gtk, Wnck while Gtk.events_pen...
[ "You need to call screen.force_update() before screen.get_windows() returns list of windows. Unfortunately docs are lacking this part :(\nIn [1]: from gi.repository import Gtk, Wnck\n\nIn [2]: Gtk.main_iteration()\nOut[2]: True\n\nIn [3]: screen = Wnck.Screen.get_default()\n\nIn [4]: screen.force_update()\n\nIn [5]...
[ 6, 1 ]
[]
[]
[ "gtk", "pygobject", "pygtk", "python", "wnck" ]
stackoverflow_0005794309_gtk_pygobject_pygtk_python_wnck.txt
Q: Sha-bang line gives different result than calling the script manually I have a Python script script.py that has been defined as executable and which begins with the following sha-bang: #!/usr/bin/env python -W all But when I call it from the shell, this is what I get: $ ./script.py /usr/bin/env: python -W all: N...
Sha-bang line gives different result than calling the script manually
I have a Python script script.py that has been defined as executable and which begins with the following sha-bang: #!/usr/bin/env python -W all But when I call it from the shell, this is what I get: $ ./script.py /usr/bin/env: python -W all: No such file or directory Calling it directly works though: $ env python -W...
[ "On a shebang line, you only get one argument. So python -W all is being passed to env as one argument. On the command line, the shell correctly parses the arguments before invoking env.\n" ]
[ 5 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0006097265_python_shell.txt
Q: Cannot include css in cherrypy I come on CherryPy from PHP, but I have problem. I created in Eclipse project ( PyDev cherrypy ) and it shows in browser basic html but for some reason it want include css and js files. I included just like in php ( html, there is css folder, relative path is ok ) <link rel="stylesh...
Cannot include css in cherrypy
I come on CherryPy from PHP, but I have problem. I created in Eclipse project ( PyDev cherrypy ) and it shows in browser basic html but for some reason it want include css and js files. I included just like in php ( html, there is css folder, relative path is ok ) <link rel="stylesheet" href="css/style.css" type="text...
[ "specify css and js and images dirs as an static directories in the configuration:\n[/css]\ntools.staticdir.on = True\ntools.staticdir.dir = \"static\"\n\nfor more info on how to write site.config file:\nhttp://www.cherrypy.org/wiki/StaticContent\n" ]
[ 5 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0006097281_cherrypy_python.txt
Q: How to use github and ec2 together to deploy a python application I am currently using github to develop a python application and am looking to deploy it on EC2. Is there a good way to automatically handle the messiness this entails (setting up SSH key pairs on the EC2 instance for github, pulling from the github ...
How to use github and ec2 together to deploy a python application
I am currently using github to develop a python application and am looking to deploy it on EC2. Is there a good way to automatically handle the messiness this entails (setting up SSH key pairs on the EC2 instance for github, pulling from the github repository every time a commit is pushed to the master branch, etc.) wi...
[ "I wrote a simple python script to do this once. I also posted about it on my blog.\nYou set up mappings of your repositories and brances to point to local folders which already contain a checkout of that repo and branch. Then, you enable GitHub's post-receive hooks to hit the script which will then automatically t...
[ 0 ]
[]
[]
[ "amazon_ec2", "github", "python" ]
stackoverflow_0005220278_amazon_ec2_github_python.txt
Q: Python get arguments for partial functions I am looking to do something similar to what was asked here Getting list of parameter names inside python function, but using partial functions. ie. I need to get the possible arguments for a partial function. I can get the keyword arguments using: my_partial_func.keyword...
Python get arguments for partial functions
I am looking to do something similar to what was asked here Getting list of parameter names inside python function, but using partial functions. ie. I need to get the possible arguments for a partial function. I can get the keyword arguments using: my_partial_func.keywords but I am currently struggling to get the non-...
[ ".args contains the arguments passed to the partial function. If you want to get the arguments that the original function expects, use the inspect solution you linked on the .func attribute.\nYou can find this out by calling dir on a functools.partial object:\n>>> dir(x)\n['__call__', '__class__', '__delattr__', '_...
[ 7 ]
[]
[]
[ "arguments", "introspection", "parameters", "partial", "python" ]
stackoverflow_0006097759_arguments_introspection_parameters_partial_python.txt
Q: Force repaint in wxPython Canvas I've got a Canvas which manipulates objects in the mouse event handler. After modifying the objects, I want to trigger the OnPaint() event for the same Canvas to show (rerender) the changes. What is the right way to do this? It doesn't let me call OnPaint() directly. Also, is trigg...
Force repaint in wxPython Canvas
I've got a Canvas which manipulates objects in the mouse event handler. After modifying the objects, I want to trigger the OnPaint() event for the same Canvas to show (rerender) the changes. What is the right way to do this? It doesn't let me call OnPaint() directly. Also, is triggering an event from another event "wro...
[ "I would just call self.Refresh() or maybe RefreshRect() and pass the area that needs to be repainted.\n", "I tried self.refresh() as suggested by Mike Driscoll. That worked partially. I'm moving my own objects with mouse events and then repainting the image - rendering my objects. So the mouse events were updati...
[ 4, 1 ]
[]
[]
[ "drawing", "python", "wxpython" ]
stackoverflow_0006076014_drawing_python_wxpython.txt
Q: How do I secure REST calls I am making in-app? I have an application that has a "private" REST API; I use RESTful URLs when making Ajax calls from my own webpages. However, this is unsecure, and anyone could make those same calls if they knew the URL patterns. What's the best (or standard) way to secure these cal...
How do I secure REST calls I am making in-app?
I have an application that has a "private" REST API; I use RESTful URLs when making Ajax calls from my own webpages. However, this is unsecure, and anyone could make those same calls if they knew the URL patterns. What's the best (or standard) way to secure these calls? Is it worth looking at something like OAuth now ...
[ "Definitely take a look at OAuth\nIt is quickly becoming the \"de-facto\" standard for securing REST APIs and a lot of big companies are using it, including Google, Twitter and Facebook just to name a few.\nFor Python on GAE you have two options:\nThe most straightforward way (IMHO) is using David Larlet's library ...
[ 6, 4, 1 ]
[]
[]
[ "google_app_engine", "python", "rest", "restful_authentication", "tipfy" ]
stackoverflow_0006091784_google_app_engine_python_rest_restful_authentication_tipfy.txt
Q: Program called with subprocess - logger messages are not printed? there's a problem getting messages from a program's logger, if this program is called with subprocess. Here's the program BooFoo.py that uses logger to print messages to a file and console window: import logging LOG_FILENAME = 'example.log' logging....
Program called with subprocess - logger messages are not printed?
there's a problem getting messages from a program's logger, if this program is called with subprocess. Here's the program BooFoo.py that uses logger to print messages to a file and console window: import logging LOG_FILENAME = 'example.log' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) logger = logging...
[ "logging.StreamHandler defaults to writing to standard error, not standard output. You can change this to standard output by using logging.StreamHandler(sys.stdout) instead.\nYou can also keep your code as is, and print the value of proc_err instead of (or in addition to) proc_out in the calling process. This will ...
[ 3 ]
[]
[]
[ "logging", "python", "subprocess" ]
stackoverflow_0006098327_logging_python_subprocess.txt
Q: Problems linking to static files in Django 1.3 I'm running django 1.3, python 2.7 on windows XP I'm trying to setup a css in a static folder for my django app. The template looks like: <html> <head> <title>css demo</title> <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/my.css"...
Problems linking to static files in Django 1.3
I'm running django 1.3, python 2.7 on windows XP I'm trying to setup a css in a static folder for my django app. The template looks like: <html> <head> <title>css demo</title> <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/my.css" /> </head> <body> The generated HTML look...
[ "I bet you have your app running at http://localhost:8000, not http://localhost :)\nChange\nSTATIC_URL = 'http://localhost/static/'\n\nto\nSTATIC_URL = '/static/'\n\nNo need for absolute URL there.\n", "I created a folder:\nC:\\root\\workspace\\mysite\\src\\mysite\\common\n\nAnd in my settings, I have:\nSTATIC_RO...
[ 5, 2 ]
[]
[]
[ "django", "python", "static_files" ]
stackoverflow_0006073916_django_python_static_files.txt
Q: Python: Encoding problem I want to copy data from one database to another database. Therefore I wrote a Python script for this purpose. Names are in german, but I don't think that will be a problem for understanding my question. The script does the following db = mysql.connect(db='', charset="utf8", use_unicode=T...
Python: Encoding problem
I want to copy data from one database to another database. Therefore I wrote a Python script for this purpose. Names are in german, but I don't think that will be a problem for understanding my question. The script does the following db = mysql.connect(db='', charset="utf8", use_unicode=True, **v.MySQLServer[server]);...
[ "The error is made more difficult to interpret by the deep nesting of expressions you have.\nIn the line\nsql += \" %s, \" % db_util.formatierFeld(unicode(str(zeile[i]), \"utf-8\"), feldTypen[i])\n\nwhere does the exception come from? It's difficult to say. However, I would suppose that it comes from str(zeile[i]...
[ 3 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0006098482_encoding_python.txt