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: Error parsing a DTD using lxml I'm trying to write a validation script that will validate XML against the NITF DTD, http://www.iptc.org/std/NITF/3.4/specification/dtd/nitf-3-4.dtd. Based on this post I came up with the following simple script to validate a NITF XML document. Bellow is the error message I get when ...
Error parsing a DTD using lxml
I'm trying to write a validation script that will validate XML against the NITF DTD, http://www.iptc.org/std/NITF/3.4/specification/dtd/nitf-3-4.dtd. Based on this post I came up with the following simple script to validate a NITF XML document. Bellow is the error message I get when the script is run, which isn't very ...
[ "I took a look at the nitf-3-4.dtd and found that it references an external module xhtml-ruby-1.mod which can be downloaded at this link. This needs to be present in the current directory so the DTD parser can load it. \nFull working example (assuming you have a valid NITF document handy):\n% wget http://www.iptc.o...
[ 5 ]
[]
[]
[ "dtd", "lxml", "python", "xml" ]
stackoverflow_0005494380_dtd_lxml_python_xml.txt
Q: How to write a simple Bittorrent application? How to write a simple bittorrent application. Something like a "hello world" using a bittorrent library, I mean a simplest of the application to understand the working of bittorrent. I would prefer a python or a C/C++ implementation, but it can be any language. Platfor...
How to write a simple Bittorrent application?
How to write a simple bittorrent application. Something like a "hello world" using a bittorrent library, I mean a simplest of the application to understand the working of bittorrent. I would prefer a python or a C/C++ implementation, but it can be any language. Platform is not an issues either, but i would prefer Linux...
[ "You should try libtorrent (rasterbar). http://libtorrent.org\nIf you want to write your client in python, on linux, install it with:\nsudo apt-get install python-libtorrent\nA very simple example of python code to use it to download a torrent:\nimport libtorrent as lt\nimport time\nimport sys\n\nses = lt.session({...
[ 90 ]
[]
[]
[ "bittorrent", "c", "network_programming", "p2p", "python" ]
stackoverflow_0005400828_bittorrent_c_network_programming_p2p_python.txt
Q: How to display objects grouped by foreign key I'm a django n00b and am lost on how to do this. sample models: class Food_Type(models.Model): name = models.CharField(max_length=200) class Food(models.Model): name = models.CharField(max_length=200) food_type = models.ForeignKey(Food_Type) And some ...
How to display objects grouped by foreign key
I'm a django n00b and am lost on how to do this. sample models: class Food_Type(models.Model): name = models.CharField(max_length=200) class Food(models.Model): name = models.CharField(max_length=200) food_type = models.ForeignKey(Food_Type) And some data: v = Food_Type(name='Veggie') f = Food_T...
[ "I think you are looking for regroup\nfood = Food.objects.all()\n\n{% regroup food by food_type as food_list %}\n\n<ul>\n{% for food_type in food_list %}\n <li>{{ food_type.grouper }}\n <ul>\n {% for item in food_type.list %}\n <li>{{ item }}</li>\n {% endfor %}\n </ul>\n </li>\n{% ...
[ 2, 0 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0005494173_django_django_templates_django_views_python.txt
Q: The App Engine datastore can either return entire entities or only entity keys from a query? I am reading Google App Engine doc and found this line difficult to understand The App Engine datastore can either return entire entities or only entity keys from a query. what does it mean? There is filter(property_oper...
The App Engine datastore can either return entire entities or only entity keys from a query?
I am reading Google App Engine doc and found this line difficult to understand The App Engine datastore can either return entire entities or only entity keys from a query. what does it mean? There is filter(property_operator, value) and fetch(limit, offset=0) And I believe django-nonrel support values() on App Engine...
[ "You can do a standard query, like this:\nresults = MyModel.all().filter('foo =', 'bar').fetch(20)\n\nThat will return a list of entities (db.Model instances). Or, you can do a keys-only query, like this:\nresults = MyModel.all(keys_only=True).filter('foo =', 'bar').fetch(20)\n\nThat will return only the keys of th...
[ 1, 1 ]
[]
[]
[ "django", "django_nonrel", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0005494962_django_django_nonrel_google_app_engine_google_cloud_datastore_python.txt
Q: How do I embed a .swf file into my Google App Engine app? First off i'm new here so if I made any mistakes please point them out. I am working on an app engine project in python were i want to be able to upload and play games in a .swf format. I am having trouble getting app engine to send(deliver, render, display...
How do I embed a .swf file into my Google App Engine app?
First off i'm new here so if I made any mistakes please point them out. I am working on an app engine project in python were i want to be able to upload and play games in a .swf format. I am having trouble getting app engine to send(deliver, render, display,...not sure what the correct term is) files with a .swf ending...
[ "This doesn't look like a standard way to embed a flash app - and it's not an App Engine issue. You've got an object tag with nothing but dimensions, and an embed tag inside it with nothing but a URL. Have you tried using some standard embed markup to do this? The Flash environment should provide a simple way to ex...
[ 2 ]
[]
[]
[ "django", "flash", "google_app_engine", "python", "static" ]
stackoverflow_0005494929_django_flash_google_app_engine_python_static.txt
Q: Is the python mechanize cache feature the same as normal browser cache feature? In its document, it says "This caching behaviour can be avoided by using Mechanize.OpenerDirector". Does this cache influence next request of the same page? A: It looks to me like the "caching" the documentation refers to is talking ...
Is the python mechanize cache feature the same as normal browser cache feature?
In its document, it says "This caching behaviour can be avoided by using Mechanize.OpenerDirector". Does this cache influence next request of the same page?
[ "It looks to me like the \"caching\" the documentation refers to is talking about seekable responses, not a browser-like cache feature. For example:\ntotal_nr_bytes = len(response.get_data())\nassert len(response.read()) == total_nr_bytes\nassert len(response.read()) == 0 # we've already read the data\nresponse.s...
[ 1 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0002295812_mechanize_python.txt
Q: urlfetch.fetch got missed content within script tag of html in app engine in my app, when I use urlfetch.fetch function to fetch a specified url, I found the content I got is empty for some special html codes. for example, the url: http://www.club.cn.sodexo.com/node/5071 in real html source, the codes including: ...
urlfetch.fetch got missed content within script tag of html in app engine
in my app, when I use urlfetch.fetch function to fetch a specified url, I found the content I got is empty for some special html codes. for example, the url: http://www.club.cn.sodexo.com/node/5071 in real html source, the codes including: <div class="content"> <div style="width: 219px; height: 262px;" id="gmap-auto3m...
[ "Perhaps the server inserts different javascript based on the user-agent (ie different code for Firefox verses Internet Explorer), and for urlfetch's user-agent the server gets confused and doesn't insert any javascript at all.\n" ]
[ 0 ]
[]
[]
[ "fetch", "google_app_engine", "python", "urlfetch" ]
stackoverflow_0002310134_fetch_google_app_engine_python_urlfetch.txt
Q: python Postgresql: Ignoring the last column from csv file I have problem with importing a CSV file. I am using postgresql's COPY FROM command to copy a CSV file into a 2-column table. I have a CSV file in the following format; "1";"A" "2";"B" "3";"C";"CAD450" "4";"D";"ABX123" I want to import all these lines of ...
python Postgresql: Ignoring the last column from csv file
I have problem with importing a CSV file. I am using postgresql's COPY FROM command to copy a CSV file into a 2-column table. I have a CSV file in the following format; "1";"A" "2";"B" "3";"C";"CAD450" "4";"D";"ABX123" I want to import all these lines of the CSV file into the table but I want to skip any extra added ...
[ "Preprocess the file with awk to strip the extra columns:\nawk -F';' '{print $1 \";\" $2 }' > new_file.csv\n\n", "Piping it through cut or awk (as suggested above) is easier than using python/psycopg.\ncat csv_file.csv | cut -d';' -f1,2 | psql -u USER DATABASE -c \"COPY table FROM STDIN WITH DELIMITER ';';\"\n",...
[ 2, 2, 1, 1 ]
[]
[]
[ "postgresql", "python" ]
stackoverflow_0005492488_postgresql_python.txt
Q: Why doesn't memory get released to system after large queries (or series of queries) in django? First off, DEBUG = False in settings.py, so no, connections['default'].queries is not growing and growing until it uses up all of memory. Lets start off with the fact that I've loaded the User table from django.contrib....
Why doesn't memory get released to system after large queries (or series of queries) in django?
First off, DEBUG = False in settings.py, so no, connections['default'].queries is not growing and growing until it uses up all of memory. Lets start off with the fact that I've loaded the User table from django.contrib.auth.models.User with 10000 users (each named 'test#' where # is a number between 1 and 10000). Here ...
[ "I decided to move my comments into an answer to make things clearer.\nSince Python 2.5, the CPython memory allocation tracks internal memory usage by the small object allocator, and attempts to return completely free arenas to the underlying OS. This works most of the time, but the fact that objects can't be moved...
[ 26, 6 ]
[]
[]
[ "django", "memory_leaks", "python" ]
stackoverflow_0005494178_django_memory_leaks_python.txt
Q: How to define a DateProperty object in App Engine I am facing difficulties in creating dateproperty object and I can't seems to create the object. Here is my code: from google.appengine.ext import db class Baby(db.Model): name = db.StringProperty() dob = db.DateProperty() for i in Baby.all(): delete(...
How to define a DateProperty object in App Engine
I am facing difficulties in creating dateproperty object and I can't seems to create the object. Here is my code: from google.appengine.ext import db class Baby(db.Model): name = db.StringProperty() dob = db.DateProperty() for i in Baby.all(): delete(i) Baby(name='wilson', dob=Date(year=1986,month=3,day=...
[ "The value of a DateProperty will need to be a datetime.date object, as mentioned here: http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#DateProperty\nSo, you will need to add:\nimport datetime\n\nand also change dob=Date(year=1986, month=3, day=5) to:\ndob = datetime.date(year=19...
[ 5, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005494734_google_app_engine_python.txt
Q: convert python programme to windows executable i m trying to create windows executable from python program which has GUI . i m using following script from distutils.core import setup import py2exe setup(console=['gui.py']) it gives following error Warning (from warnings module): File "C:\Python27\lib\distutil...
convert python programme to windows executable
i m trying to create windows executable from python program which has GUI . i m using following script from distutils.core import setup import py2exe setup(console=['gui.py']) it gives following error Warning (from warnings module): File "C:\Python27\lib\distutils\dist.py", line 267 warnings.warn(msg) UserWarn...
[ "The problem is that you are compiling this script from the Python IDLE. This is not how it is done with py2exe. If you have used Disutils before, you might have seen this:\npython setup.py install.\nAnd same is the case of py2exe, you run it from the command line and not the IDLE. So open up cmd and then issue the...
[ 7 ]
[]
[]
[ "py2exe", "python", "windows_7" ]
stackoverflow_0005495333_py2exe_python_windows_7.txt
Q: Pythonic way for calculating I have two python lists of floats (lists are of same size i.e same number of elements) list1 = [20, 30, 40, 50] list2 = [1.1, 1.3, 1.7, 1.8] I want to calculate sum(list1[i]*list2[i])/sum(list1[i]) (where i goes from 0 to len(list1). This can be done using for loop, but is there a bet...
Pythonic way for calculating
I have two python lists of floats (lists are of same size i.e same number of elements) list1 = [20, 30, 40, 50] list2 = [1.1, 1.3, 1.7, 1.8] I want to calculate sum(list1[i]*list2[i])/sum(list1[i]) (where i goes from 0 to len(list1). This can be done using for loop, but is there a better way (more pythonic way like us...
[ "Not sure about more Pythonic (simple is better, right?) but for something more concise, how about:\nsum(a * b for a, b in zip(list1, list2)) / sum(list1)\n\nThis is largely adapted from another answer by SilentGhost.\nThe first part of what you are doing (up to the division) is called the dot product, by the way. ...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005495385_python.txt
Q: 'str' object does not support item assignment - Error with django I created a Django app. The application has a user regstration page. The registration page is implemented and i was trying to implement a email confirmation after registering. ie sending an email when the user is registered. while doing this i got i...
'str' object does not support item assignment - Error with django
I created a Django app. The application has a user regstration page. The registration page is implemented and i was trying to implement a email confirmation after registering. ie sending an email when the user is registered. while doing this i got into this error," 'str' object does not support item assignment ". Can s...
[ "The problem is here:\nmsg = \"Registration Successfull\"\nmsg['Subject'] = 'The contents of %s'\n\nstrings are immutable and are not dict-like. You should also be using Django Forms, rather than doing it all yourself.\nDjango also has built-in support for sending emails. Read the Sending E-mail documentation to se...
[ 8 ]
[]
[]
[ "django", "django_models", "django_templates", "email_verification", "python" ]
stackoverflow_0005495999_django_django_models_django_templates_email_verification_python.txt
Q: Use arbitrary wx objects as a column in a wx.ListCtrl I have a wx.ListCtrl that has the wx.LC_REPORT bit set. It has 3 columns. I want the first column to be populated with a check box for each other entry. I tried using the ListCtrl.InsertItem method, but it only takes one argument (info) and I can't find any doc...
Use arbitrary wx objects as a column in a wx.ListCtrl
I have a wx.ListCtrl that has the wx.LC_REPORT bit set. It has 3 columns. I want the first column to be populated with a check box for each other entry. I tried using the ListCtrl.InsertItem method, but it only takes one argument (info) and I can't find any docs as to what that argument needs to be. I've tried just pas...
[ "Have a look at wx.lib.mixins.listctrl. \nimport wx\nimport wx.lib.mixins.listctrl as listmix\n\nclass TestListCtrl(wx.ListCtrl, listmix.CheckListCtrlMixin, listmix.ListCtrlAutoWidthMixin):\n def __init__(self, *args, **kwargs):\n wx.ListCtrl.__init__(self, *args, **kwargs)\n listmix.CheckListCtrlM...
[ 10 ]
[]
[]
[ "listctrl", "python", "wxpython" ]
stackoverflow_0005495053_listctrl_python_wxpython.txt
Q: PYTHON Sockets and structure Is there any way of converting the python socket object to a void pointer. I am using ctypes and I have tried using cast and the conversion functions of python. I am also using a DLL and there is a function which takes structure as its argument. But when i pass the structure to the fu...
PYTHON Sockets and structure
Is there any way of converting the python socket object to a void pointer. I am using ctypes and I have tried using cast and the conversion functions of python. I am also using a DLL and there is a function which takes structure as its argument. But when i pass the structure to the function I am getting invalid parame...
[ "There is no good reason to convert a socket to a pointer. You can use socket.fileno() to get the socket's file descriptor which should be usable in C code.\nIf your library expects a pointer, you might need to wrap it with a ctypes struct - but without knowing details we can't tell.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005496253_python.txt
Q: App Engine. Querying Every Other Minute In google app engine I am storing sensor data coming in once a minute. So for 24 hours that's a total of 1,440 individual readings. This means I'm bumping up against the maximum limit of 1,000 results for all queries. Unless someone can show me a way to access all 1,440 read...
App Engine. Querying Every Other Minute
In google app engine I am storing sensor data coming in once a minute. So for 24 hours that's a total of 1,440 individual readings. This means I'm bumping up against the maximum limit of 1,000 results for all queries. Unless someone can show me a way to access all 1,440 readings in sequential order, I'm okay with this ...
[ "You can also do something like this using gql .\nmodels.Log.gql(\"WHERE dateTime >= :1 AND dateTime < :2\", day_start,day_end)\n\n", "You can fetch all results using cursors:\n q = parse.YourModel.gql(YourQuery)\n tlist = []\n tl = q.fetch(1000)\n cursor = q.cursor()\n while len(tl) > 0:\n ...
[ 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005496133_google_app_engine_python.txt
Q: perl, python, parallel processing,fork From Perl or python,Which language takes less overhead,less memory consumption and time while creating a process or parallel processing when sending or receiving a mail or messages? My client want to use any one technology perl or python? Thanks in Advance A: Which are you...
perl, python, parallel processing,fork
From Perl or python,Which language takes less overhead,less memory consumption and time while creating a process or parallel processing when sending or receiving a mail or messages? My client want to use any one technology perl or python? Thanks in Advance
[ "Which are you more familiar with? Use that! There would be minor differences in both for the conditions which you mention, but both would be slower than application written in compiled language such as C. But what you get is faster development time and ability to design using high level language features and libra...
[ 5, 1 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0005496389_perl_python.txt
Q: merge a list of 2 lists or use a queryset? My models are as follows (the fields in floor and board are inconsequential and omitted) class floor(models.Model): class board(models.Model): class run(models.Model): floor = models.ForeignKey(Floor) boards = models.ManyToManyField(Board) I have a query as fol...
merge a list of 2 lists or use a queryset?
My models are as follows (the fields in floor and board are inconsequential and omitted) class floor(models.Model): class board(models.Model): class run(models.Model): floor = models.ForeignKey(Floor) boards = models.ManyToManyField(Board) I have a query as follows: runs = Run.objects.filter(floor=1) that ...
[ "Simple:\nboard.objects.filter(run__floor=1)\n\n", "The simplest method I could think of:\n>>> all_boards=[]\n>>> for boards in (run.boards.all() for run in runs):\n all_boards+=run\n>>> all_boards\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n>>> \n\nI changed the [...] list comprehension into a generator comprehensi...
[ 3, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005496177_django_python.txt
Q: Splitting a string via regex problems New to python and I'm having trouble getting the function i want out of regex. Basically i have a string that looks like "Hello, World, Nice" and i need to convert it into a list with the delimiter being ,. End result should look like ['Hello', 'World', 'Nice'] re.split(','...
Splitting a string via regex problems
New to python and I'm having trouble getting the function i want out of regex. Basically i have a string that looks like "Hello, World, Nice" and i need to convert it into a list with the delimiter being ,. End result should look like ['Hello', 'World', 'Nice'] re.split(',', string) Basically the result i get is ['...
[ "Assuming, that the whitespace can be arbitrary, there are two solutions, that come to mind:\nre.split(r'\\s*,\\s*', string)\n# ^- zero or more whitespace incl. tabs and newlines\n# the r'' syntax preserves the backslash from being interpreted\n# as escape sequence\n\nand\nmap(str.strip, string.split(','))...
[ 3, 3, 0, 0, 0, 0, 0 ]
[ "try this regex for split\n>>> a = \"Hello, World, Nice\"\n>>> a.split(\"[ ,\\\\,]\")\n\nin regex first is space and second is comma\n" ]
[ -1 ]
[ "python", "regex", "split", "string" ]
stackoverflow_0005496599_python_regex_split_string.txt
Q: What approach(es) have you used for lightweight Python unit-tests on App Engine? I'm about to embark on some large Python-based App Engine projects, and I think I should check with Stack Overflow's "wisdom of crowds" before committing to a unit-testing strategy. I have an existing unit-testing framework (based on...
What approach(es) have you used for lightweight Python unit-tests on App Engine?
I'm about to embark on some large Python-based App Engine projects, and I think I should check with Stack Overflow's "wisdom of crowds" before committing to a unit-testing strategy. I have an existing unit-testing framework (based on unittest with custom runners and extensions) that I want to use, so anything "heavy-w...
[ "You don't need to write your own stubs - the SDK includes them, since they're what it uses to emulate the production APIs. Not all of them are suitable for use in unit-tests, but most are. Check out this code for an example of the setup/teardown code you need to make use of the built in stubs.\n", "NoseGAE is a ...
[ 14, 5, 4, 3, 1, 0 ]
[]
[]
[ "google_app_engine", "python", "unit_testing" ]
stackoverflow_0001753897_google_app_engine_python_unit_testing.txt
Q: Simple graphical text display? Hey everybody, I have a script that reads a value from the Windows registry and I need a pretty way to display it on my second monitor. It's just an integer. I want to be able to choose a size in pixels and color. Thanks for the ideas! A: you dont need to install a GUI library for ...
Simple graphical text display?
Hey everybody, I have a script that reads a value from the Windows registry and I need a pretty way to display it on my second monitor. It's just an integer. I want to be able to choose a size in pixels and color. Thanks for the ideas!
[ "you dont need to install a GUI library for what you need to do, Tkinter is already in python windows, example:\nimport Tkinter as Tk\nlabel = Tk.Label(None, text='The text you want to display', font=('Times', '18'),fg='blue')\nlabel.pack()\nlabel.mainloop()\n\njust refresh the label every certain amount of time\n"...
[ 2, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0005495132_python_windows.txt
Q: Is dictionary in Python can be seen as Map in C++ Is dictionary in Python can be seen as Map in C++ And the insert complexity is constant time? and what about sort complexity of dictionary? What about iteration? Need some good points or link to good resource. Thanks! A: If I recall correctly, the C++ map impleme...
Is dictionary in Python can be seen as Map in C++
Is dictionary in Python can be seen as Map in C++ And the insert complexity is constant time? and what about sort complexity of dictionary? What about iteration? Need some good points or link to good resource. Thanks!
[ "If I recall correctly, the C++ map implementation uses a tree, so insertion and retrieval is O(log(n)) as opposed to O(1).\nPython uses hashtables, so retrieval is O(1).\n", "Python dicts are an implementation of the generic data structure commonly referred to as a hash table or hash map.\nFor Python dicts, comp...
[ 2, 2 ]
[]
[]
[ "c++", "python" ]
stackoverflow_0005496911_c++_python.txt
Q: convert code from Python 2.x to 3.x This is a followup on my previous question, I am using the 2to3 tool as suggested by Senthil Kumaran It seems to work well but it doesn't pick up this part: raise LexError,("%s:%d: Rule '%s' returned an unknown token type '%s'" % ( func.func_code.co_filename, func.func_code....
convert code from Python 2.x to 3.x
This is a followup on my previous question, I am using the 2to3 tool as suggested by Senthil Kumaran It seems to work well but it doesn't pick up this part: raise LexError,("%s:%d: Rule '%s' returned an unknown token type '%s'" % ( func.func_code.co_filename, func.func_code.co_firstlineno, func.__name__, newtok...
[ "The func_code attribute of functions has been renamed to __code__, so try\nfunc.__code__.co_filename, func.__code__.co_firstlineno,\n\nas the second line of your code snippet.\n", "Remove the comma after LexError. That works in both Python 2 and Python 3.\nIn Python 2 there was a rarely used syntax to raise exce...
[ 11, 3, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0005497013_python_python_3.x.txt
Q: Always an Error on the First Message Currently I'm working on setting up a basic WebSockets script. I can get the client to connect to the server, but whenever the server sends the first message to the client the client registers and error, and from what I can tell the readyState is open, and should allow the mess...
Always an Error on the First Message
Currently I'm working on setting up a basic WebSockets script. I can get the client to connect to the server, but whenever the server sends the first message to the client the client registers and error, and from what I can tell the readyState is open, and should allow the message to come through. The message has the c...
[ "Try to remove last \\r\\n after your token:\nreturn \"HTTP/1.1 101 WebSocket Protocol Handshake\\r\\nUpgrade: WebSocket\\r\\nConnection: Upgrade\\r\\nSec-WebSocket-Origin: %s\\r\\nSec-WebSocket-Location: ws://%s%s\\r\\nSec-WebSocket-Protocol: sample\\r\\n\\r\\n%s\"% (origin, host, resource, token)\n\nI'm sure it w...
[ 0 ]
[]
[]
[ "html", "javascript", "python", "websocket" ]
stackoverflow_0005440559_html_javascript_python_websocket.txt
Q: detect and change website encoding in python I have a problem with website encoding. I maked a program to scrape a website but i didn't have successfully with changing encoding of readed content. My code is: import sys,os,glob,re,datetime,optparse import urllib2 from BSXPath import BSXPathEvaluator,XPathResult #i...
detect and change website encoding in python
I have a problem with website encoding. I maked a program to scrape a website but i didn't have successfully with changing encoding of readed content. My code is: import sys,os,glob,re,datetime,optparse import urllib2 from BSXPath import BSXPathEvaluator,XPathResult #import BeautifulSoup #from utility import * sTarg...
[ "Well, there is no guarantee that the encoding presented by the HTTP headers is the same the some specified inside the HTML itself. This can happen either due to misconfiguration on the server side or the charset definition inside the HTML can be just wrong. There is really no automatic way to detect the encoding o...
[ 0 ]
[]
[]
[ "beautifulsoup", "encoding", "python", "scrape" ]
stackoverflow_0005497106_beautifulsoup_encoding_python_scrape.txt
Q: Attempted relative import in non-package (after 2to3) After converting to Python 3.x using 2to3 (see my previous question), I get this error during the build: File "setup.py", line 28, in <module> from . import mof_compiler ValueError: Attempted relative import in non-package The code: from . import mof_com...
Attempted relative import in non-package (after 2to3)
After converting to Python 3.x using 2to3 (see my previous question), I get this error during the build: File "setup.py", line 28, in <module> from . import mof_compiler ValueError: Attempted relative import in non-package The code: from . import mof_compiler mof_compiler._build() But I don’t know why this is w...
[ "Since there is no __init__.py, the working directory is a non-package.\nYou don't need a relative import.\nOr.\nYou need an __init__.py to make a package.\n" ]
[ 13 ]
[]
[]
[ "python", "python_2to3", "python_3.x" ]
stackoverflow_0005497951_python_python_2to3_python_3.x.txt
Q: Python: Returning max value of a dict by its tupled-key I have a dict as follows: counts = {('test1', 'alpha'): 2, ('test2', 'beta'): 1, ('test1', 'delta'): 1, ('test2', 'gamma'): 2} How can I return the 'alpha/beta/gamma/delta' of each tuple which has the max value? i.e. test1, a...
Python: Returning max value of a dict by its tupled-key
I have a dict as follows: counts = {('test1', 'alpha'): 2, ('test2', 'beta'): 1, ('test1', 'delta'): 1, ('test2', 'gamma'): 2} How can I return the 'alpha/beta/gamma/delta' of each tuple which has the max value? i.e. test1, alpha, 2 #because test1 has 'alpha' as highest value test2, ga...
[ "First, convert your dict to map the test names to lists of (count, pattern) tuples:\ncounts2 = collections.defaultdict(list)\nfor (test, pattern), c in counts.iteritems():\n counts2[test] += (c, pattern)\n\nNow you can get the maxima very easily:\nfor test, patterns in counts2.iteritems():\n print test, max(...
[ 2, 1 ]
[]
[]
[ "dictionary", "max", "python", "tuples" ]
stackoverflow_0005498020_dictionary_max_python_tuples.txt
Q: Efficient ModelChoiceField initial data To set initial data for my ModelChoiceFields, currently I do the following: foo = ModelChoiceField(label="Foo label", queryset=Foo.objects.all(), initial=Foo.objects.get(pk=14)) But I feel this may be bad practice, & i'm unsure ...
Efficient ModelChoiceField initial data
To set initial data for my ModelChoiceFields, currently I do the following: foo = ModelChoiceField(label="Foo label", queryset=Foo.objects.all(), initial=Foo.objects.get(pk=14)) But I feel this may be bad practice, & i'm unsure of the most effective way to set initial data...
[ "You are doing two queries, but they are executed at completely different times.\nQuerysets are lazy. The query in Foo.objects.all() is not executed until the form is actually rendered. That means that the list of Foo objects available will always be up-to-date.\nHowever, the Foo.objects.get(pk=14) is executed when...
[ 2, 1 ]
[]
[]
[ "django", "django_forms", "forms", "orm", "python" ]
stackoverflow_0005498080_django_django_forms_forms_orm_python.txt
Q: Iterating over os.walk in linux We have multiple linux server and i would like to get all the details of files and directories in a particular linux server. I know this can be done with os.walk function but it is storing only single file information. Please find the below code import os for d in os.walk('/'): ...
Iterating over os.walk in linux
We have multiple linux server and i would like to get all the details of files and directories in a particular linux server. I know this can be done with os.walk function but it is storing only single file information. Please find the below code import os for d in os.walk('/'): F = open('/home/david/Desktop/datafil...
[ "You could use a context manager\nimport os\nwith open('/home/david/Desktop/datafile.txt', 'w') as F:\n for d in os.walk('/'):\n F.write(str(d) + '\\n')\n\n", "You should append to the file rather than just write to it (which resets the file contents each time you open it). To enable append mode, pass a...
[ 5, 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005498276_python.txt
Q: Getting started with Pylint for Jython (jython2.5.1) We have a ton of Jython scripts for our deployment automation; I'd like Pylint to be part of our build pipeline. I downloaded and installed logilab-astng, logilab-common and pylint from here: http://www.logilab.org/857 I installed the logilab libraries successfu...
Getting started with Pylint for Jython (jython2.5.1)
We have a ton of Jython scripts for our deployment automation; I'd like Pylint to be part of our build pipeline. I downloaded and installed logilab-astng, logilab-common and pylint from here: http://www.logilab.org/857 I installed the logilab libraries successfully using: jython setup.py install However, when I attempt...
[ "you should not try to compile the test files : some of them are broken on purpose (they are test inputs for pylint). \n" ]
[ 1 ]
[]
[]
[ "jython", "pylint", "python" ]
stackoverflow_0004310446_jython_pylint_python.txt
Q: How can I get Portuguese characters in Python? I'm working with Portuguese Language. The characters are looking weird. How can I fix this? The code: import feedparser import random # Vou definir os feeds feeds_conf = [{"feedurl": "http://pplware.sapo.pt/feed/", "linktoourpage": "http://linktopage.com/gggg/"}, ...
How can I get Portuguese characters in Python?
I'm working with Portuguese Language. The characters are looking weird. How can I fix this? The code: import feedparser import random # Vou definir os feeds feeds_conf = [{"feedurl": "http://pplware.sapo.pt/feed/", "linktoourpage": "http://linktopage.com/gggg/"}, {"feedurl": "http://pplware.sapo.pt/feed/...
[ "The answer is \"it depends on where your output is going to\":\nfeedparser is very smart. It already decodes the input and returns decoded unicode objects to you.\nSo you don't have to do anything. u\"vers\\xe3o\" is already the decoded unicode object.\nYour issue is that, when you print the entire list, you get t...
[ 7 ]
[]
[]
[ "character_encoding", "python" ]
stackoverflow_0005498371_character_encoding_python.txt
Q: CouchDB and Python: how to use "_show" and "_list" functions? The python-couchdb package ( used as import couchdb ) provides a db.view() function to access a couchdb "_view", but how do you access a "_show" or "_list" function? A: I just added show/list support to couchdb-python. Any problems, please use the mai...
CouchDB and Python: how to use "_show" and "_list" functions?
The python-couchdb package ( used as import couchdb ) provides a db.view() function to access a couchdb "_view", but how do you access a "_show" or "_list" function?
[ "I just added show/list support to couchdb-python. Any problems, please use the mailing list.\n" ]
[ 4 ]
[]
[]
[ "couchdb", "python" ]
stackoverflow_0005491851_couchdb_python.txt
Q: Can we make our own S-Boxes, IP, IP~, And other tables in DES? Will it Still Work or should be use what they've provided? I'm trying to construct a DES implementation of my own! But i'm not successful with the implementation I use All the tables like Initail permutation, Expansion Permutation table, Permutation fu...
Can we make our own S-Boxes, IP, IP~, And other tables in DES? Will it Still Work or should be use what they've provided?
I'm trying to construct a DES implementation of my own! But i'm not successful with the implementation I use All the tables like Initail permutation, Expansion Permutation table, Permutation function table, PC-1, PC-2 and all the s-boxes of my own random bit positions . Should we use the S-Boxes provided by DES or we c...
[ "The first rule of cryptography: never ever invent anything yourself! Unless you have a PhD and years of experience, you will end up creating gaping security holes. As a matter of fact, history shows that even people with a PhD and years of experience often make security mistakes. Sure, you can do it for fun and ed...
[ 5, 1 ]
[]
[]
[ "cryptography", "des", "encryption", "python" ]
stackoverflow_0005234639_cryptography_des_encryption_python.txt
Q: Stop words nltk/python problem I have some code that processes a dataset for later use, the code i'm using for the stop words seems to be ok, however I think the problem lies within the rest of my code as it seems to only remove some of the stop words. import re import nltk # Quran subset filename = 'subsetQuran....
Stop words nltk/python problem
I have some code that processes a dataset for later use, the code i'm using for the stop words seems to be ok, however I think the problem lies within the rest of my code as it seems to only remove some of the stop words. import re import nltk # Quran subset filename = 'subsetQuran.txt' # create list of lower case wo...
[ "try stripping your words while making your word_list2\nword_list2 = [w.strip() for w in word_list if w.strip() not in nltk.corpus.stopwords.words('english')]\n\n" ]
[ 4 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0005499702_nltk_python.txt
Q: Converting selenium.py to python 3 by 2to3 I'm trying to convert selenium.py written in python 2. As you see below I copied selenium.py to C:\Python32\Tools\Scripts> and after execution 2to3.py selenium.py I see that the file is the same. What Have I done wrong? Or from where I can download this file converted?...
Converting selenium.py to python 3 by 2to3
I'm trying to convert selenium.py written in python 2. As you see below I copied selenium.py to C:\Python32\Tools\Scripts> and after execution 2to3.py selenium.py I see that the file is the same. What Have I done wrong? Or from where I can download this file converted? C:\Python32\Tools\Scripts>2to3.py selenium.py R...
[ "This is covered in the official documentation for the 2to3 utility: http://docs.python.org/library/2to3.html\nBy default, it just prints the diff for review (and possibly saving as a patch).\nYou must provide the -w option to actually overwrite the original file.\n" ]
[ 5 ]
[]
[]
[ "python", "python_2to3", "python_3.x", "selenium" ]
stackoverflow_0005499897_python_python_2to3_python_3.x_selenium.txt
Q: Django internationalization (i18n) lint checker? Tell me what hasn't been _()'ed or {% trans %}'ed I have to internationalize (i18n) a django project. It's combined of many in house django apps. It is partially i18n'ed already, i.e. some of the strings are _(), but some are bare. Some of the templates use {% block...
Django internationalization (i18n) lint checker? Tell me what hasn't been _()'ed or {% trans %}'ed
I have to internationalize (i18n) a django project. It's combined of many in house django apps. It is partially i18n'ed already, i.e. some of the strings are _(), but some are bare. Some of the templates use {% blocktrans %} or {% trans %}, but sometimes the english text is in there direct. It will take a lot of manual...
[ "I couldn't find anything like this, so I had to make my own.\n\nA plugin for pylint that finds strings that aren't in _()/ugettext()\nA script to find non-translated/i18n'ed strings in django templates\n\n", "You could grep through all the Python files to get yourself a list of strings and see which ones lack a ...
[ 3, 1 ]
[]
[]
[ "django", "internationalization", "lint", "python" ]
stackoverflow_0005155395_django_internationalization_lint_python.txt
Q: How do I set the PYTHON_PATH variable for my Google App Engine app? I know you can set this in the Preferences of the SDK, but I worry that it won't be correct when the app is deployed. What is the PYTHON_PATH value out on Google's Cloud? Can I set this? Going backwards a step, I just want to be able to do: from...
How do I set the PYTHON_PATH variable for my Google App Engine app?
I know you can set this in the Preferences of the SDK, but I worry that it won't be correct when the app is deployed. What is the PYTHON_PATH value out on Google's Cloud? Can I set this? Going backwards a step, I just want to be able to do: from something import something_else My app can't resolve this reference, wh...
[ "Once your code is deployed, it will have access to all of the supported libraries without you taking any action. In order to add your application-specific directories to the path, you will need to do it programatically inside your handler. I use a pattern like this:\npaths = [\n os.path.join(os.path.dirname(__f...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005500563_google_app_engine_python.txt
Q: game of tetris in python using pygame I've just implemented a very rudimentary game of tetris in python using pygame and would like anybody to constuctively criticize me. It's my first program of substantial length so there are bound to be bugs. I also have not been able to wrap my head fully around the pygame eve...
game of tetris in python using pygame
I've just implemented a very rudimentary game of tetris in python using pygame and would like anybody to constuctively criticize me. It's my first program of substantial length so there are bound to be bugs. I also have not been able to wrap my head fully around the pygame event handling so keyboard controls might be d...
[ "This is similar to my first version of Tetris which I wrote many years ago when I was learning Pascal.\nRecently I wrote another version in order to experiment with Javascript.\nThis time for representing the tetrominoes I used this structure:\n gameboard.colors = ['black','red','brown','cyan','orange','magenta...
[ 4 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0005500486_pygame_python.txt
Q: Passing Data to a Python Web Crawler from PHP Script I've got a python crawler crawling a few webpages every few minutes. I'm now trying to implement a user interface to be accessed over the web and to display the data obtained by the crawler. I'm going to use php/html for the interface. Anyway, the user interface...
Passing Data to a Python Web Crawler from PHP Script
I've got a python crawler crawling a few webpages every few minutes. I'm now trying to implement a user interface to be accessed over the web and to display the data obtained by the crawler. I'm going to use php/html for the interface. Anyway, the user interface needs some sort of button which triggers the crawler to c...
[ "Best possible way to remove dependencies of working with different languages is to use a message queuing library (like rabbitMQ or ActiveMQ)\nBy using this you can send direct messages from php to python or vice versa...\nIf you want an easy way out you need to modify your python script(more on the lines of what f...
[ 1, 0, 0 ]
[]
[]
[ "php", "python", "stdin", "stdout", "web_crawler" ]
stackoverflow_0005499558_php_python_stdin_stdout_web_crawler.txt
Q: Python - ElementTree- cannot use absolute path on element I'm getting this error in ElementTree when I try to run the code below: SyntaxError: cannot use absolute path on element My XML document looks like this: <Scripts> <Script> <StepList> <Step> <StepText> </StepText> <StepT...
Python - ElementTree- cannot use absolute path on element
I'm getting this error in ElementTree when I try to run the code below: SyntaxError: cannot use absolute path on element My XML document looks like this: <Scripts> <Script> <StepList> <Step> <StepText> </StepText> <StepText> </StepText> </Step> </StepList> </Scri...
[ "Turns out I needed to say target.findall(\".//StepText\"). I guess anything without the '.' is considered an absolute path?\nUpdated working code:\ndef search():\n root = ET.parse(INPUT_FILE_PATH)\n for target in root.findall(\"//Script\"):\n stepTexts = target.findall(\".//StepText\")\n for s...
[ 56 ]
[]
[]
[ "elementtree", "python", "xpath" ]
stackoverflow_0005501118_elementtree_python_xpath.txt
Q: Troubleshooting python sys.path The python docs at http://docs.python.org/library/sys.html say that sys.path is... Initialized from the environment variable PYTHONPATH, plus an installation-dependent default. I found a path item in my sys.path that was causing problems, and had a lot of trouble tracking it down....
Troubleshooting python sys.path
The python docs at http://docs.python.org/library/sys.html say that sys.path is... Initialized from the environment variable PYTHONPATH, plus an installation-dependent default. I found a path item in my sys.path that was causing problems, and had a lot of trouble tracking it down. All I could turn up on Google was pe...
[ "I had some issues recently with sys.path and here is how I went about trying to figure out where the entries are coming from. I was able to track all the entries and where they were coming from. Hopefully this will help you too.\n\nThe first that is added C:\\WINNT\\system32\\python27.zip (more details in PEP273)....
[ 4 ]
[]
[]
[ "path", "python" ]
stackoverflow_0005500736_path_python.txt
Q: Xpath explanation in code In the company I am working I had to dive in this part of code. One of your parses is failing and there is a suspicion that there is a fault in this part of code but I due to my inexperience cant figure exactly what its supposed to do. from lxml import etree uni = etree.tounicode def res...
Xpath explanation in code
In the company I am working I had to dive in this part of code. One of your parses is failing and there is a suspicion that there is a fault in this part of code but I due to my inexperience cant figure exactly what its supposed to do. from lxml import etree uni = etree.tounicode def results(self): return [(e.attr...
[ "The XPath expression does the following:\n//li[@class=\"g\" and not(class=\"localbox\")]//a[@class=\"l\"]\n ^ ^ ^ ^ ^\n 1 2 3 4 5\n\n\nfind all occurences of <li> elements\nthat have an attribute named class with value g (example...
[ 2 ]
[]
[]
[ "elementtree", "python", "xpath" ]
stackoverflow_0005500961_elementtree_python_xpath.txt
Q: Getting pixel data from a PythonMagick image? Does anyone know a way get the pixel data from a PythonMagick.Image instance without having to write it to disk first? For instance, I can read in an image using: import PythonMagick im = PythonMagick.Image('image.jp2') I would now like to be able to get the uncompres...
Getting pixel data from a PythonMagick image?
Does anyone know a way get the pixel data from a PythonMagick.Image instance without having to write it to disk first? For instance, I can read in an image using: import PythonMagick im = PythonMagick.Image('image.jp2') I would now like to be able to get the uncompressed image data so that I can use it in something el...
[ "Disclaimer: I don't have PythonMagick built where I am right now and am no expert, so (1) any or all of the following may be wrong, (2) it will certainly be less specific than you'd like, and (3) if someone else knows better I hope they won't be put off by seeing an answer already here. Anyway:\nFrom a quick look ...
[ 3 ]
[]
[]
[ "imagemagick", "jpeg2000", "python" ]
stackoverflow_0005501141_imagemagick_jpeg2000_python.txt
Q: Creating graph with date and time in axis labels with matplotlib I have my data in an array of the following structure, [[1293606162197, 0, 0], [1293605477994, 63, 0], [1293605478057, 0, 0], [1293605478072, 2735, 1249], [1293606162213, 0, 0], [1293606162229, 0, 0]] The first column is epoch time (in ms), sec...
Creating graph with date and time in axis labels with matplotlib
I have my data in an array of the following structure, [[1293606162197, 0, 0], [1293605477994, 63, 0], [1293605478057, 0, 0], [1293605478072, 2735, 1249], [1293606162213, 0, 0], [1293606162229, 0, 0]] The first column is epoch time (in ms), second is y1 and third is y2. I need a plot with the time on the x-axis, ...
[ "I hope this helps. I've always had a hard time with matplotlib's dates. Matplotlib requires a float format which is days since epoch. The helper functions num2date and date2num along with python builtin datetime can be used to convert to/from. The formatting business was lifted from this example. You can chan...
[ 49 ]
[]
[]
[ "datetime_format", "matplotlib", "python" ]
stackoverflow_0005498510_datetime_format_matplotlib_python.txt
Q: Forgotten password implementation in Django I am trying to implement a forgot password functionality in my django application. I have given a seperate forgottenPassword.html, where user can give his email id ; and if that email is registered(found in database) , corresponding password of that email is fetched and ...
Forgotten password implementation in Django
I am trying to implement a forgot password functionality in my django application. I have given a seperate forgottenPassword.html, where user can give his email id ; and if that email is registered(found in database) , corresponding password of that email is fetched and sent to his email id.This is what i am trying to ...
[ "There is (by design) no way to do this. You cannot get the password for a user, because it is only stored in the database as a secure hash, and there is no way of reversing that hash.\nHowever, Django does provide a built-in reset password implementation in contrib.auth - see the documentation.\n", "rv_k, I just...
[ 20, 5 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0005498361_django_django_models_django_templates_django_views_python.txt
Q: Writing tuple values to a file I have a piece of code # create list of (val, key) tuple pairs freq_list2 = [(val, key) for key, val in freq_dic.items()] # sort by val or frequency freq_list2.sort(reverse=True) freq_list3 = list(freq_list2) # display result as top 10 most frequent words for freq, word in freq_list2...
Writing tuple values to a file
I have a piece of code # create list of (val, key) tuple pairs freq_list2 = [(val, key) for key, val in freq_dic.items()] # sort by val or frequency freq_list2.sort(reverse=True) freq_list3 = list(freq_list2) # display result as top 10 most frequent words for freq, word in freq_list2: print word, freq freq_list4 =[...
[ "Short answer:\nfor my_tuple in freq_list:\n fp.write(\"{1:s}, {0:.4f}\\n\".format(*my_tuple)) # assuming (freq, word) tuples\n\nLonger, detailed variant, just in case:\nfor my_tuple in freq_list:\n freq, word = my_tuple # unpacks (0.123, 'the') into word='the' and freq=0.123\n fp.write(word) # 'the'\n fp.write...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005501525_python.txt
Q: catch TextCtrl's key/char events and forward typed key to the stdin of a subprocess I am trying to use wx.TextCtrl to catch the typed key events, and directly forward the typed key to the stdin of a subprocess. Please note, for my special purpose, I will completely disable the text editing feature of the TextCtrl....
catch TextCtrl's key/char events and forward typed key to the stdin of a subprocess
I am trying to use wx.TextCtrl to catch the typed key events, and directly forward the typed key to the stdin of a subprocess. Please note, for my special purpose, I will completely disable the text editing feature of the TextCtrl. i.e., when I type a letter, the letter will not be appearing on the TextCtrl, it will b...
[ "You can do this to convert the key code to a character:\nchr(keycode)\n\nThat won't get everything though, like enters and tabs. You'd have to handle that on a case by case basis (like you do in your example). Otherwise you'll need to create a dictionary of key code to character mappings:\ncodemap = {97:'a', 98:'b...
[ 0 ]
[]
[]
[ "keyboard_events", "python", "user_interface", "wxpython", "wxwidgets" ]
stackoverflow_0004887260_keyboard_events_python_user_interface_wxpython_wxwidgets.txt
Q: python's lxml and iterparse method Say i have this sample XML. <result> <field k='field1'> <value h='1'><text>text_value1</text></value> </field> <field k='field2'> <value><text>text_value2</text></value> </field> <field k='field3'> <value><text>some_text</text></value> ...
python's lxml and iterparse method
Say i have this sample XML. <result> <field k='field1'> <value h='1'><text>text_value1</text></value> </field> <field k='field2'> <value><text>text_value2</text></value> </field> <field k='field3'> <value><text>some_text</text></value> </field> </result> Using python's l...
[ "How about:\nimport io\nimport lxml.etree as ET\n\ncontent='''\\\n<result>\n <field k='field1'>\n <value h='1'><text>text_value1</text></value>\n </field>\n <field k='field2'>\n <value><text>text_value2</text></value>\n </field>\n <field k='field3'>\n <value><text>some_text</text...
[ 4, 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0005501572_lxml_python.txt
Q: Learning Python: Print 3 consecutives lines from a PIPE i have the following code: def cmds(cmd): cmd= Popen(cmd, shell=True, stdout=PIPE) lines = command.stdout.read().splitlines() I have a command that outputs lines like this: 2011/03/30-201 CLIENT 3 Failed 23:17 0.0000 2011/03/31-3 CLIENT 2 Completed ...
Learning Python: Print 3 consecutives lines from a PIPE
i have the following code: def cmds(cmd): cmd= Popen(cmd, shell=True, stdout=PIPE) lines = command.stdout.read().splitlines() I have a command that outputs lines like this: 2011/03/30-201 CLIENT 3 Failed 23:17 0.0000 2011/03/31-3 CLIENT 2 Completed 00:47 1.0019 I want to read the first 3 lines for a block, t...
[ "Well, if lines = command.stdout.read().splitlines() produces a list of lines like this:\n['2011/03/30-201', 'CLIENT 3', 'Failed', '23:17', '0.0000', '', '2011/03/31-3', 'CLIENT 2', 'Completed', '00:47', '1.0019']\n\nYou can just loop through it and print until you encounter a blank entry, then reset the counter. I...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005502454_python.txt
Q: Object attribute in python I have following in conf1.py file server = { '1':'ABC' '2':'CD' } client = { '4':'jh' '5':'lk' } Now in other python file s=__import__('conf1') temp='server' for v in conf.temp.keys(): print v And getting the error that conf object don't have attribute temp So how can ...
Object attribute in python
I have following in conf1.py file server = { '1':'ABC' '2':'CD' } client = { '4':'jh' '5':'lk' } Now in other python file s=__import__('conf1') temp='server' for v in conf.temp.keys(): print v And getting the error that conf object don't have attribute temp So how can I make this possible to interpre...
[ "You want:\nimport conf1\n\ntemp=conf1.server \n\nfor v in temp.keys(): print v\n\nhowever you don't need .keys() to iterate over the dict's keys, you can just do:\nfor v in temp: print v\n\n", "s = __import__('conf1')\ntemp = 'server'\nfor v in getattr(conf, temp): # .keys() not required\n print v\n\n", "Yo...
[ 2, 2, 0 ]
[]
[]
[ "attributes", "object", "python" ]
stackoverflow_0005502503_attributes_object_python.txt
Q: How can I conduct a poll through an irc bot? I've set up a irc bot using socket. I've added a few commands , but I'd like to add a "poll" function. Ideally, the bot would get a command with this format: !poll <name> <opt1> <opt2> <opt3> <time> How would I go about checking user who voted and ending the poll after ...
How can I conduct a poll through an irc bot?
I've set up a irc bot using socket. I've added a few commands , but I'd like to add a "poll" function. Ideally, the bot would get a command with this format: !poll <name> <opt1> <opt2> <opt3> <time> How would I go about checking user who voted and ending the poll after a certain time? Thanks in advance, Desperate Pyth...
[ "Well, I'm starting to get a little rusty with my Python but I think I can answer that - It may not be the best answer, though.\nIf you plan to have many polls going at once, you could implement a dictionary containing multiple instances of a custom class like Poll.. Here's a possible solution:\nclass PollVotes(obj...
[ 1 ]
[]
[]
[ "bots", "irc", "python" ]
stackoverflow_0005463118_bots_irc_python.txt
Q: Googlemaps in Python How can i Integrate GoogleMaps in python ?! so that the maps can appear in python shell ????? A: Python shell is not a graphical interface, it's a text interface. However you could display an html page in your favorite browser that you can create using python, where you embed google maps yo...
Googlemaps in Python
How can i Integrate GoogleMaps in python ?! so that the maps can appear in python shell ?????
[ "Python shell is not a graphical interface, it's a text interface. However you could display an html page in your favorite browser that you can create using python, where you embed google maps\n\nyou can use the google maps api to embed google maps in your own website and applications, and overlay your own data on ...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005502697_python.txt
Q: django.contrib.staticfiles.finders.find help needed I have the following Django project layout: project_folder/ app_folder/ static/ folder1/ file1 templates/ ... compressor -> (symlink to django_compressor app with my modifications) __init__.py mana...
django.contrib.staticfiles.finders.find help needed
I have the following Django project layout: project_folder/ app_folder/ static/ folder1/ file1 templates/ ... compressor -> (symlink to django_compressor app with my modifications) __init__.py manage.py settings.py urls.py From the templatetag s...
[ "The answer was: import the whole module, not only the find method\n", "I am using the static files with my new site and it took a while to get set up. Do you have something like this in your settings.py? \nAlso check out:\nDjango staticfiles app help\n# Absolute path to the directory that holds media.\n# Example...
[ 1, 0 ]
[]
[]
[ "django", "python", "static_files" ]
stackoverflow_0005498319_django_python_static_files.txt
Q: How to make something like a log box in wxPython I'm assuming this is possible with a multiline text box, but not sure how to do it. What I'm looking to do is make a log box in my wxPython program, where I can write messages to it when certain actions happen. Also, i need to write the messages not only when an eve...
How to make something like a log box in wxPython
I'm assuming this is possible with a multiline text box, but not sure how to do it. What I'm looking to do is make a log box in my wxPython program, where I can write messages to it when certain actions happen. Also, i need to write the messages not only when an event happens, but certain times in the code. How would i...
[ "I wrote an article on this sort of thing a couple years ago:\nhttp://www.blog.pythonlibrary.org/2009/01/01/wxpython-redirecting-stdout-stderr/\n", "If you would like just a log dialog in wxpython, use wx.LogWindow:\nimport wx\n\nclass MainWindow(wx.Frame):\n\n def __init__(self, parent=None):\n wx.Fram...
[ 6, 4 ]
[]
[]
[ "logging", "python", "wxpython" ]
stackoverflow_0005493984_logging_python_wxpython.txt
Q: connecting c/c++ and python What I am trying to do is that I want to read a file using python, and then with the data in the file, create a variable in c/c++(I don't want to read var from the file :) ). Is this possible? If this is possible, then how would you do it? Thank you guys! A: Maybe Boost.Python can hel...
connecting c/c++ and python
What I am trying to do is that I want to read a file using python, and then with the data in the file, create a variable in c/c++(I don't want to read var from the file :) ). Is this possible? If this is possible, then how would you do it? Thank you guys!
[ "Maybe Boost.Python can help. \nYou could expose a C++ function to your Python script. Something like that: \nvoid do_sth_with_processed_data(const std::string& data)\n{\n // …\n}\n\nBOOST_PYTHON_MODULE(do_sth)\n{\n def(\"do_sth_with_processed_data\", do_sth_with_processed_data);\n}\n\nIn your Python script you...
[ 7, 2, 1 ]
[]
[]
[ "c", "c++", "connection", "io", "python" ]
stackoverflow_0005502787_c_c++_connection_io_python.txt
Q: does __enter__ typically include a try block? I asked this question yesterday. But now I realize it was the wrong question. Do __enter__ functions typically contain try blocks? A: They can if you are prepared to recover from the exception gracefully, but generally you would want to allow the exception to bubble ...
does __enter__ typically include a try block?
I asked this question yesterday. But now I realize it was the wrong question. Do __enter__ functions typically contain try blocks?
[ "They can if you are prepared to recover from the exception gracefully, but generally you would want to allow the exception to bubble upward to the caller (or raise one of your own if that's more appropriate), preventing the with block from being entered if something went wrong with the setup.\n" ]
[ 4 ]
[]
[]
[ "python", "try_catch" ]
stackoverflow_0005503021_python_try_catch.txt
Q: Why is there an extra result handed back to me during this Python regex example? Code: re.findall('(/\d\d\d\d)?','/2000') Result: ['/2000', ''] Code: re.findall('/\d\d\d\d?','/2000') Result: ['/2000'] Why is the extra '' returned in the first example? i am using the first example for django url configuration...
Why is there an extra result handed back to me during this Python regex example?
Code: re.findall('(/\d\d\d\d)?','/2000') Result: ['/2000', ''] Code: re.findall('/\d\d\d\d?','/2000') Result: ['/2000'] Why is the extra '' returned in the first example? i am using the first example for django url configuration , is there a way i can prevent matching of '' ?
[ "Because using the brackets you define a group, and then with ? you ask for 0 to 1 repetitions of the group. Thus the empty string and /2000 both match.\n", "the operator ? will match 0 or 1 repetitions of the preceding expression, in the first case the preceding expression is (/\\d\\d\\d\\d), while in the second...
[ 3, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005502839_python_regex.txt
Q: Python2.7.1 import OpenCV2.2 error Windows XP I'm having some trouble using OpenCV2.2 with Python2.7.1 (which should be compatible). I've installed OpenCV to D:\OpenCV2.2PreCom\, added the D:\OpenCV2.2PreCom\Python2.7\Lib\site-packages path to sys.path as well as to the environment variable PYTHONPATH. I've also m...
Python2.7.1 import OpenCV2.2 error Windows XP
I'm having some trouble using OpenCV2.2 with Python2.7.1 (which should be compatible). I've installed OpenCV to D:\OpenCV2.2PreCom\, added the D:\OpenCV2.2PreCom\Python2.7\Lib\site-packages path to sys.path as well as to the environment variable PYTHONPATH. I've also made sure the D:\OpenCV2.2PreCom\bin path is added t...
[ "Not a Windows user, but seems that the Python module cannot find the DLL. It is not a problem of PYTHONPATH. \nDid you install it or just unpack it? Try installing it with the installer, it should take care of positioning the DLL in the right path.\n", "Can you try escaping the backslashes? Try this:\n>>>> sys....
[ 0, 0, 0 ]
[]
[]
[ "importerror", "opencv", "python", "windows_xp" ]
stackoverflow_0005503172_importerror_opencv_python_windows_xp.txt
Q: What's the most efficient way to access sibling dictionary value in a Python dict? In Python, I've got a list of dictionaries that looks like this: matchings = [ {'id': 'someid1', 'domain': 'somedomain1.com'}, {'id': 'someid2', 'domain': 'somedomain2.com'}, {'id': 'someid3', 'domain': 'somedomain3.com'...
What's the most efficient way to access sibling dictionary value in a Python dict?
In Python, I've got a list of dictionaries that looks like this: matchings = [ {'id': 'someid1', 'domain': 'somedomain1.com'}, {'id': 'someid2', 'domain': 'somedomain2.com'}, {'id': 'someid3', 'domain': 'somedomain3.com'} ] and, I have a variable: the_id = 'someid3' What's the most efficient way to retrie...
[ "You can use a list comprehension:\ndomains = [matching['domain'] for matching in matchings if matching['id'] == the_id]\n\nWhich follows the format standard format of:\nresulting_list = [item_to_return for item in items if condition]\n\nAnd basically encapsulates all the following functionality:\ndomains = []\nfor...
[ 6, 2, 1, 0, 0 ]
[]
[]
[ "dictionary", "list_comprehension", "loops", "python" ]
stackoverflow_0000451690_dictionary_list_comprehension_loops_python.txt
Q: Why can't xmlrpc client append item to list accessable via xmlrpc server procedure? Server code (based on Python library reference): from xmlrpc.server import SimpleXMLRPCServer from xmlrpc.server import SimpleXMLRPCRequestHandler class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = () server = Simp...
Why can't xmlrpc client append item to list accessable via xmlrpc server procedure?
Server code (based on Python library reference): from xmlrpc.server import SimpleXMLRPCServer from xmlrpc.server import SimpleXMLRPCRequestHandler class RequestHandler(SimpleXMLRPCRequestHandler): rpc_paths = () server = SimpleXMLRPCServer(("127.0.0.1", 8000), requestHandler=RequestHan...
[ "Your XMLRPC server is raising a fault since it cannot marshal None. You need to add allow_none=True to the server constructor:\nserver = SimpleXMLRPCServer((\"127.0.0.1\", 8000),\n requestHandler=RequestHandler, \n allow_none=True)\n\n" ]
[ 11 ]
[ "The error message is self-speaking. \nappend() returns None which can not be marshalled unless \nyou specify allow_none.\nReading error messages and the API documentation\nhttp://docs.python.org/library/simplexmlrpcserver.html\nis your friend.\n" ]
[ -1 ]
[ "python", "simplexmlrpcserver", "xml_rpc", "xmlrpcclient" ]
stackoverflow_0005503445_python_simplexmlrpcserver_xml_rpc_xmlrpcclient.txt
Q: Python selenium lib not installing on windows Trying to install Selenium's python library on a windows 7 computer: I got this: ------------------------------------------------------------ C:\Python27\Scripts\pip-script.py run on 03/31/11 11:44:21 Downloading/unpacking selenium Exception: Traceback (most recent cal...
Python selenium lib not installing on windows
Trying to install Selenium's python library on a windows 7 computer: I got this: ------------------------------------------------------------ C:\Python27\Scripts\pip-script.py run on 03/31/11 11:44:21 Downloading/unpacking selenium Exception: Traceback (most recent call last): File "C:\Python27\lib\site-packages\pip-...
[ "WindowsError: [Error 5] Access is denied: 'C:\\\\Windows\\\\System32\\\\build'\n\nWell, this line says that you don't have access to C:\\Windows\\System32\\. That usually occurs you're not an administrator.\nTry running pip from the administrator account:\n\nPress the Windows Logo Thing (technical name for it).\n...
[ 4, 1 ]
[]
[]
[ "python", "selenium", "windows_7" ]
stackoverflow_0005502619_python_selenium_windows_7.txt
Q: Print current value and next value during iteration in Python Possible Duplicate: Iterate a list as pair (current, next) in Python While iterating a list, I want to print the current item in the list, plus the next value in the list. listOfStuff = [a,b,c,d,e] for item in listOfStuff: print item, <nextItem> T...
Print current value and next value during iteration in Python
Possible Duplicate: Iterate a list as pair (current, next) in Python While iterating a list, I want to print the current item in the list, plus the next value in the list. listOfStuff = [a,b,c,d,e] for item in listOfStuff: print item, <nextItem> The output would be: a b b c c d d e
[ "The easiest way I found was:\na = ['a','b','c','d','e']\n\nfor i,nexti in zip(a,a[1::]):\n print i,nexti\n\n", "listOfStuff = ['a','b','c','d','e']\nfor i, item in enumerate(listOfStuff[:-1]):\n next_item = listOfStuff[i+1]\n print item, next_item\n\n", "How about:\nfor i in range(1, len(listOfStuff))...
[ 4, 0, 0, 0 ]
[]
[]
[ "iteration", "python" ]
stackoverflow_0005503457_iteration_python.txt
Q: "Connectedness" In Randomly Generated Graphs For past 3-4 days I have been playing with implementing graphs, and associated structures in python. among other things, i have a trivial function to generate random-graphs i.e. graphs in which two vertices are connected with a given probability. the graphs are then dis...
"Connectedness" In Randomly Generated Graphs
For past 3-4 days I have been playing with implementing graphs, and associated structures in python. among other things, i have a trivial function to generate random-graphs i.e. graphs in which two vertices are connected with a given probability. the graphs are then displayed using graphviz. anyways, during the course ...
[ "Good question!\nIn fact, the subject of random graphs is well known and dates back to Erdos and Renyi, 1959.\nThe observation of threshold is also excellent. There are other properties of graphs which share this \"threshold\" phenomena. \nIn fact, it has been proven that most \"monotone\" properties share this \"t...
[ 5 ]
[]
[]
[ "algorithm", "graph", "python" ]
stackoverflow_0005504086_algorithm_graph_python.txt
Q: Python timeit not working? Can somebody explain me why this is happening? aatiis@aiur ~ $ time python /usr/lib64/python2.7/timeit.py -n 1 \ -- 'x = 10**1000' 1 loops, best of 3: 0.954 usec per loop real 0m0.055s user 0m0.050s sys 0m0.000s aatiis@aiur ~ $ time python /usr/lib64/python2.7/timeit.py -...
Python timeit not working?
Can somebody explain me why this is happening? aatiis@aiur ~ $ time python /usr/lib64/python2.7/timeit.py -n 1 \ -- 'x = 10**1000' 1 loops, best of 3: 0.954 usec per loop real 0m0.055s user 0m0.050s sys 0m0.000s aatiis@aiur ~ $ time python /usr/lib64/python2.7/timeit.py -n 1 \ -- 'x = 10**100000' 1 ...
[ "My guess is the problem is in how you're stating the problem to timeit. I think what's happening is that the expression is being evaluated once when the test expression is compiled and then just looked at (rather than re-evaluated) with each timeit loop. So currently all you're measuring is the time it takes to ...
[ 5, 4 ]
[]
[]
[ "profiling", "python" ]
stackoverflow_0005486272_profiling_python.txt
Q: Python Headless MatplotLib / Pyplot I'm trying to make my data analysis and reports less eye stabbing and more graphical with automatically generated graph-files, and to do this I've been playing with matplotlib/pyplot/pylab. Works brilliantly, but when I try to run it on a headless server... tkinter.TclError: no ...
Python Headless MatplotLib / Pyplot
I'm trying to make my data analysis and reports less eye stabbing and more graphical with automatically generated graph-files, and to do this I've been playing with matplotlib/pyplot/pylab. Works brilliantly, but when I try to run it on a headless server... tkinter.TclError: no display name and no $DISPLAY environment ...
[ "Everything you describe sounds correct. What happens when you run this:\nimport matplotlib\nmatplotlib.use('Agg')\nimport pylab\npylab.plot([1,2], [3,4], linestyle='-')\npylab.savefig('foo.png')\n\nIn my environment it produces this (I scaled it down):\n\n", "Try importing matplotlib and setting the Agg backend ...
[ 28, 13, 12 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005503601_matplotlib_python.txt
Q: Parsing Text with PHP / Python? How? With What? I got a Drupal Ed site for foreign language learners I'm build that has a vocabulary sharing function and flashcard feature. I am thinking of adding a way to parse texts (newspaper articles and such) and output a list of words used, then perhaps cross connect to voca...
Parsing Text with PHP / Python? How? With What?
I got a Drupal Ed site for foreign language learners I'm build that has a vocabulary sharing function and flashcard feature. I am thinking of adding a way to parse texts (newspaper articles and such) and output a list of words used, then perhaps cross connect to vocabulary section. For now, I'm wondering if there are...
[ "Simplistic start:\n<?php\n // source text\n $paragraph = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n Proin congue, quam nec tincidunt congue, massa ipsum sodales tellus,\n in rhoncus sem quam quis ante. Nam condimentum pellentesque libero at\n blandit. Suspendisse felis ...
[ 2, 1, 1, 0 ]
[]
[]
[ "drupal", "parsing", "php", "python" ]
stackoverflow_0005504128_drupal_parsing_php_python.txt
Q: KD-Tree Implementation in SQL Is anyone aware of a KD-Tree, or similar spatial index, implemented in SQL? I was considering writing my own using Python and Django's ORM, but I'd like to avoid reinventing the wheel. I have a table containing millions of rows, with each row containing 128 columns representing image ...
KD-Tree Implementation in SQL
Is anyone aware of a KD-Tree, or similar spatial index, implemented in SQL? I was considering writing my own using Python and Django's ORM, but I'd like to avoid reinventing the wheel. I have a table containing millions of rows, with each row containing 128 columns representing image feature data. Given an arbitrary 12...
[ "KD-tree does not work well for high-dimensional data, and 128 dimensions would be quite high. The KD-tree indexes each dimension at a different level of the tree, and when performing a query the algorithm will do a lot of back-tracking (searching both sides of a branch) and ends up searching most of the points in ...
[ 4, 0 ]
[]
[]
[ "data_mining", "database", "kdtree", "python", "sql" ]
stackoverflow_0005503246_data_mining_database_kdtree_python_sql.txt
Q: How to : modifiy pinax Group types In Pinax documentation : Group support in Pinax allows you to define any type of group. Pinax comes bundled with two types of groups: tribes — used in social_project projects — used in code_project A group app can have any content object associated with it. Pinax includ...
How to : modifiy pinax Group types
In Pinax documentation : Group support in Pinax allows you to define any type of group. Pinax comes bundled with two types of groups: tribes — used in social_project projects — used in code_project A group app can have any content object associated with it. Pinax includes several apps that are group aware: ...
[ "Pinax also comes with photos, they use photologue (part of the social_project setup)\nI'm really not sure what you are asking.\npython manage startapp maps will allow you to create your own apps. Are you looking for prebuilt apps? You might look here for more Django packages http://djangopackages.com/\n" ]
[ 0 ]
[]
[]
[ "django", "pinax", "python" ]
stackoverflow_0005462512_django_pinax_python.txt
Q: What is wrong with this os.path usage? Getting an unexpected result with os.path on Windows XP, Python 2.6.6: a = "D:\temp\temp.txt" os.path.dirname(a) >>> 'D:' # Would expect 'D:\temp' os.path.normpath(a) >>> 'D:\temp\test.txt' os.path.basename(a) >>> '\temp\test.txt' #Would expect 'test.txt' a.replace("\\", "/")...
What is wrong with this os.path usage?
Getting an unexpected result with os.path on Windows XP, Python 2.6.6: a = "D:\temp\temp.txt" os.path.dirname(a) >>> 'D:' # Would expect 'D:\temp' os.path.normpath(a) >>> 'D:\temp\test.txt' os.path.basename(a) >>> '\temp\test.txt' #Would expect 'test.txt' a.replace("\\", "/") >>>'D:\temp\test.txt' # Would expect 'D:/te...
[ "You aren't escaping your backslashes. Either use \\\\ instead of \\, or use raw strings, e.g:\na = r\"D:\\temp\\temp.txt\"\n\nIn your unescaped strings, the \\t is interpreted as a tab character.\n", "Your problem is with the assignment of a. You need to escape the backslashes in the string Try this instead:\na ...
[ 9, 0, 0 ]
[]
[]
[ "path", "python", "windows" ]
stackoverflow_0005503458_path_python_windows.txt
Q: Python: efficiently generating a vector with different values I'm programming a scientific application in Python, and the performance of my algorithm so far is terrible. I'm trying to find an efficient way to code what I'm doing. Basically, I have to multiply def get_thing(self, chi, n): return np.sum(self.a...
Python: efficiently generating a vector with different values
I'm programming a scientific application in Python, and the performance of my algorithm so far is terrible. I'm trying to find an efficient way to code what I'm doing. Basically, I have to multiply def get_thing(self, chi, n): return np.sum(self.an[n][j] * pow(chi, -j) for j in xrange(1, self.j)) where self.an[i...
[ "Simply, try to do the computations in higher level of abstraction, i.e. try to avoid python level looping. \nStudy carefully how to do element-wise operations and how broadcasting operates, and last but not least don't forget the power of linear algebra!\n", "Within get_things you could certainly simplify thing...
[ 1, 1 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0005504498_numpy_python_scipy.txt
Q: What is the easiest way to get a list of whole factor pairs of a given integer? What is the easiest way to get a list of whole factor pairs of a given integer? For example: f(20) would return [(1,20), (2,10), (4,5)]. A: def f(value): factors = [] for i in range(1, int(value**0.5)+1): if value % i...
What is the easiest way to get a list of whole factor pairs of a given integer?
What is the easiest way to get a list of whole factor pairs of a given integer? For example: f(20) would return [(1,20), (2,10), (4,5)].
[ "def f(value):\n factors = []\n for i in range(1, int(value**0.5)+1):\n if value % i == 0:\n factors.append((i, value / i))\n return factors\n\nOr the same thing using a list comprehension:\ndef f(val):\n return [(i, val / i) for i in range(1, int(val**0.5)+1) if val % i == 0]\n\n", ...
[ 11, 3, 0 ]
[]
[]
[ "math", "python" ]
stackoverflow_0005504848_math_python.txt
Q: Python: calling process.terminate() doesn't kill it When I run the following code: p = subprocess.Popen("...", shell=True) if p.poll() == None: p.kill() The process is simply not killed. I'm on Windows. I thought it was because of multithreading, I ran it in a single thread, still same thing. Do you h...
Python: calling process.terminate() doesn't kill it
When I run the following code: p = subprocess.Popen("...", shell=True) if p.poll() == None: p.kill() The process is simply not killed. I'm on Windows. I thought it was because of multithreading, I ran it in a single thread, still same thing. Do you have any ideas why this could be happening? Thanks Update...
[ "Because you use shell=True, all you end up killing is the shell (cmd.exe process) itself.\nProcess groups are a relatively new feature of Windows and I don't know of any software apart from Task Scheduler that actually uses them yet.\n", "It may be that the command you are running is setting the sigmask to ignor...
[ 2, 0 ]
[]
[]
[ "process", "python", "terminate", "windows" ]
stackoverflow_0005504766_process_python_terminate_windows.txt
Q: Most efficient way to pull specified rows from a 2-d array? I have a 2-D numpy array with 100,000+ rows. I need to return a subset of those rows (and I need to perform that operations many 1,000s of times, so efficiency is important). A mock-up example is like this: import numpy as np a = np.array([[1,5.5], ...
Most efficient way to pull specified rows from a 2-d array?
I have a 2-D numpy array with 100,000+ rows. I need to return a subset of those rows (and I need to perform that operations many 1,000s of times, so efficiency is important). A mock-up example is like this: import numpy as np a = np.array([[1,5.5], [2,4.5], [3,9.0], [4,8.01]]) b =...
[ "EDIT: Deleted my original answer since it was a misunderstanding of the question. Instead try:\nii = np.where((a[:,0] - b.reshape(-1,1)) == 0)[1]\nc = a[ii,:]\n\nWhat I'm doing is using broadcasting to subtract each element of b from a, and then searching for zeros in that array which indicate a match. This should...
[ 6, 4 ]
[]
[]
[ "arrays", "mask", "numpy", "python" ]
stackoverflow_0005505380_arrays_mask_numpy_python.txt
Q: Using PIL to detect a scan of a blank page So I often run huge double-sided scan jobs on an unintelligent Canon multifunction, which leaves me with a huge folder of JPEGs. Am I insane to consider using PIL to analyze a folder of images to detect scans of blank pages and flag them for deletion? Leaving the folder-c...
Using PIL to detect a scan of a blank page
So I often run huge double-sided scan jobs on an unintelligent Canon multifunction, which leaves me with a huge folder of JPEGs. Am I insane to consider using PIL to analyze a folder of images to detect scans of blank pages and flag them for deletion? Leaving the folder-crawling and flagging parts out, I imagine this w...
[ "Here is an alternative solution, using mahotas and milk.\n\nStart by creating two directories: positives/ and negatives/ where you will manually pick out a few examples.\nI will assume that the rest of the data is in an unlabeled/ directory \nCompute features for all of the images in positives and negatives\nlearn...
[ 13, 5, 3 ]
[]
[]
[ "computer_vision", "image_scanner", "imaging", "python", "python_imaging_library" ]
stackoverflow_0005426482_computer_vision_image_scanner_imaging_python_python_imaging_library.txt
Q: Calling python from Actionscript I have an Adobe Air Program that calls a python script. I dont' think the actionscript 3.0 is making the proper call. Code: var file:File; var args:Vector.<String> = new Vector.<String>; file = new File().resolvePath("/usr/bin/python"); va...
Calling python from Actionscript
I have an Adobe Air Program that calls a python script. I dont' think the actionscript 3.0 is making the proper call. Code: var file:File; var args:Vector.<String> = new Vector.<String>; file = new File().resolvePath("/usr/bin/python"); var pyScript:File; pyScript ...
[ "I have faced a similar problem using Air. I needed to print to a receipt printer from an Air app. I couldn't do it from the app itself so I used a python RPC server to do the work for me and talked to it over http. below is a simplified version to give you an idea: \nThe python RPC server\nfrom SimpleXMLRPCServer...
[ 6 ]
[]
[]
[ "actionscript", "actionscript_3", "python" ]
stackoverflow_0005505355_actionscript_actionscript_3_python.txt
Q: Communication between Python script and a win32 program (developed in Delphi) I'm new to Python and I want my Python script to be able to communicate with my Windows program (developed in Delphi, FWIW). Basically, the Python script will download a set of data from other data sources, and for each record it's downl...
Communication between Python script and a win32 program (developed in Delphi)
I'm new to Python and I want my Python script to be able to communicate with my Windows program (developed in Delphi, FWIW). Basically, the Python script will download a set of data from other data sources, and for each record it's downloaded, I'll log it and tell the Windows program. For logging I'll use the Python st...
[ "If your Delphi program is the one executing the Python program, then you can simply have the script write progress messages to standard output, and you can read them in your Delphi program. (If you do it this way, then it doesn't matter that one program is in Python and the other is in Delphi. Either program can b...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "delphi", "interprocess", "python", "windows" ]
stackoverflow_0005502673_delphi_interprocess_python_windows.txt
Q: Error parsing emails using Python's email module when the encoding is in shift_jis I am getting an error that says "UnicodeDecodeError: 'shift_jis' codec can't decode bytes in position 2-3: illegal multibyte sequence" when I try to use my email parser to decode a shift_jis encoded email and convert it to unicode. ...
Error parsing emails using Python's email module when the encoding is in shift_jis
I am getting an error that says "UnicodeDecodeError: 'shift_jis' codec can't decode bytes in position 2-3: illegal multibyte sequence" when I try to use my email parser to decode a shift_jis encoded email and convert it to unicode. The code and email can be found below: import email.header import base64 import sys impo...
[ "Starting with this string:\nIn [124]: msg['Subject']\nOut[124]: '=?ISO-2022-JP?B?GyRCNS5KfSRLJEgkRiRiQmdAWiRKJCpDTiRpJDskLCQiJGo'\n\n=?ISO-2022-JP?B? means the string is ISO-2022-JP encoded, then base64 encoded.\nIn [125]: msg['Subject'].lstrip('=?ISO-2022-JP?B?')\nOut[125]: 'GyRCNS5KfSRLJEgkRiRiQmdAWiRKJCpDTiRpJD...
[ 1 ]
[]
[]
[ "email", "parsing", "python", "shift_jis" ]
stackoverflow_0005504890_email_parsing_python_shift_jis.txt
Q: haystack search startswith Why when i use: users = SearchQuerySet().all() users = users.filter(name__startswith='foo') i have query with result. And when i use users = SearchQuerySet().models(UserProfile) users = users.filter(name__startswith='foo') i have empty query Thx :) A: From all your models, in which o...
haystack search startswith
Why when i use: users = SearchQuerySet().all() users = users.filter(name__startswith='foo') i have query with result. And when i use users = SearchQuerySet().models(UserProfile) users = users.filter(name__startswith='foo') i have empty query Thx :)
[ "From all your models, in which one did you create a SearchIndex? Do you have a SearchIndex for UserProfile, something like:\nfrom haystack import indexes\nfrom haystack import site\n\n\nclass UserProfileIndex(indexes.SearchIndex):\n ...\n\nsite.register(UserProfile, UserProfileIndex)\n\nYou can only see models...
[ 0 ]
[]
[]
[ "django", "django_haystack", "python" ]
stackoverflow_0004702549_django_django_haystack_python.txt
Q: How do I specify color for output file in python I am trying to change the color of certain lines when creating a file in python. For example if I want all lines with A to be green and the rest default. logfile = open("dirpath/file",'w') logfile.write("A\n") logfile.write("B\n") logfile.close() Its on Linux by ...
How do I specify color for output file in python
I am trying to change the color of certain lines when creating a file in python. For example if I want all lines with A to be green and the rest default. logfile = open("dirpath/file",'w') logfile.write("A\n") logfile.write("B\n") logfile.close() Its on Linux by the way
[ "Files don't have color\nYou could (possibly) inject control characters that switch the console default color as the file is printed on the shell. But that would only work with a particular setup (and be a really bad idea)\nIf you want text to have a color you need to write files in a format that contains colors, s...
[ 4, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005506096_python.txt
Q: Python Multiprocessing queue I am populating a queue with a set of jobs that I want to run in parallel and using python's multiprocessing module for doing that. Code snippet below: import multiprocessing from multiprocessing import Queue queue = Queue() jobs = [['a', 'b'], ['c', 'd']] for job in jobs: queue.pu...
Python Multiprocessing queue
I am populating a queue with a set of jobs that I want to run in parallel and using python's multiprocessing module for doing that. Code snippet below: import multiprocessing from multiprocessing import Queue queue = Queue() jobs = [['a', 'b'], ['c', 'd']] for job in jobs: queue.put(job) When I do queue.get() I ge...
[ "The queue is actually geting populated. You need to call queue.get() for each time you put an object to the queue. So you just need to call queue.get() one more time.\n>>> import multiprocessing\n>>> from multiprocessing import Queue\n>>> queue = Queue()\n>>> jobs = [['a', 'b'], ['c', 'd']]\n>>> for job in jobs:\n...
[ 14, 12 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0005506227_multiprocessing_python.txt
Q: Checking number of elements in Python's `Counter` Python 2.7/3.1 introduced the awesome collections.Counter. My question: How do I count how many "element appearances" a counter has? I want this: len(list(counter.elements())) But shorter. A: A more efficient solution is to sum up the counts (values) of each ele...
Checking number of elements in Python's `Counter`
Python 2.7/3.1 introduced the awesome collections.Counter. My question: How do I count how many "element appearances" a counter has? I want this: len(list(counter.elements())) But shorter.
[ "A more efficient solution is to sum up the counts (values) of each element:\nsum(counter.values())\n\nIn Python 3.x, values() returns a view object of the dict's values.\nIn Python 2.x, values() returned an actual list. To avoid creating a new list with Python 2.x, use itervalues() instead:\nsum(counter.itervalues...
[ 4 ]
[]
[]
[ "collections", "counter", "python" ]
stackoverflow_0005506359_collections_counter_python.txt
Q: reading and extracting data from file using python I am new to python , and I want to extract the data from this format <seq id> <alignment start> <alignment end> <envelope start> <envelope end> <hmm acc> <hmm name> <type> <hmm start> <hmm end> <hmm length> <bit score> <E-value> <significance> <clan> **FBpp014349...
reading and extracting data from file using python
I am new to python , and I want to extract the data from this format <seq id> <alignment start> <alignment end> <envelope start> <envelope end> <hmm acc> <hmm name> <type> <hmm start> <hmm end> <hmm length> <bit score> <E-value> <significance> <clan> **FBpp0143497** **5 151** 5 157 PF00339.22 **Arrest...
[ "You could parse the file with the 'csv' module, using space as a delimiter.\nSee the documentation for csv.reader\n", "As this is proteomic data, probably you could find dedicated parsers in the BioPython package\n", "You can use split() to separate the items at spaces and then print out the values you want fr...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002864451_python.txt
Q: Advantages of mmap vs fileinput I read that mmap is advantageous than fileinput, because it will read a page into kernel pagecache and shares the page in user address space. Whereas, fileinput actually brings a page into kernel and copies a line to user address space. So, there is this extra space overhead with fi...
Advantages of mmap vs fileinput
I read that mmap is advantageous than fileinput, because it will read a page into kernel pagecache and shares the page in user address space. Whereas, fileinput actually brings a page into kernel and copies a line to user address space. So, there is this extra space overhead with fileinput. So, I am planning to move t...
[ "mmap takes a file and sticks it in RAM so that you can index it like an array of bytes or as a big data structure.\nIts a lot faster if you are accessing your file in a \"random-access\" manner -- that is doing a lot of fseek(), fread(), fwrite() combinations.\nBut if you are just reading the file in and processin...
[ 1 ]
[]
[]
[ "performance", "python" ]
stackoverflow_0005483163_performance_python.txt
Q: Redirection of stdout from a SWIG-wrapped C++ class to a non-file python object I'm trying to redirect the output from a SWIG-wrapped C module to a python class. The SWIG caller is a python class which already has sys.stdout overwritten in the following way: with _redirect_streams(): my_C_function(sys.stdout)...
Redirection of stdout from a SWIG-wrapped C++ class to a non-file python object
I'm trying to redirect the output from a SWIG-wrapped C module to a python class. The SWIG caller is a python class which already has sys.stdout overwritten in the following way: with _redirect_streams(): my_C_function(sys.stdout) try: out_s = sys.stdout.getvalue() except AttributeError: ou...
[ "I can only offer you an approach.\n1. Use os.pipe() to create a fd pair\n2. pass the \"write\" pipe down to your C\n3. override \"stdout\" with that pipe (in C-land)\n4. Now \"C\" stdout is going to appear in the \"read\" side of that os.pipe()\n5. Back in python-land, read out of the pipe and write into Python's ...
[ 0 ]
[]
[]
[ "python", "redirect", "stdout", "swig" ]
stackoverflow_0005425852_python_redirect_stdout_swig.txt
Q: Return a sequence of a variable length whose summation is equal to a given integer In the form f(x,y,z) where x is a given integer sum, y is the minimum length of the sequence, and z is the maximum length of the sequence. But for now let's pretend we're dealing with a sequence of a fixed length, because it will ta...
Return a sequence of a variable length whose summation is equal to a given integer
In the form f(x,y,z) where x is a given integer sum, y is the minimum length of the sequence, and z is the maximum length of the sequence. But for now let's pretend we're dealing with a sequence of a fixed length, because it will take me a long time to write the question otherwise. So our function is f(x,r) where x is ...
[ "The itertools module will definately be helpful as we're dealing with premutations - however, this looks suspiciously like a homework task...\nEdit: Looks like fun though, so I'll do an attempt.\nEdit 2: This what you want?\nfrom itertools import combinations_with_replacement\nfrom pprint import pprint\n\nf = lamb...
[ 2, 1, 0 ]
[]
[]
[ "combinations", "math", "permutation", "python" ]
stackoverflow_0005505967_combinations_math_permutation_python.txt
Q: python output of selenium IDE, should it run in console or only in IDE? I created and saved a browser test using selenium IDE in firefox. It has a export feature, and I saved the python code. Should it work in console also, i.e: python selenium_test.py Because I get this error: Errno 10061 no connection could be ...
python output of selenium IDE, should it run in console or only in IDE?
I created and saved a browser test using selenium IDE in firefox. It has a export feature, and I saved the python code. Should it work in console also, i.e: python selenium_test.py Because I get this error: Errno 10061 no connection could be made becasue the target machine actively refused it. selenium is working fin...
[ "You need to download and run the Selenium RC server. The script you have generated from the IDE is trying to connect to it, probably on a certain port on localhost, so run the server on that port.\n" ]
[ 4 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0005506637_python_selenium.txt
Q: Simultaneously acquire data and update graph using python and matplotlib I'm writing a code in Python to communicate to an ultrasonic distance meter over the serial port, to do the following: -Every 0.1 seconds, send a command to the sensor to make a distance measurement, and register the response of the sensor -D...
Simultaneously acquire data and update graph using python and matplotlib
I'm writing a code in Python to communicate to an ultrasonic distance meter over the serial port, to do the following: -Every 0.1 seconds, send a command to the sensor to make a distance measurement, and register the response of the sensor -Display a plot of all the distance measurements from the last 5 seconds Here'...
[ "matplotlib has animated plots that allow the data to be updated while the plot is displayed: take a look at this page.\nYour code might look like this:\nimport serial\nimport numpy as np\nimport time\nfrom matplotlib import pyplot as plt\n\nplt.ion() # set plot to animated\n\ntagnr=2#Tag number of the sensor that...
[ 1 ]
[]
[]
[ "ipython", "matplotlib", "multithreading", "python" ]
stackoverflow_0005505831_ipython_matplotlib_multithreading_python.txt
Q: What datatype is the output? pos_tag(word_tokenize("John's big idea isn't all that bad.")) [('John', 'NNP'), ("'s", 'POS'), ('big', 'JJ'), ('idea', 'NN'), ('is', 'VBZ'), ("n't", 'RB'), ('all', 'DT'), ('that', 'DT'), ('bad', 'JJ'), ('.', '.')] Don't recognize the syntax at all. How would I iterate over this c...
What datatype is the output?
pos_tag(word_tokenize("John's big idea isn't all that bad.")) [('John', 'NNP'), ("'s", 'POS'), ('big', 'JJ'), ('idea', 'NN'), ('is', 'VBZ'), ("n't", 'RB'), ('all', 'DT'), ('that', 'DT'), ('bad', 'JJ'), ('.', '.')] Don't recognize the syntax at all. How would I iterate over this checking for JJ in 2nd value in the...
[ "It looks like a list of pairs (tuple of size 2).\nIterating over it is simple:\nfor text, type in pos_tag(word_tokenize(\"John's big idea isn't all that bad.\")):\n if type == 'JJ':\n print 'text:', text\n print 'type:', type\n\n", "Looks like a list of 2-tuples to me.\n[x for x in L if x[1] == ...
[ 6, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005506780_python.txt
Q: Should I use pgreloaded? Or subversion of pygame? I'm using pygame with python 2.6 right now, But I want to use python 3.1.1 instead. The normal pygame only works with 2.x, but the subversion ones work with 3.x I think. But what about pgreloaded? Is that useable yet? The normal pygame actually works with 3.1 too, ...
Should I use pgreloaded? Or subversion of pygame?
I'm using pygame with python 2.6 right now, But I want to use python 3.1.1 instead. The normal pygame only works with 2.x, but the subversion ones work with 3.x I think. But what about pgreloaded? Is that useable yet? The normal pygame actually works with 3.1 too, but not for os x (at least there isn't a download). Doe...
[ "Just stick with Python 2.6.\n", "pgreloaded has documentation - there is even an own package at http://code.google.com/p/pygame/downloads/list.\n", "I think JD's link to pgreloaded doc is out of date, try this one:\nhttp://wiki.pgreloaded.googlecode.com/hg/documentation/index.html\n", "Or consider using Pygl...
[ 1, 1, 1, 0 ]
[]
[]
[ "pygame", "python", "python_3.x" ]
stackoverflow_0001414258_pygame_python_python_3.x.txt
Q: Python: Unable to easy_install (Windows 7 x64) I'm running python 2.7 on Windows 7 x64, and trying to easy_install pysqlite. With command: easy_install -U pysqlite It exits with the error: error: Setup script exited with error: Unable to find vcvarsall.bat This site: http://code.google.com/p/rdflib/issues/deta...
Python: Unable to easy_install (Windows 7 x64)
I'm running python 2.7 on Windows 7 x64, and trying to easy_install pysqlite. With command: easy_install -U pysqlite It exits with the error: error: Setup script exited with error: Unable to find vcvarsall.bat This site: http://code.google.com/p/rdflib/issues/detail?id=104#c4 suggests a workaround of installing Min...
[ "Even if you install a compiler (MinGW or Visual Studio), you still have to install SQLite3 development libraries. It is a pain to build things on Windows, so I suggest that you get the unofficial pre-built Windows binaries and install it.\nAs an aside, you should probably consider switching to ActivePython as it i...
[ 5, 0, 0 ]
[]
[]
[ "distutils", "pysqlite", "python", "windows", "windows_7_x64" ]
stackoverflow_0005504404_distutils_pysqlite_python_windows_windows_7_x64.txt
Q: Django - Cannot display a form field as a textarea I am declaring a field as a textarea. It works on my local server but not on my remote server. I am using Django version 1.2.3 on my local server and 1.2.5 on my remote server. Here is the code I am using to display a field as a textarea: message = forms.CharField...
Django - Cannot display a form field as a textarea
I am declaring a field as a textarea. It works on my local server but not on my remote server. I am using Django version 1.2.3 on my local server and 1.2.5 on my remote server. Here is the code I am using to display a field as a textarea: message = forms.CharField(widget=forms.Textarea) Then, I display the form using:...
[ "You need to restart the Python interpreter on the remote host. If you're using mod_wsgi, this would mean touch the .wsgi file.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005507264_django_python.txt
Q: How can I set up token-based authentication for web services using Python? I'm relatively new to web authentication, Python and Django. That said, I need to set up per-user token-based authentication for RESTful services and I'm not sure where to start. Any pointers would be greatly appreciated. A: There's a d...
How can I set up token-based authentication for web services using Python?
I'm relatively new to web authentication, Python and Django. That said, I need to set up per-user token-based authentication for RESTful services and I'm not sure where to start. Any pointers would be greatly appreciated.
[ "There's a django-tokenapi package. Its homepage/README looks quite informative. Did you already take a look at that? If so, please clarify the question as to what you have tried and what problems you've faced.\nNote that I'm not very familiar with Django, so I might not be able to help further.\n", "I've done so...
[ 2, 2 ]
[]
[]
[ "authentication", "django", "python", "web_services" ]
stackoverflow_0005505319_authentication_django_python_web_services.txt
Q: Problem with encoding in Python I'm fairly new to python, and I'm with some problems with encoding. Please see the code: # -*- coding: utf-8 -*- import config # Ficheiro de configuracao import twitter import random import sqlite3 import time import bitly_api #https://github.com/bitly/bitly-api-python import feed...
Problem with encoding in Python
I'm fairly new to python, and I'm with some problems with encoding. Please see the code: # -*- coding: utf-8 -*- import config # Ficheiro de configuracao import twitter import random import sqlite3 import time import bitly_api #https://github.com/bitly/bitly-api-python import feedparser class TwitterC: def logTo...
[ "Try adding from __future__ import unicode_literals at the top if your file. Alternatively you can prefix every string with a ´u´, ie u\"favoritos à distancia\"\nMake sure your file is actually saved as utf-8 too!\n" ]
[ 1 ]
[]
[]
[ "encoding", "python" ]
stackoverflow_0005507156_encoding_python.txt
Q: How do I catch an exception in a decorator but allow the caller to catch it as well? I have a python function that may raise an exception. The caller catches the exception and deals with it. Now I would like to add a decorator to that function that also catches the exception, does some handling, but then re-raises...
How do I catch an exception in a decorator but allow the caller to catch it as well?
I have a python function that may raise an exception. The caller catches the exception and deals with it. Now I would like to add a decorator to that function that also catches the exception, does some handling, but then re-raises the exception to allow the original caller to handle it. This works, except that when the...
[ "Just use raise; (i.e. do not raise anything specific, just raise;) in a catch block to re-raise the exception without \"resetting\" the traceback.\n", "I just wrote a class similar to what you are doing, but with a little more options available. Here it is:\nclass ErrorIgnore(object):\n def __init__(self, err...
[ 19, 8 ]
[]
[]
[ "decorator", "exception", "python" ]
stackoverflow_0004249939_decorator_exception_python.txt
Q: Browser and wget load JPEG differently? I'm stumped on this one. Try loading this image in your browser, and then save it to your hard disk. http://profile.ak.fbcdn.net/hprofile-ak-snc4/41674_660962816_995_n.jpg It's a valid JPEG file at 11377 bytes. Now try to download it with wget or curl. Only 11252 bytes...
Browser and wget load JPEG differently?
I'm stumped on this one. Try loading this image in your browser, and then save it to your hard disk. http://profile.ak.fbcdn.net/hprofile-ak-snc4/41674_660962816_995_n.jpg It's a valid JPEG file at 11377 bytes. Now try to download it with wget or curl. Only 11252 bytes show up, and the bottom right part of the im...
[ "Here goes…\nTaking a packet dump, I see that Facebook returns the same Content-Length to Safari as it does to curl, and that content-length is the incorrect 11252:\n\nGET /hprofile-ak-snc4/41674_660962816_995_n.jpg HTTP/1.1\nUser-Agent: curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1....
[ 13, 4 ]
[]
[]
[ "cdn", "facebook", "image", "python" ]
stackoverflow_0005507761_cdn_facebook_image_python.txt
Q: Mac Swampy (Python learning module) install I thought I would teach my kids programming and am using "Think Python" by Downey. The book is great except when he gets to installing "Swampy" a Turtle-like learning module. I've spent a few hours trying to figure it out--now I need help. Can anyone offer a clear, step-...
Mac Swampy (Python learning module) install
I thought I would teach my kids programming and am using "Think Python" by Downey. The book is great except when he gets to installing "Swampy" a Turtle-like learning module. I've spent a few hours trying to figure it out--now I need help. Can anyone offer a clear, step-by-step set of instructions on how to install Swa...
[ "Open the terminal and navigate to the folder where you unzipped Swampy. Find the full directory path of that location by typing pwd. Let's say that location is /home/downey/swampy-2.0/python2. Now in the terminal issue this command export PYHTONPATH=\"/home/downey/swampy-2.0/python2\". This will set the PYTHONPATH...
[ 1, 1 ]
[]
[]
[ "installation", "macos", "python", "pythonpath" ]
stackoverflow_0005507915_installation_macos_python_pythonpath.txt
Q: How can I get plain text from within a HTML class given a URL in python? How can I get plain text (stripped of HTML) from inside a any tag with the class name of calendardescription given a URL in python? Matching text in different tags should also be separated by a blank line. This is for text to speech purposes....
How can I get plain text from within a HTML class given a URL in python?
How can I get plain text (stripped of HTML) from inside a any tag with the class name of calendardescription given a URL in python? Matching text in different tags should also be separated by a blank line. This is for text to speech purposes. Thanks in advance.
[ "You want to use the popular library: Beautiful Soup\nHere is the documentation.\n", "look in the direction of beautiful soup.\n" ]
[ 2, 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0005508314_html_python.txt
Q: pythonxy can't be reinstalled or uninsalled For convenience, I am applying pythonxy But when I try to reload or uninstall,log2del has been in the process,program stoped there I can not reinstall or uninsall A: there is a simple way, delete the pythonxy directory (same as c:\python2.6), then run pythonxy.exe agai...
pythonxy can't be reinstalled or uninsalled
For convenience, I am applying pythonxy But when I try to reload or uninstall,log2del has been in the process,program stoped there I can not reinstall or uninsall
[ "there is a simple way, delete the pythonxy directory (same as c:\\python2.6),\nthen run pythonxy.exe again.\n" ]
[ 0 ]
[]
[]
[ "installation", "python", "pythonxy" ]
stackoverflow_0005508113_installation_python_pythonxy.txt
Q: Multiple authentication options with Tornado Just started playing with Tornado and want to offer multiple methods of authentication. Currently my app is working fine with Google's hybrid OpenID/oAuth using tornado.auth.GoogleMixin and the unauthenticated users are automatically sent to Google's auth page. If an ...
Multiple authentication options with Tornado
Just started playing with Tornado and want to offer multiple methods of authentication. Currently my app is working fine with Google's hybrid OpenID/oAuth using tornado.auth.GoogleMixin and the unauthenticated users are automatically sent to Google's auth page. If an unauthenticated user wants to use another option (...
[ "I think the easiest way to do it would be to change the AuthLoginHandler to something more specific, like GoogleAuthHandler, and create an appropriate route for that: \n(r\"/login/google/\", GoogleAuthHandler),\n(r\"/login/facebook/\", FacebookAuthHandler),\n\netc. \nThen simply create links to each authenticatio...
[ 11, 0 ]
[]
[]
[ "authentication", "python", "tornado" ]
stackoverflow_0003885085_authentication_python_tornado.txt
Q: Add and Compare Datetime in Python How do I write this pseudocode in Python? With 'created_date' being a datetime object. if (created_date + 30days) < now: print 'valid' else: print 'expired' A: import datetime as DT if (created_date + DT.timedelta(days=30)) < DT.datetime.now(): print('valid') else: ...
Add and Compare Datetime in Python
How do I write this pseudocode in Python? With 'created_date' being a datetime object. if (created_date + 30days) < now: print 'valid' else: print 'expired'
[ "import datetime as DT\nif (created_date + DT.timedelta(days=30)) < DT.datetime.now():\n print('valid')\nelse:\n print('expired')\n\n" ]
[ 13 ]
[]
[]
[ "add", "compare", "datetime", "python" ]
stackoverflow_0005508588_add_compare_datetime_python.txt