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: Python: binary file to gz file and then to jpg extension and finally return again to the original binary file I want to do the following in Python: Take a binary (executable) file Turn it into a zip file with gzip (gz extension) Then put the jpg extension Later again the desire to recover the original (without t...
Python: binary file to gz file and then to jpg extension and finally return again to the original binary file
I want to do the following in Python: Take a binary (executable) file Turn it into a zip file with gzip (gz extension) Then put the jpg extension Later again the desire to recover the original (without the gz extension or jpg). The idea is to send binary files through GMail SMTP to recover and then get them over IMAP...
[ "You can use gzip to compress the files and os.rename to change file names. In your case you could just use gzip and save it with a .jpg extension in the first place.\nimport gzip\n\n# write compressed file\nwith gzip.open('my_file.jpg', 'wb') as f:\n f.write(content)\n\n# read it again\nwith gzip.open('my_file....
[ 2, 2 ]
[]
[]
[ "binary", "file", "imap", "python", "smtp" ]
stackoverflow_0006508780_binary_file_imap_python_smtp.txt
Q: Text display with matplotlib I'm having a problem with the plt.text() method in matplotlib and I am hoping someone can help me. Below is a basic linear regression example where I would like to display some text (slope = ) and the actual slope of the line on the graph: import csv import scipy as sp import scipy.sta...
Text display with matplotlib
I'm having a problem with the plt.text() method in matplotlib and I am hoping someone can help me. Below is a basic linear regression example where I would like to display some text (slope = ) and the actual slope of the line on the graph: import csv import scipy as sp import scipy.stats import matplotlib.pyplot as plt...
[ "str='slope'+str(slope)\nplt.text(2, 30, str, fontsize=15)\n\nor just plt.text(2, 30, r'slope='+str(slope), fontsize=15)\n" ]
[ 4 ]
[]
[]
[ "matplotlib", "numpy", "python", "scipy" ]
stackoverflow_0006508963_matplotlib_numpy_python_scipy.txt
Q: python: pyPdf library and images, from pdf to image i modify pdf pages with python library "pyPdf". Then i need save pdf and images. New Pdf i save with this code: outputStream = file("new_pdf.pdf", "wb") How with python save pages as images? Thanks A: As far as I know there is no good way to do this, not with...
python: pyPdf library and images, from pdf to image
i modify pdf pages with python library "pyPdf". Then i need save pdf and images. New Pdf i save with this code: outputStream = file("new_pdf.pdf", "wb") How with python save pages as images? Thanks
[ "As far as I know there is no good way to do this, not with pyPdf or any other libraries I've seen. PIL supports writing, but not reading PDF so it doesn't help here, either. Such support would be quite nice to have. I'd recommend using ImageMagick as a work around, you can call it with subprocess from your script,...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006508641_python.txt
Q: What is meant by "classes themselves are objects"? I was just reading the Python documentation about classes; it says, in Python "classes themselves are objects". How is that different from classes in C#, Java, Ruby, or Smalltalk? What advantages and disadvantages does this type of classes have compared with those...
What is meant by "classes themselves are objects"?
I was just reading the Python documentation about classes; it says, in Python "classes themselves are objects". How is that different from classes in C#, Java, Ruby, or Smalltalk? What advantages and disadvantages does this type of classes have compared with those other languages?
[ "In Python, classes are objects in the sense that you can assign them to variables, pass them to functions, etc. just like any other objects. For example\n>>> t = type(10)\n>>> t\n<type 'int'>\n>>> len(t.__dict__)\n55\n>>> t() # construct an int\n0\n>>> t(10)\n10\n\nJava has Class objects which provide some informa...
[ 9, 3, 2, 1, 1, 1, 1 ]
[]
[]
[ "class", "object", "oop", "python" ]
stackoverflow_0006482207_class_object_oop_python.txt
Q: Python - Find non mutual items in two dicts Lets say I have two dictionaries: a = {'a': 1, 'b': 2, 'c': 3} b = {'b': 2, 'c': 3, 'd': 4, 'e': 5} What's the most pythonic way to find the non mutual items between the two of them such that for a and b I would get: {'a': 1, 'd': 4, 'e': 5} I had thought: {key: b[ke...
Python - Find non mutual items in two dicts
Lets say I have two dictionaries: a = {'a': 1, 'b': 2, 'c': 3} b = {'b': 2, 'c': 3, 'd': 4, 'e': 5} What's the most pythonic way to find the non mutual items between the two of them such that for a and b I would get: {'a': 1, 'd': 4, 'e': 5} I had thought: {key: b[key] for key in b if not a.get(key)} but that only...
[ ">>> dict(set(a.iteritems()) ^ set(b.iteritems()))\n{'a': 1, 'e': 5, 'd': 4}\n\n", "Try with the symetric difference of set() : \nout = {}\nfor key in set(a.keys()) ^ set(b.keys()):\n out[key] = a.get(key, b.get(key))\n\n", "diff = {key: a[key] for key in a if key not in b}\ndiff.update((key,b[key]) for key i...
[ 11, 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006508986_python.txt
Q: Is there a standard DSL for data integrity validation? I am faced with CSV files which come from clients and which can contain hundreds of thousands of rows. Is there a DSL (or wildly popular library in Java or Python) which can efficiently run calculations on this information, applying various rules to issue warn...
Is there a standard DSL for data integrity validation?
I am faced with CSV files which come from clients and which can contain hundreds of thousands of rows. Is there a DSL (or wildly popular library in Java or Python) which can efficiently run calculations on this information, applying various rules to issue warnings and errors (user-configurable, of course)?
[ "Can you imagine a DSL that would do it? How will the rules look like? \nSeveral months ago I worked on such problem - in the end it turned out to be harder than it seemed first.\n\nThe first step was obvious - all\nrows were parsed and placed to the\nspecial data stuctures so I could\nwork with them; the ones wit...
[ 1 ]
[]
[]
[ "import_from_csv", "java", "python", "validation" ]
stackoverflow_0006347374_import_from_csv_java_python_validation.txt
Q: django/python - what's the recommended secure way to exchange data between my infrastructure and my customers? I'm using Django/Postgres and Python for my web site and the background processes. I have hundreds of messages every minute populating my database and I would like to securely allow other customers access...
django/python - what's the recommended secure way to exchange data between my infrastructure and my customers?
I'm using Django/Postgres and Python for my web site and the background processes. I have hundreds of messages every minute populating my database and I would like to securely allow other customers access their data. My customers use either linux or windows so I would like some solution that will be platform/database ...
[ "You asked how your customers can securely transmit commands to your website and retrieve results in their response (near \"real-time\").\n... have you considered hooking a reasonable API into your django app? If you're concerned about security, you can use authentication and serve it over HTTPS.\nIt's not as fancy...
[ 3 ]
[]
[]
[ "django", "django_piston", "python", "rabbitmq", "twisted" ]
stackoverflow_0006509455_django_django_piston_python_rabbitmq_twisted.txt
Q: How do you access config outside of a request in CherryPy? I've got a webapp running on CherryPy that needs to access the CherryPy config files before a user creates a request. The docs say to use: host = cherrypy.request.app.config['database']['host'] But that won't work outside of a user request. You can also ...
How do you access config outside of a request in CherryPy?
I've got a webapp running on CherryPy that needs to access the CherryPy config files before a user creates a request. The docs say to use: host = cherrypy.request.app.config['database']['host'] But that won't work outside of a user request. You can also use the application object when you start the app like so: ... ...
[ "You can access it via the same cherrypy.tree object using the script name (minus the trailing slash):\napplication = cherrypy.tree.apps['']\nhost = application.config['database']['host']\n\nHowever, as alluded to in other answers there are likely better ways to structure your code.\n", "\nis there any way to sto...
[ 2, 0 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0002929790_cherrypy_python.txt
Q: Efficient Alternative to "in" I'm writing a web crawler with the ultimate goal of creating a map of the path the crawler has taken. While I haven't a clue at what rate other, and most definitely better crawlers pull down pages, mine clocks about 2,000 pages per minute. The crawler works on a recursive backtracking...
Efficient Alternative to "in"
I'm writing a web crawler with the ultimate goal of creating a map of the path the crawler has taken. While I haven't a clue at what rate other, and most definitely better crawlers pull down pages, mine clocks about 2,000 pages per minute. The crawler works on a recursive backtracking algorithm which I have limited to ...
[ "Perhaps you could use a set instead of a list for the urls that you have seen so far.\n", "Simply replace your 'list of crawled URLS\" with a \"set of crawled urls\". Sets are optimised for random access (using the same hashing algorithms that dictionaries use) and they're a heck of a lot faster. A lookup operat...
[ 15, 7, 3, 2 ]
[]
[]
[ "list", "memory", "optimization", "python" ]
stackoverflow_0006509647_list_memory_optimization_python.txt
Q: JTables and Jython Events I've just been getting started at getting over the hump of swing in Jython vs swing in Java directly.. and I'm wondering if someone can help me out with adding action-listeners to a JTable in Jython. I know with a button, you can just do: button = Jbutton( " Press me! ", actionPerformed =...
JTables and Jython Events
I've just been getting started at getting over the hump of swing in Jython vs swing in Java directly.. and I'm wondering if someone can help me out with adding action-listeners to a JTable in Jython. I know with a button, you can just do: button = Jbutton( " Press me! ", actionPerformed = my.function ) and I know that...
[ "The list of all possible actions can be found on this page of the Java Swing tutorial. That page lists all of the listener methods in the third column. Not all of them will apply to every Swing object, but if it does apply, you can attach a listener just like the JButton examples.\nYou specifically seemed to be ...
[ 2 ]
[]
[]
[ "actionlistener", "event_handling", "jtable", "jython", "python" ]
stackoverflow_0006507688_actionlistener_event_handling_jtable_jython_python.txt
Q: I want to perform build automation using python, and it should be cross platform. Is python a good choice? I would like to automate nightly builds using python. I am new to python and will need guidance from the programmers who can help me. A: Python is a nice language for build automation. There are two python ...
I want to perform build automation using python, and it should be cross platform. Is python a good choice?
I would like to automate nightly builds using python. I am new to python and will need guidance from the programmers who can help me.
[ "Python is a nice language for build automation. There are two python based build systems, Scons and Waf, that will ease the job for you.\n", "If your project have already any build system (automake, cmake, msbuild, ant, maven.. you name it), you can use some ready CI solution. There is some choice here, includin...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006503927_python.txt
Q: I've added style=wx.te_Multiline to my wx.textctrl item but my scroll bar is not working I would like for my TextCtrl field to gain a vertical scroll as I write events out on it. The code I have so far is; sizer = wx.BoxSizer(wx.VERTICAL) #Create a vertical sizer #Create our multiline console area self....
I've added style=wx.te_Multiline to my wx.textctrl item but my scroll bar is not working
I would like for my TextCtrl field to gain a vertical scroll as I write events out on it. The code I have so far is; sizer = wx.BoxSizer(wx.VERTICAL) #Create a vertical sizer #Create our multiline console area self.term = wx.TextCtrl(self, -1, '', style=wx.TE_MULTILINE) #Add our console to the sizer sizer...
[ "Those three buttons are children of self.panel, which is just hanging out in your frame, intercepting your mouse events. If you allow resizing, you'll see that the panel is not resized along with the buttons, but you can click on the portion of the TextCtrl that extends beyond it. \nYou can either get rid of the...
[ 2 ]
[]
[]
[ "python", "user_interface", "wxpython", "wxwidgets" ]
stackoverflow_0006508976_python_user_interface_wxpython_wxwidgets.txt
Q: subscripting python module I'm probably not using the right terminology, but I'm learning python and I'm trying something that I can easily do in Lua: def fire(self): return self._loadModule()[self._entrypoint]() #subscripting the module raises an error def _loadModule(self): return __import__(sel...
subscripting python module
I'm probably not using the right terminology, but I'm learning python and I'm trying something that I can easily do in Lua: def fire(self): return self._loadModule()[self._entrypoint]() #subscripting the module raises an error def _loadModule(self): return __import__(self._module) I want to load the m...
[ "If I understand it right; a completely useless example:\ndef my_sqrt(num):\n import math #load a module\n return math.sqrt(num) #call the function\n\nFrom string:\n>>> def f(module, function, *args):\n... return(getattr(__import__(module), function)(*args))\n... \n>>> f(\"math\", \"sqrt\", 2)\n1.41421356...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006509967_python.txt
Q: python: How many write access needed to write XML I am writing a python module that writes data into an XML file. The piece of code that handles the write is: from xml.dom.minidom import Document #using DOMXml main = Document() #create an XML Document toFile = open('output.xml','w') main.writexml(toFile, indent...
python: How many write access needed to write XML
I am writing a python module that writes data into an XML file. The piece of code that handles the write is: from xml.dom.minidom import Document #using DOMXml main = Document() #create an XML Document toFile = open('output.xml','w') main.writexml(toFile, indent =' ', newl="\n") #writexml() is the operation from ...
[ "Run the program under strace to find out.\n" ]
[ 3 ]
[]
[]
[ "gentoo", "python" ]
stackoverflow_0006509715_gentoo_python.txt
Q: KeyboardInterrupt unpredictable in Python 2.7 under ipython, how can I make it *always* abort current evaluation? I'm writing python code to do numerical analysis, and I've been using ipython or ipython -pylab as my command line interface. I often run into situations where some code is taking for-freaking-ever to ...
KeyboardInterrupt unpredictable in Python 2.7 under ipython, how can I make it *always* abort current evaluation?
I'm writing python code to do numerical analysis, and I've been using ipython or ipython -pylab as my command line interface. I often run into situations where some code is taking for-freaking-ever to run, and I need to stop it. However, Ctrl-C is problematic; sometimes it works, sometimes it doesn't do anything, and s...
[ "You are probably running a background thread that is swallowing the signal, there is no real way of prohibiting that, compare http://www.dabeaz.com/python/GIL.pdf\n" ]
[ 1 ]
[]
[]
[ "abort", "ipython", "keyboardinterrupt", "python" ]
stackoverflow_0006510138_abort_ipython_keyboardinterrupt_python.txt
Q: Changing a library's name in Python I have a rather large personal python library that I use for projects. I want to release it to the public, but first I wanted to change the name to something a little less silly then the personal anecdote that I named it after. Lets say I have a library name "FooBarLib" and it ...
Changing a library's name in Python
I have a rather large personal python library that I use for projects. I want to release it to the public, but first I wanted to change the name to something a little less silly then the personal anecdote that I named it after. Lets say I have a library name "FooBarLib" and it is contained within the folder "FooBarLib...
[ "Consider using rope or some other refactoring system to help. IDE's are better at this sort of thing because they're configured to know something about how code is being imported.\nThat said, it would be perfectly reasonable searching for FooBarLib and replacing with NewLibName (as long as FooBarLib was a pretty u...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006510064_python.txt
Q: __setattr__ only when attribute does not exist If one overrides the magic method __getattr__ in a class, the overridden method is called only when the attribute is not found, otherwise default behavior occurs. But this does not seem to be the case with __setattr__, it affects all attributes. What I am looking for ...
__setattr__ only when attribute does not exist
If one overrides the magic method __getattr__ in a class, the overridden method is called only when the attribute is not found, otherwise default behavior occurs. But this does not seem to be the case with __setattr__, it affects all attributes. What I am looking for is something which behaves normally when the attribu...
[ "class ClassName(object):\n def __setattr__(self, name, value)\n if hasattr(self, name):\n super(ClassName, self).__setattr__(name, value)\n else:\n magic\n\n", "You could use a custom __getattr__ to know if the attribute exists or not.\nTo set the attribute with default beh...
[ 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006510090_python.txt
Q: Django Filter Provides Unexpected Results Why does the following return no results: >>> count = PlayerYear.objects.filter(team__id=3128).count() >>> count # Output: 0 But this returns 32 (the number of players this year on the Admiral Farragut Academy Football team): >>> count = PlayerYear.objects.filter(team__id...
Django Filter Provides Unexpected Results
Why does the following return no results: >>> count = PlayerYear.objects.filter(team__id=3128).count() >>> count # Output: 0 But this returns 32 (the number of players this year on the Admiral Farragut Academy Football team): >>> count = PlayerYear.objects.filter(team__id=1).count() >>> count # Output: 32 Given the f...
[ "Looking at your models it looks like you should be using legacy_id in your query rather than id:\ncount = PlayerYear.objects.filter(team__legacy_id=3128).count()\n\n(Note: It appears that you have both a primary id field, and a legacy_id field in your database. You actually don't need to set ID fields manually in ...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0006510416_django_django_models_python.txt
Q: How do I update virtualenv on Ubuntu? I have installed virtualenv version 1.4.9 and the latest version is 1.6.1. How do I update to version 1.6.1. Do I have to uninstall version 1.4.9? If so, how do I uninstall it? A: Latest version is 1.6.1 use sudo pip install virtualenv it will upgrade incase you are using1.4...
How do I update virtualenv on Ubuntu?
I have installed virtualenv version 1.4.9 and the latest version is 1.6.1. How do I update to version 1.6.1. Do I have to uninstall version 1.4.9? If so, how do I uninstall it?
[ "Latest version is 1.6.1\nuse sudo pip install virtualenv it will upgrade incase you are using1.4.x version.\nIt advised to use pip over easy_install look here for the reasons\n", "no, you don't. newer installed version of virtualenv automatics override older installed version.\nif I remember currently, use this ...
[ 5, 1 ]
[]
[]
[ "python", "ubuntu", "ubuntu_11.04", "virtualenv" ]
stackoverflow_0006500110_python_ubuntu_ubuntu_11.04_virtualenv.txt
Q: Install local extras in Python setup.py of my package X uses setuptools to optionally install an extra package Y, via the extras_require parameter. Now package Y disappeared from PyPi and, as far as I can tell, from the visible Internet. easy_install X[Y] fails with error: Could not find suitable distribution for ...
Install local extras in Python
setup.py of my package X uses setuptools to optionally install an extra package Y, via the extras_require parameter. Now package Y disappeared from PyPi and, as far as I can tell, from the visible Internet. easy_install X[Y] fails with error: Could not find suitable distribution for Y. However, I still have a local cop...
[ "You could subclass setuptools.Command and then overload the default install command. Then you could have THAT execute a subprocess that installs the dependency. It's a hack, but that's what you were asking for!\nIn setup.py:\nfrom setuptools import Command\nclass MyInstallCommand(Command):\n # Overload the 'ins...
[ 1, 1 ]
[]
[]
[ "easy_install", "python", "setuptools" ]
stackoverflow_0006500216_easy_install_python_setuptools.txt
Q: in YAML with python - how can I define the types in my map? I'm stumped. here's what I want to structure my docs as: release: JULY files: # files /foo/config.py: 1.6 /bar/dao.py: 1.19 I then want to return files based on the release given in python. That part's easy, but it's retu...
in YAML with python - how can I define the types in my map?
I'm stumped. here's what I want to structure my docs as: release: JULY files: # files /foo/config.py: 1.6 /bar/dao.py: 1.19 I then want to return files based on the release given in python. That part's easy, but it's returning the Values as floats, which poses a problem. I'd like to fo...
[ "You shouldn't need to specify the type for a string, if you want to dump the float values as strings, just call str() on them first:\n>>> d = {'release': 'JULY', 'files': {'/path/file': str(1.6), '/path/file2': str(1.9)}}\n\n>>> print yaml.dump(d, default_flow_style=False)\nfiles:\n /path/file: '1.6'\n /path/fil...
[ 0, 0 ]
[]
[]
[ "python", "pyyaml", "yaml" ]
stackoverflow_0006510237_python_pyyaml_yaml.txt
Q: PYObjC NSWindow is NoneType? window = NSApplication.sharedApplication().mainWindow() window.contentView().addSubview_(chart_view) The window was made in another section and appears fine but I get this: : 'NoneType' object has no attribute 'contentView' Does anyone know why it thinks the window is "NoneT...
PYObjC NSWindow is NoneType?
window = NSApplication.sharedApplication().mainWindow() window.contentView().addSubview_(chart_view) The window was made in another section and appears fine but I get this: : 'NoneType' object has no attribute 'contentView' Does anyone know why it thinks the window is "NoneType"? Thankyou.
[ "Did you remember to connect the window outlet in the .xib?\n", "It looks like mainWindow() is returning None, which suggests that there is no active window or something like that.\n" ]
[ 0, 0 ]
[]
[]
[ "nsapplication", "nswindow", "objective_c", "pyobjc", "python" ]
stackoverflow_0006405835_nsapplication_nswindow_objective_c_pyobjc_python.txt
Q: Using mmap with popen I need to read in and process a bunch of ~40mb gzipped text files, and I need it done fast and with minimal i/o overhead (as the volumes are used by others as well). The fastest way I've found thus for this task looks like this: def gziplines(fname): f = Popen(['zcat', fname], stdout=PIP...
Using mmap with popen
I need to read in and process a bunch of ~40mb gzipped text files, and I need it done fast and with minimal i/o overhead (as the volumes are used by others as well). The fastest way I've found thus for this task looks like this: def gziplines(fname): f = Popen(['zcat', fname], stdout=PIPE) for line in f.stdout...
[ "From the mmap(2) man page:\n\n ENODEV The underlying file system of the specified file does not sup-\n port memory mapping.\n\n\nYou cannot mmap streams, only real files or anonymous swap space. You will need to read from the stream into memory yourself.\n", "Pipes aren't mmapable.\ncase MAP_PRIVATE...
[ 4, 1 ]
[]
[]
[ "mmap", "popen", "python", "subprocess", "zcat" ]
stackoverflow_0006510819_mmap_popen_python_subprocess_zcat.txt
Q: HTTPCACHE not working when deploying scrapy project to scrapyd When I try to use HTTPCACHE with scrapyd I get the following error: [scrapy] WARNING: Disabled Httpcache Middlware: unable to find scrapy.cfg file to infer project data dir A: The problem is that http caching defaults to using the relative path httpc...
HTTPCACHE not working when deploying scrapy project to scrapyd
When I try to use HTTPCACHE with scrapyd I get the following error: [scrapy] WARNING: Disabled Httpcache Middlware: unable to find scrapy.cfg file to infer project data dir
[ "The problem is that http caching defaults to using the relative path httpcache.\nThis works when you run the spider normally from the command line, but not when running it as a service.\nThe solution is to set the HTTPCACHE_DIR[docs] setting to an absolute path.\n" ]
[ 3 ]
[]
[]
[ "http_caching", "middleware", "python", "scrapy", "scrapyd" ]
stackoverflow_0006510919_http_caching_middleware_python_scrapy_scrapyd.txt
Q: Django "can't adapt type" error using mutliple databases (Postgresql 8.4 and sqlite3) Short Description Using a local (sqlite3) database I can save and extract information, however when using my production sever (postgresql 8.4 on a different machine) Django throws a "can't adapt type" error. Can someone help poi...
Django "can't adapt type" error using mutliple databases (Postgresql 8.4 and sqlite3)
Short Description Using a local (sqlite3) database I can save and extract information, however when using my production sever (postgresql 8.4 on a different machine) Django throws a "can't adapt type" error. Can someone help point me in a good direction to start debugging this? Background The python project uses Dja...
[ "Turns out that sqlite3 ignores and or tries to convert a value to a string when using it in a Django filter. From the GUI I was passing in the actual chassis object rather than the serial number. Postgresql threw the error when trying to use a Chassis object as a serial number while sqlite3 ignored it and cast i...
[ 6 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0006510529_database_django_python.txt
Q: Problem with the depth of nested elements inside list/tuple Typing first time here, before i found many helpful tips in stackoverflow, right now i have black hole in my brain and can't figure out how to solve this: i got: dirlist = ['dir1', 'dir2', 'dir3', 'dir4'] print [('a','b','c'),('x','y','z'),[('/tmp...
Problem with the depth of nested elements inside list/tuple
Typing first time here, before i found many helpful tips in stackoverflow, right now i have black hole in my brain and can't figure out how to solve this: i got: dirlist = ['dir1', 'dir2', 'dir3', 'dir4'] print [('a','b','c'),('x','y','z'),[('/tmp/9/', 'X', e) for e in dirlist ] ] ant it outputs: [('a', 'b', '...
[ "print [('a', 'b', 'c'), ('x', 'y', 'z')] + [('/tmp/9/', 'X', e) for e in dirlist]\n\n" ]
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0006511027_python.txt
Q: Python - Why is this happening? I am new to Python, and noticed something I believe its a bug. Edit 2011-09-30: Forget it. Now I know the attributes created are static and shared between the instances. Hope this thread helps another python newbies in the same situation as mine. Consider the following code: class t...
Python - Why is this happening?
I am new to Python, and noticed something I believe its a bug. Edit 2011-09-30: Forget it. Now I know the attributes created are static and shared between the instances. Hope this thread helps another python newbies in the same situation as mine. Consider the following code: class test(): dictionary1 = {} list...
[ "All your instances of test class share the same dictionary and list. The correct way to initialize the members would be:\nclass Test():\n def __init__(self):\n self.dictionary1 = {}\n self.list1 = []\n\nAttributes assigned directly in the class body will be evaluated once and then shared between a...
[ 14, 7, 5 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0006510539_dictionary_python.txt
Q: Check if a request referer is a search engine Does anyone know a reliable way to check whether the referrer of a HTTP request was a search engine or not? Thanks A: Here is a Django middleware object that offers this functionality: http://djangosnippets.org/snippets/197/ . The logic can be extracted to work in a ...
Check if a request referer is a search engine
Does anyone know a reliable way to check whether the referrer of a HTTP request was a search engine or not? Thanks
[ "Here is a Django middleware object that offers this functionality: http://djangosnippets.org/snippets/197/ . The logic can be extracted to work in a non-Django Python setting.\nThe method used here is to check the referring url to determine if it matches a given pattern (the presence of a parameter 'q', for exampl...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0006511212_python.txt
Q: creating a temporary file in python with FUSE I am trying to write a program using python-fuse, but I can't get file writing down. my file_class looks like this class FuseFile(object): def __init__(self, path, flags, *mode): debug(path) #debug(mode); self.file = tempfile.TemporaryFile(*mode); self...
creating a temporary file in python with FUSE
I am trying to write a program using python-fuse, but I can't get file writing down. my file_class looks like this class FuseFile(object): def __init__(self, path, flags, *mode): debug(path) #debug(mode); self.file = tempfile.TemporaryFile(*mode); self.fd = self.file.fileno() self.path = path def w...
[ "I eventually found out that the probelm was that I hadn't created a open(), or create() method in my file class, but eventually I settled with implementing all the methods in the main FUSE class because the file_class didn't seem to be working for me\n" ]
[ 2 ]
[]
[]
[ "fuse", "python", "temporary_files" ]
stackoverflow_0006492290_fuse_python_temporary_files.txt
Q: Python compresses entire directory rather than the sole files I have written a python script which i use in automator to compress files. the problems is that when i compress them the entire directory(meaning all the folders) + the files are compressed rather than just the files by themselves. So if i ran this on m...
Python compresses entire directory rather than the sole files
I have written a python script which i use in automator to compress files. the problems is that when i compress them the entire directory(meaning all the folders) + the files are compressed rather than just the files by themselves. So if i ran this on my desktop with two files as args, test1 and test2 the output would ...
[ "In your for loop, Instead of this - \nzf.write(f)\n\nTry this - \nzf.write(f, os.path.basename(f), zipfile.ZIP_DEFLATED)\n\n" ]
[ 2 ]
[]
[]
[ "automator", "compression", "directory", "python", "zip" ]
stackoverflow_0006511548_automator_compression_directory_python_zip.txt
Q: Find a particular list inside a list of lists I got two different lists (let's call them A and B) of lists and I have to find the elements that are in B and not in A and viceversa. The lists inside the two main lists can be unordered and they basically contains strings. I'm looking for a code or an hint to solve t...
Find a particular list inside a list of lists
I got two different lists (let's call them A and B) of lists and I have to find the elements that are in B and not in A and viceversa. The lists inside the two main lists can be unordered and they basically contains strings. I'm looking for a code or an hint to solve this problem. EDIT: I didn't post the code because ...
[ "If your two lists are l1 and l2:\nset(l1).symmetric_difference(set(l2))\n\nor\nset(l1) - set(l2)\n\ndepending on what you need.\nWhich won't work because lists aren't hashable... If the elements inside the lists are hashable then use the following:\n[list(x) for x in set([frozenset(x) for x in l1]) ^ set([frozense...
[ 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006509062_list_python.txt
Q: How do you cross-check a dictionary with a list in Python? Say I have a list list: [keith, roger, david], [5, nobody, 31], [attack, thomas, 4] and a dictionary dictionary: '55': <Trachea>, 'Roger': <Bert> I want to delete the items in the dictionary that don't match up with the SECOND part of the list of lists. ...
How do you cross-check a dictionary with a list in Python?
Say I have a list list: [keith, roger, david], [5, nobody, 31], [attack, thomas, 4] and a dictionary dictionary: '55': <Trachea>, 'Roger': <Bert> I want to delete the items in the dictionary that don't match up with the SECOND part of the list of lists. In this example, I'd want to get rid of '55': but not 'Roger': ...
[ "#!/usr/bin/python3\n\n# myList = [['keith', 'roger', 'david'], [5, 'nobody', 31], ['attack', 'thomas', 4]]\n# myDict = {'55': '...', 'roger': '...'}\n\nsecondElements = {x[1] for x in myList}\n\nfilteredDict = {k:v for k,v in myDict.items() if (k in secondElements)}\n\nprint(filteredDict)\n# prints: {'roger': '......
[ 5, 2, 0, 0 ]
[ ">>> dict_ = {'Roger': 'Bert', 55: 'trachea'}\na=[['keith', 'roger', 'david'], [5, 'nobody', 31], ['attack', 'thomas', 4]]\n>>> def delete(x):\n... del dict_[x]\n\n>>> map(lambda x: delete(x),filter(lambda x:x not in a[1],dict_))\n" ]
[ -1 ]
[ "dictionary", "list", "python" ]
stackoverflow_0006510437_dictionary_list_python.txt
Q: Eclipse camelcase python method name search Currently doing some re-factoring and am trying to get a regex pattern that can return any method that is camel case. I am going to be using the regex option in eclipse search files. def thisIsATest(self): pass def this_is_a_test(self): pass def this(self): ...
Eclipse camelcase python method name search
Currently doing some re-factoring and am trying to get a regex pattern that can return any method that is camel case. I am going to be using the regex option in eclipse search files. def thisIsATest(self): pass def this_is_a_test(self): pass def this(self): pass I would want the search to obviously pick u...
[ "Edit: Oops you wanted camel case... Fixed (again):\ndef\\s+(?=[a-z]+(?:[A-Z][a-z0-9]+)*\\s*\\().*?\\(\n\nEdit: To exclude single words I use a + instead of a *.\ndef\\s+(?=[a-z]+(?:[A-Z][a-z0-9]+)+\\s*\\().*?\\(\n\n" ]
[ 2 ]
[]
[]
[ "eclipse", "python", "regex" ]
stackoverflow_0006512027_eclipse_python_regex.txt
Q: Get everything that a Many-To-Many Field does not point to Right now my Model looks a little something like this: PageView: ... userList = models.ManytoManyField("core.UserProfile") UserProfile: ... pageView = models.OnetoOneField(PageView) The idea is that a UserProfile has a reference to a Page...
Get everything that a Many-To-Many Field does not point to
Right now my Model looks a little something like this: PageView: ... userList = models.ManytoManyField("core.UserProfile") UserProfile: ... pageView = models.OnetoOneField(PageView) The idea is that a UserProfile has a reference to a PageView that they own. PageView references many profiles, and those...
[ "UserProfile.objects.exclude(id__in=chris.pageView.userList.all())\n\n" ]
[ 2 ]
[]
[]
[ "django", "many_to_many", "python" ]
stackoverflow_0006511982_django_many_to_many_python.txt
Q: Unable to read HTML data - Python I am attempting to parse html data from a website using BeautifulSoup for python. However, urllib2 or mechanize is not able to read the whole html format. The returned data is <html> <head> <title> EC 4.1.2.13 - Fructose-bisphosphate aldolase </title> <meta name="d...
Unable to read HTML data - Python
I am attempting to parse html data from a website using BeautifulSoup for python. However, urllib2 or mechanize is not able to read the whole html format. The returned data is <html> <head> <title> EC 4.1.2.13 - Fructose-bisphosphate aldolase </title> <meta name="description" content="Information on EC ...
[ "That's because the content is in the frames. You can either parse the page and look for the src attribute of the main <frame> element or directly request the frame. In most browsers, you can right-click and select \"Frame Properties\" or so to get the frame's URL.\n" ]
[ 3 ]
[]
[]
[ "html", "mechanize", "python", "urllib2" ]
stackoverflow_0006512242_html_mechanize_python_urllib2.txt
Q: How to Find a String in a Text File And Replace Each Time With User Input in a Python Script? I am new to python so excuse my ignorance. Currently, I have a text file with some words marked as <>. My goal is to essentially build a script which runs through a text file with such marked words. Each time the script f...
How to Find a String in a Text File And Replace Each Time With User Input in a Python Script?
I am new to python so excuse my ignorance. Currently, I have a text file with some words marked as <>. My goal is to essentially build a script which runs through a text file with such marked words. Each time the script finds such a word, it would ask the user for what it wants to replace it with. For example, if I had...
[ "import re\nwith open('in.txt') as infile:\n text = infile.read()\nsearch = re.compile('<<([^>]*)>>')\ntext = search.sub(lambda m: raw_input(m.group(1) + '? '), text)\nwith open('out.txt', 'w') as outfile:\n outfile.write(text)\n\n", "To open a file and loop through it:\nUse raw_input to get input from user...
[ 8, 1, 1, 1, 0 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0006512131_python_replace.txt
Q: Accept a range of numbers in the form of 0-5 using Python's argparse? Using argparse, is there a way to accept a range of numbers and convert them into a list? For example: python example.py --range 0-5 Is there some way input a command line argument in that form and end up with: args.range = [0,1,2,3,4,5] And a...
Accept a range of numbers in the form of 0-5 using Python's argparse?
Using argparse, is there a way to accept a range of numbers and convert them into a list? For example: python example.py --range 0-5 Is there some way input a command line argument in that form and end up with: args.range = [0,1,2,3,4,5] And also have the possibility to input --range 2 = [2]?
[ "You could just write your own parser in the type argument, e.g.\nfrom argparse import ArgumentParser, ArgumentTypeError\nimport re\n\ndef parseNumList(string):\n m = re.match(r'(\\d+)(?:-(\\d+))?$', string)\n # ^ (or use .split('-'). anyway you like.)\n if not m:\n raise ArgumentTypeError(\"'\" + s...
[ 26, 8 ]
[]
[]
[ "argparse", "python" ]
stackoverflow_0006512280_argparse_python.txt
Q: Beanstalkc Timeout Question I am using beanstalkc in Python for a queuing process for a program which has to parse a list of URLs. Hence I am using timeout in beanstalk for avoiding huge time consumption by any URL. But even after using it my process doesn't time out in the limit and is taking a lot of time for pa...
Beanstalkc Timeout Question
I am using beanstalkc in Python for a queuing process for a program which has to parse a list of URLs. Hence I am using timeout in beanstalk for avoiding huge time consumption by any URL. But even after using it my process doesn't time out in the limit and is taking a lot of time for parsing few URLs. I am using the fo...
[ "I think you are misunderstanding the purpose of beanstalkd's TTR timeouts. Quoting the beanstalkd FAQ:\n\nHow does TTR work\nTTR only applies to a job at the moment it becomes reserved. At that event, a timer (called “time-left” in the job stats) starts counting down from the job’s TTR.\n\nIf the timer reaches zer...
[ 3 ]
[]
[]
[ "beanstalkc", "beanstalkd", "python" ]
stackoverflow_0006504114_beanstalkc_beanstalkd_python.txt
Q: HTML Parsing Table - BeautifulSoup I am attempting to parse the second table seen below using BeautifulSoup. I am having trouble identifying the second table verses the first because the tables attributes are the exact same. How do I access the information in the table such as name = PATHWAY? What I have used so f...
HTML Parsing Table - BeautifulSoup
I am attempting to parse the second table seen below using BeautifulSoup. I am having trouble identifying the second table verses the first because the tables attributes are the exact same. How do I access the information in the table such as name = PATHWAY? What I have used so far to attempt to access the table is: ta...
[ "Mu Mind has it right: find the \"a\" then traverse back up to the parent\nsoup.find(attrs={\"name\":\"PATHWAY\"}).findParent('table')\n\nThat's the python way....There is a single xpath command but operating with xpath on axis is more complicated and only worth the effort it it has some specific use (xslt or javas...
[ 1, 0 ]
[ "First:\ntable = soup.find('table' {'name':'PATHWAY'}\n\nis no proper Python code.\nWhat should this match?\nThis will match only.\nEither you iterate through each single table and perform related check inside each table or you iterate over each single node of the tree until you find the related node and then walk...
[ -1, -1 ]
[ "beautifulsoup", "html_parsing", "python" ]
stackoverflow_0006510345_beautifulsoup_html_parsing_python.txt
Q: A logical way to compare an array of csv file paths to an array of specified project names I'm looking for a logical way to compare a csv list of projects from the user to an array of file paths I generate with glob. It however does not have to happen specifically that way, I just need to take a csv list file of p...
A logical way to compare an array of csv file paths to an array of specified project names
I'm looking for a logical way to compare a csv list of projects from the user to an array of file paths I generate with glob. It however does not have to happen specifically that way, I just need to take a csv list file of projects and work on them. CsvScrape = glob.glob('C:\Ryans_Copy_Test\*\*DATA.CSV') f...
[ "If glob returns full pathnames:\nscrape_items = map(os.path.basename, scrape_items)\nYour reader_items is probably going to be a list of a list:\nreader_items = [row[0] for row in reader_items]\nUse sets to find what's not there:\nnot_in_csv = set(reader_items).difference(scrape_items)\n", "How close would be th...
[ 1, 0 ]
[]
[]
[ "algorithm", "csv", "python", "wxpython" ]
stackoverflow_0006512374_algorithm_csv_python_wxpython.txt
Q: SQLAlchemy 0.6.5 (and 0.6.8) SessionExtension after_flush doesn't gets called I don't get it, but this code doesn't call after_flush/before_flush/after_flush_postexec # -*- coding: utf-8 -*- from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.orm.interfaces import SessionExtension class After...
SQLAlchemy 0.6.5 (and 0.6.8) SessionExtension after_flush doesn't gets called
I don't get it, but this code doesn't call after_flush/before_flush/after_flush_postexec # -*- coding: utf-8 -*- from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.orm.interfaces import SessionExtension class AfterFlushExtension(SessionExtension): def before_commit(self, session): pri...
[ "Michael Bayer answered on SQLAlchemy's mailing list https://groups.google.com/d/msg/sqlalchemy/GrMZGtJ-yc8/mCviGB6g9HYJ :\n\nThe flush events only fire off if\n there's actually something to be\n flushed. It would be inefficient for\n the events to be emitted for every\n flush() as flush is in fact called a\n...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006476652_python_sqlalchemy.txt
Q: Recommended way to do a basic search I need to do a search for the title of a video. The search will only be searching in one column of one table, so it is a very basic search. Here is what I am currently using to do the search: video_set = video_set.filter(title__icontains=search) and using print connection.quer...
Recommended way to do a basic search
I need to do a search for the title of a video. The search will only be searching in one column of one table, so it is a very basic search. Here is what I am currently using to do the search: video_set = video_set.filter(title__icontains=search) and using print connection.queries, it turns into this -- SELECT COUNT(*)...
[ "The reason people tell you to avoid doing like '%blah%' is because it's difficult to use an index when doing such a search. That means that if you don't have any other filters, it will have to do a full table scan and check each record to see if it matches your query instead of using an index. With 10,000 records,...
[ 2, 1, 0 ]
[]
[]
[ "django", "mysql", "python", "search", "sql" ]
stackoverflow_0006512966_django_mysql_python_search_sql.txt
Q: Eclipse and python: library will import in interprer, but not in IDE I'm running Windows 7, Python 2.6.4 and the latest version of Eclipse. I downloaded the boto library (http://code.google.com/p/boto/) and ran python setup.py install, which created boto-1.9b-py2.6.egg in C:\Python26\Lib\site-packages. Importing ...
Eclipse and python: library will import in interprer, but not in IDE
I'm running Windows 7, Python 2.6.4 and the latest version of Eclipse. I downloaded the boto library (http://code.google.com/p/boto/) and ran python setup.py install, which created boto-1.9b-py2.6.egg in C:\Python26\Lib\site-packages. Importing a class - say, by doing 'from boto.sqs.connection import SQSConnection' - ...
[ "From the comment so can be marked as answered\nIn Preferences->Pydev->interpreter - Python what is the System libs value \n", "For libraries that are required only in a single project, the best practice is to add them to the Project's PYTHONPATH and not the SYSTEM PYTHONPATH.\nThis is done by right clicking on t...
[ 1, 0 ]
[]
[]
[ "boto", "eclipse", "import", "pydev", "python" ]
stackoverflow_0002767808_boto_eclipse_import_pydev_python.txt
Q: Python: send executable binary file over smtp to gmail how can i change the real file extension of executable binary to send that file through gmail smtp protocol (all in python). Example: "binary" to "binary.jpg" I'll try this: import gzip, shutil src = open('3c7983cb70e9630cc4ee2fe3e1fb16c2', 'rb') dest = gzip....
Python: send executable binary file over smtp to gmail
how can i change the real file extension of executable binary to send that file through gmail smtp protocol (all in python). Example: "binary" to "binary.jpg" I'll try this: import gzip, shutil src = open('3c7983cb70e9630cc4ee2fe3e1fb16c2', 'rb') dest = gzip.open('3c7983cb70e9630cc4ee2fe3e1fb16c2.gz.jpg', 'wb') shutil...
[ "According to Google's Policy, binary files are banned.\nGmail won't accept these types of files even if they are sent in a zipped\n(.zip, .tar, .tgz, .taz, .z, .gz) format. If this type of message is sent to \nyour Gmail address, it is bounced back to the sender automatically. \n\nSo Google is unzipping your file ...
[ 5 ]
[]
[]
[ "executable", "gmail", "python", "smtplib" ]
stackoverflow_0006513185_executable_gmail_python_smtplib.txt
Q: python, sqlite error? db is locked? but it isnt? I get "database table is locked" error in my sqlite3 db. My script is single threaded, no other app is using the program (i did have it open once in "SQLite Database Browser.exe"). I copied the file, del the original (success) and renamed the copy so i know no proce...
python, sqlite error? db is locked? but it isnt?
I get "database table is locked" error in my sqlite3 db. My script is single threaded, no other app is using the program (i did have it open once in "SQLite Database Browser.exe"). I copied the file, del the original (success) and renamed the copy so i know no process is locking it yet when i run my script everything i...
[ "I have run into this problem before also. It occurs often when you have a cursor and connection open and then your program crashes before you can close it properly. In some cases the following function can be used to make sure that the database is unlocked, even after it was not properly committed and closed bef...
[ 4, 2, 2, 0 ]
[]
[]
[ "locking", "python", "sqlite" ]
stackoverflow_0000531711_locking_python_sqlite.txt
Q: Can I cherry-pick packages from site-packages in a virtualenv? So I'm working on migrating a Django project to virtualenv/pip. I'd like to use --no-site-packages for the most control over the environment, but the sticking point appears to be PIL. Given that PIL is notoriously difficult to install with pip, especia...
Can I cherry-pick packages from site-packages in a virtualenv?
So I'm working on migrating a Django project to virtualenv/pip. I'd like to use --no-site-packages for the most control over the environment, but the sticking point appears to be PIL. Given that PIL is notoriously difficult to install with pip, especially as there are Windows users on the team, I'd rather use that one ...
[ "You can put a PIL.pth file in the virtualenv's site-packages (or wherever on the sys.path) to add the name of the PIL directory, which will be appended to sys.path. Here on linux PIL already uses a .pth file, so it's just a matter of copying it and making the path absolute.\n" ]
[ 4 ]
[]
[]
[ "pip", "python", "python_imaging_library", "virtualenv" ]
stackoverflow_0006513725_pip_python_python_imaging_library_virtualenv.txt
Q: replace URLs in text with links to URLs Using Python I want to replace all URLs in a body of text with links to those URLs, like what Gmail does. Can this be done in a one liner regular expression? Edit: by body of text I just meant plain text - no HTML A: You can load the document up with a DOM/HTML parsing lib...
replace URLs in text with links to URLs
Using Python I want to replace all URLs in a body of text with links to those URLs, like what Gmail does. Can this be done in a one liner regular expression? Edit: by body of text I just meant plain text - no HTML
[ "You can load the document up with a DOM/HTML parsing library ( see html5lib ), grab all text nodes, match them against a regular expression and replace the text nodes with a regex replacement of the URI with anchors around it using a PCRE such as:\n/(https?:[;\\/?\\\\@&=+$,\\[\\]A-Za-z0-9\\-_\\.\\!\\~\\*\\'\\(\\)%...
[ 11, 7, 1, 0, 0 ]
[]
[]
[ "hyperlink", "python", "regex", "url" ]
stackoverflow_0001727535_hyperlink_python_regex_url.txt
Q: Accept parameters only from POST request in python Is there a way to accept parameters only from POST request? If I use cgi.FieldStorage() from cgi module, it accepts parameters from both GET and POST request. A: By default, most things in the cgi module merge os.environ['QUERY_STRING'] and sys.stdin (in the for...
Accept parameters only from POST request in python
Is there a way to accept parameters only from POST request? If I use cgi.FieldStorage() from cgi module, it accepts parameters from both GET and POST request.
[ "By default, most things in the cgi module merge os.environ['QUERY_STRING'] and sys.stdin (in the format suggested by os.environ['CONTENT_TYPE']). So the simple solution would be to modify os.environ, or rather, provide an alternative, with no query string. \n# make a COPY of the environment\nenviron = dict(os.en...
[ 2, 0 ]
[]
[]
[ "cgi", "post", "python" ]
stackoverflow_0006513143_cgi_post_python.txt
Q: Accessing Entry widget information: tkinter python I am writing a Tkinter program and have a root where a labels are displayed next to entry widgets. EX: Name -> SearchTerm ENTRY BOX I am trying to create a list of values from entry wigets (EX: ['', 'user input', 'user input']) I have created the entry widgets i...
Accessing Entry widget information: tkinter python
I am writing a Tkinter program and have a root where a labels are displayed next to entry widgets. EX: Name -> SearchTerm ENTRY BOX I am trying to create a list of values from entry wigets (EX: ['', 'user input', 'user input']) I have created the entry widgets in the root and then have a function that gets the values...
[ "Button commands don't \"return\". They do, but they return to the event loop so there's nothing there to process whatever it is that is returned.\nThat being said, it's hard to know what you are asking. You say \"I can't access the returned information from the function\" but I see no reason why not. If you call i...
[ 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006512557_python_tkinter.txt
Q: How would you create a comma-delimited string from a pyodbc result row? I have a resultset of rows stored in cursor.rows which are returned from a pyodbc.cursor.execute command. What is the fastest way to unpack this data and place it into a list of comma-seperated strings (or unpack into a custom object)? Current...
How would you create a comma-delimited string from a pyodbc result row?
I have a resultset of rows stored in cursor.rows which are returned from a pyodbc.cursor.execute command. What is the fastest way to unpack this data and place it into a list of comma-seperated strings (or unpack into a custom object)? Currently I am doing the following: cursor.execute(query_str) f = open(out_file, 'w'...
[ "I'd use the csv module:\nimport csv\n\ncursor.execute(query_str)\nwith open(out_file, 'w') as f:\n csv.writer(f, quoting=csv.QUOTE_NONE).writerows(cursor)\n\nBeware that if you csv.QUOTE_NONE a csv.Error is raised if there's a comma in a data field. The sane way would be to csv.QUOTE_MINIMAL at least.\n" ]
[ 13 ]
[]
[]
[ "python" ]
stackoverflow_0006513588_python.txt
Q: How to determine if a wx control is disabled How can I programmatically determine if a particular control (In my case a wx CheckBox) is disabled? I don't see that the widget has a "disabled" property or "isDisabled" method. A: IsEnabled exists, so you can do: if not widget.IsEnabled(): # do something http:...
How to determine if a wx control is disabled
How can I programmatically determine if a particular control (In my case a wx CheckBox) is disabled? I don't see that the widget has a "disabled" property or "isDisabled" method.
[ "IsEnabled exists, so you can do:\nif not widget.IsEnabled():\n # do something\n\nhttp://docs.wxwidgets.org/stable/wx_wxwindow.html#wxwindowisenabled\n" ]
[ 7 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006514141_python_wxpython.txt
Q: HTTPS session reuse in Python I would like to be able to use parallel requests to a HTTPS server. Currently, I am using PyCURL, but it isn't able of reusing the same SSL session ID between different handles, and each handle can only take care of one download/upload each time. Taking into account the negotiation ta...
HTTPS session reuse in Python
I would like to be able to use parallel requests to a HTTPS server. Currently, I am using PyCURL, but it isn't able of reusing the same SSL session ID between different handles, and each handle can only take care of one download/upload each time. Taking into account the negotiation takes time (specially because client ...
[ "Reusing session ids isn't currently easily accessible as noted here, I haven't heard of any simple solution for this - but it should just be a matter of saving your context after the initial handshake and reusing it. \nPyOpenSSL exposes these mechanisms, but at a lower level than most people would want. I'd put my...
[ 1 ]
[]
[]
[ "https", "python", "sessionid" ]
stackoverflow_0006489894_https_python_sessionid.txt
Q: python noob question about codecs and utf-8 Using python to pick it some pieces so definitely a noob ? here but didn't seeing a satisfactory answer. I have a json utf-8 file with some pieces that have grave's, accute's etc.... I'm using codecs and have (for example): str=codecs.open('../../publish_scripts/location...
python noob question about codecs and utf-8
Using python to pick it some pieces so definitely a noob ? here but didn't seeing a satisfactory answer. I have a json utf-8 file with some pieces that have grave's, accute's etc.... I'm using codecs and have (for example): str=codecs.open('../../publish_scripts/locations.json', 'r','utf-8') locations=json.load(str) f...
[ "codec.open() will decode the contents of the file using the codec you supplied (utf-8). You then have a python unicode object (which behaves similarly to a string object).\nPrinting a unicode object will cause an implict (behind-the-scenes) encode using the default codec, which is usually ascii. If ascii cannot en...
[ 3, 2, 0, 0 ]
[]
[]
[ "python", "utf_8" ]
stackoverflow_0006514179_python_utf_8.txt
Q: Apache mod_wsgi and python 2.7 My WSGI installation uses python2.6 and my django project requires python 2.7 to work properly. Is is possible to relink the python version WSGI uses without recompiling wsgi? I've been having some odd errors trying to compile wsgi and I'd prefer to sidestep that whole troubleshootin...
Apache mod_wsgi and python 2.7
My WSGI installation uses python2.6 and my django project requires python 2.7 to work properly. Is is possible to relink the python version WSGI uses without recompiling wsgi? I've been having some odd errors trying to compile wsgi and I'd prefer to sidestep that whole troubleshooting process if possible. Thanks
[ "To answer the specific question, no it is not possible to make a mod_wsgi installation compiled for one Python version to use a different version at run time.\nWhy don't you create a separate question for the actual problem you are having with compiling from source code. Better still ask it on the mod_wsgi mailing...
[ 4, 3 ]
[]
[]
[ "apache", "django", "python", "wsgi" ]
stackoverflow_0006509571_apache_django_python_wsgi.txt
Q: Capturing images with OpenCV 2.2 and Python on Linux (Fedora 15 Beta) I have the code below ; import cv import time cv.NamedWindow("camera", 1) capture = cv.CaptureFromCAM(0) while True: img = cv.QueryFrame(capture) cv.ShowImage("camera", img) if cv.WaitKey(10) == 27: break The above code is Op...
Capturing images with OpenCV 2.2 and Python on Linux (Fedora 15 Beta)
I have the code below ; import cv import time cv.NamedWindow("camera", 1) capture = cv.CaptureFromCAM(0) while True: img = cv.QueryFrame(capture) cv.ShowImage("camera", img) if cv.WaitKey(10) == 27: break The above code is OpenCV-2.2's own CAM capture script for Python. So I know nothing is wrong wi...
[ "That symbol should be provided by the package gstreamer-plugins-base.\nCheck if you have it installed. If you do have it, it means your version of this package is older than what OpenCV 2.2 needs. It's best to update the entire GStreamer on your platform just to be sure.\n", "Try using a different camera index\...
[ 2, 0 ]
[]
[]
[ "fedora", "linux", "opencv", "python", "webcam" ]
stackoverflow_0005834234_fedora_linux_opencv_python_webcam.txt
Q: Exposing a new type to python at run time I have gone through and defined my new types, stored them in a pytypeobject and called the following functions (after initializing the interpreter): PyType_Ready(); //this takes my defined typed PyModule_AddObject(); //this adds the defined type to a module I created using...
Exposing a new type to python at run time
I have gone through and defined my new types, stored them in a pytypeobject and called the following functions (after initializing the interpreter): PyType_Ready(); //this takes my defined typed PyModule_AddObject(); //this adds the defined type to a module I created using PyModule_Create(); Now w...
[ "So I figured out what I needed to do, I had to call a function before Py_Initialize,\nPyImport_AppendInittab( ModuleName, ModuleInitFunction );\n\nThis adds the module name to the python module dictionary so when you call import ModuleName, if it is for the first time it will call the ModuleInitFunction ( which I ...
[ 2 ]
[]
[]
[ "c", "module", "python", "python_extensions", "runtime" ]
stackoverflow_0006499531_c_module_python_python_extensions_runtime.txt
Q: How can I redirect Python's getpass() to stderr? I'm trying to write a program that is going to print its prompts to standard error, and its output to standard out so that I can later manipulate the output. I'm a bit new to python, but the documentation for getpass() shows I should be able to select a stream: get...
How can I redirect Python's getpass() to stderr?
I'm trying to write a program that is going to print its prompts to standard error, and its output to standard out so that I can later manipulate the output. I'm a bit new to python, but the documentation for getpass() shows I should be able to select a stream: getpass.getpass([prompt[, stream]]) I have tried a varie...
[ "the stream argument to getpass.getpass() was added in python 2.5, and isn't available in prior versions.\n" ]
[ 5 ]
[]
[]
[ "python", "stderr" ]
stackoverflow_0006514465_python_stderr.txt
Q: Making cgi.FieldStorage Store User Inputs? I wrote a simple Python CGI script but it has a bug : #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout num1 = random.randrange(1,11) num2 = random.randrange(1,11) answer = num1 + num2 print("Content-type: text/html\n") print("<code>%d + %d :</code>")...
Making cgi.FieldStorage Store User Inputs?
I wrote a simple Python CGI script but it has a bug : #!/usr/bin/python2.7 import cgi,sys,random sys.stderr = sys.stdout num1 = random.randrange(1,11) num2 = random.randrange(1,11) answer = num1 + num2 print("Content-type: text/html\n") print("<code>%d + %d :</code>") % (num1,num2) print(""" <form method=POST actio...
[ "You have a couple of options. One is beaker. It's a WSGI middleware designed to do caching and session storage. Not sure how it integrates with a regular CGI app, but shouldn't be too difficult. This would close to PHP's session_start() and storing things in $_SESSION. Beaker has a number of ways to store session ...
[ 0 ]
[]
[]
[ "cgi", "python", "session" ]
stackoverflow_0005679333_cgi_python_session.txt
Q: Python Pickle Load Takes Longer Each Iteration I have a gzip'd pickled file that is 4mb in size. Each time I open the file and load it the time it takes to unpickle takes longer. The contents of the file never change and the size stays the same. Test Times: 1st Run: 27.5s 2nd Run: 44.1s 3rd Run: 52.7s The code I'm...
Python Pickle Load Takes Longer Each Iteration
I have a gzip'd pickled file that is 4mb in size. Each time I open the file and load it the time it takes to unpickle takes longer. The contents of the file never change and the size stays the same. Test Times: 1st Run: 27.5s 2nd Run: 44.1s 3rd Run: 52.7s The code I'm using is as follows: f = gzip.open( filepath, "rb" ...
[ "I created two test pickle file 3MBs and 22MBs, and zipped it. \nI don't understand what you are doing because I just did a test and this code:\ndef get_time():\n return int(time.time())\n\nwhile(count < 10): \n filepath='/home/shared/word_out.gz'\n start = get_time()\n f = gzip.open( filepath, \"rb...
[ 0 ]
[]
[]
[ "gzip", "pickle", "python" ]
stackoverflow_0006514788_gzip_pickle_python.txt
Q: Profiling SQL query I'm using sqlalchemy (expression language, not full ORM) with MySQL and experiencing some unexpected slowness. Particularly, the time spent performing a select query in by sqlalchemy is ten times greater than the time spent performing the same query from the mysql command line. Output from cpr...
Profiling SQL query
I'm using sqlalchemy (expression language, not full ORM) with MySQL and experiencing some unexpected slowness. Particularly, the time spent performing a select query in by sqlalchemy is ten times greater than the time spent performing the same query from the mysql command line. Output from cprofile: ncalls tottime p...
[ "One possible reason for slowness - Does sql alchemy use prepared statements? If yes, then a reason why you may be experiencing a difference in performance is because the mysql optimizer has different information when creating the two query plans.\nWhen you run the query from the command-line, the mysql optimizer h...
[ 1 ]
[]
[]
[ "python", "sql", "sqlalchemy" ]
stackoverflow_0005941234_python_sql_sqlalchemy.txt
Q: How to fix premature convergence in simple GA (Python)? Yesterday i started exploring the genetic algorithms, and when i ended up with some basic theory, i tried to write simple GA on Python, that solves Diophantine equation. I'm new to Python and GAs, so please, don't judge my code strictly. Problem I cant get an...
How to fix premature convergence in simple GA (Python)?
Yesterday i started exploring the genetic algorithms, and when i ended up with some basic theory, i tried to write simple GA on Python, that solves Diophantine equation. I'm new to Python and GAs, so please, don't judge my code strictly. Problem I cant get any result due to premature convergence (there is some no-retur...
[ "Slight logic error: parentTwo is slightly more likely to be the father than the mother. Even odds would be randint (1,100) <= 50, not randint (1,100) < 50. Won't be what's causing the issue here.\n\nYour population size is fairly small. 40 is very few for most problems. That will cause it to converge quickly. \nE...
[ 3 ]
[]
[]
[ "artificial_intelligence", "genetic_algorithm", "genetic_programming", "python" ]
stackoverflow_0006512275_artificial_intelligence_genetic_algorithm_genetic_programming_python.txt
Q: ctypes pointer to numpy array with custom dtype I have a numpy array with a custom dtype: a = np.zeros(100, dtype=np.dtype([('one',np.double),('two',np.int)])) a['one']=np.arange(100) a['two']=np.arange(100)*-1 I want to create a ctypes pointer that I can pass to a C library. The problem is that the C library exp...
ctypes pointer to numpy array with custom dtype
I have a numpy array with a custom dtype: a = np.zeros(100, dtype=np.dtype([('one',np.double),('two',np.int)])) a['one']=np.arange(100) a['two']=np.arange(100)*-1 I want to create a ctypes pointer that I can pass to a C library. The problem is that the C library expects just a pointer to a double array, the 'one' fiel...
[ "You are going to have to copy the data to a contiguous array.\none = np.ascontiguousarray(a['one'])\none.ctypes.data_as(ctypes.POINTER(ctypes.c_double))\n\n" ]
[ 1 ]
[]
[]
[ "ctypes", "numpy", "python" ]
stackoverflow_0006514856_ctypes_numpy_python.txt
Q: how code a Image button in PyQt? Im trying to do simple audio player, but I want use a image(icon) as a pushbutton. A: You can subclass QAbstractButton and make a button of your own. Here is a basic simple example: import sys from PyQt4.QtGui import * class PicButton(QAbstractButton): def __init__(self, pix...
how code a Image button in PyQt?
Im trying to do simple audio player, but I want use a image(icon) as a pushbutton.
[ "You can subclass QAbstractButton and make a button of your own. Here is a basic simple example:\nimport sys\nfrom PyQt4.QtGui import *\n\nclass PicButton(QAbstractButton):\n def __init__(self, pixmap, parent=None):\n super(PicButton, self).__init__(parent)\n self.pixmap = pixmap\n\n def paintEv...
[ 28, 5, 4, 4, 1 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt" ]
stackoverflow_0002711033_pyqt_pyqt4_python_qt.txt
Q: Django: Redirect to previous page *with query string* after login I am using django.contrib.auth and would like to redirect to the previous page after logging in. I would like something like the following: Django: Redirect to previous page after login except the redirected-to URL can contain a query string. Curren...
Django: Redirect to previous page *with query string* after login
I am using django.contrib.auth and would like to redirect to the previous page after logging in. I would like something like the following: Django: Redirect to previous page after login except the redirected-to URL can contain a query string. Currently I have the following link in my template: <a href="{% url user_logi...
[ "How about escaping the get parameters and then unquoting them in the view?\nhtml\n<a href=\"{% url user_login %}?next={{ request.get_full_path|urlencode }}\">Login</a>\n\nlogin view\nif successful_login:\n url_with_get = urllib2.unquote(request.GET.get('next'))\n return http.HttpResponseRedirect(url_with_get...
[ 11 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0006515096_django_django_authentication_python.txt
Q: Need more efficient way to parse out csv file in Python Here's a sample csv file id, serial_no 2, 500 2, 501 2, 502 3, 600 3, 601 This is the output I'm looking for (list of serial_no withing a list of ids): [2, [500,501,502]] [3, [600, 601]] I have implemented my solution but it's too much code and I'm sure the...
Need more efficient way to parse out csv file in Python
Here's a sample csv file id, serial_no 2, 500 2, 501 2, 502 3, 600 3, 601 This is the output I'm looking for (list of serial_no withing a list of ids): [2, [500,501,502]] [3, [600, 601]] I have implemented my solution but it's too much code and I'm sure there are better solutions out there. Still learning Python and ...
[ "from collections import defaultdict\n\nrecords = defaultdict(list)\n\nfile = 'test.csv'\n\ndata = csv.reader(open(file))\nfields = data.next()\n\nfor row in data:\n records[row[0]].append(row[1])\n\n#sorting by ids since keys don't maintain order\nresults = sorted(records.items(), key=lambda x: x[0])\nprint res...
[ 12, 5, 2, 1, 0 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0006515120_csv_python.txt
Q: Is there anything like Generic templates in django like Generic views Generic view have saved lot of code for me but i still have to write templates of every model. I have same code in all template i.e <form action="/{{type}}/{{ action }}/" method="post" enctype="multipart/form-data" > {% csrf_token %} {% ...
Is there anything like Generic templates in django like Generic views
Generic view have saved lot of code for me but i still have to write templates of every model. I have same code in all template i.e <form action="/{{type}}/{{ action }}/" method="post" enctype="multipart/form-data" > {% csrf_token %} {% for field in form %} <div class="fieldWrapper"> {{ fiel...
[ "If you have template code that is identical, you can use the include tag:\n{% include \"foo/bar.html\" %}\n\nAnd the included code can be modified with variables:\n{% include \"name_snippet.html\" with person=\"Jane\" %}\n\nEven if the code is different for each template (I think your example is talking about form...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0006506118_django_django_models_python.txt
Q: Do I need a specific Python module Oauthentication? I checked the documentation for Python-Twitter and I couldn't find any methods for OAuthentication. There is a methods for Basic Auth, but I obviously can't use that any more. If I get a separate module for Oauth can I still use methods in Python-Twitter that r...
Do I need a specific Python module Oauthentication?
I checked the documentation for Python-Twitter and I couldn't find any methods for OAuthentication. There is a methods for Basic Auth, but I obviously can't use that any more. If I get a separate module for Oauth can I still use methods in Python-Twitter that require Oauth or does the Oauth only support methods from ...
[ "OAuth is a generic protocol; any well-behaved library that implements it should work with any site's API (this is the whole point of having a standard...)\n", "Python-Twitter supports OAuth which is based on the python-oauth2 according to the docs.\n" ]
[ 0, 0 ]
[]
[]
[ "module", "python", "twitter" ]
stackoverflow_0006515477_module_python_twitter.txt
Q: Getting code that would self build a python data structure Is there a way where I'm able to generate the code in a file for a python data structure. For example, if I had a dictionary, it would create a file with: name_of_variable = { key: value, key:value} and so on. The use for this is testing where I don't want...
Getting code that would self build a python data structure
Is there a way where I'm able to generate the code in a file for a python data structure. For example, if I had a dictionary, it would create a file with: name_of_variable = { key: value, key:value} and so on. The use for this is testing where I don't want to manually code up a lot of data structures for my tests and I...
[ "For simple data structures such dict, list, set and other built-in things you can use repr():\n>>> d = {'a': 2, 'b': 3, 'c': 4}\n>>> repr(d)\n\"{'a': 2, 'c': 4, 'b': 3}\"\n>>> l = range(10)\n>>> repr(l)\n'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'\n>>> s = set(range(10))\n>>> repr(s)\n'set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])'\n\...
[ 3, 1, 1 ]
[]
[]
[ "data_structures", "python", "serialization" ]
stackoverflow_0006515977_data_structures_python_serialization.txt
Q: NameError: name '__builtin__' is not defined while installing SQLAlchemy I've installed Python 2.7.2 on my Windows XP computer. I recently installed SQLAlchemy 0.7.1 using 'python setup.py install'. During the installation, I got the following error messages: byte-compiling C:\Python27\Lib\site-packages\sqlalchemy...
NameError: name '__builtin__' is not defined while installing SQLAlchemy
I've installed Python 2.7.2 on my Windows XP computer. I recently installed SQLAlchemy 0.7.1 using 'python setup.py install'. During the installation, I got the following error messages: byte-compiling C:\Python27\Lib\site-packages\sqlalchemy\sql\visitors.py to visitors.pyc SyntaxError: ('invalid syntax', ('C:\\Python2...
[ "Problem partially solved: everything started working when I rolled back to SQLAlchemy 0.6.8. An issue with 0.7.1 + Windows/2.6?\n" ]
[ 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006505298_python_sqlalchemy.txt
Q: How this greatest common divisor (gcd) works in python I have taken a piece of code from http://www.s-anand.net/euler.html, problem 5: def gcd(a,b): print a,b return b and gcd(b, a % b) or a print gcd(10,20) Giving output: 10 20 20 10 10 0 10 Why the last line prints only "a" not b. Can you please e...
How this greatest common divisor (gcd) works in python
I have taken a piece of code from http://www.s-anand.net/euler.html, problem 5: def gcd(a,b): print a,b return b and gcd(b, a % b) or a print gcd(10,20) Giving output: 10 20 20 10 10 0 10 Why the last line prints only "a" not b. Can you please explain how the return statement in above code works. I am li...
[ "Python's and and or operators use a type of short-circut evaluation that is a little confusing at first.\nIf they were written as function, they would work sort-of like this, except that they don't even evaluate the right value unless they need to.\ndef and(left, right):\n if left:\n return right\n el...
[ 6, 6, 3 ]
[]
[]
[ "python" ]
stackoverflow_0006516549_python.txt
Q: Simple and effective web framework I'm looking for a suitable cross-platform web framework (if that's the proper term). I need something that doesn't rely on knowing the server's address or the absolute path to the files. Ideally it would come with a (development) server and be widely supported. I've already tried...
Simple and effective web framework
I'm looking for a suitable cross-platform web framework (if that's the proper term). I need something that doesn't rely on knowing the server's address or the absolute path to the files. Ideally it would come with a (development) server and be widely supported. I've already tried PHP, Django and web2py. Django had an a...
[ "This question is based on a complete failure to understand any of the tools you have apparently \"investigated\", or indeed web serving generally.\nDjango has an admin panel? Well, don't use it if you don't want to. There's no configuration that needs to be done there, it's for managing your data if you want.\nPHP...
[ 5, 4, 2, 1, 1, 1, 0, 0, 0, 0, 0 ]
[ "I think you need to focus on Restful web applications. Zend is a PHP based MVC framework.\n" ]
[ -1 ]
[ "python", "web_frameworks" ]
stackoverflow_0002362840_python_web_frameworks.txt
Q: How to add constant-spaced ticks on axes whose lenghts vary? [Python] To simplify my problem (it's not exactly like that but I prefer simple answers to simple questions): I have several 2D maps that portray rectangular region areas. I'd like to add on the map axes and ticks to show the distances on this map (with ...
How to add constant-spaced ticks on axes whose lenghts vary? [Python]
To simplify my problem (it's not exactly like that but I prefer simple answers to simple questions): I have several 2D maps that portray rectangular region areas. I'd like to add on the map axes and ticks to show the distances on this map (with matplotlib, since the old code is with it), but the problem is that the are...
[ "Just set the tick locator to use matplotlib.ticker.MultipleLocator(x) where x is the spacing that you want (e.g. 1.0 in your example above). \nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\n\nx = np.arange(20)\ny = x * 0.1\n\nfig, ax = plt.s...
[ 5, 0, 0 ]
[]
[]
[ "axis", "graph", "matplotlib", "python" ]
stackoverflow_0006494232_axis_graph_matplotlib_python.txt
Q: How can i distinguish the XML results of two python tests (using nosetests as test runner) with the same name but with different context I have a test footest.py which runs with mysql database, and the same test runs on psql database, is there a way to distinguish this difference in an XML result file between the ...
How can i distinguish the XML results of two python tests (using nosetests as test runner) with the same name but with different context
I have a test footest.py which runs with mysql database, and the same test runs on psql database, is there a way to distinguish this difference in an XML result file between the two tests.
[ "Why not trying to create a base_test_class.py with a base test class class BaseSQLTest(unittest.TestCase) that contains all your tests, and 2 other files mysqltest.py and psqltest.py that contains 2 inherited classes (class MySQLTest(BaseSQLTest) and class PSQLTest(BaseSQLTest)) for your MySQL and PSQL tests. \nDo...
[ 0 ]
[]
[]
[ "nosetests", "python", "xml" ]
stackoverflow_0006515166_nosetests_python_xml.txt
Q: Looping in Python and keeping current line after sub routine I've been trying to nut out an issue when looping in python 3. When returning from sub routine the "line" variable has not incremented. How do I get the script to return the latest readline from the subsroutine? Code below def getData(line): #prin...
Looping in Python and keeping current line after sub routine
I've been trying to nut out an issue when looping in python 3. When returning from sub routine the "line" variable has not incremented. How do I get the script to return the latest readline from the subsroutine? Code below def getData(line): #print(line) #while line in sTSDP_data: while "/service/con...
[ "How about using a return statement?\ndef getData(line):\n #print(line)\n #while line in sTSDP_data:\n while \"/service/content/test\" not in line:\n line = sTSDP_data.readline()\n return line\n\nimport os, sys\n\nsFileTSDP = \"d:/ess/redo/Test.log\"\nsTSDP_data = open(sFileTSDP, \"r\...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006517300_python.txt
Q: Is it possible to make different-sized ticks for graphs? Let's say that I have a graph an axis with 25 ticks, and I want to make every fifth tick (0, 5, 10, 15, 20, 25) bigger than the other ticks to make reading the graph easier. (There is already number labels on those ticks and no labels on the other ticks, but...
Is it possible to make different-sized ticks for graphs?
Let's say that I have a graph an axis with 25 ticks, and I want to make every fifth tick (0, 5, 10, 15, 20, 25) bigger than the other ticks to make reading the graph easier. (There is already number labels on those ticks and no labels on the other ticks, but reading is still rather uncomfortable...) Is it even possible...
[ "Are you looking for major and minor ticks? I assume you are looking for the following example:\nhttp://matplotlib.sourceforge.net/examples/pylab_examples/major_minor_demo1.html#pylab-examples-major-minor-demo1\nEdit\nI've adapted your example so it can be run. Next time, please post a minimal example which someone...
[ 2 ]
[]
[]
[ "axis", "graph", "matplotlib", "python" ]
stackoverflow_0006516822_axis_graph_matplotlib_python.txt
Q: Where should I store libraries in a good Django project structure? In one of the apps of my Django site I require a third-party module/library. I've been reading up on how a good Django project should be structured but it doesn't mention much about storing libraries. My current project is structured like so: urls....
Where should I store libraries in a good Django project structure?
In one of the apps of my Django site I require a third-party module/library. I've been reading up on how a good Django project should be structured but it doesn't mention much about storing libraries. My current project is structured like so: urls.py manage.py settings.py apps app1 views.py models.p...
[ "If this is a third-party library, it shouldn't be kept in your source code at all. \nIf you use virtualenv, you get a complete environment that you can install libraries in specifically for that project. Plus, in conjunction with pip, you can set up a requirements.txt file which specifies all the libraries you nee...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006517480_django_python.txt
Q: copies of classes in python Assume I have an instance foo of some class Class with some variable foo.x. Now I want to produce a copy of foo: bar = foo when I now change bar.x, this also changes foo.x. How can I get a copy of foo, where I can change everything without changing the original foo? Creating a new inst...
copies of classes in python
Assume I have an instance foo of some class Class with some variable foo.x. Now I want to produce a copy of foo: bar = foo when I now change bar.x, this also changes foo.x. How can I get a copy of foo, where I can change everything without changing the original foo? Creating a new instance of Class is not an option, b...
[ "You need to use the module copy.\nbar = copy.deepcopy(foo)\n\n", "You can use deepcopy:\nbar = deepcopy(foo)\n\n", "Note that you can also implement your own copy with customized(sure if you really need this) behavior the following way:\nfrom copy import copy\n\nclass d(object):\n\n def __copy__(self):\n ...
[ 5, 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006517498_python.txt
Q: Any ways to resuming download on HG or GIT changsets pulling? I try to find way for update speсial software (Python application) on client. Client already have HG or GIT, and I can dictate any requirements for client environment. But client have slowly and breaking out internet connection. HG, GIT and others tools...
Any ways to resuming download on HG or GIT changsets pulling?
I try to find way for update speсial software (Python application) on client. Client already have HG or GIT, and I can dictate any requirements for client environment. But client have slowly and breaking out internet connection. HG, GIT and others tools ideal for update procedure by changesets with minimal traffic band...
[ "Git is particularly efficient and resilient for such network breakdown effects.\nEfficient because, it only pulls the objects in the tree that are changed or newly added and even transmits the compressed objects.\nResilient because, unless all the necessary objects are present, the branch is not furthered. That is...
[ 3 ]
[]
[]
[ "git", "mercurial", "python" ]
stackoverflow_0006517519_git_mercurial_python.txt
Q: PyQt Web Browser: Focus on the webpage without a mouse click I am writing an application for an embedded device that has no mouse input. The web browser is very very basic and does not have any buttons, address bar, file bar , etc. For now, it simply just loads a web page. This web page uses javascript to catch...
PyQt Web Browser: Focus on the webpage without a mouse click
I am writing an application for an embedded device that has no mouse input. The web browser is very very basic and does not have any buttons, address bar, file bar , etc. For now, it simply just loads a web page. This web page uses javascript to catch key press events for actions. The problem I am having is that whe...
[ "I tried your code on my laptop and the QWebView had focus already - once Google had loaded I could type and my text appeared in the text box.\nIf it is a focus problem then as QWebView inherits QWidget you can call its setFocus() method. Here is your code with an extra line calling the QWebView's setFocus method o...
[ 0, 0 ]
[]
[]
[ "embedded", "linux", "pyqt", "python", "webkit" ]
stackoverflow_0006513311_embedded_linux_pyqt_python_webkit.txt
Q: Get key from dictionary I just started with Python, Is there some iteration in dictionary like in PHP foreach(aData as key=>value) A: It looks like something like this : my_dict = {"key1": 1, "key2":2} my_dict.items() # in python < 3 , you should use iteritems() >>> ("key1", 1), ("key2", 2) so you can i...
Get key from dictionary
I just started with Python, Is there some iteration in dictionary like in PHP foreach(aData as key=>value)
[ "It looks like something like this : \nmy_dict = {\"key1\": 1, \"key2\":2}\nmy_dict.items() # in python < 3 , you should use iteritems()\n>>> (\"key1\", 1), (\"key2\", 2)\n\nso you can iterate on it : \nfor key, value in my_dict.items():\n do_the_stuff(key, value)\n\n", "assuming python 2:\nfor key, value...
[ 9, 5, 4 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0006517793_dictionary_python.txt
Q: Tornado's AsyncHTTPClient no longer works after upgrade to 2.0 from 1.2 Decided I'd kick the tires of Tornado 2.0 tonight, but it appears to have done a number on ASyncHTTPClient for me. Nothing in the release notes for 2.0 indicates any real changes are necessary to how I'm using ASyncHTTPClient: [EDIT: made the...
Tornado's AsyncHTTPClient no longer works after upgrade to 2.0 from 1.2
Decided I'd kick the tires of Tornado 2.0 tonight, but it appears to have done a number on ASyncHTTPClient for me. Nothing in the release notes for 2.0 indicates any real changes are necessary to how I'm using ASyncHTTPClient: [EDIT: made the code more of an explicit, self-containing example ] import time import threa...
[ "Those error messages are a bit cryptic, but in both cases I think they're due to your request not having a URL (unless callback is a URL).\n2.0 switched the ASyncHTTPClient implementation to simple_httpclient (from curl_httpclient), but I don't think the example given would have worked in Tornado 1.2 either.\n" ]
[ 2 ]
[]
[]
[ "asynchronous", "pycurl", "python", "tornado" ]
stackoverflow_0006515000_asynchronous_pycurl_python_tornado.txt
Q: matching 3 or more of the same character in python I'm trying to use regular expressions to find three or more of the same character in a string. So for example: 'hello' would not match 'ohhh' would. I've tried doing things like: re.compile('(?!.*(.)\1{3,})^[a-zA-Z]*$') re.compile('(\w)\1{5,}') but neither see...
matching 3 or more of the same character in python
I'm trying to use regular expressions to find three or more of the same character in a string. So for example: 'hello' would not match 'ohhh' would. I've tried doing things like: re.compile('(?!.*(.)\1{3,})^[a-zA-Z]*$') re.compile('(\w)\1{5,}') but neither seem to work.
[ "(\\w)\\1{2,} is the regex you are looking for.\nIn Python it could be quoted like r\"(\\w)\\1{2,}\"\n", "if you're looking for the same character three times consecutively, you can do this:\n(\\w)\\1\\1\n\nif you want to find the same character three times anywhere in the string, you need to put a dot and an ast...
[ 21, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006518154_python_regex.txt
Q: Python, remove duplicates from list of tuples I have the following list: [('mail', 167, datetime.datetime(2010, 9, 29)) , ('name', 1317, datetime.datetime(2011, 12, 12)), ('mail', 1045, datetime.datetime(2010, 8, 13)), ('name', 3, datetime.datetime(2011, 11, 3))] And I want to remove items from the list wit...
Python, remove duplicates from list of tuples
I have the following list: [('mail', 167, datetime.datetime(2010, 9, 29)) , ('name', 1317, datetime.datetime(2011, 12, 12)), ('mail', 1045, datetime.datetime(2010, 8, 13)), ('name', 3, datetime.datetime(2011, 11, 3))] And I want to remove items from the list with coinciding first item in a tuple where date is no...
[ "You can use a dictionary to store the highest value found for a given key so far:\ntemp = {}\nfor key, number, date in input_list:\n if key not in temp: # we see this key for the first time\n temp[key] = (key, number, date)\n else:\n if temp[key][2] < date: # the new date is larger than the old...
[ 16, 2, 0, 0 ]
[ "Here you go.\n#!/usr/bin/python2\n\nfrom pprint import pprint\nimport datetime\n\nol = [('mail', 167, datetime.datetime(2010, 9, 29)) , \n ('name', 1317, datetime.datetime(2011, 12, 12)), \n ('mail', 1045, datetime.datetime(2010, 8, 13)), \n ('name', 3, datetime.datetime(2011, 11, 3))]\n\nd = {}\n\nfor...
[ -1 ]
[ "items", "list", "python" ]
stackoverflow_0006518071_items_list_python.txt
Q: Django: model question Hello I want to make a change to my models.py. I have two tables. Client and Note. What I want to do is have a note field in the clients table which should have some one-one relationship with the Note table. However,the note will have to store some user, client and a date time. So I need a...
Django: model question
Hello I want to make a change to my models.py. I have two tables. Client and Note. What I want to do is have a note field in the clients table which should have some one-one relationship with the Note table. However,the note will have to store some user, client and a date time. So I need another table to do this. But...
[ "I don't quite get the question, but I guess you need the OneToOneField\n", "Justinas is right. You should add a note field to your Client model, which makes the FK on your Note model obsolete. Something like this should get you started:\nclass Note(models.Model):\n datetime = models.DateTimeField(default=date...
[ 1, 0 ]
[]
[]
[ "django", "models", "python" ]
stackoverflow_0006518647_django_models_python.txt
Q: apply an xslt function to some nodes from libxml2 in Python In a python script, I want to aplly the following XSLT functions : normalize-space and translate to some nodes from an libxml2 tree Can it be done without writing a stylesheet ? If a stylesheet is needed, what will it look like ? how to set the context no...
apply an xslt function to some nodes from libxml2 in Python
In a python script, I want to aplly the following XSLT functions : normalize-space and translate to some nodes from an libxml2 tree Can it be done without writing a stylesheet ? If a stylesheet is needed, what will it look like ? how to set the context node to a given node from python ?
[ "Both normalize-space() and translate() are standard XPath functions, so they can be used in any XPath expression -- without XSLT. \nJust use the API for your XPath engine.\n", "in fact it's very easy :D\ncontext = xmlDoc.xpathNewContext()\nextractedContent = context.xpathEval( normalize-space( translate( /html[1...
[ 2, 0 ]
[]
[]
[ "libxml2", "python", "xslt" ]
stackoverflow_0006504285_libxml2_python_xslt.txt
Q: What is Facebook's new Tornado framework? Facebook just open-sourced a framework called Tornado. What is it? What does it help a site do? I believe Facebook uses a LAMP structure. Is it useful for smaller sites which are written under the LAMP stack? A: It looks like it is a web-server optimized for high-concu...
What is Facebook's new Tornado framework?
Facebook just open-sourced a framework called Tornado. What is it? What does it help a site do? I believe Facebook uses a LAMP structure. Is it useful for smaller sites which are written under the LAMP stack?
[ "It looks like it is a web-server optimized for high-concurrency and high-scalability, but made for smaller payloads.\nIt was designed to support 10,000 concurrent users well.\n\nThe framework is distinct from most\n mainstream web server frameworks (and\n certainly most Python frameworks)\n because it is non-bl...
[ 13, 0, 0 ]
[]
[]
[ "facebook", "python", "tornado" ]
stackoverflow_0001406912_facebook_python_tornado.txt
Q: "expected indented block" error in code? I m getting "expected indented block" error in below code : i am new to python please help #!/bin/env python import wx class MyFrame(wx.Frame): def __init(self): wx.Frame.__init__(self, None, -1,"My Frame", size=(300,300)) panel = wx.Panel(self, -1) ...
"expected indented block" error in code?
I m getting "expected indented block" error in below code : i am new to python please help #!/bin/env python import wx class MyFrame(wx.Frame): def __init(self): wx.Frame.__init__(self, None, -1,"My Frame", size=(300,300)) panel = wx.Panel(self, -1) panel.Bind(wx.EVT_MOTION, self.OnMove) ...
[ "Your indenting is completely strange, this is my best guess. I would suggest to try and learn Python more from the basics up.\n#!/bin/env python\nimport wx\n\nclass MyFrame(wx.Frame):\n def __init(self):\n wx.Frame.__init__(self, None, -1,\"My Frame\", size=(300,300))\n panel = wx.Panel(self, -1)\...
[ 5, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006518965_python.txt
Q: Content disposition am using xlwt module to create xls file with multiple sheets and i want to display Content disposition with the created file. wbk = xlwt.Workbook(encoding='utf-8') sheet = workbook.add_sheet('sheet1') and then response.headers['Content-Type'] = \ gluon.contenttype.contenttype('.xls') ...
Content disposition
am using xlwt module to create xls file with multiple sheets and i want to display Content disposition with the created file. wbk = xlwt.Workbook(encoding='utf-8') sheet = workbook.add_sheet('sheet1') and then response.headers['Content-Type'] = \ gluon.contenttype.contenttype('.xls') response.headers['Content...
[ "Looking at the docs, it seems that you could write out to a StringIO, and then print that out.\nimport StringIO\noutput = StringIO.StringIO()\nwbk.save(output)\n\nand then use output.getvalue().\nI have not tested this at all.\n", "[dis]claimer: I'm the maintainer of xlwt.\nWorkbook.save(destination) ...\nif des...
[ 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003433454_python.txt
Q: Dependencies. On loading modules for use in a function or a class, steer me? I am working my way through some samples, and came up with this working answer - the challenge being set in the doctests: def remove(sub, s): """ >>> remove('an', 'banana') 'bana' >>> remove('cyc', 'bicycle') '...
Dependencies. On loading modules for use in a function or a class, steer me?
I am working my way through some samples, and came up with this working answer - the challenge being set in the doctests: def remove(sub, s): """ >>> remove('an', 'banana') 'bana' >>> remove('cyc', 'bicycle') 'bile' >>> remove('iss', 'Mississippi') 'Missippi' >>> remove('eg...
[ "By convention, imports are placed at the top of your module/script. It makes them easier to find for you and others reading your code. There are sometimes good reasons to put imports elsewhere, say a conditional import with significant overhead.\nAnother convention is not to 'check' that a module is loaded but ins...
[ 2, 0 ]
[]
[]
[ "function", "python", "string" ]
stackoverflow_0006519414_function_python_string.txt
Q: How can I decide which declarative model to instantiate, based on row information I'm building a webapp that has optional Facebook Login. The users created through the Facebook API are handled differently at several points in my application. I want to encapsulate these differences in a subclass of Person that over...
How can I decide which declarative model to instantiate, based on row information
I'm building a webapp that has optional Facebook Login. The users created through the Facebook API are handled differently at several points in my application. I want to encapsulate these differences in a subclass of Person that overrides methods. class Person(Model): def get_profile_picture(self): return p...
[ "The general idea would be to store the model's class name as metadata in each row, and when you instantiate the object, do something like:\ndef query(self):\n # stuff\n return model_class(data)\n\nTo do this in SQLAlchemy, you might look at making Person the base class to something like BasicPerson and Faceb...
[ 1 ]
[]
[]
[ "flask", "flask_sqlalchemy", "python", "sqlalchemy" ]
stackoverflow_0006426267_flask_flask_sqlalchemy_python_sqlalchemy.txt
Q: Handling big text files in Python Basics are that I need to process 4gig text files on a per line basis. using .readline() or for line in f is great for memory but takes ages to IO. Would like to use something like yield, but that (I think) will chop lines. POSSIBLE ANSWER: file.readlines([sizehint])¶ Read until...
Handling big text files in Python
Basics are that I need to process 4gig text files on a per line basis. using .readline() or for line in f is great for memory but takes ages to IO. Would like to use something like yield, but that (I think) will chop lines. POSSIBLE ANSWER: file.readlines([sizehint])¶ Read until EOF using readline() and return a lis...
[ "You can just iterate over the file object:\nwith open(\"filename\") as f:\n for line in f:\n whatever\n\nThis will do some internal buffering to improve the performance. (Note that file.readline() will perform considerably worse because it does not buffer -- that's why you can't mix iteration over a fil...
[ 7, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006519297_python.txt
Q: Looking for a webapp framework that does away with the database I've been developing with Django during the last year or so and really enjoy it. But sometimes I find that the ORM is a bit of a straitjacket. All the data that I shuffle back and forth to the database would easily fit into 1GB of RAM. Even if the pro...
Looking for a webapp framework that does away with the database
I've been developing with Django during the last year or so and really enjoy it. But sometimes I find that the ORM is a bit of a straitjacket. All the data that I shuffle back and forth to the database would easily fit into 1GB of RAM. Even if the project grew a couple of orders of magnitude it would still fit into 1GB...
[ "If you are looking for \"storing data-structures in-memory\" and \"backing up them to disk\", you are really looking for a persistent cache system and Redis fits the bill perfectly.\nIf you want to use django, there is an awesome cache system built-in and that is pluggable to redis backend via Redis-Cache project....
[ 3, 1 ]
[]
[]
[ "nosql", "object_oriented_database", "python", "ram", "web_frameworks" ]
stackoverflow_0006505223_nosql_object_oriented_database_python_ram_web_frameworks.txt
Q: Logical paradox in python? I came over this, where "not None" equals both True and False simultaneously. >>> not None True >>> not None == True True >>> not None == False True At first I expected that this would be because of the order of operators, but however when testing a similar expression: >>> not False T...
Logical paradox in python?
I came over this, where "not None" equals both True and False simultaneously. >>> not None True >>> not None == True True >>> not None == False True At first I expected that this would be because of the order of operators, but however when testing a similar expression: >>> not False True >>> not False == False Fals...
[ "This is due to operator precedence. not none == True means not (None == True) means None != True, which is true. Similarly, None != False is also true. The value None is distinct from the booleans.\nYour last two expressions mean False != False, which is false, and False != True, which is true.\n", "This is inde...
[ 21, 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006520193_python.txt
Q: Find roots of a function a x^n + bx - c = 0 where n isn't an integer with Numpy? I'm writing a program in python and in it I need to find the roots of a function that is: a*x^n + b*x -c = 0 where a and b are constants that are calculated earlier in the program but there are several thousand of them. I need to re...
Find roots of a function a x^n + bx - c = 0 where n isn't an integer with Numpy?
I'm writing a program in python and in it I need to find the roots of a function that is: a*x^n + b*x -c = 0 where a and b are constants that are calculated earlier in the program but there are several thousand of them. I need to repeat this equation twice for all values of a and b once with n = 77/27 and once with n...
[ "I think your beast choice is scipy.optimize.brentq():\ndef f(x, n, a, b, c):\n return a * x**n + b * x - c\n\nprint scipy.optimize.brentq(\n f, 0.0, 100.0, args=(77.0/27.0, 1.0, 1.0, 10.0))\n\nprints\n2.0672035922580592\n\n", "Look here and here.\nI'm so proud of myself, I still remember the specifics (wit...
[ 8, 5, 5, 0 ]
[]
[]
[ "equation", "numpy", "python" ]
stackoverflow_0006519380_equation_numpy_python.txt
Q: Class referencing Error - sometimes an issue Okay so I did not know what to search for in order to answer this question. In my code for some reason some of my classes can be referenced as per instructions by Python class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello...
Class referencing Error - sometimes an issue
Okay so I did not know what to search for in order to answer this question. In my code for some reason some of my classes can be referenced as per instructions by Python class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world' x = MyClass() In my code I have imported...
[ "If i correctly understood you then the problem is that you are using import/from .. import incorrectly. First of all there is no need to use both 'import module' and right after that call 'from module import ...'.\nModify main.py:\nimport os, sys\n\nfrom tkFileDialog import <put here what you really need>\nfrom Tk...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006520400_python.txt
Q: Simple to implement struct for memory efficient list of tuples I need to create a list of the following type [(latitude, longitude, date), ...] where latitude and longitude are floats, and date is an integer. I'm running out of memory on my local machine because I need to store about 60 million of these tuples. ...
Simple to implement struct for memory efficient list of tuples
I need to create a list of the following type [(latitude, longitude, date), ...] where latitude and longitude are floats, and date is an integer. I'm running out of memory on my local machine because I need to store about 60 million of these tuples. What is the most memory efficient (and at the same time simple to i...
[ "If you are fine with using NumPy, you could use a numpy.recarray. If you want 8 significant digits for your coordinates, single precision floats are probably just not enough, so your records would have two double precision floats and a 32-bit integer, which is twenty bytes in total, so 60 million records would ne...
[ 3 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0006519830_memory_python.txt
Q: Python graph- change axis marker colours and legend border colours I'm using Python to plot a couple of graphs and I'm trying to change the formatting and essentially 'brand' the graph. I've managed to change most things using pylab.rcParams[...], but I can't work out how to change the colour of the markers on the...
Python graph- change axis marker colours and legend border colours
I'm using Python to plot a couple of graphs and I'm trying to change the formatting and essentially 'brand' the graph. I've managed to change most things using pylab.rcParams[...], but I can't work out how to change the colour of the markers on the axes and the border around the legend. Any help would be much appreciat...
[ "If you just want to use rcParams, the proper parameters are xticks.color and yticks.color. I can't seem to find a key for the legend frame color. You can set that (along with the tick colors) programmatically though. \nimport pylab\n\npylab.plot([1,2,3],[4,5,6], label ='test')\nlg = pylab.legend()\nlg.get_frame(...
[ 2 ]
[]
[]
[ "axes", "border", "colors", "graph", "python" ]
stackoverflow_0006519777_axes_border_colors_graph_python.txt
Q: Firefox, Selenium, toDataURL, Uint8ClampedArray and Python I am accessing image data on Javascript. Now I'd like to pass this to Python process through Selenium API in the most efficient possible manner. Passing canvas data is easy with canvas.toDataURL() method, but the downside is that the image is encoded and ...
Firefox, Selenium, toDataURL, Uint8ClampedArray and Python
I am accessing image data on Javascript. Now I'd like to pass this to Python process through Selenium API in the most efficient possible manner. Passing canvas data is easy with canvas.toDataURL() method, but the downside is that the image is encoded and decoded to PNG, adding substantial overhead to the process. I wa...
[ "Since your communication between Selenium and the browser through getEval is string based, I think that there is no escape from base64 encoding the image data. sending raw binary data will probably not be possible. \nYou can probably devise your own string encoding scheme, but it'll probably be as effective as the...
[ 1 ]
[]
[]
[ "canvas", "firefox", "javascript", "python", "selenium" ]
stackoverflow_0006514812_canvas_firefox_javascript_python_selenium.txt
Q: Need help writing a twisted proxy I want to write a simple proxy that shuffles the text in the body of the requested pages. I have read parts of the twisted documentation and some other similar questions here on stackoverflow but I'm a bit of a noob so I still don't get it. This is what I have now, I don't know ho...
Need help writing a twisted proxy
I want to write a simple proxy that shuffles the text in the body of the requested pages. I have read parts of the twisted documentation and some other similar questions here on stackoverflow but I'm a bit of a noob so I still don't get it. This is what I have now, I don't know how to access and modify the page from tw...
[ "What I do is to implement a new ProxyClient, where I modify the data after I've downloaded it from the webserver, and before I send it off to the web browser.\nfrom twisted.web import proxy, http\nclass MyProxyClient(proxy.ProxyClient):\n def __init__(self,*args,**kwargs):\n self.buffer = \"\"\n proxy.ProxyClien...
[ 6 ]
[]
[]
[ "proxy", "python", "twisted" ]
stackoverflow_0006491932_proxy_python_twisted.txt
Q: Want to add a one-to-one column to an existing table I have a new field in the Client called note which has a one-to-one relation with Notes. I want to be able to add the note column under the Client table in mysql. It does not work when I use python manage.py syncdb. So I would like to know how to add a one-to-on...
Want to add a one-to-one column to an existing table
I have a new field in the Client called note which has a one-to-one relation with Notes. I want to be able to add the note column under the Client table in mysql. It does not work when I use python manage.py syncdb. So I would like to know how to add a one-to-one field in mysql to an existing table. models.py class No...
[ "Syncdb doesn't change your database in order not to destroy your data. See django book.\nYou can update the database manually or use an automated migration tool (at your own risk) like South.\nEDIT:\nIn django book, you can also read detailed instructions about manual changes along with SQL examples. Other useful ...
[ 1, 0 ]
[]
[]
[ "alter_table", "django", "mysql", "python" ]
stackoverflow_0006520626_alter_table_django_mysql_python.txt