title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
How to print backslash with Python?
19,095,796
25
2013-09-30T13:42:01Z
19,095,908
19
2013-09-30T13:47:45Z
[ "python", "python-2.7" ]
When I write: `print '\'` or `print "\"` or `print "'\'"` Python doesn't print me the backslash `\` symbol. **What should I do to get the expected result?**
Another clue, if you're trying to accomplish something more complicated than just printing a backlash, you can declare a string as `raw` (with and `r` in front of it) and it will print all its characters as is: ``` >>> s = r'\abc\def' >>> print s '\abc\def' ``` This is useful for regular expressions. You can find [mo...
setuptools and pip: choice of minimal and complete install
19,096,155
7
2013-09-30T13:58:45Z
19,096,782
11
2013-09-30T14:27:55Z
[ "python", "pip", "setuptools" ]
We've made a library which depends on other libraries. But there are necessary (e.g. for server batch processing) and optional dependencies (e.g. for clients with GUI). Is something like this possible: ``` pip install mylib.tar.gz # automatically downloads and installs with the minimal set of dependencies pip insta...
You can install the packages in `extras_require` by appending the name of the recommended dependency in square brackets (i.e. `[mpl]` or `[bn]` in your case) to the package name in pip. So to install 'mylib' with the additional requirements, you would call pip like this: ``` pip install 'mylib[mpl]' pip install 'myli...
python re find string that may contain brackets
19,097,647
6
2013-09-30T15:07:54Z
19,097,703
10
2013-09-30T15:10:35Z
[ "python", "regex", "string" ]
I am trying to search for a string that may contain brackets or other characters that may not be interpreted as plain strings. ``` def findstring(string, text): match = re.search(string, text) ``` I do not control the string as it is derived from another module. My problem is that the string may contain **"xyz)"*...
You can use [`re.escape()`](http://docs.python.org/2/library/re.html#re.escape) to escape the string: ``` match = re.search(re.escape(string), text) ``` From docs: > Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression ...
Python opencv2 (cv2) wrapper get image size?
19,098,104
23
2013-09-30T15:29:04Z
19,098,258
55
2013-09-30T15:37:37Z
[ "python", "image", "opencv", "numpy" ]
How to get size of image in `cv2` wrapper in Python OpenCV (numpy). Is there a correct way to do that than `numpy.shape()`. How to get it in format dimensions: (width, height) list? Thanks
`cv2` uses `numpy` for manipulating images, so the proper and best way to get the size of an image is using `numpy.shape`. Assuming you are working with BGR images, here is an example: ``` >>> import numpy as np >>> import cv2 >>> img = cv2.imread('foo.jpg') >>> height, width, channels = img.shape >>> print height, wi...
Flask: setting application and request-specific attributes?
19,098,295
11
2013-09-30T15:39:31Z
19,103,241
21
2013-09-30T20:29:05Z
[ "python", "mongodb", "flask", "pymongo" ]
I am writing an application which connects to a database. I want to create that db connection once, and then reuse that connection throughout the life of the application. I also want to authenticate users. A user's auth will live for only the life of a request. How can I differentiate between objects stored for the l...
`flask.g` will only store things for the duration of a request. The documentation mentioned that the values are stored on the application context rather than the request, but that is more of an implementation issue: it doesn't change the fact that objects in `flask.g` are only available in the same thread, and during t...
python password generator for django
19,098,426
5
2013-09-30T15:45:54Z
19,098,490
7
2013-09-30T15:49:12Z
[ "python", "django" ]
How can I manually generate password for django? For example, in other application, but using the same database as django .For username 'admin' password like this ``` pbkdf2_sha256$10000$T0BzrDwfZSrI$pSgvDEam9V9jcdYpYDVkYMMwtSnRrFdf6Aqow82Tjr8= ```
I think this maybe what you are looking for : [Manually managing a user’s password](https://docs.djangoproject.com/en/dev/topics/auth/passwords/#module-django.contrib.auth.hashers) > **make\_password(password[, salt, hashers])** > > Creates a hashed password in > the format used by this application. It takes one ma...
psycopg2 not returning results
19,098,551
7
2013-09-30T15:53:28Z
19,098,620
8
2013-09-30T15:56:48Z
[ "python", "postgresql", "psycopg2" ]
I am trying to use `psycopg2` with my postgresql database just running on my local machine can't get it to return results no matter what I try. It seems to connect to the database ok, since if I alter any of the config parameters it throws errors, however, when I run seemingly valid and result worthy queries, I get not...
`cursor.execute` prepares and executes query but doesn’t fetch any data, and `None` is expected return type. If you want to retrieve query result you have to use one of this: ``` print cur.fetchone() rows_to_fetch = 3 print cur.fetchmany(rows_to_fetch) print cur.fetchall() ```
Is it possible to remove a break point set with ipdb.set_trace()?
19,098,850
11
2013-09-30T16:09:07Z
19,101,630
16
2013-09-30T18:52:26Z
[ "python", "debugging", "ipdb" ]
I used `ipdb.set_trace()` somewhere in my Python code. Is it possible to ignore this break point using a IPDB command? `clear` tells me that it cleared all break points, but IPDB stops again when it stumbles upon the line with `ipdb.set_trace()`. `disable 1` tells me: `No breakpoint numbered 1` `ignore 1` says: `Brea...
Well, you CAN take advantage of the fact that anything in Python is an object. While in the debugger, you can do something like this: ``` def f(): pass ipdb.set_trace = f ``` set\_trace will still be called, but it won't do anything. Of course, it's somewhat permanent, but you can just do ``` reload ipdb ``` and yo...
Prevent CSS/other resource download in PhantomJS/Selenium driven by Python
19,099,070
11
2013-09-30T16:20:53Z
19,297,876
7
2013-10-10T14:00:18Z
[ "python", "selenium", "web-scraping", "phantomjs", "headless-browser" ]
I'm trying to speed up Selenium/PhantomJS webscraper in Python by preventing download of CSS/other resources. All I need to download is img src and alt tags. I've found this code: ``` page.onResourceRequested = function(requestData, request) { if ((/http:\/\/.+?\.css/gi).test(requestData['url']) || requestData['Co...
A bold young soul by the name of “watsonmw” [recently added](https://github.com/detro/ghostdriver/commit/d9b65ed014ed9ff8a5e852cc40e59a0fd66d0cf1) functionality to Ghostdriver (which Phantom.js uses to interface with Selenium) that allows access to [Phantom.js API calls which require a page object](http://phantomjs...
Rounding entries in a Pandas DafaFrame
19,100,540
8
2013-09-30T17:47:12Z
19,101,948
15
2013-09-30T19:11:55Z
[ "python", "numpy", "pandas" ]
Using : ``` newdf3.pivot_table(rows=['Quradate'],aggfunc=np.mean) ``` which yields: ``` Alabama_exp Credit_exp Inventory_exp National_exp Price_exp Sales_exp Quradate 2010-01-15 0.568003 0.404481 0.488601 0.483097 0.431211 0.570755 2010-04-15 0.543620 ...
Just use `numpy.round`, e.g.: ``` 100 * np.round(newdf3.pivot_table(rows=['Quradate'], aggfunc=np.mean), 2) ``` As long as round is appropriate for all column types, this works on a `DataFrame`. With some data: ``` In [9]: dfrm Out[9]: A B C 0 -1.312700 0.760710 1.044006 1 -0.792521 -0.0...
After submitting form, how to wait for element to load before clicking on said element? (Selenium / Python)
19,100,695
3
2013-09-30T17:55:49Z
19,100,736
9
2013-09-30T17:58:12Z
[ "python", "python-2.7", "selenium", "selenium-webdriver" ]
I'm using Selenium and coding in Python. After I submit a Javascript form, the page proceeds to load dynamically for results. I am essentially waiting for an element (a specific button link) to appear / finish loading so I can click on it. How do I go about doing this?
You can use `WebDriverWait`, Documentation [here](http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp), ``` from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 from selenium.webdriver.support import expected_co...
Find minimum distance from point to complicated curve
19,101,864
13
2013-09-30T19:06:56Z
19,869,154
12
2013-11-08T21:51:15Z
[ "python", "numpy", "scipy", "interpolation", "spline" ]
I have a complicated curve defined as a set of points in a table like so (the full table is [here](http://pastebin.com/1w1dUXQy)): ``` # x y 1.0577 12.0914 1.0501 11.9946 1.0465 11.9338 ... ``` If I plot this table with the commands: ``` plt.plot(x_data, y_data, c='b',lw=1.) plt.scatter(x_data, y_data, marker=...
If you're open to using a library for this, have a look at `shapely`: <https://github.com/Toblerity/Shapely> As a quick example (`points.txt` contains the data you linked to in your question): ``` import shapely.geometry as geom import numpy as np coords = np.loadtxt('points.txt') line = geom.LineString(coords) poi...
overloading unittest.testcase in python
19,102,203
4
2013-09-30T19:27:24Z
19,102,520
11
2013-09-30T19:46:52Z
[ "python", "constructor", "testcase" ]
I'm trying to create a custom unit test framework by sub-classing the unittest.testcase class but seem to make a mistake when dealing with the `__init__` method. I cannot figure out why the constructor of `ComplexTest` doesn't get invoked before the one in `BasicTest` and the exception also seems to be related to my c...
Indeed your init method is wrong. ``` class BasicTest(unittest.TestCase): def __init__(self, *args, **kwargs): print('BasicTest.__init__') super(unittest.TestCase, self).__init__(*args, **kwargs) ``` Should be: ``` class BasicTest(unittest.TestCase): def __init__(self, *args, **kwargs): ...
python string formatting Columns in line
19,103,052
6
2013-09-30T20:18:03Z
19,103,221
16
2013-09-30T20:27:43Z
[ "python" ]
I am trying to format the string so everything lines up between the two. ``` APPLES $.99 214 kiwi $1.09 755 ``` I am trying this by doing: ``` fmt = ('{0:30}{1:30}{2:30}'.format(Fruit,pric...
`str.format()` is making your fields left aligned within the available space. Use [alignment specifiers](http://docs.python.org/2/library/string.html#format-specification-mini-language) to change the alignment: > `'<'` Forces the field to be left-aligned within the available space (this is the default for most objects...
Load CSV to Pandas MultiIndex DataFrame
19,103,624
10
2013-09-30T20:52:39Z
19,103,754
14
2013-09-30T21:01:13Z
[ "python", "csv", "numpy", "pandas" ]
I have a 719mb CSV file that looks like: ``` from, to, dep, freq, arr, code, mode (header row) RGBOXFD,RGBPADTON,127,0,27,99999,2 RGBOXFD,RGBPADTON,127,0,33,99999,2 RGBOXFD,RGBRDLEY,127,0,1425,99999,2 RGBOXFD,RGBCHOLSEY,127,0,52,99999,2 RGBOXFD,RGBMDNHEAD,127,0,91,99999,2 RGBDIDCOTP,RGBPADTON,127,0,46,99999,2 RGBDID...
You could use [`pd.read_csv`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html): ``` >>> df = pd.read_csv("test_data2.csv", index_col=[0,1], skipinitialspace=True) >>> df dep freq arr code mode from to RGBOXFD...
Python Dictionary Searching
19,103,785
18
2013-09-30T21:02:58Z
19,103,878
20
2013-09-30T21:08:45Z
[ "python", "search", "optimization", "dictionary" ]
I had a quick question about efficiency of searching through LARGE dictionaries in python. I am reading a large comma-separated file and getting a key and value from each line. If my key is already in the dictionary, I'm adding the value to the value listed in the dictionary, if the key doesn't exist in the dictionary,...
The problem is that for every test you're generating a new list of keys with `.keys()`. As the list of keys gets longer, the time required goes up. Also [as noted by dckrooney](http://stackoverflow.com/a/19103936/5987), the search for the key becomes linear instead of taking advantage of the hash-table structure of the...
List comprehension in python, how to?
19,104,760
2
2013-09-30T22:10:27Z
19,104,778
8
2013-09-30T22:12:05Z
[ "python", "list-comprehension" ]
I am reading about Python and I want to do a problem with list comprehensions. The problem is simple: ``` Write a Program that gives the sum of the multiples of 3 and 5 before some n take n = 1000 (Euler project, 1st problem) ``` I want to do something like this: ``` [mysum = mysum + i for i in range(2,1000) if i...
The point of list comprehensions is to generate a list of result values, one per source value (or one per *matching* source value, if you have `if` clauses). In other words, it's the same thing as `map` (or a chain of `map` and `filter` calls, if you have multiple clauses), except that you can describe each new value ...
Assign action to variable in Automator for use in Shell Script
19,105,461
3
2013-09-30T23:17:30Z
19,123,832
9
2013-10-01T19:00:25Z
[ "python", "osx", "shell", "variables", "automator" ]
![enter image description here](http://i.stack.imgur.com/8woRc.png) Ok, this thing is driving me crazy right now. So Action 1 Chooses a Folder (I want to save that folder's path as var\_1) and Action 3 Selects a File (I want to save this file's path as var\_2) so in the end . . . ``` var_1 = '/Users/Prometheus/Deskt...
The Automator variables are only used in the Automator workflow. The variable themselves are not directly accessible to either a shell script or a Python script. The `Run Shell Script` action allows you to pass the values of particular variables to a shell script in either of two ways: either piping them in through `st...
Get MM-DD-YYYY from pandas Timestamp
19,105,976
13
2013-10-01T00:16:51Z
19,106,012
24
2013-10-01T00:19:43Z
[ "python", "date", "pandas" ]
dates seem to be a tricky thing in python, and I am having a lot of trouble simply stripping the date out of the pandas TimeStamp. I would like to get from `2013-09-29 02:34:44` to simply `09-29-2013` I have a dataframe with a column Created\_date: ``` Name: Created_Date, Length: 1162549, dtype: datetime64[ns]` ``` ...
`map` over the elements: ``` In [239]: from operator import methodcaller In [240]: s = Series(date_range(Timestamp('now'), periods=2)) In [241]: s Out[241]: 0 2013-10-01 00:24:16 1 2013-10-02 00:24:16 dtype: datetime64[ns] In [238]: s.map(lambda x: x.strftime('%d-%m-%Y')) Out[238]: 0 01-10-2013 1 02-10-20...
How to implement SSDP / UPnP? Trying to use Sony's camera API
19,106,672
4
2013-10-01T01:46:36Z
20,851,540
11
2013-12-31T04:06:08Z
[ "python", "http", "httprequest", "upnp", "ssdp" ]
I'm a total beginner to HTTP requests, but I'd like to write a Python app that uses [Sony's API](http://d.pr/f/gRoD) for controlling its Wi-Fi cameras. For now, I'm just trying to talk to the camera at all, but my get request keeps failing. I have all the docs (the UPnP documentation, SSDP doc, user's manual, etc.) but...
``` import sys import socket SSDP_ADDR = "239.255.255.250"; SSDP_PORT = 1900; SSDP_MX = 1; SSDP_ST = "urn:schemas-sony-com:service:ScalarWebAPI:1"; ssdpRequest = "M-SEARCH * HTTP/1.1\r\n" + \ "HOST: %s:%d\r\n" % (SSDP_ADDR, SSDP_PORT) + \ "MAN: \"ssdp:discover\"\r\n" + \ ...
Python patch object with a side_effect
19,107,424
7
2013-10-01T03:26:02Z
19,107,511
11
2013-10-01T03:37:11Z
[ "python", "unit-testing", "mocking" ]
I'm trying to have a Mock object return certain values based on the input given. I looked up a few examples on SO and for some reason I still can't get it to work. Here's what I have right now. ``` class EmailChecker(): def is_email_correct(email): some regex to determine if email is valid, returns either ...
Use `patch.object` as decorator or context manager as following code. ``` >>> class EmailChecker(): ... def is_email_correct(self, email): ... pass ... >>> def my_side_effect(*args): ... if args[0] == '1': ... return True ... else: ... return False ... >>> with mock.patch.object(E...
How to alter the time in python?
19,108,181
5
2013-10-01T04:45:30Z
19,108,277
8
2013-10-01T04:54:26Z
[ "python", "datetime" ]
I wanted to change the minutes/hours of pythonic time. I have a string of time `start_time = "2013-09-30 14:12:08.024923"`. I want it to convert it to its ceil quater,half or full time, ie if I set interval as `15` I should get `2013-09-30 14:15:00.0000`. If interval is `30`, I should get `2013-09-30 14:15:00.0000` Ho...
You can do this with `replace`: ``` start_time = start_time.replace(minute=ceil_to, second=0, microsecond=0) ```
Python: why not (a, b, c) = (*x, 3)
19,108,907
7
2013-10-01T05:50:36Z
19,108,991
8
2013-10-01T05:57:03Z
[ "python" ]
So apparently I can't do this in Python (2.7): ``` x = (1, 2,) (a, b, c) = (*x, 3) ``` It made sense in my head, but well... I could create a function: ``` make_tuple = lambda *elements: tuple(elements) ``` then I can do ``` (c, a, b) = make_tuple(3, *x) ``` but not, for example ``` (a, b, c) = make_tuple(*x, 3)...
In response to question 1, read the [PEP 448](http://www.python.org/dev/peps/pep-0448/) and [bug 2292](http://bugs.python.org/issue2292). Also interesting is the discussion in the [mailing list](https://mail.python.org/pipermail/python-dev/2005-October/057163.html). In resume what you want should be allowed in Python 3...
numpy: how to select rows based on a bunch of criteria
19,111,450
5
2013-10-01T08:31:05Z
19,117,413
10
2013-10-01T13:25:06Z
[ "python", "arrays", "numpy" ]
How can I fetch the rows for which the second column equals to 4 or 6? ``` a = np.array(np.mat('1 2; 3 4; 5 6; 7 4')) b = [4,6] ``` Apparently, this does not work: ``` c = a[a[:,1] in b] ```
The numpythonic way of doing this would be to use [`in1d`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html), something like: ``` a[np.in1d(a[:, 1], b)] ```
Getting list of lists into pandas DataFrame
19,112,398
37
2013-10-01T09:19:40Z
19,112,890
67
2013-10-01T09:41:12Z
[ "python", "pandas", "datanitro" ]
I am reading contents of a spreadsheet into pandas. DataNitro has a method that returns a rectangular selection of cells as a list of lists. So ``` table = Cell("A1").table ``` gives ``` table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]] headers = table.pop(0) # gives the headers as list and leaves data ``` I am ...
The following gives what you want: ``` df = DataFrame(table, columns=headers) df ``` outputs ``` Out[7]: Heading1 Heading2 0 1 2 1 3 4 ```
Getting list of lists into pandas DataFrame
19,112,398
37
2013-10-01T09:19:40Z
34,996,876
10
2016-01-25T15:59:49Z
[ "python", "pandas", "datanitro" ]
I am reading contents of a spreadsheet into pandas. DataNitro has a method that returns a rectangular selection of cells as a list of lists. So ``` table = Cell("A1").table ``` gives ``` table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]] headers = table.pop(0) # gives the headers as list and leaves data ``` I am ...
With approach explained by EdChum above, the values in the list are shown as rows. To show the values of lists as columns in dataFrame instead, simply use transpose() as following: ``` table = [[1 , 2], [3, 4]] df = DataFrame(table) df = df.transpose() cols = ['Heading1', 'Heading2'] df.columns = cols ``` The output ...
Trying to run KIVY, for the first time
19,113,270
6
2013-10-01T09:59:58Z
19,114,092
14
2013-10-01T10:39:36Z
[ "python", "kivy" ]
I'm trying to run kivy for the first time. Im using a default program. ``` from kivy.app import App from kivy.uix.widget import Widget class PongGame(Widget): pass class PongApp(App): def build(self): return PongGame() if __name__ == '__main__': PongApp().run() ``` I get this error: ``` ###...
**UPDATE**: based on the error you're getting—which you just pasted now, after my original response below—, you seem to be missing not only PyGame but Kivy itself. Go ahead and run `pip install kivy`. But before you do that, I'd recommend you take a look at [virtualenv](http://www.virtualenv.org/en/latest/) and in...
How to parse broken HTML with LXML
19,118,238
11
2013-10-01T14:01:08Z
19,118,319
13
2013-10-01T14:04:55Z
[ "python", "lxml" ]
I'm trying to parse a broken HTML with LXML parser on python 2.5 and 2.7 Unlike in LXML documentation (<http://lxml.de/parsing.html#parsing-html>) parsing a broken HTML does not work: ``` from lxml import etree import StringIO broken_html = "<html><head><title>test<body><h1>page title</h3>" parser = etree.HTMLParser(...
Don't just construct that parser, use it (as per the example you link to): ``` >>> tree = etree.parse(StringIO.StringIO(broken_html), parser=parser) >>> tree <lxml.etree._ElementTree object at 0x2fd8e60> ``` Or use `lxml.html` as a shortcut: ``` >>> from lxml import html >>> broken_html = "<html><head><title>test<bo...
How to use flask-sqlalchemy with existing sqlalchemy model?
19,119,725
6
2013-10-01T15:06:39Z
19,121,073
7
2013-10-01T16:13:29Z
[ "python", "sqlalchemy", "flask", "flask-sqlalchemy" ]
I've read [flask-sqlalchemy or sqlalchemy](http://stackoverflow.com/questions/14343740/flask-sqlalchemy-or-sqlalchemy) which recommends use of flask-sqlalchemy with flask. I want to follow this approach. However, I have an existing model written for command line scripts which is based on sqlalchemy's declarative\_base...
Currently, this is something that is not well supported, but not impossible to do. See [this issue](https://github.com/mitsuhiko/flask-sqlalchemy/issues/98) on the Flask-SQLAlchemy issue list, which admits that the current implementation of the extension makes this situation more of a headache than they think it should...
Python sys.argv to preserve ' ' or ""
19,120,247
2
2013-10-01T15:31:08Z
19,120,324
10
2013-10-01T15:33:54Z
[ "python", "sys" ]
terminal: ``` python test.py blah='blah' ``` in test.py ``` print sys.argv ['test.py', 'blah=blah'] <------------ ``` How can blah arg preserve its '' OR Is there a way to know if an arg is wrap with either "" or ''?
Your *shell* removes the quotes before invoking Python. This is not something Python can control. Add more quotes: ``` python test.py "blah='blah'" ``` which can also be placed anywhere in the argument: ``` python test.py blah="'blah'" ``` or you could use backslash escapes: ``` python test.py blah=\'blah\' ``` ...
Compare two files report difference in python
19,120,489
12
2013-10-01T15:42:16Z
19,128,062
19
2013-10-02T00:14:21Z
[ "python", "file", "comparison" ]
I have 2 files called "hosts" (in different directories) I want to compare them using python to see if they are IDENTICAL. If they are not Identical, I want to print the difference on the screen. So far I have tried this ``` hosts0 = open(dst1 + "/hosts","r") hosts1 = open(dst2 + "/hosts","r") lines1 = hosts0.read...
``` import difflib lines1 = ''' dog cat bird buffalo gophers hound horse '''.strip().splitlines() lines2 = ''' cat dog bird buffalo gopher horse mouse '''.strip().splitlines() # Changes: # swapped positions of cat and dog # changed gophers to gopher # removed hound # added mouse for line in difflib.unified_diff(lin...
Django 1.6 AbstractUser m2m models validation error
19,120,527
6
2013-10-01T15:44:17Z
22,055,288
15
2014-02-26T22:54:16Z
[ "python", "django", "validation", "django-models" ]
I don't have errors with Django 1.5.4 (stable), but when I was testing my application on Django 1.6 beta 4 from official tar.gz I got error with validation models on startup. --- ***models.py*** ``` from django.contrib.auth.models import AbstractUser, User class ShopUser(AbstractUser): model_car = models.CharFi...
You must declare **AUTH\_USER\_MODEL** on your **settings.py**. In your case: ``` AUTH_USER_MODEL = 'your_app.ShopUser' ```
Is an object file a list by default?
19,121,451
9
2013-10-01T16:33:13Z
19,121,505
7
2013-10-01T16:36:41Z
[ "python" ]
I've encountered two versions of code that both can accomplish the same task with a little difference in the code itself: ``` with open("file") as f: for line in f: print line ``` and ``` with open("file") as f: data = f.readlines() for line in data: print line ``` My question is, is the file ob...
In both cases, you are getting a file line-by-line. The method is different. With your first version: ``` with open("file") as f: for line in f: print line ``` While you are interating over the file line by line, the file contents are not resident fully in memory (unless it is a 1 line file). The [open](htt...
Is an object file a list by default?
19,121,451
9
2013-10-01T16:33:13Z
19,121,508
11
2013-10-01T16:36:44Z
[ "python" ]
I've encountered two versions of code that both can accomplish the same task with a little difference in the code itself: ``` with open("file") as f: for line in f: print line ``` and ``` with open("file") as f: data = f.readlines() for line in data: print line ``` My question is, is the file ob...
`File` object is not a `list` - it's an object that conforms to *iterator* interface ([docs](http://docs.python.org/2/library/stdtypes.html#iterator-types)). I.e. it implements `__iter__` method that returns an *iterator* object. That *iterator* object implements both `__iter__` and `next` methods allowing iteration ov...
Build Dictionary in Python Loop - List and Dictionary Comprehensions
19,121,722
10
2013-10-01T16:49:04Z
19,121,755
24
2013-10-01T16:50:57Z
[ "python", "for-loop" ]
I'm playing with some loops in python. I am quite familiar with using the for loop: ``` for x in y: do something ``` You can also create a simple list using a loop: ``` i = [] for x in y: i.append(x) ``` and then I recently discovered a nice efficient type of loop, here on Stack, to build a list (is there a ...
The short form is as follows (called **dict comprehension**, as analogy to the **list comprehension**, **set comprehension** etc.): ``` x = { row.SITE_NAME : row.LOOKUP_TABLE for row in cursor } ``` so in general given some `_container` with some kind of elements and a function `_value` which for a given element retu...
Using rolling_apply on a DataFrame object
19,121,854
4
2013-10-01T16:56:57Z
19,122,337
7
2013-10-01T17:27:34Z
[ "python", "pandas" ]
I am trying to calculate Volume Weighted Average Price on a rolling basis. To do this, I have a function vwap that does this for me, like so: ``` def vwap(bars): return ((bars.Close*bars.Volume).sum()/bars.Volume.sum()).round(2) ``` When I try to use this function with rolling\_apply, as shown, I get an error: ...
This is not directly enabled, but you can do it like this ``` In [29]: bars Out[29]: <class 'pandas.core.frame.DataFrame'> DatetimeIndex: 942 entries, 2010-01-04 00:00:00 to 2013-09-30 00:00:00 Data columns (total 6 columns): Open 942 non-null values High 942 non-null values Low 942 non-nu...
Why use setattr() and getattr() built-ins?
19,123,707
11
2013-10-01T18:52:11Z
19,123,719
17
2013-10-01T18:53:03Z
[ "python", "python-3.x" ]
From reading the docs, I understand exactly what [getattr()](http://docs.python.org/3.3/library/functions.html#getattr) and [setattr()](http://docs.python.org/3.3/library/functions.html#setattr) do. But it also says explicitly that `getattr(x, 'foobar')` is equivalent to `x.foobar` and `setattr(x, 'foobar', 123)` is eq...
Because you can use a dynamic variable too: ``` somevar = 'foo' getattr(x, somevar) ``` You can't do that with regular attribute access syntax. Note that `getattr()` also takes an optional default value, to be returned if the attribute is *missing*: ``` >>> x = object() >>> getattr(x, 'foo') Traceback (most recent ...
Why use setattr() and getattr() built-ins?
19,123,707
11
2013-10-01T18:52:11Z
19,123,725
7
2013-10-01T18:53:17Z
[ "python", "python-3.x" ]
From reading the docs, I understand exactly what [getattr()](http://docs.python.org/3.3/library/functions.html#getattr) and [setattr()](http://docs.python.org/3.3/library/functions.html#setattr) do. But it also says explicitly that `getattr(x, 'foobar')` is equivalent to `x.foobar` and `setattr(x, 'foobar', 123)` is eq...
You use them if the attribute you want to access is a variable and not a literal string. They let you parameterize attribute access/setting. There's no reason to do `getattr(x, 'foobar')`, but you might have a variable called `attr` that could be set to "foobar" or "otherAttr", and then do `getattr(x, attr)`.
Copy an empty deque
19,123,763
3
2013-10-01T18:55:39Z
19,123,777
8
2013-10-01T18:56:26Z
[ "python" ]
I'd like an efficient way to create several empty deques. How can I do this in Python? My first thought was to do something like this: ``` import collections i = j = k = l = collections.deque() ``` This code simply creates multiple variables that reference the same deque. How I can quickly create several empty deque...
Use a generator expression: ``` i, j, k, l = (collections.deque() for _ in xrange(4)) ```
Modify output from Python Pandas describe
19,124,148
4
2013-10-01T19:19:05Z
19,124,335
11
2013-10-01T19:31:15Z
[ "python", "pandas" ]
Is there a way to omit some of the output from the pandas describe? This command gives me exactly what I want with a table output (count and mean of executeTime's by a simpleDate) ``` df.groupby('simpleDate').executeTime.describe().unstack(1) ``` However that's all I want, count and mean. I want to drop std, min, max...
Describe returns a series, so you can just select out what you want ``` In [6]: s = Series(np.random.rand(10)) In [7]: s Out[7]: 0 0.302041 1 0.353838 2 0.421416 3 0.174497 4 0.600932 5 0.871461 6 0.116874 7 0.233738 8 0.859147 9 0.145515 dtype: float64 In [8]: s.describe() Out[8]: co...
scikit-learn - ROC curve with confidence intervals
19,124,239
8
2013-10-01T19:24:29Z
19,132,400
9
2013-10-02T07:59:07Z
[ "python", "scikit-learn", "confidence-interval", "roc" ]
I am able to get a ROC curve using `scikit-learn` with `fpr`, `tpr`, `thresholds = metrics.roc_curve(y_true,y_pred, pos_label=1)`, where `y_true` is a list of values based on my gold standard (i.e., `0` for negative and `1` for positive cases) and `y_pred` is a corresponding list of scores (e.g., `0.053497243`, `0.0085...
You can bootstrap the roc computations (sample with replacement new versions of `y_true` / `y_pred` out of the original `y_true` / `y_pred` and recompute a new value for `roc_curve` each time) and the estimate a confidence interval this way. To take the variability induced by the train test split into account, you can...
Linking problems with Anaconda when using LD_LIBRARY_PATH
19,124,436
3
2013-10-01T19:36:52Z
19,128,577
7
2013-10-02T01:22:51Z
[ "python", "anaconda" ]
I just tried installing Anaconda on Linux 64 bit. Everything seems to have worked well, but when I tried to start IPython from a terminal, I get the following error: ``` $ ipython Traceback (most recent call last): File "/home/josh/installs/conda/1.7.0/bin/ipython", line 4, in <module> from IPython import start_...
On your system Anaconda is picking up a "system version" of libpython which is compiled with 2-byte Unicode where-as Anaconda is built with 4-byte Unicode. This is an unusual situation for some reason the dynamic loader for operator.so file indicated is picking up your system libpython library. Also, it looks like whe...
How to uninstall spf13 Vim distribution?
19,124,483
5
2013-10-01T19:38:46Z
19,160,683
11
2013-10-03T13:36:14Z
[ "python", "osx", "vim", "macvim" ]
I'm using MacVim in Mountain Lion I've installed spf13 Vim distribution but when I type`:set ft=python` MacVim suddenly crash so I want to uninstall it and try Janus. I've install it typing `curl https://j.mp/spf13-vim3 -L > spf13-vim.sh && sh spf13-vim.sh` in the terminal. How can I do that? Thanks a lot!
I'm sorry you haven't had success with the distribution. If :set ft=python is crashing your vim it's definitely due to an incompatibility between the python plugins we use and the python environment VIM is running with. This isn't uncommon, it's one of the disadvantages of using an external language in vim plugins, you...
How to uninstall spf13 Vim distribution?
19,124,483
5
2013-10-01T19:38:46Z
24,096,500
8
2014-06-07T11:04:04Z
[ "python", "osx", "vim", "macvim" ]
I'm using MacVim in Mountain Lion I've installed spf13 Vim distribution but when I type`:set ft=python` MacVim suddenly crash so I want to uninstall it and try Janus. I've install it typing `curl https://j.mp/spf13-vim3 -L > spf13-vim.sh && sh spf13-vim.sh` in the terminal. How can I do that? Thanks a lot!
I simply used this: ``` sh .spf13-vim-3/uninstall.sh ```
Is there a way to (pretty) print the entire Pandas Series / DataFrame?
19,124,601
68
2013-10-01T19:46:07Z
19,126,566
66
2013-10-01T21:48:30Z
[ "python", "pandas", "dataframe" ]
I work with Series and DataFrames on the terminal a lot. The default `__repr__` for a Series returns a reducted sample, with some head and tail values, but the rest missing. Is there a builtin way to pretty-print the entire Series / DataFrame? Ideally, it would support proper alignment, perhaps borders between columns...
Sure, if this comes up a lot, make a function like this one. You can even configure it to load every time you start IPython: <http://ipython.org/ipython-doc/dev/config/overview.html> ``` def print_full(x): pd.set_option('display.max_rows', len(x)) print(x) pd.reset_option('display.max_rows') ``` As for co...
Is there a way to (pretty) print the entire Pandas Series / DataFrame?
19,124,601
68
2013-10-01T19:46:07Z
30,691,921
121
2015-06-07T09:22:15Z
[ "python", "pandas", "dataframe" ]
I work with Series and DataFrames on the terminal a lot. The default `__repr__` for a Series returns a reducted sample, with some head and tail values, but the rest missing. Is there a builtin way to pretty-print the entire Series / DataFrame? Ideally, it would support proper alignment, perhaps borders between columns...
You can also use the [option\_context](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.option_context.html), with one or more options: ``` with pd.option_context('display.max_rows', 999, 'display.max_columns', 3): print df ``` This will automatically return the options to their previous values.
Pandas Merge - How to avoid duplicating columns
19,125,091
15
2013-10-01T20:16:26Z
19,125,531
20
2013-10-01T20:43:17Z
[ "python", "pandas" ]
I am attempting a merge between two data frames. Each data frame has two index levels (date, cusip). In the columns, some columns match between the two (currency, adj date) for example. What is the best way to merge these by index, but to not take two copies of currency and adj date. Each data frame is 90 columns, so...
You can work out the columns that are only in one dataframe and use this to select a subset of columns in the merge ``` cols_to_use = df2.columns - df.columns ``` then perform the merge using this (note this is an index object but it has a handy `tolist()` method) ``` dfNew = merge(df, df2[cols_to_use], left_index=T...
base64 encode binary string in NodeJS and Python
19,125,233
3
2013-10-01T20:24:28Z
19,125,316
7
2013-10-01T20:29:31Z
[ "python", "node.js", "encryption", "encoding", "base64" ]
I am trying to base64 encode a binary string in NodeJS and python and I'm getting 2 different values. Note that the value is `i` is 16 random bytes generated in python using `os.urandom(16)` NodeJS ``` > var i = '>e\x93\x10\xabK\xbe\xfeX\x97\x9a$\r\xef\x8f3'; > var s = new Buffer(i).toString('base64'); > console.log...
NodeJS is encoding the *UTF-8* representation of the string. Python is encoding the byte string. In Python, you'd have to do: ``` >>> i = u'>e\x93\x10\xabK\xbe\xfeX\x97\x9a$\r\xef\x8f3' >>> i.encode('utf8').encode('base64') 'PmXCkxDCq0vCvsO+WMKXwpokDcOvwo8z\n' ``` to get the same output. You created the buffer usin...
A Text Table Writer/Printer for Python
19,125,237
3
2013-10-01T20:24:37Z
19,125,273
8
2013-10-01T20:26:24Z
[ "python", "printing" ]
> **TL;DR ->** Is there a table writing module on PyPi (I've failed to find any) that takes in lists as parameters and makes a table out of those lists. I am asking this because I've looked on PyPI, but I have not found anything similar to actually printing strings or writing strings to files. Imagine having a lot of ...
[PrettyTable](https://pypi.python.org/pypi/PrettyTable) module is what you need: > PrettyTable is a simple Python library designed to make it quick and > easy to represent tabular data in visually appealing ASCII tables. ``` >>> import prettytable >>> x = prettytable.PrettyTable(["Length", "Time"]) >>> x.add_row([0, ...
Adding a legend to PyPlot in Matplotlib in the most simple manner possible
19,125,722
31
2013-10-01T20:53:05Z
19,125,863
55
2013-10-01T21:00:59Z
[ "python", "matplotlib", "plot" ]
> **TL;DR ->** How can one create a legend for a line graph in `Matplotlib`'s `PyPlot` without creating any extra variables? Please consider the graphing script below: ``` if __name__ == '__main__': PyPlot.plot(total_lengths, sort_times_bubble, 'b-', total_lengths, sort_times_ins, 'r-', ...
Add a `label=` to each of your [`plot()`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot) calls, and then call [`legend(loc='upper left')`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend). Consider this sample: ``` import numpy as np import pylab x = np.linspace(0, 20, 1000) y1 ...
pip install fails with FileNotFoundError: setup.py
19,127,874
3
2013-10-01T23:50:35Z
19,127,923
7
2013-10-01T23:57:10Z
[ "python", "pip", "pycairo" ]
When running pip install, I'm getting errors like this: ``` $ pip install pycairo Downloading/unpacking pycairo You are installing a potentially insecure and unverifiable file. Future versions of pip will default to disallowing insecure files. Downloading pycairo-1.10.0.tar.bz2 (246kB): 246kB downloaded Running ...
`pycairo` is not built by setuptools, and therefore can't be installed by `pip`. As the INSTALL documentation says: ``` Install Procedure ----------------- $ ./waf --help # shows available waf options $ ./waf configure # use --prefix and --libdir if necessary # --prefix=/usr --libdir=/usr/lib6...
Accessing non-consecutive elements of a list or string in python
19,128,523
11
2013-10-02T01:16:31Z
19,128,597
14
2013-10-02T01:25:03Z
[ "python", "string", "list", "indexing", "slice" ]
As far as I can tell, this is not officially not possible, but is there a "trick" to access arbitrary non-sequential elements of a list by slicing? For example: ``` >>> L = range(0,101,10) >>> L [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] ``` Now I want to be able to do ``` a,b = L[2,5] ``` so that `a == 20` and ...
Probably the closest to what you are looking for is [`itemgetter`](http://docs.python.org/2/library/operator.html#operator.itemgetter): ``` >>> L = range(0, 101, 10) >>> L [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] >>> from operator import itemgetter >>> itemgetter(2, 5)(L) (20, 50) ```
Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
19,128,540
31
2013-10-02T01:18:45Z
20,646,241
41
2013-12-17T22:45:20Z
[ "python", "django", "settings" ]
I am trying to set up multiple setting files (development, production, ..) that include some base settings. Cannot succeed though. When I try to run `./manage.py runserver` I am getting the following error: ``` (cb)clime@den /srv/www/cb $ ./manage.py runserver ImproperlyConfigured: The SECRET_KEY setting must not be e...
I had the same error and it turned out to be a circular dependency between something loaded by the settings and the settings module itself. In my case it was a middleware class which was named in the settings which itself tried to load the settings.
Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
19,128,540
31
2013-10-02T01:18:45Z
23,492,368
18
2014-05-06T10:38:12Z
[ "python", "django", "settings" ]
I am trying to set up multiple setting files (development, production, ..) that include some base settings. Cannot succeed though. When I try to run `./manage.py runserver` I am getting the following error: ``` (cb)clime@den /srv/www/cb $ ./manage.py runserver ImproperlyConfigured: The SECRET_KEY setting must not be e...
I ran into the same problem after restructuring the settings as per the instructions from Daniel Greenfield's book *Two scoops of Django*. I resolved the issue by setting ``` os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings.local") ``` in `manage.py` and `wsgi.py`.
Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
19,128,540
31
2013-10-02T01:18:45Z
29,867,377
11
2015-04-25T15:51:33Z
[ "python", "django", "settings" ]
I am trying to set up multiple setting files (development, production, ..) that include some base settings. Cannot succeed though. When I try to run `./manage.py runserver` I am getting the following error: ``` (cb)clime@den /srv/www/cb $ ./manage.py runserver ImproperlyConfigured: The SECRET_KEY setting must not be e...
I just grappled with this error today. It threw itself onto me out of nowhere. I was just starting my work for the day; issued `python manage.py runserver 0.0.0.0:8006` when I saw this dreaded error. Fortunately, I have got it to shut up. It turned out that it was because of one of the compiled binary (.pyc) file, in ...
Looking for inverse of url_for in Flask
19,129,407
8
2013-10-02T03:10:48Z
19,133,159
9
2013-10-02T08:46:48Z
[ "python", "json", "rest", "flask", "werkzeug" ]
I am using [Flask](http://flask.pocoo.org/docs/) and [Flask-RESTful](http://flask-restful.readthedocs.org/en/latest/index.html) to build a REST API. Within this API some of my resources contain url relations to other resources. When performing POST requests to these resources I am finding that I am needing the inverse...
The simplest way create test request context (thanks **Leon Young**): ``` with app.test_request_context(YOUR_URL) as request_ctx: url_rule = request_ctx.request.url_rule ``` But all sense under the hood of creating request context: ``` from flask.testing import make_test_environ_builder builder = make_test_envi...
Stopword removal with NLTK
19,130,512
33
2013-10-02T05:29:32Z
19,133,088
77
2013-10-02T08:41:58Z
[ "python", "nlp", "nltk", "stop-words" ]
I am trying to process a user entered text by removing stopwords using nltk toolkit, but with stopword-removal the words like 'and', 'or', 'not' gets removed. I want these words to be present after stopword removal process as they are operators which are required for later processing text as query. I don't know which a...
There is an in-built stopword list in `NLTK` made up of 2,400 stopwords for 11 languages (Porter et al), see <http://nltk.org/book/ch02.html> ``` >>> from nltk.corpus import stopwords >>> stop = set(stopwords.words('english')) >>> sentence = "this is a foo bar sentence" >>> print [i for i in sentence.lower().split() i...
Stopword removal with NLTK
19,130,512
33
2013-10-02T05:29:32Z
24,106,778
33
2014-06-08T13:45:41Z
[ "python", "nlp", "nltk", "stop-words" ]
I am trying to process a user entered text by removing stopwords using nltk toolkit, but with stopword-removal the words like 'and', 'or', 'not' gets removed. I want these words to be present after stopword removal process as they are operators which are required for later processing text as query. I don't know which a...
I suggest you create your own list of operator words that you take out of the stopword list. Sets can be conveniently subtracted, so: ``` operators = set(('and', 'or', 'not')) stop = set(stopwords...) - operators ``` Then you can simply test if a word is `in` or `not in` the set without relying on whether your operat...
Stopword removal with NLTK
19,130,512
33
2013-10-02T05:29:32Z
24,214,114
8
2014-06-13T21:37:10Z
[ "python", "nlp", "nltk", "stop-words" ]
I am trying to process a user entered text by removing stopwords using nltk toolkit, but with stopword-removal the words like 'and', 'or', 'not' gets removed. I want these words to be present after stopword removal process as they are operators which are required for later processing text as query. I don't know which a...
@alvas has a good answer. But again it depends on the nature of the task, for example in your application you want to consider all `conjunction` e.g. *and, or, but, if, while* and all `determiner` e.g. *the, a, some, most, every, no* as stop words considering all others parts of speech as legitimate, then you might wan...
Stopword removal with NLTK
19,130,512
33
2013-10-02T05:29:32Z
32,469,562
12
2015-09-09T01:27:34Z
[ "python", "nlp", "nltk", "stop-words" ]
I am trying to process a user entered text by removing stopwords using nltk toolkit, but with stopword-removal the words like 'and', 'or', 'not' gets removed. I want these words to be present after stopword removal process as they are operators which are required for later processing text as query. I don't know which a...
@alvas's answer does the job but it can be done way faster. Assuming that you have `documents`: a list of strings. ``` from nltk.corpus import stopwords from nltk.tokenize import wordpunct_tokenize stop_words = set(stopwords.words('english')) stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', '...
Python equivalent of Golang's select on channels
19,130,986
4
2013-10-02T06:16:08Z
19,131,479
7
2013-10-02T06:57:00Z
[ "python", "go" ]
Go has a select statement that works on channels. From the documentation: > The select statement lets a goroutine wait on multiple communication > operations. > > A select blocks until one of its cases can run, then it executes that > case. It chooses one at random if multiple are ready. Is there a Python equivalent ...
Here's a pretty direct translation, but the "choosing which if multiple are ready" part works differently - it's just taking what came in first. Also this is like running your code with `gomaxprocs(1)`. ``` import threading import Queue def main(): c1 = Queue.Queue(maxsize=0) c2 = Queue.Queue(maxsize=0) q...
Python: How to force overwriting of files when using setup.py install (distutil)
19,133,831
9
2013-10-02T09:27:52Z
21,788,775
15
2014-02-14T20:16:44Z
[ "python", "install", "distutils", "overwrite" ]
I am using `distutil` to install my python code using `python setup.py install` I run into problems when I want to install an older branch of my code over a new one: `setup.py install` won't overwrite older files. A work around is touching (`touch <filename>`) all files so they are forced to be newer than those insta...
The Python developers had the same idea, they just put the option after the command: ``` python setup.py install --force ``` The distutils documentation doesn't mention the --force option specifically, but you can find it by using the --help option: ``` python setup.py --help install ```
django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_content_type_pkey"
19,135,161
6
2013-10-02T10:45:52Z
19,136,200
25
2013-10-02T11:48:43Z
[ "python", "django", "postgresql" ]
Ran into a bit of a problem, i'm getting the above error message when i run '`python manage.py syncdb`' I'm working on a fairly old site. It' running django 1.2.6 with a postgres DB. The run didn't have south installed and i managed to get that working. Ran `python manage.py schemamigration --initial contact_enquiries...
Although I am not 100% certain this is the problem, there is a good chance your sequence is out of date. Does executing this within Postgres solve the issue? ``` SELECT setval('django_content_type_id_seq', (SELECT MAX(id) FROM django_content_type)); ```
What is pip's equivalent of `npm install package --save-dev`?
19,135,867
29
2013-10-02T11:28:54Z
19,136,738
25
2013-10-02T12:20:04Z
[ "python", "node.js", "pip" ]
In nodejs, I can do `npm install package --save-dev` to save the installed package into the package. How do I achieve the same thing in Python package manager `pip`? I would like to save the package name and its version into, say, `requirements.pip` just after installing the package using something like `pip install p...
There isn't an equivalent with `pip`. Best way is to `pip install package && pip freeze > requirements.txt` You can see all the available options on their [documentation page](http://www.pip-installer.org/en/latest/usage.html#pip-install). If it really bothers you, it wouldn't be too difficult to write a custom bash...
What is pip's equivalent of `npm install package --save-dev`?
19,135,867
29
2013-10-02T11:28:54Z
36,563,939
7
2016-04-12T04:57:51Z
[ "python", "node.js", "pip" ]
In nodejs, I can do `npm install package --save-dev` to save the installed package into the package. How do I achieve the same thing in Python package manager `pip`? I would like to save the package name and its version into, say, `requirements.pip` just after installing the package using something like `pip install p...
One of the issues with using `pip freeze > requirements.txt` is that not only our direct dependencies but also their dependencies get copied to requirements file and hence it becomes quite difficult to figure out the exact requirements for your app/project. I have created a small python package [pip-save](https://pypi...
Use of threading.Thread.join()
19,138,219
13
2013-10-02T13:36:47Z
19,138,327
39
2013-10-02T13:41:23Z
[ "python", "multithreading", "python-2.7", "python-multithreading" ]
I am new to multithreading in python and trying to learn multithreading using threading module. I have made a very simple program of multi threading and i am having trouble understanding the `threading.Thread.join` method. Here is the source code of the program I have made ``` import threading val = 0 def increment...
A call to `thread1.join()` blocks the thread in which you're making the call, until `thread1` is finished. It's like `wait_until_finished(thread1)`. For example: ``` import time def printer(): for _ in range(3): time.sleep(1.0) print "hello" thread = Thread(target=printer) thread.start() thread....
Django Aggreagtion: Sum return value only?
19,138,609
8
2013-10-02T13:54:03Z
19,138,663
12
2013-10-02T13:56:11Z
[ "python", "django", "sum", "aggregation" ]
I have a list of values paid and want to display the total paid. I have used Aggregation and Sum to calculate the values together. The problem is,I just want the total value printed out, but aggreagtion prints out: `{'amount__sum': 480.0}` (480.0 being the total value added. In my View, I have: ``` from django.db...
I don't believe there is a way to get only the value. You could just do `${{ total_paid.amount__sum }}` in your template. Or do `total_paid = Payment.objects.all().aggregate(Sum('amount')).get('amount__sum', 0.00)` in your view.
Django Aggreagtion: Sum return value only?
19,138,609
8
2013-10-02T13:54:03Z
26,043,405
7
2014-09-25T16:18:34Z
[ "python", "django", "sum", "aggregation" ]
I have a list of values paid and want to display the total paid. I have used Aggregation and Sum to calculate the values together. The problem is,I just want the total value printed out, but aggreagtion prints out: `{'amount__sum': 480.0}` (480.0 being the total value added. In my View, I have: ``` from django.db...
The `aggregate()` method returns a dictionary. If you know you're only returning a single-entry dictionary you could use `.values()[0]`: ``` total_paid = Payment.objects.aggregate(Sum('amount')).values()[0] ``` The end result is the same as @jproffitt's answer, but it avoids repeating the `amount__sum` part, so it's ...
Python matplotlib scatter plot : changing colour of data points based on given conditions
19,139,621
7
2013-10-02T14:37:53Z
19,139,880
11
2013-10-02T14:50:19Z
[ "python", "colors", "matplotlib", "plot" ]
I have the following data (four equal-length arrays) : ``` a = [1, 4, 5, 2, 8, 9, 4, 6, 1, 0, 6] b = [4, 7, 8, 3, 0, 9, 6, 2, 3, 6, 7] c = [9, 0, 7, 6, 5, 6, 3, 4, 1, 2, 2] d = [La, Lb, Av, Ac, Av, By, Lh, By, Lg, Ac, Bt] ``` I am making a 3d plot of arrays a, b, c : ``` import pylab import matplotlib.pyplot as plt ...
As the documentation for [scatter](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter) explains, you can pass the `c` argument: > c : color or sequence of color, optional, default > > c can be a single color format string, or a sequence of color specifications > of length N, or a sequence of N numbers...
Passing multiple arguments to apply (Python)
19,140,035
10
2013-10-02T14:56:47Z
19,140,142
9
2013-10-02T15:01:47Z
[ "python", "apply", "dataframe" ]
I'm trying to clean up some code in Python to vectorize a set of features and I'm wondering if there's a good way to use apply to pass multiple arguments. Consider the following (current version): ``` def function_1(x): if "string" in x: return 1 else: return 0 df['newFeature'] = df['oldFeatur...
I believe you want [`functools.partial`](http://docs.python.org/2/library/functools.html#functools.partial). A demo: ``` >>> from functools import partial >>> def mult(a, b): ... return a * b ... >>> doubler = partial(mult, 2) >>> doubler(4) 8 ``` In your case you need to swap arguments in `function` (because of ...
python numpy machine epsilon
19,141,432
21
2013-10-02T16:03:01Z
19,141,635
8
2013-10-02T16:12:20Z
[ "python", "numpy", "epsilon" ]
I am trying to understand what is machine epsilon. According to the Wikipedia, it can be calculated as follows: ``` def machineEpsilon(func=float): machine_epsilon = func(1) while func(1)+func(machine_epsilon) != func(1): machine_epsilon_last = machine_epsilon machine_epsilon = func(machine_eps...
It will already work, as David pointed out! ``` >>> def machineEpsilon(func=float): ... machine_epsilon = func(1) ... while func(1)+func(machine_epsilon) != func(1): ... machine_epsilon_last = machine_epsilon ... machine_epsilon = func(machine_epsilon) / func(2) ... return machine_epsilon_l...
python numpy machine epsilon
19,141,432
21
2013-10-02T16:03:01Z
19,141,711
57
2013-10-02T16:16:28Z
[ "python", "numpy", "epsilon" ]
I am trying to understand what is machine epsilon. According to the Wikipedia, it can be calculated as follows: ``` def machineEpsilon(func=float): machine_epsilon = func(1) while func(1)+func(machine_epsilon) != func(1): machine_epsilon_last = machine_epsilon machine_epsilon = func(machine_eps...
An easier way to get the machine epsilon for a given float type is to use [`np.finfo()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.finfo.html): ``` print(np.finfo(float).eps) # 2.22044604925e-16 print(np.finfo(np.float32).eps) # 1.19209e-07 ```
python numpy machine epsilon
19,141,432
21
2013-10-02T16:03:01Z
25,155,518
28
2014-08-06T08:24:54Z
[ "python", "numpy", "epsilon" ]
I am trying to understand what is machine epsilon. According to the Wikipedia, it can be calculated as follows: ``` def machineEpsilon(func=float): machine_epsilon = func(1) while func(1)+func(machine_epsilon) != func(1): machine_epsilon_last = machine_epsilon machine_epsilon = func(machine_eps...
Another easy way to get epsilon is: ``` In [1]: 7./3 - 4./3 -1 Out[1]: 2.220446049250313e-16 ```
Python regex to get everything until the first dot in a string
19,142,042
14
2013-10-02T16:32:51Z
19,142,057
22
2013-10-02T16:33:28Z
[ "python", "regex" ]
``` find = re.compile("^(.*)\..*") for l in lines: m = re.match(find, l) print m.group(1) ``` I want to regex whatever in a string until the first dot. in `[email protected]`, I want `a@b` in `[email protected]`, I want `a@b` in `[email protected]`, I want `a@b` What my code is giving me... * `[email protected]` prints `a@b` * `[email protected]` prints ...
By default all the quantifiers are greedy in nature. In the sense, they will try to consume as much string as they can. You can make them reluctant by appending a `?` after them: ``` find = re.compile(r"^(.*?)\..*") ``` As noted in comment, this approach would fail if there is no *period* in your string. So, it depen...
Python regex to get everything until the first dot in a string
19,142,042
14
2013-10-02T16:32:51Z
19,142,167
19
2013-10-02T16:39:44Z
[ "python", "regex" ]
``` find = re.compile("^(.*)\..*") for l in lines: m = re.match(find, l) print m.group(1) ``` I want to regex whatever in a string until the first dot. in `[email protected]`, I want `a@b` in `[email protected]`, I want `a@b` in `[email protected]`, I want `a@b` What my code is giving me... * `[email protected]` prints `a@b` * `[email protected]` prints ...
You can use [`.find()`](http://docs.python.org/library/stdtypes.html#str.find) instead of regex in this situation: ``` >>> s = "[email protected]" >>> print(s[0:s.find('.')]) a@b ``` --- Considering the comments, here's some modification using [`.index()`](http://docs.python.org/2/library/stdtypes.html#str.index) (it's similar ...
Cassandra: File "cqlsh", line 95 except ImportError, e:
19,142,231
13
2013-10-02T16:42:31Z
19,142,243
19
2013-10-02T16:43:21Z
[ "python", "cassandra" ]
I am having trouble getting Cassandra up and running. I have downloaded Cassandra 2.0.1 and Python 3.3.2. Upon starting the CLI for cassandra I get an error: ``` C:\Dev\ApacheCassandra\apache-cassandra-2.0.1\bin>python cqlsh File "cqlsh", line 95 except ImportError, e: ^ SyntaxError: inval...
The version of Cassandra that you are using is only compatible with Python 2.x. The following syntax: ``` except ImportError, e: ``` was deprecated in Python 2.7 and [removed in Python 3.x](https://docs.python.org/3/whatsnew/3.0.html#changed-syntax). Nowadays, you use the `as` keyword: ``` except ImportError as e: ...
IPython Notebook Multiple Checkpoints
19,142,465
22
2013-10-02T16:55:21Z
19,143,618
14
2013-10-02T18:00:14Z
[ "python", "ipython-notebook" ]
I see that IPython Notebook has a menu item: `File > Revert to Checkpoint`, but this never contains more than a single entry for any of my notebooks. Is there a way to allow this menu to hold multiple checkpoints? I can't find documentation about how to do this anywhere on the web. Thanks. Also, I put in the green bo...
[Bookstore](https://github.com/rgbkrk/bookstore) ([post on rackspace](http://developer.rackspace.com/blog/bookstore-for-ipython-notebooks.html)) is the only storage backend that supports multiple checkpoints for now. We hope that someone will write a git backend at some point. It will just not come from the core team s...
Django: The included urlconf core.urls doesn't have any patterns in it
19,142,984
4
2013-10-02T17:23:28Z
19,230,776
9
2013-10-07T17:12:10Z
[ "python", "django", "django-views" ]
I'm having some weird issues with class-based-views and reverse\_lazy. Following error shows up when calling the website: ``` ImproperlyConfigured at /dashboard/student/ The included urlconf core.urls doesn't have any patterns in it ``` My views.py: ``` class DashStudentMain(TemplateView): model_class = None ...
Change this code: ``` tab_list = { ("Main", reverse_lazy('dash_student_main_url')), #("History", reverse_lazy('dash_student_main_url')) } ``` to: ``` tab_list = [ ("Main", reverse_lazy('dash_student_main_url')), #("History", reverse_lazy('dash_student_main_url')) ] ``` Contrary to a name you gave th...
How to read a CSV without the first column
19,143,667
11
2013-10-02T18:03:21Z
19,143,833
17
2013-10-02T18:12:39Z
[ "python", "csv", "numpy" ]
I am trying to read a simple CSV file like below, and put its contents in a 2D array: ``` "","x","y","sim1","sim2","sim3","sim4","sim5","sim6","sim7","sim8","sim9","sim10","sim11","sim12" "1",181180,333740,5.56588745117188,6.29487752914429,7.4835410118103,5.75873327255249,6.62183284759521,5.81478500366211,4.8567194938...
You can specify a converter for any column. ``` converters = {0: lambda s: float(s.strip('"')} data = np.loadtxt("Data/sim.csv", delimiter=',', skiprows=1, converters=converters) ``` Or, you can specify which columns to use, something like: ``` data = np.loadtxt("Data/sim.csv", delimiter=',', skiprows=1, usecols=ran...
Pandas: bar plot xtick frequency
19,143,857
6
2013-10-02T18:14:04Z
19,387,765
7
2013-10-15T17:50:56Z
[ "python", "matplotlib", "plot", "pandas" ]
I want to create a simple bar chart for pandas DataFrame object. However, the xtick on the chart appears to be too granular, whereas if I change the plot to line chart, xtick is optimized for better viewing. I was wondering if I can bring the same line chart xtick frequency to bar chart? Thanks. ``` locks.plot(kind='b...
You can reduce the number of thicks by setting only every `n` tick, doing something like: ``` n = 10 ax = locks.plot(kind='bar', y='SUM') ticks = ax.xaxis.get_ticklocs() ticklabels = [l.get_text() for l in ax.xaxis.get_ticklabels()] ax.xaxis.set_ticks(ticks[::n]) ax.xaxis.set_ticklabels(ticklabels[::n]) ax.figure.sh...
Python unitest - Use variables defined in module and class level setup functions, in tests
19,144,235
11
2013-10-02T18:35:07Z
19,149,329
10
2013-10-03T01:15:14Z
[ "python", "unit-testing", "oop", "nose", "python-unittest" ]
Python unittest using nosetests to experiment with [Python Class and Module fixtures](http://docs.python.org/2/library/unittest.html#class-and-module-fixtures), to have minimal setup across my tests. The **problem** I am facing is, I am not sure how to use any variables defined in the `setupUpModule` and the `setUpCla...
**For str variable `a`,** the only solution is `global a`. If you look at the [unittest source code](http://hg.python.org/cpython/file/43064ded64cb/Lib/unittest/suite.py#l165), `setupModule()` doesn't appear to do anything magical, so all the usual namespace rules apply. If `a` were a mutable variable, like a list, yo...
Repositories of conda recipes and packages
19,144,482
11
2013-10-02T18:47:40Z
19,170,750
11
2013-10-03T23:23:46Z
[ "python", "git", "anaconda", "conda" ]
From what I understand, there are several repositories for [`conda`](https://github.com/ContinuumIO/conda) **recipes** (not for the program itself): * The default one (where does `conda` look for recipes by default?) * The following GitHub repository: <https://github.com/ContinuumIO/conda-recipes> * Other recipe repos...
(cross-posted from <https://github.com/ContinuumIO/conda/issues/298#issuecomment-25666539>) You can add my binstar repo to your .condarc (see <https://conda.binstar.org/asmeurer>). Note that I only build the packages for Mac OS X, which is the platform I use, so if you don't use that, then that won't help you. If that...
Pandas Series Sort
19,144,618
5
2013-10-02T18:53:58Z
19,144,791
13
2013-10-02T19:03:30Z
[ "python", "sorting", "pandas", "ipython" ]
I have a Pandas dataframe called `pd`, and I extract the number of unique values in one of the columns of this dataframe using the following command: ``` b = df.groupby('Region').size() ``` b is a Pandas series object and looks like this: ``` In [48]: b Out[48]: Region 0 8 1 25 11 1 2 ...
You are looking for [sort\_index](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_index.html?highlight=sort#pandas.Series.sort_index): ``` In [80]: b.sort() Out[80]: 6 1 11 2 9 2 1 4 10 4 2 5 3 6 4 7 8 8 5 9 dtype: int64 In [81]: b.sort_index() Out[81]: ...
Python object encapsulation security
19,145,290
7
2013-10-02T19:31:14Z
19,145,406
16
2013-10-02T19:39:33Z
[ "python", "security", "encapsulation" ]
I have a question, and my decision in choosing Python as a possible language for a bigger project depends on the answer - which I cannot come up with myself: We all know that Python has no *real* object encapsulation, so there is nothing like "private" properties of an object. Regarding this issue, Guido van Rossum sa...
You should never really rely on `private`, `public` etc for security (as in "protection against malicious code and external threats"). They are meant as something to keep the programmer from shooting himself in the foot, not as a (computer) security measure. You can also easily access private member fields of C++ objec...
NLTK - Counting Frequency of Bigram
19,145,332
10
2013-10-02T19:34:45Z
27,094,326
12
2014-11-23T21:08:25Z
[ "python", "nlp", "nltk" ]
This is a Python and NLTK newbie question. I want to find frequency of bigrams which occur more than 10 times together and have the highest PMI. For this, I am working with this code ``` def get_list_phrases(text): tweet_phrases = [] for tweet in text: tweet_words = tweet.split() tweet_phra...
The problem is with the way you are trying to use `apply_freq_filter`. We are discussing about word collocations. As you know, a word collocation is about dependancy between words. The `BigramCollocationFinder` class inherits from a class named `AbstractCollocationFinder` and the function `apply_freq_filter` belongs to...
How to find and count emoticons in a string using python?
19,149,186
6
2013-10-03T00:57:23Z
19,149,591
9
2013-10-03T01:52:32Z
[ "python", "regex", "string", "unicode" ]
This topic has been addressed for text based emoticons at [link1](http://stackoverflow.com/questions/18283681/regular-expressions-emoticons), [link2](http://stackoverflow.com/questions/10890261/how-to-match-a-emoticon-in-sentence-with-regular-expressions), [link3](http://stackoverflow.com/questions/14571103/capturing-e...
First, there is no need to encode here at all. You're got a Unicode string, and the `re` engine can handle Unicode, so just use it. A [character class](http://docs.python.org/3.3/library/re.html#regular-expression-syntax) can include a range of characters, by specifying the first and last with a hyphen in between. And...
Why won't Perceptron Learning Algorithm converge?
19,149,364
8
2013-10-03T01:20:33Z
19,150,090
11
2013-10-03T03:06:36Z
[ "python", "numpy", "machine-learning", "perceptron" ]
I have implemented the Perceptron Learning Algorithm in Python as below. Even with 500,000 iterations, it still won't converge. I have a training data matrix X with target vector Y, and a weight vector w to be optimized. My update rule is: ``` while(exist_mistakes): # dot product to check for mistakes outpu...
[Perceptrons](http://en.wikipedia.org/wiki/Perceptrons_%28book%29) by Minsky and Papert (in)famously demonstrated in 1969 that the perceptron learning algorithm is not guaranteed to converge for datasets that are not linearly separable. If you're sure that your dataset is linearly separable, you might try adding a bia...
Python, replace long dash with short dash?
19,149,577
5
2013-10-03T01:49:43Z
19,149,581
11
2013-10-03T01:51:22Z
[ "python", "replace", "python-2.x" ]
I want to replace a long dash (`–`) with a short dash (`-`). My code: ``` if " – " in string: string = string.replace(" – ", " - ") ``` results in the following error: > SyntaxError: Non-ASCII character '\xe2' in file ./script.py on line 76, but no encoding declared; see <http://www.python.org/peps/pep-0...
Long dash is not an [ASCII character](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). Declare encoding of your script, like this *(somewhere on top)*: ``` #-*- coding: utf-8 -*- ``` There are also other encodings beside `utf-8` but it is always safe to use `utf-8` if not working with ASCII characters ...
No handlers could be found for logger paramiko
19,152,578
4
2013-10-03T06:49:16Z
24,820,179
9
2014-07-18T08:10:40Z
[ "python" ]
I am using paramiko module for ssh connection.I am facing below problem: No handlers could be found for logger I am not getting the reason of this problem.I tried to get solution from below link but not able to get reason. [No handlers could be found for logger "paramiko.transport"](http://stackoverflow.com/questions/...
I found the solution from [this website](https://translate.google.com/translate?hl=en&sl=zh-CN&tl=en&u=http%3A%2F%2Fwww.ouvps.com%2F%3Fp%3D869). Basically, you just need to add a line: ``` paramiko.util.log_to_file("filename.log") ``` Then all connection will be logged to the file.
Get Excel-Style Column Names from Column Number
19,153,462
10
2013-10-03T07:37:29Z
19,154,642
8
2013-10-03T08:43:32Z
[ "python", "excel", "python-2.7" ]
This is the code for providing the COLUMN name when the row and col ID is provided but when I give values like `row = 1 and col = 104`, it should return `CZ`, but it returns `D@` ``` row = 1 col = 104 div = col column_label = str() while div: (div, mod) = divmod(div, 26) column_label = chr(mod + 64) + column_l...
You have a couple of index issues: So to fix your problem, you need to make all your indices match: ``` def colToExcel(col): # col is 1 based excelCol = str() div = col while div: (div, mod) = divmod(div-1, 26) # will return (x, 0 .. 25) excelCol = chr(mod + 65) + excelCol return exc...
Get Excel-Style Column Names from Column Number
19,153,462
10
2013-10-03T07:37:29Z
19,169,180
10
2013-10-03T21:02:39Z
[ "python", "excel", "python-2.7" ]
This is the code for providing the COLUMN name when the row and col ID is provided but when I give values like `row = 1 and col = 104`, it should return `CZ`, but it returns `D@` ``` row = 1 col = 104 div = col column_label = str() while div: (div, mod) = divmod(div, 26) column_label = chr(mod + 64) + column_l...
EDIT: I feel I must admit, as pointed out by a few others — who never left me comments — that the previous version of my answer (which you accepted) had a bug that prevented it from properly handling column numbers greater than `702` (corresponding to Excel column `'ZZ1'`). So, in the interests of correctness, that's b...
Python - Split a List into 2 by even or odd index?
19,153,525
7
2013-10-03T07:40:37Z
19,153,541
18
2013-10-03T07:41:41Z
[ "python" ]
What is **the most Pythonic way** of splitting up a list `A` into `B` and `C` such that `B` is composed of the even-indexed elements of `A` and `C` is composed of the odd-indexed elements of `A`? e.g. `A = [1, 3, 2, 6, 5, 7]`. Then `B` should be `[1, 2, 5]` and `C` should be `[3, 6, 7]`.
Use a stride slice: ``` B, C = A[::2], A[1::2] ``` Sequence slicing not only supports specifying a start and end value, but also a stride (or step); `[::2]` selects every second value starting from 0, `[1::2]` every value starting from 1. Demo: ``` >>> A = [1, 3, 2, 6, 5, 7] >>> B, C = A[::2], A[1::2] >>> B [1, 2, ...
twisted reactor.spawnProcess get stdout w/o bufffering on windows
19,155,240
2
2013-10-03T09:12:44Z
19,158,745
9
2013-10-03T12:03:34Z
[ "python", "twisted" ]
I'm running an external process and I need to get the stdout immediately so I can push it to a textview, on GNU/Linux I can use "usePTY=True" to get the stdout by line, unfortunately usePTY is not available on windows. I'm fairly new to twisted, is there a way to achieve the same result on Windows with some twisted (o...
> on GNU/Linux I can use "usePTY=True" to get the stdout by line Sort of! What `usePTY=True` actually does is create a PTY (a "pseudo-terminal" - the thing you always get when you log in to a shell on GNU/Linux unless you have a *real* terminal which no one does anymore :) instead of a boring old pipe. A PTY is a lot ...
can OpenCV be installed in python virtualenv on Mac Mountain Lion
19,155,603
3
2013-10-03T09:31:13Z
19,156,389
9
2013-10-03T10:07:08Z
[ "python", "osx", "opencv", "virtualenv" ]
I have install Numpy and Scipy with virtualenv on my mac. Today, I want to installed Opencv under virtualenv. I try: ``` pip install pyopencv ``` the terminal returned: Could not find a version that satisfies the requirement pyopencv (from versions: 2.0.wr1.0.1-demo, 2.0.wr1.0.1, 2.0.wr1.1.0, 2.1.0.wr1.0.0, 2.1.0.w...
I had the same problem, I couldn't get OpenCV installed in virtualenv using pip in the proper way. However this is what I have done: 1. Install OpenCV and Python using Homebrew (and all depenencies such as numpy) 2. Then I installed virtualenv and create a new virtual environment with numpy. 3. Finally what I did was ...
Select Pandas rows based on list index
19,155,718
9
2013-10-03T09:36:32Z
19,155,860
22
2013-10-03T09:43:39Z
[ "python", "pandas" ]
I have a dataframe df : ``` 20060930 10.103 NaN 10.103 7.981 20061231 15.915 NaN 15.915 12.686 20070331 3.196 NaN 3.196 2.710 20070630 7.907 NaN 7.907 6.459 ``` Then I want to select rows with certain sequence numbers which indicated in a list, suppos...
``` List = [1, 3] df.ix[List] ``` should do the trick! Whe I index with data frames I always use the .ix() method. Its so much easier and more flexible...
Why are global variables evil?
19,158,339
25
2013-10-03T11:44:56Z
19,158,418
40
2013-10-03T11:48:01Z
[ "python", "global-variables", "side-effects" ]
I was trying to find a good source that explains why the use of `global` is considered to be bad practice in python (and in programming in general). Can somebody point me to one or explain here?
This has nothing to do with Python; global variables are bad in any programming language. **NOTE:** \**global constants*\* are not conceptually the same as **global variables**; global constants are perfectly fine to use. It's just that in Python there is no syntactic difference. The reason they are bad is that they ...
Scrapy: Limit the number of request or request bytes
19,160,594
5
2013-10-03T13:32:06Z
19,162,026
11
2013-10-03T14:34:49Z
[ "python", "scrapy" ]
I am using a scrapy `CrawlSpider` and defined a twisted reactor to control my crawler. During the tests I crawled a news site collecting more than several GBs of data. Mostly I am interested in the newest stories so I am looking for a way to limit the number of requested pages, bytes or seconds. **Is there a common wa...
In `scrapy` there is the class `scrapy.contrib.closespider.CloseSpider`. You can define the variables `CLOSESPIDER_TIMEOUT`, `CLOSESPIDER_ITEMCOUNT`, `CLOSESPIDER_PAGECOUNT` and `CLOSESPIDER_ERRORCOUNT`. The spider closes automatically when the criteria is met: <http://doc.scrapy.org/en/latest/topics/extensions.html#m...
Convert integer to string Jinja
19,161,093
43
2013-10-03T13:53:56Z
19,162,679
83
2013-10-03T15:06:06Z
[ "python", "jinja2" ]
I have an integer ``` {% set curYear = 2013 %} ``` In `{% if %}` statement I have to compare it with some string. I can't set `curYear` to string at the beginning because I have to decrement it in loop. How can I convert it?
I found the answer. Cast integer to string: ``` myOldIntValue|string ``` Cast string to integer: ``` myOldStrValue|int ```
Numpy extract submatrix
19,161,512
15
2013-10-03T14:10:50Z
19,161,690
18
2013-10-03T14:18:40Z
[ "python", "numpy" ]
I'm pretty new in `numpy` and I am having a hard time understanding how to extract from a `np.array` a sub matrix with defined columns and rows: ``` Y = np.arange(16).reshape(4,4) ``` If I want to extract columns/rows 0 and 3, I should have: ``` [[0 3] [12 15]] ``` I tried all the reshape functions...but cannot fi...
Give [`np.ix_`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ix_.html) a try: ``` Y[np.ix_([0,3],[0,3])] ``` This returns your desired result: ``` In [25]: Y = np.arange(16).reshape(4,4) In [26]: Y[np.ix_([0,3],[0,3])] Out[26]: array([[ 0, 3], [12, 15]]) ```
Get index in the list of objects by attribute in Python
19,162,285
2
2013-10-03T14:48:21Z
19,162,335
8
2013-10-03T14:50:05Z
[ "python", "list", "indexing" ]
I have list of objects with attribute id and I want to find index of object with specific id. I wrote something like this: ``` index = -1 for i in range(len(my_list)): if my_list[i].id == 'specific_id' index = i break ``` but it doesn't look very well. Are there any better options?
Use `enumerate` when you want both the values and indices in a `for` loop: ``` for index, item in enumerate(my_list): if item.id == 'specific_id': break else: index = -1 ``` Or, as a generator expression: ``` index = next((i for i, item in enumerate(my_list) if item.id == 'specific_id'), -1) ```