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 |
|---|---|---|---|---|---|---|---|---|---|
Cloud Pub/Sub Demo : 403 User not authorized to perform this action. when try to push notification | 37,623,509 | <p>I am learning Google Cloud Pub/Sub and following this official document : <a href="https://cloud.google.com/appengine/docs/flexible/python/writing-and-responding-to-pub-sub-messages#prerequisites" rel="nofollow">Writing and Responding to Pub/Sub Messages - Python</a></p>
<p>When I deploy it to cloud, and try to sub... | 0 | 2016-06-03T21:13:52Z | 37,862,595 | <p>Make sure that the client you are using is authorized to publish to Pub/Sub. See <a href="https://cloud.google.com/pubsub/access_control" rel="nofollow">details here</a>. If your client belongs to the same project as the topic, typically it won't require additional access control configuration. Make sure that your c... | 1 | 2016-06-16T14:50:19Z | [
"python",
"google-app-engine",
"google-cloud-platform",
"google-cloud-pubsub"
] |
Cloud Pub/Sub Demo : 403 User not authorized to perform this action. when try to push notification | 37,623,509 | <p>I am learning Google Cloud Pub/Sub and following this official document : <a href="https://cloud.google.com/appengine/docs/flexible/python/writing-and-responding-to-pub-sub-messages#prerequisites" rel="nofollow">Writing and Responding to Pub/Sub Messages - Python</a></p>
<p>When I deploy it to cloud, and try to sub... | 0 | 2016-06-03T21:13:52Z | 37,890,277 | <p>Here are some notes come from google's documentation <a href="https://cloud.google.com/pubsub/troubleshooting#403" rel="nofollow">Troubleshooting 403 (Forbidden) error</a> : </p>
<blockquote>
<p>If you get this error, do the following:</p>
<ul>
<li>Make sure you've enabled the Google Cloud Pub/Sub API in t... | 0 | 2016-06-17T20:57:51Z | [
"python",
"google-app-engine",
"google-cloud-platform",
"google-cloud-pubsub"
] |
Is there a shorthand for repeated reassignment of a variable? | 37,623,525 | <p>Consider the example:</p>
<pre><code>x = 27
x = sqr(x)
x += 2
x = x * 0.1
</code></pre>
<p>This could trivially be reduced to</p>
<pre><code>x = 0.1 * (sqr(27) + 2)
</code></pre>
<p>Now, consider (x as an OrderedDict)</p>
<pre><code>x = {k: bubble_sort(v) for k, v in x.items()}
x = {k: rename(k) for k, v in x.... | 2 | 2016-06-03T21:15:14Z | 37,623,964 | <p>In the <code>operator</code> module there is the <a href="https://docs.python.org/3/library/operator.html#operator.methodcaller" rel="nofollow"><code>operator.methodcaller</code></a> function. It works like <code>itemgetter</code>, which is the one you are most likely to have already seen: given a <em>name,</em> the... | 1 | 2016-06-03T21:49:10Z | [
"python",
"python-2.7"
] |
Accessing Google Drive Files in Google App Engine [Shareable Link] | 37,623,527 | <p>I have an android app that saves an image into the Google Drive and shares the weblink to my Google App Engine server (python).</p>
<pre><code> // Create client
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addConnectionCallba... | 0 | 2016-06-03T21:15:16Z | 37,629,612 | <p>In python, you must do something like this</p>
<pre><code>@decorator.oauth_required
def get(self):
try:
http = decorator.http()
service = discovery.build("drive", "v2", http=http)
# Make the list of every files in the user's Drive
# Take every fields we will need after
f... | 0 | 2016-06-04T11:23:25Z | [
"android",
"python",
"google-app-engine",
"google-drive-sdk",
"file-sharing"
] |
Content between two span class | 37,623,543 | <p>I am trying to parse out a HTML page using beautiful soup and save it as smaller HTML files. I have two questions:
1. Is there a way that I can get content between two spans, for example:</p>
<pre><code><SPAN CLASS="c7">Q2 2016 Apple Inc Earnings Call - Final</SPAN> I am feeling lucky today <... | -2 | 2016-06-03T21:16:28Z | 37,624,021 | <pre><code>import re
text= '''<SPAN CLASS="c7">Q2 2016 Apple Inc Earnings Call - Final</SPAN> I am feeling lucky today <SPAN CLASS="c7">Event Brief of Q1 2016 Apple Inc Earnings Call - Final</SPAN>'''
text2= '<span></span>You<span>Hola</span>Hey<span></span&... | -1 | 2016-06-03T21:53:35Z | [
"python",
"html",
"beautifulsoup"
] |
Opening webpage and returning a dict of all the links and their text | 37,623,594 | <p>I'm trying to open a webpage and return all the links as a dictionary that would look like this.</p>
<pre><code>{"http://my.computer.com/some/file.html" : "link text"}
</code></pre>
<p>So the link would be after the href= and the text would be between the > and the <code></a></code></p>
<p>I'm using <code>h... | 0 | 2016-06-03T21:20:27Z | 37,623,970 | <p>The issue is that you're attempting to compare a byte string to a regular string. If you add <code>print(line)</code> as the first command in your for loops, you'll see that it will print a string of HTML but it will have a b' at the beginning, indicating it's not utf-8 encoding. This makes things difficult. The ... | 0 | 2016-06-03T21:49:55Z | [
"python"
] |
Opening webpage and returning a dict of all the links and their text | 37,623,594 | <p>I'm trying to open a webpage and return all the links as a dictionary that would look like this.</p>
<pre><code>{"http://my.computer.com/some/file.html" : "link text"}
</code></pre>
<p>So the link would be after the href= and the text would be between the > and the <code></a></code></p>
<p>I'm using <code>h... | 0 | 2016-06-03T21:20:27Z | 37,624,254 | <p>For what it's worth, here is a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><code>BeautifulSoup</code></a> and <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a> approach. </p>
<p>Feel free to replace <code>requests</code> with <code>urll... | 0 | 2016-06-03T22:17:38Z | [
"python"
] |
Unable to delete User objects in Django | 37,623,629 | <p>I have a try except block in one of my Django view functions that will delete a User object that was created in the try block if anything should fail. When I attempt to delete the User I get this error message. </p>
<pre><code>OperationalError: no such table: reversion_revision
</code></pre>
<p>The same issue happ... | 0 | 2016-06-03T21:22:38Z | 37,623,715 | <p>Problem here is not in your code but in your database state. Looks like you added <code>django reversion</code> app. Which adds new Models in your project. Run</p>
<pre><code>python manage.py syncdb
</code></pre>
<p>or if you in 1.8+</p>
<pre><code>python manage.py migrate
</code></pre>
<p><strong>Update</strong... | 1 | 2016-06-03T21:28:46Z | [
"python",
"django",
"exception",
"user"
] |
Unable to delete User objects in Django | 37,623,629 | <p>I have a try except block in one of my Django view functions that will delete a User object that was created in the try block if anything should fail. When I attempt to delete the User I get this error message. </p>
<pre><code>OperationalError: no such table: reversion_revision
</code></pre>
<p>The same issue happ... | 0 | 2016-06-03T21:22:38Z | 37,623,767 | <p>Try running</p>
<p><code>./manage.py makemigrations revisions</code></p>
<p>then</p>
<p><code>./manage.py migrate</code></p>
<p>or just delete the db file and start over with</p>
<p><code>./manage.py migrate</code></p>
| 0 | 2016-06-03T21:32:22Z | [
"python",
"django",
"exception",
"user"
] |
Python Error When creating a .py file from a .ui file (from Qt designer) | 37,623,661 | <p>I tried a lot of technics but nothing work, I want to convert my .ui file to a .py file, using the pyuic4 in cmd, but the result is :
from PyQt4 import QtCore
ImportError: DLL load failed: %1 [...] is not a valid Win32 application</p>
<p>I'm using a 64bits system with python27 and "PyQt4-4.11.4-gpl-Py2.7-Qt4.8.... | 0 | 2016-06-03T21:24:30Z | 37,623,811 | <p>Maybe try PYQT 3. Version 4 has some bugs in it</p>
| 0 | 2016-06-03T21:36:02Z | [
"python",
"qt",
"user-interface"
] |
Expose Python standard IO to Subprocess | 37,623,664 | <p>On Python 3.5.1, I have the following:</p>
<pre><code>output = subprocess.check_output(cmd).decode(encoding="UTF-8")
</code></pre>
<p>This calls the properly invoked command <code>cmd</code>. C++14 code in <code>cmd</code> looks like:</p>
<pre><code>HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
assert(handle!... | 0 | 2016-06-03T21:24:44Z | 37,634,334 | <p>A pipe is not a console. <code>check_output()</code> uses <code>stdout=PIPE</code> internally. It won't redirect the console output (produced by <code>WriteConsoleW()</code>). </p>
<p>The first error (invalid handle) suggests that the standard output is not the console device. </p>
<p>Unless it is a desired behavi... | 2 | 2016-06-04T19:44:08Z | [
"python",
"c++",
"windows",
"subprocess",
"stdio"
] |
Learning Python: is there a better way to create dictionaries from a string list than this? | 37,623,682 | <p>I am going through the Code Academy lessons on python and one lesson wants you to do the following.</p>
<p>Make three dictionaries named "lloyd", "alice", and "tyler. Then for each dictionary set the key name equal to "Lloyd", "Alice", and "Tyler" respectively. Then each dictionary should have three keys (homework,... | -1 | 2016-06-03T21:26:08Z | 37,624,180 | <p>Here is an alternative way of doing it by setting a main dictionary holding each students information as a dictionary on its own.</p>
<pre><code>students = ["lloyd", "alice", "tyler"]
students_dicts = {}
for s in students:
students_dicts[s.capitalize()] = {'homework': [], 'quizzes': [], 'tests': []}
# if the si... | 0 | 2016-06-03T22:10:05Z | [
"python"
] |
Having trouble extracting rtmp stream in both VLC and python, can't find direct stream location | 37,623,698 | <p>The "Smoken Tuna Bar", located in the florida keys, has a live webcam: <a href="http://www.smokintunasaloon.com/bar-cam.php" rel="nofollow">http://www.smokintunasaloon.com/bar-cam.php</a></p>
<p>And after going through the page source, the only camera link is here: <a href="http://www.floridakeyswebcams.tv/client-c... | 0 | 2016-06-03T21:27:11Z | 37,627,588 | <blockquote>
<p>If anyone could show me where the video is streaming from...</p>
</blockquote>
<p>An <code>RTMP</code> link is made of two parts : <strong>server</strong> and <strong>stream</strong>. Combine them to make the full URL.<br></p>
<p>Here your <strong>server</strong> is the <code>netConnectionUrl</code>... | 1 | 2016-06-04T07:25:09Z | [
"python",
"flash",
"vlc",
"rtmp",
"flowplayer"
] |
using pandas read_csv with missing data | 37,623,713 | <p>I am attempting to read a csv file where some rows may be missing chunks of data.</p>
<p>This seems to be causing a problem with the pandas read_csv function when you specify the dtype. The problem appears that in order to convert from the str to whatever the dtype specifies pandas just tries to cast it directly. ... | 0 | 2016-06-03T21:28:29Z | 37,624,007 | <p>Try this: </p>
<pre><code>import pandas as pd
import numpy as np
import io
datfile = io.StringIO(u"12 23 43| | 37| 12.23| 71.3\n12 23 55|X| | | 72.3")
names = ['id', 'flag', 'number', 'data', 'data2']
dtypes = [np.str, np.str, np.str, np.float, np.float]
dform = {name: dtypes[ind] for ind, name in enume... | 1 | 2016-06-03T21:53:04Z | [
"python",
"csv",
"numpy",
"pandas"
] |
using pandas read_csv with missing data | 37,623,713 | <p>I am attempting to read a csv file where some rows may be missing chunks of data.</p>
<p>This seems to be causing a problem with the pandas read_csv function when you specify the dtype. The problem appears that in order to convert from the str to whatever the dtype specifies pandas just tries to cast it directly. ... | 0 | 2016-06-03T21:28:29Z | 37,624,922 | <p>So, as Merlin pointed out, the main problem is that nan's can't be ints, which is probably why pandas acts this way to begin with. I unfortunately didn't have a choice so I had to make some changes to the pandas source code myself. I ended up having to change lines 1087-1096 of the file parser.pyx to</p>
<pre><co... | 0 | 2016-06-03T23:42:00Z | [
"python",
"csv",
"numpy",
"pandas"
] |
How can I get a list of hosts from an Ansible inventory file? | 37,623,849 | <p>Is there a way to use the Ansible Python API to get a list of hosts from a given inventory file / group combination?</p>
<p>For example, our inventory files are split up by service type:</p>
<pre><code>[dev:children]
dev_a
dev_b
[dev_a]
my.host.int.abc.com
[dev_b]
my.host.int.xyz.com
[prod:children]
prod_a
pro... | 2 | 2016-06-03T21:39:13Z | 37,624,444 | <p>Do the same trick from before, but instead of <code>all</code>, pass the group name you want to list:</p>
<p><code>ansible (group name here) -i (inventory file here) --list-hosts</code></p>
| 3 | 2016-06-03T22:40:16Z | [
"python",
"ansible",
"ansible-2.x"
] |
How can I get a list of hosts from an Ansible inventory file? | 37,623,849 | <p>Is there a way to use the Ansible Python API to get a list of hosts from a given inventory file / group combination?</p>
<p>For example, our inventory files are split up by service type:</p>
<pre><code>[dev:children]
dev_a
dev_b
[dev_a]
my.host.int.abc.com
[dev_b]
my.host.int.xyz.com
[prod:children]
prod_a
pro... | 2 | 2016-06-03T21:39:13Z | 37,630,085 | <p>I was struggling with this as well for awhile, but found a solution through trial & error.</p>
<p>One of the key advantages to the API is that you can pull variables and metadata, not just hostnames.</p>
<p>Starting from <a href="http://docs.ansible.com/ansible/developing_api.html#python-api-2-0" rel="nofollow... | 3 | 2016-06-04T12:11:07Z | [
"python",
"ansible",
"ansible-2.x"
] |
Assigning the value of a tensor by its name | 37,623,979 | <p>I'm grabbing a tensor inside a TensorFlow graph using the following code:</p>
<pre><code>names = [var.name for var in self.graph.get_collection('trainable_variables')]
tensor = graph.get_tensor_by_name(names[0])
sess.run(tensor)
</code></pre>
<p>How can I set the value of the <code>tensor</code>?</p>
| 0 | 2016-06-03T21:50:58Z | 37,624,060 | <p>Most TensorFlow tensors (<code>tf.Tensor</code> objects) are <em>immutable</em>, so you cannot simply assign a value to them. However, if you created the tensor as a <a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/state_ops.html#Variable" rel="nofollow"><code>tf.Variable</code></a>, you can assign ... | 2 | 2016-06-03T21:58:30Z | [
"python",
"tensorflow"
] |
How to capture prompts in stdout/stderr? | 37,624,020 | <p>I'm trying to record a user's terminal session in a log file; fairly simply, I made a Python wrapper for <code>ghci</code> (interactive Haskell) that looks like:</p>
<pre><code>#!/usr/bin/env python
import os
cmd = 'ghci 2>&1 | tee hs.log'
os.system(cmd)
</code></pre>
<p>However, this only captures what i... | 1 | 2016-06-03T21:53:35Z | 37,624,142 | <p>You can use the <a href="http://man7.org/linux/man-pages/man1/script.1.html" rel="nofollow"><code>script</code></a> command to capture both input and output.</p>
<pre><code>cmd = 'script hs.log ghci'
</code></pre>
<p>Note that this captures all the raw input and output from the terminal. You'll see all the user's ... | 3 | 2016-06-03T22:06:29Z | [
"python",
"unix",
"haskell",
"pipe",
"tee"
] |
How to remove dict keys if value is empty | 37,624,043 | <p>In my form post request I'm grabbing all form info, but it seems as though there are some empty keys and values. I'd like to remove all instances of empty keys and values. This what I have so far, and it's obviously not working. </p>
<pre><code>post_dict = dict(request.POST)
item_data = {}
for key, value in post_d... | 1 | 2016-06-03T21:56:24Z | 37,624,104 | <p>Try this,</p>
<pre><code>post_dict = {'': '', 'item_data[username]': ['johndoe'], 'item_data[email]': ['johndoe@gmail.com'], 'item_data[campus]': ['madison']}
item_data = {}
for key, value in post_dict.items():
strlist = key.split('[')
if len(strlist) == 1:
continue
new_key = strlist[1].replac... | 0 | 2016-06-03T22:03:14Z | [
"python"
] |
How to remove dict keys if value is empty | 37,624,043 | <p>In my form post request I'm grabbing all form info, but it seems as though there are some empty keys and values. I'd like to remove all instances of empty keys and values. This what I have so far, and it's obviously not working. </p>
<pre><code>post_dict = dict(request.POST)
item_data = {}
for key, value in post_d... | 1 | 2016-06-03T21:56:24Z | 37,624,194 | <pre><code>for key, value in post_dict.items():
</code></pre>
<p>In your code you are iterating on <code>post_dict</code>.
However, in the line <code>del post_dict[key]</code> you are modifying the iterator, so it will provide an inconsistent view of the dictionary to <code>for</code>. It is not good to add or delete ... | 1 | 2016-06-03T22:11:08Z | [
"python"
] |
How to remove dict keys if value is empty | 37,624,043 | <p>In my form post request I'm grabbing all form info, but it seems as though there are some empty keys and values. I'd like to remove all instances of empty keys and values. This what I have so far, and it's obviously not working. </p>
<pre><code>post_dict = dict(request.POST)
item_data = {}
for key, value in post_d... | 1 | 2016-06-03T21:56:24Z | 37,624,195 | <p>Maybe you can do what you want using one of these:</p>
<pre><code>dict_1 = {'': '', 'username': 'johndoe', 'email':'', }
dict_2 = dict(x for x in dict_1.iteritems() if any(x))
print dict_2 # {'username': 'johndoe', 'email': ''}
dict_3 = dict(x for x in dict_1.iteritems() if all(x))
print dict_3 # {'username': '... | 1 | 2016-06-03T22:11:16Z | [
"python"
] |
How to remove dict keys if value is empty | 37,624,043 | <p>In my form post request I'm grabbing all form info, but it seems as though there are some empty keys and values. I'd like to remove all instances of empty keys and values. This what I have so far, and it's obviously not working. </p>
<pre><code>post_dict = dict(request.POST)
item_data = {}
for key, value in post_d... | 1 | 2016-06-03T21:56:24Z | 37,624,208 | <p>Try this:</p>
<pre><code>new_item_data={k:item_data[k] for k in item_data if item_data[k]}
</code></pre>
<p>Any keys that do not have values will be removed.</p>
| 0 | 2016-06-03T22:13:10Z | [
"python"
] |
Very basic Keras CNN with 2 classes giving inexplicable answers | 37,624,102 | <p>Tried training a very simple CNN with Keras/Theano on a binary classification problem. The loss function always converges to 8.0151 or so. Parameter/architecture modifications did not help. So I made a very simple example: new input arrays, one is all ones, the other all zeroes. No dice, same behavior. I tried ... | 1 | 2016-06-03T22:03:12Z | 37,629,260 | <p>Your learning rate is simply set way too high, probably leading to an explosion in weights and gradient. Simply change</p>
<pre><code>sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
</code></pre>
<p>to</p>
<pre><code>sgd = SGD(lr=0.001, decay=1e-6, momentum=0.9, nesterov=True)
</code></pre>
<p>You mig... | 2 | 2016-06-04T10:46:01Z | [
"python",
"machine-learning",
"theano",
"keras"
] |
Separate items from a list of random numbers in a new list | 37,624,153 | <p>I have a list of 1000 random numbers in the interval [1, 12] and I'm looking for a way to separate them in other lists such that I get new lists only with 1's, other with only 2's, and so on.</p>
<p>My Python code to generate the list is:</p>
<pre><code>A=[]
for x in range(1,1001):
A.append(random.randint(2, ... | 0 | 2016-06-03T22:07:26Z | 37,624,235 | <p>Create a dictionary with key for each unique element of your list <code>A</code>. Then create a list for each key. </p>
<pre><code>f={}
for i in set(A):
f[i]=[i]*A.count(i)
</code></pre>
<p>This way say <code>A</code> has 82 elements of 2. A.count(2) = 82. You want a list of [2,...,2] the length of which is ... | 1 | 2016-06-03T22:15:55Z | [
"python",
"list"
] |
Separate items from a list of random numbers in a new list | 37,624,153 | <p>I have a list of 1000 random numbers in the interval [1, 12] and I'm looking for a way to separate them in other lists such that I get new lists only with 1's, other with only 2's, and so on.</p>
<p>My Python code to generate the list is:</p>
<pre><code>A=[]
for x in range(1,1001):
A.append(random.randint(2, ... | 0 | 2016-06-03T22:07:26Z | 37,624,280 | <p>Use <code>groupby</code> on your <code>sorted</code> list, and dict comprehension to build your result dictionary:</p>
<pre><code>from itertools import groupby
result = {i: list(g) for i, g in groupby(sorted(A))}
print result
# {1: [1, 1, 1], 2: [2, 2, 2, 2], 3: [3, 3]...}
</code></pre>
<p>Or to have a list of l... | 1 | 2016-06-03T22:20:33Z | [
"python",
"list"
] |
Loop list items in JSON | 37,624,186 | <p>I am able to make a successful query to Spotify searching for an artist. My issue is I want to pull the artist's image URL from the JSON response.</p>
<p>Every time I try to get the URL I get the error </p>
<pre><code>TypeError: list indices must be integers or slices, not str
</code></pre>
<p>My code is as follo... | -2 | 2016-06-03T22:10:20Z | 37,624,293 | <p>You can have a visual look at the object by</p>
<pre><code>from pprint import pprint
pprint(spotifyJson)
</code></pre>
<p>Indeed as jonrsharpe pointed out, 'items' is a list, so either you iterate over it or pick one element.
'Images' is a list also.</p>
<pre><code>images = spotifyJson['artists']['items'][0]['im... | 1 | 2016-06-03T22:22:54Z | [
"python",
"json",
"spotify"
] |
Loop list items in JSON | 37,624,186 | <p>I am able to make a successful query to Spotify searching for an artist. My issue is I want to pull the artist's image URL from the JSON response.</p>
<p>Every time I try to get the URL I get the error </p>
<pre><code>TypeError: list indices must be integers or slices, not str
</code></pre>
<p>My code is as follo... | -2 | 2016-06-03T22:10:20Z | 37,624,303 | <p>The value for the key 'items' in the json response is a list of dictionaries. You might want to do something like:</p>
<pre><code> images = spotifyJson['artists']['items'][0]['images']
for img in images:
print img
</code></pre>
<p>This will print the info dictionary for all the images. Then you can pro... | 0 | 2016-06-03T22:23:59Z | [
"python",
"json",
"spotify"
] |
value based thread lock | 37,624,289 | <p>Forgive me if this has been asked before. I have looked around a lot, but I get the feeling that I don't have the proper vocabulary to find this by searching the web.</p>
<p>I have a multithreaded application in python. I want to be able to lock a certain block of code but only to other threads with a certain condi... | 3 | 2016-06-03T22:21:41Z | 37,625,343 | <p><strong>Updated</strong></p>
<p>Good news: I was able to reproduce the <code>release_lock</code> problem you encountered using my original answer via a somewhat crude testbed I cobbled together, and fix the issue using a counting mechanism (as you suggested) â at least a far as I can tell with my testing apparatu... | 1 | 2016-06-04T01:01:27Z | [
"python",
"multithreading",
"python-multithreading"
] |
value based thread lock | 37,624,289 | <p>Forgive me if this has been asked before. I have looked around a lot, but I get the feeling that I don't have the proper vocabulary to find this by searching the web.</p>
<p>I have a multithreaded application in python. I want to be able to lock a certain block of code but only to other threads with a certain condi... | 3 | 2016-06-03T22:21:41Z | 37,626,665 | <p>Have one lock, acquired whenever a thread tries to enter or exit the critical section, and use separate condition variables for each value of <code>bar</code>. The following could probably be optimized to create less condition variables, but doing so for this post felt like premature optimization:</p>
<pre><code>im... | 1 | 2016-06-04T05:21:36Z | [
"python",
"multithreading",
"python-multithreading"
] |
Extract links from a webpage and create a dictionary Python | 37,624,353 | <p>Write a function that opens a web page and returns a dictionary of all the links and their text on that page. The links are the dictionary keys, and the text is the dictionary value. </p>
<p>Here's what I have so far.</p>
<pre><code>import urllib.request as urlrequest
def getLinks(url):
page=urlrequest.urlopen... | 0 | 2016-06-03T22:29:21Z | 37,624,532 | <p>You can't check for containment between <code>string</code> and <code>byte</code>, it has to be either <code>byte</code> and <code>byte</code> or <code>string</code> and <code>string</code>.</p>
<p>Since your webpage was returned as a <code>byte</code> object. You should do:</p>
<pre><code>if b'<a href=' in lin... | 1 | 2016-06-03T22:51:59Z | [
"python",
"http",
"url"
] |
What's the most efficient way to select a non-rectangular ROI of an Image in OpenCV? | 37,624,509 | <p>I want to create a binary image mask, containing only ones and zeros in python. The Region of Interest(white) is non-rectangular, defined by 4 corner points and looks for example as follows:
<a href="http://i.stack.imgur.com/2FRrG.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/2FRrG.jpg" alt="enter image des... | 2 | 2016-06-03T22:48:26Z | 37,624,836 | <p>Draw the mask with <a href="http://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html#fillpoly" rel="nofollow"><code>fillPoly</code></a>:</p>
<pre><code>mask = np.ones((1000, 2000)) # (height, width)
myROI = [(750, 0), (900, 1000), (1000, 1000), (1500, 0)] # (x, y)
cv2.fillPol... | 2 | 2016-06-03T23:29:14Z | [
"python",
"opencv",
"numpy"
] |
Python - Plotting Fourier transform from text file | 37,624,537 | <p>I have this text file that has columns of different recorded values to where the first column is of values of time and columns 2, 3, and 4, are of position x, y, and z, respectively, to where that if I were to plot time vs its position of x, y, or z, it will be shown to oscillate.</p>
<p>I want to take Fourier tran... | 0 | 2016-06-03T22:52:11Z | 37,624,617 | <pre><code>from matplotlib.pyplot import *
import numpy
spectrum =numpy.fft.fft(x1)
spectrum = abs(spectrum[:len(spectrum)/2]) # Just first half of the spectrum, as the second is the negative copy
figure()
plot(spectrum)
show()
</code></pre>
<p>I'll edit the answer according to your need, as your question is not very... | 1 | 2016-06-03T23:00:56Z | [
"python",
"numpy",
"scipy"
] |
Python - Plotting Fourier transform from text file | 37,624,537 | <p>I have this text file that has columns of different recorded values to where the first column is of values of time and columns 2, 3, and 4, are of position x, y, and z, respectively, to where that if I were to plot time vs its position of x, y, or z, it will be shown to oscillate.</p>
<p>I want to take Fourier tran... | 0 | 2016-06-03T22:52:11Z | 37,624,680 | <p>Fast Fourier Transforms in Numpy are pretty straightforward: </p>
<pre><code>fft = np.fft.fft(x)
</code></pre>
<p>See here for more details - <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.fft.fft.html#numpy.fft.fft" rel="nofollow">Link</a></p>
<p>Plotting a simple line is straightforwa... | 1 | 2016-06-03T23:07:02Z | [
"python",
"numpy",
"scipy"
] |
Python psutil find avaliable ports | 37,624,562 | <p>I'm trying to find all avaliable ports to connect a computer. I'm using the codes below</p>
<pre><code>import psutil
for proc in psutil.process_iter():
print (proc)
for x in proc.connections():
if x.status == psutil.CONN_LISTEN:
print (x)
</code></pre>
<p><code>print(proc)</code> prints... | 1 | 2016-06-03T22:54:49Z | 37,624,638 | <p>A <code>pid</code> is a "process ID", each process running on your system has a unique identifier, so you can adjust its parameters, or send it signals as it's running like 'terminate', 'stop', 'continue'.</p>
<p><code>laddr=('xxx.x.x.x', xxxxx)</code> is a tuple of IP address and port number. </p>
<p>Running on m... | 1 | 2016-06-03T23:02:49Z | [
"python",
"port",
"python-3.4",
"psutil"
] |
Python psutil find avaliable ports | 37,624,562 | <p>I'm trying to find all avaliable ports to connect a computer. I'm using the codes below</p>
<pre><code>import psutil
for proc in psutil.process_iter():
print (proc)
for x in proc.connections():
if x.status == psutil.CONN_LISTEN:
print (x)
</code></pre>
<p><code>print(proc)</code> prints... | 1 | 2016-06-03T22:54:49Z | 37,625,203 | <p>It's going to be hard to 'connect' to an 'open' port. When a port is opened, whatever program opened the port is listening on that port.</p>
<p>If you want to find ports that are free, your script is working in reverse! You should be looking for ports that are not being used. You can't really have two programs work... | 0 | 2016-06-04T00:30:11Z | [
"python",
"port",
"python-3.4",
"psutil"
] |
socket recv not returning | 37,624,644 | <p>I can't understand why socket recv doesn't return. I have a client application that send string to a server. The client is executed in a terminal. This is the code</p>
<pre><code>client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Enter client sender"
try:
client.connect((target, port))
if le... | 0 | 2016-06-03T23:03:17Z | 37,624,661 | <p>Your code is generally correct, although <code>buffer</code>is a built-in type and you should avoid using it as a variable name (but it will still work if you do).</p>
<p>On a blocking socket (the default state), <code>recv</code> will block until there is some data available for reading. Make sure the other endpoi... | 2 | 2016-06-03T23:05:24Z | [
"python",
"sockets"
] |
TypeError: unhashable type: 'list' from attempt to create dict | 37,624,705 | <p>I'm receiving the following error in my programm:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "bookmarks.py", line 26, in <module>
zipping = dict(zip(datelist, matchhref))
TypeError: unhashable type: 'list'
</code></pre>
<p>I want to make dictionary fro... | 0 | 2016-06-03T23:10:17Z | 37,624,749 | <p><code>zip</code> returns a list of tuples, not a tuple.</p>
<p>Besides, a tuple is only hashable if each of its elements are hashable. So a tuple of lists will not be hashable either.</p>
<p>That said, there's nothing wrong with <code>dict(zip(keys, values))</code> if <code>keys</code> is a list of hashable elemen... | 0 | 2016-06-03T23:17:35Z | [
"python"
] |
TypeError: unhashable type: 'list' from attempt to create dict | 37,624,705 | <p>I'm receiving the following error in my programm:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "bookmarks.py", line 26, in <module>
zipping = dict(zip(datelist, matchhref))
TypeError: unhashable type: 'list'
</code></pre>
<p>I want to make dictionary fro... | 0 | 2016-06-03T23:10:17Z | 37,624,756 | <p>As I commented, you can call <em>re.search</em> and then <em>.group()</em> the add the <em>string</em> and not the <em>list</em> that <em>findall</em> returns so you can use the string as the key but <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">BeautifulSoup</a> will make your life... | 1 | 2016-06-03T23:18:18Z | [
"python"
] |
Sending url form Model to Template in Django | 37,624,769 | <p>I am trying to return a link to a view but it wont work because it has a url inside of it, currently getting KeyError
<a href="http://i.stack.imgur.com/4sJNd.png" rel="nofollow">Error image</a></p>
<p>Is there a way to return urls such as:
{% url "tickets:agregar_seguimiento" object.id %}
to a template.</p>
<p>I ... | 0 | 2016-06-03T23:19:55Z | 37,625,711 | <p>The problem is that it formats as a html safe string. So try using url reverse function and concat it with the string you return from the below finction.</p>
<p>Try using the below code in models. </p>
<pre><code>from django.core.urlresolvers import reverse
def get_absolute_url(self):
return reverse('tickets:... | 1 | 2016-06-04T02:19:34Z | [
"python",
"django",
"jinja2"
] |
Build numpy array with multiple custom index ranges without explicit loop | 37,624,798 | <p>In Numpy, is there a pythonic way to create array3 with custom ranges from array1 and array2 without a loop? The straightforward solution of iterating over the ranges works but since my arrays run into millions of items, I am looking for a more efficient solution (maybe syntactic sugar too). </p>
<p>For ex.,</p>... | 4 | 2016-06-03T23:23:40Z | 37,624,918 | <p>Assuming the ranges do not overlap, you could build a mask which is nonzero where the index is between the ranges specified by <code>array1</code> and <code>array2</code> and then use <code>np.flatnonzero</code> to obtain an array of indices -- the desired <code>array3</code>:</p>
<pre><code>import numpy as np
arr... | 5 | 2016-06-03T23:41:18Z | [
"python",
"arrays",
"performance",
"numpy",
"vectorization"
] |
Build numpy array with multiple custom index ranges without explicit loop | 37,624,798 | <p>In Numpy, is there a pythonic way to create array3 with custom ranges from array1 and array2 without a loop? The straightforward solution of iterating over the ranges works but since my arrays run into millions of items, I am looking for a more efficient solution (maybe syntactic sugar too). </p>
<p>For ex.,</p>... | 4 | 2016-06-03T23:23:40Z | 37,625,101 | <p>This is my approach combining <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.vectorize.html" rel="nofollow">vectorize</a> and <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.concatenate.html" rel="nofollow">concatenate</a>:</p>
<p><strong>Implementation</strong>:... | 0 | 2016-06-04T00:10:39Z | [
"python",
"arrays",
"performance",
"numpy",
"vectorization"
] |
Build numpy array with multiple custom index ranges without explicit loop | 37,624,798 | <p>In Numpy, is there a pythonic way to create array3 with custom ranges from array1 and array2 without a loop? The straightforward solution of iterating over the ranges works but since my arrays run into millions of items, I am looking for a more efficient solution (maybe syntactic sugar too). </p>
<p>For ex.,</p>... | 4 | 2016-06-03T23:23:40Z | 37,625,115 | <p>Do you mean this?</p>
<pre><code>In [440]: np.r_[10:14,65:70,200:204]
Out[440]: array([ 10, 11, 12, 13, 65, 66, 67, 68, 69, 200, 201, 202, 203])
</code></pre>
<p>or generalizing:</p>
<pre><code>In [454]: np.r_[tuple([slice(i,j) for i,j in zip(array1,array2)])]
Out[454]: array([ 10, 11, 12, 13, 65, 66... | 0 | 2016-06-04T00:12:22Z | [
"python",
"arrays",
"performance",
"numpy",
"vectorization"
] |
Build numpy array with multiple custom index ranges without explicit loop | 37,624,798 | <p>In Numpy, is there a pythonic way to create array3 with custom ranges from array1 and array2 without a loop? The straightforward solution of iterating over the ranges works but since my arrays run into millions of items, I am looking for a more efficient solution (maybe syntactic sugar too). </p>
<p>For ex.,</p>... | 4 | 2016-06-03T23:23:40Z | 37,626,057 | <h2>Prospective Approach</h2>
<p>I will go backwards on how to approach this problem.</p>
<p>Take the sample listed in the question. We have -</p>
<pre><code>array1 = np.array([10, 65, 200])
array2 = np.array([14, 70, 204])
</code></pre>
<p>Now, look at the desired result -</p>
<pre><code>result: [10,11,12,13,65,6... | 2 | 2016-06-04T03:31:02Z | [
"python",
"arrays",
"performance",
"numpy",
"vectorization"
] |
Dimensions in keras backend functions | 37,624,813 | <p>There are many function in the Keras backend which have the <code>keepdims</code> parameter. For instance </p>
<pre><code>sum(x, axis=None, keepdims=False)
</code></pre>
<p>I can not find any explanation of what that means. Can someone explain what it does? Also, what does it mean for <code>axis</code> to be <cod... | 2 | 2016-06-03T23:25:35Z | 37,624,917 | <p>These are not <code>keras</code> specific parameters but <code>numpy.sum</code> parameters.</p>
<blockquote>
<p><strong>axis</strong> : None or int or tuple of ints, optional</p>
<p>Axis or axes along which a sum is performed. The default (axis = None) is perform a sum over all the dimensions of the input... | 1 | 2016-06-03T23:40:50Z | [
"python",
"keras"
] |
Dimensions in keras backend functions | 37,624,813 | <p>There are many function in the Keras backend which have the <code>keepdims</code> parameter. For instance </p>
<pre><code>sum(x, axis=None, keepdims=False)
</code></pre>
<p>I can not find any explanation of what that means. Can someone explain what it does? Also, what does it mean for <code>axis</code> to be <cod... | 2 | 2016-06-03T23:25:35Z | 37,661,430 | <p>You can find documentation and tutorial for theano (one of keras backends) in <a href="http://deeplearning.net" rel="nofollow">deeplearning.net</a></p>
<p>For method <code>theano.tensor.sum</code>, see <a href="http://deeplearning.net/software/theano/library/tensor/basic.html#theano.tensor.sum" rel="nofollow">here<... | 1 | 2016-06-06T15:36:23Z | [
"python",
"keras"
] |
Divide Every Other Line Between Two Files | 37,624,881 | <p>I am currently trying to automate a process that alarms me if we see a sudden change in amount of VMs running month over month. Here is what the data looks like</p>
<pre><code>January.txt February.txt
Web Fleet Web Fleet
100 112
Proxy Fleet Proxy Fl... | -1 | 2016-06-03T23:35:26Z | 37,624,963 | <p>Code -</p>
<pre><code>with open('January.txt', 'r') as f1, open('February.txt', 'r') as f2:
for x, y in zip(f1.read().splitlines()[1::2], f2.read().splitlines()[1::2]):
print(float(x) / int(y))
</code></pre>
<p>Output -</p>
<pre><code>0.8928571428571429
1.1363636363636365
1.2
</code></pre>
| 1 | 2016-06-03T23:48:08Z | [
"python",
"bash",
"division"
] |
Divide Every Other Line Between Two Files | 37,624,881 | <p>I am currently trying to automate a process that alarms me if we see a sudden change in amount of VMs running month over month. Here is what the data looks like</p>
<pre><code>January.txt February.txt
Web Fleet Web Fleet
100 112
Proxy Fleet Proxy Fl... | -1 | 2016-06-03T23:35:26Z | 37,624,964 | <p>It's probably simpler to read the contents of both files upfront, <code>zip</code> them together, then iterate moving 2 lines at a time:</p>
<pre><code>with open("jan.txt") as file1:
with open("feb.txt") as file2:
lines = zip(file1.readlines(), file2.readlines())
for line1, line2 in lines[1::2]:... | 0 | 2016-06-03T23:48:20Z | [
"python",
"bash",
"division"
] |
Python: Pandas Dataframe AttributeError: 'numpy.ndarray' object has no attribute 'fillna' | 37,624,903 | <p>Since I am creating a dataframe, I don't understand why I am getting an array error. </p>
<pre><code>M2 = df.groupby(['song_id', 'user_id']).rating.mean().unstack()
M2 = np.maximum(-1, (M - 3).fillna(0) / 2.) # scale to -1..+1 (treat "0" scores as "1" scores)
M2.head(2)
AttributeError: 'numpy.ndarray' object has... | 1 | 2016-06-03T23:38:59Z | 37,625,174 | <p><code>(M - 3)</code> is getting interpreted as a <code>numpy.ndarray</code>. This implies that <code>M</code> is defined somewhere as a <code>numpy.ndarray</code>. Test it out by running:</p>
<pre><code>print type(M)
</code></pre>
| 1 | 2016-06-04T00:23:49Z | [
"python",
"pandas",
"dataframe",
"attributeerror"
] |
Python: Pandas Dataframe AttributeError: 'numpy.ndarray' object has no attribute 'fillna' | 37,624,903 | <p>Since I am creating a dataframe, I don't understand why I am getting an array error. </p>
<pre><code>M2 = df.groupby(['song_id', 'user_id']).rating.mean().unstack()
M2 = np.maximum(-1, (M - 3).fillna(0) / 2.) # scale to -1..+1 (treat "0" scores as "1" scores)
M2.head(2)
AttributeError: 'numpy.ndarray' object has... | 1 | 2016-06-03T23:38:59Z | 37,630,216 | <p>Your code is not complete at the moment, so it is hard to pin point why <code>M</code> is causing an error. There could be a couple reasons:</p>
<ol>
<li><p>You have a typo and <code>(M - 3)</code> should be <code>(M2 - 3)</code></p>
<pre><code>M2 = df.groupby(['song_id', 'user_id']).rating.mean().unstack()
M2 = n... | 0 | 2016-06-04T12:26:35Z | [
"python",
"pandas",
"dataframe",
"attributeerror"
] |
pandas nlargest is returning more than n rows | 37,624,912 | <p>I have a <code>DataFrame</code> that looks like this:</p>
<pre><code> name value
date
2016-05-01 kelly 20
2016-05-05 john 12
2016-05-05 sarah 25
2016-05-05 george 3
2016-05-05 tom 40
2016-05-07 kara 24
2016-05-07 jane 90
2016-05-07 sa... | 0 | 2016-06-03T23:40:11Z | 37,625,007 | <p>To start, this will get the job done:</p>
<pre><code>df.sort_values('value', ascending=False).groupby(level=0).head(3).sort_index()
</code></pre>
| 1 | 2016-06-03T23:53:49Z | [
"python",
"pandas",
"dataframe"
] |
pandas nlargest is returning more than n rows | 37,624,912 | <p>I have a <code>DataFrame</code> that looks like this:</p>
<pre><code> name value
date
2016-05-01 kelly 20
2016-05-05 john 12
2016-05-05 sarah 25
2016-05-05 george 3
2016-05-05 tom 40
2016-05-07 kara 24
2016-05-07 jane 90
2016-05-07 sa... | 0 | 2016-06-03T23:40:11Z | 37,630,114 | <h1>Use <a href="https://docs.python.org/3/tutorial/introduction.html#lists" rel="nofollow"><code>[:n]</code></a> slice of <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values()</code></a> result</h1>
<p>Use <a href="http://pandas.pydata.org... | 0 | 2016-06-04T12:14:57Z | [
"python",
"pandas",
"dataframe"
] |
How to install pyhook for python 3.4? | 37,624,955 | <p>How do I install pyhook for python 3.4? I can find the files for 2.7, but not 3.4.
Does anyone have the download link to get pyhook for python 3.4? Any help would be greatly appreciated.</p>
| 0 | 2016-06-03T23:46:38Z | 37,626,677 | <p>It looks like it exists in PyPi, <a href="https://pypi.python.org/pypi/pyHook/1.5.1" rel="nofollow">https://pypi.python.org/pypi/pyHook/1.5.1</a>. </p>
<p>Try installing via:</p>
<pre><code>pip install pyhook
</code></pre>
<p>If it complains that it could not find a version that satisfies requirements, then the d... | -1 | 2016-06-04T05:23:24Z | [
"python",
"module",
"install",
"python-3.4",
"pyhook"
] |
Replace Column values o Pandas timeseries | 37,625,012 | <p>I want to replace a set of values from a series in pre-set timeseries dataframe e.g. 3 values from series a will replace 3 timestamp values. However, <strong>replace</strong> or <strong>.set_value</strong> command don't seems to be working.In this cases, timestamp is already in indexed form. Timestamp example series... | 1 | 2016-06-03T23:54:24Z | 37,625,731 | <p>Try this: </p>
<pre><code> a = pd.Series([15.0,16.0,17.0])
#0 15.0
#1 16.0
#2 17.0
# dtype: float64
a = pd.date_range('1/1/2010', periods=3, freq='900S')
#DatetimeIndex(['2010-01-01 00:00:00', '2010-01-01 00:15:00',
# '2010-01-01 00:30:00'],
# dtype='dateti... | 0 | 2016-06-04T02:22:24Z | [
"python",
"replace",
"timestamp"
] |
Replace Column values o Pandas timeseries | 37,625,012 | <p>I want to replace a set of values from a series in pre-set timeseries dataframe e.g. 3 values from series a will replace 3 timestamp values. However, <strong>replace</strong> or <strong>.set_value</strong> command don't seems to be working.In this cases, timestamp is already in indexed form. Timestamp example series... | 1 | 2016-06-03T23:54:24Z | 37,769,015 | <p><strong>Solved</strong></p>
<pre><code>In [68]:
df = pd.DataFrame({'Timestamp': ['2010-01-01 00:00:00', '2010-01-01 00:15:00', '2010-01-01 00:30:00', '2010-01-01 00:45:00'],
'Column_1':[21.17, 19.17, 17.95, 25.0]})
df = df.set_index('Timestamp')
df.head()
Out[68]:
Timestamp Column_1
... | 1 | 2016-06-11T22:28:17Z | [
"python",
"replace",
"timestamp"
] |
wait_window not working properly | 37,625,015 | <p>For some reason, when I close the window on my tkinter, it pops back up again. Not sure how to fix it. The <code>wait_window</code> is there, but it doesn't seem to work. </p>
<pre><code>import tkinter
class Othello:
def __init__(self, othello_game):
self.state = othello_game
self._root_wind... | 0 | 2016-06-03T23:54:28Z | 37,625,221 | <p>Well, the infinite loop is creating another instance of <code>Othello</code> once you close the current one. </p>
<p>I don't understand also why you would want to use <code>wait_window</code> here and what were your intentions to use the infinite while loop with such a code.</p>
<p>Check this <a href="http://stack... | 2 | 2016-06-04T00:33:20Z | [
"python",
"tkinter"
] |
Python list comprehension vs generator | 37,625,067 | <p>I found this question <a href="http://stackoverflow.com/questions/30112326/generators-vs-list-comprehension-performance-in-python">Generators vs List Comprehension performance in Python</a> and instead of cProfile I use timeit.</p>
<pre><code>from timeit import timeit
import cProfile
print timeit('sum([i for i in ... | 1 | 2016-06-04T00:02:57Z | 37,625,095 | <p>The generator version won. The cProfile profiling simply introduced way more overhead for the genexp than the list comprehension, since it has a lot more points where the profiler butts in.</p>
| 0 | 2016-06-04T00:08:58Z | [
"python"
] |
Python list comprehension vs generator | 37,625,067 | <p>I found this question <a href="http://stackoverflow.com/questions/30112326/generators-vs-list-comprehension-performance-in-python">Generators vs List Comprehension performance in Python</a> and instead of cProfile I use timeit.</p>
<pre><code>from timeit import timeit
import cProfile
print timeit('sum([i for i in ... | 1 | 2016-06-04T00:02:57Z | 37,625,096 | <p>Generators load lazily; you have to make a call to get their next value every time you want it.</p>
<p><code>sum</code> is an aggregate function, which operations on the <em>entire</em> iterable. You have to have all of the values available for it to do its work.</p>
<p>The reason that the list comprehension work... | 1 | 2016-06-04T00:09:00Z | [
"python"
] |
Python list comprehension vs generator | 37,625,067 | <p>I found this question <a href="http://stackoverflow.com/questions/30112326/generators-vs-list-comprehension-performance-in-python">Generators vs List Comprehension performance in Python</a> and instead of cProfile I use timeit.</p>
<pre><code>from timeit import timeit
import cProfile
print timeit('sum([i for i in ... | 1 | 2016-06-04T00:02:57Z | 37,625,144 | <p>In the simple case, it will be fastest to do this without a comprehension/generator:</p>
<pre><code>sum(xrange(9999999))
</code></pre>
<p>Normally, if I need to do some sort of operation where I need to choose between a comprehension and generator expression, I do:</p>
<pre><code>sum(a*b for a, b in zip(c, d))
</... | 4 | 2016-06-04T00:18:14Z | [
"python"
] |
Set model field of child class as primary_key in Django | 37,625,093 | <p>I have an abstract model class:</p>
<pre><code>class AbstractClass(models.Model):
filename_base = models.CharField(max_length=25, blank=True, null=True)
class Meta:
abstract = True
</code></pre>
<p>Is it possible to make a child class with <code>primary_key</code> set to this field without rewriti... | 0 | 2016-06-04T00:07:57Z | 37,625,817 | <p>I hope this helps.</p>
<pre><code>class ChildClass(AbstractClass):
pass
ChildClass._meta.get_field('filename_base').blank = False
ChildClass._meta.get_field('filename_base').null = False
ChildClass._meta.get_field('filename_base').primary_key = True
</code></pre>
<p>And Primary key should be blank=False and nu... | 1 | 2016-06-04T02:43:16Z | [
"python",
"django",
"django-models"
] |
Web Scraping Python Access Table data | 37,625,114 | <p>So I am trying to use Beautiful Soup to do some web scraping of this website <a href="http://www.killedbypolice.net/kbp2013.html" rel="nofollow">http://www.killedbypolice.net/kbp2013.html</a> and access the data in the table. My current code is: </p>
<pre><code>url = "http://www.killedbypolice.net/kbp2013.html"
pag... | 2 | 2016-06-04T00:12:21Z | 37,628,803 | <p>The error is because the html is very badly formatted, you get <code>RuntimeError: maximum recursion depth exceeded</code> creating the soup object with both <code>lxml</code> and <code>html.parser</code>, the only parser that works at all is <code>html5lib</code>:</p>
<pre><code>html = requests.get("http://www.ki... | 2 | 2016-06-04T09:52:31Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Python scrape style display:none | 37,625,183 | <p>I want to scrape one webpage and I need to find <strong>if the style of the element</strong> is <em>display:none; or display:block</em> as the following code . (If I see the source of the webpage I can't see any of this style. I know it because I use the Inspect element from Chrome)</p>
<pre><code><p id="add_to... | -1 | 2016-06-04T00:25:59Z | 37,625,244 | <p>I'm assuming you know how to make a request and get the page source in python.</p>
<p>If you work with BeautifulSoup you can search for the elements and get the tags and attributes from there. You could have something like:</p>
<pre><code>from bs4 import BeautifulSoup as bs
soup = bs(souce_code)
elements = soup.f... | 1 | 2016-06-04T00:38:33Z | [
"python"
] |
Printing an int list in a single line python3 | 37,625,208 | <p>I'm new to python and I'm trying to scan multiple numbers separated by spaces (let's assume '1 2 3' as an example) in a single line and add it to a list of int. I did it by using:</p>
<pre><code>#gets the string
string = input('Input numbers: ')
#converts the string into an array of int, excluding the whitespaces... | 2 | 2016-06-04T00:30:48Z | 37,625,243 | <p>You want to say</p>
<pre><code>for i in array:
print(i, end=" ")
</code></pre>
<p>The syntax <code>i in array</code> iterates over each member of the list. So, <code>array[i]</code> was trying to access <code>array[1]</code>, <code>array[2]</code>, and <code>array[3]</code>, but the last of these is out of bo... | 3 | 2016-06-04T00:38:31Z | [
"python",
"python-3.x"
] |
Printing an int list in a single line python3 | 37,625,208 | <p>I'm new to python and I'm trying to scan multiple numbers separated by spaces (let's assume '1 2 3' as an example) in a single line and add it to a list of int. I did it by using:</p>
<pre><code>#gets the string
string = input('Input numbers: ')
#converts the string into an array of int, excluding the whitespaces... | 2 | 2016-06-04T00:30:48Z | 37,625,249 | <p>Try using join on a str conversion of your ints:</p>
<pre><code>print ' '.join(str(x) for x in array)
</code></pre>
| 2 | 2016-06-04T00:38:57Z | [
"python",
"python-3.x"
] |
Printing an int list in a single line python3 | 37,625,208 | <p>I'm new to python and I'm trying to scan multiple numbers separated by spaces (let's assume '1 2 3' as an example) in a single line and add it to a list of int. I did it by using:</p>
<pre><code>#gets the string
string = input('Input numbers: ')
#converts the string into an array of int, excluding the whitespaces... | 2 | 2016-06-04T00:30:48Z | 37,625,315 | <p>these will both work in Python 2.7 and Python 3.x:</p>
<pre><code>>>> l = [1, 2, 3]
>>> print(' '.join(str(x) for x in l))
1 2 3
>>> print(' '.join(map(str, l)))
1 2 3
</code></pre>
<p>btw, <code>array</code> is a reserved word in Python.</p>
| 3 | 2016-06-04T00:56:01Z | [
"python",
"python-3.x"
] |
Printing an int list in a single line python3 | 37,625,208 | <p>I'm new to python and I'm trying to scan multiple numbers separated by spaces (let's assume '1 2 3' as an example) in a single line and add it to a list of int. I did it by using:</p>
<pre><code>#gets the string
string = input('Input numbers: ')
#converts the string into an array of int, excluding the whitespaces... | 2 | 2016-06-04T00:30:48Z | 37,625,570 | <p>You have multiple options, each with different general use cases.</p>
<p>The first would be to use a <code>for</code> loop, as you described, but in the following way.</p>
<pre><code>for value in array:
print(value, end=' ')
</code></pre>
<p>You could also use <code>str.join</code> for a simple, readable one-... | 0 | 2016-06-04T01:45:42Z | [
"python",
"python-3.x"
] |
Are Flask sessions unique to each ip? | 37,625,227 | <p>Is the Flask session object based on the ip address of the user/request? How does it actually allow each user to have their own session? Is it ideal to allow a user to login from many devices or is that risky as far as user experience vs security?</p>
| -1 | 2016-06-04T00:35:00Z | 37,625,319 | <p>Sessions in Flask are cookie based. This means that are not necessary ip/user/request based at least you develop the server logic in this way. The fact that are cookies based let the user read the content, so take care what you put there. The user can't modify the content easily because it is cipher in the server-si... | 0 | 2016-06-04T00:56:58Z | [
"python",
"flask"
] |
Filling Dataframe so rows are populated consistently | 37,625,250 | <p>I have two csv files in a folder, the first of which looks like this:</p>
<p>df1</p>
<pre><code>Value Count
1 10
2 1
3 2
4 15
5 8
</code></pre>
<p>and the second of which is like this:</p>
<p>df2</p>
<pre><code>Value Count
1 5
2 22
3 13
4 16
5 11
6 18
</... | 0 | 2016-06-04T00:39:10Z | 37,625,267 | <pre><code>from glob import glob
filenames = glob('C:/pathway/*.csv')
def rfile(fn):
return pd.read_csv(fn, index_col=0)
dfs = [rfile(fn) for fn in filenames]
idx = dfs[0].index
for i in range(1, len(dfs)):
idx = idx.union(dfs[i].index)
</code></pre>
<p><code>idx</code> is now your index that is a union of a... | 2 | 2016-06-04T00:44:41Z | [
"python",
"pandas"
] |
Filling Dataframe so rows are populated consistently | 37,625,250 | <p>I have two csv files in a folder, the first of which looks like this:</p>
<p>df1</p>
<pre><code>Value Count
1 10
2 1
3 2
4 15
5 8
</code></pre>
<p>and the second of which is like this:</p>
<p>df2</p>
<pre><code>Value Count
1 5
2 22
3 13
4 16
5 11
6 18
</... | 0 | 2016-06-04T00:39:10Z | 37,625,513 | <p>This is very easy to do <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow">using <code>reindex</code></a>. First you set the index of each df equal its own Value column. Then reindex based on the larger (df2).</p>
<pre><code>import numpy as np
import pandas ... | 1 | 2016-06-04T01:34:27Z | [
"python",
"pandas"
] |
Keras BatchNormalization, What exactly is sample wise normalization? | 37,625,272 | <p>I am trying to figure out what exactly the batch normalization in Keras does. Right now I have the following code.</p>
<pre><code>for i in range(8):
c = Convolution2D(128, 3, 3, border_mode = 'same', init = 'he_normal')(c)
c = LeakyReLU()(c)
c = Convolution2D(128, 3, 3, border_mode = 'same', init = 'he_... | 2 | 2016-06-04T00:45:58Z | 37,692,407 | <blockquote>
<p>In this it is just computing the mean over all of x which in my case is <code>(BATCH_SIZE, 128, 56, 56)</code> I think.</p>
</blockquote>
<p>By doing this you are already violating the contract of that layer. That is not a 2 dimensional but a 4 dimensional input.</p>
<blockquote>
<p>I thought it w... | 1 | 2016-06-08T02:45:55Z | [
"python",
"neural-network",
"keras"
] |
How do I find the highest value and swap it with the end value in an array? | 37,625,326 | <p>This is my python code so far and the result I'm getting at the end is [5, 2, 3, 12, 1, 12]. </p>
<pre><code>array = [5,2,3,12,1,6]
temp = ''
lastvalue = 5
highestvalue = array[0]
i=0
while i<5:
if array[i]>highestvalue:
highestvalue = array[i]
i+=1
print(highestvalue)
temp = array[5]
... | 0 | 2016-06-04T00:57:53Z | 37,625,349 | <p>Why not just get the indexes and swap the values</p>
<pre><code>array = [5,2,3,12,1,6]
maxI = array.index(max(array))
minI = array.index(min(array))
array[maxI], array[minI] = array[minI], array[maxI]
</code></pre>
| 1 | 2016-06-04T01:02:21Z | [
"python",
"arrays",
"python-3.x"
] |
How do I find the highest value and swap it with the end value in an array? | 37,625,326 | <p>This is my python code so far and the result I'm getting at the end is [5, 2, 3, 12, 1, 12]. </p>
<pre><code>array = [5,2,3,12,1,6]
temp = ''
lastvalue = 5
highestvalue = array[0]
i=0
while i<5:
if array[i]>highestvalue:
highestvalue = array[i]
i+=1
print(highestvalue)
temp = array[5]
... | 0 | 2016-06-04T00:57:53Z | 37,625,369 | <p><strong>temp</strong> is a separate variable, not an array element. Instead, identify the position needed, and swap with that. I assume that you're doing it "the hard way" (without <strong>min</strong> and <strong>max</strong> methods) for homework?</p>
<pre><code>array = [5,2,3,12,1,6]
highest_pos = 0
i=0
for i... | 2 | 2016-06-04T01:04:58Z | [
"python",
"arrays",
"python-3.x"
] |
How do I find the highest value and swap it with the end value in an array? | 37,625,326 | <p>This is my python code so far and the result I'm getting at the end is [5, 2, 3, 12, 1, 12]. </p>
<pre><code>array = [5,2,3,12,1,6]
temp = ''
lastvalue = 5
highestvalue = array[0]
i=0
while i<5:
if array[i]>highestvalue:
highestvalue = array[i]
i+=1
print(highestvalue)
temp = array[5]
... | 0 | 2016-06-04T00:57:53Z | 37,625,396 | <p>I made two modifications with your code: (1) You need to store the index of the highest value in the array in your for loop (2) You need to change your method of swapping the last and highest value in the array at the last section of your code.</p>
<pre><code>array = [5,2,3,12,1,6]
temp = ''
lastvalue = 5
highestva... | 0 | 2016-06-04T01:10:33Z | [
"python",
"arrays",
"python-3.x"
] |
ipython fails to start | 37,625,330 | <p>I had previously installed ipython against python2.7.
After I installed <code>python3-pip</code> using </p>
<pre><code>$sudo apt-get install python3-pip
</code></pre>
<p>and ran the following command</p>
<pre><code>$sudo pip3 install ipython
</code></pre>
<p>, I'm unable to start <code>ipython</code>.
I get the ... | 0 | 2016-06-04T00:58:16Z | 37,625,470 | <p>For me below commands works to shift b/w python versions.</p>
<p>To start ipyton for python 2</p>
<pre><code>$ ipython2
</code></pre>
<p>To start ipython for python 3</p>
<pre><code>$ ipython3
</code></pre>
| 0 | 2016-06-04T01:24:15Z | [
"python",
"ipython"
] |
python/pandas: convert month int to month name | 37,625,334 | <p>Most of the info I found was not in python>pandas>dataframe hence the question.</p>
<p>I want to transform an integer between 1 and 12 into an abbrieviated month name.</p>
<p>I have a df which looks like:</p>
<pre><code> client Month
1 sss 02
2 yyy 12
3 www 06
</code></pre>
<p>I want the df to look... | 2 | 2016-06-04T00:58:58Z | 37,625,422 | <p>You can do this easily with a column apply.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'client':['sss', 'yyy', 'www'], 'Month': ['02', '12', '06']})
look_up = {'01': 'Jan', '02': 'Feb', '03': 'Mrch', '04': 'April', '05': 'May',
'06': 'Jun', '07': 'Jul', '08': 'Aug', '09': 'Sep', '10': 'Nov'... | 1 | 2016-06-04T01:16:26Z | [
"python",
"date",
"pandas",
"dataframe",
"monthcalendar"
] |
python/pandas: convert month int to month name | 37,625,334 | <p>Most of the info I found was not in python>pandas>dataframe hence the question.</p>
<p>I want to transform an integer between 1 and 12 into an abbrieviated month name.</p>
<p>I have a df which looks like:</p>
<pre><code> client Month
1 sss 02
2 yyy 12
3 www 06
</code></pre>
<p>I want the df to look... | 2 | 2016-06-04T00:58:58Z | 37,625,448 | <p>One way of doing that is with the <code>apply</code> method in the dataframe but, to do that, you need a map to convert the months. You could either do that with a function / dictionary or with Python's own datetime.</p>
<p>With the datetime it would be something like:</p>
<pre><code>def mapper(month):
date = ... | 2 | 2016-06-04T01:20:41Z | [
"python",
"date",
"pandas",
"dataframe",
"monthcalendar"
] |
python/pandas: convert month int to month name | 37,625,334 | <p>Most of the info I found was not in python>pandas>dataframe hence the question.</p>
<p>I want to transform an integer between 1 and 12 into an abbrieviated month name.</p>
<p>I have a df which looks like:</p>
<pre><code> client Month
1 sss 02
2 yyy 12
3 www 06
</code></pre>
<p>I want the df to look... | 2 | 2016-06-04T00:58:58Z | 37,625,467 | <p>You can do this efficiently with combining <code>calendar.month_abbr</code> and <code>df[col].apply()</code></p>
<pre><code>import calendar
df['Month'] = df['Month'].apply(lambda x: calendar.month_abbr[x])
</code></pre>
| 3 | 2016-06-04T01:23:56Z | [
"python",
"date",
"pandas",
"dataframe",
"monthcalendar"
] |
Recursive function that prints the letters of the alphabet one per line, one per function call | 37,625,433 | <p>Well, I am still learning python and trying to print letters of alphabet one per line, one per function call. This should be done using recursion.</p>
<p>Here I am struggling due to error. Just need another pair of eyes to see if there is something missing.</p>
<pre><code>def recursive_print(cursor):
alphabet = 'a... | 0 | 2016-06-04T01:18:49Z | 37,625,501 | <p>To solve your immediate problem, you haven't indented properly. You're also missing a colon on the <strong>if</strong> statement you posted. Try this:</p>
<pre><code>def recursive_print(curser):
alphabet = 'abcdefghijklmnopqstuvwxyz'
index = len(alphabet) - curser
if index > 0:
recursive_print(index ... | 2 | 2016-06-04T01:32:01Z | [
"python",
"recursion"
] |
How to find row number of a particular value with known column number in csv file through python | 37,625,436 | <p>I am working on a problem to create a function <strong>find_row</strong> with three input parameters - file name, col_number and value. I want output like in given example:</p>
<p>For example, if we have a file a.csv:</p>
<pre><code> 1, 1.1, 1.2
2, 2.1, 2.2
3
4, 4.1, 4.2
</code></pre>
<p>then </p>
<p>print(f... | 0 | 2016-06-04T01:19:03Z | 37,625,551 | <p>In your CSV file, the 3rd row has only one column, so 2 is not a valid index. </p>
<p>As an aside, it's cleaner to do </p>
<pre><code> for index, row in enumerate(myData):
if row[col_number] == var:
return index
</code></pre>
<p>Edit: Also, that CSV is going to give you problems. It can't find '2.2' b... | 2 | 2016-06-04T01:41:29Z | [
"python",
"csv",
"row"
] |
Why can't I access the HTML of some websites | 37,625,461 | <p>So I've been trying to learn how to extract data from websites efficiently using python. Ideally I'd like to gather from stats in a more efficient manner than I currently am doing on the site www.transfermarkt.com, a footballing website but for some reason the site seems to behave different from every other site I'v... | 0 | 2016-06-04T01:23:00Z | 37,625,561 | <p>The site you specified had blocked robots in <a href="http://www.transfermarkt.com/robots.txt" rel="nofollow">http://www.transfermarkt.com/robots.txt</a> .So you have to access with user agent as a browser. </p>
<p>So basically you code should be </p>
<pre><code>import urllib2
opener = urllib2.build_opener()
opene... | 4 | 2016-06-04T01:42:45Z | [
"python",
"python-2.7"
] |
Why can't I access the HTML of some websites | 37,625,461 | <p>So I've been trying to learn how to extract data from websites efficiently using python. Ideally I'd like to gather from stats in a more efficient manner than I currently am doing on the site www.transfermarkt.com, a footballing website but for some reason the site seems to behave different from every other site I'v... | 0 | 2016-06-04T01:23:00Z | 37,625,576 | <p>From the <code>urllib#urlopen</code> documentation:</p>
<blockquote>
<p>One caveat: the read() method, if the size argument is omitted or
negative, may not read until the end of the data stream; there is no
good way to determine that the entire stream from a socket has been
read in the general case.</p>
</b... | 1 | 2016-06-04T01:46:39Z | [
"python",
"python-2.7"
] |
creating Qlabels with dynamic name at run time | 37,625,466 | <pre><code>#in this example len(list) is 5
i=0
while i < len(list):
label=q_label_i #creating a name for the label
self.label=QLabel() #
grid.addWidget(self.label,i ,0) # grid is a grid = QGridLayout()
i=i+1
</code></pre>
<p>the above code creates 5 labels however th... | -1 | 2016-06-04T01:23:52Z | 37,625,519 | <p>There are <strong>two</strong> names you have to deal with. The variable name the qlabel is bound to and the <code>objectName</code> that <code>Qt</code> uses.</p>
<p>When dealing with a variable number of items, it's usually best to store those in a dictionary or list</p>
<pre><code>self.labels = dict()
for i in... | 0 | 2016-06-04T01:35:54Z | [
"python",
"qlabel"
] |
Trying to click a button in Python using Selenium Web Driver | 37,625,468 | <p>I am attempting to click a button on a html page using Python and selenium web driver.</p>
<p>This is the source code of the page <a href="http://pastebin.com/112g1Gje" rel="nofollow">http://pastebin.com/112g1Gje</a>.</p>
<p>EDIT: The relevant part at is at the end.. "btn btn-primary"</p>
<p>I am really close to ... | 0 | 2016-06-04T01:24:01Z | 37,625,771 | <pre><code>driver.find_element_by_css_selector(".btn.btn-lg.btn-block.btn-message.open-write-message").click()
</code></pre>
<p>I was clicking the wrong thing.
Make sure to include the dots.</p>
| 1 | 2016-06-04T02:30:28Z | [
"python",
"selenium",
"elements",
"clicking"
] |
New to Tensorflow - trying to repurpose an MNIST multilayer network to a calculator | 37,625,511 | <p>Could someone help or guide me through what I should do better in order for this to work? </p>
<p>I changed the number of inputs to 2 and generated some random data, "x1" and "x2" (one number to be added to another). The idea is to use variables "add" and "mul" as the real output and base the cost (variable "Y") of... | 0 | 2016-06-04T01:34:18Z | 37,645,569 | <p>So are you training a feed forward network or a recurrent neural network?</p>
<p>The code you write within RNN() remind me of a simple neural network (feedforward network). Yet your tittle says you are working on RNN's</p>
<p>You might find <a href="http://robromijnders.github.io/LSTM_mult/" rel="nofollow">this</a... | 1 | 2016-06-05T18:51:36Z | [
"python",
"machine-learning",
"tensorflow"
] |
Pygame game doesn't work | 37,625,580 | <p>So the idea for my game is the it will open onto a menu which has four options, Easy, Medium, Hard, and Exit. The Easy option will open the first level, the Medium open the second level, the Hard will open the third level, and the exit will quit the game. </p>
<p>If the user selects the Easy, Medium, or Hard option... | 0 | 2016-06-04T01:48:24Z | 37,640,731 | <pre><code>import pygame, random, os, sys
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
YELLOW = (255, 200, 0)
GREY = (100, 100, 100)
pygame.init()
screen = pygame.display.set_mode((480, 320))
font = pygame.font.SysFont("Calibri", 50)
help_f... | 1 | 2016-06-05T10:14:30Z | [
"python",
"pygame"
] |
Precision is lost / changed once data goes to Cython module | 37,625,628 | <p>I ported some code that was using NumPy into Cython to get some performance boost. I achieved a considerable boost but I'm experiencing one issue. </p>
<p>The results obtained by Cython differ from the ones obtained by Python. I have no clue why this is happening so I decided to see what was getting pushed to the C... | 4 | 2016-06-04T01:58:21Z | 37,625,693 | <p>The first two steps to solving the problem are:</p>
<ol>
<li><p>Determine the specific integer type used by NumPy on your platform (e.g. <code>int32</code>, <code>int64</code> ...), for example by checking the <code>dtype</code> attribute of the integer array or one of its values.</p></li>
<li><p>Determine the bit-... | 1 | 2016-06-04T02:14:46Z | [
"python",
"c",
"numpy",
"cython",
"precision"
] |
How to put button on same row as django-bootstrap3 pagination | 37,625,678 | <p>I am using django-tables2 and django-bootstrap3 to render a table w/ pagination. I'd like to add a button on the same row as the pagination but my Submit button is showing below the pagination. How should I make the button align to the bottom right of the table along the same row as the pagination links?</p>
<p>He... | 1 | 2016-06-04T02:11:22Z | 37,626,466 | <p>Try to place the table and the button in two adjacent columns:</p>
<pre><code><div class="row">
<form method='POST' action='{% url "playlists:add_track" %}'>{% csrf_token %}
<div class="col-sm-10">
{% render_table table "django_tables2/bootstrap3.html" %}
</div>
<div c... | 1 | 2016-06-04T04:45:59Z | [
"python",
"django",
"twitter-bootstrap",
"pagination"
] |
Flask ImportError causing 500 error, works on local | 37,625,735 | <p>Application works on local using <code>python run.py</code> but when deployed to Ubuntu VPS with Apache, it gives a 500 error.</p>
<p>Apache Logs return:</p>
<pre><code>File "/var/www/ssapi/venv/lib/python2.7/site-packages/flask/app.py", line 28, in <module>, referer: http://api.soundshelter.net/
[Fri Jun 03... | 0 | 2016-06-04T02:23:14Z | 37,626,847 | <p>Re-install Flask fixed this. Thanks @cricket_007</p>
| 0 | 2016-06-04T05:50:27Z | [
"python",
"flask"
] |
Trying to make a function return the longest string | 37,625,776 | <p>Hey everyone I'm trying to define a function that can return the longest string in a list as this is what I have so far:</p>
<pre><code>record = ['60', 'Edward St', 'NSW','4019']
def length(lists):
a = 0
answer = ''
for item in lists:
x = len(item)
if x < a:
a = x
answer... | 1 | 2016-06-04T02:31:46Z | 37,625,786 | <p>You can do this really simply</p>
<pre><code>record = ['60', 'Edward St', 'NSW','4019']
def length(lists):
a = 0
ans = -1
answer = ''
for ind, item in enumerate(lists):
x = len(item)
if x>a:
a = x
ans=ind
return lists[a]
print length(record)
</code></pr... | 0 | 2016-06-04T02:35:17Z | [
"python",
"string"
] |
Trying to make a function return the longest string | 37,625,776 | <p>Hey everyone I'm trying to define a function that can return the longest string in a list as this is what I have so far:</p>
<pre><code>record = ['60', 'Edward St', 'NSW','4019']
def length(lists):
a = 0
answer = ''
for item in lists:
x = len(item)
if x < a:
a = x
answer... | 1 | 2016-06-04T02:31:46Z | 37,625,794 | <p>You can do it as follows.</p>
<pre><code>record = ['60', 'Edward St', 'NSW','4019']
def length(lists):
a = 0
answer = ""
for item in lists:
x = len(item)
if x > a:
a = x
answer = item
return answer
print (length(record))
</code></pre>
<p>What you did wro... | 1 | 2016-06-04T02:37:53Z | [
"python",
"string"
] |
Trying to make a function return the longest string | 37,625,776 | <p>Hey everyone I'm trying to define a function that can return the longest string in a list as this is what I have so far:</p>
<pre><code>record = ['60', 'Edward St', 'NSW','4019']
def length(lists):
a = 0
answer = ''
for item in lists:
x = len(item)
if x < a:
a = x
answer... | 1 | 2016-06-04T02:31:46Z | 37,625,796 | <p><a href="https://docs.python.org/3/library/functions.html?highlight=max#max"><code>max()</code></a> will find the maximum value from an iterable, and you can provide it a function to tell it how to compare them. Here, telling it to compare items by their length.</p>
<pre><code>record = ['60', 'Edward St', 'NSW', '4... | 6 | 2016-06-04T02:39:12Z | [
"python",
"string"
] |
Trying to make a function return the longest string | 37,625,776 | <p>Hey everyone I'm trying to define a function that can return the longest string in a list as this is what I have so far:</p>
<pre><code>record = ['60', 'Edward St', 'NSW','4019']
def length(lists):
a = 0
answer = ''
for item in lists:
x = len(item)
if x < a:
a = x
answer... | 1 | 2016-06-04T02:31:46Z | 37,625,809 | <p>this should work. </p>
<pre><code>def length(lists):
a = 0
answer = ''
for item in lists:
x = len(item)
if x > a:
a = x
answer = item
return answer
</code></pre>
| 0 | 2016-06-04T02:41:33Z | [
"python",
"string"
] |
GAE Python - No module named MySQLdb | 37,625,838 | <p>Recently I switched to "vm: true" on my app.yaml. Since then I'm having some issues regarding the MySQLdb library.</p>
<p>I'm trying to import MySQL like this:</p>
<pre><code>import MySQLdb
</code></pre>
<p>My requirements.txt looks like this:</p>
<pre><code>MySQL-python==1.2.5
</code></pre>
<p>I figured tha... | 0 | 2016-06-04T02:47:33Z | 37,637,921 | <p>You should use the following command to deploy:</p>
<pre><code>gcloud preview app deploy
</code></pre>
<p>Take a look <a href="https://cloud.google.com/appengine/docs/flexible/python/migrating-an-existing-app#deploying" rel="nofollow">here</a> for more details.</p>
<p>Also, <a href="https://github.com/GoogleCloud... | 1 | 2016-06-05T02:37:44Z | [
"python",
"mysql",
"google-app-engine"
] |
How do I overwrite method in python? | 37,625,866 | <p>I have a bit of a dilemma where in <code>fileB</code> I need to call on class <code>classC</code> but before I do that I need to overwrite <code>functionA</code>. I'm not sure how to do this. thank you for any help in advance!</p>
<pre><code>#fileA
class classA():
def functionA():
print('Hello World!')... | 1 | 2016-06-04T02:52:47Z | 37,625,985 | <p>The "proper" way to do what you want is to <em>override</em> the method, not to overwrite it. You do that by creating a subclass of the class and providing a new definition for one or more of its methods.</p>
<p>First of all though there is an error in the definition of <code>classA.functionA()</code> - you need to... | 3 | 2016-06-04T03:17:19Z | [
"python",
"python-3.x",
"overwrite"
] |
How do I overwrite method in python? | 37,625,866 | <p>I have a bit of a dilemma where in <code>fileB</code> I need to call on class <code>classC</code> but before I do that I need to overwrite <code>functionA</code>. I'm not sure how to do this. thank you for any help in advance!</p>
<pre><code>#fileA
class classA():
def functionA():
print('Hello World!')... | 1 | 2016-06-04T02:52:47Z | 37,625,993 | <p>The name of the technique you're looking for is monkeypatching.</p>
<p>Functions in Python are first-class objects. As such, you can simply assign them to a class or object. That does mean you can have two objects which are instances of the same class, that call two different methods even though the same name was i... | 0 | 2016-06-04T03:19:02Z | [
"python",
"python-3.x",
"overwrite"
] |
Python list and dictionary | 37,625,919 | <p>How do I access dictionaries inside a list?</p>
<pre><code>c = [{'team':2000,'name':'a'}, {'team':3000,'name':'b'}]
values = []
for key, value in c.iteritems():
values.append((key, value))
print values
</code></pre>
<p>I tried accessing the list using <code>iteritems</code> but I got an error specifying <c... | 0 | 2016-06-04T03:04:52Z | 37,625,954 | <p>I'm not sure what your desired output is, but the problem is that <code>c</code> is a <em><code>list()</code> of <code>dict()</code>s</em>, not a <code>dict()</code>. So if you want to loop over every key and value in each dict in the list, you need two loops:</p>
<pre><code>In [85]: for dictionary in c:
....: ... | 2 | 2016-06-04T03:10:26Z | [
"python"
] |
Python list and dictionary | 37,625,919 | <p>How do I access dictionaries inside a list?</p>
<pre><code>c = [{'team':2000,'name':'a'}, {'team':3000,'name':'b'}]
values = []
for key, value in c.iteritems():
values.append((key, value))
print values
</code></pre>
<p>I tried accessing the list using <code>iteritems</code> but I got an error specifying <c... | 0 | 2016-06-04T03:04:52Z | 37,627,054 | <p>"c" is not a dictionary therefore iteritems() will not work. Iterate through the list first to isolate the dictionaries. </p>
<pre><code>>>> c = [{'team':2000,'name':'a'}, {'team':3000,'name':'b'}]
... for i in c:
... for k,v in i.items():
... print "key : "+str(k)+' *** '+ "value : "+str(v)
.... | 0 | 2016-06-04T06:18:34Z | [
"python"
] |
Python list and dictionary | 37,625,919 | <p>How do I access dictionaries inside a list?</p>
<pre><code>c = [{'team':2000,'name':'a'}, {'team':3000,'name':'b'}]
values = []
for key, value in c.iteritems():
values.append((key, value))
print values
</code></pre>
<p>I tried accessing the list using <code>iteritems</code> but I got an error specifying <c... | 0 | 2016-06-04T03:04:52Z | 37,627,473 | <p>Try this: </p>
<pre><code>c = [{'team':2000,'name':'a'}, {'team':3000,'name':'b'}]
values = []
for row in c:
for key, value in row.iteritems():
if key == 'name':
values.append((key, value))
print(values)
# gives this
# [('name', 'a'), ('name', 'b'),]
</code></pre>
| 1 | 2016-06-04T07:11:30Z | [
"python"
] |
How to launch python 2.7 from win7 powershell after installing 3.5? | 37,626,023 | <p>I just installed python 3.5.1 on a win7 OS which also has python 2.7. Typing "python" into the Powershell now launches 3.5.1. Previously that launched 2.7.</p>
<p>How do I launch python 2.7 now? Typing "python27" or "Python27", "python2.7", "Python2.7" doesn't do it. I do have "C:\Python;" in my user Environment va... | 2 | 2016-06-04T03:25:47Z | 37,626,153 | <p>Python installations place a a <em>stub</em> executable named <code>py.exe</code> in <code>$env:SYSTEMROOT</code> (typically: <code>C:\Windows</code>), to which you can pass an option to specify the version you want to run: <code>-2</code> to launch an installed 2.x version, and <code>-3</code> for an installed 3.x ... | 3 | 2016-06-04T03:49:36Z | [
"python",
"windows",
"python-2.7",
"powershell"
] |
How to launch python 2.7 from win7 powershell after installing 3.5? | 37,626,023 | <p>I just installed python 3.5.1 on a win7 OS which also has python 2.7. Typing "python" into the Powershell now launches 3.5.1. Previously that launched 2.7.</p>
<p>How do I launch python 2.7 now? Typing "python27" or "Python27", "python2.7", "Python2.7" doesn't do it. I do have "C:\Python;" in my user Environment va... | 2 | 2016-06-04T03:25:47Z | 37,626,565 | <p>For the sake of simplicity, I would suggest you use WinPython distribution. There is a <code>winpython command prompt</code> bundled inside. You can open the It in the specific Python version and that Python will be invoked!</p>
| 1 | 2016-06-04T05:00:47Z | [
"python",
"windows",
"python-2.7",
"powershell"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.