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
Python -- how to grab images off the internet
6,415,015
2
2011-06-20T17:22:25Z
6,415,054
8
2011-06-20T17:26:11Z
[ "python", "image", "download" ]
How can I grab a picture off of a known url and save it to my computer using Python (v2.6)? Thanks
You can use [`urllib.urlretrieve`](http://docs.python.org/library/urllib.html#urllib.urlretrieve). > Copy a network object denoted by a URL to a local file, if necessary. Example: ``` >>> import urllib >>> urllib.urlretrieve('http://i.imgur.com/Ph4Xw.jpg', 'duck.jpg') ('duck.jpg', <httplib.HTTPMessage instance at 0x...
Python command line 'file input stream'
6,415,382
8
2011-06-20T17:57:46Z
6,415,415
7
2011-06-20T18:00:57Z
[ "python", "file", "file-io", "filestream" ]
I'm fairly new to python coming from C/C++, I was wondering how I would get my 'main.py' to reconize/use the imput given from a bash shell as: > python main.py < text.txt (the file is in plain text)
Read from `sys.stdin`: ``` import sys sys.stdin.read() ``` Being a [file-like object](http://docs.python.org/library/stdtypes.html#bltin-file-objects), you can use its reading functions or simply iterate over the input lines: ``` for line in sys.stdin: print line ```
Python equivalence of default in C#
6,415,663
4
2011-06-20T18:21:43Z
6,415,706
11
2011-06-20T18:25:46Z
[ "python", "python-2.7" ]
Is there a way in python to get a types default value? ``` //C# default(typeof(int)) ``` I am looking for a more pythonic way to get type defaults? ``` #python if(isinstance(myObj, int): return 0 elif(isinstance(myObj, dict): return {} else: return None ``` Obviously I dumbed it down. I am dealing with ...
Just instantiate it: ``` int() # 0 dict() # {} list() # [] ``` More detail: there's no explicit concept of a 'default value' in Python. There's just an instance of the class instantiated with the default parameters. Some classes may expect arguments when you instantiate them, in which case there isn't really a defau...
Python pickle crash when trying to return default value in __getattr__
6,415,951
5
2011-06-20T18:51:13Z
6,416,080
11
2011-06-20T19:03:17Z
[ "python", "python-2.7", "pickle" ]
I have a dictionary like class that I use to store some values as attributes. I recently added some logic(`__getattr__`) to return None if an attribute doesn't exist. As soon as I did this pickle crashed, and I wanted some insight into why? Test Code: ``` import cPickle class DictionaryLike(object): def __init__(...
Implementing `__getattr__` is a bit tricky, since it is called for every non-existing attribute. In your case, the `pickle` module tests your class for the [`__getnewargs__`](http://docs.python.org/library/pickle.html#object.__getnewargs__) special method and receives `None`, which is obviously not callable. You might...
data validation for SQLAlchemy declarative models
6,416,023
6
2011-06-20T18:58:42Z
6,416,136
8
2011-06-20T19:07:49Z
[ "python", "validation", "model", "sqlalchemy", "cherrypy" ]
I'm using CherryPy, Mako templates, and SQLAlchemy in a web app. I'm coming from a Ruby on Rails background and I'm trying to set up some data validation for my models. I can't figure out the best way to ensure, say, a 'name' field has a value when some other field has a value. I tried using [SAValidation](http://pypi....
Take a look at the documentation for adding [validation methods](http://docs.sqlalchemy.org/en/rel_0_9/orm/mapped_attributes.html#simple-validators). You could just add an "update" method that takes the POST dict, makes sure that required keys are present, and uses the decorated validators to set the values (raising an...
Need for while True:
6,416,127
2
2011-06-20T19:06:47Z
6,416,149
11
2011-06-20T19:08:39Z
[ "python" ]
I don't understand why "while True:" is needed in below example ``` import os import sys import subprocess import time from threading import Thread from Queue import Queue def worker(): while True: item = q.get() do_work(item) q.task_done() def do_work(item): ...
Because otherwise the worker thread would quit as soon as the first job was processed from the queue. The infinite loop ensures that the worker thread retrieves a new job from the queue when finished. **Update**: to summarize the comments to my (admittedly hasty) answer: the worker thread is daemonic (ensured by `t.da...
CleverCSS replacement
6,416,271
4
2011-06-20T19:19:49Z
6,418,585
7
2011-06-20T23:08:04Z
[ "python", "css", "less", "clevercss" ]
Hello I am looking into cleverCSS to use in my python App. I am looking at the Python package site and its latest version is from 2007. I was wondering if someone has continued work on a similar project? I considered using LESS but was drawn more toward clever because of it being python.
Unless there's a good reason that you need to use a Python-based one, I would recommend that you use the best tool for the job. I don't particularly like the way that LESS and SASS use Ruby—I'd far prefer Python—but if that's what they use, then that's what they use and I'm not going to complain too bitterly. I would o...
Python equivalent of PHP's __DIR__ magic constant?
6,416,321
12
2011-06-20T19:23:52Z
6,416,333
23
2011-06-20T19:25:33Z
[ "php", "python", "magic-constants" ]
In PHP, the [`__DIR__` magic constant](http://php.net/language.constants.predefined) evaluates to the path to the directory containing the file in which that constant appears. Is there an equivalent feature in Python?
``` os.path.dirname(__file__) ``` Note that [`__file__`](http://docs.python.org/reference/datamodel.html#index-869) refers to the file location relative to the cwd at *module import time*. If you call `chdir`, the information will be lost. If this becomes an issue, you can add the following to the root of your module:...
Why does my python not add current working directory to the path?
6,416,424
16
2011-06-20T19:33:27Z
6,416,470
35
2011-06-20T19:36:49Z
[ "python", "python-import" ]
I keep seeing sites mentioning that the directory that you execute 'python ' get added to the python path. For example on <http://www.stereoplex.com/blog/understanding-imports-and-pythonpath>, the author cd's to the /tmp folder then does 'print(sys.path)' and lo and behold, the /tmp folder appears in the path list. Her...
It is the *script's* directory that is added, not the current directory. If you turn `inner_folder/` into a package then you can use `python -m inner_folder.myscript` in order to run the script while having `app/` added to `sys.path`.
Simplifying an Expression in Python
6,416,432
3
2011-06-20T19:34:00Z
6,416,487
11
2011-06-20T19:38:18Z
[ "python", "string", "iteration", "expression" ]
I feel there must be a simpler/cleaner/faster (choose one or more) way to write this expression... take a BigString = "This is a long sentence about a red cat named dude." and LittleStringList = [ "red dog", "red cat", "red mouse" ] I effectively want a function/expression that returns true when one of LittleStringL...
`any([s in BigString for s in LittleStringList])` or even better using a generator expression - as pointed out by @GWW: `any(s in BigString for s in LittleStringList)`
How to avoid printing scientific notation in python without adding extra digits?
6,416,474
5
2011-06-20T19:37:16Z
6,416,645
7
2011-06-20T19:51:29Z
[ "python", "floating-point", "string-formatting" ]
[This question](http://stackoverflow.com/questions/658763/how-do-i-suppress-scientific-notation-in-python) asks how to suppress scientific notation in python. I have a series of numbers to display -- small powers of 10 -- and I'd like to display them without trailing zeros. I.e. 0.1, 0.01, and so on to 0.000001 If I ...
It seems to me a little hacky, but you can use `str.rstrip("0")` to get rid of trailing zeros: ``` >>> "{:f}".format(10**-6).rstrip("0") '0.000001' >>> "{:f}".format(10**-3).rstrip("0") '0.001' ``` Edit: As said in comments, there is a better way for this: ``` >>> format(1e-6, 'f').rstrip('0') '0.000001' >>> format(...
How to check if an object is a generator object in python?
6,416,538
67
2011-06-20T19:42:28Z
6,416,571
18
2011-06-20T19:44:54Z
[ "python", "generator" ]
In python, how do I check if an object is a generator object? Trying this - ``` >>> type(myobject, generator) ``` gives the error - ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'generator' is not defined ``` (I know I can check if the object has a `next` method for i...
You mean generator functions ? use [`inspect.isgeneratorfunction`](http://docs.python.org/library/inspect.html#inspect.isgeneratorfunction). **EDIT :** if you want a generator object you can use [inspect.isgenerator](http://docs.python.org/library/inspect.html#inspect.isgenerator) as pointed out by JAB in his comment...
How to check if an object is a generator object in python?
6,416,538
67
2011-06-20T19:42:28Z
6,416,585
92
2011-06-20T19:46:00Z
[ "python", "generator" ]
In python, how do I check if an object is a generator object? Trying this - ``` >>> type(myobject, generator) ``` gives the error - ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'generator' is not defined ``` (I know I can check if the object has a `next` method for i...
You can use GeneratorType from types: ``` >>> import types >>> types.GeneratorType <class 'generator'> >>> gen = (i for i in range(10)) >>> isinstance(gen, types.GeneratorType) True ```
How to check if an object is a generator object in python?
6,416,538
67
2011-06-20T19:42:28Z
10,644,028
8
2012-05-17T21:52:46Z
[ "python", "generator" ]
In python, how do I check if an object is a generator object? Trying this - ``` >>> type(myobject, generator) ``` gives the error - ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'generator' is not defined ``` (I know I can check if the object has a `next` method for i...
The `inspect.isgenerator` function is fine if you want to check for pure generators (i.e. objects of class "generator"). However it will return `False` if you check, for example, a `izip` iterable. An alternative way for checking for a generalised generator is to use this function: ``` def isgenerator(iterable): r...
PLY: quickly parsing long lists of items?
6,416,752
7
2011-06-20T20:01:37Z
6,430,096
7
2011-06-21T18:21:30Z
[ "python", "parsing", "optimization", "ply" ]
I'm working with a fairly simple parser in [PLY](http://www.dabeaz.com/ply/), and one of my rules takes on the following form: ``` def p_things(p): ''' things : thing things things : thing ''' p[0] = [p[1]] if len(p) == 3: p[0] += p[2] ``` Input files are generally simple lists of `thi...
Turns out I'm forgetting some of my basic compilers theory. PLY is a LALR(1) parser, and so it's better to write the rule as: ``` def p_things(p): ''' things : things thing things : thing ''' if len(p) == 2: p[0] = [p[1]] else: p[0] = p[1] p[0].append(p[2]) ``` Though i...
WTForms "too many values to unpack" with SelectField
6,417,935
6
2011-06-20T21:44:05Z
6,417,968
10
2011-06-20T21:48:04Z
[ "python", "forms", "wtforms" ]
I'm using WTForms and I'm trying to display a `SelectField`, but I get the following error: ``` >>> form.status() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\Lib\site-packages\wtforms\fields.py", line 136, in __call__ return self.widget(self, **kwargs) File "C:\Py...
[It expects a list of `(str, str)` tuples, not a list of strings.](http://wtforms.simplecodes.com/docs/0.6/fields.html#wtforms.fields.SelectField)
lxml memory usage when parsing huge xml in python
6,418,576
3
2011-06-20T23:07:10Z
6,420,893
12
2011-06-21T05:47:38Z
[ "python", "lxml" ]
I am a python newbie. I am trying to parse a huge xml file in my python module using lxml. In spite of clearing the elements at the end of each loop, my memory shoots up and crashes the application. I am sure I am missing something here. Please helpme figure out what that is. Following are main functions I am using - ...
## Welcome to Python and Stack Overflow! It looks like you've followed some good advice looking at `lxml` and especially `etree.iterparse(..)`, but I think your implementation is approaching the problem from the wrong angle. The idea of `iterparse(..)` is to get away from collecting and storing data, and instead proce...
Inline-like solution for Django Admin where Admin contains ForeignKey to other model
6,419,248
16
2011-06-21T01:02:25Z
6,419,907
7
2011-06-21T03:06:25Z
[ "python", "django", "django-admin", "foreign-keys" ]
I have several `Customer`s who book `Appointment`s. Each `Appointment` has exactly one customer, though a customer can be booked for multiple appointments occurring at different times. ``` class Customer(model.Model): def __unicode__(self): return u'%s' % (self.name,) name = models.CharField(max_length...
There is no easy way to do this with django. The inlines are designed to follow relationships backwards. Potentially the best substitute would be to provide a link to the user object. In the list view this is pretty trivial: Add a method to your appointment model like: ``` def customer_admin_link(self): return '...
how to make save / load game functions in pygame?
6,420,311
5
2011-06-21T04:22:19Z
6,424,688
11
2011-06-21T11:43:19Z
[ "python", "load", "save", "pygame" ]
I need to make save / load game functions for my rpg. I can save the location of my player, but what I want is to freeze the entire screen at one point like it is done in emulators like vba and snes9x. Or maybe to make save locations where I can save the game and start again from. Can anyone tell me how you do these th...
You can use [pickle](http://docs.python.org/library/pickle.html) to serialize Python data. This has nothing to do with pygame. So if your game state is completely stored in the object `foo`, to save to file "savegame" (`import pickle` first): ``` with open("savegame", "wb") as f: pickle.dump(foo, f) ``` To load:...
Problem with class based generic views in Django
6,420,322
13
2011-06-21T04:23:46Z
6,421,171
16
2011-06-21T06:23:13Z
[ "python", "django", "django-generic-views" ]
I'm trying to write a CRUD application using Djangos class based generic views. Following is the code i wrote to create a new user in the db. ``` from django.views.generic import CreateView from django.contrib.auth.decorators import login_required from django.contrib import messages class UserCreateView(Creat...
The answer depends on what specifically you're looking to do with the messaging framework. If it needs to be called for every `get` request you'd naturally need to put it in the `get` method (point being there's no one right place to put this code). Anyways, it sounds like you're looking for a place that's only trigge...
Why won't LD_PRELOAD work with Python?
6,421,784
8
2011-06-21T07:26:34Z
6,423,890
8
2011-06-21T10:33:36Z
[ "python", "c", "linux", "function-interposition", "interposing" ]
Using function interposition for `open()` with Python doesn't seem to work after the first few calls. I suspect Python is doing some kind of initialization, or something is temporarily bypassing my function. Here the `open` call is clearly hooked: ``` $ cat a hi $ LD_PRELOAD=./libinterpose_python.so cat a sandbox_ini...
There are open() and open64() functions, you might need to redefine both.
Python: If is running even when condition is not met
6,421,981
2
2011-06-21T07:46:29Z
6,422,018
7
2011-06-21T07:49:16Z
[ "python", "gmail" ]
``` import imaplib, re import os while(True): conn = imaplib.IMAP4_SSL("imap.gmail.com", 993) conn.login("xxx", "xxxx") unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1) print unreadCount if unreadCount > 10: os.system('ls') ``` Even when unreadCount i...
You might want to coerce that value to an *integer,* as per: ``` unreadCount = int (re.search (blah, blah, blah).group (1)) ``` The call to `re.search` is returning a string and, if you have a look at the following transcript: ``` >>> x = "7" >>> if x > 10: ... print "yes" ... yes >>> if int(x) > 10: ... p...
Python: How to peek into a pty object to avoid blocking?
6,422,016
5
2011-06-21T07:49:11Z
6,490,489
10
2011-06-27T08:50:05Z
[ "python", "stdout", "popen", "pty", "peek" ]
I am using `pty` to read non blocking the stdout of a process like this: ``` import os import pty import subprocess master, slave = pty.openpty() p = subprocess.Popen(cmd, stdout = slave) stdout = os.fdopen(master) while True: if p.poll() != None: break print stdout.readline() stdout.close() ``` ...
Yes, use the [select module's poll](http://docs.python.org/library/select.html): ``` import select q = select.poll() q.register(stdout,select.POLLIN) ``` and in the while use: ``` l = q.poll(0) if not l: pass # no input else: pass # there is some input ```
Why thread is slower than subprocess ? when should I use subprocess in place of thread and vise versa
6,422,187
4
2011-06-21T08:09:23Z
6,422,313
7
2011-06-21T08:20:52Z
[ "python", "multithreading", "subprocess" ]
In my application, I have tried python threading and subprocess module to open firefox, and I have noticed that subprocess is faster than threading. what could be the reason behind this? when to use them in place of each other?
Python (or rather CPython, the c-based implementation that is commonly used) has a Global Intepreter Lock (a.k.a. the *GIL*). Some kind of locking is necessary to synchronize memory access when several threads are accessing the same memory, which is what happens inside a process. Memory is not shared by between proces...
How to get indices of a sorted array in Python
6,422,700
67
2011-06-21T08:54:41Z
6,422,754
64
2011-06-21T08:58:19Z
[ "python", "indexing", "sorted" ]
I have a numerical list: ``` myList = [1, 2, 3, 100, 5] ``` Now if I sort this list to obtain `[1, 2, 3, 5, 100]`. What I want is the indices of the elements from the original list in the sorted order i.e. `[0, 1, 2, 4, 3]` --- ala MATLAB's sort function that returns both values and indices.
Something like next: ``` >>> myList = [1, 2, 3, 100, 5] >>> [i[0] for i in sorted(enumerate(myList), key=lambda x:x[1])] [0, 1, 2, 4, 3] ``` `enumerate(myList)` gives you a list containing tuples of (index, value): ``` [(0, 1), (1, 2), (2, 3), (3, 100), (4, 5)] ``` You sort the list by passing it to `sorted` and sp...
How to get indices of a sorted array in Python
6,422,700
67
2011-06-21T08:54:41Z
6,422,808
8
2011-06-21T09:03:05Z
[ "python", "indexing", "sorted" ]
I have a numerical list: ``` myList = [1, 2, 3, 100, 5] ``` Now if I sort this list to obtain `[1, 2, 3, 5, 100]`. What I want is the indices of the elements from the original list in the sorted order i.e. `[0, 1, 2, 4, 3]` --- ala MATLAB's sort function that returns both values and indices.
Updated answer with `enumerate` and `itemgetter`: ``` sorted(enumerate(a), key=lambda x: x[1]) # [(0, 1), (1, 2), (2, 3), (4, 5), (3, 100)] ``` Zip the lists together: The first element in the tuple will the index, the second is the value (then sort it using the second value of the tuple `x[1]`, x is the tuple) Or u...
How to get indices of a sorted array in Python
6,422,700
67
2011-06-21T08:54:41Z
6,423,325
25
2011-06-21T09:45:44Z
[ "python", "indexing", "sorted" ]
I have a numerical list: ``` myList = [1, 2, 3, 100, 5] ``` Now if I sort this list to obtain `[1, 2, 3, 5, 100]`. What I want is the indices of the elements from the original list in the sorted order i.e. `[0, 1, 2, 4, 3]` --- ala MATLAB's sort function that returns both values and indices.
``` In [15]: myList = [1, 2, 3, 100, 5] In [16]: sorted(range(len(myList)),key=lambda x:myList[x]) Out[16]: [0, 1, 2, 4, 3] ``` Also: ``` sorted(range(len(myList)),key=myList.__getitem__) ```
How to get indices of a sorted array in Python
6,422,700
67
2011-06-21T08:54:41Z
12,486,822
54
2012-09-19T00:06:37Z
[ "python", "indexing", "sorted" ]
I have a numerical list: ``` myList = [1, 2, 3, 100, 5] ``` Now if I sort this list to obtain `[1, 2, 3, 5, 100]`. What I want is the indices of the elements from the original list in the sorted order i.e. `[0, 1, 2, 4, 3]` --- ala MATLAB's sort function that returns both values and indices.
If you are using numpy, you have the argsort() function available: <http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html> This returns the arguments that would sort the array or list.
How to get indices of a sorted array in Python
6,422,700
67
2011-06-21T08:54:41Z
17,810,616
11
2013-07-23T12:48:04Z
[ "python", "indexing", "sorted" ]
I have a numerical list: ``` myList = [1, 2, 3, 100, 5] ``` Now if I sort this list to obtain `[1, 2, 3, 5, 100]`. What I want is the indices of the elements from the original list in the sorted order i.e. `[0, 1, 2, 4, 3]` --- ala MATLAB's sort function that returns both values and indices.
The answers with `enumerate` are nice, but I personally don't like the lambda used to sort by the value. The following just reverses the index and the value, and sorts that. So it'll first sort by value, then by index. ``` sorted((e,i) for i,e in enumerate(myList)) ```
How do I filter out only items from a list which is in an even position?
6,422,752
11
2011-06-21T08:58:13Z
6,422,793
20
2011-06-21T09:01:55Z
[ "python" ]
Instead of processing items based on its value, I need to run a function based on the item's position. This is an example of filtering based on the content of the list. ``` only_words = filter(str.isalpha, my_list) ``` I want to create a slice of the list that contains only items in the even position, that is: ``` n...
You can use this: `my_list[::2]` (for odd — `my_list[1::2]`)
IP address by Domain Name
6,422,907
3
2011-06-21T09:11:18Z
6,422,998
7
2011-06-21T09:19:20Z
[ "python" ]
I am trying to get IP address of a domain.. i am using following code ``` >> import socket >> socket.gethostbyname('www.google.com') ``` its giving me following error.. ``` Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> socket.gethostbyname('www.google.com') gaierror: [Errno 11001]...
Your code is correct. Perhaps you have a firewall in between you and these servers that is blocking the request?
Is there a python version of JavaScript's String.fromCharCode?
6,423,047
5
2011-06-21T09:23:41Z
6,423,064
7
2011-06-21T09:25:52Z
[ "python" ]
`String.fromCharCode` returns a string based on a list of unicode codepoint values. @see [reference](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/fromCharCode) Is there an analog in Python ?
You can use this: `''.join(map(unichr, lst))` Example: ``` ''.join(map(unichr, [65,66,67])) # outputs ABC ```
Is there a way to check if two object contain the same values in each of their variables in python?
6,423,814
6
2011-06-21T10:27:59Z
6,423,941
17
2011-06-21T10:38:11Z
[ "python", "object", "match" ]
How do I check if two instances of a ``` class FooBar(object): __init__(self, param): self.param = param self.param_2 = self.function_2(param) self.param_3 = self.function_3() ``` are identical? By identical I mean they have the same values in all of their variables. ``` a = FooBar(param)...
If you want the `==` to work, then implement the `__eq__` method in your class to perform the rich comparison. If all you want to do is compare the equality of **all** attributes, you can do that succinctly by comparison of `__dict__` in each object: ``` class MyClass: def __eq__(self, other) : return s...
Encrypt / decrypt data in python with salt
6,425,131
14
2011-06-21T12:21:15Z
6,462,056
26
2011-06-24T00:13:57Z
[ "python", "encryption" ]
I'd like to know basically how can I encrypt data with a generated salt key and then decrypt it using python ? i've gone trough a lot of websites and modules, and they all look great at encrpytion part, but none can decrypt as it seems. My main concern is to have strong salt key, that'd be probably generated over few...
The short answer to your question is that you combine the password and the salt and hash them repeatedly to create your key. Then you append the salt onto the ciphertext so that you can generate the key for decryption. To ensure that I had the right answer, I made a few functions to do the work. They are given below. ...
Is there any script to convert folder images into one pdf
6,425,311
6
2011-06-21T12:36:12Z
6,426,633
11
2011-06-21T14:06:55Z
[ "python", "windows", "pdf" ]
I have many folders and inside that i have many images. Now i want one PDF per folder so that all images contained in folder goes into PDF. I have 1000s of folders so i want something which can batchprocess or which can walk in the folder and start processing things.
I'd solve this with ImageMagick, and not with Python. ImageMagick has the console tool 'convert'. Use it like this: ``` convert *.jpg foo.pdf ``` See [here](http://bitprison.net/jpg_to_pdf). (Depends on whether you use Windows, Mac or Linux, should be easy to find out with Google)
Python equivialent of C programming techniques (while loops)
6,427,161
11
2011-06-21T14:41:38Z
6,427,231
18
2011-06-21T14:45:38Z
[ "python", "c" ]
In the C programming language, I often have done the following: ``` while ((c = getch()) != EOF) { /* do something with c */ } ``` In Python, I have not found anything similar, since I am not allowed to set variables inside the evaluated expression. I usually end up with having to setup the evaluated expression twic...
You would usually use a `for` loop in Python: ``` for c in sys.stdin.read(): # whatever ``` If you don't want to buffer the whole stdin in memory at once, you can also add some buffering with a smaller buffer yourself. Note that the constant `EOF` does not exist in Python. `read()` will simply return an empty st...
Python equivialent of C programming techniques (while loops)
6,427,161
11
2011-06-21T14:41:38Z
6,427,959
13
2011-06-21T15:33:04Z
[ "python", "c" ]
In the C programming language, I often have done the following: ``` while ((c = getch()) != EOF) { /* do something with c */ } ``` In Python, I have not found anything similar, since I am not allowed to set variables inside the evaluated expression. I usually end up with having to setup the evaluated expression twic...
I believe what you want to do is make use of the `iter` function. ``` for c in iter(getch, EOF): #inner loop ``` Iter is a very versatile function. In this case, you're telling it to repeatedly call `getch` (with no arguments) at the top of each loop until `getch` returns the sentinel value, EOF.
3D interpolation of NumPy arrays without SciPy
6,427,276
10
2011-06-21T14:48:31Z
6,444,181
8
2011-06-22T17:42:30Z
[ "python", "numpy", "scipy" ]
I am writing a plugin for an application that includes NumPy in the binary distribution, but not SciPy. My plugin needs to interpolate data from one regular 3D grid to another regular 3D grid. Running from source, this can be done very efficiently using `scipy.ndimage` or, if the user doesn't have SciPy installed, a we...
It turns out it's embarrassingly easy to vectorize it. ``` output = np.empty(indices[0].shape) x_indices = indices[0] y_indices = indices[1] z_indices = indices[2] x0 = x_indices.astype(np.integer) y0 = y_indices.astype(np.integer) z0 = z_indices.astype(np.integer) x1 = x0 + 1 y1 = y0 + 1 z1 = z0 + 1 #Check if xyz1 ...
Get new x,y coordinates of a point in a rotated image
6,428,192
11
2011-06-21T15:47:34Z
6,428,625
17
2011-06-21T16:17:09Z
[ "javascript", "python", "api", "google-maps", "image-rotation" ]
I have Google Maps icons which I need to rotate by certain angles before drawing on the map using [MarkerImage](http://code.google.com/apis/maps/documentation/javascript/reference.html#MarkerImage). I do the rotation on-the-fly in Python using PIL, and the resulting image is of the same size as the original - 32x32. Fo...
To calculate the position of a rotated point you can use a [rotation matrix](http://en.wikipedia.org/wiki/Rotation_matrix#Rotations_in_two_dimensions). Converted into JavaScript, this calculates the rotated point: ``` function rotate(x, y, xm, ym, a) { var cos = Math.cos, sin = Math.sin, a = a * ...
Polymorphic macros in Jinja
6,428,484
2
2011-06-21T16:06:37Z
6,428,734
7
2011-06-21T16:26:32Z
[ "python", "jinja2" ]
I am looking for a way to have a Jinja macro that calls different implementations depending on the type of object that is being passed. Basically, standard Python method polymorphism. Right now, I'm using an ugly workaround similar to this: ``` {% macro menuitem(obj) %} {% set type = obj.__class__.__name__ %} {% i...
The essence of OOP: polymorphism. ``` Create a presentation Layer for your objects: class MenuPresentation: def present(self): raise NotImplementedException() class ImageMenuPresentation(MenuPresentation): def present(self): return "magic url " class TextMenuPresentation(MenuPresentation): ...
python: are property fields being cached automatically?
6,428,723
14
2011-06-21T16:25:33Z
6,428,738
13
2011-06-21T16:26:45Z
[ "python", "properties" ]
My question is are the following two pieces of code run the same by the interpreter: ``` class A(object): def __init__(self): self.__x = None @property def x(self): if not self.__x: self.__x = ... #some complicated action return self.__x ``` and the much simpler: ``` class A(object): ...
No, the getter will be called every time you access the property.
python: are property fields being cached automatically?
6,428,723
14
2011-06-21T16:25:33Z
6,428,759
16
2011-06-21T16:28:44Z
[ "python", "properties" ]
My question is are the following two pieces of code run the same by the interpreter: ``` class A(object): def __init__(self): self.__x = None @property def x(self): if not self.__x: self.__x = ... #some complicated action return self.__x ``` and the much simpler: ``` class A(object): ...
No you need to add a [memoize](http://wiki.python.org/moin/PythonDecoratorLibrary) decorator: ``` class memoized(object): """Decorator that caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated. """ def __init...
python: are property fields being cached automatically?
6,428,723
14
2011-06-21T16:25:33Z
6,429,334
8
2011-06-21T17:18:47Z
[ "python", "properties" ]
My question is are the following two pieces of code run the same by the interpreter: ``` class A(object): def __init__(self): self.__x = None @property def x(self): if not self.__x: self.__x = ... #some complicated action return self.__x ``` and the much simpler: ``` class A(object): ...
Properties do not automatically cache their return values. The getter (and setters) are intended to be called each time the property is accessed. However, [Denis Otkidach](http://stackoverflow.com/users/168352/denis-otkidach) has written a wonderful cached attribute decorator (published in [the Python Cookbook, 2nd ed...
How can I scrape data from the Israeli Bureau of Statistics web query tool?
6,429,618
4
2011-06-21T17:43:32Z
6,429,695
8
2011-06-21T17:48:38Z
[ "python", "perl", "screen-scraping", "security" ]
The following url: <http://www.cbs.gov.il/ts/ID40d250e0710c2f/databank/series_func_e_v1.html?level_1=31&level_2=1&level_3=7> Gives a data generator of information from the Israeli government which limits the number of data points extracted to a maximum of 50 series at a time. I wonder, is it possible (and if so, how)...
Take a look at [WWW::Mechanize](http://search.cpan.org/dist/WWW-Mechanize/lib/WWW/Mechanize.pm#SYNOPSIS) and [WWW::HtmlUnit](http://search.cpan.org/dist/WWW-HtmlUnit/lib/WWW/HtmlUnit.pm#SYNOPSIS). ``` #!/usr/bin/perl use strict; use warnings; use WWW::Mechanize; my $m = WWW::Mechanize->new; #get page $m->get("http...
python objects, garbage collection
6,429,627
2
2011-06-21T17:44:24Z
6,429,716
7
2011-06-21T17:50:25Z
[ "python", "flask" ]
I have a python object which collects some request data so I can create the model queries based on the filters and sorters I receive via GET method. (sort=id&order=DESC...) ``` class Search( object ): sorters = [] filters = [] ``` If the request has filters and sorters the class properties get filled with th...
Because you are creating class variables rather than member variables this way. Class variables are shared among every instance (they belong to the class, not an instance); they are similar to static member variables in other languages. To create member variables, you need to initialise them in the constructor, like t...
How to split a string into two integers in python
6,429,638
18
2011-06-21T17:44:55Z
6,429,666
34
2011-06-21T17:46:52Z
[ "python", "arrays", "string", "split", "integer" ]
I have a string "42 0" (for example) and need to enter into an array the two integers. can i do a .split on a space? thanks in advance
``` text = "42 0" nums = [int(n) for n in text.split()] ```
How to split a string into two integers in python
6,429,638
18
2011-06-21T17:44:55Z
6,429,930
33
2011-06-21T18:07:44Z
[ "python", "arrays", "string", "split", "integer" ]
I have a string "42 0" (for example) and need to enter into an array the two integers. can i do a .split on a space? thanks in advance
6 answers is not nearly enough for a question that OP could easily have answered himself by testing in the [interpreter](http://docs.python.org/tutorial/interpreter.html): ``` >>> "42 0".split() # or .split(" ") ['42', '0'] ``` A: Yes. But it has not been specifically pointed out that the `split` method by default ...
Efficient distance calculation between N points and a reference in numpy/scipy
6,430,091
10
2011-06-21T18:21:03Z
6,430,140
18
2011-06-21T18:24:54Z
[ "python", "arrays", "numpy", "scipy" ]
I just started using scipy/numpy. I have an 100000\*3 array, each row is a coordinate, and a 1\*3 center point. I want to calculate the distance for each row in the array to the center and store them in another array. What is the most efficient way to do it?
I would take a look at `scipy.spatial.distance.cdist`: <http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html> ``` import numpy as np import scipy a = np.random.normal(size=(10,3)) b = np.random.normal(size=(1,3)) dist = scipy.spatial.distance.cdist(a,b) # pick the appropriate distan...
How do Python parsers handle indentation?
6,430,297
18
2011-06-21T18:38:01Z
6,430,371
17
2011-06-21T18:43:49Z
[ "python", "parsing", "whitespace" ]
When parsing a freeform language like C, it is easy for the parser to determine when several expressions are related to one another simply by looking at the symbols emitted by the parser. For example, in the code ``` if (x == 5) { a = b; c = d; } ``` The parser can tell that `a = b` and `c = d` are part of a ...
The indentations are handled with two "pseudo tokens" - INDENT and DEDENT. There are some details [here](http://docs.python.org/reference/lexical_analysis.html#indentation). For more information, you should look at the source for the python tokeniser and parser.
intersect two lists of words in python
6,431,033
5
2011-06-21T19:39:19Z
6,431,054
9
2011-06-21T19:40:58Z
[ "python", "list" ]
i want to find the intersection of two lists in python. i have something that looks like this: ``` >>> q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry'] >>> w = ['pineapple', 'peach', 'watermelon', 'kiwi'] ``` and i want to find something that looks like this: ``` t = ['peach', 'watermelon'] ``` i know its...
The intersection() method is available for [sets](http://docs.python.org/library/stdtypes.html#set), which can be easily made from lists. ETA: if you want a list out of it... ``` q = ['apple', 'peach', 'pear', 'watermelon', 'strawberry'] w = ['pineapple', 'peach', 'watermelon', 'kiwi'] t = list(set(q) & set(w)) ``` ...
Python encoding characters with urllib.quote
6,431,061
11
2011-06-21T19:41:22Z
6,431,284
19
2011-06-21T20:00:23Z
[ "javascript", "python", "encoding", "urllib" ]
I'm trying to encode non-ASCII characters so I can put them inside an url and use them in urlopen. The problem is that I want an encoding like javascript (that for example encodes "ó" as "%C3%B3"): ``` encodeURIComponent(ó) '%C3%B3' ``` But urllib.quote in python returns "ó" as "%F3": ``` urllib.quote(ó) '%F3' `...
You want to make sure you're using unicode. Example: ``` import urllib s = u"ó" print urllib.quote(s.encode("utf-8")) ``` Outputs: `%C3%B3`
gevent does not install properly on Ubuntu
6,431,096
41
2011-06-21T19:43:55Z
6,431,431
15
2011-06-21T20:15:36Z
[ "python", "gevent" ]
I want to experiment with [gevent](http://gevent.org), but after installing it I can't load any gevent module. The installation steps are: ``` sudo apt-get install libevent-dev sudo pip install greenlet sudo pip install gevent ``` The environment setup is Ubuntu 10.10 x86\_64 GNU/Linux. When I try to do a simple te...
In Ubuntu 10.10 (and later), gevent (and dependencies) is packaged in the Ubuntu repositories. on 11.04: ``` $ sudo apt-get install python-gevent ... $ python corey@lenovo:~$ python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more infor...
gevent does not install properly on Ubuntu
6,431,096
41
2011-06-21T19:43:55Z
9,990,181
60
2012-04-03T09:05:23Z
[ "python", "gevent" ]
I want to experiment with [gevent](http://gevent.org), but after installing it I can't load any gevent module. The installation steps are: ``` sudo apt-get install libevent-dev sudo pip install greenlet sudo pip install gevent ``` The environment setup is Ubuntu 10.10 x86\_64 GNU/Linux. When I try to do a simple te...
On Ubuntu 10.04 with python 2.6 I had to do: ``` apt-get install libevent-dev apt-get install python-all-dev easy_install greenlet easy_install gevent ``` By the way, nice tutorial on Gevent: <http://sdiehl.github.com/gevent-tutorial/>
Matplotlib - logarithmic scale, but require non-logarithmic labels
6,431,248
17
2011-06-21T19:57:43Z
6,431,725
19
2011-06-21T20:42:32Z
[ "python", "matplotlib" ]
How can I stop the y-axis displaying a logarithmic notation label on the y-axis? I'm happy with the logarithmic scale, but want to display the absolute values, e.g. [500, 1500, 4500, 11000, 110000] on the Y-axis. I don't want to explicitly label each tick as the labels may change in the future (I've tried out the diff...
IIUC, after ``` import matplotlib.ticker ``` any of ``` ax.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter()) ax.yaxis.set_major_formatter(matplotlib.ticker.FormatStrFormatter('%d')) ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, pos: str(int(round(x))))) ``` should work. '%d' wi...
Element-wise power of scipy.sparse matrix
6,431,557
11
2011-06-21T20:27:05Z
6,432,171
8
2011-06-21T21:23:21Z
[ "python", "numpy", "scipy", "sparse-matrix", "exponentiation" ]
How do I raise a `scipy.sparse` matrix to a power, element-wise? `numpy.power` should, according to [its manual](http://docs.scipy.org/doc/numpy/reference/generated/numpy.power.html#numpy.power), do this, but it fails on sparse matrices: ``` >>> X <1353x32100 sparse matrix of type '<type 'numpy.float64'>' with...
This is a little low-level, but for element-wise operations you can work with the underlying data array directly: ``` >>> import scipy.sparse >>> X = scipy.sparse.rand(1000,1000, density=0.003) >>> X = scipy.sparse.csr_matrix(X) >>> Y = X.copy() >>> Y.data **= 3 >>> >>> abs((X.toarray()**3-Y.toarray())).max() 0.0 ```
How to copy data from a numpy array to another
6,431,973
40
2011-06-21T21:06:41Z
6,432,072
43
2011-06-21T21:15:42Z
[ "python", "numpy" ]
What is the fastest way to copy data from array b to array a, without modifying the address of array a. I need this because an external library (PyFFTW) uses a pointer to my array that cannot change. For example: ``` a = numpy.empty(n, dtype=complex) for i in xrange(a.size): a[i] = b[i] ``` It is possible to do it...
I believe ``` a = numpy.empty_like (b) a[:] = b ``` will make a deep copy quickly. As Funsi mentions, recent versions of numpy also have the `copyto` function.
How to copy data from a numpy array to another
6,431,973
40
2011-06-21T21:06:41Z
14,873,748
16
2013-02-14T11:26:17Z
[ "python", "numpy" ]
What is the fastest way to copy data from array b to array a, without modifying the address of array a. I need this because an external library (PyFFTW) uses a pointer to my array that cannot change. For example: ``` a = numpy.empty(n, dtype=complex) for i in xrange(a.size): a[i] = b[i] ``` It is possible to do it...
numpy version 1.7 has the numpy.copyto function that does what you are looking for: > numpy.copyto(dst, src) > > Copies values from one array to another,> broadcasting as necessary. See: <http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.copyto.html>
Variable defined with with-statement available outside of with-block?
6,432,355
25
2011-06-21T21:42:48Z
6,432,420
11
2011-06-21T21:50:25Z
[ "python" ]
Consider the following example: ``` with open('a.txt') as f: pass # Is f supposed to be defined here? ``` I have read the language docs (2.7) for with-statement as well as PEP-343, but as far as I can tell they don't say anything on this matter. In CPython 2.6.5 `f` does seem to be defined outside of the with-bl...
the `with` syntax: ``` with foo as bar: baz() ``` is approximately sugar for: ``` try: bar = foo.__enter__() baz() finally: if foo.__exit__(*sys.exc_info()) and sys.exc_info(): raise: ``` This is often useful: for example ``` import threading with threading.Lock() as myLock: frob() wit...
Variable defined with with-statement available outside of with-block?
6,432,355
25
2011-06-21T21:42:48Z
6,433,149
7
2011-06-21T23:22:59Z
[ "python" ]
Consider the following example: ``` with open('a.txt') as f: pass # Is f supposed to be defined here? ``` I have read the language docs (2.7) for with-statement as well as PEP-343, but as far as I can tell they don't say anything on this matter. In CPython 2.6.5 `f` does seem to be defined outside of the with-bl...
To answer Heikki's question in the comments: yes, this scoping behavior is part of the python language specification and will work on any and all compliant Pythons (which includes PyPy, Jython, and IronPython).
Variable defined with with-statement available outside of with-block?
6,432,355
25
2011-06-21T21:42:48Z
6,433,152
53
2011-06-21T23:23:21Z
[ "python" ]
Consider the following example: ``` with open('a.txt') as f: pass # Is f supposed to be defined here? ``` I have read the language docs (2.7) for with-statement as well as PEP-343, but as far as I can tell they don't say anything on this matter. In CPython 2.6.5 `f` does seem to be defined outside of the with-bl...
Yes, the context manager will be available outside the with statement and that is not implementation or version dependent. with statements *do not* create a new execution scope.
How to do weighted random sample of categories in python
6,432,499
23
2011-06-21T21:56:45Z
6,432,707
17
2011-06-21T22:18:58Z
[ "python", "statistics", "numpy", "probability", "random-sample" ]
Given a list of tuples where each tuple consists of a probability and an item I'd like to sample an item according to its probability. For example, give the list [ (.3, 'a'), (.4, 'b'), (.3, 'c')] I'd like to sample 'b' 40% of the time. What's the canonical way of doing this in python? I've looked at the random modul...
This might do what you want: ``` numpy.array([.3,.4,.3]).cumsum().searchsorted(numpy.random.sample(5)) ```
How to do weighted random sample of categories in python
6,432,499
23
2011-06-21T21:56:45Z
6,432,755
7
2011-06-21T22:24:22Z
[ "python", "statistics", "numpy", "probability", "random-sample" ]
Given a list of tuples where each tuple consists of a probability and an item I'd like to sample an item according to its probability. For example, give the list [ (.3, 'a'), (.4, 'b'), (.3, 'c')] I'd like to sample 'b' 40% of the time. What's the canonical way of doing this in python? I've looked at the random modul...
``` import numpy n = 1000 pairs = [(.3, 'a'), (.3, 'b'), (.4, 'c')] probabilities = numpy.random.multinomial(n, zip(*pairs)[0]) result = zip(probabilities, zip(*pairs)[1]) # [(299, 'a'), (299, 'b'), (402, 'c')] [x[0] * x[1] for x in result] # ['aaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbb', 'cccccccccccccccccccc'] ``` How exact...
Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?
6,432,605
13
2011-06-21T22:07:27Z
7,445,560
19
2011-09-16T13:38:48Z
[ "python", "yaml", "pyyaml" ]
I'd like to be able to dump a dictionary containing long strings that I'd like to have in the block style for readability. For example: ``` foo: | this is a block literal bar: > this is a folded block ``` PyYAML supports the loading of documents with this style but I can't seem to find a way to dump documents...
``` import yaml class folded_unicode(unicode): pass class literal_unicode(unicode): pass def folded_unicode_representer(dumper, data): return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='>') def literal_unicode_representer(dumper, data): return dumper.represent_scalar(u'tag:yaml.org,2002:str...
Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?
6,432,605
13
2011-06-21T22:07:27Z
20,863,889
13
2013-12-31T22:40:04Z
[ "python", "yaml", "pyyaml" ]
I'd like to be able to dump a dictionary containing long strings that I'd like to have in the block style for readability. For example: ``` foo: | this is a block literal bar: > this is a folded block ``` PyYAML supports the loading of documents with this style but I can't seem to find a way to dump documents...
`pyyaml` does support dumping literal or folded blocks. # Using `Representer.add_representer` defining types: ``` class folded_str(str): pass class literal_str(str): pass class folded_unicode(unicode): pass class literal_unicode(str): pass ``` Then you can define the representers for those types. Please note tha...
Python nested generators
6,432,782
7
2011-06-21T22:27:39Z
6,432,907
7
2011-06-21T22:45:35Z
[ "python", "generator" ]
I was trying to implement the reverse function of itertools.izip on Python 2.7.1. The thing is that I find a problem, and I don't have an explantion. Solution 1, iunzip\_v1 works perfectly. But solution 2. iunzip\_v2, doesn't works as expected. Til now, I haven't found any relevant information about this problem, and r...
You're reinventing the wheel in a crazy way. `izip` is its own inverse: ``` >>> list(izip(*izip(range(10), range(10)))) [(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)] ``` But that doesn't quite answer your question, does it? The problem with your nested generators is a scoping problem that happens ...
Preferred Python XML processor
6,432,826
3
2011-06-21T22:34:00Z
6,433,099
9
2011-06-21T23:14:42Z
[ "python", "xml" ]
What is the preferred XML processor to use with Python? Some choices are * minidom * PyXML * ElementTree * ... EDIT: I will need to be able to read in documents and manipulate them. I also require pretty print functionality.
[lxml](http://lxml.de/) is where it's at. Here's some example code: ``` import textwrap from os.path import join from lxml import etree # string to Element tree = etree.XML(textwrap.dedent(''' <foo_tag> foo text <bar_tag some_attr='ok'>bar text</bar_tag> </foo_tag> ''')) print 'root text: ' , tree.tex...
How to modify elements of iterables with iterators? I.e. how to get write-iterators in Python?
6,432,898
4
2011-06-21T22:44:40Z
6,432,924
9
2011-06-21T22:48:42Z
[ "python", "iterator", "sequence", "immutability" ]
I like the Python syntax a lot, but as I'm coming from C++ I don't get one thing about iterators in Python. In C++ there are 2 kinds of iterators - constant and modifying (non-const). In python it seems (for what I've seen) like there is only the first kind and if you want to modify the elements, you have to use the in...
The syntax ``` for x in iterable ``` does not create any lazy copies -- it assigns the exact objects in the list to `x` one after the other. If these objects are mutable, you can modify them: ``` a = [[1, 2], [3, 4]] for x in a: x.append(5) print a ``` prints ``` [[1, 2, 5], [3, 4, 5]] ``` Your example uses a...
Deleting and changing a tkinter event binding in python
6,433,369
9
2011-06-21T23:54:05Z
6,433,503
17
2011-06-22T00:20:28Z
[ "python", "events", "tkinter" ]
How do i stop an event from being processed or switch what function is called for it? **Revised Code:** ``` from Tkinter import * class GUI: def __init__(self,root): Window = Frame(root) self.DrawArea = Canvas(Window) self.DrawArea.pack() Window.pack() self.DrawArea.bind(...
You can simply just call `bind()` again with the new function for the event. Since you are not making use of the third parameter, `add`, in `bind()` this will just overwrite whatever is already there. By default this parameter is `''` but it also accepts `"+"`, which will add a callback to the callbacks already trigger...
String to Object in Python
6,433,528
2
2011-06-22T00:23:17Z
6,433,590
11
2011-06-22T00:32:17Z
[ "python", "string", "object" ]
I need to be able to convert any string representation of an object back into its original state on another computer. I will use the class, A, as my example: ``` class A: def __init__(self): self.data = "test" self.name = "Bob" def __str__(self): return str(self...
You are looking at ways of serialising objects; this is a very standard problem. `pickle` is the standard solution, and you should look into it first. If you want to make a class pickleable, you need to define some custom methods on it, and ensure the module in which it is defined can be found on both the source and de...
Cross database join in sqlalchemy
6,433,592
9
2011-06-22T00:32:38Z
6,434,119
12
2011-06-22T02:04:25Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
Is there a way in SQLAlchemy to do cross-database joins. To be specific, here is my use case: **Schema** 1. db1.entity1 1. entity1\_id: Primary Key 2. entity2\_id: Foreign Key to db2.entity2.entity2\_id 2. db2.entity2 1. entity2\_id: Primary Key **Model** I'm using *declarative style* for models. ``` clas...
You probably need to pass the `schema` parameter to `sqlalchemy.schema.Table`. When using declarative base for ORM mapping, you can provide this extra parameter through the `__table_args__` property on your classes. ``` class Entity2(Base): __tablename__ = 'entity2' ## I tried combination of <db>.<table> with no s...
Is there an implementation of Hadley's ddply for python?
6,434,048
14
2011-06-22T01:50:03Z
6,434,161
8
2011-06-22T02:11:57Z
[ "python", "plyr" ]
I find Hadley's [plyr](http://had.co.nz/plyr/) package for R extremely helpful, its a great DSL for transforming data. The problem that is solves is so common, that I face it other use cases, when not manipulating data in R, but in other programming languages. Does anyone know if there exists an a module that does a s...
This is the implementation I drafted up: ``` def ddply(rows, cols, op=lambda group_rows: group_rows): """group rows by cols, then apply the function op to each group rows is list of values or dict with col names (like read from csv.reader or csv.DictReader)""" def group_key(row): ...
What is usage of the last comma in this code?
6,434,308
7
2011-06-22T02:39:51Z
6,434,317
18
2011-06-22T02:41:25Z
[ "python" ]
``` for x in range(1, 11): print repr(x).rjust(2), repr(x*x).rjust(3), # Note trailing comma on previous line print repr(x*x*x).rjust(4) ``` result: ``` 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 ``` If it is a line continuat...
It stops `print` from printing a newline at the end of the text. As Dave pointed out, the [documentation](http://docs.python.org/reference/) says: …. "A '\n' character is written at the end, unless the print statement ends with a comma."
Python function overloading
6,434,482
82
2011-06-22T03:11:02Z
6,434,546
79
2011-06-22T03:20:43Z
[ "python", "design", "method-overloading", "function-overloading" ]
I know that Python does not support method overloading, but I've run into a problem that I can't seem to solve in a nice Pythonic way. I am making a game where a character needs to shoot a variety of bullets, but how do I write different functions for creating these bullets? For example suppose I have a function that ...
Python does support "method overloading" as you present it. In fact, what you just describe is trivial to implement in Python, in so many different ways, but I would go with: ``` class Character(object): # your character __init__ and other methods go here def add_bullet(self, sprite=default, start=default, ...
Python function overloading
6,434,482
82
2011-06-22T03:11:02Z
6,434,565
8
2011-06-22T03:25:39Z
[ "python", "design", "method-overloading", "function-overloading" ]
I know that Python does not support method overloading, but I've run into a problem that I can't seem to solve in a nice Pythonic way. I am making a game where a character needs to shoot a variety of bullets, but how do I write different functions for creating these bullets? For example suppose I have a function that ...
This type of behaviour is typically solved (in OOP languages) using Polymorphism. Each type of bullet would be responsible for knowing how it travels. For instance: ``` class Bullet(object): def __init__(self): self.curve = None self.speed = None self.acceleration = None self.sprite...
Python function overloading
6,434,482
82
2011-06-22T03:11:02Z
7,308,379
58
2011-09-05T12:53:12Z
[ "python", "design", "method-overloading", "function-overloading" ]
I know that Python does not support method overloading, but I've run into a problem that I can't seem to solve in a nice Pythonic way. I am making a game where a character needs to shoot a variety of bullets, but how do I write different functions for creating these bullets? For example suppose I have a function that ...
You can use "roll-your-own" solution for function overloading. This one is copied from [Guido van Rossum's article](http://www.artima.com/weblogs/viewpost.jsp?thread=101605) about multimethods (because there is little difference between mm and overloading in python): ``` registry = {} class MultiMethod(object): d...
Python function overloading
6,434,482
82
2011-06-22T03:11:02Z
25,020,148
9
2014-07-29T16:19:36Z
[ "python", "design", "method-overloading", "function-overloading" ]
I know that Python does not support method overloading, but I've run into a problem that I can't seem to solve in a nice Pythonic way. I am making a game where a character needs to shoot a variety of bullets, but how do I write different functions for creating these bullets? For example suppose I have a function that ...
A possible option is to use the multipledispatch module as detailed here: <http://matthewrocklin.com/blog/work/2014/02/25/Multiple-Dispatch/> Instead of doing this: ``` def add(self, other): if isinstance(other, Foo): ... elif isinstance(other, Bar): ... else: raise NotImplementedE...
Python function overloading
6,434,482
82
2011-06-22T03:11:02Z
29,091,980
37
2015-03-17T05:35:19Z
[ "python", "design", "method-overloading", "function-overloading" ]
I know that Python does not support method overloading, but I've run into a problem that I can't seem to solve in a nice Pythonic way. I am making a game where a character needs to shoot a variety of bullets, but how do I write different functions for creating these bullets? For example suppose I have a function that ...
What you are asking for, is called *multiple dispatch*. See [Julia](http://nbviewer.ipython.org/gist/StefanKarpinski/b8fe9dbb36c1427b9f22) language examples which demonstrates different types of dispatches. However, before looking at that, we'll first tackle why *overloading* is not really what you want in python. # ...
How do you add csrf validation to pyramid?
6,434,550
7
2011-06-22T03:21:56Z
6,442,928
9
2011-06-22T15:59:19Z
[ "python", "pyramid" ]
I'm passing in a csrf\_token for every post and xhr request and want to validate the token against the session csrf token. If they don't match, I throw a 401. I've used the NewResponse subscriber in pyramid to inspect the request and validate the csrf token in the request params against the token in the session. The v...
The `NewResponse` subscriber is called *after* your view is invoked. You want to be using an event that is invoked earlier, for example `NewRequest` or `ContextFound`. In Pyramid 1.0, you'll need to use `ContextFound` to properly handle things because you cannot raise exceptions in `NewRequest` events (this is fixed i...
What is the Python convention **kwargs vs **kwds vs **kw?
6,435,319
12
2011-06-22T05:29:04Z
6,435,329
10
2011-06-22T05:30:38Z
[ "python", "kwargs" ]
Is there a python naming convention for **key word arguments**?
Nope, but normally it is named as `**kwargs`, but you can name it anything you want. Only thing is it should come at the last following any position args and named args.
Generate Database Schema using Python
6,437,907
9
2011-06-22T09:46:16Z
6,438,040
9
2011-06-22T09:58:20Z
[ "python", "database", "django", "schema" ]
I want to generate a basic DB schema for my django project ,to display all my Apps with Models and Model Fields with boundary conditions etc . Is there already any DB schema generator for django in python ? Or otherwise how should i go about doing it .
If your talking about needing to see the SQL schema, run `./manage.py sqlall <appname>` If you want a visualisation of the schema you can get `django-extensions` and run `./manage.py graph_models -a -g -o my_project.png`. This will produce a pretty schema graph for you, but generally omits border conditions. you may w...
Why Python is not better in multiprocessing or multithreading applications than Java?
6,439,061
5
2011-06-22T11:29:17Z
6,439,138
11
2011-06-22T11:36:22Z
[ "java", "python", "multithreading", "multiprocessing", "gil" ]
Since Python has some issues with GIL, Java is better for developing multiprocessing applications. Could you please justify the exact reasoning of java's effective processing than python in your way?
The biggest problem in multithreading in CPython is the [Global Interpreter Lock (GIL)](http://wiki.python.org/moin/GlobalInterpreterLock) (note that other Python implementations **don't** necessarily share this problem!) The GIL is an implementation detail that effectively prevents concurrent execution of separate th...
int((0.1+0.7)*10) = 7 in several languages. How to prevent this?
6,439,140
11
2011-06-22T11:36:24Z
6,439,205
29
2011-06-22T11:40:43Z
[ "php", "javascript", "python", "ruby", "internal-representation" ]
Recently I came across a bug/feature in several languages. I have a very basic knowledge about how it's caused (and I'd like some detailed explanation), but when I think of all the bugs I must have made over the years, the question is how can I determine "***Hey, this might cause a riddiculous bug, I'd better use arbit...
[What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html)
Sending a reset in TCP/IP Socket connection
6,439,790
11
2011-06-22T12:26:38Z
6,440,364
18
2011-06-22T13:07:04Z
[ "python", "sockets", "networking", "reset" ]
I am using python’s socket.py to create a connection to an ftp-server. Now I want to reset the connection (send a RST Flag) and listen to the response of the ftp-server. (FYI using socket.send('','R') does not work as the OS sends FIN flag instead of RST.)
Turn the SO\_LINGER socket option on and set the linger time to 0 seconds. This will cause TCP to abort the connection when it is closed, flush the data and send a RST. See section 7.5 and example 15.21 in UNP. In python: ``` def client(host, port): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.c...
How do i parse a string in python and write it as an xml to a new xml file?
6,440,115
2
2011-06-22T12:48:52Z
6,440,261
7
2011-06-22T12:58:45Z
[ "python", "xml" ]
I have xml data in string format which is in variable xml\_data ``` xml_data="<?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>" ``` I want to save this data to a new xml file through python. I am using this cod...
With `ET.tostring(tree)` you get a non-formatted string representation of the XML. To save it to a file: ``` with open("filename", "w") as f: f.write(ET.tostring(tree)) ```
Getting function object for int() and float() functions
6,440,397
5
2011-06-22T13:09:40Z
6,440,429
11
2011-06-22T13:12:05Z
[ "python", "function" ]
I want to pass a function to a function in Python. I know I can do this simply by putting the function name as a parameter, eg: ``` blah(5, function) ``` However, I want to pass the `int()` function and the `float()` function to this function. If I just put the function name in then it assumes I am referring to the `...
Just passing `int` and `float` is fine. You are right that this will actually pass type objects instead of functions, but that's not important. The important thing is that the passed object is callable, and calling the type objects will do what you expect.
Python multiprocessing
6,440,474
5
2011-06-22T13:15:16Z
6,440,536
10
2011-06-22T13:19:23Z
[ "python", "multicore", "multiprocessing" ]
This question is more fact finding and thought process than code oriented. I have many compiled C++ programs that I need to run at different times and with different parameters. I'm looking at using Python multiprocessing to read a job from job queue (rabbitmq) and then feed that job to a C++ program to run (maybe sub...
> The Python program would be the > central manager and would simply read > jobs from the que, spawn a process (or > subprocess?) with the appropriate C++ > program to run the job, get the > results (subprocess stdout & stderr), > feed that to a callback and put the > process back in a que of processes > waiting for th...
Executing python scripts with subprocess.call using shebang
6,441,507
3
2011-06-22T14:23:54Z
6,441,590
8
2011-06-22T14:29:19Z
[ "python", "python-3.x", "subprocess", "shebang" ]
I'm writing a (somewhat) modular application in Python 3 and I'd like to run arbitrary programs from it, said program being specified at runtime and not necessarily a python script. So I use for example, ``` subprocess.call([spam, "-i", eggs, "-o", ham]) ``` If `spam` is a python script, with shebang to `python3` an...
You need to use `shell=True`, and you need your array to be turned into a command string, like this: ``` subprocess.call(' '.join([spam, "-i", eggs, "-o", ham]), shell=True) ``` This will invoke the shell instead of the direct command, and the shell should be able to handle the shebang.
NaNs as key in dictionaries
6,441,857
14
2011-06-22T14:47:44Z
6,441,990
25
2011-06-22T14:57:55Z
[ "python", "numpy", null ]
Can anyone explain the following behaviour to me? ``` >>> import numpy as np >>> {np.nan: 5}[np.nan] 5 >>> {float64(np.nan): 5}[float64(np.nan)] KeyError: nan ``` Why does it work in the first case, but not in the second? Additionally, I found that the following DOES work: ``` >>> a ={a: 5}[a] float64(np.nan) ```
The problem here is that NaN is not equal to itself, as defined in the IEEE standard for floating point numbers: ``` >>> float("nan") == float("nan") False ``` When a dictionary looks up a key, it roughly does this: 1. Compute the hash of the key to be looked up. 2. For each key in the dict with the same hash, check...
Python equivalence to inline functions or macros
6,442,050
22
2011-06-22T15:02:55Z
6,442,497
22
2011-06-22T15:31:48Z
[ "python", "optimization", "inline-functions" ]
I just realized that doing ``` x.real*x.real+x.imag*x.imag ``` is three times faster than doing ``` abs(x)**2 ``` where x is a numpy array of complex numbers. For code readability, I could define a function like ``` def abs2(x): return x.real*x.real+x.imag*x.imag ``` which is still far faster than abs(x)\*\*2...
> Is it possible to inline such a function, as I would do in C using macro or using inline keyword? No. Before reaching this specific instruction, Python interpreters don't even know if there's such a function, much less what it does. As noted in comments, PyPy **will inline automatically** (the above still holds - i...
python -- measuring pixel brightness
6,442,118
8
2011-06-22T15:07:26Z
6,449,381
13
2011-06-23T04:35:34Z
[ "python", "image", "pixel", "brightness" ]
How can I get a measure for a pixels brightness for a specific pixel in an image? I'm looking for an absolute scale for comparing different pixels' brightness. Thanks
To get the pixel's RGB value you can use [PIL](http://www.pythonware.com/products/pil/): ``` import Image imag = Image.open("yourimage.yourextension") #Convert the image te RGB if it is a .gif for example imag = imag.convert ('RGB') #coordinates of the pixel X,Y = 0,0 #Get RGB pixelRGB = imag.getpixel((X,Y)) R,G,B = p...
How do I get the picture size with PIL?
6,444,548
43
2011-06-22T18:17:08Z
6,444,612
83
2011-06-22T18:21:24Z
[ "python", "python-imaging-library", "image" ]
How do I get a size of a pictures sides with PIL or any other Python library?
`width, height = im.size` According to the [documentation](http://effbot.org/imagingbook/image.htm).
How do I get the picture size with PIL?
6,444,548
43
2011-06-22T18:17:08Z
34,704,661
7
2016-01-10T11:06:24Z
[ "python", "python-imaging-library", "image" ]
How do I get a size of a pictures sides with PIL or any other Python library?
You can use PIL (Python Image Library) for that. The same interface, but less problems with Python 3 has [Pillow](https://python-pillow.github.io/). Here is the complete code (it is the same for PIL and Pillow): ``` from PIL import Image filename = "image.png" with Image.open(filename) as im: width, height = im....
Python method name with double-underscore is overridden?
6,444,576
28
2011-06-22T18:18:46Z
6,444,617
29
2011-06-22T18:21:33Z
[ "python" ]
Take a look at this. Note that class `B` overrides `A`'s `a()` method. ``` In [1]: class A(object): ...: def __init__(self): ...: self.a() ...: def a(self): ...: print "A.a()" ...: ...: In [2]: class B(A): ...: def __init__(self): ...: supe...
keywords with a pattern of \_\_\* are class private names. <http://docs.python.org/reference/lexical_analysis.html#reserved-classes-of-identifiers> Quoting: > Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private...
Force python to use an older version of module (than what I have installed now)
6,445,167
4
2011-06-22T19:07:06Z
6,445,404
12
2011-06-22T19:29:33Z
[ "python", "linux", "twisted", "python-import" ]
My employer has a dedicated module1 we use for internal unit / system test; however, the author of this module no longer works here and I have been asked to test some devices with it. The problem is that `pyfoo` requires an ancient version of `twisted` (v8.2.0) and it imports `twisted` in 33 different files. I tried r...
A better version of option B. would be to replace ``` import twisted ``` by ``` import pkg_resources pkg_resources.require("Twisted==8.2.0") import twisted ``` which will arrange for the correct version of twisted to be imported, so long as it's installed, and raises an exception otherwise. This is a more portable ...
how to couple 'reasons' with return values, elegantly
6,446,603
2
2011-06-22T21:09:57Z
6,446,653
8
2011-06-22T21:14:12Z
[ "python", "design" ]
What often happens in code I'm writing is I'll have a function that checks a condition dependent on many other conditions, e.g.: ``` def is_foo(bar): if X: return True if Y: return False if Z: return True return False ``` Then, I'll want to debug my code or log it, so I'll change the above to: ``` de...
This is a perfectly good way to do it. Only thing I might change is nest `is_foo_reason` in `is_foo` (so that there's only one, simple interface) and add a default argument to `is_foo()`, e.g. ``` #for backwards compatibility: def is_foo(bar, reason=False): def is_foo_reason(bar): if X: return True, "caus...
PyQt (PySide), WebKit and exposing methods from/to Javascript
6,447,011
9
2011-06-22T21:54:14Z
6,473,454
24
2011-06-24T20:31:36Z
[ "javascript", "python", "webkit", "pyqt", "pyside" ]
I am planning to use PyQt to control an embedded WebKit browser on the server side. I have some inherit application logic in Javascript in the HTML page running inside WebKit. How could I communicate from the host process (Python, PyQt) with Javascript, so that * I can call Javascript functions inside the page * Pyt...
The following source code should be helpful: ``` import sys from PyQt4.QtCore import QObject, pyqtSlot from PyQt4.QtGui import QApplication from PyQt4.QtWebKit import QWebView html = """ <html> <body> <h1>Hello!</h1><br> <h2><a href="#" onclick="printer.text('Message from QWebView')">QObject Test</a></h2> ...
Convert Any Iterable to Array in Python
6,447,388
2
2011-06-22T22:38:01Z
6,447,437
10
2011-06-22T22:43:29Z
[ "python", "arrays", "list", "iterable" ]
This just *has* to be a dupe, but I just didn't find any existing instance of this question... What is the easiest way to convert any iterable to an array in Python (ideally, without importing anything)? **Note**: Ideally, if the input is an array then it shouldn't duplicate it (but this isn't required).
It depends on what you mean by array. If you really mean array and not list or the like, then you should be aware that arrays are containers of elements of the same (basic) type (see <http://docs.python.org/library/array.html>), i.e. not all iterables can be converted into an array. If you mean list, try the following:...
Python reading of a file stops before it should in Windows 7
6,447,760
3
2011-06-22T23:33:25Z
6,447,779
7
2011-06-22T23:36:00Z
[ "python", "windows-7", "disk", "readfile" ]
I am using Python to open the physical disk in the computer to read the first sector. ``` disk = r"\\.\PhysicalDrive0" with open(disk, 'r') as f: f.seek(0) partdata = f.read(512) len(partdata) ``` In windows XP `len(partdata)` will return 512 and have the correct content. In windows 7 `len(partdata)` ...
Try opening in binary mode ``` with open(disk, 'rb') as f: ```
Implement lookahead iterator for strings in Python
6,448,117
6
2011-06-23T00:30:48Z
6,448,141
11
2011-06-23T00:37:19Z
[ "python", "algorithm" ]
I'm doing some parsing that requires one token of lookahead. What I'd like is a fast function (or class?) that would take an iterator and turn it into a list of tuples in the form (token, lookahead), such that: ``` >>> a = ['a', 'b', 'c', 'd'] >>> list(lookahead(a)) [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', None)] ``...
There are easier ways if you are just using lists - see Sven's answer. Here is one way to do it for general iterators ``` >>> from itertools import tee, izip_longest >>> a = ['a', 'b', 'c', 'd'] >>> it1, it2 = tee(iter(a)) >>> next(it2) # discard this first value 'a' >>> [(x,y) for x,y in izip_longest(it1, it2)] ...
Implement lookahead iterator for strings in Python
6,448,117
6
2011-06-23T00:30:48Z
6,448,281
8
2011-06-23T01:05:48Z
[ "python", "algorithm" ]
I'm doing some parsing that requires one token of lookahead. What I'd like is a fast function (or class?) that would take an iterator and turn it into a list of tuples in the form (token, lookahead), such that: ``` >>> a = ['a', 'b', 'c', 'd'] >>> list(lookahead(a)) [('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', None)] ``...
I like both [Sven's](http://stackoverflow.com/questions/6448117/implement-lookahead-iterator-in-python/6448126#6448126) and [gnibbler's](http://stackoverflow.com/questions/6448117/implement-lookahead-iterator-in-python/6448141#6448141) answers, but for some reason, it pleases me to roll my own generator. ``` def looka...