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
SWIG: Can you make C++ usable in Python using exclusively the C++ header file using SWIG?
38,132,125
<p>I was trying to learn how to use SWIG and was wondering if I was doing some extra steps that I didn't need to do. I currently have the files Dog.cpp, Dog.h, and Dog.i.I'm trying to wrap Dog.cpp for use in Python using SWIG. My interface file, Dog.i, looks as follows:</p> <pre><code>%module Dog %{ #include "Dog.h" %...
1
2016-06-30T19:53:58Z
38,132,255
<blockquote> <p>My question is, is there a way to create the python wrapper without referencing Dog.cpp at all?</p> </blockquote> <p>You can do that only if you create two DLLs/shared libraries. One DLL/shared libaray could have the object code corresponding toe Dog.cpp while the second DLL/shared library could have...
1
2016-06-30T20:01:35Z
[ "python", "c++", "shell", "g++", "swig" ]
When accessing Bigquery using Python API, what is the difference of using google client API and gcloud
38,132,132
<p>I searched for Python API to interact with google bigquery. And I found two packages provides similar APIs: Google BigQuery Client(Part of Google API Client Package <code>googleapiclient</code>) and Gcloud package <code>gcloud</code>.</p> <p>Here are the documentation about using these two APIs for Bigquery: Google...
0
2016-06-30T19:54:28Z
38,137,163
<p>The <code>googleapiclient</code> client is generated directly from the raw API definition (the definition is a json file, hosted <a href="https://www.googleapis.com/discovery/v1/apis/bigquery/v2/rest" rel="nofollow">here</a>.)</p> <p>Because it is automatically generated, it is not what any sane python programmer w...
4
2016-07-01T04:38:06Z
[ "python", "google-bigquery", "google-cloud-platform" ]
How to document Structure fields in Python using Sphinx
38,132,173
<p>I have python classes declared in the following way:</p> <pre><code>class Foo(Structure): _fields_ = [ ("vr", c_double), ("vi", c_double), ("vm", c_float), ("va", c_float)] </code></pre> <p>They are subclasses of <code>Structure</code> because I am using <code>ctypes</code> to w...
2
2016-06-30T19:56:48Z
38,468,050
<p>The unwanted auto-generated documentation disappears if the <code>:undoc-members:</code> option to the <code>automodule</code> directive is removed.</p> <hr> <p>Add a docstring to the <code>Foo</code> class. In that docstring, describe the the <code>_fields_</code> class variable. Perhaps the easiest way to do tha...
1
2016-07-19T20:36:19Z
[ "python", "ctypes", "python-sphinx" ]
Django allowed host with debug= false not working even with localhost and 127.0.0.1 parameters set
38,132,198
<p>Im trying to create a 404 custom template , i set <strong>DEBUG=False</strong> in my local settings.py, and set allowed host like this:</p> <pre><code>ALLOWED_HOST=['127.0.0.1', 'localhost'] </code></pre> <p>But i still get this when i try to run server:</p> <pre><code>CommandError: You must set settings.ALLOWED_...
1
2016-06-30T19:58:09Z
38,132,223
<p><code>ALLOWED_HOSTS</code> must be set. Not <code>ALLOWED_HOST</code></p>
0
2016-06-30T19:59:35Z
[ "python", "django", "http-status-code-404" ]
How do you add integer iterations together
38,132,244
<p>This function prints a pyramid made of "*" and "&amp;" characters. I want the program to print out the total number of "&amp;" characters in the pyramid, so I used .count to count how many times "&amp;" appears in each row. The problem is that I can't sum together the output from variable z to get the total time "...
0
2016-06-30T20:00:50Z
38,132,327
<p>define z outside the scope of the for loop</p> <pre><code>z = 0 </code></pre> <p>and use </p> <pre><code>z += x.count('&amp;') </code></pre> <p>rather than</p> <pre><code>z = x.count('&amp;') </code></pre>
0
2016-06-30T20:05:23Z
[ "python", "python-3.x" ]
How do you add integer iterations together
38,132,244
<p>This function prints a pyramid made of "*" and "&amp;" characters. I want the program to print out the total number of "&amp;" characters in the pyramid, so I used .count to count how many times "&amp;" appears in each row. The problem is that I can't sum together the output from variable z to get the total time "...
0
2016-06-30T20:00:50Z
38,132,333
<p>Haven't run it, but you need a variable outside the for loop that will hold the total number of '&amp;'s.</p> <pre><code>def pyramid(): min_pyramid_size = 5 max_pyramid_size = 10 num_rows = random.randint(min_pyramid_size, max_pyramid_size) total_z = 0 for i in range(num_rows): x = ''.jo...
2
2016-06-30T20:06:13Z
[ "python", "python-3.x" ]
How do you add integer iterations together
38,132,244
<p>This function prints a pyramid made of "*" and "&amp;" characters. I want the program to print out the total number of "&amp;" characters in the pyramid, so I used .count to count how many times "&amp;" appears in each row. The problem is that I can't sum together the output from variable z to get the total time "...
0
2016-06-30T20:00:50Z
38,132,432
<p>Try this:-</p> <pre><code>import random from random import choice from random import randint def pyramid(): min_pyramid_size = 5 max_pyramid_size = 10 z = 0 num_rows = random.randint(min_pyramid_size, max_pyramid_size) for i in range(num_rows): x = ''.join(str(random.choice('*&amp;')) f...
0
2016-06-30T20:13:37Z
[ "python", "python-3.x" ]
How do you add integer iterations together
38,132,244
<p>This function prints a pyramid made of "*" and "&amp;" characters. I want the program to print out the total number of "&amp;" characters in the pyramid, so I used .count to count how many times "&amp;" appears in each row. The problem is that I can't sum together the output from variable z to get the total time "...
0
2016-06-30T20:00:50Z
38,132,635
<p>Here's a more compact solution using a list comprehension:</p> <pre><code>def pyramid(min_size=5, max_size=10): N = randint(min_size, max_size) x = ''.join(' ' * (N-i) + ''.join(choice('*&amp;') for j in range(2*i+1)) + '\n' for i in range(N)) print(x) print(x.count('&amp;')) </code></pre> <p>Demo:...
0
2016-06-30T20:26:14Z
[ "python", "python-3.x" ]
How do you add integer iterations together
38,132,244
<p>This function prints a pyramid made of "*" and "&amp;" characters. I want the program to print out the total number of "&amp;" characters in the pyramid, so I used .count to count how many times "&amp;" appears in each row. The problem is that I can't sum together the output from variable z to get the total time "...
0
2016-06-30T20:00:50Z
38,133,030
<p>You need to have two variables, one for the internal and one for the external count.</p> <pre><code>def pyramid(): min_pyramid_size = 5 max_pyramid_size = 10 num_rows = random.randint(min_pyramid_size, max_pyramid_size) outer_z = 0 for i in range(num_rows): x = ''.join(str(random.choice('*&amp;')) for...
0
2016-06-30T20:51:25Z
[ "python", "python-3.x" ]
How to generate noise with a chosen spatial distribution with numpy?
38,132,250
<p>I want to add noise to an image in a way similar to this :</p> <pre><code>import numpy as np import matplotlib.pyplot as plt myImage = plt.imread('Pikachu.png') noise = np.random.normal(0, 0.1, (myImage.shape[0], myImage.shape[1])) noisyImage = myImage + noise </code></pre> <p>However, I would need the noise to ...
2
2016-06-30T20:01:06Z
38,134,404
<p>Something you could use as a starting point: </p> <pre><code>import numpy as np import matplotlib.pyplot as plt def gauss2D(shape,sx=1,sy=1): """ unnormalized 2D gauss centered on mean value, given shape and standard dev (sx and sy). """ mx = shape[0]/2 my = shape[1]/2 return np.exp( ...
1
2016-06-30T22:42:21Z
[ "python", "numpy", "image-processing", "matplotlib", "noise" ]
Making a relatively complex datetime function more pythonic
38,132,267
<p>I'm working on a function that returns a specific set of times for a given timezone and a given frequency; day, week, month. For any given timezone and a frequncy the function will return the unixtime hour start and unixtime hour end of the last full frequency given. For example, the last full day, the last full 7...
0
2016-06-30T20:02:11Z
38,132,596
<p>Making this more pythonic is probably not that easy as it's just statements. But you can certainly improve your code by:</p> <ol> <li>Not using magic numbers. This will make sure you code is configurable and scalable. Sure, the parameters wont change as they haven't over the last thousands of years, but you never k...
1
2016-06-30T20:23:41Z
[ "python" ]
Use a reverse OneToOne relation in Django FileField upload_to
38,132,299
<p>I'm trying to use the reverse relation of a <code>OneToOneField</code> to build the path in an <code>upload_to</code> method of a <code>FileField</code>, like this:</p> <pre><code>def get_upload_path(asset, filename): # Using the reverse relation `game` here return '/'.join([asset.game.slug, filename]) cl...
0
2016-06-30T20:04:06Z
38,133,051
<p>the problem is in your 'get_upload_path' function, cause you're calling to asset.game.slug... but you don't have defined any game yet...</p>
1
2016-06-30T20:52:40Z
[ "python", "django", "django-admin" ]
Matplotlib, I'm making a 2d histogram and I want to a triangular axes extension similar to what is done with colorbars
38,132,402
<p>Using MATPLOTLIB.PYPLOT I am making a 2d histogram where I want to limit my view to a certain range of y-values but at the same time I want to cluster all values below a certain number at the bottom of the y-axis. What i'm thinking of is similar to how you can make a colorbar have triangular extensions and anything ...
-1
2016-06-30T20:11:33Z
38,135,325
<p>The easiest way to achieve this that I can think of is to filter your data before calling the histogram. Here is an example using <code>np.where</code> to filter the y data.</p> <pre><code>import numpy as np; np.random.seed(17) import matplotlib.pyplot as plt # generate some random normal data N = 100000 x = np.ra...
0
2016-07-01T00:35:46Z
[ "python", "matplotlib", "histogram" ]
Python3.5 -configure a single cell to expand instead of the entire row or column
38,132,470
<p>Picture a 4x4 grid in a tkinter window. I want to expand the cell at row 2, column 2 but not everything else on row 2 or column 2. Im designing a text window with selectable options on the left side in rows 1-15. Making row 2 with weight 1 and column 2 with weight 1 allows my Text widget to expand but so does everyt...
0
2016-06-30T20:15:54Z
38,132,544
<p>One way around it would be to make your grid twice as large, setting the things you want to be expandable to span two columns/rows. </p> <p>I.e. you use exclusively odd numbered rows/columns for <code>grid</code>ing things ([1,1][1,3],[3,1][3,3]...) and you set even-numbered rows/columns to have weight. Anything yo...
1
2016-06-30T20:20:41Z
[ "python", "python-3.x", "tkinter", "grid" ]
Python3.5 -configure a single cell to expand instead of the entire row or column
38,132,470
<p>Picture a 4x4 grid in a tkinter window. I want to expand the cell at row 2, column 2 but not everything else on row 2 or column 2. Im designing a text window with selectable options on the left side in rows 1-15. Making row 2 with weight 1 and column 2 with weight 1 allows my Text widget to expand but so does everyt...
0
2016-06-30T20:15:54Z
38,145,878
<p>Your question asks about a 4x4 grid, but your example shows only two columns. That makes it hard to understand what you want. In the comments you say you simply want the text area of the example to grow and shrink and all the labels together, so that's what I'll address.</p> <p>The simplest solution is to have an e...
2
2016-07-01T12:49:12Z
[ "python", "python-3.x", "tkinter", "grid" ]
Python3.5 -configure a single cell to expand instead of the entire row or column
38,132,470
<p>Picture a 4x4 grid in a tkinter window. I want to expand the cell at row 2, column 2 but not everything else on row 2 or column 2. Im designing a text window with selectable options on the left side in rows 1-15. Making row 2 with weight 1 and column 2 with weight 1 allows my Text widget to expand but so does everyt...
0
2016-06-30T20:15:54Z
38,149,487
<p>With the information everyone has provided I was able to come up with a solution. I left the Text widget on the main window instead of in a frame and put my labels/tools in frames. Basically using the fact that a frame will not expand to lock down the labels. Now when the window is expanded only the widget grows. </...
0
2016-07-01T15:51:30Z
[ "python", "python-3.x", "tkinter", "grid" ]
Numpy apply_along_axis not returning ndarray subclass
38,132,483
<p>I have an <code>ndarray</code> subclass, with <code>__array_wrap__</code> properly implemented, <code>np.apply_along_axis</code> isn't returning instances of my subclass, but rather <code>ndarrays</code>. The code below replicates my problem:</p> <pre><code>import numpy as np class MySubClass(np.ndarray): def...
3
2016-06-30T20:17:02Z
38,134,278
<p>Looking at the <code>apply_along_axis</code> code (via Ipython ??)</p> <pre><code>Type: function String form: &lt;function apply_along_axis at 0xb5a73b6c&gt; File: /usr/lib/python3/dist-packages/numpy/lib/shape_base.py Definition: np.apply_along_axis(func1d, axis, arr, *args, **kwargs) Source: def ap...
1
2016-06-30T22:30:19Z
[ "python", "numpy", "multidimensional-array" ]
Selenium task becomes slower and slower
38,132,555
<p>not sure what the Title should be, please feel free to edit. I am new to <a href="http://selenium-python.readthedocs.io/" rel="nofollow">Selenium</a>, and was just playing around with it. I tried to experiment on one of my favorite site(<a href="http://10fastfingers.com/" rel="nofollow">10fastfingers.com</a>) which ...
2
2016-06-30T20:21:02Z
38,132,593
<p>Every <code>.find_element_*</code>, <code>.text</code>, <code>.send_keys()</code> etc calls are WebDriver commands which involve HTTP request/response (see <a href="https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol" rel="nofollow">JSON wire protocol</a>) processing. You can dramatically decrease the amoun...
3
2016-06-30T20:23:15Z
[ "python", "selenium", "automation" ]
Selenium task becomes slower and slower
38,132,555
<p>not sure what the Title should be, please feel free to edit. I am new to <a href="http://selenium-python.readthedocs.io/" rel="nofollow">Selenium</a>, and was just playing around with it. I tried to experiment on one of my favorite site(<a href="http://10fastfingers.com/" rel="nofollow">10fastfingers.com</a>) which ...
2
2016-06-30T20:21:02Z
38,134,820
<p>I love stuff like this. I did mine in Java first like this.</p> <pre><code>while (true) { String word = driver.findElement(By.cssSelector("span.highlight")).getText(); driver.findElement(By.id("inputfield")).sendKeys(word + " "); } </code></pre> <p>This got me 361 wpm but I noticed that I ran out of words ...
1
2016-06-30T23:27:59Z
[ "python", "selenium", "automation" ]
Python Selenium WebDriver Loop - send_keys working and then not working
38,132,600
<p>I'm using Python 2.7, Chrome 47 (with the chrome driver), and Selenium 2.53.5. I'm practicing by creating a bot to gather info from a cvs file and then use that info to open up ebay, type in quantity, and purchase as guest. So far it works - kinda. The script will run, open ebay to the specific item, clear the quant...
0
2016-06-30T20:23:59Z
38,156,061
<p><code>StaleElementReferenceException</code>s generally indicate the the DOM refreshed while you were interacting with the element. I commonly see them on highly dynamic webpages. </p> <p>If the calls similar to <code>driver.find_element_by_name('dayphone1').send_keys("123")</code> are what seem to be throwing the e...
0
2016-07-02T02:56:02Z
[ "python", "loops", "selenium", "crash" ]
Different values weibull pdf
38,132,647
<p>I was wondering why the values of weibull pdf with the prebuilt function dweibull.pdf are more or less the half they should be</p> <p>I did a test. For the same x I created the weibull pdf for A=10 and K=2 twice, one by writing myself the <a href="https://en.wikipedia.org/wiki/Weibull_distribution" rel="nofollow">f...
0
2016-06-30T20:26:39Z
38,134,745
<p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.dweibull.html" rel="nofollow"><code>scipy.stats.dweibull</code></a> implements the <em>double</em> Weibull distribution. Its support is the real line. Your function <code>weib</code> corresponds to the PDF of scipy's <a href="http://docs.scip...
1
2016-06-30T23:17:48Z
[ "python", "scipy", "weibull" ]
NetCDF variables that have the fill value/ missing value
38,132,657
<p>I have a variable in a NetCDF file that has a default value if the variable is null. How do you remove this value or change it to 0 when the variable is missing a value?</p>
0
2016-06-30T20:27:16Z
38,133,035
<p>It sounds like the problem is that when the variable is populated into the NetCDF file, it is set to insert some default value for values that are missing. Now, I am assuming that you need to remove these default values <em>after</em> the file has been written and you are working with the data. </p> <p>So (dependin...
0
2016-06-30T20:51:43Z
[ "python", "netcdf" ]
ImportError: No module named 'encodings'
38,132,755
<p>I recently reinstalled ubuntu and did upgrade to 16.04 and cannot use python:</p> <pre><code>$ python manage.py runserver Could not find platform independent libraries &lt;prefix&gt; Could not find platform dependent libraries &lt;exec_prefix&gt; Consider setting $PYTHONHOME to &lt;prefix&gt;[:&lt;exec_prefix&gt;] ...
3
2016-06-30T20:33:45Z
39,097,003
<p>For Python-3 try removing virtual environment files. And resetting it up.</p> <pre><code>rm -rf venv virtualenv -p /usr/bin/python3 venv/ source env/bin/activate pip install -r requirements.txt </code></pre> <p><a href="https://wiki.ubuntu.com/XenialXerus/ReleaseNotes#Python_3">https://wiki.ubuntu.com/XenialXerus/...
5
2016-08-23T09:11:32Z
[ "python", "python-3.x", "python-2.x" ]
MessageSource equivalent in Django?
38,132,832
<p>I come from a Java/Spring background and I've just recently moved to Python/Django. I'm working on a new project from scratch with Django. I was wondering how Django handles common String messages. Is there one single common file that can be called in a resources folder? For example, in Spring, we have a MessageSour...
1
2016-06-30T20:38:21Z
38,132,991
<p>You could take a look over <a href="https://docs.djangoproject.com/es/1.9/ref/contrib/messages/" rel="nofollow">Django's messages framework</a>.</p> <p>Also, you can use key-value pairs in Python, with dicts:</p> <pre><code># Upper case because it is constant LOGIN_ERRROS = { 'login_error_message': 'message h...
0
2016-06-30T20:48:50Z
[ "java", "python", "django", "string", "spring" ]
MessageSource equivalent in Django?
38,132,832
<p>I come from a Java/Spring background and I've just recently moved to Python/Django. I'm working on a new project from scratch with Django. I was wondering how Django handles common String messages. Is there one single common file that can be called in a resources folder? For example, in Spring, we have a MessageSour...
1
2016-06-30T20:38:21Z
38,133,492
<p>Django uses the standard <code>gettext</code> + <code>.po</code> files for internationalization/translation. Check out the Translation docs for all the steps needed: <a href="https://docs.djangoproject.com/en/1.9/topics/i18n/translation/" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/i18n/translation/<...
0
2016-06-30T21:22:46Z
[ "java", "python", "django", "string", "spring" ]
Script writes in reverse
38,132,854
<p>Sorry if I asked this wrong or formatted it wrong, this is my first time here. Basically, this script is a very, very, simple text editor. The problem is, when it writes to a file, I want it to write:</p> <pre><code>Hi, my name is bob. </code></pre> <p>But, it writes:</p> <pre><code>is bob. Hi, my name </code></p...
0
2016-06-30T20:39:51Z
38,133,052
<p>If you replace:</p> <pre><code>f = open(usrtxtdir,"a") f.write(words + '\n') </code></pre> <p>with:</p> <pre><code>with open(usrtxtdir,"a") as f: f.write(words + '\n') </code></pre> <p>It comes out in order. Pretty much always use <code>with open()</code> for file access. It handles the closing of the file...
0
2016-06-30T20:52:43Z
[ "python", "python-3.x" ]
Script writes in reverse
38,132,854
<p>Sorry if I asked this wrong or formatted it wrong, this is my first time here. Basically, this script is a very, very, simple text editor. The problem is, when it writes to a file, I want it to write:</p> <pre><code>Hi, my name is bob. </code></pre> <p>But, it writes:</p> <pre><code>is bob. Hi, my name </code></p...
0
2016-06-30T20:39:51Z
38,133,075
<p>Nice puzzle. Why are the lines coming out in reverse? Because of <strong>output buffering:</strong></p> <p>When you write to a file, the system doesn't immediately commit your data to disk. This happens periodically (when the buffer is full), or when the file is closed. You never close <code>f</code>, so it is clos...
2
2016-06-30T20:53:57Z
[ "python", "python-3.x" ]
Script writes in reverse
38,132,854
<p>Sorry if I asked this wrong or formatted it wrong, this is my first time here. Basically, this script is a very, very, simple text editor. The problem is, when it writes to a file, I want it to write:</p> <pre><code>Hi, my name is bob. </code></pre> <p>But, it writes:</p> <pre><code>is bob. Hi, my name </code></p...
0
2016-06-30T20:39:51Z
38,133,098
<p>You need to close your file after writing, before you try to open it again. Otherwise your writes will not be finalized until the program is closed.</p> <pre><code>def editor(): words = input("\n") f = open(usrtxtdir,"a") f.write(words + '\n') nlq = input('Line saved. "/n" for new line. "/quit" to q...
1
2016-06-30T20:55:28Z
[ "python", "python-3.x" ]
Script writes in reverse
38,132,854
<p>Sorry if I asked this wrong or formatted it wrong, this is my first time here. Basically, this script is a very, very, simple text editor. The problem is, when it writes to a file, I want it to write:</p> <pre><code>Hi, my name is bob. </code></pre> <p>But, it writes:</p> <pre><code>is bob. Hi, my name </code></p...
0
2016-06-30T20:39:51Z
38,133,394
<p>Python's <a href="https://docs.python.org/2.7/library/stdtypes.html#file.write" rel="nofollow"><code>file.write()</code></a> documentation states: "Due to buffering, the string may not actually show up in the file until the <a href="https://docs.python.org/2.7/library/stdtypes.html#file.flush" rel="nofollow"><code>f...
0
2016-06-30T21:15:26Z
[ "python", "python-3.x" ]
Using Javascript Injection in a Python Web Scraper?
38,132,965
<p>I'm trying to build a python web scraper that goes on a certain website, inputs a value, clicks a button, and retrieves the output source code. This is the Javascript that I would like to use in my python code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <di...
-1
2016-06-30T20:47:18Z
38,133,043
<p>If you want to use python, you might want to use <a href="http://selenium-python.readthedocs.io/" rel="nofollow">selenium</a>, you can simply open a browser and automate the whole task.</p>
0
2016-06-30T20:52:11Z
[ "javascript", "python", "javascript-injection" ]
"A value is trying to be set on a copy of a slice from a DataFrame" even when .loc is used
38,132,976
<p>I don't understand why this is happening if I'm using .loc to create the <code>another_df</code> dataframe</p> <pre><code>&gt;&gt;&gt; df = DataFrame({'a':range(0,10), 'b':range(10,20), 'c':range(20,30)}, index = range(0,10), columns=['a', 'b', 'c']) &gt;&gt;&gt; df a b c 0 0 10 20 1 1 11 21 2 2 12 ...
1
2016-06-30T20:47:48Z
38,133,027
<pre><code>df.loc[(df.a&gt;4)&amp;(df.b&gt;14)&amp;(df.c&gt;24),:] </code></pre> <p>Is returning a view or copy of <code>df</code></p> <p>use <code>copy</code>:</p> <pre><code>df = DataFrame({'a':range(0,10), 'b':range(10,20), 'c':range(20,30)}, index = range(0,10), columns=['a', 'b', 'c']) another_df...
1
2016-06-30T20:51:16Z
[ "python", "python-2.7", "pandas", "indexing", "dataframe" ]
"A value is trying to be set on a copy of a slice from a DataFrame" even when .loc is used
38,132,976
<p>I don't understand why this is happening if I'm using .loc to create the <code>another_df</code> dataframe</p> <pre><code>&gt;&gt;&gt; df = DataFrame({'a':range(0,10), 'b':range(10,20), 'c':range(20,30)}, index = range(0,10), columns=['a', 'b', 'c']) &gt;&gt;&gt; df a b c 0 0 10 20 1 1 11 21 2 2 12 ...
1
2016-06-30T20:47:48Z
38,133,056
<p>You need to specify which row is to obtain the value <code>'a random string'</code> for the new column, <code>'d'</code>. Or you can give the column a list of elements of length <code>len(another_df)</code>:</p> <pre><code>another_df['d']=['hello', 'world', 'hello', 'world', 'hello'] </code></pre>
-1
2016-06-30T20:52:53Z
[ "python", "python-2.7", "pandas", "indexing", "dataframe" ]
getting sum of a set of a particular element in a set of lists in python
38,133,014
<p>Suppose i have a list which contains sublists :</p> <pre><code>THELIST = [ ['0', 'xb', '"OZNG15"', '23', '50', 'P'], ['0', 'vcxbv', '"OZNG15"', '23', '-100', 'P'], ['0', 'grfds', '"OZNG15"', '23', '412', 'P'] ] </code></pre> <p>How do I calculate the sum of elements in the 5th position of each list ( i.e. 5...
-4
2016-06-30T20:50:26Z
38,133,060
<p>You can simply do this with a generator expression and <code>sum</code>:</p> <pre><code>output = sum(int(lst[4]) for lst in THELIST) </code></pre>
0
2016-06-30T20:53:07Z
[ "python", "list" ]
Get "Adj Close" using pandas DataReader
38,133,064
<p>I just switched from pandas.io to pandas_datareader and I'm having difficulties pulling in just Adjusted Close prices. before I could use the following code</p> <pre><code>pd.io.data.get_data_yahoo(stock, start, end)['Adj Close'] </code></pre> <p>now when I try the datareader (imported as web) it does not work. </...
1
2016-06-30T20:53:27Z
38,133,128
<p>i would use <a href="https://pandas-datareader.readthedocs.io/en/latest/remote_data.html" rel="nofollow">DataReader</a> for that:</p> <pre><code>In [61]: from pandas_datareader.data import DataReader In [62]: DataReader('AAPL', 'yahoo', '2016-06-25', '2016-06-30')['Adj Close'] Out[62]: Date 2016-06-27 92.040001...
1
2016-06-30T20:57:30Z
[ "python", "pandas", "datareader", "yahoo-finance" ]
Pandas: Replacing Non-numeric cells with 0
38,133,085
<p>I have the Pandas Dataframe in this format</p> <pre><code>0 or LIST requests 1 us-west-2 2 1.125e-05 3 0 4 3.032e-05 5 0 6 7.28e-06 7 or LIST requests 8 3.1e-07 9 ...
1
2016-06-30T20:54:31Z
38,133,159
<h3>Setup</h3> <pre><code>import pandas as pd from StringIO import StringIO text = """0 or LIST requests 1 us-west-2 2 1.125e-05 3 0 4 3.032e-05 5 0 6 7.28e-06 7 or LIST requests 8 ...
2
2016-06-30T20:59:23Z
[ "python", "pandas" ]
Assigning (instead of defining) a __getitem__ magic method breaks indexing
38,133,096
<p>I have a wrapper class similar to this (strongly simplified) example:</p> <pre><code>class wrap(object): def __init__(self): self._data = range(10) def __getitem__(self, key): return self._data.__getitem__(key) </code></pre> <p>I can use it like this:</p> <pre><code>w = wrap() print w[2] ...
4
2016-06-30T20:55:27Z
38,133,198
<p>Special methods (essentially anything with two underscores on each end) have to be defined on the class. The <a href="https://docs.python.org/3/reference/datamodel.html#special-lookup" rel="nofollow">internal lookup procedure</a> for special methods completely skips the instance dict. Among other things, this is so ...
4
2016-06-30T21:01:40Z
[ "python", "class", "indexing", "wrapper", "magic-methods" ]
Assigning (instead of defining) a __getitem__ magic method breaks indexing
38,133,096
<p>I have a wrapper class similar to this (strongly simplified) example:</p> <pre><code>class wrap(object): def __init__(self): self._data = range(10) def __getitem__(self, key): return self._data.__getitem__(key) </code></pre> <p>I can use it like this:</p> <pre><code>w = wrap() print w[2] ...
4
2016-06-30T20:55:27Z
38,133,854
<p>You can actually solve this by creating a new class for every type. If you want this to work transparently, <code>__new__</code> is the place for it.</p> <pre><code>import weakref class BigWrap(object): def __new__(cls, wrapped): wrapped_type = type(wrapped) print('Wrapping %s (%s)' % (wrapped...
1
2016-06-30T21:52:31Z
[ "python", "class", "indexing", "wrapper", "magic-methods" ]
Python - Pcolormesh and basemap not plotting as expected
38,133,134
<p>I have a long list of latitudes and longitudes, and the ultimate goal is to plot the number of occurrences at each latitude/longitude pair on a map of North America. As an example, I have a DataFrame, called sort_df, that looks like:</p> <pre><code>longitude -95 -94 -93 -92 latitude 43 0 4 8 ...
0
2016-06-30T20:57:46Z
38,165,298
<p>You made a missprint while convert lat-lon. Your arrays <code>lats</code> and <code>lons</code> are empty.</p> <p>Another problem of your code is that <code>data</code> have to have shape of [nx-1, ny-1] to plot with <code>pcolormesh</code> (it draw between points):</p> <pre><code>import numpy as np from mpl_toolk...
0
2016-07-02T23:22:51Z
[ "python", "matplotlib-basemap" ]
control increment in for loop Python
38,133,167
<p>I am new to Python so please excuse me if this is a very obvious questions, how do I write a statement like this in Python</p> <pre><code>for (int i=p*2; i&lt;=n; i += p) for i in range(p*2, n) </code></pre> <p>but then how does it increment? </p>
0
2016-06-30T20:59:50Z
38,133,202
<pre><code>for i in range(p*2, n + 1, p): # range(inclusive start, non inclusive end, step) </code></pre>
3
2016-06-30T21:01:52Z
[ "python", "python-2.7" ]
control increment in for loop Python
38,133,167
<p>I am new to Python so please excuse me if this is a very obvious questions, how do I write a statement like this in Python</p> <pre><code>for (int i=p*2; i&lt;=n; i += p) for i in range(p*2, n) </code></pre> <p>but then how does it increment? </p>
0
2016-06-30T20:59:50Z
38,133,230
<p>if you look up the range function you will notice that it actually can take three arguments. The third value is the amount to increment by, which is 1 by default. Just change to </p> <pre><code>range(p*2, n, p) </code></pre>
1
2016-06-30T21:03:29Z
[ "python", "python-2.7" ]
control increment in for loop Python
38,133,167
<p>I am new to Python so please excuse me if this is a very obvious questions, how do I write a statement like this in Python</p> <pre><code>for (int i=p*2; i&lt;=n; i += p) for i in range(p*2, n) </code></pre> <p>but then how does it increment? </p>
0
2016-06-30T20:59:50Z
38,133,245
<p><code>range</code> generates a sequence of numbers - a range. For example, <code>range(0,5)</code> is equivalent to <code>[0, 1, 2, 3, 4]</code>. It's signature is <code>range(start, stop, stride)</code>, which in <code>C</code> would be</p> <pre><code>for (int i= start; i&lt;stop; i += stride) </code></pre> <p>So...
3
2016-06-30T21:04:34Z
[ "python", "python-2.7" ]
How to set a default value when Scrapy selector returns None
38,133,213
<p>I was trying to set default value when the result of my xpath selector return None. This happens when in some pages the xpath node dont exist and I want to set for example 'N/A' or 'Not found'.</p> <p>I used the following code but I think this isn't clean and efficient:</p> <pre><code>value = response.xpath(proper...
1
2016-06-30T21:02:32Z
38,133,550
<p>There is no need to do the query twice, a simple solution is to pass a default value:</p> <pre><code>data[property.name] = response.xpath(property.xpath).extract_first(default='N/A') </code></pre> <p>For future reference, if you were to rewrite your own code without using the default keyword, I would query once an...
2
2016-06-30T21:26:03Z
[ "python", "xpath", "web-scraping", "scrapy" ]
Not able to retrieve all the groups using regular expression in Python
38,133,233
<p>I am very new to Python and have written regular expression where i am able to match the complete pattern but not able to retrieve all the captured matches as shown below. Can someone help me on the below content</p> <p><strong>Regular Expression</strong></p> <pre><code>(?i)(?:sections?|\&amp;\#xA7\;|Treas\.\s*Reg...
1
2016-06-30T21:03:36Z
38,133,610
<p>Remove the <code>(?i)</code> and the regex works for me on your sample... You are also using non-capturing groups, and regex won't give you separate groups for repeating the same capture group, it will just keep the last one, which is why you're seeing it output as just two copies of the same thing.</p> <p>Personal...
0
2016-06-30T21:31:09Z
[ "python", "regex", "python-3.x", "python-3.5" ]
Not able to retrieve all the groups using regular expression in Python
38,133,233
<p>I am very new to Python and have written regular expression where i am able to match the complete pattern but not able to retrieve all the captured matches as shown below. Can someone help me on the below content</p> <p><strong>Regular Expression</strong></p> <pre><code>(?i)(?:sections?|\&amp;\#xA7\;|Treas\.\s*Reg...
1
2016-06-30T21:03:36Z
38,133,612
<p>You could go for:</p> <pre><code>sections\ (?P&lt;section1&gt;[-.\w()]+) \ and\ (?P&lt;section2&gt;[-.\w()]+) (?P&lt;optional&gt; (?:,\ [-.\w()]+)+ )? </code></pre> <p>And use <code>re.finditer()</code> afterwards, see <a href="https://regex101.com/r/qJ5oQ2/2" rel="nofollow"><strong>a demo on regex101.com</s...
1
2016-06-30T21:31:18Z
[ "python", "regex", "python-3.x", "python-3.5" ]
How to output more than one API request in Flask?
38,133,261
<p>I have several API GET calls I need to do and see the output on a webpage. I'm new to Flask, and I'm only able to print the output of one request call.</p> <p>I also would like to know how to format the output. I'm able to print a name, but I want the output to look like </p> <p>I get this:</p> <blockquote> <p>...
-1
2016-06-30T21:05:32Z
38,133,425
<p>Generally you gather your variables (your GET requests in your case) and then supply them to your template to render.</p> <pre><code>@app.route('/') def getInfo(): url = 'some url' response = requests.get(url).json() other_response = requests.get(url).json() return render_template('example.html', fo...
1
2016-06-30T21:18:06Z
[ "python", "json", "flask" ]
pandas DataFrame to dict with values as tuples
38,133,332
<p>I have a <code>DataFrame</code> as follows:</p> <pre><code>In [23]: df = pandas.DataFrame({'Initial': ['C','A','M'], 'Sex': ['M', 'F', 'F'], 'Age': [49, 39, 19]}) df = df[['Initial', 'Sex', 'Age']] df Out[23]: Initial Sex Age 0 C M 49 1 A F 39 2 M F 19 </code><...
3
2016-06-30T21:11:12Z
38,133,441
<p>If lists instead of tuples are okay, then you could use:</p> <pre><code>In [45]: df.set_index('Initial')[['Age','Sex']].T.to_dict('list') Out[45]: {'A': [39, 'F'], 'C': [49, 'M'], 'M': [19, 'F']} </code></pre>
4
2016-06-30T21:19:07Z
[ "python", "pandas", "dictionary" ]
pandas DataFrame to dict with values as tuples
38,133,332
<p>I have a <code>DataFrame</code> as follows:</p> <pre><code>In [23]: df = pandas.DataFrame({'Initial': ['C','A','M'], 'Sex': ['M', 'F', 'F'], 'Age': [49, 39, 19]}) df = df[['Initial', 'Sex', 'Age']] df Out[23]: Initial Sex Age 0 C M 49 1 A F 39 2 M F 19 </code><...
3
2016-06-30T21:11:12Z
38,133,498
<p>This should work:</p> <pre><code>df.set_index('Initial')[['Age', 'Sex']].T.apply(tuple).to_dict() {'A': (39, 'F'), 'C': (49, 'M'), 'M': (19, 'F')} </code></pre>
4
2016-06-30T21:23:12Z
[ "python", "pandas", "dictionary" ]
3D object translation distorts object
38,133,379
<p>I am creating a 3D engine using this tutorial: <a href="https://www.davrous.com/2013/06/13/tutorial-series-learning-how-to-write-a-3d-soft-engine-from-scratch-in-c-typescript-or-javascript/" rel="nofollow">https://www.davrous.com/2013/06/13/tutorial-series-learning-how-to-write-a-3d-soft-engine-from-scratch-in-c-typ...
0
2016-06-30T21:14:12Z
39,683,520
<p>Matrix multiplication is not commutative, make sure you're multiplying the matrices in the correct order.</p>
2
2016-09-25T04:52:23Z
[ "python", "3d" ]
How capture all non-built-in functions' names from a module and put them into a list
38,133,418
<p>I want to capture the name of ALL non-built-in functions from a specific module and put them into a list. </p> <p>Let's say I wrote <code>func_1()</code> and <code>func_2()</code> inside the module <code>test.py</code>. Then, from inside another module, I want to do something like:</p> <pre><code>import test my_li...
1
2016-06-30T21:17:24Z
38,133,673
<p>You can get all the function names in your module with <a href="https://docs.python.org/2/library/inspect.html#inspect.getmembers" rel="nofollow"><code>inspect.getmembers</code></a></p> <blockquote> <p>Return all the members of an object in a list of (name, value) pairs sorted by name. If the optional predicate...
1
2016-06-30T21:35:35Z
[ "python", "python-2.7", "python-3.x" ]
How capture all non-built-in functions' names from a module and put them into a list
38,133,418
<p>I want to capture the name of ALL non-built-in functions from a specific module and put them into a list. </p> <p>Let's say I wrote <code>func_1()</code> and <code>func_2()</code> inside the module <code>test.py</code>. Then, from inside another module, I want to do something like:</p> <pre><code>import test my_li...
1
2016-06-30T21:17:24Z
38,133,884
<p>This should return all top-level functions from the imported module.</p> <pre><code>from types import FunctionType def all_funcs_from(module): return filter(lambda f: isinstance(f, FunctionType), module.__dict__.values()) </code></pre> <p>Builtin functions are of type <code>types.BuiltinFunctionType</code>. B...
2
2016-06-30T21:54:48Z
[ "python", "python-2.7", "python-3.x" ]
Writing to a file from a subprocess and parent process simultaneously
38,133,420
<p>I have a script (Python) that uses subprocess to call another script. The parent script writes to the console and a log file at the same time (I used the code from the accepted answer to <a href="http://stackoverflow.com/questions/11325019/output-on-the-console-and-file-using-python/%20%22this%20link:">this question...
0
2016-06-30T21:17:33Z
38,133,631
<p>Thank you <a href="http://stackoverflow.com/users/1491895/barmar">Bamar</a> for the suggestions: using 'a' for both the first and second open() works. If you need to do this for a file that already exists, you can use file.truncate() to empty the file before appending to it.</p>
0
2016-06-30T21:32:25Z
[ "python", "subprocess", "stdout", "tee" ]
Writing to a file from a subprocess and parent process simultaneously
38,133,420
<p>I have a script (Python) that uses subprocess to call another script. The parent script writes to the console and a log file at the same time (I used the code from the accepted answer to <a href="http://stackoverflow.com/questions/11325019/output-on-the-console-and-file-using-python/%20%22this%20link:">this question...
0
2016-06-30T21:17:33Z
38,147,654
<p>Opening a file in <code>'w'</code> mode truncates the file (<a href="https://docs.python.org/3/library/functions.html#open" rel="nofollow">as documented</a>). Opening a file in <code>'a'</code> mode may work on <em>some</em> systems. <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html" rel="...
0
2016-07-01T14:13:29Z
[ "python", "subprocess", "stdout", "tee" ]
How can I reduce the error in my trained values while implementing Artificial Neural Network?
38,133,438
<p>The problem is that I'm getting an error of almost 0.8-1.0 in my trained value which is not acceptable. How do I figure out a way to reduce that error? I've tried reducing the training rate but it didn't work. I'm currently training my system using a dataset in an excel sheet. Here is the link to the sample data set...
0
2016-06-30T21:18:56Z
38,134,540
<p>An artificial neural network accepts a set of hyperparameters that decides the accuracy of classification of your test dataset given that your neural network has been trained on a training dataset. </p> <p><strong>These hyperparameters are:</strong></p> <p><strong>1. Learning rate (most commonly represented by the...
0
2016-06-30T22:56:32Z
[ "python", "machine-learning", "neural-network" ]
Aggregate query in mongo works, in Pymongo do not
38,133,529
<p>I encountered a problem. I try to query this document to obtain the sum the amount and group by the LOC identifier that is outside the "COL" array.</p> <pre><code>{ "_id" : ObjectId("57506d74c469888f0d631be6"), "LOC" : "User001", "COL" : [ { "date" : "25/03/2016", "number" : "Folio009", ...
0
2016-06-30T21:24:58Z
38,135,029
<p>I'm assuming you have a valid connection with MongoDB in python. Following code snippet will return MongoDB cursor in result.</p> <pre><code>pipeline = [ {"$unwind": "$COL"}, {"$group": {"_id": "$LOC", "sum": {"$sum": "$COL.amount"}}} ] cursor = collection.aggregate(pipeline) </code></pre> <p>Now you can ...
1
2016-06-30T23:55:34Z
[ "python", "mongodb", "pymongo" ]
How to loop a text whilst pressing enter (Python)
38,133,571
<p>Is there a way in which I can allow this ">" to come up when the user presses enter or return, instead of doing this:</p> <pre><code>cout = input("&gt;") sip = input("&gt;") vat = input("&gt;") </code></pre>
0
2016-06-30T21:27:46Z
38,133,626
<p>If you want to make a loop that will print ">" on enter try something like this </p> <pre><code>while True: # infinite loop userInput = input("Enter Text: ") if userInput == "": print ("&gt; ") # prints "&gt;" </code></pre>
-1
2016-06-30T21:31:55Z
[ "python" ]
Where is item returned to when I yield an item while scraping data in Python using scrapy?
38,133,651
<p>I wanted to know from where do I access an item or where is it returned when I yield an item in parse function ? See the sample code below </p> <pre><code>from scrapy import Spider from scrapy import Selector import scrapy from scrapy.item import Item,Field class StackItem(Item): title = Field() url = ...
0
2016-06-30T21:33:56Z
38,134,171
<p>The items yielded in a Scrapy callback method are consumed by the Scrapy engine, who forwards that item to the <a href="http://doc.scrapy.org/en/latest/topics/item-pipeline.html" rel="nofollow">Item Pipelines</a>. </p> <p>So, if you want to do further actions on your items (such as data validation, database persist...
0
2016-06-30T22:21:04Z
[ "python", "scrapy", "web-crawler" ]
Python encoded message with HMAC-SHA256
38,133,665
<p>I try to encoded message with HMAC-SHA256 in python according to <a href="https://www.bitstamp.net/api/#account-balance" rel="nofollow">instructions</a></p> <pre><code>import hmac import hashlib nonce = 1234 customer_id = 123232 api_key = 2342342348273482374343434 API_SECRET = 892374928347928347283473 message = n...
0
2016-06-30T21:34:33Z
38,133,770
<p>You're using numbers where the api expects a string/bytes.</p> <pre><code># python 2 import hmac import hashlib nonce = 1234 customer_id = 123232 api_key = 2342342348273482374343434 API_SECRET = 892374928347928347283473 message = '{} {} {}'.format(nonce, customer_id, api_key) signature = hmac.new( str(API_SEC...
1
2016-06-30T21:45:13Z
[ "python", "api", "encode", "hmac" ]
Populating pandas dataframe using conditional group from another dataframe
38,133,689
<p>I have two dataframes, one being a list of teams and scores sorted by date, and the second individual players with the date. I have 60 columns of matching stats in these dataframes, and I am trying to have a code that replaces the values in each column in df2 with the average the opponent had in the dates previous f...
1
2016-06-30T21:37:03Z
38,141,319
<p>I found one solution, perhaps not very elegant, and I'll check back in case anyone actually sees this and has a better one. I created a list of the column headers, then used iterrows to iterate through both each column and row in the column:</p> <pre><code> batcol = pd.DataFrame(df1.columns) batcol = batcol...
0
2016-07-01T09:03:36Z
[ "python", "pandas", "dataframe" ]
How can I implement confidence level in a CNN with tensorflow?
38,133,707
<p>My CNN outputs an array of values that I have to check for the biggest one and take it as the predicted class. Example:</p> <pre><code>-148.7290802 , -133.90687561, -90.850914 , -135.78356934, -128.6325531 , -125.76812744, -85.41909027, -72.3269577 , -103.51300812 </code></pre> <p>For class index 6.</p...
0
2016-06-30T21:38:41Z
38,133,886
<p>Apply <strong>softmax</strong> in the last stage; this will yield posterior probabilities at the final stage. You're already using softmax in the set-up; just use it on the final vector to convert it to RMS probabilities. The <em>confidence</em> of that prediction is simply the probability of the top item.</p> <p...
0
2016-06-30T21:54:52Z
[ "python", "neural-network", "tensorflow", "conv-neural-network" ]
django how to catch a variable of a form in template
38,133,752
<p>I want to use feedback forms in my app. And I have FeedBack model and FeedBackForm form.</p> <h1>models.py:</h1> <pre><code>class Feedback(models.Model): name = models.CharField(max_length=150, blank=True) email = models.EmailField(blank=True) comment = RichTextField() </code></pre> <h1>forms.py:</h1> <pre><code...
1
2016-06-30T21:43:35Z
38,138,023
<p>If I get your question right, you want to call form.name, form.email and form.comment in template? See more at <a href="https://docs.djangoproject.com/ja/1.9/topics/forms/#rendering-fields-manually" rel="nofollow">https://docs.djangoproject.com/ja/1.9/topics/forms/#rendering-fields-manually</a></p>
0
2016-07-01T05:57:32Z
[ "python", "django" ]
How to get text from span tag in BeautifulSoup
38,133,759
<p>I have links looks like this</p> <pre><code>&lt;div class="systemRequirementsMainBox"&gt; &lt;div class="systemRequirementsRamContent"&gt; &lt;span title="000 Plus Minimum RAM Requirement"&gt;1 GB&lt;/span&gt; &lt;/div&gt; </code></pre> <p>I'm trying to get <code>1 GB</code> from there. I tried</p> <pre><code>tt ...
2
2016-06-30T21:44:12Z
38,134,038
<p>You can use a css selector, pulling the span you want using the title text :</p> <pre><code>soup = BeautifulSoup("""&lt;div class="systemRequirementsMainBox"&gt; &lt;div class="systemRequirementsRamContent"&gt; &lt;span title="000 Plus Minimum RAM Requirement"&gt;1 GB&lt;/span&gt; &lt;/div&gt;""", "xml") print(sou...
3
2016-06-30T22:08:12Z
[ "python", "web-scraping", "beautifulsoup", "python-3.4" ]
Converting a dataframe column to float
38,133,785
<p>I have a dataframes called <code>historic_price</code> with two columns called <code>'price'</code> and <code>'item'</code> that I am trying to multiple together storing the result in a different data-frame called <code>dayData</code>, but I get the exception:</p> <pre><code>TypeError: can't multiply sequence by no...
0
2016-06-30T21:46:48Z
38,136,160
<p>It's highly likely you have strings in one of the columns. Try using to_numeric with errors set to 'coerce':</p> <pre><code>df['price'] = pd.to_numeric(df['price'], errors='coerce').fillna(0) df['item'] = pd.to_numeric(df['item'], errors='coerce').fillna(0) df['cash'] = df['price'] * df['item'] </code></pre>
1
2016-07-01T02:34:41Z
[ "python", "pandas" ]
Python - Replacing y values within a certain x range with np.average
38,133,832
<p>I have several regions of a plot that I want to replace. I want to specify an x range, calculate the average of the y values within that range and repeat this process for several more x ranges. At the minute I can only figure out how to replace the y values in each range with the average of all the y values.</p> ...
0
2016-06-30T21:50:16Z
38,134,017
<p>What about something like this where the x "range" is bounded by <code>x0</code> and <code>x1</code>?</p> <pre><code>X = np.linspace(0, 10, 100) Y = X**2 x0 = 2 x1 = 7 Y[(x0 &lt; X) &amp; (X &lt; x1)] = np.average(Y[(x0 &lt; X) &amp; (X &lt; x1)]) </code></pre>
1
2016-06-30T22:06:35Z
[ "python" ]
Python - Replacing y values within a certain x range with np.average
38,133,832
<p>I have several regions of a plot that I want to replace. I want to specify an x range, calculate the average of the y values within that range and repeat this process for several more x ranges. At the minute I can only figure out how to replace the y values in each range with the average of all the y values.</p> ...
0
2016-06-30T21:50:16Z
38,134,863
<p>You can use slices on numpy arrays (in same way as on simple arrays).</p> <pre><code>#no need to loop over X for a, b in zip(xstart, xend): #just replace all values in array with indexes from a to b. y[a:b] = np.average(y[a:b]) </code></pre>
0
2016-06-30T23:34:18Z
[ "python" ]
All subsets of a list without comma at the end of one-element subsets
38,133,850
<p>I want to find all subsets of list [1,2,3]. I use the following code:</p> <pre><code>import itertools def powerset(iterable): xs = list(iterable) # note we return an iterator rather than a list return itertools.chain.from_iterable( itertools.combinations(xs,n) for n in range(len(xs)+1) ) N_set = [1,2,3] ...
-1
2016-06-30T21:52:00Z
38,133,889
<p><code>(1,)</code> is the syntax for a 1-element Python tuple whose only element is <code>1</code>. <code>(1)</code> is just <code>1</code> in grouping parentheses. If you want your output to look like a valid Python data structure, your output is already correct.</p> <p>If you don't want your output to look like a ...
1
2016-06-30T21:55:23Z
[ "python", "python-3.x" ]
Python's Pandas: Getting values from column name inputted as string (as list/array)
38,133,909
<p>I've been using pandas a lot lately, and have run across a slight impasse..</p> <p>I have a pandas data structure, which is read in from a .fits file</p> <pre><code>d = fits.getdata('filename.fits') df = pd.DataFrame(np.array(d)) df.columns = map(str.lower, df.columns) </code></pre> <p>containing column names lik...
0
2016-06-30T21:56:56Z
38,134,463
<p>Everything is working fine for me (pandas 0.18.1):</p> <pre><code>In [28]: col0name = 'n_ser_{}_f850lp'.format('f2mf1') In [29]: col0name Out[29]: 'n_ser_f2mf1_f850lp' In [30]: df[col0name] Out[30]: 285 -4.5086 286 -1.4044 287 NaN 288 2.1634 289 0.3278 Name: n_ser_f2mf1_f850lp, dtype: float64 In ...
0
2016-06-30T22:48:23Z
[ "python", "numpy", "pandas" ]
Python Pointer Ambiguity
38,133,919
<p>Say I have a function foo that takes a list baz, and in foo I wanted to clear baz like so:</p> <pre><code>baz = [] foo(baz) foo(baz): baz = [] </code></pre> <p>Now, this code does not do what I would want it to do, because it creates a new local list called baz. I know that there are other ways of doing this,...
-1
2016-06-30T21:57:51Z
38,133,943
<p>If you intend to clear the items in your list, you would not need to reassign the current name to a new list, just clear the old one by <em>slicing</em>:</p> <pre><code>foo(baz): baz[:] = [] # clears out list baz </code></pre> <p><code>baz[:]</code> is a way of indexing all the items in your list and assigning...
1
2016-06-30T22:00:27Z
[ "python", "list", "pointers" ]
Python Pointer Ambiguity
38,133,919
<p>Say I have a function foo that takes a list baz, and in foo I wanted to clear baz like so:</p> <pre><code>baz = [] foo(baz) foo(baz): baz = [] </code></pre> <p>Now, this code does not do what I would want it to do, because it creates a new local list called baz. I know that there are other ways of doing this,...
-1
2016-06-30T21:57:51Z
38,133,944
<p>Use slicing:</p> <pre><code>&gt;&gt;&gt; def foo(baz): ... baz[:] = [] ... &gt;&gt;&gt; baz = [1, 2] &gt;&gt;&gt; foo(baz) &gt;&gt;&gt; baz [] </code></pre> <p>The <code>my_list[:]</code> tells Python to replace all of the elements in <code>my_list</code> with the content on the right side of the assignment st...
0
2016-06-30T22:00:39Z
[ "python", "list", "pointers" ]
Python Pointer Ambiguity
38,133,919
<p>Say I have a function foo that takes a list baz, and in foo I wanted to clear baz like so:</p> <pre><code>baz = [] foo(baz) foo(baz): baz = [] </code></pre> <p>Now, this code does not do what I would want it to do, because it creates a new local list called baz. I know that there are other ways of doing this,...
-1
2016-06-30T21:57:51Z
38,133,946
<p>If you want to clear the list, use <code>.clear()</code> instead of creating a new list:</p> <pre><code>def foo(baz): baz.clear() </code></pre> <p>Side note: To access the outer <code>baz</code> in your <code>foo()</code> you can to use <a href="https://docs.python.org/2/reference/simple_stmts.html#the-global-...
-1
2016-06-30T22:00:42Z
[ "python", "list", "pointers" ]
Python Pointer Ambiguity
38,133,919
<p>Say I have a function foo that takes a list baz, and in foo I wanted to clear baz like so:</p> <pre><code>baz = [] foo(baz) foo(baz): baz = [] </code></pre> <p>Now, this code does not do what I would want it to do, because it creates a new local list called baz. I know that there are other ways of doing this,...
-1
2016-06-30T21:57:51Z
38,134,033
<p>Python will only treat variable assignment as assigning to a variable from an outer scope if you explicitly tell it to with the <code>global</code> or <code>nonlocal</code> keywords. <code>global</code> is for global variables, and <code>nonlocal</code> is a Python 3-exclusive keyword for closure variables:</p> <pr...
2
2016-06-30T22:07:48Z
[ "python", "list", "pointers" ]
Python Pointer Ambiguity
38,133,919
<p>Say I have a function foo that takes a list baz, and in foo I wanted to clear baz like so:</p> <pre><code>baz = [] foo(baz) foo(baz): baz = [] </code></pre> <p>Now, this code does not do what I would want it to do, because it creates a new local list called baz. I know that there are other ways of doing this,...
-1
2016-06-30T21:57:51Z
38,134,064
<p>Take a look at this post to understand python way of <a href="http://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference">passing parameters by assignment</a>.</p> <p>What is happening is that you are redefining the variable baz to another list, so it doesn't have the reference to the outer baz...
1
2016-06-30T22:10:48Z
[ "python", "list", "pointers" ]
SymPy: parse string as function on manifold
38,133,925
<p>I'm trying to define an equation on a manifold using SymPy, and SymPy's diffgeom package. Since this equation is input by a user, it's sent into the program as a string and is therefore defined prior to the manifold definition in the code. To perform meaningful calculations, I'm trying to replace the "sympified" sym...
1
2016-06-30T21:58:35Z
38,193,161
<p>After further investigation, the cause was having Symbols of the same name. The fix is to essentially substitute using methods described <a href="http://stackoverflow.com/questions/38075445/sympy-swap-two-variables">here</a>, or to use different naming conventions altogether.</p> <p>To perform the substitution, I n...
0
2016-07-04T22:57:51Z
[ "python", "sympy", "substitution", "manifold" ]
Computing custom function on numpy array results in UnpicklingError: NEWOBJ class argument has NULL tp_new
38,133,935
<p>Very strange problem I am running into where using spicy.spacial distance matrix computation works fine, but using a custom function for distance matrix results in a Spark error. </p> <p>My data looks like this:</p> <pre><code>33.848366,-84.3733852,A,1234 33.848237299999994,-84.37318470000001,A,1234 33.8488057,-84...
1
2016-06-30T21:59:35Z
38,191,031
<p>To make it work create a module <code>haversine.py</code>:</p> <pre><code>import pandas as pd import numpy as np def distHaversine(pos1, pos2, r = 6378137): pos1 = pos1 * np.pi / 180 pos2 = pos2 * np.pi / 180 cos_lat1 = np.cos(pos1[..., 0]) cos_lat2 = np.cos(pos2[..., 0]) cos_lat_d = np.cos(pos...
1
2016-07-04T19:16:12Z
[ "python", "numpy", "apache-spark", "scipy", "pyspark" ]
Computing custom function on numpy array results in UnpicklingError: NEWOBJ class argument has NULL tp_new
38,133,935
<p>Very strange problem I am running into where using spicy.spacial distance matrix computation works fine, but using a custom function for distance matrix results in a Spark error. </p> <p>My data looks like this:</p> <pre><code>33.848366,-84.3733852,A,1234 33.848237299999994,-84.37318470000001,A,1234 33.8488057,-84...
1
2016-06-30T21:59:35Z
38,213,449
<p>OK, I don't like answering my own question, but for some strange reason others hit this same problem, I am hoping it can be helpful.</p> <p>I re-wrote the above function to not use the 'ellipsis' operator to index into the array as follows:</p> <pre><code>def distHaversine(pos1, pos2, r = 6378137): pos1 = pos1...
0
2016-07-05T21:56:09Z
[ "python", "numpy", "apache-spark", "scipy", "pyspark" ]
Pandas dataframe fillna() only some columns in place
38,134,012
<p>I am trying to fill none values in a Pandas dataframe with 0's for only some subset of columns.</p> <p>When I do:</p> <pre><code>import pandas as pd df = pd.DataFrame(data={'a':[1,2,3,None],'b':[4,5,None,6],'c':[None,None,7,8]}) print df df.fillna(value=0, inplace=True) print df </code></pre> <p>The output:</p> ...
0
2016-06-30T22:06:16Z
38,134,049
<p>You can select your desired columns and do it by assignment:</p> <pre><code>df[['a', 'b']] = df[['a','b']].fillna(value=0) </code></pre> <p>The resulting output is as expected:</p> <pre><code> a b c 0 1.0 4.0 NaN 1 2.0 5.0 NaN 2 3.0 0.0 7.0 3 0.0 6.0 8.0 </code></pre>
5
2016-06-30T22:09:23Z
[ "python", "python-2.7", "pandas" ]
Project Euler #6 Python
38,134,059
<p>The question I'm trying to solve is here: <a href="https://projecteuler.net/problem=6" rel="nofollow">https://projecteuler.net/problem=6</a></p> <p>I tried this but all that was printed were two zeroes:</p> <pre><code>sumsquare = 0 ssum = 0 def sumsquaredif(n): for i in range(1, n+1): num = i ** 2 ...
-1
2016-06-30T22:10:05Z
38,134,130
<p>Your <code>+=</code> assignments are the wrong way! <code>num += sumsquare</code> is adding the sum to the current number, not the other way around, and similar for <code>ssum</code>. Also, the sum variables should be declared inside of the function.</p> <pre><code>def sumsquaredif(n): sumsquare = 0 # inside f...
2
2016-06-30T22:16:46Z
[ "python", "project" ]
How to run Pylint with PyCharm
38,134,086
<p>I want to configure pylint as an external tool on my entire project directory for a python project that I'm working on. I've tried to use the repository as a module with <code>__init__.py</code> and without, and its not working either way.</p> <p>I'm having difficulty setting up pylint to run with PyCharm. I know t...
0
2016-06-30T22:12:55Z
38,134,478
<p>At first install pylintwith pip: </p> <pre><code>pip install pylint </code></pre> <p>You have to open “Settings > Tools > External Tools” and press the “+” button at PyCharm. </p> <p>Here are an <a href="http://softwaretester.info/integrate-pylint-in-pycharm/" rel="nofollow">example</a> with good settings...
0
2016-06-30T22:49:53Z
[ "python", "python-3.x", "pycharm", "pylint" ]
Find LAN router IP address with Scapy?
38,134,095
<p>I am attempting to find my router's IP address with <a href="http://www.secdev.org/projects/scapy/doc/usage.html" rel="nofollow">Scapy</a>.</p> <p>I am running a distro of Linux and fully understand that I could use system calls or subprocess to get to the routing tables and find the gateway. However, I am trying t...
1
2016-06-30T22:13:33Z
39,308,121
<p>I used the knowledge that if i send a packet to a distant IP adress with ttl = 0, I will get an ICMP packet from the first router i pass(my default gateway), all i'll need to do later is get the IP from that packet</p> <pre><code>from scapy.all import * p = sr1(IP(dst="www.slashdot.org", ttl = 0)/ICMP()/"XXXXXXXXXX...
0
2016-09-03T14:40:08Z
[ "python", "ip-address", "router", "scapy", "gateway" ]
Why is my date column showing up as empty?
38,134,126
<p>I have calculations of a tick data file I get daily that I'm preparing to append to a table daily. The final DataFrame should show the ticker, average spread, max spread, and date. Everything else works fine except for the date column which shows up empty. </p> <p>The tick data itself has a column named 'timestamp'...
0
2016-06-30T22:16:33Z
38,136,085
<p>Use to_datetime to convert to datetime and dt.date to get the date string.</p> <pre><code>df['timestamp'] = pd.to_datetime(df['timestamp']) df['date'] = df.timestamp.dt.date </code></pre>
0
2016-07-01T02:25:34Z
[ "python", "pandas" ]
How chain of `and` operators works in python?
38,134,153
<p>In my program encountered with this:</p> <pre><code>&gt;&gt;&gt; True and True and (3 or True) 3 &gt;&gt;&gt; True and True and ('asd' or True) 'asd' </code></pre> <p>while I expected to get some boolean value depending on the result in brackets. So if I try comparisons like these <code>(0 or True)</code> or <cod...
0
2016-06-30T22:18:30Z
38,134,222
<p>From <a href="https://docs.python.org/3/library/stdtypes.html" rel="nofollow">https://docs.python.org/3/library/stdtypes.html</a>:</p> <blockquote> <p>Important exception: the Boolean operations <em>or</em> and <em>and</em> always return one of their operands</p> </blockquote> <p>The behavior can be most easil...
2
2016-06-30T22:26:22Z
[ "python", "python-3.x" ]
monitor function name error using simpy
38,134,187
<p>very new to python and trying to use a simpy script I found online to queue times. I am getting a name error when I use "Monitor" - which I thought was part of SimPy. Is there somewhere else I should be importing monitor from?</p> <p>Thanks in advance for the help!</p> <p>See below:</p> <pre><code>#!/usr/bin/en...
0
2016-06-30T22:22:47Z
38,134,248
<p>You are currently receiving a <code>name error</code> because <code>Monitor</code> hasn't currently been defined within your script. In order to use the <code>Monitor</code> from within <code>simpy</code>, you will need to either change <code>import simpy</code> to <code>from simpy import Monitor</code> or append <c...
0
2016-06-30T22:27:55Z
[ "python", "simpy" ]
I`m getting an error "[Errno 22] Invalid argument" while trying to open the file
38,134,216
<p>I am trying to write a function which takes a file and returns a list. But it doesn`t work. Instead it says:</p> <p>'IOError: [Errno 22] Invalid argument: 'C:\Python32\x07ssignment3\wordlist.txt''</p> <p>when I am trying to run the module</p> <pre><code>words_file_name = 'C:\Python32\assignment3\wordlist.txt' wor...
0
2016-06-30T22:25:37Z
38,134,259
<p>Escape the backslashes or use a raw string literal. Otherwise, that <code>\a</code> is turning into <code>\x07</code>, which is the hex representation of the escape character <code>\a</code>. I'd recommend using raw strings for this so you don't have to deal with extra backslashes.</p> <pre><code>words_file_name = ...
1
2016-06-30T22:28:38Z
[ "python", "function", "readlines", "invalid-argument" ]
Why won't PyCharm see my libraries?
38,134,361
<p>If I do something like "import selenium" (or any other kind of third party library) in a .py file and then run it from the terminal, it works just fine. But if I make a new file in PyCharm CE and do the same thing, it can't find the library / module.</p> <p>How can I fix this or get it to point in the right locatio...
0
2016-06-30T22:38:43Z
38,134,383
<p>You need to setup your project in PyCharm to use the Python interpreter that has your libraries:</p> <p>Go to: <code>file-&gt;settings-&gt;project-&gt;project interpreter</code></p> <p>And select the appropriate interpreter from the dropdown. After selecting an interpreter, the window displays a list of libraries ...
3
2016-06-30T22:40:47Z
[ "python", "osx", "pycharm", "libraries" ]
No Module named PIL
38,134,362
<p>I know PIL is deprecated, so I installed Pillow instead, and for backward compatibility reason, Pillow is still using PIL as its module name. Here's my <em>pip freeze</em> look like for Pillow: <strong><em>Pillow=3.2.0</em></strong></p> <p>Here's how I use it in my code:</p> <pre><code>import PIL as pillow from P...
0
2016-06-30T22:38:53Z
38,134,849
<p>As per my comment since it helped you out and answered your problem:</p> <p>The issue that you were seeing is that you had pip version 1.5.6, and the version of pip does dictate how packages are unzipped, which ultimately determines whether or not modules are loaded properly.</p> <p>All that is needed is:</p> <pr...
1
2016-06-30T23:32:17Z
[ "python", "python-imaging-library" ]
How to build a sparse matrix in PySpark?
38,134,370
<p>I am new to Spark. I would like to make a sparse matrix a user-id item-id matrix specifically for a recommendation engine. I know how I would do this in python. How does one do this in PySpark? Here is how I would have done it in matrix. The table looks like this now. </p> <pre><code>Session ID| Item ID | Rating ...
0
2016-06-30T22:39:24Z
38,134,814
<p>Like that:</p> <pre><code>&gt;&gt;&gt; from pyspark.mllib.linalg.distributed import CoordinateMatrix, MatrixEntry &gt;&gt;&gt; table = sqlContext.createDataFrame( ... sc.parallelize([[1, 2, 1], [1, 3, 5]]) ... ) &gt;&gt;&gt; mat = CoordinateMatrix(table.rdd.map(lambda row: MatrixEntry(*row))) </code></pre>
0
2016-06-30T23:27:31Z
[ "python", "apache-spark", "pyspark", "sparse-matrix", "recommendation-engine" ]
Dynamic importing modules results in an ImportError
38,134,411
<p>So I've been trying to make a simple program that will dynamically import modules in a folder with a certain name. I cd with <code>os</code> to the directory and I run <code>module = __import__(module_name)</code> as I'm in a for loop with all of the files names described being iterated into the variable module_name...
3
2016-06-30T22:42:55Z
38,134,600
<p>I don't think the interpreter dynamically alters <strong><a href="https://docs.python.org/3.5/library/sys.html#sys.path" rel="nofollow"><code>sys.path</code></a></strong> if you simply change the current directory with <code>os.chdir</code>. You'll manually have to insert the <code>path</code> variable into the <cod...
1
2016-06-30T23:01:35Z
[ "python", "python-3.x", "dynamic", "python-import", "dynamic-import" ]
Dynamic importing modules results in an ImportError
38,134,411
<p>So I've been trying to make a simple program that will dynamically import modules in a folder with a certain name. I cd with <code>os</code> to the directory and I run <code>module = __import__(module_name)</code> as I'm in a for loop with all of the files names described being iterated into the variable module_name...
3
2016-06-30T22:42:55Z
38,134,620
<p>You should use the try-except concept, e.g.:</p> <pre><code>try: import csv except ImportError: raise ImportError('&lt;error message&gt;') </code></pre> <p>If I did understand you correct then</p> <pre><code>try: module = __import__(module_name) except ImportError: raise ImportError('&...
0
2016-06-30T23:04:30Z
[ "python", "python-3.x", "dynamic", "python-import", "dynamic-import" ]
How to let pytest rewrite assert in non-test modules
38,134,430
<p>We defined all our custom assertions in a separate python file which is not a test module.</p> <p>For example: <code>custom_asserts.py</code></p> <pre><code>class CustomAsserts(object): def silly_assert(self, foo, bar): assert foo == bar , 'some error message' </code></pre> <p>If we use <code>assert</...
2
2016-06-30T22:44:33Z
38,138,244
<p>It's kind of wired to answer my own question but I think I found the solution and want to share.</p> <p>The trick is in how pytest collect test modules. We can define <code>python_files</code> in <code>pytest.ini</code> so that pytest will consider more modules as test modules.</p> <p>For example, in my case, all ...
3
2016-07-01T06:12:19Z
[ "python", "py.test" ]
DocuSign API Send Evnelope Python Example Error
38,134,474
<p>I am using the example given by DocuSign to send an envelope using the REST API via Python. I pretty much copy+pasted the code, and assigned the username, password, recipient info, etc (it is not in the code block for obvious reasons). My issue is that I am getting an <code>INVALID_REQUEST_BODY</code> error, specifi...
0
2016-06-30T22:49:37Z
38,149,414
<p>this line:</p> <pre><code>envelopeDef + "\r\n\r\n--BOUNDARY\Dr\n" + \ </code></pre> <p>Had an extra 'D' character in it. Removing it worked. </p>
2
2016-07-01T15:47:31Z
[ "python", "docusignapi" ]
Class inheritance with arbitrary number of **kwargs?
38,134,498
<p>I'm trying to wrap my head around class inheritance, but I can't figure out how to get the <strong>self</strong> values from the Parent class to the Child class in an intuitive way. Ideally, I'd like to be using **kwargs because I may need to add additional keyword-variables to the Parent class.</p> <pre><code>clas...
0
2016-06-30T22:52:07Z
38,134,546
<p>In this case, you can leave off <code>__init__</code> in <code>police_chief</code> entirely.</p> <pre><code>class police_chief(police_officer): """A police officer who is chief.""" </code></pre> <p>In a more general case where the police chief has additional setup to do in <code>__init__</code>, you'd probably...
3
2016-06-30T22:56:48Z
[ "python", "inheritance", "init", "self", "kwargs" ]
CSV File to SQL Insert Statement
38,134,503
<p>I have a CSV file that looks something like this:</p> <pre><code>Date,Person,Time Out,Time Back,Restaurant,Calories,Delicious? 6/20/2016,August,11:58,12:45,Black Bear,850,Y 6/20/2016,Marcellus,12:00,12:30,Brought Lunch,,Y 6/20/2016,Jessica,11:30,12:30,Wendy's,815,N 6/21/2016,August,12:05,1:01,Brought Lunch,,Y </cod...
0
2016-06-30T22:52:36Z
38,134,640
<p>Try this (I ignored the ID part since you can use the mySQL auto_increment)</p> <p>import csv</p> <pre><code>openFile = open('test.csv', 'r') csvFile = csv.reader(openFile) header = next(csvFile) headers = map((lambda x: '`'+x+'`'), header) insert = 'INSERT INTO Table (' + ", ".join(headers) + ") VALUES " for row ...
0
2016-06-30T23:06:35Z
[ "python", "mysql", "python-3.x", "csv", "sql-insert" ]
find, collect duplicates in list of lists/sets
38,134,534
<p>In Python, I have a list of tuples and a list of integers with the same length, e.g.,</p> <pre><code>a = [ [1, 2], [3, 2], [4, 66], [2, 3] ] b = [ 1, 31, 31, 44 ] </code></pre> <p>The k-th entry in <code>a</code> can thought of as being associated with the k-th entry in <...
1
2016-06-30T22:56:04Z
38,134,663
<p>For a:</p> <pre><code>a = [ [1, 2], [3, 2], [4, 66], [2, 3] ] a_set = {frozenset(i) for i in a} a2 = list(list(i) for i in a_set) print(a2) # -&gt; [[66, 4], [1, 2], [2, 3]] </code></pre> <p>Not sure what you're looking for with b.</p> <p>Edit: That makes more sense. @PadraicCunningham's answ...
1
2016-06-30T23:08:51Z
[ "python", "list", "unique" ]
find, collect duplicates in list of lists/sets
38,134,534
<p>In Python, I have a list of tuples and a list of integers with the same length, e.g.,</p> <pre><code>a = [ [1, 2], [3, 2], [4, 66], [2, 3] ] b = [ 1, 31, 31, 44 ] </code></pre> <p>The k-th entry in <code>a</code> can thought of as being associated with the k-th entry in <...
1
2016-06-30T22:56:04Z
38,134,679
<p>if you want to maintain order and group I don't think you won't get much better than grouping with an <em>OrderedDict</em>:</p> <pre><code>from collections import OrderedDict a = [ [1, 2], [3, 2], [4, 66], [2, 3] ] b = [1, 31, 31, 44] d = OrderedDict() for ind, f in enumerate(map(frozenset, a)...
5
2016-06-30T23:10:31Z
[ "python", "list", "unique" ]
Django on Heroku: relation does not exist
38,134,535
<p>I built a Django 1.9 project locally with <code>sqlite3</code> as my default database. I have an application named <code>Download</code> which defines the <code>DownloadedSongs</code> table in <code>models.py</code>:</p> <p>models.py</p> <pre><code>from __future__ import unicode_literals from django.db import mode...
0
2016-06-30T22:56:06Z
38,136,409
<blockquote> <p>As Heroku's dynos don't have a filesystem that persists across deploys, a file-based database like SQLite3 isn't going to be suitable. It's a great DB for development/quick prototypes, though. <a href="http://stackoverflow.com/a/31395988/784648">http://stackoverflow.com/a/31395988/784648</a></p> </blo...
0
2016-07-01T03:07:58Z
[ "python", "django", "python-2.7", "heroku", "django-models" ]
Django on Heroku: relation does not exist
38,134,535
<p>I built a Django 1.9 project locally with <code>sqlite3</code> as my default database. I have an application named <code>Download</code> which defines the <code>DownloadedSongs</code> table in <code>models.py</code>:</p> <p>models.py</p> <pre><code>from __future__ import unicode_literals from django.db import mode...
0
2016-06-30T22:56:06Z
38,139,048
<p>You must not run makemigrations via <code>heroku run</code>. You must run it <em>locally</em>, and commit the result to git. Then you can deploy that code and run those generated migrations via <code>heroku run python manage.py migrate</code>.</p> <p>The reason is that <code>heroku run</code> spins up a new dyno ea...
1
2016-07-01T07:02:19Z
[ "python", "django", "python-2.7", "heroku", "django-models" ]
Raspberry PI: 2 buttons, 2 LEDs
38,134,605
<p>I'm trying to make a Python program with Raspberry Pi that when I push a button, only the red LED brightens, and when I press another button, only the green LED brightens. When no buttons are pushed, all the LEDs are off. But when I try to run it, both LEDs stay on, and when I press the button, the monitor says I pr...
0
2016-06-30T23:02:13Z
38,134,987
<p>You should try removing these lines:</p> <pre><code>while True: #when the button isn't pushed, do this all_leds_off() else: pass </code></pre> <p>and replacing them with:</p> <pre><code>all_leds_off() </code></pre> <p>The callbacks should be fired every button press.</p> <p>Here is another example to lo...
0
2016-06-30T23:50:41Z
[ "python", "raspberry-pi" ]
Raspberry PI: 2 buttons, 2 LEDs
38,134,605
<p>I'm trying to make a Python program with Raspberry Pi that when I push a button, only the red LED brightens, and when I press another button, only the green LED brightens. When no buttons are pushed, all the LEDs are off. But when I try to run it, both LEDs stay on, and when I press the button, the monitor says I pr...
0
2016-06-30T23:02:13Z
38,139,170
<p>I guess you're used to C, where 0-ness is false and non-0-ness is true. In Python there is a distinct boolean type. One effect of this is that testing a variable for true-ness is NOT the same as checking for equality with 1. (IMO that was never a good idea in C anyway, much more robust to check for non-zero).</p> <...
0
2016-07-01T07:09:39Z
[ "python", "raspberry-pi" ]
How to get a SQLite database name in python
38,134,618
<p>Is there a way I can get a SQLite database name in Python. </p> <p>I am using the following code to get the database name:</p> <pre><code>con=sqlite3.connect(":memory:") cursor = con.cursor() cursor.execute("PRAGMA database_list;") curr_table = cursor.fetchall() </code></pre> <p>But the output I get is:</p> <pre...
0
2016-06-30T23:03:52Z
38,134,836
<p>You should be connecting to the actual file - otherwise you cannot view the databases within it.</p> <p>So, you just need to change your code to this:</p> <pre><code>con=sqlite3.connect('/Users/testdb.db') cursor = con.cursor() cursor.execute("PRAGMA database_list;") curr_table = cursor.fetchall() </code></pre>
0
2016-06-30T23:29:54Z
[ "python", "sql", "database", "sqlite3" ]
Data-frame Object has no Attribute
38,134,643
<p>I know that this kind of question was asked before and I've checked all the answers and I have tried several times to find a solution but in vain. In fact I call a Dataframe using Pandas. I've uploaded a csv.file. <a href="http://i.stack.imgur.com/O7rXb.png" rel="nofollow">enter image description here</a> When I ty...
2
2016-06-30T23:06:52Z
38,134,744
<p>I'm going to take a guess. I think the column name that contains <code>"Number"</code> is something like <code>" Number"</code> or <code>"Number "</code>. Notice that I'm assuming you might have a residual space in the column name somewhere. Do me a favor and run <code>print "&lt;{}&gt;".format(data.columns[1])</...
3
2016-06-30T23:17:47Z
[ "python", "csv", "pandas" ]
Data-frame Object has no Attribute
38,134,643
<p>I know that this kind of question was asked before and I've checked all the answers and I have tried several times to find a solution but in vain. In fact I call a Dataframe using Pandas. I've uploaded a csv.file. <a href="http://i.stack.imgur.com/O7rXb.png" rel="nofollow">enter image description here</a> When I ty...
2
2016-06-30T23:06:52Z
38,136,274
<p>Check your DataFrame with <code>data.columns</code></p> <p>It should print something like this </p> <pre><code>Index([u'regiment', u'company', u'name',u'postTestScore'], dtype='object') </code></pre> <p>Check for hidden white spaces..Then you can rename with </p> <pre><code>data = data.rename(columns={'Number '...
1
2016-07-01T02:51:24Z
[ "python", "csv", "pandas" ]