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: Use python decorators on class methods and subclass methods Goal: Make it possible to decorate class methods. When a class method gets decorated, it gets stored in a dictionary so that other class methods can reference it by a string name. Motivation: I want to implement the equivalent of ASP.Net's WebMethods. ...
Use python decorators on class methods and subclass methods
Goal: Make it possible to decorate class methods. When a class method gets decorated, it gets stored in a dictionary so that other class methods can reference it by a string name. Motivation: I want to implement the equivalent of ASP.Net's WebMethods. I am building this on top of google app engine, but that does no...
[ "This is unnecessary. Just use getattr:\nclass WebmethodBaseClass():\n def post(self, methodName):\n getattr(self, methodName)(\"kapow\")\n\nThe only caveat is that you have to make sure that only methods intended for use as webmethods can be used thus. The simplest solution, IMO, is to adopt the conventi...
[ 4, 1, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002711101_decorator_python.txt
Q: some register.inclusion_tag error in my code using django my helloworld_tags: from django import template register = template.Library() def show_profile(): return {"eee": '333'} register.inclusion_tag("b.html")(show_profile) my view: def b(request): return render_to_response('b.html') my html: {% load ...
some register.inclusion_tag error in my code using django
my helloworld_tags: from django import template register = template.Library() def show_profile(): return {"eee": '333'} register.inclusion_tag("b.html")(show_profile) my view: def b(request): return render_to_response('b.html') my html: {% load helloworld_tags%} dsad {{ eee }} but only show 'dsad' ,not s...
[ "This can't possibly work. You need one template for the view to render, and another different template for the inclusion template. You can't use the same template for both uses, it simply doesn't make any sense.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002711739_django_python.txt
Q: how to make multi url in a line of '- url:' ,on google-app-engine like this: handlers: - url: /media static_dir: media - url: /form;/items.html script: validate.py /form;/items.html i want /form and /item.html use validate.py thanks A: URL patterns are regular expressions, so you can simply provide a regu...
how to make multi url in a line of '- url:' ,on google-app-engine
like this: handlers: - url: /media static_dir: media - url: /form;/items.html script: validate.py /form;/items.html i want /form and /item.html use validate.py thanks
[ "URL patterns are regular expressions, so you can simply provide a regular expression that matches both:\n- url: /(form|items\\.html)\n script: validate.py\n\nAlternately, you can use multiple handlers, as Adam suggests, or just make validate.html your catchall (with an expression of '.*').\n", "List the handler...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python", "url" ]
stackoverflow_0002710755_google_app_engine_python_url.txt
Q: Python/C "defs" file - what is it? In the nautilus-python bindings, there is a file "nautilus.defs". It contains stanzas like (define-interface MenuProvider (in-module "Nautilus") (c-name "NautilusMenuProvider") (gtype-id "NAUTILUS_TYPE_MENU_PROVIDER") ) or (define-method get_mime_type (of-object "Nautilu...
Python/C "defs" file - what is it?
In the nautilus-python bindings, there is a file "nautilus.defs". It contains stanzas like (define-interface MenuProvider (in-module "Nautilus") (c-name "NautilusMenuProvider") (gtype-id "NAUTILUS_TYPE_MENU_PROVIDER") ) or (define-method get_mime_type (of-object "NautilusFileInfo") (c-name "nautilus_file_inf...
[ "All you need to create Python bindings for C code is to use the Python / C API. However, the API can be somewhat repetitive and redundant, and so various forms of automation may be used to create them. For example, you may have heard of swig. The LISP-like (Scheme) code that you see is simply a configuration file ...
[ 3, 3 ]
[]
[]
[ "c", "python" ]
stackoverflow_0002712054_c_python.txt
Q: Fetch Facebook ID with PyFacebook, "Session key is required" I'm trying to fetch the logged in user's ID with Facebook + PyFacebook via: #Establish connection to Facebook via API f = Facebook(config['app_conf']['pyfacebook.apikey'], config['app_conf']['pyfacebook.secret']) #Get the current Facebook I...
Fetch Facebook ID with PyFacebook, "Session key is required"
I'm trying to fetch the logged in user's ID with Facebook + PyFacebook via: #Establish connection to Facebook via API f = Facebook(config['app_conf']['pyfacebook.apikey'], config['app_conf']['pyfacebook.secret']) #Get the current Facebook ID facebook_id = f.users.getLoggedInUser() But I keep getting the ...
[ "A look at the source shows an example app, and in there it calls f.auth.createToken() followed by f.login() before doing anything else. If you're not logged in, you won't get a session key.\n" ]
[ 0 ]
[]
[]
[ "facebook", "pyfacebook", "pylons", "python" ]
stackoverflow_0002710146_facebook_pyfacebook_pylons_python.txt
Q: which is better to send mail on google-app-engine this: http://code.google.com/intl/en/appengine/docs/python/tools/devserver.html The web server can use an SMTP server, or it can use a local installation of Sendmail. i download the Sendmail lib,and find it is so big, and so many doc, i want to know which way is b...
which is better to send mail on google-app-engine
this: http://code.google.com/intl/en/appengine/docs/python/tools/devserver.html The web server can use an SMTP server, or it can use a local installation of Sendmail. i download the Sendmail lib,and find it is so big, and so many doc, i want to know which way is better, and if the Sendmail way is better, how to use i...
[ "As Wooble points out, this only applies to sending email from the development environment - so pick whichever option is easiest. If you can't get any of them working, email sent on the development server will still show up in your logs, so you can debug it there.\n" ]
[ 2 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0002703885_email_google_app_engine_python.txt
Q: Google App Engine getting verbose_name of a property from an instance Given a model like so: from google.appengine.ext import db class X(db.Model): p = db.StringProperty(verbose_name="Like π, but more modern.") How does one access verbose_name from x=X() (an instance of X)? One might expect that x.p.verbose...
Google App Engine getting verbose_name of a property from an instance
Given a model like so: from google.appengine.ext import db class X(db.Model): p = db.StringProperty(verbose_name="Like π, but more modern.") How does one access verbose_name from x=X() (an instance of X)? One might expect that x.p.verbose_name would work, or alternatively x.properties()['p'].verbose_name, but ne...
[ "x.properties()['p'].verbose_name definitely works - you can verify for yourself on http://shell.appspot.com/\n", "x = X(p=\"Foo!\")\nprint x.p.verbose_name\n\nDoes that work?\n" ]
[ 3, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0002702554_django_google_app_engine_python.txt
Q: How do I send an email in Django with a certain mimetype? MYMESSAGE = "<div>Hello</div><p></p>Hello" send_mail("testing",MYMESSAGE,"noreply@mydomain.com",['assdf@gmail.com'],fail_silently=False) However, this message doesn't get the HTML mime type when it is sent. In my outlook, I see the code... A: From the do...
How do I send an email in Django with a certain mimetype?
MYMESSAGE = "<div>Hello</div><p></p>Hello" send_mail("testing",MYMESSAGE,"noreply@mydomain.com",['assdf@gmail.com'],fail_silently=False) However, this message doesn't get the HTML mime type when it is sent. In my outlook, I see the code...
[ "From the docs:\nmsg = EmailMessage(subject, html_content, from_email, [to])\nmsg.content_subtype = \"html\" # Main content is now text/html\nmsg.send()\n\nYou can only change the subtype of the mimetype it seems. So it will always be\n\"text/%s\" % msg.content_subtype\n" ]
[ 5 ]
[]
[]
[ "django", "email", "mime", "python", "smtp" ]
stackoverflow_0002712484_django_email_mime_python_smtp.txt
Q: Optimizing BeautifulSoup (Python) code I have code that uses the BeautifulSoup library for parsing, but it is very slow. The code is written in such a way that threads cannot be used. Can anyone help me with this? I am using BeautifulSoup for parsing and than save into a DB. If I comment out the save statement, i...
Optimizing BeautifulSoup (Python) code
I have code that uses the BeautifulSoup library for parsing, but it is very slow. The code is written in such a way that threads cannot be used. Can anyone help me with this? I am using BeautifulSoup for parsing and than save into a DB. If I comment out the save statement, it still takes a long time, so there is no pr...
[ "soup2 = BeautifulSoup(str(arr[i]))\narr2 = soup2.findAll('td')\n\nDon't do this: Just call arr2 = arr[i].findAll('td') instead.\n\nThis will also be slow:\nif str(j).find(\"<a href=\") > 0:\n data.sourceURL = self.getAttributeValue(str(j),'<a href=\"')\n\nAssuming that getAttributeValue gives you the href attri...
[ 7 ]
[]
[]
[ "beautifulsoup", "optimization", "python" ]
stackoverflow_0002712498_beautifulsoup_optimization_python.txt
Q: How to detect identical part(s) inside string? I try to break down the decoding algorithm wanted question into smaller questions. This is Part I. Question: two strings: s1 and s2 part of s1 is identical to part of s2 space is separator how to extract the identical part(s)? example 1: s1 = "12 November 2010 - 1 v...
How to detect identical part(s) inside string?
I try to break down the decoding algorithm wanted question into smaller questions. This is Part I. Question: two strings: s1 and s2 part of s1 is identical to part of s2 space is separator how to extract the identical part(s)? example 1: s1 = "12 November 2010 - 1 visitor" s2 = "6 July 2010 - 100 visitors" the ident...
[ "For example 1\n>>> s1 = 'November 2010 - 1 visitor'\n>>> s2 = '6 July 2010 - 100 visitors'\n>>> \n>>> [i for i in s1.split() if any(j for j in s2.split() if i in j)]\n['2010', '-', '1', 'visitor']\n>>>\n\nFor both\n>>> s1 = \"Welcome, John!\"\n>>> s2 = \"Welcome, Peter!\"\n>>> [i for i in s1.replace('!',' !').spli...
[ 3, 3, 1, 1 ]
[]
[]
[ "pattern_matching", "python", "regex", "ruby" ]
stackoverflow_0002712466_pattern_matching_python_regex_ruby.txt
Q: Make the Move to Python 3 - Best practices We think about whether we should convert a quite large python web application to Python 3 in the near future. All experiences, possible challenges or guidelines are highly appreciated. A: My suggestion is that you stick with Python 2.6+, but simply add the -3 flag to wa...
Make the Move to Python 3 - Best practices
We think about whether we should convert a quite large python web application to Python 3 in the near future. All experiences, possible challenges or guidelines are highly appreciated.
[ "My suggestion is that you stick with Python 2.6+, but simply add the -3 flag to warn you about incompatibilities with Python 3.0. Then you can make sure your Python 2.6 can be easily upgraded to Python 3.0 via 2to3, without actually making that jump quite yet. I would suggest you hold back at the moment, because y...
[ 13, 4 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002712283_python_python_3.x.txt
Q: Log Unittest output to a text file I am trying to log the output of tests to a text file. I am using the unittest module and want to log results into a text file instead of the screen. I have some script here to explain what has been tryied so far. This is the test script. import unittest, sys class TestOne(unitt...
Log Unittest output to a text file
I am trying to log the output of tests to a text file. I am using the unittest module and want to log results into a text file instead of the screen. I have some script here to explain what has been tryied so far. This is the test script. import unittest, sys class TestOne(unittest.TestCase): def setUp(self): ...
[ "You can pass the text runner into the main method. The text runner must be set up to write to a file rather than the std.err as it wraps the stream in a decorator. The following worked for me in python 2.6\nif __name__ == '__main__':\n log_file = 'log_file.txt'\n with open(log_file, \"w\") as f:\n runn...
[ 30 ]
[]
[]
[ "logging", "python", "unit_testing" ]
stackoverflow_0002712831_logging_python_unit_testing.txt
Q: python dict function on enumerate object If I have an enumerate object x, why does doing the following: dict(x) clear all the items in the enumerate sequence? A: enumerate creates an iterator. A iterator is a python object that only knows about the current item of a sequence and how to get the next, but there i...
python dict function on enumerate object
If I have an enumerate object x, why does doing the following: dict(x) clear all the items in the enumerate sequence?
[ "enumerate creates an iterator. A iterator is a python object that only knows about the current item of a sequence and how to get the next, but there is no way to restart it. Therefore, once you have used a iterator in a loop, it cannot give you any more items and appears to be empty.\nIf you want to create a real ...
[ 19 ]
[]
[]
[ "dictionary", "enumerate", "python" ]
stackoverflow_0002713712_dictionary_enumerate_python.txt
Q: When to use buildout:eggs and when to install via zc.recipe.egg? There seem to be more than one way to install eggs into a buildout. Way 1: [buildout] ... eggs = eggname othereggname ... Way 2: [buildout] ... parts = eggs [eggs] recipe = zc.recipe.egg eggs = eggname = othereggname Both ways work...
When to use buildout:eggs and when to install via zc.recipe.egg?
There seem to be more than one way to install eggs into a buildout. Way 1: [buildout] ... eggs = eggname othereggname ... Way 2: [buildout] ... parts = eggs [eggs] recipe = zc.recipe.egg eggs = eggname = othereggname Both ways work. ( variation on way 2 would be to install each requirement as a separ...
[ "In both cases, the \"eggs=\" makes those eggs available to that part, which means they're getting installed.\nThe buildout eggs don't get any additional treatment.\nThe big difference is that \"recipe = zc.recipe.egg\" ALSO tries to create scripts for all the eggs defined there. (Scripts meaning the \"console_scr...
[ 2 ]
[]
[]
[ "buildout", "python" ]
stackoverflow_0002712514_buildout_python.txt
Q: More compact layout In the following code, I'd like to get rid of the margin around the buttons. I'd like to have the buttons stretch all the way to the edge of the frame. How can I do that? import sys from PyQt4.QtGui import * from PyQt4.QtCore import * app = QApplication(sys.argv) window = QWidget() layout =...
More compact layout
In the following code, I'd like to get rid of the margin around the buttons. I'd like to have the buttons stretch all the way to the edge of the frame. How can I do that? import sys from PyQt4.QtGui import * from PyQt4.QtCore import * app = QApplication(sys.argv) window = QWidget() layout = QVBoxLayout() layout.set...
[ "layout.setContentsMargin(0, 0, 0, 0)\n\nshould do the trick\n", "Unfortunately I don't have a working Qt at hand to try right now, but I believe you might get your wish by using style sheets with both margins and padding set to 0 (you might also need to tweak the size policy, as it might otherwise block the widg...
[ 4, 1 ]
[]
[]
[ "layout", "pyqt", "pyqt4", "python", "qt" ]
stackoverflow_0002712355_layout_pyqt_pyqt4_python_qt.txt
Q: python decorator to modify variable in current scope Goal: Make a decorator which can modify the scope that it is used in. If it worked: class Blah(): # or perhaps class Blah(ParentClassWhichMakesThisPossible) def one(self): pass @decorated def two(self): pass >>> Blah.decorated ["t...
python decorator to modify variable in current scope
Goal: Make a decorator which can modify the scope that it is used in. If it worked: class Blah(): # or perhaps class Blah(ParentClassWhichMakesThisPossible) def one(self): pass @decorated def two(self): pass >>> Blah.decorated ["two"] Why? I essentially want to write classes which can ...
[ "You can do what you want with a class decorator (in Python 2.6) or a metaclass. The class decorator version:\ndef rule(f):\n f.rule = True\n return f\n\ndef getRules(cls):\n cls.rules = {}\n for attr, value in cls.__dict__.iteritems():\n if getattr(value, 'rule', False):\n cls.rules[a...
[ 9, 4 ]
[]
[]
[ "decorator", "python", "scope" ]
stackoverflow_0002714244_decorator_python_scope.txt
Q: Python, implementing proxy support for a socket based application (not urllib2) I am little stumped: I have a simple messenger client program (pure python, sockets), and I wanted to add proxy support (http/s, socks), however I am a little confused on how to go about it. I am assuming that the connection on the soc...
Python, implementing proxy support for a socket based application (not urllib2)
I am little stumped: I have a simple messenger client program (pure python, sockets), and I wanted to add proxy support (http/s, socks), however I am a little confused on how to go about it. I am assuming that the connection on the socket level will be done to the proxy server, at which point the headers should contain...
[ "Maybe use something like SocksiPy which does all the protocol details for you and would let you connect through a SOCKS proxy as you would without it?\n", "It is pretty simple - after you send the HTTP request: CONNECT example.com:1234 HTTP/1.0\\r\\nHost: example.com:1234\\r\\n<additional headers incl. authentic...
[ 3, 2, 0 ]
[]
[]
[ "proxy", "python", "sockets", "socks", "tcp" ]
stackoverflow_0002646983_proxy_python_sockets_socks_tcp.txt
Q: User Crontab + Python + Random wallpapers = Not working? I have a python script that correctly sets the desktop wallpaper via gconf to a random picture in a given folder. I then have the following entry in my crontab * * * * * python /home/bolster/bin/change-background.py And syslog correctly reports exec...
User Crontab + Python + Random wallpapers = Not working?
I have a python script that correctly sets the desktop wallpaper via gconf to a random picture in a given folder. I then have the following entry in my crontab * * * * * python /home/bolster/bin/change-background.py And syslog correctly reports execution Apr 26 14:11:01 bolster-desktop CRON[9751]: (bolster) CM...
[ "Your script depends on the DISPLAY environment variable, which is set when you execute the script from the shell in an X session, but unset when the script is run from cron.\n", "As per Bolo's observation, I forgot about building in the DISPLAY into either the script or the crontab. \nEasiest solution is to prep...
[ 6, 2, 2 ]
[]
[]
[ "cron", "gconf", "gnome", "python", "ubuntu" ]
stackoverflow_0002713724_cron_gconf_gnome_python_ubuntu.txt
Q: How to get the content of "Google Dictionary" by python script Thank to the script, I've logged in google successfully. But I replaced the value of "gv_home_page_url" with http:// www.google.com.tw/dictionary/wordlist?hl=zh-TW, the error occured. The message is " urllib2.HTTPError: HTTP Error 500: Internal Serve...
How to get the content of "Google Dictionary" by python script
Thank to the script, I've logged in google successfully. But I replaced the value of "gv_home_page_url" with http:// www.google.com.tw/dictionary/wordlist?hl=zh-TW, the error occured. The message is " urllib2.HTTPError: HTTP Error 500: Internal Server Error" Any idea will be appreciated, thanks.
[ "That's not a valid URL. If you try to enter it in your bar, you'll get redirected to Google search results. Using urllib2, you'll get an error.\nSee here for another way to get data from Google Dictionary:\nhttp://googlesystem.blogspot.com/2009/12/on-googles-unofficial-dictionary-api.html\n", "Does Google requir...
[ 1, 0 ]
[]
[]
[ "python", "web_applications", "web_services" ]
stackoverflow_0002711048_python_web_applications_web_services.txt
Q: Cant fetch production db results using Google app engine remote_api Hey, I'm trying to work out with /remote_api with a django-patch app engine app i got running. i want to select a few rows from my online production app locally. i cant seem to manage to do so, everything authenticates fine, it doesnt breaks on im...
Cant fetch production db results using Google app engine remote_api
Hey, I'm trying to work out with /remote_api with a django-patch app engine app i got running. i want to select a few rows from my online production app locally. i cant seem to manage to do so, everything authenticates fine, it doesnt breaks on imports, but when i try to fetch something it just doesnt print anything. P...
[ "App Engine patch monkeypatches the ext.db module, mutilating the kind names. You need to make sure you import App Engine patch from your script, to give it the opportunity to mangle things as per usual, or you won't see any data returned.\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002708695_google_app_engine_python.txt
Q: Why would it be necessary to subclass from object in Python? I've been using Python for quite a while now, and I'm still unsure as to why you would subclass from object. What is the difference between this: class MyClass(): pass And this: class MyClass(object): pass As far as I understand, object is the ...
Why would it be necessary to subclass from object in Python?
I've been using Python for quite a while now, and I'm still unsure as to why you would subclass from object. What is the difference between this: class MyClass(): pass And this: class MyClass(object): pass As far as I understand, object is the base class for all classes and the subclassing is implied. Do you ...
[ "This is oldstyle and new style classes in python 2.x. The second form is the up to date version and exist from python 2.2 and above. For new code you should only use new style classes.\nIn Python 3.x you can again use both form indifferently as the new style is the only one left and both form are truly equivalent....
[ 12, 9 ]
[]
[]
[ "python" ]
stackoverflow_0002715186_python.txt
Q: Voting on Hacker News stories programmatically? I decided to write an app like: http://michaelgrinich.com/hackernews/ but for Android devices, my idea will use a web application backend (because I rather code in Python and for the web than completely in Java for Android devices). What I have right now implemented ...
Voting on Hacker News stories programmatically?
I decided to write an app like: http://michaelgrinich.com/hackernews/ but for Android devices, my idea will use a web application backend (because I rather code in Python and for the web than completely in Java for Android devices). What I have right now implemented is something like this: $ curl -i http://localhost:80...
[ "Twill has a way to list all the links, and you get the links as an objects:\nlogin_url = ''\nfor link in showlinks():\n if link.text == \"login\":\n login_url = link.url\n\ngo(login_url)\n\nSo link will be something like: http://news.ycombinator.com/x?fnid=SvdNlGQoqo\n" ]
[ 2 ]
[]
[]
[ "api", "python", "web_scraping" ]
stackoverflow_0002707575_api_python_web_scraping.txt
Q: Passing list and dictionary type parameter with Python When I run this code def func(x, y, *w, **z): print x print y if w: print w if z: print z else: print "None" func(10,20, 1,2,3,{'k':'a'}) I get the result as follows. 10 20 (1, 2, 3, {'k': 'a'}) None But, I expected as follows,...
Passing list and dictionary type parameter with Python
When I run this code def func(x, y, *w, **z): print x print y if w: print w if z: print z else: print "None" func(10,20, 1,2,3,{'k':'a'}) I get the result as follows. 10 20 (1, 2, 3, {'k': 'a'}) None But, I expected as follows, I mean the list parameters (1,2,3) matching *w, and diction...
[ "Put two asterisks before the dictionary:\nfunc(10,20, 1,2,3,**{'k':'a'})\n\n", "I'm not sure what the \"input\" format is, but this will work:\nfunc(10,20, 1,2,3, k='a')\n\nWith this, you don't even need to put the k=a out there at the end, it can be anywhere after the first two arguments. Then the 1,2,3 and ot...
[ 7, 2, 1 ]
[]
[]
[ "parameter_passing", "python" ]
stackoverflow_0002715751_parameter_passing_python.txt
Q: pyinotify file deletion user I'm trying to use pyinotify to alert me whenever files are deleted, but I want to know what user deleted the files. Is there a way to find this information? A: That information isn't exposed by the underlying inotify system. This is the main change notification API for the Linux ke...
pyinotify file deletion user
I'm trying to use pyinotify to alert me whenever files are deleted, but I want to know what user deleted the files. Is there a way to find this information?
[ "That information isn't exposed by the underlying inotify system. This is the main change notification API for the Linux kernel, so you aren't going to find another notification system that provides this.\nIf you want to track who deleted the file, it would be easiest to make the deleter announce what it is going ...
[ 3 ]
[]
[]
[ "delete_file", "pyinotify", "python" ]
stackoverflow_0002715819_delete_file_pyinotify_python.txt
Q: Reading a Delphi binary file in Python I have a file that was written with the following Delphi declaration ... Type Tfulldata = Record dpoints, dloops : integer; dtime, bT, sT, hI, LI : real; tm : real; data : array[1..armax] Of Real; End; ... Var: fh: File Of Tfulldata; I want to analyse...
Reading a Delphi binary file in Python
I have a file that was written with the following Delphi declaration ... Type Tfulldata = Record dpoints, dloops : integer; dtime, bT, sT, hI, LI : real; tm : real; data : array[1..armax] Of Real; End; ... Var: fh: File Of Tfulldata; I want to analyse the data in the files (many MB in size) usi...
[ "Here is the full solutions thanks to hints from KillianDS and Ritsaert Hornstra\nimport struct\nfh = open('my_file.dat', 'rb')\ns = fh.read(40256)\nvals = struct.unpack('iidddddd5025d', s)\ndpoints, dloops, dtime, bT, sT, hI, LI, tm = vals[:8]\ndata = vals[8:]\n", "I do not know how Delphi internally stores data...
[ 6, 2, 2 ]
[]
[]
[ "delphi", "file_io", "python" ]
stackoverflow_0002700155_delphi_file_io_python.txt
Q: Open source equivelants to wsdl.exe? (how to autogen a web reference proxy class) As an ASP.NET developer, I'm used to working with how VS/C# transparently autogens proxy classes for web references via wsdl.exe (yes, I know, we're spoiled), but now that I'm creating documentation for more than one coding platform ...
Open source equivelants to wsdl.exe? (how to autogen a web reference proxy class)
As an ASP.NET developer, I'm used to working with how VS/C# transparently autogens proxy classes for web references via wsdl.exe (yes, I know, we're spoiled), but now that I'm creating documentation for more than one coding platform I'm trying to discover what the equivelant to that is in any other framework. So is th...
[ "I've had (limited) success with ZSI http://pywebsvcs.sourceforge.net/ for Python. Try at your own risk.\nIf it would be possible to run IronPython or IronRuby I would check that out.\nI definitely know how VS can spoil you.\n" ]
[ 1 ]
[]
[]
[ "c#", "python", "ruby_on_rails", "web_services" ]
stackoverflow_0002703331_c#_python_ruby_on_rails_web_services.txt
Q: python function parameter evaluation model I was looking at an article on Peter Norvig's website, where he's trying to answer the following question (this is not my question, btw) "Can I do the equivalent of (test ? result : alternative) in Python?" here's one of the options listed by him, def if_(test, result, a...
python function parameter evaluation model
I was looking at an article on Peter Norvig's website, where he's trying to answer the following question (this is not my question, btw) "Can I do the equivalent of (test ? result : alternative) in Python?" here's one of the options listed by him, def if_(test, result, alternative=None): "If test is true, 'do' res...
[ "The reason the loop never terminates when you change fact to n * fact(n-1) is that n * fact(n-1) has to evaluate first (as the third argument to if). Evaluating it leads to another call to fact, ad infinitum (since there is no longer any base case to stop it).\nPreviously, you were passing a function object (lamb...
[ 4 ]
[]
[]
[ "callable", "evaluation", "lambda", "python" ]
stackoverflow_0002716228_callable_evaluation_lambda_python.txt
Q: Bitwise Operations on Rows of lil_matrix How can I quickly extract two rows of a scipy.sparse.lil_matrix and apply bitwise operations on them? I've tried: np.bitwise_and(A[1,:], A[2,:]) but NumPy seems to want an array type according to the documentation. A: By "lil_matrix", do you mean a scipy.sparse.lil_matri...
Bitwise Operations on Rows of lil_matrix
How can I quickly extract two rows of a scipy.sparse.lil_matrix and apply bitwise operations on them? I've tried: np.bitwise_and(A[1,:], A[2,:]) but NumPy seems to want an array type according to the documentation.
[ "By \"lil_matrix\", do you mean a scipy.sparse.lil_matrix? If so, you'll have to convert your sparse array to a normal dense array to do bitwise operations on it, I believe.\na = np.asarray(A.todense())\nnp.bitwise_and(a[1,:], a[2,:])\n\nShould do the trick, I think...\nEDIT: Forgot an \"asarray\" there...\n" ]
[ 3 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0002716237_numpy_python_scipy.txt
Q: How to plot non-numeric data in Matplotlib I wish to plot the time variation of my y-axis variable using Matplotlib. This is no problem for continuously discrete data, however how should this be tackled for non-continuous data. I.e. if I wanted to visualise the times at which my car was stationary on the way to w...
How to plot non-numeric data in Matplotlib
I wish to plot the time variation of my y-axis variable using Matplotlib. This is no problem for continuously discrete data, however how should this be tackled for non-continuous data. I.e. if I wanted to visualise the times at which my car was stationary on the way to work the x-axis would be time and the y-axis woul...
[ "Is this the type of thing you want? (If not, you might want to check out the matplotlib gallery page to give yourself some ideas, or maybe just draw a picture and post it.)\nimport matplotlib.pyplot as plt\n\ndata = [0]*5 + [1]*10 + [0]*3 +[1]*2\n\nprint data\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.p...
[ 7 ]
[]
[]
[ "matplotlib", "python", "visualization" ]
stackoverflow_0002715535_matplotlib_python_visualization.txt
Q: BeautifulSoup, but for CSS? BeautifulSoup parses HTML and offers various ways to manipulate and search within HTML. Is there something similar for CSS? Specifically, I'd like to know if a given HTML text is rendered as bold. Either it has an ancestor that is the <strong> or the <bold> tag (which can be done with B...
BeautifulSoup, but for CSS?
BeautifulSoup parses HTML and offers various ways to manipulate and search within HTML. Is there something similar for CSS? Specifically, I'd like to know if a given HTML text is rendered as bold. Either it has an ancestor that is the <strong> or the <bold> tag (which can be done with BeautifulSoup), or it has an ances...
[ "Have a look to CSSParser class of cssutils package.\n", "You might have some luck using some of the CSS parsing packages available for python.\nOne in particular that can take CSS blocks and turn them into inline styles is the premailer package. That might make it easier to work with the tool you're already usin...
[ 3, 0 ]
[]
[]
[ "beautifulsoup", "css", "python" ]
stackoverflow_0002716181_beautifulsoup_css_python.txt
Q: Python comparing string against several regular expressions I'm pretty experienced with Perl and Ruby but new to Python so I'm hoping someone can show me the Pythonic way to accomplish the following task. I want to compare several lines against multiple regular expressions and retrieve the matching group. In Rub...
Python comparing string against several regular expressions
I'm pretty experienced with Perl and Ruby but new to Python so I'm hoping someone can show me the Pythonic way to accomplish the following task. I want to compare several lines against multiple regular expressions and retrieve the matching group. In Ruby it would be something like this: # Revised to show variance in ...
[ "Something like this, but prettier:\nregexs = [re.compile('...'), ...]\n\nfor regex in regexes:\n m = regex.match(s)\n if m:\n print m.groups()\n break\nelse:\n print 'No match'\n\n", "There are several ways to \"bind a name on the fly\" in Python, such as my old recipe for \"assign and test\"; in this c...
[ 1, 1, 0 ]
[ "your regex simply takes whatever is after the 3rd character onwards.\nfor line in open(\"file\"):\n if line.startswith(\"A:\"):\n print \"FOO #{\"+line[2:]+\"}\"\n elif line.startswith(\"B:\"):\n print \"BAR #{\"+line[2:]+\"}\"\n else:\n print \"No match\"\n\n" ]
[ -1 ]
[ "python", "regex", "switch_statement" ]
stackoverflow_0002633738_python_regex_switch_statement.txt
Q: Hashing a python function to regenerate output when the function is modified I have a python function that has a deterministic result. It takes a long time to run and generates a large output: def time_consuming_function(): # lots_of_computing_time to come up with the_result return the_result I modify tim...
Hashing a python function to regenerate output when the function is modified
I have a python function that has a deterministic result. It takes a long time to run and generates a large output: def time_consuming_function(): # lots_of_computing_time to come up with the_result return the_result I modify time_consuming_function from time to time, but I would like to avoid having it run ag...
[ "If I understand your problem, I think I'd tackle it like this. It's a touch evil, but I think it's more reliable and on-point than the other solutions I see here.\nimport inspect\nimport functools\nimport json\n\ndef memoize_zeroadic_function_to_disk(memo_filename):\n def decorator(f):\n try:\n ...
[ 6, 1, 0, 0 ]
[ "What you describe is effectively memoization. Most common functions can be memoized by defining a decorator.\nA (overly simplified) example:\ndef memoized(f):\n cache={}\n def memo(*args):\n if args in cache:\n return cache[args]\n else:\n ret=f(*args)\n cache[a...
[ -1 ]
[ "caching", "hash", "python" ]
stackoverflow_0002716710_caching_hash_python.txt
Q: Making an asynchronous interface appear synchronous to mod_python users I have a Python-driven web interface powered by Apache 2.2 with mod_python and Python 2.4. I need to make an asynchronous process appear synchronous to users of this web interface. When users access one module on this website: An external SO...
Making an asynchronous interface appear synchronous to mod_python users
I have a Python-driven web interface powered by Apache 2.2 with mod_python and Python 2.4. I need to make an asynchronous process appear synchronous to users of this web interface. When users access one module on this website: An external SOAP interface will be contacted with a unique identifier and will respond with...
[ "Maybe you can use Orbited to get ajax push with long-lived HTTP connections to your web clients. Orbited is based on Twisted, so I think it makes sense to look at if you already know Twisted. Have a look at this tutorial to get started.\n" ]
[ 2 ]
[]
[]
[ "asynchronous", "mod_python", "python", "synchronization", "twisted" ]
stackoverflow_0002717279_asynchronous_mod_python_python_synchronization_twisted.txt
Q: Python stdout, \r progress bar and sshd with Putty not updating regularly I have a dead simple progress "bar" using something like the following: import sys from time import sleep current = 0 limit = 50 while current <= limit: sys.stdout.write('\rSynced %s/%s orders' % (current, limit)) current_order += 1...
Python stdout, \r progress bar and sshd with Putty not updating regularly
I have a dead simple progress "bar" using something like the following: import sys from time import sleep current = 0 limit = 50 while current <= limit: sys.stdout.write('\rSynced %s/%s orders' % (current, limit)) current_order += 1 sleep(1) Works fine, except over ssh with Putty. Putty only updates every...
[ "Try doing sys.stdout.flush() after sys.stdout.write call.\n", "You can use flush() to force an update.\nsys.stdout.write('\\r[%s%s]' % ('=' * completed, ' ' * (total-completed)))\nsys.stdout.flush()\n\n", "Use sys.stderr.write instead, which is not buffered as sys.stdout is, and this way you separate progress ...
[ 3, 1, 0 ]
[]
[]
[ "putty", "python", "ssh" ]
stackoverflow_0002712166_putty_python_ssh.txt
Q: Dealing with Windows line-endings in Python I've got a 700MB XML file coming from a Windows provider. As one might expect, the line endings are '\r\n' (or ^M in vi). What is the most efficient way to deal with this situation aside from getting the supplier to send over '\n' :-) Use os.linesep Use rstrip() (requi...
Dealing with Windows line-endings in Python
I've got a 700MB XML file coming from a Windows provider. As one might expect, the line endings are '\r\n' (or ^M in vi). What is the most efficient way to deal with this situation aside from getting the supplier to send over '\n' :-) Use os.linesep Use rstrip() (requiring opening the file ... which seems crazy) Usin...
[ "Why are the DOS line-endings a problem? Most things can deal with them just fine, including XML parsers. If you really want to get rid of them, open the file in universal line-endings mode:\nopen(filename, 'rU')\n\nPython will convert all line-endings to UNIX line-endings for you. If you really can't use that (whi...
[ 6, 2, 1, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0002717086_file_python.txt
Q: How to display a page in my browser with python code that is run locally on my computer with "GAE" SDK? When I run this code on my computer with the help of "Google App Engine SDK", it displays (in my browser) the HTML code of the Google home page: from google.appengine.api import urlfetch url = "http://www.google...
How to display a page in my browser with python code that is run locally on my computer with "GAE" SDK?
When I run this code on my computer with the help of "Google App Engine SDK", it displays (in my browser) the HTML code of the Google home page: from google.appengine.api import urlfetch url = "http://www.google.com/" result = urlfetch.fetch(url) print result.content How can I make it display the page itself? I mean ...
[ "Is not that easy, you have to parse content and adjust relative to absolute paths for images and javascripts.\nAnyway, give it a try adding the correct Content-Type:\nfrom google.appengine.api import urlfetch\nurl = \"http://www.google.com/\"\nresult = urlfetch.fetch(url)\nprint 'Content-Type: text/html'\nprint ''...
[ 1, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002717370_google_app_engine_python.txt
Q: Multiple range product in Python Is there a better way to do this: perms = product(range(1,7),range(1,7),range(1,7)) so that I can choose how many ranges I use? I want it to be equivalent to this, but scalable. def dice(num) if num == 1: perms = ((i,) for i in range(1,7)) elif num == 2: pe...
Multiple range product in Python
Is there a better way to do this: perms = product(range(1,7),range(1,7),range(1,7)) so that I can choose how many ranges I use? I want it to be equivalent to this, but scalable. def dice(num) if num == 1: perms = ((i,) for i in range(1,7)) elif num == 2: perms = product(range(1,7),range(1,7)) ...
[ "Yes. Use the repeat keyword argument:\nperms = product(range(1, 7), repeat=3)\n\nSee the docs for more.\n", "I think\nperms = itertools.product(*([xrange(1,7)]*num))\n\nshould work for you.\n" ]
[ 10, 0 ]
[]
[]
[ "generator", "permutation", "python", "range" ]
stackoverflow_0002718029_generator_permutation_python_range.txt
Q: How do I pass a lot of parameters to views in Django? I'm very new to Django and I'm trying to build an application to present my data in tables and charts. Till now my learning process went very smooth, but now I'm a bit stuck. My pageview retrieves large amounts of data from a database and puts it in the context...
How do I pass a lot of parameters to views in Django?
I'm very new to Django and I'm trying to build an application to present my data in tables and charts. Till now my learning process went very smooth, but now I'm a bit stuck. My pageview retrieves large amounts of data from a database and puts it in the context. The template then generates different html-tables. So far...
[ "You can't pass the data from the page view to the chart view, since they are separate HTTP requests. You have a few options:\n\nPass all the data in the URL of the chart. This may sound crazy, but this is just what Google Charts does: http://code.google.com/apis/chart/docs/making_charts.html\nStore the data in t...
[ 6, 1 ]
[]
[]
[ "charts", "django", "parameters", "python" ]
stackoverflow_0002717824_charts_django_parameters_python.txt
Q: While trying to set up Django on Windows: AttributeError: 'Settings' object has no attribute 'DATABASES' I'm following these instructions in order to set up Django on Windows. I have installed Python 2.6, PostgreSQL 8.4, Psycopg 2.0.14 for Python 2.6 and the latest version of Django from SVN. I'm now following the...
While trying to set up Django on Windows: AttributeError: 'Settings' object has no attribute 'DATABASES'
I'm following these instructions in order to set up Django on Windows. I have installed Python 2.6, PostgreSQL 8.4, Psycopg 2.0.14 for Python 2.6 and the latest version of Django from SVN. I'm now following these instructions to run a test project (copied from the page linked to above): C:\Documents and Settings\John>c...
[ "The SVN checkout version of Django is looking for a setting like this in settings.py:\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'mydatabase'\n }\n}\n\nThis is slightly different than the way it's shown in the Django book and many tutorials.\nCheckout the ...
[ 4 ]
[]
[]
[ "django", "postgresql", "psycopg2", "python" ]
stackoverflow_0002717704_django_postgresql_psycopg2_python.txt
Q: python script to download xml files on my server I need a python script that will do the following: connect to a URL, and that URL will return a number like 1200. Use the number, to download xml files named: 1 to x where x is the number from #1. store the files in a particular directory. Sorry I've never written...
python script to download xml files on my server
I need a python script that will do the following: connect to a URL, and that URL will return a number like 1200. Use the number, to download xml files named: 1 to x where x is the number from #1. store the files in a particular directory. Sorry I've never written a python script, so if you could guide me along that ...
[ "Example using urllib:\nimport urllib\nimport os\n\nURL = 'http://someurl.com/foo/bar'\nDIRECTORY = '/some/local/folder'\n\n# connect to a URL, and that URL will return a number like 1200.\nnumber = int(urllib.urlopen(URL).read())\n\n# Use the number, to download xml files named: \n# 1 to x where x is the number fr...
[ 2, 1 ]
[]
[]
[ "cron", "python", "scripting" ]
stackoverflow_0002718176_cron_python_scripting.txt
Q: Find all Chinese text in a string using Python and Regex I needed to strip the Chinese out of a bunch of strings today and was looking for a simple Python regex. Any suggestions? A: Python 2: #!/usr/bin/env python # -*- encoding: utf8 -*- import re sample = u'I am from 美国。We should be friends. 朋友。' for n in r...
Find all Chinese text in a string using Python and Regex
I needed to strip the Chinese out of a bunch of strings today and was looking for a simple Python regex. Any suggestions?
[ "Python 2:\n#!/usr/bin/env python\n# -*- encoding: utf8 -*-\n\n\nimport re\n\nsample = u'I am from 美国。We should be friends. 朋友。'\nfor n in re.findall(ur'[\\u4e00-\\u9fff]+',sample):\n print n\n\nPython 3:\nsample = 'I am from 美国。We should be friends. 朋友。'\nfor n in re.findall(r'[\\u4e00-\\u9fff]+', sample):\n ...
[ 43, 31 ]
[]
[]
[ "cjk", "python", "regex" ]
stackoverflow_0002718196_cjk_python_regex.txt
Q: How can I set the line style of a specific cell in a QTableView? I am working with a QT GUI. I am implementing a simple hex edit control using a QTableView. My initial idea is to use a table with seventeen columns. Each row of the table will have 16 hex bytes and then an ASCII representation of that data in the se...
How can I set the line style of a specific cell in a QTableView?
I am working with a QT GUI. I am implementing a simple hex edit control using a QTableView. My initial idea is to use a table with seventeen columns. Each row of the table will have 16 hex bytes and then an ASCII representation of that data in the seventeenth column. Ideally, I would like to edit/set the style of the s...
[ "I could think about a couple of ways of doing what you need; both would include drawing custom grid as it looks like there is no straight forward way of hooking into the grid painting routine of QTableView class:\n1.Switch off the standard grid for your treeview grid by calling setShowGrid(false) and draw grid lin...
[ 4 ]
[]
[]
[ "c++", "pyqt4", "python", "qt", "qtableview" ]
stackoverflow_0002717318_c++_pyqt4_python_qt_qtableview.txt
Q: Why can't I display a unicode character in the Python Interpreter on Mac OS X Terminal.app? If I try to paste a unicode character such as the middle dot: · in my python interpreter it does nothing. I'm using Terminal.app on Mac OS X and when I'm simply in in bash I have no trouble: :~$ · But in the interpreter: ...
Why can't I display a unicode character in the Python Interpreter on Mac OS X Terminal.app?
If I try to paste a unicode character such as the middle dot: · in my python interpreter it does nothing. I'm using Terminal.app on Mac OS X and when I'm simply in in bash I have no trouble: :~$ · But in the interpreter: :~$ python Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] ...
[ "unicode('\\xc2\\xb7') means to decode the byte string in question with the default codec, which is ascii -- and that of course fails (trying to set a different default encoding has never worked well, and in particular doesn't apply to \"pasted literals\" -- that would require a different setting anyway). You coul...
[ 6 ]
[]
[]
[ "macos", "python", "terminal", "unicode" ]
stackoverflow_0002718491_macos_python_terminal_unicode.txt
Q: get city, state or zip from a string in python I'd like to be able to parse out the city, state or zip from a string in python. So, if I entered Boulder, Co 80303 Boulder, Colorado Boulder, Co 80303 ... any variation of these it would return the city, state or zip. This is all going to be user inputted data an...
get city, state or zip from a string in python
I'd like to be able to parse out the city, state or zip from a string in python. So, if I entered Boulder, Co 80303 Boulder, Colorado Boulder, Co 80303 ... any variation of these it would return the city, state or zip. This is all going to be user inputted data and inputted in one text field.
[ "Just ask for their zip only, then give a (short) list of applicable cities by using a geocode database. That way you get nice clean 5-digit input, they save time, and you all go home happy.\nIf you already have the data, look just for the zip, find a list of possible cities (there will only be one applicable state...
[ 3, 3, 1, 1, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0002054422_python_regex_string.txt
Q: How do I create a type of compression that my software can read / write? My software only I am working on a project that requires programmatically distributing a compressed file that in a format that is associated with my software. I am writing the software in Python. I would use .zip, but I don't want to overwrit...
How do I create a type of compression that my software can read / write? My software only
I am working on a project that requires programmatically distributing a compressed file that in a format that is associated with my software. I am writing the software in Python. I would use .zip, but I don't want to overwrite any previouse filetype associations. ( with zip utilities )
[ "You could create new file extension other than .zip and associate that file extension with your program.\n", "Do what Java does: use zip format[*] file, but use a different filename extension.\n[*] or a standard compression format of your choosing.\n", "If you are looking to be able to associate an extension w...
[ 4, 0, 0 ]
[]
[]
[ "associations", "compression", "format", "python" ]
stackoverflow_0002718933_associations_compression_format_python.txt
Q: filter queryset based on list, including None I dont know if its a django bug or a feature but i have a strange ORM behaviour with MySQL. class Status(models.Model): name = models.CharField(max_length = 50) class Article(models.Model) status = models.ForeignKey(status, blank = True, null=True) filters = ...
filter queryset based on list, including None
I dont know if its a django bug or a feature but i have a strange ORM behaviour with MySQL. class Status(models.Model): name = models.CharField(max_length = 50) class Article(models.Model) status = models.ForeignKey(status, blank = True, null=True) filters = Q(status__in =[0, 1,2] ) | Q(status=None) items =...
[ "Try using this query instead:\nfilters = Q(status__in =[0, 1,2] ) | Q(status__isnull=True) \n\n", "In your foreign key attribute for the Article model, you're referencing status with a lowercase 's'. But your Status model has an uppercase 'S'. Not sure where your typo is, but in case your model is actually def...
[ 1, 0 ]
[]
[]
[ "django", "mysql", "orm", "python", "sql" ]
stackoverflow_0002717282_django_mysql_orm_python_sql.txt
Q: how to diff / align Python lists using arbitrary matching function? I'd like to align two lists in a similar way to what difflib.Differ would do except I want to be able to define a match function for comparing items, not just use string equality, and preferably a match function that can return a number between 0....
how to diff / align Python lists using arbitrary matching function?
I'd like to align two lists in a similar way to what difflib.Differ would do except I want to be able to define a match function for comparing items, not just use string equality, and preferably a match function that can return a number between 0.0 and 1.0, not just a boolean. So, for example, say I had the two lists: ...
[ "I just wrote this implementation of Needleman-Wunsch and it seems to do what I want:\ndef nw_align(a, b, replace_func, insert, delete):\n\n ZERO, LEFT, UP, DIAGONAL = 0, 1, 2, 3\n\n len_a = len(a)\n len_b = len(b)\n\n matrix = [[(0, ZERO) for x in range(len_b + 1)] for y in range(len_a + 1)]\n\n for...
[ 8, 0 ]
[]
[]
[ "diff", "python" ]
stackoverflow_0002718809_diff_python.txt
Q: python packaging problem hi develop code in python to scan wifi and send to the server, its working fine when execute manually, but i packaged it via http://www.python-packager.com by uploading my .py file and they create package for me as deb file for linux, and i download it and install the package but nothing ...
python packaging problem
hi develop code in python to scan wifi and send to the server, its working fine when execute manually, but i packaged it via http://www.python-packager.com by uploading my .py file and they create package for me as deb file for linux, and i download it and install the package but nothing happen when i click the .exe o...
[ "I'm the maintainer of the project, I thought I'd chime in and give my 2c.\nI had a look at your program. With .deb's, it installs everything to /opt/application-name. So to debug-it, run it from the command line. eg. \"/opt/Jemapoh_Wifi/Jemapoh_Wifi\".\nI just ran it myself and your programs gives the error \"IOEr...
[ 4, 2 ]
[]
[]
[ "package", "python" ]
stackoverflow_0002711462_package_python.txt
Q: Break nested loop in Django views.py with a function I have a nested loop that I would like to break out of. After searching this site it seems the best practice is to put the nested loop into a function and use return to break out of it. Is it acceptable to have functions inside the views.py file that are not a v...
Break nested loop in Django views.py with a function
I have a nested loop that I would like to break out of. After searching this site it seems the best practice is to put the nested loop into a function and use return to break out of it. Is it acceptable to have functions inside the views.py file that are not a view? What is the best practice for the location of this fu...
[ "Yes. it's fine to have functions in views.py that are not views - (I do this all the time). This is particularly appropriate if the function is only for use within that module (i.e. by views in that views.py), or by just a single view function.\nYou could always make it a private function if you're worried about e...
[ 2, 2 ]
[]
[]
[ "django", "django_views", "loops", "python" ]
stackoverflow_0002718890_django_django_views_loops_python.txt
Q: Posting messages in two RabbitMQ queue, instead of one (using py-amqp) I've got this strange problem using py-amqp and the Flopsy module. I have written a publisher that sends messages to a RabbitMQ server, and I wanted to be able to send it to a specified queue. On the Flopsy module that is not possible, so I twe...
Posting messages in two RabbitMQ queue, instead of one (using py-amqp)
I've got this strange problem using py-amqp and the Flopsy module. I have written a publisher that sends messages to a RabbitMQ server, and I wanted to be able to send it to a specified queue. On the Flopsy module that is not possible, so I tweaked it adding a parameter and a line to declare the queue on the _init__ me...
[ "OK, I've think I've got it. unless anybody else have a better idea. I've check this tutorial on AMQP I was assuming that the publisher should know the queue, but that's not the case, you need to send the message to a exchange, and the consumer will declare that the queue is related to the exchange. That allow diff...
[ 0 ]
[]
[]
[ "amqp", "flopsy", "py_amqplib", "python" ]
stackoverflow_0002719638_amqp_flopsy_py_amqplib_python.txt
Q: best framework on gae(python) ,like jquery on javascript ? has it? i want to find a framework to make my work simple on gae , has it ? thanks i found one, but not very good http://code.google.com/p/appengine-framework/ A: There are a large number of frameworks you can use on App Engine - both those custom desig...
best framework on gae(python) ,like jquery on javascript ? has it?
i want to find a framework to make my work simple on gae , has it ? thanks i found one, but not very good http://code.google.com/p/appengine-framework/
[ "There are a large number of frameworks you can use on App Engine - both those custom designed for it, and those that are general purpose and work fine on App Engine. If you've used a Python framework in the past, some small amount of searching will tell you if it will work on App Engine with or without modificatio...
[ 1 ]
[]
[]
[ "frameworks", "google_app_engine", "python" ]
stackoverflow_0002719752_frameworks_google_app_engine_python.txt
Q: JQuery cookie access has stopped working for GAE app I have a google app engine app that has been running for some time, and some javascript code that checks for a login cookie has suddenly stopped working. As far as I can tell, NO code has changed. The relevant code uses the jquery cookies plugin (jquery.cookies...
JQuery cookie access has stopped working for GAE app
I have a google app engine app that has been running for some time, and some javascript code that checks for a login cookie has suddenly stopped working. As far as I can tell, NO code has changed. The relevant code uses the jquery cookies plugin (jquery.cookies.2.2.0.min.js)... // control the default screen depending ...
[ "Possibly the ACSID cookie is now being marked as 'secure', and hence unavailable to Javascript. Why the devil are you doing this in the first place, though?\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "javascript", "jquery", "python" ]
stackoverflow_0002716892_google_app_engine_javascript_jquery_python.txt
Q: multi-line pattern matching in python A periodic computer generated message (simplified): Hello user123, - (604)7080900 - 152 - minutes Regards Using python, how can I extract "(604)7080900", "152", "minutes" (i.e. any text following a leading "- " pattern) between the two empty lines (empty line is the \n\n af...
multi-line pattern matching in python
A periodic computer generated message (simplified): Hello user123, - (604)7080900 - 152 - minutes Regards Using python, how can I extract "(604)7080900", "152", "minutes" (i.e. any text following a leading "- " pattern) between the two empty lines (empty line is the \n\n after "Hello user123" and the \n\n before "Re...
[ ">>> import re\n>>>\n>>> x=\"\"\"Hello user123,\n...\n... - (604)7080900\n... - 152\n... - minutes\n...\n... Regards\n... \"\"\"\n>>>\n>>> re.findall(\"\\n+\\n-\\s*(.*)\\n-\\s*(.*)\\n-\\s*(minutes)\\s*\\n\\n+\",x)\n[('(604)7080900', '152', 'minutes')]\n>>>\n\n", "The simplest approach is to go over these lines (a...
[ 4, 3, 1, 1 ]
[]
[]
[ "multiline", "python", "regex" ]
stackoverflow_0002720022_multiline_python_regex.txt
Q: Why are my two date fields not identical when I copy them? I use django, and have two models with a models.DateTimeField(). Sometimes I need a copy of a date - but look at this: >>>myobject.date = datetime.datetime.now() >>>print myobject.date >>>2010-04-27 12:10:43.526277 >>>other_object.date_copy = myobject.da...
Why are my two date fields not identical when I copy them?
I use django, and have two models with a models.DateTimeField(). Sometimes I need a copy of a date - but look at this: >>>myobject.date = datetime.datetime.now() >>>print myobject.date >>>2010-04-27 12:10:43.526277 >>>other_object.date_copy = myobject.date >>>print other_object.date_copy >>>2010-04-27 12:10:43 Why a...
[ "What version of python are you using?\nSeems to work for me...\nIn [3]: s = datetime.datetime.now()\nIn [4]: x = s\nIn [5]: print s\n------> print(s)\n2010-04-27 06:37:02.303067\nIn [6]: print x\n------> print(x)\n2010-04-27 06:37:02.303067\n\nAre you storing the datetime into a 3rd party structure like an sqldb v...
[ 3 ]
[]
[]
[ "datetime", "django", "python" ]
stackoverflow_0002720414_datetime_django_python.txt
Q: Simple check authentication decorator in Python + Pylons I'd like to write a simple decorator that I can put above functions in my controller to check authentication and re-direct to the login page if the current user is not authenticated. What is the best way to do this? Where should the decorator go? How shou...
Simple check authentication decorator in Python + Pylons
I'd like to write a simple decorator that I can put above functions in my controller to check authentication and re-direct to the login page if the current user is not authenticated. What is the best way to do this? Where should the decorator go? How should I pass cookie info to the decorator? Sample code is greatl...
[ "Another approach for authorization in pylons (decorator based, repoze.what like)\n\nHow should I pass cookie info to the\n decorator?\n\nUse a global request object and get cookie or use wsgi environ of the request\n" ]
[ 2 ]
[]
[]
[ "decorator", "pylons", "python" ]
stackoverflow_0002718716_decorator_pylons_python.txt
Q: making binned boxplot in matplotlib with numpy and scipy in Python I have a 2-d array containing pairs of values and I'd like to make a boxplot of the y-values by different bins of the x-values. I.e. if the array is: my_array = array([[1, 40.5], [4.5, 60], ...]]) then I'd like to bin my_array[:, 0] and then for ...
making binned boxplot in matplotlib with numpy and scipy in Python
I have a 2-d array containing pairs of values and I'd like to make a boxplot of the y-values by different bins of the x-values. I.e. if the array is: my_array = array([[1, 40.5], [4.5, 60], ...]]) then I'd like to bin my_array[:, 0] and then for each of the bins, produce a boxplot of the corresponding my_array[:, 1] ...
[ "You're getting the 3rd bin for the maximum value in the array (I'm assuming you have a typo there, and max_x should be \"max(my_array[:,0])\" instead of \"max(my_array[:,1])\"). You can avoid this by adding 1 (or any positive number) to the last bin.\nAlso, if I'm understanding you correctly, you want to bin one ...
[ 7, 4 ]
[]
[]
[ "matplotlib", "numpy", "plot", "python", "scipy" ]
stackoverflow_0002716894_matplotlib_numpy_plot_python_scipy.txt
Q: QPluginLoader with PyQt modules as plugins: possible? I have a C++ application that loads externals plugins thanks to QPluginloader. QPluginLoader provides access to a Qt plugin. A Qt plugin is stored in a shared library (a DLL). The plugins have to inherit from a pure virtual class ( and Q_DECLARE_INTERFACE ) and...
QPluginLoader with PyQt modules as plugins: possible?
I have a C++ application that loads externals plugins thanks to QPluginloader. QPluginLoader provides access to a Qt plugin. A Qt plugin is stored in a shared library (a DLL). The plugins have to inherit from a pure virtual class ( and Q_DECLARE_INTERFACE ) and QObject. I would like to create plugins by using python an...
[ "Well, I don't think it's possible without too much work. If you write a module in PyQt, chances are that you would have to add the entire Python interpreter to your executable in order to be able to interpret those modules. Even if you translate those modules into C++, the translated functions will have to call th...
[ 2 ]
[]
[]
[ "c++", "plugins", "pyqt", "python", "qt" ]
stackoverflow_0002691724_c++_plugins_pyqt_python_qt.txt
Q: Python: Traffic-Simulation (cars on a road) I want to create a traffic simulator like here: http://www.doobybrain.com/wp-content/uploads/2008/03/traffic-simulation.gif But I didn't thougt very deep about this. I would create the class car. Every car has his own color, position and so on. And I could create the ro...
Python: Traffic-Simulation (cars on a road)
I want to create a traffic simulator like here: http://www.doobybrain.com/wp-content/uploads/2008/03/traffic-simulation.gif But I didn't thougt very deep about this. I would create the class car. Every car has his own color, position and so on. And I could create the road with an array. But how to tell the car where t...
[ "You don't tell a car where to go. It goes anyway due to its velocity. By looking ahead (where will it be a few timesteps from now, and is there still a road?) you can see whether you need to adjust the velocity.\nAnd a road isn't an array; it's a matrix or bitmap. You can't go all that fast in the corner or you'll...
[ 5, 2, 2, 2, 2, 1, 0 ]
[]
[]
[ "python", "simulation", "traffic" ]
stackoverflow_0002720378_python_simulation_traffic.txt
Q: Django ModelFormSet with Google app engine I'm using Django with google app engine. I'm using the google furnished django app engine helper project. I'm attempting to create a Django modelformset like this: #MyModel inherits from BaseModel MyFormSet = modelformset_factory(models.MyModel) However, it's failing...
Django ModelFormSet with Google app engine
I'm using Django with google app engine. I'm using the google furnished django app engine helper project. I'm attempting to create a Django modelformset like this: #MyModel inherits from BaseModel MyFormSet = modelformset_factory(models.MyModel) However, it's failing with this error: 'ModelOptions' object has no ...
[ "It is a fundamental incompatibility between Django and GAE, because they do not share the same interface for their models. The django helper does not include a patch for the modelformsets, but django-nonrel probably does, or will eventually.\nSince the google team does not spend much time on the django helper any...
[ 0 ]
[]
[]
[ "django", "django_forms", "google_app_engine", "python" ]
stackoverflow_0002526394_django_django_forms_google_app_engine_python.txt
Q: How to create Python module distribution to gracefully fall-back to pure Python code I have written a Python module, and I have two versions: a pure Python implementation and a C extension. I've written the __init__.py file so that it tries to import the C extension, and if that fails, it imports the pure Python c...
How to create Python module distribution to gracefully fall-back to pure Python code
I have written a Python module, and I have two versions: a pure Python implementation and a C extension. I've written the __init__.py file so that it tries to import the C extension, and if that fails, it imports the pure Python code (is that reasonable?). Now, I'd like to know what is the best way to distribute this m...
[ "\n(is that reasonable?).\n\nYep, perfectly sensible.\nTo catch the \"no suitable C compiler case\": the call to setup(...) will do a sys.exit in case of problems. So, first try it with the ext_modules argument set as desired, within a try:\ntry:\n setup(..., ext_modules=...)\nexcept SystemExit: ...\n\nand in the...
[ 7, 0, 0 ]
[]
[]
[ "python", "software_distribution" ]
stackoverflow_0002398699_python_software_distribution.txt
Q: How does large text file viewer work? How to build a large text reader how does large text file viewer work? I'm assuming that: Threading is used to handle the file The TextBox is updated line by line Effective memory handling is used Are these assumptions correct? if someone were to develop their own, what are...
How does large text file viewer work? How to build a large text reader
how does large text file viewer work? I'm assuming that: Threading is used to handle the file The TextBox is updated line by line Effective memory handling is used Are these assumptions correct? if someone were to develop their own, what are the mustsand don'ts? I'm looking to implement one using a DataGrid instead ...
[ "I believe that the trick is not loading the entire file into memory, but using seek and such to just load the part which is viewed (possibly with a block before and after to handle a bit of scrolling). Perhaps even using memory-mapped buffers, though I have no experience with those.\nDo realize that modifying a la...
[ 6, 4 ]
[]
[]
[ "c++", "multithreading", "pyqt", "python", "qt" ]
stackoverflow_0002720752_c++_multithreading_pyqt_python_qt.txt
Q: Using PyLab to create a 2D graph from two separate lists This seems like a basic problem with an easy answer but I simply cannot figure it out no matter how much I try. I am trying to create a line graph based on two lists. For my x-axis, I want my list to be a set of strings. x_axis_list = ["Jan-06","Jul-06","J...
Using PyLab to create a 2D graph from two separate lists
This seems like a basic problem with an easy answer but I simply cannot figure it out no matter how much I try. I am trying to create a line graph based on two lists. For my x-axis, I want my list to be a set of strings. x_axis_list = ["Jan-06","Jul-06","Jan-07","Jul-07","Jan-08"] y_axis_list = [5,7,6,8,9] Any sugge...
[ "from pylab import *\nfrom matplotlib.font_manager import FontProperties\n\ndates = [\"Jan-06\",\"Jul-06\",\"Jan-07\",\"Jul-07\",\"Jan-08\"]\nx_axis_list = range(len(dates))\ny_axis_list = [5,7,6,8,9]\n\nfigure()\nplot(x_axis_list, y_axis_list, \"k\")\nxticks(x_axis_list, dates, rotation=45)\nshow()\n\n" ]
[ 5 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0002722216_matplotlib_python.txt
Q: optimize pymssql code i am inserting records to sql server from python using pymssql. The database takes 2 milliseconds to execute a query, yet it insert 6 rows per second. The only problem is at code side. how to optimize following code or what is the fastest method to insert records. def save(self): conn = p...
optimize pymssql code
i am inserting records to sql server from python using pymssql. The database takes 2 milliseconds to execute a query, yet it insert 6 rows per second. The only problem is at code side. how to optimize following code or what is the fastest method to insert records. def save(self): conn = pymssql.connect(host=dbHost,...
[ "It looks like you're creating a new connection per insert there. That's probably the major reason for the slowdown: building new connections is typically quite slow. Create the connection outside the method and you should see a large improvement. You can also create a cursor outside function and re-use it, which w...
[ 4, 3 ]
[]
[]
[ "optimization", "pymssql", "python" ]
stackoverflow_0002721063_optimization_pymssql_python.txt
Q: Various way to send data to the web server Client Environment : Windows XP , Internet connection Available, PHP Not installed. Server Environment : CentOS , Internet connection Available, PHP , MYsql installed. Data are stored in files at client machine , suggest better ways to send data fetched from the file to t...
Various way to send data to the web server
Client Environment : Windows XP , Internet connection Available, PHP Not installed. Server Environment : CentOS , Internet connection Available, PHP , MYsql installed. Data are stored in files at client machine , suggest better ways to send data fetched from the file to the server. Normally i would be using HTTP reques...
[ "Unless you want to install some sort of software on the client machine to make the data available to the server, there is really no other simple way that I can think of other than writing a web app to upload the files (which may not be practical, and certainly requires manual labor).\nOtherwise, you could setup an...
[ 0 ]
[]
[]
[ "http", "php", "python", "web_services" ]
stackoverflow_0002718932_http_php_python_web_services.txt
Q: One letter game Issue? Recently at a job interview I was given the following problem: Write a script capable of running on the command line as python It should take in two words on the command line (or optionally if you'd prefer it can query the user to supply the two words via the console). Given those two word...
One letter game Issue?
Recently at a job interview I was given the following problem: Write a script capable of running on the command line as python It should take in two words on the command line (or optionally if you'd prefer it can query the user to supply the two words via the console). Given those two words: a. Ensure they are of equ...
[ "I wouldn't say your solution is wrong, but it is a little slow. For two reasons. \n\nBreadth-first-search is going to visit all paths of length one shorter than is needed, plus some-to-all of paths of length needed, before it can give you an answer. A best-first-search (A*) will ideally skip most irrelevant paths....
[ 10, 3, 1, 1, 0 ]
[]
[]
[ "letter", "optimization", "python" ]
stackoverflow_0002721514_letter_optimization_python.txt
Q: Use Twisted's getPage as urlopen? I would like to use Twisted non-blocking getPage method within a webapp, but it feels quite complicated to use such function compared to urlopen. This is an example of what I'm trying to achive: def web_request(request): response = urllib.urlopen('http://www.example.org') re...
Use Twisted's getPage as urlopen?
I would like to use Twisted non-blocking getPage method within a webapp, but it feels quite complicated to use such function compared to urlopen. This is an example of what I'm trying to achive: def web_request(request): response = urllib.urlopen('http://www.example.org') return HttpResponse(len(response.read()))...
[ "The thing to realize about non-blocking operations (which you seem to explicitly want) is that you can't really write sequential code with them. The operations don't block because they don't wait for a result. They start the operation and return control to your function. So, getPage doesn't return a file-like obje...
[ 20, 4 ]
[]
[]
[ "django", "python", "twisted", "urllib", "urllib2" ]
stackoverflow_0002720484_django_python_twisted_urllib_urllib2.txt
Q: writing a fast parser in python I've written a hands-on recursive pure python parser for a some file format (ARFF) we use in one lecture. Now running my exercise submission is awfully slow. Turns out by far the most time is spent in my parser. It's consuming a lot of CPU time, the HD is not the bottleneck. I wonde...
writing a fast parser in python
I've written a hands-on recursive pure python parser for a some file format (ARFF) we use in one lecture. Now running my exercise submission is awfully slow. Turns out by far the most time is spent in my parser. It's consuming a lot of CPU time, the HD is not the bottleneck. I wonder what performant ways are there to w...
[ "You could use ANTLR or pyparsing, they might speed up your parsing process.\nAnd if you want to keep your current code, you might want to look at Cython/PyPy, which increases your perfomance (sometimes upto 4x).\n", "The most general tip I'd give without further information would be to read the entire file, or a...
[ 10, 10 ]
[]
[]
[ "arff", "parsing", "python" ]
stackoverflow_0002722995_arff_parsing_python.txt
Q: Tokenize a command string I have string like this: command ". / * or any other char like this" some_param="string param" some_param2=50 I want to tokenize this string into: command ". / * or any other char like this" some_param="string param" some_param2=50 I know it's possible to split with spaces but these par...
Tokenize a command string
I have string like this: command ". / * or any other char like this" some_param="string param" some_param2=50 I want to tokenize this string into: command ". / * or any other char like this" some_param="string param" some_param2=50 I know it's possible to split with spaces but these parameters can also be seperated b...
[ "The stdlib module shlex is designed for parsing shell-like command syntax:\n>>> import shlex\n>>> s = 'command \". / * or any other char like this\" some_param=\"string param\" some_param2=50'\n>>> shlex.split(s)\n['command', '. / * or any other char like this', 'some_param=string param', 'some_param2=50']\n\nThe ...
[ 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002723040_python_regex.txt
Q: python: list manipulation I have a list L of objects (for what it's worth this is in scons). I would like to create two lists L1 and L2 where L1 is L with an item I1 appended, and L2 is L with an item I2 appended. I would use append but that modifies the original list. How can I do this in Python? (sorry for the b...
python: list manipulation
I have a list L of objects (for what it's worth this is in scons). I would like to create two lists L1 and L2 where L1 is L with an item I1 appended, and L2 is L with an item I2 appended. I would use append but that modifies the original list. How can I do this in Python? (sorry for the beginner question, I don't use t...
[ "L1 = L + [i1]\nL2 = L + [i2]\n\nThat is probably the simplest way. Another option is to copy the list and then append:\nL1 = L[:] #make a copy of L\nL1.append(i1)\n\n", "L1=list(L)\n\nduplicates the list. I guess you can figure out the rest :)\n", "You can make a copy of your list\n>>> x = [1, 2, 3]\n>>>...
[ 8, 3, 2 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002723404_list_python.txt
Q: Why doesn't my QsciLexerCustom subclass work in PyQt4 using QsciScintilla? My end goal is to get Erlang syntax highlighting in QsciScintilla using PyQt4 and Python 2.6. I'm running on Windows 7, but will also need Ubuntu support. PyQt4 is missing the necessary wrapper code for the Erlang lexer/highlighter that "ba...
Why doesn't my QsciLexerCustom subclass work in PyQt4 using QsciScintilla?
My end goal is to get Erlang syntax highlighting in QsciScintilla using PyQt4 and Python 2.6. I'm running on Windows 7, but will also need Ubuntu support. PyQt4 is missing the necessary wrapper code for the Erlang lexer/highlighter that "base" scintilla has, so I figured I'd write a lightweight one on top of QsciLexerC...
[ "The answer was that the documentation for QsciLexerCustom is misleading.\nIt's not enough to call setStyling() with a QsciStyle object. Only the numeric index from that object actually seems to matter.\nAdditionally, your custom lexer needs to override the font(), color() and other style-getting functions that tak...
[ 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "scintilla" ]
stackoverflow_0002694593_pyqt_pyqt4_python_qt_scintilla.txt
Q: Why is recordset result being returned in this way for Python database query? I have searched high and low for an answer to why query results returned in this format and how to convert to a list. data = cursor.fetchall() When I print data, it results in: (('car',), ('boat',), ('plane',), ('truck',)) I want to have...
Why is recordset result being returned in this way for Python database query?
I have searched high and low for an answer to why query results returned in this format and how to convert to a list. data = cursor.fetchall() When I print data, it results in: (('car',), ('boat',), ('plane',), ('truck',)) I want to have the results in a list as ["car", "boat", "plane", "truck"]
[ "It's returning it in that way because a recordset is comprised of many rows of data, not a list of single elements.\nYou can flatten it if you want using a list comprehension:\ndata = [row[0] for row in cursor.fetchall()]\n\n", "The result for fetchall() returns an array of rows, where each row is an array with ...
[ 5, 1, 0 ]
[]
[]
[ "list", "mysql", "python", "recordset" ]
stackoverflow_0002723432_list_mysql_python_recordset.txt
Q: Python Regex To VB.net I made a program in Python and now I whant to transfert it to vb.net. But I have some difficulties with the vb.net regular expression.... Someone can help me please? There are my Python regex: id = re.search('(?<=watch\?v\=)[\w|-]+|(?<=/v/)[\w|-]+', src) id = id.group(0) t = re.search('(?<=...
Python Regex To VB.net
I made a program in Python and now I whant to transfert it to vb.net. But I have some difficulties with the vb.net regular expression.... Someone can help me please? There are my Python regex: id = re.search('(?<=watch\?v\=)[\w|-]+|(?<=/v/)[\w|-]+', src) id = id.group(0) t = re.search('(?<=\&t\=)[\w|-]+', src) t = t.g...
[ "An easy way to parse query strings is by using a NameValueCollection, using the HttpUtility.ParseQueryString method. This also takes care of encoding.\nFor example:\nNameValueCollection parameters = HttpUtility.ParseQueryString(\"?var1=1&var2=2\");\n\n" ]
[ 1 ]
[]
[]
[ "python", "regex", "vb.net" ]
stackoverflow_0002723485_python_regex_vb.net.txt
Q: How to convert Selenese (html) to Python programmatically? How would I convert test cases made by Selenium IDE to Python without exporting every test case by hand? Is there any command line converter for that job? In the end I want to use Selenium RC and Pythons build in unittest to test my websites. Thanks a lot....
How to convert Selenese (html) to Python programmatically?
How would I convert test cases made by Selenium IDE to Python without exporting every test case by hand? Is there any command line converter for that job? In the end I want to use Selenium RC and Pythons build in unittest to test my websites. Thanks a lot. Update: I started to write a converter but its too much work to...
[ "I've started building a Selenese-to-Python parser, PySelenese, which I've posted on Github. Feel free to fork/clone the repository and give it a try: http://github.com/jpstacey/PySelenese .\n", "No there isn't a way but in theory it shouldn't be too difficult to do as all you need to do is have something that us...
[ 3, 0 ]
[]
[]
[ "python", "selenium", "selenium_ide", "selenium_rc" ]
stackoverflow_0002617684_python_selenium_selenium_ide_selenium_rc.txt
Q: fd.seek() IOError: [Errno 22] Invalid argument My Python Interpreter (v2.6.5) raises the above error in the following codepart: fd = open("some_filename", "r") fd.seek(-2, os.SEEK_END) #same happens if you exchange the second arg. w/ 2 data=fd.read(2); last call is fd.seek() Traceback (most recent call last): ...
fd.seek() IOError: [Errno 22] Invalid argument
My Python Interpreter (v2.6.5) raises the above error in the following codepart: fd = open("some_filename", "r") fd.seek(-2, os.SEEK_END) #same happens if you exchange the second arg. w/ 2 data=fd.read(2); last call is fd.seek() Traceback (most recent call last): File "bot.py", line 250, in <module> fd.see...
[ "From lseek(2):\n\nEINVAL \nwhence is not one of SEEK_SET,\n SEEK_CUR, SEEK_END; or the resulting\n file offset would be negative, or\n beyond the end of a seekable device.\n\nSo double-check the value of iterator. \n" ]
[ 8 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0002724015_python_python_2.6.txt
Q: Python recommendation engine Is there a recommendation engine for python similar to Java Taste? A: I haven't found much that runs natively in python, but someone created python wrappers for SUGGEST, which looks like a solid program. SUGGEST overview python wrappers Since python is still fairly slow when compared...
Python recommendation engine
Is there a recommendation engine for python similar to Java Taste?
[ "I haven't found much that runs natively in python, but someone created python wrappers for SUGGEST, which looks like a solid program.\nSUGGEST overview\npython wrappers\nSince python is still fairly slow when compared to C or Java, using wrappers will probably improve performance.\n" ]
[ 0 ]
[]
[]
[ "python", "recommendation_engine" ]
stackoverflow_0002704845_python_recommendation_engine.txt
Q: CAC Client Application Authentication in Python I am building a python application to pull data from a website. The application has to authenticate(HTTPS/SSL) with a CAC card and pin in order to make requests. Am I correct in my assumptions that you can't retrieve the private key from a CAC card, and am therefore ...
CAC Client Application Authentication in Python
I am building a python application to pull data from a website. The application has to authenticate(HTTPS/SSL) with a CAC card and pin in order to make requests. Am I correct in my assumptions that you can't retrieve the private key from a CAC card, and am therefore stuck using a PKCS #11 Wrapper like PyKCS? Any tips o...
[ "Authentication and signature keys are usually generated on the card and are not extractable, unlike encryption keys which can/should be escrowed somewhere.\nSee Need help using M2Crypto.Engine to access USB Token for an example with M2Crypto that explains how to use a smart card via PKCS#11 for website access in p...
[ 4, 0, 0 ]
[]
[]
[ "cac", "pkcs#11", "python", "smartcard" ]
stackoverflow_0002366636_cac_pkcs#11_python_smartcard.txt
Q: Help with authorization and redirection decorator in python (pylons) I'm trying to write a simple decorator to check the authentication of a user, and to redirect to the login page if s/he is not authenticated: def authenticate(f): try: if user['authenticated'] is True: return f except:...
Help with authorization and redirection decorator in python (pylons)
I'm trying to write a simple decorator to check the authentication of a user, and to redirect to the login page if s/he is not authenticated: def authenticate(f): try: if user['authenticated'] is True: return f except: redirect_to(controller='login', action='index') class IndexContr...
[ "i don't know pylons, but it seems the way you wrote your decorator is not good. \na decorator is a callable which must return a callable. the decorator is called at the moment the function is defined, and it should return a callable (generally a function) which will be called in place of the function being decorat...
[ 5 ]
[]
[]
[ "decorator", "pylons", "python", "redirect" ]
stackoverflow_0002724057_decorator_pylons_python_redirect.txt
Q: Can python code (say if I used djangno) be obfuscated to the same 'level' as c#/java? If I obfuscated python code, would it provide the same level of 'security' as c#/java obfuscating? i.e it makes things a little hard, but really you can still reverse engineer if you really wanted to, its just a bit cryptic. A: ...
Can python code (say if I used djangno) be obfuscated to the same 'level' as c#/java?
If I obfuscated python code, would it provide the same level of 'security' as c#/java obfuscating? i.e it makes things a little hard, but really you can still reverse engineer if you really wanted to, its just a bit cryptic.
[ "Obfuscation is a form of security through obscurity. All obfuscated code can, if the attacker is determined enough, be reversed. There are no exceptions.\n", "Python code gets compiled to bytecode (.pyc) files as it is imported. You can distribute those .pyc files instead of the .py source code files, and the Py...
[ 7, 0, 0 ]
[ "Why don't you write something and examine the bytecode? Make some functions that depend on random numbers but are almost complete improbable to execute. This way the compiler can't optimize and you'll see more 'junk'. \ndef myfunc(num):\n if (num > 1):\n return 1\n else:\n return 0\n\n>>> dis.d...
[ -2 ]
[ "c#", "java", "obfuscation", "python" ]
stackoverflow_0002724885_c#_java_obfuscation_python.txt
Q: Search engine recommendation for 100 sites of about 4000 pages I am looking for a search engine that can regularly (daily-ish) scan about 100 pages for changes and index an associated site if changes since the last scan are found. It should be able to handle about 100 sites, each averaging 4000 pages of about 5k a...
Search engine recommendation for 100 sites of about 4000 pages
I am looking for a search engine that can regularly (daily-ish) scan about 100 pages for changes and index an associated site if changes since the last scan are found. It should be able to handle about 100 sites, each averaging 4000 pages of about 5k average size, each on a different server (but only the one centralize...
[ "I recommend PyLucene. PyLucene is a Python extension for accessing Java Lucene and works very well and fast.\n", "If you're looking for a pure python search engine you could look at whoosh. The problem with whoosh is that it's slow and not as full featured. It would be fine if your site doesn't get much traffic,...
[ 1, 1, 0 ]
[]
[]
[ "python", "search_engine" ]
stackoverflow_0002715733_python_search_engine.txt
Q: What's the non brute force way to filter a Python dictionary? I can filter the following dictionary like: data = { 1: {'name': 'stackoverflow', 'traffic': 'high'}, 2: {'name': 'serverfault', 'traffic': 'low'}, 3: {'name': 'superuser', 'traffic': 'low'}, 4: {'name': 'mathoverflow', 'traffic': 'low'}...
What's the non brute force way to filter a Python dictionary?
I can filter the following dictionary like: data = { 1: {'name': 'stackoverflow', 'traffic': 'high'}, 2: {'name': 'serverfault', 'traffic': 'low'}, 3: {'name': 'superuser', 'traffic': 'low'}, 4: {'name': 'mathoverflow', 'traffic': 'low'}, } traffic = 'low' for k, v in data.items(): if v['traffic']...
[ "At some level the filter will have to do exactly what you describe. If you're going to filter on the values, you'll have to process each one, one-by-one.\n", "If you're doing this a lot, you could have two dictionaries, one for each direction. The new dictionary will map values to lists of values. This is a g...
[ 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002725248_python.txt
Q: Python: How to extract xml embedded in a html file? I have a html file with xml snipped embedded, the source code is pasted in the pastbin: <html> <head> <title> test֤</title> </head> <body> <form name="acsForm" action="" method="post" > <textarea rows=10 cols=80 name="xmlText"><?xml version="1...
Python: How to extract xml embedded in a html file?
I have a html file with xml snipped embedded, the source code is pasted in the pastbin: <html> <head> <title> test֤</title> </head> <body> <form name="acsForm" action="" method="post" > <textarea rows=10 cols=80 name="xmlText"><?xml version="1.0" encoding="UTF-8"?> <samlp:Response xmlns:saml...
[ "Try using the BeautifulStoneSoup part of the BeautifulSoup library, which is designed for XML.\n", "Perhaps lxml would work, although I've never used it myself so I don't know how easy/complicated it would be to do what you want.\n", "(Ugh! Why do so many authors seem to think <textarea> content doesn't need H...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "screen_scraping", "xml" ]
stackoverflow_0002717363_python_screen_scraping_xml.txt
Q: What's the best way to join an array into a readable list? I've got an array listing days of the week: days = ['Monday', 'Tuesday', 'Wednesday'] What's the easiest / best way to output it in a human readable format: Monday, Tuesday and Wednesday The best I have is rather ugly: ', '.join(days[:-2]+['']) + ' and '...
What's the best way to join an array into a readable list?
I've got an array listing days of the week: days = ['Monday', 'Tuesday', 'Wednesday'] What's the easiest / best way to output it in a human readable format: Monday, Tuesday and Wednesday The best I have is rather ugly: ', '.join(days[:-2]+['']) + ' and '.join(days[-2:])
[ "Here is what I would do:\n'%s and %s' % (', '.join(days[:-1]), days[-1])\n\nI am not sure it's pretty, but I am not sure it has to be either. :)\n", "Why is everyone trying to force-fit this into a single expression?\ndef comma_separated(lst):\n \"\"\"\n >>> comma_separated(['a'])\n 'a'\n >>> comma_s...
[ 6, 2, 0 ]
[ "you really don't need that second join() in your 'best' sample. you can rewrite it this way:\n', '.join(days[:-1])+' and '+days[-1]\n\npersonally, i always prefer calling the class method, because i find the syntax closer to the intent:\nstr.join(', ',days[:-1])+' and '+days[-1]\n\n" ]
[ -1 ]
[ "join", "python", "string" ]
stackoverflow_0002723998_join_python_string.txt
Q: Sending email from an web2py on GAE I am trying to send a mail from my web2py app hosted on GoogleAppEngine. But it is not working. I used the mail function that was given with the web2py. Does anybody how to do this? I read in the GAE Documentation that python mail library would not work with GAE and GAE mail lib...
Sending email from an web2py on GAE
I am trying to send a mail from my web2py app hosted on GoogleAppEngine. But it is not working. I used the mail function that was given with the web2py. Does anybody how to do this? I read in the GAE Documentation that python mail library would not work with GAE and GAE mail library has to be used. Does it also applies...
[ "The web2py gluon.tools.Mail class (that is used by the Auth module too) works on GAE and non-GAE out of the box. You just need to pass the correct settings:\nmail=Mail()\nmail.settings.server=\"smtp.example.com:25\" or \"gae\"\nmail.settings.sender=\"you@example.com\"\nmail.settings.tls=True or False\nmail.setting...
[ 5, 3 ]
[ "You should use the native App Engine mailer:\nhttp://code.google.com/appengine/docs/python/mail/sendingmail.html\n" ]
[ -1 ]
[ "google_app_engine", "python", "web2py" ]
stackoverflow_0002656068_google_app_engine_python_web2py.txt
Q: Reading colors from a config file with ConfigParser to use with Pygame In the config file I have the variable defined as BackgroundColor = 0,0,0 Which should work for the screen.fill settings for Pygame or any color argument for that matter. Where I can just do screen.fill(0,0,0) The problem I think is with this ...
Reading colors from a config file with ConfigParser to use with Pygame
In the config file I have the variable defined as BackgroundColor = 0,0,0 Which should work for the screen.fill settings for Pygame or any color argument for that matter. Where I can just do screen.fill(0,0,0) The problem I think is with this is that for integers read through a configfile I have to put int() to conver...
[ "You've got a string representing the color, e.g. '0,0,0'. Use split(',') to split it into separate fields, then convert each one.\ne.g.\ncolor = '255, 255, 255'\nred, green, blue = color.split(',')\nred = int(red)\ngreen = int(green)\nblue = int(blue)\n\nOr if you want to do it in one step and the comprehensions ...
[ 2 ]
[]
[]
[ "configparser", "pygame", "python" ]
stackoverflow_0002725806_configparser_pygame_python.txt
Q: Am I correctly extracting JPEG binary data from this mysqldump? I have a very old .sql backup of a vbulletin site that I ran around 8 years ago. I am trying to see the file attachments that are stored in the DB. The script below extracts them all and is verified to be JPEG by hex dumping and checking the SOI (star...
Am I correctly extracting JPEG binary data from this mysqldump?
I have a very old .sql backup of a vbulletin site that I ran around 8 years ago. I am trying to see the file attachments that are stored in the DB. The script below extracts them all and is verified to be JPEG by hex dumping and checking the SOI (start of image) and EOI (end of image) bytes (FFD8 and FFD9, respectively...
[ "Update your question with a sample SQL statement, including a few lines/bytes of the JPEG string value. Perhaps the data is base64 encoded, or even straight hex values. We'll help you further.\nAlso, it's easier to see the type of a file's contents by issuing a:\nfile yourfile.jpg\n\n" ]
[ 1 ]
[]
[]
[ "jpeg", "mysql", "python" ]
stackoverflow_0002723973_jpeg_mysql_python.txt
Q: mouse rollover event in Python (VPython) Is there something similar to scene.mouse.getclick in the visual module (VPython)? I need it for a rollover. Thanks in advance. EDIT: I need a function for doing something when the mouse moves inside a special area without clicking. A: As mentioned by mathmike, it would s...
mouse rollover event in Python (VPython)
Is there something similar to scene.mouse.getclick in the visual module (VPython)? I need it for a rollover. Thanks in advance. EDIT: I need a function for doing something when the mouse moves inside a special area without clicking.
[ "As mentioned by mathmike, it would seem that you could use scene.mouse.pick to get the object that is currently under the mouse, and as for the 'scene-position', I think scene.mouse.pickpos is what you're looking for - if not, you should be able to calculate it from the global mouse position (through getEvent()). ...
[ 1, 0, 0 ]
[]
[]
[ "mouseevent", "python", "rollover", "vpython" ]
stackoverflow_0002655747_mouseevent_python_rollover_vpython.txt
Q: Can I get the amount of time for which a key is pressed on a keyboard I am working on a project in which I have to develop bio-passwords based on user's keystroke style. Suppose a user types a password for 20 times, his keystrokes are recorded, like holdtime : time for which a particular key is pressed. digraph...
Can I get the amount of time for which a key is pressed on a keyboard
I am working on a project in which I have to develop bio-passwords based on user's keystroke style. Suppose a user types a password for 20 times, his keystrokes are recorded, like holdtime : time for which a particular key is pressed. digraph time : time it takes to press a different key. suppose a user types a pass...
[ "Record the KeyDown and KeyUp events, and do a diff on the timestamps of each.\nhttp://code.activestate.com/recipes/203830/\nEdit:\nYou may want to check out wxPython, it should help you out:\nhttp://www.wxpython.org/onlinedocs.php\nin particular:\nhttp://docs.wxwidgets.org/stable/wx_wxkeyevent.html#wxkeyevent\n", ...
[ 6, 3, 2, 0, 0 ]
[]
[]
[ "c", "c++", "linux", "python", "unix" ]
stackoverflow_0002726176_c_c++_linux_python_unix.txt
Q: how to use @ in python.. and the @property and the @classmethod this is my code: def a(): print 'sss' @a() def b(): print 'aaa' b() and the Traceback is: sss Traceback (most recent call last): File "D:\zjm_code\a.py", line 8, in <module> @a() TypeError: 'NoneType' object is not callable so how t...
how to use @ in python.. and the @property and the @classmethod
this is my code: def a(): print 'sss' @a() def b(): print 'aaa' b() and the Traceback is: sss Traceback (most recent call last): File "D:\zjm_code\a.py", line 8, in <module> @a() TypeError: 'NoneType' object is not callable so how to use the '@' thanks updated class a: @property def b(x): ...
[ "A decorator needs to be a callable object (either a function or an object implementing __call__), where the parameter is the function that has been decorated, and the result is a function that will replace the function that has been decorated, so, to use your example of printing 'sss' instead of printing 'aaa':\n\...
[ 8, 4 ]
[]
[]
[ "python" ]
stackoverflow_0002726345_python.txt
Q: Add a value to an element in a list of sets I'm using python, and I have a list of sets, constructed like this: list = [set([])]*n ...where n is the number of sets I want in the list. I want to add a value to a specific set in the list. Say, the second set. I tried list[1].add(value) But this instead adds the va...
Add a value to an element in a list of sets
I'm using python, and I have a list of sets, constructed like this: list = [set([])]*n ...where n is the number of sets I want in the list. I want to add a value to a specific set in the list. Say, the second set. I tried list[1].add(value) But this instead adds the value to each set in the list. This behaviour is pr...
[ "You've pretty much summarized the problem yourself -- the X*n syntax makes one instance of X and includes it n times. It's not a problem for things like 'a'*10 because it doesn't matter if every character in that string happens to point to the same 'a', but it does for mutable constructions like lists and sets. Yo...
[ 5, 1 ]
[]
[]
[ "mutable", "python" ]
stackoverflow_0002726418_mutable_python.txt
Q: Look of the app - Py2exe / wxPython So my problem is the look and feel from my application, as it looks like an old look app. It is an wxPython application, and on python it runs fine and looks fine, but when I convert it to .exe using py2exe, the look is just bad. Now I know that if you are using XP you need some...
Look of the app - Py2exe / wxPython
So my problem is the look and feel from my application, as it looks like an old look app. It is an wxPython application, and on python it runs fine and looks fine, but when I convert it to .exe using py2exe, the look is just bad. Now I know that if you are using XP you need some manifest to correct it but I am in other...
[ "Try use Gui2exe\nI use gui2exe on win7 running on virtualbox.\nThis make gui look ok on all windows version.\nupx.exe to compress exe,dll,pyd.\nAnd inno-setup,for a setup fil for windows.\n" ]
[ 4 ]
[]
[]
[ "look_and_feel", "py2exe", "python", "wxpython" ]
stackoverflow_0002725516_look_and_feel_py2exe_python_wxpython.txt
Q: Fastest way to make a dict a single comma-separated string I have a list of uids: ['1234','4321','1111'] and I would like to turn this into a single string of: "uid = '1234' OR uid = '4321' OR uid = '1111'" What's the most efficient way to do this? Thanks! A: ' OR '.join("uid = '%s'" % u for u in uids) Thi...
Fastest way to make a dict a single comma-separated string
I have a list of uids: ['1234','4321','1111'] and I would like to turn this into a single string of: "uid = '1234' OR uid = '4321' OR uid = '1111'" What's the most efficient way to do this? Thanks!
[ "' OR '.join(\"uid = '%s'\" % u for u in uids)\n\nThis invokes the join function on the string ' OR ', which takes the list passed in and puts the string in between each element, then concatenates them all together. (Used to put the ORs in between each key=val pair.)\nThe part inside the () is a comprehension that...
[ 9, 2 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002725912_python_string.txt
Q: List of objects or parallel arrays of properties? The question is, basically: what would be more preferable, both performance-wise and design-wise - to have a list of objects of a Python class or to have several lists of numerical properties? I am writing some sort of a scientific simulation which involves a rathe...
List of objects or parallel arrays of properties?
The question is, basically: what would be more preferable, both performance-wise and design-wise - to have a list of objects of a Python class or to have several lists of numerical properties? I am writing some sort of a scientific simulation which involves a rather large system of interacting particles. For simplicity...
[ "Having an object for each ball in this example is certainly better design. Parallel arrays are really a workaround for languages that do not support proper objects. I wouldn't use them in a language with OO capabilities unless it's a tiny case that fits within a function (and maybe not even then) or if I've run ou...
[ 2, 2, 1, 0 ]
[]
[]
[ "data_structures", "numpy", "performance", "python" ]
stackoverflow_0002723790_data_structures_numpy_performance_python.txt
Q: How to make lists automatically instantiate on use in Python as they do in Perl? In Perl, I can do this: push(@{$h->[x]}, y); Can I simplify the following python codes according to above Perl example? if x not in h: h[x] = [] h[x].append(y) I want to simplify this, because it goes many places in my code, (and ...
How to make lists automatically instantiate on use in Python as they do in Perl?
In Perl, I can do this: push(@{$h->[x]}, y); Can I simplify the following python codes according to above Perl example? if x not in h: h[x] = [] h[x].append(y) I want to simplify this, because it goes many places in my code, (and I cannot initialize all possible x with []). I do not want to make it a function, beca...
[ "A very elegant way (since Python 2.5) is to use defaultdict from the \"collections\" module:\n>>> from collections import defaultdict\n>>> h = defaultdict(list)\n>>> h['a'].append('b')\n>>> h\ndefaultdict(<type 'list'>, {'a': ['b']})\n\ndefaultdict is like a dict, but provides a default value using whichever const...
[ 9, 4, 3 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0002726632_perl_python.txt
Q: Intersection of two querysets in django I can't do an AND on two querysets. As in, q1 & q2. I get the empty set and I do not know why. I have tested this with the simplest cases. I am using django 1.1.1 I have basically objects like this: item1 name="Joe" color = "blue" item2 name="Jim" color = "b...
Intersection of two querysets in django
I can't do an AND on two querysets. As in, q1 & q2. I get the empty set and I do not know why. I have tested this with the simplest cases. I am using django 1.1.1 I have basically objects like this: item1 name="Joe" color = "blue" item2 name="Jim" color = "blue" color = "white" item3 name="John" ...
[ "qs = Item.objects.filter(color__in=['blue','white'])\n\n", "Item.objects.filter(color=\"blue\").filter(color=\"white\")\n\n" ]
[ 3, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002719128_django_python.txt
Q: Call Python From PHP And Get Return Code I am calling a python script from PHP. The python program has to return some value according to the arguments passed to it. Here is a sample python program, which will give you a basic idea of what i am doing currently: #!/usr/bin/python import sys #get the arguments passe...
Call Python From PHP And Get Return Code
I am calling a python script from PHP. The python program has to return some value according to the arguments passed to it. Here is a sample python program, which will give you a basic idea of what i am doing currently: #!/usr/bin/python import sys #get the arguments passed argList = sys.argv #Not enough arguments. E...
[ "In PHP, you can execute a command and obtain the return code using exec.\nThe manual for exec says the third parameter is a variable in which the return code will be stored, for example\nexec('python blibble.py', $output, $ret_code);\n\n$ret_code will be the shell return code, and $output is an array of the lines ...
[ 15, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0002726551_php_python.txt
Q: Replace each char in a multi-line string except space and \r \n, how? A multi-line string, e.g. abc 123 456 def wanted result (ordinal + 2): cde 345 678 fgh if I use: text = "abc 123\n456 def" add2=''.join(chr(ord(c)+2) for c in text) print text print add2 the space and \r \n will also be replaced, how can I ad...
Replace each char in a multi-line string except space and \r \n, how?
A multi-line string, e.g. abc 123 456 def wanted result (ordinal + 2): cde 345 678 fgh if I use: text = "abc 123\n456 def" add2=''.join(chr(ord(c)+2) for c in text) print text print add2 the space and \r \n will also be replaced, how can I add the exception of not including space, \r or \n in the 2nd line of code. p...
[ "Your other question suggests that you might be translating a very long string (a PDF file). In that case, using the string translate method will be quicker than doing a character-by-character for-loop over the string:\ntest.py:\nimport string\n\ninfile='filename.pdf'\noutfile='newfile.pdf'\n\nwith open(infile,'r')...
[ 3, 2, 2, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002726688_python_string.txt
Q: Recommendations for a simple 2D graphics python library that can output to screen and pdf? I'm looking for an easy-to-use graphics lib for python that can output to screen as well as pdf. So, I would use code to draw some stuff (simple prims like ovals, rectangles, lines and points) to screen and then when things ...
Recommendations for a simple 2D graphics python library that can output to screen and pdf?
I'm looking for an easy-to-use graphics lib for python that can output to screen as well as pdf. So, I would use code to draw some stuff (simple prims like ovals, rectangles, lines and points) to screen and then when things look good, have it output to pdf.
[ "If you use Tkinter, you can draw on a Canvas widget, then use its .postscript method to save the contents as a PostScript file, which you can convert to PDF using ps2pdf.\n\npostscript(self, cnf={}, **kw)\n Print the contents of the canvas to a postscript\n file. Valid options: colormap, colormode, file, fontmap...
[ 3, 2, 1, 0, 0, 0 ]
[]
[]
[ "graphics", "pdf", "python" ]
stackoverflow_0002725735_graphics_pdf_python.txt
Q: How to build an interactive search engine web interface using python I have build a static web interface for searching data from some tables in my PostgreSQL database. The query website consists of a simple textfield for entering the search term, the result website presents the results as a simple html table. The ...
How to build an interactive search engine web interface using python
I have build a static web interface for searching data from some tables in my PostgreSQL database. The query website consists of a simple textfield for entering the search term, the result website presents the results as a simple html table. The server side code for searching the PostgreSQL database and returning the r...
[ "I have not had to build a search outside of Django, but Haystack http://haystacksearch.org/ makes things very easy.\nIf you don't want to get into Django you could look at Whoosh. http://bitbucket.org/mchaput/whoosh/wiki/Home\n", "what you call \"Ajax features\" are technically known as auto-suggest. Unless you ...
[ 1, 0 ]
[]
[]
[ "ajax", "python", "search_engine", "web_frameworks" ]
stackoverflow_0002613316_ajax_python_search_engine_web_frameworks.txt
Q: Help with filetype association! I have the actual association part down, but when I open the file that is associated with my Python program, how do I get the filepath of the file opened? I think it is something like sys.argv? But that just returns the path to the python program, not the associated file. A: The _...
Help with filetype association!
I have the actual association part down, but when I open the file that is associated with my Python program, how do I get the filepath of the file opened? I think it is something like sys.argv? But that just returns the path to the python program, not the associated file.
[ "The __file__ attribute of your module looks what you're looking for. E.g., save in foo.py:\n$ cat foo.py\nprint 'Hello', __file__\n$ python foo.py \nHello foo.py\n\nos.path.abspath will help you if you want the absolute rather than relative path, etc, etc.\n", "The contents of sys.argv are platform-dependent, a...
[ 1, 1 ]
[]
[]
[ "filepath", "python" ]
stackoverflow_0002726835_filepath_python.txt
Q: Using M2Crypto to save and load X509 certs in pem files I would expect that if I have a X509 cert as an object in memory, saved it as a pem file, then loaded it back in, I would end up with the same cert I started with. This seems not to be the case however. Let's call the original cert A, and the cert loaded from...
Using M2Crypto to save and load X509 certs in pem files
I would expect that if I have a X509 cert as an object in memory, saved it as a pem file, then loaded it back in, I would end up with the same cert I started with. This seems not to be the case however. Let's call the original cert A, and the cert loaded from the pem file B. A.as_text() is identical to B.as_text(), but...
[ "If you try this with a cert that you created with OpenSSL command line tools (for example, the server.pem in tests directory sans the key and text) by loading and saving it with M2Crypto, you should get identical files.\nI thought SimpleX509Create.py in the contrib directory worked differently, but I tested it and...
[ 1 ]
[]
[]
[ "cryptography", "m2crypto", "pem", "python", "x509certificate" ]
stackoverflow_0002726003_cryptography_m2crypto_pem_python_x509certificate.txt