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 |
|---|---|---|---|---|---|---|---|---|---|
send 2Dimensional Listarray From Raspberry pi to the Arduino with I2c protocol | 39,449,076 | <p>im working on Computer vision (opencv )python and i had a result from the image , so this results is 2D List-arrays that should go to the Arduino by i2c buffer , so i realized that there is a library called smbus that interfacing the Raspberry pi with i2c ports so send and receive data , So i searched on References ... | 0 | 2016-09-12T11:15:14Z | 39,478,707 | <p>Check <a href="https://github.com/carlos-jenkins/smart-lights/tree/master/semaphore/chip/drivers/python/grid_io" rel="nofollow">this repository</a>. We connected a NTC CHIP to a Adafruit Trinket using I2C, but connecting the PI with the an Arduino should be very much the same.</p>
<p>The key file is the <a href="ht... | 0 | 2016-09-13T20:45:00Z | [
"python",
"opencv",
"raspbian",
"i2c",
"smbus"
] |
Numpy computes wrong eigeinvectors | 39,449,091 | <p>I was computing the eigenvectors of a matrix using numpy and I was getting some weird results. Then I decided to use Matlab and everything was fine.</p>
<pre><code>L = np.array(([2,-1,-1],[-1,2,-1],[-1,-1,2]))
Lam,U = np.linalg.eig(L) #compute eigenvalues and vectors
#sort by ascending eigenvalues
I = [i[0] for i i... | 1 | 2016-09-12T11:16:16Z | 39,449,374 | <p>While it is true that there is an orthonormal basis of eigenvectors of a symmetrical matrix, there is no guarantee that Numpy will return that basis. It will return <em>any</em> basis of eigenvectors, and there is nothing wrong about this approach.</p>
<p>The matrix you are looking at has two eigenspaces: A two-di... | 5 | 2016-09-12T11:33:59Z | [
"python",
"matlab",
"numpy"
] |
Numpy computes wrong eigeinvectors | 39,449,091 | <p>I was computing the eigenvectors of a matrix using numpy and I was getting some weird results. Then I decided to use Matlab and everything was fine.</p>
<pre><code>L = np.array(([2,-1,-1],[-1,2,-1],[-1,-1,2]))
Lam,U = np.linalg.eig(L) #compute eigenvalues and vectors
#sort by ascending eigenvalues
I = [i[0] for i i... | 1 | 2016-09-12T11:16:16Z | 39,449,777 | <p>I think the problem is that your matrix is NOT reversible</p>
<pre><code>np.linalg.det(L) # Return 0
Lam # Return [3, 3, 0]
</code></pre>
<p>So:</p>
<pre><code>det(L * U) = det(L) * det(U) = 0 != det(I) = 1
</code></pre>
| -2 | 2016-09-12T11:56:36Z | [
"python",
"matlab",
"numpy"
] |
explode pandas dataframe by unique elements in columns (strings) and create contingency table? | 39,449,235 | <p>I have a pandas dataframe that I would like to do some analysis on, it looks like this:</p>
<pre><code>from pandas import DataFrame
a = DataFrame([{'var1': 'K802', 'var2': 'No Concatenation', 'var3':'73410'},
{'var1': 'O342,O820,Z370', 'var2': '59514,01968', 'var3':'146010'},
{'var1': 'Z094', '... | 2 | 2016-09-12T11:24:23Z | 39,449,569 | <p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.get_dummies.html" rel="nofollow"><code>get_dummies</code></a> method defined on pd.Series. It is more straightforward to use than <code>pd.get_dummies</code> function for this use case. You can then use pd.concat to comb... | 3 | 2016-09-12T11:45:02Z | [
"python",
"pandas",
"join",
"split"
] |
Completing a curve using a function | 39,449,251 | <p>I have developed a model in Python to simulate something physical. This model outputs angular velocity over a distance range. For various reasons the model does not give results for small distance values, but it has been suggested to me that I complete the curve using a function which we believe approximates the sm... | -2 | 2016-09-12T11:26:03Z | 39,449,316 | <p>You can make a piecewise function. For example if you know that your angular velocity function is valid for <code>r > 10</code>, then you could do something like</p>
<pre><code>def angular_velocity(r):
if r > 10:
your_analytical_function(r)
else:
some_alternative_for_small_distance(r)
... | 1 | 2016-09-12T11:30:29Z | [
"python",
"plot",
"model"
] |
Resize without changing the structure of the image | 39,449,259 | <p>I have an image here (DMM_a01_s01_e01_sdepth.PNG, it is basically a human depth map or something, I don't really know the details :( ):</p>
<p><a href="http://i.stack.imgur.com/2Ux3i.png" rel="nofollow"><img src="http://i.stack.imgur.com/2Ux3i.png" alt="DMM_a01_s01_e01_sdepth.PNG"></a></p>
<p>It's very small (54x1... | 0 | 2016-09-12T11:26:32Z | 39,449,474 | <p>What you are asking for is impossible. Resizing of image is a destructive operation. You have 54x102 pixels (5508 pixels of data) and you are trying to fit that amount of data into a 20x20 image - that's just 400 pixels! You'll always lose some detail, structure etc. based on the algorithm you used - in this case sc... | 0 | 2016-09-12T11:40:07Z | [
"python",
"image-processing"
] |
Django: Database Model For Prize Structure | 39,449,331 | <p>I'm trying to figure out the proper way to go about structuring a model for a contest's payout/prize structure, an example is below</p>
<p>1st: $50000
2nd: $10000
3rd-10th: $1000
10th-70th: $500
70th-150th: $25
150th-400th: $1</p>
<p>My first thought was to design it like this:</p>
<pre><code>class Prize(models.M... | -1 | 2016-09-12T11:31:11Z | 39,449,397 | <p>First of all, never use integers to store prices. Always try to use decimal field. If you have never tried it, there is a thing to notice. You have to supply max_digits and decimal_places. For example:</p>
<pre><code>prize = forms.DecimalField(max_digits=10, decimal_places=2)
</code></pre>
<p>So you can only use 8... | 0 | 2016-09-12T11:35:53Z | [
"python",
"django",
"django-models"
] |
16-bit color images with pyinsane | 39,449,350 | <p>pyinsane's scan sessions return a list of 8-bit PIL images by default. This is true, even when the scan has been done in 16-bit mode (for instance using the transparency unit). Is there any way to get 16-bit images (I suppose PIL does not support that) or the original raw data out of pyinsane?</p>
<p>Here is the sa... | 0 | 2016-09-12T11:32:14Z | 39,920,000 | <p>You're right, this is a limitation from Pillow (PIL). You can actually see the conversion from raw to PIL Image here : <a href="https://github.com/jflesch/pyinsane/blob/stable/src/pyinsane2/sane/abstract.py#L161" rel="nofollow">https://github.com/jflesch/pyinsane/blob/stable/src/pyinsane2/sane/abstract.py#L161</a></... | 0 | 2016-10-07T14:44:25Z | [
"python",
"pillow",
"scanning",
"pyinsane"
] |
How do I replace values in 2D numpy array using a dictionary of {value:(row#,column#)} pairs | 39,449,394 | <pre><code> import numpy as np
</code></pre>
<p>the array looks like so:</p>
<pre><code> array = np.zeros((10,10))
array =
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.... | 0 | 2016-09-12T11:35:46Z | 39,449,633 | <p>I hope I understood your question correctly</p>
<pre><code>array = np.zeros((10,10))
data = {72: (3, 4), 11: (1, 5), 10: (2, 4), 43: (2, 3), 22: (24,35)}
for i in data.keys():
try:
array[data[i][0],data[i][1]] = float(i)
except IndexError:
pass
print array
</code></pre>
<p>I changed the ind... | 3 | 2016-09-12T11:48:49Z | [
"python",
"numpy",
"dictionary"
] |
How do I replace values in 2D numpy array using a dictionary of {value:(row#,column#)} pairs | 39,449,394 | <pre><code> import numpy as np
</code></pre>
<p>the array looks like so:</p>
<pre><code> array = np.zeros((10,10))
array =
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0.... | 0 | 2016-09-12T11:35:46Z | 39,450,333 | <p>We need to invert mapping from values=>coordinates to co-ordinates=>values before replacement in the array. I have edited the dictionary entries for demo purpose and as pointed in comments, dictionary co-ordinate entries should be less than dimensions of array</p>
<pre><code>import numpy as np
arrObj = np.zeros(... | 1 | 2016-09-12T12:27:34Z | [
"python",
"numpy",
"dictionary"
] |
PyQt, How to change BoxLayout's weight (size) | 39,449,531 | <p>I have a Gui layout as in the picture.
<a href="http://i.stack.imgur.com/hFAR1.png" rel="nofollow"><img src="http://i.stack.imgur.com/hFAR1.png" alt="enter image description here"></a></p>
<p>So currently Sublayout1 and Sublayout2 are equal in size. However I want to make Sublayout1's width smaller and stretch Sub... | 0 | 2016-09-12T11:42:50Z | 39,449,710 | <p>Use the <code>stretch</code> parameter passed to <a href="http://doc.qt.io/qt-5/qboxlayout.html#addLayout" rel="nofollow"><code>QBoxLayout::addLayout</code></a></p>
<pre><code>sublayout1 = QtGui.QVBoxLayout()
sublayout2 = QtGui.QVBoxLayout()
plotBox = QtGui.QHBoxLayout()
plotBox.addLayout(sublayout1, 1)
plotBox.add... | 2 | 2016-09-12T11:53:05Z | [
"python",
"qt",
"pyqt"
] |
python SyntaxError: invalid syntax %matplotlib inline | 39,449,549 | <p>I got this error in my python script:</p>
<pre><code>%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from utils import progress_bar_downloader
import os
#Hosting files on my dropbox since downloading from google code is painful
#Original project hosting is here: https://code.google.com/p/hmm-... | 1 | 2016-09-12T11:43:51Z | 39,449,602 | <p>"%matplotlib inline" isn't valid python code, so you can't put it in a script.</p>
<p>I assume you're using a Jupyter notebook? If so, put it in the first cell and all should work.</p>
| 1 | 2016-09-12T11:47:33Z | [
"python"
] |
python SyntaxError: invalid syntax %matplotlib inline | 39,449,549 | <p>I got this error in my python script:</p>
<pre><code>%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from utils import progress_bar_downloader
import os
#Hosting files on my dropbox since downloading from google code is painful
#Original project hosting is here: https://code.google.com/p/hmm-... | 1 | 2016-09-12T11:43:51Z | 39,449,990 | <p>if you are not using Jupyter IPython notebook, just comment out (or delete) the line, everything will work fine and a separate plot window will be opened if you are running your python script from the console. </p>
<p>if you are not using Jupyter IPython notebook, the very first python code cell in your notebook sh... | 0 | 2016-09-12T12:09:56Z | [
"python"
] |
Using Google Maps API with custom tiles | 39,449,597 | <p>So, basic gist is, I have my own tiles of not the real world I'd like to display with the Google Maps viewer. I've found examples of how to split an existing single image into tiles for use with it, but nothing that deals with setting up your own tiler.</p>
<p>I have map data such as this:
<a href="https://dl.dropb... | 0 | 2016-09-12T11:47:09Z | 39,449,979 | <p>I think what you are looking for is the google maps imageMapTypes:</p>
<p><a href="https://developers.google.com/maps/documentation/javascript/maptypes#ImageMapTypes" rel="nofollow">https://developers.google.com/maps/documentation/javascript/maptypes#ImageMapTypes</a></p>
| 0 | 2016-09-12T12:09:32Z | [
"javascript",
"python",
"html",
"google-maps"
] |
Using Google Maps API with custom tiles | 39,449,597 | <p>So, basic gist is, I have my own tiles of not the real world I'd like to display with the Google Maps viewer. I've found examples of how to split an existing single image into tiles for use with it, but nothing that deals with setting up your own tiler.</p>
<p>I have map data such as this:
<a href="https://dl.dropb... | 0 | 2016-09-12T11:47:09Z | 39,516,370 | <p>Basically, each zoom level is the 4 lower zoom tiles combined. A Projection function can be skipped to get orthogonal mapping.</p>
| 0 | 2016-09-15T16:46:53Z | [
"javascript",
"python",
"html",
"google-maps"
] |
Can't get all names with selenium from Facebook - Python 3 | 39,449,705 | <p>i'm creating a scraper using python and selenium to improve my ability with python.
I'm having trouble with selecting certain elements.</p>
<p>On facebook i'm trying to scrape the list of someone friends.
This is the piece of code i wrote</p>
<pre><code>nomifb = driver.find_elements_by_xpath("//div[@class='fsl fw... | 0 | 2016-09-12T11:52:49Z | 39,726,176 | <p>you can try by element name
<code>element = driver.find_element_by_name("name of tag")</code></p>
| 0 | 2016-09-27T13:37:26Z | [
"python",
"facebook",
"python-3.x",
"selenium",
"screen-scraping"
] |
Python: modul not found after Anaconda installation | 39,449,725 | <p>I've successfully installed Python 2.7 and Anaconda but when i try to import a library i get always this error:</p>
<pre><code>>>> import scipy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<p>I've set up the <code>PYTHO... | 0 | 2016-09-12T11:53:31Z | 39,449,767 | <p>Try to install <code>scipy</code> again with:</p>
<pre><code>conda install numpy scipy
</code></pre>
| 0 | 2016-09-12T11:56:07Z | [
"python",
"windows",
"python-2.7",
"anaconda"
] |
Python: modul not found after Anaconda installation | 39,449,725 | <p>I've successfully installed Python 2.7 and Anaconda but when i try to import a library i get always this error:</p>
<pre><code>>>> import scipy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<p>I've set up the <code>PYTHO... | 0 | 2016-09-12T11:53:31Z | 39,450,523 | <p>As pointed out by @Mr.F the error was given by the presence of the <code>PYTHONPATH</code> and <code>PYTHONHOME</code>. Deleting them i was able to use the Anaconda version of python.</p>
| 0 | 2016-09-12T12:37:53Z | [
"python",
"windows",
"python-2.7",
"anaconda"
] |
Python: modul not found after Anaconda installation | 39,449,725 | <p>I've successfully installed Python 2.7 and Anaconda but when i try to import a library i get always this error:</p>
<pre><code>>>> import scipy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
</code></pre>
<p>I've set up the <code>PYTHO... | 0 | 2016-09-12T11:53:31Z | 39,469,995 | <p>The problem is that you should not have either <code>PYTHONPATH</code> or <code>PYTHONHOME</code> set. They are both pointing to a non-Continuum version of Anaconda, I believe. Anaconda will install (by default) into a directory called <code>Anaconda</code>, either at <code>C:\Anaconda</code> or at <code>C:\Users\... | 0 | 2016-09-13T12:22:43Z | [
"python",
"windows",
"python-2.7",
"anaconda"
] |
aiohttp: how-to retrieve the data (body) in aiohttp server from requests.get | 39,449,739 | <p>Could you please advise on the following?</p>
<p>On the localhost:8900 there is aiohttp server running</p>
<p>when i do a request like (using the python2 module requests) from python
<code>
requests.get("http://127.0.01:8900/api/bgp/show-route", data={'topo':"switzerland", 'pop':"zrh", 'prefix':"1.1.1.1/32"})
</co... | 2 | 2016-09-12T11:54:16Z | 39,452,219 | <p>ahh the <code>data</code> part is accessed like that </p>
<pre><code>await request.json()
</code></pre>
<p>You can find this in official <a href="http://aiohttp.readthedocs.io/en/stable/web_reference.html#aiohttp.web.Request.json" rel="nofollow">aiohttp docs</a></p>
| 3 | 2016-09-12T14:03:47Z | [
"python",
"rest",
"python-3.x",
"aiohttp"
] |
Reusing Mock to create attribute mocks unittest.patch | 39,449,844 | <pre><code>from unittest.mock import patch
class A:
def b(self):
return 'HAHAHA A'
a = A()
with patch('__main__.A') as a_mock:
a_mock.b.return_value = 'not working'
print(a.b())
HAHAHA A
>>>
</code></pre>
<p>Why doesn't it print <code>'not working'</code>? What for is a_mock, then? ___... | 0 | 2016-09-12T12:00:09Z | 39,449,878 | <p>You replaced the <em>whole class</em> with your patch, not the method on the existing class. <code>a = A()</code> created an instance of <code>A</code> before you replaced the class, so <code>a.__class__</code> still references the actual class, not the mock.</p>
<p>Mocking can only ever replace one reference at a ... | 2 | 2016-09-12T12:02:47Z | [
"python",
"mocking",
"python-unittest"
] |
Reusing Mock to create attribute mocks unittest.patch | 39,449,844 | <pre><code>from unittest.mock import patch
class A:
def b(self):
return 'HAHAHA A'
a = A()
with patch('__main__.A') as a_mock:
a_mock.b.return_value = 'not working'
print(a.b())
HAHAHA A
>>>
</code></pre>
<p>Why doesn't it print <code>'not working'</code>? What for is a_mock, then? ___... | 0 | 2016-09-12T12:00:09Z | 39,449,998 | <p>You may want to patch your instance instead of your class:</p>
<pre><code>with patch('__main__.a') as a_mock:
a_mock.b.return_value = 'works perfectly ;)'
print(a.b())
</code></pre>
| 0 | 2016-09-12T12:10:08Z | [
"python",
"mocking",
"python-unittest"
] |
optimization & numpy vectorization: repeat set of arrays | 39,449,853 | <p>I am getting used to the awesomness of <code>numpy.apply_along_axis</code> and I was wondering whether I could take the vectorization to the next level - mainly for speed purposes, that is using the potential of the function by trying to eliminate the for loop I have in the code below. </p>
<pre><code>from pandas i... | 0 | 2016-09-12T12:00:43Z | 39,457,518 | <pre><code>def foo(x):
print(x) # add for diagnosis
return [x[0].prod(), x[1].sum()]
</code></pre>
<p>You apply it to a 3d array, which for simplicity I'll use:</p>
<pre><code>In [64]: x=np.arange(2*3*2).reshape(2,3,2)
In [66]: np.apply_along_axis(foo,0,x)
[0 6]
[1 7]
[2 8]
[3 9]
[ 4 10]
[ 5 11]
Out[66]:
arr... | 0 | 2016-09-12T19:34:09Z | [
"python",
"arrays",
"numpy",
"vectorization"
] |
Manual implementation of a Support Vector Machine | 39,449,904 | <p>I am wondering is there any article where SVM (Support Vector Machine) is implemented manually in R or Python.</p>
<p>I do <strong>not</strong> want to use a built-in function or package. ?</p>
<p>The example could be very simple in terms of feature space and linear separable. </p>
<p>I just want to go through th... | -1 | 2016-09-12T12:04:36Z | 39,498,571 | <p>The answer to this question is rather broad since there are several possible algorithms in order to train SVMs. Also packages like LibSVM (available both for Python and R) are open-source so you are free to check the code inside.</p>
<p>Hereinafter I will consider the Sequential Minimal Optimization (SMO) algorithm... | 0 | 2016-09-14T19:50:11Z | [
"python",
"svm"
] |
Segmentation fault: 11 when trying to run Pygame | 39,449,909 | <p>I am using OSX 10.11.6, Python 2.17.12 and Pygame 1.9.1.
I made this simple program that should display a black rectangle in the middle of a white field. However, when I try to run it I get an error saying:</p>
<pre><code>Segmentation fault: 11
</code></pre>
<p>I have tried several things, but nothing seems to wor... | 0 | 2016-09-12T12:04:56Z | 39,719,491 | <p>This is due to a flaw in the built-in SDL library that Pygame depends on. Pygame can create a screen, but attempting to touch it will immediately crash it with Segmentation error 11.</p>
<p>From the official SDL website, go to <a href="https://www.libsdl.org/download-1.2.php" rel="nofollow">the download page</a> an... | 0 | 2016-09-27T08:13:52Z | [
"python",
"terminal",
"pygame"
] |
numpy apply_over_axes forcing keepdims=True? | 39,449,926 | <p>I have the following code </p>
<pre><code>import numpy as np
import sys
def barycenter( arr, axis=0 ) :
bc = np.mean( arr, axis, keepdims=False )
print( "src shape:", arr.shape, ", **** trg shape:", bc.shape, "****" )
sys.stdout.flush()
return bc
a = np.array([[[0.1, 0.2, 0.3], [0.2, 0.3, 0.4]],
... | 0 | 2016-09-12T12:05:51Z | 39,450,318 | <p>The result follows directly from the doc:</p>
<blockquote>
<p>func is called as res = func(a, axis), where axis is the first element
of axes. The result res of the function call must have either the same
dimensions as a or one less dimension. If res has one less dimension
than a, a dimension is inserted bef... | 1 | 2016-09-12T12:26:59Z | [
"python",
"numpy"
] |
python unittest.TestCase.assertRaises not working | 39,450,098 | <p>I'm trying to run tests on my 'add' function in Python but it is giving an error :</p>
<pre><code>7
E
======================================================================
ERROR: test_upper (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent ca... | 2 | 2016-09-12T12:16:12Z | 39,450,218 | <p>As the error message is telling you, your <em>assert raises</em> object has no attribute <code>exception</code>. To be more specific, this call: </p>
<pre><code>cm.exception.message
</code></pre>
<p><code>cm</code> is your assert object in this case, and because the code you are testing never actually raises, your... | 4 | 2016-09-12T12:22:14Z | [
"python",
"pycharm"
] |
Looping over widgets inside widgets inside layouts | 39,450,141 | <p>Similar question to what we have here <a href="http://stackoverflow.com/questions/5150182/loop-over-widgets-in-pyqt-layout">Loop over widgets in PyQt Layout</a> but a bit more complex...</p>
<p>I have</p>
<pre><code>QVGridLayout
QGroupBox
QGridLayout
QLineEdit
</code></pre>
<p>I'd like to access... | 0 | 2016-09-12T12:18:29Z | 39,453,020 | <p>Sorted :</p>
<pre><code>for i in range(self.GridLayout.count()):
item = self.GridLayout.itemAt(i)
if type(item.widget()) == QGroupBox:
child = item.widget().children()
</code></pre>
<p>I had to use item.widget() to get access to GroupBox.
Hope this helps some1. </p>
| 0 | 2016-09-12T14:45:09Z | [
"python",
"pyqt",
"qgroupbox"
] |
Looping over widgets inside widgets inside layouts | 39,450,141 | <p>Similar question to what we have here <a href="http://stackoverflow.com/questions/5150182/loop-over-widgets-in-pyqt-layout">Loop over widgets in PyQt Layout</a> but a bit more complex...</p>
<p>I have</p>
<pre><code>QVGridLayout
QGroupBox
QGridLayout
QLineEdit
</code></pre>
<p>I'd like to access... | 0 | 2016-09-12T12:18:29Z | 39,475,208 | <p>When a widget is added to a layout, it automatically becomes a child of the widget the layout it is set on. So the example reduces to a two-liner:</p>
<pre><code>for group in self.GridLayout.parentWidget().findChildren(QGroupBox):
for edit in group.findChildren(QLineEdit):
# do stuff with edit
</code></... | 1 | 2016-09-13T16:49:37Z | [
"python",
"pyqt",
"qgroupbox"
] |
Passing Django Model to Template | 39,450,186 | <p>I have a little problem which I can't seem to get my head around. It seems like a very trivial thing but I just can't figure it out. Essentially what I'm trying to do is to create a <code>Project</code> model which holds information on a certain project and then have another model called <code>Link</code> which hold... | 1 | 2016-09-12T12:20:39Z | 39,450,279 | <p>Inside your template <code>projects.html</code> you should be able to loop over the Links for each project with</p>
<pre><code>{% for project in projects %}
{% for link in project.link_set.all %}
{{ link }}
{% endfor %}
{% endfor %}
</code></pre>
| 1 | 2016-09-12T12:24:55Z | [
"python",
"django",
"django-models"
] |
Passing Django Model to Template | 39,450,186 | <p>I have a little problem which I can't seem to get my head around. It seems like a very trivial thing but I just can't figure it out. Essentially what I'm trying to do is to create a <code>Project</code> model which holds information on a certain project and then have another model called <code>Link</code> which hold... | 1 | 2016-09-12T12:20:39Z | 39,450,352 | <p>You really should do the tutorial. </p>
<pre><code>for project in projects:
for link in project.link_set.all:
<...>
</code></pre>
<p>Add a <code>related_name="links"</code> to your foreign key, and the inner loop can be</p>
<pre><code>for link in project.links:
</code></pre>
| 0 | 2016-09-12T12:28:55Z | [
"python",
"django",
"django-models"
] |
Efficiently read/shift out-of-range datetimes using pandas | 39,450,309 | <p>so I have a dataset (a bunch of csv files) which contains (anonymized) datetimes in the following form:</p>
<blockquote>
<p>3202-11-11 14:51:00 EST</p>
</blockquote>
<p>The dates have been shifted by some random time for each entity. So differences in time for a given entity are still meaningful.</p>
<p>When tr... | 1 | 2016-09-12T12:26:33Z | 39,450,551 | <p>One thing you could do is to work on this at the string level, deducting some number of years (in the following, 1200):</p>
<pre><code>s = '3202-11-11 14:51:00 EST'
>>> In [21]: pd.to_datetime(str(int(s[: 4]) - 1200) + s[4: ])
Out[21]: Timestamp('2002-11-11 14:51:00')
</code></pre>
<p>You can also vector... | 0 | 2016-09-12T12:39:55Z | [
"python",
"datetime",
"pandas"
] |
Efficiently read/shift out-of-range datetimes using pandas | 39,450,309 | <p>so I have a dataset (a bunch of csv files) which contains (anonymized) datetimes in the following form:</p>
<blockquote>
<p>3202-11-11 14:51:00 EST</p>
</blockquote>
<p>The dates have been shifted by some random time for each entity. So differences in time for a given entity are still meaningful.</p>
<p>When tr... | 1 | 2016-09-12T12:26:33Z | 39,451,384 | <p>The pandas datetime object uses a 64-bit integer to represent time, and since it has nanosecond resolution, the upper limitation stops at <code>2262-04-11</code>, referenced <a href="http://pandas-docs.github.io/pandas-docs-travis/timeseries.html#timeseries-timestamp-limits" rel="nofollow">here</a>.</p>
<p>I'm not ... | 0 | 2016-09-12T13:23:07Z | [
"python",
"datetime",
"pandas"
] |
Weird for loop in python 2.7 | 39,450,444 | <p>I have a codewars problem and i'm new to python (less than 24hrs using it).
I'm solving the diamond problem:</p>
<blockquote>
<p>Task:</p>
<p>You need to a string that when printed, displays a diamond shape on
the screen using asterisk ("*") characters. Please see provided test
cases for exact output for... | -1 | 2016-09-12T12:33:43Z | 39,450,624 | <p>You have </p>
<pre><code>retorno = " *\n"
</code></pre>
<p>and append to it after first iteration(i = 3):</p>
<pre><code>retorno = " *\n***" # printed
# *
#***
</code></pre>
<p>No newline was appended.
After second iteration (i = 1):</p>
<pre><code>retorno = " *\n****" # printed
# *
#****
</code></pre>
<... | 2 | 2016-09-12T12:44:02Z | [
"python",
"python-2.7",
"for-loop"
] |
Weird for loop in python 2.7 | 39,450,444 | <p>I have a codewars problem and i'm new to python (less than 24hrs using it).
I'm solving the diamond problem:</p>
<blockquote>
<p>Task:</p>
<p>You need to a string that when printed, displays a diamond shape on
the screen using asterisk ("*") characters. Please see provided test
cases for exact output for... | -1 | 2016-09-12T12:33:43Z | 39,450,635 | <p>It isn't repeating. It starts life as *\n, the first time through the loop you add '***' so it becomes *\n***, the next time, you add '*' so it becomes *\n****, thus the output:</p>
<pre><code>*
***
*
****
</code></pre>
<p>Note also that n%3 is not the way to test for odd numbers, you want n%2==1.</p>
| 1 | 2016-09-12T12:44:35Z | [
"python",
"python-2.7",
"for-loop"
] |
Weird for loop in python 2.7 | 39,450,444 | <p>I have a codewars problem and i'm new to python (less than 24hrs using it).
I'm solving the diamond problem:</p>
<blockquote>
<p>Task:</p>
<p>You need to a string that when printed, displays a diamond shape on
the screen using asterisk ("*") characters. Please see provided test
cases for exact output for... | -1 | 2016-09-12T12:33:43Z | 39,450,679 | <p>Ok, let me explain you what exactly is happening in your script step by step:</p>
<p>That is your code with the "number of line":</p>
<pre><code>(1)def diamond(n):
(2) retorno = " *\n"
(3) if n%3 == 0:
(4) for i in range(n,0,-2):
(5) retorno += i * "*"
(6) print(retorno + str(i)... | 2 | 2016-09-12T12:47:05Z | [
"python",
"python-2.7",
"for-loop"
] |
Return name of column after comparing cummulative sum with random drawn number | 39,450,527 | <p>I have a <code>DataFrame</code> in which the sum of the columns is <code>1</code>, like so:</p>
<pre><code>Out[]:
cod_mun ws_1 1_3 4 5_7 8 9_10 11 12 13 14 15 nd
1100015 0.1379 0.273 0.2199 0.1816 0.0566 0.0447 0.0617 0.0015 0 0.0021 0.0074 0.0137
1100023... | 1 | 2016-09-12T12:38:05Z | 39,450,618 | <p>I think you can count <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.cumsum.html" rel="nofollow"><code>DataFrame.cumsum</code></a>, compare with <code>prob</code> and get first column with <code>True</code> value by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/panda... | 4 | 2016-09-12T12:43:50Z | [
"python",
"pandas",
"random"
] |
Python: split list into indices based on consecutive identical values | 39,450,575 | <p>If you could advice me how to write the script to split list by number of values I mean: </p>
<pre><code>my_list =[11,11,11,11,12,12,15,15,15,15,15,15,20,20,20]
</code></pre>
<p>And there are 11-4,12-2,15-6,20-3 items.
So in next list for exsample range(0:100)
I have to split on 4,2,6,3 parts
So I counted same... | 2 | 2016-09-12T12:41:07Z | 39,450,720 | <p>You can use <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>, <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>, and <a href="https://docs.python.org/2/library/operator.html" rel... | 3 | 2016-09-12T12:49:14Z | [
"python",
"list",
"split"
] |
Python: split list into indices based on consecutive identical values | 39,450,575 | <p>If you could advice me how to write the script to split list by number of values I mean: </p>
<pre><code>my_list =[11,11,11,11,12,12,15,15,15,15,15,15,20,20,20]
</code></pre>
<p>And there are 11-4,12-2,15-6,20-3 items.
So in next list for exsample range(0:100)
I have to split on 4,2,6,3 parts
So I counted same... | 2 | 2016-09-12T12:41:07Z | 39,452,018 | <p>Solution in Python 3 , If you are only using <code>counter</code> :</p>
<pre><code>from collections import Counter
my_list =[11,11,11,11,12,12,15,15,15,15,15,15,20,20,20]
count = Counter(my_list)
div= list(count.keys()) # take only keys
div.sort()
l = []
num = 0
for i in div:
t = []
for j in range(... | 1 | 2016-09-12T13:55:12Z | [
"python",
"list",
"split"
] |
for loop questions python matching excel | 39,450,609 | <p>I am trying to go through an entire row of cells and compare it to the row of cells on another excel sheet. i have figured it out so that it reads from the sheet, but there must be something wrong with my for loops and if statements. what i am doing is assigning the first cell and then comparing it to the first cell... | 0 | 2016-09-12T12:43:26Z | 39,451,714 | <p>Second iteration is the one that is making the error. Just try this:</p>
<pre><code>for row in range(sheet.nrows):
cell = str(sheet.cell_value(row, 0))
windcell = str(windc_sheet.cell_value(row, 0))
if cell == windcell:
outputsheet.write(row, 1, ' ')
else:
sixdig = cell[0:6]
six... | 0 | 2016-09-12T13:40:02Z | [
"python",
"excel",
"for-loop"
] |
Setting up sockets with Django on gninx | 39,450,642 | <p>I have a Django application running on nginx. This application use sockets, which (as far as I know) should be proxied. So I have troubles configuring nginx and other stuff. Same application works fine on Apache/2.4.7, so I assume that it is not a programming mistake.</p>
<p>Sockets using is based on Django-Channel... | 0 | 2016-09-12T12:45:03Z | 39,451,790 | <p>First of all, do not ever try to create sock manually.
Just set up a path, and it will be created automatically. </p>
<p>This is example nginx and uwsgi conf:</p>
<pre><code>server {
root /your/djang/app/main/folder/;
# the port your site will be served on
listen 80;
server_name your-domain.com *.your-domai... | 0 | 2016-09-12T13:43:11Z | [
"python",
"django",
"sockets",
"nginx",
"redis"
] |
Python csv reader // how to ignore enclosing char (because sometimes it's missing) | 39,450,667 | <p>I am trying to import csv data from files where sometimes the enclosing char " is missing.</p>
<p>So I have rows like this:</p>
<pre><code>"ThinkPad";"2000.00";"EUR"
"MacBookPro";"2200.00;EUR"
# In the second row the closing " after 2200.00 is missing
# also the closing " before EUR" is missing
</code></pre>
<p... | 0 | 2016-09-12T12:46:43Z | 39,450,927 | <p>If you're looping through all the lines/rows of the file, you can use string's .replace() function to get rid off the quotes (if you don't need them later-on for other purposes.).</p>
<pre><code>>>> import csv
>>> with open('eggs.csv', 'rb') as csvfile:
... my_file = csv.reader(codecs.open(fil... | 0 | 2016-09-12T13:00:33Z | [
"python",
"csv"
] |
Python csv reader // how to ignore enclosing char (because sometimes it's missing) | 39,450,667 | <p>I am trying to import csv data from files where sometimes the enclosing char " is missing.</p>
<p>So I have rows like this:</p>
<pre><code>"ThinkPad";"2000.00";"EUR"
"MacBookPro";"2200.00;EUR"
# In the second row the closing " after 2200.00 is missing
# also the closing " before EUR" is missing
</code></pre>
<p... | 0 | 2016-09-12T12:46:43Z | 39,451,085 | <p>This <em>might</em> work:</p>
<pre><code>import csv
import io
file = io.StringIO(u'''
"ThinkPad";"2000.00";"EUR"
"MacBookPro";"2200.00;EUR"
'''.strip())
reader = csv.reader((line.replace('"', '') for line in file), delimiter=';', quotechar='"')
for row in reader:
print(row)
</code></pre>
<p>The problem is th... | 0 | 2016-09-12T13:08:06Z | [
"python",
"csv"
] |
How to pass PIL image to Add_Picture in python-pptx | 39,450,718 | <p>I'm trying to get the image from clipboard and I want to add that image in python-pptx .
I don't want to save the image in the Disk.
I have tried this:</p>
<pre><code>from pptx import Presentation
from PIL import ImageGrab,Image
from pptx.util import Inches
im = ImageGrab.grabclipboard()
prs = Presentation()
titl... | 0 | 2016-09-12T12:49:02Z | 39,459,980 | <p>The image needs to be in the form of a stream (i.e. logical file) object. So you need to "save" it to a memory file first, probably StringIO is what you're looking for.</p>
<p><a href="http://stackoverflow.com/questions/646286/python-pil-how-to-write-png-image-to-string">This other question</a> provides some of the... | 0 | 2016-09-12T23:03:35Z | [
"python",
"python-imaging-library",
"python-pptx"
] |
Save and restore in CNN | 39,450,721 | <p>i am beginner in tensorflow and i have one question related to save and restore checkpoint in Convolutional neural networks. I am trying to create CNN to classify faces. My question is:</p>
<p>If is it possible when i add new class in my dataset to make partial training? So i just want to retrain the new class inst... | 0 | 2016-09-12T12:49:16Z | 39,450,900 | <p>Sure. You can use the var_list parameter in tf.train.Optimizer.minimize() to control the weights you want to optimize. If you don't include the variables you restored (or currently have trained,) they shouldn't get changed.</p>
| 0 | 2016-09-12T12:59:00Z | [
"python",
"python-2.7",
"tensorflow",
"conv-neural-network"
] |
Save and restore in CNN | 39,450,721 | <p>i am beginner in tensorflow and i have one question related to save and restore checkpoint in Convolutional neural networks. I am trying to create CNN to classify faces. My question is:</p>
<p>If is it possible when i add new class in my dataset to make partial training? So i just want to retrain the new class inst... | 0 | 2016-09-12T12:49:16Z | 39,479,531 | <p>Your question has multiple facets. Let's look at each in detail:</p>
<ul>
<li><p><strong>Is it possible to restore the weights and bias from previous training?</strong> Yes. You can create a <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/state_ops.html#Saver" rel="nofollow"><code>tf.train.Saver<... | 0 | 2016-09-13T21:50:12Z | [
"python",
"python-2.7",
"tensorflow",
"conv-neural-network"
] |
Insert row and col label when dumping matrix data to text file in python | 39,450,799 | <p>I want to insert labels to col and row. like below.</p>
<pre><code> x y z
a 1 3 4
b 4 3 2
</code></pre>
<p>Actually I could do to add header like below.</p>
<pre><code>import numpy as np
row_label = ["a", "b"]
col_label = ["x", "y", "z"]
data = np.array([[1,3,4], [4,3,2]])
np.savetxt("out.csv",... | 1 | 2016-09-12T12:54:01Z | 39,452,254 | <pre><code>import numpy as np
import pandas as pd
row_label = ["a", "b"]
col_label = ["x", "y", "z"]
data = np.array([[1,3,4], [4,3,2]])
df = pd.DataFrame(data, index=row_label, columns=col_label)
df.to_csv(r'temp.csv', sep='\t')
</code></pre>
<p>temp.csv</p>
<pre><code> x y z
a 1 3 4
b 4 3 2
</cod... | 1 | 2016-09-12T14:05:15Z | [
"python",
"numpy"
] |
Control flux in python if/elif continue | 39,450,887 | <p>I have a <code>if</code>/<code>elif</code> statement in Python, but I want to execute both commands next. I want to show <code>AD0</code> and <code>AD1</code> every second, but the code is just showing <code>AD1</code> (Not entering on <code>elif</code>).</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-... | 0 | 2016-09-12T12:58:21Z | 39,450,982 | <p>Python will pick the <em>first</em> matching condition out of a series of <code>if..elif..</code> tests, and will execute just that <em>one</em> block of code.</p>
<p>If your two tests should be <em>independent</em> and both should be considered, replace the <code>elif</code> block with a separate <code>if</code> s... | 0 | 2016-09-12T13:03:45Z | [
"python",
"if-statement"
] |
Apache Spark Count State Change | 39,450,896 | <p>I am new to Apache Spark (Pyspark) and would be glad to get some help resolving this problem. I am currently using Pyspark 1.6 (Had to ditch 2.0 since there is not MQTT support).</p>
<p>So, I have a data frame that has the following information,</p>
<pre><code>+----------+-----------+
| time|door_status|
+---... | 2 | 2016-09-12T12:58:47Z | 39,452,029 | <p>In this case, using accumulator should solve the issue.
Basically, you create three different accumulators for the three statuses.</p>
<pre><code>status_1 = sc.accumulator(0)
status_2 = sc.accumulator(0)
status_3 = sc.accumulator(0)
</code></pre>
<p>then you can do something like the following </p>
<pre... | 0 | 2016-09-12T13:55:33Z | [
"python",
"apache-spark",
"pyspark"
] |
Apache Spark Count State Change | 39,450,896 | <p>I am new to Apache Spark (Pyspark) and would be glad to get some help resolving this problem. I am currently using Pyspark 1.6 (Had to ditch 2.0 since there is not MQTT support).</p>
<p>So, I have a data frame that has the following information,</p>
<pre><code>+----------+-----------+
| time|door_status|
+---... | 2 | 2016-09-12T12:58:47Z | 39,453,568 | <p>There is no efficient method which can perform operation like this out-of-the-box. You could use window functions:</p>
<pre><code>from pyspark.sql.window import Window
from pyspark.sql.functions import col, lag
df = sc.parallelize([
(1473678846, 2), (1473678852, 1),
(1473679029, 3), (1473679039, 3),
(1... | 1 | 2016-09-12T15:13:24Z | [
"python",
"apache-spark",
"pyspark"
] |
Apache Spark Count State Change | 39,450,896 | <p>I am new to Apache Spark (Pyspark) and would be glad to get some help resolving this problem. I am currently using Pyspark 1.6 (Had to ditch 2.0 since there is not MQTT support).</p>
<p>So, I have a data frame that has the following information,</p>
<pre><code>+----------+-----------+
| time|door_status|
+---... | 2 | 2016-09-12T12:58:47Z | 39,464,578 | <p>You can try the following solution:</p>
<pre><code>import org.apache.spark.sql.expressions.Window
var data = Seq((1473678846, 2), (1473678852, 1), (1473679029, 3), (1473679039, 3), (1473679045, 2), (1473679055, 1),(1473779045, 1), (1474679055, 2), (1475679055, 1), (1476679055, 3)).toDF("time","door_status")
data.... | 0 | 2016-09-13T07:37:37Z | [
"python",
"apache-spark",
"pyspark"
] |
Apache Spark Count State Change | 39,450,896 | <p>I am new to Apache Spark (Pyspark) and would be glad to get some help resolving this problem. I am currently using Pyspark 1.6 (Had to ditch 2.0 since there is not MQTT support).</p>
<p>So, I have a data frame that has the following information,</p>
<pre><code>+----------+-----------+
| time|door_status|
+---... | 2 | 2016-09-12T12:58:47Z | 39,465,339 | <p>i tried it out in java, but actually it should also be possible in python by the dataframes API in a comparable way.</p>
<p>Doing the following:</p>
<ul>
<li>load your data as dataframe/dataset</li>
<li>register dataframe as temp table</li>
<li>execute this query: SELECT state, COUNT(*) FROM doorstates GROUP BY st... | 0 | 2016-09-13T08:21:23Z | [
"python",
"apache-spark",
"pyspark"
] |
Ensure the POST data is valid JSON | 39,451,002 | <p>I am developping a JSON API with Python Flask.<br>
What I want is to always return JSON, with a error message indicating any error that occured.</p>
<p>That API also only accept JSON data in the POST body, but Flask by default return a HTML error 400 if it can't read the data as JSON.</p>
<p>Preferably, I d also l... | 1 | 2016-09-12T13:04:36Z | 39,451,086 | <p>You can try to decode JSON object using python json library.
The main idea is to take plain request body and try to convert to JSON.E.g:</p>
<pre><code>import json
...
# somewhere in view
def view():
try:
json.loads(request.get_data())
except ValueError:
# not a JSON! return error
r... | 0 | 2016-09-12T13:08:10Z | [
"python",
"json",
"flask"
] |
Ensure the POST data is valid JSON | 39,451,002 | <p>I am developping a JSON API with Python Flask.<br>
What I want is to always return JSON, with a error message indicating any error that occured.</p>
<p>That API also only accept JSON data in the POST body, but Flask by default return a HTML error 400 if it can't read the data as JSON.</p>
<p>Preferably, I d also l... | 1 | 2016-09-12T13:04:36Z | 39,451,091 | <p>You have three options:</p>
<ul>
<li><p>Register a <a href="http://flask.pocoo.org/docs/0.11/patterns/errorpages/#error-handlers" rel="nofollow">custom error handler</a> for 400 errors on the API views. Have this error return JSON instead of HTML.</p></li>
<li><p>Set the <a href="https://flask.readthedocs.io/en/lat... | 4 | 2016-09-12T13:08:21Z | [
"python",
"json",
"flask"
] |
Ensure the POST data is valid JSON | 39,451,002 | <p>I am developping a JSON API with Python Flask.<br>
What I want is to always return JSON, with a error message indicating any error that occured.</p>
<p>That API also only accept JSON data in the POST body, but Flask by default return a HTML error 400 if it can't read the data as JSON.</p>
<p>Preferably, I d also l... | 1 | 2016-09-12T13:04:36Z | 39,452,642 | <p>Combining the options <code>force=True</code> and <code>silent=True</code> make the result of <code>request.get_json</code> be <code>None</code> if the data is not parsable, then a simple <code>if</code> allow you to check the parsing.</p>
<pre><code>from flask import Flask
from flask import request
@app.route('/f... | 0 | 2016-09-12T14:24:35Z | [
"python",
"json",
"flask"
] |
Dynamically change combobox size Python Tkinter | 39,451,019 | <p>In Python Tkinter is it possible to dynamically change the size of a <code>combobox</code> (the width of the entry widget) based on the length of the selected item?</p>
| 0 | 2016-09-12T13:05:13Z | 39,453,139 | <p>Is this what you are looking for:</p>
<pre><code>from tkinter import *
import ttk
root = Tk()
defaultCar = StringVar()
defaultCar.set("Mercedes Benz")
carList = ["BMW", "Lamborghini", "Honda"]
def resizeFunc():
newLen = len(cars.get())
cars.configure(width=newLen+2)
cars = ttk.Combobox(root,
... | 0 | 2016-09-12T14:50:41Z | [
"python",
"tkinter",
"combobox",
"width",
"dynamically-generated"
] |
resample dataframe with python | 39,451,021 | <p>I need to resample a dataframe using pandas.DataFrame.resample function like this : </p>
<pre><code>data.set_index('TIMESTAMP').resample('24min', how='sum')
</code></pre>
<p>This works without no problem, but when I try call the fucntion with 'xmin" where x is a general argment</p>
<pre><code> data.set_index('TI... | 1 | 2016-09-12T13:05:16Z | 39,451,045 | <p>IIUC you need pass variable <code>xmin</code>:</p>
<pre><code>xmin = '24min'
data.set_index('TIMESTAMP').resample(xmin, how='sum')
</code></pre>
<p>More general is convert <code>int</code> value to <code>str</code> and add substring <code>min</code>:</p>
<pre><code>step = 10
xmin = str(step) + 'min'
data = data.s... | 1 | 2016-09-12T13:06:27Z | [
"python",
"pandas",
"dataframe",
"resampling",
"datetimeindex"
] |
Separating decades and centuries in python | 39,451,104 | <p>I have a program I'm creating where I need to be able to take a year, as an integer, and separate the century from the decade:</p>
<pre><code>year=1970
decade=70
century=1900
</code></pre>
<p>I want to be able to do this:</p>
<pre><code>year= new Year(1970)
dec= year.decade
cent=year.century
</code></pre>
<p>I k... | 0 | 2016-09-12T13:09:09Z | 39,451,200 | <p>Divide the year by 100 (integer only). The result is the century:</p>
<pre><code>1972 / 100 = 19
</code></pre>
<p>(Of course, multiply again with 100 to get 1900).</p>
<p>The remainder is the year within that century:</p>
<pre><code>1972 - (19 * 100) = 72
</code></pre>
<p>Do the same if you want to get the deca... | 2 | 2016-09-12T13:13:28Z | [
"python"
] |
Separating decades and centuries in python | 39,451,104 | <p>I have a program I'm creating where I need to be able to take a year, as an integer, and separate the century from the decade:</p>
<pre><code>year=1970
decade=70
century=1900
</code></pre>
<p>I want to be able to do this:</p>
<pre><code>year= new Year(1970)
dec= year.decade
cent=year.century
</code></pre>
<p>I k... | 0 | 2016-09-12T13:09:09Z | 39,451,211 | <p>Well, you could just convert your year in string, then take the two first char and add 00 and take the two ending char. That would look like that:</p>
<pre><code>year = 1970
stringyear = str(1970)
century = stringyear[:2] + "00"
century = int(century)
print century
decade = stringyear[2:]
decade = int(decade)
print... | 0 | 2016-09-12T13:13:52Z | [
"python"
] |
Separating decades and centuries in python | 39,451,104 | <p>I have a program I'm creating where I need to be able to take a year, as an integer, and separate the century from the decade:</p>
<pre><code>year=1970
decade=70
century=1900
</code></pre>
<p>I want to be able to do this:</p>
<pre><code>year= new Year(1970)
dec= year.decade
cent=year.century
</code></pre>
<p>I k... | 0 | 2016-09-12T13:09:09Z | 39,451,296 | <p>you can use <a href="https://docs.python.org/2/library/functions.html?highlight=divmod#divmod" rel="nofollow">divmod</a> builtin function:</p>
<pre><code>>>> divmod(1664, 100)
(16, 64)
</code></pre>
| 0 | 2016-09-12T13:19:03Z | [
"python"
] |
Separating decades and centuries in python | 39,451,104 | <p>I have a program I'm creating where I need to be able to take a year, as an integer, and separate the century from the decade:</p>
<pre><code>year=1970
decade=70
century=1900
</code></pre>
<p>I want to be able to do this:</p>
<pre><code>year= new Year(1970)
dec= year.decade
cent=year.century
</code></pre>
<p>I k... | 0 | 2016-09-12T13:09:09Z | 39,550,705 | <p>Actually, year%100 returns the decade quite nicely.</p>
<p>here is the finished version of my program that works...</p>
<pre><code>critters=('Rat','ox', 'tiger','rabbit', 'dragon', 'snake', 'horse', 'ram', 'monkey', 'rooster', 'dog', 'pig')
def docrit(yrint):
modval=yrint%12
return critters[modval]
def w... | 0 | 2016-09-17T19:08:58Z | [
"python"
] |
Pythonic way to write many try/except clauses? | 39,451,126 | <p>I am writing a script to write ~200 cells of somewhat unique data to an excel spreadsheet. My code is following this basic pattern:</p>
<pre><code>try:
sheet.cell(row=9, column=7).value = getData()
except:
sheet.cell(row=9, column=7).value = 'NA'
</code></pre>
<p>Basically if there is an error then write s... | 1 | 2016-09-12T13:09:57Z | 39,451,298 | <p>As I understand, exception could be occurred in getData() call. So you can wrap getData function as:</p>
<pre><code>def get_data_or_default(default="NA"):
try:
return getData()
except Exception:
return default
</code></pre>
<p>And then just use:</p>
<pre><code>sheet.cell(row=9, column=7).value... | 7 | 2016-09-12T13:19:10Z | [
"python",
"excel"
] |
Pythonic way to write many try/except clauses? | 39,451,126 | <p>I am writing a script to write ~200 cells of somewhat unique data to an excel spreadsheet. My code is following this basic pattern:</p>
<pre><code>try:
sheet.cell(row=9, column=7).value = getData()
except:
sheet.cell(row=9, column=7).value = 'NA'
</code></pre>
<p>Basically if there is an error then write s... | 1 | 2016-09-12T13:09:57Z | 39,451,374 | <p>Put all your cells into a list, or better, get column/row from nested <code>for i in xrange()</code> loops so that you can write one line of code to perform on all of them.</p>
<pre><code>for r in xrange(0, 10):
for c in xrange(0, 10):
try:
sheet(row=r, column=c).value = getData()
ex... | 0 | 2016-09-12T13:22:30Z | [
"python",
"excel"
] |
Issues when attempting to install NAPALM for use with Ansible | 39,451,128 | <p>I have tried to figure this out but have come to a dead end.
I am trying to install NAPALM on Fedora (release 21)</p>
<p>You can install either NAPALM as a whole 'napalm' or sub packages as needed- i.e </p>
<p>napalm-ibm
napalm-ios
napalm-junos
etc</p>
<p>When I run "pip3 install napalm" all the packages download... | 0 | 2016-09-12T13:10:01Z | 39,525,715 | <p>Looks like you are trying to install under python3, Napalm does not currently support python 3.
<a href="https://github.com/napalm-automation/napalm/issues/199" rel="nofollow">https://github.com/napalm-automation/napalm/issues/199</a></p>
| 0 | 2016-09-16T07:13:12Z | [
"python",
"networking",
"automation",
"ansible"
] |
Efficiency of for loops in python3 | 39,451,346 | <p>I am currently learning Python (3), having mostly experience with R as main programming language. While in R <code>for</code>-loops have mostly the same functionality as in Python, I was taught to avoid using it for big operations and instead use <code>apply</code>, which is more efficient.</p>
<p>My question is: h... | 2 | 2016-09-12T13:20:47Z | 39,451,668 | <p>The comments correctly point out that for loops are "only as efficient as your logic"; however, the <code>range</code> and <code>xrange</code> in Python do have performance implications, and this may be what you had in mind when asking this question. <em>These methods have nothing to do with the intrinsic performanc... | 1 | 2016-09-12T13:37:36Z | [
"python"
] |
How does one identify if python script was run for the first time? | 39,451,347 | <p>I've been wondering if there's any way to find out if a python script was run for the first time.</p>
<p>Let's suppose I have this simple program:</p>
<pre><code>import random
import string
from uuid import getnode
def get_mac():
return getnode()
def generate_unique_id():
return ''.join(random.choice(s... | 0 | 2016-09-12T13:21:06Z | 39,451,585 | <p><strong> If you want to keep track of all the times your software was run </strong></p>
<p>There really is no way without writing to a file every time you start, and then appending to this file. So that way, you'd simply go look up the file to keep track of your program.</p>
<p><strong> If you want to see when the... | 1 | 2016-09-12T13:33:40Z | [
"python",
"windows",
"python-3.x"
] |
How to count the number of occurrences in either of two columns | 39,451,385 | <p>I have a simple looking problem. I have a dataframe <code>df</code> with two columns. For each of the strings that occurs in either of these columns I would like to count the number of rows which has the symbol in either column.</p>
<p>E.g.</p>
<pre><code>g k
a h
c i
j e
d i
i h
b b
d d
i a
d h
</code></pre>
<p>T... | 0 | 2016-09-12T13:23:08Z | 39,451,438 | <p>OK this is much trickier than I thought, not sure how this will scale but if you have a lot of repeating values then it will be more efficient than your current method, basically we can use <code>str.get_dummies</code> and reindex the columns from that result to generate a dummies df for all unique values, we can th... | 1 | 2016-09-12T13:26:07Z | [
"python",
"pandas"
] |
How to count the number of occurrences in either of two columns | 39,451,385 | <p>I have a simple looking problem. I have a dataframe <code>df</code> with two columns. For each of the strings that occurs in either of these columns I would like to count the number of rows which has the symbol in either column.</p>
<p>E.g.</p>
<pre><code>g k
a h
c i
j e
d i
i h
b b
d d
i a
d h
</code></pre>
<p>T... | 0 | 2016-09-12T13:23:08Z | 39,458,178 | <p>You can use <code>loc</code> to filter out row level matches from <code>'col2'</code>, append the filtered <code>'col2'</code> values to <code>'col1'</code>, and then call <code>value_counts</code>:</p>
<pre><code>counts = df['col1'].append(df.loc[df['col1'] != df['col2'], 'col2']).value_counts()
</code></pre>
<p>... | 2 | 2016-09-12T20:18:43Z | [
"python",
"pandas"
] |
Opening and closing a large number of files on python | 39,451,470 | <p>I'm writing a program which organizes my school mark and for every subject I created a file.pck where are saved all the marks of that subject. Since I have to open and pickle.load 10+ files I decided to make 2 functions, files_open():</p>
<pre><code>subj1 = open(subj1_file)
subj1_marks = pickle.load(subj1)
subj2 = ... | 0 | 2016-09-12T13:27:53Z | 39,451,613 | <p>since you just want to open, load and close the file afterwards I would suggest a simple helper function:</p>
<pre><code>def load_marks(filename):
with open(filename,"rb") as f: # don't forget to open as binary
marks = pickle.load(f)
return marks
</code></pre>
<p>Use like this:</p>
<pre><code>su... | 1 | 2016-09-12T13:34:52Z | [
"python"
] |
How to return the value of a counter in Python when comparing non-identical elements? | 39,451,485 | <p>I have the following list:</p>
<pre><code>x = [['A', 'A', 'A', 'A'], ['C', 'T', 'C', 'C'], ['G', 'T', 'C', 'C'], ['T', 'T', 'C', 'C'], ['A', 'T', 'C']]
</code></pre>
<p>I need to compare each element in sub_list to the other and note number of changes</p>
<pre><code>x[0] --> # No change
x[1] --> # 1 change... | 1 | 2016-09-12T13:28:37Z | 39,452,294 | <p>If I understand well...</p>
<pre><code>from collections import Counter
from itertools import combinations
x = [['A', 'A', 'A', 'A'],
['C', 'T', 'C', 'C'],
['G', 'T', 'C', 'C'],
['T', 'T', 'C', 'C'],
['A', 'T', 'C', 'Z']]
def divide_and_square(number, divisor):
return (1. * number / diviso... | 1 | 2016-09-12T14:07:18Z | [
"python",
"list",
"compare",
"counter"
] |
SQL query date range in python | 39,451,583 | <p>I was simply trying to query an <code>SQLServer</code> database in a specific date range. Somehow I just can't figure it out myself. Here is what I did:</p>
<pre><code> import pyodbc
import pandas as pd
con = pyodbc.connect("Driver={SQL Server}; Server=link")
tab = pd.read_sql_query("SELECT * FROM OP... | 1 | 2016-09-12T13:33:23Z | 39,451,767 | <p>You should use <a href="https://mkleehammer.github.io/pyodbc/#params" rel="nofollow">parameter binding</a>:</p>
<pre><code>tab2 = pd.read_sql_query("SELECT * FROM bbb.ccc WHERE DT between ? and ?", con, params=['2015-09-18', '2015-10-02'])
</code></pre>
<p>The <code>?</code> are placeholders for the values you are... | 0 | 2016-09-12T13:42:17Z | [
"python",
"sql-server",
"tsql"
] |
Posting Request Data | 39,451,640 | <p>I am trying to post requests with Python to register an account.</p>
<p>It is not creating the account.</p>
<p>Any help would be great! </p>
<p>It has to accept the user's email and password and confirmation of their password.</p>
<pre><code>import requests
with requests.Session() as c:
url="http://icebitho... | 0 | 2016-09-12T13:36:07Z | 39,453,786 | <p>Your form file names are incorrect, they should be:</p>
<pre><code>email:'[email protected]'
password:'bar'
confirm_password:'bar' # confirm_password
</code></pre>
<p>Which you can see if you monitor the request in chrome tools:</p>
<p><a href="http://i.stack.imgur.com/ISTEe.png" rel="nofollow"><img src="http://i.stack... | -1 | 2016-09-12T15:24:22Z | [
"python",
"python-3.x",
"module",
"python-requests"
] |
Pythonic way to find integer in list of strings | 39,451,670 | <p>I have an array as follows:</p>
<pre><code>hour = ['01','02','12']
</code></pre>
<p>and I want </p>
<pre><code>h = 1
str(h) in hour
</code></pre>
<p>to return <code>True</code>. What would be the most "Pythonic" way to do this? I could of course pad <code>h</code> with a zero, but is there a better way?</p>
| -1 | 2016-09-12T13:37:39Z | 39,451,826 | <p>A good rule of thumb is that the type and structure of data should reflect the model you have in mind. So, if your model is that hours are integers in the range 1..24, or whatever, you should model them that way:</p>
<pre><code>hours = [ int(hr) for hr in hour ]
</code></pre>
<p>then things like:</p>
<pre><code>h... | 1 | 2016-09-12T13:45:30Z | [
"python",
"arrays"
] |
Pythonic way to find integer in list of strings | 39,451,670 | <p>I have an array as follows:</p>
<pre><code>hour = ['01','02','12']
</code></pre>
<p>and I want </p>
<pre><code>h = 1
str(h) in hour
</code></pre>
<p>to return <code>True</code>. What would be the most "Pythonic" way to do this? I could of course pad <code>h</code> with a zero, but is there a better way?</p>
| -1 | 2016-09-12T13:37:39Z | 39,451,842 | <pre><code>if [i for i in hour if h == int(i)]:
print("found it")
</code></pre>
<p><code>[i for i in hour if h == int(i)]</code> is a list comprehension which basically means generating a list from an iterable object. It looks into <code>hours</code> which is a list which is iterable, and one at a time checks if t... | 0 | 2016-09-12T13:46:21Z | [
"python",
"arrays"
] |
Export a MySQL database with contacts to a compatible CardDav system | 39,451,708 | <p>I have a standard MySQL database, with a table containing contacts (I'm adding contacts to the table using a webapp using Zend Framework), thus with my own fields.</p>
<p>Is it possible to create a server which would be compatible to be used with the Address Book system of OsX? I think I must be compatible with the... | 0 | 2016-09-12T13:39:50Z | 39,457,249 | <blockquote>
<p>Is it possible to create a server which would be compatible to be used
with the Address Book system of OsX? I think I must be compatible with
the CardDav system.</p>
</blockquote>
<p>Yes you can create such a server and there are plenty already. You can choose between either CardDAV or LDAP, depe... | 0 | 2016-09-12T19:17:20Z | [
"python",
"mysql",
"osx",
"carddav"
] |
python string formatting portion cut off | 39,451,756 | <p>I'm a total beginner and this is my first question so I know this is probably stupid. But in python when I try and format a string with this code:</p>
<pre><code>x = 7
print "% how do you do" % (x)
</code></pre>
<p>I get this as a result:</p>
<pre><code>7w do you do
</code></pre>
<p>Is there a reason why the "ho... | 0 | 2016-09-12T13:41:52Z | 39,451,848 | <p>Probably using %d instead of % will solve the problem</p>
| 0 | 2016-09-12T13:46:36Z | [
"python",
"string-formatting"
] |
python string formatting portion cut off | 39,451,756 | <p>I'm a total beginner and this is my first question so I know this is probably stupid. But in python when I try and format a string with this code:</p>
<pre><code>x = 7
print "% how do you do" % (x)
</code></pre>
<p>I get this as a result:</p>
<pre><code>7w do you do
</code></pre>
<p>Is there a reason why the "ho... | 0 | 2016-09-12T13:41:52Z | 39,451,992 | <p>Best solution here is to use <code>format</code> function.</p>
<pre><code>>>> '{0} is bigger than {1}'.format('elephant', 'dog')
'elephant is bigger than dog
</code></pre>
<p>You can read more about formatting in the <a href="https://docs.python.org/3.1/library/string.html#format-examples" rel="nofollow">... | 0 | 2016-09-12T13:54:15Z | [
"python",
"string-formatting"
] |
Beautiful soup missing some html table tags | 39,451,810 | <p>I'm trying to extract data from a website using beautiful soup to parse the html. I'm currently trying to get the table data from the following webpage :</p>
<p><a href="http://www.installationsclassees.developpement-durable.gouv.fr/ficheEtablissement.php?selectRegion=-1&selectDept=-1&champcommune=&cham... | 0 | 2016-09-12T13:44:31Z | 39,452,389 | <p>Ok actually it was an issue in the html file, in the first line the html tags were opened with th but closed with td. I don't know much about HTML but replacing the th by td solved the issue.</p>
<pre><code><tr class="listeEtablenTete">
<th title="Rubrique IC">Rubri. IC</td>
<th title="Alin&... | 0 | 2016-09-12T14:11:37Z | [
"python",
"beautifulsoup"
] |
What's the closest I can get to calling a Python function using a different Python version? | 39,451,822 | <p>Say I have two files:</p>
<pre><code># spam.py
import library_Python3_only as l3
def spam(x,y)
return l3.bar(x).baz(y)
</code></pre>
<p>and</p>
<pre><code># beans.py
import library_Python2_only as l2
...
</code></pre>
<p>Now suppose I wish to call <code>spam</code> from within <code>beans</code>. It's not ... | 18 | 2016-09-12T13:45:20Z | 39,451,894 | <p>Assuming the caller is Python3.5+, you have access to a nicer <a href="https://docs.python.org/3/library/subprocess.html">subprocess</a> module. Perhaps you could user <code>subprocess.run</code>, and communicate via pickled Python objects sent through stdin and stdout, respectively. There would be some setup to do,... | 10 | 2016-09-12T13:49:12Z | [
"python",
"compatibility",
"popen"
] |
What's the closest I can get to calling a Python function using a different Python version? | 39,451,822 | <p>Say I have two files:</p>
<pre><code># spam.py
import library_Python3_only as l3
def spam(x,y)
return l3.bar(x).baz(y)
</code></pre>
<p>and</p>
<pre><code># beans.py
import library_Python2_only as l2
...
</code></pre>
<p>Now suppose I wish to call <code>spam</code> from within <code>beans</code>. It's not ... | 18 | 2016-09-12T13:45:20Z | 39,452,087 | <p>You could create a simple script as such :</p>
<pre><code>import sys
import my_wrapped_module
import json
params = sys.argv
script = params.pop(0)
function = params.pop(0)
print(json.dumps(getattr(my_wrapped_module, function)(*params)))
</code></pre>
<p>You'll be able to call it like that :</p>
<pre><code>python... | 1 | 2016-09-12T13:58:00Z | [
"python",
"compatibility",
"popen"
] |
What's the closest I can get to calling a Python function using a different Python version? | 39,451,822 | <p>Say I have two files:</p>
<pre><code># spam.py
import library_Python3_only as l3
def spam(x,y)
return l3.bar(x).baz(y)
</code></pre>
<p>and</p>
<pre><code># beans.py
import library_Python2_only as l2
...
</code></pre>
<p>Now suppose I wish to call <code>spam</code> from within <code>beans</code>. It's not ... | 18 | 2016-09-12T13:45:20Z | 39,452,583 | <p>Here is a complete example implementation using <code>subprocess</code> and <code>pickle</code> that I actually tested. Note that you need to use protocol version 2 explicitly for pickling on the Python 3 side (at least for the combo Python 3.5.2 and Python 2.7.3).</p>
<pre><code># py3bridge.py
import sys
import p... | 11 | 2016-09-12T14:22:21Z | [
"python",
"compatibility",
"popen"
] |
What's the closest I can get to calling a Python function using a different Python version? | 39,451,822 | <p>Say I have two files:</p>
<pre><code># spam.py
import library_Python3_only as l3
def spam(x,y)
return l3.bar(x).baz(y)
</code></pre>
<p>and</p>
<pre><code># beans.py
import library_Python2_only as l2
...
</code></pre>
<p>Now suppose I wish to call <code>spam</code> from within <code>beans</code>. It's not ... | 18 | 2016-09-12T13:45:20Z | 39,454,074 | <p>It's possible to use the <a href="https://docs.python.org/2/library/multiprocessing.html#managers" rel="nofollow"><code>multiprocessing.managers</code></a> module to achieve what you want. It does require a small amount of hacking though.</p>
<p>Given a module that has functions you want to expose then you need to ... | 1 | 2016-09-12T15:40:30Z | [
"python",
"compatibility",
"popen"
] |
403 error "Not Authorized to access this resource/api" Google Admin SDK in web app even being admin | 39,451,823 | <p>I'm struggling to find the problem since two days without any idea why I get this error now even though the app was fully functional one month before.</p>
<p>Among the tasks done by the web app, it makes an Admin SDK API call to get the list of members of a group. The app has the scope <code>https://www.googleapis.... | -1 | 2016-09-12T13:45:25Z | 39,470,559 | <p>Finally, after knocking my head against the wall, I found what was the problem:
the <code>groupKey</code> used to get the members of a group <code>https://www.googleapis.com/admin/directory/v1/groups/groupKey/members</code> had a <strong>trailing whitespace</strong>.</p>
<p>Yes, that's all. I just had to strip the ... | 0 | 2016-09-13T12:50:30Z | [
"python",
"web-applications",
"google-api",
"google-admin-sdk"
] |
OpenCV python: Show images in channel's color and not in grayscale | 39,452,011 | <p>I read an rgb image</p>
<pre><code>img = cv2.imread('image.jpg')
</code></pre>
<p>I split channels:</p>
<pre><code>b,g,r = cv2.split(img)
</code></pre>
<p>When I'm trying to show red image I get a grayscale image. Can I see it in red?</p>
<pre><code>cv2.imshow('Red image',r)
</code></pre>
| 2 | 2016-09-12T13:54:53Z | 39,452,189 | <p>Make blue and green channels of all zeroes, and merge these with your red channel.
Then you will see just the red channel displayed in red.</p>
<p>Or you could just set the b and g channels of the image to 0. </p>
<pre><code>img[:,:,0] = 0
img[:,:,1] = 0
</code></pre>
| 3 | 2016-09-12T14:02:31Z | [
"python",
"python-2.7",
"opencv"
] |
Remove uuid4 string pattern | 39,452,068 | <p>I have the below string examples</p>
<pre><code>1# 00000 Gin-a19ea68e-64bf-4471-b4d1-44f6bd9c1708-62fa6ae2-599c-4ff1-8249-bf6411ce3be7-83930e63-2149-40f0-b6ff-0838596a9b89 Kin
2# 00000 Gin-a19ea68e-64bf-4471-b4d1-44f6bd9c1708 Kin
</code></pre>
<p>I am trying to remove the uuid4 generated string and any text that ... | 1 | 2016-09-12T13:57:07Z | 39,452,154 | <p>You could use:</p>
<pre><code>import re
strings = ["00000 Gin-a19ea68e-64bf-4471-b4d1-44f6bd9c1708-62fa6ae2-599c-4ff1-8249-bf6411ce3be7-83930e63-2149-40f0-b6ff-0838596a9b89 Kin",
"00000 Gin-a19ea68e-64bf-4471-b4d1-44f6bd9c1708 Kin"]
rx = re.compile(r'^[^-]+')
# match the start and anything not - greedily
new_str... | 1 | 2016-09-12T14:01:07Z | [
"python",
"uuid"
] |
How to fillna() with value 0 after calling resample? | 39,452,095 | <p>Either I don't understand the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html">documentation</a> or it is outdated.</p>
<p>If I run </p>
<pre><code>user[["DOC_ACC_DT", "USER_SIGNON_ID"]].groupby("DOC_ACC_DT").agg(["count"]).resample("1D").fillna(value=0, method="ffill")
... | 6 | 2016-09-12T13:58:15Z | 39,452,261 | <p>Well, I don't get why the code above is not working and I'm going to wait for somebody to give a better answer than this but I just found</p>
<pre><code>.replace(np.nan, 0)
</code></pre>
<p>does what I would have expected from <code>.fillna(0)</code>.</p>
| 3 | 2016-09-12T14:05:39Z | [
"python",
"pandas"
] |
How to fillna() with value 0 after calling resample? | 39,452,095 | <p>Either I don't understand the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html">documentation</a> or it is outdated.</p>
<p>If I run </p>
<pre><code>user[["DOC_ACC_DT", "USER_SIGNON_ID"]].groupby("DOC_ACC_DT").agg(["count"]).resample("1D").fillna(value=0, method="ffill")
... | 6 | 2016-09-12T13:58:15Z | 39,453,317 | <p>The only workaround close to using <code>fillna</code> directly would be to call it after performing <code>.head(len(df.index))</code>. </p>
<p>I'm presuming <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.head.html" rel="nofollow"><code>DF.head</code></a> to be useful in this case m... | 1 | 2016-09-12T15:00:32Z | [
"python",
"pandas"
] |
How to fillna() with value 0 after calling resample? | 39,452,095 | <p>Either I don't understand the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html">documentation</a> or it is outdated.</p>
<p>If I run </p>
<pre><code>user[["DOC_ACC_DT", "USER_SIGNON_ID"]].groupby("DOC_ACC_DT").agg(["count"]).resample("1D").fillna(value=0, method="ffill")
... | 6 | 2016-09-12T13:58:15Z | 39,465,991 | <p>I do some test and it is very interesting.</p>
<p>Sample:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(1)
rng = pd.date_range('1/1/2012', periods=20, freq='S')
df = pd.DataFrame({'a':['a'] * 10 + ['b'] * 10,
'b':np.random.randint(0, 500, len(rng))}, index=rng)
df.b.iloc[... | 1 | 2016-09-13T08:57:26Z | [
"python",
"pandas"
] |
Faster For Loop to Manipulate Data in Pandas | 39,452,097 | <p>I am working with pandas dataframes that have shapes of ~<code>(100000, 50)</code> and although I can achieve the desired data formatting and manipulations, I find my code takes longer than desired to run (3-10mins) depending on the specific task, including:</p>
<ol>
<li>Combining strings in different columns</li>
... | 1 | 2016-09-12T13:58:27Z | 39,452,439 | <p>So what you seem to have here is a dataframe where the history entry of each row contains a list of dictionaries? Like:</p>
<pre><code>import pandas as pd
john_history = [{'title': 'a', 'dept': 'cs'}, {'title': 'cj', 'dept': 'sales'}]
john_history
jill_history = [{'title': 'boss', 'dept': 'cs'}, {'title': 'boss', '... | 1 | 2016-09-12T14:14:40Z | [
"python",
"pandas",
"numpy"
] |
django ORM - prevent direct setting of model fields | 39,452,165 | <p>I have a Django class </p>
<pre><code>class Chat(models.Model):
primary_node = models.ForeignKey('nodes.Node', blank=True, null=True, related_name='chats_at_this_pri_node', on_delete=models.SET_NULL)
secondary_node = models.ForeignKey('nodes.Node', blank=True, null=True, related_name='chats_at_this_sec_node... | 0 | 2016-09-12T14:01:31Z | 39,452,271 | <p>This simply disable setting of 'primary_node'</p>
<pre><code>class Chat(models.Model)
def __setattr__(self, attrname, val):
if attrname == 'primary_node': #sets only the attribute if it's not primary_node
print('[!] You cannot assign primary_node like that! Use assign_node() method please.')... | 0 | 2016-09-12T14:06:15Z | [
"python",
"django"
] |
django ORM - prevent direct setting of model fields | 39,452,165 | <p>I have a Django class </p>
<pre><code>class Chat(models.Model):
primary_node = models.ForeignKey('nodes.Node', blank=True, null=True, related_name='chats_at_this_pri_node', on_delete=models.SET_NULL)
secondary_node = models.ForeignKey('nodes.Node', blank=True, null=True, related_name='chats_at_this_sec_node... | 0 | 2016-09-12T14:01:31Z | 39,454,176 | <p>You could try do prevent assignment to these fields with <code>__setattr__</code>, but I recommend you don't do that for two reasons:</p>
<ol>
<li>this will probably introduce all kinds of unexpected side-effects</li>
<li>you are performing a check at runtime, to prevent something introduced at the time the code wa... | 0 | 2016-09-12T15:46:53Z | [
"python",
"django"
] |
At which moment and how often are executed the __init__.py files by python | 39,452,319 | <p>Can someone help and clarify, when using <code>import</code> command(s), at which moment the <em>__init__.py</em> files in various package directory(s) is/are executed?</p>
<ol>
<li>For each included module?</li>
<li>Only once at 1st <code>import</code> command?</li>
<li>For each <code>import</code> command?</li>
<... | 0 | 2016-09-12T14:08:19Z | 39,455,964 | <p>It's evaluated on first module import. On next imports, intrpreter detects that module was already loaded and simply returns reference to it. There is no need to re-execute code.</p>
<p>Quoting <a href="https://docs.python.org/3/reference/import.html" rel="nofollow">The import system</a>:</p>
<p>On caching modules... | 0 | 2016-09-12T17:49:47Z | [
"python",
"python-import"
] |
Insert elements in lists under array python | 39,452,531 | <p>I have a array consisting of tuples.</p>
<pre><code>Data = [('1234', 'abcd'), ('5678', 'efgh')]
</code></pre>
<p>I now have another set of variables in an array:</p>
<pre><code>add = ["#happy", "#excited"]
</code></pre>
<p>I'm trying to append 'add' to 'Data' in the same order such that the output should look li... | 0 | 2016-09-12T14:19:54Z | 39,452,833 | <p>You can use list comprehension with <code>enumerate()</code>:</p>
<pre><code>>>> Data = [('1234', 'abcd'), ('5678', 'efgh')]
>>> add = ['#happy', '#excited']
>>> [x + (add[i],) for i,x in enumerate(Data)]
[('1234', 'abcd', '#happy'), ('5678', 'efgh', '#excited')]
</code></pre>
<p>Note th... | 2 | 2016-09-12T14:34:46Z | [
"python",
"arrays",
"list",
"python-2.7",
"tuples"
] |
Insert elements in lists under array python | 39,452,531 | <p>I have a array consisting of tuples.</p>
<pre><code>Data = [('1234', 'abcd'), ('5678', 'efgh')]
</code></pre>
<p>I now have another set of variables in an array:</p>
<pre><code>add = ["#happy", "#excited"]
</code></pre>
<p>I'm trying to append 'add' to 'Data' in the same order such that the output should look li... | 0 | 2016-09-12T14:19:54Z | 39,454,115 | <p>You can add tuples in a list comprehension and use zip:</p>
<pre><code>>>> [t+(e,) for t, e in zip(Data, add)]
[('1234', 'abcd', '#happy'), ('5678', 'efgh', '#excited')]
</code></pre>
<p>(works in Python 2 and 3)</p>
| 1 | 2016-09-12T15:42:58Z | [
"python",
"arrays",
"list",
"python-2.7",
"tuples"
] |
Issues using json.load | 39,452,587 | <p>I am trying to print a list of commit messages from a git repo using python. The code I am using so far is:</p>
<pre><code>import requests, json, pprint
password = "password"
user = "user"
r = requests.get("https://api.github.com/repos/MyProduct/ios-app/commits", auth=(user, password))
j = json.load(r.json())
js... | -1 | 2016-09-12T14:22:32Z | 39,452,668 | <p>The <code>.json()</code> method on requests object already return a proper dict. No need to parse it. So just do <code>j = r.json()</code>.</p>
<p>Use <code>json.load</code> to get a dict from <a href="https://docs.python.org/3/glossary.html#term-file-like-object" rel="nofollow">file-like objects</a> and <code>json... | 2 | 2016-09-12T14:25:52Z | [
"python",
"json"
] |
Getting an N-N relation in a template | 39,452,708 | <p>I have these models (an owner can have multiple cars, and a car can have multiple owners):</p>
<pre><code>class Car(models.Model):
name = models.CharField(max_length=20)
class Owner(models.Model):
name = models.CharField(max_length=20)
class CarOwner(models.Model):
car = models.ForeignKey(Car, default... | 0 | 2016-09-12T14:27:31Z | 39,452,780 | <p>CarOwner is the through table of a many-to-many relationship. You should make that explicit:</p>
<pre><code>class Car(models.Model):
name = models.CharField(max_length=20)
owners = models.ManyToManyField('Owner', through='CarOwner')
</code></pre>
<p>Now you can do:</p>
<pre><code>{% for car in cars %}
... | 0 | 2016-09-12T14:30:59Z | [
"python",
"django"
] |
Python dict.fromkeys return same id element | 39,452,721 | <p>When i do this on python i update all keys in one time.</p>
<pre><code>>>> base = {}
>>> keys = ['a', 'b', 'c']
>>> base.update(dict.fromkeys(keys, {}))
>>> base.get('a')['d'] = {}
>>> base
{'a': {'d': {}}, 'c': {'d': {}}, 'b': {'d': {}}}
>>> map(id, base.values... | -1 | 2016-09-12T14:28:04Z | 39,452,781 | <p>When you initialize the value for the new keys as <code>{}</code> a new dictionary is created and a reference to this dictionary is becoming the values. There is only one dictionary and so if you change one, you will change "all".</p>
| 0 | 2016-09-12T14:31:02Z | [
"python",
"dictionary"
] |
Python dict.fromkeys return same id element | 39,452,721 | <p>When i do this on python i update all keys in one time.</p>
<pre><code>>>> base = {}
>>> keys = ['a', 'b', 'c']
>>> base.update(dict.fromkeys(keys, {}))
>>> base.get('a')['d'] = {}
>>> base
{'a': {'d': {}}, 'c': {'d': {}}, 'b': {'d': {}}}
>>> map(id, base.values... | -1 | 2016-09-12T14:28:04Z | 39,453,198 | <p>I tried it with both Python 2.7.6 and 3.4.3. I get the same answer when either <code>get('a')</code> or <code>['a']</code> is used. Appreciate if you can verify this at your end. Python does object reuse. Thus, <code>dict.fromkeys()</code> reuses the same empty <code>dict</code> is to initialize. To make each one a ... | 0 | 2016-09-12T14:54:04Z | [
"python",
"dictionary"
] |
Coloring given words in a text with Python | 39,452,744 | <p>I have already read the questions about how coloring text with Python and the Colorama package but I didn't find what I was looking for.</p>
<p>I have some raw text:</p>
<blockquote>
<p>Impossible considered invitation him men instrument saw celebrated unpleasant. Put rest and must set kind next many near nay. H... | 0 | 2016-09-12T14:28:53Z | 39,452,869 | <p>This should work:</p>
<pre><code>from colorama import Fore, Style
for word in text.split(' '):
if word in good:
print Fore.red + word
elif word in bad:
print Fore.green + word
else:
print Style.RESET_ALL + word
</code></pre>
| 2 | 2016-09-12T14:36:18Z | [
"python"
] |
Coloring given words in a text with Python | 39,452,744 | <p>I have already read the questions about how coloring text with Python and the Colorama package but I didn't find what I was looking for.</p>
<p>I have some raw text:</p>
<blockquote>
<p>Impossible considered invitation him men instrument saw celebrated unpleasant. Put rest and must set kind next many near nay. H... | 0 | 2016-09-12T14:28:53Z | 39,452,987 | <p>You could always do this (though it's probably a little slow):</p>
<pre><code>from colorama import Fore
for word in good:
text = text.replace(word, Fore.GREEN+word)
for word in bad:
text = text.replace(word, Fore.RED+word)
print(text)
</code></pre>
<p><code>re.sub</code> might also be interesting here, ... | 1 | 2016-09-12T14:43:42Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.