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: foreignkey problem Imagine you have this model: class Category(models.Model): node_id = models.IntegerField(primary_key = True) type_id = models.IntegerField(max_length = 20) parent_id = models.IntegerField(max_length = 20) sort_order = models.IntegerField(max_length = 20) name = mode...
foreignkey problem
Imagine you have this model: class Category(models.Model): node_id = models.IntegerField(primary_key = True) type_id = models.IntegerField(max_length = 20) parent_id = models.IntegerField(max_length = 20) sort_order = models.IntegerField(max_length = 20) name = models.CharField(max_length ...
[ "To filter on fields in a related table, use the double-underscore notation. To get all Category objects where type_id of the related Category_info object is 15, use:\nCategory.objects.filter(node__type_id=15)\n\nDjango will then automagically understand that you're referring to the type_id field on whatever table ...
[ 4, 0, 0 ]
[]
[]
[ "django", "foreign_keys", "python" ]
stackoverflow_0002766637_django_foreign_keys_python.txt
Q: Windows equivalent to this Makefile The advantage of writing a Makefile is that "make" is generally assumed to be present on the various Unices (Linux and Mac primarily). Now I have the following Makefile: PYTHON := python all: e installdeps e: virtualenv --distribute --python=${PYTHON} e installdeps: ...
Windows equivalent to this Makefile
The advantage of writing a Makefile is that "make" is generally assumed to be present on the various Unices (Linux and Mac primarily). Now I have the following Makefile: PYTHON := python all: e installdeps e: virtualenv --distribute --python=${PYTHON} e installdeps: e/bin/python setup.py develop ...
[ "Something simple like that, yes. However, if you'd like to continue to improve that makefile, you might consider just writing the \"makefile\" (rather installation script) in a more portable language. You have to have some assumptions. If its a python project, I'm sure you assume python is installed. So write ...
[ 4 ]
[]
[]
[ "cross_platform", "makefile", "python", "windows" ]
stackoverflow_0002768481_cross_platform_makefile_python_windows.txt
Q: Getting Started with Python: Attribute Error I am new to python and just downloaded it today. I am using it to work on a web spider, so to test it out and make sure everything was working, I downloaded a sample code. Unfortunately, it does not work and gives me the error: "AttributeError: 'MyShell' object has no ...
Getting Started with Python: Attribute Error
I am new to python and just downloaded it today. I am using it to work on a web spider, so to test it out and make sure everything was working, I downloaded a sample code. Unfortunately, it does not work and gives me the error: "AttributeError: 'MyShell' object has no attribute 'loaded' " I am not sure if the code its...
[ "\nAnd what does that error generally\n mean?\n\nAn Attribute in Python is a name belonging to an object - a method or a variable. An AttributeError means that the program tried to use an attribute of an object, but the object did not have the requested attribute.\nFor instance, string objects have the 'upper' att...
[ 6 ]
[ "1) Put code in Try ... Except block. get exception details.\n2) Could you tell StackTrace details means which line # and method thrown error\nAnd also are you able to run other simple python scripts without any error. Means just try to run some sample script etc.\n" ]
[ -1 ]
[ "attributeerror", "chilkat", "python", "web_crawler" ]
stackoverflow_0002767607_attributeerror_chilkat_python_web_crawler.txt
Q: Convert array to CSV/TSV-formated string in Python Python provides csv.DictWriter for outputting CSV to a file. What is the simplest way to output CSV to a string or to stdout? For example, given a 2D array like this: [["a b c", "1,2,3"], ["i \"comma-heart\" you", "i \",heart\" u, too"]] return the following str...
Convert array to CSV/TSV-formated string in Python
Python provides csv.DictWriter for outputting CSV to a file. What is the simplest way to output CSV to a string or to stdout? For example, given a 2D array like this: [["a b c", "1,2,3"], ["i \"comma-heart\" you", "i \",heart\" u, too"]] return the following string: "a b c, \"1, 2, 3\"\n\"i \"\"comma-heart\"\" you\",...
[ "We use StringIO for this\nmyFakeFile = StringIO.StringIO()\nwtr = csv.DictWriter( myFakeFile, headings )\n...\nmyFakeFile.getvalue()\n\nUsually works.\n" ]
[ 5 ]
[]
[]
[ "csv", "python", "string", "text" ]
stackoverflow_0002768810_csv_python_string_text.txt
Q: Dynamic Class Creation in SQLAlchemy We have a need to create SQLAlchemy classes to access multiple external data sources that will increase in number over time. We use the declarative base for our core ORM models and I know we can manually specify new ORM classes using the autoload=True to auto generate the mapp...
Dynamic Class Creation in SQLAlchemy
We have a need to create SQLAlchemy classes to access multiple external data sources that will increase in number over time. We use the declarative base for our core ORM models and I know we can manually specify new ORM classes using the autoload=True to auto generate the mapping. The problem is that we need to be abl...
[ "You can dynamically create MyObject using the 3-argument call to type:\ntype(name, bases, dict)\n\n Return a new type object. This is essentially a dynamic form of the \n class statement... \n\nFor example:\nmydict={'__tablename__':stored['tablename'],\n '__table_args__':{'autoload':True},}\n\nMyObj=t...
[ 33 ]
[]
[]
[ "declarative", "metaclass", "metaprogramming", "python", "sqlalchemy" ]
stackoverflow_0002768607_declarative_metaclass_metaprogramming_python_sqlalchemy.txt
Q: Generating content diffs using SequenceMatcher (Python) I want to generate a diff between to revisions of text (more specifically, Markdown-formatted articles) in Python. I want to format this diff in a manner similar to what Github does. I've looked at difflib and have found that it does what I want. However, the...
Generating content diffs using SequenceMatcher (Python)
I want to generate a diff between to revisions of text (more specifically, Markdown-formatted articles) in Python. I want to format this diff in a manner similar to what Github does. I've looked at difflib and have found that it does what I want. However, the Differ class is too high-level; I would have to parse the di...
[ "SequenceMatcher is actually not that low-level. The most interesting method for you is get_grouped_opcodes. It will return a generator, which generates lists with change descriptions.\nI'll explain it on an example from a random commit on GitHub. Let's say you run SequenceMatcher(None, a, b).get_grouped_opcodes() ...
[ 8 ]
[]
[]
[ "diff", "python" ]
stackoverflow_0002767822_diff_python.txt
Q: Is there something similar to node-git for python? http://github.com/creationix/node-git Reading blog posts from a repository. If not, how would you do it (chaching, ...)? A: Well, there's Dulwich, "a pure-Python implementation of the Git file formats and protocols," and GitPython, which is apparently a wrapper ...
Is there something similar to node-git for python?
http://github.com/creationix/node-git Reading blog posts from a repository. If not, how would you do it (chaching, ...)?
[ "Well, there's Dulwich, \"a pure-Python implementation of the Git file formats and protocols,\" and GitPython, which is apparently a wrapper around the git command line tools.\n" ]
[ 1 ]
[]
[]
[ "git", "python" ]
stackoverflow_0002769233_git_python.txt
Q: Creating a unique key based on file content in python I got many, many files to be uploaded to the server, and I just want a way to avoid duplicates. Thus, generating a unique and small key value from a big string seemed something that a checksum was intended to do, and hashing seemed like the evolution of that. S...
Creating a unique key based on file content in python
I got many, many files to be uploaded to the server, and I just want a way to avoid duplicates. Thus, generating a unique and small key value from a big string seemed something that a checksum was intended to do, and hashing seemed like the evolution of that. So I was going to use hash md5 to do this. But then I read s...
[ "Sticking with MD5 is a good idea. Just to make sure I'd append the file length or number of chunks to your file-hash table.\nYes, there is the possibility that you run into two files that have the same MD5 hash, but that's quite unlikely (if your files are decent sized). Thus adding the number of chunks to your ha...
[ 7, 3, 2 ]
[]
[]
[ "checksum", "cryptography", "hash", "python", "unique_key" ]
stackoverflow_0002769461_checksum_cryptography_hash_python_unique_key.txt
Q: Most elegant way to break CSV columns into separate data structures using Python? I'm trying to pick up Python. As part of the learning process I'm porting a project I wrote in Java to Python. I'm at a section now where I have a list of CSV headers of the form: headers = [a, b, c, d, e, .....] and separate lists ...
Most elegant way to break CSV columns into separate data structures using Python?
I'm trying to pick up Python. As part of the learning process I'm porting a project I wrote in Java to Python. I'm at a section now where I have a list of CSV headers of the form: headers = [a, b, c, d, e, .....] and separate lists of groups that these headers should be broken up into, e.g.: headers_for_list_a = [b, c...
[ "Try the CSV module of Python, in particular the DictReader class.\n", "Not necessary the most pythonic way to achieve the same thing as your code, but this version of your code is somewhat more concise due to the use of generator expressions:\nfrom itertools import izip\n\nfor row in data:\n dict_a = dict((co...
[ 5, 2, 2 ]
[]
[]
[ "csv", "data_structures", "python" ]
stackoverflow_0002768912_csv_data_structures_python.txt
Q: Iterating through String word at a time in Python I have a string buffer of a huge text file. I have to search a given words/phrases in the string buffer. Whats the efficient way to do it ? I tried using re module matches. But As i have a huge text corpus that i have to search through. This is taking large amount...
Iterating through String word at a time in Python
I have a string buffer of a huge text file. I have to search a given words/phrases in the string buffer. Whats the efficient way to do it ? I tried using re module matches. But As i have a huge text corpus that i have to search through. This is taking large amount of time. Given a Dictionary of words and Phrases. I it...
[ "Iterating word-by-word through the contents of a file (the Wizard of Oz from Project Gutenberg, in my case), three different ways:\nfrom __future__ import with_statement\nimport time\nimport re\nfrom cStringIO import StringIO\n\ndef word_iter_std(filename):\n start = time.time()\n with open(filename) as f:\n...
[ 7, 1, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "string", "string_matching" ]
stackoverflow_0002768628_python_string_string_matching.txt
Q: Paginating requests to an API I'm consuming (via urllib/urllib2) an API that returns XML results. The API always returns the total_hit_count for my query, but only allows me to retrieve results in batches of, say, 100 or 1000. The API stipulates I need to specify a start_pos and end_pos for offsetting this, in ord...
Paginating requests to an API
I'm consuming (via urllib/urllib2) an API that returns XML results. The API always returns the total_hit_count for my query, but only allows me to retrieve results in batches of, say, 100 or 1000. The API stipulates I need to specify a start_pos and end_pos for offsetting this, in order to walk through the results. Say...
[ "I'd suggest using\npositions = ((n, n + hits_per_page - 1) for n in xrange(1, total_hits, hits_per_page))\nfor start, end in positions:\n\nand then not worry about whether end exceeds hits_per_page unless the API you're using really cares whether you request something out of range; most will handle this case grace...
[ 1, 1 ]
[]
[]
[ "api", "list_comprehension", "python" ]
stackoverflow_0002769857_api_list_comprehension_python.txt
Q: heterogeneous comparisons in python3 I'm 99+% still using python 2.x, but I'm trying to think ahead to the day when I switch. So, I know that using comparison operators (less/greater than, or equal to) on heterogeneous types that don't have a natural ordering is no longer supported in python3.x -- instead of some ...
heterogeneous comparisons in python3
I'm 99+% still using python 2.x, but I'm trying to think ahead to the day when I switch. So, I know that using comparison operators (less/greater than, or equal to) on heterogeneous types that don't have a natural ordering is no longer supported in python3.x -- instead of some consistent (but arbitrary) result we raise...
[ "Rather than \"fixing\" something the python 3.x community \"fixed\" in the global scope, you may try the approach of enabling your objects/types to sort properly. I'm not as familiar with python 3.x, but I'm sure there still is a __cmp__ method that you could override in a sub-class and fix so that comparisons wo...
[ 0 ]
[]
[]
[ "comparison", "python" ]
stackoverflow_0002769996_comparison_python.txt
Q: Setting timeouts to parse webpages using python lxml I am using python lxml library to parse html pages: import lxml.html # this might run indefinitely page = lxml.html.parse('http://stackoverflow.com/') Is there any way to set timeout for parsing? A: It looks to be using urllib.urlopen as the opener, but the ...
Setting timeouts to parse webpages using python lxml
I am using python lxml library to parse html pages: import lxml.html # this might run indefinitely page = lxml.html.parse('http://stackoverflow.com/') Is there any way to set timeout for parsing?
[ "It looks to be using urllib.urlopen as the opener, but the easiest way to do this would just to modify the default timeout for the socket handler.\nimport socket\ntimeout = 10\nsocket.setdefaulttimeout(timeout)\n\nOf course this is a quick-and-dirty solution.\n" ]
[ 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0002770320_lxml_python.txt
Q: Correctly parsing an ATOM feed I currently have setup a Python script that uses feedparser to read a feed and parse it. However, I have recently come across a problem with the date parsing. The feed I am reading contains <modified>2010-05-05T24:17:54Z</modified> - which comes up in Python as a datetime object - 20...
Correctly parsing an ATOM feed
I currently have setup a Python script that uses feedparser to read a feed and parse it. However, I have recently come across a problem with the date parsing. The feed I am reading contains <modified>2010-05-05T24:17:54Z</modified> - which comes up in Python as a datetime object - 2010-05-06 00:17:54. Notice the discre...
[ "There are some interesting special cases in the rfc here (https://www.rfc-editor.org/rfc/rfc3339), however, typically its for the 00:00:60 vs 00:00:59 to allow for leap seconds. It may be though that that is legal. My guess is that its doing the \"right thing\". In all honesty, date/time things get really messy...
[ 1, 0 ]
[]
[]
[ "atom_feed", "feedparser", "python" ]
stackoverflow_0002769955_atom_feed_feedparser_python.txt
Q: Adding variably named fields to Python classes I have a python class, and I need to add an arbitrary number of arbitrarily long lists to it. The names of the lists I need to add are also arbitrary. For example, in PHP, I would do this: class MyClass { } $c = new MyClass(); $n = "hello" $c.$n = array(1, 2, 3); H...
Adding variably named fields to Python classes
I have a python class, and I need to add an arbitrary number of arbitrarily long lists to it. The names of the lists I need to add are also arbitrary. For example, in PHP, I would do this: class MyClass { } $c = new MyClass(); $n = "hello" $c.$n = array(1, 2, 3); How do I do this in Python? I'm also wondering if thi...
[ "Use setattr.\n>>> class A(object):\n... pass\n... \n>>> a = A()\n>>> f = 'field'\n>>> setattr(a, f, 42)\n>>> a.field\n42\n\n", "I would write it the simplest way for now, and profile next, and then look to optimize specific elements. \nLet's remember the KISS principle.\n" ]
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002770629_python.txt
Q: python regex of a date in some text, enclosed by two keywords This is Part 2 of this question and thanks very much for David's answer. What if I need to extract dates which are bounded by two keywords? Example: text = "One 09 Jun 2011 Two 10 Dec 2012 Three 15 Jan 2015 End" Case 1 bounding keyboards: "One" and "Th...
python regex of a date in some text, enclosed by two keywords
This is Part 2 of this question and thanks very much for David's answer. What if I need to extract dates which are bounded by two keywords? Example: text = "One 09 Jun 2011 Two 10 Dec 2012 Three 15 Jan 2015 End" Case 1 bounding keyboards: "One" and "Three" Result expected: ['09 Jun 2011', '10 Dec 2012'] Case 2 boundi...
[ "You can do this with two regular expressions. One regex gets the text between the two keywords. The other regex extracts the dates.\nmatch = re.search(r\"\\bOne\\b(.*?)\\bThree\\b\", text, re.DOTALL)\nif match:\n betweenwords = match.group(1)\n dates = re.findall(r'\\d\\d (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug...
[ 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002770260_python_regex.txt
Q: entity set expansion python Do you know of any existing implementation in any language (preferably python) of any entity set expansion algorithms, such that the one from Google sets ? ( http://labs.google.com/sets ) I couldn't find any library implementing such algorithms and I'd like to play with some of those to...
entity set expansion python
Do you know of any existing implementation in any language (preferably python) of any entity set expansion algorithms, such that the one from Google sets ? ( http://labs.google.com/sets ) I couldn't find any library implementing such algorithms and I'd like to play with some of those to see how they would perform on so...
[ "I'm not aware of any ready to use open source libraries that implement the sort of clustering on demand of named entities provided by Google Sets. However, there are a few academic papers that describe in detail how to build similar systems, e.g.:\n\nLanguage-Independent Set Expansion of Named Entities using the W...
[ 2 ]
[]
[]
[ "information_retrieval", "java", "nlp", "python" ]
stackoverflow_0002761678_information_retrieval_java_nlp_python.txt
Q: Django urls on json request When making a django request through json as, var info=id + "##" +name+"##" $.post("/supervise/activity/" + info ,[] , function Handler(data,arr) { } In urls.py (r'^activity/(?P<info>\d+)/$, 'activity'), In views, def activity(request,info): print info The request d...
Django urls on json request
When making a django request through json as, var info=id + "##" +name+"##" $.post("/supervise/activity/" + info ,[] , function Handler(data,arr) { } In urls.py (r'^activity/(?P<info>\d+)/$, 'activity'), In views, def activity(request,info): print info The request does not go through.info is a stri...
[ "^activity/(?P<info>\\d+)/$ will only match something like 'activity/42/' and the number (in this case 42) will be info.\nIf you appended '##name##' to the url, it will not be recognized.\n" ]
[ 4 ]
[]
[]
[ "django", "django_urls", "django_views", "python" ]
stackoverflow_0002771267_django_django_urls_django_views_python.txt
Q: boost::python string-convertible properties I have a C++ class, which has the following methods: class Bar { ... const Foo& getFoo() const; void setFoo(const Foo&); }; where class Foo is convertible to std::string (it has an implicit constructor from std::string and an std::string cast operator). I define...
boost::python string-convertible properties
I have a C++ class, which has the following methods: class Bar { ... const Foo& getFoo() const; void setFoo(const Foo&); }; where class Foo is convertible to std::string (it has an implicit constructor from std::string and an std::string cast operator). I define a Boost.Python wrapper class, which, among other...
[ "I ended up giving up and implementing something similar to custom string class conversion example in Boost.Python FAQ, which is a bit verbose, but works as advertised.\n" ]
[ 2 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0002711432_boost_boost_python_c++_python.txt
Q: What happens when I instantiate class in Python? Could you clarify some ideas behind Python classes and class instances? Consider this: class A(): name = 'A' a = A() a.name = 'B' # point 1 (instance of class A is used here) print a.name print A.name prints: B A if instead in point 1 I use class name, outp...
What happens when I instantiate class in Python?
Could you clarify some ideas behind Python classes and class instances? Consider this: class A(): name = 'A' a = A() a.name = 'B' # point 1 (instance of class A is used here) print a.name print A.name prints: B A if instead in point 1 I use class name, output is different: A.name = 'B' # point 1 (updated, clas...
[ "First of all, the right way in Python to create fields of an instance (rather than class fields) is using the __init__ method. I trust that you know that already.\nPython does not limit you in assigning values to non-declared fields of an object. For example, consider the following code:\nclass Empty: pass\ne = Em...
[ 4, 1, 1 ]
[]
[]
[ "class", "python", "variables" ]
stackoverflow_0002771078_class_python_variables.txt
Q: Python profiler and CPU seconds Hey, I'm totally behind this topic. Yesterday I was doing profiling using Python profiler module for some script I'm working on, and the unit for time spent was a 'CPU second'. Can anyone remind me with the definition of it? For example for some profiling I got: 200.750 CPU seconds....
Python profiler and CPU seconds
Hey, I'm totally behind this topic. Yesterday I was doing profiling using Python profiler module for some script I'm working on, and the unit for time spent was a 'CPU second'. Can anyone remind me with the definition of it? For example for some profiling I got: 200.750 CPU seconds. What does that supposed to mean? At ...
[ "Roughly speaking, a CPU time of, say, 200.75 seconds means that if only one processor worked on the task and that processor were working on it all the time, it would have taken 200.75 seconds. CPU time can be contrasted with wall clock time, which means the actual time elapsed from the start of the task to the end...
[ 8, 1 ]
[]
[]
[ "profiling", "python" ]
stackoverflow_0002771561_profiling_python.txt
Q: querying for timestamp field in django In my views i have the date in the following format s_date=20090106 and e_date=20100106 The model is defined as class Activity(models.Model): timestamp = models.DateTimeField(auto_now_add=True) how to query for the timestamp filed with the above info. Acti...
querying for timestamp field in django
In my views i have the date in the following format s_date=20090106 and e_date=20100106 The model is defined as class Activity(models.Model): timestamp = models.DateTimeField(auto_now_add=True) how to query for the timestamp filed with the above info. Activity.objects.filter(timestamp>=s_date and ti...
[ "You have to convert your date to an instance of datetime.datetime class. Easiest way to do it for your case is:\nimport datetime\n\n#\n# This creates new instace of `datetime.datetime` from a string according to\n# the pattern given as the second argument.\n#\nstart = datetime.datetime.strptime(s_date, '%Y%m%d')\n...
[ 6, 2 ]
[]
[]
[ "django", "django_models", "django_views", "python" ]
stackoverflow_0002771739_django_django_models_django_views_python.txt
Q: Import Error when use templatetags in Django Well, when I'm trying to use 'inclusion' in Django, I met some confused problems that I can't solve it by myself. There is the structures for my project. MyProject--- App1--- __init__.py models.py test...
Import Error when use templatetags in Django
Well, when I'm trying to use 'inclusion' in Django, I met some confused problems that I can't solve it by myself. There is the structures for my project. MyProject--- App1--- __init__.py models.py test.py urls.py ...
[ "\nThe templatetags folder should live in the app folder:\n App1---\n __init__.py\n models.py\n test.py\n urls.py\n views.py\n templatetags---\n __init__.py\n inclusion_test.py\n ...
[ 2 ]
[]
[]
[ "django", "python", "templatetags" ]
stackoverflow_0002771850_django_python_templatetags.txt
Q: Python subprocess block I'm having a problem with the module subprocess; I'm running a script from Python: subprocess.Popen('./run_pythia.sh', shell=True).communicate() and sometimes it just blocks and it doesn't finish to execute the script. Before I was using .wait(), but I switched to .communicate(). Neverthel...
Python subprocess block
I'm having a problem with the module subprocess; I'm running a script from Python: subprocess.Popen('./run_pythia.sh', shell=True).communicate() and sometimes it just blocks and it doesn't finish to execute the script. Before I was using .wait(), but I switched to .communicate(). Nevertheless the problem continues. Fi...
[ "Is the script you execute, is run_pythia.sh guaranteed to finish executing? If not, you might not want to use blocking methods like communicate(). You might want to look into interacting with the .stdout, .stderr, and .stdin file handles of the returned process handle yourself (in a non-blocking manner). \nAlso, i...
[ 3, 0 ]
[]
[]
[ "blocking", "communicate", "python", "subprocess", "wait" ]
stackoverflow_0002769694_blocking_communicate_python_subprocess_wait.txt
Q: Modify headers in Pylons using Middleware I'm trying to modify a header using Middleware in Pylons to make my application RESTful, basically, if the user request "application/json" via GET that is what he get back. The question I have is, the variable headers is basically a long list. Looking something like this: ...
Modify headers in Pylons using Middleware
I'm trying to modify a header using Middleware in Pylons to make my application RESTful, basically, if the user request "application/json" via GET that is what he get back. The question I have is, the variable headers is basically a long list. Looking something like this: [('Content-Type', 'text/html; charset=utf-8'), ...
[ "Try this\n\nfrom webob import Request, Response\nfrom my_wsgi_application import App\nclass MyMiddleware(object):\n def init(self, app):\n self.app = app\n def call(self, environ, start_response):\n req = Request(environ)\n ...\n rsp = req.get_response(app)\n rsp.headers['C...
[ 1 ]
[]
[]
[ "middleware", "pylons", "python", "rest" ]
stackoverflow_0002771974_middleware_pylons_python_rest.txt
Q: Python: create a function to modify a list by reference not value I'm doing some performance-critical Python work and want to create a function that removes a few elements from a list if they meet certain criteria. I'd rather not create any copies of the list because it's filled with a lot of really large objects...
Python: create a function to modify a list by reference not value
I'm doing some performance-critical Python work and want to create a function that removes a few elements from a list if they meet certain criteria. I'd rather not create any copies of the list because it's filled with a lot of really large objects. Functionality I want to implement: def listCleanup(listOfElements): ...
[ "Python passes everything the same way, but calling it \"by value\" or \"by reference\" will not clear everything up, since Python's semantics are different than the languages for which those terms usually apply. If I was to describe it, I would say that all passing was by value, and that the value was an object re...
[ 30, 6, 2, 2, 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002770038_list_python.txt
Q: Getting unpredictable data into a tabular format The situation: Each page I scrape has <input> elements with a title= and a value= I don't know what is going to be on the page. I want to have all my collected data in a single table at the end, with a column for each title. So basically, I need each row of data to ...
Getting unpredictable data into a tabular format
The situation: Each page I scrape has <input> elements with a title= and a value= I don't know what is going to be on the page. I want to have all my collected data in a single table at the end, with a column for each title. So basically, I need each row of data to line up with all the others, and if a row doesn't have...
[ "You need a multipass algorithm. Remember all the scraped pages in a list of dicts. In the first pass, go over this list and collect all the titles in a set(), and create an ordering (for example, convert to list sort them alphabetically). \nIn the second pass you print the table and use your generated ordering as ...
[ 2, 0 ]
[]
[]
[ "python", "tabular" ]
stackoverflow_0002772294_python_tabular.txt
Q: python get time in minutes import datetime start = datetime.datetime(2009, 1, 31) end = datetime.datetime(2009, 2, 1) print end-start >>1 day, 0:00:00//output How to get the output in minutes Thanks, A: import datetime start = datetime.datetime(2009, 1, 31) end = datetime.datetime(2009, 2, 1) diff = end-start p...
python get time in minutes
import datetime start = datetime.datetime(2009, 1, 31) end = datetime.datetime(2009, 2, 1) print end-start >>1 day, 0:00:00//output How to get the output in minutes Thanks,
[ "import datetime\nstart = datetime.datetime(2009, 1, 31)\nend = datetime.datetime(2009, 2, 1)\ndiff = end-start\nprint (diff.days * 1440) + (diff.seconds / 60)\n>> 1440.0\n\n(I'm assuming you don't need microsecond resolution here - but if you do, just add in a third term using diff.microseconds with the proper div...
[ 4 ]
[]
[]
[ "datetime", "python", "python_2.4" ]
stackoverflow_0002772376_datetime_python_python_2.4.txt
Q: Python: for statement behavior My question concerns the output of this statement: for x in range(4), y in range(4): print x print y Results in: [0, 1, 2, 3] 2 True 2 It seems there is a comparison involved, I just can't figure out why the output is structured like this. A: My guess is that you're runni...
Python: for statement behavior
My question concerns the output of this statement: for x in range(4), y in range(4): print x print y Results in: [0, 1, 2, 3] 2 True 2 It seems there is a comparison involved, I just can't figure out why the output is structured like this.
[ "My guess is that you're running this from an interactive console, and already had y defined with a value of 2 (otherwise, you'd get NameError: name 'y' is not defined). That would lead to the output you observed.\nThis is due to for x in range(4), y in range(4): actually being equivalent to the following when eval...
[ 6, 3, 3, 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0002772264_python_syntax.txt
Q: Programmatically sync the db in Django I'm trying to sync my db from a view, something like this: from django import http from django.core import management def syncdb(request): management.call_command('syncdb') return http.HttpResponse('Database synced.') The issue is, it will block the dev server by as...
Programmatically sync the db in Django
I'm trying to sync my db from a view, something like this: from django import http from django.core import management def syncdb(request): management.call_command('syncdb') return http.HttpResponse('Database synced.') The issue is, it will block the dev server by asking for user input from the terminal. How c...
[ "management.call_command('syncdb', interactive=False)\n\n", "Works like this (at least with Django 1.1.):\nfrom django.core.management.commands import syncdb\nsyncdb.Command().execute(noinput=True)\n\n" ]
[ 20, 4 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0002772990_django_django_admin_python.txt
Q: Mapping functions of 2D numpy arrays I have a function foo that takes a NxM numpy array as an argument and returns a scalar value. I have a AxNxM numpy array data, over which I'd like to map foo to give me a resultant numpy array of length A. Curently, I'm doing this: result = numpy.array([foo(x) for x in data]) ...
Mapping functions of 2D numpy arrays
I have a function foo that takes a NxM numpy array as an argument and returns a scalar value. I have a AxNxM numpy array data, over which I'd like to map foo to give me a resultant numpy array of length A. Curently, I'm doing this: result = numpy.array([foo(x) for x in data]) It works, but it seems like I'm not takin...
[ "If NxM is big (say, 100), they the cost of iterating over A will be amortized into basically nothing.\nSay the array is 1000 X 100 X 100.\nIterating is O(1000), but the cumulative cost of the inside function is O(1000 X 100 X 100) - 10,000 times slower. (Note, my terminology is a bit wonky, but I do know what I'm ...
[ 2, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002772661_numpy_python.txt
Q: Getting the indices of all non-None items from a sub-list in Python? As per the title, I have a nested lists like so (the nested list is a fixed length): # ID, Name, Value list1 = [[ 1, "foo", 10], [ 2, "bar", None], [ 3, "fizz", 57], [ 4, "buzz", None]] I'd like to retur...
Getting the indices of all non-None items from a sub-list in Python?
As per the title, I have a nested lists like so (the nested list is a fixed length): # ID, Name, Value list1 = [[ 1, "foo", 10], [ 2, "bar", None], [ 3, "fizz", 57], [ 4, "buzz", None]] I'd like to return a list (the number of items equal to the length of a sub-list from list1...
[ ">>> [[i for i, j in enumerate(c) if j is not None] for c in zip(*list1)]\n[[0, 1, 2, 3], [0, 1, 2, 3], [0, 2]]\n\nin python-2.x you could use itertools.izip instead of zip to avoid generating intermediate list.\n", "[[i for i in range(len(list1)) if list1[i] is not None] for _ in range(len(log[0]))]\n\nThe above...
[ 7, 1, 0 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0002772528_list_list_comprehension_python.txt
Q: List comprehension from multiple sources in Python? Is it possible to replace the following with a list comprehension? res = [] for a, _, c in myList: for i in c: res.append((a, i)) For example: # Input myList = [("Foo", None, [1, 2, 3]), ("Bar", None, ["i", "j"])] # Output res = [("Foo", 1), ("Foo",...
List comprehension from multiple sources in Python?
Is it possible to replace the following with a list comprehension? res = [] for a, _, c in myList: for i in c: res.append((a, i)) For example: # Input myList = [("Foo", None, [1, 2, 3]), ("Bar", None, ["i", "j"])] # Output res = [("Foo", 1), ("Foo", 2), ("Foo", 3), ("Bar", "i"), ("Bar", "j")]
[ ">>> [(i, j) for i, _, k in myList for j in k]\n[('Foo', 1), ('Foo', 2), ('Foo', 3), ('Bar', 'i'), ('Bar', 'j')]\n\n" ]
[ 7 ]
[]
[]
[ "list", "list_comprehension", "python" ]
stackoverflow_0002773295_list_list_comprehension_python.txt
Q: python: open file, feed line to list, process list data I want to process the data in the file "output.log" and feed it to graphdata['eth0] I have done this but it process only the first line: logread = open("output.log", "r").readlines() for line in logread: print "line", line i = line.rstrip("\n"...
python: open file, feed line to list, process list data
I want to process the data in the file "output.log" and feed it to graphdata['eth0] I have done this but it process only the first line: logread = open("output.log", "r").readlines() for line in logread: print "line", line i = line.rstrip("\n") b = float(i) colors = [ (0.2, 03, .65), (0....
[ "logread = open(\"output.log\", \"r\").readlines()\nfor line in logread:\n print \"line\", line\n i = line.rstrip(\"\\n\")\n b = float(i)\n colors = [ (0.2, 03, .65), (0.5, 0.7, .1), (.35, .2, .45), ]\n graphData = {}\n graphData['eth0'] = [b]\n cairoplot.dot_line_pl...
[ 0, 0, 0 ]
[]
[]
[ "cairo", "cairoplot", "python" ]
stackoverflow_0002773416_cairo_cairoplot_python.txt
Q: Accelerometer data analysis I would like to know if there are some libraries/algorithms/techniques (python, if at all possible) that help to extract features from accelerometer data (extracted from and android phone, btw), like periodicity of movements, energy of acceleration and the like. Has anyone done this kin...
Accelerometer data analysis
I would like to know if there are some libraries/algorithms/techniques (python, if at all possible) that help to extract features from accelerometer data (extracted from and android phone, btw), like periodicity of movements, energy of acceleration and the like. Has anyone done this kind of task before? Thank you very ...
[ "I dont know about android but a lot of work has been done on Python/Symbain Accelerometer stuff.\nYou can find a link here\n" ]
[ 0 ]
[]
[]
[ "accelerometer", "android", "data_analysis", "python" ]
stackoverflow_0002773668_accelerometer_android_data_analysis_python.txt
Q: Customizing Django form widgets? - Django I'm having a little problem here! I have discovered the following as being the globally accepted method for customizing Django admin field. from django import forms from django.utils.safestring import mark_safe class AdminImageWidget(forms.FileInput): """ A Image...
Customizing Django form widgets? - Django
I'm having a little problem here! I have discovered the following as being the globally accepted method for customizing Django admin field. from django import forms from django.utils.safestring import mark_safe class AdminImageWidget(forms.FileInput): """ A ImageField Widget for admin that shows a thumbnail. ...
[ "You are correct that the widgets themselves are independent. My first thought for doing something more complex is to either provide a custom admin template that does what you want, or to pass in a piece of javascript code to handle the interrelated fields (much like how prepopulated fields work).\n", "you probab...
[ 1, 1 ]
[]
[]
[ "django", "django_admin", "django_models", "field", "python" ]
stackoverflow_0002766839_django_django_admin_django_models_field_python.txt
Q: Python Locking Implementation (with threading module) This is probably a rudimentary question, but I'm new to threaded programming in Python and am not entirely sure what the correct practice is. Should I be creating a single lock object (either globally or being passed around) and using that everywhere that I ...
Python Locking Implementation (with threading module)
This is probably a rudimentary question, but I'm new to threaded programming in Python and am not entirely sure what the correct practice is. Should I be creating a single lock object (either globally or being passed around) and using that everywhere that I need to do locking? Or, should I be creating multiple lock...
[ "In the general case, a single global lock is less efficient (more contention) but safer (no risk of deadlock) as long as it's a RLock (reentrant) rather than a plain Lock.\nThe potential problems come when a thread that's executing while holding a lock tries to acquire another (or the same) lock, for example by ca...
[ 9, 9 ]
[]
[]
[ "locking", "multithreading", "python" ]
stackoverflow_0002773935_locking_multithreading_python.txt
Q: Creating Python C module from Fortran sources on Ubuntu 10.04 LTS In a project I work on we use a Python C module compiled from Fortran with f2py. I've had no issues building it on Windows 7 32bit (using mingw32) and on the servers it's built on 32bit Linux. But I've recently installed Ubuntu 10.04 LTS 64bit on my...
Creating Python C module from Fortran sources on Ubuntu 10.04 LTS
In a project I work on we use a Python C module compiled from Fortran with f2py. I've had no issues building it on Windows 7 32bit (using mingw32) and on the servers it's built on 32bit Linux. But I've recently installed Ubuntu 10.04 LTS 64bit on my laptop that I use for development, and when I build it I get a lot of ...
[ "Fortunately managed to solve this.\nIt seems I didn't notice that the numpy package version in the repositories for Ubuntu 10.04 are only v1.3.0. I removed numpy, then built v1.4.1 from source.\nAfter that re-running f2py did give the same warnings, however using the module does not produce the crash anymore.\n" ]
[ 0 ]
[]
[]
[ "32bit_64bit", "f2py", "fortran", "python" ]
stackoverflow_0002768404_32bit_64bit_f2py_fortran_python.txt
Q: Internet Explorer URL blocking with Python? I need to be able to block the urls that are stored in a text file on the hard disk using Python. If the url the user tries to visit is in the file, it redirects them to another page instead. How is this done? A: There are several proxies written in Python: you can pic...
Internet Explorer URL blocking with Python?
I need to be able to block the urls that are stored in a text file on the hard disk using Python. If the url the user tries to visit is in the file, it redirects them to another page instead. How is this done?
[ "There are several proxies written in Python: you can pick one of them and modify it so that it proxies most URLs normally but redirects those in your text file. You'll also need to set IE to use that proxy, of course.\n", "Doing this at the machine level is a weak solution, it would be pretty easy for a technic...
[ 3, 1 ]
[]
[]
[ "internet_explorer", "python", "url", "windows" ]
stackoverflow_0002774006_internet_explorer_python_url_windows.txt
Q: Python/Numpy: Divide array I have some data represented in a 1300x1341 matrix. I would like to split this matrix in several pieces (e.g. 9) so that I can loop over and process them. The data needs to stay ordered in the sense that x[0,1] stays below (or above if you like) x[0,0] and besides x[1,1]. Just like if yo...
Python/Numpy: Divide array
I have some data represented in a 1300x1341 matrix. I would like to split this matrix in several pieces (e.g. 9) so that I can loop over and process them. The data needs to stay ordered in the sense that x[0,1] stays below (or above if you like) x[0,0] and besides x[1,1]. Just like if you had imaged the data, you could...
[ "Sounds like you need to use numpy.split() which has its documentation here ... or perhaps its sibling numpy.array_split() here. They are for splitting an array into equal subsections without re-arranging the numbers like reshape does,\nI haven't tested this but something like:\nnumpy.array_split(numpy.zeros((1300...
[ 5, 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002773632_numpy_python.txt
Q: Comparing dicts and update a list of result I have a list of dicts and I want to compare each dict in that list with a dict in a resulting list, add it to the result list if it's not there, and if it's there, update a counter associated with that dict. At first I wanted to use the solution described at Python : Li...
Comparing dicts and update a list of result
I have a list of dicts and I want to compare each dict in that list with a dict in a resulting list, add it to the result list if it's not there, and if it's there, update a counter associated with that dict. At first I wanted to use the solution described at Python : List of dict, if exists increment a dict value, if ...
[ "Well, if your original dicts contain only src, dst and cmd, you can use named tuples instead, which are hashable, so you can use named tuples in a dict as keys.\nfrom collections import namedtuple\n\nDataClass = namedtuple(\"DataClass\", \"src dst cmd\")\nd1 = DataClass(src='192.168.0.2', dst='192.168.0.1', cmd='c...
[ 1, 1 ]
[]
[]
[ "compare", "dictionary", "python" ]
stackoverflow_0002773522_compare_dictionary_python.txt
Q: Can distribute setuptools be used to port packages implemented in python 2 to 3 Found some info on porting packages from python 2 to 3 using distribute setuptools in below link. http://packages.python.org/distribute/python3.html I have a C api which could be build using python 2.x, but i need to build it in pytho...
Can distribute setuptools be used to port packages implemented in python 2 to 3
Found some info on porting packages from python 2 to 3 using distribute setuptools in below link. http://packages.python.org/distribute/python3.html I have a C api which could be build using python 2.x, but i need to build it in python 3.x. Can it be done using distribute. Do anyone have idea on this?
[ "No, it cannot be done using Distribute. Distribute just calls the 2to3 script in the build phase, but 2to3 can convert only between Python 2.x source files and Python 3.x source files. For the C API, you have to do it the hard way by manually tweaking your code to compile with both Python APIs.\nA very incomplete ...
[ 3, 0 ]
[]
[]
[ "build", "c", "package", "python", "python_3.x" ]
stackoverflow_0002774654_build_c_package_python_python_3.x.txt
Q: How do I strip the comma from the end of a string in Python? How do I strip comma from the end of a string? I tried awk = subprocess.Popen([r"awk", "{print $10}"], stdin=subprocess.PIPE) awk_stdin = awk.communicate(uptime_stdout)[0] print awk_stdin temp = awk_stdin t = temp.strip(",") also tried t = temp.rstrip(...
How do I strip the comma from the end of a string in Python?
How do I strip comma from the end of a string? I tried awk = subprocess.Popen([r"awk", "{print $10}"], stdin=subprocess.PIPE) awk_stdin = awk.communicate(uptime_stdout)[0] print awk_stdin temp = awk_stdin t = temp.strip(",") also tried t = temp.rstrip(","), both don't work. This is the code: uptime = subprocess.Pope...
[ "Err, how about the venerable:\nif len(str) > 0:\n if str[-1:] == \",\":\n str = str[:-1]\n\nOn second thought, rstrip itself should work fine, so there's something about the string you're getting from awk that's not quite what you expect. We'll need to see that.\n\nI suspect it's because your string does...
[ 7, 7, 2, 1, 0 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002774558_python_string.txt
Q: merging indexed array in Python Suppose that I have two numpy arrays of the form x = [[1,2] [2,4] [3,6] [4,NaN] [5,10]] y = [[0,-5] [1,0] [2,5] [5,20] [6,25]] is there an efficient way to merge them such that I have xmy = [[0, NaN, -5 ] [1, 2, 0 ] [2, 4,...
merging indexed array in Python
Suppose that I have two numpy arrays of the form x = [[1,2] [2,4] [3,6] [4,NaN] [5,10]] y = [[0,-5] [1,0] [2,5] [5,20] [6,25]] is there an efficient way to merge them such that I have xmy = [[0, NaN, -5 ] [1, 2, 0 ] [2, 4, 5 ] [3, 6, NaN] ...
[ "See numpy.lib.recfunctions.join_by \nIt only works on structured arrays or recarrays, so there are a couple of kinks. \nFirst you need to be at least somewhat familiar with structured arrays. See here if you're not.\nimport numpy as np\nimport numpy.lib.recfunctions\n\n# Define the starting arrays as structured a...
[ 10 ]
[]
[]
[ "arrays", "numpy", "python", "scipy" ]
stackoverflow_0002774949_arrays_numpy_python_scipy.txt
Q: Intellisense on custom types in Iron Python I'm just starting to play around with IronPython and am having a hard time using it with custom types created in C#. I can get IronPython to load in assemblies from C# classes, but I'm struggling without the help of intellisense. If I have a class in C# as defined below,...
Intellisense on custom types in Iron Python
I'm just starting to play around with IronPython and am having a hard time using it with custom types created in C#. I can get IronPython to load in assemblies from C# classes, but I'm struggling without the help of intellisense. If I have a class in C# as defined below, how can I make it so that IronPython will be abl...
[ "If you want to do it from an editor/IDE, IronPython Tools for Visual Studio has that capability (and much more). If you don't have VS 2010 Pro, you can install it into the Integrated Shell.\nIf you want to do it from the console, I don't believe that it's possible yet.\n" ]
[ 2 ]
[]
[]
[ "c#", "intellisense", "ironpython", "python" ]
stackoverflow_0002772230_c#_intellisense_ironpython_python.txt
Q: How do I check the methods that an object has, in Python? For example, a list. l1 = [1, 5 , 7] How do I check the methods that it has? (l1.append, for example) Or a string... string.lower( A: You can use dir to get a list the methods of any object. This is very useful in the interactive prompt: >>> dir(l1) ['__a...
How do I check the methods that an object has, in Python?
For example, a list. l1 = [1, 5 , 7] How do I check the methods that it has? (l1.append, for example) Or a string... string.lower(
[ "You can use dir to get a list the methods of any object. This is very useful in the interactive prompt:\n>>> dir(l1)\n['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__',\n'__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__ia...
[ 21, 4, 2, 1, 1, 0 ]
[]
[]
[ "methods", "object", "python" ]
stackoverflow_0001897960_methods_object_python.txt
Q: A question about DOM parser used with Python I'm using the following python code to search for a node in an XML file and changing the value of an attribute of one of it's children.Changes are happening correctly when the node is displayed using toxml().But, when it is written to a file, the attributes rearrange th...
A question about DOM parser used with Python
I'm using the following python code to search for a node in an XML file and changing the value of an attribute of one of it's children.Changes are happening correctly when the node is displayed using toxml().But, when it is written to a file, the attributes rearrange themselves(as seen in the Source and the Final XML b...
[ "Per XML's standards for the DOM, attributes are not held as an ordered collection; in Python's xml.dom implementations, they're a NamedNodeMap, whose docs say:\n\nThe order you get the attributes in is\n arbitrary but will be consistent for\n the life of a DOM\n\nIn particular, there's no promise that this arbit...
[ 2, 1 ]
[]
[]
[ "dom", "python", "xml" ]
stackoverflow_0002775202_dom_python_xml.txt
Q: Help with Python structure in *nixes I came from a Windows background whern it comes to development environments. I'm used to run .exe's from everything I need to run and just forget. I usually code in php, javascript, css, html and python. Now, I have to use Linux at my work, in a non changeable Ubuntu 8.04, with...
Help with Python structure in *nixes
I came from a Windows background whern it comes to development environments. I'm used to run .exe's from everything I need to run and just forget. I usually code in php, javascript, css, html and python. Now, I have to use Linux at my work, in a non changeable Ubuntu 8.04, with permissions to upgrade my system using co...
[ "You may have installed Python 2.4 in /usr/local/bin, which, in turn, may come in your $PATH before /usr/bin where 2.5 lives. There are various possible remediations, if that is the case: simplest is probably to rm the link named /usr/local/bin/python (leaving only the \"system\" one named /usr/bin/python). You w...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0002775213_linux_python.txt
Q: Django ImageField validation & PIL On sunday, I had problems with python modules, when I installed stackless python. Now I have compiled and installed : setuptools & python-mysqldb and i got my django project up and running again. (i also reinstalled django-1.1), Then I compiled and installed, jpeg, freetype2 a...
Django ImageField validation & PIL
On sunday, I had problems with python modules, when I installed stackless python. Now I have compiled and installed : setuptools & python-mysqldb and i got my django project up and running again. (i also reinstalled django-1.1), Then I compiled and installed, jpeg, freetype2 and PIL. I also started using mod_wsgi i...
[ "Might want to check out this blog post and see if it addresses your problem.\nhttp://www.chipx86.com/blog/2008/07/25/django-tips-pil-imagefield-and-unit-tests/\n" ]
[ 0 ]
[]
[]
[ "django", "mod_wsgi", "python", "python_imaging_library", "python_stackless" ]
stackoverflow_0001292061_django_mod_wsgi_python_python_imaging_library_python_stackless.txt
Q: Recurrent yearly date alert in Python A user can set a day alert for a birthday. (We do not care about the year of birth) He also picks if he wants to be alerted 0, 1, 2, ou 7 days (Delta) before the D day. Users have a timezone setting. I want the server to send the alerts at 8 am on the the D day - deleta +- use...
Recurrent yearly date alert in Python
A user can set a day alert for a birthday. (We do not care about the year of birth) He also picks if he wants to be alerted 0, 1, 2, ou 7 days (Delta) before the D day. Users have a timezone setting. I want the server to send the alerts at 8 am on the the D day - deleta +- user timezone Example: 12 jun, with "alert me ...
[ "Although using plain datetime python module you will be able to implement all you need, a much more powerful python-dateutil extension is available, especially if you need to work with recurring events. The code below should give you an indication of how to achieve your goal:\nfrom datetime import *\nfrom dateutil...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "algorithm", "date", "python", "timezone" ]
stackoverflow_0002776311_algorithm_date_python_timezone.txt
Q: traversing an object tree I'm trying to find information on different ways to traverse an object tree in python. I don't know much about the language in general yet, so any suggestions/techniques would be welcome. Thanks so much jml A: See the inspect module. It has functions for accessing/listing all kinds of o...
traversing an object tree
I'm trying to find information on different ways to traverse an object tree in python. I don't know much about the language in general yet, so any suggestions/techniques would be welcome. Thanks so much jml
[ "See the inspect module. It has functions for accessing/listing all kinds of object information.\n", "i found out how to do it. basically myobject.membername1.membername2\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002776663_python.txt
Q: How do you store accented characters coming from a web service into a database? I have the following word that I fetch via a web service: André From Python, the value looks like: "Andr\u00c3\u00a9". The input is then decoded using json.loads: >>> import json >>> json.loads('{"name":"Andr\\u00c3\\u00a9"}') >>> {u'...
How do you store accented characters coming from a web service into a database?
I have the following word that I fetch via a web service: André From Python, the value looks like: "Andr\u00c3\u00a9". The input is then decoded using json.loads: >>> import json >>> json.loads('{"name":"Andr\\u00c3\\u00a9"}') >>> {u'name': u'Andr\xc3\xa9'} When I store the above in a utf8 MySQL database, the data is...
[ "The fault is already in the string you pass to json.loads(). \\u00c3 is \"A tilde\" and \\00a9 is the copyright sign. Correct for é would be \\u00e9.\nProbably the string has been encoded in UTF-8 by the sender and decoded as ISO-8859-1 by the receiver.\nFor example, if you run the following Python script:\n# -*- ...
[ 6 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0002775751_django_mysql_python.txt
Q: if else-if making code look ugly any cleaner solution? I have around 20 functions (is_func1, is_fucn2, is_func3...) returning boolean I assume there is only one function which returns true and I want that! I am doing: if is_func1(param1, param2): # I pass 1 to following abc(1) # I pass 1 some_list.appe...
if else-if making code look ugly any cleaner solution?
I have around 20 functions (is_func1, is_fucn2, is_func3...) returning boolean I assume there is only one function which returns true and I want that! I am doing: if is_func1(param1, param2): # I pass 1 to following abc(1) # I pass 1 some_list.append(1) elif is_func2(param1, param2): # I pass 2 to follo...
[ "What about\nfunctionList = [is_func1, is_func2, ..., is_func20]\nfor index, func in enumerate(functionList):\n if(func(param1, param2)):\n abc(index+1)\n some_list.append(index+1)\n break\n\n", "\nI can think of putting functions in a data structure and loop to call them.\n\nYes, probably...
[ 4, 2, 1, 1, 1, 1, 0, 0 ]
[ "I know I will be modded down for being offtopic, but still. If you find anything that can be done with standard control constructs off-putting, then you need to use a different language, such as Common Lisp, which allows for macros, in effect makes it possible to create your own control constructs. (Having recentl...
[ -3 ]
[ "python" ]
stackoverflow_0002776125_python.txt
Q: python httplib and broken tcp connection How do I find out if a connection has been broken using the httplib library? Seems like something so basic yet I can't find the answer on here or google. A: While Connecting You get one of these: http://docs.python.org/library/httplib.html#httplib.HTTPException you could...
python httplib and broken tcp connection
How do I find out if a connection has been broken using the httplib library? Seems like something so basic yet I can't find the answer on here or google.
[ "While Connecting You get one of these:\nhttp://docs.python.org/library/httplib.html#httplib.HTTPException\nyou could do something like this.\n>>> import httplib\n>>> conn = httplib.HTTPConnection(\"www.python.org\")\n>>> try:\n>>> conn.request(\"GET\", \"/index.html\")\n>>> except Exception as e:\n>>> #tak...
[ 4 ]
[]
[]
[ "http", "httplib", "python", "sockets", "tcp" ]
stackoverflow_0002777435_http_httplib_python_sockets_tcp.txt
Q: Python operators returning ints Is there any way to have Python operators line "==" and ">" return ints instead of bools. I know that I could use the int function (int(1 == 1)) or add 0 ((1 == 1) + 0) but I was wondering if there was an easy way to do it. Like when you want division to return floats you could type...
Python operators returning ints
Is there any way to have Python operators line "==" and ">" return ints instead of bools. I know that I could use the int function (int(1 == 1)) or add 0 ((1 == 1) + 0) but I was wondering if there was an easy way to do it. Like when you want division to return floats you could type from __future__ import division. Is ...
[ "You cant override the built-in comparison functions. In some sense the comparison operators are already returning int. bool is a subclass of int, so you can do anything to it that you can do to a int. The question then becomes why would you want to have comparisons return int objects, not bool objects?\n", "You ...
[ 3, 1, 1, 1, 0, 0 ]
[]
[]
[ "boolean", "int", "operators", "python" ]
stackoverflow_0002777366_boolean_int_operators_python.txt
Q: Python Drawing Portion of Image When Mouse Hover My question relates to Python GTK I have an image -a JPG - which I draw onto a drawing area. I want to reveal a portion of the image -say a 10pix by 10 px square -only where the mouse pointer is currently at. Everything 10 x 10 px square away from the mouse should h...
Python Drawing Portion of Image When Mouse Hover
My question relates to Python GTK I have an image -a JPG - which I draw onto a drawing area. I want to reveal a portion of the image -say a 10pix by 10 px square -only where the mouse pointer is currently at. Everything 10 x 10 px square away from the mouse should hidden i.e. black. I'm am new to PyGtk please can anyon...
[ "#!/usr/bin/python \n\nimport os\nimport sys\nimport gtk\n\nMASK_COLOR = 0x000000\n\ndef composite(source, start_x=345, start_y=345):\n width = 50 \n height = 50 \n alpha = 255 ...
[ 2 ]
[]
[]
[ "image_processing", "pygtk", "python" ]
stackoverflow_0002336916_image_processing_pygtk_python.txt
Q: Shutting Down SSH Tunnel in Paramiko Programmatically We are attempting to use the paramiko module for creating SSH tunnels on demand to arbitrary servers for purposes of querying remote databases. We attempted to use the forward.py demo that ships with paramiko but the big limitation is there does not seem to be...
Shutting Down SSH Tunnel in Paramiko Programmatically
We are attempting to use the paramiko module for creating SSH tunnels on demand to arbitrary servers for purposes of querying remote databases. We attempted to use the forward.py demo that ships with paramiko but the big limitation is there does not seem to be an easy way to close an SSH tunnel and the SSH connection ...
[ "I'm not sure what you mean by \"implement it correctly\" -- you just need to keep track of the server object and call shutdown on it when you want. In forward.py, the server isn't kept track of, because the last line of forward_tunnel is\nForwardServer(('', local_port), SubHander).serve_forever()\n\nso the server...
[ 5 ]
[]
[]
[ "paramiko", "python", "tunnel" ]
stackoverflow_0002777884_paramiko_python_tunnel.txt
Q: python webtest port configuration? I am attempting to write some tests using webtest to test out my python GAE application. The problem I am running into is that the application is listening on port 8080 but I cannot configure webtest to hit that port. For example, I want to use app.get('/getreport') to hit http:...
python webtest port configuration?
I am attempting to write some tests using webtest to test out my python GAE application. The problem I am running into is that the application is listening on port 8080 but I cannot configure webtest to hit that port. For example, I want to use app.get('/getreport') to hit http://localhost:8080/getreport. Obviously, ...
[ "With paste.proxy.TransparentProxy you can test anything that responds to an http request...\nfrom webtest import TestApp\nfrom paste.proxy import TransparentProxy\ntestapp = TestApp(TransparentProxy())\nres = testapp.get(\"http://google.com\")\nassert res.status==\"200 OK\",\"failure.....\"\n\n", "In config, and...
[ 4, 2, 2 ]
[]
[]
[ "google_app_engine", "python", "webtest" ]
stackoverflow_0002774249_google_app_engine_python_webtest.txt
Q: Content-Length header not returned from Pylons response I'm still struggling to Stream a file to the HTTP response in Pylons. In addition to the original problem, I'm finding that I cannot return the Content-Length header, so that for large files the client cannot estimate how long the download will take. I've tri...
Content-Length header not returned from Pylons response
I'm still struggling to Stream a file to the HTTP response in Pylons. In addition to the original problem, I'm finding that I cannot return the Content-Length header, so that for large files the client cannot estimate how long the download will take. I've tried response.content_length = 12345 and I've tried response.h...
[ "There's a bit of middleware code here that ensures all responses get a content length header if they're missing it. You could tweak it so that you set some other header in your response (say 'X-The-Content-Length') and the middleware uses that to make the content length if the latter's missing. I view the whole ...
[ 1, 0 ]
[]
[]
[ "content_length", "http", "pylons", "python" ]
stackoverflow_0002777866_content_length_http_pylons_python.txt
Q: Embed FCKeditor in python app I have a python application which need a gui HTML editor, I know FCKeditor is nice, so how to embed the FCKeditor in a python desktop app? A: To embed FCKeditor (or maybe better the current CKeditor?), you basically need to embed a full-fledged browser (with Javascript) -- I believe...
Embed FCKeditor in python app
I have a python application which need a gui HTML editor, I know FCKeditor is nice, so how to embed the FCKeditor in a python desktop app?
[ "To embed FCKeditor (or maybe better the current CKeditor?), you basically need to embed a full-fledged browser (with Javascript) -- I believe wxPython may currently be the best bet for that, as I hear it has wxIE for Windows and wxWebKitCtrl for the Mac (I don't know if old summer-of-code ideas about making someth...
[ 1, 0 ]
[]
[]
[ "editor", "html", "python" ]
stackoverflow_0002777919_editor_html_python.txt
Q: Difference between URLLIB2 call in IDLE and from Django? The following piece of code works as expected when running in a local install of django apache 2.2 fx = urllib2.Request(f); fx.add_header('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/1.0.154.36...
Difference between URLLIB2 call in IDLE and from Django?
The following piece of code works as expected when running in a local install of django apache 2.2 fx = urllib2.Request(f); fx.add_header('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/1.0.154.36 Safari/525.19'); url_opened = urllib2.urlopen(fx); However ...
[ "urllib and urllib2 I think look at environment variables for proxies if one isn't set programatically. Maybe the proxy environment variables haven't been set properly in IDLE? \nCompare the output of the following from IDLE to the Django program:\nimport os, pprint\nfor k in os.environ:\n if 'proxy' in k.lower(...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002778000_django_python.txt
Q: Convert a sequence of sequences to a dictionary and vice-versa One way to manually persist a dictionary to a database is to flatten it into a sequence of sequences and pass the sequence as an argument to cursor.executemany(). The opposite is also useful, i.e. reading rows from a database and turning them into dict...
Convert a sequence of sequences to a dictionary and vice-versa
One way to manually persist a dictionary to a database is to flatten it into a sequence of sequences and pass the sequence as an argument to cursor.executemany(). The opposite is also useful, i.e. reading rows from a database and turning them into dictionaries for later use. What's the best way to go from myseq to mydi...
[ "mydict = dict((s[0], s[1:]) for s in myseq)\n\nmyseq = tuple(sorted((k,) + v for k, v in mydict.iteritems()))\n\n", ">>> mydict = dict((t[0], t[1:]) for t in myseq))\n\n>>> myseq = tuple(((key,) + values) for (key, values) in mydict.items())\n\nThe ordering of tuples in myseq is not preserved, since dictionaries...
[ 5, 2 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0002778452_dictionary_list_python.txt
Q: MongoDB lists with paginations? for documents with lists with pagination, is it better to embed or use reference? im reading the custom type "SONManipulator" and it appears to transform every thing on retrieval, even the sub docs. i want to keep the list in the document sorted, should this impact anything? ...
MongoDB lists with paginations?
for documents with lists with pagination, is it better to embed or use reference? im reading the custom type "SONManipulator" and it appears to transform every thing on retrieval, even the sub docs. i want to keep the list in the document sorted, should this impact anything?
[ "I don't fully understand your question, but it is generally better to embed documents for performance reasons. That is one of the major advantages of MongoDB's approach, data locality. The pymongo lib uses SON sorted dict implementation which will maintain the ordering of your document keys.\nIf you document co...
[ 1 ]
[]
[]
[ "mongodb", "python" ]
stackoverflow_0002777859_mongodb_python.txt
Q: Stream a file to the HTTP response in Pylons I have a Pylons controller action that needs to return a file to the client. (The file is outside the web root, so I can't just link directly to it.) The simplest way is, of course, this: with open(filepath, 'rb') as f: response.write(f.read()) That works, ...
Stream a file to the HTTP response in Pylons
I have a Pylons controller action that needs to return a file to the client. (The file is outside the web root, so I can't just link directly to it.) The simplest way is, of course, this: with open(filepath, 'rb') as f: response.write(f.read()) That works, but it's obviously inefficient for large files. Wh...
[ "The correct tool to use is shutil.copyfileobj, which copies from one to the other a chunk at a time.\nExample usage:\nimport shutil\nwith open(filepath, 'r') as f:\n shutil.copyfileobj(f, response)\n\nThis will not result in very large memory usage, and does not require implementing the code yourself.\nThe usua...
[ 8, 4, 1 ]
[]
[]
[ "http", "pylons", "python" ]
stackoverflow_0002413707_http_pylons_python.txt
Q: Python: Problems finding string in website source code I open a website with urlopen. I then put the website sourcecode into a variable like so source = website.read() When I just print the source it comes out formatted correctly, however when I try to iterate through each line each character is it's own line. fo...
Python: Problems finding string in website source code
I open a website with urlopen. I then put the website sourcecode into a variable like so source = website.read() When I just print the source it comes out formatted correctly, however when I try to iterate through each line each character is it's own line. for example when I just print it looks like this <HTML> title<...
[ "Use readlines() instead of read() to get a list of lines.\n", "Or use:\nfor line in source.split(\"\\n\"):\n ...\n\n" ]
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002779115_python.txt
Q: How can I find "week" in django's calendar app? MyCalendar.py Code: from django import template imort calendar import datetime date = datetime.date.today() week = ??? ... The question is that I want to get the week which contains today's date. How can I do? Thanks for help! Ver: Django-1.0 Python-2.6.4 A: Afte...
How can I find "week" in django's calendar app?
MyCalendar.py Code: from django import template imort calendar import datetime date = datetime.date.today() week = ??? ... The question is that I want to get the week which contains today's date. How can I do? Thanks for help! Ver: Django-1.0 Python-2.6.4
[ "After reading your comment I think this is what you want:\nimport datetime\n\ntoday = datetime.date.today()\nweekday = today.weekday()\nstart_delta = datetime.timedelta(days=weekday)\nstart_of_week = today - start_delta\nweek_dates = [start_of_week + datetime.timedelta(days=i) for i in range(7)]\nprint week_dates\...
[ 11, 3 ]
[]
[]
[ "calendar", "django", "python" ]
stackoverflow_0002778715_calendar_django_python.txt
Q: Run and terminate a program (Python under Windows) I'd like to create a small script that basically does this: run program1.exe --> kill program1.exe after n seconds --> run program1.exe again. I know some basic Python and would read up on this, but I'm in a bit of a hurry and just need this to get done ASAP. ...
Run and terminate a program (Python under Windows)
I'd like to create a small script that basically does this: run program1.exe --> kill program1.exe after n seconds --> run program1.exe again. I know some basic Python and would read up on this, but I'm in a bit of a hurry and just need this to get done ASAP. If someone has a script/idea or could help my out with ...
[ "Read up on the subprocess module.\nimport subprocess, time\np = subprocess.Popen(['program1.exe'])\ntime.sleep(1) # Parameter is in seconds\np.terminate()\np.wait()\n\n" ]
[ 3 ]
[]
[]
[ "autorun", "python", "windows" ]
stackoverflow_0002779464_autorun_python_windows.txt
Q: Python faster way to read fixed length fields form a file into dictionary I have a file of names and addresses as follows (example line) OSCAR ,CANNONS ,8 ,STIEGLITZ CIRCUIT And I want to read it into a dictionary of name and value. Here self.field_list is a list of the name, length and start point ...
Python faster way to read fixed length fields form a file into dictionary
I have a file of names and addresses as follows (example line) OSCAR ,CANNONS ,8 ,STIEGLITZ CIRCUIT And I want to read it into a dictionary of name and value. Here self.field_list is a list of the name, length and start point of the fixed fields in the file. What ways are there to speed up this method? ...
[ "struct.unpack() combined with s specifiers with lengths will tear the string apart faster than slicing.\n", "Edit: Just saw your remark below about commas. The approach below is fast when it comes to file reading, but it is delimiter-based, and would fail in your case. It's useful in other cases, though.\nIf y...
[ 2, 2, 0, 0, 0 ]
[]
[]
[ "dictionary", "file", "performance", "python" ]
stackoverflow_0002778724_dictionary_file_performance_python.txt
Q: How to programatically pause spotify when a call comes in on skype Skype has an inbuilt function where iTunes playback is paused and resumed automatically when a call comes in. It would be nice to have something similar for Spotify. Both provide a python API so this would seem the obvious route to go down. A: I'...
How to programatically pause spotify when a call comes in on skype
Skype has an inbuilt function where iTunes playback is paused and resumed automatically when a call comes in. It would be nice to have something similar for Spotify. Both provide a python API so this would seem the obvious route to go down.
[ "I've had a stab at doing this in python. It runs in the background as a daemon, pausing/resuming spotify when a call comes. It uses the Python libraries for Skype & Spotify:\nhttp://code.google.com/p/pytify/\nhttps://developer.skype.com/wiki/Skype4Py\nimport Skype4Py\nimport time\nfrom pytify import Spotify\n\n# C...
[ 6 ]
[]
[]
[ "python", "skype", "spotify" ]
stackoverflow_0002779578_python_skype_spotify.txt
Q: Parsing groupings of strings (Python) I have a string that looks something like this: [["Name1","ID1","DDY1", "CALL1", "WHEN1"], ["Name2","ID2","DDY2", "CALL2", "WHEN2"],...]; This string was taken from a website. There can be any amount of groupings. How could I parse this string and print just the Name variable...
Parsing groupings of strings (Python)
I have a string that looks something like this: [["Name1","ID1","DDY1", "CALL1", "WHEN1"], ["Name2","ID2","DDY2", "CALL2", "WHEN2"],...]; This string was taken from a website. There can be any amount of groupings. How could I parse this string and print just the Name variables of each grouping?
[ "Hope I understood well.\n>>> import json\n>>> a = json.loads('[[\"Name1\",\"ID1\",\"DDY1\", \"CALL1\", \"WHEN1\"], [\"Name2\",\"ID2\",\"DDY2\", \"CALL2\", \"WHEN2\"]]')\n>>> [x[0] for x in a]\n[u'Name1', u'Name2']\n>>> \n\n", "import ast\ny = ast.literal_eval(input)\n[x[0] for x in y]\n\nThanks to @stephan for p...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002779584_python.txt
Q: Is it OK to set "Cache-Control: public" when sending “304 Not Modified” for images stored in the datastore After asking a question about sending “304 Not Modified” for images stored in the in the Google App Engine datastore, I now have a question about Cache-Control. My app now sends Last-Modified and Etag, but by...
Is it OK to set "Cache-Control: public" when sending “304 Not Modified” for images stored in the datastore
After asking a question about sending “304 Not Modified” for images stored in the in the Google App Engine datastore, I now have a question about Cache-Control. My app now sends Last-Modified and Etag, but by default GAE alsto sends Cache-Control: no-cache. According to this page: The “no-cache” directive, according t...
[ "It isn't necessary to set Cache-Control: public unless your content is protected by HTTP authentication or SSL. \nTry setting Cache-Control: max-age=nn (where nn is an integer number of seconds that you'd like caches to consider the response fresh for). AppEngine should remove the no-cache.\n", "See http://www.k...
[ 1, 1, 0 ]
[]
[]
[ "caching", "google_app_engine", "http", "python" ]
stackoverflow_0002754644_caching_google_app_engine_http_python.txt
Q: How to build and deploy Python web applications I have a Python web application consisting of several Python packages. What is the best way of building and deploying this to the servers? Currently I'm deploying the packages with Capistrano, installing the packages into a virtualenv with bash, and configuring the s...
How to build and deploy Python web applications
I have a Python web application consisting of several Python packages. What is the best way of building and deploying this to the servers? Currently I'm deploying the packages with Capistrano, installing the packages into a virtualenv with bash, and configuring the servers with puppet, but I would like to go for a more...
[ "Depends on what Your infrastructure is. We're just using debian packages and buildbot to make them.\nOn other setups, I use Fabric scripts. As for format, I'm just using tbz2 files, but I've heard about people just depoloying eggs.\nI'd strongly recommend having proper build and having BuildBot/Hudson to build pac...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "deployment", "python" ]
stackoverflow_0000166334_deployment_python.txt
Q: Setting the first day of the week with the wx.lib.calendar.Calendar control? As per the title, is it possible to change the first day of the week (Monday instead of Sunday)? A: Use the wx.CAL_MONDAY_FIRST value in the style argument of the constructir. Update Hier is code generated by wxGlade: wx.calendar.Calend...
Setting the first day of the week with the wx.lib.calendar.Calendar control?
As per the title, is it possible to change the first day of the week (Monday instead of Sunday)?
[ "Use the wx.CAL_MONDAY_FIRST value in the style argument of the constructir.\nUpdate\nHier is code generated by wxGlade:\nwx.calendar.CalendarCtrl(self, -1, style=wx.calendar.CAL_MONDAY_FIRST)\n\nIt has Monday in the leftmost column.\n", "Found it: you have to call cal.SetBusType().\n" ]
[ 0, 0 ]
[]
[]
[ "calendar", "python", "wxpython" ]
stackoverflow_0002779883_calendar_python_wxpython.txt
Q: Getting error on inserting tuple values in postgreSQL table using python I want to keep last.fm's user recent music tracks list to postgresql database table using pylast interface.But when I tried to insert values to the table it shows errors.Code example: import pylast import psycopg2 import re from md5 import m...
Getting error on inserting tuple values in postgreSQL table using python
I want to keep last.fm's user recent music tracks list to postgresql database table using pylast interface.But when I tried to insert values to the table it shows errors.Code example: import pylast import psycopg2 import re from md5 import md5 import sys import codecs import psycopg2.extensions psycopg2.extensions.re...
[ "sorted(artist) returns a ordered list of artist, when you're iterating over it it returns still elements of artist. So when you're trying to access artist[key] it is actually trying to access an element of artist indexed by the index, which is an element of artist itself. Tuples do not work this way.\nIt seems you...
[ 1, 0, 0 ]
[]
[]
[ "last.fm", "python" ]
stackoverflow_0002780579_last.fm_python.txt
Q: Extract data from PostgreSQL DB without using pg_dump There is a PostgreSQL database on which I only have limited access (e.g, I can't use pg_dump). I am trying to create a local "mirror" by exporting certain tables from the database. I do not have the permissions needed to just dump a table as SQL from within psq...
Extract data from PostgreSQL DB without using pg_dump
There is a PostgreSQL database on which I only have limited access (e.g, I can't use pg_dump). I am trying to create a local "mirror" by exporting certain tables from the database. I do not have the permissions needed to just dump a table as SQL from within psql. Right now, I just have a Python script that iterates thr...
[ "It puzzles me the bit about \"I do not have the permissions needed to just dump a table as SQL from within psql.\" pg_dump runs standalone, outside psql (both are clients) and if you have permission to connect to the database and select a table, I'd guess you'd also be able to dump it using pg_dump -t <table>. Am ...
[ 3, 2, 1 ]
[]
[]
[ "postgresql", "python", "sql", "xml" ]
stackoverflow_0002770792_postgresql_python_sql_xml.txt
Q: stop minidom converting < > to < > Im trying to output some data from my google app engine datastore to xml so that a flash file can read it, The problem is when using CDATA tags the outputted xml contains &lt; instead of < e.g <name>&lt;![CDATA][name]]&gt;</name> here is my python which outputs the xml: d...
stop minidom converting < > to < >
Im trying to output some data from my google app engine datastore to xml so that a flash file can read it, The problem is when using CDATA tags the outputted xml contains &lt; instead of < e.g <name>&lt;![CDATA][name]]&gt;</name> here is my python which outputs the xml: doc = Document() feed = doc.createEl...
[ "It seems the createCDATASection method works for me.\nfor tag in tags:\n tag_element = doc.createCDATASection(tag.thetag)\n tags_element.appendChild(tag_element)\n\n", "To do what you are attempting, you need to actually add a CDATA-block using the appropriate minidom methods. It's not an encoding issue, p...
[ 8, 0, 0 ]
[]
[]
[ "google_app_engine", "minidom", "python", "xml" ]
stackoverflow_0002780506_google_app_engine_minidom_python_xml.txt
Q: why in python giving to str func a unicode string will throw an exception? for example the following: str(u'לשום') will throw an error. how can i prevent these? A: Calling str() on a unicode is the same as calling .encode(sys.getdefaultencoding()) on it. If the unicode contains characters that can't be encoded i...
why in python giving to str func a unicode string will throw an exception?
for example the following: str(u'לשום') will throw an error. how can i prevent these?
[ "Calling str() on a unicode is the same as calling .encode(sys.getdefaultencoding()) on it. If the unicode contains characters that can't be encoded in the default encoding then it will throw a UnicodeEncodeError. The fix is to explicitly encode the unicode in a useful encoding, such as 'utf-8'.\n", "If you're ru...
[ 7, 0 ]
[]
[]
[ "python", "string", "unicode" ]
stackoverflow_0002780413_python_string_unicode.txt
Q: Can Distribute setuptool be used to convert Python 2 packages to Python 3? Possible Duplicate: Can distribute setuptools be used to port packages implemented in python 2 to 3 Also, does the tool make it easy? A: The only thing that Distribute does is that it calls the 2to3 script (supplied with Python 3) that ...
Can Distribute setuptool be used to convert Python 2 packages to Python 3?
Possible Duplicate: Can distribute setuptools be used to port packages implemented in python 2 to 3 Also, does the tool make it easy?
[ "The only thing that Distribute does is that it calls the 2to3 script (supplied with Python 3) that converts a Python 2.x source code to Python 3 using some automatic transformations. Basically, you write your code using Python 2.x and let Distribute convert it to Python 3 when your package is installed on Python 3...
[ 2 ]
[]
[]
[ "events", "package", "python", "python_3.x" ]
stackoverflow_0002781001_events_package_python_python_3.x.txt
Q: Django 1.2 + South 0.7 + django-annoying's AutoOneToOneField leads to TypeError: 'LegacyConnection' object is not iterable I'm using Django 1.2 trunk with South 0.7 and an AutoOneToOneField copied from django-annoying. South complained that the field does not have rules defined and the new version of South no long...
Django 1.2 + South 0.7 + django-annoying's AutoOneToOneField leads to TypeError: 'LegacyConnection' object is not iterable
I'm using Django 1.2 trunk with South 0.7 and an AutoOneToOneField copied from django-annoying. South complained that the field does not have rules defined and the new version of South no longer has an automatic field type parser. So I read the South documentation and wrote the following definition (basically an exact ...
[ "Try to change this line\n(AutoOneToOneField),\n\nTo this:\n(AutoOneToOneField,),\n\nA tuple declared like you did, is not iterable.\n", "Solved the problem by removing the rules and adding the following method to AutoOneToOneField:\ndef south_field_triple(self):\n \"Returns a suitable description of this fiel...
[ 5, 3, 1 ]
[]
[]
[ "django", "django_models", "django_south", "python" ]
stackoverflow_0002781210_django_django_models_django_south_python.txt
Q: cgi.FieldStorage always empty - never returns POSTed form Data This problem is probably embarrassingly simple. I'm trying to give python a spin. I thought a good way to start doing that would be to create a simple cgi script to process some form data and do some magic. My python script is executed properly by apac...
cgi.FieldStorage always empty - never returns POSTed form Data
This problem is probably embarrassingly simple. I'm trying to give python a spin. I thought a good way to start doing that would be to create a simple cgi script to process some form data and do some magic. My python script is executed properly by apache using mod_python, and will print out whatever I want it to print ...
[ "Your problem is that you're mixing two different approaches: CGI and mod_python. You declare your script as a mod_python publisher, which is why its index method gets called -- and which also makes it a module, not a script.\nIf you were using CGI, you would remove the mod_python directives from your Apache config...
[ 6 ]
[]
[]
[ "apache", "cgi", "mod_python", "python" ]
stackoverflow_0002781493_apache_cgi_mod_python_python.txt
Q: Informational messages in python unit testing I'm using Python's unittest module for unit testing. I'd like to be able to report informational messages as part of the unit test output—other than pass/fail status. Specifically in my case, I want to report whether the module under test is using the pure Python imple...
Informational messages in python unit testing
I'm using Python's unittest module for unit testing. I'd like to be able to report informational messages as part of the unit test output—other than pass/fail status. Specifically in my case, I want to report whether the module under test is using the pure Python implementation or the C extension. Is there a mechanism ...
[ "Yes, you can use nosetests, which has a plugin system which allows this. For example the TestResult api allows to provide extended reporting:\n\nProvides a TextTestResult that extends unittest’s _TextTestResult to provide support for error classes (such as the builtin skip and deprecated classes), and hooks for pl...
[ 3, 1 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0002781186_python_unit_testing.txt
Q: Two Dimensional Python Array: Sort second by First I have a Multidimensional array in Python. How do I go about sorting the second array, by the first - all the while keeping it in the same order? A: I'm not sure from your answer if this is what you want, but take a look and see. If I have a multidimensional arr...
Two Dimensional Python Array: Sort second by First
I have a Multidimensional array in Python. How do I go about sorting the second array, by the first - all the while keeping it in the same order?
[ "I'm not sure from your answer if this is what you want, but take a look and see. If I have a multidimensional array x:\n>>> x = [[100,50,39,69,22,23,19,80,94,72],range(10)]\n>>> print x\n[[100, 50, 39, 69, 22, 23, 19, 80, 94, 72], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]\n\nand I want to sort the second subarray by the fir...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002781622_python.txt
Q: Why does Python output a string and a unicode of the same value differently? I'm using Python 2.6.5 and when I run the following in the Python shell, I get: >>> print u'Andr\xc3\xa9' André >>> print 'Andr\xc3\xa9' André >>> What's the explanation for the above? Given u'Andr\xc3\xa9', how can I display the above...
Why does Python output a string and a unicode of the same value differently?
I'm using Python 2.6.5 and when I run the following in the Python shell, I get: >>> print u'Andr\xc3\xa9' André >>> print 'Andr\xc3\xa9' André >>> What's the explanation for the above? Given u'Andr\xc3\xa9', how can I display the above value properly in an html page so that it shows André instead of André?
[ "'\\xc3\\xa9' is the UTF-8 encoding of the unicode character u'\\u00e9' (which can also be specified as u'\\xe9'). So you can use u'Andr\\u00e9' or u'Andr\\xe9'.\nYou can convert from one to the other:\n>>> 'Andr\\xc3\\xa9'.decode('utf-8')\nu'Andr\\xe9'\n>>> u'Andr\\xe9'.encode('utf-8')\n'Andr\\xc3\\xa9'\n\nNote th...
[ 11, 1 ]
[ "I am not sure, but I would guess that different codecs are applied by the print operation. Probably some utf-8 vs. unicode issue. \nFor HTML, you would need to encode certain characters using the HTML syntax for unicode.\nI think that the Python codecs module might be able to help you.\n" ]
[ -2 ]
[ "python", "unicode" ]
stackoverflow_0002782085_python_unicode.txt
Q: Remove n characters from a start of a string I want to remove the first characters from a string. Is there a function that works like this? >>> a = "BarackObama" >>> print myfunction(4,a) ckObama >>> b = "The world is mine" >>> print myfunction(6,b) rld is mine A: Yes, just use slices: >> a = "BarackObama" >> ...
Remove n characters from a start of a string
I want to remove the first characters from a string. Is there a function that works like this? >>> a = "BarackObama" >>> print myfunction(4,a) ckObama >>> b = "The world is mine" >>> print myfunction(6,b) rld is mine
[ "Yes, just use slices:\n >> a = \"BarackObama\"\n >> a[4:]\n 'ckObama'\n\nDocumentation is here http://docs.python.org/tutorial/introduction.html#strings\n", "The function could be:\ndef cutit(s,n): \n return s[n:]\n\nand then you call it like this:\nname = \"MyFullName\"\n\nprint cutit(name, 2) # prints \...
[ 18, 13, 8, 4 ]
[]
[]
[ "python", "string" ]
stackoverflow_0002782318_python_string.txt
Q: libxml2 install error: command 'gcc' failed with exit status 1? What are the dependencies of libxml2? I am trying to install libxml2 on Ubuntu 9.10 and getting errors: $ sudo python setup.py develop Its a very lengthy error message but the last error is Setup script exited with error: Command 'gcc' failed with e...
libxml2 install error: command 'gcc' failed with exit status 1? What are the dependencies of libxml2?
I am trying to install libxml2 on Ubuntu 9.10 and getting errors: $ sudo python setup.py develop Its a very lengthy error message but the last error is Setup script exited with error: Command 'gcc' failed with exit status 1. Can anybody tell me why I am getting this error? What are the dependencies or libraries requ...
[ "I encountered the same problem today on Centos 5.4. If you experience such an error on this system (and on RHEL and probably Fedora) you have to install libxml2-devel and/or libxslt-devel.\nP.S. I know it's not an answer for this question in general however it maybe helpful for someone so I decided to write down i...
[ 3, 1, 0 ]
[ "This is the entire error:\named ‘_extensions’\nsrc/lxml/lxml.etree.c:134800: error: ‘struct __pyx_obj_4lxml_5etree__BaseContext’ has no member named ‘_namespaces’\nsrc/lxml/lxml.etree.c:134800: error: ‘struct __pyx_obj_4lxml_5etree__BaseContext’ has no member named ‘_namespaces’\nsrc/lxml/lxml.etree.c:134800: erro...
[ -1 ]
[ "python", "ubuntu" ]
stackoverflow_0002330062_python_ubuntu.txt
Q: Datastore query outputting for Django form instance I'm using google appengine and Django. I'm using de djangoforms module and wanted to specify the form instance with the information that comes from the query below. userquery = db.GqlQuery("SELECT * FROM User WHERE googleaccount = :1", users.get_current_user(...
Datastore query outputting for Django form instance
I'm using google appengine and Django. I'm using de djangoforms module and wanted to specify the form instance with the information that comes from the query below. userquery = db.GqlQuery("SELECT * FROM User WHERE googleaccount = :1", users.get_current_user()) form = forms.AccountForm(data=request.POST or Non...
[ "If you know the userquery will only have one User object in it (or if you only care about the first one if there are duplicates), you can modify your code like so:\nuserquery = db.GqlQuery(\"SELECT * FROM User WHERE googleaccount = :1\", users.get_current_user())\nuser = userquery.get() # Gets the first User insta...
[ 2 ]
[]
[]
[ "django", "forms", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0002782137_django_forms_google_app_engine_google_cloud_datastore_python.txt
Q: name of the class that contains the method code I'm trying to find the name of the class that contains method code. In the example underneath I use self.__class__.__name__, but of course this returns the name of the class of which self is an instance and not class that contains the test() method code. b.test() wil...
name of the class that contains the method code
I'm trying to find the name of the class that contains method code. In the example underneath I use self.__class__.__name__, but of course this returns the name of the class of which self is an instance and not class that contains the test() method code. b.test() will print 'B' while I would like to get 'A'. I looked i...
[ "In Python 3.x, you can simply use __class__.__name__. The __class__ name is mildly magic, and not the same thing as the __class__ attribute of self.\nIn Python 2.x, there is no good way to get at that information. You can use stack inspection to get the code object, then walk the class hierarchy looking for the ri...
[ 7, 4, 2, 2, 0 ]
[]
[]
[ "introspection", "python" ]
stackoverflow_0002781701_introspection_python.txt
Q: Python: Hack to call a method on an object that isn't of its class Assume you define a class, which has a method which does some complicated processing: class A(object): def my_method(self): # Some complicated processing is done here return self And now you want to use that method on some obje...
Python: Hack to call a method on an object that isn't of its class
Assume you define a class, which has a method which does some complicated processing: class A(object): def my_method(self): # Some complicated processing is done here return self And now you want to use that method on some object from another class entirely. Like, you want to do A.my_method(7). Thi...
[ "Of course I wouldn't recommend doing this in real code, but yes, sure, you can reach inside of classes and use its methods as functions:\nclass A(object):\n def my_method(self):\n # Some complicated processing is done here\n return 'Hi'\n\nprint(A.__dict__['my_method'](7))\n# Hi\n\n", "You can't...
[ 6, 2, 2, 0, 0, 0, 0, 0 ]
[]
[]
[ "class", "methods", "object", "python" ]
stackoverflow_0002782516_class_methods_object_python.txt
Q: Mutable global variables don't get hide in python functions, right? Please see the following code: def good(): foo[0] = 9 # why this foo isn't local variable who hides the global one def bad(): foo = [9, 2, 3] # foo is local, who hides the global one for func in [good, bad]: foo = [1,2,3] pri...
Mutable global variables don't get hide in python functions, right?
Please see the following code: def good(): foo[0] = 9 # why this foo isn't local variable who hides the global one def bad(): foo = [9, 2, 3] # foo is local, who hides the global one for func in [good, bad]: foo = [1,2,3] print('Before "{}": {}'.format(func.__name__, foo)) func() print('After ...
[ "Because you're not setting foo, you're getting something in foo (foo[0] to be exact).\nIn bad you create a new variable foo. In good you do something like foo.set(0, 9) (set item 0 to value 9). Which is using a variable, and not defining a new name.\n", "Variables will look to their inner scope first then to out...
[ 7, 0, 0, 0 ]
[]
[]
[ "python", "scope" ]
stackoverflow_0002781690_python_scope.txt
Q: Break up a polygon into smaller ones I am working with geodjango and I want to breakup a 2D Rectangular Polygon into smaller ones. My input is a big rectangle and I want to subdivide it in smaller rectangles. The sum of the smaller rectangles must be the original rectangle. All subrectangles should be equal size. ...
Break up a polygon into smaller ones
I am working with geodjango and I want to breakup a 2D Rectangular Polygon into smaller ones. My input is a big rectangle and I want to subdivide it in smaller rectangles. The sum of the smaller rectangles must be the original rectangle. All subrectangles should be equal size. How can I do that? Thank you.
[ "\nPick any point inside the rectangle\nDraw two lines through it parallel to the edges of the rectangle. Now you've divided your rectangle into four smaller ones.\n\n" ]
[ 2 ]
[]
[]
[ "geodjango", "geometry", "gis", "python" ]
stackoverflow_0002783075_geodjango_geometry_gis_python.txt
Q: Can I use django.contrib.gis on GAE? Can I use GeoDjango with GAE / BigTable? A: Another limitation is that the GEOS and GDAL libs aren't available on App Engine. A: No. You can't use Django models on App Engine, and therefore, can't use anything else that uses them, such as django.contrib.gis. A: You might ...
Can I use django.contrib.gis on GAE?
Can I use GeoDjango with GAE / BigTable?
[ "Another limitation is that the GEOS and GDAL libs aren't available on App Engine.\n", "No. You can't use Django models on App Engine, and therefore, can't use anything else that uses them, such as django.contrib.gis.\n", "You might be interested in geohash: read a previous answer of mine.\n" ]
[ 5, 4, 0 ]
[]
[]
[ "django", "gis", "google_app_engine", "python" ]
stackoverflow_0002774723_django_gis_google_app_engine_python.txt
Q: Compare string with all values in list I am trying to fumble through python, and learn the best way to do things. I have a string where I am doing a compare with another string to see if there is a match: if paid[j].find(d)>=0: #BLAH BLAH If d were an list, what is the most efficient way to see if the string ...
Compare string with all values in list
I am trying to fumble through python, and learn the best way to do things. I have a string where I am doing a compare with another string to see if there is a match: if paid[j].find(d)>=0: #BLAH BLAH If d were an list, what is the most efficient way to see if the string contained in paid[j] has a match to any valu...
[ "If you only want to know if any item of d is contained in paid[j], as you literally say:\nif any(x in paid[j] for x in d): ...\n\nIf you also want to know which items of d are contained in paid[j]:\ncontained = [x for x in d if x in paid[j]]\n\ncontained will be an empty list if no items of d are contained in paid...
[ 56, 11, 10, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002783969_python.txt
Q: Python - copy by reference Is there any possibility to copy variable by reference no matter if its int or class instance? My goal is to have two lists of the same objects and when one changes, change is visible in second. In other words i need pointers:/ I simply want int, float and other standard types which are...
Python - copy by reference
Is there any possibility to copy variable by reference no matter if its int or class instance? My goal is to have two lists of the same objects and when one changes, change is visible in second. In other words i need pointers:/ I simply want int, float and other standard types which are normally copied by value, force...
[ "Python always works by reference, unless you explicitly ask for a copy (a slice of a built-in list is deemed to \"ask for a copy\" -- but a slice of a numpy array also works by reference). However, exactly because of that, alist=anotherlist; alist.sort() means the single list objects (with two equivalent names al...
[ 9, 8, 1, 0, 0 ]
[]
[]
[ "python", "reference" ]
stackoverflow_0002783489_python_reference.txt
Q: Python - How to catch outside exceptions inside methods I want to know if there would be a way to catch exceptions inside called methods. Example: def foo(value): print value foo(x) This would throw a NameError exception, because x is not declared. I'd like to catch this NameError exception inside foo method...
Python - How to catch outside exceptions inside methods
I want to know if there would be a way to catch exceptions inside called methods. Example: def foo(value): print value foo(x) This would throw a NameError exception, because x is not declared. I'd like to catch this NameError exception inside foo method. Is there a way?
[ "The NameError occurs when x is attempted to be evaluated. foo is never entered, so you can't catch the NameError inside foo.\nI think what you think is that when you do foo(x), foo is entered, and then x is looked up. You'd like to say, \"I don't know what x is\", instead of letting a NameError get raised.\nUnfo...
[ 9, 1 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0002784695_exception_python.txt
Q: Is it possible to use P4Python API with IronPython? Is it possible to use P4Python (the perforce python api) with IronPython? I'd like to use the python api because it seems much faster than using p4.net implementionat of a Perforce API but when I try to import p4 into IronPython I receive the following error. Ir...
Is it possible to use P4Python API with IronPython?
Is it possible to use P4Python (the perforce python api) with IronPython? I'd like to use the python api because it seems much faster than using p4.net implementionat of a Perforce API but when I try to import p4 into IronPython I receive the following error. IronPython 2.6.1 (2.6.10920.0) on .NET 4.0.30128.1 Type "...
[ "I guess P4API is CPython extension so it does not work in IronPython. In that case, try ironclad.\n" ]
[ 1 ]
[]
[]
[ "ironpython", "p4python", "perforce", "python" ]
stackoverflow_0002783285_ironpython_p4python_perforce_python.txt
Q: Assign variable with variable in function Let's say we have def Foo(Bar=0,Song=0): print(Bar) print(Song) And I want to assign any one of the two parameters in the function with the variable sing and SongVal: Sing = Song SongVal = 2 So that it can be run like: Foo(Sing=SongVal) Where Sing would assign...
Assign variable with variable in function
Let's say we have def Foo(Bar=0,Song=0): print(Bar) print(Song) And I want to assign any one of the two parameters in the function with the variable sing and SongVal: Sing = Song SongVal = 2 So that it can be run like: Foo(Sing=SongVal) Where Sing would assign the Song parameter to the SongVal which is 2. ...
[ "What you're looking for is the **kwargs way of passing arbitrary keyword arguments:\nkwargs = {Sing: SongVal}\nfoo(**kwargs)\n\nSee section 4.7 of the tutorial at www.python.org for more examples.\n" ]
[ 4 ]
[]
[]
[ "function", "python" ]
stackoverflow_0002784977_function_python.txt
Q: What are some strategies for maintaining a common database schema with a team of developers and no DBA? I'm curious about how others have approached the problem of maintaining and synchronizing database changes across many (10+) developers without a DBA? What I mean, basically, is that if someone wants to make a c...
What are some strategies for maintaining a common database schema with a team of developers and no DBA?
I'm curious about how others have approached the problem of maintaining and synchronizing database changes across many (10+) developers without a DBA? What I mean, basically, is that if someone wants to make a change to the database, what are some strategies to doing that? (i.e. I've created a 'Car' model and now I wan...
[ "The solution is rather administrative then technical :)\nThe general rule is easy, there should only be tree-like dependencies in the project:\n- There should always be a single master source of schema, stored together with the project source code in the version control\n- Everything affected by the change in the ...
[ 2, 1, 1, 1 ]
[]
[]
[ "database", "database_schema", "postgresql", "python", "sqlalchemy" ]
stackoverflow_0002748946_database_database_schema_postgresql_python_sqlalchemy.txt
Q: Capture global touch events (Symbian) Basically I wanted what the pys60 module keycapture does (global capture of keystrokes) but I wanted to do this with the touchscreen. So if the program is running, all touch events can be intercepted and logged by the program. How is this possible? A: Not quite sure if I und...
Capture global touch events (Symbian)
Basically I wanted what the pys60 module keycapture does (global capture of keystrokes) but I wanted to do this with the touchscreen. So if the program is running, all touch events can be intercepted and logged by the program. How is this possible?
[ "Not quite sure if I understand, but I am witnessing a plug-in kind of touch-screen interceptor that uses FEP (Front End Processor). This way some people override standard touch-screen keyboard.\nhttp://www.google.com/search?hl=en&source=hp&q=S60+Front+End+Processor&aq=f&aqi=&aql=&oq=&gs_rfai=\n" ]
[ 0 ]
[]
[]
[ "nokia", "pys60", "python", "s60", "symbian" ]
stackoverflow_0002744691_nokia_pys60_python_s60_symbian.txt
Q: SQLAlchemy introspection of ORM classes/objects I am looking for a way to introspect SQLAlchemy ORM classes/entities to determine the types and other constraints (like maximum lengths) of an entity's properties. For example, if I have a declarative class: class User(Base): __tablename__ = "USER_TABLE" id ...
SQLAlchemy introspection of ORM classes/objects
I am looking for a way to introspect SQLAlchemy ORM classes/entities to determine the types and other constraints (like maximum lengths) of an entity's properties. For example, if I have a declarative class: class User(Base): __tablename__ = "USER_TABLE" id = sa.Column(sa.types.Integer, primary_key=True) f...
[ "Something like:\ntable = User.__table__\nfield = table.c[\"fullname\"]\nprint \"Type\", field.type\nprint \"Length\", field.type.length\nprint \"Nullable\", field.nullable\n\nEDIT:\nThe upcoming 0.8 version has a New Class Inspection System:\n\nNew Class Inspection System\nStatus: completed, needs docs\nLots of SQ...
[ 11 ]
[]
[]
[ "introspection", "python", "sqlalchemy" ]
stackoverflow_0002784986_introspection_python_sqlalchemy.txt
Q: Include upper bound in range() How can I include the upper bound in range() function? I can't add by 1 because my for-loop looks like: for x in range(1,math.floor(math.sqrt(x))): y = math.sqrt(n - x * x) But as I understand it will actually be 1 < x < M where I need 1 < x <= M Adding 1 will completely change ...
Include upper bound in range()
How can I include the upper bound in range() function? I can't add by 1 because my for-loop looks like: for x in range(1,math.floor(math.sqrt(x))): y = math.sqrt(n - x * x) But as I understand it will actually be 1 < x < M where I need 1 < x <= M Adding 1 will completely change the result. I am trying to rewrite ...
[ "Just add one to the second argument of your range function:\nrange(1,math.floor(math.sqrt(x))+1)\nYou could also use this:\nrange(math.floor(math.sqrt(x)))\nand then add one inside your loop. The former will be faster, however.\nAs an additional note, unless you're working with Python 3, you should be using xrang...
[ 8, 4 ]
[]
[]
[ "python" ]
stackoverflow_0002785370_python.txt