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 |
|---|---|---|---|---|---|---|---|---|---|
Logical operations with array of strings in Python | 39,666,136 | <p>I know the following logical operation works with numpy: </p>
<pre><code>A = np.array([True, False, True])
B = np.array([1.0, 2.0, 3.0])
C = A*B = array([1.0, 0.0, 3.0])
</code></pre>
<p>But the same isn't true if B is an array of strings. Is it possible to do the following: </p>
<pre><code>A = np.array([True, ... | 2 | 2016-09-23T17:08:51Z | 39,666,179 | <p>Since strings may be multiplied by integers, and booleans are integers:</p>
<pre><code>A = [True, False, True]
B = ['eggs', 'milk', 'cheese']
C = [a*b for a, b in zip(A, B)]
# C = ['eggs', '', 'cheese']
</code></pre>
<p>I still uses some kind of loop (same as numpy solution), but it's hidden in concise list compre... | 1 | 2016-09-23T17:11:35Z | [
"python",
"string",
"numpy",
"logical-operators"
] |
Logical operations with array of strings in Python | 39,666,136 | <p>I know the following logical operation works with numpy: </p>
<pre><code>A = np.array([True, False, True])
B = np.array([1.0, 2.0, 3.0])
C = A*B = array([1.0, 0.0, 3.0])
</code></pre>
<p>But the same isn't true if B is an array of strings. Is it possible to do the following: </p>
<pre><code>A = np.array([True, ... | 2 | 2016-09-23T17:08:51Z | 39,667,515 | <p><code>np.char</code> applies string methods to elements of an array:</p>
<pre><code>In [301]: np.char.multiply(B, A.astype(int))
Out[301]:
array(['eggs', '', 'cheese'],
dtype='<U6')
</code></pre>
<p>I had to convert the boolean to integer, and place it second.</p>
<p>Timing in other questions indicates... | 1 | 2016-09-23T18:38:32Z | [
"python",
"string",
"numpy",
"logical-operators"
] |
Html missing when using View page source | 39,666,183 | <p>Im trying to extract all the images from a page. I have used Mechanize Urllib and selenium to extract the Html but the part i want to extract is never there. Also when i view the page source im not able to view the part i want to extract. Instead of the Description i want to extract there is this: </p>
<pre><code> ... | -1 | 2016-09-23T17:11:51Z | 39,666,291 | <p>Possibly you're trying to get elements that are created with a client sided script. I don't think javascript elements run when you just send a GET/POST request (which is what I'm assuming you mean by "view source").</p>
| 0 | 2016-09-23T17:18:21Z | [
"java",
"python",
"html",
"selenium",
"web-scraping"
] |
Function pointer across classes and threads | 39,666,221 | <p>Here is my QT code</p>
<pre><code>from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QTime
from PyQt4.QtGui import QApplication
from keithley.PS2231A import PS2231A
class A(QtGui.QMainWindow, gui.Ui_MainWindow):
def __init__(self, parent=None):
super(A, self).__init__(parent)
self.setupUi... | 0 | 2016-09-23T17:13:43Z | 39,672,550 | <p>You really should revise your question more (see <a href="http://stackoverflow.com/help/mcve">Minimal, Complete and Verifiable</a>), but here is one solution, that should work for at least for both Python 2.7 and 3.5:</p>
<pre><code>import types
class PS2231A:
# Rest of your class
def set_over_current_ca... | 0 | 2016-09-24T04:36:50Z | [
"python",
"qt",
"python-3.x"
] |
matplotlib. legend for one curve | 39,666,246 | <p>I am trying to make a label for a curve</p>
<pre><code>plt.plot([1,2],[1,8])
plt.legend("some text")
plt.show()
</code></pre>
<p>However, there is only one first letter of my text in the graph:
<a href="http://i.stack.imgur.com/rXHsf.png" rel="nofollow"><img src="http://i.stack.imgur.com/rXHsf.png" alt="enter imag... | 0 | 2016-09-23T17:15:17Z | 39,666,481 | <p><code>
plt.plot([1,2],[1,8], label="some text")
plt.legend()
plt.show()</code></p>
| 0 | 2016-09-23T17:31:04Z | [
"python",
"matplotlib",
"plot",
"label"
] |
matplotlib. legend for one curve | 39,666,246 | <p>I am trying to make a label for a curve</p>
<pre><code>plt.plot([1,2],[1,8])
plt.legend("some text")
plt.show()
</code></pre>
<p>However, there is only one first letter of my text in the graph:
<a href="http://i.stack.imgur.com/rXHsf.png" rel="nofollow"><img src="http://i.stack.imgur.com/rXHsf.png" alt="enter imag... | 0 | 2016-09-23T17:15:17Z | 39,666,656 | <p>You can achieve this with out passing any arguments to the <code>legend</code> function by passing a value to the label property of the plot function:</p>
<pre><code>plt.plot([1,2],[1,8],label='some text')
plt.plot([1,2],[1,4],label='some other text')
plt.legend()
plt.show()
</code></pre>
<p>You can find more deta... | 1 | 2016-09-23T17:44:08Z | [
"python",
"matplotlib",
"plot",
"label"
] |
How to run python scripts and do CMD in Dockerfile for the docker container | 39,666,270 | <p>I have an image with a custom Dockerfile. When I start the container, I want to run <code>CMD ["npm, "start"]</code> but right before that, I need to run three scripts.</p>
<p>I've tried:</p>
<p>1)putting the python scripts followed by npm start in a .sh script, and running <code>CMD ["script-location/script.sh"]<... | 0 | 2016-09-23T17:16:54Z | 39,666,587 | <p>Had to run <code>ENTRYPOINT ["script-path/script.sh"]</code></p>
| 0 | 2016-09-23T17:39:25Z | [
"python",
"docker",
"npm",
"dockerfile"
] |
pd.read_csv by default treats integers like floats | 39,666,308 | <p>I have a <code>csv</code> that looks like (headers = first row):</p>
<pre><code>name,a,a1,b,b1
arnold,300311,arnld01,300311,arnld01
sam,300713,sam01,300713,sam01
</code></pre>
<p>When I run:</p>
<pre><code>df = pd.read_csv('file.csv')
</code></pre>
<p>Columns <code>a</code> and <code>b</code> have a <code>.0</co... | 1 | 2016-09-23T17:19:38Z | 39,666,666 | <p>As <a href="http://stackoverflow.com/questions/39666308/pd-read-csv-by-default-treats-integers-like-floats#comment66634324_39666308">root</a> mentioned in the comments, this is a limitation of Pandas (and Numpy). <code>NaN</code> is a float and the empty values you have in your CSV are NaN.</p>
<p>This is listed in... | 1 | 2016-09-23T17:45:09Z | [
"python",
"csv",
"pandas",
"integer"
] |
Port sweep with python | 39,666,387 | <p>Well im trying to do something really simpale but from some reason i just can't understand how to do it.</p>
<p>Im trying to write a simple port sweep
let's say i have a gateway address of 192.168.1.1 all i want to do is to create a for loop to run between 1 to 254 and test what ip address there are over the networ... | 0 | 2016-09-23T17:25:06Z | 39,666,488 | <p>There's a way of doing this in the standard library:</p>
<pre><code>>>> import ipaddress
>>> for addr in ipaddress.IPv4Network('192.168.1.0/24'):
... print(addr)
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3
#more addresses
192.168.1.254
192.168.1.255
</code></pre>
| 0 | 2016-09-23T17:31:36Z | [
"python",
"for-loop",
"networking",
"ping"
] |
Port sweep with python | 39,666,387 | <p>Well im trying to do something really simpale but from some reason i just can't understand how to do it.</p>
<p>Im trying to write a simple port sweep
let's say i have a gateway address of 192.168.1.1 all i want to do is to create a for loop to run between 1 to 254 and test what ip address there are over the networ... | 0 | 2016-09-23T17:25:06Z | 39,666,496 | <p>Use string formatting to accomplish that</p>
<pre><code>'192.168.1.{0}'.format(i)
</code></pre>
<p>Or be a brute and do concatenation</p>
<pre><code>'192.168.1.' + str(i)
</code></pre>
| 1 | 2016-09-23T17:32:03Z | [
"python",
"for-loop",
"networking",
"ping"
] |
Keep the subprocess run | 39,666,405 | <p>I have an exe file build from C++ to get the mouse shape in two states: hand or arrow. But in code it only detects one current time (run in only time and close), the output is state.
I call it in python to get the output in the Windows shell:</p>
<pre><code>output = subprocess.check_output([r'C:\Users\TomCang\Deskt... | 0 | 2016-09-23T17:26:07Z | 39,666,615 | <p>Yes you can. Instead of using the convenient function <code>check_output</code>, you would construct a <a href="https://docs.python.org/3/library/subprocess.html#subprocess.Popen" rel="nofollow"><code>Popen</code> object</a>. This will start the process and let you control it while running. One possibility is to cap... | 0 | 2016-09-23T17:41:12Z | [
"python",
"cursor"
] |
Python - concatenating byte to string cutting off some bytes in string | 39,666,422 | <p>I'm trying to decrypt an image file using Python with the AES cipher. We've been given a key with 15 bytes, and it's our job to decrypt the image running through the first byte. </p>
<p>and what I have so far is:</p>
<pre><code>fifteenbytes = b'\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
for i i... | 1 | 2016-09-23T17:27:06Z | 39,666,543 | <p>You are getting correct output, but you appear to be confused by the <code>repr()</code> output for a <code>bytes</code> value.</p>
<p>Python gives you a value that can safely be copied and pasted back into a Python session. This aids debugging. This display uses ASCII printable text where possible to represent the... | 1 | 2016-09-23T17:35:31Z | [
"python",
"byte",
"aes",
"pycrypto"
] |
Cannot get gcloud to work with Python and Pycharm | 39,666,449 | <p>I am trying to connect to the Google App Engine Datastore from my local machine. I have spent all day digging in to this without any luck.</p>
<p>I have tried the approach here (as well as alot of other suggestions from SO such as <a href="http://stackoverflow.com/questions/27057935/using-gcloud-python-in-gae">Usin... | 1 | 2016-09-23T17:28:42Z | 39,823,292 | <p>The <code>google-cloud</code> library is <a href="https://github.com/GoogleCloudPlatform/google-cloud-python/issues/1893" rel="nofollow">not working on App Engine</a> and most likely you don't even have to since you can use the build in functionality.</p>
<p>From the <a href="https://cloud.google.com/appengine/docs... | 1 | 2016-10-03T01:04:55Z | [
"python",
"google-app-engine",
"gcloud-python",
"google-cloud-python"
] |
Cannot get gcloud to work with Python and Pycharm | 39,666,449 | <p>I am trying to connect to the Google App Engine Datastore from my local machine. I have spent all day digging in to this without any luck.</p>
<p>I have tried the approach here (as well as alot of other suggestions from SO such as <a href="http://stackoverflow.com/questions/27057935/using-gcloud-python-in-gae">Usin... | 1 | 2016-09-23T17:28:42Z | 40,041,928 | <p>I solved it this way:- </p>
<p>1.) Create a lib folder in your project path.</p>
<p>2.) Install gcloud libraries by running following command into terminal from your project path:-</p>
<pre><code> pip install -t lib gcloud
</code></pre>
<p>3.) Create an appengine_config.py module in your project and add follo... | 0 | 2016-10-14T11:20:27Z | [
"python",
"google-app-engine",
"gcloud-python",
"google-cloud-python"
] |
python dash button trigger not working | 39,666,459 | <p>this is my script to see if the amazon dash button is pressed:</p>
<pre><code>from scapy.all import *
def udp_filter(pkt):
options = pkt[DHCP].options
for option in options:
if isinstance(option, tuple):
if 'requested_addr' in option:
print('button pressed')
break
print('Waiting for a b... | 0 | 2016-09-23T17:29:31Z | 39,667,162 | <p>It looks like the error is saying it can't find a DHCP Layer in the packet. Could you add <code>if pkt.haslayer(DHCP):</code> just above <code>options = pkt[DHCP].options</code> like this:</p>
<p><code>def udp_filter(pkt):
if pkt.haslayer(DHCP):
options = pkt[DHCP].options
for option in options... | 0 | 2016-09-23T18:15:37Z | [
"python",
"python-3.x"
] |
Using multiple levels of inheritance with sqlalchemy declarative base | 39,666,510 | <p>I have many tables with identical columns. The difference is the table names themselves. I want to set up a inheritance chain to minimize code duplication. The following single layer inheritance works the way I want it to:</p>
<pre><code>from sqlalchemy import Column, Integer, Text
from sqlalchemy.ext.declarative i... | 0 | 2016-09-23T17:33:07Z | 39,667,190 | <p>An example is in the <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/mixins.html#augmenting-the-base" rel="nofollow">docs</a>. In particular, <code>__abstract__ = True</code> is not necessary. This works fine:</p>
<pre><code>class Base(object):
@declared_attr
def __tablename__(cls):... | 1 | 2016-09-23T18:17:26Z | [
"python",
"sqlalchemy"
] |
How to make requests.post not to wrap dict values in arrays in python? | 39,666,570 | <p>I use python requests.post function to send json queries to my django app.</p>
<pre><code>r = requests.post(EXTERNAL_SERVER_ADDRESS, data={'123':'456', '456':'789'})
</code></pre>
<p>But on the external server request.POST object looks like this:</p>
<p><code><QueryDict: {'123': ['456'], '456': ['789']}></c... | 0 | 2016-09-23T17:38:21Z | 39,666,715 | <p>requests is not doing anything here. Presumably your receiving server is Django; that's just how it represents data from a request. <code>request.POST['123']</code> would still give '456'.</p>
| 1 | 2016-09-23T17:47:43Z | [
"python",
"json",
"python-requests"
] |
How to make requests.post not to wrap dict values in arrays in python? | 39,666,570 | <p>I use python requests.post function to send json queries to my django app.</p>
<pre><code>r = requests.post(EXTERNAL_SERVER_ADDRESS, data={'123':'456', '456':'789'})
</code></pre>
<p>But on the external server request.POST object looks like this:</p>
<p><code><QueryDict: {'123': ['456'], '456': ['789']}></c... | 0 | 2016-09-23T17:38:21Z | 39,666,727 | <p>You are sending a dict, Django transform this JSON in this QueryDict objetc automatically when it receives the message. If you want to parse it to an dict, do:</p>
<pre><code>myDict = dict(queryDict.iterlists())
</code></pre>
| 1 | 2016-09-23T17:48:30Z | [
"python",
"json",
"python-requests"
] |
How to extract x,y data from kdensity plot from matplotlib for python | 39,666,591 | <p>I am trying to figure out how to make a 3d figure of uni-variate kdensity plots as they change over time (since they pull from a sliding time window of data over time). </p>
<p>Since I can't figure out how to do that directly, I am first trying to get the x,y plotting data for kdensity plots of matplotlib in pytho... | 0 | 2016-09-23T17:39:35Z | 39,668,247 | <p>Not sure how kdensity plots work, but note that <code>matplotlib.pyplot.plot</code> returns a list of the added <code>Line2D</code> objects, which are, in fact, where the X and Y data are stored. I suspect they did that to make it work similarly to MATLAB.</p>
<pre><code>import matplotlib.pyplot as plt
h = plt.pl... | 0 | 2016-09-23T19:28:45Z | [
"python",
"matplotlib",
"distribution"
] |
How to extract x,y data from kdensity plot from matplotlib for python | 39,666,591 | <p>I am trying to figure out how to make a 3d figure of uni-variate kdensity plots as they change over time (since they pull from a sliding time window of data over time). </p>
<p>Since I can't figure out how to do that directly, I am first trying to get the x,y plotting data for kdensity plots of matplotlib in pytho... | 0 | 2016-09-23T17:39:35Z | 39,676,657 | <p>The answer was already contained in another thread (<a href="http://stackoverflow.com/questions/4150171/how-to-create-a-density-plot-in-matplotlib">How to create a density plot in matplotlib?</a>). It is pretty easy to get a set of kdensity x's and y's from a set of data. </p>
<pre><code>import matplotlib.pyplot ... | 0 | 2016-09-24T13:06:44Z | [
"python",
"matplotlib",
"distribution"
] |
re.compile only takes two arguments, is there a way to make it take more? Or another way around that? | 39,666,617 | <p>I am able to access an email in txt file form on my computer, and now my goal is to scrape specific data out of it. I have utilized <code>re.compile</code> and <code>enumerate</code> to parse through the email looking for matching words (in my case, fish species such as GOM Cod), and then printing them. But there ar... | 0 | 2016-09-23T17:41:24Z | 39,666,675 | <p>You can <em>alternate</em> between fish species using the vertical bar <code>|</code>:</p>
<blockquote>
<p><code>A|B</code>, where A and B can be arbitrary REs, creates a regular expression
that will match either A or B</p>
</blockquote>
<pre><code>pattern = re.compile(r"GOM Cod|Salmon|Tuna", re.IGNORECASE)
</... | 1 | 2016-09-23T17:45:33Z | [
"python",
"screen-scraping",
"enumerate"
] |
Difference between numpy.float and numpy.float64 | 39,666,638 | <p>There seems to be a subtle difference between numpy.float and numpy.float64.</p>
<pre><code>>>> import numpy as np
>>> isinstance(2.0, np.float)
True
>>> isinstance(2.0, np.float64)
False
</code></pre>
<p>Can someone clarify this? Thanks</p>
| 1 | 2016-09-23T17:42:43Z | 39,666,701 | <p>This would seem to be the difference between a 32-bit floating point number and a 64-bit floating point number (in C, a float vs. a double), and 2.0 ends up being a 32-bit floating point number.</p>
| -1 | 2016-09-23T17:46:55Z | [
"python",
"numpy",
"types"
] |
Difference between numpy.float and numpy.float64 | 39,666,638 | <p>There seems to be a subtle difference between numpy.float and numpy.float64.</p>
<pre><code>>>> import numpy as np
>>> isinstance(2.0, np.float)
True
>>> isinstance(2.0, np.float64)
False
</code></pre>
<p>Can someone clarify this? Thanks</p>
| 1 | 2016-09-23T17:42:43Z | 39,667,343 | <p><code>np.float</code> is an alias for python <code>float</code> type.
<code>np.float32</code> and <code>np.float64</code> are numpy specific 32 and 64-bit float types.</p>
<pre><code>float?
Init signature: float(self, /, *args, **kwargs)
Docstring:
float(x) -> floating point number
Convert a string or num... | 4 | 2016-09-23T18:27:04Z | [
"python",
"numpy",
"types"
] |
Buildozer, How to add external python packages? | 39,666,644 | <p>I have built a kivy app using Python 2.7. I have used the import statements</p>
<pre><code>from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.properties import *
from kivy.uix.textinput import TextInput
from kivy.uix.image import Image
from kivy.uix.im... | 0 | 2016-09-23T17:43:09Z | 39,965,942 | <p>I have been having the same problem. I've narrowed it down to the bs4 library, at the moment i havent got to the bottom of it but i think it is something to do with mixing python 2.7 ans python 3. Anyway the first link is to my (so far) unsolved question.</p>
<p><a href="http://stackoverflow.com/questions/39880264/... | 0 | 2016-10-10T20:05:31Z | [
"java",
"android",
"python",
"python-2.7",
"import"
] |
Python: Animating a vector using mplot3d and animation | 39,666,721 | <p>I'm trying to make a 3d plot with Matplotlib and the animation package from matplotlib. In addition, the animation should be a part of a Gui generated using PyQt and Qt-Designer. Currently I'm stuck on using the "animation.Funcnimation()" correctly, at least i think so...
So here is my code:</p>
<pre><code>import s... | 0 | 2016-09-23T17:48:05Z | 39,679,617 | <p>Since your problem is with the animation part, below you can see a snippet that animate an arrow that is rotating.</p>
<pre><code>import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def data_gen(num):
"""Data generation"""
ang... | 1 | 2016-09-24T18:24:22Z | [
"python",
"qt",
"animation",
"matplotlib"
] |
Python: Animating a vector using mplot3d and animation | 39,666,721 | <p>I'm trying to make a 3d plot with Matplotlib and the animation package from matplotlib. In addition, the animation should be a part of a Gui generated using PyQt and Qt-Designer. Currently I'm stuck on using the "animation.Funcnimation()" correctly, at least i think so...
So here is my code:</p>
<pre><code>import s... | 0 | 2016-09-23T17:48:05Z | 39,795,232 | <p>So if someone is interested in a solution of the mentioned problem, here we go: (again it is not a code for copy-paste because of the missing 'Newsphere.ui', but I try to explain the important snippets)</p>
<pre><code>import sys
from PyQt4.uic import loadUiType
from PyQt4 import QtGui
from matplotlib import pyplot... | 0 | 2016-09-30T15:40:17Z | [
"python",
"qt",
"animation",
"matplotlib"
] |
invalid literal for int() with base 10: '' for map(int, str(num)) | 39,666,826 | <p>I am running a recursive function that takes in a positive integer and a list (that is updated as it runs through the function):</p>
<pre><code>def happy_number(num, tracking_list = []):
if (num == 1):
print 1
else:
digit_list = map(int, str(num))
digit_sum = 0
for n in digi... | 0 | 2016-09-23T17:55:21Z | 39,667,150 | <p>It sounds like you are parsing your numbers from a file, and when a space <code>' '</code> or a newline <code>'\n'</code> shows up (or anything that is not a string digit for that matter), your script will fail. You can try:</p>
<pre><code>def happy_number(num, tracking_list = []):
if (num == 1):
print ... | 0 | 2016-09-23T18:14:29Z | [
"python"
] |
How does "tf.train.replica_device_setter" work? | 39,666,845 | <p>I understood that <code>tf.train.replica_device_setter</code> can be used for automatically assigning the variables always on the same parameter server (PS) (using round-robin) and the compute intensive nodes on one worker.</p>
<p>How do the same variables get reused across multiple graph replicas, build up by diff... | 0 | 2016-09-23T17:56:29Z | 39,681,502 | <p>The <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/train.html#replica_device_setter" rel="nofollow"><code>tf.train.replica_device_setter()</code></a> is quite simple in its behavior: it makes a purely local decision to assign a device to each <a href="https://www.tensorflow.org/versions/r0.10/api... | 1 | 2016-09-24T22:26:09Z | [
"python",
"tensorflow"
] |
Extracting a row from a table from a url | 39,666,890 | <p>I want to download EPS value for all years (Under Annual Trends) from the below link.
<a href="http://www.bseindia.com/stock-share-price/stockreach_financials.aspx?scripcode=500180&expandable=0" rel="nofollow">http://www.bseindia.com/stock-share-price/stockreach_financials.aspx?scripcode=500180&expandable=0<... | 2 | 2016-09-23T17:58:57Z | 39,667,197 | <p>The text is in the <em>td</em> not the <em>tr</em> so get the <em>td</em> using the text and then call <em>.parent</em> to get the <em>tr</em>:</p>
<pre><code>In [12]: table = soup.find('table',{'id' :'acr'})
In [13]: tr = table.find('td', text='EPS').parent
In [14]: print(tr)
<tr><td class="TTRow_left" ... | 2 | 2016-09-23T18:17:56Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Creating a Quote form in Django | 39,667,031 | <p>i am creating a django powered website. Specifically, a courier website. I need to create an application that serves as a quoting app. The user will type in the dimensions of the package into a form and after submitting the form, a price/quote will be returned , based on the dimensions inputted.</p>
<p>I have done ... | 0 | 2016-09-23T18:06:56Z | 39,668,357 | <p>You have redirected to a 'thanks' page after the input is received. You should not have to return anything at this point.</p>
<p>After you have the input of length, breadth and height. You can calculate the price by doing: (Length * Breadth * Height )/ 5000.</p>
<p>This can be stored into a variable 'total_price'.... | 0 | 2016-09-23T19:36:59Z | [
"python",
"html",
"django",
"rest"
] |
Creating a Quote form in Django | 39,667,031 | <p>i am creating a django powered website. Specifically, a courier website. I need to create an application that serves as a quoting app. The user will type in the dimensions of the package into a form and after submitting the form, a price/quote will be returned , based on the dimensions inputted.</p>
<p>I have done ... | 0 | 2016-09-23T18:06:56Z | 39,674,292 | <p>When i submit the form it returns to just the form with my inputs</p>
<p>(views.py)</p>
<pre><code>from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from quote.forms import QuoteForm
def quoting(request):
if request.method == 'GET':
form ... | 0 | 2016-09-24T08:34:56Z | [
"python",
"html",
"django",
"rest"
] |
Accessing data from a JSON file | 39,667,039 | <p>I am quite new with JSON. My code consists in extracting data from a website wich requires a API key. Having extracted the information. I am trying to reach the information which is encoded in son through this format (here is a sample):</p>
<pre><code>[{"number":31705,"name":"31705 - CHAMPEAUX (BAGNOLET)","address"... | -1 | 2016-09-23T18:07:23Z | 39,667,093 | <p>you could convert your <code>json</code> data to dict and then access it like dictionary.
I believe it should be something like</p>
<p><code>data = json.loads(response.content.decode('utf-8'))</code></p>
| 1 | 2016-09-23T18:10:15Z | [
"python",
"json",
"extract"
] |
Accessing data from a JSON file | 39,667,039 | <p>I am quite new with JSON. My code consists in extracting data from a website wich requires a API key. Having extracted the information. I am trying to reach the information which is encoded in son through this format (here is a sample):</p>
<pre><code>[{"number":31705,"name":"31705 - CHAMPEAUX (BAGNOLET)","address"... | -1 | 2016-09-23T18:07:23Z | 39,667,397 | <p>Requests has a builtin JSON decoder, so there's no need to use the json library:</p>
<pre><code>import requests
response = requests.get(url)
data = response.json()
</code></pre>
<p>Based on the details in your question, "data" <em>might</em> be a list of dicts that contain latitude. So to extract the first one m... | 0 | 2016-09-23T18:30:35Z | [
"python",
"json",
"extract"
] |
Accessing data from a JSON file | 39,667,039 | <p>I am quite new with JSON. My code consists in extracting data from a website wich requires a API key. Having extracted the information. I am trying to reach the information which is encoded in son through this format (here is a sample):</p>
<pre><code>[{"number":31705,"name":"31705 - CHAMPEAUX (BAGNOLET)","address"... | -1 | 2016-09-23T18:07:23Z | 39,668,529 | <p>You've messed up your url. I'm not sure what's about <code>HTTP/1.1</code> suffix, but id definitely does not belong here. Also, all parameters in curled brackets looks off.</p>
<pre><code>import requests
r = requests.get('https://api.jcdecaux.com/vls/v1/stations/31705?contract=Paris&apiKey=0617697a9795f803697d... | 1 | 2016-09-23T19:50:42Z | [
"python",
"json",
"extract"
] |
Python vectorizing nested for loops | 39,667,089 | <p>I'd appreciate some help in finding and understanding a pythonic way to optimize the following array manipulations in nested for loops:</p>
<pre><code>def _func(a, b, radius):
"Return 0 if a>b, otherwise return 1"
if distance.euclidean(a, b) < radius:
return 1
else:
return 0
def _... | 11 | 2016-09-23T18:10:01Z | 39,667,248 | <p>Say you first build an <code>xyzy</code> array:</p>
<pre><code>import itertools
xyz = [np.array(p) for p in itertools.product(range(volume.shape[0]), range(volume.shape[1]), range(volume.shape[2]))]
</code></pre>
<p>Now, using <a href="http://docs.scipy.org/doc/numpy-1.10.4/reference/generated/numpy.linalg.norm.h... | 5 | 2016-09-23T18:21:10Z | [
"python",
"numpy",
"vectorization"
] |
Python vectorizing nested for loops | 39,667,089 | <p>I'd appreciate some help in finding and understanding a pythonic way to optimize the following array manipulations in nested for loops:</p>
<pre><code>def _func(a, b, radius):
"Return 0 if a>b, otherwise return 1"
if distance.euclidean(a, b) < radius:
return 1
else:
return 0
def _... | 11 | 2016-09-23T18:10:01Z | 39,667,342 | <p><strong>Approach #1</strong></p>
<p>Here's a vectorized approach -</p>
<pre><code>m,n,r = volume.shape
x,y,z = np.mgrid[0:m,0:n,0:r]
X = x - roi[0]
Y = y - roi[1]
Z = z - roi[2]
mask = X**2 + Y**2 + Z**2 < radius**2
</code></pre>
<p>Possible improvement : We can probably speedup the last step with <code>numexp... | 14 | 2016-09-23T18:26:59Z | [
"python",
"numpy",
"vectorization"
] |
Serperate user input into numeric and alpha charaters | 39,667,123 | <p>I want to take a user input like "3M" or "3 M" and have it print 3000000</p>
<p>where M = 10**6</p>
| -8 | 2016-09-23T18:12:30Z | 39,667,148 | <pre><code>import humanfriendly
user_input = raw_input("Enter a readable file size: ")
Enter a readable file size: 16G
num_bytes = humanfriendly.parse_size(user_input)
print num_bytes
17179869184
print "You entered:", humanfriendly.format_size(num_bytes)
You entered: 16 GB
</code></pre>
<p>I hope this is what you are ... | -1 | 2016-09-23T18:14:24Z | [
"python",
"arrays",
"split"
] |
Using the "i-=smallest" statement in the code below, I intend to alter my original array arr, but that isn't happening. What do I do? | 39,667,130 | <p>Here's the code:</p>
<pre><code>n = int(input())
arr = input().split()
arr = [int(x) for x in arr]
smallest = 1001
while(True):
if smallest==0:
break
arr.sort()
count = 0
smallest = arr[0]
for i in arr:
if i==0:
arr.remove(i)
i-=smallest #This statem... | 1 | 2016-09-23T18:12:53Z | 39,667,464 | <p>Let's look at the inside loop</p>
<pre><code>for i in arr:
if i==0:
arr.remove(i)
i-=smallest
count+=1
</code></pre>
<p>It assigns the first value in <code>arr</code> to <code>i</code>. Since no value of the array is zero, it doesn't remove anything from the list. </p>
<p>It then reassigns the... | 2 | 2016-09-23T18:35:20Z | [
"python",
"arrays",
"python-3.x"
] |
Popup in Kivy Python - show in front | 39,667,142 | <pre><code>from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout
from kivy.uix.modalview import ModalView
from kivy.config import Config
from ai import Ai
from random import randint
class TicTacToe(Stac... | 0 | 2016-09-23T18:14:05Z | 39,668,689 | <p>I suggest you simply open the pop-up after opening your view like</p>
<pre><code>view = ModalView(auto_dismiss=False)
view.add_widget(Label(text='Hello world'))
view.open()
popup = Popup(
title=title,
content=content,
auto_dismiss=True)
popup.open()
</code></pre>
| 0 | 2016-09-23T20:02:14Z | [
"python",
"popup",
"kivy"
] |
How to query for SQLite database column names in Python/Django? | 39,667,191 | <p>I can get all the values from the database for a particular Django model in Python using something like</p>
<pre><code>a = Attorney.objects.all().values_list()
print(a)
</code></pre>
<p>What command would I use to make a similar query but for all the column names in the database?
Also, how would I append all the ... | 0 | 2016-09-23T18:17:35Z | 39,668,198 | <p>If I understand correctly, I think something like the following would do what you're asking about.</p>
<pre><code>import django.apps
models = django.apps.apps.get_models()
for model in models:
field_names = [f.attname for f in model._meta.get_fields()]
for fields in model.objects.values_list(*field_names):
... | 0 | 2016-09-23T19:25:40Z | [
"python",
"django",
"sqlite",
"django-queryset"
] |
printing out date in uniform order and a counter | 39,667,257 | <p>I have been doing these for hours! please help! New to python</p>
<p>example 1990 for input year
and 2000 for end year.</p>
<p>basically i want the output to be </p>
<blockquote>
<p>the years are 1992 1996 2000 </p>
<p>there are 3 counts</p>
</blockquote>
<p>I thought of converting them to a list and usin... | 0 | 2016-09-23T18:21:48Z | 39,667,363 | <p>The problem was when needed year occur, the <code>break</code> stopped your loop.</p>
<pre><code>year = int(raw_input("Input year: "))
end_year = int(raw_input("Input end year:"))
print "The number of leap years are "
counter = 0
temp = []
for x in range(year, end_year+1):
if x % 4 == 0 and (x % 100 != 0 or x... | 1 | 2016-09-23T18:28:29Z | [
"python"
] |
printing out date in uniform order and a counter | 39,667,257 | <p>I have been doing these for hours! please help! New to python</p>
<p>example 1990 for input year
and 2000 for end year.</p>
<p>basically i want the output to be </p>
<blockquote>
<p>the years are 1992 1996 2000 </p>
<p>there are 3 counts</p>
</blockquote>
<p>I thought of converting them to a list and usin... | 0 | 2016-09-23T18:21:48Z | 39,667,405 | <p>You can use the <code>calendar.isleap</code> to count the number of leap years between given years.</p>
<pre><code>from calendar import isleap
year = int(raw_input("Input year: "))
endyear = int(raw_input("Input end year:"))
print "The number of leap years are "
counter = 0
years = []
for x in range(year,endyear+1)... | 1 | 2016-09-23T18:30:58Z | [
"python"
] |
printing out date in uniform order and a counter | 39,667,257 | <p>I have been doing these for hours! please help! New to python</p>
<p>example 1990 for input year
and 2000 for end year.</p>
<p>basically i want the output to be </p>
<blockquote>
<p>the years are 1992 1996 2000 </p>
<p>there are 3 counts</p>
</blockquote>
<p>I thought of converting them to a list and usin... | 0 | 2016-09-23T18:21:48Z | 39,667,523 | <p>you can do it in a shorter way:</p>
<pre><code>from calendar import isleap
years = [ str(x) for x in range(year,endyear+1) if isleap(x)]
print "the years are ", ''.join(elem + " " for elem in years)
print "there are ", len(years), "counts"
</code></pre>
| 0 | 2016-09-23T18:39:04Z | [
"python"
] |
Pandas slicing by element in cell | 39,667,277 | <p>What is the best way to slice by looking for a single element within a cell? I know how to do it with the .isin() function where the cell element is in a list. But I am actually looking for the reverse:</p>
<pre><code>id vals
1 ['wow', 'very', 'such']
2 ['wow', 'such']
3 ['very', 'such']
... | 1 | 2016-09-23T18:22:56Z | 39,667,418 | <p>A <code>list-comprehension</code> to select rows which contain only the string <em>very</em> could be used:</p>
<pre><code>df[['very' in x for x in df['vals'].values]]
</code></pre>
<p><a href="http://i.stack.imgur.com/CwrgU.png" rel="nofollow"><img src="http://i.stack.imgur.com/CwrgU.png" alt="Image"></a></p>
| 2 | 2016-09-23T18:31:37Z | [
"python",
"pandas",
"slice"
] |
Pandas slicing by element in cell | 39,667,277 | <p>What is the best way to slice by looking for a single element within a cell? I know how to do it with the .isin() function where the cell element is in a list. But I am actually looking for the reverse:</p>
<pre><code>id vals
1 ['wow', 'very', 'such']
2 ['wow', 'such']
3 ['very', 'such']
... | 1 | 2016-09-23T18:22:56Z | 39,667,525 | <pre><code>df[df.vals.apply(lambda x: 'very' in x)]
Out[9]:
vals
0 [wow, very, such]
2 [very, such]
</code></pre>
| 1 | 2016-09-23T18:39:11Z | [
"python",
"pandas",
"slice"
] |
elif raises a syntax error, but if does not | 39,667,333 | <p>I get an error when I try to change an "if" to an "elif." The code works perfectly when I'm using an if, but raises a syntax error if I try to use "elif" instead. I need to use "elif" because I only want one of the if statements to run, not both. This code works fine:</p>
<pre><code>guess_row=0
guess_col=0
ship_loc... | 0 | 2016-09-23T18:26:26Z | 39,667,408 | <p><code>elif</code> is not a separate statement. <code>elif</code> is an option part of an existing <code>if</code> statement.</p>
<p>As such, you can only use <code>elif</code> <em>directly</em> after an <code>if</code> block:</p>
<pre><code>if sometest:
indented lines
forming a block
elif anothertest:
... | 4 | 2016-09-23T18:31:08Z | [
"python",
"python-3.x"
] |
how to compare list to text file and delete missing entries | 39,667,383 | <p>If I have a list with different values like <code>Eind, Shf, Asuf</code>.
And a text file with</p>
<pre><code>20:36:00 - Baarn
20:36:00 - Enschede
20:37:00 - Eindhoven
20:37:00 - Eind
20:37:00 - Shf
20:37:00 - Asuf
20:38:00 - Nijmegen
</code></pre>
<p>How do I delete the values in the list from the text file but d... | -1 | 2016-09-23T18:29:40Z | 39,667,462 | <p>I would create a new file:</p>
<p>Given that you have a list like this</p>
<pre><code>to_delete = ['Eind', 'Shf', 'Asuf']
</code></pre>
<p>you can open both your current file and a new file and create a new version</p>
<pre><code>in_file = open('input.txt')
out_file = open('output.txt')
for line in in_file:
... | 1 | 2016-09-23T18:35:15Z | [
"python",
"list",
"text-files"
] |
how to compare list to text file and delete missing entries | 39,667,383 | <p>If I have a list with different values like <code>Eind, Shf, Asuf</code>.
And a text file with</p>
<pre><code>20:36:00 - Baarn
20:36:00 - Enschede
20:37:00 - Eindhoven
20:37:00 - Eind
20:37:00 - Shf
20:37:00 - Asuf
20:38:00 - Nijmegen
</code></pre>
<p>How do I delete the values in the list from the text file but d... | -1 | 2016-09-23T18:29:40Z | 39,667,553 | <p>This is your list:</p>
<pre><code>deletion_list = ["Eind", "Shf", "Asuf"]
</code></pre>
<p>First convert into a set in order to make faster searches:</p>
<pre><code>deletion_set = set(deletion_list)
</code></pre>
<p>Then filter it out:</p>
<pre><code># Open the file in a with statement to make sure it closes co... | 0 | 2016-09-23T18:41:28Z | [
"python",
"list",
"text-files"
] |
PyQt5 Attribute Error: 'GUI' object has no attribute 'setLayout' | 39,667,545 | <p>There seems to be an attribute error when I run my code. Specifically, the error I encounter is:</p>
<pre><code>AttributeError: 'GUI' object has no attribute 'setLayout'
</code></pre>
<p>The code I'm currently using:</p>
<pre><code>class GUI(object):
def __init__(self):
super(GUI,self).__init__()
... | 0 | 2016-09-23T18:41:07Z | 39,667,642 | <p>You get an attribute error because neither your class nor <code>object</code> defines the methods you try to access through <code>self</code>. You need to inherit these from a <code>Qt</code> class that defines them. For example, inheriting from <code>QWidget</code>.</p>
<pre><code>from PyQt5 import QtWidgets
clas... | 1 | 2016-09-23T18:48:02Z | [
"python",
"python-3.x",
"pyqt5"
] |
Why does the result variable update itself? | 39,667,572 | <p>I have the following code:</p>
<p><code>result = datetime.datetime.now() - datetime.timedelta(seconds=60)</code></p>
<pre><code>>>> result.utcnow().isoformat()
'2016-09-23T18:39:34.174406'
>>> result.utcnow().isoformat()
'2016-09-23T18:40:18.240571'
</code></pre>
<p>Somehow the variable is being... | 2 | 2016-09-23T18:42:19Z | 39,667,609 | <p><code>result</code> is a <code>datetime</code> object</p>
<p><code>datetime.utcnow()</code> is a class method of all <code>datetime</code> objects. </p>
<p><code>result</code> is not changing at all. <code>utcnow()</code> is </p>
| 8 | 2016-09-23T18:45:19Z | [
"python",
"datetime"
] |
translate SQL query to flask-sqlalchemy statements | 39,667,585 | <p>I am changing my old SQL implementations of a web app to flask-alchemy and having some difficulties about the correspondence.</p>
<p>The old code looks like this. It does the name query about some properties and returns a csv style text. </p>
<pre><code>header = 'id,display_name,city,state,latitude,longitude\n'
ba... | 0 | 2016-09-23T18:43:17Z | 39,667,708 | <p>If you just want a result set as before, you can do:</p>
<pre><code>results = db.session.query(*(getattr(User, col) for col in cols)).filter_by(...)
</code></pre>
<p>and then you can use <code>results</code> as you did before.</p>
<p>If, OTOH, you want to use the ORM, you can use <a href="http://docs.sqlalchemy.o... | 1 | 2016-09-23T18:52:55Z | [
"python",
"sql",
"sqlalchemy",
"flask-sqlalchemy"
] |
translate SQL query to flask-sqlalchemy statements | 39,667,585 | <p>I am changing my old SQL implementations of a web app to flask-alchemy and having some difficulties about the correspondence.</p>
<p>The old code looks like this. It does the name query about some properties and returns a csv style text. </p>
<pre><code>header = 'id,display_name,city,state,latitude,longitude\n'
ba... | 0 | 2016-09-23T18:43:17Z | 39,667,839 | <p>As it seems that you want to output comma separated values, use the <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">proper module</a> for that. You can override the query's entities with <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.with_entities" rel="no... | 1 | 2016-09-23T19:01:45Z | [
"python",
"sql",
"sqlalchemy",
"flask-sqlalchemy"
] |
How would I create a form for a foreign key field that has a drop down menu with an 'add item' option in django? | 39,667,610 | <p>I'll start with my model fields: </p>
<pre><code>class Store(models.Model):
name = models.CharField(max_length=250)
def __str__(self):
return self.name
class Product(models.Model):
type = models.CharField(max_length=250)
def __str__(self):
return self.type
class Receipt(models... | 0 | 2016-09-23T18:45:20Z | 39,668,094 | <p>Django implements this in terms of <a href="https://docs.djangoproject.com/en/1.10/topics/forms/formsets/" rel="nofollow">a "formset"</a>. Check out this tutorial for additional information: <a href="http://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html" rel="nofollow">http://whoisnicoleharris.co... | 1 | 2016-09-23T19:18:29Z | [
"python",
"django",
"django-forms",
"foreign-keys",
"modelform"
] |
Python 2.7 BeautifulSoup email scraping stops before end of full database | 39,667,624 | <p>Hope you are all well! I'm new and using Python 2.7! I'm tring to extract emails from a public available directory website that does not seems to have API: this is the site: <a href="http://www.tecomdirectory.com/companies.php?segment=&activity=&search=category&submit=Search" rel="nofollow">http://www.... | 0 | 2016-09-23T18:46:26Z | 39,668,546 | <p>You just need to post some data, in particular incrementing <code>group_no</code> to simulate clicking the load more button:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
# you can set whatever here to influence the results
data = {"group_no": "1",
"search": "category",
"segment": ""... | 1 | 2016-09-23T19:51:59Z | [
"python",
"python-2.7",
"web-scraping",
"beautifulsoup"
] |
Need help adding API PUT method to Python script | 39,667,630 | <p>I am using the script below to collect inventory information from servers and send it to a product called Device42. The script currently works however one of the APIs that I'm trying to add uses PUT instead of POST. I'm not a programmer and just started using python with this script. This script is using iron python... | 0 | 2016-09-23T18:46:59Z | 39,667,874 | <p>My standard answer would be to replace urllib2 with the <a href="http://docs.python-requests.org/en/master/" rel="nofollow">Requests</a> package. It makes doing HTTP work a lot easier.</p>
<p>But take a look at <a href="http://stackoverflow.com/a/111988/63802">this SO answer</a> for a 'hack' to get PUT working.</p>... | 0 | 2016-09-23T19:04:10Z | [
"python",
"api",
"put"
] |
Need help adding API PUT method to Python script | 39,667,630 | <p>I am using the script below to collect inventory information from servers and send it to a product called Device42. The script currently works however one of the APIs that I'm trying to add uses PUT instead of POST. I'm not a programmer and just started using python with this script. This script is using iron python... | 0 | 2016-09-23T18:46:59Z | 39,667,889 | <p>Ok first things first you need to understand the difference between PUT and POST. I would write it out but another member of the community gave a very good description of the two <a href="http://stackoverflow.com/questions/107390/whats-the-difference-between-a-post-and-a-put-http-request">here</a>.</p>
<p>Now, yes ... | 1 | 2016-09-23T19:05:08Z | [
"python",
"api",
"put"
] |
Getting 403 (Forbidden) when trying to send POST to set_language view in Django | 39,667,647 | <p>I'm new to Django and am trying to create a small website where I click on a flag and the language changes. I'm using django i18n for that:</p>
<p><strong>urls.py</strong></p>
<pre><code>from django.conf.urls import patterns, include, url
from django.conf.urls.i18n import i18n_patterns
urlpatterns = [url(r'^i18n/... | -1 | 2016-09-23T18:48:26Z | 39,676,214 | <p>Any POST request in django requires you to send the CSRF-Cookie by default. Your options around this:</p>
<ul>
<li>Don't use a POST request. Use GET instead.</li>
<li>Send the CSRF-Token with the request. <a href="https://docs.djangoproject.com/en/1.9/ref/csrf/" rel="nofollow">https://docs.djangoproject.com/en/1.9/... | 0 | 2016-09-24T12:14:36Z | [
"python",
"django",
"internationalization",
"django-i18n"
] |
profiler: can I find what calls my function? | 39,667,657 | <p>I'm working on a tool to visualize Python profile traces, and to do that, it would be useful to know what line a function is called from.</p>
<p>Suppose I have the following simple program:</p>
<pre><code>import time
def my_sleep(x):
time.sleep(x)
def main():
my_sleep(1)
my_sleep(2)
main()
</code></pre>
... | 0 | 2016-09-23T18:49:10Z | 39,667,800 | <p>You may use <a href="https://docs.python.org/3/library/sys.html#sys._getframe" rel="nofollow"><code>sys._getframe(1)</code></a> in order to know the caller like so:</p>
<pre><code>import sys
def my_sleep():
print("Line #" + str(sys._getframe(1).f_lineno))
time.sleep(x)
</code></pre>
<p>Keep in mind doing ... | 0 | 2016-09-23T18:58:53Z | [
"python",
"performance",
"profiling"
] |
How to resolve ImportError: no module named tarfile | 39,667,732 | <p>I am not able to use tarfile module in my python script.</p>
<p>When i run the script i am getting error "ImportError: no module named tarfile"</p>
<p>if i remove "import tarfile" then its failing at tarfile.open;
Error says--NameError: tarfile</p>
<pre><code>def make_tarfile(output_filename, source_dir):
tar... | 0 | 2016-09-23T18:54:20Z | 39,669,613 | <p>I need 50 reputation to comment, so I'll leave an answer instead:</p>
<p>Could you add the following line to your script:</p>
<pre><code>print sys.version
</code></pre>
<p>Just to make absolutely sure the Python version running the script is the same as the one you use as an interpreter. Like people said, maybe a... | 1 | 2016-09-23T21:10:55Z | [
"python",
"jython"
] |
How can I use descriptors for non-static methods? | 39,667,904 | <p>I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it references to, instead of the value in the object.</p>
<p>If I have</p>
<p>Normal use, considering that the method(para... | 0 | 2016-09-23T19:06:06Z | 39,668,135 | <p>Considering <code>method(param)</code> returns a descriptor, you may invoke it manually with a property like so:</p>
<pre><code>class SomeClass(object):
def __init__(self):
self._descriptor = method(param)
@property
def my_attribute(self):
return self._descriptor.__get__(self, self.__c... | 0 | 2016-09-23T19:21:24Z | [
"python",
"python-2.7"
] |
How can I use descriptors for non-static methods? | 39,667,904 | <p>I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it references to, instead of the value in the object.</p>
<p>If I have</p>
<p>Normal use, considering that the method(para... | 0 | 2016-09-23T19:06:06Z | 39,668,294 | <p>Descriptors provide a simple mechanism for variations on the usual patterns of binding functions into methods.</p>
<p>To recap, functions have a <code>__get__()</code> method so that they can be converted to a method when accessed as attributes. The non-data descriptor transforms an <code>obj.f(*args)</code> call i... | 1 | 2016-09-23T19:32:07Z | [
"python",
"python-2.7"
] |
How can I use descriptors for non-static methods? | 39,667,904 | <p>I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it references to, instead of the value in the object.</p>
<p>If I have</p>
<p>Normal use, considering that the method(para... | 0 | 2016-09-23T19:06:06Z | 39,669,564 | <p>Properties are "computed attributes". Properties are implemented using descriptors. If an object's attribute is looked up and a descriptor object is found, the descriptor's getter function will compute the value. </p>
<p><strong>This special rule is valid only at the class level</strong>.</p>
<p>That's why:</p>
<... | 0 | 2016-09-23T21:06:45Z | [
"python",
"python-2.7"
] |
How can I use descriptors for non-static methods? | 39,667,904 | <p>I am aware that I can use descriptors to change static property as if it were a normal property. However, when I try using descriptors for a normal class property, I end up changing the object it references to, instead of the value in the object.</p>
<p>If I have</p>
<p>Normal use, considering that the method(para... | 0 | 2016-09-23T19:06:06Z | 39,693,584 | <p>guys,</p>
<p>Thanks for the help. Out of many great suggestions, I decided to wrap the <strong>set</strong> and <strong>get</strong> methods, thus losing the practicality of descriptors, while keeping the practicality of having a module completely programmed for me. I simply extended the class "PageElement" and cre... | 0 | 2016-09-26T01:38:39Z | [
"python",
"python-2.7"
] |
Sum even and odd number output not correct | 39,667,976 | <blockquote>
<p><strong>INPUTS 1</strong></p>
<p>"1 2 3 4 5 6" <<< YES WITH SPACE</p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 12 and 6 <strong>[x]</strong></li>
<li>The difference between biggest and smallest nu... | -3 | 2016-09-23T19:10:41Z | 39,668,030 | <p>Your <code>else</code> is aligned directly under the <code>for</code> which can also take an <code>else</code>, so the sum of even numbers is taken correctly while the sum of odd numbers is the last value of <code>num</code> in the for loop. You should move your <code>else</code> block to align with the <code>if</co... | 4 | 2016-09-23T19:14:02Z | [
"python"
] |
Sum even and odd number output not correct | 39,667,976 | <blockquote>
<p><strong>INPUTS 1</strong></p>
<p>"1 2 3 4 5 6" <<< YES WITH SPACE</p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 12 and 6 <strong>[x]</strong></li>
<li>The difference between biggest and smallest nu... | -3 | 2016-09-23T19:10:41Z | 39,668,050 | <p>dont have enough rep to comment, but I think the answer is probalby that your else statement is not properly indented...</p>
<p>Also I think the logic on your even and odd count is off, I think it should be something more like:</p>
<p><code>evencount = evencount+1</code></p>
<p>Try this:</p>
<pre><code>even_sum,... | 1 | 2016-09-23T19:15:42Z | [
"python"
] |
Sum even and odd number output not correct | 39,667,976 | <blockquote>
<p><strong>INPUTS 1</strong></p>
<p>"1 2 3 4 5 6" <<< YES WITH SPACE</p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 12 and 6 <strong>[x]</strong></li>
<li>The difference between biggest and smallest nu... | -3 | 2016-09-23T19:10:41Z | 39,668,069 | <p>Your problem is in these lines</p>
<pre><code>evencount = len(numbers)
oddcount = len(numbers)
</code></pre>
<p>In both cases, you end up saying </p>
<pre><code>evencount = all numbers i've encountered
oddcount = all numbers i've encountered
</code></pre>
<p>that is why you get <code>4,4</code> for evencount an... | 3 | 2016-09-23T19:16:45Z | [
"python"
] |
Sum even and odd number output not correct | 39,667,976 | <blockquote>
<p><strong>INPUTS 1</strong></p>
<p>"1 2 3 4 5 6" <<< YES WITH SPACE</p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 12 and 6 <strong>[x]</strong></li>
<li>The difference between biggest and smallest nu... | -3 | 2016-09-23T19:10:41Z | 39,668,880 | <p>You've received corrections to your code from other answers (namely <code>evencount += 1</code>), but just for some potential further investigations into the capabilities of the language here's another approach to the solution.</p>
<p>Python has a strong iterator algebra and in the itertools recipes is <code>partit... | 0 | 2016-09-23T20:16:45Z | [
"python"
] |
Sum even and odd number output not correct | 39,667,976 | <blockquote>
<p><strong>INPUTS 1</strong></p>
<p>"1 2 3 4 5 6" <<< YES WITH SPACE</p>
<blockquote>
<p><strong>Results returned</strong></p>
<ul>
<li>The summation of even and odd numbers are 12 and 6 <strong>[x]</strong></li>
<li>The difference between biggest and smallest nu... | -3 | 2016-09-23T19:10:41Z | 39,672,378 | <p>Problem is with following statements :</p>
<ul>
<li>evencount = len(numbers)</li>
<li>oddcount = len(numbers)</li>
<li>else indentation</li>
</ul>
<p>Solution is ::</p>
<pre><code>even_sum, odd_sum = 0,0
even_count,odd_count = 0,0
s = raw_input("Please Input a series of numbers")
numbers = map(int, s.split())
f... | 0 | 2016-09-24T04:07:40Z | [
"python"
] |
Define a Django model that is shared among many apps | 39,668,055 | <p>How to define a generic Django model (that would perfectly fit in utility/common module), that is going to be used by many apps? I would prefer to define it outside an app, because semantically it does not belong to any of them.
Is it possible? How to deal with the migration of it outside the app?</p>
<p>More speci... | -1 | 2016-09-23T19:15:50Z | 39,668,238 | <p>If the models don't belong to any app, they can certainly be declared in a separate app. I would create a 'global' app with models and views that you might use from other apps. Migrations would function as usual as long as you declare the new app with 'startapp newapp' etc.</p>
| 1 | 2016-09-23T19:28:17Z | [
"python",
"django",
"model-view-controller",
"model"
] |
Define a Django model that is shared among many apps | 39,668,055 | <p>How to define a generic Django model (that would perfectly fit in utility/common module), that is going to be used by many apps? I would prefer to define it outside an app, because semantically it does not belong to any of them.
Is it possible? How to deal with the migration of it outside the app?</p>
<p>More speci... | -1 | 2016-09-23T19:15:50Z | 39,669,373 | <p>If it's something based on the users like in your example, consider <a href="https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-the-existing-user-model" rel="nofollow">extending the user model</a>.</p>
| 0 | 2016-09-23T20:53:14Z | [
"python",
"django",
"model-view-controller",
"model"
] |
determine length (or number of digits) of every row in column | 39,668,138 | <p>I have a dataframe with columns that are <code>floats</code>. Some rows have <code>NaN</code> values.</p>
<p>I want to find rows where the length (or number of digits) of the number is <code>!=6</code>. </p>
<p>I tried the following:</p>
<pre><code>len(str(df['a'])) != 6
</code></pre>
<p>But this seems to only r... | 0 | 2016-09-23T19:21:32Z | 39,668,323 | <p>Cast it to a string and then use the string ops.</p>
<pre><code>df['a'].astype(str).str.len()
</code></pre>
<p>EDIT: To your more complete version, you might just go with:</p>
<pre><code>df[(df['a'].fillna(0) < 100000) & (pd.notnull(df[b]))]
</code></pre>
| 3 | 2016-09-23T19:34:45Z | [
"python",
"pandas"
] |
Python regex not matching | 39,668,156 | <p>I am trying to extract a file name using regex. File names are in the list <code>files</code> , the pattern to be matched is <code>songTitle</code>. </p>
<pre><code> files = listdir(curdir)
print("Pattern : %s" % songTitle)
for songs in files:
print(songs)
re_found = re.match... | 0 | 2016-09-23T19:23:22Z | 39,668,250 | <p>The regular expression actually looks fine, but the problem is in your indentation and in the if statement. Try this:</p>
<pre><code>files = listdir(curdir)
print(files)
print("Pattern : %s" %songTitle)
for songs in files:
re_found = re.match(re.escape(songTitle) + r'.*\.mp3$', songs)
if re_found:
F... | 0 | 2016-09-23T19:28:52Z | [
"python",
"regex"
] |
Python regex not matching | 39,668,156 | <p>I am trying to extract a file name using regex. File names are in the list <code>files</code> , the pattern to be matched is <code>songTitle</code>. </p>
<pre><code> files = listdir(curdir)
print("Pattern : %s" % songTitle)
for songs in files:
print(songs)
re_found = re.match... | 0 | 2016-09-23T19:23:22Z | 39,668,625 | <p>This works:</p>
<pre><code>files = listdir(curdir)
print("Pattern : %s" % songTitle)
for songs in files:
re_found = re.match(re.escape(songTitle) + r'.*\.mp3$', songs)
if re_found:
FileName = re_found.group()
print(FileName)
break
</code></pre>
| 0 | 2016-09-23T19:56:49Z | [
"python",
"regex"
] |
homography and image scaling in opencv | 39,668,174 | <p>I am calculating an homography between two images <code>img1</code> and <code>img2</code> (the images contain mostly one planar object, so the homography works well between them) using standard methods in OpenCV in python. Namely, I compute point matches between the images using sift and then call <code>cv2.findHomo... | 0 | 2016-09-23T19:24:26Z | 39,668,864 | <p>The way I see it, the problem is that homography applies a perspective projection which is a non linear transformation (it is linear only while homogeneous coordinates are being used) that cannot be represented as a normal transformation matrix. Multiplying such perspective projection matrix with some other transfor... | 0 | 2016-09-23T20:14:59Z | [
"python",
"opencv",
"coordinate-transformation",
"homography"
] |
homography and image scaling in opencv | 39,668,174 | <p>I am calculating an homography between two images <code>img1</code> and <code>img2</code> (the images contain mostly one planar object, so the homography works well between them) using standard methods in OpenCV in python. Namely, I compute point matches between the images using sift and then call <code>cv2.findHomo... | 0 | 2016-09-23T19:24:26Z | 39,674,477 | <p>I think your wrong assumption in this passage </p>
<blockquote>
<p><code>H_full_size = A * H * A_inverse</code> where <code>A</code> is the matrix representing the scaling from img1 to small1</p>
</blockquote>
<p>derives from humans "love" from symmetry. Out of the joke, your formula is correct after introducing... | 0 | 2016-09-24T08:55:45Z | [
"python",
"opencv",
"coordinate-transformation",
"homography"
] |
Dataframe column showing half hour intervals | 39,668,193 | <p>I can create an hour of day column in pandas as follows:</p>
<pre><code>data['hod'] = [r.hour for r in data.index]
</code></pre>
<p>This allows me to easily check stats on my data based on the time of day. How can I create a similar column showing every half hour? </p>
<p>Example data:</p>
<pre><code> ... | 1 | 2016-09-23T19:25:26Z | 39,668,441 | <p>Since your index is a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="nofollow"><code>DatetimeIndex</code></a>, it has certain attributes that we can access like <code>hour</code>. Another attribute you may find useful for your task is <code>minute</code>. Something lik... | 2 | 2016-09-23T19:43:56Z | [
"python",
"pandas"
] |
pandas: sort alphabetically if rows have same rank | 39,668,202 | <p>Say I have a dataframe with two rows that have the same value:</p>
<pre><code>testdf = pd.DataFrame({'a': ['alpha','beta','theta','delta','epsilon'],'b':[1,2,3,3,4]})
a b
0 alpha 1
1 beta 2
2 theta 3
3 delta 3
4 epsilon 4
</code></pre>
<p>Now I want to sort them based on column B:</p>... | 1 | 2016-09-23T19:25:50Z | 39,668,293 | <p>It's possible to sort by more than one column using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a>, what you want is to sort by <code>rank</code> first, then by the <code>a</code> column, and if you want it to happen inpla... | 1 | 2016-09-23T19:32:06Z | [
"python",
"pandas"
] |
python: regex - catch variable number of groups | 39,668,228 | <p>I have a string that looks like:</p>
<pre><code>TABLE_ENTRY.0[hex_number]= <FIELD_1=hex_number, FIELD_2=hex_number..FIELD_X=hex>
TABLE_ENTRY.1[hex_number]= <FIELD_1=hex_number, FIELD_2=hex_number..FIELD_Y=hex>
</code></pre>
<p>number of fields is unknown and varies from entry to entry, I want to captur... | 0 | 2016-09-23T19:27:17Z | 39,668,332 | <p>Use a capture group for match unfit lengths:</p>
<pre><code>([A-Z_0-9\.]+\[0x[0-9]+\]=)\s+<(([A-Z_0-9]+)=(0x[0-9]+|0),\s?)*([A-Z_0-9]+)=(0x[0-9]+|0)
</code></pre>
<p>The following part matches every number of fields with trailing comma and whitespace</p>
<pre><code>(([A-Z_0-9]+)=(0x[0-9]+|0),\s?)*
</code></pre... | 1 | 2016-09-23T19:35:42Z | [
"python",
"regex"
] |
python: regex - catch variable number of groups | 39,668,228 | <p>I have a string that looks like:</p>
<pre><code>TABLE_ENTRY.0[hex_number]= <FIELD_1=hex_number, FIELD_2=hex_number..FIELD_X=hex>
TABLE_ENTRY.1[hex_number]= <FIELD_1=hex_number, FIELD_2=hex_number..FIELD_Y=hex>
</code></pre>
<p>number of fields is unknown and varies from entry to entry, I want to captur... | 0 | 2016-09-23T19:27:17Z | 39,668,425 | <p>In short, it's impossible to do all of this in the <code>re</code> engine. You cannot generate more groups dynamically. It will all put it in one group. You should re-parse the results like so:</p>
<pre><code>import re
input_str = ("TABLE_ENTRY.0[0x1234]= <FIELD_1=0x1234, FIELD_2=0x1234, FIELD_3=0x1234>\n"
... | 2 | 2016-09-23T19:42:26Z | [
"python",
"regex"
] |
SQLAlchemy - given a Query object, can you determine if limit has already been applied? | 39,668,254 | <p>If you do a query like this:</p>
<pre><code>models.Article.query.limit(5).limit(10)
</code></pre>
<p>The limit will actually be 10, the 5 is overridden. </p>
<p>I have some code that wants to apply a limit to a <code>Query</code>, but only if one hasn't already been applied. Is there a way to determine if there... | 1 | 2016-09-23T19:29:16Z | 39,668,326 | <p>From what I understand, you can check if there is a <code>_limit</code> private attribute set:</p>
<pre><code>query = models.Article.query.limit(5)
print(query._limit) # prints 5
query = models.Article.query
print(query._limit) # prints None
</code></pre>
<p>This is probably the most direct way to check the pre... | 6 | 2016-09-23T19:34:50Z | [
"python",
"sqlalchemy"
] |
Flask redirect with uploaded file - I/O operation on closed file | 39,668,362 | <p>This app should allow a user to upload a file and then depending on the file type it would perform a save task. If it's a PDF file a new selection page loads prompting the user to select a folder. Once selected the error: <strong>ValueError: I/O operation on closed file</strong> pops up and an <strong>empty PDF</s... | 1 | 2016-09-23T19:37:16Z | 39,675,271 | <p>Flask creates a <a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage.save" rel="nofollow">FileStorage</a> object which is a thin wrapper over incoming files.</p>
<p>The stream attribute of this object usually points to an open temporary file (according to the documentatio... | 1 | 2016-09-24T10:20:55Z | [
"python",
"flask",
"werkzeug"
] |
Creating a new Qapplication from Qapplication event loop | 39,668,472 | <p>I have rewritten the question so that it is more clear.</p>
<p>In my code I created a QApplication, connected a slot to the application using QTimer.singleShot(), then executed my application.</p>
<p>Now in this slot I want to create another QApplication in another process, I used multiprocessing.Process Class and... | -1 | 2016-09-23T19:45:49Z | 39,670,396 | <p>A few problems</p>
<ol>
<li><p>In your code, you're not calling any of the multiprocessing code (maybe a typo)?</p></li>
<li><p>Don't create the first <code>QApplication</code> in the global scope, put it inside a function. Before creating a new process, <code>multiprocessing</code> will copy the global state to t... | 0 | 2016-09-23T22:26:25Z | [
"python",
"qt",
"pyqt",
"multiprocessing",
"qapplication"
] |
How do I store class data in an array and recall this data as needed? | 39,668,488 | <p>I'm trying to create a version of the game Snakeeyes, which will take in n at the start of the program, n being the number of players.<br>
So far, I have managed to get this far:</p>
<pre><code>import random
def rollDice():
dice = random.randint(1, 6)
print "You rolled a", dice
return dice
def addUs... | 0 | 2016-09-23T19:46:49Z | 39,668,623 | <p>Re written player class:</p>
<pre><code>class player():
def __init__(self):
self.score = 0
self.players = []
def addScore(self, dice1, dice2):
if dice1 == 1 or dice2 == 1:
player.score = 0
if dice1 == 1 and dice2 == 1:
print "SNAKE EYES"
... | 0 | 2016-09-23T19:56:29Z | [
"python"
] |
Compose for Elasticsearch Authentication in Python | 39,668,569 | <p>I am having issues getting the Python Elasticsearch library working with the Compose for Elasticsearch offering from Bluemix. When I use the following code against an Elasticsearch cluster I created using IBM containers it connects just fine. </p>
<h3>IBM Container Cluster running Elasticsearch with the Shield Plug... | 0 | 2016-09-23T19:53:48Z | 39,709,295 | <p>in your python code that creates the ES connection you're missing an option.</p>
<p>Add: <code>use_ssl=True</code></p>
<p>It is going to complain at that point about missing certificate validation, but will proceed. To round it out you should use the certificate provided in the VCAP connection info, along with the... | 1 | 2016-09-26T17:52:24Z | [
"python",
"elasticsearch",
"ibm-bluemix",
"compose"
] |
Object order in StackLayout (Kivy) | 39,668,662 | <p>I have a </p>
<pre><code>layout = StackLayout()
</code></pre>
<p>now I put buttons like this</p>
<pre><code>for x in range(9): # range() explanation: http://pythoncentral.io/pythons-range-function-explained/
bt = Button(text=' ', font_size=200, width=200, height=200, size_hint=(None, None), id=str(x+1... | 0 | 2016-09-23T19:59:46Z | 39,669,089 | <p>a possible trick would be:</p>
<pre><code>y = 10
for x in range(y):
bt = Button(text=' ', font_size=200, width=200, height=200, size_hint=(None, None), id=str(y-x))
bt.bind(on_release=self.btn_pressed)
layout.add_widget(bt)
</code></pre>
| 0 | 2016-09-23T20:33:06Z | [
"python",
"layout",
"order",
"kivy"
] |
Object order in StackLayout (Kivy) | 39,668,662 | <p>I have a </p>
<pre><code>layout = StackLayout()
</code></pre>
<p>now I put buttons like this</p>
<pre><code>for x in range(9): # range() explanation: http://pythoncentral.io/pythons-range-function-explained/
bt = Button(text=' ', font_size=200, width=200, height=200, size_hint=(None, None), id=str(x+1... | 0 | 2016-09-23T19:59:46Z | 39,669,259 | <p>Kivy reverses the order here for reasons to do with internal dispatching order. It doesn't have to, but it's a design decision.</p>
<p>However, this really doesn't matter at all. If you want to store your objects in some particular structure, do that yourself.</p>
| 2 | 2016-09-23T20:44:27Z | [
"python",
"layout",
"order",
"kivy"
] |
Format a table that was added to a plot using pandas.DataFrame.plot | 39,668,665 | <p>I'm producing a bar graph with a table using pandas.DataFrame.plot.</p>
<p>Is there a way to format the table size and/or font size in the table to make it more readable?</p>
<p>My DataFrame (dfexe):</p>
<pre><code>City State Waterfalls Lakes Rivers
LA CA 2 3 1
SF CA 4 9 0
Dallas TX 5 6 ... | 0 | 2016-09-23T20:00:00Z | 39,669,727 | <p>Here is an answer.</p>
<pre><code># Test data
dfex = DataFrame({'City': ['LA', 'SF', 'Dallas'],
'Lakes': [3, 9, 6],
'Rivers': [1, 0, 0],
'State': ['CA', 'CA', 'TX'],
'Waterfalls': [2, 4, 5]})
myplot = dfex.plot(x=['City','State'],kind='bar',stacked='True',table=True)
myplot.axes.get_xaxis().set_visible(False)
... | 1 | 2016-09-23T21:21:13Z | [
"python",
"pandas",
"matplotlib"
] |
Python - Multiple line printed image not displaying correctly issues | 39,668,683 | <p>I am having some issues with displaying images for Rock - Paper - Scissors. I'm very new to python (3 weeks) and I am trying to print a multiple line 'image'.<br>
Please excuse my terrible art!</p>
<pre><code>import random
def Display_Rock():
print ("""\n
_---___
/ .#.... \
/ .$../\.. \
|_________/
""")... | 1 | 2016-09-23T20:01:48Z | 39,668,772 | <p>Use <code>r</code> before of your strings like so:</p>
<pre><code>def Display_Rock():
print (r"""
_---___
/ .#.... \
/ .$../\.. \
|_________/
""")
>>> Display_Rock()
_---___
/ .#.... \
/ .$../\.. \
|_________/
</code></pre>
<p>Python treats your <code>\</code> as escape chars.</p>
| 0 | 2016-09-23T20:07:39Z | [
"python",
"printing"
] |
Python - Multiple line printed image not displaying correctly issues | 39,668,683 | <p>I am having some issues with displaying images for Rock - Paper - Scissors. I'm very new to python (3 weeks) and I am trying to print a multiple line 'image'.<br>
Please excuse my terrible art!</p>
<pre><code>import random
def Display_Rock():
print ("""\n
_---___
/ .#.... \
/ .$../\.. \
|_________/
""")... | 1 | 2016-09-23T20:01:48Z | 39,669,096 | <p>While the others are correct, you can also escape the <code>\</code> so that it is not treated specially by adding another <code>\</code>: </p>
<pre><code>print ("""\n
_----_
/ /--\ \\
| \__/ \_________________
\____ \\
/ ------------------\\
/ /--\ ________... | 0 | 2016-09-23T20:33:45Z | [
"python",
"printing"
] |
how to install python module via terminal? | 39,668,695 | <p>Recently while doing a webcrawler project in python, I was using PyCharm and had to download and install an external module.</p>
<p><a href="http://i.stack.imgur.com/gl6He.png" rel="nofollow">Installing on PyCharm</a></p>
<p>Does anyone knows how to install those modules using unix terminal?</p>
| 1 | 2016-09-23T20:02:24Z | 39,668,873 | <p>Pycharm uses pip underneath. If you have pip installed you just type on the terminal:</p>
<pre><code>pip install "module name"
</code></pre>
| 2 | 2016-09-23T20:15:54Z | [
"python",
"pycharm"
] |
Shell restarting rather than running code | 39,668,751 | <p>Trying to draw a straight line using</p>
<pre><code>import turtle
def draw_line():
window =turtle.Screen()
window.bgcolor("blue")
animal=turtle.Turtle ()
animal.forward(100)
window.exitonclick()
draw_line()
</code></pre>
<p>but the shell keeps restarting and doesn't run the code.
Help!</p>
| -1 | 2016-09-23T20:06:11Z | 39,668,956 | <p>I tried to run your code as follows:</p>
<pre><code>import turtle
def draw_line():
window = turtle.Screen()
window.bgcolor('blue')
animal = turtle.Turtle()
animal.forward(100)
window.exitonclick()
draw_line()
</code></pre>
<p>And I can successfully run it.</p>
<p>I saved the above code in a ... | 1 | 2016-09-23T20:23:06Z | [
"python",
"class"
] |
Python: how to check whether Google street view API returns no image or the API key is expired? | 39,668,776 | <p>I want to use <a href="https://developers.google.com/maps/documentation/streetview/" rel="nofollow">Google Street View API</a> to download some images in python.</p>
<p>Sometimes there is no image return in one area, but the API key can be <strong>used</strong>. </p>
<p><a href="http://i.stack.imgur.com/pXSWd.jpg"... | 0 | 2016-09-23T20:07:59Z | 39,669,215 | <p>One way to do this would be to make an api call with the <code>requests</code> library, and parse the JSON response:</p>
<pre><code>import requests
url = 'https://maps.googleapis.com/maps/api/streetview?size=600x300&location=46.414382,10.013988&heading=151.78&pitch=-0.76&key=YOUR_API_KEY'
r = reque... | 1 | 2016-09-23T20:41:47Z | [
"python",
"api",
"google-maps",
"google-maps-api-3",
"google-street-view"
] |
python ctypes array will not return properly | 39,668,820 | <p>This does not work:</p>
<pre><code>def CopyExportVars(self, n_export):
export_array = (ctypes.c_double * n_export)()
self.dll_handle.vs_copy_export_vars(ctypes.cast(export_array, ctypes.POINTER(ctypes.c_double)))
return export_array().contents
</code></pre>
<p>I get this error (<code>n_export</code> i... | 0 | 2016-09-23T20:11:15Z | 39,669,034 | <p>Error is pretty self-explainatory. <code>export_array</code> is not a callable object, but you try to call it in last line of function. Also, you try to use pointer-related interface ('.contents') to retrieve value from array, not pointer to it.</p>
<p>Simplest way to make it work would be to convert <code>ctypes</... | 0 | 2016-09-23T20:28:49Z | [
"python",
"arrays",
"ctypes"
] |
cx_Oracle returning varchar columns with HTML entities | 39,668,841 | <p>When using cx_Oracle to query a database, I have a a column storing text as varchar2. For some reason, if I have "<" or ">" or characters like those stored in the table, then when I query the table it replaces those values with their HTML entity equivalent (ex: "<" becomes "&lt;"). For example:</p>
<p>If... | 0 | 2016-09-23T20:12:41Z | 39,704,817 | <p>You must have some sort of code that is coming between cx_Oracle and your code in order to do this. cx_Oracle returns tuples, not lists, when returning data. As in the following:</p>
<pre><code>[(1, '<span>hi1</span>'), (2, '<span>hi2</span>')]
</code></pre>
<p>Try using python at the comma... | 0 | 2016-09-26T13:54:08Z | [
"python",
"oracle",
"cx-oracle"
] |
How to create a pandas "link" (href) style? | 39,668,851 | <p>From the <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">documentation</a> I realize that it is possible to create styles over pandas dataframes. However, I would like to know if it is possible to create a link style. So far this is what I tried:</p>
<pre><code>def linkify(data_frame... | 0 | 2016-09-23T20:13:51Z | 39,669,278 | <p>You can use the IPython's display.HTML type</p>
<pre><code>from IPython.display import HTML
import pandas as pd
df = pd.DataFrame(['<a href="http://example.com">example.com</a>'])
HTML(df.to_html(escape=False))
</code></pre>
| 0 | 2016-09-23T20:45:44Z | [
"python",
"html",
"python-3.x",
"pandas",
"flask"
] |
Bokeh (Python) Figure.vbar() vs Bar() | 39,668,868 | <p>I'm just starting to take a look at Bokeh for data visualization and am wondering the advantage/disadvantage to using <code>Figure.vbar()</code> vs <code>Bar()</code> if someone could clarify. </p>
| 1 | 2016-09-23T20:15:23Z | 39,824,201 | <p><code>bar</code> is from the high level <strong>Charts</strong> interface. It gives you quick, easy access to bar charts with limited control.</p>
<p><code>vbar</code> is from the mid level <strong>Plotting</strong> interface and gives you more control over the layout of your bar chart. Alternatives to <code>vbar... | 2 | 2016-10-03T03:28:45Z | [
"python",
"bokeh"
] |
read the file and prduce sorted dictionary | 39,668,933 | <p>Create a file with contents: </p>
<pre><code>Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5
</code></pre>
<p>Read this file and create a dictionary with keys of the type tuple and values of the type float i.e., an item of the dictionary should look like this: </p>
<pre><code>(... | 1 | 2016-09-23T20:20:51Z | 39,668,963 | <p>You should also <em>split</em> the keys on comma <code>','</code> and not only <em>strip</em>:</p>
<pre><code>answer[tuple(k.strip().split(','))] = float(v.strip())
</code></pre>
<p>On a side note, you don't need that initial dict stunt code:</p>
<pre><code>answer = {}
with open('sam.txt') as f: # open with conte... | 0 | 2016-09-23T20:23:40Z | [
"python",
"dictionary"
] |
read the file and prduce sorted dictionary | 39,668,933 | <p>Create a file with contents: </p>
<pre><code>Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5
</code></pre>
<p>Read this file and create a dictionary with keys of the type tuple and values of the type float i.e., an item of the dictionary should look like this: </p>
<pre><code>(... | 1 | 2016-09-23T20:20:51Z | 39,669,193 | <p>Its much easier if you have your data in new lines like this:</p>
<pre><code>Mary,Jane : 5.8
Mary,Doe : 6.0
John,Doe : 6.3
John,Muller : 5.6
Mary,Muller : 6.5
</code></pre>
<p>and then the code would be :</p>
<pre><code>f = open('data.txt', 'r')
answer = {}
for line in f:
k, v = ((line.strip()).split(':')... | 0 | 2016-09-23T20:40:19Z | [
"python",
"dictionary"
] |
read the file and prduce sorted dictionary | 39,668,933 | <p>Create a file with contents: </p>
<pre><code>Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5
</code></pre>
<p>Read this file and create a dictionary with keys of the type tuple and values of the type float i.e., an item of the dictionary should look like this: </p>
<pre><code>(... | 1 | 2016-09-23T20:20:51Z | 39,674,414 | <p>I did answer like this may i know is there any further upgrade needed to it to make it more efficient</p>
<pre><code>f = open('sam.txt')
answer = {tuple(x.split(':')[0].strip().split(',')): float(x.split('[1].strip()) for x in f}
print "\ndictionary taken from file is:\n"
print answer
c = answer.items()
d = sor... | 0 | 2016-09-24T08:49:40Z | [
"python",
"dictionary"
] |
read the file and prduce sorted dictionary | 39,668,933 | <p>Create a file with contents: </p>
<pre><code>Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5
</code></pre>
<p>Read this file and create a dictionary with keys of the type tuple and values of the type float i.e., an item of the dictionary should look like this: </p>
<pre><code>(... | 1 | 2016-09-23T20:20:51Z | 39,674,647 | <p>Built-in functions are often useful, but sometimes all you need is a simple regular expression:</p>
<pre><code># Generate file
txt = "Mary,Jane : 5.8 Mary,Doe : 6.0 John,Doe : 6.3 John,Muller : 5.6 Mary,Muller : 6.5"
with open("out.txt","w+") as FILE: FILE.write(txt)
# Read file and grab content
content= [ re.find... | 0 | 2016-09-24T09:14:26Z | [
"python",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.