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: sorting lines based on data in the middle of the line (in python) I have a list of domains and I want to sort them based on tld. whats the fastest way to do this? A: Use the key parameter to .sort() to provide a function that can retrieve the proper data to sort by. import urlparse def get_tld_from_domain(domai...
sorting lines based on data in the middle of the line (in python)
I have a list of domains and I want to sort them based on tld. whats the fastest way to do this?
[ "Use the key parameter to .sort() to provide a function that can retrieve the proper data to sort by.\nimport urlparse\n\ndef get_tld_from_domain(domain)\n return urlparse.urlparse(domain).netloc.split('.')[-1]\n\nlist_of_domains.sort(key=get_tld_from_domain)\n\n# or if you want to make a new list, instead of so...
[ 5, 2, 1 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0003553581_python_sorting.txt
Q: Is there a better trivial Python WebDAV server code snippet than this? Does anyone have a better code snippet for a trivial Python WebDAV server? The code below (which is cobbled together from some Google search results) appears to work under Python 2.6, but I wonder if someone has something they have used before...
Is there a better trivial Python WebDAV server code snippet than this?
Does anyone have a better code snippet for a trivial Python WebDAV server? The code below (which is cobbled together from some Google search results) appears to work under Python 2.6, but I wonder if someone has something they have used before, a little more tested and complete. I'd prefer a stdlib-only snippet over ...
[ "Or try WsgiDAV which is a refactored version of PyFileServer.\n", "You can try akaDAV. It is a WebDAV module for Twisted.\nI think it is not maintained anymore, but I've got it to work and it supports most operations (except locks).\n", "WsgiDAV\n" ]
[ 5, 1, 1 ]
[]
[]
[ "python", "webdav" ]
stackoverflow_0000702780_python_webdav.txt
Q: Django / Python, using variablized object names I'm confused on how to do this, I'm passing in a dictionary with different values, such as "app" which is the name of the app (so that I can better decouple code for easier modularization).. so this is just a simplified example and its not working so I'm wondering ho...
Django / Python, using variablized object names
I'm confused on how to do this, I'm passing in a dictionary with different values, such as "app" which is the name of the app (so that I can better decouple code for easier modularization).. so this is just a simplified example and its not working so I'm wondering how to use the variable "app" within the string that is...
[ "You probably need something like importlib (Python 2.7). If you version of Python doesn't have importlib then you can use plain old __import__.\nFor example:\nimport sys\nmodule_name = \"web1.%s.models\" % app\n__import__(module_name)\nmodels = sys.modules[module_name]\nmodels.modelname\n\n", "you should use con...
[ 1, 1 ]
[]
[]
[ "django", "import", "object", "python" ]
stackoverflow_0003554233_django_import_object_python.txt
Q: How to best pickle/unpickle in class hierarchies if parent and child class instances are pickled Assume I have a class A and a class B that is derived from A. I want to pickle/unpickle an instance of class B. Both A and B define the __getstate__/__setstate__ methods (Let's assume A and B are complex, which makes t...
How to best pickle/unpickle in class hierarchies if parent and child class instances are pickled
Assume I have a class A and a class B that is derived from A. I want to pickle/unpickle an instance of class B. Both A and B define the __getstate__/__setstate__ methods (Let's assume A and B are complex, which makes the use of __getstate__ and __setstate__ necessary). How should B call the __getstate__/__setstate__ me...
[ "I would use super(B,self) to get instances of B to call the methods of A:\nimport cPickle\nclass A(object):\n def __init__(self):\n self.value=1\n def __getstate__(self):\n return self.value\n def __setstate__(self, state):\n self.value = state\n\nclass B(A):\n def __init__(self):\...
[ 4 ]
[]
[]
[ "persistence", "pickle", "python" ]
stackoverflow_0003554310_persistence_pickle_python.txt
Q: Integrating messenger to an existing website For an existing website and the users in it,how to integrate a chat application like yahoo or gmail or any other with minimum code changes. A: Ajax IM looks very good for this. Alternatively, maybe something like PHP121? These are both instant messenger style chat sys...
Integrating messenger to an existing website
For an existing website and the users in it,how to integrate a chat application like yahoo or gmail or any other with minimum code changes.
[ "Ajax IM looks very good for this.\nAlternatively, maybe something like PHP121?\nThese are both instant messenger style chat systems. If you're looking for something more like a chatroom, I have used Ajax Chat successfully in the past.\nI think you'll need a fair bit of code changes however you approach this, if y...
[ 1 ]
[]
[]
[ "api", "gmail", "jquery", "python", "yahoo_messenger" ]
stackoverflow_0003554640_api_gmail_jquery_python_yahoo_messenger.txt
Q: Histogram Equalization I am a beginner in Python. I want to make a small project on histogram equalisation. Basically I want to include changing contrast, color and crop option etc in my project. I am blank right now. Please suggest something. I am very keen to make this project but how to start? A: Python's P...
Histogram Equalization
I am a beginner in Python. I want to make a small project on histogram equalisation. Basically I want to include changing contrast, color and crop option etc in my project. I am blank right now. Please suggest something. I am very keen to make this project but how to start?
[ "Python's PIL module has methods for controlling contrast, color, and cropping.\n", "You can use PythonMagick. It suports histogram equalization:\nimport PythonMagick\nimg = PythonMagick.Image(\"original.png\")\nimg.equalize()\nimg.write(\"equalized.png\")\n\nPythonMagick is not very well documented itself, but i...
[ 3, 3 ]
[]
[]
[ "image_processing", "python" ]
stackoverflow_0003554763_image_processing_python.txt
Q: Get a list of the absolute paths of all the images in a page using BeautifulSoup Could someone show me how to get a list of aboslute paths for all the images in a webpage using BeautifulSoup? It's simple to get all the images. I'm doing this: page_images = [image["src"] for image in soup.findAll("img")] ...but I...
Get a list of the absolute paths of all the images in a page using BeautifulSoup
Could someone show me how to get a list of aboslute paths for all the images in a webpage using BeautifulSoup? It's simple to get all the images. I'm doing this: page_images = [image["src"] for image in soup.findAll("img")] ...but I'm having difficulties getting the absolute paths. Any help? Thank you.
[ "You will have to normalize the paths after getting them. This can be done using urlparse.urljoin. For example:\n>>> urlparse.urljoin(\"http://google.com/some/path/\", \"../../img/icon.png\")\n'http://google.com/img/icon.png'\n\n", "This is not using BeautifulSoup, but the more elegant (and well-maintained) lxml+...
[ 5, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003554826_beautifulsoup_python.txt
Q: unmount fuse fs from python script I have developed fuse fs with python and now want to write tests for it. Before testing I mount fs to some dir: fs = MyFuseFS() fs.parse(errex=1, ['some_dir']) fs.main() After testing I want unmount my fs, want to do something like this: fs.unmount() Is it somethi...
unmount fuse fs from python script
I have developed fuse fs with python and now want to write tests for it. Before testing I mount fs to some dir: fs = MyFuseFS() fs.parse(errex=1, ['some_dir']) fs.main() After testing I want unmount my fs, want to do something like this: fs.unmount() Is it something like "unmount" method? Maybe there ...
[ "http://packages.python.org/fs/expose/fuse.html\nyou can see what you need from this link.\n>>> from fs.memoryfs import MemoryFS\n>>> from fs.expose import fuse\n>>> fs = MemoryFS()\n>>> mp = fuse.mount(fs,\"/mnt/my-memory-fs\")\n>>> mp.unmount()\n\nyou guessed the function name right :)\n" ]
[ 3 ]
[]
[]
[ "filesystems", "fuse", "linux", "python", "unit_testing" ]
stackoverflow_0003156264_filesystems_fuse_linux_python_unit_testing.txt
Q: Why does a meta class change the way issubclass() work? OK, so I'm writing a framework that looks for python files in sub directories that are named task.py and then look for classes that are derived from the base class Task and collect them. I decided that I needed to add a meta class to Task, but then the issubc...
Why does a meta class change the way issubclass() work?
OK, so I'm writing a framework that looks for python files in sub directories that are named task.py and then look for classes that are derived from the base class Task and collect them. I decided that I needed to add a meta class to Task, but then the issubclass() started to behave in a weird way. Here is how the dire...
[ "Your code doesn't work via normal import either. \n>>> from tasks.base import Task1\n>>> type(Task1)\n<class 'tasks.base.MetaClass'>\n>>> from types import TypeType\n>>> type(Task1) == TypeType\nFalse\n>>> issubclass(type(Task1), TypeType)\nTrue\n>>> \n\nWhen you instantiate the metaclass (as a class), the instanc...
[ 2, 0 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0003555283_introspection_python.txt
Q: Python's urllib equivalent in .net Is there a .net equivalent for urllib I used in Python? I've seen WebRequest and WebResponse classes but I wonder if there is a simpler wrapper. In urllib you can use dictionary object (tupple) to set POST parameters while in .Net one must fiddle with streams. Is there any free,...
Python's urllib equivalent in .net
Is there a .net equivalent for urllib I used in Python? I've seen WebRequest and WebResponse classes but I wonder if there is a simpler wrapper. In urllib you can use dictionary object (tupple) to set POST parameters while in .Net one must fiddle with streams. Is there any free, small web client library available for ...
[ "You can use Webclient's UploadValues() or UploadString().\n" ]
[ 2 ]
[]
[]
[ ".net", "python", "webclient" ]
stackoverflow_0003555549_.net_python_webclient.txt
Q: Is there a python twitter search library that handle results the right way? All the libraries I've tested search in twitter, let you specify the rpp (results per page) parameter but only gives you ONE page results. It'd be cool a Python lib that provide a generator and each time gen.next() is called, a new search ...
Is there a python twitter search library that handle results the right way?
All the libraries I've tested search in twitter, let you specify the rpp (results per page) parameter but only gives you ONE page results. It'd be cool a Python lib that provide a generator and each time gen.next() is called, a new search result is yielded. If the page is over, jump to the next page alone.
[ "This is what I was talking about: http://github.com/ryanmcgrath/twython/commit/e9aaaa7c39dad0306fec9e83cb377975f5c2d4d5\n", "I'm not sure I understand what you are asking, but I think the limit on what you can get is not a library limitation, but an API limitation (imposed by Twitter). You can read the methods a...
[ 1, 0 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0003552560_python_twitter.txt
Q: Better way, than this, to rename files using Python I am python newbie and am still discovering its wonders. I wrote a script which renames a number of files : from Edison_03-08-2010-05-02-00_PM.7z to Edison_08-03-2010-05-02-00_PM.7z "03-08-2010" is changed to "08-03-2010" The script is: import os, os.path locatio...
Better way, than this, to rename files using Python
I am python newbie and am still discovering its wonders. I wrote a script which renames a number of files : from Edison_03-08-2010-05-02-00_PM.7z to Edison_08-03-2010-05-02-00_PM.7z "03-08-2010" is changed to "08-03-2010" The script is: import os, os.path location = "D:/codebase/_Backups" files = os.listdir(location) ...
[ "datetime's strptime (parse time string) and strftime (format time string) will do most of the heavy lifting for you:\nimport datetime\n\n_IN_FORMAT = 'Edison_%d-%m-%Y-%I-%M-%S_%p.7z'\n_OUT_FORMAT = 'Edison_%m-%d-%Y-%I-%M-%S_%p.7z'\n\noldfilename = 'Edison_03-08-2010-05-02-00_PM.7z'\n\n# Parse to datetime.\ndt = da...
[ 8, 3 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0003556175_file_io_python.txt
Q: How to control links2 with Python How can I execute links2 to open a web page and locate and click a text link with Python? Is pexpect able to do it? Any examples are appreciated. A: Not sure why you want to do this. If you want to grab the web link and process the page content, urllib2 together with an HTML par...
How to control links2 with Python
How can I execute links2 to open a web page and locate and click a text link with Python? Is pexpect able to do it? Any examples are appreciated.
[ "Not sure why you want to do this. If you want to grab the web link and process the page content, urllib2 together with an HTML parser (BeautifulSoup for example) may be just fine. \nIf you do want to simulate moust clicks, you may want to use AutoPy. \n", "Why do you want to use links2? I don't see how you could...
[ 1, 0, 0 ]
[]
[]
[ "pexpect", "python" ]
stackoverflow_0003544596_pexpect_python.txt
Q: Adding an array in numpy at a specified location Is there a fast way in numpy to add array A to array B at a specified location? For instance, if B = [ [0, 1, 2], [2, 3, 4], [5, 6, 7] ] and A = [ [2, 2], [2, 2] ] and I want to add A to B starting from point (0, 0) to get C = [ [2, 3, 2]...
Adding an array in numpy at a specified location
Is there a fast way in numpy to add array A to array B at a specified location? For instance, if B = [ [0, 1, 2], [2, 3, 4], [5, 6, 7] ] and A = [ [2, 2], [2, 2] ] and I want to add A to B starting from point (0, 0) to get C = [ [2, 3, 2], [4, 5, 4], [5, 6, 7], ] Of course I can do ...
[ "To modify B in place\nB[:2,:2] += A\n\notherwise\nC = B.copy()\nC[:2,:2] += A\n\n" ]
[ 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003556613_numpy_python.txt
Q: Bug import main with arguments in Python In a script I'm trying to import the main module from another script with an argument. I get the error message "NameError: global name 'model' is not defined". If someone sees the mistake, I'd be grateful ! My code : script1 #!/usr/bin/python import sys import getopt impo...
Bug import main with arguments in Python
In a script I'm trying to import the main module from another script with an argument. I get the error message "NameError: global name 'model' is not defined". If someone sees the mistake, I'd be grateful ! My code : script1 #!/usr/bin/python import sys import getopt import pdb import shelve class Car: """ class...
[ "argv is a list. Therefore you should call script1.main as\nscript1.main(['-m', 'Carrera'])\n\nor, equivalently,\nscript1.main('-m Carrera'.split())\n\n" ]
[ 3 ]
[]
[]
[ "arguments", "import", "program_entry_point", "python" ]
stackoverflow_0003556817_arguments_import_program_entry_point_python.txt
Q: How do I use Twitter Streaming API to track new followers of other accounts I don't have login information for? I'm heavily basing my code off of this excellent tutorial at Ars Technica, so I am able to track my own new followers because my login information is hard-coded in. However, I'd like to track new followe...
How do I use Twitter Streaming API to track new followers of other accounts I don't have login information for?
I'm heavily basing my code off of this excellent tutorial at Ars Technica, so I am able to track my own new followers because my login information is hard-coded in. However, I'd like to track new followers of other people's accounts too. How can I do this without their passwords? import pycurl, json, StringIO STREAM_U...
[ "Taylor Singletary of Twitter responded to the same question on the Google group for Twitter Development Talk:\n\nThis is unfortunately not currently\n possible with the Streaming API. \n Given the flexibility of followers/ids\n and friends/ids API methods, tracking \n changes over time with those methods\n wo...
[ 1 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0003523364_python_twitter.txt
Q: need checking and padding sqlite database housekeeping and manipulate code All, Update: based on google result and answer, I added more hints, still not finished. In using sqlite3 and during study of sqlalchemy, I found it is necessary to write below code for those housekeeping purpose for managing data, however,...
need checking and padding sqlite database housekeeping and manipulate code
All, Update: based on google result and answer, I added more hints, still not finished. In using sqlite3 and during study of sqlalchemy, I found it is necessary to write below code for those housekeeping purpose for managing data, however, it may be a hard part for me to doing that in sqlalchemy then I turning back to...
[ "To copy data to/from a different database, the general SQLite approach is:\n\nConnect to one database \ndb_connection = sqlite3.connect(database_file) \n\nAttach the second database\ndb_connection.execute(\"ATTACH database_file2 AS database_name2\")\n\nInsert from one to the other:\ndb_connection.execute(\"INSERT ...
[ 2 ]
[]
[]
[ "database", "python", "sqlalchemy", "sqlite" ]
stackoverflow_0003554137_database_python_sqlalchemy_sqlite.txt
Q: How to reload the modified files without restarting in pylons? I'm using pylons, and using this command to start the server: paster serve --reload development.ini I found when I modify something, the paster will reload the application. In the console, it shows: -------------------- Restarting --------------------...
How to reload the modified files without restarting in pylons?
I'm using pylons, and using this command to start the server: paster serve --reload development.ini I found when I modify something, the paster will reload the application. In the console, it shows: -------------------- Restarting -------------------- Starting server in PID 7476. serving on http://127.0.0.1:5000 This...
[ "To controllers, you can configure Routes to rescan the directory controllers without restart application:\nhttp://pylonshq.com/docs/en/1.0/controllers/#adding-controllers-dynamically\n" ]
[ 1 ]
[]
[]
[ "pylons", "python", "reload" ]
stackoverflow_0003555032_pylons_python_reload.txt
Q: Where can I find a full reference of wxpython? Sorry the question may sound stupid, but I do need one. Right now I'm just adding a wx.TextCtrl in my GUI program, and I want to know what styles can I add (such as style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER), so I googled and end up reading this page: http://www.wxpyt...
Where can I find a full reference of wxpython?
Sorry the question may sound stupid, but I do need one. Right now I'm just adding a wx.TextCtrl in my GUI program, and I want to know what styles can I add (such as style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER), so I googled and end up reading this page: http://www.wxpython.org/docs/api/wx.TextCtrl-class.html. It must be ...
[ "I find Andrea Gavana's (creator of wx.lib.agw ) documentation more comprehensive then the offical wxpython docs.\n http://xoomer.virgilio.it/infinity77/wxPython/APIMain.html\nHeres the page for the textCtrl which shows all the styles that are available.\n", "The problem is that the official docs are mostly auto-...
[ 7, 2, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003556716_python_wxpython.txt
Q: Using Mysql and sql server from python I need to write a python application with use both of the mysql and sql server is there a general python module or library that can access both mysql and sql server as DBI with perl or should i use 2 libraries and if yes which libraries do you recommend . A: I guess you ar...
Using Mysql and sql server from python
I need to write a python application with use both of the mysql and sql server is there a general python module or library that can access both mysql and sql server as DBI with perl or should i use 2 libraries and if yes which libraries do you recommend .
[ "I guess you are looking for SQLAlchemy. You will probably need some time getting into it, but it is invaluable once you have covered the basics.\nSQLAlchemy acts as a frontend to other, database-specific libraries using the Python DB-API -- but beyond this, it provides a query builder library that abstracts out d...
[ 3, 0, 0 ]
[]
[]
[ "mysql", "python", "sql_server" ]
stackoverflow_0003556342_mysql_python_sql_server.txt
Q: Printing objects and unicode, what's under the hood ? What are the good guidelines? I'm struggling with print and unicode conversion. Here is some code executed in the 2.5 windows interpreter. >>> import sys >>> print sys.stdout.encoding cp850 >>> print u"é" é >>> print u"é".encode("cp850") é >>> print u"é".encode...
Printing objects and unicode, what's under the hood ? What are the good guidelines?
I'm struggling with print and unicode conversion. Here is some code executed in the 2.5 windows interpreter. >>> import sys >>> print sys.stdout.encoding cp850 >>> print u"é" é >>> print u"é".encode("cp850") é >>> print u"é".encode("utf8") ├® >>> print u"é".__repr__() u'\xe9' >>> class A(): ... def __unicode__(self...
[ "Python doesn't have many semantic type constraints on given functions and methods, but it has a few, and here's one of them: __str__ (in Python 2.*) must return a byte string. As usual, if a unicode object is found where a byte string is required, the current default encoding (usually 'ascii') is applied in the a...
[ 8, 0 ]
[]
[]
[ "printing", "python", "stdout", "unicode" ]
stackoverflow_0003557095_printing_python_stdout_unicode.txt
Q: How to add images/bitmaps to wx.Dialog I want to add images to wx.Dialog (and then sizer) some like wx.ImageList and display it dynamically. But I don't want to change already displayed image, I want to add next. How can I resolve this problem? A: I don't think a dialog is a good choice for a growing list of im...
How to add images/bitmaps to wx.Dialog
I want to add images to wx.Dialog (and then sizer) some like wx.ImageList and display it dynamically. But I don't want to change already displayed image, I want to add next. How can I resolve this problem?
[ "I don't think a dialog is a good choice for a growing list of images, but if you have a good argument for that...\nAnyway, you should be able to display your images using the wx.StaticBitmap widget. To add another one, use your sizer's Add method, then call the dialog's Layout() method and maybe its Refresh() meth...
[ 2 ]
[]
[]
[ "image", "python", "wxpython" ]
stackoverflow_0003555065_image_python_wxpython.txt
Q: add nods and attribute list and KeyError! I have nodes with a list of attributes for each called 'times' in my case. I made a simple model like this and I get KeyError'times'. I need my graph save each node with a list of 'times' as an attribute. How can I fix it? import networkx as nx G = nx.DiGraph() for u in r...
add nods and attribute list and KeyError!
I have nodes with a list of attributes for each called 'times' in my case. I made a simple model like this and I get KeyError'times'. I need my graph save each node with a list of 'times' as an attribute. How can I fix it? import networkx as nx G = nx.DiGraph() for u in range(10): for t in range(5): if G.h...
[ "You can do\nG[u].setdefault('times', []).append(t)\n\ninstead of\nG[u]['times'].append(t)\n\n", "Try this\nimport networkx as nx\nG = nx.DiGraph()\nfor u in range(10):\n for t in range(5):\n if G.has_node(u):\n if not 'times' in G[u] # this\n G[u]['times'] = [] # and this\n ...
[ 1, 0, 0 ]
[]
[]
[ "networkx", "python" ]
stackoverflow_0003548470_networkx_python.txt
Q: Is there a way of having a GUI for bash scripts? I have some bash scripts, some simple ones to copy, search, write lines to files and so on. I am an Ubuntu. and I've searched in google, but it seems that everybody is doing that on python. I could do these on python, but since I am not a python programmer, I just k...
Is there a way of having a GUI for bash scripts?
I have some bash scripts, some simple ones to copy, search, write lines to files and so on. I am an Ubuntu. and I've searched in google, but it seems that everybody is doing that on python. I could do these on python, but since I am not a python programmer, I just know the basics. I have no idea of how calling a sh scr...
[ "\nIs there a way of having a GUI for bash scripts?\n\nYou can try using Zenity.\n\na tool that allows you to display GTK dialog boxes in commandline and shell scripts. \n\n\n\nI have no idea of how calling a sh script from a GUI written on python.\n\nYou can do this using subprocess.\nPersonally I would recommend ...
[ 7, 0, 0, 0 ]
[]
[]
[ "bash", "python", "user_interface" ]
stackoverflow_0003556027_bash_python_user_interface.txt
Q: Reading a Turtle/N3 RDF File with Python I'm trying to encode some botanical data in Turtle format, and read this data from Python using RDFLib. However, I'm having trouble, and I'm not sure if it's because my Turtle is malformed or I'm misusing RDFLib. My test data is: @PREFIX rdf: <http://www.w3.org/1999/02/22-r...
Reading a Turtle/N3 RDF File with Python
I'm trying to encode some botanical data in Turtle format, and read this data from Python using RDFLib. However, I'm having trouble, and I'm not sure if it's because my Turtle is malformed or I'm misusing RDFLib. My test data is: @PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . @PREFIX rdfs: <http://www.w3....
[ "I think the first problem is w/the uppercase PREFIX-- if you lowercase those it gets past that point. Not sure if it's a bug in rdflib or in the Turtle .ttl, but the Turtle Validator online demo seems to agree it's a problem with the .ttl (says Validation failed: The @PREFIX directive is not supported, line 1 co...
[ 10 ]
[]
[]
[ "debugging", "python", "rdflib", "semantic_web", "turtle_rdf" ]
stackoverflow_0003557561_debugging_python_rdflib_semantic_web_turtle_rdf.txt
Q: Dealing with simultaneous button presses and changing shift states I am currently working on a (Python2.5) application which handles input from a game controller. We've designated a button as a shift button to change the mapping (inputtype,value->function) of the other buttons on the fly. The mapping also depends ...
Dealing with simultaneous button presses and changing shift states
I am currently working on a (Python2.5) application which handles input from a game controller. We've designated a button as a shift button to change the mapping (inputtype,value->function) of the other buttons on the fly. The mapping also depends on the mode our application is running in. We are running into lots of h...
[ "Satemachines are a good pattern to handle complex inputs.\nHere is a machine that handle the above sequence.\n\nYou can implement statemachines with switch or state pattern (see Python state-machine design )\n" ]
[ 2 ]
[]
[]
[ "controls", "input", "joystick", "python", "user_input" ]
stackoverflow_0003557219_controls_input_joystick_python_user_input.txt
Q: How to measure Python import latencies My django application takes forever to load so I'd like to find a way to measure the import latencies so I can find the offending module and make it load lazily. Is there an obvious way to do this? I was considering tweaking the import statement itself to produce the latencie...
How to measure Python import latencies
My django application takes forever to load so I'd like to find a way to measure the import latencies so I can find the offending module and make it load lazily. Is there an obvious way to do this? I was considering tweaking the import statement itself to produce the latencies but I'm not sure exactly how to do that. I...
[ "You can redefine the __import__ built-in function to log the start and end times (delegating everything else to the original built-in __import__). That's exactly the way to \"tweak the import statement\" in Python: redefine __import__!\nEdit: here's a simple example...:\nimport sys\n\nimport __builtin__\n_orgimp ...
[ 7 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003558073_import_python.txt
Q: add Python path to PATH system variable automatically under Windows I'm creating one-click python installer (integrated with my application). Is there any way to force Python MSI installer to add python's path to SYSTEM PATH variable? I'm using MSI installer because it is very easy to specify (using command line) ...
add Python path to PATH system variable automatically under Windows
I'm creating one-click python installer (integrated with my application). Is there any way to force Python MSI installer to add python's path to SYSTEM PATH variable? I'm using MSI installer because it is very easy to specify (using command line) how it should interact with the user.
[ "There has to be a way, but what some people do is provide batch files that set up the environment before invoking Python. That's what BZR does, anyway. If you can write that batch file somewhere that's already normally in the path, so much the better.\nIf you're just worried about invoking Python, the normal Pytho...
[ 0, 0 ]
[]
[]
[ "python", "python_install" ]
stackoverflow_0003557949_python_python_install.txt
Q: How to apply __str__ function when printing a list of objects in Python Well this interactive python console snippet will tell everything: >>> class Test: ... def __str__(self): ... return 'asd' ... >>> t = Test() >>> print(t) asd >>> l = [Test(), Test(), Test()] >>> print(l) [__main__.Test instance at...
How to apply __str__ function when printing a list of objects in Python
Well this interactive python console snippet will tell everything: >>> class Test: ... def __str__(self): ... return 'asd' ... >>> t = Test() >>> print(t) asd >>> l = [Test(), Test(), Test()] >>> print(l) [__main__.Test instance at 0x00CBC1E8, __main__.Test instance at 0x00CBC260, __main__.Test instance at...
[ "Try:\nclass Test:\n def __repr__(self):\n return 'asd'\n\nAnd read this documentation link:\n", "The suggestion in other answers to implement __repr__ is definitely one possibility. If that's unfeasible for whatever reason (existing type, __repr__ needed for reasons other than aesthetic, etc), then just...
[ 54, 10, 3 ]
[]
[]
[ "list", "object", "printing", "python", "string" ]
stackoverflow_0003558474_list_object_printing_python_string.txt
Q: Pass each element of a list to a function that takes multiple arguments in Python? For example, if I have a=[['a','b','c'],[1,2,3],['d','e','f'],[4,5,6]] How can I get each element of a to be an argument of say, zip without having to type zip(a[0],a[1],a[2],a[3])? A: Using sequence unpacking (thanks to delnan ...
Pass each element of a list to a function that takes multiple arguments in Python?
For example, if I have a=[['a','b','c'],[1,2,3],['d','e','f'],[4,5,6]] How can I get each element of a to be an argument of say, zip without having to type zip(a[0],a[1],a[2],a[3])?
[ "Using sequence unpacking (thanks to delnan for the name):\nzip(*a)\n\n" ]
[ 25 ]
[ "Chain()?\nhttp://docs.python.org/library/itertools.html#itertools.chain\nnm, read it wrong. That won't work.\n" ]
[ -1 ]
[ "arguments", "function", "python" ]
stackoverflow_0003558593_arguments_function_python.txt
Q: How do I pickle an object? Here is the code I have: import pickle alist = ['here', 'there'] c = open('config.pck', 'w') pickle.dump(alist, c) and this is the error I receive: Traceback (most recent call last): File "C:\pickle.py", line 1, in ? import pickle File "C:\pickle.py", line 6, in ? pickle.dump(ali...
How do I pickle an object?
Here is the code I have: import pickle alist = ['here', 'there'] c = open('config.pck', 'w') pickle.dump(alist, c) and this is the error I receive: Traceback (most recent call last): File "C:\pickle.py", line 1, in ? import pickle File "C:\pickle.py", line 6, in ? pickle.dump(alist, c) AttributeError: 'module' ...
[ "Don't call your file pickle.py. It conflicts with the python standard libary module of the same name. So your import pickle is not picking up the python module.\n", "The code you have works fine for me.\nPython 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on\nwin32\nType \"help\", \"copy...
[ 21, 3, 1 ]
[]
[]
[ "debugging", "pickle", "python" ]
stackoverflow_0003558718_debugging_pickle_python.txt
Q: Why is my variable empty in post? This is what I'm trying to do. Have one main form with all the data and have several dialogs, from which the data will be added to the main form. After all the data is in the main form I will submit the form. But the problem is it won't save the values of the data in the dialogs w...
Why is my variable empty in post?
This is what I'm trying to do. Have one main form with all the data and have several dialogs, from which the data will be added to the main form. After all the data is in the main form I will submit the form. But the problem is it won't save the values of the data in the dialogs when I copy the html to the main form. I...
[ "I'm pretty sure values aren't passed when you call .html on a form input element. Try looping through all of the elements in your dialog and adding them as hidden elements to the form. \n$(\"select, textarea, input\", $(\"#dialog\")).each(function (i) {\n $(\"#hiddeninform\").append($(\"<input/>\").attr(\"name\...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "jquery", "jquery_ui", "python" ]
stackoverflow_0003514857_google_app_engine_jquery_jquery_ui_python.txt
Q: Python: how many similar words in string? I have some ugly strings similar to these: string1 = 'Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour)' string2 = 'Vinci, Leonardo {c.1690-1730...
Python: how many similar words in string?
I have some ugly strings similar to these: string1 = 'Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour)' string2 = 'Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Didone A...
[ "Regex could easily give you all the words:\nimport re\ns1 = \"Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour)\"\ns2 = \"Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Did...
[ 7, 2, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0003558787_python_string.txt
Q: regex to eliminate field in bibtex file I am trying to slim down the bib text files I get from my reference manager because it leaves extra fields that end up getting mangled when I put it into LaTeX. A characteristic entry that I want to clean up is: @Article{Kholmurodov:2001p113, author = {K Kholmurodov and I Pu...
regex to eliminate field in bibtex file
I am trying to slim down the bib text files I get from my reference manager because it leaves extra fields that end up getting mangled when I put it into LaTeX. A characteristic entry that I want to clean up is: @Article{Kholmurodov:2001p113, author = {K Kholmurodov and I Puzynin and W Smith and K Yasuoka and T Ebisuza...
[ "What about this regex (apply with multi-line and dotall flags):\n\n^(?:month|annote|note|abstract)\\s*=\\s*\\{(?:(?!\\},$).)*\\},[\\r\\n]+\n\nExplanation:\n\n^ # start-of-line\n(?: # non-capturing group 1\n month|annote|note|abstract # one of these terms\n)...
[ 2 ]
[]
[]
[ "bibtex", "parsing", "python", "regex" ]
stackoverflow_0003558691_bibtex_parsing_python_regex.txt
Q: Python - TypeError: unbound method So this Python problem has been giving me problems since I've tried refactoring the code into different files. I have a file called object.py and in it, the related code is: class Object: #this is a generic object: the player, a monster, an item, the stairs... #it's always repre...
Python - TypeError: unbound method
So this Python problem has been giving me problems since I've tried refactoring the code into different files. I have a file called object.py and in it, the related code is: class Object: #this is a generic object: the player, a monster, an item, the stairs... #it's always represented by a character on screen. def __i...
[ "Update\nYou are defining Object in a file called object.py. And yet the client refers to object_info.Object. Is this a typo?\n\nAlso I assume having a class called Object isn't a very good coding practice, correct?\n\nCorrect. Rename your class to something else, say GenericObject or GenericBase. Also don't use th...
[ 4, 1 ]
[]
[]
[ "attributeerror", "initialization", "python" ]
stackoverflow_0003558937_attributeerror_initialization_python.txt
Q: how do python module variables work? I used to think that once a module was loaded, no re-importing would be done if other files imported that same module, or if it were imported in different ways. For example, I have mdir/__init__.py, which is empty, and mdir/mymod.py, which is: thenum = None def setNum(n): g...
how do python module variables work?
I used to think that once a module was loaded, no re-importing would be done if other files imported that same module, or if it were imported in different ways. For example, I have mdir/__init__.py, which is empty, and mdir/mymod.py, which is: thenum = None def setNum(n): global thenum if thenum is not None: ...
[ "mymod and mdir.mymod are considered different modules - here's somewhat related discussion: http://code.djangoproject.com/ticket/3951\nExplanation:\nIt's best to play with python interactive interpreter and see for yourself. I created directory (package) mydir under some directory and inside it two files (modules)...
[ 4 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0003558979_import_module_python.txt
Q: Handling arbitrary number of command line arguments in python I am trying to have my script be able to take in an arbitrary number of file names as command line arguments. In Unix, it is possible to use the '*' key to represent any character. For example, ls blah*.txt will list every file with blah at the begin...
Handling arbitrary number of command line arguments in python
I am trying to have my script be able to take in an arbitrary number of file names as command line arguments. In Unix, it is possible to use the '*' key to represent any character. For example, ls blah*.txt will list every file with blah at the beginning and txt at the end. I need something like this for my python ...
[ "import sys\n\nfor arg in sys.argv[1:]:\n print arg\n\nIn Unix-land, the shell does the job of glob-expanding the commandline arguments, so you don't need to do it yourself. If you're processing a bunch of files in sequence, you might also look at the fileinput module, which works like Perl's \"magic ARGV\" handle...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003559477_python.txt
Q: Is there a way of using breakpoints in python? I am just wondering if there is a way to add breakpoints in IDLE so that I can stop at a point in my script and write other lines in the idle shell for testing. If not, is there other software that can do this? A: you can add the line import pdb; pdb.set_trace() an...
Is there a way of using breakpoints in python?
I am just wondering if there is a way to add breakpoints in IDLE so that I can stop at a point in my script and write other lines in the idle shell for testing. If not, is there other software that can do this?
[ "you can add the line\nimport pdb; pdb.set_trace()\n\nanywhere in your code, when reached it will drop you into a debug shell. so useful i have an emacs shortcut to add the snippet.\nyou may also want to look at ipdb, and use\nimport ipdb; ipdb.set_trace()\n\ninstead\n", "http://docs.python.org/library/pdb.html\...
[ 6, 3, 1 ]
[]
[]
[ "breakpoints", "debugging", "python" ]
stackoverflow_0003555945_breakpoints_debugging_python.txt
Q: How to check that a path is an existing regular file and not a directory? One script is used to exchange file information amongst teams. It is used as: $ share.py -p /path/to/file.txt The argument checking ensures that /path/to/file.txt exists and has the correct permissions: #[...] # ensure that file exists and ...
How to check that a path is an existing regular file and not a directory?
One script is used to exchange file information amongst teams. It is used as: $ share.py -p /path/to/file.txt The argument checking ensures that /path/to/file.txt exists and has the correct permissions: #[...] # ensure that file exists and is readable if not os.access(options.path, os.F_OK): raise MyError('the file d...
[ "import os.path\nos.path.isfile(filename)\n\n", "os.path.exists(path) and not os.path.isdir(path)\n\n" ]
[ 9, 4 ]
[]
[]
[ "file", "python" ]
stackoverflow_0003559617_file_python.txt
Q: If you import yourself in Python, why don't you get an infinite loop? This question is a response to the following SO post: How do I pickle an object? In that thread, the OP accidentally imports his own module at the top of the same module. Why doesn't this cause an infinite loop? A: Modules are imported only on...
If you import yourself in Python, why don't you get an infinite loop?
This question is a response to the following SO post: How do I pickle an object? In that thread, the OP accidentally imports his own module at the top of the same module. Why doesn't this cause an infinite loop?
[ "Modules are imported only once. Python realizes it already has been imported, so does not do it again.\nSee: http://docs.python.org/tutorial/modules.html#more-on-modules\n", "When Python encounters an import statement, it checks sys.modules for the presence of the module first before doing anything\n", "import...
[ 12, 5, 2, 2, 2 ]
[]
[]
[ "import", "infinite_loop", "python" ]
stackoverflow_0003558842_import_infinite_loop_python.txt
Q: modifying list elements How can I modify the list below: [('AAA', '1-1', 1, (1.11, (2.22, 3.33))), ('BBB', '2-2', 2, (4.44, (5.55, 6.66))), ('CCC', '3-3', 3, (7, (8, 9)))] into something like this: [('AAA', '1-1', 1, 1.11, 2.22, 3.33), ('BBB', '2-2', 2, 4.44, 5.55, 6.66), ('CCC', '3-3', 3, 7, 8, 9)] Many thanks ...
modifying list elements
How can I modify the list below: [('AAA', '1-1', 1, (1.11, (2.22, 3.33))), ('BBB', '2-2', 2, (4.44, (5.55, 6.66))), ('CCC', '3-3', 3, (7, (8, 9)))] into something like this: [('AAA', '1-1', 1, 1.11, 2.22, 3.33), ('BBB', '2-2', 2, 4.44, 5.55, 6.66), ('CCC', '3-3', 3, 7, 8, 9)] Many thanks in advance.
[ "It looks like you want to flatten the tuples that are members of the outer list?\nTry this:\n>>> def flatten(lst):\n return sum( ([x] if not isinstance(x, (list, tuple)) else flatten(x)\n for x in lst), [] )\n\n>>> def modify(lst):\n return [tuple(flatten(x)) for x in lst]\n\n>>> x = [('AAA', '1-...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003559729_python.txt
Q: Need to delete part of text lines in python I have the following problem. I have a list of different text lines that all has a comma in it. I want to keep the text to the left of the comma and delete everything that occurs after the comma for all the lines in the file. Here is a sample line from the file: 1780375...
Need to delete part of text lines in python
I have the following problem. I have a list of different text lines that all has a comma in it. I want to keep the text to the left of the comma and delete everything that occurs after the comma for all the lines in the file. Here is a sample line from the file: 1780375 "004956 , down , 943794 , 22634 , ET , 2115 , I...
[ "You can use split for this. It splits the string on a given substring. As you only need the first part, I set 1 as the second parameter to make it only split on the first one.\nInstead of using a counter, you could use enumerate, like this:\ndatafile = open('C:\\\\middlelist3.txt', 'r')\n\nsmallerdataset = open('C...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003559939_python.txt
Q: merge sort in python basically I have a bunch of files containing domains. I've sorted each individual file based on its TLD using .sort(key=func_that_returns_tld) now that I've done that I want to merge all the files and end up wtih one massive sorted file. I assume I need something like this: open all files read...
merge sort in python
basically I have a bunch of files containing domains. I've sorted each individual file based on its TLD using .sort(key=func_that_returns_tld) now that I've done that I want to merge all the files and end up wtih one massive sorted file. I assume I need something like this: open all files read one line from each file i...
[ "If your files are not very large, then simply read them all into memory (as S. Lott suggests). That would definitely be simplest. \nHowever, you mention collation creates one \"massive\" file. If it's too massive to fit in memory, then perhaps use heapq.merge. It may be a little harder to set up, but it has the ad...
[ 8, 0, 0 ]
[]
[]
[ "merge", "python", "sorting" ]
stackoverflow_0003559807_merge_python_sorting.txt
Q: How to scroll an inactive Tkinter ListBox? I'm writing a Tkinter GUI in Python. It has an Entry for searching with a results ListBox below it. The ListBox also has a Scrollbar. How can I get scrolling with the mouse and arrow keys to work in the ListBox without switching focus away from the search field? IE I want...
How to scroll an inactive Tkinter ListBox?
I'm writing a Tkinter GUI in Python. It has an Entry for searching with a results ListBox below it. The ListBox also has a Scrollbar. How can I get scrolling with the mouse and arrow keys to work in the ListBox without switching focus away from the search field? IE I want the user to be able to type a search, scroll ar...
[ "Add bindings to the entry widget that call the listbox yview and/or see commands when the user presses up and down or uses the up/down scrollwheel.\nFor example, you can do something like this for the arrow keys:\nclass App(Tkinter.Tk):\n def __init__(self):\n Tkinter.Tk.__init__(self)\n self.entr...
[ 6 ]
[]
[]
[ "events", "listbox", "python", "scroll", "tkinter" ]
stackoverflow_0003559673_events_listbox_python_scroll_tkinter.txt
Q: blank space in the top of the plot matplotlib django I've a question about matplotlib bars. I've already made some bar charts but I don't know why, this one left a huge blank space in the top. the code is similar to other graphics I've made and they don't have this problem. If anyone has any idea, I appreciate th...
blank space in the top of the plot matplotlib django
I've a question about matplotlib bars. I've already made some bar charts but I don't know why, this one left a huge blank space in the top. the code is similar to other graphics I've made and they don't have this problem. If anyone has any idea, I appreciate the help. x = matplotlib.numpy.arange(0, max(total)) ind = m...
[ "By \"blank space in the top\" do you mean that the y-limits are set too large?\nBy default, matplotlib will choose the x and y axis limits so that they're rounded to the closest \"even\" number (e.g. 1, 2, 12, 5, 50, -0.5 etc...).\nIf you want the axis limits to be set so that they're \"tight\" around the plot (i....
[ 7 ]
[]
[]
[ "django", "matplotlib", "python" ]
stackoverflow_0003558950_django_matplotlib_python.txt
Q: Problems defining install-platlib in pydistutils.cfg -- According to the docs I should be able to simply define this in my ~/.pydistutils.cfg and be off and running. [install] install-base=$HOME install-purelib=python/lib install-platlib=python/lib.$PLAT install-scripts=python/scripts install-data=python/data But...
Problems defining install-platlib in pydistutils.cfg --
According to the docs I should be able to simply define this in my ~/.pydistutils.cfg and be off and running. [install] install-base=$HOME install-purelib=python/lib install-platlib=python/lib.$PLAT install-scripts=python/scripts install-data=python/data But - when I do this I simply get this error... error: install-...
[ "You MUST include this..\ninstall-headers=python/??\n\nSo the final looks like this..\n[install]\ninstall-base=$HOME\ninstall-purelib=python/lib\ninstall-platlib=python/lib.$PLAT\ninstall-scripts=python/scripts\ninstall-headers=python/include\ninstall-data=python/data\n\n" ]
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0003560865_python.txt
Q: i need to do object cleanup when instance is deleted, but not on exit. can an instance delete itself? i'd like to do some cleanup whenever an instance is deleted at runtime, but not during garbage collection that happens on exit. in the example below, when c is deleted, a file is removed, and this is what i want; ...
i need to do object cleanup when instance is deleted, but not on exit. can an instance delete itself?
i'd like to do some cleanup whenever an instance is deleted at runtime, but not during garbage collection that happens on exit. in the example below, when c is deleted, a file is removed, and this is what i want; however, that file is also removed when the program exits, and this is NOT what i want. class C: def __de...
[ "CPython uses reference counting and only runs a fully-fledged GC (that removes cyclic references) once in a while, c = C(); del c would trigger the new C to be gc'd right away, yeah. As for __del__ and interpreter exit, the docs say:\n\nIt is not guaranteed that __del__() methods are called for objects that still ...
[ 4, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003560804_oop_python.txt
Q: Problem with dragging mouse cursor with Python Could someone tell me why this doesn't work? def selectAndCopy(x,y,z,w): ctypes.windll.user32.SetCursorPos(x,y) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0) time.sleep(1) ctypes.windll.user32.SetCursorPos(z,w) time...
Problem with dragging mouse cursor with Python
Could someone tell me why this doesn't work? def selectAndCopy(x,y,z,w): ctypes.windll.user32.SetCursorPos(x,y) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0) time.sleep(1) ctypes.windll.user32.SetCursorPos(z,w) time.sleep(1) win32api.mouse_event(win32con.MOUSEEVE...
[ "Don't reinvent the wheel! There's the package pywinauto that has a ready-to-use function for this:\npywinauto.controls.HwndWrapper.DragMouse(button='left', pressed='', \n press_coords=(0, 0), \n release_coords=(0, 0))\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003560901_python.txt
Q: URL is appended to WSGI script's path, why? I have a development server set up running Apache 2.2 with mod_wsgi. I have a test project and a webapp in development setup, and they half work. When I attempt to access something other than the project's landing page, Apache appends the rest of the URL onto the path of...
URL is appended to WSGI script's path, why?
I have a development server set up running Apache 2.2 with mod_wsgi. I have a test project and a webapp in development setup, and they half work. When I attempt to access something other than the project's landing page, Apache appends the rest of the URL onto the path of the WSGI script and won't load the page. In http...
[ "Use /dubserv and not /dubserv/ with WSGIScriptAlias. The instructions shouldn't show a trailing slash and so one should not be included.\n" ]
[ 0 ]
[]
[]
[ "apache2", "django", "mod_wsgi", "python" ]
stackoverflow_0003558795_apache2_django_mod_wsgi_python.txt
Q: python, datetime.date: difference between two days I'm playing around with 2 objects {@link http://docs.python.org/library/datetime.html#datetime.date} I would like to calculate all the days between them, assuming that date 1 >= date 2, and print them out. Here is an example what I would like to achieve. But I do...
python, datetime.date: difference between two days
I'm playing around with 2 objects {@link http://docs.python.org/library/datetime.html#datetime.date} I would like to calculate all the days between them, assuming that date 1 >= date 2, and print them out. Here is an example what I would like to achieve. But I don't think this is efficient at all. Is there a better wa...
[ "I don't see this as particularly inefficient, but you could make it slightly cleaner without the while loop:\ndelta = dateTo - dateFrom\n\nfor delta_day in range(0, delta.days+1): # Or use xrange in Python 2.x\n print dateFrom + datetime.timedelta(delta_day)\n\n(Also, notice how printing or using str on a date ...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0003561183_python.txt
Q: Django many-to-many problem in admin I am essentially creating a blog application in django as a way of learning the ropes and boosting my skill level in django. I basically have a many-to-many relationship that I am having problems with in the admin site. I have two main types, Article and ArticleTag. Many Articl...
Django many-to-many problem in admin
I am essentially creating a blog application in django as a way of learning the ropes and boosting my skill level in django. I basically have a many-to-many relationship that I am having problems with in the admin site. I have two main types, Article and ArticleTag. Many Articles can belong to many ArticleTags, and the...
[ "You forgot to specify blank=True in your ManyToManyField declaration:\nclass Article(models.Model):\n tags = models.ManyToManyField(ArticleTag, blank=True, \n related_name=\"articles\")\n\n\nAlso, is there a fairly easy way to create a control to facilitate tagging as per stack overflow or delicious.com?...
[ 3 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0003561508_django_django_admin_django_models_python.txt
Q: Confusing loop problem (python) this is similar to the question in merge sort in python I'm restating because I don't think I explained the problem very well over there. basically I have a series of about 1000 files all containing domain names. altogether the data is > 1gig so I'm trying to avoid loading all the...
Confusing loop problem (python)
this is similar to the question in merge sort in python I'm restating because I don't think I explained the problem very well over there. basically I have a series of about 1000 files all containing domain names. altogether the data is > 1gig so I'm trying to avoid loading all the data into ram. each individual file ...
[ "Whether you're able to keep 1000 files at once is a separate issue and depends on your OS and its configuration; if not, you'll have to proceed in two steps -- merge groups of N files into temporary ones, then merge the temporary ones into the final-result file (two steps should suffice, as they let you merge a to...
[ 6, 3, 2, 1, 0 ]
[]
[]
[ "loops", "python", "sorting" ]
stackoverflow_0003561221_loops_python_sorting.txt
Q: Decimal to hex in python So I have kind of a ignorant (maybe?) question. I'm working with writing to a serial device for the first time. I have a frame [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, X, Y] that I need to send. X and Y are checksum values. My understanding in using the pyserial module is that I need to convert thi...
Decimal to hex in python
So I have kind of a ignorant (maybe?) question. I'm working with writing to a serial device for the first time. I have a frame [12, 0, 0, 0, 0, 0, 0, 0, 7, 0, X, Y] that I need to send. X and Y are checksum values. My understanding in using the pyserial module is that I need to convert this frame into a string represen...
[ "It's perfectly normal for ASCII bytes to be represented by single characters if they can be printed, and by the \\x?? notation otherwise. In both cases they represent a single byte, and you can write strings in either fashion:\n>>> '\\x68\\x65\\x6c\\x6c\\x6f'\n'hello'\n\nHowever if you're using Python 2.6 or later...
[ 3, 1, 0, 0 ]
[]
[]
[ "hex", "python", "serial_port" ]
stackoverflow_0003561117_hex_python_serial_port.txt
Q: Dissecting a line of (obfuscated?) Python I was reading another question on Stack Overflow (Zen of Python), and I came across this line in Jaime Soriano's answer: import this "".join([c in this.d and this.d[c] or c for c in this.s]) Entering the above in a Python shell prints: "The Zen of Python, by Tim Peters\n\...
Dissecting a line of (obfuscated?) Python
I was reading another question on Stack Overflow (Zen of Python), and I came across this line in Jaime Soriano's answer: import this "".join([c in this.d and this.d[c] or c for c in this.s]) Entering the above in a Python shell prints: "The Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is be...
[ "The operators in the list comprehension line associate like this:\n\"\".join([(((c in this.d) and this.d[c]) or c) for c in this.s])\n\nRemoving the list comprehension:\nresult = []\nfor c in this.s:\n result.append(((c in this.d) and this.d[c]) or c)\nprint \"\".join(result)\n\nRemoving the and/or boolean trick...
[ 11, 2, 2, 2, 2, 0 ]
[]
[]
[ "control_flow", "execution", "obfuscation", "python" ]
stackoverflow_0003559124_control_flow_execution_obfuscation_python.txt
Q: Where are Python dylibs installed on the Mac? On Mac OSX 10.6.4 where do you install dynamic libraries (dylib) so Python 2.6.1 can import them? I've tried placing them in /usr/local/lib and usr/localbin and /Library/Python/2.6/site-packages but none of these locations have worked. The library I'm trying to install...
Where are Python dylibs installed on the Mac?
On Mac OSX 10.6.4 where do you install dynamic libraries (dylib) so Python 2.6.1 can import them? I've tried placing them in /usr/local/lib and usr/localbin and /Library/Python/2.6/site-packages but none of these locations have worked. The library I'm trying to install is libevecache.dylib a library to access cache fil...
[ "Anywhere in your $DYLD_LIBRARY_PATH should work for compiled library files; you can also try setting $PYTHONPATH / sys.path.\n", "Run the included setup.py file. You should never try to copy things into place manually; it'll lead to disaster, especially in situations involving pip or easy_install.\n" ]
[ 0, 0 ]
[]
[]
[ "dylib", "macos", "python" ]
stackoverflow_0003561209_dylib_macos_python.txt
Q: Django utf-8 and django-mailer strangeness Latest django mailer from trunk http://github.com/jtauber/django-mailer/tree/master/docs/ Tested with Postgresql 8.4, sqlite3 template {{ title }} forms.py #-*- coding: utf-8 -*- if "mailer" in settings.INSTALLED_APPS: from mailer import send_mail else: from dja...
Django utf-8 and django-mailer strangeness
Latest django mailer from trunk http://github.com/jtauber/django-mailer/tree/master/docs/ Tested with Postgresql 8.4, sqlite3 template {{ title }} forms.py #-*- coding: utf-8 -*- if "mailer" in settings.INSTALLED_APPS: from mailer import send_mail else: from django.core.mail import send_mail ... bod...
[ "U+00E9 is LATIN SMALL LETTER E WITH ACUTE.\nThis MAY be the source (not necessarily the cause) of the problem: 'title':u\"éééààà\",.\nCause may be something like your_title.encode('latin1').decode('utf8') (not in one step, of course).\n" ]
[ 0 ]
[]
[]
[ "django", "encoding", "mailer", "python", "utf_8" ]
stackoverflow_0003559855_django_encoding_mailer_python_utf_8.txt
Q: how remove special characters from the end of every word in a string? i want it match only the end of every word example: "i am test-ing., i am test.ing-, i am_, test_ing," output should be: "i am test-ing i am test.ing i am test_ing" A: >>> import re >>> test = "i am test-ing., i am test.ing-, i am_, test_ing...
how remove special characters from the end of every word in a string?
i want it match only the end of every word example: "i am test-ing., i am test.ing-, i am_, test_ing," output should be: "i am test-ing i am test.ing i am test_ing"
[ ">>> import re\n>>> test = \"i am test-ing., i am test.ing-, i am_, test_ing,\"\n>>> re.sub(r'([^\\w\\s]|_)+(?=\\s|$)', '', test)\n'i am test-ing i am test.ing i am test_ing'\n\nMatches one or more non-alphanumeric characters ([^\\w\\s]|_) followed by either a space (\\s) or the end of the string ($). The (?= ) con...
[ 6 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003561999_python_regex.txt
Q: Need help with basic function - Python want to count the number of times a letter appears in a string, having issues here. any help def countLetters(string, character): count = 0 for character in string: if character == character: count = count + 1 print count A: The others have c...
Need help with basic function - Python
want to count the number of times a letter appears in a string, having issues here. any help def countLetters(string, character): count = 0 for character in string: if character == character: count = count + 1 print count
[ "The others have covered the errors of your function. Here's an alternative way of doing what you want. Python's built-in string method count() returns the number of occurrences of a string.\nx = \"Don't reinvent the wheel.\"\nx.count(\"e\")\n\nGives:\n5\n\n", "if character == character:\n\ncharacter will always ...
[ 10, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003562057_python.txt
Q: Pre-configured Python web framework with Authentication, Profiles, etc I want port some my Python scripts into web apps so that others can use it and I'll use some sort of web framework. I've been playing around with Django lately but it doesn't have the basic user registration, email verification stuff built in a...
Pre-configured Python web framework with Authentication, Profiles, etc
I want port some my Python scripts into web apps so that others can use it and I'll use some sort of web framework. I've been playing around with Django lately but it doesn't have the basic user registration, email verification stuff built in and one would probably end up using django-registration. Almost all web appli...
[ "Take a look at Pinax ( http://pinaxproject.com/ ), which consists of a set of Django apps that take care of some of the most common tasks. Including the user registration one you outlined.\nHowever, this is actually not very difficult to build. You are right, most sides need it, but implementing it even from scrat...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003557832_python.txt
Q: How do I determine the appropriate check interval? I'm just starting to work on a tornado application that is having some CPU issues. The CPU time will monotonically grow as time goes by, maxing out the CPU at 100%. The system is currently designed to not block the main thread. If it needs to do something that ...
How do I determine the appropriate check interval?
I'm just starting to work on a tornado application that is having some CPU issues. The CPU time will monotonically grow as time goes by, maxing out the CPU at 100%. The system is currently designed to not block the main thread. If it needs to do something that blocks and asynchronous drivers aren't available, it wil...
[ "The first thing I would check for would be to ensure that you're properly exiting threads. It's very hard to figure out what's going on with just your description to go from, but you use the word \"monotonically,\" which implies that CPU use is tied to time rather than to load.\nYou may very well be running into t...
[ 1 ]
[]
[]
[ "gil", "multithreading", "python", "tornado" ]
stackoverflow_0003559457_gil_multithreading_python_tornado.txt
Q: Should I make a copy of the instance of a class to achieve this? If yes, how do I do it? Sorry if the title is not very clear. I was not sure about the appropriate title. Let me explain what I need. I am doing multiple runs of a simulation, where each run corresponds to a different seed. However, I want the start...
Should I make a copy of the instance of a class to achieve this? If yes, how do I do it?
Sorry if the title is not very clear. I was not sure about the appropriate title. Let me explain what I need. I am doing multiple runs of a simulation, where each run corresponds to a different seed. However, I want the starting characteristics of the instances of a class to remain the same across the different runs. ...
[ "From what I understand, you always want your initial conditions (e.g. the state of city before you even get to your loop) to be the same. If that's the case, I would prefer to just reinitialize the class whenever you run through the loop, as it's much clearer.\ninitargs = 21, 50000\ninitkwargs = {car: 'blue', mak...
[ 2 ]
[]
[]
[ "class", "copy", "python" ]
stackoverflow_0003562034_class_copy_python.txt
Q: Python, string (consisting of variable and strings, concatenated) used as new variable name? I've been searching on this but am coming up a little short on exactly how to do specifically what i am trying to do.. I want to concatentate a string (I guess it would be a string in this case as it has a variable and str...
Python, string (consisting of variable and strings, concatenated) used as new variable name?
I've been searching on this but am coming up a little short on exactly how to do specifically what i am trying to do.. I want to concatentate a string (I guess it would be a string in this case as it has a variable and string) such as below, where I need to use a variable consisting of a string to call a listname that ...
[ "This is not recommended. Use a dict instead.\nvars['list%s' % toreplacetype][5] = ...\n\n", "Hrm...\nglobals()['list%s'% toreplacetype][toreplace_indx]\n\n", "replacement_string = 'list'+toreplacetype+'['+str(toreplace_indx)+']'\n\nwill yield listtype[5] when you print it.\nYou need to basically break it into ...
[ 1, 1, 0 ]
[]
[]
[ "concatenation", "python", "variables" ]
stackoverflow_0003562386_concatenation_python_variables.txt
Q: Basic Financial Library for Python I am looking for a financial library for Python that will enable me to do a discounted cash flow analysis. I have looked around and found the QuantLib, which is overkill for what I want to do. I just need a small library that I can use to input a series of cash flows and have i...
Basic Financial Library for Python
I am looking for a financial library for Python that will enable me to do a discounted cash flow analysis. I have looked around and found the QuantLib, which is overkill for what I want to do. I just need a small library that I can use to input a series of cash flows and have it output a net present value and interna...
[ "Just for completeness, since I'm late: \nnumpy has some functions for (very) basic financial calculations. numpy, scipy could also be used, to do the calculations from the basic formulas as in R.\nnet present value of cashflow\n>>> cashflow = 2*np.ones(6)\n>>> cashflow[-1] +=100\n>>> cashflow\narray([ 2., 2.,...
[ 12, 3 ]
[]
[]
[ "finance", "python" ]
stackoverflow_0002259379_finance_python.txt
Q: Monitor Multiple Pylons Application Are there any tools that I can run on my server to monitor multiple Pylons applications? I need to monitor the number of requests each application receives, how much memory each application is using, how much of the cpu is being used and other stats similar to those. I need to s...
Monitor Multiple Pylons Application
Are there any tools that I can run on my server to monitor multiple Pylons applications? I need to monitor the number of requests each application receives, how much memory each application is using, how much of the cpu is being used and other stats similar to those. I need to see the stats for each individual Pylons a...
[ "You probably want to use something like Zenoss.\nThere is some specific nginx integration graphs here: http://community.zenoss.org/docs/DOC-7441\n", "If your server is unix-like, you have a lot of tools that helps with processes monitoring such as ps, top, lsof etc.\nTo monitor the requests to the server, depend...
[ 2, 1 ]
[]
[]
[ "monitoring", "nginx", "pylons", "python" ]
stackoverflow_0003518149_monitoring_nginx_pylons_python.txt
Q: Is it possible in numpy to use advanced list slicing and still get a view? In other words, I want to do something like A[[-1, 0, 1], [2, 3, 4]] += np.ones((3, 3)) instead of A[-1:3, 2:5] += np.ones((1, 3)) A[0:2, 2:5] += np.ones((2, 3)) A: If I understand correctly, you can do what you want to do with the foll...
Is it possible in numpy to use advanced list slicing and still get a view?
In other words, I want to do something like A[[-1, 0, 1], [2, 3, 4]] += np.ones((3, 3)) instead of A[-1:3, 2:5] += np.ones((1, 3)) A[0:2, 2:5] += np.ones((2, 3))
[ "If I understand correctly, you can do what you want to do with the following:\nA[[[-1],[0],[1]],[2,3,4]] += np.ones((3, 3))\n\nHowever, the numpy folks made a function, ix_, to make it a little bit easier:\nA[np.ix_([-1,0,1],[2,3,4])] += np.ones((3, 3))\n\nI hope that helps. \n" ]
[ 3 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0003562387_numpy_python.txt
Q: How to access Gmail's "Send" button using Selenium RC for Java or C# or Python I have tried this probably 6 or 7 different ways, such as using various attribute values, XPath, id pattern matching (it always matches ":\w\w"), etc. as locators, and nothing has worked. If anyone can give me a tested, confirmed-workin...
How to access Gmail's "Send" button using Selenium RC for Java or C# or Python
I have tried this probably 6 or 7 different ways, such as using various attribute values, XPath, id pattern matching (it always matches ":\w\w"), etc. as locators, and nothing has worked. If anyone can give me a tested, confirmed-working locator string for this button, I'd be much obliged.
[ "If you want to emulate a click on the button, just go to #compose.\n", "If you're using Python, use the mechanize library and access Gmail's HTML version. The Send button is simply a form submit button.\nimport re\nimport mechanize\n\nbr = mechanize.Browser()\nbr.open(\"http://htmlversionofgmail.com/composewind...
[ 0, 0 ]
[]
[]
[ "c#", "gmail", "java", "python", "selenium_rc" ]
stackoverflow_0003561993_c#_gmail_java_python_selenium_rc.txt
Q: How to check if DataStore Indexes are being served on AppEngine? How can I check if datastore Indexes as defined in index.yaml are serving in the python code? I am using Python 1.3.6 AppEngine SDK. A: Attempt to perform a query that requires that index. If it raises a NeedIndexError, it's not uploaded or not ye...
How to check if DataStore Indexes are being served on AppEngine?
How can I check if datastore Indexes as defined in index.yaml are serving in the python code? I am using Python 1.3.6 AppEngine SDK.
[ "Attempt to perform a query that requires that index. If it raises a NeedIndexError, it's not uploaded or not yet serving.\n", "I don't think there's a way to check without adding some logging to the SDK code. If you're using the SQLite stub, __FindIndexForQuery, lines 1114-1140, is the part that looks for appli...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003562466_google_app_engine_python.txt
Q: Polymorphism or Inheritance or any other suggestion? I trying my hands on python. I am trying to implement a crypto class which does enc/dec . In my crypto class i require user to pass 3 args to do the enc dec operations. Till now i was reading key from file and doing the operations. Now i want to provide a genera...
Polymorphism or Inheritance or any other suggestion?
I trying my hands on python. I am trying to implement a crypto class which does enc/dec . In my crypto class i require user to pass 3 args to do the enc dec operations. Till now i was reading key from file and doing the operations. Now i want to provide a generate key function also. But problem is that to call generate...
[ "You want a factory with either inherited or duck-typed objects. For example:\nclass CryptoBasic(object):\n\n def __init__(self, *args):\n \"\"\"Do what you need to do.\"\"\"\n\n def basic_method(self, *args):\n \"\"\"Do some basic method.\"\"\"\n\nclass CryptoExtended(CryptoBasic):\n\n def _...
[ 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003562972_oop_python.txt
Q: How to decode the pixels in a JPG in App Engine (using pure python)? Using python App Engine I need to convert a JPG image that is one 9 MB file (of Pakistan's floods) into many PNG tiles. For the PNG part, I already know how to use PyPNG, which is great. Note: PIL cant be used with App Engine. So how do I decode...
How to decode the pixels in a JPG in App Engine (using pure python)?
Using python App Engine I need to convert a JPG image that is one 9 MB file (of Pakistan's floods) into many PNG tiles. For the PNG part, I already know how to use PyPNG, which is great. Note: PIL cant be used with App Engine. So how do I decode the JPG into pixel data?
[ "Using Image class and crop and execute_transforms to encode as png? \nNote: You should provide relevant part of your code\n", "You can use the efforts here to get a pure python JPEG Parser. Why the absolute need to use App Engine ? If you want more flexible library usage try EC2.\n" ]
[ 2, 1 ]
[]
[]
[ "google_app_engine", "jpeg", "python" ]
stackoverflow_0003562958_google_app_engine_jpeg_python.txt
Q: Can search(r'(ab)+', "ababababab") match all the characters in python I found that findall(r'(ab)+', "ababababab") can only match the ["ab"] >>> re.findall(r'(ab)+', "ababababab") ['ab'] i just know that using r'(?:ab)+' can match all the characters >>> re.findall(r'(?:ab)+', "ababababab") ['ababababab'] Why do...
Can search(r'(ab)+', "ababababab") match all the characters in python
I found that findall(r'(ab)+', "ababababab") can only match the ["ab"] >>> re.findall(r'(ab)+', "ababababab") ['ab'] i just know that using r'(?:ab)+' can match all the characters >>> re.findall(r'(?:ab)+', "ababababab") ['ababababab'] Why does this happen? Sorry,i may not speak my question clearly (?:ab) takes 'ab...
[ "I think the question you are asking here is why does it return this:\n>>> re.findall(r'(ab)+', \"ababababab\")\n['ab']\n\nThe answer is that if you have one or more groups in the pattern then findall will return a list with all the matched groups. However your regex has one group that is matched multiple times wi...
[ 6, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003563318_python_regex.txt
Q: Django: output aggregation of aggregation ordered by counts I'm trying to output the following data in my django templates. Countries would be ordered descending by # of stories. Cities would be ordered descending by # of stories (under that country) Country A(# of stories) City A (# of stories) City B (# of s...
Django: output aggregation of aggregation ordered by counts
I'm trying to output the following data in my django templates. Countries would be ordered descending by # of stories. Cities would be ordered descending by # of stories (under that country) Country A(# of stories) City A (# of stories) City B (# of stories) Country B(# of stories) City A (# of stories) City B...
[ "This solution worked for me. You will need to tweak it to pass it to a template though.\nfrom django.db.models import Count\nall_countries = Country.objects.annotate(Count('story')).order_by('-story__count')\n\nfor country in all_countries:\n print \"Country %s (%s)\" % (country.name, country.story__count)\n ...
[ 0 ]
[]
[]
[ "aggregate", "django", "python" ]
stackoverflow_0003562036_aggregate_django_python.txt
Q: How do I set a Jabber status with python-xmpp? How do I set a GChat or jabber status via python? Right now I've got this: import xmpp new_status = "blah blah blah" login = 'email' pwd = 'password' cnx = xmpp.Client('gmail.com') cnx.connect( server=('talk.google.com',5223) ) cnx.auth(login, pwd, 'botty')...
How do I set a Jabber status with python-xmpp?
How do I set a GChat or jabber status via python? Right now I've got this: import xmpp new_status = "blah blah blah" login = 'email' pwd = 'password' cnx = xmpp.Client('gmail.com') cnx.connect( server=('talk.google.com',5223) ) cnx.auth(login, pwd, 'botty') pres = xmpp.Presence() pres.setStatus(new_status) ...
[ "You might want to take a look at this file:\nhttp://steliosm.net/projects/picaxejabber/picaxe_xmpp.py\nEdit:\nMy bad, first answer was out of context, I've misread your code.\ncnx.sendInitPresence()\n\nYou haven't send your initial state I guess ...\n", "NOTE: wanted to mention this to those who want to do what'...
[ 1, 1 ]
[]
[]
[ "chat", "python", "status", "xmpp" ]
stackoverflow_0002473487_chat_python_status_xmpp.txt
Q: Google map plotting I was wondering if anyone has any ideas/tutorials on how to plot various points on a google map, and save the points in a database with custom marker titles. I want something similar to http://www.mapmyrun.com/create_new , where i can actually draw on a map and mark out paths and such. A: Plo...
Google map plotting
I was wondering if anyone has any ideas/tutorials on how to plot various points on a google map, and save the points in a database with custom marker titles. I want something similar to http://www.mapmyrun.com/create_new , where i can actually draw on a map and mark out paths and such.
[ "Plotting the points is done in Javascript, I managed to learn everything I needed from the maps API docs:\nhttp://code.google.com/apis/maps/documentation/javascript/basics.html\nI scraped the code below off a site I made which moves a single point to where the mouse is clicked. You should be able to store a set of...
[ 1 ]
[]
[]
[ "google_maps", "path", "php", "python" ]
stackoverflow_0003563885_google_maps_path_php_python.txt
Q: __del__ at program end Suppose there is a program with a couple of objects living in it at runtime. Is the __del__ method of each object called when the programs ends? If yes I could for example do something like this: class Client: __del__( self ): disconnect_from_server() A: There are many potential diff...
__del__ at program end
Suppose there is a program with a couple of objects living in it at runtime. Is the __del__ method of each object called when the programs ends? If yes I could for example do something like this: class Client: __del__( self ): disconnect_from_server()
[ "There are many potential difficulties associated with using __del__.\nUsually, it is not necessary, or the best idea to define it yourself.\nInstead, if you want an object that cleans up after itself upon exit or an exception, use a context manager:\nper Carl's comment:\nclass Client:\n def __exit__(self,ext_ty...
[ 7, 5, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003554952_python.txt
Q: Decorator changing function status from method to function [Updated]: Answer inline below question I have an inspecting program and one objective is for logic in a decorator to know whether the function it is decorating is a class method or regular function. This is failing in a strange way. Below is code run in...
Decorator changing function status from method to function
[Updated]: Answer inline below question I have an inspecting program and one objective is for logic in a decorator to know whether the function it is decorating is a class method or regular function. This is failing in a strange way. Below is code run in Python 2.6: def decorate(f): print 'decorator thinks functi...
[ "As others have said, a function is decorated before it is bound, so you cannot directly determine whether it's a 'method' or 'function'.\nA reasonable way to determine if a function is a method or not is to check whether 'self' is the first parameter. While not foolproof, most Python code adheres to this conventio...
[ 5, 3, 1, 0 ]
[]
[]
[ "decorator", "inspection", "python" ]
stackoverflow_0003564049_decorator_inspection_python.txt
Q: Python, mechanize, proper syntax for setting multiple headers? I can't seem to find how to do this anywere, I am trying to set multiple headers with python's mechanize module, such as: br.addheaders = [('user-agent', ' Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefo...
Python, mechanize, proper syntax for setting multiple headers?
I can't seem to find how to do this anywere, I am trying to set multiple headers with python's mechanize module, such as: br.addheaders = [('user-agent', ' Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3')] br.addheaders = [('accept', 'text/html,application/xhtml+...
[ "According to http://wwwsearch.sourceforge.net/mechanize/doc.html#adding-headers, the syntax would be \nbr.addheaders = [('user-agent', ' Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.3) Gecko/20100423 Ubuntu/10.04 (lucid) Firefox/3.6.3'),\n('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;...
[ 10 ]
[]
[]
[ "http_headers", "mechanize", "python", "webautomation" ]
stackoverflow_0003564509_http_headers_mechanize_python_webautomation.txt
Q: Create and retrieve object list in Python I would like to keep a reference of the objects I've created in one script to use them in another script (without using shelve). I would like something close to : script 1 class Porsche(Car): """ class representing a Porsche """ def __init__(self, color): ...
Create and retrieve object list in Python
I would like to keep a reference of the objects I've created in one script to use them in another script (without using shelve). I would like something close to : script 1 class Porsche(Car): """ class representing a Porsche """ def __init__(self, color): self.color = color class Porsche_Contain...
[ "The best way to do this is explicitly to construct the set of objects that you want to access. It is possible to list e.g. all global variables defined in the other script, but not a good idea.\n\nscript1\n...\nporsche_container = { myPorsche1, myPorsche2 }\n\nscript 2\nimport script1\nfor porsche in script1.porsc...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003564749_python.txt
Q: How do i render a template inside another template? I'm new in Django and Python and I'm stuck! It's complicated to explain but I will give it a try... I have my index.html template with an include tag: {% include 'menu.inc.html' %} The menu is a dynamic (http://code.google.com/p/django-treemenus/). The menu-app...
How do i render a template inside another template?
I'm new in Django and Python and I'm stuck! It's complicated to explain but I will give it a try... I have my index.html template with an include tag: {% include 'menu.inc.html' %} The menu is a dynamic (http://code.google.com/p/django-treemenus/). The menu-app holds a view that renders menu.inc.html: from django.htt...
[ "At first blush this seems to be a case for adding an inclusion tag. You might want to write a custom tag that renders the tree menu. From the main view you can then pass the necessary context variables for this tag to work.\nFrom the documentation:\n\nAnother common type of template tag is the type that displays s...
[ 2 ]
[]
[]
[ "django", "python", "templates", "url" ]
stackoverflow_0003565245_django_python_templates_url.txt
Q: Django - dreaded 'iteration over non-sequence' Hi I'm looking to populate a list of members, based on where their club comes from. This is my code: members = [] if userprofile.countries.count() > 0: for c in userprofile.countries.all(): clubs = Club.objects.filter(location__country = c) fo...
Django - dreaded 'iteration over non-sequence'
Hi I'm looking to populate a list of members, based on where their club comes from. This is my code: members = [] if userprofile.countries.count() > 0: for c in userprofile.countries.all(): clubs = Club.objects.filter(location__country = c) for club in clubs: members_list = Member....
[ "Can't comment unless looking at Member model. But\n\nCan't we use .filter with back navigation, instead of get_members\nDo we need those many loops, and db access inside loop? ex:\n\nclubs = Club.objects.filter(location__country__in = list_of_user_countries)\nIf your final list is list of members, you can do that ...
[ 2 ]
[]
[]
[ "django", "django_models", "django_queryset", "python" ]
stackoverflow_0003565166_django_django_models_django_queryset_python.txt
Q: Problem requiring lists The current issue im facing is comes from the following scenario. I have a script that runs a commandline program to find all files of a certain extension within an specific folder, lets call these files File A. Another section of the script runs a grep command through each file for filenam...
Problem requiring lists
The current issue im facing is comes from the following scenario. I have a script that runs a commandline program to find all files of a certain extension within an specific folder, lets call these files File A. Another section of the script runs a grep command through each file for filenames within File A. What would ...
[ "EDIT: I see you were the one who asked the previous question! Why open a new one?\n\nThere was a recent question on this exact problem -- the structure you are modelling is a directed graph. See my answer to that question, using Python's networkx package. Using this package is a good idea if you are going to do so...
[ 2 ]
[]
[]
[ "dictionary", "nested_lists", "python" ]
stackoverflow_0003565543_dictionary_nested_lists_python.txt
Q: Create and retrieve object list in Python enhanced This post is the follow-up of my previous post (Create and retrieve object list in Python). I had to modify my code in the following way : script1 #!/usr/bin/python class Porsche: """ class representing a Porsche """ def __init__(self, color): ...
Create and retrieve object list in Python enhanced
This post is the follow-up of my previous post (Create and retrieve object list in Python). I had to modify my code in the following way : script1 #!/usr/bin/python class Porsche: """ class representing a Porsche """ def __init__(self, color): self.color = color def create_porsche(parameter_1, ...
[ "create_porsche doesn't return anything, so you don't know what it's created. Make it return a list of the cars that it creates, which you can then store in your global variable.\ndef create_porsche(parameter_1, parameter_2):\n myPorsche = Porsche(color = parameter_1)\n myPorsche2 = Porsche(color = parameter_...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003565930_python.txt
Q: How to maintain mail conversion (reply / forward / reply to all like gmail) of email using Python pop/imap lib? I've develop webmail client for any mail server. I want to implement message conversion for it — for example same emails fwd/reply/reply2all should be shown together like gmail does... My question is: w...
How to maintain mail conversion (reply / forward / reply to all like gmail) of email using Python pop/imap lib?
I've develop webmail client for any mail server. I want to implement message conversion for it — for example same emails fwd/reply/reply2all should be shown together like gmail does... My question is: what's the key to find those emails which are either reply/fwd or related to the original mail....
[ "The In-Reply-To header of the child should have the value of the Message-Id header of the parent(s).\n", "Google just seems to chain messages based on the subject line (so does Apple Mail by the way.)\n" ]
[ 4, 3 ]
[]
[]
[ "imap", "imaplib", "pop3", "poplib", "python" ]
stackoverflow_0003530851_imap_imaplib_pop3_poplib_python.txt
Q: Reportlab 'LayoutError' handling and debugging I have been working with some complex PDF outputs with reportlab. These are generally fine but there are some cases still where I get LayoutErrors - these are usually because Flowables are too big at some point. It's proving o be pretty hard to debug these as I don't ...
Reportlab 'LayoutError' handling and debugging
I have been working with some complex PDF outputs with reportlab. These are generally fine but there are some cases still where I get LayoutErrors - these are usually because Flowables are too big at some point. It's proving o be pretty hard to debug these as I don't often have more information than something like this...
[ "Make sure you are not re-using any of your flowable objects (as in, rendering multiple versions of a document using common template parts). This is not supported by ReportLab, and can cause this error.\nThe reason seems to be that ReportLab will set an attribute on these objects when performing the layout to indic...
[ 4, 2 ]
[]
[]
[ "debugging", "python", "reportlab", "testing" ]
stackoverflow_0003069288_debugging_python_reportlab_testing.txt
Q: How do I make wx.TextCtrl multi-line text update smoothly? I'm working on an GUI program, and I use AppendText to update status in a multi-line text box(made of wx.TextCtrl). I noticed each time there's a new line written in this box, instead of smoothly adding this line to the end, the whole texts in the box just...
How do I make wx.TextCtrl multi-line text update smoothly?
I'm working on an GUI program, and I use AppendText to update status in a multi-line text box(made of wx.TextCtrl). I noticed each time there's a new line written in this box, instead of smoothly adding this line to the end, the whole texts in the box just disappear(not in real, just visually) and I have to click the s...
[ "try this:\nself.logs = wx.TextCtrl(self, id=-1, value='', pos=wx.DefaultPosition,\n size=(-1,300),\n style= wx.TE_MULTILINE | wx.SUNKEN_BORDER)\nself.logs.AppendText(text + \"\\n\")\n\n", "Try calling the Refresh() method on the textCtrl\nUpdate:\nA question ...
[ 4, 2 ]
[]
[]
[ "python", "wx.textctrl", "wxpython" ]
stackoverflow_0003566603_python_wx.textctrl_wxpython.txt
Q: Python: shape of a matrix and imshow() I have a 3-D array ar. print shape(ar) # --> (81, 81, 256) I want to plot this array. fig = plt.figure() ax1 = fig.add_subplot(111) for i in arange(256): im1 = ax1.imshow(ar[:][:][i]) plt.draw() print i I get this error-message: im1 = ax1.imshow(ar[:][:][i...
Python: shape of a matrix and imshow()
I have a 3-D array ar. print shape(ar) # --> (81, 81, 256) I want to plot this array. fig = plt.figure() ax1 = fig.add_subplot(111) for i in arange(256): im1 = ax1.imshow(ar[:][:][i]) plt.draw() print i I get this error-message: im1 = ax1.imshow(ar[:][:][i]) IndexError: list index out of range Why ...
[ "Do:\nar[:,:,i]\n\nThe syntax ar[:] makes a copy of ar (slices all its elements), so ar[:][:][i] is semantically equivalent to ar[i]. This is an 81*256 matrix, since ndarrays are nested lists.\n" ]
[ 2 ]
[]
[]
[ "arrays", "matplotlib", "multidimensional_array", "numpy", "python" ]
stackoverflow_0003566782_arrays_matplotlib_multidimensional_array_numpy_python.txt
Q: Google App Engine : Cursor Versus Offset Do you know which is the best approach for fetching chunks of result from a query? 1.Cursor q = Person.all() last_cursor = memcache.get('person_cursor') if last_cursor: q.with_cursor(last_cursor) people = q.fetch(100) cursor = q.cursor() memcache.set('person_cursor', cu...
Google App Engine : Cursor Versus Offset
Do you know which is the best approach for fetching chunks of result from a query? 1.Cursor q = Person.all() last_cursor = memcache.get('person_cursor') if last_cursor: q.with_cursor(last_cursor) people = q.fetch(100) cursor = q.cursor() memcache.set('person_cursor', cursor) 2.Offset q = Person.all() offset = memc...
[ "While it's hard to measure precise and reliably, I'd be astonished if the cursor didn't run rings around the offset approach at soon as a sufficiently large set of Person entities are getting returned. As the docs say very clearly and explicitly,\n\nThe datastore fetches offset + limit\n results to the applicati...
[ 31 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003566462_google_app_engine_python.txt
Q: URL encoding/decoding with Python I am trying to encode and store, and decode arguments in Python and getting lost somewhere along the way. Here are my steps: 1) I use google toolkit's gtm_stringByEscapingForURLArgument to convert an NSString properly for passing into HTTP arguments. 2) On my server (python), I s...
URL encoding/decoding with Python
I am trying to encode and store, and decode arguments in Python and getting lost somewhere along the way. Here are my steps: 1) I use google toolkit's gtm_stringByEscapingForURLArgument to convert an NSString properly for passing into HTTP arguments. 2) On my server (python), I store these string arguments as somethin...
[ "url encoding a \"raw\" unicode doesn't really make sense. What you need to do is .encode(\"utf8\") first so you have a known byte encoding and then .quote() that.\nThe output isn't very pretty but it should be a correct uri encoding.\n>>> s = u'1234567890-/:;()$&@\".,?!\\'[]{}#%^*+=_\\|~<>\\u20ac\\xa3\\xa5\\u2022....
[ 71, 4, 2 ]
[]
[]
[ "python", "url_encoding" ]
stackoverflow_0003563126_python_url_encoding.txt
Q: Trouble with receiving data from HTML: <form enctype="multipart/form-data" action="/convert_upl" method="post"> Name: <input type="text" name="file_name"> File: <input type="file" name="subs_file"> <input type="submit" value="Send"> </form> Python (Google App Engine): if se...
Trouble with receiving data from
HTML: <form enctype="multipart/form-data" action="/convert_upl" method="post"> Name: <input type="text" name="file_name"> File: <input type="file" name="subs_file"> <input type="submit" value="Send"> </form> Python (Google App Engine): if self.request.get('file_name'): ...
[ "You are using the POST method to send the data but then are trying to get it with the GET method.\ninstead of \nself.request.get('file_name')\n\ndo something like\nself.request.post('file_name')\n\n", "The uploading example code works fine for me. Have you tried using that code exactly? Does it work for you, o...
[ 0, 0 ]
[]
[]
[ "cgi", "google_app_engine", "html", "python" ]
stackoverflow_0003566458_cgi_google_app_engine_html_python.txt
Q: How add already captured screenshot to wx.BoxSizer? My Python code: self.images = wx.StaticBitmap(self, id=-1, pos=wx.DefaultPosition, size=(200,150), style= wx.SUNKEN_BORDER) self.hbox = wx.BoxSizer(wx.HORIZONTAL) self.sizer.Add(self.hbox) # my m...
How add already captured screenshot to wx.BoxSizer?
My Python code: self.images = wx.StaticBitmap(self, id=-1, pos=wx.DefaultPosition, size=(200,150), style= wx.SUNKEN_BORDER) self.hbox = wx.BoxSizer(wx.HORIZONTAL) self.sizer.Add(self.hbox) # my main sizer #in function dynamically captured images ...
[ "In your function for dynamically captured images, you need to create a new staticBitmap rather than setting self.images which overwrites and therefore replaces...\nSo instead of \nself.images.SetBitmap(bmp)\nyou need to do \nnewImage = wx.StaticBitmap(self, id=-1\n size=(200,150),\n ...
[ 3 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0003566528_python_wxpython_wxwidgets.txt
Q: Python module installed or not installed? How can I check if my Python module is successfully installed. I did: python setup.py install inside the folder where my module was downloaded. Now, I can see that this resulted in a folder inside this location: /usr/lib/python2.4/site-packages (I can see my module folder...
Python module installed or not installed?
How can I check if my Python module is successfully installed. I did: python setup.py install inside the folder where my module was downloaded. Now, I can see that this resulted in a folder inside this location: /usr/lib/python2.4/site-packages (I can see my module folder is inside here) Now I am using PHP to execute...
[ "You can check that the Python interpreter that you are calling sees your module by doing:\n/usr/bin/python -c \"import MyModule\"\n\nThis command should simply import MyModule/__init__.py and not complain about MyModule not being found.\nSince there are many modules in your code, you actually want to create a pack...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003563205_php_python.txt
Q: Python unix timestamp conversion and timezone Hey all! Ive got timezone troubles. I have a time stamp of 2010-07-26 23:35:03 What I really want to do is subtract 15 minutes from that time. My method was going to be a simple conversion to unix time, subtract the seconds and convert back. Simple right? My problem i...
Python unix timestamp conversion and timezone
Hey all! Ive got timezone troubles. I have a time stamp of 2010-07-26 23:35:03 What I really want to do is subtract 15 minutes from that time. My method was going to be a simple conversion to unix time, subtract the seconds and convert back. Simple right? My problem is that python adjusts the returned unix time using ...
[ "Subtract datetime.timedelta(seconds=15*60).\n", "The online docs have a handy table (what you call \"unix time\" is more properly called \"UTC\", for \"Universal Time Coordinate\", and \"seconds since the epoch\" is a \"timestamp\" as a float...):\n\nUse the following functions to convert\n between time represe...
[ 6, 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003567425_python.txt
Q: Combine SimpleXMLRPCServer and BaseHTTPRequestHandler in Python Because cross-domain xmlrpc requests are not possible in JavaScript I need to create a Python app which exposes both some HTML through HTTP and an XML-RPC service on the same domain. Creating an HTTP request handler and SimpleXMLRPCServer in python is...
Combine SimpleXMLRPCServer and BaseHTTPRequestHandler in Python
Because cross-domain xmlrpc requests are not possible in JavaScript I need to create a Python app which exposes both some HTML through HTTP and an XML-RPC service on the same domain. Creating an HTTP request handler and SimpleXMLRPCServer in python is quite easy, but they both have to listen on a different port, which ...
[ "Both of them subclass of SocketServer.TCPServer. There must be someway to refactor them so that once server instance can dispatch to both.\nAn easier alternative may be to keep the HTTPServer in front and proxy XML RPC to the SimpleXMLRPCServer instance.\n", "The solution was actually quite simple, based on Wai...
[ 2, 2, 0 ]
[]
[]
[ "httpserver", "python", "simplexmlrpcserver" ]
stackoverflow_0003561140_httpserver_python_simplexmlrpcserver.txt
Q: How to use named parameters in Python methods that are defaulting to a class level value? Usage scenario: # case #1 - for classes a = MyClass() # default logger is None a = MyClass(logger="a") # set the default logger to be "a" a.test(logger="b") # this means that logger will be "b" only inside this method a.test(...
How to use named parameters in Python methods that are defaulting to a class level value?
Usage scenario: # case #1 - for classes a = MyClass() # default logger is None a = MyClass(logger="a") # set the default logger to be "a" a.test(logger="b") # this means that logger will be "b" only inside this method a.test(logger=None) # this means that logger will be None but only inside this method a.test() # here ...
[ "_sentinel = object()\n\nclass MyClass(object):\n def __init__(self, logger=None):\n self.logger = logger\n def test(self, logger=_sentinel):\n if logger is _sentinel: logger = self.logger\n\n# in case you want to use this inside a function from your module use:\n_sentinel = object()\nlogger = None\ndef tes...
[ 9, 3, 1 ]
[]
[]
[ "named_parameters", "python" ]
stackoverflow_0003567618_named_parameters_python.txt
Q: how do I get variables from one wx notebook page to a different wx notebook page? I am wondering how one would get a variable from one page to another from a wx notebook. I am thinking there should be some way to reference a variable if I know the variable name and page id. For example if I had the following code,...
how do I get variables from one wx notebook page to a different wx notebook page?
I am wondering how one would get a variable from one page to another from a wx notebook. I am thinking there should be some way to reference a variable if I know the variable name and page id. For example if I had the following code, how would I reference variable x from panel y and vice versa import wx class PanelX(...
[ "The variables you're creating in your panels aren't \"saved\" in the class - they're a local variable used in the constructor, and discarded from memory as soon as that method's executed.\nYou'll have to create your variables with \"self\" in front of them -- self.x = 3\nThis will create \"instance variables\" - v...
[ 5 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003567225_python_wxpython.txt
Q: Using python ctypes to call io_submit in Linux I'm trying to call io_submit using python ctypes. The code I'm writing is supposed to work on both 32 and 64-bit Intel/AMD architectures, but here I'll focus on 64 bits. I have defined the following: def PADDED64(type, name1, name2): return [(name1, type), (name2,...
Using python ctypes to call io_submit in Linux
I'm trying to call io_submit using python ctypes. The code I'm writing is supposed to work on both 32 and 64-bit Intel/AMD architectures, but here I'll focus on 64 bits. I have defined the following: def PADDED64(type, name1, name2): return [(name1, type), (name2, type)] def PADDEDptr64(type, name1, name2): r...
[ "The way I understand it is that the iocbpp argument to io_submit() is an array of pointers to struct iocb. \nThis seems to be reinforced with the Linux-specific example here: http://voinici.ceata.org/~sana/blog/?p=248 and by the EINVAL error documentation here: http://linux.die.net/man/2/io_submit (array subscrip...
[ 1 ]
[]
[]
[ "c", "ctypes", "linux", "python", "stack" ]
stackoverflow_0003565417_c_ctypes_linux_python_stack.txt
Q: PyQt: How to catch mouse-over-event of QTableWidget-headers? what I want to do is to change the text of a QLable, everytime I hover with the mouse over the horizontalHeaders of my QTableWidget. How can I do that? Everytime I'm over a new header I need a signal and the index of the header. Hope someone of you has a...
PyQt: How to catch mouse-over-event of QTableWidget-headers?
what I want to do is to change the text of a QLable, everytime I hover with the mouse over the horizontalHeaders of my QTableWidget. How can I do that? Everytime I'm over a new header I need a signal and the index of the header. Hope someone of you has an idea. There must be a function, because if you hover over the he...
[ "Install an event filter that on the horizontalHeader() by using QObject.installEventFilter():\nclass HeaderViewFilter(QObject):\n # ...\n def eventFilter(self, object, event):\n if event.type() == QEvent.HoverEvent:\n pass # do something useful\n # you could emit a signal here if...
[ 2 ]
[]
[]
[ "header", "mousehover", "pyqt", "python", "qtablewidget" ]
stackoverflow_0003562447_header_mousehover_pyqt_python_qtablewidget.txt
Q: How do you directly write to a request body in Python I am currently implementing code to call out to an API where the post request body needs to contain several columns of data in csv format. e.g. Col1, Col2, Col3 1, 2, 3 4, 5, 6 etc, with the content type header is set to 'text/csv' How do I directly write to t...
How do you directly write to a request body in Python
I am currently implementing code to call out to an API where the post request body needs to contain several columns of data in csv format. e.g. Col1, Col2, Col3 1, 2, 3 4, 5, 6 etc, with the content type header is set to 'text/csv' How do I directly write to the request body? I have a coworker who is doing the same t...
[ "Any HTTP client will give you some way to set the request body. For example, httplib.HTTPConnection.request takes an optional body parameter that allows you to pass request data. Same with urllib2.urlopen (there it's called data). I've never used PycURL myself but it definitely provides some way to include a body ...
[ 2 ]
[]
[]
[ "csv", "httplib", "pycurl", "python", "request" ]
stackoverflow_0003568530_csv_httplib_pycurl_python_request.txt
Q: Which cross platform scripting language should we adopt for a group of DBAs? I wanted to get the community's feedback on a language choice our team is looking to make in the near future. We are a software developer, and I work in a team of Oracle and SQL Server DBAs supporting a cross platform Java application wh...
Which cross platform scripting language should we adopt for a group of DBAs?
I wanted to get the community's feedback on a language choice our team is looking to make in the near future. We are a software developer, and I work in a team of Oracle and SQL Server DBAs supporting a cross platform Java application which runs on Oracle Application Server. We have SQL Server and Oracle code bases, ...
[ "You can opt for Python. Its dynamic(interpreted) , is available on Windows/Linux/Solaris, has easy to read syntax so that your code maintenance is easy. There modules/libraries for Oracle interaction and various other database servers as well. there are also library support for XML. All 7 points are covered.\n", ...
[ 6, 5, 4, 3, 1, 0 ]
[]
[]
[ "groovy", "jython", "python", "scala", "shell" ]
stackoverflow_0003564177_groovy_jython_python_scala_shell.txt
Q: Displaying QComboBox text rather than index value in QStyledItemDelegate So I have a model and one of the columns contains a country. However because I want to display a combo box to choose the country from a list of options, I don't store the country name in the model directly. Instead I store an index value into...
Displaying QComboBox text rather than index value in QStyledItemDelegate
So I have a model and one of the columns contains a country. However because I want to display a combo box to choose the country from a list of options, I don't store the country name in the model directly. Instead I store an index value into a list of allowable countries. This allows me to use a QComboBox in my form v...
[ "Models have different item data roles for different data. There's a Qt::DisplayRole, Qt::EditRole, and a Qt::UserRole among others. In this case, you want to display something different than your actual data, so add a new role, let's say Qt::UserRole+1 that's used for your index.\nThen you want your delegate to ...
[ 4 ]
[]
[]
[ "pyqt", "pyqt4", "python" ]
stackoverflow_0003568422_pyqt_pyqt4_python.txt
Q: using DES/3DES with python what is the best module /package in python to use des /3des for encryption /decryption. could someone provide example to encrypt data with des/3des on python. A: pyDes can be used for both, DES and 3DES. Sample usage: from pyDes import * data = "Please encrypt my data" k = des("DESCRY...
using DES/3DES with python
what is the best module /package in python to use des /3des for encryption /decryption. could someone provide example to encrypt data with des/3des on python.
[ "pyDes can be used for both, DES and 3DES. Sample usage:\nfrom pyDes import *\n\ndata = \"Please encrypt my data\"\nk = des(\"DESCRYPT\", CBC, \"\\0\\0\\0\\0\\0\\0\\0\\0\", pad=None, padmode=PAD_PKCS5)\nd = k.encrypt(data)\nprint \"Encrypted: %r\" % d\nprint \"Decrypted: %r\" % k.decrypt(d)\nassert k.decrypt(d, pad...
[ 21, 7 ]
[]
[]
[ "3des", "cryptography", "python" ]
stackoverflow_0002435283_3des_cryptography_python.txt