title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How do I write a unix filter in python?
1,589,994
9
2009-10-19T17:24:43Z
1,590,058
7
2009-10-19T17:38:29Z
[ "python", "unix", "filter" ]
I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars `x` from stdin.
I don't know exactly what you mean by buffered in this context, but it is pretty simple to do what you are asking... so\_gen.py (generating a constant stream that we can watch): ``` import time import sys while True: for char in 'abcdefx': sys.stdout.write(char) sys.stdout.flush() time.sle...
How do I write a unix filter in python?
1,589,994
9
2009-10-19T17:24:43Z
1,590,069
8
2009-10-19T17:40:43Z
[ "python", "unix", "filter" ]
I want to write a program that reads stdin (unbuffered) and writes stdout (unbuffered) doing some trivial char-by-char transformation. For the sake of the example let's say I want to remove all chars `x` from stdin.
You can use the [`fileinput` class](http://docs.python.org/library/fileinput.html), which lets you process inputs like the Perl diamond operator would. From the docs: ``` import fileinput for line in fileinput.input(): process(line) ``` where process does something like `print line.replace('x','')`. You can foll...
Cache a django view that has URL parameters
1,590,372
9
2009-10-19T18:41:59Z
1,590,735
12
2009-10-19T19:50:09Z
[ "python", "django", "memcached" ]
I have recently implemented Django's excellent cache framework. However from what I understand Django will not cache a view that is passed parameters in a get request. I have an Ajax view that is passed get parameters that I would like to cache for X seconds, what would be an easy way to do this? In psuedo code I curr...
Right, vary headers is not the correct solution, it's used when you want to cache based on client request headers like user-agent etc. You'll need to use [low-level API](http://docs.djangoproject.com/en/dev/topics/cache/#the-low-level-cache-api) or [template fragment caching](http://docs.djangoproject.com/en/dev/topic...
Cache a django view that has URL parameters
1,590,372
9
2009-10-19T18:41:59Z
1,640,573
8
2009-10-28T22:34:01Z
[ "python", "django", "memcached" ]
I have recently implemented Django's excellent cache framework. However from what I understand Django will not cache a view that is passed parameters in a get request. I have an Ajax view that is passed get parameters that I would like to cache for X seconds, what would be an easy way to do this? In psuedo code I curr...
Yes, you can use django-view-cache-utils, here is code for your case: ``` from view_cache_utils import cache_page_with_prefix from django.utils.hashcompat import md5_constructor ... @cache_page_with_prefix(60*15, lambda request: md5_constructor(request.get_full_path()).hexdigest()) def my_view(request): ... ```
Is it possible to forward-declare a function in Python?
1,590,608
80
2009-10-19T19:29:21Z
1,590,640
45
2009-10-19T19:33:53Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python? I want to sort a list using my own `cmp` function before it is declared. ``` print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) ``` I've organized my code to put the definition of `cmp_configs` method after the invocation. It fails with thi...
If you kick-start your script through the following: ``` if __name__=="__main__": main() ``` then you probably do not have to worry about things like "forward declaration". You see, the interpreter would go loading up all your functions and then start your main() function. Of course, make sure you have all the imp...
Is it possible to forward-declare a function in Python?
1,590,608
80
2009-10-19T19:29:21Z
1,590,655
47
2009-10-19T19:36:32Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python? I want to sort a list using my own `cmp` function before it is declared. ``` print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) ``` I've organized my code to put the definition of `cmp_configs` method after the invocation. It fails with thi...
What you can do is to wrap the invocation into a function of its own. So that ``` foo() def foo(): print "Hi!" ``` will break, but ``` def bar(): foo() def foo(): print "Hi!" bar() ``` will be working properly. General rule in `Python` is *not* that function should be defined higher in the code (as...
Is it possible to forward-declare a function in Python?
1,590,608
80
2009-10-19T19:29:21Z
1,590,657
42
2009-10-19T19:36:50Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python? I want to sort a list using my own `cmp` function before it is declared. ``` print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) ``` I've organized my code to put the definition of `cmp_configs` method after the invocation. It fails with thi...
If you don't want to define a function *before* it's used, and defining it *afterwards* is impossible, what about defining it in some other module? Technically you still define it first, but it's clean. You could create a recursion like the following: ``` def foo(): bar() def bar(): foo() ``` Python's func...
Is it possible to forward-declare a function in Python?
1,590,608
80
2009-10-19T19:29:21Z
1,590,660
7
2009-10-19T19:37:31Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python? I want to sort a list using my own `cmp` function before it is declared. ``` print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) ``` I've organized my code to put the definition of `cmp_configs` method after the invocation. It fails with thi...
No, I don't believe there is any way to forward-declare a function in Python. Imagine you are the Python interpreter. When you get to the line ``` print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) ``` either you know what cmp\_configs is or you don't. In order to proceed, you have to know cmp\...
Is it possible to forward-declare a function in Python?
1,590,608
80
2009-10-19T19:29:21Z
1,590,664
8
2009-10-19T19:38:52Z
[ "python", "forward-declaration" ]
Is it possible to forward-declare a function in Python? I want to sort a list using my own `cmp` function before it is declared. ``` print "\n".join([str(bla) for bla in sorted(mylist, cmp = cmp_configs)]) ``` I've organized my code to put the definition of `cmp_configs` method after the invocation. It fails with thi...
If the call to cmp\_configs is inside its own function definition, you should be fine. I'll give an example. ``` def a(): b() # b() hasn't been defined yet, but that's fine because at this point, we're not # actually calling it. We're just defining what should happen when a() is called. a() # This call fai...
Clojure prime numbers lazy sequence
1,590,716
7
2009-10-19T19:46:12Z
1,591,051
10
2009-10-19T20:46:22Z
[ "python", "clojure" ]
What is the Clojure equivalent (for the exact algorithm) of the following Python code? ``` from itertools import count from math import sqrt def prime_gen(): primes = [] for n in count(2): if all(n%p for p in primes if p <= sqrt(n)): primes.append(n) yield n ```
This is as Pythonish as I can make it: ``` (def prime-gen (let [primes (atom [])] (for [n (iterate inc 2) :when (not-any? #(zero? (rem n %)) (filter #(<= % (Math/sqrt n)) @primes))] (do (swap! primes conj n) ...
Python: How can I know which exceptions might be thrown from a method call
1,591,319
45
2009-10-19T21:43:36Z
1,591,337
23
2009-10-19T21:51:39Z
[ "python", "exception" ]
Is there a way knowing (at coding time) which exceptions to expect when executing python code? I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown(and don't tell me to read the documentation. many times an exception can be propagated from the deep. and many...
You should only catch exceptions that you will handle. Catching all exceptions by their concrete types is nonsense. You should catch specific exceptions you *can* and *will* handle. For other exceptions, you may write a generic catch that catches "base Exception", logs it (use `str()` function) and terminates your pro...
Python: How can I know which exceptions might be thrown from a method call
1,591,319
45
2009-10-19T21:43:36Z
1,591,368
8
2009-10-19T21:56:46Z
[ "python", "exception" ]
Is there a way knowing (at coding time) which exceptions to expect when executing python code? I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown(and don't tell me to read the documentation. many times an exception can be propagated from the deep. and many...
The correct tool to solve this problem is unittests. If you are having exceptions raised by real code that the unittests do not raise, then you need more unittests. Consider this ``` def f(duck): try: duck.quack() except ??? could be anything ``` duck can be any object Obviously you can have an `Att...
Python: How can I know which exceptions might be thrown from a method call
1,591,319
45
2009-10-19T21:43:36Z
1,591,432
14
2009-10-19T22:15:17Z
[ "python", "exception" ]
Is there a way knowing (at coding time) which exceptions to expect when executing python code? I end up catching the base Exception class 90% of the time since I don't know which exception type might be thrown(and don't tell me to read the documentation. many times an exception can be propagated from the deep. and many...
I guess a solution could be only imprecise because of lack of static typing rules. I'm not aware of some tool that checks exceptions, but you could come up with your own tool matching your needs (a good chance to play a little with static analysis). As a first attempt, you could write a function that builds an AST, f...
How to update/modify a XML file in python?
1,591,579
8
2009-10-19T22:52:30Z
1,591,655
12
2009-10-19T23:12:10Z
[ "python", "xml", "io" ]
I have a xml file that I would like to update after it has already data. I thought about open the xml file in "a" (append) mode. The problem is that the new data will start to be dumped after the "root" tag has been closed. What I wanted someone to be kind enough to tell me is how can I delete the last line of a file...
Useful Python XML parsers: 1. [Minidom](http://docs.python.org/library/xml.dom.minidom.html) - functional but limited 2. [ElementTree](http://effbot.org/zone/element-index.htm) - decent performance, more functionality 3. [lxml](http://lxml.de/) - high-performance *in most cases*, high functionality including real xpat...
How to update/modify a XML file in python?
1,591,579
8
2009-10-19T22:52:30Z
27,934,162
16
2015-01-14T00:52:58Z
[ "python", "xml", "io" ]
I have a xml file that I would like to update after it has already data. I thought about open the xml file in "a" (append) mode. The problem is that the new data will start to be dumped after the "root" tag has been closed. What I wanted someone to be kind enough to tell me is how can I delete the last line of a file...
Using `ElementTree`: ``` import xml.etree.ElementTree # Open original file et = xml.etree.ElementTree.parse('file.xml') # Append new tag: <a x='1' y='abc'>body text</a> new_tag = xml.etree.ElementTree.SubElement(et.getroot(), 'a') new_tag.text = 'body text' new_tag.attrib['x'] = '1' # must be str; cannot be an int n...
How to make all combinations of the elements in an array?
1,591,762
2
2009-10-19T23:51:01Z
1,591,774
7
2009-10-19T23:56:35Z
[ "python" ]
I have a list. It contains x lists, each with y elements. I want to pair each element with all the other elements, just once, (a,b = b,a) EDIT: this has been criticized as being too vague.So I'll describe the history. My function produces random equations and using genetic techniques, mutates and crossbreeds them, sel...
`itertools.product` is your friend. about removing the duplicates, try with a set of sets. Now it's a little bit clearer what you want: ``` import itertools def recombinate(families): "families is the list of 8 elements, each one with 12 individuals" for fi, fj in itertools.combinations(families, 2): ...
How do I go about setting up a TDD development process with Google App Engine?
1,591,875
15
2009-10-20T00:31:05Z
1,592,003
26
2009-10-20T01:25:29Z
[ "python", "unit-testing", "google-app-engine", "tdd" ]
I'm primarily a Ruby guy, but lately I've been working on a lot of Python stuff, in particular, App Engine code. In Ruby, I'd use automated continuous integration ([autotest](http://www.zenspider.com/ZSS/Products/ZenTest/)), code coverage tools ([rcov](http://github.com/relevance/rcov)), static analysis ([reek](http://...
You won't always find one to one equivalents of Ruby testing tools in Python, but there are some great testing tools in Python. Some of the tools that I've found useful include: * [unittest](http://docs.python.org/library/unittest.html) - the xUnit tool included in the Python standard library. It includes all the basi...
How do I go about setting up a TDD development process with Google App Engine?
1,591,875
15
2009-10-20T00:31:05Z
1,592,108
15
2009-10-20T02:07:44Z
[ "python", "unit-testing", "google-app-engine", "tdd" ]
I'm primarily a Ruby guy, but lately I've been working on a lot of Python stuff, in particular, App Engine code. In Ruby, I'd use automated continuous integration ([autotest](http://www.zenspider.com/ZSS/Products/ZenTest/)), code coverage tools ([rcov](http://github.com/relevance/rcov)), static analysis ([reek](http://...
On my GAE project, I use: * [NoseGAE](http://code.google.com/p/nose-gae/)—This is the critical piece that ties all the rest together * Mock, as in John's excellent answer. I use this largely for AWS and other web services * Fixtures (the package, not the idea) I also prefer many of Rails's idioms. I broke my tests in...
Python binary data reading
1,591,920
3
2009-10-20T00:51:46Z
1,592,361
10
2009-10-20T04:00:48Z
[ "python", "binary-data" ]
A urllib2 request receives binary response as below: ``` 00 00 00 01 00 04 41 4D 54 44 00 00 00 00 02 41 97 33 33 41 99 5C 29 41 90 3D 71 41 91 D7 0A 47 0F C6 14 00 00 01 16 6A E0 68 80 41 93 B4 05 41 97 1E B8 41 90 7A E1 41 96 8F 57 46 E6 2E 80 00 00 01 16 7A 53 7C 80 FF FF ``` Its structure is: ``` DATA, TYPE, DES...
So here's my best shot at interpreting the data you're giving...: ``` import datetime import struct class Printable(object): specials = () def __str__(self): resultlines = [] for pair in self.__dict__.items(): if pair[0] in self.specials: continue resultlines.append('%10s %s' % pair) retur...
A simple framework for Google App Engine (like Sinatra)?
1,592,088
5
2009-10-20T01:59:57Z
1,593,411
7
2009-10-20T09:21:32Z
[ "python", "google-app-engine", "web-frameworks" ]
Is there a simple 'wrapper' framework for appengine? Something like [Sinatra](http://www.sinatrarb.com/) or [Juno](http://github.com/breily/juno)? So that one can write code like the following: ``` from juno import * @route('/') def index(web): return 'Juno says hi' run() ``` **UPDATE**: I want to use the Pytho...
There are several frameworks either specifically for App Engine, or well suited to it: * [web.py](http://webpy.org/) - Not specifically for App Engine, but well suited. * [Google App Engine Oil](http://code.google.com/p/google-app-engine-oil/) * [web2py](http://code.google.com/p/web2py/) - Also not specifically for Ap...
Convert hex to float
1,592,158
20
2009-10-20T02:32:02Z
1,592,200
10
2009-10-20T02:49:58Z
[ "python", "binary", "floating-point", "hex", "decimal" ]
How to convert the following hex string to float (single precision 32-bit) in Python? ``` "41973333" -> 1.88999996185302734375E1 "41995C29" -> 1.91700000762939453125E1 "470FC614" -> 3.6806078125E4 ```
I recommend using [the ctypes module](http://docs.python.org/library/ctypes.html) which basically lets you work with low level data types. In your case you could say ``` from ctypes import * def convert(s): i = int(s, 16) # convert from hex to a Python int cp = pointer(c_int(i)) # ...
Convert hex to float
1,592,158
20
2009-10-20T02:32:02Z
1,592,362
36
2009-10-20T04:00:51Z
[ "python", "binary", "floating-point", "hex", "decimal" ]
How to convert the following hex string to float (single precision 32-bit) in Python? ``` "41973333" -> 1.88999996185302734375E1 "41995C29" -> 1.91700000762939453125E1 "470FC614" -> 3.6806078125E4 ```
``` >>> import struct >>> struct.unpack('!f', '41973333'.decode('hex'))[0] 18.899999618530273 >>> struct.unpack('!f', '41995C29'.decode('hex'))[0] 19.170000076293945 >>> struct.unpack('!f', '470FC614'.decode('hex'))[0] 36806.078125 ``` Update: see comment on how to do this in Python 3.
Decoding Mac OS text in Python
1,592,925
6
2009-10-20T07:05:44Z
1,592,936
8
2009-10-20T07:09:54Z
[ "python", "osx" ]
I'm writing some code to parse RTF documents, and need to handle the various codepages they can use. Python comes with decoders for all the necessary Windows codepages, but I'm not sure how to handle the Mac ones: ``` # 77: "10000", # Mac Roman # 78: "10001", # Mac Shift Jis # 79: "10003", # Mac Hangul # 80: "10008", ...
You can use the python codecs for these that are known by their names 'mac-roman', 'mac-turkish', etc. ``` >>> 'foo'.decode('mac-turkish') u'foo' ``` You'll have to refer to them by their names, these numbers you've got in your question don't appear in the source files. For more information look at `$pylib/encodings/...
Is there any simple way to benchmark python script?
1,593,019
39
2009-10-20T07:40:54Z
1,593,034
60
2009-10-20T07:45:04Z
[ "python", "unix", "shell", "benchmarking" ]
Usually I use shell command `time`. My purpose is to test if data is small, medium, large or very large set, how much time and memory usage will be. Any tools for linux or just python to do this?
Have a look at [timeit](http://docs.python.org/library/timeit.html), [the python profiler](http://docs.python.org/library/profile.html) and [pycallgraph](https://pycallgraph.readthedocs.org/en/master/). ## timeit ``` def test(): """Stupid test function""" lst = [] for i in range(100): lst.append(i...
Is there any simple way to benchmark python script?
1,593,019
39
2009-10-20T07:40:54Z
11,151,365
14
2012-06-22T06:46:52Z
[ "python", "unix", "shell", "benchmarking" ]
Usually I use shell command `time`. My purpose is to test if data is small, medium, large or very large set, how much time and memory usage will be. Any tools for linux or just python to do this?
I use a simple decorator to time the func ``` def st_time(func): """ st decorator to calculate the total time of a func """ def st_func(*args, **keyArgs): t1 = time.time() r = func(*args, **keyArgs) t2 = time.time() print "Function=%s, Time=%s" % (func.__name__, t2 ...
How do I check if the python debug option is set from within a script
1,593,274
7
2009-10-20T08:50:46Z
1,593,355
9
2009-10-20T09:08:05Z
[ "python", "script-debugging" ]
If I'm in debug mode, I want to do other stuff than when I'm not. ``` if DEBUG: STORED_DATA_FILE = os.path.join(TEMP_DIR, 'store.dat') LOG_LEVEL = logging.DEBUG print "debug mode" else: STORED_DATA_FILE = os.path.join(SCRIPT_PATH, 'store.dat') LOG_LEVEL = logging.INFO print "not debug mode" ```...
you can use `python -O` with the `__debug__` variable where `-O` means optimise. so `__debug__` is false `-d` turns on debugging for the parser, which is not what you want
python queue get(),task_done() question
1,593,299
18
2009-10-20T08:54:43Z
1,593,330
34
2009-10-20T09:00:46Z
[ "python", "queue" ]
my consumer side of the queue: ``` m = queue.get() queue.task_done() <rest of the program> ``` questions: 1. does task\_done() effectively pop m off the queue and release whatever locks the consumer has on the queue? 2. i need to use m during the rest of the program. is it safe, or do i need to copy it before i cal...
No, `queue.get()` pops the item off the queue. After you do that, you can do whatever you want with it, as long as the producer works like it should and doesn't touch it anymore. `queue.task_done()` is called only to notify the queue that you are done with something (it doesn't even know about the specific item, it jus...
Python: How to check if a nested list is essentially empty?
1,593,564
6
2009-10-20T09:57:24Z
1,593,759
7
2009-10-20T10:38:54Z
[ "python", "list" ]
Is there a Pythonic way to **check** if a *list* (a *nested* list with elements & lists) is essentially **empty**? What I mean by empty here is that the list might have elements, but those are also empty lists. The Pythonic way to check an empty list works only on a flat list: ``` alist = [] if not alist: print("...
Simple code, works for any iterable object, not just lists: ``` >>> def empty(seq): ... try: ... return all(map(empty, seq)) ... except TypeError: ... return False ... >>> empty([]) True >>> empty([4]) False >>> empty([[]]) True >>> empty([[], []]) True >>> empty([[], [8]]) False >>> empty([[],...
Python: How to check if a nested list is essentially empty?
1,593,564
6
2009-10-20T09:57:24Z
1,593,797
9
2009-10-20T10:51:43Z
[ "python", "list" ]
Is there a Pythonic way to **check** if a *list* (a *nested* list with elements & lists) is essentially **empty**? What I mean by empty here is that the list might have elements, but those are also empty lists. The Pythonic way to check an empty list works only on a flat list: ``` alist = [] if not alist: print("...
If you do not need to iterate through the lists, simpler is better, so something like this will work: ``` def empty_tree(input_list): """Recursively iterate through values in nested lists.""" for item in input_list: if not isinstance(item, list) or not empty_tree(item): return False re...
Python: How to check if a nested list is essentially empty?
1,593,564
6
2009-10-20T09:57:24Z
1,605,679
7
2009-10-22T08:11:16Z
[ "python", "list" ]
Is there a Pythonic way to **check** if a *list* (a *nested* list with elements & lists) is essentially **empty**? What I mean by empty here is that the list might have elements, but those are also empty lists. The Pythonic way to check an empty list works only on a flat list: ``` alist = [] if not alist: print("...
I have combined the use of `isinstance()` by **Ants Aasma** and `all(map())` by **Stephan202**, to form the following solution. `all([])` returns `True` and the function relies on this behaviour. I think it has the best of both and is better since it does not rely on the `TypeError` exception. ``` def isListEmpty(inLi...
Making Django admin display the Primary Key rather than each object's Object type
1,594,436
11
2009-10-20T12:58:26Z
1,594,453
26
2009-10-20T13:00:35Z
[ "python", "django", "admin" ]
In Django 1.1 admin, when I go to add or change an object, my objects are displayed as: ``` Select host to change * Add host Host object Host object Host object Host object Host object ``` This happens for all models in my site, not just Hosts. Rather than display the same name for each obje...
Add a [`__unicode__()`](http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.__unicode__) method to `Host`. To show the primary key of your host objects, you'd want something like: ``` class Host(models.Model): host = models.CharField(max_length=100, primary_key=True) def __unicod...
Making Django admin display the Primary Key rather than each object's Object type
1,594,436
11
2009-10-20T12:58:26Z
1,594,468
10
2009-10-20T13:03:07Z
[ "python", "django", "admin" ]
In Django 1.1 admin, when I go to add or change an object, my objects are displayed as: ``` Select host to change * Add host Host object Host object Host object Host object Host object ``` This happens for all models in my site, not just Hosts. Rather than display the same name for each obje...
`contrib.admin` has been reworked in 1.0, and old `Admin` classes inside models no longer work. What you need is `ModelAdmin` subclass in `your_application.admin` module, e.g. ``` from your_application.models import Host from django.contrib import admin class HostAdmin(admin.ModelAdmin): list_display = ('host',) ...
SPARQL Query gives unexpected result
1,594,518
7
2009-10-20T13:12:33Z
1,594,959
7
2009-10-20T14:22:28Z
[ "python", "rdf", "sparql", "rdflib" ]
I hope someone can help me on this probably totally easy-to-solve problem: I want to run a SPARQL query against the following RDF (noted in N3, the RDF/XMl sits [here](http://rdf.schalljugend.net/umstaetter.rdf)). This is the desription of a journal article and descriptions of the journal, author and publisher: ``` ...
I don't think that you can use a QName in an XML attribute value; e.g. the value of `rdf:about`. So consider this line from your RDF/XML file: ``` <bibo:Journal rdf:about="ex:bibdienst"> ``` I think that this is actually saying that the subject URI is "ex:bibdienst". That is a syntactically valid URI, but it is not ...
Cleaning build directory in setup.py
1,594,827
23
2009-10-20T14:01:15Z
1,594,896
56
2009-10-20T14:12:39Z
[ "python", "build", "distutils" ]
How could I make my `setup.py` pre-delete and post-delete the build directory?
Does [this](http://docs.python.org/distutils/apiref.html#module-distutils.command.clean) answer it? IIRC, you'll need to use the `--all` flag to get rid of stuff outside of `build/lib`: ``` python setup.py clean --all ```
Why do simple math operations on floating point return unexpected (inaccurate) results in VB.Net and Python?
1,594,985
2
2009-10-20T14:25:03Z
1,594,999
13
2009-10-20T14:27:40Z
[ "python", "vb.net", "floating-point" ]
``` x = 4.2 - 0.1 ``` vb.net gives `4.1000000000000005` python gives `4.1000000000000005` Excel gives `4.1` [Google calc](http://www.google.com/search?q=4.2-.1) gives `4.1` What is the reason this happens?
[Float/double precision.](http://en.wikipedia.org/wiki/Floating%5Fpoint) You must remember that in binary, 4.1 = 4 + 1/10. 1/10 is an infinitely repeating sum in binary, much like 1/9 is an infinite sum in decimal.
Why do simple math operations on floating point return unexpected (inaccurate) results in VB.Net and Python?
1,594,985
2
2009-10-20T14:25:03Z
1,595,044
10
2009-10-20T14:32:07Z
[ "python", "vb.net", "floating-point" ]
``` x = 4.2 - 0.1 ``` vb.net gives `4.1000000000000005` python gives `4.1000000000000005` Excel gives `4.1` [Google calc](http://www.google.com/search?q=4.2-.1) gives `4.1` What is the reason this happens?
``` >>> x = 4.2 - 0.1 >>> x 4.1000000000000005 >>>>print(x) 4.1 ``` This happens because of [how numbers are stored internally](http://en.wikipedia.org/wiki/Floating%5Fpoint). Computers represent numbers in binary, instead of decimal, as us humans are used to. With floating point numbers, computers have to make an ...
blocks - send input to python subprocess pipeline
1,595,492
28
2009-10-20T15:30:51Z
1,616,457
18
2009-10-23T23:33:38Z
[ "python", "ipc", "pipe", "subprocess", "blocking" ]
I'm testing subprocesses pipelines with python. I'm aware that I can do what the programs below do in python directly, but that's not the point. I just want to test the pipeline so I know how to use it. My system is Linux Ubuntu 9.04 with default python 2.6. I started with this [documentation example](http://docs.pyt...
I found out how to do it. It is not about threads, and not about select(). When I run the first process (`grep`), it creates two low-level file descriptors, one for each pipe. Lets call those `a` and `b`. When I run the second process, `b` gets passed to `cut` `sdtin`. But there is a brain-dead default on `Popen` - ...
Threading in a PyQt application: Use Qt threads or Python threads?
1,595,649
74
2009-10-20T15:54:19Z
1,595,690
23
2009-10-20T15:59:08Z
[ "python", "multithreading", "pyqt" ]
I'm writing a GUI application that regularly retrieves data through a web connection. Since this retrieval takes a while, this causes the UI to be unresponsive during the retrieval process (it cannot be split into smaller parts). This is why I'd like to outsource the web connection to a separate worker thread. [Yes, I...
Python's threads will be simpler and safer, and since it is for an I/O-based application, they are able to bypass the GIL. That said, have you considered non-blocking I/O using Twisted or non-blocking sockets/select? **EDIT: more on threads** **Python threads** Python's threads are system threads. However, Python us...
Threading in a PyQt application: Use Qt threads or Python threads?
1,595,649
74
2009-10-20T15:54:19Z
1,595,754
19
2009-10-20T16:11:23Z
[ "python", "multithreading", "pyqt" ]
I'm writing a GUI application that regularly retrieves data through a web connection. Since this retrieval takes a while, this causes the UI to be unresponsive during the retrieval process (it cannot be split into smaller parts). This is why I'd like to outsource the web connection to a separate worker thread. [Yes, I...
The advantage of `QThread` is that it's integrated with the rest of the Qt library. That is, thread-aware methods in Qt will need to know in which thread they run, and to move objects between threads, you will need to use `QThread`. Another useful feature is running your own event loop in a thread. If you are accessin...
Threading in a PyQt application: Use Qt threads or Python threads?
1,595,649
74
2009-10-20T15:54:19Z
1,628,262
11
2009-10-27T01:17:08Z
[ "python", "multithreading", "pyqt" ]
I'm writing a GUI application that regularly retrieves data through a web connection. Since this retrieval takes a while, this causes the UI to be unresponsive during the retrieval process (it cannot be split into smaller parts). This is why I'd like to outsource the web connection to a separate worker thread. [Yes, I...
I asked myself the same question when I was working to [PyTalk](http://pytalk.trunat.fr/). If you are using Qt, you need to use `QThread` to be able to use the Qt framework and expecially the signal/slot system. With the signal/slot engine, you will be able to talk from a thread to another and with every part of your...
Threading in a PyQt application: Use Qt threads or Python threads?
1,595,649
74
2009-10-20T15:54:19Z
1,645,666
72
2009-10-29T18:28:21Z
[ "python", "multithreading", "pyqt" ]
I'm writing a GUI application that regularly retrieves data through a web connection. Since this retrieval takes a while, this causes the UI to be unresponsive during the retrieval process (it cannot be split into smaller parts). This is why I'd like to outsource the web connection to a separate worker thread. [Yes, I...
This was [discussed](http://www.mail-archive.com/[email protected]/msg16050.html) not too long ago in PyQt mailing list. Quoting Giovanni Bajo's [comments](http://www.mail-archive.com/[email protected]/msg16052.html) on the subject: > It's mostly the same. The main difference is that QThreads are b...
filtering lists in python
1,596,390
4
2009-10-20T18:12:40Z
1,596,399
12
2009-10-20T18:14:26Z
[ "python", "list", "unique" ]
I want to filter repeated elements in my list for instance ``` foo = ['a','b','c','a','b','d','a','d'] ``` I am only interested with: ``` ['a','b','c','d'] ``` What would be the efficient way to do achieve this ? Cheers
Cast foo to a [set](http://docs.python.org/library/stdtypes.html#set), if you don't care about element order.
filtering lists in python
1,596,390
4
2009-10-20T18:12:40Z
1,596,400
20
2009-10-20T18:14:27Z
[ "python", "list", "unique" ]
I want to filter repeated elements in my list for instance ``` foo = ['a','b','c','a','b','d','a','d'] ``` I am only interested with: ``` ['a','b','c','d'] ``` What would be the efficient way to do achieve this ? Cheers
`list(`[`set`](http://docs.python.org/library/stdtypes.html#set)`(foo))` if you are using Python 2.5 or greater, but that doesn't maintain order.
django urls without a trailing slash do not redirect
1,596,552
42
2009-10-20T18:41:56Z
1,596,600
58
2009-10-20T18:49:39Z
[ "python", "django", "django-urls" ]
I've got two applications located on two separate computers. On computer A, in the `urls.py` file I have a line like the following: ``` (r'^cast/$', 'mySite.simulate.views.cast') ``` And that url will work for both `mySite.com/cast/` and `mySite.com/cast`. But on computer B I have a similar url written out like: ```...
check your `APPEND_SLASH` setting in the settings.py file [more info in the django docs](http://docs.djangoproject.com/en/dev/ref/settings/#append-slash)
django urls without a trailing slash do not redirect
1,596,552
42
2009-10-20T18:41:56Z
11,690,144
100
2012-07-27T14:44:14Z
[ "python", "django", "django-urls" ]
I've got two applications located on two separate computers. On computer A, in the `urls.py` file I have a line like the following: ``` (r'^cast/$', 'mySite.simulate.views.cast') ``` And that url will work for both `mySite.com/cast/` and `mySite.com/cast`. But on computer B I have a similar url written out like: ```...
Or you can write your urls like this: ``` (r'^login/?$', 'mySite.myUser.views.login') ``` The question sign after the trailing slash makes it optional in regexp. Use it if for some reasons you don't want to use APPEND\_SLASH setting.
XML Parsing with Python and minidom
1,596,829
12
2009-10-20T19:36:07Z
1,598,016
7
2009-10-21T00:04:10Z
[ "python", "xml", "minidom" ]
I'm using Python (minidom) to parse an XML file that prints a hierarchical structure that looks something like this (indentation is used here to show the significant hierarchical relationship): ``` My Document Overview Basic Features About This Software Platforms Supported ``` Instead, the program ite...
Let me put that comment here ... Thanks for the attempt. It didn't work but it gave me some ideas. The following works (the same general idea; FWIW, the nodeType is ELEMENT\_NODE): ``` import xml.dom.minidom from xml.dom.minidom import Node dom = xml.dom.minidom.parse("docmap.xml") def getChildrenByTitle(node): ...
Read a file from server with ssh using python
1,596,963
18
2009-10-20T20:04:00Z
1,597,750
32
2009-10-20T22:53:20Z
[ "python", "file-io" ]
I am trying to read a file from a server using ssh from python. I am using paramiko to connect. I can connect to the server and run a command like 'cat filename' and get the data back from the server but some files I am trying to read are around 1 GB or more in size. How can I read the file on the server line by line ...
[Paramiko's](https://github.com/paramiko/paramiko) `SFTPClient` class allows you to get a file-like object to read data from a remote file in a Pythonic way. Assuming you have an open `SSHClient`: ``` sftp_client = ssh_client.open_sftp() remote_file = sftp_client.open('remote_filename') try: for line in remote_fi...
Read a file from server with ssh using python
1,596,963
18
2009-10-20T20:04:00Z
1,598,554
7
2009-10-21T03:15:19Z
[ "python", "file-io" ]
I am trying to read a file from a server using ssh from python. I am using paramiko to connect. I can connect to the server and run a command like 'cat filename' and get the data back from the server but some files I am trying to read are around 1 GB or more in size. How can I read the file on the server line by line ...
Here's an extension to [@Matt Good's answer](http://stackoverflow.com/questions/1596963/read-a-file-from-server-with-ssh-using-python/1597750#1597750): ``` from contextlib import closing from fabric.network import connect with closing(connect(user, host, port)) as ssh, \ closing(ssh.open_sftp()) as sftp, \ ...
Replace strings in files by Python
1,597,649
10
2009-10-20T22:17:55Z
1,597,739
9
2009-10-20T22:49:27Z
[ "python", "regex", "search", "replace", "operating-system" ]
**How can you replace the match with the given replacement recursively in a given directory and its subdirectories?** ## Pseudo-code ``` import os import re from os.path import walk for root, dirs, files in os.walk("/home/noa/Desktop/codes"): for name in dirs: re.search("dbname=noa user=noa", ...
Do you really need regular expressions? ``` import os def recursive_replace( root, pattern, replace ) for dir, subdirs, names in os.walk( root ): for name in names: path = os.path.join( dir, name ) text = open( path ).read() if pattern in text: open( pat...
Replace strings in files by Python
1,597,649
10
2009-10-20T22:17:55Z
1,597,755
19
2009-10-20T22:54:46Z
[ "python", "regex", "search", "replace", "operating-system" ]
**How can you replace the match with the given replacement recursively in a given directory and its subdirectories?** ## Pseudo-code ``` import os import re from os.path import walk for root, dirs, files in os.walk("/home/noa/Desktop/codes"): for name in dirs: re.search("dbname=noa user=noa", ...
Put all this code into a file called `mass_replace`. Under Linux or Mac OS X, you can do `chmod +x mass_replace` and then just run this. Under Windows, you can run it with `python mass_replace` followed by the appropriate arguments. ``` #!/usr/bin/python import os import re import sys # list of extensions to replace...
Is there a better, pythonic way to do this?
1,597,764
10
2009-10-20T22:58:28Z
1,597,795
7
2009-10-20T23:06:58Z
[ "dictionary", "set", "python" ]
This is my first python program - Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds. Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way? CODE : ``` import csv adDict...
You could shorten the for-loop to this: ``` for row in reader: adDict.setdefault(row[0], set()).add(row[1]) ```
Is there a better, pythonic way to do this?
1,597,764
10
2009-10-20T22:58:28Z
1,597,800
18
2009-10-20T23:08:26Z
[ "dictionary", "set", "python" ]
This is my first python program - Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds. Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way? CODE : ``` import csv adDict...
Congratulations, your code is very nice. There are a few little tricks you could use to make it shorter/simpler. There is a nifty object type called defaultdict which is provided by the collections module. Instead of having to check if adDict has an adId key, you can set up a defaultdict which acts like a regular dict...
Is there a better, pythonic way to do this?
1,597,764
10
2009-10-20T22:58:28Z
1,598,247
10
2009-10-21T01:13:15Z
[ "dictionary", "set", "python" ]
This is my first python program - Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds. Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way? CODE : ``` import csv adDict...
the line of code: ``` adDict[adId] = set(userId) ``` is unlikely to do what you want -- it will treat string `userId` as a sequence of letters, so for example if `userId` was `aleax` you'd get a set with four items, just like, say, `set(['a', 'l', 'e', 'x'])`. Later, an `.add(userId)` when `userId` is `aleax` again w...
Pythonic way to only do work first time a variable is called
1,598,174
6
2009-10-21T00:51:30Z
1,598,204
13
2009-10-21T01:01:54Z
[ "class", "variables", "python", "precompute" ]
my Python class has some variables that require work to calculate the first time they are called. Subsequent calls should just return the precomputed value. I don't want to waste time doing this work unless they are actually needed by the user. So is there a clean Pythonic way to implement this use case? My initial t...
``` class myclass(object): def __init__(self): self.__age=None @property def age(self): if self.__age is None: self.__age=21 #This can be a long computation return self.__age ``` Alex mentioned you can use `__getattr__`, this is how it works ``` class myclass(object): ...
Adding row to numpy recarray
1,598,251
6
2009-10-21T01:14:57Z
1,598,295
9
2009-10-21T01:32:54Z
[ "python", "numpy" ]
Is there an easy way to add a record/row to a numpy recarray without creating a new recarray? Let's say I have a recarray that takes 1Gb in memory, I want to be able to add a row to it without having python take up 2Gb of memory temporarily.
You can call [`yourrecarray.resize`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.recarray.resize.html#numpy.recarray.resize) with a shape which has one more row, then assign to that new row. Of course. `numpy` *might* still have to allocate completely new memory if it just doesn't have room to grow the ar...
Rounding decimals with new Python format function
1,598,579
25
2009-10-21T03:27:10Z
1,598,650
49
2009-10-21T03:56:46Z
[ "python", "string", "python-3.x" ]
How do I round a decimal to a particular number of decimal places using the Python 3.0 `format` function?
Here's a typical, useful example...: ``` >>> n = 4 >>> p = math.pi >>> '{0:.{1}f}'.format(p, n) '3.1416' ``` the nested `{1}` takes the second argument, the current value of n, and applies it as specified (here, to the "precision" part of the format -- number of digits after the decimal point), and the outer resultin...
Pure python solution to convert XHTML to PDF
1,598,715
16
2009-10-21T04:26:37Z
1,605,075
8
2009-10-22T04:51:45Z
[ "python", "google-app-engine", "pdf" ]
I am after a pure Python solution (for the GAE) to convert webpages to pdf. I had a look at [reportlab](http://www.reportlab.org/rl%5Ftoolkit.html) but the documentation focuses on generating pdfs from scratch, rather than converting from HTML. What do you recommend? - [pisa](http://www.xhtml2pdf.com/doc/pisa-en.html...
[Pisa](http://www.xhtml2pdf.com/) claims to support what I want to do: > pisa is a html2pdf converter using the > ReportLab Toolkit, the HTML5lib and > pyPdf. It supports HTML 5 and CSS 2.1 > (and some of CSS 3). It is completely > written in pure Python so it is > platform independent. The main benefit > of this tool...
Python Console Website
1,598,733
14
2009-10-21T04:38:56Z
1,598,755
12
2009-10-21T04:44:44Z
[ "python" ]
I believe that I once saw a website that is like an online Python console. Does anyone know of such a website?
This is one I know of: > <http://shell.appspot.com/> There's also Lord of the REPL's: > <http://lotrepls.appspot.com/> Python on repl.it: > <http://repl.it/languages/Python>
Python Console Website
1,598,733
14
2009-10-21T04:38:56Z
1,598,764
11
2009-10-21T04:46:53Z
[ "python" ]
I believe that I once saw a website that is like an online Python console. Does anyone know of such a website?
While not really a "console", [skulpt.org](http://www.skulpt.org/) runs python code client-side with no plugins or anything, which makes it a lot faster than a server-side prompt. For server side and a more traditional shell I found this: <http://shell.appspot.com/>.
Elegant setup of Python logging in Django
1,598,823
74
2009-10-21T05:07:01Z
1,598,979
44
2009-10-21T06:03:38Z
[ "python", "django", "logging" ]
I have yet to find a way of setting up Python logging with Django that I'm happy with. My requirements are fairly simple: * Different log handlers for different events - that is, I want to be able to log to different files * Easy access to loggers in my modules. The module should be able to find its logger with little...
The best way I've found so far is to initialize logging setup in settings.py - nowhere else. You can either use a configuration file or do it programmatically step-by-step - it just depends on your requirements. The key thing is that I usually add the handlers I want to the root logger, using levels and sometimes loggi...
Elegant setup of Python logging in Django
1,598,823
74
2009-10-21T05:07:01Z
5,806,903
102
2011-04-27T15:50:04Z
[ "python", "django", "logging" ]
I have yet to find a way of setting up Python logging with Django that I'm happy with. My requirements are fairly simple: * Different log handlers for different events - that is, I want to be able to log to different files * Easy access to loggers in my modules. The module should be able to find its logger with little...
I know this is a solved answer already, but as per django >= 1.3 there's a new logging setting. Moving from old to new is not automatic, so I thought i'll write it down here. And of course checkout [the django doc](http://docs.djangoproject.com/en/dev/topics/logging "Django Logging Doc") for some more. This is the b...
Atomic increment of a counter in django
1,598,932
33
2009-10-21T05:49:08Z
1,599,090
51
2009-10-21T06:43:45Z
[ "python", "django", "transactions", "race-condition" ]
I'm trying to atomically increment a simple counter in Django. My code looks like this: ``` from models import Counter from django.db import transaction @transaction.commit_on_success def increment_counter(name): counter = Counter.objects.get_or_create(name = name)[0] counter.count += 1 counter.save() ```...
[New in Django 1.1](http://docs.djangoproject.com/en/dev/topics/db/queries/#query-expressions) ``` Counter.objects.get_or_create(name = name) Counter.objects.filter(name = name).update(count = F('count')+1) ``` or using [an F expression](https://docs.djangoproject.com/en/dev/ref/models/expressions/#f-expressions): `...
Atomic increment of a counter in django
1,598,932
33
2009-10-21T05:49:08Z
8,901,941
11
2012-01-17T21:26:25Z
[ "python", "django", "transactions", "race-condition" ]
I'm trying to atomically increment a simple counter in Django. My code looks like this: ``` from models import Counter from django.db import transaction @transaction.commit_on_success def increment_counter(name): counter = Counter.objects.get_or_create(name = name)[0] counter.count += 1 counter.save() ```...
In Django 1.4 there is [support for SELECT ... FOR UPDATE](https://docs.djangoproject.com/en/dev/releases/1.4/#select-for-update-support) clauses, using database locks to make sure no data is accesses concurrently by mistake.
How can I get an accurate UTC time with Python?
1,599,060
8
2009-10-21T06:34:31Z
1,599,094
19
2009-10-21T06:45:09Z
[ "python", "datetime", "timestamp", "utc" ]
I wrote a desktop application and was using `datetime.datetime.utcnow()` for timestamping, however I've recently noticed that some people using the application get wildly different results than I do when we run the program at the same time. Is there any way to get the UTC time locally without using urllib to fetch it f...
Python depends on the underlying operating system to provide an accurate time-of-day clock. If it isn't doing that, you don't have much choice other than to bypass the o/s. There's a pure-Python implementation of an NTP client [here](http://pypi.python.org/pypi/ntplib/). A very simple-minded approach: ``` >>> import n...
How can I get an accurate UTC time with Python?
1,599,060
8
2009-10-21T06:34:31Z
1,715,510
7
2009-11-11T14:29:05Z
[ "python", "datetime", "timestamp", "utc" ]
I wrote a desktop application and was using `datetime.datetime.utcnow()` for timestamping, however I've recently noticed that some people using the application get wildly different results than I do when we run the program at the same time. Is there any way to get the UTC time locally without using urllib to fetch it f...
Actually, ntplib computes this offset accounting for round-trip delay. It's available through the "offset" attribute of the NTP response. Therefore the result should not very wildly.
Is there easy way in python to extrapolate data points to the future?
1,599,754
8
2009-10-21T09:42:52Z
1,614,148
15
2009-10-23T15:15:12Z
[ "python", "numpy", "interpolation", "spline", "burndowncharts" ]
I have a simple numpy array, for every date there is a data point. Something like this: ``` >>> import numpy as np >>> from datetime import date >>> from datetime import date >>> x = np.array( [(date(2008,3,5), 4800 ), (date(2008,3,15), 4000 ), (date(2008,3, 20), 3500 ), (date(2008,4,5), 3000 ) ] ) ``` Is there easy ...
It's all too easy for extrapolation to generate garbage; try this. Many different extrapolations are of course possible; some produce obvious garbage, some non-obvious garbage, many are ill-defined. ![alt text](http://i39.tinypic.com/am62wp.png) ``` """ extrapolate y,m,d data with scipy UnivariateSpline """ import nu...
Configuring Python's default exception handling
1,599,962
14
2009-10-21T10:29:55Z
1,599,973
20
2009-10-21T10:31:41Z
[ "python" ]
For an uncaught exception, Python by default prints a stack trace, the exception itself, and terminates. Is anybody aware of a way to tailor this behaviour on the program level (other than establishing my own global, catch-all exception handler), so that the stack trace is omitted? I would like to toggle in my app whet...
You are looking for sys.excepthook: **sys.excepthook(type, value, traceback)** This function prints out a given traceback and exception to sys.stderr. When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. ...
Using south to refactor a Django model with inheritance
1,600,129
32
2009-10-21T11:05:57Z
1,603,570
49
2009-10-21T20:56:57Z
[ "python", "django", "migration", "django-south" ]
I was wondering if the following migration is possible with Django [south](http://south.aeracode.org/) and still retain data. ## Before: I currently have two apps, one called tv, one called movies, each with a VideoFile model (simplified here): **tv/models.py:** ``` class VideoFile(models.Model): show = models....
**Check out response below by Paul for some notes on compatibility with newer versions of Django/South.** --- This seemed like an interesting problem, and I'm becoming a big fan of South, so I decided to look into this a bit. I built a test project on the abstract of what you've described above, and have successfully...
Using south to refactor a Django model with inheritance
1,600,129
32
2009-10-21T11:05:57Z
4,805,806
9
2011-01-26T14:42:52Z
[ "python", "django", "migration", "django-south" ]
I was wondering if the following migration is possible with Django [south](http://south.aeracode.org/) and still retain data. ## Before: I currently have two apps, one called tv, one called movies, each with a VideoFile model (simplified here): **tv/models.py:** ``` class VideoFile(models.Model): show = models....
I did try to walk through the solution outlined by T Stone and while I think it's a superb starter and explains how things should be done I ran into a few problems. I think mostly you **don't** need to create the table entry for the parent class anymore, i.e. you don't need ``` new_movie.videofile_ptr = orm['media.Vi...
Using a Python Dictionary as a Key (Non-nested)
1,600,591
10
2009-10-21T12:47:53Z
1,600,806
30
2009-10-21T13:21:19Z
[ "python", "data-structures", "dictionary" ]
Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys? The general problem with more complicated non-hashable objects and my specific use case has been [moved here](http://stackoverflow.com/questions/1611797/using-non-hashable-python...
If you have a really immutable dictionary (although it isn't clear to me why you don't just use a list of pairs: e.g. `[('content-type', 'text/plain'), ('host', 'example.com')]`), then you may convert your `dict` into: 1. A tuple of pairs. You've already done that in your question. A `tuple` is required instead of `li...
Using a Python Dictionary as a Key (Non-nested)
1,600,591
10
2009-10-21T12:47:53Z
1,600,859
8
2009-10-21T13:29:38Z
[ "python", "data-structures", "dictionary" ]
Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys? The general problem with more complicated non-hashable objects and my specific use case has been [moved here](http://stackoverflow.com/questions/1611797/using-non-hashable-python...
If I needed to use dictionaries as keys, I would flatten the dictionary into a tuple of tuples. You might find this SO question useful: <http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python> And here is an example of a flatten module that will flatten dictionaries:...
How to make a completely unshared copy of a complicated list? (Deep copy is not enough)
1,601,269
5
2009-10-21T14:38:27Z
1,601,334
7
2009-10-21T14:47:25Z
[ "python", "list", "copy" ]
Have a look at this Python code: ``` a = [1, 2, 3] b = [4, 5, 6] c = [[a, b], [b, a]] # [[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]] c[0][0].append(99) # [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]] ``` Notice how modifying one element of `c` modifies that everywhere. That is, if `99` is appended to...
When you want a copy, you explicitly make a copy - the cryptical `[:]` "slice it all" form is idiomatic, but my favorite is the much-more-readable approach of explicitly calling `list`. If `c` is constructed in the wrong way (with references instead of shallow copies to lists you want to be able to modify independentl...
How to make a completely unshared copy of a complicated list? (Deep copy is not enough)
1,601,269
5
2009-10-21T14:38:27Z
1,601,774
7
2009-10-21T15:49:41Z
[ "python", "list", "copy" ]
Have a look at this Python code: ``` a = [1, 2, 3] b = [4, 5, 6] c = [[a, b], [b, a]] # [[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]] c[0][0].append(99) # [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]] ``` Notice how modifying one element of `c` modifies that everywhere. That is, if `99` is appended to...
To convert an existing list of lists to one where nothing is shared, you could recursively copy the list. `deepcopy` will not be sufficient, as it will copy the structure as-is, keeping *internal* references as references, not copies. ``` def unshared_copy(inList): if isinstance(inList, list): return list...
Recursion - Python, return value question
1,601,757
3
2009-10-21T15:46:44Z
1,601,799
12
2009-10-21T15:55:19Z
[ "python", "recursion", "stack" ]
I realize that this may sound like a silly question, but the last time I programmed it was in assembler so my thinking may be off: A recursive function as so: ``` def fac(n): if n == 0: return 1 else: return n * fac(n - 1) ``` Why is it that when the function reaches n == 0 that it does not r...
Think about like this, for `fac(5)` for example: ``` return 5 * fac(4) return 4 * fac(3) return 3 * fac(2) return 2 * fac(1) return 1 * fac(0) 1 ``` So `...
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
18
2009-10-21T16:10:20Z
1,601,907
14
2009-10-21T16:12:50Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? For example, [Erlang](http://www.erlang.org/) would seem particularly well-suited to robotic applications, since it makes concurrent progr...
Because embedded devices mostly have limited resources where it is not welcome to have luxury such as automatic garbage collector. C/C++ allows you to work on quite low levels and program close to machine so that you get effective code as very much needed on those devices. One more area where high-level languages like...
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
18
2009-10-21T16:10:20Z
1,601,917
11
2009-10-21T16:15:14Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? For example, [Erlang](http://www.erlang.org/) would seem particularly well-suited to robotic applications, since it makes concurrent progr...
You can do robotics with Java on the Mindstorm robots and MS has a push for doing robotics, but to a large extent C/C++ is used due to limited resources, and LISP is used for AI because for a long time this was an area of research and researchers were the main users of LISP, so they used the language they knew. This i...
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
18
2009-10-21T16:10:20Z
1,602,139
45
2009-10-21T16:54:20Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? For example, [Erlang](http://www.erlang.org/) would seem particularly well-suited to robotic applications, since it makes concurrent progr...
I once built a robot based on Java. It garbage collected right into a wall. If you're going to have processes running that you can't micromanage (eg, a Linux based system) then they must know to yield to certain high priority processes like motion control. So either you do it yourself in a low level language like C, o...
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
18
2009-10-21T16:10:20Z
1,602,925
27
2009-10-21T19:04:03Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? For example, [Erlang](http://www.erlang.org/) would seem particularly well-suited to robotic applications, since it makes concurrent progr...
* As others have pointed out already, C and C++ are used because they are low-level. Another reason for C's popularity is that just about every architecture gets a C compiler targeted for it. This is good enough for a lot of people, so extra effort isn't often put into other languages. This is sort of like saying C is ...
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
18
2009-10-21T16:10:20Z
1,608,682
12
2009-10-22T17:17:42Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? For example, [Erlang](http://www.erlang.org/) would seem particularly well-suited to robotic applications, since it makes concurrent progr...
In 20 years in embedded systems (including 8 years on a commercial robotics project), I have never seen Lisp used anywhere and would not regard it as 'prevalent'. I seen far more Ada for example. I would say that it is a niche, but if you happen to be working in that niche, it might *look* prevalent to you. C and C++ ...
Why are C, C++, and LISP so prevalent in embedded devices and robots?
1,601,893
18
2009-10-21T16:10:20Z
1,776,810
10
2009-11-21T21:15:06Z
[ "python", "embedded", "erlang", "lisp", "robotics" ]
It seems that the software language skills most sought for embedded devices and robots are C, C++, and LISP. Why haven't more recent languages made inroads into these applications? For example, [Erlang](http://www.erlang.org/) would seem particularly well-suited to robotic applications, since it makes concurrent progr...
I once fell over this interesting snippet on using Lisp at NASA: <http://www.flownet.com/gat/jpl-lisp.html> > In 1994 JPL started working on the > Remote Agent (RA), an autonomous > spacecraft control system. RA was > written entirely in Common Lisp > despite unrelenting political pressure > to move to C++. At one poi...
Casting vs. coercion in Python
1,602,122
23
2009-10-21T16:51:30Z
1,602,151
26
2009-10-21T16:55:57Z
[ "python", "casting", "types", "coercion" ]
In the Python documentation and on mailing lists I see that values are sometimes "cast", and sometimes "coerced". What is the difference?
I think "casting" shouldn't be used for Python; there are only type conversion, but no casts (in the C sense). A type conversion is done e.g. through `int(o)` where the object o is converted into an integer (actually, an integer object is constructed out of o). Coercion happens in the case of binary operations: if you ...
Casting vs. coercion in Python
1,602,122
23
2009-10-21T16:51:30Z
1,602,216
34
2009-10-21T17:11:03Z
[ "python", "casting", "types", "coercion" ]
In the Python documentation and on mailing lists I see that values are sometimes "cast", and sometimes "coerced". What is the difference?
Cast is explicit. Coerce is implicit. The examples in Python would be: ``` cast(2, POINTER(c_float)) #cast 1.0 + 2 #coerce 1.0 + float(2) #conversion ``` Cast really only comes up in the C FFI. What is typically called casting in C or Java is referred to as conversion in python, though it often gets referred to as...
Python compute cluster
1,602,177
5
2009-10-21T17:00:33Z
1,602,251
13
2009-10-21T17:16:17Z
[ "python", "python-3.x", "parallel-processing", "cluster-computing" ]
Would it be possible to make a python cluster, by writing a telnet server, then telnet-ing the commands and output back-and-forth? Has anyone got a better idea for a python compute cluster? PS. Preferably for python 3.x, if anyone knows how.
The Python wiki hosts a very comprehensive list of [Python cluster computing libraries and tools](http://wiki.python.org/moin/ParallelProcessing). You might be especially interested in [Parallel Python](http://www.parallelpython.com/). **Edit:** There is a new library that is IMHO especially good at clustering: [execn...
Python compute cluster
1,602,177
5
2009-10-21T17:00:33Z
1,602,252
11
2009-10-21T17:16:21Z
[ "python", "python-3.x", "parallel-processing", "cluster-computing" ]
Would it be possible to make a python cluster, by writing a telnet server, then telnet-ing the commands and output back-and-forth? Has anyone got a better idea for a python compute cluster? PS. Preferably for python 3.x, if anyone knows how.
You can see most of the third-party packages available for Python 3 listed [here](http://pypi.python.org/pypi?%3Aaction=browse&c=533&show=all); relevant to cluster computation is [mpi4py](http://pypi.python.org/pypi/mpi4py/1.1.0) -- most other distributed computing tools such as pyro are still Python-2 only, but MPI is...
How do I wrangle python lookups: make.up.a.dot.separated.name.and.use.it.until.destroyed = 777
1,602,745
3
2009-10-21T18:38:38Z
1,602,855
11
2009-10-21T18:55:25Z
[ "python", "namespaces", "lookup" ]
I'm a Python newbie with a very particular itch to experiment with Python's dot-name-lookup process. How do I code either a class or function in "make.py" so that these assignment statements work succesfully? ``` import make make.a.dot.separated.name = 666 make.something.else.up = 123 make.anything.i.want = 777 ```
``` #!/usr/bin/env python class Make: def __getattr__(self, name): self.__dict__[name] = Make() return self.__dict__[name] make = Make() make.a.dot.separated.name = 666 make.anything.i.want = 777 print make.a.dot.separated.name print make.anything.i.want ``` The special `__getattr__` method is ...
Python problem executing popen in cron
1,602,830
7
2009-10-21T18:51:01Z
1,602,848
18
2009-10-21T18:54:24Z
[ "python", "console", "cron" ]
I use `popen` to execute commands in a Python script, and I call it via cron. Cron calls out this script but the behavior isn't the same if I call it by hand. ### Source: ``` from subprocess import Popen, PIPE pp = Popen('/usr/bin/which iptables', shell=True, stdout=PIPE) data = '' for ln in pp.stdout: data =...
Normally when processes are run from cron, the `PATH` is set to a very restrictive value (the man page for my crontab says `/usr/bin:/bin`). You may need to add: ``` PATH=/usr/bin:/bin:/sbin ``` to the top of your crontab file.
Check if a given key already exists in a dictionary
1,602,934
1,211
2009-10-21T19:05:09Z
1,602,944
600
2009-10-21T19:06:30Z
[ "python", "dictionary" ]
I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: ``` if 'key1' in dict.keys(): print "blah" else: print "boo" ``` I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
You don't have to call keys: ``` if 'key1' in dict: print "blah" else: print "boo" ``` That will be much faster as it uses the dictionary's hashing as opposed to doing a linear search, which calling keys would do.
Check if a given key already exists in a dictionary
1,602,934
1,211
2009-10-21T19:05:09Z
1,602,945
42
2009-10-21T19:06:40Z
[ "python", "dictionary" ]
I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: ``` if 'key1' in dict.keys(): print "blah" else: print "boo" ``` I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
You can shorten this: ``` if 'key1' in dict: ... ``` However, this is at best a cosmetic improvement. Why do you believe this is not the best way?
Check if a given key already exists in a dictionary
1,602,934
1,211
2009-10-21T19:05:09Z
1,602,950
28
2009-10-21T19:07:28Z
[ "python", "dictionary" ]
I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: ``` if 'key1' in dict.keys(): print "blah" else: print "boo" ``` I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
I would recommend using the `setdefault` method instead. It sounds like it will do everything you want. ``` >>> d = {'foo':'bar'} >>> q = d.setdefault('foo','baz') #Do not override the existing key >>> print q #The value takes what was originally in the dictionary bar >>> print d {'foo': 'bar'} >>> r = d.setdefault('b...
Check if a given key already exists in a dictionary
1,602,934
1,211
2009-10-21T19:05:09Z
1,602,964
1,258
2009-10-21T19:10:21Z
[ "python", "dictionary" ]
I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: ``` if 'key1' in dict.keys(): print "blah" else: print "boo" ``` I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
`in` is the intended way to test for the existence of a key in a `dict`. ``` d = dict() for i in xrange(100): key = i % 10 if key in d: d[key] += 1 else: d[key] = 1 ``` If you wanted a default, you can always use `dict.get()`: ``` d = dict() for i in xrange(100): key = i % 10 d[...
Check if a given key already exists in a dictionary
1,602,934
1,211
2009-10-21T19:05:09Z
1,602,990
180
2009-10-21T19:16:46Z
[ "python", "dictionary" ]
I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: ``` if 'key1' in dict.keys(): print "blah" else: print "boo" ``` I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
You can test for the presence of a key in a dictionary, using the **in** keyword: ``` d = {'a': 1, 'b': 2} 'a' in d # <== evaluates to True 'c' in d # <== evaluates to False ``` A common use for checking the existence of a key in a dictionary before mutating it is to default-initialize the value (e.g. if your values ...
Check if a given key already exists in a dictionary
1,602,934
1,211
2009-10-21T19:05:09Z
16,637,874
9
2013-05-19T18:12:35Z
[ "python", "dictionary" ]
I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: ``` if 'key1' in dict.keys(): print "blah" else: print "boo" ``` I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
Just an FYI adding to Chris. B (best answer): ``` d = defaultdict(int) ``` Works as well; the reason is that calling `int()` returns `0` which is what `defaultdict` does behind the scenes (when constructing a dictionary), hence the name "Factory Function" in the documentation.
Check if a given key already exists in a dictionary
1,602,934
1,211
2009-10-21T19:05:09Z
30,527,984
13
2015-05-29T11:06:44Z
[ "python", "dictionary" ]
I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code: ``` if 'key1' in dict.keys(): print "blah" else: print "boo" ``` I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
For additional info on speed execution of the accepted answer's proposed methods (10m loops): * `'key' in mydict` elapsed time 1.07 sec * `mydict.get('key')` elapsed time 1.84 sec * `mydefaultdict['key']` elapsed time 1.07 sec Therefore using `in` or `defaultdict` are recommended against `get`.
How to make a Python script run like a service or daemon in Linux
1,603,109
96
2009-10-21T19:36:34Z
1,603,138
65
2009-10-21T19:43:06Z
[ "python", "linux", "scripting", "daemons" ]
I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed...
You have two options here. 1. Make a proper **cron job** that calls your script. Cron is a common name for a GNU/Linux daemon that periodically launches scripts according to a schedule you set. You add your script into a crontab or place a symlink to it into a special directory and the daemon handles the job of launch...
How to make a Python script run like a service or daemon in Linux
1,603,109
96
2009-10-21T19:36:34Z
1,603,141
33
2009-10-21T19:43:45Z
[ "python", "linux", "scripting", "daemons" ]
I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed...
You should use the [python-daemon](http://pypi.python.org/pypi/python-daemon/) library, it takes care of everything. From PyPI: *Library to implement a well-behaved Unix daemon process.*
How to make a Python script run like a service or daemon in Linux
1,603,109
96
2009-10-21T19:36:34Z
1,603,152
27
2009-10-21T19:45:12Z
[ "python", "linux", "scripting", "daemons" ]
I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed...
You can use fork() to detach your script from the tty and have it continue to run, like so: ``` import os, sys fpid = os.fork() if fpid!=0: # Running as daemon now. PID is fpid sys.exit(0) ``` Of course you also need to implement an endless loop, like ``` while 1: do_your_check() sleep(5) ``` Hope this get'...
How to make a Python script run like a service or daemon in Linux
1,603,109
96
2009-10-21T19:36:34Z
6,374,881
43
2011-06-16T15:58:40Z
[ "python", "linux", "scripting", "daemons" ]
I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed...
Here's a nice class that is taken from [here](https://web.archive.org/web/20160305151936/http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/): ``` #!/usr/bin/env python import sys, os, time, atexit from signal import SIGTERM class Daemon: """ A generic daemon class. U...
How to make a Python script run like a service or daemon in Linux
1,603,109
96
2009-10-21T19:36:34Z
19,514,587
10
2013-10-22T09:56:08Z
[ "python", "linux", "scripting", "daemons" ]
I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed...
You can also make the python script run as a service using a shell script. First create a shell script to run the python script like this (scriptname arbitary name) ``` #!/bin/sh script='/home/.. full path to script' /usr/bin/python $script & ``` now make a file in /etc/init.d/scriptname ``` #! /bin/sh PATH=/bin:/u...
Python idiom for 'Try until no exception is raised'
1,603,578
7
2009-10-21T20:58:03Z
1,603,615
14
2009-10-21T21:02:53Z
[ "python" ]
I want my code to automatically try multiple ways to create a database connection. As soon as one works, the code needs to move on (i.e. it shouldn't try to other ways anymore). If they all fail well, then the script can just blow up. So in - what I thought was, but most likely isn't - a stroke of genius I tried this:...
Approximately: ``` attempts = [ { 'database'='postgres', 'user'='pgsql', ...}, { 'database'='postgres', 'user'='postgres', 'host'='localhost', 'password'=getpass()}, ... ] conn = None for attempt in attempts: try: conn = psycopg2.connect(**attempt) break except psycopg2.OperationalE...
Why is this simple python class not working?
1,603,696
2
2009-10-21T21:15:55Z
1,603,733
7
2009-10-21T21:19:11Z
[ "python", "class", "list" ]
I'm trying to make a class that will get a list of numbers then print them out when I need. I need to be able to make 2 objects from the class to get two different lists. Here's what I have so far ``` class getlist: def newlist(self,*number): lst=[] self.number=number lst.append(number) ...
In Python, when you are writing methods inside an object, you need to prefix all references to variables belonging to that object with self. - like so: ``` class getlist: def newlist(self,*number): self.lst=[] self.lst += number #I changed this to add all args to the list def printlist(self...