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: Django deployment problem in Apache/mod_wsgi. ImportError: Could not import settings 'site.settings' When I'm executing django-admin.py startproject site it works. But if I'm only copying site folder it doesn't work. Why? <VirtualHost *:80> ServerName django.stanislavfeldman.com # Django settings WSGIScriptAlias...
Django deployment problem in Apache/mod_wsgi. ImportError: Could not import settings 'site.settings'
When I'm executing django-admin.py startproject site it works. But if I'm only copying site folder it doesn't work. Why? <VirtualHost *:80> ServerName django.stanislavfeldman.com # Django settings WSGIScriptAlias / /var/www/django/wsgi_handler.py WSGIDaemonProcess django.stanislavfeldman.com maximum-requests=200 stac...
[ "If you have something like this in apache configs:\nWSGIScriptAlias /path /base/path/devel/your_project.wsgi\n\nAnd this inside your_project.wsgi:\nsys.path.append('/base/path')\nos.environ['DJANGO_SETTINGS_MODULE'] = 'devel.settings'\n\nThen apache will look at /base/path/devel/settings.py. If you move or copy /b...
[ 6, 5, 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004462276_django_python.txt
Q: Django Dev Environment Broken Following Mac OS 10.7 Reinstall I recently experienced trouble with my hard drive and used Disk Utilities to reinstall Mac OS 10.7 Lion. When I went to run my Django app, I got the following errors: ################ BEGIN ERRORS ################## Traceback (most recent call last): ...
Django Dev Environment Broken Following Mac OS 10.7 Reinstall
I recently experienced trouble with my hard drive and used Disk Utilities to reinstall Mac OS 10.7 Lion. When I went to run my Django app, I got the following errors: ################ BEGIN ERRORS ################## Traceback (most recent call last): File "manage.py", line 17, in <module> execute_manager(settings...
[ "You have two options:\n\nManual Install\nUse macports\n\nTo do either of those, you need to install xcode first - available from the mac app store (free, but 4GB+ download).\n" ]
[ 0 ]
[]
[]
[ "django", "mysql_python", "osx_lion", "python", "virtualenv" ]
stackoverflow_0008720856_django_mysql_python_osx_lion_python_virtualenv.txt
Q: PyQt - How to turn on/off spellchecking I'm using the following as a basis for my editor's spellchecker. I want to make an auto-spellcheck button, which when pressed will make the spellchecker work, and when not pressed, the spellchecker should not highlight or suggest anything. You know the one similar to LibreOf...
PyQt - How to turn on/off spellchecking
I'm using the following as a basis for my editor's spellchecker. I want to make an auto-spellcheck button, which when pressed will make the spellchecker work, and when not pressed, the spellchecker should not highlight or suggest anything. You know the one similar to LibreOffice/OpenOffice auto-spelcheck toolbar button...
[ "You can enable and disable the syntax highlighter by using it's setDocument method.\nThe SpellTextEdit class keeps a reference to its highlighter, so just add a couple of methods like this:\ndef highlighterEnabled(self):\n return self.highlighter.document() is not None\n\ndef setHighlighterEnabled(self, enable...
[ 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "spell_checking", "syntax_highlighting" ]
stackoverflow_0008722061_pyqt_pyqt4_python_spell_checking_syntax_highlighting.txt
Q: Are there any libraries for embedding Lua in Python using ctypes? Are there any libraries for doing this yet? If so, are they production quality? A: Dunno. But why bother when Lunatic exists.
Are there any libraries for embedding Lua in Python using ctypes?
Are there any libraries for doing this yet? If so, are they production quality?
[ "Dunno. But why bother when Lunatic exists.\n" ]
[ 2 ]
[]
[]
[ "ctypes", "embedding", "lua", "python" ]
stackoverflow_0008722327_ctypes_embedding_lua_python.txt
Q: Multiple cherrypy webapps on one server with apache serving other PHP projects? When I work in PHP I can work on seperate projects in different folders and run them by just pointing to the domain/folder. Is there a way to run cherrypy app in similar way? Basically I have a apache server I use for running my websit...
Multiple cherrypy webapps on one server with apache serving other PHP projects?
When I work in PHP I can work on seperate projects in different folders and run them by just pointing to the domain/folder. Is there a way to run cherrypy app in similar way? Basically I have a apache server I use for running my website. I use the same server to develop and test other PHP projects. Can I also easily us...
[ "http://tools.cherrypy.org/wiki/ModWSGI\nBasically, you have to set the engine to run in embedded mode. That's the python side.\nThe Apache side is covered in mod_wsgi discussions, but basically you create a virtual host with this directive\nWSGIScriptAlias /path/to/script.py\n\nYou should be able to run as many vi...
[ 0 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0008291197_cherrypy_python.txt
Q: Django building objects filter with GET params I have a page that returns a list of items and since the list if large I have put a little filter form on top of it to let users narrow down their view to exactly they want. They are able to select values from a couple of drop downs or leave them empty. So comes the r...
Django building objects filter with GET params
I have a page that returns a list of items and since the list if large I have put a little filter form on top of it to let users narrow down their view to exactly they want. They are able to select values from a couple of drop downs or leave them empty. So comes the request: /projects/?group=1&project_phase= with empt...
[ "Maybe you can use:\nparameters = {field_name: value for field_name, value in request.GET.items()\n if value and field_name in model._meta.get_all_field_names()}\nmodel.objects.filter(**parameters)\n\nAs suggested by the comments below, there aer a couple of checks to ignore undesired parameters:\n\nEm...
[ 4, 0 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0008720326_django_django_views_python.txt
Q: How to transfer a file between two connected computers in python? I don't know if this has been answered before(i looked online but couldn't find one), but how can i send a file (.exe if possible) over a network to another computer that is connected to the network? I tried sockets but i could only send strings and...
How to transfer a file between two connected computers in python?
I don't know if this has been answered before(i looked online but couldn't find one), but how can i send a file (.exe if possible) over a network to another computer that is connected to the network? I tried sockets but i could only send strings and i've tried to learn ftplib but i don't understand it at all or if ftp ...
[ "A. \nPython3\nWe can use http.server for this. From SO answer here, SimpleHTTPServer is moved to http.server in python3.\npython -m http.server\n\nPython2:\nI use SimpleHTTPServer for this sometimes:\npython -m SimpleHTTPServer\n\n...which would serve the files in the current directory on port 8000. Open your web ...
[ 10, 7, 3, 3 ]
[]
[]
[ "file", "python", "sockets" ]
stackoverflow_0008721870_file_python_sockets.txt
Q: What does an image look like as a Blob? I am working on an AppEngine application, to store images, they have to be stored in a BlobProperty. Is there a Mac/Linux way to convert images to their Blob representation or is there any tool (especially online) that can do this? A: Blobs do store bytes, and images ( as ...
What does an image look like as a Blob?
I am working on an AppEngine application, to store images, they have to be stored in a BlobProperty. Is there a Mac/Linux way to convert images to their Blob representation or is there any tool (especially online) that can do this?
[ "Blobs do store bytes, and images ( as any other file ) are represented by bytes, so you just store it\nSee: http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#Blob\n", "\"Blob\" stands for \"Binary Large OBject\". It's bytes. Just instantiate a db.Blob, passing the bytes.\n" ]
[ 5, 2 ]
[]
[]
[ "blob", "google_app_engine", "image", "python" ]
stackoverflow_0008722427_blob_google_app_engine_image_python.txt
Q: How to use regex to find functions call themself? I have a code.py: def funA(): print('A') funA() def funB(): print('B') def funC(): print('C') funB() funC() I want to find all functions call themself: funA funC How to write the regex? Constraint: All function call is normal: funname(...
How to use regex to find functions call themself?
I have a code.py: def funA(): print('A') funA() def funB(): print('B') def funC(): print('C') funB() funC() I want to find all functions call themself: funA funC How to write the regex? Constraint: All function call is normal: funname(arg1, arg2, ...) No obfuscated ways(such as lambda,exec...
[ "It's hard, because the function can call itself in obfuscated ways. E.g., does this count?\ndef funA():\n print 'A'\n foo = funA\n foo()\n\nfunA()\n\nWhat about this?\ndef funA():\n funB()\n\ndef funB():\n funA()\n\nfunA()\n\nOr even this?\ndef funA():\n exec('Anuf'[::-1] + '()')\n\nfunA()\n\nI don't think ...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "awk", "python", "regex", "shell" ]
stackoverflow_0008721514_awk_python_regex_shell.txt
Q: How to enable cookie support with pyWebKit? The documentation for pyWebKitGTK is pretty scarce. I've looked through their python .def files but they don't seem to contain the words cookie, session, (lib)soup or (lib)curl.. so maybe it isn't possible, huh. I've also looked through the WebKitGTK docs (for the C-base...
How to enable cookie support with pyWebKit?
The documentation for pyWebKitGTK is pretty scarce. I've looked through their python .def files but they don't seem to contain the words cookie, session, (lib)soup or (lib)curl.. so maybe it isn't possible, huh. I've also looked through the WebKitGTK docs (for the C-based library) and aside from a brief mention of libs...
[ "I can confirm that WebKitGTK supports cookies, and that you can use them with pywebkitgtk and ctypes successfully- though I'm not sure if that was the case when this question was posted! \nTo make cookies persist in a useful way, see my answer to this question.\n", "webkit is a html renderer, not a complete brow...
[ 1, -1 ]
[]
[]
[ "cookies", "python", "webkit" ]
stackoverflow_0001761473_cookies_python_webkit.txt
Q: How to install (run) Jumo (Python/Django) on localhost I am trying to run Jumo open source platform ( https://github.com/jumoconnect/openjumo) on my local machine (Windows 7). I have Python and Django installed and it works - I can create new project without problems, but I am not sure how to set existing project ...
How to install (run) Jumo (Python/Django) on localhost
I am trying to run Jumo open source platform ( https://github.com/jumoconnect/openjumo) on my local machine (Windows 7). I have Python and Django installed and it works - I can create new project without problems, but I am not sure how to set existing project and make it work. I am not experienced with Python/Django, s...
[ "as you may know Django is a powerful web framework and Python is a programming language, for python itself you need more than a few months to become some kind of expert.\nit's very easy to start, but not that easy to learn the whole stuff. Django is one of the most or maybe the most powerful web frameworks (beside...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008716794_django_python.txt
Q: Format comma seperated list of dates in python I've got a list of dates (datetimes): >>> print str(range) [datetime.datetime(2011, 12, 15, 0, 0), datetime.datetime(2011, 12, 16, 0, 0), datetime.datetime(2011, 12, 17, 0, 0)] and I'd like to format them as "%d/%m/%Y" and comma separate them, ie: 15/12/2011, 16/12/...
Format comma seperated list of dates in python
I've got a list of dates (datetimes): >>> print str(range) [datetime.datetime(2011, 12, 15, 0, 0), datetime.datetime(2011, 12, 16, 0, 0), datetime.datetime(2011, 12, 17, 0, 0)] and I'd like to format them as "%d/%m/%Y" and comma separate them, ie: 15/12/2011, 16/12/2011, 17/12/2011 At the moment I'm using map to run...
[ "map() is considered deprecated (although there are those that will argue otherwise).\n\", \".join(x.strftime(\"%d/%m/%Y\") for x in daterange)\n\n", "why not use list expression?\n\",\".join([ date.strftime(\"%d/%m/%Y\") for date in range])\n\nyes, map is deprecated, this is in the official documentation, becaus...
[ 2, 0 ]
[]
[]
[ "date", "datetime", "list", "map", "python" ]
stackoverflow_0008722473_date_datetime_list_map_python.txt
Q: Django and Rails - what should I expect in a Windows environment? I work in an environment that is totally .NET. However, over the past few months I've been learning Ruby and Rails on the side and enjoying it very much. I have been using Windows 7 to develop - along with Aptana - and so far things have gone bette...
Django and Rails - what should I expect in a Windows environment?
I work in an environment that is totally .NET. However, over the past few months I've been learning Ruby and Rails on the side and enjoying it very much. I have been using Windows 7 to develop - along with Aptana - and so far things have gone better than I expected. I have run into a few issues with gems on windows -...
[ "I am using Django on Windows Vista and it works very well. I am using sqlite, mysql and postgres. \nmysql install is a bit tricky: I recommend to download the right binaries from the web.\nI am using popular django apps and python modules without any problem. However, I've made a quick test with GeoDjango and noti...
[ 1 ]
[]
[]
[ "django", "python", "ruby_on_rails", "windows", "windows_7" ]
stackoverflow_0008719976_django_python_ruby_on_rails_windows_windows_7.txt
Q: I want to use matplotlib to make a 3d plot given a z function I have a z function that accepts x and y parameters and returns a z output. I want to plot this in 3d and set the scales. How can I do this easily? I've spent way too much time looking through the documentation and not once do I see a way to do this. A...
I want to use matplotlib to make a 3d plot given a z function
I have a z function that accepts x and y parameters and returns a z output. I want to plot this in 3d and set the scales. How can I do this easily? I've spent way too much time looking through the documentation and not once do I see a way to do this.
[ "The plotting style depends on your data: are you trying to plot a 3D curve (line), a surface, or a scatter of points? \nIn the first example below I've just used a simple grid of evenly spaced points in the x-y plane for the domain. Generally, you first create a domain of xs and ys, and then calculate the zs from...
[ 33 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0008722735_matplotlib_python.txt
Q: Generic way to create nested dictionary from flat list in python I am looking for the simplest generic way to convert this python list: x = [ {"foo":"A", "bar":"R", "baz":"X"}, {"foo":"A", "bar":"R", "baz":"Y"}, {"foo":"B", "bar":"S", "baz":"X"}, {"foo":"A", "bar":"S", "baz":"Y"}, ...
Generic way to create nested dictionary from flat list in python
I am looking for the simplest generic way to convert this python list: x = [ {"foo":"A", "bar":"R", "baz":"X"}, {"foo":"A", "bar":"R", "baz":"Y"}, {"foo":"B", "bar":"S", "baz":"X"}, {"foo":"A", "bar":"S", "baz":"Y"}, {"foo":"C", "bar":"R", "baz":"Y"}, ] into: foos = [ ...
[ "#!/usr/bin/env python3\nfrom itertools import groupby\nfrom pprint import pprint\n\nx = [\n {\"foo\":\"A\", \"bar\":\"R\", \"baz\":\"X\"},\n {\"foo\":\"A\", \"bar\":\"R\", \"baz\":\"Y\"},\n {\"foo\":\"B\", \"bar\":\"S\", \"baz\":\"X\"},\n {\"foo\":\"A\", \"bar\":\"S\", \"baz\":\"Y\"},\n...
[ 3, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0008711794_dictionary_python.txt
Q: Using Google Cloud Datastore and AJAX(blobs)-python Hi I have some images stored as BlobProperty in Google Cloud Datastore. I am trying to load these images via ajax into my template. For eg:- a user has an image and a name. Now the image and name area gets populated via an AJAX get call to the server. I am not un...
Using Google Cloud Datastore and AJAX(blobs)-python
Hi I have some images stored as BlobProperty in Google Cloud Datastore. I am trying to load these images via ajax into my template. For eg:- a user has an image and a name. Now the image and name area gets populated via an AJAX get call to the server. I am not understanding how to I send these images to the client , JS...
[ "This thread suggests that if you just create an image element, set its src, and add it to your page using Javascript, the browser will take care of making an HTTP request for the image:\nhttp://bytes.com/topic/javascript/answers/472046-using-ajax-xmlhttprequest-load-images\nIf you do want to do it with 'pure' AJAX...
[ 1, 0 ]
[]
[]
[ "flask", "google_app_engine", "google_cloud_datastore", "javascript", "python" ]
stackoverflow_0004177492_flask_google_app_engine_google_cloud_datastore_javascript_python.txt
Q: multiple coefficients with python Here is the problem: Let there be 9 distinct objects, find all the ways of dividing it into groups of 2, 3 and 4. Mathematically, the total number of division method can be expressed as 9!/2!3!4! Here is what I have tried, import itertools def multiCoef(seta, n1, n2): seta = se...
multiple coefficients with python
Here is the problem: Let there be 9 distinct objects, find all the ways of dividing it into groups of 2, 3 and 4. Mathematically, the total number of division method can be expressed as 9!/2!3!4! Here is what I have tried, import itertools def multiCoef(seta, n1, n2): seta = set(seta) for comba in itertools.combin...
[ "See itertools.\nhttp://docs.python.org/library/itertools.html\n", "To find the number of ways to divide (m+n+p) items in group of m,n,pis first to divide the set in groups of m and then each of these groups divide by n followed by divide by p.\nNow of ways to divide (m+n+p) items in groups of (n+p) is \n==> (n+m...
[ 2, 2, 1, 1 ]
[]
[]
[ "combinatorics", "python" ]
stackoverflow_0008723208_combinatorics_python.txt
Q: TypeError: 'int' object is not iterable I am trying to have a program look inside multiple lists to see if there are multiple integers in those lists. I received an answer on a previous question I asked to accomplish that task. However a problem arose with that answer and I can not figure out what it is. Here is ...
TypeError: 'int' object is not iterable
I am trying to have a program look inside multiple lists to see if there are multiple integers in those lists. I received an answer on a previous question I asked to accomplish that task. However a problem arose with that answer and I can not figure out what it is. Here is the code: def all_num_in_list(d, numbers): ...
[ "The first parameter to all_num_in_any_list, [2,3,4,5,6,7,8,9], is a single list, not a \nlist of lists. When you iterate through it, d is 1, then d is 2, and so forth. When\nyou pass d as the first parameter to all_num_in_list, it is trying to treat it as a list even though it is an integer.\n", "Here is your ma...
[ 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008721600_python.txt
Q: PyMongo and toArray() method I need to make some benchmarks on a small database (64MB) and I need to figure out what is the smartest way to fetch whole Mongo collection into python object with PyMongo? In JavaScript, there is toArray() method but I cannot find anything similar in python. Thanks in advance! A: Ha...
PyMongo and toArray() method
I need to make some benchmarks on a small database (64MB) and I need to figure out what is the smartest way to fetch whole Mongo collection into python object with PyMongo? In JavaScript, there is toArray() method but I cannot find anything similar in python. Thanks in advance!
[ "Have you tried?\nresult = list(db.collection.find())\n\n" ]
[ 17 ]
[]
[]
[ "database", "document_oriented_db", "mongodb", "pymongo", "python" ]
stackoverflow_0008723613_database_document_oriented_db_mongodb_pymongo_python.txt
Q: A django model that subclasses an abc, gives a metaclass conflict I have a following model and abstract base class import abc from django.db import models class AbstractBase(): __metaclass__ = abc.ABCMeta @abc.abstractmethod def my_method(self): return class MyModel(models.Model, AbstractBas...
A django model that subclasses an abc, gives a metaclass conflict
I have a following model and abstract base class import abc from django.db import models class AbstractBase(): __metaclass__ = abc.ABCMeta @abc.abstractmethod def my_method(self): return class MyModel(models.Model, AbstractBase): @abc.abstractmethod def my_method(self): return 1...
[ "Apart from creating a new metaclass that inherits from both ABCMeta and ModelBase, or making ABCMeta inherit from ModelBase, there isn't much you can do.\nHowever, possibly a different registration pattern might be appropriate? Maybe something like contrib.admin.autodiscover? Or a class decorator? Or a loop at the...
[ 2 ]
[]
[]
[ "abc", "conflict", "django", "metaclass", "python" ]
stackoverflow_0008723639_abc_conflict_django_metaclass_python.txt
Q: Python keep scrollbar at end point So when assigning Scrollbars to Listboxes, if you later on insert new lines, the scroll thumb does not "update". I want the scroll thumb to be set to the bottom of my vertical scrollbar everytime i insert new lines into my listbox. I've tried: mylistbox.yview = command("moveto", ...
Python keep scrollbar at end point
So when assigning Scrollbars to Listboxes, if you later on insert new lines, the scroll thumb does not "update". I want the scroll thumb to be set to the bottom of my vertical scrollbar everytime i insert new lines into my listbox. I've tried: mylistbox.yview = command("moveto", 1) mylistbox.yview = ('moveto', 1) mylis...
[ "see 'see'\nhttp://groups.google.com/group/comp.lang.python/msg/32d00fb2ad61cab3\n" ]
[ -1 ]
[]
[]
[ "listbox", "python", "scrollbar", "tkinter" ]
stackoverflow_0008720174_listbox_python_scrollbar_tkinter.txt
Q: python: elegant way to deal with lock on a variable? I have code that looks like something like this: def startSearching(self): self.searchingLock.acquire() searching = self.searching if self.searching: self.searchingLock.release() self.logger.error("Already searching!") return ...
python: elegant way to deal with lock on a variable?
I have code that looks like something like this: def startSearching(self): self.searchingLock.acquire() searching = self.searching if self.searching: self.searchingLock.release() self.logger.error("Already searching!") return False self.searching = True self.searchingLock.re...
[ "Maybe you need to separate this logic like:\ndef initSearch(self):\n with self.searchingLock:\n if self.searching : raise SearchingError('AlreadySearching')\n self.searching = True\ndef startSearching(self):\n try: self.initSearch()\n except SearchingError as error :\n self.logger.err...
[ 6, 4, 1 ]
[]
[]
[ "locking", "multithreading", "python", "thread_safety" ]
stackoverflow_0003462566_locking_multithreading_python_thread_safety.txt
Q: argparse - Why the code is executed without being called? I'm having a bit of trouble understanding how python argparse works. My script has three positional arguments that don't take parameters: make, compile and clean. I've done it through subparsers like the documentation says, but my code keeps running without...
argparse - Why the code is executed without being called?
I'm having a bit of trouble understanding how python argparse works. My script has three positional arguments that don't take parameters: make, compile and clean. I've done it through subparsers like the documentation says, but my code keeps running without arguments or even with arguments it doesn't call the right fun...
[ "That's because you're calling make yourself, here:\nparser_make.set_defaults(func=lang.make())\n\nIn particullar, this part:\nlang.make()\n\nAs a result, the func arg is set to the return value of make.\nInstead, you probably want to pass the method as argument, without calling it:\nparser_make.set_defaults(func=l...
[ 8 ]
[]
[]
[ "argparse", "arguments", "class", "python" ]
stackoverflow_0008724262_argparse_arguments_class_python.txt
Q: How to allow UltimateListCtrl to rearrange itself, wxpython how can I allow a UltimateListCtrl, to be able to reorder/rearrange itself with the users input? The following shows the ability however i am not sure how it can be done. DATA = { 0 : ("3", "3", "1"), 1 : ("2", "1", "2"), 2 : ("1", "2", "3...
How to allow UltimateListCtrl to rearrange itself, wxpython
how can I allow a UltimateListCtrl, to be able to reorder/rearrange itself with the users input? The following shows the ability however i am not sure how it can be done. DATA = { 0 : ("3", "3", "1"), 1 : ("2", "1", "2"), 2 : ("1", "2", "3") } import wx import wx.lib.mixins.listctrl as listmix from ...
[ "Maybe you are asking for something like this:\nclass MyList(ULC.UltimateListCtrl, listmix.ColumnSorterMixin):\n def __init__(self, parent, data):\n ULC.UltimateListCtrl.__init__(self, parent, agwStyle=ULC.ULC_REPORT | ULC.ULC_HAS_VARIABLE_ROW_HEIGHT)\n self.data = data\n self.IDoMyself()\n ...
[ 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0008720957_python_wxpython_wxwidgets.txt
Q: Linking segments of edges I have written a canny edge detection algorithm for a project. I want to know is there any method to link the broken segments of an edge, since i am getting a single edge as a conglomeration of a few segments. I am getting around 100 segments, which i am sure can be decreased with some in...
Linking segments of edges
I have written a canny edge detection algorithm for a project. I want to know is there any method to link the broken segments of an edge, since i am getting a single edge as a conglomeration of a few segments. I am getting around 100 segments, which i am sure can be decreased with some intelligence. Please help.
[ "You can use a method named dynamic programming. A very good intro on this can be found on chapter 6 of Sonka's digital image processing book\n" ]
[ 0 ]
[]
[]
[ "edge_detection", "image_processing", "python" ]
stackoverflow_0008699665_edge_detection_image_processing_python.txt
Q: How to run a python script from another python script and get the returned status code? I'm relatively new to both Python and bash. However, I am finding Python much more intuitive and easier than bash. I have a few bash scripts I have managed to cobble together, but I would like to replace them with Python script...
How to run a python script from another python script and get the returned status code?
I'm relatively new to both Python and bash. However, I am finding Python much more intuitive and easier than bash. I have a few bash scripts I have managed to cobble together, but I would like to replace them with Python scripts - for ease of maintenance etc. The bash scripts essentially run python scripts, check the r...
[ "Using subprocess module\nmaster.py\nimport subprocess\nretcode = subprocess.call([\"/usr/bin/python\", \"/path/to/test.py\"])\nprint \"Return code of test.py is \", retcode\n\n", "I would suggest you to look at the subprocess module in python. You can start another process using it, manipulate its streams and ge...
[ 6, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0008724557_bash_python.txt
Q: Deploying Python Qt application cross-platform: Win, OSX, Linux We are designing open source UI controller application for Plone CMS. The application itself would be just simple start/stop dialog window for Plone daemon process, mainly aimed for Windows users. However we are hoping to use the same app for OSX and ...
Deploying Python Qt application cross-platform: Win, OSX, Linux
We are designing open source UI controller application for Plone CMS. The application itself would be just simple start/stop dialog window for Plone daemon process, mainly aimed for Windows users. However we are hoping to use the same app for OSX and Linux. We can create the code for Python Qt application, but we feel ...
[ "PyInstaller is a nice one to create executables and it comes with full PyQt support. It says it can create executables for Windows, OsX and Linux but I've never used it for anything other than Windows. For Windows, it was quite painless and easy.\n", "This doesn't address the packaging/deployment component of yo...
[ 3, 1 ]
[]
[]
[ "linux", "macos", "python", "qt", "windows" ]
stackoverflow_0008016370_linux_macos_python_qt_windows.txt
Q: subscription to redis channel does not keep alive I have one client subscribe to one channel. After a certain period of time about 10 minutes idle, the client can not receive any message, but the publish command still returns 1. I've tried redis-py and servicestack.redis clients. The only difference is seems th...
subscription to redis channel does not keep alive
I have one client subscribe to one channel. After a certain period of time about 10 minutes idle, the client can not receive any message, but the publish command still returns 1. I've tried redis-py and servicestack.redis clients. The only difference is seems the idle period can be little longer when use servicestac...
[ "I had similar issues with an older version of Redis that was fixed by the latest version.\nAs an alternative you could try adding a separate thread that sends a \"PING\" command once in a while to keep the connection up.\n" ]
[ 0 ]
[]
[]
[ "c#", "python", "redis" ]
stackoverflow_0008678349_c#_python_redis.txt
Q: Python functional programming There is my problem: Suppose we have 3 functions : f, g, h and the following code y = f(x) a = g(y) b = h(y) I want to do this on a single line, like : a,b = g(f(x)),h(f(x)) but this is not efficient if f is very slow ( and doesn't cache it's result) I have one solution with a gene...
Python functional programming
There is my problem: Suppose we have 3 functions : f, g, h and the following code y = f(x) a = g(y) b = h(y) I want to do this on a single line, like : a,b = g(f(x)),h(f(x)) but this is not efficient if f is very slow ( and doesn't cache it's result) I have one solution with a generator: a,b = ((g(y),h(y)) for y in ...
[ "Use a lambda. Ta-dah!:\n>>> def f(a):\n... return a+1\n... \n>>> def g(a):\n... return a*2\n... \n>>> def h(a):\n... return a*3\n... \n>>> (lambda x: (g(x),h(x)))(1)\n(2, 3)\n>>> (lambda x: (g(x),h(x)))(f(1))\n(4, 6)\n>>> a,b=(lambda x: (g(x),h(x)))(f(1))\n>>> a\n4\n>>> b\n6\n\n", "I'm probably missi...
[ 6, 3, 1 ]
[]
[]
[ "function", "functional_programming", "python" ]
stackoverflow_0008724539_function_functional_programming_python.txt
Q: Choosing where to install Django project I know that django-admin.py startproject whateveryourfolderis would install your project But this create the project within the "django/bin" folder. If I want to create the project somewhere eles (c:/whatever. What is the correct command? Thanks. A: I see what your issu...
Choosing where to install Django project
I know that django-admin.py startproject whateveryourfolderis would install your project But this create the project within the "django/bin" folder. If I want to create the project somewhere eles (c:/whatever. What is the correct command? Thanks.
[ "I see what your issue might be here.\nIn order to use django within your system, you must navigate to the bin directory to execute the django-admin command.\nYou do not need to do this. You must setup an environment path pointing to your site-packages folder in your python directory.\nYou may also add a path point...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008724658_django_python.txt
Q: How do I get a eval statement to run the numbers as floats I have created a GUI calculator (a screen shot included) and when a button is pressed it adds text to the textctrl so that the equation is displayed to the user. when the user presses enter it takes that text and runs it usesing eval then prints using SetV...
How do I get a eval statement to run the numbers as floats
I have created a GUI calculator (a screen shot included) and when a button is pressed it adds text to the textctrl so that the equation is displayed to the user. when the user presses enter it takes that text and runs it usesing eval then prints using SetValue but if i run a problem in the texctrl like 5/6 it comes out...
[ "Place at the top of your file:\nfrom __future__ import division\n\nThis redefines the meaning of / so it is always floating point division. (Integer division is //.)\nFor more information on what this means, see PEP 238.\n", "Just add on the start of your program, the following line:\nfrom __future__ import divi...
[ 5, 2, 1 ]
[]
[]
[ "eval", "floating_point", "python", "user_interface", "wxpython" ]
stackoverflow_0008721818_eval_floating_point_python_user_interface_wxpython.txt
Q: Adding dictionaries recursively in Python I have the following two functions which take two dictionaries and recursively add their values. def recursive_dict_sum_helper(v1, d2, k): try: v2 = d2[k] except KeyError: return v1 #problem is here if key not found it just return value but what about rest of the k...
Adding dictionaries recursively in Python
I have the following two functions which take two dictionaries and recursively add their values. def recursive_dict_sum_helper(v1, d2, k): try: v2 = d2[k] except KeyError: return v1 #problem is here if key not found it just return value but what about rest of the keys which is in d2?? if not v1: return v2 ...
[ "If I understand right what you want to do, all of it could be achieved with the following code:\ndef dict_sum(d1, d2):\n if d1 is None: return d2\n if d2 is None: return d1\n if isinstance(d1, list) and isinstance(d2, list):\n return list(set(d1 + d2))\n try:\n return d1 + d2\n except ...
[ 3, 3 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0008725060_dictionary_python.txt
Q: How to find whether a text contains zero? I want to check in a piece of text whether that text contains "0" or not. I cannot use string.__contains(" 0") as this is bad coding, or if I can use this, I do not have enough points to back to my senior, that this is the only way. Or if you can let me know some points? T...
How to find whether a text contains zero?
I want to check in a piece of text whether that text contains "0" or not. I cannot use string.__contains(" 0") as this is bad coding, or if I can use this, I do not have enough points to back to my senior, that this is the only way. Or if you can let me know some points? The other way we found out is to extract from ea...
[ "At first, I thought you could just use in:\nif \"0\" in myString:\n print \"%s contains 0\" % myString\n\nHowever, this doesn't seem to be what you want to do, when re-reading your question. This will detect the 0 in a row such as:\nabc: 200\n\nWhich I guess you don't want to do. You need to use something a bit m...
[ 3, 2, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008725156_python.txt
Q: Difference between Python and Javascript in evaluating a regular expression First of all, this is not a dupe of this question. In Javascript this expression seems to be evaluated correctly: \\/(omniture|mbox|hbx|omniunih)(.*)? If I pass it to Python re module, bad things happen. In fact, the following returns an ...
Difference between Python and Javascript in evaluating a regular expression
First of all, this is not a dupe of this question. In Javascript this expression seems to be evaluated correctly: \\/(omniture|mbox|hbx|omniunih)(.*)? If I pass it to Python re module, bad things happen. In fact, the following returns an error: import re re.compile (u'\\/(omniture|mbox|hbx|omniunih)(.*)?') In [101]: ...
[ "The question mark is superfluous, as you reflect yourself, it doesn't really make any sense, remove it and you should be in business.\n", "Your regular expression does not make sense, the ? at the end of your string is not needed and will in fact never match anything. In addition I suggest you use r'' to make yo...
[ 6, 2 ]
[]
[]
[ "javascript", "python", "regex" ]
stackoverflow_0008725401_javascript_python_regex.txt
Q: Change case of first letter in every cell in spreadsheet I have many cells which I'd like to convert such that the first letter in every cell is capitalized. E.g. cook, chef, fireman becomes Cook, Chef, Fireman. I have the spreadsheet in OpenOffice.org, but it seems to only have options for "all uppercase" or "al...
Change case of first letter in every cell in spreadsheet
I have many cells which I'd like to convert such that the first letter in every cell is capitalized. E.g. cook, chef, fireman becomes Cook, Chef, Fireman. I have the spreadsheet in OpenOffice.org, but it seems to only have options for "all uppercase" or "all lowercase". I can edit it in OpenOffice.org or export to a C...
[ "I happen to do this task. You have to install Spreadsheet::ParseExcel and Spreadsheet::WriteExcel modules.\nuse strict;\nuse warnings;\n\nuse Spreadsheet::ParseExcel::SaveParser;\n\nmy $parser = Spreadsheet::ParseExcel::SaveParser->new();\nmy $workbook = $parser->Parse('Book1.xls');\n\nif ( !defined $workbook ) ...
[ 8, 7, 6, 3, 3, 2, 2, 1, 1, 1 ]
[]
[]
[ "bash", "csv", "openoffice_calc", "perl", "python" ]
stackoverflow_0008720589_bash_csv_openoffice_calc_perl_python.txt
Q: TemplateSyntaxError with django.contrib.auth.views.login Getting started with Django 1.3 here. Loving the system so far, but struggling on stuff. Also loving stackoverflow for the Q&As. :) I'm currently working on getting logins & registrations working and I'm getting a TemplateSyntaxError with my login view. Te...
TemplateSyntaxError with django.contrib.auth.views.login
Getting started with Django 1.3 here. Loving the system so far, but struggling on stuff. Also loving stackoverflow for the Q&As. :) I'm currently working on getting logins & registrations working and I'm getting a TemplateSyntaxError with my login view. Template error In template /templates/login.html, error at line ...
[ "Like demalexx wrote the problem is in userProfile/views.py. According to error message it looks like your context dictionary is invalid. Key 'form' hasn`t got its value.\n", "The problem is not in your template but rather in your views.py file, line 47:\nreturn render_to_response('login.html', {'form': })\n\nThe...
[ 0, 0 ]
[]
[]
[ "django", "django_authentication", "django_templates", "python" ]
stackoverflow_0008721137_django_django_authentication_django_templates_python.txt
Q: python po box split for auth.net Authorize.net ( or the banks ) will not validate an address unless for a PO Box address, unless its in the form of 123 P.O. Box. Most people use P.O Box 123. There are loads of variations PO Box formats and I need an algorithm that puts the number in front of the PO Box Any suggest...
python po box split for auth.net
Authorize.net ( or the banks ) will not validate an address unless for a PO Box address, unless its in the form of 123 P.O. Box. Most people use P.O Box 123. There are loads of variations PO Box formats and I need an algorithm that puts the number in front of the PO Box Any suggests would be helpful.
[ "The regular expression '(P[\\.\\s]*O[\\.\\s]*Box)?\\s*(\\d+)\\s*(P[\\.\\s]*O[\\.\\s]*Box)?' will match almost anything that looks like a PO Box (but will match a number only address too). The replacement '\\2 PO Box' would normalize the data.\nSo the code would be something like this\n\nimport re\nrgx = re.compile...
[ 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008370147_python_regex.txt
Q: python, COM and multithreading issue I'm trying to take a look at IE's DOM from a separate thread that dispatched IE, and for some properties I'm getting a "no such interface supported" error. I managed to reduce the problem to this script: import threading, time import pythoncom from win32com.client import Dispa...
python, COM and multithreading issue
I'm trying to take a look at IE's DOM from a separate thread that dispatched IE, and for some properties I'm getting a "no such interface supported" error. I managed to reduce the problem to this script: import threading, time import pythoncom from win32com.client import Dispatch, gencache gencache.EnsureModule('{3050...
[ "The correct answer is to marshal stuff by hand. That's not a workaround it is what you are supposed to do here. You shouldn't have to use apartment threading though.\nYou initialised as multithreaded apartment - that tells COM that it can call your interfaces on any thread. It does not allow you to call other inte...
[ 1 ]
[]
[]
[ "automation", "com", "internet_explorer", "python" ]
stackoverflow_0008712806_automation_com_internet_explorer_python.txt
Q: how to deal with Nasty unparallel tag in HTML? I have few thousands HTML sources to read. It is from forum which started from 2004. My basic idea is to read through page by change the page number in Python script. All thing I need is like this lot of other tag from beginning <div id="posts"> lot of stuff betwe...
how to deal with Nasty unparallel tag in HTML?
I have few thousands HTML sources to read. It is from forum which started from 2004. My basic idea is to read through page by change the page number in Python script. All thing I need is like this lot of other tag from beginning <div id="posts"> lot of stuff between </div> lot of other tag till ending I use beau...
[ "oh dear.\nEasiest way would be to fix the page so all end tags have a start tag....\nBasically the mark up is not correct, browsers have all sorts of ifs and buts to cope with this and other fun ones like\n<Tag1><Tag2></Tag1></Tag2>\n\nto cope with the bad old days where html wasn't valid xml.\nIt's do able in cod...
[ 2 ]
[]
[]
[ "html", "python" ]
stackoverflow_0008726069_html_python.txt
Q: Django Chart using Highcharts I am following the highchart demos but I am do not understand how they are importing using the following line: from ..charts import Chart, PivotChart Please tell me the meaning of the above line. A: This is relative import PEP 0328 http://docs.python.org/tutorial/modules.html#intr...
Django Chart using Highcharts
I am following the highchart demos but I am do not understand how they are importing using the following line: from ..charts import Chart, PivotChart Please tell me the meaning of the above line.
[ "This is relative import \nPEP 0328\nhttp://docs.python.org/tutorial/modules.html#intra-package-references\n", "These are explicit relative imports which started with Python 2.5 >. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import.\n" ]
[ 2, 1 ]
[]
[]
[ "django", "highcharts", "python" ]
stackoverflow_0008726012_django_highcharts_python.txt
Q: Passing in arguments to a called script I'm running nosetests on my project with --with-snort for Growl notifications. The problem is that I have some lib files that I put on the path, so I have a custom python script at bin/python. I have no issues running nose via my bin/python by doing which nosetests and usi...
Passing in arguments to a called script
I'm running nosetests on my project with --with-snort for Growl notifications. The problem is that I have some lib files that I put on the path, so I have a custom python script at bin/python. I have no issues running nose via my bin/python by doing which nosetests and using that executable - bin/python /usr/local/bi...
[ "What makes you think that flags will go to bin/python? Have you tested this? If I write a simple program to test this out:\nimport sys\nprint sys.argv[1:]\n\nI get the following ouput from these example calls (assuming I have saved this in a file called test.py)\npython test.py prints []\npython test.py 5 prints [...
[ 3 ]
[]
[]
[ "nose", "nosetests", "python", "shell" ]
stackoverflow_0008726440_nose_nosetests_python_shell.txt
Q: Is there any way to get a REPL in pydev? I would like to be able to drop to the python REPL from the debugger -- if this is not possible is there an easier way to evaluate python expressions in the context of the current breakpoint other than manually adding them all as watch expressions? A: There is a dedicate...
Is there any way to get a REPL in pydev?
I would like to be able to drop to the python REPL from the debugger -- if this is not possible is there an easier way to evaluate python expressions in the context of the current breakpoint other than manually adding them all as watch expressions?
[ "There is a dedicated Pydev Console available by clicking on the \"New console\" dropdown in the console view.\nSee http://pydev.sourceforge.net/console.html\n", "I don't use pydev, but to drop to python's interactive REPL from code:\nimport code\ncode.interact(local=locals())\n\nTo drop to python's debugger from...
[ 6, 3, 2 ]
[]
[]
[ "ide", "pydev", "python", "read_eval_print_loop" ]
stackoverflow_0000241995_ide_pydev_python_read_eval_print_loop.txt
Q: How do I start a subprocess which runs in the background until it is told to terminate gracefully? From within my python script, I want to start another python script which will run in the background waiting for the instruction to terminate. Host Python script (H1) starts subprocess P1. P1 performs some short li...
How do I start a subprocess which runs in the background until it is told to terminate gracefully?
From within my python script, I want to start another python script which will run in the background waiting for the instruction to terminate. Host Python script (H1) starts subprocess P1. P1 performs some short lived work & returns a sentinel to indicate that it is now going to sleep awaiting instructions to termina...
[ "Yes, start the process with :\np=subprocess.Popen([list for the script to execute], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)\n\nYou can then read from p.stdout and p.stderr to watch for your sentinel and write to p.stdin to send messages to the child process. If you are running on a ...
[ 2, 1 ]
[]
[]
[ "concurrency", "python" ]
stackoverflow_0008710617_concurrency_python.txt
Q: Python: Email content configuration file I would like to be able to have a configuration file with an assortment of content to be mailed out. Each email would need to contain a subject and a body, with new lines. For example: [Message_One] Subject: Hey there Body: This is a test How are you? Blah blah ...
Python: Email content configuration file
I would like to be able to have a configuration file with an assortment of content to be mailed out. Each email would need to contain a subject and a body, with new lines. For example: [Message_One] Subject: Hey there Body: This is a test How are you? Blah blah blah Sincerely, SOS [Message_Two...
[ "Maybe like this:\nfrom ConfigParser import ConfigParser\nimport random\n\nconf = ConfigParser()\nconf.read('test.conf')\n\nmail = random.choice(conf.sections())\nprint \"mail: %s\" % mail\nprint \"subject: %s\" % conf.get(mail, 'subject')\nprint \"body: %s\" % conf.get(mail, 'body')\n\nIt's just a matter of select...
[ 3, 1 ]
[]
[]
[ "ini", "python", "random" ]
stackoverflow_0008726281_ini_python_random.txt
Q: How to get the diff between two JSONs? Is there any library/script to compare two JSONs objects and show the diff between them? Thanks EDIT: I want to do that using python OR jquery/javascript A: comparing the two JSONs is very simple (in all languages) - you just compare the strings. showing the diffs is a li...
How to get the diff between two JSONs?
Is there any library/script to compare two JSONs objects and show the diff between them? Thanks EDIT: I want to do that using python OR jquery/javascript
[ "comparing the two JSONs is very simple (in all languages) - you just compare the strings. \n\nshowing the diffs is a little more complicated - i guess that one need to deserialize the JSONs and compare the objects.\n" ]
[ 0 ]
[]
[]
[ "javascript", "json", "python" ]
stackoverflow_0008724172_javascript_json_python.txt
Q: What are good ways to make my Python code run first time? I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this? A: If you're having problems with synta...
What are good ways to make my Python code run first time?
I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?
[ "If you're having problems with syntax, you could try an editor with syntax highlighting. Until you get the feel for a language, simple errors won't just pop out at you.\nThe simplest form of debugging is just to insert some print statements. A more advanced (and extensible) way to do this would be to use the loggi...
[ 36, 30, 15, 10, 10, 7, 7, 6, 5, 4, 4, 1, 1, 1, 0, 0 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0000299704_debugging_python.txt
Q: Difference between .pack and .configure for widgets in TkInter? I am currently studying a text to try and teach myself more about TkInter as I'm trying to improve my Python 3 programming. The text can be found here, if necessary: http://www.ferg.org/thinking_in_tkinter/all_programs.html In the section labelled "tt...
Difference between .pack and .configure for widgets in TkInter?
I am currently studying a text to try and teach myself more about TkInter as I'm trying to improve my Python 3 programming. The text can be found here, if necessary: http://www.ferg.org/thinking_in_tkinter/all_programs.html In the section labelled "tt040.py" there is an example code, part of it is: self.button1 = B...
[ "Tkinter objects attribute are not handled through python attribute mechanism (ie you can not do self.button1.text = \"hello\"). Instead, tkinter provide two ways to alter this attribute:\n\nuse the object as a dictionnary: self.button1[\"text\"] = \"hello\"\nuse the config method with named argument: self.button1...
[ 4, 2 ]
[]
[]
[ "methods", "python", "tkinter" ]
stackoverflow_0008707039_methods_python_tkinter.txt
Q: MongoDB: how to get db.stats() from API I'm trying to get results of db.stats() mongo shell command in my python code (for monitoring purposes). But unlike for example serverStatus I can't do db.command('stats'). I was not able to find any API equivalent in mongodb docs. I've also tried variations with db.$cmd but...
MongoDB: how to get db.stats() from API
I'm trying to get results of db.stats() mongo shell command in my python code (for monitoring purposes). But unlike for example serverStatus I can't do db.command('stats'). I was not able to find any API equivalent in mongodb docs. I've also tried variations with db.$cmd but none of that worked. So, Small question: ho...
[ "The Javascript shell's stats command helper actually invokes a command named dbstats, which you can run from PyMongo using the Database.command method. The easiest way to find out what command a shell helper will run is to invoke the shell helper without parentheses -- this will print out the Javascript code it ru...
[ 12 ]
[]
[]
[ "mongodb", "pymongo", "python", "python_2.7" ]
stackoverflow_0008726152_mongodb_pymongo_python_python_2.7.txt
Q: Python doesn't show anything It's my first Python program and my first excercise is that I just need to swap places in a tuple: stamboom = [("Frans","Eefje"), ("Klaar","Eefje"), ("Eefje","Mattho"), ("Eefje","Salammbo"), ("Gustave","Mattho"), ("Gustave","Salambo")] Is the tuple, and I need to swap Fran...
Python doesn't show anything
It's my first Python program and my first excercise is that I just need to swap places in a tuple: stamboom = [("Frans","Eefje"), ("Klaar","Eefje"), ("Eefje","Mattho"), ("Eefje","Salammbo"), ("Gustave","Mattho"), ("Gustave","Salambo")] Is the tuple, and I need to swap Frans with Eefje (those are just names...
[ "To show something you have to print it.\nChange the last line to:\nprint map(switchplace,range(0,len(stamboom)))\n\n", "That was very complicated code for a simple task. Check out something called list comprehension.\nChange the code to:\nstamboom = [(\"Frans\",\"Eefje\"), (\"Klaar\",\"Eefje\"), (\"Eefje\",\"Mat...
[ 8, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008727304_python.txt
Q: Py2exe and PyGTK Entry Point Not Found i have created a pygtk example from http://www.py2exe.org/index.cgi/Py2exeAndPyGTK and when i start the .exe file it geves me an error message: The procedure entry point gdk_win32_window_get_impl_hwnd could not be located in the dynamic link library libgdk-win32-2.0-0.dll. t...
Py2exe and PyGTK Entry Point Not Found
i have created a pygtk example from http://www.py2exe.org/index.cgi/Py2exeAndPyGTK and when i start the .exe file it geves me an error message: The procedure entry point gdk_win32_window_get_impl_hwnd could not be located in the dynamic link library libgdk-win32-2.0-0.dll. the app is then running, but it is a ugly err...
[ "The problem is that you're mixing the pygtk-all-in-one installer and gtk2-runtime. You only need one of them not both.\nThe problem probably comes from loading the win32 theme, it'll work fine but look ugly.\nThe solution is to stop using gtk2-runtime.\n" ]
[ 2 ]
[]
[]
[ "dll", "gtk", "py2exe", "pygtk", "python" ]
stackoverflow_0008727301_dll_gtk_py2exe_pygtk_python.txt
Q: Replacing built-in types with more complex types. Python I want to create a replacement class of the built-in type set that can be constructed exactly like set. Inheritance must not be used because some functions are removed to trigger method not found exceptions. This class is also used to find places where there...
Replacing built-in types with more complex types. Python
I want to create a replacement class of the built-in type set that can be constructed exactly like set. Inheritance must not be used because some functions are removed to trigger method not found exceptions. This class is also used to find places where there might be implicit type conversions of the built-in python col...
[ "Define exactly...\nThe best way to create a set-like class is to derive from collections.Set. You'll need to implement __len__, __iter__ and __contains__.\nTo be able to add element, derive from collections.MutableSet instead and implement add and discard.\n", "Inherit from set:\n>>> class SetFacade(set):\n... ...
[ 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008727626_python.txt
Q: How to invoke Jython interpreter from python source code in Windows Stated here, one can invoke Jython in source code in Unix platforms. I've installed Jython and put the directory in PATH in windows. How could I set this up to invoke Jython from .py code automatically? Thanks. Make the example more specific and ...
How to invoke Jython interpreter from python source code in Windows
Stated here, one can invoke Jython in source code in Unix platforms. I've installed Jython and put the directory in PATH in windows. How could I set this up to invoke Jython from .py code automatically? Thanks. Make the example more specific and clear: #!/usr/bin/env jython import sys sys.path.append("./package.jar") ...
[ "An ImportError is already a Python error, so it looks like jython is working. You need, however, to set up the path.\nIf xxx stands for one of your Python modules, set up sys.path to contain the appropriate directory before importing it.\nIf xxx stands for one of your Java modules, set up the Java Classpath to con...
[ 2, 0 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0008093122_jython_python.txt
Q: Converting dict object to string in Django/Jinja2 template If you use Django or Jinja2, you've probably ran into this problem before. I have a JSON string that looks like this: { "data":{ "name":"parent", "children":[ { "name":"child_a", "fav_colors":[ "blue", "r...
Converting dict object to string in Django/Jinja2 template
If you use Django or Jinja2, you've probably ran into this problem before. I have a JSON string that looks like this: { "data":{ "name":"parent", "children":[ { "name":"child_a", "fav_colors":[ "blue", "red" ] }, { "name":"child_b", ...
[ "You need to convert the fav_colors list back to JSON. Probably the easiest way to do this would be with a quick template filter:\n@register.filter\ndef to_json(value):\n return mark_safe(simplejson.dumps(value))\n\nSo now you could do \n<option value=\"{{ c.fav_colors|to_json }}\">\n\n" ]
[ 15 ]
[]
[]
[ "django", "jinja2", "python" ]
stackoverflow_0008727349_django_jinja2_python.txt
Q: PySide methods signature in Eclipse/WingIDE/PyCharm? Is there any way to have the signature of the methods of PySide classes in Eclipse, WingIDE, PyCharm or any Python IDE? Currently, it auto-completes the classes and method names, but not the parameters of the methods. All functions are detected as functions with...
PySide methods signature in Eclipse/WingIDE/PyCharm?
Is there any way to have the signature of the methods of PySide classes in Eclipse, WingIDE, PyCharm or any Python IDE? Currently, it auto-completes the classes and method names, but not the parameters of the methods. All functions are detected as functions without parameters. I know it's a Python binding of a C++ fra...
[ "I use PyDev (Eclipse plugin) and it works like a charm, also with function signatures.\nEDIT:\nI'm not 100% sure with C++ extensions, but it should work well if there's a Python wrapper for it. With pure C++ extensions there might be problems, but actually I haven't tried it.\n", "Try running help(some-qt-method...
[ 0, 0 ]
[]
[]
[ "autocomplete", "eclipse", "pycharm", "pyside", "python" ]
stackoverflow_0007567572_autocomplete_eclipse_pycharm_pyside_python.txt
Q: Retrieving data from rows based on condition I have a tab delimited file of 10 columns and 200 rows: a b 1 0 1 1 0 1 0 0 c d 0 0 0 1 1 1 1 0 e f 1 0 1 0 0 1 0 0 and so on, the condition to extract data is, "if from column 3 to last column, the count of 0 is more than 4, it should not take...
Retrieving data from rows based on condition
I have a tab delimited file of 10 columns and 200 rows: a b 1 0 1 1 0 1 0 0 c d 0 0 0 1 1 1 1 0 e f 1 0 1 0 0 1 0 0 and so on, the condition to extract data is, "if from column 3 to last column, the count of 0 is more than 4, it should not take that row into account" the answer for above set w...
[ "import csv\n\nfin = open(\"text.txt\",\"rb\")\nr = csv.reader(fin,delimiter=\"\\t\")\nfor line in r:\n if (sum(1 if x=='0' else 0 for x in line[3:]) < 4):\n print line\nfin.close()\n\n", "If awk is acceptable, try:\nawk '{\n c = x\n for (i = f - 1; ++i <= NF;)\n $i == 0 && c++\n }\nc > l' l=4 f=3...
[ 2, 1, 1, 1, 1, 1, 1, 1, 1 ]
[]
[]
[ "bash", "perl", "python", "shell" ]
stackoverflow_0008727674_bash_perl_python_shell.txt
Q: Python - how can I change default path when installing modules? I'm trying to install a Python Module by running a Windows installer (an EXE file). The Problem is that the default python folder and the defualt Installation Library are set To disc D:\ and are grayed out (meaning I can't change it). It might be fine...
Python - how can I change default path when installing modules?
I'm trying to install a Python Module by running a Windows installer (an EXE file). The Problem is that the default python folder and the defualt Installation Library are set To disc D:\ and are grayed out (meaning I can't change it). It might be fine is some places, but in my computer, D is the DVD drive, meaning that...
[ "It's not \"default folder\", and there's a reason there's \"found in registry\" next to the version. You need to re-register the Python installation if you've moved it, either by installing it again (without removing) in the same folder, or changing the directory saved in registry (HKCU\\Software\\Python\\PythonCo...
[ 7, 1 ]
[]
[]
[ "installation", "module", "python", "windows" ]
stackoverflow_0008726822_installation_module_python_windows.txt
Q: Skip URL if timeout I have a list of URL's I am using the following to retrieve their contents: for url in url_list: req = urllib2.Request(url) resp = urllib2.urlopen(req, timeout=5) resp_page = resp.read() print resp_page When there is a timeout, the program just crashes. I just want to read the ...
Skip URL if timeout
I have a list of URL's I am using the following to retrieve their contents: for url in url_list: req = urllib2.Request(url) resp = urllib2.urlopen(req, timeout=5) resp_page = resp.read() print resp_page When there is a timeout, the program just crashes. I just want to read the next URL if there is a so...
[ "Although there already is an answer, I'd like to point out that URLlib2 might not be the sole responsible with this behavior.\nAs pointed out here (and as it also seems based on the problem description), the exception may belong to the socket library.\nIn that case just add another except:\nimport socket\n\ntry:\n...
[ 7, 1, 1 ]
[]
[]
[ "exception_handling", "python", "sockets", "timeout", "urllib2" ]
stackoverflow_0008072597_exception_handling_python_sockets_timeout_urllib2.txt
Q: How to access inner structures in R? I am unable to explain this without python, suppose: a=((((()),(),())*3,((((())))))*2) now how can I get a[0][2] in R with similar structure? I am a bit lost how these x[2,] etc mean in R -- here I am trying by x[2,] to get every second column and keep the structure but R mix...
How to access inner structures in R?
I am unable to explain this without python, suppose: a=((((()),(),())*3,((((())))))*2) now how can I get a[0][2] in R with similar structure? I am a bit lost how these x[2,] etc mean in R -- here I am trying by x[2,] to get every second column and keep the structure but R mixes it so now trying to understand how to p...
[ "Take a little time to read up on the R objects of type \"matrix,\" \"dataframe,\" and \"list\" . If you've got a nice, well-behaved :-) collection of values in an N-rank tensor (to use the math terminology), then each element is found by mydata[i,j,k,l] for a 4-th rank. Typically we call that 4-dimensional matr...
[ 3 ]
[]
[]
[ "python", "r" ]
stackoverflow_0008728518_python_r.txt
Q: Detect if external call takes to long time in Python In my Python script I make an external call using subprocess.Popen(). If the call hasn't returned within x seconds I need to send an email indicating that something is wrong. How can I put a time limit on the execution of the external call? Note that I am not in...
Detect if external call takes to long time in Python
In my Python script I make an external call using subprocess.Popen(). If the call hasn't returned within x seconds I need to send an email indicating that something is wrong. How can I put a time limit on the execution of the external call? Note that I am not interested in terminating the call, just detecting that it t...
[ "That's what the subprocess object's poll is for. See http://docs.python.org/library/subprocess.html#subprocess.Popen.poll\nYou can use time.sleep() to wait for the timeout interval. Then poll the subprocess object to see if it's done.\nIf it's done, that's good.\nIf it's not done, your app sends an email.\n", ...
[ 1, 0 ]
[ "You could use sleep and check if the subprocess is alive like this : \nfrom multiprocessing import Process\nchecker = Process(target=yourFunction, args=(some_queue))\ntimeout = 150\nchecker.start()\ncounter = 0\nwhile checker.is_alive() == True:\n time.sleep(1)\n counter += 1\n if counter > ti...
[ -1 ]
[ "external", "popen", "python", "subprocess", "timer" ]
stackoverflow_0008727863_external_popen_python_subprocess_timer.txt
Q: what is wrong with importing modules in scipy , is it a bug? ok , i don't think, i can explain this problem in words so , here is the snippet of ipython session , where i import scipy , in order to construct a sparse matrix. In [1]: import scipy as sp In [2]: a = sp.sparse.lil_matrix((5,5)) --------------...
what is wrong with importing modules in scipy , is it a bug?
ok , i don't think, i can explain this problem in words so , here is the snippet of ipython session , where i import scipy , in order to construct a sparse matrix. In [1]: import scipy as sp In [2]: a = sp.sparse.lil_matrix((5,5)) --------------------------------------------------------------------------- ...
[ "This is an artifact of Python's importing, not of SciPy. Do\nfrom scipy import sparse [as sp]\n\nor\nimport scipy.sparse [as sp]\n\n(where [] is meta-notation for optionality).\nIn short, the import statement needs to know the module's \"true\" name, not some abbreviation created by an import as statement.\n" ]
[ 10 ]
[]
[]
[ "python", "scipy", "sparse_matrix" ]
stackoverflow_0008728732_python_scipy_sparse_matrix.txt
Q: Running Unit Tests in Test Bundle in Python I am trying to write a parser in Python for a special text file format. To get an idea how to structure the code I looked into the source code of the JSON parser which is part of the Python standard library (Python/Lib/json). In this json directory there is a tests direc...
Running Unit Tests in Test Bundle in Python
I am trying to write a parser in Python for a special text file format. To get an idea how to structure the code I looked into the source code of the JSON parser which is part of the Python standard library (Python/Lib/json). In this json directory there is a tests directory which holds a number of unit tests. I replac...
[ "First: the __init__.py file in a directory marks the directory as a package and all other files with the .py ending therein are modules.\nSecond: To validate the __name__ == '__main__' conditional you have to execute the file. So a simple import won't do.\nFor further question on package and module structure i wou...
[ 6 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0008728426_python_unit_testing.txt
Q: Reading a text file with dates into a list of dictionaries in Python I would like to read the following text file: date candy 1/12/2011 300 1/20/2010 200 1/16/2010 200 into a list of dictionaries as follows: candysales= [ {'date': d(2011,1,12), 'sales': 300}, {'date': d(2010,1,20), 'sales': 200},{'...
Reading a text file with dates into a list of dictionaries in Python
I would like to read the following text file: date candy 1/12/2011 300 1/20/2010 200 1/16/2010 200 into a list of dictionaries as follows: candysales= [ {'date': d(2011,1,12), 'sales': 300}, {'date': d(2010,1,20), 'sales': 200},{'date': d(2010,1,16), 'sales': 200}] Does anyone have any ideas of how to ...
[ "You can use csv.DictReader which will read a CSV file, using the first row as the dictionary key names, and parsing each row into a dictionary (you will lose field order in this case, as dictionaries are not reliably ordered). You can then convert the date from a string to a datetime.date object using datetime.dat...
[ 4, 3 ]
[]
[]
[ "date", "import", "python", "text" ]
stackoverflow_0008728854_date_import_python_text.txt
Q: Matplotlib subplots_adjust hspace so titles and xlabels don't overlap? With, say, 3 rows of subplots in matplotlib, xlabels of one row can overlap the title of the next. One has to fiddle with pl.subplots_adjust(hspace), which is annoying. Is there a recipe for hspace that prevents overlaps and works for any nr...
Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?
With, say, 3 rows of subplots in matplotlib, xlabels of one row can overlap the title of the next. One has to fiddle with pl.subplots_adjust(hspace), which is annoying. Is there a recipe for hspace that prevents overlaps and works for any nrow? """ matplotlib xlabels overlap titles ? """ import sys import numpy as n...
[ "The link posted by Jose has been updated and pylab now has a tight_layout() function that does this automatically (in matplotlib version 1.1.0).\nhttp://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout\nhttp://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout\n", "I find t...
[ 43, 31 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002418125_matplotlib_python.txt
Q: How the datas are connected to the specific user ID? I'm new to Django and python. I've done login forms but I need to know. How can I connect the contents of the page with the user. For example: It's a Q&A site. When you logged in, It shows profile page with the questions that user asked before. How the datas ar...
How the datas are connected to the specific user ID?
I'm new to Django and python. I've done login forms but I need to know. How can I connect the contents of the page with the user. For example: It's a Q&A site. When you logged in, It shows profile page with the questions that user asked before. How the datas are linked to the specific user ID in the model? Can it be d...
[ "Anything that \"belongs\" to a user, should either have a ForeignKey or ManyToManyField (depending on whether the object is owned by one user or many) to User on it. Then you can either filter the model based on the User:\nSomeModel.objects.filter(user=some_user)\n# where `user` is the name of your foreign key fie...
[ 1 ]
[]
[]
[ "django", "django_authentication", "django_profiles", "python" ]
stackoverflow_0008728330_django_django_authentication_django_profiles_python.txt
Q: Changing a setting variable from settings.py I am using Django 1.3 with mod_wsgi In my settings.py DISABLE_SYSTEM = False DISABLE_USER_INTERFACE = False MIDDLEWARE_CLASSES = [ 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale....
Changing a setting variable from settings.py
I am using Django 1.3 with mod_wsgi In my settings.py DISABLE_SYSTEM = False DISABLE_USER_INTERFACE = False MIDDLEWARE_CLASSES = [ 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.contrib.auth.middle...
[ "When you have scheduled changes to your settings, you might want to reconsider what you're doing.\nYour Middleware can be much, much smarter. This makes it possible for your settings to be much, much dumber.\nI would strongly suggest that you have one SomeMiddleware class which is always installed.\nThat SomeMidd...
[ 1 ]
[]
[]
[ "django", "django_settings", "python" ]
stackoverflow_0008728501_django_django_settings_python.txt
Q: Python Extension not installing into subpackage I'm trying to build a Python extension and package it up using distutils but the extension installs in the root package no matter how I name it. My directory layout looks like this: foo/bar/extension.c My setup.py looks like this: from distutils.core import setup f...
Python Extension not installing into subpackage
I'm trying to build a Python extension and package it up using distutils but the extension installs in the root package no matter how I name it. My directory layout looks like this: foo/bar/extension.c My setup.py looks like this: from distutils.core import setup from distutils.extension import Extension setup(name=...
[ "I think you need to have foo/__init__.py and foo/bar/__init__.py so that distutils installs first these packages and then the extension module. (An error would be better than a silent misbehavior here, I shall open a bug report so that distutils2 behaves better.)\nAre you using a custom build_ext class? (asking ...
[ 1 ]
[]
[]
[ "distutils", "python", "python_extensions" ]
stackoverflow_0008638534_distutils_python_python_extensions.txt
Q: Python list-comprehension in R? I want this in R: fsC=[read.table(x) for x in Sys.glob('./Trial7/*.csv')] i.e. trying to read the content of each file to a separate vector where vectors belong to a data structure. Python [file(x, 'r').read() for x in glob.glob('./Trial7/*.csv')] or better actually [file(x, 'r') ...
Python list-comprehension in R?
I want this in R: fsC=[read.table(x) for x in Sys.glob('./Trial7/*.csv')] i.e. trying to read the content of each file to a separate vector where vectors belong to a data structure. Python [file(x, 'r').read() for x in glob.glob('./Trial7/*.csv')] or better actually [file(x, 'r') for x in glob.glob('./Trial7/*.csv')]...
[ "You have two questions here. First, \"given a vector of filenames, how do you read those files into R?\".\nHere's your list of filenames\ntrial7_files <- Sys.glob(\"Trial7/*.csv\") \n#if you prefer to specify the names using regular expressions, try \ntrial7_files <- dir(\"Trial7\", \"\\\\.csv$\")\n\nAs previousl...
[ 7, 5 ]
[]
[]
[ "list_comprehension", "python", "r" ]
stackoverflow_0008727811_list_comprehension_python_r.txt
Q: Can't append_entry FieldList in Flask-wtf more than once I have a form with flask-wtf for uploading images, also file field can be multiple fields. my form: class ComposeForm(Form): attachment = FieldList(FileField(_('file')), _('attachment')) add_upload = SubmitField(_('Add upload')) my view: if form.val...
Can't append_entry FieldList in Flask-wtf more than once
I have a form with flask-wtf for uploading images, also file field can be multiple fields. my form: class ComposeForm(Form): attachment = FieldList(FileField(_('file')), _('attachment')) add_upload = SubmitField(_('Add upload')) my view: if form.validate_on_submit(): if form.add_upload.data: form.a...
[ "You call to append_entry is missing it's data.\nFrom the Documentation:\n\nappend_entry([data]) \nCreate a new entry with optional default data.\nEntries added in this way will not receive formdata however, and can only receive object data.\n\nIf you're trying to get the data that was submitted on the form, you mi...
[ 4 ]
[]
[]
[ "flask", "python", "wtforms" ]
stackoverflow_0008637831_flask_python_wtforms.txt
Q: Twisted MySQL adbapi return dictionary Is there any way to return dictionary result from adbapi query to MySQL? [name: 'Bob', phone_number: '9123 4567'] Default returns tuple. ['Bob', '9123 4567'] For simple Python & MySQL we can use MySQLdb.cursors.DictCursor. But how to use it with twisted adbapi UPD: I solv...
Twisted MySQL adbapi return dictionary
Is there any way to return dictionary result from adbapi query to MySQL? [name: 'Bob', phone_number: '9123 4567'] Default returns tuple. ['Bob', '9123 4567'] For simple Python & MySQL we can use MySQLdb.cursors.DictCursor. But how to use it with twisted adbapi UPD: I solved it but I think there should be better way...
[ "You can direct MySQLdb to use DictCursor by passing it as the value for the cursorclass argument to the connect function. ConnectionPool allows you to pass arbitrary arguments through to the connect method:\nimport MySQLdb\npool = ConnectionPool(\"MySQLdb\", ..., cursorclass=MySQLdb.cursors.DictCursor)\n...\n\nWh...
[ 10 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0008411613_python_twisted.txt
Q: How to pass on regex argument to another script through SSH I want to call a python script, script1.py, which takes a regex string as argument. This script then connects to another server and calls a script2.py. script1.py: regex = sys.argv[1] log = os.popen('ssh otherserver python /home/log/scripts/script2.py \"%...
How to pass on regex argument to another script through SSH
I want to call a python script, script1.py, which takes a regex string as argument. This script then connects to another server and calls a script2.py. script1.py: regex = sys.argv[1] log = os.popen('ssh otherserver python /home/log/scripts/script2.py \"%s\"' % regex) for line in log: print line.strip() log.close()...
[ "Try this:\nimport subprocess\noutput = subprocess.check_output(['ssh', 'otherserver', 'python', '/home/log/scripts/script2.py', regex])\n\n" ]
[ 2 ]
[]
[]
[ "python", "regex", "ssh" ]
stackoverflow_0008730058_python_regex_ssh.txt
Q: Python Timeit and “global name ... is not defined” I have a problem with timit function for code optimization. For example, I writing functions with parameters in a file, let's call it myfunctions.py containing : def func1(X): Y = X+1 return Y and I test this function in a second file test.py where I call...
Python Timeit and “global name ... is not defined”
I have a problem with timit function for code optimization. For example, I writing functions with parameters in a file, let's call it myfunctions.py containing : def func1(X): Y = X+1 return Y and I test this function in a second file test.py where I call the timer function to test code performance (in obvious...
[ "You need setup parameter. Try:\nTimer(\"Y0 = myfunctions.func1(X0)\", setup=\"import myfunctions; X0 = 1\")\n\n", "The reason for Y0 being undefined is that you have defined that in a string, but at parse time in the beginning of the execution the string is not evaluated yet to bring the variable into life. So ...
[ 6, 4 ]
[]
[]
[ "global_variables", "python", "timeit" ]
stackoverflow_0008727108_global_variables_python_timeit.txt
Q: Parsing lxml.etree._Element contents I have the following element that I parsed out of a <table> <td align="center" valign="top"> <a href="ConfigGroups.aspx?cfgID=451161&amp;prjID=11778&amp;grpID=DTST" target="_blank"> 5548U </a><br/>Power La Vaca<br/>(M8025K)<br/>Linux 4.2.x.x<br/> </td> I am trying...
Parsing lxml.etree._Element contents
I have the following element that I parsed out of a <table> <td align="center" valign="top"> <a href="ConfigGroups.aspx?cfgID=451161&amp;prjID=11778&amp;grpID=DTST" target="_blank"> 5548U </a><br/>Power La Vaca<br/>(M8025K)<br/>Linux 4.2.x.x<br/> </td> I am trying to extract "55488 Power La Vaca (8025K) L...
[ "I know there must be a better way but this works.\nlink = td_elem.find('a').text.strip()\ntext = ''.join(td_elem.itertext()).strip()\ntext.split(link)[1]\n\nOutput is Power La Vaca(M8025K)Linux 4.2.x.x\nUpdate: \nThis is actually better if you want spaces in place of those <br>s\n' '.join(map(str, [el.tail for el ...
[ 3, 3 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0008729997_lxml_python.txt
Q: Python string.find() giving error "slice indices must be integers or None or have an __index__ method" I am trying to do a simple sub string matching in Python and although I remember last night it was working fine, but since morning this piece of code is giving the following error. It seems to be a known error, c...
Python string.find() giving error "slice indices must be integers or None or have an __index__ method"
I am trying to do a simple sub string matching in Python and although I remember last night it was working fine, but since morning this piece of code is giving the following error. It seems to be a known error, can anyone suggest why is it happening? if string.find(row[1],drug) != -1: print "abstract id = ", row[0...
[ "What is string?\nThis would work if it were the module string.\nIf it is a string object instead (the error suggests that this is the case), then the second argument is the position at which it should start searching. The position must be an integer or None or an object with __index__ method. drug is a string so y...
[ 8, 5 ]
[]
[]
[ "python" ]
stackoverflow_0008730499_python.txt
Q: What algorithms can I use to make inferences from a graph? Edited question to make it a bit more specific. Not trying to base it on content of nodes but solely of structure of directed graph. For example, pagerank(at first) solely used the link structure(directed graph) to make inferences on what was more relevant...
What algorithms can I use to make inferences from a graph?
Edited question to make it a bit more specific. Not trying to base it on content of nodes but solely of structure of directed graph. For example, pagerank(at first) solely used the link structure(directed graph) to make inferences on what was more relevant. I'm not totally sure, but I think Elo(chess ranking) does som...
[ "Eigenvector centrality is a network metric that can be used to model the probability that a node will be encountered in a random walk. It factors in not only the number of edges that a node has but also the number of edges the nodes it connects to have and onward with the edges that the nodes connected to its conn...
[ 4, 2 ]
[]
[]
[ "algorithm", "machine_learning", "python", "statistics" ]
stackoverflow_0008721316_algorithm_machine_learning_python_statistics.txt
Q: Getting started with Git Python My goal is to access existing Git repos from Python. I want to get repo history and on demand diffs. In order to do that I started with dulwich. So I tried: from dulwich.repo import Repo Repo.init('/home/umpirsky/Projects/my-exising-git-repo') and got OSError: [Errno 17] File exist...
Getting started with Git Python
My goal is to access existing Git repos from Python. I want to get repo history and on demand diffs. In order to do that I started with dulwich. So I tried: from dulwich.repo import Repo Repo.init('/home/umpirsky/Projects/my-exising-git-repo') and got OSError: [Errno 17] File exists: '/home/umpirsky/Projects/my-exisin...
[ "I think that init method is used to create a new repository, to open an existing one you just pass the path to it this way:\nfrom dulwich.repo import Repo\nrepo = Repo(<path>)\n\nFor a summary of alternative libraries please have a look at this answer. Basically, it suggests that it's easier to use subprocess modu...
[ 6, 4 ]
[]
[]
[ "dulwich", "git", "python" ]
stackoverflow_0008724264_dulwich_git_python.txt
Q: Access Google Apps users from Google App Engine Is there a way to access the Google Apps users for my domain from a Google App Engine App on uploaded on that domain. I know I can use it for authentication, and I could build queries to the Google Apps api that would pull this data up, I was just wondering if there ...
Access Google Apps users from Google App Engine
Is there a way to access the Google Apps users for my domain from a Google App Engine App on uploaded on that domain. I know I can use it for authentication, and I could build queries to the Google Apps api that would pull this data up, I was just wondering if there is a native way to take care of this. I would be writ...
[ "There's not an App Engine-specific API, but you can use the gdata-python library. See this article.\n" ]
[ 3 ]
[]
[]
[ "google_app_engine", "google_apps", "python" ]
stackoverflow_0008730302_google_app_engine_google_apps_python.txt
Q: Error in Python This is my 1st Python program.I implemented a dictionary as shown below. Here I'm trying to retrieve values*(either key or value)* depending upon the user input. For eg: If user enters "1" then I need to retrieve "Sachin Tendulkar " from the dictioanry. If user enter "Sachin Tendulkar" then I need...
Error in Python
This is my 1st Python program.I implemented a dictionary as shown below. Here I'm trying to retrieve values*(either key or value)* depending upon the user input. For eg: If user enters "1" then I need to retrieve "Sachin Tendulkar " from the dictioanry. If user enter "Sachin Tendulkar" then I need to retrieve "1" from...
[ "The problem is within this line:\ninp=input('Enter M/N:')\n\nYou use input instead of raw_input, which you really shouldn't, as it executes everything the user inputs as Python code. Just use raw_input here and it should be fine.\nHowever, the rest of your code is also broken and shouldn't work as you expect it to...
[ 5, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008730866_python.txt
Q: Convert django Charfield "\t" to tab I have a django model with a Charfield that contains the unicode escaped string "\\t". What is the easiest way to convert this to a real tab (as in str("\t"))? A: Found the answer: "\\t".decode("string_escape") as described here in the comments In Python3 syntax: In [5]: b'\...
Convert django Charfield "\t" to tab
I have a django model with a Charfield that contains the unicode escaped string "\\t". What is the easiest way to convert this to a real tab (as in str("\t"))?
[ "Found the answer:\n\"\\\\t\".decode(\"string_escape\")\n\nas described here in the comments\nIn Python3 syntax:\nIn [5]: b'\\\\t'.decode(\"unicode_escape\")\nOut[5]: '\\t'\n\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008730270_django_python.txt
Q: Python If then Else style when getting values from Dicts I often struggle with the following if/else syntax and I was hoping some people could give me some of their opinions as to what they think is more clear or if this violates any Pythonisms (I've searched and wasn't able to find anything). Is one of these bett...
Python If then Else style when getting values from Dicts
I often struggle with the following if/else syntax and I was hoping some people could give me some of their opinions as to what they think is more clear or if this violates any Pythonisms (I've searched and wasn't able to find anything). Is one of these better and or right/wrong? value = None if 'value' in some_dict: ...
[ "Of course the last one is the best - described situation is exact case for dict.get.\nJust a note - second parameter to get is superfluous, you can simply write:\nsome_func(value=some_dict.get('value'))\n\n", "This looks most natural to me:\nvalue = some_dict.get('value')\nsome_func(value=value)\n\nOr: the last ...
[ 8, 1, 1, 0, 0 ]
[]
[]
[ "if_statement", "python", "syntax" ]
stackoverflow_0008730946_if_statement_python_syntax.txt
Q: Net-SNMP returns HexString and then just String (Eclipse and Pydev) I am doing an snmpget using Net-SNMP. Specifically I am sending a command via os.popen("etc"). The value returned is a Hex-string separated by spaces, something like this : "A0 f0 D0". The returned value comes sometimes in the form :"Hex-String...
Net-SNMP returns HexString and then just String (Eclipse and Pydev)
I am doing an snmpget using Net-SNMP. Specifically I am sending a command via os.popen("etc"). The value returned is a Hex-string separated by spaces, something like this : "A0 f0 D0". The returned value comes sometimes in the form :"Hex-String: A0 f0 D0.." but sometimes comes in the form "String:\xA0\xf0\xD0" where...
[ "PyDev does one thing differently, which is setting: sys.setdefaultencoding(encoding) with the encoding of the java console (so that if you print unicode to the console it won't fail saying that the unicode doesn't decode as ascii). To see if this is your problem, you can go to eclipse\\plugins\\org.python.pydev\\P...
[ 0 ]
[]
[]
[ "eclipse", "net_snmp", "pydev", "python" ]
stackoverflow_0008714233_eclipse_net_snmp_pydev_python.txt
Q: Python script to verify IPTV streams (UDP) My fiber internet provider supports IPTV over UDP. They do not however list the channels anywhere. I have found most of them manually, but would like to have a script that can verify if a channel is active/available. Any ideas on how to go about this in Python? A: I th...
Python script to verify IPTV streams (UDP)
My fiber internet provider supports IPTV over UDP. They do not however list the channels anywhere. I have found most of them manually, but would like to have a script that can verify if a channel is active/available. Any ideas on how to go about this in Python?
[ "I think the python code should look like below. Note that don't run it in Python IDLE since ipRange() will hang it.\ndef ipRange(start_ip, end_ip):\n start = list(map(int, start_ip.split(\".\")))\n end = list(map(int, end_ip.split(\".\")))\n temp = start\n ip_range = []\n\n ip_range.append(start_ip)\n while ...
[ 1 ]
[]
[]
[ "iptv", "python" ]
stackoverflow_0004578764_iptv_python.txt
Q: Inconsistency between %time and %timeit in IPython I am confronted to a weird situation that I can't explain. Here is my test timing the generation of a large list of tuples: In [1]: def get_list_of_tuples(): ...: return [(i,) for i in range(10**6)] ...: In [2]: %time res = get_list_of_tuples() CPU time...
Inconsistency between %time and %timeit in IPython
I am confronted to a weird situation that I can't explain. Here is my test timing the generation of a large list of tuples: In [1]: def get_list_of_tuples(): ...: return [(i,) for i in range(10**6)] ...: In [2]: %time res = get_list_of_tuples() CPU times: user 0.93 s, sys: 0.08 s, total: 1.01 s Wall time: 0....
[ "The main difference is because \"by default, timeit() temporarily turns off garbage collection during the timing\".\nTurning the garbage collection returns results similar to the one shown in the question, i.e. the time of execution with garbage collection is magnitude bigger than the one without:\nIn [1]: import ...
[ 42, 3 ]
[ "%time - runs statement only once, and have measurement error\n%timeit - runs statement few times, and choses most accurate time.\nSee Python timeit module documentation for some explanations\n" ]
[ -5 ]
[ "ipython", "python", "timeit" ]
stackoverflow_0008619167_ipython_python_timeit.txt
Q: Eclipse PyDev auto-import malfunctioning I've been trying to get used to pydev for a couple of days now, and I really like it, but if I keep the auto-import option on, it keeps importing for example from test.test_iterlen import len (and many others) whenever I want a len(something) even though it's not necessary....
Eclipse PyDev auto-import malfunctioning
I've been trying to get used to pydev for a couple of days now, and I really like it, but if I keep the auto-import option on, it keeps importing for example from test.test_iterlen import len (and many others) whenever I want a len(something) even though it's not necessary. On the other hand if I completely turn the au...
[ "The auto-import works by going through what's called the 'code completion (ctx insensitive)'... here the major issue seems to be that you're requesting the code-completion for 'len' and it's defined in many other places (and you end up choosing one of those).\nSo, I think in your case, if you usually do completion...
[ 1, 0 ]
[]
[]
[ "blank_line", "eclipse", "import", "pydev", "python" ]
stackoverflow_0008681750_blank_line_eclipse_import_pydev_python.txt
Q: Python regular expression to replace unencoded ampersands in text I'm working with an upstream system that sometimes sends me text destined for HTML/XML output with ampersands that are unencoded: str1 = "Stay at this B&B" str2 = "He&#8217;s going to Texas A&M" str3 = "He&#8217;s going to a B&amp;B and then Texas A...
Python regular expression to replace unencoded ampersands in text
I'm working with an upstream system that sometimes sends me text destined for HTML/XML output with ampersands that are unencoded: str1 = "Stay at this B&B" str2 = "He&#8217;s going to Texas A&M" str3 = "He&#8217;s going to a B&amp;B and then Texas A&M" I need to replace the unencoded ampersands with &amp; while preser...
[ "If the ampersand is part of a character entity, it can be any named entity (not just &amp;), a decimal entity, OR a hexadecimal entity. This should cover it:\nre.sub(r'&(?![A-Za-z]+[0-9]*;|#[0-9]+;|#x[0-9a-fA-F]+;)',\n r'&amp;', your_string)\n\n", "I would suggest using a negative lookahead for this. It ...
[ 12, 5, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008731454_python_regex.txt
Q: PYTHON 2.6 XML.ETREE to output single quote for attributes instead of double quote i got the following code : #!/usr/bin/python2.6 from lxml import etree n = etree.Element('test') n.set('id','1234') print etree.tostring(n) the output generate is <test id="1234"/> but i want <test id='1234'/> can s...
PYTHON 2.6 XML.ETREE to output single quote for attributes instead of double quote
i got the following code : #!/usr/bin/python2.6 from lxml import etree n = etree.Element('test') n.set('id','1234') print etree.tostring(n) the output generate is <test id="1234"/> but i want <test id='1234'/> can someone help ?
[ "I checked the documentation and found no reference for single/double-quote option.\nI think your only recourse is print etree.tostring(n).replace('\"', \"'\")\nUpdate\nGiven:\nfrom lxml import etree\nn = etree.Element('test')\nn.set('id', \"Zach's not-so-good answer\")\n\nmy original answer could output malformed ...
[ 7 ]
[]
[]
[ "lxml", "python", "python_2.6", "xml" ]
stackoverflow_0008730950_lxml_python_python_2.6_xml.txt
Q: Add Section to OpenDocument Text file with ODFpy I am using Python2.7 and ODFpy to write an OpenDocument Text (ODT) file. Is there a way using the existing ODFpy API to add sections (a la Format->Sections...) to the document? Is there a way to import them from another document and then populate them, or to otherwi...
Add Section to OpenDocument Text file with ODFpy
I am using Python2.7 and ODFpy to write an OpenDocument Text (ODT) file. Is there a way using the existing ODFpy API to add sections (a la Format->Sections...) to the document? Is there a way to import them from another document and then populate them, or to otherwise fetch the styling from another document?
[ "A section can be added to a document by a method something like this:\nfrom odf import text as odftext\nfrom odf import opendocument\ndocument = opendocument.OpenDocument()\ndocument.text.addElement(odftext.Section(name=\"section1\"))\n\n" ]
[ 0 ]
[]
[]
[ "odfpy", "odt", "opendocument", "python" ]
stackoverflow_0007692114_odfpy_odt_opendocument_python.txt
Q: what is the as3 bitmapdata bytearray format / how to transform into png in python in a local as3 application i need to capture a video at 25 frames per second and send the bytearray to a local python script. when i try to encode the bytearray to png inside as3 it is much to slow. so i decided to just write the raw...
what is the as3 bitmapdata bytearray format / how to transform into png in python
in a local as3 application i need to capture a video at 25 frames per second and send the bytearray to a local python script. when i try to encode the bytearray to png inside as3 it is much to slow. so i decided to just write the raw bytearray i got from : var bitmapdata:BitmapData = new BitmapData(_videow,_videoh,fals...
[ "It's roughly the same as PCX* (some earlier variant of BMP). It is actually very similar to BMP, save that there are no headers, and the pixels are written from left to right, top down ARGB for transparent bitmapdata and RGB for solid. \nWhat PNG encoder did you use? Have you tried this one: http://www.blooddy.by/...
[ 0 ]
[]
[]
[ "actionscript_3", "python" ]
stackoverflow_0008718746_actionscript_3_python.txt
Q: Parsing xml with etree I am trying to parse an XML response from Amazon's Product Advertising API, this is the xml <?xml version="1.0" ?> <ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2010-11-01"> <OperationRequest> <HTTPHeaders> <Header Name="UserAgent" Value...
Parsing xml with etree
I am trying to parse an XML response from Amazon's Product Advertising API, this is the xml <?xml version="1.0" ?> <ItemLookupResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2010-11-01"> <OperationRequest> <HTTPHeaders> <Header Name="UserAgent" Value="TSN (Language=Python)"></H...
[ "It is a namespace issue. This works:\nfrom xml.etree import ElementTree as ET\n\nXML = \"\"\"<?xml version=\"1.0\" ?>\n <ItemLookupResponse xmlns=\"http://webservices.amazon.com/AWSECommerceService/2010-11-01\"> \n <OperationRequest>\n <HTTPHeaders>\n <Header Name=\"UserAgent\" Value=\"TS...
[ 4, 1 ]
[]
[]
[ "amazon_web_services", "elementtree", "python", "xml" ]
stackoverflow_0008719282_amazon_web_services_elementtree_python_xml.txt
Q: Scatter plot of 10k record extracted from database I am trying to make a scatter plot in Python. I supposed it will be fairly simple but got stuck with understanding in scatterplot (x and y value) while plotting. ==My mission == I have database and more then 10k record (all float) till now and will increase on da...
Scatter plot of 10k record extracted from database
I am trying to make a scatter plot in Python. I supposed it will be fairly simple but got stuck with understanding in scatterplot (x and y value) while plotting. ==My mission == I have database and more then 10k record (all float) till now and will increase on daily basis. The record range is from 200-2000 (in float d...
[ "Perhaps you are looking for a matplotlib histogram:\nimport numpy as np\nimport MySQLdb\nimport matplotlib.pyplot as plt # This is meant for scripts\n# import pylab as pl # This is meant for interactive sessions; \nimport operator\n\nconn = MySQLdb.connect(\n host=\"localhost\",\n user=\"root\",\n passwd=...
[ 3, 2 ]
[]
[]
[ "matplotlib", "mysql", "python", "scatter_plot" ]
stackoverflow_0008732009_matplotlib_mysql_python_scatter_plot.txt
Q: Python XML processing after a specific comment I have an automated process that keeps an XML file up to date based on an external data source. This XML file can also be modified by users, their manual changes need to be maintained. <Nodes> <!-- User added data goes here --> <Node name="1">Data Data Data...
Python XML processing after a specific comment
I have an automated process that keeps an XML file up to date based on an external data source. This XML file can also be modified by users, their manual changes need to be maintained. <Nodes> <!-- User added data goes here --> <Node name="1">Data Data Data</Node> <Node name="2">Data Data Data</Node> ...
[ "In XML, comments are comments, and can be rightfully stripped out of the document in any stage of processing. You should adapt your program to add a special attribute, like\n<Nodes>\n <!-- User added data goes here -->\n <Node name=\"1\">Data Data Data</Node>\n <Node name=\"2\">Data Data Data</Node>\n ...
[ 3 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0008732165_minidom_python_xml.txt
Q: Are there any graph/plotting/anything-like-that libraries for Python 3.0? As per the title. I am trying to create a simple scater plot, but haven't found any Python 3.0 libraries that can do it. Note, this isn't for a website, so the web ones are a bit useless. A: Maybe you can use Python Imaging Library (PIL). ...
Are there any graph/plotting/anything-like-that libraries for Python 3.0?
As per the title. I am trying to create a simple scater plot, but haven't found any Python 3.0 libraries that can do it. Note, this isn't for a website, so the web ones are a bit useless.
[ "Maybe you can use Python Imaging Library (PIL).\nAlso have a look at PyX, but this library is meant to output to PDF, ...\n", "The GChartWrapper (http://pypi.python.org/pypi/GChartWrapper/0.7) does work for py3k\n", "Have you looked at the Google Chart Wrapper?\nhttp://pypi.python.org/pypi/GChartWrapper/0.7\n"...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "graphing", "plot", "python", "python_3.x", "scatter_plot" ]
stackoverflow_0000418835_graphing_plot_python_python_3.x_scatter_plot.txt
Q: Comparing strings and numbers in Python Why does the following piece behave like it behaves? >>> '10' > 100 True >>> 100 < '10' True Shouldn't it raise an exception? A: From the documentation: CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of t...
Comparing strings and numbers in Python
Why does the following piece behave like it behaves? >>> '10' > 100 True >>> 100 < '10' True Shouldn't it raise an exception?
[ "From the documentation:\n\nCPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.\n\nSo it's just something that happens in CPython ('int' < 'str'), but that isn't guarant...
[ 6, 1, 0, 0 ]
[ "I am not 100% sure, but some internal type conversion might be happening here. It might be doing what is called lexicographic comparison, where '1' which is 49 in ASCII is greater than 1 (the first digit), and so on.\n" ]
[ -1 ]
[ "comparison", "numbers", "python", "string" ]
stackoverflow_0008732240_comparison_numbers_python_string.txt
Q: Optional number of wildcards in URL patterns in Django #views.py def sum(*args): return reduce((lambda x, y: int(x)+int(y)), args) Is it possible to write one URL pattern that will handle uniformly such requests as /sum/1/2 (result = 3), /sum/1/2/3 (result = 6), etc.? A: It's not exactly what you want, but ...
Optional number of wildcards in URL patterns in Django
#views.py def sum(*args): return reduce((lambda x, y: int(x)+int(y)), args) Is it possible to write one URL pattern that will handle uniformly such requests as /sum/1/2 (result = 3), /sum/1/2/3 (result = 6), etc.?
[ "It's not exactly what you want, but you could use\n(r'^sum/(?P<allargs>[/0-9]+)$', 'views.sum')\n\nand then\ndef sum(request, allargs):\n args = map( int, allargs.split('/') )\n # Compute sum\n\n", "Unless you absolutely want to use the form \"/1/2/3\", you'd rather use query string \"/sum?1&2&3\". It will...
[ 3, 3 ]
[]
[]
[ "django", "python", "url_pattern" ]
stackoverflow_0008732148_django_python_url_pattern.txt
Q: Best way to implement 2-D array of series elements in Python I have a dynamic set consisting of a data series on the order of hundreds of objects, where each series must be identified (by integer) and consists of elements, also identified by an integer. Each element is a custom class. I used a defaultdict to creat...
Best way to implement 2-D array of series elements in Python
I have a dynamic set consisting of a data series on the order of hundreds of objects, where each series must be identified (by integer) and consists of elements, also identified by an integer. Each element is a custom class. I used a defaultdict to created a nested (2-D) dictionary. This enables me to quickly access a ...
[ "I think what you want is a dict with array values:\ndict = {1:[...],3:[...], ....}\n\nYou can then operate on the arrays as you please. If the array values are sequential ints\njust use:\ndict[key].append(vals)\ndict[key].sort()\n\nDon't worry about the speed unless you find out it's a problem. Premature optimizat...
[ 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0008732120_dictionary_list_python.txt
Q: In Python, How do I skip to a specific line in a script? I am making a script that opens programs, in this case, Google Chrome and iTunes. Google Chrome comes first, and in the script it asks if you want to enter the password to launch Google Chrome. If the user types 'Yes' then it asks for the password, etc. Howe...
In Python, How do I skip to a specific line in a script?
I am making a script that opens programs, in this case, Google Chrome and iTunes. Google Chrome comes first, and in the script it asks if you want to enter the password to launch Google Chrome. If the user types 'Yes' then it asks for the password, etc. However, iTunes is several lines lower in the script, So is there ...
[ "Once you have the code correct, whether on not Chrome is launched the script will then ask if you want to launch iTunes.\nHere is some minimal code to hopefully get you going:\nimport os\n\nchrome = raw_input ('Would You Like to Launch Google Chrome' )\nif chrome.lower() == 'yes':\n\n pw = 'memebase145'\n pa...
[ 2, 1 ]
[]
[]
[ "python", "raw_input" ]
stackoverflow_0008732292_python_raw_input.txt
Q: Is it possible to get detailed help on a given function using the command line? I am a new Python user :) Is it possible to get detailed help on a given function using the command line ? A: As python tells you when you start the CLI: Type "help", "copyright", "credits" or "license" for more information. >>> ju...
Is it possible to get detailed help on a given function using the command line?
I am a new Python user :) Is it possible to get detailed help on a given function using the command line ?
[ "As python tells you when you start the CLI:\n\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>>\n\njust ask for help:\nhelp(help)\nhelp(list)\nhelp(locals)\nimport math\nhelp(math)\nhelp(math.atan2)\n\n", "Consider installing IPython. Not only does it give you quick and easy ac...
[ 4, 3, 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008732418_python.txt
Q: Python default values and setting the value based on other variables. To if else or to not. At times I have a variable that I want to default to something and if something else is set change it to something else. The question is. What is preferred? Setting the default value and then changing it if the condition is...
Python default values and setting the value based on other variables. To if else or to not.
At times I have a variable that I want to default to something and if something else is set change it to something else. The question is. What is preferred? Setting the default value and then changing it if the condition is met or setting the condition only once depending on the initial check with an added else? Exampl...
[ "How about this:\ny = '%s-other' % x if x else 'some_default'\n\n", "As Rob pointed out,\ny = '%s-other' % x if x else 'some_default'\n\nis a very common construct across various language\nPython provides some more alternatives and the choice depends on the User \ny = ['some_default','%s-other'][x!=None]\n\nIf yo...
[ 5, 4, 0 ]
[]
[]
[ "coding_style", "default_value", "python", "syntax" ]
stackoverflow_0008732867_coding_style_default_value_python_syntax.txt
Q: What packaging option are available for python/django I am starting on developing a django application on a shared webhosting server(alwaysdata.com). I would like to understand what are the packaing options available to package a django application (preferably in compiled form) I would like to setup the source cod...
What packaging option are available for python/django
I am starting on developing a django application on a shared webhosting server(alwaysdata.com). I would like to understand what are the packaing options available to package a django application (preferably in compiled form) I would like to setup the source code repository on my system and build using the python packag...
[ "I've found fabric to be a pretty nice tool for deploying Django projects. To compile your python code you can use compileall:\npython -m compileall <dir>\n\n", "How is this API key used? Is it a google maps api? Is it provided in scripts that go to the browser? If so, it's already out in the open, anyone using ...
[ 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008715370_django_python.txt
Q: accessing columns within an array within a for loop below is the code to create multiple sets of 0's and fill it with random numbers, im then taking the first column and calculating the maximum value, the problem is I need to be able to do this for every row (i.e rows 2 through 10) ive tried putting it into a for ...
accessing columns within an array within a for loop
below is the code to create multiple sets of 0's and fill it with random numbers, im then taking the first column and calculating the maximum value, the problem is I need to be able to do this for every row (i.e rows 2 through 10) ive tried putting it into a for loop however it doesnt work with the traditional y=1, mx[...
[ "import numpy as np\nmx = np.random.randn(10, 6)\nnp.max(mx, axis=0)\n\nI've taken the library of using NumPy instead of Pylab; that's what Pylab uses internally, anyway. You can also use pylab.amax instead of np.max, that's exactly the same function.\n", "If you are looking for the max of rows 2 through 10,\nthe...
[ 1, 1 ]
[]
[]
[ "arrays", "matplotlib", "numpy", "python" ]
stackoverflow_0008733069_arrays_matplotlib_numpy_python.txt
Q: CSV formatted data off website not being properly parsed My Python script opens a file through urllib2; the data looks like this: "Charitable Donation: Contribution","012","","","","","","","","","","","","","","","","","","","","" The Python script: reader = csv.reader(data, delimiter=',', quotechar='"', quoting...
CSV formatted data off website not being properly parsed
My Python script opens a file through urllib2; the data looks like this: "Charitable Donation: Contribution","012","","","","","","","","","","","","","","","","","","","","" The Python script: reader = csv.reader(data, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL) for row in reader: print row The output i...
[ "You're using double-quote (\") as the delimiter instead of comma (,) ...why? How about\nreader = csv.reader(data, delimiter=',', quoting=csv.QUOTE_ALL)\nfor row in reader:\n print row\n\n# you can omit the delimiter argument as well, since comma is the default:\nreader = csv.reader(data, quoting=csv.QUOTE_ALL)\...
[ 3, 2, 2, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0008733517_csv_python.txt