text
stringlengths
185
26.5k
<s>[INST] Extracting text from HTML file using Python I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad. Update html2text looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean. Related questions: Filter out HTML tags and resolve entities in python Convert XML/HTML Entities into Unicode String in Python [/INST] NOTE: NTLK no longer supports clean_html function Original answer below. Use NLTK I wasted my 4-5 hours fixing the issues with html2text. Luckily i could encounter NLTK. It works magically. import nltk from urllib import urlopen url = "http://news.bbc.co.uk/2/hi/health/2284783.stm" html = urlopen(url).read() raw = nltk.clean_html(html) print(raw) </s>
<s>[INST] How Python web frameworks, WSGI and CGI fit together I have a Bluehost account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in .htaccess: Options +ExecCGI AddType text/html py AddHandler cgi-script .py Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining .htaccess commands). How are WSGI, CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say web.py or CherryPy) on my basic CGI configuration? How to install WSGI support? [/INST] How WSGI, CGI, and the frameworks are all connected ? Apache listens on port 80. It gets an HTTP request. It parses the request to find a way to respond. Apache has a LOT of choices for responding. One way to respond is to use CGI to run a script. Another way to respond is to simply serve a file. In the case of CGI, Apache prepares an environment and invokes the script through the CGI protocol. This is a standard Unix Fork/Exec situation -- the CGI subprocess inherits an OS environment including the socket and stdout. The CGI subprocess writes a response, which goes back to Apache; Apache sends this response to the browser. CGI is primitive and annoying. Mostly because it forks a subprocess for every request, and subprocess must exit or close stdout and stderr to signify end of response. WSGI is an interface that is based on the CGI design pattern. It is not necessarily CGI -- it does not have to fork a subprocess for each request. It can be CGI, but it doesn't have to be. WSGI adds to the CGI design pattern in several important ways. It parses the HTTP Request Headers for you and adds these to the environment. It supplies any POST-oriented input as a file-like object in the environment. It also provides you a function that will formulate the response, saving you from a lot of formatting details. What do I need to know / install / do if I want to run a web framework (say web.py or cherrypy) on my basic CGI configuration ? Recall that forking a subprocess is expensive. There are two ways to work around this. Embedded mod_wsgi or mod_python embeds Python inside Apache; no process is forked. Apache runs the Django application directly. Daemon mod_wsgi or mod_fastcgi allows Apache to interact with a separate daemon (or "long-running process"), using the WSGI protocol. You start your long-running Django process, then you configure Apache's mod_fastcgi to communicate with this process. Note that mod_wsgi can work in either mode: embedded or daemon. When you read up on mod_fastcgi, you'll see that Django uses flup to create a WSGI-compatible interface from the information provided by mod_fastcgi. The pipeline works like this. Apache -> mod_fastcgi -> FLUP (via FastCGI protocol) -> Django (via WSGI protocol) Django has several "django.core.handlers" for the various interfaces. For mod_fastcgi, Django provides a manage.py runfcgi that integrates FLUP and the handler. For mod_wsgi, there's a core handler for this. How to install WSGI support ? Follow these instructions. http://code.google.com/p/modwsgi/wiki/IntegrationWithDjango For background see this http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index </s>
<s>[INST] How can I get the source code of a Python function? Suppose I have a Python function as defined below: def foo(arg1,arg2): #do something with args a = arg1 + arg2 return a I can get the name of the function using foo.func_name. How can I programmatically get its source code, as I typed above? [/INST] If the function is from a source file available on the filesystem, then inspect.getsourcelines(foo) might be of help. I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code. </s>
<s>[INST] How to invoke the super constructor in Python? class A: def __init__(self): print "world" class B(A): def __init__(self): print "hello" B() hello In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect super(self) but this doesn't work [/INST] super() returns a parent-like object in new-style classes: class A(object): def __init__(self): print "world" class B(A): def __init__(self): print "hello" super(B, self).__init__() B() </s>
<s>[INST] Is "x < y < z" faster than "x < y and y < z"? From this page, we know that: Chained comparisons are faster than using the and operator. Write x < y < z instead of x < y and y < z. However, I got a different result testing the following code snippets: $ python -m timeit "x = 1.2" "y = 1.3" "z = 1.8" "x < y < z" 1000000 loops, best of 3: 0.322 usec per loop $ python -m timeit "x = 1.2" "y = 1.3" "z = 1.8" "x < y and y < z" 1000000 loops, best of 3: 0.22 usec per loop $ python -m timeit "x = 1.2" "y = 1.3" "z = 1.1" "x < y < z" 1000000 loops, best of 3: 0.279 usec per loop $ python -m timeit "x = 1.2" "y = 1.3" "z = 1.1" "x < y and y < z" 1000000 loops, best of 3: 0.215 usec per loop It seems that x < y and y < z is faster than x < y < z. Why? After searching some posts in this site (like this one) I know that "evaluated only once" is the key for x < y < z, however I'm still confused. To do further study, I disassembled these two functions using dis.dis: import dis def chained_compare(): x = 1.2 y = 1.3 z = 1.1 x < y < z def and_compare(): x = 1.2 y = 1.3 z = 1.1 x < y and y < z dis.dis(chained_compare) dis.dis(and_compare) And the output is: ## chained_compare ## 4 0 LOAD_CONST 1 (1.2) 3 STORE_FAST 0 (x) 5 6 LOAD_CONST 2 (1.3) 9 STORE_FAST 1 (y) 6 12 LOAD_CONST 3 (1.1) 15 STORE_FAST 2 (z) 7 18 LOAD_FAST 0 (x) 21 LOAD_FAST 1 (y) 24 DUP_TOP 25 ROT_THREE 26 COMPARE_OP 0 (<) 29 JUMP_IF_FALSE_OR_POP 41 32 LOAD_FAST 2 (z) 35 COMPARE_OP 0 (<) 38 JUMP_FORWARD 2 (to 43) >> 41 ROT_TWO 42 POP_TOP >> 43 POP_TOP 44 LOAD_CONST 0 (None) 47 RETURN_VALUE ## and_compare ## 10 0 LOAD_CONST 1 (1.2) 3 STORE_FAST 0 (x) 11 6 LOAD_CONST 2 (1.3) 9 STORE_FAST 1 (y) 12 12 LOAD_CONST 3 (1.1) 15 STORE_FAST 2 (z) 13 18 LOAD_FAST 0 (x) 21 LOAD_FAST 1 (y) 24 COMPARE_OP 0 (<) 27 JUMP_IF_FALSE_OR_POP 39 30 LOAD_FAST 1 (y) 33 LOAD_FAST 2 (z) 36 COMPARE_OP 0 (<) >> 39 POP_TOP 40 LOAD_CONST 0 (None) It seems that the x < y and y < z has less dissembled commands than x < y < z. Should I consider x < y and y < z faster than x < y < z? Tested with Python 2.7.6 on an Intel(R) Xeon(R) CPU E5640 @ 2.67GHz. [/INST] The difference is that in x < y < z y is only evaluated once. This does not make a large difference if y is a variable, but it does when it is a function call, which takes some time to compute. from time import sleep def y(): sleep(.2) return 1.3 %timeit 1.2 < y() < 1.8 10 loops, best of 3: 203 ms per loop %timeit 1.2 < y() and y() < 1.8 1 loops, best of 3: 405 ms per loop </s>
<s>[INST] Reducing Django Memory Usage. Low hanging fruit? My memory usage increases over time and restarting Django is not kind to users. I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful. I have a feeling that there are some simple steps that could produce big gains. Ensuring 'debug' is set to 'False' is an obvious biggie. Can anyone suggest others? How much improvement would caching on low-traffic sites? In this case I'm running under Apache 2.x with mod_python. I've heard mod_wsgi is a bit leaner but it would be tricky to switch at this stage unless I know the gains would be significant. Edit: Thanks for the tips so far. Any suggestions how to discover what's using up the memory? Are there any guides to Python memory profiling? Also as mentioned there's a few things that will make it tricky to switch to mod_wsgi so I'd like to have some idea of the gains I could expect before ploughing forwards in that direction. Edit: Carl posted a slightly more detailed reply here that is worth reading: http://stackoverflow.com/questions/488864/django-deployment-cutting-apaches-overhead Edit: Graham Dumpleton's article is the best I've found on the MPM and mod_wsgi related stuff. I am rather disappointed that no-one could provide any info on debugging the memory usage in the app itself though. Final Edit: Well I have been discussing this with Webfaction to see if they could assist with recompiling Apache and this is their word on the matter: "I really don't think that you will get much of a benefit by switching to an MPM Worker + mod_wsgi setup. I estimate that you might be able to save around 20MB, but probably not much more than that." So! This brings me back to my original question (which I am still none the wiser about). How does one go about identifying where the problems lies? It's a well known maxim that you don't optimize without testing to see where you need to optimize but there is very little in the way of tutorials on measuring Python memory usage and none at all specific to Django. Thanks for everyone's assistance but I think this question is still open! Another final edit ;-) I asked this on the django-users list and got some very helpful replies Honestly the last update ever! This was just released. Could be the best solution yet: Profiling Django object size and memory usage with Pympler [/INST] Make sure you are not keeping global references to data. That prevents the python garbage collector from releasing the memory. Don't use mod_python. It loads an interpreter inside apache. If you need to use apache, use mod_wsgi instead. It is not tricky to switch. It is very easy. mod_wsgi is way easier to configure for django than brain-dead mod_python. If you can remove apache from your requirements, that would be even better to your memory. spawning seems to be the new fast scalable way to run python web applications. EDIT: I don't see how switching to mod_wsgi could be "tricky". It should be a very easy task. Please elaborate on the problem you are having with the switch. </s>
<s>[INST] Check if multiple strings exist in another string How can I check if any of the strings in an array exists in another string? Like: a = ['a', 'b', 'c'] str = "a123" if a in str: print "some of the strings found in str" else: print "no strings found in str" That code doesn't work, it's just to show what I want to achieve. [/INST] You can use any: if any(x in str for x in a): Similarly to check if all the strings from the list are found, use all instead of any. </s>
<s>[INST] Why does ~True result in -2? In Python console: ~True Gives me: -2 Why? Can someone explain this particular case to me in binary? [/INST] What is int(True)? It is 1. 1 is: 00000001 and ~1 is: 11111110 Which is -2 in Two's complement1 1 Flip all the bits, add 1 to the resulting number and interpret the result as a binary representation of the magnitude and add a negative sign (since the number begins with 1): 11111110 → 00000001 → 00000010 ↑ ↑ Flip Add 1 Which is 2, but the sign is negative since the MSB is 1. Worth mentioning: Think about bool, you'll find that it's numeric in nature - It has two values, True and False, and they are just "customized" versions of the integers 1 and 0 that only print themselves differently. They are subclasses of the integer type int. So they behave exactly as 1 and 0, except that bool redefines str and repr to display them differently. >>> type(True) <class 'bool'> >>> isinstance(True, int) True >>> True == 1 True >>> True is 1 # they're still different objects False </s>
<s>[INST] Python -- return, return None, and no return at all Consider three functions: def my_func1(): print "Hello World" return None def my_func2(): print "Hello World" return def my_func3(): print "Hello World" They all appear to return None. Are there any differences between how the returned value of these functions behave? Are there any reasons to prefer one versus the other? [/INST] On the actual behavior, there is no difference. They all return None and that's it. However, there is a time and place for all of these. The following instructions are basically how the different methods should be used (or atleast how I was taught they should be used), but they are not absolute rules so you can mix them up if you feel necessary to. Using return None. This tells that the function is indeed meant to return a value for later use, and in this case it returns None. This value None can then be used elsewhere. return None is never used if there are no other possible return values from the function. In the following example, we return person's mother if the person given is a human. If it's not a human, we return None since the "person" doesn't have a mother (let's suppose it's not an animal or so). def get_mother(person): if is_human(person): return person.mother else: return None Using return. This is used for the same reason as break in loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even tho you don't need it that often. We got 15 prisoners and we know one of them has a knife. We loop through each prisoner one by one to check if they have a knife. If we hit the person with a knife, we can just exit the function cause we know there's only one knife and no reason the check rest of the prisoners. If we don't find the prisoner with a knife, we raise an the alert. This could be done in many different ways and using return is probably not even the best way, but it's just an example to show how to use return for exiting a function. def find_prisoner_with_knife(prisoners): for prisoner in prisoners: if "knife" in prisoner.items: prisoner.move_to_inquisition() return # no need to check rest of the prisoners nor raise an alert raise_alert() Note: You should never do var = find_prisoner_with_knife(), since the return value is not meant to be caught. Using no return at all. This will also return None, but that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as return in void functions in languages such as C++ or Java. In the following example, we set person's mother's name, and then the function exits after completing successfully. def set_mother(person, mother): if is_human(person): person.mother = mother Note: You should never do var = set_mother(my_person, my_mother), since the return value is not meant to be caught. </s>
<s>[INST] In practice, what are the main uses for the new "yield from" syntax in Python 3.3? I'm having a hard time wrapping my brain around PEP 380. What are the situations where "yield from" is useful? What is the classic use case? Why is it compared to micro-threads? [ update ] Now I understand the cause of my difficulties. I've used generators, but never really used coroutines (introduced by PEP-342). Despite some similarities, generators and coroutines are basically two different concepts. Understanding coroutines (not only generators) is the key to understanding the new syntax. IMHO coroutines are the most obscure Python feature, most books make it look useless and uninteresting. Thanks for the great answers, but special thanks to agf and his comment linking to David Beazley presentations. David rocks. [/INST] Let's get one thing out of the way first. The explanation that yield from g is equivalent to for v in g: yield v does not even begin to do justice to what yield from is all about. Because, let's face it, if all yield from does is expand the for loop, then it does not warrant adding yield from to the language and preclude a whole bunch of new features from being implemented in Python 2.x. Think of yield from as providing a transparent two-way channel from the caller to the sub-generator. That includes both getting data from and sending data to the sub-generator. BTW, if you are not sure what sending data to a generator even means, you need to drop everything and read about coroutines first. Dave Beazley's Curious Course on Couroutines is an excellent start. Read slides 24-33 for a quick primer. Reading data from a generator using yield from def reader(): """A generator that fakes a read from a file, socket, etc.""" for i in range(4): yield '<< %s' % i def reader_wrapper(g): # Manually iterate over data produced by reader for v in g: yield v wrap = reader_wrapper(reader()) for i in wrap: print(i) # Result << 0 << 1 << 2 << 3 Instead of manually iterating over reader(), we can just yield from it. def reader_wrapper(g): yield from g That works, and we eliminated one line of code. And probably the intent is a little bit clearer (or not). But nothing life changing. Sending data to a generator (coroutine) using yield from - Part 1 Now let's do something more interesting. Let's create a coroutine called writer that accepts data sent to it and writes to a socket, fd, etc. def writer(): """A coroutine that writes data *sent* to it to fd, socket, etc.""" while True: w = (yield) print('>> ', w) Now the question is, how should the wrapper function handle sending data to the writer, so that any data that is sent to the wrapper is transparently sent to the writer()? def writer_wrapper(coro): # TBD pass w = writer() wrap = writer_wrapper(w) wrap.send(None) # "prime" the coroutine for i in range(4): wrap.send(i) # Expected result >> 0 >> 1 >> 2 >> 3 The wrapper needs to accept the data that is sent to it (obviously) and should also handle the StopIteration when the for loop is exhausted. Evidently just doing for x in coro: yield x won't do. Here is a version that works. def writer_wrapper(coro): coro.send(None) # prime the coro while True: try: x = (yield) # Capture the value that's sent coro.send(x) # and pass it to the writer except StopIteration: pass Or, we could do this. def writer_wrapper(coro): yield from coro That saves 6 lines of code, make it much much more readable and it just works. Magic! Sending data to a generator yield from - Part 2 - Exception handling Let's make it more complicated. What if our writer needs to handle exceptions? Let's say the writer handles a SpamException and it prints *** if it encounters one. class SpamException(Exception): pass def writer(): while True: try: w = (yield) except SpamException: print('***') else: print('>> ', w) What if we don't change writer_wrapper? Does it work? Let's try # writer_wrapper same as above w = writer() wrap = writer_wrapper(w) wrap.send(None) # "prime" the coroutine for i in [0, 1, 2, 'spam', 4]: if i == 'spam': wrap.throw(SpamException) else: wrap.send(i) # Expected Result >> 0 >> 1 >> 2 *** >> 4 # Actual Result >> 0 >> 1 >> 2 Traceback (most recent call last): ... redacted ... File ... in writer_wrapper x = (yield) __main__.SpamException Um, it's not working because x = (yield) just raises the exception and everything comes to a crashing halt. Let's make it work, but manually handling exceptions and sending them or throwing them into the sub-generator (writer) def writer_wrapper(coro): """Works. Manually catches exceptions and throws them""" coro.send(None) # prime the coro while True: try: try: x = (yield) except Exception as e: # This catches the SpamException coro.throw(e) else: coro.send(x) except StopIteration: pass This works. # Result >> 0 >> 1 >> 2 *** >> 4 But so does this! def writer_wrapper(coro): yield from coro The yield from transparently handles sending the values or throwing values into the sub-generator. This still does not cover all the corner cases though. What happens if the outer generator is closed? What about the case when the sub-generator returns a value (yes, in python 3, generators can return values), how should the return value be propagated? All the corner cases that yield from handles transparently is really impressive. yield from just magically works and handles all those cases. I personally feel yield from is a poor keyword choice because it does not make the two-way nature apparent. There were other keywords proposed (like delegate but were rejected because adding a new keyword to the language is much more difficult than combining existing ones. In summary, its best to think of yield from as a transparent two way channel between the caller and the sub-generator. References: PEP 380 - Syntax for delegating to a sub-generator (Ewing) [v3.3, 2009-02-13] PEP 342 - Coroutines via Enhanced Generators (GvR, Eby) [v2.5, 2005-05-10] </s>
<s>[INST] django import error - No module named core.management Ok, I see plenty of these errors around. I have tried everything I know to do and have yet to figure this out. I am working on a development server running python 2.5 and Django 1.3. Django 1.3 was installed using python setup.py install after unpacking the tar.gz download. All works well, I seldom have the need to run manage.py but am trying to use the new staticfiles app and am running into problems. python manage.py collectstatic Traceback (most recent call last): File "manage.py", line 2, in <module> from django.core.management import execute_manager ImportError: No module named core.management Ok, so I have PATH issue. From Django install I double check my site-packages directory. python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" /usr/lib/python2.5/site-packages Ok, let's check out what I have, echo $PYTHON_PATH was empty, so I set it export PYTHON_PATH=/usr/lib/python2.5/site-packages/django Still no luck. Lets check what sys.path has to say >>> import sys >>> print sys.path ['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/django', '/var/lib/python-support/python2.5'] path is there, I even created /usr/lib/python2.5/site-packages/django.pth with contents cat /usr/lib/python2.5/site-packages/django.pth /usr/lib/python2.5/site-packages/django/ Anyone got an clues to what is going on here? I found a symlink further up the path that was getting in the way, but no on to a new error. python manage.py collectstatic Traceback (most recent call last): File "manage.py", line 14, in <module> execute_manager(settings) File "/usr/lib/python2.5/site-packages/django/core/management/__init__.py", line 438, in execute_manager utility.execute() File "/usr/lib/python2.5/site-packages/django/core/management/__init__.py", line 349, in execute version=get_version(), File "/usr/lib/python2.5/site-packages/django/__init__.py", line 12, in get_version from django.utils.version import get_svn_revision ImportError: No module named utils.version I also tried creating a new project to see if there were any issues there and get the same utils.version error. Side node: Unode from #django helped me a bit, set up virtualenv on same machine and got past the errors so still not sure what is up with this actual install here, but it seems to not be in the django projects but in the django/python install. [/INST] If, like me, you are running your django in a virtualenv, and getting this error, look at your manage.py. The first line should define the python executable used to run the script. This should be the path to your virtualenv's python, but it is something wrong like /usr/bin/python, which is not the same path and will use the global python environment (and packages will be missing). Just change the path into the path to the python executable in your virtualenv. You can also replace your shebang line with #!/usr/bin/env python. This should use the proper python environment and interpreter provided that you activate your virtualenv first (I assume you know how to do this). </s>
<s>[INST] How to use Python to login to a webpage and retrieve cookies for later usage? I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response header and store them so I can use them in the request to download the webpage /data.php. How would I do this in python (preferably 2.6)? If possible I only want to use builtin modules. [/INST] import urllib, urllib2, cookielib username = 'myuser' password = 'mypassword' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login_data = urllib.urlencode({'username' : username, 'j_password' : password}) opener.open('http://www.example.com/login.php', login_data) resp = opener.open('http://www.example.com/hiddenpage.php') print resp.read() resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie. </s>
<s>[INST] Standard way to embed version into python package? Is there a standard way to associate version string with a python package in such way that I could do the following? import foo print foo.version I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in setup.py already. Alternative solution that I found was to have import __version__ in my foo/__init__.py and then have __version__.py generated by setup.py. [/INST] Here is how I do this. Advantages of the following method: It provides a __version__ attribute. It provides the standard metadata version. Therefore it will be detected by pkg_resources or other tools that parse the package metadata (EGG-INFO and/or PKG-INFO, PEP 0345). It doesn't import your package (or anything else) when building your package, which can cause problems in some situations. (See the comments below about what problems this can cause.) There is only one place that the version number is written down, so there is only one place to change it when the version number changes, and there is less chance of inconsistent versions. Here is how it works: the "one canonical place" to store the version number is a .py file, named "_version.py" which is in your Python package, for example in myniftyapp/_version.py. This file is a Python module, but your setup.py doesn't import it! (That would defeat feature 3.) Instead your setup.py knows that the contents of this file is very simple, something like: __version__ = "3.6.5" And so your setup.py opens the file and parses it, with code like: import re VERSIONFILE="myniftyapp/_version.py" verstrline = open(VERSIONFILE, "rt").read() VSRE = r"^__version__ = ['\"]([^'\"]*)['\"]" mo = re.search(VSRE, verstrline, re.M) if mo: verstr = mo.group(1) else: raise RuntimeError("Unable to find version string in %s." % (VERSIONFILE,)) Then your setup.py passes that string as the value of the "version" argument to setup(), thus satisfying feature 2. To satisfy feature 1, you can have your package (at run-time, not at setup time!) import the _version file from myniftyapp/__init__.py like this: from _version import __version__ Here is an example of this technique that I've been using for years. The code in that example is a bit more complicated, but the simplified example that I wrote into this comment should be a complete implementation. Here is example code of importing the version. If you see anything wrong with this approach, please let me know: zooko at zooko dot com. If you don't see anything wrong with this approach then use it! Because the more packages come with their version numbers in the expected places the better! </s>
<s>[INST] Ruby equivalent of virtualenv? Is there something similar to the Python utility virtualenv? Basically it allows you to install Python packages into a sandboxed environment, so easy_install django doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory. For example: $ virtualenv test New python executable in test/bin/python Installing setuptools...cd .........done. $ cd test/ $ source bin/activate (test)$ easy_install tvnamer Searching for tvnamer Best match: tvnamer 0.5.1 Processing tvnamer-0.5.1-py2.5.egg Adding tvnamer 0.5.1 to easy-install.pth file Installing tvnamer script to /Users/dbr/test/bin Using /Library/Python/2.5/site-packages/tvnamer-0.5.1-py2.5.egg Processing dependencies for tvnamer Finished processing dependencies for tvnamer (test)$ which tvnamer /Users/dbr/test/bin/tvnamer Is there something like this for RubyGems? [/INST] RVM works closer to how virtualenv works since it lets you sandbox different ruby versions and their gems, etc. </s>
<s>[INST] Python strftime - date without leading 0? When using Python strftime, is there a way to remove the first 0 of the date if it's before the 10th, ie. so 01 is 1? Can't find a %thingy for that? Thanks! [/INST] Actually I had the same problem and I realized that, if you add a hyphen between the % and the letter, you can remove the leading zero. For example %Y/%-m/%-d. Only works on Unix (Linux, OS X). Doesn't work in Windows (including Cygwin). </s>
<s>[INST] How to get a random number between a float range? (Python) randrange(start, stop) only takes integer arguments... So how would I get a random number between two float values? [/INST] Use random.uniform(a, b): >>> random.uniform(1.5, 1.9) 1.8733202628557872 </s>
<s>[INST] Creating a range of dates in Python I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this? import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList [/INST] Marginally better... base = datetime.datetime.today() date_list = [base - datetime.timedelta(days=x) for x in range(0, numdays)] </s>
<s>[INST] How to remove convexity defects in a Sudoku square? I was doing a fun project: Solving a Sudoku from an input image using OpenCV (as in Google goggles etc). And I have completed the task, but at the end I found a little problem for which I came here. I did the programming using Python API of OpenCV 2.3.1. Below is what I did : Read the image Find the contours Select the one with maximum area, ( and also somewhat equivalent to square). Find the corner points. e.g. given below: (Notice here that the green line correctly coincides with the true boundary of the Sudoku, so the Sudoku can be correctly warped. Check next image) warp the image to a perfect square eg image: Perform OCR ( for which I used the method I have given in Simple Digit Recognition OCR in OpenCV-Python ) And the method worked well. Problem: Check out this image. Performing the step 4 on this image gives the result below: The red line drawn is the original contour which is the true outline of sudoku boundary. The green line drawn is approximated contour which will be the outline of warped image. Which of course, there is difference between green line and red line at the top edge of sudoku. So while warping, I am not getting the original boundary of the Sudoku. My Question : How can I warp the image on the correct boundary of the Sudoku, i.e. the red line OR how can I remove the difference between red line and green line? Is there any method for this in OpenCV? [/INST] I have a solution that works, but you'll have to translate it to OpenCV yourself. It's written in Mathematica. The first step is to adjust the brightness in the image, by dividing each pixel with the result of a closing operation: src = ColorConvert[Import["http://davemark.com/images/sudoku.jpg"], "Grayscale"]; white = Closing[src, DiskMatrix[5]]; srcAdjusted = Image[ImageData[src]/ImageData[white]] The next step is to find the sudoku area, so I can ignore (mask out) the background. For that, I use connected component analysis, and select the component that's got the largest convex area: components = ComponentMeasurements[ ColorNegate@Binarize[srcAdjusted], {"ConvexArea", "Mask"}][[All, 2]]; largestComponent = Image[SortBy[components, First][[-1, 2]]] By filling this image, I get a mask for the sudoku grid: mask = FillingTransform[largestComponent] Now, I can use a 2nd order derivative filter to find the vertical and horizontal lines in two separate images: lY = ImageMultiply[MorphologicalBinarize[GaussianFilter[srcAdjusted, 3, {2, 0}], {0.02, 0.05}], mask]; lX = ImageMultiply[MorphologicalBinarize[GaussianFilter[srcAdjusted, 3, {0, 2}], {0.02, 0.05}], mask]; I use connected component analysis again to extract the grid lines from these images. The grid lines are much longer than the digits, so I can use caliper length to select only the grid lines-connected components. Sorting them by position, I get 2x10 mask images for each of the vertical/horizontal grid lines in the image: verticalGridLineMasks = SortBy[ComponentMeasurements[ lX, {"CaliperLength", "Centroid", "Mask"}, # > 100 &][[All, 2]], #[[2, 1]] &][[All, 3]]; horizontalGridLineMasks = SortBy[ComponentMeasurements[ lY, {"CaliperLength", "Centroid", "Mask"}, # > 100 &][[All, 2]], #[[2, 2]] &][[All, 3]]; Next I take each pair of vertical/horizontal grid lines, dilate them, calculate the pixel-by-pixel intersection, and calculate the center of the result. These points are the grid line intersections: centerOfGravity[l_] := ComponentMeasurements[Image[l], "Centroid"][[1, 2]] gridCenters = Table[centerOfGravity[ ImageData[Dilation[Image[h], DiskMatrix[2]]]* ImageData[Dilation[Image[v], DiskMatrix[2]]]], {h, horizontalGridLineMasks}, {v, verticalGridLineMasks}]; The last step is to define two interpolation functions for X/Y mapping through these points, and transform the image using these functions: fnX = ListInterpolation[gridCenters[[All, All, 1]]]; fnY = ListInterpolation[gridCenters[[All, All, 2]]]; transformed = ImageTransformation[ srcAdjusted, {fnX @@ Reverse[#], fnY @@ Reverse[#]} &, {9*50, 9*50}, PlotRange -> {{1, 10}, {1, 10}}, DataRange -> Full] All of the operations are basic image processing function, so this should be possible in OpenCV, too. The spline-based image transformation might be harder, but I don't think you really need it. Probably using the perspective transformation you use now on each individual cell will give good enough results. </s>
<s>[INST] Python if not == vs if != What is the difference between these two lines of code: if not x == 'val': and if x != 'val': Is one more efficient than the other? Would it be better to use if x == 'val': pass else: [/INST] Using dis to look at the bytecode generated for the two versions: not == 4 0 LOAD_FAST 0 (foo) 3 LOAD_FAST 1 (bar) 6 COMPARE_OP 2 (==) 9 UNARY_NOT 10 RETURN_VALUE != 4 0 LOAD_FAST 0 (foo) 3 LOAD_FAST 1 (bar) 6 COMPARE_OP 3 (!=) 9 RETURN_VALUE The latter has fewer operations, and is therefore likely to be slightly more efficient. It was pointed out in the commments (thanks, @Quincunx) that where you have if foo != bar vs. if not foo == bar the number of operations is exactly the same, it's just that the COMPARE_OP changes and POP_JUMP_IF_TRUE switches to POP_JUMP_IF_FALSE: not ==: 2 0 LOAD_FAST 0 (foo) 3 LOAD_FAST 1 (bar) 6 COMPARE_OP 2 (==) 9 POP_JUMP_IF_TRUE 16 != 2 0 LOAD_FAST 0 (foo) 3 LOAD_FAST 1 (bar) 6 COMPARE_OP 3 (!=) 9 POP_JUMP_IF_FALSE 16 In this case, unless there was a difference in the amount of work required for each comparison, it's unlikely you'd see any performance difference at all. However, note that the two versions won't always be logically identical, as it will depend on the implementations of __eq__ and __ne__ for the objects in question. Per the data model documentation: There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. For example: >>> class Dummy(object): def __eq__(self, other): return True def __ne__(self, other): return True >>> not Dummy() == Dummy() False >>> Dummy() != Dummy() True Finally, and perhaps most importantly: in general, where the two are logically identical, x != y is much more readable than not x == y. </s>
<s>[INST] Why do you have to call .iteritems() when iterating over a dictionary in python? Why do you have to call iteritems() to iterate over key, value pairs in a dictionary? ie dic = {'one':'1', 'two':'2'} for k, v in dic.iteritems(): print k, v Why isn't that the default behavior of iterating over a dictionary for k, v in dic: print k, v [/INST] For every python container C, the expectation is that for item in C: assert item in C will pass just fine -- wouldn't you find it astonishing if one sense of in (the loop clause) had a completely different meaning from the other (the presence check)? I sure would! It naturally works that way for lists, sets, tuples, ... So, when C is a dictionary, if in were to yield key/value tuples in a for loop, then, by the principle of least astonishment, in would also have to take such a tuple as its left-hand operand in the containment check. How useful would that be? Pretty useless indeed, basically making if (key, value) in C a synonym for if C.get(key) == value -- which is a check I believe I may have performed, or wanted to perform, 100 times more rarely than what if k in C actually means, checking the presence of the key only and completely ignoring the value. On the other hand, wanting to loop just on keys is quite common, e.g.: for k in thedict: thedict[k] += 1 having the value as well would not help particularly: for k, v in thedict.items(): thedict[k] = v + 1 actually somewhat less clear and less concise. (Note that items was the original spelling of the "proper" methods to use to get key/value pairs: unfortunately that was back in the days when such accessors returned whole lists, so to support "just iterating" an alternative spelling had to be introduced, and iteritems it was -- in Python 3, where backwards compatibility constraints with previous Python versions were much weakened, it became items again). </s>
<s>[INST] Define css class in django Forms Assume I have a form class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page? I was hoping not to have to manually build the form. [/INST] Yet another solution that doesn't require changes in python code and so is better for designers and one-off presentational changes: django-widget-tweaks. Hope somebody will find it useful. </s>
<s>[INST] Python format timedelta to string I'm a Python newbie (2 weeks) and I'm having trouble formatting a datetime.timedelta object. Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes. I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes. By the way, I'm using Google AppEngine with Django Templates for presentation. If anyone can help or knows of a better way to resolve this, I would be very happy. Thanks, [/INST] You can just convert the timedelta to a string with str(). Here's an example: import datetime start = datetime.datetime(2009,2,10,14,00) end = datetime.datetime(2009,2,10,16,00) delta = end-start print str(delta) # prints 2:00:00 </s>
<s>[INST] How do I modify a text file in Python? I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that? [/INST] Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it. This is an operating system thing, not a Python thing. It is the same in all languages. What I usually do is read from the file, make the modifications and write it out to a new file called myfile.txt.tmp or something like that. This is better than reading the whole file into memory because the file may be too large for that. Once the temporary file is completed, I rename it the same as the original file. This is a good, safe way to do it because if the file write crashes or aborts for any reason, you still have your untouched original file. </s>
<s>[INST] Best programming aids for a quadriplegic programmer Before you jump to conclusions, yes, this is programming related. It covers a situation that comes under the heading of, "There, but for the grace of God, go you or I." This is brand new territory for me so I'm asking for some serious help here. A young man, Honza Ripa, in a nearby town did the classic Dumb Thing two weeks after graduating from High School -- he dove into shallow water in the Russian River and had a C-4/C-5 break, sometimes called a Swimming Pool break. In a matter of seconds he went from an exceptional golfer and wrestler to a quadriplegic. (Read the story ... all of us should have been so lucky as to have a girlfriend like Brianna.) That was 10 months ago and he has regained only tiny amounts of control of his right index finger and a couple of other hand/foot motions, none of them fine-grained. His total control of his computer (currently running Win7, but we can change that as needed) is via voice command. Honza's not dumb. He had a 3.7 GPA with AP math and physics. The Problems: Since all of his input is via voice command, he is concerned that the predominance of special characters in programming will require vast amount of verbose commands. Does anyone know of any well done voice input system specifically designed for programmers? I'm thinking about something that might be modal--e.g. you say "Python input" and it goes into a macro mode for doing class definitions, etc. Given all of the RSI in programmer-land there's got to be something out there. What OS(es) does it run on? I am planning on teaching him Python, which is my preferred language for programming and teaching. Are there any applications / whatevers that are written in Python and would be a particularly good match for engaging him mentally while supporting his disability? One of his expressed interests is in stock investing, but that not might be a good starting point for a brand-new programmer. There are a lot of environments (Flash, JavaScript, etc) that are not particularly friendly to people with accessibility challenges. I vaguely remember (but cannot find) a research project that basically created an overlay system on top of a screen environment and then allowed macro command construction on top of the screen image. If we can get/train this system, we may be able to remove many hurdles to using the net. I am particularly interested in finding open source Python-based robotics and robotic prostheses projects so that he can simultaneously learn advanced programming concepts while learning to solve some of his own immediate problems. I've done a ton of googling on this, but I know there are things I'm missing. I'm asking the SO community to step up to the plate here. I know this group has the answers, so let me hear them! Overwhelm me with the opportunities that any of us might have/need to still program after such a life-changing event. Update: I just registered computingforquads.org and I'll be creating pages for all sorts of solutions to all sorts of problems. Thanks for you help so far and keep those answers coming! [/INST] I have sports injuries, and I cannot type more than few characters without serious pain. Instead, I use emacs together with Dragon NaturallySpeaking. I have written macros and scripts to help it get by. The system is not perfect, but it works. I program mostly in C++, but I also use python. If you want to, I will help you with that. I have to warn you, it takes few months to get used to speech to text software and train it. moreover, I am not native English speaker, am sure that gets in the way Do not despair, there are solutions. here a link to emacs and Dragon files (unfortunately have not documented yet) http://code.google.com/p/asadchev/source/browse/#svn/trunk/home/Dragon http://code.google.com/p/asadchev/source/browse/#svn/trunk/emacs/elisp also, if you need more info, my number is 515 230 9363 (United States, Iowa). I will be glad to help you if I can </s>
<s>[INST] Can't pickle <type 'instancemethod'> when using python's multiprocessing Pool.map() I'm trying to use multiprocessing's Pool.map() function to divide out work simultaneously. When I use the following code, it works fine: import multiprocessing def f(x): return x*x def go(): pool = multiprocessing.Pool(processes=4) print pool.map(f, range(10)) if __name__== '__main__' : go() However, when I use it in a more object-oriented approach, it doesn't work. The error message it gives is: PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed This occurs when the following is my main program: import someClass if __name__== '__main__' : sc = someClass.someClass() sc.go() and the following is my someClass class: import multiprocessing class someClass(object): def __init__(self): pass def f(self, x): return x*x def go(self): pool = multiprocessing.Pool(processes=4) print pool.map(self.f, range(10)) Anyone know what the problem could be, or an easy way around it? [/INST] The problem is that multiprocessing must pickle things to sling them among processes, and bound methods are not picklable. The workaround (whether you consider it "easy" or not;-) is to add the infrastructure to your program to allow such methods to be pickled, registering it with the copy_reg standard library method. For example, Steven Bethard's contribution to this thread (towards the end of the thread) shows one perfectly workable approach to allow method pickling/unpickling via copy_reg. </s>
<s>[INST] Why do you need explicitly have the "self" argument into a Python method? When defining a method on a class in Python, it looks something like this: class MyClass(object): def __init__(self, x, y): self.x = x self.y = y But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument? [/INST] I like to quote Peters' Zen of Python. "Explicit is better than implicit." In Java and C++, 'this.' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't. Python elects to make things like this explicit rather than based on a rule. Additionally, since nothing is implied or assumed, parts of the implementation are exposed. self.__class__, self.__dict__ and other "internal" structures are available in an obvious way. </s>
<s>[INST] Using Python 3 in virtualenv Using virtualenv, I run my projects with the default version of Python (2.7). On one project, I need to use Python 3.4. I used brew install python3 to install it on my Mac. Now, how do I create a virtualenv that uses the new version? e.g. sudo virtualenv envPython3 If I try: virtualenv -p python3 test I get: Running virtualenv with interpreter /usr/local/bin/python3 Using base prefix '/usr/local/Cellar/python3/3.4.0_1/Frameworks/Python.framework/Versions/3.4' New python executable in test/bin/python3.4 Also creating executable in test/bin/python Failed to import the site module Traceback (most recent call last): File "/Users/user/Documents/workspace/test/test/bin/../lib/python3.4/site.py", line 67, in <module> import os File "/Users/user/Documents/workspace/test/test/bin/../lib/python3.4/os.py", line 634, in <module> from _collections_abc import MutableMapping ImportError: No module named '_collections_abc' ERROR: The executable test/bin/python3.4 is not functioning ERROR: It thinks sys.prefix is '/Users/user/Documents/workspace/test' (should be '/Users/user/Documents/workspace/test/test') ERROR: virtualenv is not compatible with this system or executable [/INST] simply run virtualenv -p python3 envname Update after OP's edit: There was a bug in the OP's version of virtualenv, as described here. The problem was fixed by running: pip install --upgrade virtualenv </s>
<s>[INST] Print in one line dynamically I would like to make several statements that give standard output without seeing newlines in between statements. Specifically, suppose I have: for item in range(1,100): print item The result is: 1 2 3 4 . . . How get this to instead look like: 1 2 3 4 5 ... Even better, is it possible to print the single number over the last number, so only one number is on the screen at a time? [/INST] Change print item to: print item, in Python 2.7 print(item, end=" ") in Python 3 </s>
<s>[INST] Python: Run function from the command line I have below code in my file: def hello(): return 'Hi :)' How would I run this from the command line? [/INST] With the -c (command) argument (assuming your file is named foo.py): $ python -c 'import foo; print foo.hello()' Alternatively, if you don't care about namespace pollution: $ python -c 'from foo import *; print hello()' And the middle ground: $ python -c 'from foo import hello; print hello()' </s>
<s>[INST] How do I get the path of the current executed file in Python? This may seem like a newbie question, but it is not. Some common approaches don't work in all cases: sys.argv[0] This means using path = os.path.abspath(os.path.dirname(sys.argv[0])), but this does not work if you are running from another Python script in another directory, and this can happen in real life. __file__ This means using path = os.path.abspath(os.path.dirname(__file__)), but I found that this doesn't work: py2exe doesn't have a __file__ attribute, but there is a workaround When you run from IDLE with execute() there is no __file__ attribute OS X 10.6 where I get NameError: global name '__file__' is not defined Related questions with incomplete answers: Python - Find Path to File Being Run Path to current file depends on how I execute the program How to know the path of the running script in Python? Change directory to the directory of a Python script I'm looking for a generic solution, one that would work in all above use cases. Update Here is the result of a testcase: Output of python a.py (on Windows) a.py: __file__= a.py a.py: os.getcwd()= C:\zzz b.py: sys.argv[0]= a.py b.py: __file__= a.py b.py: os.getcwd()= C:\zzz a.py #! /usr/bin/env python import os, sys print "a.py: sys.argv[0]=", sys.argv[0] print "a.py: __file__=", __file__ print "a.py: os.getcwd()=", os.getcwd() print execfile("subdir/b.py") subdir/b.py #! /usr/bin/env python import os, sys print "b.py: sys.argv[0]=", sys.argv[0] print "b.py: __file__=", __file__ print "b.py: os.getcwd()=", os.getcwd() print tree C:. | a.py \---subdir b.py [/INST] You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory. However, you can reliably determine the location of a module, since modules are always loaded from a file. If you create a module with the following code and put it in the same directory as your main script, then the main script can import the module and use that to locate itself. some_path/module_locator.py: def we_are_frozen(): # All of the modules are built-in to the interpreter, e.g., by py2exe return hasattr(sys, "frozen") def module_path(): encoding = sys.getfilesystemencoding() if we_are_frozen(): return os.path.dirname(unicode(sys.executable, encoding)) return os.path.dirname(unicode(__file__, encoding)) some_path/main.py: import module_locator my_path = module_locator.module_path() If you have several main scripts in different directories, you may need more than one copy of module_locator. Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool. </s>
<s>[INST] Python code to pick out all possible combinations from a list? I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers. I've found some code (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary of using it. Plus I have a feeling there must be a more elegant solution. The only thing that occurs to me would be to just loop through the decimal integers 1-32768 and convert those to binary, and use the binary representation as a filter to pick out the appropriate numbers. Does anyone know of a better way? Using map(), maybe? [/INST] This answer missed one aspect: the OP asked for ALL combinations... not just combinations of length "r". So you'd either have to loop through all lengths "L": import itertools stuff = [1, 2, 3] for L in range(0, len(stuff)+1): for subset in itertools.combinations(stuff, L): print(subset) Or -- if you want to get snazzy (or bend the brain of whoever reads your code after you) -- you can generate the chain of "combinations()" generators, and iterate through that: from itertools import chain, combinations def all_subsets(ss): return chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1))) for subset in all_subsets(stuff): print(subset) </s>
<s>[INST] Python vs Cpython What's all this fuss about Python and CPython (Jython,IronPython), I don't get it: python.org mentions that CPython is: The "traditional" implementation of Python (nicknamed CPython) yet another Stack Overflow question mentions that: CPython is the default byte-code interpreter of Python, which is written in C. Honestly I don't get what both of those explanations practically mean but what I thought was that, if I use CPython does that mean when I run a sample python code, it compiles it to C language and then executes it as if it were C code So what exactly is CPython and how does it differ when compared with python and should I probably use CPython over Python and if so what are its advantages? [/INST] So what is CPython CPython is the original Python implementation. It is the implementation you download from Python.org. People call it CPython to distinguish it from other, later, Python implementations, and to distinguish the implementation of the language engine from the Python programming language itself. The latter part is where your confusion comes from; you need to keep Python-the-language separate from whatever runs the Python code. CPython happens to be implemented in C. That is just an implementation detail really. CPython compiles your python code into bytecode (transparently) and interprets that bytecode in a evaluation loop. CPython is also the first to implement new features; Python-the-language development uses CPython as the base, other implementations follow. What about Jython, etc. Jython, IronPython and PyPy are the current 'other' implementations of the Python programming language; these are implemented in Java, C# and RPython (a subset of Python), respectively. Jython compiles your Python code to Java bytecode, so your Python code can run on the JVM. IronPython lets you run Python on the Microsoft CLR. And PyPy, being implemented in (a subset of) Python, lets you run Python code faster than CPython, which rightly should blow your mind. :-) Actually compiling to C So CPython does not translate your Python code to C by itself. It instead runs a interpreter loop. There is a project that does translate Python-ish code to C, and that is called Cython. Cython adds a few extensions to the Python language, and lets you compile your code to C extensions, code that plugs into the CPython interpreter. </s>
<s>[INST] How do I copy a string to the clipboard on Windows using Python? I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python? [/INST] Actually, pywin32 and ctypes seem to be an overkill for this simple task. Tkinter is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff. If all you need is to put some text to system clipboard, this will do it: from Tkinter import Tk r = Tk() r.withdraw() r.clipboard_clear() r.clipboard_append('i can has clipboardz?') r.destroy() And that's all, no need to mess around with platform-specific third-party libraries. </s>
<s>[INST] Cross-platform way of getting temp directory in Python Is there a cross-platform way of getting the path to the temp directory in Python 2.6? For example, under Linux that would be /tmp, while under XP C:\Documents and settings\[user]\Application settings\Temp. Thanks! [/INST] That would be the tempfile module. It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed. Example: import tempfile print tempfile.gettempdir() # prints the current temporary directory f = tempfile.TemporaryFile() f.write('something on temporaryfile') f.seek(0) # return to beginning of file print f.read() # reads data back from the file f.close() # temporary file is automatically deleted here For completeness, here's how it searches for the temporary directory, according to the documentation: The directory named by the TMPDIR environment variable. The directory named by the TEMP environment variable. The directory named by the TMP environment variable. A platform-specific location: On RiscOS, the directory named by the Wimp$ScrapDir environment variable. On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order. On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order. As a last resort, the current working directory. </s>
<s>[INST] How do I check if a string is unicode or ascii? What do I have to do in Python to figure out which encoding? [/INST] In Python 3, all strings are sequences of Unicode characters. There is a bytes type that holds raw bytes. In Python 2, a string may be of type str or of type unicode. You can tell which using code something like this: def whatisthis(s): if isinstance(s, str): print "ordinary string" elif isinstance(s, unicode): print "unicode string" else: print "not a string" </s>
<s>[INST] Can I force pip to reinstall the current version? I've come across situations where a current version of a package seems not to be working and requires reinstallation. But pip install -U won't touch a package that is already up-to-date. I see how to force a reinstallation by first uninstalling (with pip uninstall) and then installing, but is there a way to simply force an "update" to a nominally current version in a single step? [/INST] --force-reinstall When upgrading, reinstall all packages even if they are already up-to-date. -I, --ignore-installed Ignore the installed packages (reinstalling instead). </s>
<s>[INST] Iterate over model instance field names and values in template I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose_name specifically if specified on the field) in the first column and the value of that field in the second column. For example, let's say we have the following model definition: class Client(Model): name = CharField(max_length=150) email = EmailField(max_length=100, verbose_name="E-mail") I would want it to be output in the template like so (assume an instance with the given values): Field Name Field Value ---------- ----------- Name Wayne Koorts E-mail waynes@email.com What I'm trying to achieve is being able to pass an instance of the model to a template and be able to iterate over it dynamically in the template, something like this: <table> {% for field in fields %} <tr> <td>{{ field.name }}</td> <td>{{ field.value }}</td> </tr> {% endfor %} </table> Is there a neat, "Django-approved" way to do this? It seems like a very common task, and I will need to do it often for this particular project. [/INST] model._meta.get_all_field_names() will give you all the model's field names, then you can use model._meta.get_field() to work your way to the verbose name, and getattr(model_instance, 'field_name') to get the value from the model. NOTE: model._meta.get_all_field_names() is deprecated in django 1.9. Instead use model._meta.get_fields() to get the model's fields and field.name to get each field name. </s>
<s>[INST] How can I explicitly free memory in Python? I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is: read an input file process the file and create a list of triangles, represented by their vertices output the vertices in the OFF format: a list of vertices followed by a list of triangles. The triangles are represented by indices into the list of vertices The requirement of OFF that I print out the complete list of vertices before I print out the triangles means that I have to hold the list of triangles in memory before I write the output to file. In the meanwhile I'm getting memory errors because of the sizes of the lists. What is the best way to tell Python that I no longer need some of the data, and it can be freed? [/INST] According to Python Official Documentation, you can force the Garbage Collector to release unreferenced memory with gc.collect() </s>
<s>[INST] Proper way to handle multiple forms on one page in Django I have a template page expecting two forms. If I just use one form, things are fine as in this typical example: if request.method == 'POST': form = AuthorForm(request.POST,) if form.is_valid(): form.save() # do something. else: form = AuthorForm() If I want to work with multiple forms however, how do I let the view know that I'm submitting only one of the forms and not the other (i.e. it's still request.POST but I only want to process the form for which the submit happened)? This is the solution based on the answer where expectedphrase and bannedphrase are the names of the submit buttons for the different forms and expectedphraseform and bannedphraseform are the forms. if request.method == 'POST': if 'bannedphrase' in request.POST: bannedphraseform = BannedPhraseForm(request.POST, prefix='banned') if bannedphraseform.is_valid(): bannedphraseform.save() expectedphraseform = ExpectedPhraseForm(prefix='expected') elif 'expectedphrase' in request.POST: expectedphraseform = ExpectedPhraseForm(request.POST, prefix='expected') if expectedphraseform.is_valid(): expectedphraseform.save() bannedphraseform = BannedPhraseForm(prefix='banned') else: bannedphraseform = BannedPhraseForm(prefix='banned') expectedphraseform = ExpectedPhraseForm(prefix='expected') [/INST] You have a few options: Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms. Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons django form? </s>
<s>[INST] How should I log while using multiprocessing in Python? Right now I have a central module in a framework that spawns multiple processes using the Python 2.6 multiprocessing module. Because it uses multiprocessing, there is module-level multiprocessing-aware log, LOG = multiprocessing.get_logger(). Per the docs, this logger has process-shared locks so that you don't garble things up in sys.stderr (or whatever filehandle) by having multiple processes writing to it simultaneously. The issue I have now is that the other modules in the framework are not multiprocessing-aware. The way I see it, I need to make all dependencies on this central module use multiprocessing-aware logging. That's annoying within the framework, let alone for all clients of the framework. Are there alternatives I'm not thinking of? [/INST] I just now wrote a log handler of my own that just feeds everything to the parent process via a pipe. I've only been testing it for ten minutes but it seems to work pretty well. (Note: This is hardcoded to RotatingFileHandler, which is my own use case.) Update: Implementation! This now uses a queue for correct handling of concurrency, and also recovers from errors correctly. I've now been using this in production for several months, and the current version below works without issue. from logging.handlers import RotatingFileHandler import multiprocessing, threading, logging, sys, traceback class MultiProcessingLog(logging.Handler): def __init__(self, name, mode, maxsize, rotate): logging.Handler.__init__(self) self._handler = RotatingFileHandler(name, mode, maxsize, rotate) self.queue = multiprocessing.Queue(-1) t = threading.Thread(target=self.receive) t.daemon = True t.start() def setFormatter(self, fmt): logging.Handler.setFormatter(self, fmt) self._handler.setFormatter(fmt) def receive(self): while True: try: record = self.queue.get() self._handler.emit(record) except (KeyboardInterrupt, SystemExit): raise except EOFError: break except: traceback.print_exc(file=sys.stderr) def send(self, s): self.queue.put_nowait(s) def _format_record(self, record): # ensure that exc_info and args # have been stringified. Removes any chance of # unpickleable things inside and possibly reduces # message size sent over the pipe if record.args: record.msg = record.msg % record.args record.args = None if record.exc_info: dummy = self.format(record) record.exc_info = None return record def emit(self, record): try: s = self._format_record(record) self.send(s) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) def close(self): self._handler.close() logging.Handler.close(self) </s>
<s>[INST] Get loop count inside a Python FOR loop In a Python for loop that iterates over a list we can write: for item in list: print item and it neatly goes through all the elements in the list. Is there a way to know within the loop how many times I've been looping so far? For instance, I want to take a list and after I've processed ten elements I want to do something with them. The alternatives I thought about would be something like: count=0 for item in list: print item count +=1 if count % 10 == 0: print 'did ten' Or: for count in range(0,len(list)): print list[count] if count % 10 == 0: print 'did ten' Is there a better way (just like the for item in list) to get the number of iterations so far? [/INST] The pythonic way is to use enumerate: for idx,item in enumerate(list): </s>
<s>[INST] Loading all modules in a folder in Python Could someone provide me with a good way of importing a whole directory of modules? I have a structure like this: /Foo bar.py spam.py eggs.py I tried just converting it to a package by adding __init__.py and doing from Foo import * but it didn't work the way I had hoped. [/INST] List all python (.py) files in the current folder and put them as __all__ variable in __init__.py from os.path import dirname, basename, isfile import glob modules = glob.glob(dirname(__file__)+"/*.py") __all__ = [ basename(f)[:-3] for f in modules if isfile(f)] </s>
<s>[INST] Python: How to get a value of datetime.today() that is "timezone aware"? I am trying to subtract one date value from the value of datetime.today() to calculate how long ago something was. But it complains: TypeError: can't subtract offset-naive and offset-aware datetimes The value datetime.today() doesn't seem to be "timezone aware", while my other date value is. How do I get a value of datetime.today() that is timezone aware? Right now it's giving me the time in local time, which happens to be PST, i.e. UTC-8hrs. Worst case, is there a way I can manually enter a timezone value into the datetime object returned by datetime.today() and set it to UTC-8? Of course, the ideal solution would be for it to automatically know the timezone. [/INST] In the standard library, there is no cross-platform way to create aware timezones without creating your own timezone class. On Windows, there's win32timezone.utcnow(), but that's part of pywin32. I would rather suggest to use the pytz library, which has an up-to-date database of most timezones. Working with local timezones can be very tricky (read the pytz documentation!), so you may rather want to use UTC throughout your application. You can get the current date/time like so: import pytz from datetime import datetime datetime.utcnow().replace(tzinfo=pytz.utc) Mind that datetime.today() and datetime.now() return the local time, not the UTC time, so applying .replace(tzinfo=pytz.utc) to them would not be correct. Another nice way to do it is: datetime.now(pytz.utc) which is a bit shorter and does the same. </s>
<s>[INST] Is there a standardized method to swap two variables in Python? In Python, I've seen two variable values swapped using this syntax: left, right = right, left Is this considered the standard way to swap two variable values or is there some other means by which two variables are by convention most usually swapped? [/INST] Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side. http://docs.python.org/2/reference/expressions.html#evaluation-order That means the following for the expression a,b = b,a : the right-hand side b,a is evaluated, that is to say a tuple of two elements is created in the memory. The two element are the objects designated by the identifiers b and a, that were existing before the instruction is encoutered during an execution of program just after the creation of this tuple, no assignement of this tuple object have still been made, but it doesn't matter, Python internally knows where it is then, the left-hand side is evaluated, that is to say the tuple is assigned to the left-hand side as the left-hand side is composed of two identifiers, the tuple is unpacked in order that the first identifier a be assigned to the first element of the tuple (which is the object that was formely b before the swap because it had name b) and the second identifier b is assigned to the second element of the tuple (which is the object that was formerly a before the swap because its identifiers was a) This mechanism has effectively swapped the objects assigned to the identifiers a and b So, to answer to your question is: YES, it's the standard way to swap two identifiers on two objects. By the way, the objects are not variables, they are objects. </s>
<s>[INST] How does Python compare string and int? The following snippet is annotated with the output (as seen on ideone.com): print "100" < "2" # True print "5" > "9" # False print "100" < 2 # False print 100 < "2" # True print 5 > "9" # False print "5" > 9 # True Can someone explain why the output is as such? Implementation details Is this behavior mandated by the language spec, or is it up to implementors? Are there differences between any of the major Python implementations? Are there differences between versions of the Python language? [/INST] From the manual: CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address. When you order two strings or two numeric types the ordering is done in the expected way (lexicographic ordering for string, numeric ordering for integers). When you order a numeric and a non-numeric type, the numeric type comes first. >>> 5 < 'foo' True >>> 5 < (1, 2) True >>> 5 < {} True >>> 5 < [1, 2] True When you order two incompatible types where neither is numeric, they are ordered by the alphabetical order of their typenames: >>> [1, 2] > 'foo' # 'list' < 'str' False >>> (1, 2) > 'foo' # 'tuple' > 'str' True >>> class Foo(object): pass >>> class Bar(object): pass >>> Bar() < Foo() True One exception is old-style classes that always come before new-style classes. >>> class Foo: pass # old-style >>> class Bar(object): pass # new-style >>> Bar() < Foo() False Is this behavior mandated by the language spec, or is it up to implementors? There is no language specification. The language reference says: Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. So it is an implementation detail. Are there differences between any of the major Python implementations? I can't answer this one because I have only used the official CPython implementation, but there are other implementations of Python such as PyPy. Are there differences between versions of the Python language? In Python 3.x the behaviour has been changed so that attempting to order an integer and a string will raise an error: >>> '10' > 5 Traceback (most recent call last): File "", line 1, in '10' > 5 TypeError: unorderable types: str() > int() </s>
<s>[INST] Efficient way to shift a list in python What is the most efficient way to shift a list in python? Right now I have something like this: >>> def shift(l, n): ... return l[n:] + l[:n] ... >>> l = [1,2,3,4] >>> shift(l,1) [2, 3, 4, 1] >>> shift(l,2) [3, 4, 1, 2] >>> shift(l,0) [1, 2, 3, 4] >>> shift(l,-1) [4, 1, 2, 3] Is there a better way? [/INST] A collections.deque is optimized for pulling and pushing on both ends. They even have a dedicated rotate() method. from collections import deque items = deque([1, 2]) items.append(3) # deque == [1, 2, 3] items.rotate(1) # The deque is now: [3, 1, 2] items.rotate(-1) # Returns deque to original state: [1, 2, 3] item = items.popleft() # deque == [2, 3] </s>
<s>[INST] Is there a way to detach matplotlib plots so that the computation can continue? After these instructions in the Python interpreter one gets a window with a plot: from matplotlib.pyplot import * plot([1,2,3]) show() # other code Unfortunately, I don't know how to continue to interactively explore the figure created by show() while the program does further calculations. Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results. [/INST] Use matplotlib's calls that won't block: Using draw(): from matplotlib.pyplot import plot, draw, show plot([1,2,3]) draw() print 'continue computation' # at the end call show to ensure window won't close. show() Using interactive mode: from matplotlib.pyplot import plot, ion, show ion() # enables interactive mode plot([1,2,3]) # result shows immediatelly (implicit draw()) print 'continue computation' # at the end call show to ensure window won't close. show() </s>
<s>[INST] Get last n lines of a file with Python, similar to tail I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom. So I need a tail() method that can read n lines from the bottom and supports an offset. What I came up with looks like this: def tail(f, n, offset=0): """Reads a n lines from f with an offset of offset lines.""" avg_line_length = 74 to_read = n + offset while 1: try: f.seek(-(avg_line_length * to_read), 2) except IOError: # woops. apparently file is smaller than what we want # to step back, go to the beginning instead f.seek(0) pos = f.tell() lines = f.read().splitlines() if len(lines) >= to_read or pos == 0: return lines[-to_read:offset and -offset or None] avg_line_length *= 1.3 Is this a reasonable approach? What is the recommended way to tail log files with offsets? [/INST] This may be quicker than yours. Makes no assumptions about line length. Backs through the file one block at a time till it's found the right number of '\n' characters. def tail( f, lines=20 ): total_lines_wanted = lines BLOCK_SIZE = 1024 f.seek(0, 2) block_end_byte = f.tell() lines_to_go = total_lines_wanted block_number = -1 blocks = [] # blocks of size BLOCK_SIZE, in reverse order starting # from the end of the file while lines_to_go > 0 and block_end_byte > 0: if (block_end_byte - BLOCK_SIZE > 0): # read the last block we haven't yet read f.seek(block_number*BLOCK_SIZE, 2) blocks.append(f.read(BLOCK_SIZE)) else: # file too small, start from begining f.seek(0,0) # only read what was not read blocks.append(f.read(block_end_byte)) lines_found = blocks[-1].count('\n') lines_to_go -= lines_found block_end_byte -= BLOCK_SIZE block_number -= 1 all_read_text = ''.join(reversed(blocks)) return '\n'.join(all_read_text.splitlines()[-total_lines_wanted:]) I don't like tricky assumptions about line length when -- as a practical matter -- you can never know things like that. Generally, this will locate the last 20 lines on the first or second pass through the loop. If your 74 character thing is actually accurate, you make the block size 2048 and you'll tail 20 lines almost immediately. Also, I don't burn a lot of brain calories trying to finesse alignment with physical OS blocks. Using these high-level I/O packages, I doubt you'll see any performance consequence of trying to align on OS block boundaries. If you use lower-level I/O, then you might see a speedup. </s>
<s>[INST] What is the difference between encode/decode? I've never been sure that I understand the difference between str/unicode decode and encode. I know that str().decode() is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string. I know that unicode().encode() converts unicode chars into a string of bytes according to a given encoding name. But I don't understand what str().encode() and unicode().decode() are for. Can anyone explain, and possibly also correct anything else I've gotten wrong above? EDIT: Several answers give info on what .encode does on a string, but no-one seems to know what .decode does for unicode. [/INST] The decode method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone. unicode().decode() will perform an implicit encoding of s using the default (ascii) codec. Verify this like so: >>> s = u'ö' >>> s.decode() Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0: ordinal not in range(128) >>> s.encode('ascii') Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0: ordinal not in range(128) The error messages are exactly the same. For str().encode() it's the other way around -- it attempts an implicit decoding of s with the default encoding: >>> s = 'ö' >>> s.decode('utf-8') u'\xf6' >>> s.encode() Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) Used like this, str().encode() is also superfluous. But there is another application of the latter method that is useful: there are encodings that have nothing to do with character sets, and thus can be applied to 8-bit strings in a meaningful way: >>> s.encode('zip') 'x\x9c;\xbc\r\x00\x02>\x01z' You are right, though: the ambiguous usage of "encoding" for both these applications is... awkard. Again, with separate byte and string types in Python 3, this is no longer an issue. </s>
<s>[INST] error: command 'gcc' failed with exit status 1 while installing eventlet I wanted to install eventlet on my system in order to have "Herd" for software deployment.. but the terminal is showing a gcc error: root@agrover-OptiPlex-780:~# easy_install -U eventlet Searching for eventlet Reading http://pypi.python.org/simple/eventlet/ Reading http://wiki.secondlife.com/wiki/Eventlet Reading http://eventlet.net Best match: eventlet 0.9.16 Processing eventlet-0.9.16-py2.7.egg eventlet 0.9.16 is already the active version in easy-install.pth Using /usr/local/lib/python2.7/dist-packages/eventlet-0.9.16-py2.7.egg Processing dependencies for eventlet Searching for greenlet>=0.3 Reading http://pypi.python.org/simple/greenlet/ Reading https://github.com/python-greenlet/greenlet Reading http://bitbucket.org/ambroff/greenlet Best match: greenlet 0.3.4 Downloading http://pypi.python.org/packages/source/g/greenlet/greenlet- 0.3.4.zip#md5=530a69acebbb0d66eb5abd83523d8272 Processing greenlet-0.3.4.zip Writing /tmp/easy_install-_aeHYm/greenlet-0.3.4/setup.cfg Running greenlet-0.3.4/setup.py -q bdist_egg --dist-dir /tmp/easy_install-_aeHYm/greenlet-0.3.4/egg-dist-tmp-t9_gbW In file included from greenlet.c:5:0: greenlet.h:8:20: fatal error: Python.h: No such file or directory compilation terminated. error: Setup script exited with error: command 'gcc' failed with exit status 1` Why can't Python.h be found? [/INST] Your install is failing because you don't have the python development headers installed. You can do this through apt on ubuntu/debian with: sudo apt-get install python-dev for python3 use: sudo apt-get install python3-dev For eventlet you might also need the libevent libraries installed so if you get an error talking about that you can install libevent with: sudo apt-get install libevent-dev </s>
<s>[INST] Converting datetime.date to UTC timestamp in Python I am dealing with dates in Python and I need to convert them to UTC timestamps to be used inside Javascript. The following code does not work: >>> d = datetime.date(2011,01,01) >>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple())) datetime.datetime(2010, 12, 31, 23, 0) Converting the date object first to datetime also does not help. I tried the example at this link from, but: from pytz import utc, timezone from datetime import datetime from time import mktime input_date = datetime(year=2011, month=1, day=15) and now either: mktime(utc.localize(input_date).utctimetuple()) or mktime(timezone('US/Eastern').localize(input_date).utctimetuple()) does work. So general question: how can I get a date converted to seconds since epoch according to UTC? [/INST] If d = date(2011, 1, 1) is in UTC: >>> from datetime import datetime, date >>> import calendar >>> timestamp1 = calendar.timegm(d.timetuple()) >>> datetime.utcfromtimestamp(timestamp1) datetime.datetime(2011, 1, 1, 0, 0) If d is in local timezone: >>> import time >>> timestamp2 = time.mktime(d.timetuple()) # DO NOT USE IT WITH UTC DATE >>> datetime.fromtimestamp(timestamp2) datetime.datetime(2011, 1, 1, 0, 0) timestamp1 and timestamp2 may differ if midnight in the local timezone is not the same time instance as midnight in UTC. mktime() may return a wrong result if d corresponds to an ambiguous local time (e.g., during DST transition) or if d is a past(future) date when the utc offset might have been different and the C mktime() has no access to the tz database on the given platform. You could use pytz module (e.g., via tzlocal.get_localzone()) to get access to the tz database on all platforms. Also, utcfromtimestamp() may fail and mktime() may return non-POSIX timestamp if "right" timezone is used. To convert datetime.date object that represents date in UTC without calendar.timegm(): DAY = 24*60*60 # POSIX day in seconds (exact value) timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * DAY timestamp = (utc_date - date(1970, 1, 1)).days * DAY How can I get a date converted to seconds since epoch according to UTC? To convert datetime.datetime (not datetime.date) object that already represents time in UTC to the corresponding POSIX timestamp (a float). Python 3.3+ datetime.timestamp(): timestamp = dt.replace(tzinfo=timezone.utc).timestamp() Note: It is necessary to supply timezone.utc explicitly otherwise .timestamp() assume that your naive datetime object is in local timezone. Python 3 (< 3.3) From the docs for datetime.utcfromtimestamp(): There is no method to obtain the timestamp from a datetime instance, but POSIX timestamp corresponding to a datetime instance dt can be easily calculated as follows. For a naive dt: timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1) And for an aware dt: timestamp = (dt - datetime(1970,1,1, tzinfo=timezone.utc)) / timedelta(seconds=1) Interesting read: Epoch time vs. time of day on the difference between What time is it? and How many seconds have elapsed? See also: datetime needs an "epoch" method Python 2 To adapt the above code for Python 2: timestamp = (dt - datetime(1970, 1, 1)).total_seconds() where timedelta.total_seconds() is equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 computed with true division enabled. Example from __future__ import division from datetime import datetime, timedelta def totimestamp(dt, epoch=datetime(1970,1,1)): td = dt - epoch # return td.total_seconds() return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 now = datetime.utcnow() print now print totimestamp(now) Beware of floating-point issues. Output 2012-01-08 15:34:10.022403 1326036850.02 How to convert an aware datetime object to POSIX timestamp assert dt.tzinfo is not None and dt.utcoffset() is not None timestamp = dt.timestamp() # Python 3.3+ On Python 3: from datetime import datetime, timedelta, timezone epoch = datetime(1970, 1, 1, tzinfo=timezone.utc) timestamp = (dt - epoch) / timedelta(seconds=1) integer_timestamp = (dt - epoch) // timedelta(seconds=1) On Python 2: # utc time = local time - utc offset utc_naive = dt.replace(tzinfo=None) - dt.utcoffset() timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds() </s>
<s>[INST] Initialize a datetime object with seconds since epoch The time module can be initialized using seconds since epoch: >>> import time >>> t1=time.gmtime(1284286794) >>> t1 time.struct_time(tm_year=2010, tm_mon=9, tm_mday=12, tm_hour=10, tm_min=19, tm_sec=54, tm_wday=6, tm_yday=255, tm_isdst=0) Is there an elegant way to initialize a datetime.datetime object in the same way? [/INST] datetime.datetime.fromtimestamp will do, if you know the time zone, you could produce the same output as with time.gmtime >>> datetime.datetime.fromtimestamp(1284286794) datetime.datetime(2010, 9, 12, 11, 19, 54) or >>> datetime.datetime.utcfromtimestamp(1284286794) datetime.datetime(2010, 9, 12, 10, 19, 54) </s>
<s>[INST] Python multiprocessing.Pool: when to use apply, apply_async or map? I have not seen clear examples with use-cases for Pool.apply, Pool.apply_async and Pool.map. I am mainly using Pool.map; what are the advantages of others? [/INST] Back in the old days of Python, to call a function with arbitrary arguments, you would use apply: apply(f,args,kwargs) apply still exists in Python2.7 though not in Python3, and is generally not used anymore. Nowadays, f(*args,**kwargs) is preferred. The multiprocessing.Pool modules tries to provide a similar interface. Pool.apply is like Python apply, except that the function call is performed in a separate process. Pool.apply blocks until the function is completed. Pool.apply_async is also like Python's built-in apply, except that the call returns immediately instead of waiting for the result. An ApplyResult object is returned. You call its get() method to retrieve the result of the function call. The get() method blocks until the function is completed. Thus, pool.apply(func, args, kwargs) is equivalent to pool.apply_async(func, args, kwargs).get(). In contrast to Pool.apply, the Pool.apply_async method also has a callback which, if supplied, is called when the function is complete. This can be used instead of calling get(). For example: import multiprocessing as mp import time def foo_pool(x): time.sleep(2) return x*x result_list = [] def log_result(result): # This is called whenever foo_pool(i) returns a result. # result_list is modified only by the main process, not the pool workers. result_list.append(result) def apply_async_with_callback(): pool = mp.Pool() for i in range(10): pool.apply_async(foo_pool, args = (i, ), callback = log_result) pool.close() pool.join() print(result_list) if __name__ == '__main__': apply_async_with_callback() may yield a result such as [1, 0, 4, 9, 25, 16, 49, 36, 81, 64] Notice, unlike pool.map, the order of the results may not correspond to the order in which the pool.apply_async calls were made. So, if you need to run a function in a separate process, but want the current process to block until that function returns, use Pool.apply. Like Pool.apply, Pool.map blocks until the complete result is returned. If you want the Pool of worker processes to perform many function calls asynchronously, use Pool.apply_async. The order of the results is not guaranteed to be the same as the order of the calls to Pool.apply_async. Notice also that you could call a number of different functions with Pool.apply_async (not all calls need to use the same function). In contrast, Pool.map applies the same function to many arguments. However, unlike Pool.apply_async, the results are returned in an order corresponding to the order of the arguments. </s>
<s>[INST] Python: Why is functools.partial necessary? Partial application is cool. What functionality does functools.partial offer that you can't get through lambdas? >>> sum = lambda x, y : x + y >>> sum(1, 2) 3 >>> incr = lambda y : sum(1, y) >>> incr(2) 3 >>> def sum2(x, y): return x + y >>> incr2 = functools.partial(sum2, 1) >>> incr2(4) 5 Is functools somehow more efficient, or readable? [/INST] What functionality does functools.partial offer that you can't get through lambdas? Not much in terms of extra functionality (but, see later) -- and, readability is in the eye of the beholder. Most people who are familiar with functional programming languages (those in the Lisp/Scheme families in particular) appear to like lambda just fine -- I say "most", definitely not all, because Guido and I definitely are among those "familiar with" (etc) yet think of lambda as an eyesore anomaly in Python... he was repentant of ever having accepted it into Python and planned to remove it in Python 3, as one of "Python's glitches", and I fully supported him in that. (I love lambda in Scheme... but its limitations in Python, and the weird way it just doesn't fit in with the rest of the language, make my skin crawl). Not so, however, for the hordes of lambda lovers -- who staged one of the closest things to a rebellion ever seen in Python's history, until Guido backtracked and decided to leave lambda in. Several possible additions to functools (to make functions returning constants, identity, etc) didn't happen (to avoid explicitly duplicating more of lambda's functionality), though partial did of course remain (it's no total duplication, nor is it an eyesore). Remember that lambda's body is limited to be an expression, so it's got limitations. For example...: >>> import functools >>> f = functools.partial(int, base=2) >>> f.args () >>> f.func <type 'int'> >>> f.keywords {'base': 2} >>> functools.partial's returned function is decorated with attributes useful for introspection -- the function it's wrapping, and what positional and named arguments it fixes therein. Further, the named arguments can be overridden right back (the "fixing" is rather, in a sense, the setting of defaults): >>> f('23', base=10) 23 So, as you see, it's definely not as simplistic as lambda s: int(s, base=2)!-) Yes, you could contort your lambda to give you some of this -- e.g., for the keyword-overriding, >>> f = lambda s, **k: int(s, **dict({'base': 2}, **k)) but I dearly hope that even the most ardent lambda-lover doesn't consider this horror more readable than the partial call!-). And, the "attribute setting" part is even harder, because of the "body's a single expression" limitation of Python's lambda (plus the fact that assignment can never be part of a Python expression)... you end up "faking assignments within an expression" by stretching list comprehension well beyond its design limits...: >>> f = [f for f in (lambda f: int(s, base=2),) if setattr(f, 'keywords', {'base': 2}) is None][0] Now combine the named-arguments overridability, plus the setting of three attributes, into a single expression, and tell me just how readable that is going to be...!-) </s>
<s>[INST] Getting the index of the returned max or min item using max()/min() on a list I'm using Python's max and min functions on lists for a minimax algorithm, and I need the index of the value returned by max() or min(). In other words, I need to know which move produced the max (at a first player's turn) or min (second player) value. for i in range(9): newBoard = currentBoard.newBoardWithMove([i / 3, i % 3], player) if newBoard: temp = minMax(newBoard, depth + 1, not isMinLevel) values.append(temp) if isMinLevel: return min(values) else: return max(values) I need to be able to return the actual index of the min or max value, not just the value. [/INST] You can find the min/max index and value at the same time if you enumerate the items in the list, but perform min/max on the original values of the list. Like so: import operator min_index, min_value = min(enumerate(values), key=operator.itemgetter(1)) max_index, max_value = max(enumerate(values), key=operator.itemgetter(1)) This way the list will only be traversed once for min (or max). </s>
<s>[INST] When should I use uuid.uuid1() vs. uuid.uuid4() in python? I understand the differences between the two from the docs. uuid1(): Generate a UUID from a host ID, sequence number, and the current time uuid4(): Generate a random UUID. So uuid1 uses machine/sequence/time info to generate a UUID. What are the pros and cons of using each? I know uuid1() can have privacy concerns, since it's based off of machine-information. I wonder if there's any more subtle when choosing one or the other. I just use uuid4() right now, since it's a completely random UUID. But I wonder if I should be using uuid1 to lessen the risk of collisions. Basically, I'm looking for people's tips for best-practices on using one vs. the other. Thanks! [/INST] uuid1() is guaranteed to not produce any collisions (under the assumption you do not create too many of them at the same time). I wouldn't use it if it's important that there's no connection between the uuid and the computer, as the mac address gets used to make it unique across computers. You can create duplicates by creating more than 214 uuid1 in less than 100ns, but this is not a problem for most use cases. uuid4() generates, as you said, a random UUID. The chance of a collision is really, really, really small. Small enough, that you shouldn't worry about it. The problem is, that a bad random-number generator makes it more likely to have collisions. This excellent answer by Bob Aman sums it up nicely. (I recommend reading the whole answer.) Frankly, in a single application space without malicious actors, the extinction of all life on earth will occur long before you have a collision, even on a version 4 UUID, even if you're generating quite a few UUIDs per second. </s>
<s>[INST] Why can tuples contain mutable items? If a tuple is immutable then why can it contain mutable items? It is seemingly a contradiction that when a mutable item such as a list does get modified, the tuple it belongs to maintains being immutable. [/INST] That's because tuples don't contain lists, strings or numbers. They contain references to other objects.1 The inability to change the sequence of references a tuple contains doesn't mean that you can't mutate the objects associated with those references.2 1. Objects, values and types (see: second to last paragraph) 2. The standard type hierarchy (see: "Immutable sequences") </s>
<s>[INST] What is the most efficient way to loop through dataframes with pandas? I want to perform my own complex operations on financial data in dataframes in a sequential manner. For example I am using the following MSFT CSV file taken from Yahoo Finance: Date,Open,High,Low,Close,Volume,Adj Close 2011-10-19,27.37,27.47,27.01,27.13,42880000,27.13 2011-10-18,26.94,27.40,26.80,27.31,52487900,27.31 2011-10-17,27.11,27.42,26.85,26.98,39433400,26.98 2011-10-14,27.31,27.50,27.02,27.27,50947700,27.27 .... I then do the following: #!/usr/bin/env python from pandas import * df = read_csv('table.csv') for i, row in enumerate(df.values): date = df.index[i] open, high, low, close, adjclose = row #now perform analysis on open/close based on date, etc.. Is that the most efficient way? Given the focus on speed in pandas, I would assume there must be some special function to iterate through the values in a manner that one also retrieves the index (possibly through a generator to be memory efficient)? df.iteritems unfortunately only iterates column by column. [/INST] The newest versions of pandas now include a built-in function for iterating over rows. for index, row in df.iterrows(): # do some logic here Or, if you want it faster use itertuples() But, unutbu's suggestion to use numpy functions to avoid iterating over rows will produce the fastest code. </s>
<s>[INST] Retrieving the output of subprocess.call() How can I get the output of a process run using subprocess.call()? Passing a StringIO.StringIO object to stdout gives this error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 444, in call return Popen(*popenargs, **kwargs).wait() File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 588, in __init__ errread, errwrite) = self._get_handles(stdin, stdout, stderr) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py", line 945, in _get_handles c2pwrite = stdout.fileno() AttributeError: StringIO instance has no attribute 'fileno' >>> [/INST] If you have Python version >= 2.7, you can use subprocess.check_output which basically does exactly what you want (it returns standard output as string). As commented below you can find sample code and a more detailed explanation in this other answer. </s>
<s>[INST] BaseException.message deprecated in Python 2.6 I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception: class MyException(Exception): def __init__(self, message): self.message = message def __str__(self): return repr(self.message) This is the warning: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 self.message = message What's wrong with this? What do I have to change to get rid of the deprecation warning? [/INST] Solution - almost no coding needed Just inherit your exception class from Exception and pass the message as the first parameter to the constructor Example: class MyException(Exception): """My documentation""" try: raise MyException('my detailed description') except MyException as my: print my # outputs 'my detailed description' You can use str(my) or (less elegant) my.args[0] to access the custom message. Background In the newer versions of Python (from 2.6) we are supposed to inherit our custom exception classes from Exception which (starting from Python 2.5) inherits from BaseException. The background is described in detail in PEP352. class BaseException(object): """Superclass representing the base of the exception hierarchy. Provides an 'args' attribute that contains all arguments passed to the constructor. Suggested practice, though, is that only a single string argument be passed to the constructor.""" __str__ and __repr__ are already implemented in a meaningful way, especially for the case of only one arg (that can be used as message). You do not need to repeat __str__ or __init__ implementation or create _get_message as suggested by others. </s>
<s>[INST] Shuffle an array with python, randomize array item order with python What's the easiest way to shuffle an array with python? [/INST] import random random.shuffle(array) </s>
<s>[INST] Failed to install Python Cryptography package with PIP and setup.py When I try to install the Cryptography package for Python through either pip install cryptography or by downloading the package from their site and running python setup.py, I get the following error: D:\Anaconda\Scripts\pip-script.py run on 02/27/14 16:13:17 Downloading/unpacking cryptography Getting page https://pypi.python.org/simple/cryptography/ URLs to search for versions for cryptography: * https://pypi.python.org/simple/cryptography/ Analyzing links from page https://pypi.python.org/simple/cryptography/ Skipping https://pypi.python.org/packages/cp26/c/cryptography/cryptography-0.2-cp26-none-win32.whl#md5=13e5c4b19520e7dc6f07c6502b3f74e2 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python Skipping https://pypi.python.org/packages/cp26/c/cryptography/cryptography-0.2.1-cp26-none-win32.whl#md5=00e733648ee5cdb9e58876238b1328f8 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python Skipping https://pypi.python.org/packages/cp27/c/cryptography/cryptography-0.2-cp27-none-win32.whl#md5=013ccafa6a5a3ea92c73f2c1c4879406 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python Skipping https://pypi.python.org/packages/cp27/c/cryptography/cryptography-0.2.1-cp27-none-win32.whl#md5=127d6a5dc687250721f892d55720a06c (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python Skipping https://pypi.python.org/packages/cp32/c/cryptography/cryptography-0.2-cp32-none-win32.whl#md5=051424a36e91039807b72f112333ded3 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python Skipping https://pypi.python.org/packages/cp32/c/cryptography/cryptography-0.2.1-cp32-none-win32.whl#md5=53f6f57db8e952d64283baaa14cbde3d (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python Skipping https://pypi.python.org/packages/cp33/c/cryptography/cryptography-0.2-cp33-none-win32.whl#md5=302812c1c1a035cf9ba3292f8dbf3f9e (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python Skipping https://pypi.python.org/packages/cp33/c/cryptography/cryptography-0.2.1-cp33-none-win32.whl#md5=81acca90caf8a45f2ca73f3f9859fae4 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python Found link https://pypi.python.org/packages/source/c/cryptography/cryptography-0.1.tar.gz#md5=bdc1c5fe069deca7467b71a0cc538f17 (from https://pypi.python.org/simple/cryptography/), version: 0.1 Found link https://pypi.python.org/packages/source/c/cryptography/cryptography-0.2.1.tar.gz#md5=872fc04268dadc66a0305ae5ab1c123b (from https://pypi.python.org/simple/cryptography/), version: 0.2.1 Found link https://pypi.python.org/packages/source/c/cryptography/cryptography-0.2.tar.gz#md5=8a3d21e837a21e1b7634ee1f22b06bb6 (from https://pypi.python.org/simple/cryptography/), version: 0.2 Using version 0.2.1 (newest of versions: 0.2.1, 0.2, 0.1) Downloading from URL https://pypi.python.org/packages/source/c/cryptography/cryptography-0.2.1.tar.gz#md5=872fc04268dadc66a0305ae5ab1c123b (from https://pypi.python.org/simple/cryptography/) Running setup.py (path:c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography\setup.py) egg_info for package cryptography In file included from c/_cffi_backend.c:7:0: c/misc_win32.h:225:23: error: two or more data types in declaration specifiers c/misc_win32.h:225:1: warning: useless type name in empty declaration [enabled by default] c/_cffi_backend.c: In function 'convert_array_from_object': c/_cffi_backend.c:1105:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1105:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1130:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1130:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1150:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1150:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'convert_struct_from_object': c/_cffi_backend.c:1183:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1183:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1196:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1196:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'cdata_repr': c/_cffi_backend.c:1583:13: warning: unknown conversion type character 'L' in format [-Wformat] c/_cffi_backend.c:1583:13: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1595:9: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1595:9: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'cdataowning_repr': c/_cffi_backend.c:1647:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1647:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function '_cdata_get_indexed_ptr': c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1820:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function '_cdata_getslicearg': c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1872:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'cdata_ass_slice': c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1951:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1969:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1983:22: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1983:22: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'cdata_call': c/_cffi_backend.c:2367:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:2367:30: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat] c/_cffi_backend.c:2367:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'cast_to_integer_or_char': c/_cffi_backend.c:2916:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:2916:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat] c/_cffi_backend.c:2916:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:2928:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:2928:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat] c/_cffi_backend.c:2928:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'new_array_type': c/_cffi_backend.c:3480:9: warning: unknown conversion type character 'l' in format [-Wformat] c/_cffi_backend.c:3480:9: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'b_complete_struct_or_union': c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:3878:22: warning: too many arguments for format [-Wformat-extra-args] Traceback (most recent call last): File "<string>", line 17, in <module> File "c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography\setup.py", line 113, in <module> "build": cffi_build, File "D:\Anaconda\lib\distutils\core.py", line 112, in setup _setup_distribution = dist = klass(attrs) File "build\bdist.win-amd64\egg\setuptools\dist.py", line 239, in __init__ File "build\bdist.win-amd64\egg\setuptools\dist.py", line 264, in fetch_build_eggs File "build\bdist.win-amd64\egg\pkg_resources.py", line 580, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "build\bdist.win-amd64\egg\pkg_resources.py", line 818, in best_match return self.obtain(req, installer) # try and download/install File "build\bdist.win-amd64\egg\pkg_resources.py", line 830, in obtain return installer(requirement) File "build\bdist.win-amd64\egg\setuptools\dist.py", line 314, in fetch_build_egg File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 593, in easy_install File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 623, in install_item File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 809, in install_eggs File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1015, in build_and_install File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1003, in run_setup distutils.errors.DistutilsError: Setup script exited with error: command 'gcc' failed with exit status 1 Complete output from command python setup.py egg_info: In file included from c/_cffi_backend.c:7:0: c/misc_win32.h:225:23: error: two or more data types in declaration specifiers c/misc_win32.h:225:1: warning: useless type name in empty declaration [enabled by default] c/_cffi_backend.c: In function 'convert_array_from_object': c/_cffi_backend.c:1105:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1105:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1130:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1130:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1150:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1150:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'convert_struct_from_object': c/_cffi_backend.c:1183:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1183:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1196:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1196:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'cdata_repr': c/_cffi_backend.c:1583:13: warning: unknown conversion type character 'L' in format [-Wformat] c/_cffi_backend.c:1583:13: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1595:9: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1595:9: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'cdataowning_repr': c/_cffi_backend.c:1647:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1647:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function '_cdata_get_indexed_ptr': c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1820:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function '_cdata_getslicearg': c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1872:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'cdata_ass_slice': c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1951:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1969:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:1983:22: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:1983:22: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'cdata_call': c/_cffi_backend.c:2367:30: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:2367:30: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat] c/_cffi_backend.c:2367:30: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'cast_to_integer_or_char': c/_cffi_backend.c:2916:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:2916:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat] c/_cffi_backend.c:2916:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c:2928:26: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:2928:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat] c/_cffi_backend.c:2928:26: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'new_array_type': c/_cffi_backend.c:3480:9: warning: unknown conversion type character 'l' in format [-Wformat] c/_cffi_backend.c:3480:9: warning: too many arguments for format [-Wformat-extra-args] c/_cffi_backend.c: In function 'b_complete_struct_or_union': c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat] c/_cffi_backend.c:3878:22: warning: too many arguments for format [-Wformat-extra-args] Traceback (most recent call last): File "<string>", line 17, in <module> File "c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography\setup.py", line 113, in <module> "build": cffi_build, File "D:\Anaconda\lib\distutils\core.py", line 112, in setup _setup_distribution = dist = klass(attrs) File "build\bdist.win-amd64\egg\setuptools\dist.py", line 239, in __init__ File "build\bdist.win-amd64\egg\setuptools\dist.py", line 264, in fetch_build_eggs File "build\bdist.win-amd64\egg\pkg_resources.py", line 580, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "build\bdist.win-amd64\egg\pkg_resources.py", line 818, in best_match return self.obtain(req, installer) # try and download/install File "build\bdist.win-amd64\egg\pkg_resources.py", line 830, in obtain return installer(requirement) File "build\bdist.win-amd64\egg\setuptools\dist.py", line 314, in fetch_build_egg File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 593, in easy_install File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 623, in install_item File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 809, in install_eggs File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1015, in build_and_install File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1003, in run_setup distutils.errors.DistutilsError: Setup script exited with error: command 'gcc' failed with exit status 1 ---------------------------------------- Cleaning up... Removing temporary dir c:\users\paco\appdata\local\temp\pip_build_Paco... Command python setup.py egg_info failed with error code 1 in c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography Exception information: Traceback (most recent call last): File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\basecommand.py", line 122, in main status = self.run(options, args) File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\commands\install.py", line 278, in run requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle) File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\req.py", line 1229, in prepare_files req_to_install.run_egg_info() File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\req.py", line 325, in run_egg_info command_desc='python setup.py egg_info') File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\util.py", line 697, in call_subprocess % (command_desc, proc.returncode, cwd)) InstallationError: Command python setup.py egg_info failed with error code 1 in c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography I found other egg_info error posts (here and here) but the solutions there provided wouldn't solve my problem. Also, I am able to install other packages through PIP. PIP version 1.5.4 setuptools version 2.2 [/INST] I had a similar issue, and found i was simply missing a dependancy (libssl-dev, for me). As referenced in https://cryptography.io/en/latest/installation/, ensure that all dependancies are met: On Windows If you’re on Windows you’ll need to make sure you have OpenSSL installed. There are pre-compiled binaries available. If your installation is in an unusual location set the LIB and INCLUDE environment variables to include the corresponding locations. For example: C:\> \path\to\vcvarsall.bat x86_amd64 C:\> set LIB=C:\OpenSSL-1.0.1f-64bit\lib;%LIB% C:\> set INCLUDE=C:\OpenSSL-1.0.1f-64bit\include;%INCLUDE% C:\> pip install cryptography Building cryptography on Linux cryptography should build very easily on Linux provided you have a C compiler, headers for Python (if you’re not using pypy), and headers for the OpenSSL and libffi libraries available on your system. For Debian and Ubuntu, the following command will ensure that the required dependencies are installed: sudo apt-get install build-essential libssl-dev libffi-dev python-dev For Fedora and RHEL-derivatives, the following command will ensure that the required dependencies are installed: sudo yum install gcc libffi-devel python-devel openssl-devel You should now be able to build and install cryptography with the usual. pip install cryptography </s>
<s>[INST] Pandas writing dataframe to CSV file I have a dataframe in pandas which I would like to write to a CSV file. I am doing this using: df.to_csv('out.csv') And getting the error: UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128) Is there any way to get around this easily (i.e. I have unicode characters in my data frame)? And is there a way to write to a tab delimited file instead of a CSV using e.g. a 'to-tab' method (that I dont think exists)? [/INST] To delimit by a tab you can use the sep argument of to_csv: df.to_csv(file_name, sep='\t') To use a specific encoding (e.g. 'utf-8') use the encoding argument: df.to_csv(file_name, sep='\t', encoding='utf-8') </s>
<s>[INST] Deleting DataFrame row in Pandas based on column value I have the following DataFrame: daysago line_race rating rw wrating line_date 2007-03-31 62 11 56 1.000000 56.000000 2007-03-10 83 11 67 1.000000 67.000000 2007-02-10 111 9 66 1.000000 66.000000 2007-01-13 139 10 83 0.880678 73.096278 2006-12-23 160 10 88 0.793033 69.786942 2006-11-09 204 9 52 0.636655 33.106077 2006-10-22 222 8 66 0.581946 38.408408 2006-09-29 245 9 70 0.518825 36.317752 2006-09-16 258 11 68 0.486226 33.063381 2006-08-30 275 8 72 0.446667 32.160051 2006-02-11 475 5 65 0.164591 10.698423 2006-01-13 504 0 70 0.142409 9.968634 2006-01-02 515 0 64 0.134800 8.627219 2005-12-06 542 0 70 0.117803 8.246238 2005-11-29 549 0 70 0.113758 7.963072 2005-11-22 556 0 -1 0.109852 -0.109852 2005-11-01 577 0 -1 0.098919 -0.098919 2005-10-20 589 0 -1 0.093168 -0.093168 2005-09-27 612 0 -1 0.083063 -0.083063 2005-09-07 632 0 -1 0.075171 -0.075171 2005-06-12 719 0 69 0.048690 3.359623 2005-05-29 733 0 -1 0.045404 -0.045404 2005-05-02 760 0 -1 0.039679 -0.039679 2005-04-02 790 0 -1 0.034160 -0.034160 2005-03-13 810 0 -1 0.030915 -0.030915 2004-11-09 934 0 -1 0.016647 -0.016647 I need to remove the rows where line_race is equal to 0. What's the most efficient way to do this? [/INST] If I'm understanding correctly, it should be as simple as: df = df[df.line_race != 0] </s>
<s>[INST] Create an empty list in python with certain size I want to create an empty list (or whatever is the best way) that can hold 10 elements. After that I want to assign values in that list, for example this is supposed to display 0 to 9: s1 = list(); for i in range(0,9): s1[i] = i print s1 But when I run this code, it generates an error or in another case it just displays [] (empty). Can someone explain why? [/INST] You cannot assign to a list like lst[i] = something. You need to use append. lst.append(i). (You could use the assignment notation if you were using a dictionary). Creating an empty list: >>> l = [None] * 10 >>> l [None, None, None, None, None, None, None, None, None, None] range(x) creates a list from [0, 1, 2, ... x-1] # 2.X only. Use list(range(10)) in 3.X. >>> l = range(10) >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Using a function to create a list: >>> def display(): ... s1 = [] ... for i in range(9): # This is just to tell you how to create a list. ... s1.append(i) ... return s1 ... >>> print display() [0, 1, 2, 3, 4, 5, 6, 7, 8] List comprehension (Using the squares because for range you don't need to do all this, you can just return range(0,9) ): >>> def display(): ... return [x**2 for x in range(9)] ... >>> print display() [0, 1, 4, 9, 16, 25, 36, 49, 64] </s>
<s>[INST] How to check if a string in Python is in ASCII? I want to I check whether a string is in ASCII or not. I am aware of ord(), however when I try ord('é'), I have TypeError: ord() expected a character, but string of length 2 found. I understood it is caused by the way I built Python (as explained in ord()'s documentation). Is there another way to check? [/INST] I think you are not asking the right question-- A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you need to go for an answer. Perhaps the question you can ask is: "Is this string the result of encoding a unicode string in ascii?" -- This you can answer by trying: try: mystring.decode('ascii') except UnicodeDecodeError: print "it was not a ascii-encoded unicode string" else: print "It may have been an ascii-encoded unicode string" </s>
<s>[INST] Use of "global" keyword in Python What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use global. I'm using Python 2.7 and I tried this little test >>> sub = ['0', '0', '0', '0'] >>> def getJoin(): ... return '.'.join(sub) ... >>> getJoin() '0.0.0.0' It seems things are working fine even without global. I was able to access global variable without any problem. Am I missing anything? Also, following is from Python documentation: Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement. While formal parameters and class definition make sense to me, I'm not able to understand the restriction on for loop control target and function definition. [/INST] The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution. def bob(): me = "locally defined" # Defined only in local context print me bob() print me # Asking for a global variable The above will give you: locally defined Traceback (most recent call last): File "file.py", line 9, in <module> print me NameError: name 'me' is not defined While if you use the global statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable. def bob(): global me me = "locally defined" # Defined locally but declared as global print me bob() print me # Asking for a global variable So the above code will give you: locally defined locally defined In addition, due to the nature of python, you could also use global to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging. </s>
<s>[INST] Assign output of os.system to a variable and prevent it from being displayed on the screen I want to assign the output of a command I run using os.system to a variable and prevent it from being output to the screen. But, in the below code ,the output is sent to the screen and the value printed for var is 0, which I guess signifies whether the command ran successfully or not. Is there any way to assign the command output to the variable and also stop it from being displayed on the screen? var = os.system("cat /etc/services") print var #Prints 0 [/INST] From "Equivalent of Bash Backticks in Python", which I asked a long time ago, what you may want to use is popen: os.popen('cat /etc/services').read() I'm told that subprocess is a much better way to solve this, so here's the corresponding code: import subprocess proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() print "program output:", out </s>
<s>[INST] How do I add a placeholder on a CharField in Django? Take this very simple form for example. class SearchForm(Form): q = forms.CharField(label='search') This gets rendered in the template: <input type="text" name="q" id="id_q" /> However, I want to add the 'placeholder' attribute to this field with a value of "Search" so that the HTML would look something like: <input type="text" name="q" id="id_q" placeholder="Search" /> Preferably I would like to pass the placeholder value in to CharField in the form class through a dictionary or something like: q = forms.CharField(label='search', placeholder='Search') What would be the best way to accomplish this? [/INST] Look at the widgets documentation. Basically it would look like: q = forms.CharField(label='search', widget=forms.TextInput(attrs={'placeholder': 'Search'})) More writing, yes, but the separation allows for better abstraction of more complicated cases. You can also declare a widgets attribute containing a <field name> => <widget instance> mapping directly on the Meta of your ModelForm sub-class. </s>
<s>[INST] How to convert 2D float numpy array to 2D int numpy array? How to convert real numpy array to int numpy array? Tried using map directly to array but it did not work. [/INST] Use the astype method. >>> x = np.array([[1.0, 2.3], [1.3, 2.9]]) >>> x array([[ 1. , 2.3], [ 1.3, 2.9]]) >>> x.astype(int) array([[1, 2], [1, 2]]) </s>
<s>[INST] read subprocess stdout line by line My python script uses subprocess to call a linux utility that is very noisy. I want to store all of the output to a log file and show some of it to the user. I thought the following would work, but the output doesn't show up in my application until the utility has produced a significant amount of output. #fake_utility.py, just generates lots of output over time import time i = 0 while True: print hex(i)*512 i += 1 time.sleep(0.5) #filters output import subprocess proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE) for line in proc.stdout: #the real code does filtering here print "test:", line.rstrip() The behavior I really want is for the filter script to print each line as it is received from the subprocess. Sorta like what tee does but with python code. What am I missing? Is this even possible? Update: If a sys.stdout.flush() is added to fake_utility.py, the code has the desired behavior in python 3.1. I'm using python 2.6. You would think that using proc.stdout.xreadlines() would work the same as py3k, but it doesn't. Update 2: Here is the minimal working code. #fake_utility.py, just generates lots of output over time import sys, time for i in range(10): print i sys.stdout.flush() time.sleep(0.5) #display out put line by line import subprocess proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE) #works in python 3.0+ #for line in proc.stdout: for line in iter(proc.stdout.readline,''): print line.rstrip() [/INST] It's been a long time since I last worked with Python, but I think the problem is with the statement for line in proc.stdout, which reads the entire input before iterating over it. The solution is to use readline() instead: #filters output import subprocess proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE) while True: line = proc.stdout.readline() if line != '': #the real code does filtering here print "test:", line.rstrip() else: break Of course you still have to deal with the subprocess' buffering. Note: according to the documentation the solution with an iterator should be equivalent to using readline(), except for the read-ahead buffer, but (or exactly because of this) the proposed change did produce different results for me (Python 2.5 on Windows XP). </s>
<s>[INST] Is there a way to perform "if" in python's lambda In python 2.6, I want to do: f = lambda x: if x==2 print x else raise Exception() f(2) #should print "2" f(3) #should throw an exception This clearly isn't the syntax. Is it possible to perform an if in lambda and if so how to do it? thanks [/INST] The syntax you're looking for: lambda x: True if x % 2 == 0 else False But you can't use print or raise in a lambda. </s>
<s>[INST] Clearing Python lists Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python: old_list = [] old_list = list() The reason I ask is that I just saw this in some running code: del old_list[ 0:len(old_list) ] [/INST] Clearing a list in place will affect all other references of the same list. For example, this method doesn't affect other references: >>> a = [1, 2, 3] >>> b = a >>> a = [] >>> print(a) [] >>> print(b) [1, 2, 3] But this one does: >>> a = [1, 2, 3] >>> b = a >>> del a[:] # equivalent to del a[0:len(a)] >>> print(a) [] >>> print(b) [] >>> a is b True You could also do: >>> a[:] = [] </s>
<s>[INST] A simple way to remove multiple spaces in a string in Python Suppose this is the string: The fox jumped over the log. It would result in: The fox jumped over the log. What is the simplest, 1-2 liner that can do this? Without splitting and going into lists... [/INST] foo is your string: " ".join(foo.split()) </s>
<s>[INST] Can I install Python windows packages into virtualenvs? Virtualenv is great: it lets me keep a number of distinct Python installations so that different projects' dependencies aren't all thrown together into a common pile. But if I want to install a package on Windows that's packaged as a .exe installer, how can I direct it to install into the virtualenv? For example, I have pycuda-0.94rc.win32-py2.6.exe. When I run it, it examines the registry, and finds only one Python26 to install into, the common one that my virtualenv is based off of. How can I direct it to install into the virtualenv? [/INST] Yes, you can. All you need is easy_install binary_installer_built_with_distutils.exe Surprised? It looks like binary installers for Windows made with distutils combine .exe with .zip into one .exe file. Change extension to .zip to see it's a valid zip file. I discovered this after reading answers to my question Where can I download binary eggs with psycopg2 for Windows? UPDATE As noted by Tritium21 in his answer nowadays you should use pip instead of easy_install. Pip can't install binary packages created by distutils but it can install binary packages in the new wheel format. You can convert from old format to the new one using wheel package, which you have to install first. </s>
<s>[INST] Convert base-2 binary number string to int I'd simply like to convert a base-2 binary number string into an int, something like this: >>> '11111111'.fromBinaryToInt() 255 Is there a way to do this in Python? [/INST] You use the built-in [int() function][1], and pass it the base of the input number, i.e. 2 for a binary number: >>> int('11111111', 2) 255 Update: I removed the use of print so the above "code" is now compatible with either, as pointed out in a comment. The documentation link is also just to the current documentation, which is 3.x-aware but since the function exists in 2.x too that's not a big deal. </s>
<s>[INST] Using python map and other functional tools This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code: foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3] def maptest(foo, bar): print foo, bar map(maptest, foos, bars) produces: 1.0 1 2.0 2 3.0 3 4.0 None 5.0 None Q. Is there a way to use map or any other functional tools in python to produce the following without loops etc. 1.0 [1,2,3] 2.0 [1,2,3] 3.0 [1,2,3] 4.0 [1,2,3] 5.0 [1,2,3] Just as a side note how would the implementation change if there is a dependency between foo and bar. e.g. foos = [1.0,2.0,3.0,4.0,5.0] bars = [1,2,3,4,5] and print: 1.0 [2,3,4,5] 2.0 [1,3,4,5] 3.0 [1,2,4,5] ... P.S: I know how to do it naively using if, loops and/or generators, but I'd like to learn how to achieve the same using functional tools. Is it just a case of adding an if statement to maptest or apply another filter map to bars internally within maptest? [/INST] Are you familiar with other functional languages? i.e. are you trying to learn how python does functional programming, or are you trying to learn about functional programming and using python as the vehicle? Also, do you understand list comprehensions? map(f, sequence) is directly equivalent (*) to: [f(x) for x in sequence] In fact, I think map() was once slated for removal from python 3.0 as being redundant (that didn't happen). map(f, sequence1, sequence2) is mostly equivalent to: [f(x1, x2) for x1, x2 in zip(sequence1, sequence2)] (there is a difference in how it handles the case where the sequences are of different length. As you saw, map() fills in None when one of the sequences runs out, whereas zip() stops when the shortest sequence stops) So, to address your specific question, you're trying to produce the result: foos[0], bars foos[1], bars foos[2], bars # etc. You could do this by writing a function that takes a single argument and prints it, followed by bars: def maptest(x): print x, bars map(maptest, foos) Alternatively, you could create a list that looks like this: [bars, bars, bars, ] # etc. and use your original maptest: def maptest(x, y): print x, y One way to do this would be to explicitely build the list beforehand: barses = [bars] * len(foos) map(maptest, foos, barses) Alternatively, you could pull in the itertools module. itertools contains many clever functions that help you do functional-style lazy-evaluation programming in python. In this case, we want itertools.repeat, which will output its argument indefinitely as you iterate over it. This last fact means that if you do: map(maptest, foos, itertools.repeat(bars)) you will get endless output, since map() keeps going as long as one of the arguments is still producing output. However, itertools.imap is just like map(), but stops as soon as the shortest iterable stops. itertools.imap(maptest, foos, itertools.repeat(bars)) Hope this helps :-) (*) It's a little different in python 3.0. There, map() essentially returns a generator expression. </s>
<s>[INST] How to find all occurrences of an element in a list? index() will just give the first occurrence of an item in a list. Is there a neat trick which returns all indices in a list? [/INST] You can use a list comprehension: indices = [i for i, x in enumerate(my_list) if x == "whatever"] </s>
<s>[INST] How to check whether a variable is a class or not? I was wondering how to check whether a variable is a class (not an instance!) or not. I've tried to use the function isinstance(object, class_or_type_or_tuple) to do this, but I don't know what type would a class will have. For example, in the following code class Foo: pass isinstance(Foo, **???**) # i want to make this return True. I tried to substitute "class" with ???, but I realized that class is a keyword in python. [/INST] Even better: use the inspect.isclass function. >>> import inspect >>> class X(object): ... pass ... >>> inspect.isclass(X) True >>> x = X() >>> isinstance(x, X) True >>> y = 25 >>> isinstance(y, X) False </s>
<s>[INST] What is `related_name` used for in Django? What is the related_name argument useful for on ManyToManyField and ForeignKey fields? For example, given the following code, what is the effect of related_name='maps'? class Map(db.Model): members = models.ManyToManyField(User, related_name='maps', verbose_name=_('members')) [/INST] The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set, for instance User.map_set.all(). If you do specify, e.g. related_name=maps on the User model, User.map_set will still work, but the User.maps. syntax is obviously a bit cleaner and less clunky; so for example, if you had a user object current_user, you could use current_user.maps.all() to get all instances of your Map model that have a relation to current_user. The Django documentation has more details. </s>
<s>[INST] Cron and virtualenv I am trying to run a Django management command from cron. I am using virtualenv to keep my project sandboxed. I have seen examples here and elsewhere that show running management commands from within virtualenv's like: 0 3 * * * source /home/user/project/env/bin/activate && /home/user/project/manage.py command arg However, even though syslog shows an entry when the task should have started, this task never actually runs (the log file for the script is empty). If I run the line manually from the shell, it works as expected. The only way I can currently get the command to run via cron, is to break the commands up and put them in a dumb bash wrapper script: #!/bin/sh source /home/user/project/env/bin/activate cd /home/user/project/ ./manage.py command arg Please enlighten me what the difference is. What am I missing? Thanks EDIT: ars came up with a working combination of commands: 0 3 * * * cd /home/user/project && /home/user/project/env/bin/python /home/user/project/manage.py command arg At least in my case, invoking the activate script for the virtualenv did nothing. This works, so on with the show. [/INST] You should be able to do this by using the python in your virtual environment: /home/my/virtual/bin/python /home/my/project/manage.py command arg EDIT: If your django project isn't in the PYTHONPATH, then you'll need to switch to the right directory: cd /home/my/project && /home/my/virtual/bin/python ... You can also try to log the failure from cron: cd /home/my/project && /home/my/virtual/bin/python /home/my/project/manage.py > /tmp/cronlog.txt 2>&1 Another thing to try is to make the same change in your manage.py script at the very top: #!/home/my/virtual/bin/python </s>
<s>[INST] Python - When to use file vs open What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5) [/INST] You should always use open(). As the documentation states: When opening a file, it's preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing "isinstance(f, file)"). Also, file() has been removed since Python 3.0. </s>
<s>[INST] Safest way to convert float to integer in python? Python's math module contain handy functions like floor & ceil. These functions take a floating point number and return the nearest integer below or above it. However these functions return the answer as a floating point number. For example: import math f=math.floor(2.3) Now f returns: 2.0 What is the safest way to get an integer out of this float, without running the risk of rounding errors (for example if the float is the equivalent of 1.99999) or perhaps I should use another function altogether? [/INST] All integers that can be represented by floating point numbers have an exact representation. So you can safely use int on the result. Inexact representations occur only if you are trying to represent a rational number with a denominator that is not a power of two. That this works is not trivial at all! It's a property of the IEEE floating point representation that int∘floor = ⌊⋅⌋ if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1. To quote from Wikipedia, Any integer with absolute value less than or equal to 224 can be exactly represented in the single precision format, and any integer with absolute value less than or equal to 253 can be exactly represented in the double precision format. </s>
<s>[INST] What's the best practice using a settings file in Python? I have a command line script that I run with a lot of arguments. I have now come to a point where I have too many arguments, and I want to have some arguments in dictionary form too. So in order to simplify things I would like to run the script with a settings file instead. I don't really know what libraries to use for the parsing of the file. What's the best practice for doing this? I could of course hammer something out myself, but if there is some library for this, I'm all ears. A few 'demands': Rather than using pickle I would like it to be a straight forward text file that can easily be read and edited. I wan't to be able to add dictionary-like data in it, i.e., some form of nesting should be supported. A simplified pseudo example file: truck: color: blue brand: ford city: new york cabriolet: color: black engine: cylinders: 8 placement: mid doors: 2 [/INST] You can have a regular Python module, say config.py, like this : truck = dict( color = 'blue', brand = 'ford', ) city = 'new york' cabriolet = dict( color = 'black', engine = dict( cylinders = 8, placement = 'mid', ), doors = 2, ) and use it like that : import config print config.truck['color'] </s>
<s>[INST] Alphabet range python Instead of making a list of alphabet like this: alpha = ['a', 'b', 'c', 'd'.........'z'] Is there any way that we can group it to a range or something? For example, for numbers it can be grouped using range() range(1, 10) [/INST] >>> import string >>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' If you really need a list: >>> list(string.ascii_lowercase) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] And to do it with range >>> list(map(chr, range(97, 123))) #or list(map(chr, range(ord('a'), ord('z')+1))) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] Other helpful string module features: >>> help(string) # on Python 3 .... DATA ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits = '0123456789' hexdigits = '0123456789abcdefABCDEF' octdigits = '01234567' printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c' punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' whitespace = ' \t\n\r\x0b\x0c' </s>
<s>[INST] PyCharm shows unresolved references error for valid code I am using PyCharm to work on a project. The project is opened and configured with an interpreter, and can run successfully. The remote interpreter paths are mapped properly. This seems to be the correct configuration, but PyCharm is highlighting my valid code with "unresolved reference" errors, even for built-in Python functions. Why don't these seem to be detected, even though the code runs? Is there any way to get PyCharm to recognize these correctly? This specific instance of the problem is with a remote interpreter, but the problem appears on local interpreters as well. [/INST] File | Invalidate Caches... and restarting PyCharm helps. </s>
<s>[INST] How to print an error in Python? try: something here except: print 'the whatever error occurred.' How can I print the error in my except: block? [/INST] except Exception,e: print str(e) </s>
<s>[INST] Why are pandas merges in python faster than data.table merges in R? I recently came across the pandas library for python, which according to this benchmark performs very fast in-memory merges. It's even faster than the data.table package in R (my language of choice for analysis). Why is pandas so much faster than data.table? Is it because of an inherent speed advantage python has over R, or is there some tradeoff I'm not aware of? Is there a way to perform inner and outer joins in data.table without resorting to merge(X, Y, all=FALSE) and merge(X, Y, all=TRUE)? Here's the R code and the Python code used to benchmark the various packages. [/INST] The reason pandas is faster is because I came up with a better algorithm, which is implemented very carefully using a fast hash table implementation - klib and in C/Cython to avoid the Python interpreter overhead for the non-vectorizable parts. The algorithm is described in some detail in my presentation: A look inside pandas design and development. The comparison with data.table is actually a bit interesting because the whole point of R's data.table is that it contains pre-computed indexes for various columns to accelerate operations like data selection and merges. In this case (database joins) pandas' DataFrame contains no pre-computed information that is being used for the merge, so to speak it's a "cold" merge. If I had stored the factorized versions of the join keys, the join would be significantly faster - as factorizing is the biggest bottleneck for this algorithm. I should also add that the internal design of pandas' DataFrame is much more amenable to these kinds of operations than R's data.frame (which is just a list of arrays internally). </s>
<s>[INST] Ubuntu running `pip install` gives error 'The following required packages can not be built: * freetype' When performing pip install -r requirements.txt, I get the following error during the stage where it is installing matplotlib: REQUIRED DEPENDENCIES AND EXTENSIONS numpy: yes [not found. pip may install it below.] dateutil: yes [dateutil was not found. It is required for date axis support. pip/easy_install may attempt to install it after matplotlib.] tornado: yes [tornado was not found. It is required for the WebAgg backend. pip/easy_install may attempt to install it after matplotlib.] pyparsing: yes [pyparsing was not found. It is required for mathtext support. pip/easy_install may attempt to install it after matplotlib.] pycxx: yes [Couldn't import. Using local copy.] libagg: yes [pkg-config information for 'libagg' could not be found. Using local copy.] freetype: no [pkg-config information for 'freetype2' could not be found.] ... The following required packages can not be built: * freetype Shouldn't pip install -r requirements.txt also install freetype? How should freetype be installed in Ubuntu 12.04 so it works with matplotlib? [/INST] No. pip will not install system-level dependencies. This means pip will not install RPM(s) (Redhat based systems) or DEB(s) (Debian based systems). To install system dependencies you will need to use one of the following methods depending on your system. Ubuntu/Debian: apt-get install libfreetype6-dev To search for packages on Ubuntu/Debian based systems: apt-cache search <string> e.g: apt-cache search freetype | grep dev Redhat/CentOS/Fedora: yum -y install freetype-devel To search for packages on Redhat/CentOS/Fedora based systems: yum search <string> e.g: yum search freetype | grep devel Mac OS X: (via Homebrew) brew install freetype To search for packages on Redhat/CentOS/Fedora based systems: brew search <string> e.g: brew search freetype </s>
<s>[INST] How to check which version of Numpy I'm using? How can I check which version of Numpy I'm using? I'm using Mac OS X 10.6.1 Snow Leopard. [/INST] import numpy numpy.version.version </s>
<s>[INST] How do I look inside a Python object? I'm starting to code in various projects using Python (including Django web development and Panda3D game development). To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. So say I have a Python object, what would I need to print out its contents? Is that even possible? [/INST] Python has a strong set of introspection features. Take a look at the following built-in functions: type() dir() id() getattr() hasattr() globals() locals() callable() type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively. </s>
<s>[INST] Most efficient way to reverse a numpy array Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the common view-based method: reversed_arr = arr[::-1] Is there any other way to do it more efficiently, or is it just an illusion from my obsession with unrealistic numpy performance? [/INST] When you create reversed_arr you are creating a view into the original array. You can then change the original array, and the view will update to reflect the changes. Are you re-creating the view more often than you need to? You should be able to do something like this: arr = np.array(some_sequence) reversed_arr = arr[::-1] do_something(arr) look_at(reversed_arr) do_something_else(arr) look_at(reversed_arr) I'm not a numpy expert, but this seems like it would be the fastest way to do things in numpy. If this is what you are already doing, I don't think you can improve on it. P.S. Great discussion of numpy views here: View onto a numpy array? </s>
<s>[INST] What does -> mean in Python function definitions? I've recently noticed something interesting when looking at Python 3.3 grammar specification: funcdef: 'def' NAME parameters ['->' test] ':' suite The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in Python 3. It turns out this is correct Python and it's accepted by the interpreter: def f(x) -> 123: return x I thought that this might be some kind of a precondition syntax, but: I cannot test x here, at it is still undefined, No matter what I put after the arrow (e.g. 2 < 1), it doesn't affect the function behaviour. Could anyone accustomed with this syntax explain it? [/INST] It's a function annotation. In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values. There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring. </s>
<s>[INST] How to delete an item in a list if it exists? I am getting new_tag from a form text field with self.response.get("new_tag") and selected_tags from checkbox fields with self.response.get_all("selected_tags") I combine them like this: tag_string = new_tag new_tag_list = f1.striplist(tag_string.split(",") + selected_tags) (f1.striplist is a function that strips white spaces inside the strings in the list.) But in the case that tag_list is empty (no new tags are entered) but there are some selected_tags, new_tag_list contains an empty string " ". For example, from logging.info: new_tag selected_tags[u'Hello', u'Cool', u'Glam'] new_tag_list[u'', u'Hello', u'Cool', u'Glam'] How do I get rid of the empty string? If there is an empty string in the list: >>> s = [u'', u'Hello', u'Cool', u'Glam'] >>> i = s.index("") >>> del s[i] >>> s [u'Hello', u'Cool', u'Glam'] But if there is no empty string: >>> s = [u'Hello', u'Cool', u'Glam'] >>> if s.index(""): i = s.index("") del s[i] else: print "new_tag_list has no empty string" But this gives: Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> if new_tag_list.index(""): ValueError: list.index(x): x not in list Why does this happen, and how do I work around it? [/INST] 1) Almost-English style: Test for presence using the in operator, then apply the remove method. if thing in some_list: some_list.remove(thing) The removemethod will remove only the first occurrence of thing, in order to remove all occurrences you can use while instead of if. while thing in some_list: some_list.remove(thing) Simple enough, probably my choice.for small lists (can't resist one-liners) 2) Duck-typed, EAFP style: This shoot-first-ask-questions-last attitude is common in Python. Instead of testing in advance if the object is suitable, just carry out the operation and catch relevant Exceptions: try: some_list.remove(thing) except ValueError: pass # or scream: thing not in some_list! except AttributeError: pass # call security, some_list not quacking like a list! If you expect multiple occurrences of thing: while True: try: some_list.remove(thing) except ValueError: break a little verbose for this specific use case, but very idiomatic in Python. this performs better than #1 PEP 463 proposed a shorter syntax for try/except simple usage that would be handy here, but it was not approved. However, with contextlib's suppress() contextmanager (introduced in python 3.4) the above code can be simplified to this: with suppress(ValueError, AttributeError): some_list.remove(thing) Again, if you expect multiple occurrences of thing: with suppress(ValueError): while True: some_list.remove(thing) 3) Functional style: Around 1993, Python got lambda, reduce(), filter() and map(), courtesy of a Lisp hacker who missed them and submitted working patches*. You can use filter to remove elements from the list: is_not_thing = lambda x: x is not thing cleaned_list = filter(is_not_thing, some_list) There is a shortcut that may be useful for your case: if you want to filter out empty items (in fact items where bool(item) == False, like None, zero, empty strings or other empty collections), you can pass None as the first argument: cleaned_list = filter(None, some_list) [update]: in Python 2.x, filter(function, iterable) used to be equivalent to [item for item in iterable if function(item)] (or [item for item in iterable if item] if the first argument is None); in Python 3.x, it is now equivalent to (item for item in iterable if function(item)). The subtle difference is that filter used to return a list, now it works like a generator expression - this is OK if you are only iterating over the cleaned list and discarding it, but if you really need a list, you have to enclose the filter() call with the list() constructor. *These Lispy flavored constructs are considered a little alien in Python. Around 2005, Guido was even talking about dropping filter - along with companions map and reduce (they are not gone yet but reduce was moved into the functools module, which is worth a look if you like high order functions). 4) Mathematical style: List comprehensions became the preferred style for list manipulation in Python since introduced in version 2.0 by PEP 202. The rationale behind it is that List comprehensions provide a more concise way to create lists in situations where map() and filter() and/or nested loops would currently be used. cleaned_list = [ x for x in some_list if x is not thing ] Generator expressions were introduced in version 2.4 by PEP 289. A generator expression is better for situations where you don't really need (or want) to have a full list created in memory - like when you just want to iterate over the elements one at a time. If you are only iterating over the list, you can think of a generator expression as a lazy evaluated list comprehension: for item in (x for x in some_list if x is not thing): do_your_thing_with(item) See this Python history blog post by GvR. This syntax is inspired by the set-builder notation in math. Python 3 has also set and dict comprehensions. Notes you may want to use the inequality operator != instead of is not (the difference is important) for critics of methods implying a list copy: contrary to popular belief, generator expressions are not always more efficient than list comprehensions - please profile before complaining </s>
<s>[INST] Change the name of a key in dictionary I want to change the key of an entry in a Python dictionary. Is there a straightforward way to do this? [/INST] Easily done in 2 steps: dictionary[new_key] = dictionary[old_key] del dictionary[old_key] Or in 1 step: dictionary[new_key] = dictionary.pop(old_key) which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete dictionary[old_key]. >>> dictionary = { 1: 'one', 2:'two', 3:'three' } >>> dictionary['ONE'] = dictionary.pop(1) >>> dictionary {2: 'two', 3: 'three', 'ONE': 'one'} >>> dictionary['ONE'] = dictionary.pop(1) Traceback (most recent call last): File "<input>", line 1, in <module> KeyError: 1 </s>
<s>[INST] Get a filtered list of files in a directory I am trying to get a list of files in a directory using Python, but I do not want a list of ALL the files. What I essentially want is the ability to do something like the following but using Python and not executing ls. ls 145592*.jpg If there is no built-in method for this, I am currently thinking of writing a for loop to iterate through the results of an os.listdir() and to append all the matching files to a new list. However, there are a lot of files in that directory and therefore I am hoping there is a more efficient method (or a built-in method). [/INST] glob.glob('145592*.jpg') </s>
<s>[INST] How do I fix PyDev "Undefined variable from import" errors? I've got a Python project using PyDev in Eclipse, and PyDev keeps generating false errors for my code. I have a module settings that defines a settings object. I import that in module b and assign an attribute with: from settings import settings settings.main = object() In some of my code--but not all of it, statements like: from settings import settings print settings.main ... generate "Undefined variable from import: main" messages in the Eclipse code error pane, even though the code runs without a problem. How can I correct these? [/INST] For code in your project, the only way is adding a comment saying that you expected that (the static code-analysis only sees what you see, not runtime info -- if you opened that module yourself, you'd have no indication that main was expected). You can use ctrl+1 (Cmd+1 for Mac) in a line with an error and pydev will present you an option to add a comment to ignore that error. If it was some external module, you could add it to the forced builtins so that it was forced to be analyzed by a running shell with runtime information (see http://pydev.org/manual_101_interpreter.html for details). Another option could be creating a 'stub' yourself and adding it to the 'predefined' completions (http://pydev.org/manual_101_interpreter.html also has details on that). </s>
<s>[INST] Maximum recursion depth? I have this tail recursive function here: def fib(n, sum): if n < 1: return sum else: return fib(n-1, sum+n) c = 998 print(fib(c, 0)) It works up to n=997, then it just breaks and spits a "maximum recursion depth exceeded in comparison" RuntimeError. Is this just a stack overflow? Is there a way to get around it? [/INST] It is a guard against a stack overflow, yes. Python (or rather, the CPython implementation) doesn't optimize tail recursion, and unbridled recursion causes stack overflows. You can change the recursion limit with sys.setrecursionlimit, but doing so is dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big. Python isn't a functional language and tail recursion is not a particularly efficient technique. Rewriting the algorithm iteratively, if possible, is generally a better idea. </s>
<s>[INST] What is the '@=' symbol for in Python? I know @ is for decorators, but what is @= for in Python? Is it just reservation for some future idea? This is just one of my many questions while reading tokenizer.py. [/INST] From the documentation: The @ (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator. The @ operator was introduced in Python 3.5. @= is matrix multiplication followed by assignment, as you would expect. They map to __matmul__, __rmatmul__ or __imatmul__ similar to how + and += map to __add__, __radd__ or __iadd__. The operator and the rationale behind it are discussed in detail in PEP 465. </s>
<s>[INST] How do I find the time difference between two datetime objects in python? How do I tell the time difference in minutes between two datetime objects? [/INST] >>> import datetime >>> a = datetime.datetime.now() >>> b = datetime.datetime.now() >>> c = b - a datetime.timedelta(0, 8, 562000) >>> divmod(c.days * 86400 + c.seconds, 60) (0, 8) # 0 minutes, 8 seconds </s>