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 use Java/Scala function from an action or a transformation?
31,684,842
20
2015-07-28T18:54:01Z
34,412,182
18
2015-12-22T09:14:25Z
[ "python", "scala", "apache-spark", "pyspark", "apache-spark-mllib" ]
### Background My original question here was *Why using `DecisionTreeModel.predict` inside map function raises an exception?* and is related to [How to generate tuples of (original lable, predicted label) on Spark with MLlib?](http://stackoverflow.com/q/31680704/1560062) When we use Scala API [a recommended way](http...
Communication using default Py4J gateway is simply not possible. To understand why we have to take a look at the following diagram from the PySpark Internals document [1]: [![enter image description here](http://i.stack.imgur.com/sfcDU.jpg)](http://i.stack.imgur.com/sfcDU.jpg) Since Py4J gateway runs on the driver it...
Trade off between code duplication and performance
31,688,034
12
2015-07-28T22:13:02Z
31,688,190
21
2015-07-28T22:26:23Z
[ "python", "performance", "optimization", "code-duplication" ]
Python, being the dynamic language that it is, offer multiple ways to implement the same feature. These options may vary in readability, maintainability and performance. Even though the usual scripts that I write in Python are of a disposable nature, I now have a certain project that I am working on (academic) that mus...
*Very* broadly speaking, there are two types of optimization: *macro optimizations* and *micro optimizations*. Macro optimizations include things like your choice of **algorithms**, deciding between different **data structures**, and the like. **Things that can have a big impact on performance** and often have large ri...
Get the name or ID of the current Google Compute Instance
31,688,646
3
2015-07-28T23:08:42Z
31,689,692
7
2015-07-29T01:15:43Z
[ "python", "google-compute-engine", "google-cloud-platform" ]
I'm running a number of Google Compute Engine instances that run Python code, and I want to find the name or the ID of each instance from inside the instances. One solution I've found is to get the internal IP of the instance using: ``` import socket internal_ip = socket.gethostbyname(socket.gethostname()) ``` Then ...
**Instance Name:** `socket.gethostname()` or `platform.node()` should return the name of the instance. You might have to do a bit of parsing depending on your OS. This worked for me on Debian and Ubuntu systems: ``` import socket gce_name = socket.gethostname() ``` However, on a CoreOS instance, the `hostname` comm...
Creating large Pandas DataFrames: preallocation vs append vs concat
31,690,076
4
2015-07-29T02:06:02Z
31,713,471
7
2015-07-30T00:42:03Z
[ "python", "pandas" ]
I am confused by the performance in Pandas when building a large dataframe chunk by chunk. In Numpy, we (almost) always see better performance by preallocating a large empty array and then filling in the values. As I understand it, this is due to Numpy grabbing all the memory it needs at once instead of having to reall...
Your benchmark is actually too small to show the real difference. Appending, copies EACH time, so you are actually doing copying a size N memory space N\*(N-1) times. This is horribly inefficient as the size of your dataframe grows. This certainly might not matter in a very small frame. But if you have any real size th...
max() not returning the correct maximum number
31,692,420
2
2015-07-29T06:07:55Z
31,692,532
7
2015-07-29T06:14:18Z
[ "python", "floating-point" ]
I am using the following code to find out which of the two numbers has a maximum value: ``` maximum = max(2.3,2.300000000001) print maximum ``` But the output I get is `2.3` and not `2.300000000001`. Can anyone explain why this happens?
Don't worry - `max` isn't broken, and `maximum` indeed holds `2.300000000001`. `print`, however, rounds it when printing. You could use [`repr`](https://docs.python.org/2/library/functions.html#func-repr) to prove that: ``` >>> maximum = max(2.3,2.300000000001) >>> print maximum 2.3 >>> print repr(maximum) 2.30000000...
all( generator ) returns True when it should return False
31,692,660
3
2015-07-29T06:21:35Z
31,692,765
7
2015-07-29T06:27:15Z
[ "python", "numpy", "generator", "canopy" ]
I want to check if a string contains all the keywords. I am using the [Enthought Canopy](https://www.enthought.com/products/canopy/) distribution. For example: ``` string = 'I like roses but not violets' key_words = ['roses', 'violets', 'tulips'] ``` I've read that the `all` function would serve me well. When I use...
You probably have a `from numpy import *` in your code. `numpy`'s `all` method does not handle generators well. ``` [1]: string = 'I like roses but not violets' [2]: key_words = ['roses', 'violets', 'tulips'] [3]: if all( keys in string.lower().split() for keys in key_words): ...: print True ...
Lost important .py file (overwritten as 0byte file), but the old version still LOADED IN IPYTHON as module -- can it be retrieved?
31,707,587
21
2015-07-29T17:46:44Z
31,707,930
22
2015-07-29T18:04:05Z
[ "python", "linux", "vim", "ipython", "recovery" ]
Due to my stupidity, while managing several different screen sessions with vim open in many of them, in the process of trying to "organize" my sessions I somehow managed to overwrite a very important .py script with a 0Byte file. HOWEVER, I have an ipython instance open that, when running that same .py file as a modul...
As noted in comments, `inspect.getsource` will not work because it depends on the original file (ie, `module.__file__`). Best option: check to see if there's a `.pyc` file (ex, `foo.pyc` should be beside `foo.py`). If there is, you can use [Decompile Python 2.7 .pyc](http://stackoverflow.com/questions/8189352/decompil...
patching a class yields "AttributeError: Mock object has no attribute" when accessing instance attributes
31,709,792
7
2015-07-29T19:47:21Z
31,710,001
10
2015-07-29T19:59:41Z
[ "python", "attributes", "mocking", "python-unittest" ]
**The Problem** Using `mock.patch` with `autospec=True` to patch a class is not preserving attributes of instances of that class. **The Details** I am trying to test a class `Bar` that instantiates an instance of class `Foo` as a `Bar` object attribute called `foo`. The `Bar` method under test is called `bar`; it ...
No, autospeccing cannot mock out attributes set in the `__init__` method of the original class (or in any other method). It can only mock out *static attributes*, everything that can be found on the class. Otherwise, the mock would have to create an instance of the class you tried to replace with a mock in the first p...
Python equivalent of Haskell's [1..] (to index a list)
31,710,499
6
2015-07-29T20:29:49Z
31,710,528
20
2015-07-29T20:31:30Z
[ "python", "list", "loops", "haskell" ]
I have a list of elements in python. I don't know the number of elements in the list. I would like to add indexes to the list. In Haskell, I could do the following ``` zip [1..] "abcdefghijklmnop" [(1,'a'),(2,'b'),(3,'c'),(4,'d'),(5,'e'),(6,'f'),(7,'g'),(8,'h'),(9,'i'),(10,'j'),(11,'k'),(12,'l'),(13,'m'),(14,'n'),(15...
Just do `list(enumerate(s))`. This iterates over the `enumerate` object and converts it to a `list`.
Can't catch mocked exception because it doesn't inherit BaseException
31,713,054
8
2015-07-29T23:49:32Z
31,873,937
10
2015-08-07T09:13:28Z
[ "python", "exception-handling", "python-requests", "python-3.3", "python-mock" ]
I'm working on a project that involves connecting to a remote server, waiting for a response, and then performing actions based on that response. We catch a couple of different exceptions, and behave differently depending on which exception is caught. For example: ``` def myMethod(address, timeout=20): try: ...
I could reproduce the error with a minimal example: foo.py: ``` class MyError(Exception): pass class A: def inner(self): err = MyError("FOO") print(type(err)) raise err def outer(self): try: self.inner() except MyError as err: print ("catche...
Replace a character with multiple characters using Python
31,714,940
2
2015-07-30T03:56:38Z
31,714,963
7
2015-07-30T03:59:42Z
[ "python", "string", "generator", "str-replace" ]
I have been trying to solve the following problem using Python, and so far without success: Assume you have a string with the characters '0', '1' and '?'. the '?' sign can be either '0' or '1'. Your goal is to print all the possible outputs for such given string.For example, the output for the string '0?1?' should be ...
`comb()` is a generator function , when you do - ``` yield comb(S.replace('?','0',1)) ``` The `yield` statement does not automatically loop over all the values in the generator and yield them, you have to loop over the values and yield them one by one, Example - ``` def comb(S): if not '?' in S: yield S ...
replacing of numbers to zero in a sum
31,716,622
2
2015-07-30T06:31:12Z
31,716,674
12
2015-07-30T06:33:41Z
[ "python" ]
I have to define a function `'func(a, b, c)'` in which there are 3 variables it calculates their sum. I have to check if there value is greater than `'13'` then the number becomes `'0'` eg., `'def func(3,4,14)'` ---> 7 (3+4+0) I've tried this code below: ``` def no_teen_sum(a, b, c): if(a>13): a=0 elif(b>1...
Your problem is using `elif`. You want to use `if`: ``` def no_teen_sum(a, b, c): if a > 13: a = 0 if b > 13: b = 0 if c > 13: c = 0 return a + b + c ``` To create a general function you could use [`*args`](https://docs.python.org/2/tutorial/controlflow.html#arbitrary-argument-...
Why does printing a file with unicode characters does not produce the emojis?
31,725,918
2
2015-07-30T14:02:57Z
31,726,061
8
2015-07-30T14:09:01Z
[ "python", "unicode" ]
the content of the text file is ``` u'\u26be\u26be\u26be' ``` When I run the script... ``` import codecs f1 = codecs.open("test1.txt", "r", "utf-8") text = f1.read() print text str1 = u'\u26be\u26be\u26be' print(str1) ``` I get the output... ``` u'\u26be\u26be\u26be' ⚾⚾⚾ ``` Question: Why is that a string, ...
File content `u'\u26be\u26be\u26be'` is like `r"u'\u26be\u26be\u26be'"`. In other words, characters of `u`, `\`, `u`, `2`, ... You can convert such string to the string `⚾⚾⚾` using [`ast.literal_eval`](https://docs.python.org/2/library/ast.html#ast.literal_eval): ``` import ast import codecs with codecs.open("...
Is there a best way to change given number of days to years months weeks days in Python?
31,739,208
3
2015-07-31T06:12:16Z
31,739,388
7
2015-07-31T06:24:58Z
[ "python", "django", "datetime" ]
I am giving number of days to convert them to years, months, weeks and days, but I am taking default days to 365 and month days to 30. How do I do it in an effective way? ``` def get_year_month_week_day(days): year = days / 365 days = days % 365 month = days / 30 days = days % 30 week = days / 7 ...
It is much easier if you use a third-party library named [`python-dateutil`](https://dateutil.readthedocs.org/en/latest/relativedelta.html#module-dateutil.relativedelta): ``` >>> import datetime >>> from dateutil.relativedelta import relativedelta >>> now = datetime.datetime.now() >>> td = datetime.timedelta(days=500...
Create a list of integers with duplicate values in Python
31,743,603
6
2015-07-31T10:08:10Z
31,743,627
11
2015-07-31T10:09:46Z
[ "python", "list", "python-2.7", "integer" ]
This question will no doubt to a piece of cake for a Python 2.7 expert (or enthusiast), so here it is. How can I create a list of integers whose value is duplicated next to it's original value like this? ``` a = list([0, 0, 1, 1, 2, 2, 3, 3, 4, 4]) ``` It's really easy to do it like this: ``` for i in range(10): a....
``` >>> [i//2 for i in xrange(10)] [0, 0, 1, 1, 2, 2, 3, 3, 4, 4] ``` A simple generic approach: ``` >>> f = lambda rep, src: reduce(lambda l, e: l+rep*[e], src, []) >>> f(2, xrange(5)) [0, 0, 1, 1, 2, 2, 3, 3, 4, 4] >>> f(3, ['a', 'b']) ['a', 'a', 'a', 'b', 'b', 'b'] ```
What is choice_set.all in Django tutorial
31,746,571
4
2015-07-31T12:46:30Z
31,746,649
8
2015-07-31T12:50:24Z
[ "python", "django" ]
In the Django tutorial: ``` {% for choice in question.choice_set.all %} ``` I couldn't find a brief explanation for this. I know that in the admin.py file, I have created a foreign key of Question model on the choice model such that for every choice there is a question.
That's the Django metaclass magic in action! Since you have a foreign key from `Choice` model to the `Question` model, you will automagically get the [inverse relation](https://docs.djangoproject.com/en/1.8/ref/models/relations/) on instances of the `question` model back to the set of possible choices. `question.choic...
How do you install mysql-connector-python (development version) through pip?
31,748,278
12
2015-07-31T14:11:52Z
34,027,037
31
2015-12-01T18:02:38Z
[ "python", "mysql", "django" ]
I have a virtualenv in which I am running Django 1.8 with Python 3.4 I am trying to get support for MySQL however I am having trouble getting the different connectors to work. I have always used mysql-connector-python with django 1.7 and would like to continue using it. The development version of mysql-connector-pyth...
I agree, the debian packages appear to be broken for at least Ubuntu 14.04. The apt-get version and the pip version do not include the 2.1.x releases. To get it done, I had to grab the source: ``` $ git clone https://github.com/mysql/mysql-connector-python.git $ cd mysql-connector-python $ python ./setup.py build...
Too many if statements
31,748,617
5
2015-07-31T14:27:40Z
31,748,695
10
2015-07-31T14:30:55Z
[ "python", "if-statement", "conditional", "code-readability", "code-maintainability" ]
I have some topic to discuss. I have a fragment of code with 24 ifs/elifs. *Operation* is my own class that represents functionality similar to Enum. Here is a fragment of code: ``` if operation == Operation.START: strategy = strategy_objects.StartObject() elif operation == Operation.STOP: strategy = strategy_...
You could possibly use a dictionary. Dictionaries store references, which means functions are perfectly viable to use, like so: ``` operationFuncs = { Operation.START: strategy_objects.StartObject Operation.STOP: strategy_objects.StopObject Operation.STATUS: strategy_objects.StatusObject (...) ...
How to add percentages on top of bars in seaborn?
31,749,448
5
2015-07-31T15:04:38Z
31,754,317
9
2015-07-31T20:03:17Z
[ "python", "matplotlib", "seaborn" ]
Given the following count plot how do I place percentages on top of the bars? ``` import seaborn as sns sns.set(style="darkgrid") titanic = sns.load_dataset("titanic") ax = sns.countplot(x="class", hue="who", data=titanic) ``` [![enter image description here](http://i.stack.imgur.com/b1m5F.png)](http://i.stack.imgur....
`sns.barplot` doesn't explicitly return the barplot values the way `matplotlib.pyplot.bar` does (see last para), but if you've plotted nothing else you can risk assuming that all the `patches` in the axes are your values. Then you can use the sub-totals that the barplot function has calculated for you: ``` from matplo...
TypeError: 'float' object is not iterable, Python list
31,749,695
3
2015-07-31T15:18:23Z
31,749,762
12
2015-07-31T15:21:50Z
[ "python", "list", "python-2.7", "loops", "typeerror" ]
I am writing a program in Python and am trying to extend a list as such: ``` spectrum_mass[second] = [1.0, 2.0, 3.0] spectrum_intensity[second] = [4.0, 5.0, 6.0] spectrum_mass[first] = [1.0, 34.0, 35.0] spectrum_intensity[second] = [7.0, 8.0, 9.0] for i in spectrum_mass[second]: if i not in spectrum_mass[first]: ...
I am guessing the issue is with the line - ``` spectrum_intensity[first].extend(spectrum_intensity[second][spectrum_mass[second].index(i)]) ``` `extend()` function expects an iterable , but you are trying to give it a float. Same behavior in a very smaller example - ``` >>> l = [1,2] >>> l.extend(1.2) Traceback (mos...
How do I close an image opened in Pillow?
31,751,464
4
2015-07-31T17:00:27Z
31,751,501
10
2015-07-31T17:02:13Z
[ "python", "python-imaging-library", "pillow" ]
I have a python file with the Pillow library imported. I can open an image with ``` Image.open(test.png) ``` But how do I close that image? I'm not using Pillow to edit the image, just to show the image and allow the user to choose to save it or delete it.
With [`Image.close().`](https://pillow.readthedocs.org/en/latest/reference/Image.html#PIL.Image.Image.close) You can also do it in a with block: ``` with Image.open('test.png') as test_image: do_things(test_image) ``` An example of using `Image.close()`: ``` test = Image.open('test.png') test.close() ```
Python vs perl sort performance
31,752,670
5
2015-07-31T18:20:37Z
31,753,182
7
2015-07-31T18:52:48Z
[ "python", "performance", "perl", "sorting" ]
***Solution*** This solved all issues with my Perl code (plus extra implementation code.... :-) ) In conlusion both Perl and Python are equally awesome. ``` use WWW::Curl::Easy; ``` Thanks to ALL who responded, very much appreciated. ***Edit*** It appears that the Perl code I am using is spending the majority of i...
Your benchmark is flawed, you're benchmarking multiple variables, not one. It is not just sorting data, but it is also doing JSON decoding, and creating strings, and appending to an array. You can't know how much time is spent sorting and how much is spent doing everything else. The matter is made worse in that there ...
How can I know which element in a list triggered an any() function?
31,759,256
6
2015-08-01T07:04:25Z
31,759,295
9
2015-08-01T07:08:55Z
[ "python", "python-2.7" ]
I'm developing a Python program to detect names of cities in a list of records. The code I've developed so far is the following: ``` aCities = ['MELBOURNE', 'SYDNEY', 'PERTH', 'DUBAI', 'LONDON'] cxTrx = db.cursor() cxTrx.execute( 'SELECT desc FROM AccountingRecords' ) for row in cxTrx.fetchall() : if any( city i...
I don't think it's possible with `any`. You can use [`next`](https://docs.python.org/2/library/functions.html#next) with default value: ``` for row in cxTrx.fetchall() : city = next((city for city in aCities if city in row[0]), None) if city is not None: #print the name of the city that fired the any()...
String comparison '1111' < '99' is True
31,760,478
2
2015-08-01T09:47:31Z
31,760,495
10
2015-08-01T09:49:05Z
[ "python" ]
There is something wrong if you compare two string like this: ``` >>> "1111">'19' False >>> "1111"<'19' True ``` Why is '1111' less than than '19'?
Because strings are compared [*lexicographically*](https://en.wikipedia.org/wiki/Lexicographical_order). `'1'` is smaller than `'9'` (comes earlier in the character set). It doesn't matter that there are other characters after that. If you want to compare *numbers* you have to convert the string to a number first: ``...
swig unable to find openssl conf
31,762,106
2
2015-08-01T12:59:53Z
31,861,876
16
2015-08-06T17:13:08Z
[ "python", "ubuntu", "openssl", "swig", "m2crypto" ]
Trying to install m2crypto and getting these errors, can anyone help ? ``` SWIG/_evp.i:12: Error: Unable to find 'openssl/opensslconf.h' SWIG/_ec.i:7: Error: Unable to find 'openssl/opensslconf.h' ```
``` ln -s /usr/include/x86_64-linux-gnu/openssl/opensslconf.h /usr/include/openssl/opensslconf.h ``` Just made this and everything worked fine.
ImportError: cannot import name RAND_egd
31,762,371
10
2015-08-01T13:28:24Z
31,763,219
7
2015-08-01T15:00:54Z
[ "python", "ssl", "import", "executable", "py2exe" ]
I've tried to create an exe file using py2exe. I've recently updated Python from 2.7.7 to 2.7.10 to be able to work with `requests` - `proxies`. Before the update everything worked fine but now, the exe file recently created, raising this error: ``` Traceback (most recent call last): File "puoka_2.py", line 1, ...
According to results in google, it seems to be a very rare Error. I don't know exactly what is wrong but I found a **workaround** for that so if somebody experiences this problem, maybe this answer helps. Go to `socket.py` file and search for `RAND_egd`. There is a block of code (67 line in my case): ``` from _ssl im...
pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory
31,768,128
21
2015-08-02T02:49:20Z
31,769,149
14
2015-08-02T06:21:35Z
[ "python", "osx", "installation", "pip", "osx-mavericks" ]
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cach...
I'm guessing you have two python installs, or two pip installs, one of which has been partially removed. Why do you use `sudo`? Ideally you should be able to install and run everything from your user account instead of using root. If you mix root and your local account together you are more likely to run into permissi...
pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory
31,768,128
21
2015-08-02T02:49:20Z
33,872,341
90
2015-11-23T13:31:00Z
[ "python", "osx", "installation", "pip", "osx-mavericks" ]
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cach...
I had used home-brew to install 2.7 on OS X 10.10 and the new install was missing the sym links. I ran ``` brew link --overwrite python ``` as mentioned in [How to symlink python in Homebrew?](http://stackoverflow.com/questions/13354207/how-to-symlink-python-in-homebrew/13354417#13354417) and it solved the problem.
pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory
31,768,128
21
2015-08-02T02:49:20Z
34,550,600
9
2015-12-31T18:57:13Z
[ "python", "osx", "installation", "pip", "osx-mavericks" ]
I don't know what's the deal but I am stuck following some stackoverflow solutions which gets nowhere. Can you please help me on this? ``` Monas-MacBook-Pro:CS764 mona$ sudo python get-pip.py The directory '/Users/mona/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cach...
I made the same error using sudo for my installation. (oops) ``` brew install python brew linkapps python brew link --overwrite python ``` This brought everything back to normal.
Add bias to Lasagne neural network layers
31,773,204
6
2015-08-02T15:05:37Z
31,774,280
8
2015-08-02T16:57:33Z
[ "python", "neural-network", "theano", "lasagne" ]
I am wondering if there is a way to add bias node to each layer in Lasagne neural network toolkit? I have been trying to find related information in documentation. This is the network I built but i don't know how to add a bias node to each layer. ``` def build_mlp(input_var=None): # This creates an MLP of two hid...
Actually you don't have to explicitly create biases, because `DenseLayer()`, and convolution base layers too, has a default keyword argument: `b=lasagne.init.Constant(0.)`. Thus you can avoid creating `bias`, if you don't want to have with explicitly pass `bias=None`, but this is not that case. Thus in brief you do ...
PCA Analysis in PySpark
31,774,311
3
2015-08-02T17:01:05Z
31,775,865
8
2015-08-02T19:40:58Z
[ "python", "apache-spark", "pca" ]
Looking at <http://spark.apache.org/docs/latest/mllib-dimensionality-reduction.html>. The examples seem to only contain Java and Scala. Does Spark MLlib support PCA analysis for python? If so please point me to an example. If not, how to combine Spark with Sklearn?
### Spark < 1.5.0 PySpark <= 1.4.1 doesn't support distributed data structures yet so there is no built-in method to compute PCA. If input matrix is relatively thin you can compute covariance matrix in a distributed manner, collect the results and perform eigendecomposition locally on a driver. Order of operations is...
Installing mechanize for python 3.4
31,774,756
5
2015-08-02T17:46:07Z
31,774,959
8
2015-08-02T18:05:38Z
[ "python", "mechanize" ]
I'm trying to retrieve the mechanize module for python 3.4. Can anybody guide me in the right direction and perhaps walk me through the steps that I would need to take in order to make the correct installation? I'm currently using Windows 10. Thank you.
unfortunately mechanize only works with Python 2.4, Python 2.5, Python 2.6, and Python 2.7. The good news is there are other projects you can take a look at: [RoboBrowser](https://github.com/jmcarp/robobrowser), [MechanicalSoup](https://github.com/hickford/MechanicalSoup) There are more alternatives in this thread as...
Python Operator (+=) and SyntaxError
31,778,646
2
2015-08-03T02:32:02Z
31,778,661
8
2015-08-03T02:34:17Z
[ "python", "python-2.7", "syntax-error", "operators" ]
Ok, what am I doing wrong? ``` x = 1 print x += 1 ``` Error: ``` print x += 1 ^ SyntaxError: invalid syntax ``` Or, does `+=` not work in Python 2.7 anymore? I would swear that I have used it in the past.
`x += 1` is an [augmented assignment statement](https://docs.python.org/2/reference/simple_stmts.html#augmented-assignment-statements) in Python. You cannot use *statements* inside the print statement , that is why you get the syntax error. You can only use [*Expressions*](https://docs.python.org/2/reference/expressio...
Runtime error when trying to logout django
31,779,234
4
2015-08-03T04:01:12Z
31,779,289
7
2015-08-03T04:08:25Z
[ "python", "django", "recursion", "runtime", "logout" ]
When I try to logout from my django project, I get the following error: "maximum recursion depth exceeded while calling a Python object" Here is the url for the logout button: ``` url(r'^logout', 'users.views.logout', name='logout'), ``` And here is the view: ``` from django.shortcuts import render from deck1.mode...
Your view `logout` is overriding the namespace of built-in `logout` function. Define an alias for `django.contrib.auth.login` function using `as` keyword. ``` from django.contrib.auth import logout as django_logout @login_required def logout(request): django_logout(request) return HttpResponseRedirect('/deck...
If statement check list contains is returning true when it shouldn't
31,780,687
10
2015-08-03T06:28:22Z
31,780,723
35
2015-08-03T06:30:32Z
[ "python", "list", "if-statement" ]
I have a list which contains the values: ``` ['1', '3', '4', '4'] ``` I have an if statement which will check if the values are contained within the list then output a statement: ``` if "1" and "2" and "3" in columns: print "1, 2 and 3" ``` Considering the list doesn't contain value "2", it should not print the...
It gets evaluated in order of [operator precedence](https://docs.python.org/2/reference/expressions.html#operator-precedence): ``` if "1" and "2" and ("3" in columns): ``` Expands into: ``` if "1" and "2" and True: ``` Which then evaluates `("1" and "2")` leaving us with: ``` if "2" and True ``` Finally: ``` if ...
If statement check list contains is returning true when it shouldn't
31,780,687
10
2015-08-03T06:28:22Z
31,784,924
11
2015-08-03T10:23:05Z
[ "python", "list", "if-statement" ]
I have a list which contains the values: ``` ['1', '3', '4', '4'] ``` I have an if statement which will check if the values are contained within the list then output a statement: ``` if "1" and "2" and "3" in columns: print "1, 2 and 3" ``` Considering the list doesn't contain value "2", it should not print the...
There's two general rules to keep in mind in order to understand what's happening: * **a boolean operator always [returns the result of the evaluation of one operand](https://docs.python.org/2/reference/expressions.html#boolean-operations)**. * **operations are executed in the [order of precendence](https://docs.pytho...
How to parallelized file downloads?
31,784,484
2
2015-08-03T09:58:58Z
31,795,242
9
2015-08-03T19:26:44Z
[ "python", "python-3.x", "download", "subprocess", "wget" ]
I can download a file at a time with: ``` import urllib.request urls = ['foo.com/bar.gz', 'foobar.com/barfoo.gz', 'bar.com/foo.gz'] for u in urls: urllib.request.urlretrieve(u) ``` I could try to `subprocess` it as such: ``` import subprocess import os def parallelized_commandline(command, files, max_processes=...
You could use a thread pool to download files in parallel: ``` #!/usr/bin/env python3 from multiprocessing.dummy import Pool # use threads for I/O bound tasks from urllib.request import urlretrieve urls = [...] result = Pool(4).map(urlretrieve, urls) # download 4 files at a time ``` You could also download several f...
Django Rest Framework: turn on pagination on a ViewSet (like ModelViewSet pagination)
31,785,966
8
2015-08-03T11:24:02Z
31,789,223
10
2015-08-03T13:56:18Z
[ "python", "django", "django-rest-framework" ]
I have a ViewSet like this one to list users' data: ``` class Foo(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) ``` I want to turn on pagination like the default pagination for Mo...
> Pagination is only performed automatically if you're using the generic > views or viewsets The first roadblock is translating the docs to english. What they intended to convey is that you desire a generic viewset. The generic viewsets extend from [generic ApiViews](https://github.com/tomchristie/django-rest-framewor...
Python if statement without indent
31,787,110
2
2015-08-03T12:19:22Z
31,787,348
8
2015-08-03T12:31:24Z
[ "python", "python-2.7" ]
I'm working with an inherited Python program, which runs OK, but does not have correct Python indenting. ``` if not arg_o: print >> sys.stderr, 'Output file needed.' print >> sys.stderr, usage exit() ``` What is going on here? Shouldn't the code below the **if** be indented? **SOLVED** See the accepted answer. It t...
After checking the file - `MPprimer.py` - from the code found [here](https://code.google.com/p/mpprimer/downloads/list) . I can see the following lines in it - ``` if not arg_o: print >> sys.stderr, 'Output file needed.' print >> sys.stderr, usage exit() ``` Starting at line 175 . The issue is that this ...
Stop Django from creating migrations if the list of choices of a field changes
31,788,450
12
2015-08-03T13:21:05Z
31,788,759
10
2015-08-03T13:33:56Z
[ "python", "django", "database-migration" ]
I have a django core app called "foocore". There are several optional pluging-like apps. For example "superfoo". In my case every plugin adds a new choice in a model CharField which belongs to "foocore". Django migrations detect changes if the list of choices get changed. I think this is not necessary. At least one...
See this bug report and discussion for more info: <https://code.djangoproject.com/ticket/22837> The proposed solution was to use a callable as the argument for choices, but it appears this has not been executed for fields but for forms only. If you really need dynamic choices than a `ForeignKey` is the best solution....
Removing a character from a string in a list of lists
31,794,610
3
2015-08-03T18:48:57Z
31,794,656
7
2015-08-03T18:51:46Z
[ "python", "string", "list", "replace" ]
I'm trying to format some data for performing an analysis. I'm trying to remove `'*'` from all strings that start with one. Here's a snippet of the data: ``` [['Version', 'age', 'language', 'Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9', 'Q10', 'Q11', 'Q12', 'Q13', 'Q14', 'Q15', 'Q16', 'Q17', 'Q18', 'Q19', 'Q20'...
`string`s are immutable , and as such `item.replace('*','')` returns back the string with the replaced characters, it does not replace them inplace (it cannot , since `string`s are immutable) . you can enumerate over your lists, and then assign the returned string back to the list - Example - ``` for lst in testList:...
Sum element by element multiple lists of different lengths
31,795,569
4
2015-08-03T19:47:52Z
31,795,607
9
2015-08-03T19:49:58Z
[ "python", "python-3.x" ]
Is there any way to sum over multiple lists, index by index, to get one final list? Knowing that these lists might not have the same length? For example, with these ``` [2,4,0,0], [0,0,2], [0,4] ``` I would like to have ``` [2,8,2,0] ``` as a result. I haven't found any result so far.
You can use [`itertools.zip_longest`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest) with the `fillvalue` argument set to `0`. If you use this in a list comprehension, you can unpack and zip the inner lists and add them in an element-wise fashion. ``` >>> from itertools import zip_longest >>> ...
psycopg2 insert python dictionary as json
31,796,332
2
2015-08-03T20:37:03Z
31,796,487
8
2015-08-03T20:48:14Z
[ "python", "postgresql", "dictionary", "psycopg2" ]
I want to insert a python dictionary as a json into my postgresql database (via python and psycopg2). I have: ``` ... thedictionary = {'price money': '$1', 'name': 'Google', 'color': '', 'imgurl': 'http://www.google.com/images/nav_logo225.png', 'charateristics': 'No Description', 'store': 'google'} ... cur.execute("I...
``` cur.execute("INSERT INTO product(store_id, url, price, charecteristics, color, dimensions) VALUES (%s, %s, %s, %s, %s, %s)", (1, 'http://www.google.com', '$20', json.dumps(thedictionary), 'red', '8.5x11')) ``` That will solve your problem. However, you really should be storing keys and values in their own separat...
How does python "know" what to do with the "in" keyword?
31,796,910
33
2015-08-03T21:17:33Z
31,796,967
12
2015-08-03T21:22:17Z
[ "python" ]
I'm a bit bewildered by the "in" keyword in python. If I take a sample list of tuples: ``` data = [ (5, 1, 9.8385465), (10, 1, 8.2087544), (15, 1, 7.8788187), (20, 1, 7.5751283) ] ``` I can do two different "for - in" loops and get different results: ``` for G,W,V in data: print G,W,V ``` This ...
It's called [tuple unpacking](https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences), and has nothing to do with the `in` keyword. The `for` loop returns the single thing (a `tuple` in this case), and then that `tuple` gets assigned -- to a single item in the second case, or multiple items in the...
How does python "know" what to do with the "in" keyword?
31,796,910
33
2015-08-03T21:17:33Z
31,796,997
35
2015-08-03T21:23:48Z
[ "python" ]
I'm a bit bewildered by the "in" keyword in python. If I take a sample list of tuples: ``` data = [ (5, 1, 9.8385465), (10, 1, 8.2087544), (15, 1, 7.8788187), (20, 1, 7.5751283) ] ``` I can do two different "for - in" loops and get different results: ``` for G,W,V in data: print G,W,V ``` This ...
According to [the `for` compound statement documentation](https://docs.python.org/2/reference/compound_stmts.html#the-for-statement): > Each item in turn is assigned to the target list using the standard > rules for assignments... Those *"standard rules"* are in [the assignment statement documentation](https://docs.p...
How does python "know" what to do with the "in" keyword?
31,796,910
33
2015-08-03T21:17:33Z
31,797,008
21
2015-08-03T21:24:32Z
[ "python" ]
I'm a bit bewildered by the "in" keyword in python. If I take a sample list of tuples: ``` data = [ (5, 1, 9.8385465), (10, 1, 8.2087544), (15, 1, 7.8788187), (20, 1, 7.5751283) ] ``` I can do two different "for - in" loops and get different results: ``` for G,W,V in data: print G,W,V ``` This ...
This isn't really a feature of the `in` keyword, but of the Python language. The same works with assignment. ``` x = (1, 2, 3) print(x) >>> (1, 2, 3) a, b, c = (1, 2, 3) print(a) >>> 1 print(b) >>> 2 print(c) >>> 3 ``` So to answer your question, it's more that Python knows what to do with assignments when you eithe...
Get java version number from python
31,807,882
2
2015-08-04T11:18:21Z
31,808,419
7
2015-08-04T11:44:47Z
[ "python", "bash", "sed", "grep", "cut" ]
I need to get the java version number, for example "1.5", from python (or bash). I would use: ``` os.system('java -version 2>&1 | grep "java version" | cut -d "\\\"" -f 2') ``` But that returns 1.5.0\_30 It needs to be compatible if the number changes to "1.10" for example. I would like to use cut or grep or even ...
The Java runtime seems to send the version information to the stderr. You can get at this using Python's [`subprocess`](https://docs.python.org/2/library/subprocess.html#subprocess.check_output) module: ``` >>> import subprocess >>> version = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT) >>>...
pip install requests[security] vs pip install requests: Difference
31,811,949
5
2015-08-04T14:24:45Z
31,812,342
9
2015-08-04T14:42:01Z
[ "python", "python-2.7", "pip", "virtualenv", "python-requests" ]
I am using Ubuntu 14.04 with python version 2.7.6. Today, when I created a new `virtualenv` and tried doing `pip install requests` , I got the error `InsecurePlatformWarning`. I resolved this issue by following the instructions over here [SSL InsecurePlatform error when using Requests package](http://stackoverflow.co...
> Why does the former install 3 additional packages? Using `requests[security]` instead of `requests` will install [three additional packages](https://github.com/kennethreitz/requests/blob/master/setup.py#L72): * `pyOpenSSL` * `ndg-httpsclient` * `pyasn1` These are defined in `extras_requires`, as [optional features...
AttributeError: 'Nonetype' object has no attribute '_info'
31,816,158
3
2015-08-04T18:00:40Z
32,358,780
9
2015-09-02T16:48:25Z
[ "python", "django" ]
I am working on a `Django` project and this error arises when I try to run any management commands such as: `python manage.py validate --settings ord.settings.development`, `python manage.py syncdb --settings ord.settings.development`. The project uses `Django 1.5` The error is: `AttributeError: 'Nonetype' object has n...
Had the same issue, Please follow the steps: 1. go to `django/utils/translation/trans_real.py` 2. search for `res = _translation(globalpath)` 3. Add the following: ``` if res is None: return gettext_module.NullTranslations() ``` source: <https://code.djangoproject.com/ticket/18192>
Can't import pprint
31,817,717
2
2015-08-04T19:33:03Z
31,817,755
7
2015-08-04T19:34:58Z
[ "python", "import", "pprint" ]
Programming newbie here. Whenever I attempt to 'import pprint' in the Python IDLE, I get the following error: ``` >>> import pprint Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> import pprint File "C:\Python34\pprint.py", line 10, in <module> pprint(count) NameError: name 'ppr...
You've named a program `pprint`. Rename your program to something other than `pprint.py` and remove any `pprint.pyc` file that might be present.
Python 2.7: round number to nearest integer
31,818,050
25
2015-08-04T19:51:39Z
31,818,069
47
2015-08-04T19:52:36Z
[ "python", "python-2.7" ]
I've been trying to round long float numbers like: ``` 32.268907563; 32.268907563; 31.2396694215; 33.6206896552; ... ``` With no success so far. I tried `math.ceil(x)` , `math.floor(x)` (although that would round up or down, which is not what I'm looking for) and `round(x)` which didn't work either (still float numbe...
``` int(round(x)) ``` Will round it and change it to integer EDIT: You are not assigning int(round(h)) to any variable. When you call int(round(h)), it returns the integer number but does nothing else; you have to change that line for: ``` h = int(round(h)) ``` To assign the new value to h
python 2 strange list comprehension behaviour
31,820,774
6
2015-08-04T23:00:47Z
31,820,859
12
2015-08-04T23:09:15Z
[ "python", "list-comprehension" ]
I was looking around list comprehension and saw smth strange. Code: ``` a = ['a', 'a', 'a', 'b', 'd', 'd', 'c', 'c', 'c'] print [(len(list(g)), k) if len(list(g)) > 1 else k for k, g in groupby(a)] ``` Result: `[(0, 'a'), 'b', (0, 'd'), (0, 'c')]` But I wanted to see: `[(3, 'a'), 'b', (2, 'd'), (3, 'c')]` What's ...
When you call `list()` on an `itertools._grouper` object, you exhaust the object. Since you're doing this twice, the second instance results in a length of 0. First: ``` if len(list(g)) ``` now it's exhausted. Then: ``` (len(list(g)), k)) ``` It will have a length of 0. You can nest a generator/comprehension in y...
How does the @timeout(timelimit) decorator work?
31,822,190
9
2015-08-05T01:56:13Z
31,822,272
13
2015-08-05T02:07:18Z
[ "python" ]
I found this decorator that times out a function here on Stack Overflow, and I am wondering if someone could explain in detail how it works, as the code is very elegant but not clear at all. Usage is `@timeout(timelimit)`. ``` from functools import wraps import errno import os import signal class TimeoutError(Excepti...
> # How does the @timeout(timelimit) decorator work? ## Decorator Syntax To be more clear, the usage is like this: ``` @timeout(100) def foo(arg1, kwarg1=None): '''time this out!''' something_worth_timing_out() ``` The above is the decorator syntax. The below is exactly equivalent: ``` def foo(arg1, kwarg1...
Python: Importing urllib.quote
31,827,012
8
2015-08-05T08:17:28Z
31,827,113
14
2015-08-05T08:22:11Z
[ "python", "python-3.x", "import", "urllib" ]
I would like to use `urllib.quote()`. But python (python3) is not finding the module. Suppose, I have this line of code: ``` print(urllib.quote("châteu", safe='')) ``` How do I import urllib.quote? `import urllib` or `import urllib.quote` both give ``` AttributeError: 'module' object has no attribute 'quote' ``` ...
In Python 3.x, you need to import [`urllib.parse.quote`](https://docs.python.org/3/library/urllib.parse.html): ``` >>> import urllib.parse >>> urllib.parse.quote("châteu", safe='') 'ch%C3%A2teu' ``` According to [Python 2.x `urllib` module documentation](https://docs.python.org/2/library/urllib.html): > **NOTE** > ...
Generating NXN spirals
31,832,862
9
2015-08-05T12:41:21Z
31,833,990
15
2015-08-05T13:29:57Z
[ "python" ]
I have been given the task of creating a spiral in python where the user inputs a number e.g 3 and it will output a 3x3 spiral which looks like this: ``` - - \ / \ | \ - / ``` **I am not looking for the full code** I just have no idea how to do it, obviously printing out every possible solution using if statements is...
I respect you for not wanting the full code. This is intentionally only a partial answer. Start by making a 2-dimensional array. Something like: ``` grid = [[None]*n for i in range(n)] ``` This allows you to write code like `grid[i][j] = '\'`. Start with `i,j = 0,0`. In a loop spiral around the grid. It might help ...
Generating NXN spirals
31,832,862
9
2015-08-05T12:41:21Z
31,834,067
14
2015-08-05T13:32:48Z
[ "python" ]
I have been given the task of creating a spiral in python where the user inputs a number e.g 3 and it will output a 3x3 spiral which looks like this: ``` - - \ / \ | \ - / ``` **I am not looking for the full code** I just have no idea how to do it, obviously printing out every possible solution using if statements is...
Things to note: * number of characters in rows/cols is **n** * first row will always have **n - 1** `-`s and one `\` * last row will always have **n - 2** `-`s, begin with `\` and ends with `/` For example, when `n` is 4: First row: `- - - \` Last row: `\ - - /` Can be easily achieved using: ``` def get_first_ra...
Difference between 'number % 2:' and 'number % 2 == 0'?
31,837,170
3
2015-08-05T15:48:27Z
31,837,211
11
2015-08-05T15:50:17Z
[ "python", "python-3.x" ]
I'm learning about Python's boolean logic and how you can shorten things down. Are the two expressions in the title equivalent? If not, what are the differences between them?
`number % 2` is 0 (so False) if number is even `number % 2 == 0` is True is number is even The first returns an `int` where the second returns a `bool`. Python's [truthiness](https://docs.python.org/2/library/stdtypes.html#truth-value-testing) lets you handle them the same though.
Why does this class run?
31,839,816
2
2015-08-05T18:10:01Z
31,839,958
7
2015-08-05T18:17:16Z
[ "python", "python-3.x" ]
I've been playing with my codes a little for a while, and this one is not about a bug or anything, but i just don't understand why class main() runs without needing to initialize it... ``` class vars(): var1 = "Universe!" var2 = "Oscar!" var3 = "Rainbow!" class main(): print (vars.var1) def __init...
Unlike many other languages, class body is an executable statement in Python and is executed immediately as the interpreter reaches the `class` line. When you run this "program": ``` class Foo: print("hey") ``` it just prints "hey" without any `Foo` object being created. The same applies to the function definiti...
More efficient way to look up dictionary values whose keys start with same prefix
31,841,303
5
2015-08-05T19:33:04Z
31,841,363
8
2015-08-05T19:36:30Z
[ "python", "performance", "dictionary", "lookup", "startswith" ]
I have a dictionary whose keys come in sets that share the same prefix, like this: ``` d = { "key1":"valA", "key123":"valB", "key1XY":"valC", "key2":"valD", "key2-22":"valE" } ``` Given a query string, I need to look up all the values associated with keys that start with that prefix, e.g. for `query="key1"` I n...
You can avoid producing the intermediate list generated by `dict.keys()` (in python 2.x): ``` result = [d[key] for key in d if key.startswith(query)] ``` But you most likely want to use a [*trie*](https://en.wikipedia.org/wiki/Trie) instead of a dictionary, so you can find all the values associated with a key with a ...
What is this python expression containing curly braces and a for in loop?
31,846,592
2
2015-08-06T03:59:18Z
31,846,617
8
2015-08-06T04:01:19Z
[ "python" ]
I just came across this line of python: ``` order.messages = {c.Code:[] for c in child_orders} ``` I have no idea what it is doing, other than it is looping over the list `child_orders` and placing the result in `order.messages`. What does it do and what is it called?
It's dictionary comprehension! It's iterating through `child_orders` and creating a dictionary where the key is `c.Code` and the value is `[]`. More info [here](http://stackoverflow.com/questions/1747817/python-create-a-dictionary-with-list-comprehension).
What is this python expression containing curly braces and a for in loop?
31,846,592
2
2015-08-06T03:59:18Z
31,846,622
7
2015-08-06T04:01:29Z
[ "python" ]
I just came across this line of python: ``` order.messages = {c.Code:[] for c in child_orders} ``` I have no idea what it is doing, other than it is looping over the list `child_orders` and placing the result in `order.messages`. What does it do and what is it called?
That's a *dict comprehension*. It is just like a *list comprehension* ``` [3*x for x in range(5)] --> [0,3,6,9,12] ``` except: ``` {x:(3*x) for x in range(5)} ---> { 0:0, 1:3, 2:6, 3:9, 4:12 } ``` * produces a Python `dictionary`, not a `list` * uses curly braces `{}` not square braces `[]` * defines *key:value*...
How to compute skipgrams in python?
31,847,682
10
2015-08-06T05:44:34Z
31,886,292
7
2015-08-07T20:40:18Z
[ "python", "nlp", "n-gram", "language-model" ]
A k [skipgram](http://homepages.inf.ed.ac.uk/ballison/pdf/lrec_skipgrams.pdf) is an ngram which is a superset of all ngrams and each (k-i )skipgram till (k-i)==0 (which includes 0 skip grams). So how to efficiently compute these skipgrams in python? Following is the code i tried but it is not doing as expected: ``` <...
From the [paper](http://homepages.inf.ed.ac.uk/ballison/pdf/lrec_skipgrams.pdf) that OP links, the following string: > Insurgents killed in ongoing fighting Yields: > 2-skip-bi-grams = {insurgents killed, insurgents in, insurgents > ongoing, killed in, killed ongoing, killed fighting, in ongoing, in > fighting, ongo...
Classifying Python array by nearest "seed" region?
31,848,309
12
2015-08-06T06:30:07Z
31,852,160
9
2015-08-06T09:37:41Z
[ "python", "arrays", "numpy", "scipy", "image-segmentation" ]
I have a raster of ecological habitats which I've converted into a two-dimensional Python numpy array (example\_array below). I also have an array containing "seed" regions with unique values (seed\_array below) which I'd like to use to classify my habitat regions. I'd like to **'grow' my seed regions 'into' my habitat...
You can use [watershed segmentation](http://scikit-image.org/docs/dev/auto_examples/plot_watershed.html) from scikits-image: * Distance transform ``` from scipy import ndimage as nd distance = nd.distance_transform_edt(example_array) ``` * Watershed segmentation ``` from skimage.morphology import watersh...
Serve image stored in SQLAlchemy LargeBinary column
31,849,494
5
2015-08-06T07:32:14Z
31,858,076
7
2015-08-06T14:13:07Z
[ "python", "flask", "sqlalchemy", "blob", "jinja" ]
I want to upload a file and store it in the database. I created a LargeBinary column. ``` logo = db.Column(db.LargeBinary) ``` I read the uploaded file and store it in the database. ``` files = request.files.getlist('file') if files: event.logo = files[0].file.read() ``` Is this the proper way to store an imag...
If you absolutely need to store the image in the database, then yes, this is correct. Typically, files are stored in the filesystem and the path is stored in the database. This is the better solution because the web server typically has an efficient method of serving files from the filesystem, as opposed to the applica...
Filling Many2many field (odoo 8)
31,853,402
6
2015-08-06T10:29:11Z
32,028,259
17
2015-08-15T19:01:23Z
[ "python", "xml", "postgresql", "openerp", "odoo" ]
**What I've done:** I have a module with ``` myfield = fields.Many2one('res.partner', string="Graduate", domain=[('is_graduated', '=', True)]) ``` Then I have another class with ``` _inherit = 'res.partner' is_graduated = fields.Boolean("Graduated before?", default=False) graduations = fields.Many2many('my_module.c...
``` user_rel_ids = fields.Many2many(comodel_name='course', relation='user_course_rel', column1='user_id', column2='course_id') ``` Or ``` user_rel_id = fields.Many2many('course') ``` For Filling Data (for add new relation) ``` user_rel_id = (4,...
What's the best way to share Jupyter notebooks with non-programmers?
31,855,794
19
2015-08-06T12:28:06Z
33,248,969
8
2015-10-21T00:22:11Z
[ "python", "ipython-notebook", "jupyter" ]
I am trying to wrap my head around what I can/cannot do with Jupyter. I have a Jupyter server running on our internal server, accessible via VPN and password protected. I am the only one actually creating notebooks but I would like to make some notebooks visible to other team members in a read-only way. Ideally I cou...
The "best" way to share a Jupyter notebook is to simply to place it on GitHub (and view it directly) or some other public link and use the [Jupyter Notebook Viewer](https://nbviewer.jupyter.org/). When privacy is more of an issue then there are alternatives but it's certainly more complex, there's no built in way to do...
What's the best way to share Jupyter notebooks with non-programmers?
31,855,794
19
2015-08-06T12:28:06Z
33,249,008
8
2015-10-21T00:27:39Z
[ "python", "ipython-notebook", "jupyter" ]
I am trying to wrap my head around what I can/cannot do with Jupyter. I have a Jupyter server running on our internal server, accessible via VPN and password protected. I am the only one actually creating notebooks but I would like to make some notebooks visible to other team members in a read-only way. Ideally I cou...
Michael's suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server. Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it's automatically refreshed after running the whole thing: `!ipython ...
Rotate tick labels for seaborn barplot
31,859,285
6
2015-08-06T15:04:16Z
31,861,477
8
2015-08-06T16:50:17Z
[ "python", "matplotlib", "seaborn" ]
I am trying to display a chart with rotated x-axis labels, but the chart is not displaying. ``` import seaborn as sns %matplotlib inline yellow='#FFB11E' by_school=sns.barplot(x ='Organization Name',y ='Score',data = combined.sort('Organization Name'),color=yellow,ci=None) ``` At this point I can see the image, but ...
You need a different method call, namely `.set_rotation` for each `ticklable`s. Since you already have the ticklabels, just change their rotations: ``` for item in by_school.get_xticklabels(): item.set_rotation(45) ``` `barplot` returns a `matplotlib.axes` object (as of `seaborn` 0.6.0), therefore you have to rot...
Format: KeyError when using curly brackets in strings
31,859,757
3
2015-08-06T15:24:56Z
31,859,804
7
2015-08-06T15:26:51Z
[ "python", "format" ]
I'm running the following code: ``` asset = {} asset['abc'] = 'def' print type(asset) print asset['abc'] query = '{"abc": "{abc}"}'.format(abc=asset['abc']) print query ``` Which throws a `KeyError` error: ``` [user@localhost] : ~/Documents/vision/inputs/perma_sniff $ python ~/test.py <type 'dict'> def Traceback (m...
To insert a literal brace, double it up: ``` query = '{{"abc": "{abc}"}}'.format(abc=asset['abc']) ``` (This is documented [here](https://docs.python.org/2/library/string.html#format-string-syntax), but not highlighted particularly obviously).
Deleting hdf5 dataset using h5py
31,861,724
5
2015-08-06T17:04:38Z
33,224,934
8
2015-10-19T22:21:15Z
[ "python", "dataset", "hdf5", "h5py" ]
Is there any way to remove a dataset from an hdf5 file, preferably using h5py? Or alternatively, is it possible to overwrite a dataset while keeping the other datasets intact? To my understanding, h5py can read/write hdf5 files in 5 modes ``` f = h5py.File("filename.hdf5",'mode') ``` where mode can be `r`for read, `...
Yes, this can be done. ``` with h5py.File(input, "a") as f: f.__delitem__(datasetname) ``` You will need to have the file open in a writeable mode, for example append (as above) or write. UPDATE: As noted by @seppo-enarvi the purpose of `__delitem__` function is to implement the `del` operator, so that one can...
How to load IPython shell with PySpark
31,862,293
5
2015-08-06T17:36:53Z
31,863,595
8
2015-08-06T18:48:28Z
[ "python", "apache-spark", "ipython", "pyspark" ]
I want to load IPython shell (not IPython notebook) in which I can use PySpark through command line. Is that possible? I have installed Spark-1.4.1.
If you use Spark < 1.2 you can simply execute `bin/pyspark` with an environmental variable `IPYTHON=1`. ``` IPYTHON=1 /path/to/bin/pyspark ``` or ``` export IPYTHON=1 /path/to/bin/pyspark ``` While above will still work on the Spark 1.2 and above recommended way to set Python environment for these versions is `PYSP...
Python: Split NumPy array based on values in the array
31,863,083
7
2015-08-06T18:20:45Z
31,863,171
7
2015-08-06T18:25:03Z
[ "python", "arrays", "numpy", "split" ]
I have one big array: ``` [(1.0, 3.0, 1, 427338.4297000002, 4848489.4332) (1.0, 3.0, 2, 427344.7937000003, 4848482.0692) (1.0, 3.0, 3, 427346.4297000002, 4848472.7469) ..., (1.0, 1.0, 7084, 427345.2709999997, 4848796.592) (1.0, 1.0, 7085, 427352.9277999997, 4848790.9351) (1.0, 1.0, 7086, 427359.16060000006, 48487...
You can find the indices where the values differ by using [`numpy.where`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html) and [`numpy.diff`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html) on the first column: ``` >>> arr = np.array([(1.0, 3.0, 1, 427338.4297000002, 4848489.4...
Loop through folders in Python and for files containing strings
31,866,706
5
2015-08-06T22:14:54Z
31,866,815
8
2015-08-06T22:27:38Z
[ "python" ]
I am very new to python. I need to iterate through the subdirectories of a given directory and return all files containing a certain string. ``` for root, dirs, files in os.walk(path): for name in files: if name.endswith((".sql")): if 'gen_dts' in open(name).read(): print name `...
You're getting that error because you're trying to open `name`, which is just the file's *name*, not it's full relative path. What you need to do is `open(os.path.join(root, name), 'r')` (I added the mode since it's good practice). ``` for root, dirs, files in os.walk(path): for name in files: if name.ends...
Making an asynchronous task in Flask
31,866,796
5
2015-08-06T22:24:44Z
31,867,108
7
2015-08-06T22:56:04Z
[ "python", "asynchronous", "flask" ]
I am writing an application in `Flask`, which works really well except that `WSGI` is synchronous and blocking. I have one task in particular which calls out to a third party API and that task can take several minutes to complete. I would like to make that call (it's actually a series of calls) and let it run. while co...
I would use [Celery](http://www.celeryproject.org/) to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended). `app.py`: ``` from flask import Flask from celery import Celery broker_url = 'amqp://guest@localhost' # Broker URL fo...
Pandas DataFrame: How to natively get minimum across range of rows and columns
31,866,802
14
2015-08-06T22:25:45Z
32,764,796
9
2015-09-24T15:04:47Z
[ "python", "arrays", "numpy", "pandas", "dataframe" ]
I have a Pandas DataFrame that looks similar to this but with 10,000 rows and 500 columns. [![My Dataframe](http://i.stack.imgur.com/SVMYI.png)](http://i.stack.imgur.com/SVMYI.png) For each row, I would like to find the minimum value between 3 days ago at 15:00 and today at 13:30. Is there some native numpy way to d...
You can first stack the DataFrame to create a series and then index slice it as required and take the min. For example: ``` first, last = ('2011-01-07', datetime.time(15)), ('2011-01-10', datetime.time(13, 30)) df.stack().loc[first: last].min() ``` The result of `df.stack` is a `Series` with a `MultiIndex` where the ...
How can I use zip(), python
31,872,135
3
2015-08-07T07:39:13Z
31,872,162
10
2015-08-07T07:40:42Z
[ "python" ]
For example, I have these variables ``` a = [1,2] b = [3,4] ``` If I use function zip() for it, the result will be: ``` [(1, 3), (2, 4)] ``` But I have this list: ``` a = [[1,2], [3,4]] ``` And, I need to get the same as in the first result: `[(1, 3), (2, 4)]`. But, when I do: ``` zip(a) ``` I get: ``` [([1, 2...
[`zip`](https://docs.python.org/2/library/functions.html#zip) expects multiple iterables, so if you pass a *single* list of lists as parameter, the sublists are just wrapped into tuples with one element each. You have to use `*` to unpack the list when you pass it to `zip`. This way, you effectively pass *two* lists, ...
Python- text based game not calling the correct room
31,879,660
3
2015-08-07T14:03:59Z
31,879,811
8
2015-08-07T14:12:15Z
[ "python", "class", "oop", "namespaces", "python-import" ]
I am writing a text based game and I want to link each room to four other rooms- north, south, east and west. I am starting with just north for now. The user should be able to type 'walk north' and the north room should be called. I have used three files- one where I will write the main story, one to call the appropri...
My guess is that the issue occurs because of how the dictionary `rooms` is defined. When you do - ``` rooms = { 'first_room': first_room.start(), 'north_room': north_room.start(), } rooms[room] ``` The functions get called when you define the dictionary itself, not when you access the values from it (so b...
Unpacking a tuple in for loop
31,881,759
3
2015-08-07T15:44:26Z
31,881,855
12
2015-08-07T15:49:08Z
[ "python" ]
I'm having some trouble with unpacking tuples. Specifically, I don't know why this doesn't work: ``` a = [0,1,2,3] b = [4,5,6,7] p = a,b for i,k in p: print i,k --------------------------------------------------------------------------- ValueError Traceback (most recent call last) ...
If you go step-by-step... First, doing `p = a, b` will get you a tuple consisting of exactly 2 elements -- your lists: ``` >>> a = [0, 1, 2, 3] >>> b = [4, 5, 6, 7] >>> p = a, b >>> print p ([0,1,2,3], [4, 5, 6, 7]) ``` Then, when you do `for i, k in p`, Python will attempt to get the first item inside `p` then unpa...
Why are .pyc files created on import?
31,882,967
12
2015-08-07T16:54:51Z
31,883,142
17
2015-08-07T17:07:53Z
[ "python", "bytecode", "python-internals", "pyc" ]
I've seen several resources describing what `.pyc` files are and when they're created. But now I'm wondering why they're created when `.py` files are imported? Also, why not create a `.pyc` file for the main Python file doing the importing? I'm guessing it has to do with performance optimization and learning this has...
Python source code is compiled to bytecode, and it is the bytecode that is run. A `.pyc` file contains a copy of that bytecode, and by caching that Python doesn't have to re-compile the Python code each time it needs to load the module. You can get an idea of how much time is saved by timing the `compile()` function: ...
Elegant way to match a string to a random color matplotlib
31,883,097
3
2015-08-07T17:04:00Z
31,883,160
9
2015-08-07T17:09:03Z
[ "python", "matplotlib" ]
I want to translate the labels of some data to colors for graphing with matplotlib I have a list of names `["bob", "joe", "andrew", "pete"]` Is there a built in way to map these strings with color values in matplotlib? I thought about randomly creating hex values but I could end up with similar colors or non visible ...
Choose a [color map](http://matplotlib.org/examples/color/colormaps_reference.html), such as `jet`: ``` cmap = plt.get_cmap('jet') ``` The colormap, `cmap`, is a function which can take an array of values from 0 to 1 and map them to RGBA colors. `np.linspace(0, 1, len(names))` produces an array of equally spaced numb...
Why is Flask checking `'\\/' in json.dumps('/')` in its json module?
31,883,132
6
2015-08-07T17:06:58Z
31,883,568
7
2015-08-07T17:33:55Z
[ "python", "flask" ]
[The source for the `flask.json` module contains the following line.](https://github.com/mitsuhiko/flask/blob/0.10.1/flask/json.py#L30) What does `'\\/'` mean, and why is Flask checking this? ``` _slash_escape = '\\/' not in _json.dumps('/') ```
Flask is using this to test if the JSON library it's using escapes slashes when it doesn't have to. If the library does, then `json.dump('/')` will produce `'"\\/"'` (equivalent to the raw string `r'"\/"'`, see [here for an explanation on escape characters](http://stackoverflow.com/questions/24085680/why-do-backslashes...
In Python 3.x, why is there not an itertools shared-object on disk?
31,883,364
4
2015-08-07T17:21:44Z
31,883,380
7
2015-08-07T17:22:32Z
[ "python", "python-3.x", "python-internals" ]
Is the [itertools C module](https://hg.python.org/cpython/file/3.4/Modules/itertoolsmodule.c) included somehow in the main Python binary in 3.x? Assuming that the C module is built and included, which it appears to be: ``` >>> import inspect >>> import itertools >>> >>> inspect.getsourcefile(itertools) Traceback (mos...
There are hints in the makefile that's near the Python wrapper of `inspect.py`: `/usr/local/Cellar/python3/3.4.3_2/Frameworks/Python.framework/Versions/3.4/lib/python3.4/config-3.4m/Makefile` We can see the build rules for the itertools.c source: ``` 1668 Modules/itertoolsmodule.o: $(srcdir)/Modules/itertoolsmodule....
when does `datetime.now(pytz_timezone)` fail?
31,886,808
8
2015-08-07T21:20:17Z
31,931,682
7
2015-08-11T01:16:56Z
[ "python", "datetime", "timezone", "pytz", "delorian" ]
[`delorean` docs](https://github.com/myusuf3/delorean) show this way to *get the current time in a given timezone* [using `datetime`](https://github.com/myusuf3/delorean/blob/2016040e07e63edfe3d565129049b1099d75be5f/README.rst#getting-started): ``` from datetime import datetime from pytz import timezone EST = "US/Eas...
> When does `datetime.now(pytz_timezone)` fail? As far as I can tell, there are no scenarios where it could fail. `datetime.now` invokes the `fromutc` function on the `tzinfo` instance passed in the parameter. All conversions from UTC to local time are unambiguous, so there are no opportunities for failure. Also, the...
How do Twisted python Factory and Protocol interfaces work?
31,888,037
4
2015-08-07T23:32:58Z
31,889,487
9
2015-08-08T03:57:02Z
[ "python", "twisted", "twisted.web", "twisted.internet" ]
I am learning Twisted, and beginner's [tutorial](http://krondo.com/?page_id=1327) often uses Factory and Protocol as examples. It appears that Factory and [Protocol](http://twistedmatrix.com/trac/browser/tags/releases/twisted-12.3.0/twisted/internet/interfaces.py) interfaces do not support sending messages. Is it expec...
See: * <http://twistedmatrix.com/documents/current/api/twisted.internet.protocol.Factory.html> * <http://twistedmatrix.com/documents/current/api/twisted.internet.protocol.html> Factories create Protocol instances. What this means is that a protocol (see [here](http://twistedmatrix.com/documents/current/api/twisted.p...
Why round off of 0.500000 in python differs from 45.500000 using '%.0f'?
31,889,834
4
2015-08-08T05:03:10Z
31,889,938
7
2015-08-08T05:23:22Z
[ "python", "python-2.7", "string-formatting" ]
Recently, I learned art of string formatting in Python 2.7. I decided to play with floating point numbers. Came across an awkward looking solution, as written below. ``` print "%.0f"%45.5000000 #46 print "%.0f"%0.5000000 #0 #Why?? ``` BUT ``` print int(round(45.5000000)) #46 print int(round(0.5000000)) #1 ``` P...
The internal implementation for the `%.0f` string format uses a [round-half-even](https://en.wikipedia.org/wiki/Rounding#Round_half_to_even) rounding mode. In Python 2, the [`round()`](https://docs.python.org/3/library/functions.html#round) function uses [round-away-from-zero](https://en.wikipedia.org/wiki/Rounding#Ro...
Repeatedly remove characters from string
31,893,524
3
2015-08-08T13:17:05Z
31,893,568
8
2015-08-08T13:23:05Z
[ "python", "loops", "for-loop", "repeat" ]
``` >>> split=['((((a','b','+b'] >>> [ (w[1:] if w.startswith((' ','!', '@', '#', '$', '%', '^', '&', '*', "(", ")", '-', '_', '+', '=', '~', ':', "'", ';', ',', '.', '?', '|', '\\', '/', '<', '>', '{', '}', '[', ']', '"')) else w) for w in split] ['(((a','b','b'] ``` I wanted `['a', 'b', 'b']` instead. I want to cre...
There is no need to repeat your expression, you are not using the right tools, is all. You are looking for the [`str.lstrip()` method](https://docs.python.org/2/library/stdtypes.html#str.lstrip): ``` [w.lstrip(' !@#$%^&*()-_+=~:\';,.?|\\/<>{}[]"') for w in split] ``` The method treats the string argument as a *set* o...
Smarter than If Else
31,896,495
3
2015-08-08T17:09:35Z
31,896,539
9
2015-08-08T17:14:53Z
[ "python", "if-statement" ]
I'm trying to do a switch (of sorts) of commands. ``` if 'Who' in line.split()[:3]: Who(line) elif 'Where' in line.split()[:3]: Where(line) elif 'What' in line.split()[:3]: What(line) elif 'When' in line.split()[:3]: When(line) elif 'How' in line.split()[:3]: How(line) elif "Make" in line.split(...
Try creating a dictionary with keys being the command names and the values the actual command functions. Example: ``` def who(): ... def where(): ... def default_command(): ... commands = { 'who': who, 'where': where, ... } # usage cmd_name = line.split()[:3][0] # or use all commands in th...
Why does `a<b<c` work in Python?
31,896,870
2
2015-08-08T17:51:32Z
31,896,904
9
2015-08-08T17:55:52Z
[ "python", "boolean-expression" ]
The title says it all. For example `1<2<3` returns `True` and `2<3<1` returns `False`. It's great that it works, but I can't explain *why* it works... I can't find anything about it in the documentation. It's always: `expression boolean_operator expression`, not two boolean operators). Also: `a<b` returns a boolean, a...
This is known as operator chaining. Documentation is available at: <https://docs.python.org/2/reference/expressions.html#not-in> > Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is...
How do you assert two functions throw the same error without knowing the error?
31,897,053
3
2015-08-08T18:13:06Z
31,897,099
7
2015-08-08T18:18:51Z
[ "python", "unit-testing" ]
I have an outer function that calls an inner function by passing the arguments along. Is it possible to test that both functions throw the same exception/error without knowing the exact error type? I'm looking for something like: ``` def test_invalidInput_throwsSameError(self): arg = 'invalidarg' self.assertR...
Assuming you're using `unittest` (and python2.7 or newer) and that you're not doing something pathological like raising old-style class instances as errors, you can get the exception from the error context if you use [`assertRaises`](https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertRaises) as a c...
How to write the resulting RDD to a csv file in Spark python
31,898,964
9
2015-08-08T21:53:51Z
31,899,173
14
2015-08-08T22:24:12Z
[ "python", "csv", "apache-spark", "pyspark", "file-writing" ]
I have a resulting RDD `labelsAndPredictions = testData.map(lambda lp: lp.label).zip(predictions)`. This has output in this format: ``` [(0.0, 0.08482142857142858), (0.0, 0.11442786069651742),.....] ``` What I want is to create a CSV file with one column for `labels` (the first part of the tuple in above output) and ...
Just `map` the lines of the RDD (`labelsAndPredictions`) into strings (the lines of the CSV) then use `rdd.saveAsTextFile()`. ``` def toCSVLine(data): return ','.join(str(d) for d in data) lines = labelsAndPredictions.map(toCSVLine) lines.saveAsTextFile('hdfs://my-node:9000/tmp/labels-and-predictions.csv') ```
"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)
31,900,008
80
2015-08-09T01:00:37Z
31,900,088
15
2015-08-09T01:21:20Z
[ "python", "osx", "python-2.7", "scrapy" ]
I'm trying to install Scrapy Python framework in OSX 10.11 (El Capitan) via pip. The installation script downloads the required modules and at some point returns the following error: ``` OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extra...
**Warnings** I would suggest **very strongly** against modifying the system Python on Mac; there are numerous issues that can occur. Your particular error shows that the installer has issues resolving the dependencies for Scrapy without impacting the current Python installation. The system uses Python for a number of...
"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)
31,900,008
80
2015-08-09T01:00:37Z
32,723,204
11
2015-09-22T17:29:25Z
[ "python", "osx", "python-2.7", "scrapy" ]
I'm trying to install Scrapy Python framework in OSX 10.11 (El Capitan) via pip. The installation script downloads the required modules and at some point returns the following error: ``` OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extra...
You should disable "System Integrity Protection" which is a new feature in El Capitan. First, you should run the command for rootless config on your terminal ``` # nvram boot-args="rootless=0" # reboot ``` Then, you should run the command below on recovery partition's terminal (Recovery OS) ``` # csrutil disable # ...
"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)
31,900,008
80
2015-08-09T01:00:37Z
33,136,494
154
2015-10-14T22:12:25Z
[ "python", "osx", "python-2.7", "scrapy" ]
I'm trying to install Scrapy Python framework in OSX 10.11 (El Capitan) via pip. The installation script downloads the required modules and at some point returns the following error: ``` OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extra...
``` pip install --ignore-installed six ``` Would do the trick. Source: [github.com/pypa/pip/issues/3165](https://github.com/pypa/pip/issues/3165)
"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)
31,900,008
80
2015-08-09T01:00:37Z
33,245,444
65
2015-10-20T19:40:42Z
[ "python", "osx", "python-2.7", "scrapy" ]
I'm trying to install Scrapy Python framework in OSX 10.11 (El Capitan) via pip. The installation script downloads the required modules and at some point returns the following error: ``` OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extra...
I also think it's absolutely not necessary to start hacking OS X. I was able to solve it doing a ``` brew install python ``` It seems that using the python / pip that comes with new El Capitan has some issues.
"OSError: [Errno 1] Operation not permitted" when installing Scrapy in OSX 10.11 (El Capitan) (System Integrity Protection)
31,900,008
80
2015-08-09T01:00:37Z
36,921,836
7
2016-04-28T17:40:18Z
[ "python", "osx", "python-2.7", "scrapy" ]
I'm trying to install Scrapy Python framework in OSX 10.11 (El Capitan) via pip. The installation script downloads the required modules and at some point returns the following error: ``` OSError: [Errno 1] Operation not permitted: '/tmp/pip-nIfswi-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extra...
I tried to install AWS via pip in El Capitan but this error appear > OSError: [Errno 1] Operation not permitted: > '/var/folders/wm/jhnj0g\_s16gb36y8kwvrgm7h0000gp/T/pip-wTnb\_D-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info' I found the answer [here](http...
Why is 'a' in ('abc') True while 'a' in ['abc'] is False?
31,900,892
71
2015-08-09T04:24:52Z
31,900,920
135
2015-08-09T04:28:59Z
[ "python" ]
When using the interpreter, the expression `'a' in ('abc')` returns True, while `'a' in ['abc']` returns False. Can somebody explain this behaviour?
`('abc')` is the same as `'abc'`. `'abc'` contains the substring `'a'`, hence `'a' in 'abc' == True`. If you want the tuple instead, you need to write `('abc', )`. `['abc']` is a list (containing a single element, the string `'abc'`). `'a'` is not a member of this list, so `'a' in ['abc'] == False`
Why is 'a' in ('abc') True while 'a' in ['abc'] is False?
31,900,892
71
2015-08-09T04:24:52Z
31,900,922
50
2015-08-09T04:29:15Z
[ "python" ]
When using the interpreter, the expression `'a' in ('abc')` returns True, while `'a' in ['abc']` returns False. Can somebody explain this behaviour?
`('abc')` is not a tuple. I think you confused that with tuple `('abc',)`. Actually, `('abc')` is same as `'abc'`, an `array of characters` where `a` as character is in it, hence, the first lookup returns `True`: ``` >>> 'a' in 'abc' True ``` On the other hand, `['abc']` is a list of string or a list of list of char...
How to recalculate a variable value every time it is used?
31,905,803
3
2015-08-09T15:26:00Z
31,905,856
9
2015-08-09T15:31:19Z
[ "python" ]
I want a variable to be calculated each time it is used. For example, `var1 = var2 + var3` each time `var1` is printed. How can I create a "dynamic" variable like this? ``` var2 = 4 var3 = 2 print(var1) # 6 var3 = 8 print(var1) # 12 ```
You'll need a property on a class instance. The property will execute some code each time it's accessed. For example, here's a property that increments its value each time it is accessed. Define `__str__` to access the property, so you can `print(var1)` and get its incrementing value. ``` class MyVar(object): def ...
Pylint to show only warnings and errors
31,907,762
3
2015-08-09T18:57:13Z
31,908,039
7
2015-08-09T19:28:58Z
[ "python", "pylint" ]
I would like to use pylint to check my code but I am only interested in error and warning levels. Is there a way to do that in command line or in pylintrc? I am not interested in filtering given issues (like listing all messages in MESSAGE CONTROL), I just want pylint to ignore **all** convention and refactor messages...
Use the `-d` / `--disable` option to turn off the "C" and "R" message classes (convention and refactor): ``` -d <msg ids>, --disable=<msg ids> Disable the message, report, category or checker with the given id(s). You can either give multiple identifiers sepa...
how to match all 3 digit except a particular number
31,907,906
4
2015-08-09T19:11:56Z
31,908,004
10
2015-08-09T19:24:13Z
[ "python", "regex", "regex-negation" ]
How do i match all 3 digit integers except one particular integer, say 914. Getting all 3 digit integers is simple enough `[0=9][0-9][0-9]` Trying something like `[0-8][0,2-9][0-3,5-9]` removes more integers from the set apart from just 914. How do we solve this problem?
You can use a negative look-ahead to add an exception: ``` \b(?!914)\d{3}\b ``` The word boundary `\b` ensures we match a number as a whole word. See [regex demo](https://regex101.com/r/aH7qQ6/1) and [IDEONE demo](https://ideone.com/0yhWuk): ``` import re p = re.compile(r'\b(?!914)\d{3}\b') test_str = "123\n235\n45...