text
stringlengths
185
26.5k
<s>[INST] Find out how much memory is being used by an object in Python How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. [/INST] There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries). There is a big chunk of code (and an updated big chunk of code) out there to try to best approximate the size of a python object in memory. There's also some simpler approximations. But they will always be approximations. You may also want to check some old description about PyObject (the internal C struct that represents virtually all python objects). </s>
<s>[INST] flask - how do you get a query string from flask Not obvious from the flask documention on how to get the query string. I am new, looked at the docs, could not find! So @app.route('/') @app.route('/data') def data(): query_string=?????? return render_template("data.html") [/INST] from flask import request @app.route('/data') def data(): # here we want to get the value of user (i.e. ?user=some-value) user = request.args.get('user') </s>
<s>[INST] Get key with the least value from a dictionary If I have a Python dictionary, how do I get the key to the entry which contains the minimum value? I was thinking about something to do with the min() function... Given the input: {320:1, 321:0, 322:3} It would return 321. [/INST] Best: min(d, key=d.get) -- no reason to interpose a useless lambda indirection layer or extract items or keys! </s>
<s>[INST] Python append dictionary to dictionary I have two existing dictionaries, and I wish to 'append' one of them to the other. By that I mean that the key,values of the other dictionary should be made into the first dictionary. For example: orig = { 'A': 1, 'B': 2, 'C': 3, } extra = { 'D': 4, 'E': 5, } dest = # something here involving orig and extra print dest { 'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5 } I think this all can be achieved through a for loop (maybe?) but is there some method in the dictionaries or any other module that saves this job for me? The actual dictionaries I'm using are really big... [/INST] You can do orig.update(extra) or, if you don't want orig to be modified, make a copy first: dest = dict(orig) # or orig.copy() dest.update(extra) Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example, >>> d1 = {1: 1, 2: 2} >>> d2 = {2: 'ha!', 3: 3} >>> d1.update(d2) >>> d1 {1: 1, 2: 'ha!', 3: 3} </s>
<s>[INST] Why does range(start, end) not include end? >>> range(1,11) gives you [1,2,3,4,5,6,7,8,9,10] Why not 1-11? Did they just decide to do it like that at random or does it have some value I am not seeing? [/INST] Because it's more common to call range(0, 10) which returns [0,1,2,3,4,5,6,7,8,9] which contains 10 elements which equals len(range(0, 10)). Remember that programmers prefer 0-based indexing. Also, consider the following common code snippet: for i in range(len(li)): pass Could you see that if range() went up to exactly len(li) that this would be problematic? The programmer would need to explicitly subtract 1. This also follows the common trend of programmers preferring for(int i = 0; i < 10; i++) over for(int i = 0; i <= 9; i++). If you are calling range with a start of 1 frequently, you might want to define your own function: >>> range1 = lambda start, end: range(start, end+1) >>> range1(1, 10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] </s>
<s>[INST] Which is faster in Python: x**.5 or math.sqrt(x)? I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power? UPDATE This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works? I sent Guido van Rossum an email cause I really wanted to know the differences in these methods. My email: There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better? His response: pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea... [/INST] As per comments, I've updated the code: import time import math def timeit1(): s = time.time() for i in xrange(750000): z=i**.5 print "Took %f seconds" % (time.time() - s) def timeit2(arg=math.sqrt): s = time.time() for i in xrange(750000): z=arg(i) print "Took %f seconds" % (time.time() - s) timeit1() timeit2() Now the math.sqrt function is directly in a local argument, meaning it has the fastest lookup possible. UPDATE: The python version seems to matter here. I used to think that timeit1 would be faster, since when python parses "i**.5" it knows, syntactically, which method to call (__pow__ or some variant), so it doesn't have to go through the overhead of lookup that the math.sqrt variant does. But I might be wrong: Python 2.5: 0.191000 vs. 0.224000 Python 2.6: 0.195000 vs. 0.139000 Also psyco seems to deal with math.sqrt better: Python 2.5 + Psyco 2.0: 0.109000 vs. 0.043000 Python 2.6 + Psyco 2.0: 0.128000 vs. 0.067000 | Interpreter | x**.5, | sqrt, | sqrt faster, % | | | seconds | seconds | | |----------------+---------+---------+----------------| | Python 3.2rc1+ | 0.32 | 0.27 | 19 | | Python 3.1.2 | 0.136 | 0.088 | 55 | | Python 3.0.1 | 0.155 | 0.102 | 52 | | Python 2.7 | 0.132 | 0.079 | 67 | | Python 2.6.6 | 0.121 | 0.075 | 61 | | PyPy 1.4.1 | 0.083 | 0.0159 | 422 | | Jython 2.5.1 | 0.132 | 0.22 | -40 | | Python 2.5.5 | 0.129 | 0.125 | 3 | | Python 2.4.6 | 0.131 | 0.123 | 7 | #+TBLFM: $4=100*($2-$3)/$3;%.0f Table results produced on machine: $ uname -vms Linux #42-Ubuntu SMP Thu Dec 2 02:41:37 UTC 2010 x86_64 $ cat /proc/cpuinfo | grep 'model name' | head -1 model name : Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz To reproduce results: get source: git clone git://gist.github.com/783011.git gist-783011 install tox: pip install tox run tox from the directory with tox.ini file. </s>
<s>[INST] Test if a variable is a list or tuple In python, what's the best way to test if a variable contains a list or a tuple? (ie. a collection) Is isinstance as evil as suggested here? http://www.canonical.org/~kragen/isinstance/ Update : the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / data-structure of lists of lists of lists of strings etc. which I'm exploring with a recursive algorithm and I need to know when I've hit the "leaf" nodes. [/INST] if type(x) is list: print 'a list' elif type(x) is tuple: print 'a tuple' else: print 'neither a tuple or a list' </s>
<s>[INST] Installing SciPy and NumPy using pip I'm trying to create required libraries in a package I'm distributing. It requires both the SciPy and NumPy libraries. While developing, I installed both using apt-get install scipy which installed SciPy 0.9.0 and NumPy 1.5.1, and it worked fine. I would like to do the same using pip install - in order to be able to specify dependencies in a setup.py of my own package. The problem is, when I try: pip install 'numpy==1.5.1' it works fine. But then pip install 'scipy==0.9.0' fails miserably, with raise self.notfounderror(self.notfounderror.__doc__) numpy.distutils.system_info.BlasNotFoundError: Blas (http://www.netlib.org/blas/) libraries not found. Directories to search for the libraries can be specified in the numpy/distutils/site.cfg file (section [blas]) or by setting the BLAS environment variable. How do I get it to work? [/INST] This worked for me on Ubuntu 14.04: sudo apt-get install libblas-dev liblapack-dev libatlas-base-dev gfortran pip install scipy </s>
<s>[INST] Find String index from last in Python I think it might be a silly question but as I'm totally new to Python, i don't know anything about it. I want to find the last position of a target string in given str as a input. For ex. str='hello' and target='l' then it should output 3. How can i do this? [/INST] Use .rfind(): >>> s = 'hello' >>> s.rfind('l') 3 Also don't use str as variable name or you'll shadow the built-in str(). </s>
<s>[INST] e.printStackTrace equivalent in python I know that print e {where e is Exception} prints the occurred exception but, I was trying to find the python equivalent of e.printStackTrace() that exactly traces the exception what line it occurred and prints the entire trace of it. Could anyone please tell me the equivalent of e.printStackTrace() in python? [/INST] import traceback traceback.print_exc() When doing this inside an except ...: block it will automatically use the current exception. See http://docs.python.org/library/traceback.html for more information. </s>
<s>[INST] Python When I catch an exception, how do I get the type, file, and line number? Catching an exception that would print like this: Traceback (most recent call last): File "c:/tmp.py", line 1, in <module> 4 / 0 ZeroDivisionError: integer division or modulo by zero I want to format it into: ZeroDivisonError, tmp.py, 1 [/INST] import sys, os try: raise NotImplementedError("No error") except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) </s>
<s>[INST] Python3 error: "Import error: No module name urllib2" Here's my code: import urllib2.request response = urllib2.urlopen("http://www.google.com") html = response.read() print(html) Any help? [/INST] As stated in the urllib2 documentation at http://docs.python.org/library/urllib2.html: The urllib2 module has been split across several modules in Python 3.0 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to 3 So you should instead be saying from urllib.request import urlopen html = urlopen("http://www.google.com/") print(html) Your current, now-edited code sample is incorrect because you are saying urllib.urlopen("http://www.google.com/") instead of just urlopen("http://www.google.com/"). </s>
<s>[INST] Why doesn't Python have a sign function? I can't understand why Python doesn't have a sign function. It has an abs builtin (which I consider sign's sister), but no sign. In python 2.6 there is even a copysign function (in math), but no sign. Why bother to write a copysign(x,y) when you could just write a sign and then get the copysign directly from abs(x) * sign(y)? The latter would be much more clear: x with the sign of y, whereas with copysign you have to remember if it's x with the sign of y or y with the sign of x! Obviously sign(x) does not provide anything more than cmp(x,0), but it would be much more readable that this too (and for a greatly readable language like python, this would have been a big plus). If I were a python designer, I would been the other way arond: no cmp builtin, but a sign. When you need cmp(x,y), you could just do a sign(x-y) (or, even better for non-numerical stuff, just a x>y - of course this should have required sorted accepting a boolean instead of an integer comparator). This would also be more clear: positive when x>y (whereas with cmp you have to remember the convention positive when the first is bigger, but it could be the other way around). Of course cmp makes sense in its own for other reasons (e.g. when sorting non-numerical things, or if you want the sort to be stable, which is not possible using with simply a boolean) So, the question is: why did the Python designer(s) decide to leave the sign function out of the language? Why the heck bother with copysign and not its parent sign? Am I missing something? EDIT - after Peter Hansen comment. Fair enough that you didn't use it, but you didn't say what you use python for. In 7 years that I use python, I needed it countless times, and the last is the straw that broke the camel's back! Yes, you can pass cmp around, but 90% of the times that I needed to pass it was in an idiom like lambda x,y: cmp(score(x),score(y)) that would have worked with sign just fine. Finally, I hope you agree that sign would be more useful than copysign, so even if I bought your view, why bother about defining that in math, instead of sign? How can copysign be so much useful than sign? [/INST] EDIT: Indeed there was a patch which included sign() in math, but it wasn't accepted, because they didn't agree on what it should return in all the edge cases (+/-0, +/-nan, etc) So they decided to implement only copysign, which (although more verbose) can be used to delegate to the end user the desired behavior for edge cases - which sometimes might require the call to cmp(x,0). I don't know why it's not a built-in, but I have some thoughts. copysign(x,y): Return x with the sign of y. Most importantly, copysign is a superset of sign! Calling copysign with x=1 is the same as a sign function. So you could just use copysign and forget about it. >>> math.copysign(1, -4) -1.0 >>> math.copysign(1, 3) 1.0 If you get sick of passing two whole arguments, you can implement sign this way, and it will still be compatible with the IEEE stuff mentioned by others: >>> sign = functools.partial(math.copysign, 1) # either of these >>> sign = lambda x: math.copysign(1, x) # two will work >>> sign(-4) -1.0 >>> sign(3) 1.0 >>> sign(0) 1.0 >>> sign(-0.0) -1.0 >>> sign(float('nan')) -1.0 Secondly, usually when you want the sign of something, you just end up multiplying it with another value. And of course that's basically what copysign does. So, instead of: s = sign(a) b = b * s You can just do: b = copysign(b, a) And yes, I'm surprised you've been using Python for 7 years and think cmp could be so easily removed and replaced by sign! Have you never implemented a class with a __cmp__ method? Have you never called cmp and specified a custom comparator function? In summary, I've found myself wanting a sign function too, but copysign with the first argument being 1 will work just fine. I disagree that sign would be more useful than copysign, as I've shown that it's merely a subset of the same functionality. </s>
<s>[INST] Python normal arguments vs. keyword arguments How are "keyword arguments" different from regular arguments? Can't all arguments be passed as name=value instead of using positional syntax? [/INST] there are two related concepts, both called "keyword arguments". On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all. The other concept is on the function definition side: You can define a function that takes parameters by name -- and you don't even have to specify what those names are. These are pure keyword arguments, and can't be passed positionally. The syntax is def my_function(arg1, arg2, **kwargs) Any keyword arguments you pass into this function will be placed into a dictionary named kwargs. You can examine the keys of this dictionary at run-time, like this: def my_function(**kwargs): print str(kwargs) my_function(a=12, b="abc") {'a': 12, 'b': 'abc'} </s>
<s>[INST] Activate a virtualenv via fabric as deploy user I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull. def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') I typically use the workon command from virtualenvwrapper which sources the activate file and the postactivate file will put me in the project folder. In this case, it seems that because fabric runs from within shell, control is give over to fabric, so I can't use bash's source built-in to '$source ~/.virtualenv/myvenv/bin/activate' Anybody have an example and explanation of how they have done this? [/INST] As an update to bitprophet's forecast: With Fabric 1.0 you can make use of prefix() and your own context managers. from __future__ import with_statement from fabric.api import * from contextlib import contextmanager as _contextmanager env.hosts = ['servername'] env.user = 'deploy' env.keyfile = ['$HOME/.ssh/deploy_rsa'] env.directory = '/path/to/virtualenvs/project' env.activate = 'source /path/to/virtualenvs/project/bin/activate' @_contextmanager def virtualenv(): with cd(env.directory): with prefix(env.activate): yield def deploy(): with virtualenv(): run('pip freeze') </s>
<s>[INST] datetime.datetime.utcnow() why no tzinfo? datetime.datetime.utcnow() datetime.datetime(2010, 2, 25, 4, 14, 37, 366086) Why does this datetime not have any tz info say its a utc date. [/INST] That means it is timezone naive, so you can't use it with datetime.astimezone you can give it a timezone like this import pytz # 3rd party: $ pip install pytz u = datetime.utcnow() u = u.replace(tzinfo=pytz.utc) #NOTE: it works only with a fixed utc offset now you can change timezones print(u.astimezone(pytz.timezone("America/New_York"))) To get the current time in a given timezone, you could pass tzinfo to datetime.now() directly: #!/usr/bin/env python from datetime import datetime import pytz # $ pip install pytz print(datetime.now(pytz.timezone("America/New_York"))) It works for any timezone including those that observe daylight saving time (DST) i.e., it works for timezones that may have different utc offsets at different times (non-fixed utc offset). Don't use tz.localize(datetime.now()) -- it may fail during end-of-DST transition when the local time is ambiguous. </s>
<s>[INST] Is it possible to implement a Python for range loop without an iterator variable? Is is possible to do this; for i in range(some_number): #do something without the i? If you just want to do something x amount of times and don't need the iterator. [/INST] Off the top of my head, no. I think the best you could do is something like this: def loop(f,n): for i in xrange(n): f() loop(lambda: <insert expression here>, 5) But I think you can just live with the extra i variable. Here is the option to use the _ variable, which in reality, is just another variable. for _ in range(n): do_something() Note that _ is assigned the last result that returned in an interactive python session: >>> 1+2 3 >>> _ 3 For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter. >>> for _ in xrange(10): pass ... >>> _ 9 >>> 1+2 3 >>> _ 9 And according to python grammar, it is an acceptable variable name: identifier ::= (letter|"_") (letter | digit | "_")* </s>
<s>[INST] Adding Python Path on Windows 7 I've been trying to add the Python path to the command line on Windows 7, yet no matter the method I try, nothing seems to work. I've used the set command, I've tried adding it through the Edit Environment variables prompt etc. Further more if I run the set command on the command line it lists this python = c:\python27 Yet it still doesn't recognize the Python command. Reading the documentation, and various other sources hasn't seemed to help. Edit: Just to clarify further, I've appended the path of the Python executable to PATH in edit environment prompt. Doesn't seem to work. [/INST] Hold Win and press Pause. Click Advanced System Settings. Click Environment Variables. Append ;C:\python27 to the Path variable. Restart Command Prompt. </s>
<s>[INST] Python: How do I format a date in Jinja2? Using Jinja2, how do I format a date field? I know in Python I can simply do this: print car.date_of_manufacture.strftime('%Y-%m-%d') But how do I format the date in Jinja2? Thanks. [/INST] There are two ways to do it. The direct approach would be to simply call (and print) the strftime() method in your template, for example {{ car.date_of_manufacture.strftime('%Y-%m-%d') }} Another, sightly better approach would be to define your own filter, e.g.: def format_datetime(value, format='medium'): if format == 'full': format="EEEE, d. MMMM y 'at' HH:mm" elif format == 'medium': format="EE dd.MM.y HH:mm" return babel.dates.format_datetime(value, format) jinja_env.filters['datetime'] = format_datetime (This filter is based on babel for reasons regarding i18n, but you can use strftime too). The advantage of the filter is, that you can write {{ car.date_of_manufacture|datetime }} which looks nicer and is more maintainable. Another common filter is also the "timedelta" filter, which evaluates to something like "written 8 minutes ago". You can use babel.dates.format_timedelta for that, and register it as filter similar to the datetime example given here. </s>
<s>[INST] How do you use the ellipsis slicing syntax in Python? This came up in Hidden features of Python, but I can't see good documentation or examples that explain how the feature works. [/INST] The ellipsis is used to slice higher-dimensional data structures. It's designed to mean at this point, insert as many full slices (:) to extend the multi-dimensional slice to all dimensions. Example: >>> from numpy import arange >>> a = arange(16).reshape(2,2,2,2) Now, you have a 4-dimensional matrix of order 2x2x2x2. To select all first elements in the 4th dimension, you can use the ellipsis notation >>> a[..., 0].flatten() array([ 0, 2, 4, 6, 8, 10, 12, 14]) which is equivalent to >>> a[:,:,:,0].flatten() array([ 0, 2, 4, 6, 8, 10, 12, 14]) In your own implementations, you're free to ignore the contract mentioned above and use it for whatever you see fit. </s>
<s>[INST] Explaining Python's '__enter__' and '__exit__' this is i saw in someone's code: def __enter__(self): return self def __exit__(self, type, value, tb): self.stream.close() from __future__ import with_statement#for python2.5 class a(object): def __enter__(self): print 'sss' return 'sss111' def __exit__(self ,type, value, traceback): print 'ok' return False with a() as s: print s print s [/INST] Using these magic methods (__enter__, __exit__) allows you to implement objects which can be used easily with the with statement. The idea is that it makes it easy to build code which needs some 'cleandown' code executed (think of it as a try-finally block). Some more explanation here. A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope): class DatabaseConnection(object): def __enter__(self): # make a database connection and return it ... return self.dbconn def __exit__(self, exc_type, exc_val, exc_tb): # make sure the dbconnection gets closed self.dbconn.close() ... As explained above, use this object with the with statement (you may need to do from __future__ import with_statement at the top of the file if you're on Python 2.5). with DatabaseConnection() as mydbconn: # do stuff PEP343 -- The 'with' statement' has a nice writeup as well. </s>
<s>[INST] Difference between map, applymap and apply methods in Pandas Can you tell me when to use these vectorization methods with basic examples? I see that map is a Series method whereas the rest are DataFrame methods. I got confused about apply and applymap methods though. Why do we have two methods for applying a function to a DataFrame? Again, simple examples which illustrate the usage would be great! Thanks! [/INST] Straight from Wes McKinney's Python for Data Analysis book, pg. 132 (I highly recommended this book): Another frequent operation is applying a function on 1D arrays to each column or row. DataFrame’s apply method does exactly this: In [116]: frame = DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['Utah', 'Ohio', 'Texas', 'Oregon']) In [117]: frame Out[117]: b d e Utah -0.029638 1.081563 1.280300 Ohio 0.647747 0.831136 -1.549481 Texas 0.513416 -0.884417 0.195343 Oregon -0.485454 -0.477388 -0.309548 In [118]: f = lambda x: x.max() - x.min() In [119]: frame.apply(f) Out[119]: b 1.133201 d 1.965980 e 2.829781 dtype: float64 Many of the most common array statistics (like sum and mean) are DataFrame methods, so using apply is not necessary. Element-wise Python functions can be used, too. Suppose you wanted to compute a formatted string from each floating point value in frame. You can do this with applymap: In [120]: format = lambda x: '%.2f' % x In [121]: frame.applymap(format) Out[121]: b d e Utah -0.03 1.08 1.28 Ohio 0.65 0.83 -1.55 Texas 0.51 -0.88 0.20 Oregon -0.49 -0.48 -0.31 The reason for the name applymap is that Series has a map method for applying an element-wise function: In [122]: frame['e'].map(format) Out[122]: Utah 1.28 Ohio -1.55 Texas 0.20 Oregon -0.31 Name: e, dtype: object Summing up, apply works on a row / column basis of a DataFrame, applymap works element-wise on a DataFrame, and map works element-wise on a Series. </s>
<s>[INST] What is __main__.py? What is the __main__.py file for, what sort of code should I put into it, and when should I have one? [/INST] Often, a Python program is run by naming a .py file on the command line: $ python my_program.py You can also create a directory or zipfile full of code, and include a __main__.py. Then you can simply name the directory or zipfile on the command line, and it executes the __main__.py automatically: $ python my_program_dir $ python my_program.zip # Or, if the program is accessible as a module $ python -m my_program You'll have to decide for yourself whether your application could benefit from being executed like this. </s>
<s>[INST] Use cases for the 'setdefault' dict method The addition of collections.defaultdict in Python 2.5 greatly reduced the need for dict's setdefault method. This question is for our collective education: What is setdefault still useful for, today in Python 2.6/2.7? What popular use cases of setdefault were superseded with collections.defaultdict? [/INST] You could say defaultdict is useful for settings defaults before filling the dict and setdefault is useful for setting defaults while or after filling the dict. Probably the most common use case: Grouping items (in unsorted data, else use itertools.groupby) # really verbose new = {} for (key, value) in data: if key in new: new[key].append( value ) else: new[key] = [value] # easy with setdefault new = {} for (key, value) in data: group = new.setdefault(key, []) # key might exist already group.append( value ) # even simpler with defaultdict new = defaultdict(list) for (key, value) in data: new[key].append( value ) # all keys have a default already Sometimes you want to make sure that specific keys exist after creating a dict. defaultdict doesn't work in this case, because it only creates keys on explicit access. Think you use something HTTP-ish with many headers -- some are optional, but you want defaults for them: headers = parse_headers( msg ) # parse the message, get a dict # now add all the optional headers for headername, defaultvalue in optional_headers: headers.setdefault( headername, defaultvalue ) </s>
<s>[INST] Multiprocessing: How to use Pool.map on a function defined in a class? When I run something like: from multiprocessing import Pool p = Pool(5) def f(x): return x*x p.map(f, [1,2,3]) it works fine. However, putting this as a function of a class: class calculate(object): def run(self): def f(x): return x*x p = Pool() return p.map(f, [1,2,3]) cl = calculate() print cl.run() Gives me the following error: Exception in thread Thread-1: Traceback (most recent call last): File "/sw/lib/python2.6/threading.py", line 532, in __bootstrap_inner self.run() File "/sw/lib/python2.6/threading.py", line 484, in run self.__target(*self.__args, **self.__kwargs) File "/sw/lib/python2.6/multiprocessing/pool.py", line 225, in _handle_tasks put(task) PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed I've seen a post from Alex Martelli dealing with the same kind of problem, but it wasn't explicit enough. [/INST] I could not use the codes posted so far for three reasons. The codes using "multiprocessing.Pool" do not work with lambda expressions. The codes not using "multiprocessing.Pool" spawn as many processes as there are work items. All codes iterate through the whole input list before doing the actual work. 2.) is a performance concern, 3.) prohibits the use of a progress bar like http://code.google.com/p/python-progressbar/ I adapted the code s.t. it spawns a predefined amount of workers and only iterates through the input list if there exists an idle worker. I also enabled the "daemon" mode for the workers s.t. strg-c works as expected. import multiprocessing def fun(f, q_in, q_out): while True: i, x = q_in.get() if i is None: break q_out.put((i, f(x))) def parmap(f, X, nprocs=multiprocessing.cpu_count()): q_in = multiprocessing.Queue(1) q_out = multiprocessing.Queue() proc = [multiprocessing.Process(target=fun, args=(f, q_in, q_out)) for _ in range(nprocs)] for p in proc: p.daemon = True p.start() sent = [q_in.put((i, x)) for i, x in enumerate(X)] [q_in.put((None, None)) for _ in range(nprocs)] res = [q_out.get() for _ in range(len(sent))] [p.join() for p in proc] return [x for i, x in sorted(res)] if __name__ == '__main__': print(parmap(lambda i: i * 2, [1, 2, 3, 4, 6, 7, 8])) </s>
<s>[INST] Best way to format integer as string with leading zeros? I need to add leading zeros to integer to make a string with defined quantity of digits ($cnt). What the best way to translate this simple function from PHP to Python: function add_nulls($int, $cnt=2) { $int = intval($int); for($i=0; $i<($cnt-strlen($int)); $i++) $nulls .= '0'; return $nulls.$int; } Is there a function that can do this? [/INST] You can use the zfill() method to pad a string with zeros: In [3]: str(1).zfill(2) Out[3]: '01' </s>
<s>[INST] Write to UTF-8 file in Python I'm really confused with the codecs.open function. When I do: file = codecs.open("temp", "w", "utf-8") file.write(codecs.BOM_UTF8) file.close() It gives me the error UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128) If I do: file = open("temp", "w") file.write(codecs.BOM_UTF8) file.close() It works fine. Question is why does the first method fail? And how do I insert the bom? If the second method is the correct way of doing it, what the point of using codecs.open(filename, "w", "utf-8")? [/INST] Disclaimer: I'm not a Python programmer. I believe the problem is that codecs.BOM_UTF8 is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!" Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8: import codecs file = codecs.open("lol", "w", "utf-8") file.write(u'\ufeff') file.close() (That seems to give the right answer - a file with bytes EF BB BF.) EDIT: S. Lott's suggestion of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before. </s>
<s>[INST] Is it possible only to declare a variable without assigning any value in Python? Is it possible to declare a variable in Python, like so?: var so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why? EDIT: I want to do this for cases like this: value for index in sequence: if value == None and conditionMet: value = index break Duplicate Uninitialised value in python (by same author) Are there any declaration keywords in Python? (by the same author) Related Python: variable scope and function calls Other languages have "variables" [/INST] Why not just do this: var = None Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above. This is nice, because you'll never end up with an uninitialized variable. But be careful -- this doesn't mean that you won't end up with incorrectly initialized variables. If you init something to None, make sure that's what you really want, and assign something more meaningful if you can. </s>
<s>[INST] Python Requests throwing up SSLError I'm working on a simple script that involves CAS, jspring security check, redirection, etc. I would like to use Kenneth Reitz's python requests because it's a great piece of work! However, CAS requires getting validated via SSL so I have to get past that step first. I don't know what Python requests is wanting? Where is this SSL certificate suppose to reside? Traceback (most recent call last): File "./test.py", line 24, in <module> response = requests.get(url1, headers=headers) File "build/bdist.linux-x86_64/egg/requests/api.py", line 52, in get File "build/bdist.linux-x86_64/egg/requests/api.py", line 40, in request File "build/bdist.linux-x86_64/egg/requests/sessions.py", line 209, in request File "build/bdist.linux-x86_64/egg/requests/models.py", line 624, in send File "build/bdist.linux-x86_64/egg/requests/models.py", line 300, in _build_response File "build/bdist.linux-x86_64/egg/requests/models.py", line 611, in send requests.exceptions.SSLError: [Errno 1] _ssl.c:503: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed [/INST] The problem you are having is caused by an untrusted SSL certificate. Like @dirk mentioned in a previous comment, the quickest fix is setting verify=False. Please note that this will cause the certificate not to be verified. This will expose your application to security risks, such as man-in-the-middle attacks. Of course, apply judgment. As mentioned in the comments, this may be acceptable for quick/throwaway applications/scripts, but really should not go to production software. If just skipping the certificate check is not acceptable in your particular context, consider the following options, your best option is to set the verify parameter to a string that is the path of the .pem file of the certificate (which you should obtain by some sort of secure means). So, as of version 2.0, the verify parameter accepts the following values, with their respective semantics: True: causes the certificate to validated against the library's own trusted certificate authorities (Note: you can see which Root Certificates Requests uses via the Certifi library, a trust database of RCs extracted from Requests: Certifi - Trust Database for Humans). False: bypasses certificate validation completely. Path to a CA_BUNDLE file for Requests to use to validate the certificates. Source: Requests - SSL Cert Verification Also take a look at the cert parameter on the same link. </s>
<s>[INST] Lexical closures in Python While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) Note that this example mindfully avoids lambda. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } "0 2 4" is printed. Can you please explain the difference ? Update: The problem is not with i being global. This displays the same behavior: flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) As the commented line shows, i is unknown at that point. Still, it prints "4 4 4". [/INST] The functions defined in the loop keep accessing the same variable i while its value changes. At the end of the loop, all the functions point to the same variable, which is holding the last value in the loop: the effect is what reported in the example. In order to evaluate i and use its value, a common pattern is to set it as a parameter default: parameter defaults are evaluated when the def statement is executed, and thus the value of the loop variable is frozen. The following works as expected: flist = [] for i in xrange(3): def func(x, i=i): # the *value* of i is copied in func() environment return x * i flist.append(func) for f in flist: print f(2) </s>
<s>[INST] How To Use The Pass Statement In Python I am in the process of learning Python and I have reached the section about the pass statement. The guide I'm using defines it as being a Null statement that is commonly used as a placeholder. I still don't fully understand what that means though. Can someone show me a simple/basic situation where the pass statement would be used and why it is needed? [/INST] Suppose you are designing a new class with some methods that you don't want to implement, yet. class MyClass(object): def meth_a(self): pass def meth_b(self): print "I'm meth_b" If you would leave out the pass, the code wouldn't run. You would then get an IndentationError: expected an indented block To summarize, the pass statement does nothing particular but can act as a placeholder, as shown before. </s>
<s>[INST] How to state in requirements.txt a direct github source I've installed a library using the command pip install git+git://github.com/mozilla/elasticutils.git which installs it directly from a Github repository. This works fine and I want to have that dependency in my requirements.txt. I've looked at other tickets like this but that didn't solve my problem. If I put something like -f git+git://github.com/mozilla/elasticutils.git elasticutils==0.7.dev in the requirements.txt file, a pip install -r requirements.txt results in the following output: Downloading/unpacking elasticutils==0.7.dev (from -r requirements.txt (line 20)) Could not find a version that satisfies the requirement elasticutils==0.7.dev (from -r requirements.txt (line 20)) (from versions: ) No distributions matching the version for elasticutils==0.7.dev (from -r requirements.txt (line 20)) The documentation of the requirements file does not mention links using the git+git protocol specifier, so maybe this is just not supported. Does anybody have a solution for my problem? [/INST] “Editable” packages syntax can be used in requirements.txt to import packages from a variety of VCS (git, hg, bzr, svn): -e git://github.com/mozilla/elasticutils.git#egg=elasticutils Also, it is possible to point to particular commit: -e git://github.com/mozilla/elasticutils.git@000b14389171a9f0d7d713466b32bc649b0bed8e#egg=elasticutils </s>
<s>[INST] Bubble Sort Homework In class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them. This is my attempt in Python: mylist = [12, 5, 13, 8, 9, 65] def bubble(badList): length = len(badList) - 1 unsorted = True while unsorted: for element in range(0,length): unsorted = False if badList[element] > badList[element + 1]: hold = badList[element + 1] badList[element + 1] = badList[element] badList[element] = hold print badList else: unsorted = True print bubble(mylist) Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely. How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size? P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet. [/INST] To explain why your script isn't working right now, I'll rename the variable unsorted to sorted. At first, your list isn't yet sorted. Of course, we set sorted to False. As soon as we start the while loop, we assume that the list is already sorted. The idea is this: as soon as we find two elements that are not in the right order, we set sorted back to False. sorted will remain True only if there were no elements in the wrong order. sorted = False # We haven't started sorting yet while not sorted: sorted = True # Assume the list is now sorted for element in range(0, length): if badList[element] > badList[element + 1]: sorted = False # We found two elements in the wrong order hold = badList[element + 1] badList[element + 1] = badList[element] badList[element] = hold # We went through the whole list. At this point, if there were no elements # in the wrong order, sorted is still True. Otherwise, it's false, and the # while loop executes again. There are also minor little issues that would help the code be more efficient or readable. In the for loop, you use the variable element. Technically, element is not an element; it's a number representing a list index. Also, it's quite long. In these cases, just use a temporary variable name, like i for "index". for i in range(0, length): The range command can also take just one argument (named stop). In that case, you get a list of all the integers from 0 to that argument. for i in range(length): The Python Style Guide recommends that variables be named in lowercase with underscores. This is a very minor nitpick for a little script like this; it's more to get you accustomed to what Python code most often resembles. def bubble(bad_list): To swap the values of two variables, write them as a tuple assignment. The right hand side gets evaluated as a tuple (say, (badList[i+1], badList[i]) is (3, 5)) and then gets assigned to the two variables on the left hand side ((badList[i], badList[i+1])). bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i] Put it all together, and you get this: my_list = [12, 5, 13, 8, 9, 65] def bubble(bad_list): length = len(bad_list) - 1 sorted = False while not sorted: sorted = True for i in range(length): if bad_list[i] > bad_list[i+1]: sorted = False bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i] bubble(my_list) print my_list (I removed your print statement too, by the way.) </s>
<s>[INST] Does Python have a built in function for string natural sort? Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort. Natural sort: The order by which files in Windows are sorted. For instance, the following list is naturally sorted (what I want): ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13'] And here's the "sorted" version of the above list (what I have): ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9'] I'm looking for a sort function which behaves like the first one. [/INST] Try this: import re def natural_sort(l): convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] return sorted(l, key = alphanum_key) Output: ['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13'] See it working online: ideone. Code adapted from here: Sorting for Humans : Natural Sort Order. </s>
<s>[INST] Django Passing Custom Form Parameters to Formset This was fixed in Django 1.9 with form_kwargs. I have a Django Form that looks like this: class ServiceForm(forms.Form): option = forms.ModelChoiceField(queryset=ServiceOption.objects.none()) rate = forms.DecimalField(widget=custom_widgets.SmallField()) units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField()) def __init__(self, *args, **kwargs): affiliate = kwargs.pop('affiliate') super(ServiceForm, self).__init__(*args, **kwargs) self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate) I call this form with something like this: form = ServiceForm(affiliate=request.affiliate) Where request.affiliate is the logged in user. This works as intended. My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this: ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3) And then I need to create it like this: formset = ServiceFormSet() Now how can I pass affiliate=request.affiliate to the individual forms this way? [/INST] I would use functools.partial and functools.wraps: from functools import partial, wraps from django.forms.formsets import formset_factory ServiceFormSet = formset_factory(wraps(ServiceForm)(partial(ServiceForm, affiliate=request.affiliate)), extra=3) I think this is the cleanest approach, and doesn't affect ServiceForm in any way (i.e. by making it difficult to subclass). </s>
<s>[INST] Why does Python print unicode characters when the default encoding is ASCII? From the Python 2.6 shell: >>> import sys >>> print sys.getdefaultencoding() ascii >>> print u'\xe9' é >>> I expected to have either some gibberish or an Error after the print statement, since the "é" character isn't part of ASCII and I haven't specified an encoding. I guess I don't understand what ASCII being the default encoding means. EDIT I moved the edit to the Answers section and accepted it as suggested. [/INST] Thanks to bits and pieces from various replies, I think we can stitch up an explanation. By trying to print an unicode string, u'\xe9', Python implicitly try to encode that string using the encoding scheme currently stored in sys.stdout.encoding. Python actually picks up this setting from the environment it's been initiated from. If it can't find a proper encoding from the environment, only then does it revert to its default, ASCII. For example, I use a bash shell which encoding defaults to UTF-8. If I start Python from it, it picks up and use that setting: $ python >>> import sys >>> print sys.stdout.encoding UTF-8 Let's for a moment exit the Python shell and set bash's environment with some bogus encoding: $ export LC_CTYPE=klingon # we should get some error message here, just ignore it. Then start the python shell again and verify that it does indeed revert to its default ascii encoding. $ python >>> import sys >>> print sys.stdout.encoding ANSI_X3.4-1968 Bingo! If you now try to output some unicode character outside of ascii you should get a nice error message >>> print u'\xe9' UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128) Lets exit Python and discard the bash shell. We'll now observe what happens after Python outputs strings. For this we'll first start a bash shell within a graphic terminal (I use Gnome Terminal) and we'll set the terminal to decode output with ISO-8859-1 aka latin-1 (graphic terminals usually have an option to Set Character Encoding in one of their dropdown menus). Note that this doesn't change the actual shell environment's encoding, it only changes the way the terminal itself will decode output it's given, a bit like a web browser does. You can therefore change the terminal's encoding, independantly from the shell's environment. Let's then start Python from the shell and verify that sys.stdout.encoding is set to the shell environment's encoding (UTF-8 for me): $ python >>> import sys >>> print sys.stdout.encoding UTF-8 >>> print '\xe9' # (1) é >>> print u'\xe9' # (2) é >>> print u'\xe9'.encode('latin-1') # (3) é >>> (1) python outputs binary string as is, terminal receives it and tries to match its value with latin-1 character map. In latin-1, 0xe9 or 233 yields the character "é" and so that's what the terminal displays. (2) python attempts to implicitly encode the Unicode string with whatever scheme is currently set in sys.stdout.encoding, in this instance it's "UTF-8". After UTF-8 encoding, the resulting binary string is '\xc3\xa9' (see later explanation). Terminal receives the stream as such and tries to decode 0xc3a9 using latin-1, but latin-1 goes from 0 to 255 and so, only decodes streams 1 byte at a time. 0xc3a9 is 2 bytes long, latin-1 decoder therefore interprets it as 0xc3 (195) and 0xa9 (169) and that yields 2 characters: à and ©. (3) python encodes unicode code point u'\xe9' (233) with the latin-1 scheme. Turns out latin-1 code points range is 0-255 and points to the exact same character as Unicode within that range. Therefore, Unicode code points in that range will yield the same value when encoded in latin-1. So u'\xe9' (233) encoded in latin-1 will also yields the binary string '\xe9'. Terminal receives that value and tries to match it on the latin-1 character map. Just like case (1), it yields "é" and that's what's displayed. Let's now change the terminal's encoding settings to UTF-8 from the dropdown menu (like you would change your web browser's encoding settings). No need to stop Python or restart the shell. The terminal's encoding now matches Python's. Let's try printing again: >>> print '\xe9' # (4) >>> print u'\xe9' # (5) é >>> print u'\xe9'.encode('latin-1') # (6) >>> (4) python outputs a binary string as is. Terminal attempts to decode that stream with UTF-8. But UTF-8 doesn't understand the value 0xe9 (see later explanation) and is therefore unable to convert it to a unicode code point. No code point found, no character printed. (5) python attempts to implicitly encode the Unicode string with whatever's in sys.stdout.encoding. Still "UTF-8". The resulting binary string is '\xc3\xa9'. Terminal receives the stream and attempts to decode 0xc3a9 also using UTF-8. It yields back code value 0xe9 (233), which on the Unicode character map points to the symbol "é". Terminal displays "é". (6) python encodes unicode string with latin-1, it yields a binary string with the same value '\xe9'. Again, for the terminal this is pretty much the same as case (4). Conclusions: - Python outputs non-unicode strings as raw data, without considering its default encoding. The terminal just happens to display them if its current encoding matches the data. - Python outputs Unicode strings after encoding them using the scheme specified in sys.stdout.encoding. - Python gets that setting from the shell's environment. - the terminal displays output according to its own encoding settings. - the terminal's encoding is independant from the shell's. More details on unicode, UTF-8 and latin-1: Unicode is basically a table of characters where some keys (code points) have been conventionally assigned to point to some symbols. e.g. by convention it's been decided that key 0xe9 (233) is the value pointing to the symbol 'é'. ASCII and Unicode use the same code points from 0 to 127, as do latin-1 and Unicode from 0 to 255. That is, 0x41 points to 'A' in ASCII, latin-1 and Unicode, 0xc8 points to 'Ü' in latin-1 and Unicode, 0xe9 points to 'é' in latin-1 and Unicode. When working with electronic devices, Unicode code points need an efficient way to be represented electronically. That's what encoding schemes are about. Various Unicode encoding schemes exist (utf7, UTF-8, UTF-16, UTF-32). The most intuitive and straight forward encoding approach would be to simply use a code point's value in the Unicode map as its value for its electronic form, but Unicode currently has over a million code points, which means that some of them require 3 bytes to be expressed. To work efficiently with text, a 1 to 1 mapping would be rather impractical, since it would require that all code points be stored in exactly the same amount of space, with a minimum of 3 bytes per character, regardless of their actual need. Most encoding schemes have shortcomings regarding space requirement, the most economic ones don't cover all unicode code points, for example ascii only covers the first 128, while latin-1 covers the first 256. Others that try to be more comprehensive end up also being wasteful, since they require more bytes than necessary, even for common "cheap" characters. UTF-16 for instance, uses a minimum of 2 bytes per character, including those in the ascii range ('B' which is 65, still requires 2 bytes of storage in UTF-16). UTF-32 is even more wasteful as it stores all characters in 4 bytes. UTF-8 happens to have cleverly resolved the dilemma, with a scheme able to store code points with a variable amount of byte spaces. As part of its encoding strategy, UTF-8 laces code points with flag bits that indicate (presumably to decoders) their space requirements and their boundaries. UTF-8 encoding of unicode code points in the ascii range (0-127): 0xxx xxxx (in binary) the x's show the actual space reserved to "store" the code point during encoding The leading 0 is a flag that indicates to the UTF-8 decoder that this code point will only require 1 byte. upon encoding, UTF-8 doesn't change the value of code points in that specific range (i.e. 65 encoded in UTF-8 is also 65). Considering that Unicode and ASCII are also compatible in the same range, it incidentally makes UTF-8 and ASCII also compatible in that range. e.g. Unicode code point for 'B' is '0x42' or 0100 0010 in binary (as we said, it's the same in ASCII). After encoding in UTF-8 it becomes: 0xxx xxxx <-- UTF-8 encoding for Unicode code points 0 to 127 *100 0010 <-- Unicode code point 0x42 0100 0010 <-- UTF-8 encoded (exactly the same) UTF-8 encoding of Unicode code points above 127 (non-ascii): 110x xxxx 10xx xxxx <-- (from 128 to 2047) 1110 xxxx 10xx xxxx 10xx xxxx <-- (from 2048 to 65535) the leading bits '110' indicate to the UTF-8 decoder the beginning of a code point encoded in 2 bytes, whereas '1110' indicates 3 bytes, 11110 would indicate 4 bytes and so forth. the inner '10' flag bits are used to signal the beginning of an inner byte. again, the x's mark the space where the Unicode code point value is stored after encoding. e.g. 'é' Unicode code point is 0xe9 (233). 1110 1001 <-- 0xe9 When UTF-8 encodes this value, it determines that the value is larger than 127 and less than 2048, therefore should be encoded in 2 bytes: 110x xxxx 10xx xxxx <-- UTF-8 encoding for Unicode 128-2047 ***0 0011 **10 1001 <-- 0xe9 1100 0011 1010 1001 <-- 'é' after UTF-8 encoding C 3 A 9 The 0xe9 Unicode code points after UTF-8 encoding becomes 0xc3a9. Which is exactly how the terminal receives it. If your terminal is set to decode strings using latin-1 (one of the non-unicode legacy encodings), you'll see é, because it just so happens that 0xc3 in latin-1 points to à and 0xa9 to ©. </s>
<s>[INST] Image library for Python 3 What is python-3 using instead of PIL for manipulating Images? [/INST] The "friendly PIL fork" Pillow works on Python 2 and 3. Check out the Github project for support matrix and so on. </s>
<s>[INST] Ignore python multiple return value Say I have a Python function that returns multiple values in a tuple: def func(): return 1, 2 Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this: x, temp = func() [/INST] You can use x = func()[0] to return the first value, x = func()[1] to return the second, and so on. If you want to get multiple values at a time, use something like x, y = func()[2:4]. </s>
<s>[INST] Python datetime to string without microsecond component I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is 2011-11-03 11:07:04 (followed by +00:00, but that's not germane). What's the best way to create such a string (without a microsecond component) from a datetime instance with a microsecond component? >>> import datetime >>> print unicode(datetime.datetime.now()) 2011-11-03 11:13:39.278026 I'll add the best option that's occurred to me as a possible answer, but there may well be a more elegant solution. Edit: I should mention that I'm not actually printing the current time – I used datetime.now to provide a quick example. So the solution should not assume that any datetime instances it receives will include microsecond components. [/INST] >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") '2011-11-03 18:21:26' </s>
<s>[INST] Named colors in matplotlib What named colors are available in matplotlib for use in plots? I can find a list on the matplotlib documentation that claims that these are the only names: b: blue g: green r: red c: cyan m: magenta y: yellow k: black w: white However, I've found that these colors can also be used, at least in this context: scatter(X,Y, color='red') scatter(X,Y, color='orange') scatter(X,Y, color='darkgreen') but these are not on the above list. Does anyone know an exhaustive list of the named colors that are available? [/INST] There is a complete dictionary in colors.py in the matplotlib directory. import matplotlib for name, hex in matplotlib.colors.cnames.iteritems(): print(name, hex) This is the complete dictionary: cnames = { 'aliceblue': '#F0F8FF', 'antiquewhite': '#FAEBD7', 'aqua': '#00FFFF', 'aquamarine': '#7FFFD4', 'azure': '#F0FFFF', 'beige': '#F5F5DC', 'bisque': '#FFE4C4', 'black': '#000000', 'blanchedalmond': '#FFEBCD', 'blue': '#0000FF', 'blueviolet': '#8A2BE2', 'brown': '#A52A2A', 'burlywood': '#DEB887', 'cadetblue': '#5F9EA0', 'chartreuse': '#7FFF00', 'chocolate': '#D2691E', 'coral': '#FF7F50', 'cornflowerblue': '#6495ED', 'cornsilk': '#FFF8DC', 'crimson': '#DC143C', 'cyan': '#00FFFF', 'darkblue': '#00008B', 'darkcyan': '#008B8B', 'darkgoldenrod': '#B8860B', 'darkgray': '#A9A9A9', 'darkgreen': '#006400', 'darkkhaki': '#BDB76B', 'darkmagenta': '#8B008B', 'darkolivegreen': '#556B2F', 'darkorange': '#FF8C00', 'darkorchid': '#9932CC', 'darkred': '#8B0000', 'darksalmon': '#E9967A', 'darkseagreen': '#8FBC8F', 'darkslateblue': '#483D8B', 'darkslategray': '#2F4F4F', 'darkturquoise': '#00CED1', 'darkviolet': '#9400D3', 'deeppink': '#FF1493', 'deepskyblue': '#00BFFF', 'dimgray': '#696969', 'dodgerblue': '#1E90FF', 'firebrick': '#B22222', 'floralwhite': '#FFFAF0', 'forestgreen': '#228B22', 'fuchsia': '#FF00FF', 'gainsboro': '#DCDCDC', 'ghostwhite': '#F8F8FF', 'gold': '#FFD700', 'goldenrod': '#DAA520', 'gray': '#808080', 'green': '#008000', 'greenyellow': '#ADFF2F', 'honeydew': '#F0FFF0', 'hotpink': '#FF69B4', 'indianred': '#CD5C5C', 'indigo': '#4B0082', 'ivory': '#FFFFF0', 'khaki': '#F0E68C', 'lavender': '#E6E6FA', 'lavenderblush': '#FFF0F5', 'lawngreen': '#7CFC00', 'lemonchiffon': '#FFFACD', 'lightblue': '#ADD8E6', 'lightcoral': '#F08080', 'lightcyan': '#E0FFFF', 'lightgoldenrodyellow': '#FAFAD2', 'lightgreen': '#90EE90', 'lightgray': '#D3D3D3', 'lightpink': '#FFB6C1', 'lightsalmon': '#FFA07A', 'lightseagreen': '#20B2AA', 'lightskyblue': '#87CEFA', 'lightslategray': '#778899', 'lightsteelblue': '#B0C4DE', 'lightyellow': '#FFFFE0', 'lime': '#00FF00', 'limegreen': '#32CD32', 'linen': '#FAF0E6', 'magenta': '#FF00FF', 'maroon': '#800000', 'mediumaquamarine': '#66CDAA', 'mediumblue': '#0000CD', 'mediumorchid': '#BA55D3', 'mediumpurple': '#9370DB', 'mediumseagreen': '#3CB371', 'mediumslateblue': '#7B68EE', 'mediumspringgreen': '#00FA9A', 'mediumturquoise': '#48D1CC', 'mediumvioletred': '#C71585', 'midnightblue': '#191970', 'mintcream': '#F5FFFA', 'mistyrose': '#FFE4E1', 'moccasin': '#FFE4B5', 'navajowhite': '#FFDEAD', 'navy': '#000080', 'oldlace': '#FDF5E6', 'olive': '#808000', 'olivedrab': '#6B8E23', 'orange': '#FFA500', 'orangered': '#FF4500', 'orchid': '#DA70D6', 'palegoldenrod': '#EEE8AA', 'palegreen': '#98FB98', 'paleturquoise': '#AFEEEE', 'palevioletred': '#DB7093', 'papayawhip': '#FFEFD5', 'peachpuff': '#FFDAB9', 'peru': '#CD853F', 'pink': '#FFC0CB', 'plum': '#DDA0DD', 'powderblue': '#B0E0E6', 'purple': '#800080', 'red': '#FF0000', 'rosybrown': '#BC8F8F', 'royalblue': '#4169E1', 'saddlebrown': '#8B4513', 'salmon': '#FA8072', 'sandybrown': '#FAA460', 'seagreen': '#2E8B57', 'seashell': '#FFF5EE', 'sienna': '#A0522D', 'silver': '#C0C0C0', 'skyblue': '#87CEEB', 'slateblue': '#6A5ACD', 'slategray': '#708090', 'snow': '#FFFAFA', 'springgreen': '#00FF7F', 'steelblue': '#4682B4', 'tan': '#D2B48C', 'teal': '#008080', 'thistle': '#D8BFD8', 'tomato': '#FF6347', 'turquoise': '#40E0D0', 'violet': '#EE82EE', 'wheat': '#F5DEB3', 'white': '#FFFFFF', 'whitesmoke': '#F5F5F5', 'yellow': '#FFFF00', 'yellowgreen': '#9ACD32'} You could plot them like this: import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.colors as colors import math fig = plt.figure() ax = fig.add_subplot(111) ratio = 1.0 / 3.0 count = math.ceil(math.sqrt(len(colors.cnames))) x_count = count * ratio y_count = count / ratio x = 0 y = 0 w = 1 / x_count h = 1 / y_count for c in colors.cnames: pos = (x / x_count, y / y_count) ax.add_patch(patches.Rectangle(pos, w, h, color=c)) ax.annotate(c, xy=pos) if y >= y_count-1: x += 1 y = 0 else: y += 1 plt.show() </s>
<s>[INST] How to format a floating number to fixed width in Python How do I format a floating number to a fixed width with the following requirements: Leading zero if n < 1 Add trailing decimal zero(s) to fill up fixed width Truncate decimal digits past fixed width Align all decimal points For example: % formatter something like '{:06}' numbers = [23.23, 0.123334987, 1, 4.223, 9887.2] for number in numbers: print formatter.format(number) The output would be like 23.2300 0.1233 1.0000 4.2230 9887.2000 [/INST] for x in numbers: print "{:10.4f}".format(x) prints 23.2300 0.1233 1.0000 4.2230 9887.2000 </s>
<s>[INST] Calculate difference in keys contained in two Python dictionaries Suppose I have two Python dictionaries - dictA and dictB. I need to find out if there are any keys which are present in dictB but not in dictA. What is the fastest way to go about it? Should I convert the dictionary keys into a set and then go about? Interested in knowing your thoughts... Thanks for your responses. Apologies for not stating my question properly. My scenario is like this - I have a dictA which can be the same as dictB or may have some keys missing as compared to dictB or else the value of some keys might be different which has to be set to that of dictA key's value. Problem is the dictionary has no standard and can have values which can be dict of dict. Say dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}} dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}....... So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict. The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict. [/INST] You can use set operations on the keys: diff = set(dictb.keys()) - set(dicta.keys()) Here is a class to find all the possibilities: what was added, what was removed, which key-value pairs are the same, and which key-value pairs are changed. class DictDiffer(object): """ Calculate the difference between two dictionaries as: (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values """ def __init__(self, current_dict, past_dict): self.current_dict, self.past_dict = current_dict, past_dict self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys()) self.intersect = self.set_current.intersection(self.set_past) def added(self): return self.set_current - self.intersect def removed(self): return self.set_past - self.intersect def changed(self): return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o]) def unchanged(self): return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o]) Here is some sample output: >>> a = {'a': 1, 'b': 1, 'c': 0} >>> b = {'a': 1, 'b': 2, 'd': 0} >>> d = DictDiffer(b, a) >>> print "Added:", d.added() Added: set(['d']) >>> print "Removed:", d.removed() Removed: set(['c']) >>> print "Changed:", d.changed() Changed: set(['b']) >>> print "Unchanged:", d.unchanged() Unchanged: set(['a']) Available as a github repo: https://github.com/hughdbrown/dictdiffer </s>
<s>[INST] Python function global variables? So I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (I am trying to call the global copy of a variable created in a separate function.) x = somevalue def func_A (): global x # do things to x return x def func_B(): x=func_A() # do things return x func_A() func_B() Does the x that the second function uses have the same value of the global copy of x that func_a uses and modifies? When calling the functions after definition, does order matter? [/INST] If you want to simply access a global variable you just use its name. However to change its value you need to use the global keyword. E.g. global someVar someVar = 55 This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable. The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does. </s>
<s>[INST] 'too many values to unpack', iterating over a dict. key=>string, value=>list I am getting the 'too many values to unpack' error. Any idea how I can fix this? first_names = ['foo', 'bar'] last_names = ['gravy', 'snowman'] fields = { 'first_names': first_names, 'last_name': last_names, } for field, possible_values in fields: # error happens on this line [/INST] You need to use something like iteritems. for field, possible_values in fields.iteritems(): print field, possible_values See this answer for more information on iterating through dictionaries, such as using items(), across python versions. </s>
<s>[INST] Converting NumPy array into Python List structure? How do I convert a NumPy array to a Python List (for example [[1,2,3],[4,5,6]] ), and do it reasonably fast? [/INST] Use tolist(): import numpy as np >>> np.array([[1,2,3],[4,5,6]]).tolist() [[1, 2, 3], [4, 5, 6]] </s>
<s>[INST] best way to extract subset of key-value pairs from python dictionary object I have a big dictionary object that has several key value pairs (about 16), I am only interested in 3 of them. What is the best way (shortest/efficient/elegant) to achieve that? The best I know is: bigdict = {'a':1,'b':2,....,'z':26} subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']} I am sure there is more elegant way than this. Ideas? [/INST] You could try: dict((k, bigdict[k]) for k in ('l', 'm', 'n')) ... or in Python 3 Python versions 2.7 or later (thanks to Fábio Diniz for pointing that out that it works in 2.7 too): {k: bigdict[k] for k in ('l', 'm', 'n')} Update: As Håvard S points out, I'm assuming that you know the keys are going to be in the dictionary - see his answer if you aren't able to make that assumption. Alternatively, as timbo points out in the comments, if you want a key that's missing in bigdict to map to None, you can do: {k: bigdict.get(k, None) for k in ('l', 'm', 'n')} If you're using Python 3, and you only want want keys in the new dict that actually exist in the original one, you can use the fact the view objects implement some set operations: {k: bigdict[k] for k in bigdict.keys() & {'l', 'm', 'n'}} </s>
<s>[INST] py2exe - generate single executable file I thought I heard that py2exe was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used? Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs. [/INST] The way to do this using py2exe is to use the bundle_files option in your setup.py file. For a single file you will want to set bundle_files to 1, compressed to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution. Here is a more complete description of the bundle_file option quoted directly from the py2exe site* Using "bundle_files" and "zipfile" An easier (and better) way to create single-file executables is to set bundle_files to 1 or 2, and to set zipfile to None. This approach does not require extracting files to a temporary location, which provides much faster program startup. Valid values for bundle_files are: 3 (default) don't bundle 2 bundle everything but the Python interpreter 1 bundle everything, including the Python interpreter If zipfile is set to None, the files will be bundle within the executable instead of library.zip. Here is a sample setup.py: from distutils.core import setup import py2exe, sys, os sys.argv.append('py2exe') setup( options = {'py2exe': {'bundle_files': 1, 'compressed': True}}, windows = [{'script': "single.py"}], zipfile = None, ) </s>
<s>[INST] Project structure for Google App Engine I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is BowlSK. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working. What I have: Main Level contains: all .py files (didn't know how to make packages work) all .html templates for main level pages Subdirectories: separate folders for css, images, js, etc. folders that hold .html templates for subdirecty-type urls Example: http://www.bowlsk.com/ maps to HomePage (default package), template at "index.html" http://www.bowlsk.com/games/view-series.html?series=7130 maps to ViewSeriesPage (again, default package), template at "games/view-series.html" It's nasty. How do I restructure? I had 2 ideas: Main Folder containing: appdef, indexes, main.py? Subfolder for code. Does this have to be my first package? Subfolder for templates. Folder heirarchy would match package heirarchy Individual subfolders for css, images, js, etc. Main Folder containing appdef, indexes, main.py? Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage" Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again. [/INST] First, I would suggest you have a look at "Rapid Development with Python, Django, and Google App Engine" GvR describes a general/standard project layout on page 10 of his slide presentation. Here I'll post a slightly modified version of the layout/structure from that page. I pretty much follow this pattern myself. You also mentioned you had trouble with packages. Just make sure each of your sub folders has an __init__.py file. It's ok if its empty. Boilerplate files These hardly vary between projects app.yaml: direct all non-static requests to main.py main.py: initialize app and send it all requests Project lay-out static/*: static files; served directly by App Engine myapp/*.py: app-specific python code views.py, models.py, tests.py, __init__.py, and more templates/*.html: templates (or myapp/templates/*.html) Here are some code examples that may help as well: main.py import wsgiref.handlers from google.appengine.ext import webapp from myapp.views import * application = webapp.WSGIApplication([ ('/', IndexHandler), ('/foo', FooHandler) ], debug=True) def main(): wsgiref.handlers.CGIHandler().run(application) myapp/views.py import os import datetime import logging import time from google.appengine.api import urlfetch from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from models import * class IndexHandler(webapp.RequestHandler): def get(self): date = "foo" # Do some processing template_values = {'data': data } path = os.path.join(os.path.dirname(__file__) + '/../templates/', 'main.html') self.response.out.write(template.render(path, template_values)) class FooHandler(webapp.RequestHandler): def get(self): #logging.debug("start of handler") myapp/models.py from google.appengine.ext import db class SampleModel(db.Model): I think this layout works great for new and relatively small to medium projects. For larger projects I would suggest breaking up the views and models to have their own sub-folders with something like: Project lay-out static/: static files; served directly by App Engine js/*.js images/*.gif|png|jpg css/*.css myapp/: app structure models/*.py views/*.py tests/*.py templates/*.html: templates </s>
<s>[INST] How can I filter a date of a DateTimeField in Django? I am trying to filter a DateTimeField comparing with a date. I mean: MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time". Is there an easy way in Django for doing this? I have the time in the datetime setted, it is not 00:00. [/INST] Such lookups are implemented in django.views.generic.date_based as follows: {'date_time_field__range': (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max))} Because it is quite verbose there are plans to improve the syntax using __date operator. Check "#9596 Comparing a DateTimeField to a date is too hard" for more details. </s>
<s>[INST] Why does the expression 0 < 0 == 0 return False in Python? Looking into Queue.py in Python 2.6, I found this construct that I found a bit strange: def full(self): """Return True if the queue is full, False otherwise (not reliable!).""" self.mutex.acquire() n = 0 < self.maxsize == self._qsize() self.mutex.release() return n If maxsize is 0 the queue is never full. My question is how does it work for this case? How 0 < 0 == 0 is considered False? >>> 0 < 0 == 0 False >>> (0) < (0 == 0) True >>> (0 < 0) == 0 True >>> 0 < (0 == 0) True [/INST] I believe Python has special case handling for sequences of relational operators to make range comparisons easy to express. It's much nicer to be able to say 0 < x <= 5 than to say (0 < x) and (x <= 5). These are called chained comparisons. And that's a link to the documentation for them. With the other cases you talk about, the parenthesis force one relational operator to be applied before the other, and so they are no longer chained comparisons. And since True and False have values as integers you get the answers you do out of the parenthesized versions. </s>
<s>[INST] How do I write good/correct package __init__.py files My package has the following structure: mobilescouter/ __init__.py #1 mapper/ __init__.py #2 lxml/ __init__.py #3 vehiclemapper.py vehiclefeaturemapper.py vehiclefeaturesetmapper.py ... basemapper.py vehicle/ __init__.py #4 vehicle.py vehiclefeature.py vehiclefeaturemapper.py ... I'm not sure how the __init__.py files should be correctly written. The __init__.py #1 looks like: __all__ = ['mapper', 'vehicle'] import mapper import vehicle But how should for example __init__.py #2 look like? Mine is: __all__ = ['basemapper', 'lxml'] from basemaper import * import lxml When should be __all__ used? [/INST] My own __init__.py files are empty more often than not. In particular, I never have a from blah import * as part of __init__.py -- if "importing the package" means getting all sort of classes, functions etc defined directly as part of the package, then I would lexically copy the contents of blah.py into the package's __init__.py instead and remove blah.py (the multiplication of source files does no good here). If you do insist on supporting the import * idioms (eek), then using __all__ (with as miniscule a list of names as you can bring yourself to have in it) may help for damage control. In general, namespaces and explicit imports are good things, and I strong suggest reconsidering any approach based on systematically bypassing either or both concepts!-) </s>
<s>[INST] How to get a variable name as a string in Python? I would like to be able to get the name of a variable as a string but I don't know if Python has that much introspection capabilities. Something like: >>> print(my_var.__name__) 'my_var' I want to do that because I have a bunch of vars I'd like to turn into a dictionary like : bar = True foo = False >>> my_dict = dict(bar=bar, foo=foo) >>> print my_dict {'foo': False, 'bar': True} But I'd like something more automatic than that. Python have locals() and vars(), so I guess there is a way. [/INST] As unwind said, this isn't really something you do in Python - variables are actually name mappings to objects. However, here's one way to try and do it: >>> a = 1 >>> for k, v in list(locals().iteritems()): if v is a: a_as_str = k >>> a_as_str a >>> type(a_as_str) 'str' </s>
<s>[INST] "Pretty" Continuous Integration for Python This is a slightly.. vain question, but BuildBot's output isn't particularly nice to look at.. For example, compared to.. phpUnderControl Jenkins Hudson CruiseControl.rb ..and others, BuildBot looks rather.. archaic I'm currently playing with Hudson, but it is very Java-centric (although with this guide, I found it easier to setup than BuildBot, and produced more info) Basically: is there any Continuous Integration systems aimed at python, that produce lots of shiny graphs and the likes? Update: Since this time the Jenkins project has replaced Hudson as the community version of the package. The original authors have moved to this project as well. Jenkins is now a standard package on Ubuntu/Debian, RedHat/Fedora/CentOS, and others. The following update is still essentially correct. The starting point to do this with Jenkins is different. Update: After trying a few alternatives, I think I'll stick with Hudson. Integrity was nice and simple, but quite limited. I think Buildbot is better suited to having numerous build-slaves, rather than everything running on a single machine like I was using it. Setting Hudson up for a Python project was pretty simple: Download Hudson from http://hudson-ci.org/ Run it with java -jar hudson.war Open the web interface on the default address of http://localhost:8080 Go to Manage Hudson, Plugins, click "Update" or similar Install the Git plugin (I had to set the git path in the Hudson global preferences) Create a new project, enter the repository, SCM polling intervals and so on Install nosetests via easy_install if it's not already In the a build step, add nosetests --with-xunit --verbose Check "Publish JUnit test result report" and set "Test report XMLs" to **/nosetests.xml That's all that's required. You can setup email notifications, and the plugins are worth a look. A few I'm currently using for Python projects: SLOCCount plugin to count lines of code (and graph it!) - you need to install sloccount separately Violations to parse the PyLint output (you can setup warning thresholds, graph the number of violations over each build) Cobertura can parse the coverage.py output. Nosetest can gather coverage while running your tests, using nosetests --with-coverage (this writes the output to **/coverage.xml) [/INST] You might want to check out Nose and the Xunit output plugin. You can have it run your unit tests, and coverage checks with this command: nosetests --with-xunit --enable-cover That'll be helpful if you want to go the Jenkins route, or if you want to use another CI server that has support for JUnit test reporting. Similarly you can capture the output of pylint using the violations plugin for Jenkins </s>
<s>[INST] Python syntax for "if a or b or c but not all of them" I have a python script that can receive either zero or three command line arguments. (Either it runs on default behavior or needs all three values specified.) What's the ideal syntax for something like: if a and (not b or not c) or b and (not a or not c) or c and (not b or not a): ? [/INST] How about: conditions = [a, b, c] if any(conditions) and not all(conditions): ... Other variant: if 1 <= sum(map(bool, conditions)) <= 2: ... </s>
<s>[INST] pip broke. how to fix DistributionNotFound error? Whenever i try to use pip I get an error. For exampple: $ sudo pip install gevent-websocket Traceback (most recent call last): File "/usr/local/bin/pip", line 5, in <module> from pkg_resources import load_entry_point File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2675, in <module> parse_requirements(__requires__), Environment() File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 552, in resolve raise DistributionNotFound(req) pkg_resources.DistributionNotFound: pip==0.8.1 I feel tempted to change the value of into pip==0.8.2.. but I dont feel dealing with the consequences of 'hacking' up my installation... I'm running python 2.7 and pip is at version 0.8.2. [/INST] I find this problem in my MacBook, the reason is because as @Stephan said, I use easy_install to install pip, and the mixture of both py package manage tools led to the pkg_resources.DistributionNotFound problem. The resolve is: easy_install --upgrade pip Remember: just use one of the above tools to manage your Py packages. </s>
<s>[INST] Concatenate item in list to strings Is there a simpler way to concatenate string items in list into a single string? Can I use the str.join() function to join items in list? E.g. this is the input ['this','is','a','sentence'] and this is the desired output this-is-a-sentence sentence = ['this','is','a','sentence'] sent_str = "" for i in sentence: sent_str += str(i) + "-" sent_str = sent_str[:-1] print sent_str [/INST] Use join: >>> sentence = ['this','is','a','sentence'] >>> '-'.join(sentence) 'this-is-a-sentence' </s>
<s>[INST] Executing Python script from Django shell I need to execute a Python script from the Django shell. I tried ./manage.py shell << my_script.py But it didn't work. It was just kinda waiting for me to write something. [/INST] The << part is wrong, use < instead: $ ./manage.py shell < myscript.py You could also do: $ ./manage.py shell ... >>> execfile('myscript.py') </s>
<s>[INST] bash: pip: command not found I downloaded pip and ran python setup.py install and everything worked just fine. The very next step in the tutorial is to run pip install <lib you want> but before it even tries to find anything online I get an error "bash: pip: command not found". This is on Mac OS X, which I'm new too, so I'm assuming there's some kind of path setting that was not set correctly when I ran setup.py. How can I investigate further? What do I need to check to get a better idea of the exact cause of the problem? EDIT: I also tried installing Python 2.7 for Mac in the hopes that the friendly install process would do any housekeeping like editing PATH and whatever else needs to happy for everything to work according to the tutorials, but this didn't work. After installing is running 'python' still ran Python 2.6 and PATH was not updated. [/INST] Why not just do sudo easy_install pip or if this is for python 2.6 sudo easy_install-2.6 pip? This installs pip using the default python package installer system and saves you the hassle of manual set-up all at the same time. This will allow you to then run the pip command for python package installation as it will be installed with the system python. I also recommend once you have pip using the virtualenv package and pattern. :) </s>
<s>[INST] Get all object attributes in Python? Is there a way to get all attributes/methods/fields/etc. of an object in Python? vars() is close to what I want, but it doesn't work unless an object has a __dict__, which isn't always true (e.g. it's not true for a list, a dict, etc.). [/INST] Use the built-in function dir(). </s>
<s>[INST] what is difference between __init__ and __call__ in python? I want to know what is difference between __init__ and __call__ methods? For example : class test: def __init__(self): self.a = 10 def __call__(self): b = 20 [/INST] The first is used to initialise newly created object, and receives arguments used to do that: class foo: def __init__(self, a, b, c): # ... x = foo(1, 2, 3) # __init__ The second implements function call operator. class foo: def __call__(self, a, b, c): # ... x = foo() x(1, 2, 3) # __call__ </s>
<s>[INST] How to sort my paws? In my previous question I got an excellent answer that helped me detect where a paw hit a pressure plate, but now I'm struggling to link these results to their corresponding paws: I manually annotated the paws (RF=right front, RH= right hind, LF=left front, LH=left hind). As you can see there's clearly a repeating pattern and it comes back in almost every measurement. Here's a link to a presentation of 6 trials that were manually annotated. My initial thought was to use heuristics to do the sorting, like: There's a ~60-40% ratio in weight bearing between the front and hind paws; The hind paws are generally smaller in surface; The paws are (often) spatially divided in left and right. However, I’m a bit skeptical about my heuristics, as they would fail on me as soon as I encounter a variation I hadn’t thought off. They also won’t be able to cope with measurements from lame dogs, whom probably have rules of their own. Furthermore, the annotation suggested by Joe sometimes get's messed up and doesn't take into account what the paw actually looks like. Based on the answers I received on my question about peak detection within the paw, I’m hoping there are more advanced solutions to sort the paws. Especially because the pressure distribution and the progression thereof are different for each separate paw, almost like a fingerprint. I hope there's a method that can use this to cluster my paws, rather than just sorting them in order of occurrence. So I'm looking for a better way to sort the results with their corresponding paw. For anyone up to the challenge, I have pickled a dictionary with all the sliced arrays that contain the pressure data of each paw (bundled by measurement) and the slice that describes their location (location on the plate and in time). To clarfiy: walk_sliced_data is a dictionary that contains ['ser_3', 'ser_2', 'sel_1', 'sel_2', 'ser_1', 'sel_3'], which are the names of the measurements. Each measurement contains another dictionary, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] (example from 'sel_1') which represent the impacts that were extracted. Also note that 'false' impacts, such as where the paw is partially measured (in space or time) can be ignored. They are only useful because they can help recognizing a pattern, but won't be analyzed. And for anyone interested, I’m keeping a blog with all the updates regarding the project! [/INST] Alright! I've finally managed to get something working consistently! This problem pulled me in for several days... Fun stuff! Sorry for the length of this answer, but I need to elaborate a bit on some things... (Though I may set a record for the longest non-spam stackoverflow answer ever!) As a side note, I'm using the full dataset that Ivo provided a link to in his original question. It's a series of rar files (one-per-dog) each containing several different experiment runs stored as ascii arrays. Rather than try to copy-paste stand-alone code examples into this question, here's a bitbucket mercurial repository with full, stand-alone code. You can clone it with hg clone https://joferkington@bitbucket.org/joferkington/paw-analysis Overview There are essentially two ways to approach the problem, as you noted in your question. I'm actually going to use both in different ways. Use the (temporal and spatial) order of the paw impacts to determine which paw is which. Try to identify the "pawprint" based purely on its shape. Basically, the first method works with the dog's paws follow the trapezoidal-like pattern shown in Ivo's question above, but fails whenever the paws don't follow that pattern. It's fairly easy to programatically detect when it doesn't work. Therefore, we can use the measurements where it did work to build up a training dataset (of ~2000 paw impacts from ~30 different dogs) to recognize which paw is which, and the problem reduces to a supervised classification (With some additional wrinkles... Image recognition is a bit harder than a "normal" supervised classification problem). Pattern Analysis To elaborate on the first method, when a dog is walking (not running!) normally (which some of these dogs may not be), we expect paws to impact in the order of: Front Left, Hind Right, Front Right, Hind Left, Front Left, etc. The pattern may start with either the front left or front right paw. If this were always the case, we could simply sort the impacts by initial contact time and use a modulo 4 to group them by paw. However, even when everything is "normal", this doesn't work. This is due to the trapezoid-like shape of the pattern. A hind paw spatially falls behind the previous front paw. Therefore, the hind paw impact after the initial front paw impact often falls off the sensor plate, and isn't recorded. Similarly, the last paw impact is often not the next paw in the sequence, as the paw impact before it occured off the sensor plate and wasn't recorded. Nonetheless, we can use the shape of the paw impact pattern to determine when this has happened, and whether we've started with a left or right front paw. (I'm actually ignoring problems with the last impact here. It's not too hard to add it, though.) def group_paws(data_slices, time): # Sort slices by initial contact time data_slices.sort(key=lambda s: s[-1].start) # Get the centroid for each paw impact... paw_coords = [] for x,y,z in data_slices: paw_coords.append([(item.stop + item.start) / 2.0 for item in (x,y)]) paw_coords = np.array(paw_coords) # Make a vector between each sucessive impact... dx, dy = np.diff(paw_coords, axis=0).T #-- Group paws ------------------------------------------- paw_code = {0:'LF', 1:'RH', 2:'RF', 3:'LH'} paw_number = np.arange(len(paw_coords)) # Did we miss the hind paw impact after the first # front paw impact? If so, first dx will be positive... if dx[0] > 0: paw_number[1:] += 1 # Are we starting with the left or right front paw... # We assume we're starting with the left, and check dy[0]. # If dy[0] > 0 (i.e. the next paw impacts to the left), then # it's actually the right front paw, instead of the left. if dy[0] > 0: # Right front paw impact... paw_number += 2 # Now we can determine the paw with a simple modulo 4.. paw_codes = paw_number % 4 paw_labels = [paw_code[code] for code in paw_codes] return paw_labels In spite of all of this, it frequently doesn't work correctly. Many of the dogs in the full dataset appear to be running, and the paw impacts don't follow the same temporal order as when the dog is walking. (Or perhaps the dog just has severe hip problems...) Fortunately, we can still programatically detect whether or not the paw impacts follow our expected spatial pattern: def paw_pattern_problems(paw_labels, dx, dy): """Check whether or not the label sequence "paw_labels" conforms to our expected spatial pattern of paw impacts. "paw_labels" should be a sequence of the strings: "LH", "RH", "LF", "RF" corresponding to the different paws""" # Check for problems... (This could be written a _lot_ more cleanly...) problems = False last = paw_labels[0] for paw, dy, dx in zip(paw_labels[1:], dy, dx): # Going from a left paw to a right, dy should be negative if last.startswith('L') and paw.startswith('R') and (dy > 0): problems = True break # Going from a right paw to a left, dy should be positive if last.startswith('R') and paw.startswith('L') and (dy < 0): problems = True break # Going from a front paw to a hind paw, dx should be negative if last.endswith('F') and paw.endswith('H') and (dx > 0): problems = True break # Going from a hind paw to a front paw, dx should be positive if last.endswith('H') and paw.endswith('F') and (dx < 0): problems = True break last = paw return problems Therefore, even though the simple spatial classification doesn't work all of the time, we can determine when it does work with reasonable confidence. Training Dataset From the pattern-based classifications where it worked correctly, we can build up a very large training dataset of correctly classified paws (~2400 paw impacts from 32 different dogs!). We can now start to look at what an "average" front left, etc, paw looks like. To do this, we need some sort of "paw metric" that is the same dimensionality for any dog. (In the full dataset, there are both very large and very small dogs!) A paw print from an Irish elkhound will be both much wider and much "heavier" than a paw print from a toy poodle. We need to rescale each paw print so that a) they have the same number of pixels, and b) the pressure values are standardized. To do this, I resampled each paw print onto a 20x20 grid and rescaled the pressure values based on the maximum, mininum, and mean pressure value for the paw impact. def paw_image(paw): from scipy.ndimage import map_coordinates ny, nx = paw.shape # Trim off any "blank" edges around the paw... mask = paw > 0.01 * paw.max() y, x = np.mgrid[:ny, :nx] ymin, ymax = y[mask].min(), y[mask].max() xmin, xmax = x[mask].min(), x[mask].max() # Make a 20x20 grid to resample the paw pressure values onto numx, numy = 20, 20 xi = np.linspace(xmin, xmax, numx) yi = np.linspace(ymin, ymax, numy) xi, yi = np.meshgrid(xi, yi) # Resample the values onto the 20x20 grid coords = np.vstack([yi.flatten(), xi.flatten()]) zi = map_coordinates(paw, coords) zi = zi.reshape((numy, numx)) # Rescale the pressure values zi -= zi.min() zi /= zi.max() zi -= zi.mean() #<- Helps distinguish front from hind paws... return zi After all of this, we can finally take a look at what an average left front, hind right, etc paw looks like. Note that this is averaged across >30 dogs of greatly different sizes, and we seem to be getting consistent results! However, before we do any analysis on these, we need to subtract the mean (the average paw for all legs of all dogs). Now we can analyize the differences from the mean, which are a bit easier to recognize: Image-based Paw Recognition Ok... We finally have a set of patterns that we can begin to try to match the paws against. Each paw can be treated as a 400-dimensional vector (returned by the paw_image function) that can be compared to these four 400-dimensional vectors. Unfortunately, if we just use a "normal" supervised classification algorithm (i.e. find which of the 4 patterns is closest to a particular paw print using a simple distance), it doesn't work consistently. In fact, it doesn't do much better than random chance on the training dataset. This is a common problem in image recognition. Due to the high dimensionality of the input data, and the somewhat "fuzzy" nature of images (i.e. adjacent pixels have a high covariance), simply looking at the difference of an image from a template image does not give a very good measure of the similarity of their shapes. Eigenpaws To get around this we need to build a set of "eigenpaws" (just like "eigenfaces" in facial recognition), and describe each paw print as a combination of these eigenpaws. This is identical to principal components analysis, and basically provides a way to reduce the dimensionality of our data, so that distance is a good measure of shape. Because we have more training images than dimensions (2400 vs 400), there's no need to do "fancy" linear algebra for speed. We can work directly with the covariance matrix of the training data set: def make_eigenpaws(paw_data): """Creates a set of eigenpaws based on paw_data. paw_data is a numdata by numdimensions matrix of all of the observations.""" average_paw = paw_data.mean(axis=0) paw_data -= average_paw # Determine the eigenvectors of the covariance matrix of the data cov = np.cov(paw_data.T) eigvals, eigvecs = np.linalg.eig(cov) # Sort the eigenvectors by ascending eigenvalue (largest is last) eig_idx = np.argsort(eigvals) sorted_eigvecs = eigvecs[:,eig_idx] sorted_eigvals = eigvals[:,eig_idx] # Now choose a cutoff number of eigenvectors to use # (50 seems to work well, but it's arbirtrary... num_basis_vecs = 50 basis_vecs = sorted_eigvecs[:,-num_basis_vecs:] return basis_vecs These basis_vecs are the "eigenpaws". To use these, we simply dot (i.e. matrix multiplication) each paw image (as a 400-dimensional vector, rather than a 20x20 image) with the basis vectors. This gives us a 50-dimensional vector (one element per basis vector) that we can use to classify the image. Instead of comparing a 20x20 image to the 20x20 image of each "template" paw, we compare the 50-dimensional, transformed image to each 50-dimensional transformed template paw. This is much less sensitive to small variations in exactly how each toe is positioned, etc, and basically reduces the dimensionality of the problem to just the relevant dimensions. Eigenpaw-based Paw Classification Now we can simply use the distance between the 50-dimensional vectors and the "template" vectors for each leg to classify which paw is which: codebook = np.load('codebook.npy') # Template vectors for each paw average_paw = np.load('average_paw.npy') basis_stds = np.load('basis_stds.npy') # Needed to "whiten" the dataset... basis_vecs = np.load('basis_vecs.npy') paw_code = {0:'LF', 1:'RH', 2:'RF', 3:'LH'} def classify(paw): paw = paw.flatten() paw -= average_paw scores = paw.dot(basis_vecs) / basis_stds diff = codebook - scores diff *= diff diff = np.sqrt(diff.sum(axis=1)) return paw_code[diff.argmin()] Here are some of the results: Remaining Problems There are still some problems, particularly with dogs too small to make a clear pawprint... (It works best with large dogs, as the toes are more clearly seperated at the sensor's resolution.) Also, partial pawprints aren't recognized with this system, while they can be with the trapezoidal-pattern-based system. However, because the eigenpaw analysis inherently uses a distance metric, we can classify the paws both ways, and fall back to the trapezoidal-pattern-based system when the eigenpaw analysis's smallest distance from the "codebook" is over some threshold. I haven't implemented this yet, though. Phew... That was long! My hat is off to Ivo for having such a fun question! </s>
<s>[INST] Concatenating two lists - difference between '+=' and extend() I've seen there are actually two (maybe more) ways to concatenate lists in Python: One way is to use the extend() method: a = [1, 2] b = [2, 3] b.extend(a) the other to use the plus(+) operator: b += a Now I wonder: Which of those two options is the 'pythonic' way to do list concatenation and is there a difference between the two (I've looked up the official Python tutorial but couldn't find anything anything about this topic). [/INST] The only difference on a bytecode level is that the .extend way involves a function call, which is slightly more expensive in Python than the INPLACE_ADD. It's really nothing you should be worrying about, unless you're performing this operation billions of times. It is likely, however, that the bottleneck would lie some place else. </s>
<s>[INST] Why is printing to stdout so slow? Can it be sped up? I've always been amazed/frustrated with how long it takes to simply output to the terminal with a print statement. After some recent painfully slow logging I decided to look into it and was quite surprised to find that almost all the time spent is waiting for the terminal to process the results. Can writing to stdout be sped up somehow? I wrote a script ('print_timer.py' at the bottom of this question) to compare timing when writing 100k lines to stdout, to file, and with stdout redirected to /dev/null. Here is the timing result: $python print_timer.py this is a test this is a test <snipped 99997 lines> this is a test ----- timing summary (100k lines each) ----- print :11.950 s write to file (+ fsync) : 0.122 s print with stdout = /dev/null : 0.050 s Wow. To make sure python isn't doing something behind the scenes like recognizing that I reassigned stdout to /dev/null or something, I did the redirection outside the script... $ python print_timer.py > /dev/null ----- timing summary (100k lines each) ----- print : 0.053 s write to file (+fsync) : 0.108 s print with stdout = /dev/null : 0.045 s So it isn't a python trick, it is just the terminal. I always knew dumping output to /dev/null sped things up, but never figured it was that significant! It amazes me how slow the tty is. How can it be that writing to physical disk is WAY faster than writing to the "screen" (presumably an all-RAM op), and is effectively as fast as simply dumping to the garbage with /dev/null? This link talks about how the terminal will block I/O so it can "parse [the input], update its frame buffer, communicate with the X server in order to scroll the window and so on"... but I don't fully get it. What can be taking so long? I expect there is no way out (short of a faster tty implementation?) but figure I'd ask anyway. UPDATE: after reading some comments I wondered how much impact my screen size actually has on the print time, and it does have some significance. The really slow numbers above are with my Gnome terminal blown up to 1920x1200. If I reduce it very small I get... ----- timing summary (100k lines each) ----- print : 2.920 s write to file (+fsync) : 0.121 s print with stdout = /dev/null : 0.048 s That is certainly better (~4x), but doesn't change my question. It only adds to my question as I don't understand why the terminal screen rendering should slow down an application writing to stdout. Why does my program need to wait for screen rendering to continue? Are all terminal/tty apps not created equal? I have yet to experiment. It really seems to me like a terminal should be able to buffer all incoming data, parse/render it invisibly, and only render the most recent chunk that is visible in the current screen configuration at a sensible frame rate. So if I can write+fsync to disk in ~0.1 seconds, a terminal should be able to complete the same operation in something of that order (with maybe a few screen updates while it did it). I'm still kind of hoping there is a tty setting that can be changed from the application side to make this behaviour better for programmer. If this is strictly a terminal application issue, then this maybe doesn't even belong on StackOverflow? What am I missing? Here is the python program used to generate the timing: import time, sys, tty import os lineCount = 100000 line = "this is a test" summary = "" cmd = "print" startTime_s = time.time() for x in range(lineCount): print line t = time.time() - startTime_s summary += "%-30s:%6.3f s\n" % (cmd, t) #Add a newline to match line outputs above... line += "\n" cmd = "write to file (+fsync)" fp = file("out.txt", "w") startTime_s = time.time() for x in range(lineCount): fp.write(line) os.fsync(fp.fileno()) t = time.time() - startTime_s summary += "%-30s:%6.3f s\n" % (cmd, t) cmd = "print with stdout = /dev/null" sys.stdout = file(os.devnull, "w") startTime_s = time.time() for x in range(lineCount): fp.write(line) t = time.time() - startTime_s summary += "%-30s:%6.3f s\n" % (cmd, t) print >> sys.stderr, "-----" print >> sys.stderr, "timing summary (100k lines each)" print >> sys.stderr, "-----" print >> sys.stderr, summary [/INST] How can it be that writing to physical disk is WAY faster than writing to the "screen" (presumably an all-RAM op), and is effectively as fast as simply dumping to the garbage with /dev/null? Congratulations, you have just discovered the importance of I/O buffering. :-) The disk appears to be faster, because it is highly buffered: all Python's write() calls are returning before anything is actually written to physical disk. (The OS does this later, combining many thousands of individual writes into a big, efficient chunks.) The terminal, on the other hand, does little or no buffering: each individual print / write(line) waits for the full write (i.e. display to output device) to complete. To make the comparison fair, you must make the file test use the same output buffering as the terminal, which you can do by modifying your example to: fp = file("out.txt", "w", 1) # line-buffered, like stdout [...] for x in range(lineCount): fp.write(line) os.fsync(fp.fileno()) # wait for the write to actually complete I ran your file writing test on my machine, and with buffering, it also 0.05s here for 100,000 lines. However, with the above modifications to write unbuffered, it takes 40 seconds to write only 1,000 lines to disk. I gave up waiting for 100,000 lines to write, but extrapolating from the previous, it would take over an hour. That puts the terminal's 11 seconds into perspective, doesn't it? So to answer your original question, writing to a terminal is actually blazingly fast, all things considered, and there's not a lot of room to make it much faster (but individual terminals do vary in how much work they do; see Russ's comment to this answer). (You could add more write buffering, like with disk I/O, but then you wouldn't see what was written to your terminal until after the buffer gets flushed. It's a trade-off: interactivity versus bulk efficiency.) </s>
<s>[INST] Is there a python equivalent of Ruby's 'rvm'? Q: Do we have anything functionally equivalent in Python to the Ruby version manager 'rvm'? (RVM lets you easily switch completely between different versions of the ruby interpreter and different sets of gems (modules). Everything concerning download-build-install-switch of interpreter(-s) and gems gets taken care of by invoking rvm. It is all run under your regular user account.) [/INST] Pythonbrew is no longer under development. The former maintainer suggests to use "PyEnv" instead (see below)". pythonbrew has come! http://github.com/utahta/pythonbrew pyenv: https://github.com/yyuu/pyenv </s>
<s>[INST] How to generate dynamic (parametrized) unit tests in python? I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this: import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name self.assertEqual(a,b) if __name__ == '__main__': unittest.main() The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions? [/INST] i use something like this: import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequense(unittest.TestCase): pass def test_generator(a, b): def test(self): self.assertEqual(a,b) return test if __name__ == '__main__': for t in l: test_name = 'test_%s' % t[0] test = test_generator(t[1], t[2]) setattr(TestSequense, test_name, test) unittest.main() The nose-parameterized package can be used to automate this process: from nose_parameterized import parameterized class TestSequence(unittest.TestCase): @parameterized.expand([ ["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"], ]) def test_sequence(self, name, a, b): self.assertEqual(a,b) Which will generate the tests: test_sequence_0_foo (__main__.TestSequence) ... ok test_sequence_1_bar (__main__.TestSequence) ... FAIL test_sequence_2_lee (__main__.TestSequence) ... ok ====================================================================== FAIL: test_sequence_1_bar (__main__.TestSequence) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/nose_parameterized/parameterized.py", line 233, in <lambda> standalone_func = lambda *a: func(*(a + p.args), **p.kwargs) File "x.py", line 12, in test_sequence self.assertEqual(a,b) AssertionError: 'a' != 'b' </s>
<s>[INST] Event system in Python What event system for Python do you use? I'm already aware of pydispatcher, but I was wondering what else can be found, or is commonly used? I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend. [/INST] Wrapping up the various event systems that are mentioned in the answers here: The most basic style of event system is the 'bag of handler methods', which is a simple implementation of the Observer pattern. Basically, the handler methods (callables) are stored in an array and are each called when the event 'fires'. zope.event shows the bare bones of how this works (see Lennart's answer). Note: this example does not even support handler arguments. LongPoke's 'callable list' implementation shows that such an event system can be implemented very minimalistically by subclassing list. spassig's EventHook (Michael Foord's Event Pattern) is a straightforward implementation. Josip's Valued Lessons Event class is basically the same, but uses a set instead of a list to store the bag, and implements __call__ which are both reasonable additions. PyNotify is similar in concept and also provides additional concepts of variables and conditions ('variable changed event'). axel is basically a bag-of-handlers with more features related to threading, error handling, ... The disadvantage of these event systems is that you can only register the handlers on the actual Event object (or handlers list). So at registration time the event already needs to exist. That's why the second style of event systems exists: the publish-subscribe pattern. Here, the handlers don't register on an event object (or handler list), but on a central dispatcher. Also the notifiers only talk to the dispatcher. What to listen for, or what to publish is determined by 'signal', which is nothing more than a name (string). blinker has some nifty features such as automatic disconnection and filtering based on sender. PyPubSub at first sight seems to be pretty straightforward; apparently does not yet support Python3 PyDispatcher seems to emphasize flexibility with regards to many-to-many publication etc. louie is a reworked PyDispatcher "providing plugin infrastructure including Twisted and PyQt specific support". django.dispatch is a rewritten PyDispatcher "with a more limited interface, but higher performance". Qt's Signals and Slots are available from PyQt or PySide. They work as callback when used in the same thread, or as events (using an event loop) between two different threads. Signals and Slots have the limitation that they only work in objects of classes that derive from QObject. Note: threading.Event is not an 'event system' in the above sense. It's a thread synchronization system where one thread waits until another thread 'signals' the Event object. </s>
<s>[INST] Django FileField with upload_to determined at runtime I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA_ROOT/joe as opposed to having everyone's files go to MEDIA_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks: class Content(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User) file = models.FileField(upload_to='.') So what I want is instead of '.' as the upload_to, have it be the user's name. I understand that as of Django 1.0 you can define your own function to handle the upload_to but that function has no idea of who the user will be either so I'm a bit lost. Thanks for the help! [/INST] You've probably read the documentation, so here's an easy example to make it make sense: def content_file_name(instance, filename): return '/'.join(['content', instance.user.username, filename]) class Content(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User) file = models.FileField(upload_to=content_file_name) As you can see, you don't even need to use the filename given - you could override that in your upload_to callable too if you liked. </s>
<s>[INST] How can I convert a Python dictionary to a list of tuples? If I have a dictionary like: { 'a': 1, 'b': 2, 'c': 3 } How can I convert it to this? [ ('a', 1), ('b', 2), ('c', 3) ] And how can I convert it to this? [ (1, 'a'), (2, 'b'), (3, 'c') ] [/INST] >>> d = { 'a': 1, 'b': 2, 'c': 3 } >>> d.items() [('a', 1), ('c', 3), ('b', 2)] >>> [(v, k) for k, v in d.iteritems()] [(1, 'a'), (3, 'c'), (2, 'b')] It's not in the order you want, but dicts don't have any specific order anyway. Sort it or organize it as necessary. See: items(), iteritems() In Python 3.x, you would not use iteritems (which no longer exists), but instead use items, which now returns a "view" into the dictionary items. See the What's New document for Python 3.0, and the new documentation on views. </s>
<s>[INST] How to access the local Django webserver from outside world I followed the instructions here to run Django using the built-in webserver and was able to successfully run it using python manage.py runserver. If I access 127.0.0.1:port locally from the webserver, I get the Django page indicating it worked. I realize the Django webserver is not a production server, but it's important for me for testing purposes to be able to access it from the outside world -- i.e. not from a web browser on the server, but from a different computer. I tried: http://mywebserver:port_django_runs_on but it did not work. I also tried using the IP instead (based on ifconfig) to access: http://myipaddress:port_django_runs_on which did not work either. The web server is running so it must be accessible from the outside, I'm just not sure how. I am running Linux with Apache, though I have not configured Django with Apache. Any ideas on how to do this? [/INST] You have to run the development server such that it listens on the interface to your network. E.g. python manage.py runserver 0.0.0.0:8000 listens on every interface on port 8000. It doesn't matter whether you access the webserver with the IP or the hostname. I guess you are still in your own LAN. If you really want to access the server from outside, you also have to configure your router to forward port e.g. 8000 to your server. Check your firewall on your server whether incoming connections to the port in use are allowed! Assuming you can access your Apache server from the outside successfully, you can also try this: Stop the Apache server, so that port 80 is free. Start the development server with sudo python manage.py runserver 0.0.0.0:80 </s>
<s>[INST] how to access dictionary element in django template? I have this code in template, which I would like to printout number of votes that each choice got. votes is just dictionary while choices are model object. {% for choice in choices %} {{choice.choice}} - {{votes[choice.id]}} <br /> {% endfor %} it raises an exception with this message "Could not parse the remainder" [/INST] choices = {'key1':'val1', 'key2':'val2'} Here's the template: <ul> {% for key, value in choices.items %} <li>{{key}} - {{value}}</li> {% endfor %} </ul> Basically, .items is a Django keyword that splits a dictionary into a list of (key, value) pairs. This enables iteration over a dictionary in a Django template. </s>
<s>[INST] Does Python have a package/module management system? Does Python have a package/module management system, similar to how Ruby has rubygems where you can do gem install packagename? On Installing Python Modules, I only see references to python setup.py install, but that requires you to find the package first. [/INST] Recent progress March 2014: Good news! Python 3.4 ships with Pip. Pip has long been Python's de-facto standard package manager. You can install a package like this: pip install httpie Wahey! This is the best feature of any Python release. It makes the community's wealth of libraries accessible to everyone. Newbies are no longer excluded from using community libraries by the prohibitive difficulty of setup. However, there remains a number of outstanding frustrations with the Python packaging experience. Cumulatively, they make Python very unwelcoming for newbies. Also, the long history of neglect (ie. not shipping with a package manager for 14 years from Python 2.0 to Python 3.3) did damage to the community. I describe both below. Outstanding frustrations It's important to understand that while experienced users are able to work around these frustrations, they are significant barriers to people new to Python. In fact, the difficulty and general user-unfriendliness is likely to deter many of them. PyPI website is counter-helpful Every language with a package manager has an official (or quasi-official) repository for the community to download and publish packages. Python has the Python Package Index, PyPI. https://pypi.python.org/pypi Let's compare its pages with those of RubyGems and Npm (the Node package manager). https://rubygems.org/gems/rails RubyGems page for the package rails https://www.npmjs.org/package/express Npm page for the package express https://pypi.python.org/pypi/simplejson/ PyPI page for the package simplejson You'll see the RubyGems and Npm pages both begin with a one-line description of the package, then large friendly instructions how to install it. Meanwhile, woe to any hapless Python user who naively browses to PyPI. On https://pypi.python.org/pypi/simplejson/ , they'll find no such helpful instructions. There is however, a large green 'Download' link. It's not unreasonable to follow it. Aha, they click! Their browser downloads a .tar.gz file. Many Windows users can't even open it, but if they persevere they may eventually extract it, then run setup.py and eventually with the help of Google setup.py install. Some will give up and reinvent the wheel.. Of course, all of this is wrong. The easiest way to install a package is with a Pip command. But PyPI didn't even mention Pip. Instead, it led them down an archaic and tedious path. Error: Unable to find vcvarsall.bat Numpy is one of Python's most popular libraries. Try to install it with Pip, you get this cryptic error message: Error: Unable to find vcvarsall.bat Trying to fix that is one of the most popular questions on Stack Overflow: "error: Unable to find vcvarsall.bat" Few people succeed. For comparison, in the same situation, Ruby prints this message, which explains what's going on and how to fix it: Please update your PATH to include build tools or download the DevKit from http://rubyinstaller.org/downloads and follow the instructions at http://github.com/oneclick/rubyinstaller/wiki/Development-Kit Publishing packages is hard Ruby and Nodejs ship with full-featured package managers, Gem (since 2007) and Npm (since 2011), and have nurtured sharing communities centred around GitHub. Npm makes publishing packages as easy as installing them, it already has 64k packages. RubyGems lists 72k packages. The venerable Python package index lists only 41k. History Flying in the face of its "batteries included" motto, Python shipped without a package manager until 2014. Until Pip, the de facto standard was a command easy_install. It was woefully inadequate. The was no command to uninstall packages. Pip was a massive improvement. It had most the features of Ruby's Gem. Unfortunately, Pip was--until recently--ironically difficult to install. In fact, the problem remains a top Python question on Stack Overflow: "How do I install pip on Windows?" </s>
<s>[INST] How can I parse a time string containing milliseconds in it with python? I am able to parse strings containing date/time with time.strptime >>> import time >>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S') (2009, 3, 30, 16, 31, 32, 0, 89, -1) How can I parse a time string that contains milliseconds? >>> time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/_strptime.py", line 333, in strptime data_string[found.end():]) ValueError: unconverted data remains: .123 [/INST] Python 2.6 added a new strftime/strptime macro %f, which does microseconds. Not sure if this is documented anywhere. But if you're using 2.6 or 3.0, you can do this: time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f') Edit: I never really work with the time module, so I didn't notice this at first, but it appears that time.struct_time doesn't actually store milliseconds/microseconds. You may be better off using datetime, like this: >>> from datetime import datetime >>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f') >>> a.microsecond 123000 </s>
<s>[INST] Sorting list based on values from another list? I am a list of strings like this: X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1] What is the shortest way of sorting X using values from Y to get the following output? ["a", "d", "h", "b", "c", "e", "i", "f", "g"] The order for the elements having the same "key" does not matter. I can resort to using for constructs but I am curious if there is a shorter way. Any suggestions? [/INST] [x for (y,x) in sorted(zip(Y,X))] </s>
<s>[INST] Python idiom to return first item or None I'm sure there's a simpler way of doing this that's just not occurring to me. I'm calling a bunch of methods that return a list. The list may be empty. If the list is non-empty, I want to return the first item; otherwise, I want to return None. This code works: my_list = get_list() if len(my_list) > 0: return my_list[0] return None It seems to me that there should be a simple one-line idiom for doing this, but for the life of me I can't think of it. Is there? Edit: The reason that I'm looking for a one-line expression here is not that I like incredibly terse code, but because I'm having to write a lot of code like this: x = get_first_list() if x: # do something with x[0] # inevitably forget the [0] part, and have a bug to fix y = get_second_list() if y: # do something with y[0] # inevitably forget the [0] part AGAIN, and have another bug to fix What I'd like to be doing can certainly be accomplished with a function (and probably will be): def first_item(list_or_none): if list_or_none: return list_or_none[0] x = first_item(get_first_list()) if x: # do something with x y = first_item(get_second_list()) if y: # do something with y I posted the question because I'm frequently surprised by what simple expressions in Python can do, and I thought that writing a function was a silly thing to do if there was a simple expression could do the trick. But seeing these answers, it seems like a function is the simple solution. [/INST] The best way is this: a = get_list() return a[0] if a else None You could also do it in one line, but it's much harder for the programmer to read: return (get_list()[:1] or [None])[0] </s>
<s>[INST] Django CSRF check failing with an Ajax POST request I could use some help complying with Django's CSRF protection mechanism via my AJAX post. I've followed the directions here: http://docs.djangoproject.com/en/dev/ref/contrib/csrf/ I've copied the AJAX sample code they have on that page exactly: http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax I put an alert printing the contents of getCookie('csrftoken') before the xhr.setRequestHeader call and it is indeed populated with some data. I'm not sure how to verify that the token is correct, but I'm encouraged that it's finding and sending something. But Django is still rejecting my AJAX post. Here's my JavaScript: $.post("/memorize/", data, function (result) { if (result != "failure") { get_random_card(); } else { alert("Failed to save card data."); } }); Here's the error I'm seeing from Django: [23/Feb/2011 22:08:29] "POST /memorize/ HTTP/1.1" 403 2332 I'm sure I'm missing something, and maybe it's simple, but I don't know what it is. I've searched around SO and saw some information about turning off the CSRF check for my view via the csrf_exempt decorator, but I find that unappealing. I've tried that out and it works, but I'd rather get my POST to work the way Django was designed to expect it, if possible. Just in case it's helpful, here's the gist of what my view is doing: def myview(request): profile = request.user.profile if request.method == 'POST': """ Process the post... """ return HttpResponseRedirect('/memorize/') else: # request.method == 'GET' ajax = request.GET.has_key('ajax') """ Some irrelevent code... """ if ajax: response = HttpResponse() profile.get_stack_json(response) return response else: """ Get data to send along with the content of the page. """ return render_to_response('memorize/memorize.html', """ My data """ context_instance=RequestContext(request)) Thanks for your replies! [/INST] Real solution Ok, I managed to trace the problem down. It lies in the Javascript (as I suggested below) code. What you need is this: $.ajaxSetup({ beforeSend: function(xhr, settings) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) { // Only send the token to relative URLs i.e. locally. xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); } } }); instead of the code posted in the official docs: http://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#ajax The working code, comes from this Django entry: http://www.djangoproject.com/weblog/2011/feb/08/security/ So the general solution is: "use ajaxSetup handler instead of ajaxSend handler". I don't know why it works. But it works for me :) Previous post (without answer) I'm experiencing the same problem actually. It occurs after updating to Django 1.2.5 - there were no errors with AJAX POST requests in Django 1.2.4 (AJAX wasn't protected in any way, but it worked just fine). Just like OP, I have tried the JavaScript snippet posted in Django documentation. I'm using jQuery 1.5. I'm also using the "django.middleware.csrf.CsrfViewMiddleware" middleware. I tried to follow the the middleware code and I know that it fails on this: request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '') and then if request_csrf_token != csrf_token: return self._reject(request, REASON_BAD_TOKEN) this "if" is true, because "request_csrf_token" is empty. Basically it means that the header is NOT set. So is there anything wrong with this JS line: xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken')); ? I hope that provided details will help us in resolving the issue :) </s>
<s>[INST] Python: How to "perfectly" override a dict How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase. It would seem that should be some tiny set of primitives I can override to make this work, but all my research and attempts have made it seem like this isn't the case: If I override __getitem__/__setitem__, then get/set don't work. How do I make them work? Surely I don't need to implement them individually? Am I preventing pickling from working, and do I need to implement __setstate__ etc? Do I need repr, update and __init__? Should I just use mutablemapping (it seems one shouldn't use UserDict or DictMixin)? If so, how? The docs aren't exactly enlightening. Here is my first go at it, get() doesn't work at least, and no doubt there are many minor subtle problems: class arbitrary_dict(dict): """A dictionary that applies an arbitrary key-altering function before accessing the keys.""" def __keytransform__(self, key): return key # Overridden methods. List from # http://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict def __init__(self, *args, **kwargs): self.update(*args, **kwargs) # Note: I'm using dict directly, since super(dict, self) doesn't work. # I'm not sure why, perhaps dict is not a new-style class. def __getitem__(self, key): return dict.__getitem__(self, self.__keytransform__(key)) def __setitem__(self, key, value): return dict.__setitem__(self, self.__keytransform__(key), value) def __delitem__(self, key): return dict.__delitem__(self, self.__keytransform__(key)) def __contains__(self, key): return dict.__contains__(self, self.__keytransform__(key)) class lcdict(arbitrary_dict): def __keytransform__(self, key): return str(key).lower() [/INST] You can write an object that behaves like a dict quite easily with ABCs (Abstract Base Classes) from the collections module. It even tells you if you missed a method, so below is the minimal version that shuts the ABC up. import collections class TransformedDict(collections.MutableMapping): """A dictionary that applies an arbitrary key-altering function before accessing the keys""" def __init__(self, *args, **kwargs): self.store = dict() self.update(dict(*args, **kwargs)) # use the free update to set keys def __getitem__(self, key): return self.store[self.__keytransform__(key)] def __setitem__(self, key, value): self.store[self.__keytransform__(key)] = value def __delitem__(self, key): del self.store[self.__keytransform__(key)] def __iter__(self): return iter(self.store) def __len__(self): return len(self.store) def __keytransform__(self, key): return key You get a few free methods from the ABC: class MyTransformedDict(TransformedDict): def __keytransform__(self, key): return key.lower() s = MyTransformedDict([('Test', 'test')]) assert s.get('TEST') is s['test'] # free get assert 'TeSt' in s # free __contains__ # free setdefault, __eq__, and so on import pickle assert pickle.loads(pickle.dumps(s)) == s # works too since we just use a normal dict I wouldn't subclass dict (or other builtins) directly. It often makes no sense, because what you actually want to do is implement the interface of a dict. And that is exactly what ABCs are for. </s>
<s>[INST] What is getattr() exactly and how do I use it? I was reading about the getattr() function. The problem is that I still can't grasp the idea of its usage. The only thing I understand about getattr() is that getattr(li, "pop") is the same as calling li.pop. I didn't understand when the book mentioned how you use it to get a reference to a function without knowing its name until run-time. Maybe this is me being a noob in programming, in general. Could anyone shed some light to the subject? When and how do I use this exactly? [/INST] Objects in Python can have attributes (actually, every object has built-in attributes -- data attributes and methods (functions are values, i.e. objects, too) to work with those). For example you have an object person, that has several attributes: name, gender, etc. You access these attributes (be it methods or data objects) usually writing: person.name, person.gender, person.the_method(), etc. But what if you don't know the attribute's name at the time you write the program? For example you have attribute's name stored in a variable called attr_name. if attr_name = 'gender' then, instead of writing gender = person.gender you can write gender = getattr(person, attr_name) Some practice: Python 3.4.0 (default, Apr 11 2014, 13:05:11) >>> class Person(): ... name = 'Victor' ... def say(self, what): ... print(self.name, what) ... >>> getattr(Person, 'name') 'Victor' >>> attr_name = 'name' >>> person = Person() >>> getattr(person, attr_name) 'Victor' >>> getattr(person, 'say')('Hello') Victor Hello getattr will raise AttributeError if attribute with the given name does not exist in the object: >>> getattr(person, 'age') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Person' object has no attribute 'age' But you can pass a default value as the third argument, which will be returned if such attribute does not exist: >>> getattr(person, 'age', 0) 0 You can use getattr along with dir to iterate over all attribute names and get their values: >>> dir(1000) ['__abs__', '__add__', ..., '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] >>> obj = 1000 >>> for attr_name in dir(obj): ... attr_value = getattr(obj, attr_name) ... print(attr_name, attr_value, callable(attr_value)) ... __abs__ <method-wrapper '__abs__' of int object at 0x7f4e927c2f90> True __add__ <method-wrapper '__add__' of int object at 0x7f4e927c2f90> True ... __trunc__ <built-in method __trunc__ of int object at 0x7f4e927c2f90> True __xor__ <method-wrapper '__xor__' of int object at 0x7f4e927c2f90> True bit_length <built-in method bit_length of int object at 0x7f4e927c2f90> True conjugate <built-in method conjugate of int object at 0x7f4e927c2f90> True denominator 1 False from_bytes <built-in method from_bytes of type object at 0x9ee4c0> True imag 0 False numerator 1000 False real 1000 False to_bytes <built-in method to_bytes of int object at 0x7f4e927c2f90> True >>> getattr(1000, 'bit_length')() 10 A practical use for this would be to find all methods whose names start with test and call them. </s>
<s>[INST] Object of custom type as dictionary key What must I do to use my objects of a custom type as keys in a Python dictionary (where I don't want the "object id" to act as the key) , e.g. class MyThing: def __init__(self,name,location,length): self.name = name self.location = location self.length = length I'd want to use MyThing's as keys that are considered the same if name and location are the same. From C#/Java I'm used to having to override and provide an equals and hashcode method, and promise not to mutate anything the hashcode depends on. What must I do in Python to accomplish this ? Should I even ? (In a simple case, like here, perhaps it'd be better to just place a (name,location) tuple as key - but consider I'd want the key to be an object) [/INST] You need to add two methods: class MyThing: def __init__(self,name,location,length): self.name = name self.location = location self.length = length def __hash__(self): return hash((self.name, self.location)) def __eq__(self, other): return (self.name, self.location) == (other.name, other.location) def __ne__(self, other): # Not strictly necessary, but to avoid having both x==y and x!=y # True at the same time return not(self == other) The Python dict documentation defines these requirements on key objects, i.e. they must be hashable. </s>
<s>[INST] Python Linked List What's the easiest way to use a linked list in python? In scheme, a linked list is defined simply by '(1 2 3 4 5). Python's lists, [1, 2, 3, 4, 5], and tuples, (1, 2, 3, 4, 5), are not, in fact, linked lists, and linked lists have some nice properties such as constant-time concatenation, and being able to reference separate parts of them. Make them immutable and they are really easy to work with! [/INST] For some needs, a deque may also be useful. You can add and remove items on both ends of a deque at O(1) cost. from collections import deque d = deque([1,2,3,4]) print d for x in d: print x print d.pop(), d </s>
<s>[INST] Python - Create a list with initial capacity Code like this often happens: l = [] while foo: #baz l.append(bar) #qux This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements. In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient. I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us Python programmers? [/INST] def doAppend( size=10000 ): result = [] for i in range(size): message= "some unique object %d" % ( i, ) result.append(message) return result def doAllocate( size=10000 ): result=size*[None] for i in range(size): message= "some unique object %d" % ( i, ) result[i]= message return result Results. (evaluate each function 144 times and average the duration) simple append 0.0102 pre-allocate 0.0098 Conclusion. It barely matters. Premature optimization is the root of all evil. </s>
<s>[INST] What is the difference between Python and IPython? What exactly is the difference between Python and IPython? If I write code in Python, will it run in IPython as is or does it need to be modified? I know IPython is supposed to be an interactive shell for Python, but is that all? Or is there a language called IPython? If I write something under IPython, will it run in Python, and vice-versa? If there are differences, how do I know what they are? Will all packages used by Python work as is in IPython? [/INST] ipython is an interactive shell built with python. From the project website: IPython provides a rich toolkit to help you make the most out of using Python, with: Powerful Python shells (terminal and Qt-based). A web-based notebook with the same core features but support for code, text, mathematical expressions, inline plots and other rich media. Support for interactive data visualization and use of GUI toolkits. Flexible, embeddable interpreters to load into your own projects. Easy to use, high performance tools for parallel computing. Note that the first 2 lines tell you it helps you make the most of using Python. Thus, you don't need to alter your code, the IPython shell runs your python code just like the normal python shell does, only with more features. I recommend reading the IPython tutorial to get a sense of what features you gain when using IPython. </s>
<s>[INST] Java "Virtual Machine" vs. Python "Interpreter" parlance? It's seems rare to read of a Python "virtual machine" while in Java "virtual machine" is used all the time. Both interpret byte codes, why call one a virtual machine and the other an interpreter? [/INST] A virtual machine is a virtual computing environment with a specific set of atomic well defined instructions that are supported independent of any specific language and it is generally thought of as a sandbox unto itself. The VM is analogous to an instruction set of a specific CPU and tends to work at a more fundamental level with very basic building blocks of such instructions (or byte codes) that are independent of the next. An instruction executes deterministically based only on the current state of the virtual machine and does not depend on information elsewhere in the instruction stream at that point in time. An interpreter on the other hand is more sophisticated in that it is tailored to parse a stream of some syntax that is of a specific language and of a specific grammer that must be decoded in the context of the surrounding tokens. You can't look at each byte or even each line in isolation and know exactly what to do next. The tokens in the language can't be taken in isolation like they can relative to the instructions (byte codes) of a VM. A Java compiler converts Java language into a byte-code stream no different than a C compiler converts C Language programs into assembly code. An interpreter on the other hand doesn't really convert the program into any well defined intermediate form, it just takes the program actions as a matter of the process of interpreting the source. Another test of the difference between a VM and an interpreter is whether you think of it as being language independent. What we know as the Java VM is not really Java specific. You could make a compiler from other languages that result in byte codes that can be run on the JVM. On the other hand, I don't think we would really think of "compiling" some other language other than Python into Python for interpretation by the Python interpreter. Because of the sophistication of the interpretation process, this can be a relatively slow process....specifically parsing and identifying the language tokens, etc. and understanding the context of the source to be able to undertake the execution process within the interpreter. To help accelerate such interpreted languages, this is where we can define intermediate forms of pre-parsed, pre-tokenized source code that is more readily directly interpreted. This sort of binary form is still interpreted at execution time, it is just starting from a much less human readable form to improve performance. However, the logic executing that form is not a virtual machine, because those codes still can't be taken in isolation - the context of the surrounding tokens still matter, they are just now in a different more computer efficient form. </s>
<s>[INST] How do I install the yaml package for Python? I have a Python program that uses YAML. I attempted to install it on a new server using pip install yaml and it returns the following: $ sudo pip install yaml Downloading/unpacking yaml Could not find any downloads that satisfy the requirement yaml No distributions at all found for yaml Storing complete log in /home/pa/.pip/pip.log How do I install the yaml package for Python? I'm running Python 2.7. [/INST] You could try the search feature in pip, $ pip search yaml which looks for packages in PyPI with yaml in the short description. That reveals various packages, including PyYaml, yamltools, and PySyck, among others (Note that PySyck docs recommend using PyYaml, since syck is out of date). Now you know a specific package name, you can install it: $ pip install pyyaml If you want to install python yaml system-wide in linux, you can also use a package manager, like aptitude or yum: $ sudo apt-get install python-yaml $ sudo yum install python-yaml </s>
<s>[INST] Truncate Python DateTime What is a classy way to way truncate a python datetime object? In this particular case, to the day. So basically setting hour, minute, seconds, and microseconds to 0. I would like the output to also be a datetime object, not a string. [/INST] I think this is what you're looking for... >>> dt = datetime.datetime.now() >>> dt = dt.replace(hour=0, minute=0, second=0, microsecond=0) # Returns a copy >>> dt datetime.datetime(2011, 3, 29, 0, 0) But if you really don't care about the time aspect of things, then you should really only be passing around date objects... >>> d_truncated = datetime.date(dt.year, dt.month, dt.day) >>> d_truncated datetime.date(2011, 3, 29) </s>
<s>[INST] How to pull a random record using Django's ORM? I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. I'm using Django 1.0.2. While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this: number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things. Any other options how I can do it, preferably somehow inside the model abstraction? [/INST] Simply use: MyModel.objects.order_by('?').first() It is documented in QuerySet API. </s>
<s>[INST] Wrap long lines in Python How do I wrap long lines in Python without sacrificing indentation? For example: def fun(): print '{0} Here is a really long sentence with {1}'.format(3, 5) Suppose this goes over the 79 character recommended limit. The way I read it, here is how to indent it: def fun(): print '{0} Here is a really long \ sentence with {1}'.format(3, 5) However, with this approach, the indentation of the continued line matches the indentation of the fun(). This looks kinda ugly. If someone was to go through my code, it would look bad to have uneven indentation because of this print statement. How do I indent lines like this effectively without sacrificing code readability? [/INST] def fun(): print '{0} Here is a really long ' \ 'sentence with {1}'.format(3, 5) Adjecent string literals are concatenated at compile time, just as in C. http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation is a good place to start for more info. </s>
<s>[INST] How to install python modules without root access? I'm taking some university classes and have been given an 'instructional account', which is a school account I can ssh into to do work. I want to run my computationally intensive Numpy, matplotlib, scipy code on that machine, but I cannot install these modules because I am not a system administrator. How can I do the installation? [/INST] In most situations the best solution is to rely on the so-called "user site" location (see the PEP for details) by running: pip install --user package_name Below is a more "manual" way from my original answer, you do not need to read it if the above solution works for you. With easy_install you can do: easy_install --prefix=$HOME/local package_name which will install into $HOME/local/lib/pythonX.Y/site-packages (the 'local' folder is a typical name many people use, but of course you may specify any folder you have permissions to write into). You will need to manually create $HOME/local/lib/pythonX.Y/site-packages and add it to your PYTHONPATH environment variable (otherwise easy_install will complain -- btw run the command above once to find the correct value for X.Y). If you are not using easy_install, look for a prefix option, most install scripts let you specify one. With pip you can use: pip install --install-option="--prefix=$HOME/local" package_name </s>
<s>[INST] json.dumps vs flask.jsonify I am not sure I understand the purpose of flask.jsonify method. I try to make json string from this: data = {"id": str(album.id), "title": album.title} but what I get with json.dumps differs from what I get with flask.jsonify. json.dumps(data): [{"id": "4ea856fd6506ae0db42702dd", "title": "Business"}] flask.jsonify(data): {"id", "title"} Obviously I need to get result that looks more like what json.dumps returns. What am I doing wrong? [/INST] The jsonify() function in flask returns flask.Response() object that already has the appropriate content-type header 'application/json' for use with json responses, whereas the json.dumps() will just return an encoded string, which would require manually adding the mime type header. See more about the jsonify() function here for full reference. Edit: Also, I've noticed that jsonify() handles kwargs or dictionaries, while json.dumps() additionally supports lists and others. </s>
<s>[INST] Removing pip's cache? I need to install psycopg2 v2.4.1 specifically. I accidentally did: pip install psycopg2 Instead of: pip install psycopg2==2.4.1 That installs 2.4.4 instead of the earlier version. Now even after I pip uninstall psycopg2 and attempt to reinstall with the correct version, it appears that pip is re-using the cache it downloaded the first time. How can I force pip to clear out its download cache and use the specific version I'm including in the command? [/INST] If using pip older than pip 6.0, try deleting the entry in ~/.pip/cache/ and or the directory $PWD/build/ if it exists. You can also try the --ignore-installed option. In windows this is located under %USERPROFILE%\AppData\Local\pip\cache. If using pip 6.0 or newer, try using the --no-cache-dir option. </s>
<s>[INST] Using pip behind a proxy I'm trying to use pip behind a proxy at work. I'm not a networking expert so bear with me if this super obvious. One of the answers from this post suggested using CNTLM. I installed and configured it per this other post, but running cntlm.exe -c cntlm.ini -I -M http://google.com gave the error Connection to proxy failed, bailing out. I also tried pip install -–proxy=user:pass@localhost:3128 (the default CNTLM port) but that raised Cannot fetch index base URL http://pypi.python.org/simple/. Clearly something's up with the proxy. Does anyone know how to check more definitively whether CNTLM is set up right, or if there's another way around this altogether? I know you can also set the http_proxy environment variable as described here but I'm not sure what credentials to put in. The ones from cntlm.ini? Thanks! [/INST] Under Ubuntu: I could not get the proxy option to work as advertised - so following command did not work: sudo pip --proxy http://web-proxy.mydomain.com install somepackage But exporting the https_proxy env variable (note its https_proxy not http_proxy) did the trick: export https_proxy=http://web-proxy.mydomain.com then sudo -E pip install somepackage </s>
<s>[INST] What is the reason for performing a double fork when creating a daemon? I'm trying to create a daemon in python. I've found the following question, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found plenty of resources declaring that one is necessary, but not why. Some mention that it is to prevent the daemon from acquiring a controlling terminal. How would it do this without the second fork? What are the repercussions? [/INST] I was trying to understand the double fork and stumbled upon this question here. After a lot of research this is what I figured out. Hopefully it will help clarify things better for anyone who has the same question. In Unix every process belongs to a group which in turn belongs to a session. Here is the hierarchy… Session (SID) → Process Group (PGID) → Process (PID) The first process in the process group becomes the process group leader and the first process in the session becomes the session leader. Every session can have one TTY associated with it. Only a session leader can take control of a TTY. For a process to be truly daemonized (ran in the background) we should ensure that the session leader is killed so that there is no possibility of the session ever taking control of the TTY. I ran Sander Marechal's python example daemon program from this site on my Ubuntu. Here are the results with my comments. 1. `Parent` = PID: 28084, PGID: 28084, SID: 28046 2. `Fork#1` = PID: 28085, PGID: 28084, SID: 28046 3. `Decouple#1`= PID: 28085, PGID: 28085, SID: 28085 4. `Fork#2` = PID: 28086, PGID: 28085, SID: 28085 Note that the process is the session leader after Decouple#1, because it's PID = SID. It could still take control of a TTY. Note that Fork#2 is no longer the session leader PID != SID. This process can never take control of a TTY. Truly daemonized. I personally find terminology fork-twice to be confusing. A better idiom might be fork-decouple-fork. Additional links of interest: Unix processes - http://www.win.tue.nl/~aeb/linux/lk/lk-10.html </s>
<s>[INST] how to get the return value from a thread in python? How can I access that return value 'foo' from the thread? def foo(bar): print 'hello {0}'.format(bar) return 'foo' from threading import Thread t = Thread(target=foo, args=('world!',)) t.start() x = t.join() print x The one obvious way to do it, above, seems to just return None in x. [/INST] FWIW, the multiprocessing module has a nice interface for this using the Pool class. And if you want to stick with threads rather than processes, you can just use the multiprocessing.pool.ThreadPool class as a drop-in replacement. def foo(bar, baz): print 'hello {0}'.format(bar) return 'foo' + baz from multiprocessing.pool import ThreadPool pool = ThreadPool(processes=1) async_result = pool.apply_async(foo, ('world', 'foo')) # tuple of args for foo # do some other stuff in the main process return_val = async_result.get() # get the return value from your function. </s>
<s>[INST] In Python, what does it mean if an object is subscriptable or not? Which types of objects fall into the domain of "subscriptable"? [/INST] It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes lists, tuples, and dictionaries. </s>
<s>[INST] Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)? I want to slice a NumPy nxn array. I want to extract an arbitrary selection of m rows and columns of that array (i.e. without any pattern in the numbers of rows/columns), making it a new, mxm array. For this example let us say the array is 4x4 and I want to extract a 2x2 array from it. Here is our array: from numpy import * x = range(16) x = reshape(x,(4,4)) print x [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] The line and columns to remove are the same. The easiest case is when I want to extract a 2x2 submatrix that is at the beginning or at the end, i.e. : In [33]: x[0:2,0:2] Out[33]: array([[0, 1], [4, 5]]) In [34]: x[2:,2:] Out[34]: array([[10, 11], [14, 15]]) But what if I need to remove another mixture of rows/columns? What if I need to remove the first and third lines/rows, thus extracting the submatrix [[5,7],[13,15]]? There can be any composition of rows/lines. I read somewhere that I just need to index my array using arrays/lists of indices for both rows and columns, but that doesn't seem to work: In [35]: x[[1,3],[1,3]] Out[35]: array([ 5, 15]) I found one way, which is: In [61]: x[[1,3]][:,[1,3]] Out[61]: array([[ 5, 7], [13, 15]]) First issue with this is that it is hardly readable, although I can live with that. If someone has a better solution, I'd certainly like to hear it. Other thing is I read on a forum that indexing arrays with arrays forces NumPy to make a copy of the desired array, thus when treating with large arrays this could become a problem. Why is that so / how does this mechanism work? [/INST] To answer this question, we have to look at how indexing a multidimensional array works in Numpy. Let's first say you have the array x from your question. The buffer assigned to x will contain 16 ascending integers from 0 to 15. If you access one element, say x[i,j], NumPy has to figure out the memory location of this element relative to the beginning of the buffer. This is done by calculating in effect i*x.shape[1]+j (and multiplying with the size of an int to get an actual memory offset). If you extract a subarray by basic slicing like y = x[0:2,0:2], the resulting object will share the underlying buffer with x. But what happens if you acces y[i,j]? NumPy can't use i*y.shape[1]+j to calculate the offset into the array, because the data belonging to y is not consecutive in memory. NumPy solves this problem by introducing strides. When calculating the memory offset for accessing x[i,j], what is actually calculated is i*x.strides[0]+j*x.strides[1] (and this already includes the factor for the size of an int): x.strides (16, 4) When y is extracted like above, NumPy does not create a new buffer, but it does create a new array object referencing the same buffer (otherwise y would just be equal to x.) The new array object will have a different shape then x and maybe a different starting offset into the buffer, but will share the strides with x (in this case at least): y.shape (2,2) y.strides (16, 4) This way, computing the memory offset for y[i,j] will yield the correct result. But what should NumPy do for something like z=x[[1,3]]? The strides mechanism won't allow correct indexing if the original buffer is used for z. NumPy theoretically could add some more sophisticated mechanism than the strides, but this would make element access relatively expensive, somehow defying the whole idea of an array. In addition, a view wouldn't be a really lightweight object anymore. This is covered in depth in the NumPy documentation on indexing. Oh, and nearly forgot about your actual question: Here is how to make the indexing with multiple lists work as expected: x[[[1],[3]],[1,3]] This is because the index arrays are broadcasted to a common shape. Of course, for this particular example, you can also make do with basic slicing: x[1::2, 1::2] </s>
<s>[INST] Python dictionary, how to keep keys/values in same order as declared? new to Python and had a question about dictionaries. I have a dictionary that I declared in a particular order and want to keep it in that order all the time. The keys/values can't really be kept in order based on their value, I just want it in the order that I declared it. So if I have the dictionary: d = {'ac':33, 'gw':20, 'ap':102, 'za':321, 'bs':10} It isn't in that order if I view it or iterate through it, is there any way to make sure Python will keep the explicit order that I declared the keys/values in? Using Python 2.6 [/INST] from collections import OrderedDict OrderedDict((word, True) for word in words) contains OrderedDict([('He', True), ('will', True), ('be', True), ('the', True), ('winner', True)]) If the values are True (or any other immutable object), you can also use: OrderedDict.fromkeys(words, True) </s>
<s>[INST] Django database query: How to filter objects by date range? I've got a field in one model like class Sample(models.Model): date = fields.DateField(auto_now=False) Now, I need to filter the objects by a data range, for example, all the objects that has date between 1 Jan 2011 to 31 Jan 2011? Thanks for your help! [/INST] Use Sample.objects.filter(date__range=["2011-01-01", "2011-01-31"]) Or if you are just trying to filter month wise: Sample.objects.filter(date__year='2011', date__month='01') Edit As lazerscience said, if you want a queryset which excludes the specified range ends you should consider his solution, which utilizes gt/lt (greater-than/less-than). </s>
<s>[INST] Compiling with cython and mingw produces gcc: error: unrecognized command line option '-mno-cygwin' I'm trying to compile a python extension with cython in win 7 64-bit using mingw (64-bit). I'm working with Python 2.6 (Active Python 2.6.6) and with the adequate distutils.cfg file (setting mingw as the compiler) When executing > C:\Python26\programas\Cython>python setup.py build_ext --inplace I get an error saying that gcc has not an -mno-cygwin option: > C:\Python26\programas\Cython>python setup.py build_ext --inplace running build_ext skipping 'hello2.c' Cython extension (up-to-date) building 'hello2' extension C:\mingw\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python26\include -IC:\Python26\PC -c hello2.c -o build\temp.win-amd64-2.6\Release\hello2.o gcc: error: unrecognized command line option '-mno-cygwin' error: command 'gcc' failed with exit status 1 gcc is: C:\>gcc --version gcc (GCC) 4.7.0 20110430 (experimental) Copyright (C) 2011 Free Software Foundation, Inc. How could I fix it? [/INST] It sounds like GCC 4.7.0 has finally removed the deprecated -mno-cygwin option, but distutils has not yet caught up with it. Either install a slightly older version of MinGW, or edit distutils\cygwinccompiler.py in your Python directory to remove all instances of -mno-cygwin. </s>
<s>[INST] Abstract methods in Python I am having trouble in using inheritance with Python. While the concept seems too easy for me in Java yet up till now I have been unable to understand in Python which is surprising to me at least. I have a prototype which follow: class Shape(): def __init__(self, shape_name): self.shape = shape_name class Rectangle(Shape): def __init__(self, name): self.shape = name In the above code how can I make an abstract method that would need to be implemented for all the subclasses? [/INST] Before abc was introduced you would see this frequently. class Base(object): def go(self): raise NotImplementedError("Please Implement this method") class Specialized(Base): def go(self): print "Consider me implemented" </s>
<s>[INST] Python - merge items of two lists into a list of tuples What's the pythonic way of achieving the following? list_a = [1, 2, 3, 4] list_b = [5, 6, 7, 8] #Need to create a of tuples from list_a and list_b list_c = [(1,5), (2,6), (3,7), (4,8)] Each member of list_c is a tuple, whose first member is from list_a and the second is from list_b. [/INST] >>> list_a = [1, 2, 3, 4] >>> list_b = [5, 6, 7, 8] >>> zip(list_a, list_b) [(1, 5), (2, 6), (3, 7), (4, 8)] </s>
<s>[INST] How to get indices of N maximum values in a numpy array? Numpy proposes a way to get the index of the maximum value of an array via np.argmax. I would like a similar thing, but returning the indexes of the N maximum values. For instance, if I have an array [1, 3, 2, 4, 5], it function(array, n=3) would return [4, 3, 1]. Thanks :) [/INST] Newer NumPy versions (1.8 and up) have a function called argpartition for this. To get the indices of the four largest elements, do >>> a array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0]) >>> ind = np.argpartition(a, -4)[-4:] >>> ind array([1, 5, 8, 0]) >>> a[ind] array([4, 9, 6, 9]) Unlike argsort, this function runs in linear time in the worst case, but the returned indices are not sorted, as can be seen from the result of evaluating a[ind]. If you need that too, sort them afterwards: >>> ind[np.argsort(a[ind])] array([1, 8, 5, 0]) To get the top-k elements in sorted order in this way takes O(n + k log k) time. </s>