title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How to assign member variables temporarily?
38,531,851
<p>I often find that I need to assign some member variables temporarily, <em>e.g.</em></p> <pre><code>old_x = c.x old_y = c.y # keep c.z unchanged c.x = new_x c.y = new_y do_something(c) c.x = old_x c.y = old_y </code></pre> <p>but I wish I could simply write</p> <pre><code>with c.x = new_x; c.y = new_y: do_s...
12
2016-07-22T17:02:28Z
38,532,027
<p><code>mock</code> provides this functionality, specifically look at the context-manager usage of <a href="https://docs.python.org/3/library/unittest.mock.html#patch-object" rel="nofollow"><code>patch.object</code></a>. It's in core libraries in python3, and <a href="https://pypi.python.org/pypi/mock" rel="nofollow"...
3
2016-07-22T17:14:08Z
[ "python", "python-2.7", "python-decorators", "python-descriptors" ]
How to assign member variables temporarily?
38,531,851
<p>I often find that I need to assign some member variables temporarily, <em>e.g.</em></p> <pre><code>old_x = c.x old_y = c.y # keep c.z unchanged c.x = new_x c.y = new_y do_something(c) c.x = old_x c.y = old_y </code></pre> <p>but I wish I could simply write</p> <pre><code>with c.x = new_x; c.y = new_y: do_s...
12
2016-07-22T17:02:28Z
38,532,086
<p><a href="https://docs.python.org/2/reference/datamodel.html#context-managers">Context managers</a> may be used for it easily.</p> <p>Quoting official docs:</p> <blockquote> <p>Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing o...
20
2016-07-22T17:19:17Z
[ "python", "python-2.7", "python-decorators", "python-descriptors" ]
How to assign member variables temporarily?
38,531,851
<p>I often find that I need to assign some member variables temporarily, <em>e.g.</em></p> <pre><code>old_x = c.x old_y = c.y # keep c.z unchanged c.x = new_x c.y = new_y do_something(c) c.x = old_x c.y = old_y </code></pre> <p>but I wish I could simply write</p> <pre><code>with c.x = new_x; c.y = new_y: do_s...
12
2016-07-22T17:02:28Z
38,532,088
<p>I think a <a href="https://docs.python.org/3/library/contextlib.html"><code>contextmanager</code></a> should do what you want:</p> <pre><code>from contextlib import contextmanager @contextmanager def current_instance(c, temp_x, temp_y): old_x, old_y = c.x, c.y c.x, c.y = temp_x, temp_y yield c c.x,...
5
2016-07-22T17:19:23Z
[ "python", "python-2.7", "python-decorators", "python-descriptors" ]
How to assign member variables temporarily?
38,531,851
<p>I often find that I need to assign some member variables temporarily, <em>e.g.</em></p> <pre><code>old_x = c.x old_y = c.y # keep c.z unchanged c.x = new_x c.y = new_y do_something(c) c.x = old_x c.y = old_y </code></pre> <p>but I wish I could simply write</p> <pre><code>with c.x = new_x; c.y = new_y: do_s...
12
2016-07-22T17:02:28Z
38,532,167
<p>You can also do this natively using <code>__enter__</code> and <code>__exit__</code>. Simplistic example:</p> <pre><code>class SomeObject(object): def __init__(self): self.a = 1 self.b = 2 self.c = 3 class Temporary(object): def __init__(self, target, **kv): self.target = ta...
3
2016-07-22T17:25:26Z
[ "python", "python-2.7", "python-decorators", "python-descriptors" ]
How to assign member variables temporarily?
38,531,851
<p>I often find that I need to assign some member variables temporarily, <em>e.g.</em></p> <pre><code>old_x = c.x old_y = c.y # keep c.z unchanged c.x = new_x c.y = new_y do_something(c) c.x = old_x c.y = old_y </code></pre> <p>but I wish I could simply write</p> <pre><code>with c.x = new_x; c.y = new_y: do_s...
12
2016-07-22T17:02:28Z
38,532,169
<p>Goofy solution</p> <pre><code>&gt;&gt;&gt; class Foo(object): def __init__(self): self._x = [] self._y = [] @property def x(self): return self._x[-1] or None @x.setter def x(self, val): self._x.append(val) def reset...
2
2016-07-22T17:25:31Z
[ "python", "python-2.7", "python-decorators", "python-descriptors" ]
Django: model OneToOneField with User can't add default value
38,531,939
<p>I have an model and I want to add an OneToOneField to hold the creator of an object: models.py</p> <pre><code>creator = models.OneToOneField(User, blank=True, default=User.objects.filter( username="antoni4040")) </code></pre> <p>I already have a dat...
0
2016-07-22T17:08:05Z
38,532,035
<p>You are using the queryset <code>User.objects.filter(username="antoni4040")</code>. To get a model instance, you would use <code>User.objects.get(username="antoni4040")</code>.</p> <p>However, you shouldn't use a a model instance for as the default in the model field. There's no error handling if the user does not ...
1
2016-07-22T17:14:47Z
[ "python", "django", "user", "database-migration", "one-to-one" ]
how to set the number of features to use in random selection sklearn
38,531,941
<p>I am using sklearn RandomForest Classifier/Bag classifier for learning and I am not getting the expected results when compared to Java/Weka Machine Learning library. In Weka, I am learning the model with - Random forest of 10 trees, each constructed while considering 6 random features. (setNumFeatures need to be se...
0
2016-07-22T17:08:22Z
38,534,795
<p>I think the issue is that the individual trees get confused since they only use 6 features, but you give them 31. You can try to get the prediction to work by setting <code>check_input = False</code>:</p> <pre><code> list(classifier_list[i].predict(feature_data_arr, check_input = False)) </code></pre>
0
2016-07-22T20:29:17Z
[ "python", "scikit-learn", "random-forest", "decision-tree" ]
Flink batch data processing
38,531,965
<p>I'm evaluating <a href="http://flink.apache.org/" rel="nofollow">Flink</a> for some processing batches of data. As a simple example say I have 2000 points which I would like to pass through an FIR filter using functionality provided by <a href="http://www.scipy.org/" rel="nofollow">scipy</a>. The scipy filter is a...
0
2016-07-22T17:10:27Z
38,560,225
<p>This should certainly be possible. Flink already has a <a href="https://ci.apache.org/projects/flink/flink-docs-release-1.0/apis/batch/python.html" rel="nofollow">Python API (beta)</a> you might want to use.</p> <p>About your second question: Flink can apply a function point by point and can do other stuff, too. It...
0
2016-07-25T05:22:58Z
[ "python", "apache-flink" ]
Django Static Files Not Being Found (debug off)
38,531,966
<p>I cannot get Django to correctly reference my static files when debug is off. I know there are many other posts on this site about this, but none of them have fixed my issue. </p> <p>My directory tree is like this:</p> <pre><code>└── project └── app1 └── app1 ├── manage.py â...
1
2016-07-22T17:10:29Z
38,534,301
<p>You should configure your nginx: edit nginx.conf the following way: add this:</p> <pre><code>location ~* ^(/static/|/media/).+.(jpg|jpeg|gif|png|zip|eot|woff|woff2|svg|ttf|tgz|gz|rar|bz2|doc|xls|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf)$ { root /path/to/parent/folder/of/static/folder; } </code></pre> <p>to the <co...
0
2016-07-22T19:51:11Z
[ "python", "django", "nginx" ]
How to enable dependencies with python?
38,531,982
<p>I've written a python program to define and load a sheet in smartsheet from an Excel spreadsheet, and have provided a start date, end date, predecessors, duration and %complete columns in the definition (it works well). But, now I want enable dependencies for the sheet using API 2.0 and tell smartsheet to use my pr...
0
2016-07-22T17:11:33Z
38,532,245
<p>It is not currently possible to create a dependency-enabled project sheet by using the Smartsheet API. The information in the <a href="http://smartsheet-platform.github.io/api-docs/#column-types" rel="nofollow">Column Types</a> section of the API documentation supports this assertion -- i.e., the <em>Duration</em>,...
0
2016-07-22T17:30:06Z
[ "python", "dependencies", "smartsheet-api" ]
Memory efficient way to add columns to .csv files
38,532,023
<p>Ok, I couldn't really find an answer to this anywhere else, so I figured I'd ask.</p> <p>I'm working with some .csv files that have about 74 million lines right now and I'm trying to add columns into one file from another file.</p> <p>ex.</p> <pre><code>Week,Sales Depot,Sales Channel,Route,Client,Product,Units So...
2
2016-07-22T17:13:58Z
38,532,276
<p>Something like this might work for you:</p> <h3>Using <code>csv.DictReader()</code></h3> <pre><code>import csv from itertools import izip with open('file1.csv') as file1: with open('file2.csv') as file2: with open('result.csv', 'w') as result: file1 = csv.DictReader(file1) file...
4
2016-07-22T17:31:25Z
[ "python", "csv" ]
Numba not speeding up function
38,532,055
<p>I have some code I'm trying to speed up with numba. I've done some reading on the topic, but I haven't been able to figure it out 100%.</p> <p>Here is the code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np import scipy.stats as st import seaborn as sns from numba import jit...
0
2016-07-22T17:16:18Z
38,535,181
<p>As said, there is likely some code that is falling back to object mode. I just wanted to add that you can use njit instead of jit to disable object mode. That will help diagnose what code is the culprit.</p>
0
2016-07-22T21:02:56Z
[ "python", "performance", "numpy", "numba" ]
Numba not speeding up function
38,532,055
<p>I have some code I'm trying to speed up with numba. I've done some reading on the topic, but I haven't been able to figure it out 100%.</p> <p>Here is the code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import numpy as np import scipy.stats as st import seaborn as sns from numba import jit...
0
2016-07-22T17:16:18Z
38,541,770
<p>I was able to make a few changes to your code to make it so the jit version could compile completely in <code>nopython</code> mode. On my laptop, this results in:</p> <pre><code>%timeit solver_jit(200, 25) 1 loop, best of 3: 50.9 ms per loop %timeit solver_norm(200, 25) 1 loop, best of 3: 192 ms per loop </code></...
1
2016-07-23T12:26:28Z
[ "python", "performance", "numpy", "numba" ]
Python: Wrong output and ValueError: Prime Factors Creator
38,532,164
<p>I've created a program that successfully detects whether a number is prime, or not, it also will return a list of the factors of the number if it isn't, but that part is not successful. </p> <p>Here is my code:</p> <pre><code>def prime_num(): num = int(input("Give me a number...: ")) prime = True if ...
1
2016-07-22T17:25:02Z
38,532,373
<p>This should make it clear what your problem is:</p> <pre><code>factors = [1,5,25] for x in factors: for y in range(1,x): print x,y 5 1 5 2 5 3 5 4 25 1 25 2 25 3 25 4 25 5 25 6 25 7 25 8 25 9 25 10 25 11 25 12 25 13 25 14 25 15 25 16 25 17 25 18 25 19 25 20 25 21 25 22 25 23 25 24 </code></pre> <p>Yo...
1
2016-07-22T17:38:15Z
[ "python", "loops", "error-handling", "prime-factoring" ]
Partitioning a (string or integer) into n-elements of min (length or value) of 2
38,532,199
<p>I have a list of ~120'000 strings of various lengths (from 4 to 27) and I want to check if this strings are made of sub-strings that exist in a dictionary, and this sub-strings can be of various lengths and min 2 chars long.</p> <p>For example a string 9 chars long would be divided into min 2 sub-strings. And of co...
1
2016-07-22T17:27:20Z
38,532,266
<p>I'm not sure this helps, but you could try implementing a modified <a href="https://en.wikipedia.org/wiki/Radix_tree" rel="nofollow">radix tree</a>.</p>
1
2016-07-22T17:31:05Z
[ "python", "string", "slice" ]
Speeding up cross-reference filtering in Pandas DB
38,532,244
<p>I am working with a very large donation database of data with relevant columns for donation ID, conduit ID, amount, for example:</p> <pre><code> TRANSACTION_ID BACK_REFERENCE_TRAN_ID_NUMBER CONTRIBUTION_AMOUNT 0 VR0P4H2SEZ1 0 100 1 VR0P4H3X770 ...
4
2016-07-22T17:30:05Z
38,532,344
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>Series.isin</code></a>. It is a vectorized operation that checks if each element of the Series is in a supplied iterable.</p> <pre><code>df['CONDUIT_FOR_OTHER_DONATION'] = df['TRANSACTION_ID'].is...
5
2016-07-22T17:35:49Z
[ "python", "performance", "pandas" ]
Speeding up cross-reference filtering in Pandas DB
38,532,244
<p>I am working with a very large donation database of data with relevant columns for donation ID, conduit ID, amount, for example:</p> <pre><code> TRANSACTION_ID BACK_REFERENCE_TRAN_ID_NUMBER CONTRIBUTION_AMOUNT 0 VR0P4H2SEZ1 0 100 1 VR0P4H3X770 ...
4
2016-07-22T17:30:05Z
38,532,485
<p>Here's a NumPy based approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow"><code>np.in1d</code></a> -</p> <pre><code>vals = np.in1d(df.TRANSACTION_ID,df.BACK_REFERENCE_TRAN_ID_NUMBER).astype(int) df['CONDUIT_FOR_OTHER_DONATION'] = vals </code></pre>
2
2016-07-22T17:44:46Z
[ "python", "performance", "pandas" ]
SPI_SETDESKWALLPAPER not working with tempfile.NamedTemporaryFile()
38,532,270
<p><strong>Code:</strong></p> <pre><code>import urllib.request import tempfile import shutil import ctypes SPI_SETDESKWALLPAPER = 20 with urllib.request.urlopen('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png') as response, tempfile.NamedTemporaryFile() as f: shutil.copyfileobj...
0
2016-07-22T17:31:13Z
38,533,681
<p>You need to read the next couple sentences in the documentation, which read something like this:</p> <blockquote> <p>Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. Other platforms do not support this; your code should not rely on ...
0
2016-07-22T19:05:32Z
[ "python", "python-3.5" ]
SPI_SETDESKWALLPAPER not working with tempfile.NamedTemporaryFile()
38,532,270
<p><strong>Code:</strong></p> <pre><code>import urllib.request import tempfile import shutil import ctypes SPI_SETDESKWALLPAPER = 20 with urllib.request.urlopen('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png') as response, tempfile.NamedTemporaryFile() as f: shutil.copyfileobj...
0
2016-07-22T17:31:13Z
40,027,054
<p>I figured out the problem:</p> <p>To begin with, the value of the <code>fWinIni</code> parameter needs to be changed:</p> <pre><code>SPIF_UPDATEINIFILE = 0x01 SPIF_SENDCHANGE = 0x02 ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, f.name, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE) </code></pre> <p>...
0
2016-10-13T17:08:37Z
[ "python", "python-3.5" ]
possible combinations of strings in an array in python?
38,532,277
<p><code>arr=['one','two','three']</code> <br><br>Result must be like this: <code>onetwo,twothree,onethree</code></p> <blockquote> <p>itertools.permutations will not work in this situation.</p> </blockquote> <p>we can do this by simply adding for loops and appending them ,that works for small arrays but takes time ...
2
2016-07-22T17:31:27Z
38,532,356
<p>Perhaps what you wanted was the <code>itertools.combinations</code>?</p> <pre><code>&gt;&gt;&gt; [''.join(comb) for comb in (itertools.combinations(arr, 2))] ['onetwo', 'onethree', 'twothree'] </code></pre>
4
2016-07-22T17:36:31Z
[ "python", "arrays", "python-3.x", "python-3.4", "itertools" ]
possible combinations of strings in an array in python?
38,532,277
<p><code>arr=['one','two','three']</code> <br><br>Result must be like this: <code>onetwo,twothree,onethree</code></p> <blockquote> <p>itertools.permutations will not work in this situation.</p> </blockquote> <p>we can do this by simply adding for loops and appending them ,that works for small arrays but takes time ...
2
2016-07-22T17:31:27Z
38,532,961
<blockquote> <p>for two lists</p> <ul> <li>create a list with equal length compare with other list</li> <li>zip new list with other list</li> <li>put all sublist together </li> <li>join list</li> </ul> </blockquote> <pre><code>from itertools import permutations arr1=['name1','name2'] arr2=['name3','n...
1
2016-07-22T18:16:31Z
[ "python", "arrays", "python-3.x", "python-3.4", "itertools" ]
Import test failed when using Conda Build
38,532,279
<p>I am trying to create my own Conda package, but I'm having a problem when I go to "Build" the package, specifically within the "Testing" phase. I have been following the tutorial linked below, and it's been very helpful in explaining what each part is doing. </p> <p><a href="http://kylepurdon.com/blog/packaging-p...
0
2016-07-22T17:31:34Z
38,534,741
<p>The correct import test would be <code>src.twitter_tools</code>, since you've named your package directory <code>src</code>. You can also see the Python packaging documentation to help in naming your package, etc.: <a href="https://python-packaging.readthedocs.io/en/latest/index.html" rel="nofollow">https://python-p...
1
2016-07-22T20:24:58Z
[ "python", "conda", "miniconda" ]
Create a unit test using Django's test client post method passing parameters and requesting JSON from rest_framework
38,532,288
<p>I want to instantiate a <code>django.test.client.Client()</code> or <code>rest_framework.test.APIClient()</code>, POST a simple set of parameters, and request a JSON format response from a djangorestframework class-based view.</p> <p>The documentation <a href="http://www.django-rest-framework.org/api-guide/testing/...
0
2016-07-22T17:32:04Z
38,591,996
<p>Turns out the AJAX data is <em>supposed</em> to appear in <code>request.data</code>, and I was using the wrong approach to submit the data via AJAX from the browser. Django rest_framework (DRF) assumes that data from the request will be passed in the same format as data returned to the client - in this case JSON bot...
0
2016-07-26T14:00:49Z
[ "python", "json", "django", "unit-testing", "django-rest-framework" ]
How can you plot data from a .txt file using matplotlib?
38,532,298
<p>Hi I'm trying to plot of .txt file using matplotlib but I keep getting this error, I'm not that familiar with python, as I started learning a couple of weeks ago, Apologises! The text file is formatted like (it is 2048 rows long) </p> <pre><code>6876.593750 1 6876.302246 1 6876.003418 0 </code></pre> <p>I would...
0
2016-07-22T17:33:32Z
38,532,503
<p>A quick solution woul dbe to remove the 4th element in data like this:</p> <pre><code>data.pop() </code></pre> <p>Place it after </p> <pre><code>data = data.split('\n') </code></pre>
0
2016-07-22T17:46:16Z
[ "python", "matplotlib" ]
How can you plot data from a .txt file using matplotlib?
38,532,298
<p>Hi I'm trying to plot of .txt file using matplotlib but I keep getting this error, I'm not that familiar with python, as I started learning a couple of weeks ago, Apologises! The text file is formatted like (it is 2048 rows long) </p> <pre><code>6876.593750 1 6876.302246 1 6876.003418 0 </code></pre> <p>I would...
0
2016-07-22T17:33:32Z
38,532,516
<p>You're just reading in the data wrong. Here's a cleaner way:</p> <pre><code>with open('Alpha_Particle.txt') as f: lines = f.readlines() x = [line.split()[0] for line in lines] y = [line.split()[1] for line in lines] x ['6876.593750', '6876.302246', '6876.003418'] y ['1', '1', '0'] </code></pre>
1
2016-07-22T17:46:45Z
[ "python", "matplotlib" ]
mpi4py passing dict object
38,532,336
<pre><code>#mpiexec -n 3 python pass_dict.py from mpi4py import MPI import psycopg2 comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() tax_dict={} if rank == 0: tax_files=['2008','2009','2011','2012','2013','2014','2015'] file_dir='/zhome/nah316/taxonomy/' for tax_file in tax_files: ...
0
2016-07-22T17:35:28Z
38,573,438
<p>I don't know much about python or mpi4py in detail, but I found some code at <a href="https://pythonhosted.org/mpi4py/usrman/tutorial.html" rel="nofollow">https://pythonhosted.org/mpi4py/usrman/tutorial.html</a> that would imply that you need to assign the result of comm.bcast to the dictionaries on the other ranks....
0
2016-07-25T16:51:54Z
[ "python", "parallel-processing", "mpi4py" ]
How to extract a value from a Python dictionary using Javascript?
38,532,380
<p>I have a Python dictionary that looks like this...</p> <pre><code>{u'reason': u'invalidQuery', u'message': u'Encountered " &lt;ID&gt; "asd "" at line 1, column 1.\nWas expecting:\n &lt;EOF&gt; \n ', u'location': u'query'} </code></pre> <p>How do I access the <code>u'message'</code> value using Javascript? It...
1
2016-07-22T17:38:34Z
38,532,410
<p>This is not a valid JavaScript object.</p>
2
2016-07-22T17:40:12Z
[ "javascript", "python", "dictionary", "unicode", "key" ]
How to extract a value from a Python dictionary using Javascript?
38,532,380
<p>I have a Python dictionary that looks like this...</p> <pre><code>{u'reason': u'invalidQuery', u'message': u'Encountered " &lt;ID&gt; "asd "" at line 1, column 1.\nWas expecting:\n &lt;EOF&gt; \n ', u'location': u'query'} </code></pre> <p>How do I access the <code>u'message'</code> value using Javascript? It...
1
2016-07-22T17:38:34Z
38,532,571
<p>In views.py</p> <pre><code>import json json_object = json.dumps(your_object) </code></pre> <p>In .html / .js</p> <pre><code>var json_object = {{json_object|safe}}; </code></pre> <p>The .py side converts it to a valid JSON object. The tag in html escapes invalid json characters like "&amp;"</p> <p>In case you a...
2
2016-07-22T17:50:41Z
[ "javascript", "python", "dictionary", "unicode", "key" ]
Running both Python 2.7 and 3.5 on PC
38,532,440
<p>I have both versions of Python installed on my PC running Windows 10 and I can switch between them manually as needed, but I was wondering if there is a way to edit their path environment variables so that I can launch both of them from the CMD easily.</p> <p>For example, instead of typing "python" to launch whatev...
3
2016-07-22T17:42:14Z
38,532,808
<p>This has more to do with Windows and less to do with Python IMO. You might want to take a look at <a href="http://stackoverflow.com/questions/20530996/aliases-in-windows-command-prompt">Aliases in windows command prompt</a> You should be able to use </p> <pre><code>DOSKEY python3=C:\path\to\python3.exe $* DOSKEY p...
2
2016-07-22T18:06:32Z
[ "python", "windows", "python-2.7", "python-3.x" ]
Running both Python 2.7 and 3.5 on PC
38,532,440
<p>I have both versions of Python installed on my PC running Windows 10 and I can switch between them manually as needed, but I was wondering if there is a way to edit their path environment variables so that I can launch both of them from the CMD easily.</p> <p>For example, instead of typing "python" to launch whatev...
3
2016-07-22T17:42:14Z
38,533,464
<p>You can try <a href="https://virtualenv.pypa.io/en/stable/userguide/" rel="nofollow"><code>virtualenv</code></a> or <a href="https://www.cygwin.com/" rel="nofollow"><code>cygwin</code></a>. Using the later you can have both versions python installed and invoked as you from the same terminal.</p> <p>Another possible...
0
2016-07-22T18:50:03Z
[ "python", "windows", "python-2.7", "python-3.x" ]
Running both Python 2.7 and 3.5 on PC
38,532,440
<p>I have both versions of Python installed on my PC running Windows 10 and I can switch between them manually as needed, but I was wondering if there is a way to edit their path environment variables so that I can launch both of them from the CMD easily.</p> <p>For example, instead of typing "python" to launch whatev...
3
2016-07-22T17:42:14Z
38,534,073
<p>I have copied two batch files from WinPython distribution, </p> <p><em>cmd.bat</em></p> <pre><code>@echo off call %~dp0env.bat cmd.exe /k </code></pre> <p>and <em>env.bat</em> (edited)</p> <pre><code>@echo off set WINPYDIR=C:\devel\Python34 set PATH=%WINPYDIR%\;%WINPYDIR%\DLLs;%WINPYDIR%\Scripts;%PATH%; </code><...
0
2016-07-22T19:34:15Z
[ "python", "windows", "python-2.7", "python-3.x" ]
Difference between __new__ and __init__ order in Python2/3
38,532,445
<p>In Python 3, if any value that is not an instance of <code>cls</code> is returned, the <code>__init__</code> method is never called. So I can, for example, do this:</p> <pre><code>class Foo: @staticmethod def bar(n): return n * 5 def __new__(cls, n): return Foo.bar(n) print(Foo(3)) # ...
4
2016-07-22T17:42:25Z
38,532,508
<p>In Python 2, you need to use new-style classes to make classes work properly. That means you need to define your class as <code>class Foo(object)</code>. Then your first example will work in both Python 2 and Python 3.</p>
6
2016-07-22T17:46:27Z
[ "python", "python-2.7", "python-3.x", "metaclass" ]
How can I use a Python defaultdict to divide one value by another?
38,532,479
<p>I have a defaultdict built with keys and values, but I need to be able to divide the first value by the second value if there are two values in the pair.</p> <pre><code>defaultdict(&lt;type 'list'&gt;, {3: [7567, 6525], 4: [0], 65542: [609, 5245], 13: [73585, 84764], 14: [159, 19385], 65552: [1834], 22: [47333...
0
2016-07-22T17:44:10Z
38,532,576
<p>You could do something like this:</p> <pre><code>for k in mydict.keys(): if len(mydict[k]) != 2: mydict.pop(k) else: v1, v2 = mydict[k] mydict[k] = v1 / v2 </code></pre>
0
2016-07-22T17:50:58Z
[ "python" ]
How can I use a Python defaultdict to divide one value by another?
38,532,479
<p>I have a defaultdict built with keys and values, but I need to be able to divide the first value by the second value if there are two values in the pair.</p> <pre><code>defaultdict(&lt;type 'list'&gt;, {3: [7567, 6525], 4: [0], 65542: [609, 5245], 13: [73585, 84764], 14: [159, 19385], 65552: [1834], 22: [47333...
0
2016-07-22T17:44:10Z
38,532,645
<p>Use a dictionary comprehension and the ternary operator. </p> <p>Python 3</p> <pre><code>from operator import truediv {key: (truediv(*val) if len(val) == 2 else val[0]) for key, val in dic.items()} </code></pre> <p>Python 2</p> <pre><code>from operator import truediv {key: (truediv(*val) if len(val) == 2 else ...
2
2016-07-22T17:55:36Z
[ "python" ]
How can I use a Python defaultdict to divide one value by another?
38,532,479
<p>I have a defaultdict built with keys and values, but I need to be able to divide the first value by the second value if there are two values in the pair.</p> <pre><code>defaultdict(&lt;type 'list'&gt;, {3: [7567, 6525], 4: [0], 65542: [609, 5245], 13: [73585, 84764], 14: [159, 19385], 65552: [1834], 22: [47333...
0
2016-07-22T17:44:10Z
38,532,667
<p>I guess since everyone else is interpreting the question this way I'll post my version as an answer:</p> <pre><code>{k: reduce(operator.div, map(float, v)) for k, v in original.items()} </code></pre> <p>Alternatively:</p> <pre><code>{k: reduce(operator.truediv, v) for k, v in original.items()} </code></pre> <p>W...
1
2016-07-22T17:56:55Z
[ "python" ]
Google's Python Course: iterating through list of regular expressions and printing each output on a new line
38,532,502
<p>I am trying to pass some regular expressions examples that are provided by Google's Python Course to a list and print each output on a new line.</p> <pre><code>import re str='an example word:cat!!' match=re.search(r'word:\w\w\w',str) if match: print('I found a cat :)',match.group()) ## 'found word:cat' else: pr...
0
2016-07-22T17:46:13Z
38,532,647
<p>You have an infinite loop:</p> <pre><code>for the_match in matches: matches.append(the_match) </code></pre> <p>This will append new items to the list forever. I don't know what you were trying to achieve with this, but it looks like you can simply remove these two lines.</p>
0
2016-07-22T17:55:42Z
[ "python", "regex", "tuples" ]
Google's Python Course: iterating through list of regular expressions and printing each output on a new line
38,532,502
<p>I am trying to pass some regular expressions examples that are provided by Google's Python Course to a list and print each output on a new line.</p> <pre><code>import re str='an example word:cat!!' match=re.search(r'word:\w\w\w',str) if match: print('I found a cat :)',match.group()) ## 'found word:cat' else: pr...
0
2016-07-22T17:46:13Z
38,532,660
<p>The reason it keeps running forever is becasue you are appending to <code>matches</code> inside the for loop. You are always adding to it making the list longer which in turn makes the for loop run until it can reach the end, but it will never reach it. </p> <pre><code>for the_match in matches: print (the_match...
2
2016-07-22T17:56:42Z
[ "python", "regex", "tuples" ]
How do I create a matplotlib slideshow?
38,532,522
<p>The Python/pyplot code below generates four figures and four windows. I need code that opens one window showing fig1. Then when the user presses right arrow button or right arrow key the same window clears fig1 and shows fig2. So basically only one of the four figures will be selected by the user for viewing in a sl...
1
2016-07-22T17:46:59Z
38,551,548
<p>Maybe something like this: (click on the graph to switch)</p> <pre><code>import matplotlib.pyplot as plt import numpy as np i = 0 def fig1(fig): ax = fig.add_subplot(111) ax.plot(x, np.sin(x)) def fig2(fig): ax = fig.add_subplot(111) ax.plot(x, np.cos(x)) def fig3(fig): ax = fig.add_subplo...
1
2016-07-24T11:29:45Z
[ "python", "matplotlib", "cross-platform", "slideshow" ]
Quickbase module add_record() function—file upload parameters?
38,532,528
<p>The code below is part of the Python Quickbase module which has not been updated in quite a while. The help text for one of the function shown below is not clear on how to pass the parameters to upload a file (the value of which is actually base64 encoded).</p> <pre><code>def add_record(self, fields, named=False, d...
1
2016-07-22T17:47:11Z
38,544,832
<p>Based on the definition you provided, it appears that you you need to pass an array of dictionaries that each provide the field name/id, filename, and the base64 encoding of the file for the <code>uploads</code> parameter. So, if I had a table where I record the name of a color to the field named "color" with the f...
1
2016-07-23T17:50:43Z
[ "python", "api", "quickbase" ]
How to load a CSV string into MySQL using Python
38,532,655
<p>In my use case, I have a csv stored as a string and I want to load it into a MySQL table. Is there a better way than saving the string as a file, use LOAD DATA INFILE, and then deleting the file? I find <a href="http://stackoverflow.com/questions/3627537/is-a-load-data-without-a-file-i-e-in-memory-possible-for-mysql...
0
2016-07-22T17:56:11Z
38,532,713
<p>Yes what you describe is very possible! Say, for example, that your csv file has three columns:</p> <pre><code>import MySQLdb conn = MySQLdb.connect('your_connection_string') cur = conn.cursor() with open('yourfile.csv','rb') as fin: for row in fin: cur.execute('insert into yourtable (col1,col2,col3) va...
0
2016-07-22T18:00:12Z
[ "python", "mysql" ]
Numpy Conditional Max of Range
38,532,678
<p>I'm trying to make a version of my program faster using as much Pandas and Numpy as possible. I am new to Numpy but have been grasping most of it, but I am having trouble with conditional formatting a column with the max of a range. This is the code I am trying to use to achieve this:</p> <pre><code>x=3 df1['Max']...
4
2016-07-22T17:57:36Z
38,532,806
<p>Use <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.filters.maximum_filter1d.html" rel="nofollow"><code>Scipy's maximum_filter</code></a> -</p> <pre><code>from scipy.ndimage.filters import maximum_filter1d df['max'] = maximum_filter1d(df.High,size=3,origin=1,mode='nearest') </code...
5
2016-07-22T18:06:30Z
[ "python", "numpy", "pandas" ]
Numpy Conditional Max of Range
38,532,678
<p>I'm trying to make a version of my program faster using as much Pandas and Numpy as possible. I am new to Numpy but have been grasping most of it, but I am having trouble with conditional formatting a column with the max of a range. This is the code I am trying to use to achieve this:</p> <pre><code>x=3 df1['Max']...
4
2016-07-22T17:57:36Z
38,532,905
<p>Here is the logic on <code>np.where</code> </p> <pre><code> numpy.where('test something,if true ,if false) </code></pre> <p>I think you need below. </p> <pre><code>dd= {'to': [100, 200, 300, 400, -500, 600, 700,800, 900, 1000]} df = pd.DataFrame(dd) df to 0 100 1 200 2 300 3 400 4 -500 5 60...
3
2016-07-22T18:13:20Z
[ "python", "numpy", "pandas" ]
How to use rpartition to split the string with backward slashes
38,532,681
<p>I need to print the last string which is "foo" here, it's an error with no escape character and wrong result with escape character.</p> <pre><code>&gt;&gt;&gt; str1='\\a\b\c\foo' &gt;&gt;&gt; print str1.rpartition('\')[1] File "&lt;stdin&gt;", line 1 print str1.rpartition('\')[1] ^ Synta...
0
2016-07-22T17:58:02Z
38,532,776
<p>Assuming you have:</p> <pre><code>s = r'\\a\b\c\foo' </code></pre> <p>You need:</p> <pre><code>s.rsplit('\\', 1)[-1] </code></pre> <p>If your backslashes are messed up, see the other answers (no need to repeat those caveats here).</p>
0
2016-07-22T18:03:48Z
[ "python" ]
How to use rpartition to split the string with backward slashes
38,532,681
<p>I need to print the last string which is "foo" here, it's an error with no escape character and wrong result with escape character.</p> <pre><code>&gt;&gt;&gt; str1='\\a\b\c\foo' &gt;&gt;&gt; print str1.rpartition('\')[1] File "&lt;stdin&gt;", line 1 print str1.rpartition('\')[1] ^ Synta...
0
2016-07-22T17:58:02Z
38,532,781
<p>Two mistakes:</p> <p>First of all, there's no <code>foo</code> in <code>\\a\b\c\foo</code>. Why? Because <code>\f</code> is a form feed character. You can either escape the backslash with another backslash <code>\\\\a\\b\\c\\foo</code> or use a raw string <code>str1=r'\\a\b\c\foo'</code>.</p> <p>Secondly, <code>rp...
1
2016-07-22T18:04:06Z
[ "python" ]
How to use rpartition to split the string with backward slashes
38,532,681
<p>I need to print the last string which is "foo" here, it's an error with no escape character and wrong result with escape character.</p> <pre><code>&gt;&gt;&gt; str1='\\a\b\c\foo' &gt;&gt;&gt; print str1.rpartition('\')[1] File "&lt;stdin&gt;", line 1 print str1.rpartition('\')[1] ^ Synta...
0
2016-07-22T17:58:02Z
38,532,784
<p>You need the third element of the partition tuple:</p> <pre><code>&gt;&gt;&gt; str1=r'a\b\c\foo' &gt;&gt;&gt; str1.rpartition('\\') ('a\\b\\c', '\\', 'foo') &gt;&gt;&gt; str1.rpartition('\\')[2] 'foo' </code></pre>
0
2016-07-22T18:04:29Z
[ "python" ]
How to use rpartition to split the string with backward slashes
38,532,681
<p>I need to print the last string which is "foo" here, it's an error with no escape character and wrong result with escape character.</p> <pre><code>&gt;&gt;&gt; str1='\\a\b\c\foo' &gt;&gt;&gt; print str1.rpartition('\')[1] File "&lt;stdin&gt;", line 1 print str1.rpartition('\')[1] ^ Synta...
0
2016-07-22T17:58:02Z
38,532,794
<p>In you print line the '\' character is escaping the second <code>'</code> . It can't parse the line of code becasue to to the compiler it looks like the line doesn't end. it looks like this to the compiler <code>')[1]</code> It things the quote mark is part of the string. you need to add a second '\' to escape the ...
0
2016-07-22T18:05:18Z
[ "python" ]
Python/Matlab - Taking rank of matrix in quad precision or more
38,532,778
<p>I have a 14x14 matrix of which I'm trying to take the rank. The problem is that it has a high condition number so using double precision my matrix is not full rank. I know that it should be, so I'm trying to take the rank in higher precision. </p> <p>So far I have installed the bigfloat package in python, but hav...
2
2016-07-22T18:03:58Z
38,532,908
<p>Has matlab's <code>rank</code> function not worked for you?</p> <pre><code>&gt;&gt; A = [1,0; 0, 1e-20]; &gt;&gt; rank(A, 1e-19) ans = 1 &gt;&gt; rank(A, 1e-21) ans = 2 </code></pre>
0
2016-07-22T18:13:24Z
[ "python", "matrix", "precision", "rank", "quad" ]
Speeding up reading xml files
38,532,805
<p>I have a document of patents that is a concatenated string of xml files in one text document. I'm looking to split it up into separate documents each a single xml file. My code works but I need to speed it up. My code is like this: </p> <pre><code>import time count = 0 filestr = '' line = 'x' start_time = ti...
1
2016-07-22T18:06:30Z
38,533,009
<p>instead of checking each line, you might want to load the whole file content and perform the python regex pattern matcher. This way you will reduce the steps to check and get all the matches just by calling method findall().</p> <p>Here is the doc link - <a href="https://docs.python.org/3/howto/regex.html" rel="nof...
1
2016-07-22T18:19:00Z
[ "python", "xml", "performance" ]
How to transform a polygon string on a real polygon
38,532,816
<p>I need some support to real a polygon. Today I have a string and I need to change in a format that is possible to recognize as a polygon.</p> <p>I am acquiring directly from SQL the value of polygon:</p> <p>Example:</p> <p>I read on this way:</p> <pre><code>string = "POLYGON ((-47.158846224312285 -21.3497602423...
0
2016-07-22T18:06:54Z
38,533,545
<p>You can try parsing the string with a regular expression via the <a href="https://docs.python.org/2/library/re.html#module-re" rel="nofollow"><code>re</code> module</a> something like this:</p> <pre><code>import re pat = re.compile(r'''(-*\d+\.\d+ -*\d+\.\d+);*''') s = "POLYGON ((-47.158846224312285 -21.3497602423...
1
2016-07-22T18:56:38Z
[ "python", "polygon" ]
How to transform a polygon string on a real polygon
38,532,816
<p>I need some support to real a polygon. Today I have a string and I need to change in a format that is possible to recognize as a polygon.</p> <p>I am acquiring directly from SQL the value of polygon:</p> <p>Example:</p> <p>I read on this way:</p> <pre><code>string = "POLYGON ((-47.158846224312285 -21.3497602423...
0
2016-07-22T18:06:54Z
38,533,657
<p>Depending on how string your inputs are, this may be an easy case to simply use some string manipulation <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regular expression</a> library and some string manipulation.</p> <pre class="lang-py prettyprint-override"><code>import re # create a regular ex...
0
2016-07-22T19:03:31Z
[ "python", "polygon" ]
Replacing cells in a column, but not header, in a csv file with python
38,532,831
<p>I've been looking for a few hours now and not found what I'm looking for...</p> <p>I'm looking to make a program that takes an already compiled .csv file with some information missing and asking the user what they would like to add and then placing this in the csv but not effecting the header line. Then saving the ...
0
2016-07-22T18:07:53Z
38,532,975
<p>I believe the main part of your question (how to skip the header) has been answered here:</p> <p><a href="http://stackoverflow.com/questions/14257373/skip-the-headers-when-editing-a-csv-file-using-python">Skip the headers when editing a csv file using Python</a> </p> <p>If you call <code>next()</code> on the reade...
0
2016-07-22T18:17:23Z
[ "python", "csv" ]
Replacing cells in a column, but not header, in a csv file with python
38,532,831
<p>I've been looking for a few hours now and not found what I'm looking for...</p> <p>I'm looking to make a program that takes an already compiled .csv file with some information missing and asking the user what they would like to add and then placing this in the csv but not effecting the header line. Then saving the ...
0
2016-07-22T18:07:53Z
38,533,063
<ol> <li>We open the input file and the output file with a python context manager.</li> <li>get the user input using <code>input()</code> (python 3) or <code>raw_input()</code> (python 2) functions</li> <li>grab the 1st row in the file and write it out without changing anything and write that out</li> <li><p>Loop throu...
1
2016-07-22T18:22:43Z
[ "python", "csv" ]
Returning two dictionaries, using each one in separate functions
38,532,850
<pre><code>def make(node): # takes some input for reg_names in reg.names # dont worry about reg_names and reg.names if reg.size &gt; 0: #reg.size is an inbuilt function found_dict = {} # first dictionary found_dict['reg.name'] = 'reg.size' # i want to save the name of the register : size of the reg...
-1
2016-07-22T18:09:01Z
38,533,028
<p>First of all in your first section in the for loop every time you do :<code>found_dict = {}</code> or <code>not_found_dict = {}</code> you are clearing the contents of the dictionary. I'm not sure if this is what you want. </p> <p>Second if you want to return more than one thing from a function you could always ret...
0
2016-07-22T18:20:12Z
[ "python" ]
python regex - how to create and reference arbitrary, unknown number of groups
38,532,873
<p>I have a text file consisting of space-separate text values:</p> <pre><code>a: b c d e f g h: i j k l: m: n </code></pre> <p>I do not know how many of these values - right of <code>;</code>- I'll have a priori.</p> <p>I want to use <a href="https://docs.python.org/3/library/re.html" rel="nofollow">Python groups</...
2
2016-07-22T18:11:00Z
38,533,069
<p>See <a href="http://stackoverflow.com/questions/6673686/python-regex-repetition-with-capture-question">this answer</a>.</p> <blockquote> <p>Most or all regular expression engines in common use, including in particular those based on the PCRE syntax (like Python's), label their capturing groups according to the nu...
2
2016-07-22T18:23:24Z
[ "python", "regex" ]
time complexity of this approach
38,532,919
<p>So I am reading two files and storing each line in two different lists respectively. Now I have to check if a string in the first list is present in the 2nd list.</p> <p>By normal comparison this will take O(n^2)</p> <p>But using a graph based data structure like -</p> <p>File1_visited[string] = True </p> <p>Fil...
0
2016-07-22T18:13:56Z
38,533,334
<p>Yes, you went from <code>O(n^2)</code> to <code>O(n)</code>. You might want to look into the space complexity as well, you would have to store the graph for one of them while for the other one you would use less space. A HashMap looks ideal for this situation if you do not care about memory, or any other array if i...
0
2016-07-22T18:41:59Z
[ "java", "python", "time", "time-complexity" ]
Pandas - join item from different dataframe within an array
38,532,939
<p>I am a first data frame looking like this</p> <pre><code>item_id | options ------------------------------------------ item_1_id | [option_1_id, option_2_id] </code></pre> <p>And a second like this:</p> <pre><code>option_id | option_name --------------------------- option_1_id | option_1_name </code></...
-1
2016-07-22T18:15:13Z
38,533,095
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>apply</code></a>.</p> <p>For the record, storing lists in <code>DataFrames</code> is typically unnecessary and not very "pandonic". Also, if you only have one column, you can do this with a <cod...
0
2016-07-22T18:25:15Z
[ "python", "pandas" ]
python Iterative loop through columns of dataframe
38,532,978
<p>Working on a problem, I have the following dataframe in python</p> <pre><code> week hour week_hr store_code baskets 0 201616 106 201616106 505 0 1 201616 107 201616107 505 0 2 201616 108 201616108 505 0 3 201616 109 201616109 505 18 4...
4
2016-07-22T18:17:30Z
38,533,819
<p>You can solve:</p> <ol> <li>Sort by store_code, week_hr</li> <li>Filter by 0</li> <li>Group by store_code</li> <li>Find continuous</li> </ol> <p>Code:</p> <pre><code>t1 = df.sort_values(['store_code', 'week_hr']) t2 = t1[t1['baskets'] == 0] grouped = t2.groupby('store_code')['week_hr'].apply(lambda x: x.tolist(...
0
2016-07-22T19:14:33Z
[ "python", "loops", "python-3.x", "pandas", "dataframe" ]
python Iterative loop through columns of dataframe
38,532,978
<p>Working on a problem, I have the following dataframe in python</p> <pre><code> week hour week_hr store_code baskets 0 201616 106 201616106 505 0 1 201616 107 201616107 505 0 2 201616 108 201616108 505 0 3 201616 109 201616109 505 18 4...
4
2016-07-22T18:17:30Z
38,534,604
<p>Do the following:</p> <ol> <li>Sort by store_code, week_hr</li> <li>Filter by 0</li> <li>Store the subtraction between df['week_hr'][1:].values-df['week_hr'][:-1].values so you will get to know if they are continuos.</li> <li><p>Now you can give groups to continuous and filter as you want.</p> <pre><code>import nu...
1
2016-07-22T20:14:26Z
[ "python", "loops", "python-3.x", "pandas", "dataframe" ]
how to specify a page title in a django views.py file using a context variable?
38,532,985
<p>I am trying to specify a page title that shows up in the browser tab within a views.py file for a class based view. I am working with a file that uses a base template html page for many different pages where I am trying specify the title using something such as:</p> <pre><code>{% block title %}{{ view.build_page_ti...
0
2016-07-22T18:18:06Z
38,533,122
<p>You don't pass values to the template by defining arbitrary methods on your view class; the template has no access to the view at all. </p> <p>Instead, the view class will call its own <code>get_context_data</code> to determine the values to pass to the template; you can override that and add your own value.</p> <...
1
2016-07-22T18:27:16Z
[ "python", "django", "django-views" ]
xml libxml2 parsing
38,533,050
<p>In the code below, my problem is that it's writing output to all folders based on only one input file. Can some one give me a hint and check if my code is looping properly?</p> <pre><code>import libxml2 import os.path from numpy import * from cfs_utils import * np=[1,2,3,4,5,6,7,8] n=[20,30,40,60,80,100,130] solve...
0
2016-07-22T18:21:51Z
38,541,613
<p>Problem solved, I = o, was outside the loop</p>
0
2016-07-23T12:07:06Z
[ "python", "xml", "parsing", "xml-parsing" ]
How exactly does the caller see a change in the object?
38,533,094
<p>From <a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">Chapter "Classes"</a> of the official Python tutorial:</p> <blockquote> <p>[...] if a function modifies an object passed as an argument, the caller will see the change — this eliminates the need for two different argument passing mech...
2
2016-07-22T18:25:11Z
38,533,145
<blockquote> <p>What would be an example of how exactly the caller will see a change?</p> </blockquote> <pre><code>&gt;&gt;&gt; def modify(x): ... x.append(1) ... &gt;&gt;&gt; seq = [] &gt;&gt;&gt; print(seq) [] &gt;&gt;&gt; modify(seq) &gt;&gt;&gt; print(seq) [1] </code></pre> <blockquote> <p>Or how could it...
3
2016-07-22T18:28:56Z
[ "python", "function", "object" ]
How exactly does the caller see a change in the object?
38,533,094
<p>From <a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">Chapter "Classes"</a> of the official Python tutorial:</p> <blockquote> <p>[...] if a function modifies an object passed as an argument, the caller will see the change — this eliminates the need for two different argument passing mech...
2
2016-07-22T18:25:11Z
38,533,147
<p>It basically means that if a mutable object is changed, it will change everywhere.</p> <p>For an example of passing by reference (which is what Python does):</p> <pre><code>x = [] def foo_adder(y): y.append('foo') foo_addr(x) print(x) # ['foo'] </code></pre> <p>vs something like Pascal, where you can pass co...
3
2016-07-22T18:29:10Z
[ "python", "function", "object" ]
How to specify pem file path when using gateway in Fabric
38,533,102
<p>I have followed many question related to this topic.</p> <p>My scenario:</p> <blockquote> <p>Local host -> Gateway -> Remote host</p> </blockquote> <p>I am using env.gateway variable to specify gateway host.</p> <p>sample code</p> <pre><code>env.user = "ec2-user" env.key_filename = ["/home/ec2-user/.ssh/inte...
0
2016-07-22T18:25:42Z
38,562,686
<p>I havn't had to do this yet, but what about having a function that fecth those pem file ? something like :</p> <pre><code>@'x.x.x.189' def get_pem(): env.key_filename.append(get("/home/ec2-user/.ssh/internal.pem") env.key_filename.append(get("/home/ec2-user/.ssh/test2.pem") </code></pre> <p>Also, I could y...
1
2016-07-25T08:15:07Z
[ "python", "amazon-web-services", "fabric" ]
How to return only one level of keys using Boto3?
38,533,252
<p>I have an s3 bucket with a structure like so:</p> <pre><code>bucket ---key_1 ---sub_key_1 ---file_a ---sub_key_2 ---file_b ---sub_key_3 ---file_c </code></pre> <p>Where the keys are all separated by /. I want to run a boto 3 command to return just the sub keys. I've tried a few things. U...
0
2016-07-22T18:36:34Z
38,533,378
<p>I've actually found the answer here: <a href="https://github.com/boto/boto3/issues/134" rel="nofollow">https://github.com/boto/boto3/issues/134</a>. The simplest way is to use the client.list_objects call as posted above and retrieve the CommonPrefixes attribute from it.</p>
0
2016-07-22T18:44:14Z
[ "python", "amazon-web-services", "amazon-s3", "boto3" ]
how can argparse set default value of optional parameter to null or empty?
38,533,258
<p>I am using python argparse to read an optional parameter that defines an "exemplar file" that users sometimes provide via the command line. I want the default value of the variable to be empty, that is no file found.</p> <pre><code>parser.add_argument("--exemplar_file", help = "file to inspire book", default = '')...
0
2016-07-22T18:37:04Z
38,533,331
<p>Just don't set a default:</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument('--exemplar_file', help='file to inspire book') args = parser.parse_args() print(args.exemplar_file) # Output: # None </code></pre>
2
2016-07-22T18:41:51Z
[ "python", "argparse" ]
how can argparse set default value of optional parameter to null or empty?
38,533,258
<p>I am using python argparse to read an optional parameter that defines an "exemplar file" that users sometimes provide via the command line. I want the default value of the variable to be empty, that is no file found.</p> <pre><code>parser.add_argument("--exemplar_file", help = "file to inspire book", default = '')...
0
2016-07-22T18:37:04Z
38,534,929
<p>The default <code>default</code> is <code>None</code> (for the default <code>store</code> action). A nice thing about is that your user can't provide that value (there's no string that converts to <code>None</code>). It is easy to test</p> <pre><code> if args.examplar_file is None: # do your thing # arg...
1
2016-07-22T20:41:13Z
[ "python", "argparse" ]
Python pretty print dictionary of lists, abbreviate long lists
38,533,282
<p>I have a dictionary of lists and the lists are quite long. How can I print it in a way that only a few elements of the list show up? Obviously, I can write a custom function for that but is there any built-in way or library that can achieve this? For example when printing large data frames, <code>pandas</code> print...
8
2016-07-22T18:38:32Z
38,533,415
<p>This recursive function I wrote does something you're asking for.. You can choose the indentation you want too</p> <pre><code>def pretty(d, indent=0): for key in sorted(d.keys()): print '\t' * indent + str(key) if isinstance(d[key], dict): pretty(d[key], indent+1) else: ...
2
2016-07-22T18:46:56Z
[ "python", "list", "dictionary", "pretty-print" ]
Python pretty print dictionary of lists, abbreviate long lists
38,533,282
<p>I have a dictionary of lists and the lists are quite long. How can I print it in a way that only a few elements of the list show up? Obviously, I can write a custom function for that but is there any built-in way or library that can achieve this? For example when printing large data frames, <code>pandas</code> print...
8
2016-07-22T18:38:32Z
38,533,419
<p>You could use the <a href="https://docs.python.org/3/library/pprint.html"><code>pprint</code></a> module:</p> <pre><code>pprint.pprint(obj) </code></pre> <p>Would output:</p> <pre><code>{'key_1': ['EG8XYD9FVN', 'S2WARDCVAO', 'J00YCU55DP', 'R07BUIF2F7', 'VGPS1JD0UM', ...
6
2016-07-22T18:47:12Z
[ "python", "list", "dictionary", "pretty-print" ]
Python pretty print dictionary of lists, abbreviate long lists
38,533,282
<p>I have a dictionary of lists and the lists are quite long. How can I print it in a way that only a few elements of the list show up? Obviously, I can write a custom function for that but is there any built-in way or library that can achieve this? For example when printing large data frames, <code>pandas</code> print...
8
2016-07-22T18:38:32Z
38,533,524
<p>Use <a href="https://docs.python.org/3/library/reprlib.html" rel="nofollow">reprlib</a>. The formatting is not that pretty, but it actually abbreviates.</p> <pre><code>&gt; import repr &gt; repr.repr(map(lambda _: range(100000), range(10))) '[[0, 1, 2, 3, 4, 5, ...], [0, 1, 2, 3, 4, 5, ...], [0, 1, 2, 3, 4, 5, ...]...
2
2016-07-22T18:54:54Z
[ "python", "list", "dictionary", "pretty-print" ]
Python pretty print dictionary of lists, abbreviate long lists
38,533,282
<p>I have a dictionary of lists and the lists are quite long. How can I print it in a way that only a few elements of the list show up? Obviously, I can write a custom function for that but is there any built-in way or library that can achieve this? For example when printing large data frames, <code>pandas</code> print...
8
2016-07-22T18:38:32Z
38,534,524
<p>If it weren't for the pretty printing, the <a href="https://docs.python.org/3/library/reprlib.html" rel="nofollow"><code>reprlib</code></a> module would be the way to go: Safe, elegant and customizable handling of deeply nested and recursive / self-referencing data structures is what it has been made for.</p> <p>Ho...
3
2016-07-22T20:08:34Z
[ "python", "list", "dictionary", "pretty-print" ]
Python pretty print dictionary of lists, abbreviate long lists
38,533,282
<p>I have a dictionary of lists and the lists are quite long. How can I print it in a way that only a few elements of the list show up? Obviously, I can write a custom function for that but is there any built-in way or library that can achieve this? For example when printing large data frames, <code>pandas</code> print...
8
2016-07-22T18:38:32Z
38,534,603
<p>You could use <a href="https://ipython.org/ipython-doc/3/api/generated/IPython.lib.pretty.html" rel="nofollow">IPython.lib.pretty</a>.</p> <pre><code>from IPython.lib.pretty import pprint &gt; pprint(obj, max_seq_length=5) {'key_1': ['EG8XYD9FVN', 'S2WARDCVAO', 'J00YCU55DP', 'R07BUIF2F7', 'VGPS1JD0UM', ....
1
2016-07-22T20:14:25Z
[ "python", "list", "dictionary", "pretty-print" ]
Pivot Table not writing to pre-existing sheet
38,533,320
<p>I have two sheets in my excel workbook. The first sheet contains the data used to make the pivot table, and the second sheet as you can see I create in this section of the code. I would like my pivot table to be drawn into the new sheet that I created (worksheet2).</p> <p>When I run my code, my excel file contains ...
1
2016-07-22T18:40:57Z
38,533,583
<p>you can do it <a href="http://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data/20221655#20221655">this way</a>:</p> <pre><code>df = pd.read_excel(filename, usecols=['Product Description', 'Supervisor']) table1 = df.pivot_table(index='Supervisor', columns='Product...
1
2016-07-22T18:59:12Z
[ "python", "pandas" ]
django {% url %} with parameters (list of dicts)
38,533,430
<p>I'm following the suggestion at: <a href="http://stackoverflow.com/questions/3583534/refresh-div-element-generated-by-a-django-template">Refresh &lt;div&gt; element generated by a django template</a></p> <p>I'm passing along a few variables, a la:</p> <pre><code>url: '{% url 'search_results' 'sched_dep_local' flig...
0
2016-07-22T18:48:00Z
38,533,637
<p>This isn't the right way to deal with complex data. Rather than sending it via the URL, you should be using a POST and sending it in the body of the request: since you're using jQuery, you can just do <code>method: "POST"</code> in that call. In the backend, you can deserialize it from JSON.</p> <p>However, it does...
0
2016-07-22T19:02:34Z
[ "python", "django" ]
Indicating missing data in Pandas
38,533,460
<h2>Update</h2> <p>So I have been playing around with this, and it seems that this actually happens when I read a different csv file into my program using <code>read_csv()</code>. And what then happens is exactly what the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollo...
0
2016-07-22T18:49:57Z
38,537,108
<p>You can try it this way:</p> <pre><code>spreadsheet = pd.DataFrame({'name': ['NA', 'NA', 'NA', 'NA', 'NA']}) spreadsheet name 0 NA 1 NA 2 NA 3 NA 4 NA </code></pre> <p>Then if you want to replace a couple of the <code>NA</code>s you can just select where you want to replace them.</p> <pre><code>spre...
0
2016-07-23T00:55:15Z
[ "python", "csv", "pandas", "spreadsheet", null ]
Inheriting list: Creating division by other lists, integers and floats
38,533,476
<p>I wanted to be able to divide entire lists by integers, floats, and other lists of equal length in Python, so I wrote the following little script.</p> <pre><code>class divlist(list): def __init__(self, *args, **kwrgs): super(divlist, self).__init__(*args, **kwrgs) self.__cont_ = args[0] ...
1
2016-07-22T18:50:43Z
38,533,565
<blockquote> <blockquote> <p>How can I write this in a simpler way?</p> </blockquote> </blockquote> <p>By using <code>self[i]</code> instead of <code>self.__cont_[i]</code>.</p> <blockquote> <p>Do I really need the lines self.__cont_ and self.__len_?</p> </blockquote> <p>No. Just use the regular methods of...
5
2016-07-22T18:57:54Z
[ "python", "list" ]
Inheriting list: Creating division by other lists, integers and floats
38,533,476
<p>I wanted to be able to divide entire lists by integers, floats, and other lists of equal length in Python, so I wrote the following little script.</p> <pre><code>class divlist(list): def __init__(self, *args, **kwrgs): super(divlist, self).__init__(*args, **kwrgs) self.__cont_ = args[0] ...
1
2016-07-22T18:50:43Z
38,534,820
<p>Instead of examining the explicit types of each argument, assume that either the second argument is iterable, or it is a suitable value as the denominator for <code>//</code>.</p> <pre><code>def __floordiv__(self, other): try: pairs = zip(self, other) except TypeError: pairs = ((x, other) fo...
3
2016-07-22T20:32:02Z
[ "python", "list" ]
makemigrations failing with django_enumfield in Django 1.9
38,533,597
<p>I just updated my Bitnami Django VM from 1.8.9 to 1.9.7. Everything was working smoothly before the upgrade, but now when I run makemigrations I get the following error:</p> <pre><code>TypeError: Couldn't reconstruct field role on rapid.GeoViewRole: __init__() takes at least 2 arguments (1 given) </code></pre> <p>...
1
2016-07-22T19:00:09Z
39,468,611
<p>It was the version of django-enumfield for me. I had</p> <pre><code>django-enumfield==1.2.1 </code></pre> <p>Migrations worked after I removed it, and installed</p> <pre><code>django_enumfield==1.3b2 </code></pre>
1
2016-09-13T11:12:33Z
[ "python", "django", "upgrade", "typeerror" ]
Scrap Table HTML with beautifulSoup
38,533,642
<p>I'm trying to scrap a website which has been built with tables. Here a link of a page's example: <a href="http://www.rc2.vd.ch/registres/hrcintapp-pub/companyReport.action?rcentId=5947621600000055031025&amp;lang=FR&amp;showHeader=false" rel="nofollow">http://www.rc2.vd.ch/registres/hrcintapp-pub/companyReport.action...
1
2016-07-22T19:02:44Z
38,534,279
<p>Something like this?</p> <pre><code>results = soup.find_all("tr", {"bgcolor" : "#ffffff"}) for result in results: the_name = result.td.span.get_text().split(',')[0] </code></pre>
0
2016-07-22T19:49:51Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
Scrap Table HTML with beautifulSoup
38,533,642
<p>I'm trying to scrap a website which has been built with tables. Here a link of a page's example: <a href="http://www.rc2.vd.ch/registres/hrcintapp-pub/companyReport.action?rcentId=5947621600000055031025&amp;lang=FR&amp;showHeader=false" rel="nofollow">http://www.rc2.vd.ch/registres/hrcintapp-pub/companyReport.action...
1
2016-07-22T19:02:44Z
38,534,706
<p>This will get the name from the page, the table is right after the anchor with the <em>id</em> <em>adm</em>, once you have that you have numerous ways to get what you need:</p> <pre><code>from bs4 import BeautifulSoup import requests r = requests.get('http://www.rc2.vd.ch/registres/hrcintapp-pub/companyReport.acti...
2
2016-07-22T20:21:32Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
Include requirements.txt file in Python wheel
38,533,669
<p>To avoid specifying dependencies in two places, I have a Python project whose setup.py parses a requirements.txt file to generate the list of install_requires packages. This works great until I try to upload a wheel to a devpi server and then install it - I get the error that requirements.txt is not found.</p> <p>I...
1
2016-07-22T19:04:29Z
38,533,721
<p>Just add a <code>MANIFEST.in</code> in the project folder with the content:</p> <pre><code>include requirements.txt </code></pre> <p>And it would include the file. You can also use wildcards like <code>*</code> too.</p>
1
2016-07-22T19:07:32Z
[ "python", "pip", "setuptools", "python-wheel", "devpi" ]
ImportError: No module named helpers (Python 2.7.12- Windows 10)
38,533,715
<p>I am having a problem running below code in python; </p> <pre><code>from helpers import process_titanic_line print(process_titanic_line(lines[0])) </code></pre> <p>The error which I am getting is; </p> <pre><code>ImportError Traceback (most recent call last) &lt;ipython-input-29-5691...
0
2016-07-22T19:07:15Z
38,535,424
<p>I had to upload helpers module to python. I did it by uploading helpers.py file for the project. I would like to thank all who contributed to the discussion. </p>
0
2016-07-22T21:21:42Z
[ "python", "scikit-learn" ]
Why data frame can not plotted in 3d graph in matplotlib?
38,533,726
<p>thank you for reading this. I am beginner with python and English. I wanted to graph 3D graph with datasets- X,Y and Z from loaded csv file. so I set x as the second column from csv file:</p> <pre><code>mpl.rcParams['legend.fontsize'] = 10 fig = plt.figure() f = fig.gca(projection='3d') x = df[[1]] y = df[[2]] z...
0
2016-07-22T19:07:57Z
38,534,303
<p>Your error is with pandas, not matplotlib. Use the following to get your column names:</p> <pre><code>df.keys() </code></pre> <p>and then you need to extract out the columns: say for example my column names are ["hi", "bye", "world"], then my commands are:</p> <pre><code>x = df["hi"] y = df["bye"] z = df["world"...
1
2016-07-22T19:51:20Z
[ "python", "csv", "matplotlib", "graph", "keyerror" ]
Why does unified_diff method from the difflib library in Python leave out some characters?
38,533,751
<p>I am trying to check for differences between lines. This is my code:</p> <pre><code>from difflib import unified_diff s1 = ['a', 'b', 'c', 'd', 'e', 'f'] s2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'k', 'l', 'm', 'n'] for line in unified_diff(s1, s2): print line </code></pre> <p>It prints:</p> <pre><code>-...
1
2016-07-22T19:09:44Z
38,534,581
<p>If you take a look at <code>unified_diff</code> code you will find description about a parameter called <code>n</code>:</p> <blockquote> <p>Unified diffs are a compact way of showing line changes and a few lines of context. The number of context lines is set by 'n' which defaults to three.</p> </bloc...
0
2016-07-22T20:12:56Z
[ "python", "difflib", "unified-diff" ]
python time.time() differences in python 2 vs 3
38,533,756
<p>I am wondering why <code>python 2.7</code> uses <code>gettimeofday()</code> when running <code>time.time()</code> but yet in <code>python 3.4</code> it does not?</p> <p>It appears when running strace that it may be querying /etc/localtime</p>
3
2016-07-22T19:09:57Z
38,534,282
<p>Python 3 will use <code>gettimeofday()</code> when your system has been detected to support this <em>at compile time</em>. However, on POSIX systems it'll only use that if <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_gettime.html" rel="nofollow"><code>clock_gettime(CLOCK_REALTIME)</code><...
3
2016-07-22T19:50:04Z
[ "python", "python-2.7", "python-3.x", "python-internals", "gettimeofday" ]
Complex Python object to JSON Conversion
38,533,832
<p>I need to convert a complex python object to JSON, by complex I mean an object that contains int variables, string variables, and 2 lists of custom objects. </p> <p>My Python object's constructor is:</p> <pre><code> def __init__(self, skills="",vid=""): self.Skills = list([]) for skillID in skills.split("-...
0
2016-07-22T19:15:24Z
38,535,271
<p>Encode:</p> <pre><code>import base64 import pickle token = base64.b64encode(pickle.dumps(token,-1)) </code></pre> <p>Decode:</p> <pre><code>import pickle import base64 Obj = pickle.loads(base64.b64decode(token)) </code></pre>
0
2016-07-22T21:09:30Z
[ "python", "json", "class", "oop" ]
Django custom Widget failing on choices above 1 (enter whole number)
38,533,860
<p>I wanted a multiState clickbox. So I spend some free time on a nice Django solution that makes it:</p> <pre><code>class MultiStateChoiceInput(forms.widgets.ChoiceInput): input_type = 'radio' def __init__(self, name, value, attrs, choice, index, label_id): # Override to use the label_id which is uppe...
0
2016-07-22T19:17:08Z
38,543,119
<p>@edgarzamora Your comment is not the answer, but it is close!</p> <p>I removed the 'field' from the Form class Meta, so it looked like:</p> <pre><code>class Meta: model = MyModal fields = ('',) widgets = {'id': forms.HiddenInput(), } </code></pre> <p>And now everything works, because I ha...
0
2016-07-23T14:57:59Z
[ "python", "html", "css", "django", "django-forms" ]
Pandas groupby on two conditions
38,533,882
<p>I have the following table:</p> <p><a href="http://i.stack.imgur.com/EWOD0.png" rel="nofollow"><img src="http://i.stack.imgur.com/EWOD0.png" alt="enter image description here"></a></p> <p>I'm attempting to do two things with the table:</p> <p>1) If a call only appears once, make it so that any of these single-cal...
1
2016-07-22T19:18:27Z
38,535,938
<p>If I understand correctly, the first part works for you, and for the second part you want to mark the lines with the lowest delta value (per call). The following code fetched the line numbers of these calls, and then assigns ORDER=1 on those lines.</p> <pre><code>cond = calls.groupby(['ANI'])['delta'].transform(min...
1
2016-07-22T22:09:59Z
[ "python", "pandas", "group-by" ]
botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint
38,533,897
<p>I'm running Ubuntu 12.04, Python 2.7.3 and trying to run <a href="https://github.com/awslabs/chalice" rel="nofollow">chalice</a></p> <p>However, when I run </p> <blockquote> <p>chalice deploy</p> </blockquote> <p>I get back:</p> <blockquote> <p>botocore.exceptions.EndpointConnectionError: Could not connect t...
0
2016-07-22T19:19:14Z
38,534,529
<p>As per your config you have setup the region to <code>region = us-west-1</code> and you are trying to access a Lambda function in region us-east-1.</p> <p>Change that region to us-east-1 in the config and then give it a try it will work.</p>
1
2016-07-22T20:08:58Z
[ "python", "amazon-web-services", "aws-lambda", "boto3" ]
Non-Blocking Server Apache Thrift Python
38,533,973
<p>In one Python Module A I am doing some stuff. In the middle of doing that stuff I am creating a Thrift connection. The problem is after that connection starts, the program gets stuck in the network logic. (i.e blocking).</p> <p>In module A I have: </p> <pre><code>stuff = "do some stuff" network.ConnectionManager(h...
1
2016-07-22T19:25:50Z
38,544,162
<p>The code blocks at <code>server.serve()</code> which is by design, across all target languages supported by Thrift. The usual use case is to run a server like this (pseudo code):</p> <pre><code>init server setup thrift protocol/tramsport stack server.serve() shutdown code </code></pre> <p>The "nonblocking" does no...
2
2016-07-23T16:46:18Z
[ "python", "multithreading", "apache", "thrift", "nonblocking" ]
use existing field as _id using elasticsearch dsl python DocType
38,533,990
<p>I have class, where I try to set <code>student_id</code> as <code>_id</code> field in <a href="/questions/tagged/elasticsearch" class="post-tag" title="show questions tagged &#39;elasticsearch&#39;" rel="tag"><img src="//i.stack.imgur.com/817gJ.png" height="16" width="18" alt="" class="sponsor-tag-img">elasticsearch...
0
2016-07-22T19:27:10Z
38,651,072
<p>There are a few ways to assign an id:</p> <p>You can do it like this</p> <pre><code>a = StudentDoc(meta={'id':1}, student_id=1, tags=['test']) a.save() </code></pre> <p>Like this:</p> <pre><code>a = StudentDoc(student_id=1, tags=['test']) a.meta.id = 1 a.save() </code></pre> <p>Also note that before ES 1.5, one...
1
2016-07-29T05:26:51Z
[ "python", "elasticsearch", "elasticsearch-dsl" ]
django: customized decorator running before django-rest-framework authentication class
38,534,019
<p>My REST APIs:</p> <pre><code>class FileView(APIView): parser_classes = (MultiPartParser,) authentication_classes = (BasicAuthentication,) permission_classes = (IsAuthenticated,) @method_decorator(csrf_exempt) @method_decorator(operation_logger) def dispatch(self, request, *args, **kwargs): return s...
1
2016-07-22T19:29:47Z
38,537,258
<p>You can change the order your decorators are applied: the one nearest to <code>def</code> line will run first.</p> <pre><code>@method_decorator(operation_logger) @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(FileView, self).dispatch(request, *args, **kwargs) </code></...
0
2016-07-23T01:23:11Z
[ "python", "django", "django-rest-framework" ]
How to find and query a specific build in Jenkins using the Python Jenkins API
38,534,171
<p>We have a Jenkins job that runs builds using specific parameters. Two of these parameters are important for me: the machine that the build is being deployed on, and the version number of the package that is deployed.</p> <blockquote> <p><a href="https://jenkinsurl/job/folder_level1/job/folder_level2/job/folder_le...
2
2016-07-22T19:41:50Z
40,026,577
<p>Use the /api/xml format:</p> <pre><code>https://jenkinsurl/job/folder_level1/api/xml </code></pre> <p>which returns the <code>action</code> XML node which can be queried via XPath:</p> <ul> <li><a href="https://jenkinsurl/job/folder_level1/api/xml?xpath=//action&amp;wrapper=root" rel="nofollow">https://jenkinsurl...
1
2016-10-13T16:39:20Z
[ "python", "json", "jenkins", "querying", "jenkins-api" ]
transform irregular timeseries into zscores relative to closest neighbors
38,534,194
<p>I have a time series with an irregularly spaced index. I want to transform the data by subtracting a mean and dividing by a standard deviation for every point. However, I only want to calculate the means and standard deviations using those data values that are a predefined time distance away. In my example below,...
3
2016-07-22T19:43:39Z
38,534,472
<p>This is something I've been working on. Keep in mind this is related to but different than (as I suspect you know, otherwise you probably wouldn't be asking the question) pandas <code>rolling</code> feature. For your the regularly spaced data you gave, it would tie out pretty well and we can use that to compare.</...
4
2016-07-22T20:04:42Z
[ "python", "numpy", "pandas" ]
transform irregular timeseries into zscores relative to closest neighbors
38,534,194
<p>I have a time series with an irregularly spaced index. I want to transform the data by subtracting a mean and dividing by a standard deviation for every point. However, I only want to calculate the means and standard deviations using those data values that are a predefined time distance away. In my example below,...
3
2016-07-22T19:43:39Z
38,535,525
<p>This isn't a <code>pandas</code>/<code>numpy</code> solution but should give decent performance. Essentially, to find closest points you can build an <a href="https://en.wikipedia.org/wiki/Interval_tree" rel="nofollow">Interval Tree</a> using the <a href="https://pypi.python.org/pypi/intervaltree" rel="nofollow"><c...
3
2016-07-22T21:30:16Z
[ "python", "numpy", "pandas" ]
Why limit DB Connection Pool Size in SQLAlchemy?
38,534,203
<p>This is a follow-up to a <a href="http://stackoverflow.com/questions/38515488/load-testing-sql-alchemy-timeouterror-queuepool-limit-of-size-3-overflow-0-re">question</a> I posted earlier about DB Connection Pooling errors in SQLAlchemy.</p> <p>According to the SQLAlchemy <a href="http://docs.sqlalchemy.org/en/lates...
1
2016-07-22T19:44:07Z
38,534,463
<p>The main drawback to not limiting the pool size would be the potential for a runaway program to create too many connections. </p> <p>There are real limits, both at the database level, and O/S level to how many connections the database will support. Each connection will also use additional memory. Limiting the po...
2
2016-07-22T20:03:59Z
[ "python", "database", "sqlalchemy" ]
Ordering a nested dictionary in python
38,534,228
<p>I have a nested dictionary (category and subcategories), <code>dict</code>, that I am having trouble sorting. </p> <p>The output of <code>dict</code> is:</p> <pre><code>{u'sports': {u'basketball': {'name': u'Basketball', 'slug': u'basketball'}, u'baseball': {'name': u'Baseball', 'slug': u'baseball'}}, u'dance': {u...
0
2016-07-22T19:46:06Z
38,534,313
<p>You have some major concept misunderstanding about dictionary. Dictionary in python is like a <a href="https://en.wikipedia.org/wiki/Hash_table" rel="nofollow">hash table</a>, hash table has no order. The output of the dict is really environment dependent so you couldn't depend on that. You might see one way of the ...
3
2016-07-22T19:52:14Z
[ "python", "django" ]
Ordering a nested dictionary in python
38,534,228
<p>I have a nested dictionary (category and subcategories), <code>dict</code>, that I am having trouble sorting. </p> <p>The output of <code>dict</code> is:</p> <pre><code>{u'sports': {u'basketball': {'name': u'Basketball', 'slug': u'basketball'}, u'baseball': {'name': u'Baseball', 'slug': u'baseball'}}, u'dance': {u...
0
2016-07-22T19:46:06Z
38,534,406
<p>Python dictionaries (regular <code>dict</code> instances) are not sorted. If you want to sort your dict, you could:</p> <pre><code>from collections import OrderedDict mynewdict = OrderedDict(sorted(yourdict.items())) </code></pre> <p>An OrderedDict does not provide a sorting mechanism, but only respect the order ...
0
2016-07-22T19:59:11Z
[ "python", "django" ]
How nested filters work?
38,534,246
<p>I guess I don't fully understand how nested filters work. </p> <p>I've created highly nested (and slightly silly) filter object:</p> <pre><code>L = iter(range(100000)) for i in range(10000): L = filter(lambda x, i=i: x != i, L) </code></pre> <p>Each of the additional filter level just trim the iterator some ...
0
2016-07-22T19:47:36Z
38,534,404
<p>The first iteration has to apply about 50 million predicate tests to reject the first 10 thousand elements, so it takes ages. Every iteration after that only needs to apply 10 thousand tests to accept the next element, so they're about 5000 times faster. The variation you see between later iterations is just noise; ...
2
2016-07-22T19:59:00Z
[ "python", "python-3.x" ]
python-plotly-boxplot Why not showing the max and minimum value on graph
38,534,310
<p>This is my data:[0, 45, 47, 46, 47,47,43,100]. And picture looks like this: <a href="https://plot.ly/~zfrancica/8/" rel="nofollow">https://plot.ly/~zfrancica/8/</a></p> <p>I want to have a picture like this: <a href="https://plot.ly/~zfrancica/9/" rel="nofollow">https://plot.ly/~zfrancica/9/</a> (an out come pictur...
1
2016-07-22T19:52:02Z
39,922,298
<h3>Credentials</h3> <p>For those who don't know how to save credentials permanently;</p> <pre><code>import plotly.tools as tls tls.set_credentials_file(username='username', api_key='api-key') </code></pre> <p>Assuming you have already saved your credentials;</p> <h3>A - Simple Solution</h3> <p>For a single one di...
0
2016-10-07T16:48:20Z
[ "python", "matplotlib", "plot", "boxplot", "plotly" ]
Tensorflow Mac GPU pywrap_tensorflow ignored in restricted program
38,534,364
<p>When running <code>python -c "import tensorflow"</code> after following tensorflow's Mac GPU installation instructions and building the package from source, I'm getting </p> <pre><code>dyld: warning, LC_RPATH $ORIGIN/../../_solib_darwin/_U_S_Sthird_Uparty_Sgpus_Scuda_Ccudart___Uthird_Uparty_Sgpus_Scuda_Slib in /Lib...
2
2016-07-22T19:56:06Z
38,535,656
<p>Have you tried v 0.9 ? <code>sudo pip install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.9.0rc0-py2-none-any.whl</code></p>
1
2016-07-22T21:42:29Z
[ "python", "osx", "tensorflow", "nvidia", "dyld" ]