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: List Changing In Python [(946871.62999999884, [303.91000000000003]), (964918.62999999884, [353.75]), (965117.81999999878, [356.98000000000002]), (959944.86999999883, [528.53999999999996])] I have a list that looks like this. I was wondering if there was any way to remove the minilist, so that it would look lik...
List Changing In Python
[(946871.62999999884, [303.91000000000003]), (964918.62999999884, [353.75]), (965117.81999999878, [356.98000000000002]), (959944.86999999883, [528.53999999999996])] I have a list that looks like this. I was wondering if there was any way to remove the minilist, so that it would look like [(946871.62999999884, 303....
[ "Use a list comprehension.\nL = [(x, y[0]) for x, y in L]\n\n", "This should do that:\nnewList = [(x, y[0]) for x, y in oldList]\n\n" ]
[ 6, 4 ]
[]
[]
[ "list", "python" ]
stackoverflow_0006737798_list_python.txt
Q: Mixing unicode and str in python 2.X ... problems? mystr = 'aaaa' myvar = u'My string %s' % str(mystr) Can this be a problem in the future? I'm messing up woth some in-house code that uses email modules in Python and found some code like this. mystr will always have only ascii characters since it comes from a lis...
Mixing unicode and str in python 2.X ... problems?
mystr = 'aaaa' myvar = u'My string %s' % str(mystr) Can this be a problem in the future? I'm messing up woth some in-house code that uses email modules in Python and found some code like this. mystr will always have only ascii characters since it comes from a list with pre defined ascii only characters. I didn't write...
[ "Try putting actual unicode symbols in the strings (like umlauts or cyrillic) and watch hell breaking lose. :)\ns = 'свят' # world\nv = u'здравей %s' % s # hello %s \n\nTraceback (most recent call last):\nFile \"<input>\", line 1, in <module>\nUnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 0: ...
[ 4, 0 ]
[]
[]
[ "email", "python" ]
stackoverflow_0006737736_email_python.txt
Q: Don't understand pisa(xhtml2pdf) license A client ask me to generate PDF in python, but i don't know if i have to pay the license or just use it. what do i have to do? In their web site said: XHTML2PDF is dual-licensed: 1. GNU General Public License Version 2.0 (GPLv2) 2. A commercial license In their docs...
Don't understand pisa(xhtml2pdf) license
A client ask me to generate PDF in python, but i don't know if i have to pay the license or just use it. what do i have to do? In their web site said: XHTML2PDF is dual-licensed: 1. GNU General Public License Version 2.0 (GPLv2) 2. A commercial license In their docs: pisa is copyrighted by Dirk Holtwick, Ge...
[ "I think unless you have licensed your code under GPL you need the commercial license. (GPL requires you to provide your code if you have used a library licensed under GPL)\nIf you are not certain you could ask the distributers.\nUsual disclaimer that this is a legal question and I am not qualified to answer.\n", ...
[ 1, 1, 1, 0 ]
[]
[]
[ "licensing", "open_source", "pdf_generation", "python" ]
stackoverflow_0002850943_licensing_open_source_pdf_generation_python.txt
Q: How can I make Python/Sphinx document object attributes only declared in __init__? I have Python classes with object attributes which are only declared as part of running the constructor, like so: class Foo(object): def __init__(self, base): self.basepath = base temp = [] for run in os...
How can I make Python/Sphinx document object attributes only declared in __init__?
I have Python classes with object attributes which are only declared as part of running the constructor, like so: class Foo(object): def __init__(self, base): self.basepath = base temp = [] for run in os.listdir(self.basepath): if self.foo(run): temp.append(run) ...
[ "\nI've tried searching for a standard way to ensure that these \"dynamically declared\" attributes can be found (and preferably docstring'd) by the parser, but no luck so far. Any suggestions? \n\nThey cannot ever be \"detected\" by any parser. \nPython has setattr. The complete set of attributes is never \"dete...
[ 11, 2 ]
[]
[]
[ "attributes", "docstring", "python", "python_sphinx" ]
stackoverflow_0003959615_attributes_docstring_python_python_sphinx.txt
Q: Difference between results from Python and C I wrote very simple program in C (PI computation) and I got result like this: 3.1406174152499528235728265546100601568468846380710601806640625 Result doesn't look like proper PI then I found code in Python on internet I ran it and got something like that: 3.141592653589...
Difference between results from Python and C
I wrote very simple program in C (PI computation) and I got result like this: 3.1406174152499528235728265546100601568468846380710601806640625 Result doesn't look like proper PI then I found code in Python on internet I ran it and got something like that: 3.1415926535897932384626433832795028841971693993751058209749 - P...
[ "The problem is a typo in your code, p = tn; should be p = pn;.\nNote: for long doubles use sqrtl.\nUpdate: if you print out the approximation for pi after each iteration it doesn't get any better after the fifth iteration and only the first 20 digits are correct. for more precision you need better (not builtin) da...
[ 8, 6, 0 ]
[]
[]
[ "c", "python" ]
stackoverflow_0006737804_c_python.txt
Q: Python dateutil parser fails I am attempting to parse the following date strings obtained from email headers: from dateutil import parser d1 = parser.parse('Tue, 28 Jun 2011 01:46:52 +0200') d2 = parser.parse('Mon, 11 Jul 2011 10:01:56 +0200 (CEST)') d3 = parser.parse('Wed, 13 Jul 2011 02:00:01 +0000 (GMT+00:00)')...
Python dateutil parser fails
I am attempting to parse the following date strings obtained from email headers: from dateutil import parser d1 = parser.parse('Tue, 28 Jun 2011 01:46:52 +0200') d2 = parser.parse('Mon, 11 Jul 2011 10:01:56 +0200 (CEST)') d3 = parser.parse('Wed, 13 Jul 2011 02:00:01 +0000 (GMT+00:00)') The third one fails; am I missin...
[ "have you tried parser.parse('...', fuzzy=True)? (I suppose it works :))\n", "Give a try to parsedatetime library.\nIn [16]: import parsedatetime.parsedatetime as pdt\n\nIn [17]: p = pdt.Calendar()\n\nIn [18]: p.parse(\"Wed, 13 Jul 2011 02:00:01 +0000 (GMT+00:00)\")\nOut[18]: ((2011, 7, 20, 0, 0, 0, 2, 201, -1), ...
[ 4, 2 ]
[]
[]
[ "python", "python_dateutil" ]
stackoverflow_0006729902_python_python_dateutil.txt
Q: Django model layer for HBase support I am looking for HBase backend support for Django. Does anyone know if something like that exists? A: It doesn't exist at the minute have a look at this recent discussion. It is a suggested Hbase support GSoC project, but is turned down on the basis that mongoDB project was w...
Django model layer for HBase support
I am looking for HBase backend support for Django. Does anyone know if something like that exists?
[ "It doesn't exist at the minute have a look at this recent discussion. It is a suggested Hbase support GSoC project, but is turned down on the basis that mongoDB project was worked on last year and has not yet been added to trunk. Hbase baackend works quite differently from Django's ORM design, in short support isn...
[ 7 ]
[]
[]
[ "database", "django", "hbase", "python" ]
stackoverflow_0006735261_database_django_hbase_python.txt
Q: Associative Array does not work with eval() JavaScript I am generating a data expressed as a Python dictionary which is dumped using simplejson via url which is in this format. {"2": "London", "3": "Tokyo", "4": "Sydney"} I am using $.get and storing into a variable data. However eval(data) does not generate an A...
Associative Array does not work with eval() JavaScript
I am generating a data expressed as a Python dictionary which is dumped using simplejson via url which is in this format. {"2": "London", "3": "Tokyo", "4": "Sydney"} I am using $.get and storing into a variable data. However eval(data) does not generate an Associative Array. Actually throws up an error. What is the p...
[ "Your error is because a { at the beggining of a statement is read as a code block (like the kind you use in ifs and fors) and not as an object literal. You can put parenthesis around for the eval to do as you want:\neval('(' + str + ')');\n\nOf course, eval is evil and you should use something like JSON.parse inst...
[ 9, 6, 2, 2, 1 ]
[]
[]
[ "javascript", "jquery", "json", "python" ]
stackoverflow_0006738210_javascript_jquery_json_python.txt
Q: Do Python dictionaries have all memory freed when reassigned? Working in Python. I have a function that reads from a queue and creates a dictionary based on some of the XML tags in the record read from the queue, and returns this dictionary. I call this function in a loop forever. The dictionary gets reassigned ea...
Do Python dictionaries have all memory freed when reassigned?
Working in Python. I have a function that reads from a queue and creates a dictionary based on some of the XML tags in the record read from the queue, and returns this dictionary. I call this function in a loop forever. The dictionary gets reassigned each time. Does the memory previously used by the dictionary get free...
[ "The memory of an object will be freed if it can be proven (from the knowledge the language implementation has at runtime) that it cannot possibly be accessed any more and the garbage collector sees it fit to make a collection. That's the absolute minimum, and you shouldn't assume any more. And you usually shouldn'...
[ 9, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006738270_python.txt
Q: Is factory pattern meaningless in Python? Since Python is a duck-typed language is writing factory classes meaningless in Python? http://en.wikipedia.org/wiki/Factory_method_pattern A: While there may be times when the factory pattern is unnecessary where it may be required in other languages, there are still ti...
Is factory pattern meaningless in Python?
Since Python is a duck-typed language is writing factory classes meaningless in Python? http://en.wikipedia.org/wiki/Factory_method_pattern
[ "While there may be times when the factory pattern is unnecessary where it may be required in other languages, there are still times when it would be valid to use it - it might just be a way of making your API cleaner - for example as a way of preventing duplication of code that decides which of a series of subclas...
[ 12, 4 ]
[]
[]
[ "factory_pattern", "python" ]
stackoverflow_0006738309_factory_pattern_python.txt
Q: HTML form name array parsing in Pyramid (Python) Is there any way for Pyramid to process HTML form input which looks like this: <input type="text" name="someinput[]" value="" /> or even more usefully: <input type="text" name="someinput[0][subelement1]" value="" /> <input type="text" name="someinput[0][subelement2...
HTML form name array parsing in Pyramid (Python)
Is there any way for Pyramid to process HTML form input which looks like this: <input type="text" name="someinput[]" value="" /> or even more usefully: <input type="text" name="someinput[0][subelement1]" value="" /> <input type="text" name="someinput[0][subelement2]" value="" /> <input type="text" name="someinput[1][s...
[ "One solution would be to use peppercorn. Although it does not support the syntax you're looking for, it will let you send structured data to your Pyramid application through the use of forms. A more casual description exists too.\n" ]
[ 3 ]
[]
[]
[ "forms", "html", "pyramid", "python" ]
stackoverflow_0006734702_forms_html_pyramid_python.txt
Q: Shell script in python with variables Im still new to python. I have a text file with a list of numbers, and each number has two 'attributes' along with it: 250 121 6000.654 251 8472 650.15614 252 581 84.2 i want to search for the 1st column and return the 2nd and 3rd columns as separate variables so i can use t...
Shell script in python with variables
Im still new to python. I have a text file with a list of numbers, and each number has two 'attributes' along with it: 250 121 6000.654 251 8472 650.15614 252 581 84.2 i want to search for the 1st column and return the 2nd and 3rd columns as separate variables so i can use them later. cmd = """ cat new.txt | nawk '/'...
[ "Don't use cat and nawk. Please.\nJust use Python\nimport sys\ntarget= raw_input( 'target: ' ) # or target= sys.argv[1]\nwith open('new.txt','r') as source:\n for columns in ( raw.strip().split() for raw in source ):\n if column[0] == target: print column[1]\n\nNo cat. No nawk.\n", "First of all, to f...
[ 5, 2, 0 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0006738378_python_shell.txt
Q: Why doesn't Python have a hybrid getattr + __getitem__ built in? I have methods that accept dicts or other objects and the names of "fields" to fetch from those objects. If the object is a dict then the method uses __getitem__ to retrieve the named key, or else it uses getattr to retrieve the named attribute. This...
Why doesn't Python have a hybrid getattr + __getitem__ built in?
I have methods that accept dicts or other objects and the names of "fields" to fetch from those objects. If the object is a dict then the method uses __getitem__ to retrieve the named key, or else it uses getattr to retrieve the named attribute. This is pretty common in web templating languages. For example, in a Chame...
[ "I sort of half-read your question, wrote the below, and then reread your question and realized I had answered a subtly different question. But I think the below actually still provides an answer after a sort. If you don't think so, pretend instead that you had asked this more general question, which I think includ...
[ 17, 5, 4 ]
[]
[]
[ "getattr", "magic_methods", "python" ]
stackoverflow_0006738087_getattr_magic_methods_python.txt
Q: Printing Request debug information on a Java Servlet I find it extremely useful when doing Django/Python web development to fully inspect a HTTP request like this: logger = logging.getLogger(__name__) def index(request): logger.info(request) Is there something similar for a Java Servlet? public void doGet(Htt...
Printing Request debug information on a Java Servlet
I find it extremely useful when doing Django/Python web development to fully inspect a HTTP request like this: logger = logging.getLogger(__name__) def index(request): logger.info(request) Is there something similar for a Java Servlet? public void doGet(HttpServletRequest request, HttpServletResponse response) ...
[ "Since I got no answers, I wrote a little helper class to help me with this issue. Hope someone else finds it interesting and useful.\n" ]
[ 2 ]
[]
[]
[ "django", "jakarta_ee", "java", "python", "servlets" ]
stackoverflow_0006693742_django_jakarta_ee_java_python_servlets.txt
Q: How to I get Python 2.x and 3.x to co-exist? I'm new to programming and thought Python would be a good language to learn. Most of the tutorials I found were 2.7 based so I started to learn using that version. I've recently found a tkinter tutorial that I'd like to try out but I'm having a problem. If I run a scrip...
How to I get Python 2.x and 3.x to co-exist?
I'm new to programming and thought Python would be a good language to learn. Most of the tutorials I found were 2.7 based so I started to learn using that version. I've recently found a tkinter tutorial that I'd like to try out but I'm having a problem. If I run a script it will use Python 2.7 which contains Tkinter an...
[ "I'm not sure I understand your question, but I'll take a shot. I'm also assuming you're on Windows.\nIt's simple -- just install both. They will install to different directories, create different start menu folders, etc. I'd also reccomend PyWin32 for the PythonWin editor installed in both 2.7 and 3.2, \n\nhttp://...
[ 7, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006737694_python.txt
Q: Using sax.utils how can i add a tag I have the following code that creates an xml doc self.errorlist.append( '<testcase classname=%(cls)s name=%(name)s time="%(taken)d">' '<%(type)s type=%(errtype)s message=%(message)s><![CDATA[%(tb)s]]>' '</%(type)s></testcase>' % {...
Using sax.utils how can i add a tag
I have the following code that creates an xml doc self.errorlist.append( '<testcase classname=%(cls)s name=%(name)s time="%(taken)d">' '<%(type)s type=%(errtype)s message=%(message)s><![CDATA[%(tb)s]]>' '</%(type)s></testcase>' % {'cls': self._quoteattr('.'.join(id.split(...
[ "solved: using the code below, i was abe to get db=\"mysql\" in the XML Doc\nself.errorlist.append(\n '<testcase classname=%(cls)s name=%(name)s db=\"%(db)s\" time=\"%(taken)d\">'\n '<%(type)s type=%(errtype)s message=%(message)s><![CDATA[%(tb)s]]>'\n '</%(type)s></testcase>' %\n ...
[ 0 ]
[]
[]
[ "python", "sax", "saxparser" ]
stackoverflow_0006714057_python_sax_saxparser.txt
Q: Sorting in python with a dict I have an array of dicts. This works tickets.sort(key=itemgetter('start')), however if the starts equal each other, I need a second criteria to sort by (If there's an easy way to do this, that would solve everything), so I'd like to write my own sort. I've done it before, in the form ...
Sorting in python with a dict
I have an array of dicts. This works tickets.sort(key=itemgetter('start')), however if the starts equal each other, I need a second criteria to sort by (If there's an easy way to do this, that would solve everything), so I'd like to write my own sort. I've done it before, in the form tickets.sort(sort_function) but ...
[ "You can simply pass a second parameter to itemgetter and it will create the necessary function for you:\ntickets.sort(key = itemgetter('start', 'end'))\n\n", "\n…however if the starts equal each other, I need a second criteria to sort by (If there's an easy way to do this, that would solve everything)\n\nThere i...
[ 5, 1, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0006739334_python_sorting.txt
Q: Importing an ancestor module I have a directory structure like this: in src folder i have a module named util.py in src/dir1/dir2 i have another module named client.py i need to import util.py in client.py. I have seen different questions about this topic in stackoverflow i tried different cases: (relative path) i...
Importing an ancestor module
I have a directory structure like this: in src folder i have a module named util.py in src/dir1/dir2 i have another module named client.py i need to import util.py in client.py. I have seen different questions about this topic in stackoverflow i tried different cases: (relative path) in init.py of client.py folder i tr...
[ "I usually do the following\nimport sys\nsys.path.append('../..') #assure that src directory is in sys.path\nimport util\n\n", "You'll need to add __init__.py from the src folder and every subfolder containing files you want to import. You'll also need to be sure that the src is in your PYTHONPATH.\nAssuming clie...
[ 1, 0 ]
[ "Well. First, put all the files in the same folder.\nFrom there, you can say from .....util.py import util\nor from ....util.py import *\nIf you just say import util.py, you will have to say util.(insert function here) whenever you are calling anything.\nAlso, you need an absolute directory if its not in the same f...
[ -1 ]
[ "python" ]
stackoverflow_0006739083_python.txt
Q: Python regex replace to create smiley faces I'd like to create a regex string that would turn this text: Hello this is a mighty fine day today into 8===D 8==D 8D D 8====D 8==D 8=D 8===D is this possible with a python re.sub oneliner? A: No need for regexes: s = 'Hello this is a mighty fine day today' ' '.join(...
Python regex replace to create smiley faces
I'd like to create a regex string that would turn this text: Hello this is a mighty fine day today into 8===D 8==D 8D D 8====D 8==D 8=D 8===D is this possible with a python re.sub oneliner?
[ "No need for regexes:\ns = 'Hello this is a mighty fine day today'\n' '.join('%s%sD'%('8' if len(w) > 1 else '', '='*(len(w)-2)) for w in s.split())\n# '8===D 8==D 8D D 8====D 8==D 8=D 8===D'\n\nEdit: debugged ;) Thanks for the pointer @tg\n", "The question is asking for a re.sub one-liner, so here is one that do...
[ 8, 3, 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006737846_python_regex.txt
Q: subprocess.Popen not escaping command line arguments properly? I am trying to call the following curl command with python: curl -k -F file=@something.zip -F "data={\\"title\\":\\"Another App\\"}" -Lu usr:pwd https://build.phonegap.com/api/v0/apps For it to work, I've found that the json I'm passing in data needs ...
subprocess.Popen not escaping command line arguments properly?
I am trying to call the following curl command with python: curl -k -F file=@something.zip -F "data={\\"title\\":\\"Another App\\"}" -Lu usr:pwd https://build.phonegap.com/api/v0/apps For it to work, I've found that the json I'm passing in data needs to be escaped with backslashes. I can call this command with... os.s...
[ "perhaps using shell=True\npush = subprocess.Popen(s, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n", "Instead of doing \ns.split()\n\ntry using shlex from the standard library\nimport shlex\nshlex.split(s)\n\nShlex allows you configure the escaping behavior (see the link for details, the defaul...
[ 7, 4, 1 ]
[]
[]
[ "cordova", "curl", "json", "python" ]
stackoverflow_0006739865_cordova_curl_json_python.txt
Q: How to intercept WM_DELETE_WINDOW on OSX using Tkinter I'm trying to keep a Toplevel window from being closed in OSX by intercepting window manager WM_DELETE_WINDOW event. #!/usr/bin/env python from Tkinter import * def speak(): print "woof" root = Tk() root.title("root") win = Toplevel() win.title("win")...
How to intercept WM_DELETE_WINDOW on OSX using Tkinter
I'm trying to keep a Toplevel window from being closed in OSX by intercepting window manager WM_DELETE_WINDOW event. #!/usr/bin/env python from Tkinter import * def speak(): print "woof" root = Tk() root.title("root") win = Toplevel() win.title("win") win.protocol('WM_DELETE_WINDOW', speak) root.mainloop() Wh...
[ "See the reply to Python Issue 12584. It appears to be a bug in the very buggy Cocoa Tcl/Tk 8.5 that Apple shipped with OS X 10.6. Don't use it or the Apple-supplied Pythons in 10.6 if you are using Tkinter or anything that uses Tkinter, like IDLE. More info here.\n" ]
[ 2 ]
[]
[]
[ "macos", "osx_snow_leopard", "python", "tkinter" ]
stackoverflow_0001800452_macos_osx_snow_leopard_python_tkinter.txt
Q: Django debug toolbar on a remote server I have just installed django debug toolbar locally to test my django app and it works great. I've just committed and pushed with mercurial the new changes on my test remote server and I can't see the toolbar. The files are the same. Why? A: If DEBUG is True and you are not...
Django debug toolbar on a remote server
I have just installed django debug toolbar locally to test my django app and it works great. I've just committed and pushed with mercurial the new changes on my test remote server and I can't see the toolbar. The files are the same. Why?
[ "If DEBUG is True and you are not seeing the toolbar, then you probably need to add the IP address of the computer you are accessing the site from to INTERNAL_IPS in your settings.py file.\nINTERNAL_IPS = (<your_ip_address>,)\n\n" ]
[ 6 ]
[]
[]
[ "django", "django_debug_toolbar", "python" ]
stackoverflow_0006740077_django_django_debug_toolbar_python.txt
Q: Getting no search results I just installed and setup haystack and solr with django 1.3, but when I search (with haystack default template), I get nothing. I copy and pasted the solr schema and updated my indexes, but I am getting no results. Maybe my model/table isn't connected to solr? How do I fix this? I ha...
Getting no search results
I just installed and setup haystack and solr with django 1.3, but when I search (with haystack default template), I get nothing. I copy and pasted the solr schema and updated my indexes, but I am getting no results. Maybe my model/table isn't connected to solr? How do I fix this? I have no idea what's going on... T...
[ "You will need to populate the field text in your search index somehow; either map it to model field - or - use a template for this! For the start you should be fine using a template, therefore set use_template=True and add a template. Read this paragraph for more information on how to create the template file!\n" ...
[ 1 ]
[]
[]
[ "django", "django_haystack", "python", "search", "solr" ]
stackoverflow_0006739039_django_django_haystack_python_search_solr.txt
Q: Stackless Python development using Python Tools for Visual Studio Does the Python Tools for Visual Studio Beta, which includes support for CPython, allow you to develop in Stackless Python? If so, could you expand your answers to include any of the steps necessary to set a Stackless Python environment up beyond in...
Stackless Python development using Python Tools for Visual Studio
Does the Python Tools for Visual Studio Beta, which includes support for CPython, allow you to develop in Stackless Python? If so, could you expand your answers to include any of the steps necessary to set a Stackless Python environment up beyond installing PTVS on an existing VS2010 installation please?
[ "You certainly can develop for Stackless but there is currently no specialized support for Stackless. This means that you'll find the code editing experience and the REPL window work just fine. But profiling and debugging, which rely upon sys.settrace, won't work for tasklets. \nIf you install Stackless via the ...
[ 5 ]
[]
[]
[ "cpython", "ptvs", "python", "python_stackless", "stackless" ]
stackoverflow_0005583138_cpython_ptvs_python_python_stackless_stackless.txt
Q: underlying data structure for float in python Got a question regarding to the underlying data structure of float (and precision) in Python: >>> b = 1.4 + 2.3 >>> b 3.6999999999999997 >>> c = 3.7 >>> c 3.7000000000000002 >>> print b, c 3.7 3.7 >>> b == c False it seems the values of b and c are machine depende...
underlying data structure for float in python
Got a question regarding to the underlying data structure of float (and precision) in Python: >>> b = 1.4 + 2.3 >>> b 3.6999999999999997 >>> c = 3.7 >>> c 3.7000000000000002 >>> print b, c 3.7 3.7 >>> b == c False it seems the values of b and c are machine dependent, they are the numbers that closest to the target...
[ "For the answer to your first question, take a look at the following (slightly condensed) code from Python's source:\n#define PREC_REPR 17\n#define PREC_STR 12\n\nvoid PyFloat_AsString(char *buf, PyFloatObject *v) {\n format_float(buf, 100, v, PREC_STR);\n}\n\nvoid PyFloat_AsReprString(char *buf, Py...
[ 7, 2, 1, 0, 0, 0 ]
[]
[]
[ "floating_point_precision", "python" ]
stackoverflow_0006740418_floating_point_precision_python.txt
Q: Why is this Python method leaking memory? This method iterate over a list of terms in the data base, check if the terms are in a the text passed as argument, and if one is, replace it with a link to the search page with the term as parameter. The number of terms is high (about 100000), so the process is pretty slo...
Why is this Python method leaking memory?
This method iterate over a list of terms in the data base, check if the terms are in a the text passed as argument, and if one is, replace it with a link to the search page with the term as parameter. The number of terms is high (about 100000), so the process is pretty slow, but this is Ok since it is performed as a cr...
[ "The whole queryset is loaded into memory once you call it, that is what will eat up your memory. You want to get chunks of results if the resultset is that large, it might be more hits on the database but it will mean a lot less memory consumption.\n", "I was complety unable to find the cause of the problem, but...
[ 3, 2, 1 ]
[ "\nI think I should say that this method is called inside a Django model method itself.\n@classmethod\n\nWhy? Why is this \"class level\"\nWhy aren't these ordinary methods that can have ordinary scope rules and -- in the normal course of events -- get garbage collected?\nIn other words (in the form of an answer)...
[ -1 ]
[ "memory_leaks", "python" ]
stackoverflow_0006739679_memory_leaks_python.txt
Q: Trying to gran a screenshot of a tube website takes forever using the code in Python Webkit making web-site screenshots using virtual framebuffer as it is to take a screenshot of a random tube video and it just takes on forever plus it just eats up all my memory any suggestions? A: You might want to try other d...
Trying to gran a screenshot of a tube website takes forever
using the code in Python Webkit making web-site screenshots using virtual framebuffer as it is to take a screenshot of a random tube video and it just takes on forever plus it just eats up all my memory any suggestions?
[ "You might want to try other drivers such as HtmlUnitDriver or ChromeDriver, if you do need Firefox try different versions, the firefox 8 alpha/beta takes half the ram. If you are not, try to maintain your seleminum session for multiple uses and websites as the display.start() browser = webdrive() to browswer.quit...
[ 1 ]
[]
[]
[ "python", "selenium", "webpage_screenshot" ]
stackoverflow_0006740980_python_selenium_webpage_screenshot.txt
Q: python feedparser with yahoo weather rss I'm trying to use feedparser to get some data from yahoos weather rss. It looks like feed parser strips out the yweather namespace data: http://weather.yahooapis.com/forecastrss?w=24260013&u=c <yweather:condition text="Fair" code="34" temp="23" date="Wed, 19 May 2010 5:5...
python feedparser with yahoo weather rss
I'm trying to use feedparser to get some data from yahoos weather rss. It looks like feed parser strips out the yweather namespace data: http://weather.yahooapis.com/forecastrss?w=24260013&u=c <yweather:condition text="Fair" code="34" temp="23" date="Wed, 19 May 2010 5:55 pm EDT" /> looks like feedparser is complet...
[ "Here is one way you could get the data using using lxml:\nimport urllib2\nimport lxml.etree\n\nurl = \"http://weather.yahooapis.com/forecastrss?w=24260013&u=c\"\ndoc = lxml.etree.parse( urllib2.urlopen(url) ).getroot()\nconditions = doc.xpath('*/*/yweather:condition',\n namespaces={'yweather'...
[ 0, 0 ]
[]
[]
[ "feedparser", "python" ]
stackoverflow_0002870258_feedparser_python.txt
Q: How do I Extract a Javascript Value using Regular Expressions? I'm trying the extract the ProductValue from the following bit of Javascript: <script language="javascript" type="text/javascript"> lpAddVars('page','Section','womens'); lpAddVars('page','CartTotal','0.00'); lpAddVars('page','ProductID','43577'); ...
How do I Extract a Javascript Value using Regular Expressions?
I'm trying the extract the ProductValue from the following bit of Javascript: <script language="javascript" type="text/javascript"> lpAddVars('page','Section','womens'); lpAddVars('page','CartTotal','0.00'); lpAddVars('page','ProductID','43577'); lpAddVars('page','ProductValue','128.00'); </script> I don't...
[ "This should work:\nimport re\n\njavascript_text = '''\n <script language=\"javascript\" type=\"text/javascript\">\n lpAddVars('page','Section','womens');\n lpAddVars('page','CartTotal','0.00');\n\n lpAddVars('page','ProductID','43577');\n lpAddVars('page','ProductValue','128.00'); \n\n <...
[ 1, 0 ]
[]
[]
[ "javascript", "parsing", "python", "regex" ]
stackoverflow_0006741287_javascript_parsing_python_regex.txt
Q: a python stack for a simple webapp with xmlrpc and sqlalchemy I'm looking for a nice python based framework that integrated well with xml-rpc and sqlalchemy. I've investigated php based solutions already, and CodeIgniter + Doctrine has the features I need, but SQLAlchemy seems so much nicer than Doctrine, that I w...
a python stack for a simple webapp with xmlrpc and sqlalchemy
I'm looking for a nice python based framework that integrated well with xml-rpc and sqlalchemy. I've investigated php based solutions already, and CodeIgniter + Doctrine has the features I need, but SQLAlchemy seems so much nicer than Doctrine, that I would prefer using it if I can get it integrated easily into an xmlr...
[ "web.py is one of the simplest frameworks, that do not impose unreasonable restrictions on used components. If you need a tool that \"integrates easily with X\", then give it a try.\nYou can use this example of xmlrpc integration: http://webpy.org/tricks/xmlrpc\nAnd this one, for sqlalchemy: http://webpy.org/cookbo...
[ 1, 0 ]
[]
[]
[ "python", "sqlalchemy", "xml_rpc" ]
stackoverflow_0006735957_python_sqlalchemy_xml_rpc.txt
Q: Application is launched in wrong way on os x I start application within python using subprocess module, so this application appears in Activity Monitor utility under roots "launchd. cmd = "/usr/bin/sudo -H -u "+ self.getCurrentUserName() + "-P" + +os.path.join(dir, app) + app_args p = subprocess.Popen(cmd, stdout=...
Application is launched in wrong way on os x
I start application within python using subprocess module, so this application appears in Activity Monitor utility under roots "launchd. cmd = "/usr/bin/sudo -H -u "+ self.getCurrentUserName() + "-P" + +os.path.join(dir, app) + app_args p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=T...
[ "When you run a command as sudo, it will always show up as belonging to root, that is what sudo does...\n--Dave\n" ]
[ 1 ]
[]
[]
[ "launchd", "macos", "python", "subprocess" ]
stackoverflow_0004934859_launchd_macos_python_subprocess.txt
Q: Convert Unicode to UTF-8 Python I am working with a database that has throughout it scattered characters like this: ’. I need to take this from the database, convert it to UTF-8, and then import it into a different database, using python. When printed to the Windows Command Prompt, these characters look like thi...
Convert Unicode to UTF-8 Python
I am working with a database that has throughout it scattered characters like this: ’. I need to take this from the database, convert it to UTF-8, and then import it into a different database, using python. When printed to the Windows Command Prompt, these characters look like this: \xe2\u20ac\u2122. I have tried var...
[ "Always decode on input, and encode on output. (There ought to be handy mnemonic for this: perhaps \"take your code [coat] off when you come indoors\".)\nDecode on input: You say that the database encoding is \"UTF_8_bin\". Are you using MySQL-Python? If so, then you can set the use_unicode option when you connect ...
[ 10 ]
[]
[]
[ "database", "python", "unicode", "utf_8" ]
stackoverflow_0006740865_database_python_unicode_utf_8.txt
Q: JSON to python dictionary: Printing values Noob here. I have a large number of json files, each is a series of blog posts in a different language. The key-value pairs are meta data about the posts, e.g. "{'author':'John Smith', 'translator':'Jane Doe'}. What I want to do is convert it to a python dictionary, then ...
JSON to python dictionary: Printing values
Noob here. I have a large number of json files, each is a series of blog posts in a different language. The key-value pairs are meta data about the posts, e.g. "{'author':'John Smith', 'translator':'Jane Doe'}. What I want to do is convert it to a python dictionary, then extract the values so that I have a list of all ...
[ "See if this works for you: \nimport json\n\n# you have lots of \"posts\", so let's assume\n# you've stored them in some list. We'll use\n# the example text you gave as one of the entries\n# in said list\n\nposts = [\"{'author':'John Smith', 'translator':'Jane Doe'}\"]\n\n# strictly speaking, the single-quotes in y...
[ 2 ]
[]
[]
[ "dictionary", "json", "python" ]
stackoverflow_0006738350_dictionary_json_python.txt
Q: Can this Python script be improved? Can this Python code be improved? def build_list(types): for x in types: for a in ['short', 'long', 'average']: for b in ['square', 'sloped', 'average']: for c in ['small', 'large', 'average']: fo...
Can this Python script be improved?
Can this Python code be improved? def build_list(types): for x in types: for a in ['short', 'long', 'average']: for b in ['square', 'sloped', 'average']: for c in ['small', 'large', 'average']: for d in ['thin', 'thick', 'average']: ...
[ "Yes. You can use itertools.product()\nimport itertools\nfacets_list = list(itertools.product(types,\n ['short', 'long', 'average'],\n ['square', 'sloped', 'average'],\n ['small', 'large', 'average'],\n ...
[ 12 ]
[]
[]
[ "python", "yield" ]
stackoverflow_0006741696_python_yield.txt
Q: typcasting queryset to list() errors in view function - works on the shell sI have the following code: s = StoryCat.objects.filter(category=c) ids=s.values_list('id',flat=True) ids=list(ids) str= json.dumps( ids ) return HttpResponse(str) This runs fine when trying it with python shell. when running it in a view...
typcasting queryset to list() errors in view function - works on the shell
sI have the following code: s = StoryCat.objects.filter(category=c) ids=s.values_list('id',flat=True) ids=list(ids) str= json.dumps( ids ) return HttpResponse(str) This runs fine when trying it with python shell. when running it in a view function I get the following error: list() takes exactly 2 arguments (1 given) ...
[ "The list builtin has been overridden in the local scope. Here is an example of a workaround if you really want to use list():\ndef list(a, b): pass # somewhere list is redefined\ntry:\n c = list() # so this will fail\nexcept TypeError as e:\n print \"TypeError:\", e # with this error\nfrom __builtin__ import...
[ 3 ]
[]
[]
[ "django", "django_views", "json", "list", "python" ]
stackoverflow_0006741748_django_django_views_json_list_python.txt
Q: Limit the queryset of entries displayed for a django admin Inline In django admin, using django 1.2, i'm trying to add a InlineModelAdmin to apply a comment on save when a change is made to an entry. (An entry is expected to have a "ChangeComment" for every edit). I don't want to show previous entries, so I am try...
Limit the queryset of entries displayed for a django admin Inline
In django admin, using django 1.2, i'm trying to add a InlineModelAdmin to apply a comment on save when a change is made to an entry. (An entry is expected to have a "ChangeComment" for every edit). I don't want to show previous entries, so I am trying to force the ChangeCommentInline's formset.queryset to be empty, by...
[ "As benjaoming mentioned in the comments, it was necessary to override the get_queryset() method in the InlineModelAdmin. It was not necessary to override and attach a new formset to the InlineModelAdmin definition as I initially thought.\nHere is the resulting implementation:\nclass ChangeCommentInline(admin.Stack...
[ 14, 3 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0006703652_django_django_admin_python.txt
Q: Getting keys that were updated with the using a dictionaries update method Is it possible to get the keys that where changed when using the update method? def func(**kw): d = {'key0' : 0, 'key1' : 1} d.update(**kw) func(kw0=0, kw1=1) In the above code I'd want to get the keys 'kw0' and 'kw1'. A: No, on...
Getting keys that were updated with the using a dictionaries update method
Is it possible to get the keys that where changed when using the update method? def func(**kw): d = {'key0' : 0, 'key1' : 1} d.update(**kw) func(kw0=0, kw1=1) In the above code I'd want to get the keys 'kw0' and 'kw1'.
[ "No, once update() is called, they are indistinguishable from the other keys.\nInside the function you can still look at kw.keys() to see which ones were passed in\neg\ndef func(**kw):\n d = {'key0' : 0, 'key1' : 1}\n d.update(**kw)\n print \"updated %s\"%kw.keys()\n\nfunc(kw0=0, kw1=1)\n\n", "The only w...
[ 6, 2 ]
[]
[]
[ "data_structures", "dictionary", "key", "python" ]
stackoverflow_0006741478_data_structures_dictionary_key_python.txt
Q: Overridden attribute access does not work (as expected) The main objective of the following module, is to provide a kind of "constant" semantics for some names. class ConstantError(Exception): def __init__(self, msg): self._msg = msg class Constant(object): def __init__(self, name): ...
Overridden attribute access does not work (as expected)
The main objective of the following module, is to provide a kind of "constant" semantics for some names. class ConstantError(Exception): def __init__(self, msg): self._msg = msg class Constant(object): def __init__(self, name): self._name = name def __get__(self, instance, owner...
[ "The descriptor protocol only works on attributes of the class, not on attributes of instances of a class. See the How-To Guide for Descriptors\n", "You are missing a str() or unicode() method in Constants.\nAdd:\ndef __unicode__(self):\n return self._name\n\n", "I think python prevents classes from accessin...
[ 3, 0, 0 ]
[]
[]
[ "attributes", "python", "setattr" ]
stackoverflow_0001874043_attributes_python_setattr.txt
Q: Overriding a "compiled statement" in python For the sake of argument, let us say that I wanted to create my own module with a name like math (which is already pre-defined) and then import it from another module. Here is the directory structure of my code: __init__.py math.py So in the __init__.py I wish to do li...
Overriding a "compiled statement" in python
For the sake of argument, let us say that I wanted to create my own module with a name like math (which is already pre-defined) and then import it from another module. Here is the directory structure of my code: __init__.py math.py So in the __init__.py I wish to do like from math import whatever If I run __init__.p...
[ "First of all, it is a bad idea to name your module with the same name as stdlib modules. You may not know when you will trip over unexpected results.\nSecondly, what you are saying is perfectly possible. \n\nCreate a dir by name foo.\nCreate __init__.py with the content you mentioned.\nCreate math.py with a conten...
[ 3, 2, 1 ]
[]
[]
[ "overriding", "python" ]
stackoverflow_0006742072_overriding_python.txt
Q: Python 3.2.1 ; Pygame 1.9.2 ; Invalid Syntax When I attempt to run the following program, I receive a syntax error notification: balli = "ball.png" backgroundi = "background.png" import pygame , sys from pygame.locals import * pygame.init() screen = pygame.display.set_mode((500,500) , 0 ...
Python 3.2.1 ; Pygame 1.9.2 ; Invalid Syntax
When I attempt to run the following program, I receive a syntax error notification: balli = "ball.png" backgroundi = "background.png" import pygame , sys from pygame.locals import * pygame.init() screen = pygame.display.set_mode((500,500) , 0 , 32) background = pygame.image.load(backgroun...
[ "There is a ) missing on the previous line.\nAn assignment can only be a statement.\nHappy coding.\n", "Specifically, screen.blit(background , (0,0) should be screen.blit(background , (0,0)).\n" ]
[ 4, 4 ]
[]
[]
[ "pygame", "python", "python_3.x", "syntax" ]
stackoverflow_0006742333_pygame_python_python_3.x_syntax.txt
Q: Reverse Proxy for Static Files (hiding upstream filename/paths) I've got a set of static files I want to serve. They're all available in an Amazon S3 bucket. However, I don't want to reveal the actual url/path of those files on S3. I only want a subset of those files to be available at any given time. The subset i...
Reverse Proxy for Static Files (hiding upstream filename/paths)
I've got a set of static files I want to serve. They're all available in an Amazon S3 bucket. However, I don't want to reveal the actual url/path of those files on S3. I only want a subset of those files to be available at any given time. The subset is determined dynamically by a Django application. For example, let's ...
[ "You could do this with twisted's web server, although not sure how fast it would be. I've only used the twisted.web.wsgi.WSGIResource, so maybe this can be done simpler, but just set up an app like this:\nhttp://twistedmatrix.com/documents/10.1.0/web/howto/using-twistedweb.html#auto19\nAnd in your application, usi...
[ 2 ]
[ "With nginx:\nstart by adding the proxy.conf file to you /etc/nginx/conf.d directory (see auxilliary file section: http://wiki.nginx.org/FullExample)\nThen use a similar configuration file for your server:\nserver {\n server_name mysver.com ;\n location /image_a.jog {\n proxy_pass http://$host/amazon/1...
[ -1 ]
[ "django", "nginx", "python", "reverse_proxy", "twisted" ]
stackoverflow_0006740983_django_nginx_python_reverse_proxy_twisted.txt
Q: django-appengine server not starting I've been trying to use Django-appengine to write a small web app, but I am stuck on setting up the development server. I have followed the tutorial as best a human can, and I have modified the test app's app.yaml to include my app ID, but nothing more: application: appidgoeshe...
django-appengine server not starting
I've been trying to use Django-appengine to write a small web app, but I am stuck on setting up the development server. I have followed the tutorial as best a human can, and I have modified the test app's app.yaml to include my app ID, but nothing more: application: appidgoeshere version: 1 runtime: python api_version:...
[ "It sounds like you're running an old version of the SDK. Have you tried updating the SDK?\n", "Have you tried removing:\nbuiltins:\n- remote_api: on\n\nIt looks just fine to me, but that is the specific error above.\n" ]
[ 1, 0 ]
[]
[]
[ "django_nonrel", "djangoappengine", "google_app_engine", "python" ]
stackoverflow_0006740417_django_nonrel_djangoappengine_google_app_engine_python.txt
Q: How to embed this matplotlib code into tkinter canvas? The matplotlib code is in http://matplotlib.sourceforge.net/examples/animation/strip_chart_demo.html I want to embed this code in my tkinter GUI,what should I do ? As it say"""This example uses gtk but does not depend on it intimately. It just uses the idle h...
How to embed this matplotlib code into tkinter canvas?
The matplotlib code is in http://matplotlib.sourceforge.net/examples/animation/strip_chart_demo.html I want to embed this code in my tkinter GUI,what should I do ? As it say"""This example uses gtk but does not depend on it intimately. It just uses the idle handler to trigger events. You can plug this into a differen...
[ "This may or may not be what you were looking for:\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\nfrom matplotlib.lines import Line2D\nimport numpy as np\n\ntry:\n import Tkinter as Tk\ne...
[ 2 ]
[]
[]
[ "matplotlib", "python", "tkinter" ]
stackoverflow_0003554241_matplotlib_python_tkinter.txt
Q: Python `tee` stdout of child process Is there a way in Python to do the equivalent of the UNIX command line tee? I'm doing a typical fork/exec pattern, and I'd like the stdout from the child to appear in both a log file and on the stdout of the parent simultaneously without requiring any buffering. In this python ...
Python `tee` stdout of child process
Is there a way in Python to do the equivalent of the UNIX command line tee? I'm doing a typical fork/exec pattern, and I'd like the stdout from the child to appear in both a log file and on the stdout of the parent simultaneously without requiring any buffering. In this python code for instance, the stdout of the child...
[ "In the following, SOMEPATH is the path to the child executable, in a format suitable for subprocess.Popen (see its docs). \nimport sys, subprocess\n\n\nf = open('logfile.txt', 'w')\nproc = subprocess.Popen(SOMEPATH, stdout=subprocess.PIPE)\n\nwhile True:\n out = proc.stdout.read(1)\n if out == '' and proc.po...
[ 6, 6, 2, 2, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0006544659_file_io_python.txt
Q: List problem with extracting data from Twitter XML page With my function I can extract usernames from a twitter xml search page for a friend finder app I am building as a project. The problem though is that when I grab the usernames and input them into a list something strange happens. Instead of having each usern...
List problem with extracting data from Twitter XML page
With my function I can extract usernames from a twitter xml search page for a friend finder app I am building as a project. The problem though is that when I grab the usernames and input them into a list something strange happens. Instead of having each username as a separate element within a list I have each username ...
[ "You're making a new list, called data, for each URI. If you move the data = [] line out of the for uri in soup.findAll('uri'): loop, you should end up with one list instead of a list of lists.\nIn addition, you've got some other problems. \nThere is a syntax error on your next to last line: you're missing a close-...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "python", "twitter" ]
stackoverflow_0006742943_beautifulsoup_python_twitter.txt
Q: How to use pgdb.executemany? I'm trying to execute insert statements from Python to PostgreSQL using the pgdb module. I see the documentation says: cursor.executemany(query, list of params) # Execute a query many times, binding each param dictionary # from the list. So I'm trying things like: >>> inse...
How to use pgdb.executemany?
I'm trying to execute insert statements from Python to PostgreSQL using the pgdb module. I see the documentation says: cursor.executemany(query, list of params) # Execute a query many times, binding each param dictionary # from the list. So I'm trying things like: >>> insert = "insert into foo (name, numbe...
[ "you want \ninsert = \"insert into foo (name, number) value (%(name)s, %(number)s);\"\n\nWhich style for parameter inclusion is supported by your DBAPI driver can be found with the paramstyle module-level constant. According to the PEP 249 (aka python database API 2 specification):\n\nString constant stating the ty...
[ 6 ]
[]
[]
[ "database", "parameters", "pgdb", "postgresql", "python" ]
stackoverflow_0006741636_database_parameters_pgdb_postgresql_python.txt
Q: Getting around, numpy objects mismatch error in python I'm having a problem with multiplying two big matrices in python using numpy. I have a (15,7) matrix and I want to multipy it by its transpose, i.e. AT(7,15)*A(15*7) and mathemeticaly this should work, but I get an error : ValueError:shape mismatch:objects can...
Getting around, numpy objects mismatch error in python
I'm having a problem with multiplying two big matrices in python using numpy. I have a (15,7) matrix and I want to multipy it by its transpose, i.e. AT(7,15)*A(15*7) and mathemeticaly this should work, but I get an error : ValueError:shape mismatch:objects cannot be broadcast to a single shape I'm using numpy in Python...
[ "You've probably represented the matrices as arrays. You can either convert them to matrices with np.asmatrix, or use np.dot to do the matrix multiplication:\n>>> X = np.random.rand(15 * 7).reshape((15, 7))\n>>> X.T * X\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: operan...
[ 14 ]
[]
[]
[ "arrays", "matrix", "mismatch", "numpy", "python" ]
stackoverflow_0006743158_arrays_matrix_mismatch_numpy_python.txt
Q: Naming convention for a function that analyzes several objects and returns a boolean value It is well accepted that assertion functions that check a single value/object have names that start with "is" (is_valid, is_ok, is_empty). I have a function that compares several objects (strings, in my case) and decides whe...
Naming convention for a function that analyzes several objects and returns a boolean value
It is well accepted that assertion functions that check a single value/object have names that start with "is" (is_valid, is_ok, is_empty). I have a function that compares several objects (strings, in my case) and decides whether they are "similar enough". How would you name such a function? My variant is are_strings_s...
[ "Personally, I would go with is_strings_similar or just is_similar. Why? Because it makes the string search through your code for all assertion functions that much easier. It's code, not a research paper. Improperly conjugated verbs are not the main issue, ease of maintenance is. Most any English speaker can read \...
[ 4, 1, 1, 1 ]
[]
[]
[ "naming_conventions", "python" ]
stackoverflow_0006743033_naming_conventions_python.txt
Q: Cross platform, stable, and with great feature web platform We are a group of 2 C# programmers, which have experience in wcf web services, asp.net MVC 3, different architectural patterns, Inversion of control etc. We have to implement a web site, which will run on Linux with minimum of 10k online users. The proble...
Cross platform, stable, and with great feature web platform
We are a group of 2 C# programmers, which have experience in wcf web services, asp.net MVC 3, different architectural patterns, Inversion of control etc. We have to implement a web site, which will run on Linux with minimum of 10k online users. The problem is that it will run on Linux, and we don't know what language t...
[ "\nWe are a group of 2 C# programmers, which have experience in (snip) asp.net MVC\n\nYou want to write a web-site, and you have asp.net MVC experience... ASP.NET MVC can run on linux / Mono. So my suggestion... do that.\nSome links:\n\nDeploy ASP.NET MVC on Linux: Best Practices, Tools & Surprises\nDeveloping ASP....
[ 4, 2, 1 ]
[]
[]
[ ".net", "c#", "java", "linux", "python" ]
stackoverflow_0006743061_.net_c#_java_linux_python.txt
Q: Access Most Recently Used (MRU) entries via Python on Windows? Using Python, is it possible to get access to the Most Recently Used (MRU) list in windows. This is where Windows keeps a list of the most recently opened documents and programs. Thanks! A: Possible: yes, easy yes. the challenge though is choosing wh...
Access Most Recently Used (MRU) entries via Python on Windows?
Using Python, is it possible to get access to the Most Recently Used (MRU) list in windows. This is where Windows keeps a list of the most recently opened documents and programs. Thanks!
[ "Possible: yes, easy yes.\nthe challenge though is choosing which MRU to choose from... windows and programs stores dozens of em - windows alone probably stores 6 of them.\npresuming you want the Windows run dialogue you can get it like so (Python 2x syntax, tested on python 2.7):\ndef get_run_mru():\n import _w...
[ 2 ]
[]
[]
[ "python", "pywin32", "windows" ]
stackoverflow_0006325301_python_pywin32_windows.txt
Q: How to sort files in a directory before reading? I am working with a program that writes output to a csv file based on the order that files are read in from a directory. However with a large number of files with the endings 1,2,3,4,5,6,7,8,9,10,11,12. My program actually reads the files by I guess alphabetical o...
How to sort files in a directory before reading?
I am working with a program that writes output to a csv file based on the order that files are read in from a directory. However with a large number of files with the endings 1,2,3,4,5,6,7,8,9,10,11,12. My program actually reads the files by I guess alphabetical ordering: 1,10,11,12....,2,20,21.....99. The problem i...
[ "files = ['String.ext.ext2.1.txt', 'String.ext.ext2.12.txt', 'String.ext.ext2.2.txt']\n# files: coming from os.listdir() sorted alphabetically, thus not numerically\n\nsorted_files = sorted(files, key=lambda x: int(x.split('.')[3]))\n# returns: ['String.ext.ext2.1.txt', 'String.ext.ext2.2.txt', 'String.ext.ext2.12....
[ 16, 5, 5, 2 ]
[]
[]
[ "file_io", "python", "sorting" ]
stackoverflow_0006743407_file_io_python_sorting.txt
Q: Replace current process with invocation of subprocess? In python, is there a way to invoke a new process in, hand it the same context, such as standard IO streams, close the current process, and give control to the invoked process? This would effectively 'replace' the process. I have a program whose behavior I wan...
Replace current process with invocation of subprocess?
In python, is there a way to invoke a new process in, hand it the same context, such as standard IO streams, close the current process, and give control to the invoked process? This would effectively 'replace' the process. I have a program whose behavior I want to repeat. However, it uses a third-party library, and it ...
[ "You may be interested in os.execv() and friends:\n\nThese functions all execute a new program, replacing the current\n process; they do not return. On Unix, the new executable is loaded\n into the current process, and will have the same process id as the\n caller. Errors will be reported as OSError exceptions.\...
[ 35 ]
[]
[]
[ "process", "python", "replace" ]
stackoverflow_0006743567_process_python_replace.txt
Q: Writing a lockscreen for Linux? I've been looking around for a nice lockscreen to use with my XFCE system, but it seems like there are any slim lock screens around. I'm currently using slock, but it's just a blank screen with absolutely no interface whatsoever. I'm looking to code a lockscreen in Python. I looked ...
Writing a lockscreen for Linux?
I've been looking around for a nice lockscreen to use with my XFCE system, but it seems like there are any slim lock screens around. I'm currently using slock, but it's just a blank screen with absolutely no interface whatsoever. I'm looking to code a lockscreen in Python. I looked at the source code for slock, and it ...
[ "If you want to go low-level, you can use python xcb bindings.\nIf you want to use higher level bindings, you may find this tutorial on writing a screen saver with Qt useful. Porting it to PyQt should be quite straightforward. I'm pretty sure similar resources exist for GTK. \n" ]
[ 2 ]
[]
[]
[ "linux", "lockscreen", "python", "xorg" ]
stackoverflow_0006741204_linux_lockscreen_python_xorg.txt
Q: Google App Engine Python, virtualenv and mimetypes I have working project built with djangoappengine and running under App Engine dev server. So I run "manage.py runserver" and all works as appreciated. All requirements (django, djangoappengine etc) are located in project root dir. Now I am trying to use virtualen...
Google App Engine Python, virtualenv and mimetypes
I have working project built with djangoappengine and running under App Engine dev server. So I run "manage.py runserver" and all works as appreciated. All requirements (django, djangoappengine etc) are located in project root dir. Now I am trying to use virtualenv (I am running commands in project root): virutalenv --...
[ "This is described in Issue 4339 for GAE. Here's how to fix it:\n\nDownload patch from this Issue comment: patch\nMove the patch to google_appengine/google/appengine/tools/\nChange your working directory to the same path as above\nType: patch -p0 < dev_appserver.patch\n\n", "Virtualenv does not copy full Python ...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "python", "virtualenv" ]
stackoverflow_0004090268_google_app_engine_python_virtualenv.txt
Q: Dictionary in python I'm creating a server-client communication, and I want to store some information in a dictionary, so I created a Global dictionary global commandList commandList = {} And when a client is connection to the server I'm trying to store some information in the following way self.clientname = str...
Dictionary in python
I'm creating a server-client communication, and I want to store some information in a dictionary, so I created a Global dictionary global commandList commandList = {} And when a client is connection to the server I'm trying to store some information in the following way self.clientname = str( self.client_address ) co...
[ "Other people have already pointed out how to fix this problem, but perhaps not explained why.\nWhat you are trying to do is create values in a nested dictionary, or, in other words, a dictionary of dictionaries.\nThus your first dictionary is called commandList with keys of self.clientname. Each of the values in t...
[ 5, 3, 2, 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0006743893_dictionary_python.txt
Q: Validate expression/infix in python How do I validate an expression/infix in python? Is it possible? For example: a-d*9 5-(a*0.3-d+(0.4-e))/k*5 (a-d*9)/(k-y-4.3*e)+(t-7*c) A: If you want Python-style expressions, you can use the parser in the ast module and check for SyntaxError: >>> ast.parse('5-(a*0.3-d+(0.4-e...
Validate expression/infix in python
How do I validate an expression/infix in python? Is it possible? For example: a-d*9 5-(a*0.3-d+(0.4-e))/k*5 (a-d*9)/(k-y-4.3*e)+(t-7*c)
[ "If you want Python-style expressions, you can use the parser in the ast module and check for SyntaxError:\n>>> ast.parse('5-(a*0.3-d+(0.4-e))/k*5')\n<_ast.Module object at 0x7fc7bdd9e790>\n>>> ast.parse('5-(a*0.3-d+(0.4-e))/k*')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \...
[ 2 ]
[]
[]
[ "arithmetic_expressions", "expression", "infix_notation", "python" ]
stackoverflow_0006744389_arithmetic_expressions_expression_infix_notation_python.txt
Q: OAuth and the YouTube API I am trying to use the YouTube services with OAuth. I have been able to obtain request tokens, authorize them and transform them into access tokens. Now I am trying to use those tokens to actually do requests to the YouTube services. For instance I am trying to add a video to a playlist. ...
OAuth and the YouTube API
I am trying to use the YouTube services with OAuth. I have been able to obtain request tokens, authorize them and transform them into access tokens. Now I am trying to use those tokens to actually do requests to the YouTube services. For instance I am trying to add a video to a playlist. Hence I am making a POST reques...
[ "Turns out the problem was the newline before xmlns:yt. I was able to debug this using ncat, as suggeested here, and inspecting the full response.\n", "i would suggest using the oauth python module, because it much more simple and takes care of the auth headers :) https://github.com/simplegeo/python-oauth2, as a ...
[ 1, 0 ]
[]
[]
[ "oauth", "python", "youtube", "youtube_api" ]
stackoverflow_0006731966_oauth_python_youtube_youtube_api.txt
Q: Global objects in python wsgi server I am creating an application in python which uses a web server to serve the frontend, and after accepting data as a web request, forwards the task to a job queue, which is being shared with the main processing function using a thread. But the problem is that python web server ...
Global objects in python wsgi server
I am creating an application in python which uses a web server to serve the frontend, and after accepting data as a web request, forwards the task to a job queue, which is being shared with the main processing function using a thread. But the problem is that python web server tries to import itself to run threads, and...
[]
[]
[ "Shared data is best stored in a database.\nIf you want a global variable per user's session, then you want to store these with the session data: here are details for web.py and for flask.\nIf you have a persistent process that is processing a queue, you might look at running your server with FastCGI, where your py...
[ -2 ]
[ "global_variables", "mod_wsgi", "python" ]
stackoverflow_0006744139_global_variables_mod_wsgi_python.txt
Q: Create ,UPDATE and DELETE call using django-tastypie I am using django-tastypie to build the API for my project. I followed the tastypie-doc. Using this doc I am able to call the GET method and filter the data based on the parameter. But I couldn't find any examples for PUT(UPDATE), DELETE (delete object) and POST...
Create ,UPDATE and DELETE call using django-tastypie
I am using django-tastypie to build the API for my project. I followed the tastypie-doc. Using this doc I am able to call the GET method and filter the data based on the parameter. But I couldn't find any examples for PUT(UPDATE), DELETE (delete object) and POST(Create a new object). Does anyone know how to write a cal...
[ "post_list and other post commands are CREATEs, while puts are updates and deletes are deletes. There are also obj_ methods that implement these methods.\nYou can also take a look at the examples at http://django-tastypie.readthedocs.org/en/latest/cookbook.html which show how to do each of the basic actions.\nAlso,...
[ 6 ]
[]
[]
[ "api", "django", "python", "sql", "tastypie" ]
stackoverflow_0006744541_api_django_python_sql_tastypie.txt
Q: Python threads in C I'am writing a multi-threaded program in C. Before creating the threads, a global python environment is initialized by calling Py_Initialize(). Then, in every created thread, the global python environment is shared, and each thread calls a python method with the parameters converted in C. Every...
Python threads in C
I'am writing a multi-threaded program in C. Before creating the threads, a global python environment is initialized by calling Py_Initialize(). Then, in every created thread, the global python environment is shared, and each thread calls a python method with the parameters converted in C. Everything works well until he...
[ "My problem has been solved. You may have your problems more particular, so I'm trying to write my solution in a more generic way here. Hope it helps.\n\n- In main C thread\n\ninitialize the Python environment at the very begining:\n\n/*define a global variable to store the main python thread state*/\nPyThreadState...
[ 4, 2 ]
[]
[]
[ "c", "multithreading", "python" ]
stackoverflow_0006596016_c_multithreading_python.txt
Q: Python - Best practices to queue / dequeue threads I have a queue which can contain max 4 queued objects. These objects are threads running web service requests. The thread part is OK. I have followed many tutorials which talk about consumer and producer threads used to fill in and out the queue object. My questio...
Python - Best practices to queue / dequeue threads
I have a queue which can contain max 4 queued objects. These objects are threads running web service requests. The thread part is OK. I have followed many tutorials which talk about consumer and producer threads used to fill in and out the queue object. My question is about the consumer part. In all these tutorials and...
[ "Maybe you could use conditions\nImagine you want to put a new thread into your queue but it is full. Then you could wait() for the condition object (pseudo code):\ncondition.acquire()\nwhile not queue.has_free_place():\n condition.wait()\nadd_new_thread_to_queue()\ncondition.release()\n\nAnd inside your queued ...
[ 0 ]
[]
[]
[ "architecture", "multithreading", "python", "queue" ]
stackoverflow_0006745195_architecture_multithreading_python_queue.txt
Q: Creating a password with an extra booleanField I have the following problem. I made a registration password for my site so that a user needs to know this password to be able to register. Also I would like a boolean value linked to it which would determine what kind of rights the user gets with this password. class...
Creating a password with an extra booleanField
I have the following problem. I made a registration password for my site so that a user needs to know this password to be able to register. Also I would like a boolean value linked to it which would determine what kind of rights the user gets with this password. class RegistrationPassword(models.Model): password = ...
[ "\nAlso I would like a boolean value linked to it which would determine what kind of rights the user gets with this password\n\nDon't. Use Groups. That's what they're for.\nIf this \"power user\" is not the superuser, then you need to define a group that has their extra privileges and put power users in this grou...
[ 1, 0, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "django_views", "python" ]
stackoverflow_0006744135_django_django_forms_django_models_django_views_python.txt
Q: SQL Alchemy or SQL Object in Bottle Python hi i am a newbie just starting off on bottle.py framework does anyone have a sample CRUD application that we can learn from? secondly which of the two wrappers runs faster in bottle?thanks. A: Here is a simple Wiki with bottle and Elixir (a simpler frontend for SQL Alch...
SQL Alchemy or SQL Object in Bottle Python
hi i am a newbie just starting off on bottle.py framework does anyone have a sample CRUD application that we can learn from? secondly which of the two wrappers runs faster in bottle?thanks.
[ "Here is a simple Wiki with bottle and Elixir (a simpler frontend for SQL Alchemy):\nhttps://bitbucket.org/ms4py/bottle-wiki \n" ]
[ 1 ]
[]
[]
[ "bottle", "python", "sql", "sqlalchemy", "sqlobject" ]
stackoverflow_0006742933_bottle_python_sql_sqlalchemy_sqlobject.txt
Q: Is there a built in python function to escape a string of unicode characters into unicode escape sequences "\uXXXX\uXXXX\uXXXX"? Like repr(), except converting into \uXXXX instead of \x00 *edited title A: repr() works fine on Unicode strings. For printable ASCII characters, it will print the character, and for...
Is there a built in python function to escape a string of unicode characters into unicode escape sequences "\uXXXX\uXXXX\uXXXX"?
Like repr(), except converting into \uXXXX instead of \x00 *edited title
[ "repr() works fine on Unicode strings. For printable ASCII characters, it will print the character, and for unprintable characters, it will print the Unicode escape sequence.\n" ]
[ 2 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0006745521_python_unicode.txt
Q: Controls are not clickable in my collapsible pane (wxPython) I got a problem with my collapsible pane. The expand/collapse functionality works. But I can not click on my expanded buttons or textfields. The pane shows my content but it is not clickable. I work with explicit position-coordinates?(But I did it on pur...
Controls are not clickable in my collapsible pane (wxPython)
I got a problem with my collapsible pane. The expand/collapse functionality works. But I can not click on my expanded buttons or textfields. The pane shows my content but it is not clickable. I work with explicit position-coordinates?(But I did it on purpose.) Is that the reason? Here an example: (You will see the exp...
[ "I think the parent parameter is incorrect.\nEdit this line:\nsubpanel = wxPanel(self, 0) \n\nin\nsubpanel = wxPanel(self.GetPane(), 0) \n\nand it will work ;)\n" ]
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006744562_python_wxpython.txt
Q: Can you use bit shift operations in a 'for-loop'? I have the following C for loop using bit shifts, that I want to reimplement in python. n = 64 for(int stride = n>>1; stride >0; stride >>=1) {... So wow would this loop look in python? I know that n>>1 stands for division by 2, but I find it hard to model tha...
Can you use bit shift operations in a 'for-loop'?
I have the following C for loop using bit shifts, that I want to reimplement in python. n = 64 for(int stride = n>>1; stride >0; stride >>=1) {... So wow would this loop look in python? I know that n>>1 stands for division by 2, but I find it hard to model that with range().
[ "Think simpler:\n>>> n = 64\n>>> while n:\n... print n\n... n = n >> 1\n...\n64\n32\n16\n8\n4\n2\n1\n\n", "Amadan's answer is spot on.\nIf you use this pattern a lot, I'd extract this into a simple generator function to be reused in for-loops:\n>>> def strider(n):\n... stride = n >> 1\n... while s...
[ 5, 5, 3, 1, 0, 0 ]
[ "How about using a logarithm?\nfor i in range(int(math.log(n, 2)), -1, -1):\n # stride is 2**i\n\n", "Well, closest is to use itertools module:\n>>> from itertools import takewhile, imap, count\n>>> n = 64\n>>> for i in takewhile(bool, imap(lambda x:n >> x, count(1))):\n... print i\n... \n32\n16\n8\n4\n2\n...
[ -1, -2 ]
[ "python" ]
stackoverflow_0006745555_python.txt
Q: issue installing python modules on mac 10.6.8 with xcode 4 ive had this issue with PIL and reportlab so far. the issue is that the install fails with error: command 'gcc-4.2' failed with exit status 1 i've found a fix, in this document paikialog question is, why does the ARCHFLAGS="-arch i386 -arch x86_64" ...
issue installing python modules on mac 10.6.8 with xcode 4
ive had this issue with PIL and reportlab so far. the issue is that the install fails with error: command 'gcc-4.2' failed with exit status 1 i've found a fix, in this document paikialog question is, why does the ARCHFLAGS="-arch i386 -arch x86_64" fix the issue? whats it doing? and how can i force that globally...
[ "The explanation is here. You could avoid the problem by installing Xcode 3 instead of Xcode 4. Or, better, you can avoid the problem by installing another Python instance that does not include the PPC arch; a good choice is the current Python 2.7.2 64-/32-bit installer from python.org.\n", "I suggest using Mac...
[ 1, 0 ]
[]
[]
[ "macos", "python", "python_imaging_library", "reportlab", "xcode4" ]
stackoverflow_0006739215_macos_python_python_imaging_library_reportlab_xcode4.txt
Q: Get windows/system folder location in Python How would I go about getting the Windows/System folder paths in python? I need to be able to read from an INI that gets written to the Windows directory. A: Use the environment variable %WINDIR%. import os winpath = os.environ['WINDIR'] + "\\System\\" inifile = open...
Get windows/system folder location in Python
How would I go about getting the Windows/System folder paths in python? I need to be able to read from an INI that gets written to the Windows directory.
[ "Use the environment variable %WINDIR%. \nimport os\nwinpath = os.environ['WINDIR'] + \"\\\\System\\\\\"\ninifile = open(winpath + filename)\n\n" ]
[ 8 ]
[]
[]
[ "path", "python", "system", "windows" ]
stackoverflow_0006745794_path_python_system_windows.txt
Q: Django settings don't load on other views.py manager.py runfcgi host=127.0.0.1 port=9992 daemonize=false then, when i start nginx as webserver, i get an error. settings.py from lib import rpc rpc.backend = ARPCClient({xxxxxx}) asite/views.py from lib import rpc AttributeError at / 'rpc' object has no attribu...
Django settings don't load on other views.py
manager.py runfcgi host=127.0.0.1 port=9992 daemonize=false then, when i start nginx as webserver, i get an error. settings.py from lib import rpc rpc.backend = ARPCClient({xxxxxx}) asite/views.py from lib import rpc AttributeError at / 'rpc' object has no attribute 'backend'
[ "it seems that you don't have the import statement for the settings\nfrom settings import *\n\nor substitute * with rpc.backend if you need only that.\n" ]
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006746296_django_python.txt
Q: Error while installing dependencies for PyGTK on Mac OS 10.6.3 I tried to install the following dependencies for PyGTK 2.16.0 (the Python GIMP Tool Kit) on Mac OS 10.6.3: glib 2.25.5 gettext-0.18 libiconv-1.13.1 When I tried to install glib, I got the following error message: gconvert.c:55:2: error: #error GNU l...
Error while installing dependencies for PyGTK on Mac OS 10.6.3
I tried to install the following dependencies for PyGTK 2.16.0 (the Python GIMP Tool Kit) on Mac OS 10.6.3: glib 2.25.5 gettext-0.18 libiconv-1.13.1 When I tried to install glib, I got the following error message: gconvert.c:55:2: error: #error GNU libiconv not in use but included iconv.h is from libiconv The libico...
[ "Though it is an old question, still want to share the solution that worked for me.\nNavigate to the ‘glib’ folder (just plain glib, the one INSIDE of the main glib source folder), and open ‘gconvert.c’ with your favorite editor.\n#if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)\n#error GNU libiconv in use b...
[ 2, 0, 0, -1 ]
[]
[]
[ "gettext", "glib", "macos", "pygtk", "python" ]
stackoverflow_0002842425_gettext_glib_macos_pygtk_python.txt
Q: A property's `fdel` method is not invoked when `__delattr__` is overridden I have a class like this, in which I have declared a property x, and overridden __delattr__: class B(object): def __init__(self, x): self._x = x def _get_x(self): return self._x def _set_x(self, x): self....
A property's `fdel` method is not invoked when `__delattr__` is overridden
I have a class like this, in which I have declared a property x, and overridden __delattr__: class B(object): def __init__(self, x): self._x = x def _get_x(self): return self._x def _set_x(self, x): self._x = x def _del_x(self): print '_del_x' x = property(_get_x, _s...
[ "_del_x is called from the default __del_attr__. But since you have overridden __del_attr__, the onus is on you to call _del_x from inside your __del_attr__.\n", "You have to call the __delattr__ of your ancestor to achieve this correctly.\nclass B(object): \n .....\n\n def __delattr__(self, name):\n ...
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006745390_python.txt
Q: How to get kernel version by using kernel name (not current kernel) Simply I want to clean older kernel's modules. It's "uname -r" but I need to get such information for all kernels with Python (I already know their names and can clean kernel files, initramfs and System.map). if that is possible ... Thank you. A:...
How to get kernel version by using kernel name (not current kernel)
Simply I want to clean older kernel's modules. It's "uname -r" but I need to get such information for all kernels with Python (I already know their names and can clean kernel files, initramfs and System.map). if that is possible ... Thank you.
[ "The uname command reports on the running kernel, so it won't help you. But the modules are all stored under /lib/modules. The following program can clean them all out.\n#!/usr/bin/python2\n\nimport os\nimport shutil\n\nmoddirs = os.listdir(\"/lib/modules\")\nmoddirs.remove(os.uname()[2])\n\nfor d in moddirs:\n ...
[ 3, 0, 0, 0 ]
[]
[]
[ "gentoo", "kernel", "linux", "python" ]
stackoverflow_0006746614_gentoo_kernel_linux_python.txt
Q: Using XLRD module and Python to determine cell font style (italics or not) I'm trying to parse data in an excel spreadsheet using XLRD to determine which cell values are italicized. This information will be used to set a flag as to whether the value is an estimated or reported value. Below is an example of the dat...
Using XLRD module and Python to determine cell font style (italics or not)
I'm trying to parse data in an excel spreadsheet using XLRD to determine which cell values are italicized. This information will be used to set a flag as to whether the value is an estimated or reported value. Below is an example of the data: owner_name year Jan Feb Mar Apr May Jun J...
[ "My solution here was based on a class written by 'timmorgan' which can be found here. The class requires that the excel document you wish to act upon be open. You then create the excel document object and then call the 'get_range' method which returns a range object. This range object can then be used to get at fo...
[ 1, 0 ]
[]
[]
[ "python", "xlrd" ]
stackoverflow_0006735845_python_xlrd.txt
Q: how to check for platform incompatible folder (file) names in python I would like to be able to check from python if a given string could be a valid cross platform folder name - below is the concrete problem I ran into (folder name ending in .), but I'm sure there are some more special cases (e.g.: con, etc.). Is ...
how to check for platform incompatible folder (file) names in python
I would like to be able to check from python if a given string could be a valid cross platform folder name - below is the concrete problem I ran into (folder name ending in .), but I'm sure there are some more special cases (e.g.: con, etc.). Is there a library for this? From python (3.2) I created a folder on Windows...
[ "\nDo not end a file or directory name with a space or a period. Although\n the underlying file system may support such names, the Windows shell\n and user interface does not.\n\nhttp://msdn.microsoft.com/en-us/library/aa365247.aspx#naming_conventions\nThat page will give you information about other illegal names...
[ 2, 2 ]
[]
[]
[ "cross_platform", "filesystems", "python", "validation", "windows" ]
stackoverflow_0006745097_cross_platform_filesystems_python_validation_windows.txt
Q: Causes of a delayed Python sched execution We are using the sched module in Python 2.6 to run a function every 60 seconds. Each call issues the sched.enter() function after executing with a delay of 60 and priority of 1. This has been working fine. However, we have found a situation when the next execution of the ...
Causes of a delayed Python sched execution
We are using the sched module in Python 2.6 to run a function every 60 seconds. Each call issues the sched.enter() function after executing with a delay of 60 and priority of 1. This has been working fine. However, we have found a situation when the next execution of the sched function doesn't happen for several minute...
[ "How long takes the processing that happens before sched.enter is called? I would suggest monitoring this, and maybe taking that processing time into account in the delay parameter of sched.enter. \nThe load of the VM and of the VM host may also be important factors. I've seen performance degradations in some apps ...
[ 0 ]
[]
[]
[ "python", "scheduled_tasks", "virtualization" ]
stackoverflow_0006745801_python_scheduled_tasks_virtualization.txt
Q: Iterating over two text files in python I have 2 text files and I want to iterate over both of them simultaneously. i.e: File1: x1 y1 z1 A,53,45,23 B,65,45,32 File2: x2 y2 z2 A,0.6,0.9,0.4 B,8.6,1.0,2.3 and I want use values from both files simultaneously: e.g: c1 = x1*x2 + y1*y2 + z1*z2 #for first line ...
Iterating over two text files in python
I have 2 text files and I want to iterate over both of them simultaneously. i.e: File1: x1 y1 z1 A,53,45,23 B,65,45,32 File2: x2 y2 z2 A,0.6,0.9,0.4 B,8.6,1.0,2.3 and I want use values from both files simultaneously: e.g: c1 = x1*x2 + y1*y2 + z1*z2 #for first line c2 = x1*x2 + y1*y2 + z1*z2 #for second line ...
[ "You need to treat both files as iterators and zip them. Izip will allow you to read the files in a lazy way:\nfrom itertools import izip\n\nfa=open('file1')\nfb=open('file2')\nfor x,y in izip(fa, fb):\n print x,y\n\nNow that you've got pairs of lines, you should be able to parse them as you need and print out t...
[ 6, 1, 0, 0 ]
[]
[]
[ "iteration", "python", "text_files" ]
stackoverflow_0006745746_iteration_python_text_files.txt
Q: Twisted program and TERM signal I have a simple example: from twisted.internet import utils,reactor def test: utils.getProcessOutput(executable="/bin/sleep",args=["10000"]) reactor.callWhenRunning(test) reactor.run() when I send signal "TERM" to program, "sleep" continues to be carried ...
Twisted program and TERM signal
I have a simple example: from twisted.internet import utils,reactor def test: utils.getProcessOutput(executable="/bin/sleep",args=["10000"]) reactor.callWhenRunning(test) reactor.run() when I send signal "TERM" to program, "sleep" continues to be carried out, when I press Ctrl-C on keyboard ...
[ "Ctrl-C sends SIGINT to the entire foreground process group. That means it gets send to your Twisted program and to the sleep child process.\nIf you want to kill the sleep process whenever the Python process is going to exit, then you may want a before shutdown trigger:\ndef killSleep():\n # Do it, somehow\n\nr...
[ 4 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0006743866_python_twisted.txt
Q: Combination of all possible cases of a string I am trying to create a program to generate all possible capitalization cases of a string in python. For example, given 'abcedfghij', I want a program to generate: Abcdefghij ABcdef.. . . aBcdef.. . ABCDEFGHIJ And so on. I am trying to find a quick way to do it, but I ...
Combination of all possible cases of a string
I am trying to create a program to generate all possible capitalization cases of a string in python. For example, given 'abcedfghij', I want a program to generate: Abcdefghij ABcdef.. . . aBcdef.. . ABCDEFGHIJ And so on. I am trying to find a quick way to do it, but I don't know where to start.
[ "Similar to Dan's solution, but much simpler:\n>>> import itertools\n>>> def cc(s):\n... return (''.join(t) for t in itertools.product(*zip(s.lower(), s.upper())))\n...\n>>> print list(cc('dan'))\n\n['dan', 'daN', 'dAn', 'dAN', 'Dan', 'DaN', 'DAn', 'DAN']\n", "from itertools import product, izip\ndef Cc(s):\n...
[ 10, 7, 0 ]
[]
[]
[ "permutation", "python", "string" ]
stackoverflow_0006747123_permutation_python_string.txt
Q: Cannot execute custom Selenium assert function from user-extensions.js file, when running Python RC against Selenium server I'm trying to export a Selenium script to Python from the Selenium IDE. I am using a few user-extension.js functions though (which are working in Selenium IDE). After exporting to Python, the...
Cannot execute custom Selenium assert function from user-extensions.js file, when running Python RC against Selenium server
I'm trying to export a Selenium script to Python from the Selenium IDE. I am using a few user-extension.js functions though (which are working in Selenium IDE). After exporting to Python, the generated script looks like this: from selenium import selenium import unittest, time, re class new_selenium_test(unittest.Test...
[ "You need to rewrite your custom JavaScript functions in Python, as described here:\nhttp://groups.google.com/group/selenium-users/browse_thread/thread/e927dad7e6cb2944/1712b997934cece5\nIt can't connect the Python object to your custom JS, so it leaves that comment there to remind you to implement it in Python.\n"...
[ 0 ]
[]
[]
[ "attributeerror", "python", "selenium", "selenium_ide", "user_extensions.js" ]
stackoverflow_0006747441_attributeerror_python_selenium_selenium_ide_user_extensions.js.txt
Q: Attempting to add a simple image into a label Using a Tkinter tutorial site -as supplied by school-, I attempted to add a simple Paint-drawn gif into a Label on my Python program. mainframe = ttk.Frame(sub, padding="3 3 12 12") mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weigh...
Attempting to add a simple image into a label
Using a Tkinter tutorial site -as supplied by school-, I attempted to add a simple Paint-drawn gif into a Label on my Python program. mainframe = ttk.Frame(sub, padding="3 3 12 12") mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) mainframe[...
[ "When you do \nlabel = ttk.Label(mainframe).grid(column=1, row=1)\n\nit's storing the output of Label().grid() in label, not the new Label instance created by Label().\nYou need to do\nlabel = ttk.Label(mainframe)\nlabel.grid(column=1, row=1)\n\nif you want to both store the Label instance in label and set the grid...
[ 2 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006747626_python_tkinter.txt
Q: attribute error : str has no attribute remove I am sorry the last time I had used this website was my first time and I did not indent my code and all. But this time I tried to do so. I hope the code is understandable. I am working on a python program syllabifier.py written by Joshua Tauberer available from https:...
attribute error : str has no attribute remove
I am sorry the last time I had used this website was my first time and I did not indent my code and all. But this time I tried to do so. I hope the code is understandable. I am working on a python program syllabifier.py written by Joshua Tauberer available from https://p2tk.svn.sourceforge.net/svnrooot/p2tk/python/syl...
[ "phoneme = phoneme.replace(\"pau\", \"\")\n\n", "def syllabify(language, text) :\n #These lines will take any list of phonemes or string of phonemes\n #and strip all of the whitespace and 'pau's\n #and won't return any empty phonemes\n if type(text) is not str:\n text = ' '.join(text)\n text...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006747657_python.txt
Q: Autocompletion in Django + pydev I am trying to make pydev autocomplete my variables from model data, but for now I have been unable to do it. I have configured the PYTHONPATH in Window->Preferences->PyDev->Interpreter - Python to include both the django folder and my project folder. Then if I have a model like ...
Autocompletion in Django + pydev
I am trying to make pydev autocomplete my variables from model data, but for now I have been unable to do it. I have configured the PYTHONPATH in Window->Preferences->PyDev->Interpreter - Python to include both the django folder and my project folder. Then if I have a model like this: class Team(models.Model): name...
[ "Have you added your site packages and your project folder to the PyDev Pythonpath?\nRight click on your project folder and...\nPyDev > Set as PyDev project\nRight click again and...\nProperties > PyDev - PYTHONPATH\nClick on External Libraries.\nClick on Add source folder.\nChoose your project folder and also your...
[ 2, 0 ]
[]
[]
[ "autocomplete", "django", "eclipse", "pydev", "python" ]
stackoverflow_0006740847_autocomplete_django_eclipse_pydev_python.txt
Q: Python doesn't write all entries from list I'm exploring python and tried to sort all files from a directory by last modified and then write the list into a txt file. import time import os i=1 a="path" def getfiles(dirpat): b = [s for s in os.listdir(dirpat) if os.path.isf...
Python doesn't write all entries from list
I'm exploring python and tried to sort all files from a directory by last modified and then write the list into a txt file. import time import os i=1 a="path" def getfiles(dirpat): b = [s for s in os.listdir(dirpat) if os.path.isfile(os.path.join(dirpat, s))] b.sort(key...
[ "Correct the join(), e.g:\n'\\n'.join(str(path) for path in list)\n\nAnd please rename the \"list\" variable, because list is a built-in data type in Python. \n", "import os, os.path\n\na=\"path\"\n\ndef getfiles(dirpat):\n b = [s for s in os.listdir(dirpat)\n if os.path.isfile(os.path.join(dirpat, s))...
[ 4, 3, 2, 2, 2 ]
[]
[]
[ "file", "join", "list", "python" ]
stackoverflow_0006747921_file_join_list_python.txt
Q: Shelve module in Python 3.1.1 I'm new to Python and learning through the O'Reilly "Learning Python" series. I'm stuck on a shelve example and can't figure out why the program doesn't work. I'm trying to build some sample data and then load it into a shelve file. The weird thing is that it works when I type it i...
Shelve module in Python 3.1.1
I'm new to Python and learning through the O'Reilly "Learning Python" series. I'm stuck on a shelve example and can't figure out why the program doesn't work. I'm trying to build some sample data and then load it into a shelve file. The weird thing is that it works when I type it into the IDLE shell but not when I t...
[ "Rename your module to something else than shelve.py — you're importing yourself.\n" ]
[ 7 ]
[]
[]
[ "python", "shelve" ]
stackoverflow_0006748096_python_shelve.txt
Q: Selecting specific columns with generative selects I'm learning SQL alchemy and going through the Expression Language Tutorial. I really like the generative selects because I can use table reflection and then easily query the table with Table class methods. This is what I'm doing now to do what I want. from sqlalc...
Selecting specific columns with generative selects
I'm learning SQL alchemy and going through the Expression Language Tutorial. I really like the generative selects because I can use table reflection and then easily query the table with Table class methods. This is what I'm doing now to do what I want. from sqlalchemy import Table, create_engine, MetaData engine = crea...
[ "Read more on the select() in the documentation, especially in respect to first two parameters.\nBut the following should be the right direction for you to work:\nfrom sqlalchemy.sql import select, and_, or_, not_\n# ...\nquery = select(# what to select (tables or columns)\n [table.c.column1, table.c....
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0006747307_python_sqlalchemy.txt
Q: Python bind cmd.exe to port How do I bind cmd.exe onto a port in Python? I want to do the same thing as Netcats "-e" argument. So the equivilent in Netcat would be: netcat -l -p 8080 -e cmd.exe But I want to code it myself in Python, without using Netcat. So how is this done? Are there any functions/modules that ...
Python bind cmd.exe to port
How do I bind cmd.exe onto a port in Python? I want to do the same thing as Netcats "-e" argument. So the equivilent in Netcat would be: netcat -l -p 8080 -e cmd.exe But I want to code it myself in Python, without using Netcat. So how is this done? Are there any functions/modules that can do this? How can I convert th...
[ "\nListen to a port \nRead the input \nPipe it to cmd.exe \nSend back the output\n\n", "Something along the lines of this, except you would have to change it into running on Windows (this example runs fine on Linux):\n#!/usr/bin/env python\n\nimport socket\nimport subprocess\n\ns = socket.socket(socket.AF_INET)\n...
[ 0, 0 ]
[]
[]
[ "netcat", "python", "sockets" ]
stackoverflow_0006748176_netcat_python_sockets.txt
Q: web.py printing the html code on Apache server I have web.py configured for my Apache server by installing flups. However when I go to my application, the html code is printed instead of the html page. (See below). Content-Type: text/html <HTML><HEAD><TITLE>Login Details</TITLE></HEAD><BODY>.......</BODY></HTML>...
web.py printing the html code on Apache server
I have web.py configured for my Apache server by installing flups. However when I go to my application, the html code is printed instead of the html page. (See below). Content-Type: text/html <HTML><HEAD><TITLE>Login Details</TITLE></HEAD><BODY>.......</BODY></HTML> I created another file Test.py in the same directo...
[ "The issue was in the line\ninit=\"Content-Type: text/html\\n\\n\"\nThat was the incorrect way to pass the header in web.py. The issue was resolved after replacing it with \nweb.header('Content-Type','text/html; charset=utf-8', unique=True)\n" ]
[ 1 ]
[]
[]
[ "apache", "python", "web.py" ]
stackoverflow_0006743001_apache_python_web.py.txt
Q: Problem parsing files when extracting filenames os.listdir() as If I use filename = argv[n] from a windows command line, the extract() function below seems to work okay. If I instead use the list of files names from the list(dir), which uses the os.listdir() built-in function to extract the filenames from the work...
Problem parsing files when extracting filenames os.listdir() as
If I use filename = argv[n] from a windows command line, the extract() function below seems to work okay. If I instead use the list of files names from the list(dir), which uses the os.listdir() built-in function to extract the filenames from the working directory, then the extract() function fails. The input_file.read...
[ "You've redefined list! When you try to do date = list(date_match[0]), you're calling your list function, not the builtin list function. Rename the list function and it should work fine.\n" ]
[ 4 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0006748632_python_windows.txt
Q: Python: Questions about subprocess, piped data, and multiprocessing I have a Python program that uses Popen to call a test C++ program. The test C++ program simply writes 0-99999 to stdout. The Python program has two functions that should be run as seperate processes. One function, funcA, should launch the C++ ...
Python: Questions about subprocess, piped data, and multiprocessing
I have a Python program that uses Popen to call a test C++ program. The test C++ program simply writes 0-99999 to stdout. The Python program has two functions that should be run as seperate processes. One function, funcA, should launch the C++ program, read the integers from the stdout pipe, and insert those integer...
[ "Use the communicate method of Popen, like this:\nhandle = subprocess.Popen(['../C++/C++.exe'], stdout=subprocess.PIPE)\nout, err = handle.communicate() # this will block until the underlying subprocess exits\n\nAs for the queue, the data structure defines methods to query said queue if it is full or empty. Util...
[ 2, 1 ]
[]
[]
[ "multiprocessing", "pipe", "popen", "python", "subprocess" ]
stackoverflow_0006528107_multiprocessing_pipe_popen_python_subprocess.txt
Q: Understanding timedelta Given the python code below, please help me understand what is happening there. start_time = time.time() time.sleep(42) end_time = time.time() uptime = end_time - start_time human_uptime = str(datetime.timedelta(seconds=int(uptime))) So I get the difference between start time and end tim...
Understanding timedelta
Given the python code below, please help me understand what is happening there. start_time = time.time() time.sleep(42) end_time = time.time() uptime = end_time - start_time human_uptime = str(datetime.timedelta(seconds=int(uptime))) So I get the difference between start time and end time, on line 5 I round up the d...
[ "Because timedelta is defined like:\nclass datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])\n\nAll arguments are optional and default to 0.\nYou can easily say \"Three days and four milliseconds\" with optional arguments that way.\n>>> datetime.timedelta(days=3, mil...
[ 117, 13 ]
[]
[]
[ "python", "timedelta" ]
stackoverflow_0006749294_python_timedelta.txt
Q: Path environment variables in Python and Mac OS X when using subprocess.call Python (2.6.6 -- EPD 6.3-1 (32-bit)) can not find a binary executable when using call(cmmd, shell=True) On Mac OS 10.6.8, started from Eclipse/Pydev, and returns that sh could not find the executable. Running print os.environ['PATH'] ...
Path environment variables in Python and Mac OS X when using subprocess.call
Python (2.6.6 -- EPD 6.3-1 (32-bit)) can not find a binary executable when using call(cmmd, shell=True) On Mac OS 10.6.8, started from Eclipse/Pydev, and returns that sh could not find the executable. Running print os.environ['PATH'] returns the default paths: /usr/bin:/bin:/usr/sbin:/sbin Now, running this execut...
[ "There is a difference between a login shell and a non-login shell. When run by python launched from Eclipse, your shell will start as a non-login shell, which will NOT load the ~/.profile. This article has the details. So you need to make sure os.environ has the directory where your executable lives in it befor...
[ 2 ]
[]
[]
[ "macos", "operating_system", "path", "python" ]
stackoverflow_0006749284_macos_operating_system_path_python.txt
Q: Creating Outlook Tasks with Python Is there a way using Python to automate adding Tasks to Outlook (2007 or 2010)? I see there is a way to create Outlook Invites through pywin32, however, I'm not sure about the parameters required, and I couldn't find any relevant docs that outline the parameter/value requirement...
Creating Outlook Tasks with Python
Is there a way using Python to automate adding Tasks to Outlook (2007 or 2010)? I see there is a way to create Outlook Invites through pywin32, however, I'm not sure about the parameters required, and I couldn't find any relevant docs that outline the parameter/value requirements (although I'm sure they're out there)....
[ "I found a snippet but I am not sure if that really works because I have not installed Outlook. And it requires a Taskcoach task file. But maybe you will get new ideas and some inspiration through this example.\n" ]
[ 1 ]
[]
[]
[ "automation", "ms_office", "outlook", "python" ]
stackoverflow_0006749143_automation_ms_office_outlook_python.txt
Q: merging pdf files with pypdf I am writing a script that parses an internet site (maya.tase.co.il) for links, downloads pdf file and merges them. It works mostly, but merging gives me different kinds of errors depending on the file. I cant seem to figure out why. I cut out the relevant code and built a test only fo...
merging pdf files with pypdf
I am writing a script that parses an internet site (maya.tase.co.il) for links, downloads pdf file and merges them. It works mostly, but merging gives me different kinds of errors depending on the file. I cant seem to figure out why. I cut out the relevant code and built a test only for two specific files that are caus...
[ "I once wrote a complex PDF generation/merging stuff which I have now open-sourced.\nYou can have a look at it: https://github.com/becomingGuru/nikecup/blob/master/reg/models.py#L71\ndef merge_pdf(self):\n from pyPdf import PdfFileReader,PdfFileWriter\n\n pdf_file = file_names['main_pdf']%settings.MEDIA_ROOT\...
[ 1, 0 ]
[]
[]
[ "pdf", "pypdf", "python" ]
stackoverflow_0006737409_pdf_pypdf_python.txt
Q: python utf-8 problem this is my script # -*- coding: utf-8 -*- from BeautifulSoup import BeautifulSoup import urllib2 res = urllib2.urlopen('http://tazeh.net') html = res.read() soup = BeautifulSoup(''.join(html)) title = soup.findAll('title') print title when im am running this script in terminal i get wrong...
python utf-8 problem
this is my script # -*- coding: utf-8 -*- from BeautifulSoup import BeautifulSoup import urllib2 res = urllib2.urlopen('http://tazeh.net') html = res.read() soup = BeautifulSoup(''.join(html)) title = soup.findAll('title') print title when im am running this script in terminal i get wronged text like that $ python...
[ "if i add (like one of the comments suggested doing in less useful place):\nhtml = html[:10000].decode(\"utf-8\")\n\n(the slice is because decode failed at an offset further into the page)\nbefore:\nsoup = BeautifulSoup(html)\n\nit prints:\n[<title>پایگاه خبری تحلیلی تازه</title>]\n\n", "''.join(html) is needless...
[ 3, 1 ]
[]
[]
[ "persian", "python", "utf_8" ]
stackoverflow_0006749890_persian_python_utf_8.txt
Q: Problems with PyQT4 Library I installed PyQT4 library from http://www.riverbankcomputing.co.uk/software/pyqt/download( Binary Packages section). I have Python 2.7. I'm trying to get on my PyQT4 and It didnt work! I tried: import qt import pyqt4 import pyqt And it didnt found! What would do? A: Try from PyQt4 imp...
Problems with PyQT4 Library
I installed PyQT4 library from http://www.riverbankcomputing.co.uk/software/pyqt/download( Binary Packages section). I have Python 2.7. I'm trying to get on my PyQT4 and It didnt work! I tried: import qt import pyqt4 import pyqt And it didnt found! What would do?
[ "Try\nfrom PyQt4 import QtCore, QtGui\n\n", "If you have more than one python installation maybe PyQt got installed onto one you aren't using. Anyway, if you installed PyQt4 there must be a directory with that name somewhere in your drive. Do a search and find it. It should be under one of your python installatio...
[ 1, 1 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0006748059_pyqt4_python.txt
Q: Top 5 Folders Consuming The Most Space? My hard drive is full. What is the easiest way to find out the TOP 5 FOLDERS that consume the most disk space? A python solution would be greatly appreciated. I use Ubuntu Linux. A: Not a python solution, but one using the shell is to use du. To list the number of kilobyte...
Top 5 Folders Consuming The Most Space?
My hard drive is full. What is the easiest way to find out the TOP 5 FOLDERS that consume the most disk space? A python solution would be greatly appreciated. I use Ubuntu Linux.
[ "Not a python solution, but one using the shell is to use du. To list the number of kilobytes in each folder under /var/ then sort by size with the largest one last, run the following in a shell prompt: \ndu -k --max-depth 1 /var/|sort -n\n\nIf you want this under python, use the always super-handy subprocess modul...
[ 3, 2, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006748791_python.txt
Q: Import a library that imports a GPL library? So I am importing a library (reportlab), which is licensed BSD, but itself uses some libraries that are licensed GPL. My question is, if I import reportlab into python - do I have to abide by BSD or GPL license? A: IANAL. You have to abide by the licenses of all the p...
Import a library that imports a GPL library?
So I am importing a library (reportlab), which is licensed BSD, but itself uses some libraries that are licensed GPL. My question is, if I import reportlab into python - do I have to abide by BSD or GPL license?
[ "IANAL. You have to abide by the licenses of all the packages you're using. \nHowever, most would say if you only use the public API of those libraries, and they could theoretically be swapped out for other libraries implementing the same API, your code does not fall under the GPL, only any modifications you make t...
[ 8, 3, 0 ]
[]
[]
[ "licensing", "python" ]
stackoverflow_0006748333_licensing_python.txt
Q: Python, import a modulo from a father directory I want to know how import a file that is one level up. I read in google this: >>> sys.path.append("../") But I dont like it and i hope there are a better solution A: Another option, if what you are writing is part of a package, is to use relative imports like so: ...
Python, import a modulo from a father directory
I want to know how import a file that is one level up. I read in google this: >>> sys.path.append("../") But I dont like it and i hope there are a better solution
[ "Another option, if what you are writing is part of a package, is to use relative imports like so:\nfrom .. import foo\n\nwhere foo is the name of the module you're trying to import.\nSimilarly, if you've got another module in the current directory, you can use:\nfrom . import bar\n\nSadly (or perhaps not so sadly)...
[ 3, 0 ]
[]
[]
[ "import", "module", "python" ]
stackoverflow_0006749000_import_module_python.txt
Q: Access std::complex<> from gdb python macro I'm trying to write a python script that evaluates a vector Complex numbers so I can do things like plot it via matplotlib. Python code below with comment where code breaks: import sys import gdb import matplotlib.pyplot as plt class Plotter (gdb.Command): """ Plots v...
Access std::complex<> from gdb python macro
I'm trying to write a python script that evaluates a vector Complex numbers so I can do things like plot it via matplotlib. Python code below with comment where code breaks: import sys import gdb import matplotlib.pyplot as plt class Plotter (gdb.Command): """ Plots vector""" # _iterator pulled directly from # /usr/...
[ " try:\n it = self._iterator(val['_M_impl']['_M_start'],\n val['_M_impl']['_M_finish'])\n vector = []\n while(True):\n x = it.next()\n vector.append(complex(x[1])) # doesn't work...\n return\n\n except StopIteration:\n pass\n ...
[ 0 ]
[]
[]
[ "c++", "gdb", "python" ]
stackoverflow_0006751176_c++_gdb_python.txt
Q: How does Django know which location the user is from? I am reading the Django localization documentation:http://docs.djangoproject.com/en/dev/topics/i18n/localization/ Of course, where the user is from determines what "message file" to use. How do I determine where the user is from and what to use? Does it do it a...
How does Django know which location the user is from?
I am reading the Django localization documentation:http://docs.djangoproject.com/en/dev/topics/i18n/localization/ Of course, where the user is from determines what "message file" to use. How do I determine where the user is from and what to use? Does it do it automatically?
[ "You can add Locale middleware to your MIDDLEWARE_CLASSES in settings if you want to enable language selection based on data from the request in Django.\nRead how Django discovers language preference to learn details.\nFrom docs\n\nLocaleMiddleware tries to determine\n the user's language preference by\n followin...
[ 2, 0 ]
[]
[]
[ "django", "localization", "python" ]
stackoverflow_0002877088_django_localization_python.txt