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 |
|---|---|---|---|---|---|---|---|---|---|
TypeError: cannot concatenate 'str' and 'NoneType' objects when placing the custom url in scrapy.Request() | 39,794,747 | <p>I get a url that cannot be used to fetch data from next page, so created a <code>base_url = 'http://www.marinetraffic.com'</code> variable and passed it scrapy request. <code>port_homepage_url = base_url + port_homepage_url</code>. It works fine, when i yeild the result like this. <code>yield {'a': port_homepage_u... | 2 | 2016-09-30T15:11:26Z | 39,794,893 | <p>The problem does not happen on the initial start URL page, but happens later on when subsequent requests are processed. Take for example <a href="http://www.marinetraffic.com/en/ais/index/ships/range/port_id:1699/port_name:HAMRIYA" rel="nofollow">this page</a>. There are no links in the 7-th <code>td</code> element ... | 2 | 2016-09-30T15:20:21Z | [
"python",
"scrapy"
] |
When saving ManyToMany Field value in django ,error occures invalid literal for int() with base 10 | 39,794,828 | <p>I am trying to save ManyToMany filed value in django model objects.But when i ma saving an error comes invalid literal for int() with base 10.
My code is</p>
<pre><code>def saveDetail(request):
userExp = str(request.GET.get('user'))
tags = request.POST.getlist('tags')
comment = request.POST.get('commen... | 0 | 2016-09-30T15:16:22Z | 39,795,071 | <p><code>tags</code> is a <code>ManyToMany</code> field. You can't use a direct assignment to a list item to update the field. You should instead assign via the field's <code>add</code> method tag <em>objects</em> corresponding to the items in the list.</p>
<p>Assuming you <code>TagsExp</code> has a field <code>label<... | 1 | 2016-09-30T15:30:36Z | [
"python",
"django"
] |
Understanding Parsing Error when reading model file into PySD | 39,794,851 | <p>I am receiving the following error message when I try to read a Vensim model file (.mdl) using Python's PySD package. </p>
<p>My code is:</p>
<pre><code>import pysd
import os
os.chdir('path/to/model_file')
model = pysd.read_vensim('my_model.mdl')
</code></pre>
<p>The Error I receive is:</p>
<pre><code>Traceba... | 0 | 2016-09-30T15:17:57Z | 40,115,491 | <p>Good news is that there is nothing wrong with your code. =) (Although you can also just include the path to the file in the <code>.read_vensim</code> call, if you don't want to make the dir change). </p>
<p>That being the case, there are a few possibilities that would cause this issue. One is if the model file is c... | 0 | 2016-10-18T18:28:44Z | [
"python",
"vensim"
] |
Understanding Parsing Error when reading model file into PySD | 39,794,851 | <p>I am receiving the following error message when I try to read a Vensim model file (.mdl) using Python's PySD package. </p>
<p>My code is:</p>
<pre><code>import pysd
import os
os.chdir('path/to/model_file')
model = pysd.read_vensim('my_model.mdl')
</code></pre>
<p>The Error I receive is:</p>
<pre><code>Traceba... | 0 | 2016-09-30T15:17:57Z | 40,134,671 | <p>If you aren't using subscripts, you may have found a bug in the parser. If so, best course is to create a report in the github <a href="https://github.com/JamesPHoughton/pysd/issues" rel="nofollow">issue tracker</a> for the project. The stack trace you posted says that the error is happening in the first line of the... | 0 | 2016-10-19T14:43:24Z | [
"python",
"vensim"
] |
OCR pytesseract, recognize the biggest word in an image | 39,794,876 | <p>I'm using <strong>pytesseract</strong> to recognize text from an image, is there anyway i can detect/recognize the biggest word in that image</p>
<p><a href="http://i.stack.imgur.com/7lgZs.jpg" rel="nofollow">Click here to display the image</a></p>
<p>In the image above, i'm trying to detect/recognize "Atacand Plu... | 2 | 2016-09-30T15:19:28Z | 40,003,222 | <p>The issue here is that when you use the Tesseract segmentation it doesn't segment the image word by word, rather it does it by zones in the image, so paragraphs and blocks of words. So if you are trying to do this pre-recognition, then you are going to run into issues and errors. </p>
<p>Another option is to do pos... | 2 | 2016-10-12T16:03:42Z | [
"python",
"image-processing",
"ocr"
] |
print average percentage of a student from an array | 39,794,878 | <p>The program is supposed to calculate and print out a given student's average percentage.</p>
<p>Unfortunately I am only able to print out the average percentage of the last student name in the array.
I want to know where exacltly I am going wrong with my coding.
Thanks. Heres my code below.</p>
<pre><code>def ave... | 0 | 2016-09-30T15:19:29Z | 39,795,301 | <p>In your first loop:</p>
<pre><code>for i in range(N):
name_marks = input('name & marks').split() #enter name & three different scores
name = str(name_marks[0])
arr.append(name)
print(arr)
</code></pre>
<p>you don't store the marks of the previous students, you replace your variable <code>n... | 0 | 2016-09-30T15:43:51Z | [
"python",
"arrays",
"python-3.x",
"iteration"
] |
What to do when api returns html or json for different errors | 39,794,885 | <p>Using python requests to talk to the github api.</p>
<pre><code>response = requests.post('https://api.github.com/orgs/orgname/repos', auth, data)
</code></pre>
<p>If the request returns a 405 error I get HTML in the response.text</p>
<pre><code><html>
<head><title>405 Not Allowed</title>&l... | 0 | 2016-09-30T15:19:55Z | 39,795,745 | <p>In response to:</p>
<blockquote>
<p>If not, can I find out what type the response content will be?</p>
</blockquote>
<p>If you want to know why github returns html rather than JSON for the API call, I can not answer that; however, to the answer to the above asked question, you can look at the "content" header of... | 0 | 2016-09-30T16:08:37Z | [
"python",
"json",
"http",
"python-requests"
] |
Better way to implement `df[m] = df[x] + df[y] + df[z]` | 39,794,937 | <p>I want to get the sum of three columns, the method I took is as follows:</p>
<pre><code>In [14]:
a_pd = pd.DataFrame({'a': np.arange(3),
'b': [5, 7, np.NAN],
'c': [2, 9, 0]})
a_pd
Out[14]:
a b c
0 0 5.0 2
1 1 7.0 9
2 2 NaN 0
In [18]:
b_pd = a_pd['a'] + a_p... | 2 | 2016-09-30T15:22:21Z | 39,794,989 | <p>You can use the sum method of the DataFrame:</p>
<pre><code>a_pd.sum(axis=1)
Out:
0 7.0
1 17.0
2 2.0
dtype: float64
</code></pre>
<p>If you want to specify columns:</p>
<pre><code>a_pd[['a', 'b', 'c']].sum(axis=1)
Out:
0 7.0
1 17.0
2 2.0
dtype: float64
</code></pre>
| 5 | 2016-09-30T15:25:28Z | [
"python",
"pandas",
"apply",
null
] |
Better way to implement `df[m] = df[x] + df[y] + df[z]` | 39,794,937 | <p>I want to get the sum of three columns, the method I took is as follows:</p>
<pre><code>In [14]:
a_pd = pd.DataFrame({'a': np.arange(3),
'b': [5, 7, np.NAN],
'c': [2, 9, 0]})
a_pd
Out[14]:
a b c
0 0 5.0 2
1 1 7.0 9
2 2 NaN 0
In [18]:
b_pd = a_pd['a'] + a_p... | 2 | 2016-09-30T15:22:21Z | 39,795,083 | <p>np.add requires inputs</p>
<pre><code>b_pd = a_pd[['a', 'b', 'c']].apply(np.sum, axis=1)
</code></pre>
| 2 | 2016-09-30T15:31:20Z | [
"python",
"pandas",
"apply",
null
] |
Python Flask Split Text in Form by comma | 39,795,018 | <p>I'm writing a function in Flask that takes a list of IDs and sends a request to Amazon for data on those IDs. I'm running into an issue where the contents of the form are not splitting the way I want it to. I'd like it to be split by a comma or whitespace so that each ID is sent to the request, but instead it's send... | 0 | 2016-09-30T15:27:05Z | 39,795,602 | <p>You have a for loop that you don't need. Instead the following would work</p>
<pre><code>if request.method == 'POST':
ids = request.form['ids']
f_n = request.form['f_n']
IDlist = ids.split(',')
</code></pre>
<p>What you are doing is you are looping through each individual character, splitting each char... | 1 | 2016-09-30T15:59:27Z | [
"python",
"forms",
"flask"
] |
Filtering out stopwords | 39,795,061 | <p>I've created a simple word count program and I'm trying to filter out commonly used words from my list using nltk (see below).</p>
<p>My question is how would I apply my "stop" filter to my "frequency" list?</p>
<pre><code>#Start
from nltk.corpus import stopwords
import re
import string
frequency = {}
document_te... | 0 | 2016-09-30T15:29:59Z | 39,795,146 | <pre><code>stop = set(stopwords.words('english'))
stop.(".")
frequency = {k:v for k,v in frequency.items() if v>1 and k not in stop}
</code></pre>
<p>While <code>stop</code> is still a <code>set</code>, check the keys of your <code>frequency</code> dictionary when doing the comprehension. You can still make stop ... | 1 | 2016-09-30T15:34:45Z | [
"python",
"nltk",
"stop-words"
] |
Finding width of peaks | 39,795,062 | <p>I have a data set on which I'm trying to detect peaks and the left/right bounds of those peaks.</p>
<p>I'm successfully using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks_cwt.html" rel="nofollow">scipy <code>find_peaks_cwt</code></a> to find the peaks, but I don't know how to... | 2 | 2016-09-30T15:30:07Z | 39,797,156 | <p>If a Gaussian fit would be appropriate, you could take the number of peaks you have found and fit n Gaussian distributions (1 for each peak) plus a constant variable for the background noise (or you could add another Gaussian to the curve fit</p>
<pre class="lang-python prettyprint-override"><code>import numpy as n... | 1 | 2016-09-30T17:41:49Z | [
"python",
"numpy",
"scipy"
] |
Max heap throwing index out of bounds | 39,795,082 | <p>Below is my max heap implementation. I can really figure out why I am getting the index out of bounds error. I have assigned array to self.heap</p>
<pre><code>class heap:
def __init__(self):
self.heapsize=0
self.heap=[0]
def builheap(self,list):
self.heapsize = len(list)
sel... | 0 | 2016-09-30T15:31:19Z | 39,796,197 | <p>You have this code:</p>
<pre><code> if list[2*index]<=self.heapsize and list[2*index]>list[index]:
largest=list[2*index]
else:
largest=index
if list[2*index+1]<= self.heapsize and list[2*index+1]>list[index]:
</code></pre>
<p>You're trying to index into the list before checki... | 1 | 2016-09-30T16:36:09Z | [
"python",
"algorithm",
"tree",
"heap",
"binary-heap"
] |
How to put these outputs into 9 by 9 array using Numpy array | 39,795,138 | <p>sorry if this is a basic question. I am just starting with python and programming.</p>
<p>I want the output from iteration in a 9 by 9 array. For now I just get the output in one column.</p>
<pre><code>for q in range(11,20,1):
for x in range(11,20,1):
if q <= x:
V = 3.5*q â 1.5 * x
... | 0 | 2016-09-30T15:34:24Z | 39,795,514 | <p>Your problem is exactly what the error says: you are trying to access index 11 in a an array of size 9 (by 9).</p>
<p><code>for q in range(11,20):</code> is iterating over <code>q = 11, 12, 13,..., 19</code>.
Then <code>V[q][x]</code> is trying to access element with indexes <code>q</code> and <code>x</code> in <c... | 1 | 2016-09-30T15:55:34Z | [
"python",
"arrays",
"numpy",
"multidimensional-array"
] |
Regex to match repeated set of characters | 39,795,262 | <p>I'd like to be able to extract the following patterns from free text.</p>
<pre><code>VBAV/123456.01
VBAV/132453.02
VSAV/132452.01.03
VMAV/142143.01.02
</code></pre>
<p>Currently I am trying as below but not much success</p>
<pre><code>df["Project Id"] = df["WBS element"].str.cat(
df["Network VxAV"]).str.cat(
df["... | 2 | 2016-09-30T15:41:42Z | 39,795,337 | <p>Why not:</p>
<pre><code>V[BSM]AV/[\d.]+
</code></pre>
<p>See <a href="https://regex101.com/r/zHX8gH/1" rel="nofollow"><strong>a demo on regex101.com</strong></a>.</p>
| 0 | 2016-09-30T15:45:51Z | [
"python",
"regex",
"pandas"
] |
Regex to match repeated set of characters | 39,795,262 | <p>I'd like to be able to extract the following patterns from free text.</p>
<pre><code>VBAV/123456.01
VBAV/132453.02
VSAV/132452.01.03
VMAV/142143.01.02
</code></pre>
<p>Currently I am trying as below but not much success</p>
<pre><code>df["Project Id"] = df["WBS element"].str.cat(
df["Network VxAV"]).str.cat(
df["... | 2 | 2016-09-30T15:41:42Z | 39,796,413 | <pre><code>r'V[BSM]AV/\d{6}(?:\.\d\d){0,2}(?!\d)'
</code></pre>
<p>Matches exactly 6 digits, and 0-2 instances of <code>.##</code>. <code>(?:xxxx)</code> is a non-capturing group. Cannot be followed by another digit, so it won't match:</p>
<pre><code>VBAV\1234567
VBAV\122346.123
</code></pre>
<p>You may need to adj... | 0 | 2016-09-30T16:52:05Z | [
"python",
"regex",
"pandas"
] |
Regex to match repeated set of characters | 39,795,262 | <p>I'd like to be able to extract the following patterns from free text.</p>
<pre><code>VBAV/123456.01
VBAV/132453.02
VSAV/132452.01.03
VMAV/142143.01.02
</code></pre>
<p>Currently I am trying as below but not much success</p>
<pre><code>df["Project Id"] = df["WBS element"].str.cat(
df["Network VxAV"]).str.cat(
df["... | 2 | 2016-09-30T15:41:42Z | 39,796,677 | <p>consider the the <code>pd.Series</code> <code>s</code></p>
<pre><code>s = pd.concat([pd.Series(txt.split('\n')) for _ in range(3)], ignore_index=True)
</code></pre>
<p><strong><em>Option 1</em></strong><br>
my preference</p>
<pre><code>s.str.split('/', expand=True)
</code></pre>
<p><a href="http://i.stack.imgur.... | 1 | 2016-09-30T17:11:10Z | [
"python",
"regex",
"pandas"
] |
Numpy array trims string values | 39,795,280 | <p>Here is the code I am trying to execute</p>
<pre><code>matrix = []
sample = [10,10,'mike','']
for i in range(10):
r = [sample] * 3
matrix.append(r)
matrix = np.array(matrix)
matrix[1][1] = [123,123,'james', 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
print matrix[1][1]
</code></pre>
<p>and here is... | 2 | 2016-09-30T15:42:37Z | 39,795,516 | <p>I found the problem.</p>
<p>conversion from native Python array to Numpy should take place as the last step.</p>
<pre><code>matrix[1][1] = [123,123,'james', 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
matrix = np.array(matrix)
</code></pre>
<p>Now works fine.</p>
| 0 | 2016-09-30T15:55:44Z | [
"python",
"numpy"
] |
Numpy array trims string values | 39,795,280 | <p>Here is the code I am trying to execute</p>
<pre><code>matrix = []
sample = [10,10,'mike','']
for i in range(10):
r = [sample] * 3
matrix.append(r)
matrix = np.array(matrix)
matrix[1][1] = [123,123,'james', 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
print matrix[1][1]
</code></pre>
<p>and here is... | 2 | 2016-09-30T15:42:37Z | 39,795,556 | <p>If you do not specify the <code>dtype</code> when you are converting your list to an array, it will use default behavior. In your case, you are mixing int's and strings, so it will default to unicode <11:</p>
<pre><code>>>> np.array([1,2,'a'])
array(['1', '2', 'a'],
dtype='<U11')
</code></pre>
<p>Wh... | 0 | 2016-09-30T15:57:13Z | [
"python",
"numpy"
] |
Numpy array trims string values | 39,795,280 | <p>Here is the code I am trying to execute</p>
<pre><code>matrix = []
sample = [10,10,'mike','']
for i in range(10):
r = [sample] * 3
matrix.append(r)
matrix = np.array(matrix)
matrix[1][1] = [123,123,'james', 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
print matrix[1][1]
</code></pre>
<p>and here is... | 2 | 2016-09-30T15:42:37Z | 39,795,656 | <p>Your solution:</p>
<pre><code>matrix[1][1] = [123,123,'james', 'sdfsdfsdf werwerwer sdfsdfsd werwerwer sdfsdfsdf']
matrix = np.array(matrix)
</code></pre>
<p>works only because if you do not specify the data type in the array method, numpy set's it to the smallest size possible to hold all data.</p>
<p>If from an... | 0 | 2016-09-30T16:02:39Z | [
"python",
"numpy"
] |
Using "self" in function arguments definition | 39,795,312 | <p>Instead of doing the following:</p>
<pre><code>def MyFunc(self, a, b, c)
self.a = a
self.b = b
self.c = c
</code></pre>
<p>I want to do the following:</p>
<pre><code>def MyFunc(self, self.a, self.b, self.c)
</code></pre>
<p>Why does this not work?</p>
<p>If I have to use the first approach, is there... | -1 | 2016-09-30T15:44:32Z | 39,795,846 | <p>Maybe the problem is related to this behaviour, which might be supprising for new pythoneers:</p>
<pre><code>class Cl():
def MyFunction(self, a):
self.a = a
a= {"w":"old"}
myCl = Cl()
myCl.MyFunction(a)
print a, myCl.a
a.update({"w":"new"})
print a, myCl.a
</code></pre>
<p>which outputs</p>
<pre>... | -3 | 2016-09-30T16:15:19Z | [
"python"
] |
Using "self" in function arguments definition | 39,795,312 | <p>Instead of doing the following:</p>
<pre><code>def MyFunc(self, a, b, c)
self.a = a
self.b = b
self.c = c
</code></pre>
<p>I want to do the following:</p>
<pre><code>def MyFunc(self, self.a, self.b, self.c)
</code></pre>
<p>Why does this not work?</p>
<p>If I have to use the first approach, is there... | -1 | 2016-09-30T15:44:32Z | 39,799,261 | <p>I'm really not sure why you want to do something such as what you describe. It doesn't really make sense that parameters of a function are class attributes.</p>
<p>Now, if what your asking is how to stop the parameters <code>MyFunc()</code> from conflicting with the parameters of another function, then your covered... | 0 | 2016-09-30T20:01:32Z | [
"python"
] |
Using SRV DNS records with the python requests library | 39,795,400 | <p>Is it possible to have the Python requests library resolve a consul domain name with a SRV record and utilize the correct IP address and port when making the request?</p>
<p>For example, given that I have serviceA running with the IP address 172.18.0.5 on port 8080 and this service is registered with consul. And gi... | 0 | 2016-09-30T15:49:43Z | 39,803,800 | <p>No, you can't unless you rewrite <code>requests</code>.</p>
<p>SRV record is design to find a service.<br>
In this case, you already indicate to use http. So client will only query A or AAAA record for <code>serviceA.service.consul</code>.</p>
| 0 | 2016-10-01T06:46:48Z | [
"python",
"dns",
"python-requests",
"consul"
] |
Trying to automate a python script.....Using Windows scheduler | 39,795,451 | <p>So I have the following script which I am using to grab data from the net and save it as an html file in a folder on my pc (same pc) each time I run the script. I'm now trying to automate the process.</p>
<pre><code>import pandas as pd
import datetime as dt
today_date = dt.date.today().isoformat()
df = pd.read_html... | 0 | 2016-09-30T15:52:04Z | 39,802,210 | <p>I got it working by filling in the "Start in(optional)" parameter under the Actions tab, with the first part of the path to the Python exe. </p>
<p>"C:\Python27"</p>
| 0 | 2016-10-01T01:41:40Z | [
"python",
"windows",
"scheduler"
] |
Detect if key is down mac python | 39,795,518 | <p>I've googled all over the place.</p>
<p>I have a python application and I'd like to detect if a key is down (on OSX).</p>
<p>The only answers I've been able to find are either libraries for windows, or libraries that require an application window to be active (like pygame).</p>
<p>Similar to how pymouse has a pos... | 0 | 2016-09-30T15:55:47Z | 39,795,982 | <p>The only way I could think of is <a href="https://docs.python.org/2/library/tty.html" rel="nofollow">tty</a> or <a href="https://docs.python.org/2/library/termios.html#module-termios" rel="nofollow">termios</a>.</p>
<p>Here is a minimal example that waits for user input and prints the keycode if 'a' pressed ...</p>... | 0 | 2016-09-30T16:23:31Z | [
"python",
"osx",
"python-2.7"
] |
Detect if key is down mac python | 39,795,518 | <p>I've googled all over the place.</p>
<p>I have a python application and I'd like to detect if a key is down (on OSX).</p>
<p>The only answers I've been able to find are either libraries for windows, or libraries that require an application window to be active (like pygame).</p>
<p>Similar to how pymouse has a pos... | 0 | 2016-09-30T15:55:47Z | 39,801,622 | <p>Python comex with tkinter, a gui framework that includes cross-platform key press and release handling. The gui part can be suppressed if one only wants the event handling. This works as expected on my Windows machine. It should work on your Mac.</p>
<pre><code>from time import sleep
import tkinter as tk
root = ... | 0 | 2016-09-30T23:59:54Z | [
"python",
"osx",
"python-2.7"
] |
adding score when clicking inside rectangle | 39,795,640 | <p>I have the following exercise to do for school:</p>
<p>Create a textfield which shows a score as follows "Score: " (You can use the text(StringValue, IntegerXposition, IntegerYposition) for the drawing of text), starting at zero.
Make it so that when the user clicks the left mouseButton a score of 10 is added to th... | 0 | 2016-09-30T16:01:29Z | 39,802,030 | <p>I'm not quiet sure if this is possible with just <code>Python/Python 3.5.1</code> alone. I think <code>tkinter</code> is more suitable with making shapes with Python (And I'm not quiet sure because, I never used it before). I would suggest you use a <code>class</code> initialization for this. Here is what I got:</p>... | 0 | 2016-10-01T01:07:48Z | [
"python",
"python-3.x"
] |
adding score when clicking inside rectangle | 39,795,640 | <p>I have the following exercise to do for school:</p>
<p>Create a textfield which shows a score as follows "Score: " (You can use the text(StringValue, IntegerXposition, IntegerYposition) for the drawing of text), starting at zero.
Make it so that when the user clicks the left mouseButton a score of 10 is added to th... | 0 | 2016-09-30T16:01:29Z | 39,802,060 | <p>Just check the position of the mouse pointer when there is a click.</p>
<p>I don't know what library you are using, but just replace <code>mouseX</code> and <code>mouseY</code> with the actual variable names.</p>
<pre><code>def mousePressed():
global Score, xPos, yPos
if mouseButton == LEFT and xPos < m... | 0 | 2016-10-01T01:13:31Z | [
"python",
"python-3.x"
] |
Python beginner - Sorting tuples using lambda functions | 39,795,734 | <p>I'm going through the tutorial intro for Python and I'm stuck on understanding a piece of code. This is from section 4.7.5 of the tutorial.</p>
<pre><code>pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs
</code></pre>
<p>This bit of code returns </p>
<pre><cod... | 0 | 2016-09-30T16:07:46Z | 39,795,817 | <p>your lambda function takes an tuple as input and return the element with index 1 (so the second element since the first would have 0 for index).
so the sorting will only take into consideration the second element of each tuple (the English word). That's why your output is sorted alphabetically in the second element ... | 0 | 2016-09-30T16:13:45Z | [
"python",
"sorting",
"lambda"
] |
Python beginner - Sorting tuples using lambda functions | 39,795,734 | <p>I'm going through the tutorial intro for Python and I'm stuck on understanding a piece of code. This is from section 4.7.5 of the tutorial.</p>
<pre><code>pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs
</code></pre>
<p>This bit of code returns </p>
<pre><cod... | 0 | 2016-09-30T16:07:46Z | 39,795,832 | <p>A <code>lambda</code> is a simplified function, using only an expression.</p>
<p>Any lambda can be written as a function, by adding in a <code>return</code> before the expression, so <code>lambda pair: pair[1]</code> becomes:</p>
<pre><code>def lambda_function(pair): return pair[1]
</code></pre>
<p>So the lambda ... | 0 | 2016-09-30T16:14:26Z | [
"python",
"sorting",
"lambda"
] |
Python beginner - Sorting tuples using lambda functions | 39,795,734 | <p>I'm going through the tutorial intro for Python and I'm stuck on understanding a piece of code. This is from section 4.7.5 of the tutorial.</p>
<pre><code>pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
pairs
</code></pre>
<p>This bit of code returns </p>
<pre><cod... | 0 | 2016-09-30T16:07:46Z | 39,795,839 | <p>Sometimes when starting to work with <code>lambda</code>, it's easier to write out the function explicitly. Your lambda function is equivalent to:</p>
<pre><code>def sort_key(pair):
return pair[1]
</code></pre>
<p>If we want to be more verbose, we can unpack pair to make it even more obvious:</p>
<pre><code>... | 0 | 2016-09-30T16:14:56Z | [
"python",
"sorting",
"lambda"
] |
Get the index of a unique character in a table (list of lists)? | 39,795,784 | <p>I have a list of r lists of r elements each.
Let's say <code>r=3</code> then I have something that looks like this:</p>
<pre><code>list=[["o","o","o"],["o","i","o"],["o","o","o"]]
</code></pre>
<p>I would like, using the method """<code>list.index(item)</code>""", to get the index of the "i" elements inside this l... | -1 | 2016-09-30T16:11:12Z | 39,795,995 | <p>You could <code>try</code> to find the index row by row:</p>
<pre><code>def findI(rows):
for i,row in enumerate(rows):
try:
return (i,row.index("i"))
except ValueError:
pass
</code></pre>
<p>For example:</p>
<pre><code>>>> x =[["o","o","o"],["o","i","o"],["o","... | 1 | 2016-09-30T16:24:32Z | [
"python",
"list",
"python-3.x"
] |
Get the index of a unique character in a table (list of lists)? | 39,795,784 | <p>I have a list of r lists of r elements each.
Let's say <code>r=3</code> then I have something that looks like this:</p>
<pre><code>list=[["o","o","o"],["o","i","o"],["o","o","o"]]
</code></pre>
<p>I would like, using the method """<code>list.index(item)</code>""", to get the index of the "i" elements inside this l... | -1 | 2016-09-30T16:11:12Z | 39,796,244 | <p>Or you can try this:</p>
<pre><code>list=[["o","o","o"],["o","i","o"],["o","o","o"]]
f = [sublist for sublist in list if element in sublist][0]
print(list.index(f), f.index(element))
</code></pre>
<p>That <code>[0]</code> is because it will return something like <code>[[a,b]]</code>, because is like a filter. But... | 0 | 2016-09-30T16:38:53Z | [
"python",
"list",
"python-3.x"
] |
Get the index of a unique character in a table (list of lists)? | 39,795,784 | <p>I have a list of r lists of r elements each.
Let's say <code>r=3</code> then I have something that looks like this:</p>
<pre><code>list=[["o","o","o"],["o","i","o"],["o","o","o"]]
</code></pre>
<p>I would like, using the method """<code>list.index(item)</code>""", to get the index of the "i" elements inside this l... | -1 | 2016-09-30T16:11:12Z | 39,797,970 | <p>If you are looking for a solution that finds an index for all values in the nested list, here is a function for you:</p>
<pre><code>def find_indexes(needle, lst):
return [(lst_idx, sub_idx) for lst_idx, sublst in enumerate(lst)
for sub_idx, i in enumerate(sublst)
... | 2 | 2016-09-30T18:34:05Z | [
"python",
"list",
"python-3.x"
] |
Iterating through two lists, operating and creating a third list in Python | 39,795,840 | <p>I am a completely Python beginner and am really struggling with iterations on Lists!
There's this problem I have been trying to solve using python using Lists:</p>
<p>I have a "<strong>TotalList</strong>" for the total costs on each hour for a product:</p>
<p>Hr totalcost<br>
1 100<br>
2 50<br>
...<br>
24 1... | 0 | 2016-09-30T16:14:57Z | 39,795,948 | <p>You can create a dictionary from your total cost list and compute the minute costs by referencing the total cost at each hour (from the dict) and multiplying by the percentage minute cost.</p>
<p>A <em>list comprehension</em> will do:</p>
<pre><code>tc_mapping = dict(totalList) # map hour to cost
minute_cost = [(h... | 1 | 2016-09-30T16:21:23Z | [
"python",
"list",
"numpy",
"comparison"
] |
Iterating through two lists, operating and creating a third list in Python | 39,795,840 | <p>I am a completely Python beginner and am really struggling with iterations on Lists!
There's this problem I have been trying to solve using python using Lists:</p>
<p>I have a "<strong>TotalList</strong>" for the total costs on each hour for a product:</p>
<p>Hr totalcost<br>
1 100<br>
2 50<br>
...<br>
24 1... | 0 | 2016-09-30T16:14:57Z | 39,796,114 | <p>Easiest for a beginner to understand IMO:</p>
<pre><code>minuteCost = []
x = 0
for i in minList:
tempList = [i[0], i[1], totalList[x][1]*i[2]]
minuteCost.append(tempList)
x += 1
</code></pre>
<p>This assumes that TotalList and minList are the same length.</p>
| 0 | 2016-09-30T16:31:25Z | [
"python",
"list",
"numpy",
"comparison"
] |
python Return value none | 39,796,124 | <p>I need some clarification. When I execute the below code with the function using <code>return</code>, I am getting different behavior from when I use the function using <code>print</code>. I am getting the same output but it is printing a word "none" which is not in the program.</p>
<pre><code>import random
# **W... | -1 | 2016-09-30T16:32:03Z | 39,796,469 | <p>The problem is that the function you use with print statements does not have a return value. However you are printing the return of that function with the line <code>print(fortune)</code>. So what should it print if there is nothing there? Well, it prints <code>None</code>.</p>
| 0 | 2016-09-30T16:55:44Z | [
"python",
"python-2.7"
] |
python Return value none | 39,796,124 | <p>I need some clarification. When I execute the below code with the function using <code>return</code>, I am getting different behavior from when I use the function using <code>print</code>. I am getting the same output but it is printing a word "none" which is not in the program.</p>
<pre><code>import random
# **W... | -1 | 2016-09-30T16:32:03Z | 39,796,577 | <p>Every Python function implicitly returns <code>None</code>, unless you explicitly return something else.</p>
<p>In your first section, you are explicitly returning the string, and printing that value.</p>
<p>In your second section, you are printing the message, and then printing the return value (<code>None</code>... | 0 | 2016-09-30T17:04:53Z | [
"python",
"python-2.7"
] |
Proxybroker IndexError | 39,796,177 | <p>I'm trying to use the python package proxybroker.<br>
I tried to use one of the examples mentioned here. I just copied the following example to run locally:</p>
<blockquote>
<pre><code>import asyncio from proxybroker import Broker
async def save(proxies, filename):
"""Save proxies to a file."""
with open(... | 0 | 2016-09-30T16:35:00Z | 39,804,885 | <p>Deprecation warnings are harmless (at least unless I'll remove this kind of backward compatibility).</p>
<p>The error just says that <code>getproxy.net</code> is not available -- this is your main problem.</p>
| 0 | 2016-10-01T09:15:02Z | [
"python",
"asynchronous",
"python-3.5",
"python-asyncio",
"aiohttp"
] |
statsmodels mosaic plot - how to order categories | 39,796,183 | <p>Here is dataframe:</p>
<pre><code>import pandas as pd
from statsmodels.graphics.mosaicplot import mosaic
df = pd.DataFrame({'size' : ['small', 'large', 'large', 'small', 'large', 'small'],
'length' : ['long', 'short', 'short', 'long', 'long', 'short']})
</code></pre>
<p>if I plot it <code>mosaic(df, ['size', 'len... | 2 | 2016-09-30T16:35:10Z | 39,796,405 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a> to sort values present in the size column to alter the order.</p>
<pre><code>mosaic(df.sort_values('size'), ['size', 'length'])
</code></pre>
<p><a href="http://i.stack.... | 2 | 2016-09-30T16:51:02Z | [
"python",
"pandas",
"statsmodels",
"mosaic"
] |
PCRE Regex (*COMMIT) equivalent for Python | 39,796,252 | <p>The below pattern took me a long time to find. When I finally found it, it turns out that it doesn't work in Python. Does anyone know if there is an alternative?</p>
<p><code>(*COMMIT)</code> Defined: Causes the whole match to fail outright if the rest of the pattern does not match.</p>
<p><code>(*FAIL)</code> doe... | 2 | 2016-09-30T16:39:24Z | 39,796,696 | <p>This might not be a generic replacement, but for your case you can work with lookaheads, to assert that dog is matched, but park is not: <code>^(?=.*dog)(?!.*park).*$</code></p>
<p>Your samples on <a href="https://regex101.com/r/gOY9GT/1" rel="nofollow">regex101</a></p>
| 2 | 2016-09-30T17:12:32Z | [
"python",
"regex"
] |
get list in python | 39,796,301 | <pre><code>#ideal nodes list should be
['A','B','C','D','E','F','G','H','I','J','K','L','M','N']
</code></pre>
<p>So I tried to write a definition to read the nodes and edges.Here is my code,but it seems does not work.</p>
<pre><code>""" read nodes"""
def rd_nodes(a):
nline =[line.split(":")[1].replace(';',',').s... | 1 | 2016-09-30T16:42:57Z | 39,796,787 | <p><a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations</code></a> can help you here.</p>
<p>Try this:</p>
<pre><code>from itertools import combinations
s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
nodes = set()
edges = set()
for line in s... | 1 | 2016-09-30T17:18:33Z | [
"python",
"list",
"edges"
] |
get list in python | 39,796,301 | <pre><code>#ideal nodes list should be
['A','B','C','D','E','F','G','H','I','J','K','L','M','N']
</code></pre>
<p>So I tried to write a definition to read the nodes and edges.Here is my code,but it seems does not work.</p>
<pre><code>""" read nodes"""
def rd_nodes(a):
nline =[line.split(":")[1].replace(';',',').s... | 1 | 2016-09-30T16:42:57Z | 39,797,325 | <p>As @skovorodkin has the correct answer, but if you want pure Python version (Though I wonder why) you could use this code</p>
<pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def combinations(nodes):
if len(nodes) < 2:
return (tuple(nodes))
else:
i = 1
ret_tuple = []
... | 0 | 2016-09-30T17:52:53Z | [
"python",
"list",
"edges"
] |
range as input in python | 39,796,305 | <p>this is a simple program for Fibonacci series . its running perfectly for fixed range. but i would like to know is it possible to get range as input? if so please let me know the syntax to get range as input. </p>
<pre><code>xx=0
x=float (raw_input("enter the starting number:"))
r1=xx+x
print r1
r2=r1+x
print ... | -5 | 2016-09-30T16:43:06Z | 39,796,421 | <p>Do it like you asked for the starting number:</p>
<pre><code>number_of_outputs = int( raw_input('Enter the number of outputs: '))
#Your code goes here
for i in range(number_of_ouputs):
#More code goes here
</code></pre>
| 1 | 2016-09-30T16:53:03Z | [
"python",
"fibonacci"
] |
How can I call prompt_toolkit from the tornado event loop? | 39,796,344 | <p>I am trying to use prompt_toolkit from an application that uses the tornado event loop, but I can not work out the correct way to add the prompt_toolkit prompt to the event loop.</p>
<p>The prompt_toolkit documentation has an example of using it in asyncio (<a href="http://python-prompt-toolkit.readthedocs.io/en/st... | 0 | 2016-09-30T16:46:32Z | 39,805,136 | <p>To use <a href="http://www.tornadoweb.org/en/stable/asyncio.html" rel="nofollow">Tornado's asyncio integration</a>, you must tell Tornado to use the asyncio event loop. Usually, that means doing this at the start of your app:</p>
<pre><code>from tornado.platform.asyncio import AsyncIOMainLoop
AsyncIOMainLoop().inst... | 0 | 2016-10-01T09:44:38Z | [
"python",
"tornado",
"prompt",
"toolkit"
] |
My Django application is not displaying content from the db | 39,796,387 | <pre><code>{% extends 'photos/base.html' %}
{% block galleries_active %}active{% endblock %}
{% block body%}
<div class="gallery-container" container-fluid>
<!--- Galleries--->
<div class="row">
<div class="col-sm-12">
<h3>Text's Gallery</h3>
<... | 0 | 2016-09-30T16:49:25Z | 39,796,496 | <p>You have <code>context_object_name = 'all_galleries'</code> in </p>
<pre><code>class IndexView(generic.ListView):
template_name = 'photos/index.html'
context_object_name = 'all_galleries'
...
</code></pre>
<p>However you loop over <code>galleries</code> in template</p>
<pre><code>{% for gallery in gal... | 1 | 2016-09-30T16:59:09Z | [
"python",
"django"
] |
Error handling np.arccos() and classifying triangles in Python | 39,796,422 | <p>The code below is my attempt at a codewars challenge asking you to <a href="https://www.codewars.com/kata/53907ac3cd51b69f790006c5/train/python" rel="nofollow">calculate the interior angles of a triangle</a>. Really inelegant, brute force. I'm passing all test cases, but also receiving an error: </p>
<pre><code>-c... | 0 | 2016-09-30T16:53:12Z | 39,797,430 | <p>You need to check the values you pass to <code>numpy.arccos</code>. They must be between -1 and 1. But due to floating point calculations they could end up larger than 1 or smaller than -1.</p>
| 0 | 2016-09-30T17:59:58Z | [
"python",
"numpy",
"math",
"triangulation"
] |
Running python in powershell crashes | 39,796,424 | <p>I am learning python from the book <em>Learn Python the Hardway</em>. I tried running python in powershell and python crashes.</p>
<pre class="lang-none prettyprint-override"><code>PS C:\python27>Fatal Python error:
Py_Initialize: can't initialize sys standard streams
File ".\lib\encodings\__init__.p... | 0 | 2016-09-30T16:53:16Z | 39,796,569 | <p>I'm assuming here that you have tried using cmd.exe (the command prompt) (which you can run by pressing the windows key + R and then typing cmd). It might be a bug. When I looked at the Python <a href="https://bugs.python.org/issue10920" rel="nofollow">issue trackers</a>, it seems that something like this has happen... | 0 | 2016-09-30T17:04:21Z | [
"python",
"python-2.7",
"powershell"
] |
Python Pycharm loop error | 39,796,455 | <p>I started at university and programming in python 3.5 is one of our important courses. We use an online website to code and compile the programs but I like to save them on my computer as well but there is a slight error...</p>
<pre><code>tolerantie = float(input("Tolerantie = "))
i = 0
fact = 1
nterm = float(1)
s ... | 0 | 2016-09-30T16:55:07Z | 39,796,828 | <p>In your case <code>PyCharm</code> uses <code>python2.x</code> to compile the script.<br>
You can <a href="http://stackoverflow.com/questions/1267869/how-can-i-force-division-to-be-floating-point-in-python">force division to be floating point in <code>Pythno2.x</code></a> or change pycharm configuration and choose <... | 0 | 2016-09-30T17:21:12Z | [
"python",
"while-loop",
"pycharm"
] |
How to break the string into pieces and assign the values to the substrings preceding the number in the originial string | 39,796,484 | <p>I want to break the string into pieces (delimiters are space and <code>/</code>) and assign values to the sub-strings every time a float or int follows the string:</p>
<p>For example, the string could be:</p>
<p>'ABC 12/5 a1 b-2.5 c34.5d54'</p>
<p>Using this, I want the output as:</p>
<p><code>somelist=['ABC', '... | 0 | 2016-09-30T16:57:49Z | 39,797,368 | <p>I propose this script:</p>
<pre><code>import re
s = 'ABC 12/5 a1 b-2.5 c34.5d54'
parts = re.findall('([a-z]+)(-?\d+(?:\.\d+)?)|([^ /]+)', s)
somelist = [rest for (key, value, rest) in parts if key == '']
vars = dict((key, float(value)) for (key, value, rest) in parts if key != '')
print(somelist)
print(vars)
</co... | 1 | 2016-09-30T17:56:06Z | [
"python",
"regex"
] |
How would I count the number of days based on months with zero data? | 39,796,519 | <p>I'm writing a script in which I read in a csv with several columns and rows. I need the script to total the values in each column for a single row and return which columns have a value of zero for the row. Here's an example of what the data looks like, there are several other columns but these are the columns of int... | 3 | 2016-09-30T17:00:50Z | 39,796,814 | <p>well, I would get rid of the "fout" line. You don't seem to write to that file, and it doesn't need to be open to use the "read_csv" feature of pandas. then you can go through each row and find what's zero, and what isn't</p>
<pre><code>returnArray = []
i=0
while i < len(df.values):
j=14 #since user only c... | 0 | 2016-09-30T17:20:12Z | [
"python",
"pandas"
] |
How would I count the number of days based on months with zero data? | 39,796,519 | <p>I'm writing a script in which I read in a csv with several columns and rows. I need the script to total the values in each column for a single row and return which columns have a value of zero for the row. Here's an example of what the data looks like, there are several other columns but these are the columns of int... | 3 | 2016-09-30T17:00:50Z | 39,796,873 | <p>Consider the <code>pd.DataFrame</code> <code>df</code></p>
<pre><code>cols = ['JAN', 'FEB', 'MAR', 'APR',
'MAY', 'JUN', 'JUL', 'AUG',
'SEP', 'OCT', 'NOV', 'DEC']
df = pd.DataFrame(np.random.randint(0, 3, (10, 12)), columns=cols)
df
</code></pre>
<p><a href="http://i.stack.imgur.com/1iTj9.png" rel=... | 1 | 2016-09-30T17:23:36Z | [
"python",
"pandas"
] |
Python how to sum a list | 39,796,664 | <p>I'm having trouble because I'm asking the user to input 6 numbers into a list and then total and average it depending on input from user. It's my HWK. Please help.</p>
<pre><code>x = 0
list = []
while x < 6:
user = int(input("Enter a number"))
list.append(user)
x = x + 1
numb = input("Do you want a t... | -2 | 2016-09-30T17:10:34Z | 39,800,096 | <p>Here is my answer:</p>
<pre><code>def numberTest():
global x, y, z
L1 = []
x = 0
y = 6
z = 1
while(x < 6):
try:
user = int(input("Enter {0} more number(s)".format(y)))
print("Your entered the number {0}".format(user))
x += 1
y -= 1
... | 0 | 2016-09-30T21:05:42Z | [
"python",
"list",
"sum",
"average"
] |
Why doesn't this python keyboard interrupt work? (in pycharm) | 39,796,689 | <p>My python try/except loop does not seem to trigger a keyboard interrupt when Ctrl + C is pressed while debugging my code in pycharm. My code look like this:</p>
<pre><code>numbers = []
loop = True
try:
# ===========SUBROUTINES==================
def help():
print("To view the list type 'view'"
... | 2 | 2016-09-30T17:12:11Z | 39,796,898 | <p>If that comment doesn't solve your problem, (from @tdelaney) you need to have your shell window focused (meaning you've clicked on it when the program is running.) and then you can use <kbd>Control</kbd>+<kbd>C</kbd></p>
| 1 | 2016-09-30T17:25:04Z | [
"python",
"pycharm",
"try-except",
"keyboardinterrupt"
] |
Why doesn't this python keyboard interrupt work? (in pycharm) | 39,796,689 | <p>My python try/except loop does not seem to trigger a keyboard interrupt when Ctrl + C is pressed while debugging my code in pycharm. My code look like this:</p>
<pre><code>numbers = []
loop = True
try:
# ===========SUBROUTINES==================
def help():
print("To view the list type 'view'"
... | 2 | 2016-09-30T17:12:11Z | 39,796,979 | <p>Make sure the window is selected when you press ctrl+c. I just ran your program in IDLE and it worked perfectly for me.</p>
| 1 | 2016-09-30T17:31:16Z | [
"python",
"pycharm",
"try-except",
"keyboardinterrupt"
] |
Why doesn't this python keyboard interrupt work? (in pycharm) | 39,796,689 | <p>My python try/except loop does not seem to trigger a keyboard interrupt when Ctrl + C is pressed while debugging my code in pycharm. My code look like this:</p>
<pre><code>numbers = []
loop = True
try:
# ===========SUBROUTINES==================
def help():
print("To view the list type 'view'"
... | 2 | 2016-09-30T17:12:11Z | 39,797,021 | <p>Here is working normally, since i put a variable "x" in your code and i use <em>tabs</em> instead <em>spaces</em>.</p>
<pre><code>try:
def help():
print("Help.")
def doStuff():
print("Doing Stuff")
while True:
x = int(input())
if x == 1:
help()
elif... | 1 | 2016-09-30T17:33:27Z | [
"python",
"pycharm",
"try-except",
"keyboardinterrupt"
] |
Why doesn't this python keyboard interrupt work? (in pycharm) | 39,796,689 | <p>My python try/except loop does not seem to trigger a keyboard interrupt when Ctrl + C is pressed while debugging my code in pycharm. My code look like this:</p>
<pre><code>numbers = []
loop = True
try:
# ===========SUBROUTINES==================
def help():
print("To view the list type 'view'"
... | 2 | 2016-09-30T17:12:11Z | 39,797,131 | <p>From your screen shot it appears that you are running this code in an IDE. The thing about IDEs is that they are not quite the same as running normally, especially when it comes to handling of keyboard characters. The way you press ctrl-c, your IDE thinks you want to copy text. The python program never sees the char... | 2 | 2016-09-30T17:40:37Z | [
"python",
"pycharm",
"try-except",
"keyboardinterrupt"
] |
Append 1D numpy array to file with new element in new line | 39,796,811 | <p>I have a number of numpy arrays which I generate iteratively. I want to save each array to a file. I then generate the next array and append it to the file and so forth (if I did it in one go I would use too much memory). How do I best do that? Is there a way of making us of numpy functions such as e.g. <code>numpy.... | 0 | 2016-09-30T17:20:07Z | 39,797,820 | <p>I would recommend using HDF5. They are very fast for IO.
Here is how you write your data:</p>
<pre><code>import numpy as np
import tables
fname = 'myOutput.h5'
length = 100 # your data length
my_data_generator = xrange(length) # Your data comes here instead of the xrange
filters = tables.Filters(complib='blosc'... | 0 | 2016-09-30T18:25:40Z | [
"python",
"arrays",
"numpy",
"file-io"
] |
Append 1D numpy array to file with new element in new line | 39,796,811 | <p>I have a number of numpy arrays which I generate iteratively. I want to save each array to a file. I then generate the next array and append it to the file and so forth (if I did it in one go I would use too much memory). How do I best do that? Is there a way of making us of numpy functions such as e.g. <code>numpy.... | 0 | 2016-09-30T17:20:07Z | 39,799,398 | <p>You could pass the open file (handle) to <code>savetxt</code></p>
<pre><code>with open('paths.dat','w') as output:
for i in range(len(hist[0])):
amount = hist[0][i].astype(int)
myArray = hist[1][i] * np.ones(amount)
np.savetxt(output, myArray, delimiter=',', fmt='%10f')
</code></pre>
<p... | 1 | 2016-09-30T20:12:14Z | [
"python",
"arrays",
"numpy",
"file-io"
] |
Using .apply() in Sframes to manipulate multiple columns of each row | 39,796,839 | <p>I have an SFrame with the columns Date1 and Date2.</p>
<p>I am trying to use <code>.apply()</code> to find the datediff between Date1 and Date2, but I can't figure out how to use the other argument.</p>
<p>Ideally something like </p>
<pre><code>frame['new_col'] = frame['Date1'].apply(lambda x: datediff(x,frame('... | 0 | 2016-09-30T17:21:49Z | 39,822,429 | <p>You can directly take the difference between the dates in column <code>Date2</code> and those in <code>Date1</code> by just subtracting <code>frame['Date1']</code> from <code>frame['Date2']</code>. That, for some reason, returns the number of seconds between the two dates (only tested with python's <code>datetime</c... | 0 | 2016-10-02T22:34:51Z | [
"python",
"sframe"
] |
Regular Expression Matching First Non-Repeated Character | 39,796,852 | <p><strong>TL;DR</strong></p>
<p><code>re.search("(.)(?!.*\1)", text).group()</code> doesn't match the first non-repeating character contained in text (it always returns a character at or before the first non-repeated character, or before the end of the string if there are no non-repeated characters. My understanding ... | 27 | 2016-09-30T17:22:24Z | 39,796,953 | <p>Well let's take your <code>tooth</code> example - here is what the regex-engine does (a lot simplified for better understanding)</p>
<p>Start with <code>t</code> then look ahead in the string - and fail the lookahead, as there is another <code>t</code>.</p>
<pre><code>tooth
^ °
</code></pre>
<p>Next take <code>... | 14 | 2016-09-30T17:29:38Z | [
"python",
"regex",
"regex-lookarounds"
] |
Regular Expression Matching First Non-Repeated Character | 39,796,852 | <p><strong>TL;DR</strong></p>
<p><code>re.search("(.)(?!.*\1)", text).group()</code> doesn't match the first non-repeating character contained in text (it always returns a character at or before the first non-repeated character, or before the end of the string if there are no non-repeated characters. My understanding ... | 27 | 2016-09-30T17:22:24Z | 39,796,971 | <p>The reason why your regex is not working is that it will not match a character that is <em>followed</em> by the same character, but there is nothing to prevent it from matching a character that isn't <em>followed</em> by the same character, <em>even if</em> it is preceded by the same character.</p>
| 3 | 2016-09-30T17:30:49Z | [
"python",
"regex",
"regex-lookarounds"
] |
Regular Expression Matching First Non-Repeated Character | 39,796,852 | <p><strong>TL;DR</strong></p>
<p><code>re.search("(.)(?!.*\1)", text).group()</code> doesn't match the first non-repeating character contained in text (it always returns a character at or before the first non-repeated character, or before the end of the string if there are no non-repeated characters. My understanding ... | 27 | 2016-09-30T17:22:24Z | 39,818,123 | <p>Regular expressions are not optimal for the task even if you use alternative implementations of re that do not limit lookbehind by fixed length strings (such as Matthew Barnett's regex).</p>
<p>The easiest way is to count occurrences of letters and print the first one with frequency equal to 1:</p>
<pre><code>impo... | 5 | 2016-10-02T14:42:39Z | [
"python",
"regex",
"regex-lookarounds"
] |
Regular Expression Matching First Non-Repeated Character | 39,796,852 | <p><strong>TL;DR</strong></p>
<p><code>re.search("(.)(?!.*\1)", text).group()</code> doesn't match the first non-repeating character contained in text (it always returns a character at or before the first non-repeated character, or before the end of the string if there are no non-repeated characters. My understanding ... | 27 | 2016-09-30T17:22:24Z | 39,890,983 |
<p><a href="http://stackoverflow.com/a/39796953/3764814">Sebastian's answer</a> already explains pretty well why your current attempt doesn't work.</p>
<h3>.NET</h3>
<p>Since <s>you're</s> <a href="http://stackoverflow.com/users/1020526/revo">revo</a> is interested in a .NET flavor workaround, the solution becomes ... | 11 | 2016-10-06T08:19:28Z | [
"python",
"regex",
"regex-lookarounds"
] |
Installing MoviePy for Python 3.2 with pip | 39,796,864 | <p>I am trying to install the Python module MoviePy onto my Raspberry Pi for use with Python 3.2.3 which came ready installed with the OS. I have tried every command line command that I can find and lots of possible permutations of certain words.</p>
<p>Following are the download instructions.
<a href="https://zulko.... | 0 | 2016-09-30T17:23:00Z | 39,797,542 | <p>Do</p>
<pre><code>sudo pip install ez_setup
sudo pip install moviepy
</code></pre>
<p>If it says like pip not found type </p>
<pre><code>sudo apt-get install python
</code></pre>
<p>Python 3 is a little harder to setup so doing that command will give you 2.7
But there syntax is basicly the same.</p>
| 0 | 2016-09-30T18:08:02Z | [
"python",
"python-3.x",
"pip",
"moviepy"
] |
Dynamic call to an Instance Variable | 39,796,880 | <p>I have a dynamic string based on the current file's extension called "extension"</p>
<pre><code>fileextension = os.path.splitext(file.filename)[1]
extension = fileextension.replace(".","")
</code></pre>
<p>Lets say extension = "pdf"</p>
<p>How would I be able to call the Ext.pdf() instance variable below?</p>
<p... | 2 | 2016-09-30T17:24:13Z | 39,796,947 | <p>You called the instance attribute correctly. To fix your issue do not assign the result to the <code>filetype</code> attribute:</p>
<pre><code>ext = Ext()
getattr(ext, extension)()
print(ext.filetype)
</code></pre>
<p>It did not work because you return <code>None</code> within <code>pdf()</code> and <code>txt()</c... | 4 | 2016-09-30T17:29:11Z | [
"python"
] |
How do you change a variable in a function to then be used in the main code? | 39,797,042 | <p>I am quite new to Python and I am having some trouble figuring out the following:</p>
<pre><code>import random
import sys
print("Welcome to this Maths quiz.")
playerName = str(input("Please enter your name: "))
playerAge = int(input("Please enter your age: "))
if playerAge < 11:
print("This quiz is not for ... | 0 | 2016-09-30T17:34:52Z | 39,797,103 | <p>You have to declare it as a global variable inside the function so that it can modify the variable in the global scope</p>
<pre><code>def displayQuestion(quizQuestions, quizAnswers, questionNumber):
global quizScore
...
quizScore += 1
</code></pre>
<p>That being said, you should generally avoid glo... | 3 | 2016-09-30T17:38:31Z | [
"python",
"function",
"variables"
] |
How do you change a variable in a function to then be used in the main code? | 39,797,042 | <p>I am quite new to Python and I am having some trouble figuring out the following:</p>
<pre><code>import random
import sys
print("Welcome to this Maths quiz.")
playerName = str(input("Please enter your name: "))
playerAge = int(input("Please enter your age: "))
if playerAge < 11:
print("This quiz is not for ... | 0 | 2016-09-30T17:34:52Z | 39,797,897 | <p>Although this won't be the shortest answer, which is to use another global variable. It instead will show you how to avoid using global variables (<a href="http://c2.com/cgi/wiki?GlobalVariablesConsideredHarmful" rel="nofollow">which are considered harmful</a>) by using <a href="https://en.wikipedia.org/wiki/Object-... | 0 | 2016-09-30T18:29:56Z | [
"python",
"function",
"variables"
] |
How to make Q lookups in django look for multiple values | 39,797,090 | <p>Currently I have a very simple search option which goes through my pages and looks up through several fields for requested query. If I input a single word in it it works just fine, however if I input multiple words in search query, I get nothing, even if a single page contains all attributes. For example if I search... | 0 | 2016-09-30T17:37:57Z | 39,797,874 | <p>You're asking for something like the following, where you filter by each individual word in the query:</p>
<pre><code>import operator
queryset = Page.objects.all().filter(archived=False).order_by("title")
query = request.GET.get("q")
if query:
words = query.split()
fields = ["title__icontains", "content__... | 1 | 2016-09-30T18:28:48Z | [
"python",
"django",
"search",
"django-q"
] |
Need uppate SQL in SQL within table | 39,797,096 | <p>I have 2 columns in my table <code>Office</code> (<code>Cust_id</code>, <code>customer</code>)</p>
<p>The data is like below, I want to update the <code>cust_id</code> for the customer who have nulls, because I got in late the <code>cust_id</code> in the table ,</p>
<p>EX: I need an update script to search the cus... | 0 | 2016-09-30T17:38:04Z | 39,797,233 | <p>Use <code>UPDATE</code> with a self-JOIN:</p>
<pre><code>UPDATE Office AS o1
JOIN Office AS o2 ON o1.Customer = o2.Customer
SET o1.cust_id = o2.cust_id
WHERE o1.cust_id IS NULL
AND o2.cust_id IS NOT NULL
</code></pre>
| 0 | 2016-09-30T17:47:14Z | [
"python"
] |
Turn pandas series to series of lists or numpy array to array of lists | 39,797,206 | <p>I have a series <code>s</code></p>
<pre><code>s = pd.Series([1, 2])
</code></pre>
<p>What is an efficient way to make <code>s</code> look like</p>
<pre><code>0 [1]
1 [2]
dtype: object
</code></pre>
| 1 | 2016-09-30T17:45:54Z | 39,797,310 | <p>This does it: </p>
<pre><code>import numpy as np
np.array([[a] for a in s],dtype=object)
array([[1],
[2]], dtype=object)
</code></pre>
| 1 | 2016-09-30T17:51:52Z | [
"python",
"pandas",
"numpy"
] |
Turn pandas series to series of lists or numpy array to array of lists | 39,797,206 | <p>I have a series <code>s</code></p>
<pre><code>s = pd.Series([1, 2])
</code></pre>
<p>What is an efficient way to make <code>s</code> look like</p>
<pre><code>0 [1]
1 [2]
dtype: object
</code></pre>
| 1 | 2016-09-30T17:45:54Z | 39,797,632 | <p>If you want the result to still be a pandas <code>Series</code> you can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="nofollow"><code>apply</code></a> method :</p>
<pre><code>In [1]: import pandas as pd
In [2]: s = pd.Series([1, 2])
In [3]: s.apply(lambda x:... | 2 | 2016-09-30T18:14:29Z | [
"python",
"pandas",
"numpy"
] |
Turn pandas series to series of lists or numpy array to array of lists | 39,797,206 | <p>I have a series <code>s</code></p>
<pre><code>s = pd.Series([1, 2])
</code></pre>
<p>What is an efficient way to make <code>s</code> look like</p>
<pre><code>0 [1]
1 [2]
dtype: object
</code></pre>
| 1 | 2016-09-30T17:45:54Z | 39,797,640 | <p>Adjusting atomh33ls' answer, here's a series of lists:</p>
<pre><code>output = pd.Series([[a] for a in s])
type(output)
>> pandas.core.series.Series
type(output[0])
>> list
</code></pre>
<p>Timings for a selection of the suggestions:</p>
<pre><code>import numpy as np, pandas as pd
s = pd.Series(np.ran... | 1 | 2016-09-30T18:15:10Z | [
"python",
"pandas",
"numpy"
] |
Turn pandas series to series of lists or numpy array to array of lists | 39,797,206 | <p>I have a series <code>s</code></p>
<pre><code>s = pd.Series([1, 2])
</code></pre>
<p>What is an efficient way to make <code>s</code> look like</p>
<pre><code>0 [1]
1 [2]
dtype: object
</code></pre>
| 1 | 2016-09-30T17:45:54Z | 39,798,234 | <p>Here's one approach that extracts into array and extends to <code>2D</code> by introducing a new axis with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/arrays.indexing.html#numpy.newaxis" rel="nofollow"><code>None/np.newaxis</code></a> -</p>
<pre><code>pd.Series(s.values[:,None].tolist())
</code></pre>... | 4 | 2016-09-30T18:50:48Z | [
"python",
"pandas",
"numpy"
] |
Playing music on loop until a key is released. Python | 39,797,210 | <p>I'm making a little GUI with python, using cocos2d and pyglet modules. The GUI should play a sound while the "h" is pressed and stop when it is released. The problem here is that I can't find a solution to this. After searching this site I've found this question - <a href="http://stackoverflow.com/questions/27391240... | 0 | 2016-09-30T17:46:03Z | 39,807,492 | <p>Nevermind, I have figured this out, all I had to do was move the line <code>player.queue(loop)</code> from the initialization function to the function that handles keypresses. The updated code looks like this: </p>
<pre><code>class Heartbeat (cocos.layer.Layer):
is_event_handler=True
def __init__ (self):
... | 0 | 2016-10-01T13:58:05Z | [
"python",
"python-3.x",
"audio",
"pyglet",
"keyrelease"
] |
Resolving shift/reduce conflict for default label in switch block | 39,797,216 | <p>I'm writing a parser for Unrealscript using PLY, and I've run into (hopefully) one of the last ambiguities in the parsing rules that I've set up.</p>
<p>Unrealscript has a keyword, <code>default</code>, which is used differently depending on the context. In a regular statement line, you could use <code>default</cod... | 2 | 2016-09-30T17:46:17Z | 39,811,928 | <p>What you have here is a simple shift/reduce conflict (with the token <code>default</code> as lookahead) being resolved as a shift.</p>
<p>Let's reduce this all to a much smaller, if not minimal example. Here's the grammar, partly based on the one in the Github repository pointed to in the OP (but intended to be sel... | 1 | 2016-10-01T22:10:35Z | [
"python",
"ply",
"lalr",
"unrealscript"
] |
choosing correct form according to form input's name | 39,797,218 | <p>I want to submit forms in multiple websites. Usually I can't exactly know the form name or form id, but I know the input name that I want to submit.</p>
<p>Let's say there is a website which has couple of forms inside it. My code should check all of the forms, if one of them has a input value named "birthday" it wi... | -2 | 2016-09-30T17:46:31Z | 39,797,265 | <p>You can basically loop over all forms and skip forms that don't contain the desired input:</p>
<pre><code>for form in br.forms():
if not form.find_control(name="birthday"):
continue
# fill form and submit here
</code></pre>
<p>More about <code>find_control()</code> <a href="http://wwwsearch.source... | 1 | 2016-09-30T17:49:42Z | [
"python",
"mechanize"
] |
choosing correct form according to form input's name | 39,797,218 | <p>I want to submit forms in multiple websites. Usually I can't exactly know the form name or form id, but I know the input name that I want to submit.</p>
<p>Let's say there is a website which has couple of forms inside it. My code should check all of the forms, if one of them has a input value named "birthday" it wi... | -2 | 2016-09-30T17:46:31Z | 39,817,061 | <p>You are gonna need to use an <a href="http://stackoverflow.com/a/9884259/6209196">iterator</a> to check all the forms in the website. In this case we will be using <code>for</code>. But this doesn't let us know about which form we are working on, it just lets us use it. So we are going to assign 0(the first form's I... | 0 | 2016-10-02T12:36:13Z | [
"python",
"mechanize"
] |
Process substitution not allowed by Python's subprocess with shell=True? | 39,797,234 | <p>Here is a toy example of process substitution that works fine in Bash:</p>
<pre><code>$ wc -l <(pwd)
1 /proc/self/fd/11
</code></pre>
<p>So why does the same command give a syntax error when invoked from Python's subprocess with shell=True? </p>
<pre><code>>>> subprocess.check_call('wc -l <(pwd)',... | 0 | 2016-09-30T17:47:17Z | 39,797,316 | <blockquote>
<p>/bin/sh: 1: Syntax error: "(" unexpected</p>
</blockquote>
<p>You have a <a href="https://en.wiktionary.org/wiki/bashism" rel="nofollow">bashism</a>. It is not valid according to POSIX, which is what <code>/bin/sh</code> implements.</p>
| 2 | 2016-09-30T17:52:15Z | [
"python",
"bash",
"shell",
"subprocess",
"process-substitution"
] |
Process substitution not allowed by Python's subprocess with shell=True? | 39,797,234 | <p>Here is a toy example of process substitution that works fine in Bash:</p>
<pre><code>$ wc -l <(pwd)
1 /proc/self/fd/11
</code></pre>
<p>So why does the same command give a syntax error when invoked from Python's subprocess with shell=True? </p>
<pre><code>>>> subprocess.check_call('wc -l <(pwd)',... | 0 | 2016-09-30T17:47:17Z | 39,797,861 | <p>An alternate solution is to shift more of the shell code to Python itself. For example:</p>
<pre><code>from subprocess import Popen, PIPE, check_call
p1 = Popen(["pwd"], stdout=PIPE)
p2 = check_call(["wc", "-l"], stdin=p1.stdout)
</code></pre>
<p>This could often be the first step towards eliminating the need to ... | 1 | 2016-09-30T18:27:58Z | [
"python",
"bash",
"shell",
"subprocess",
"process-substitution"
] |
How do I determine what ip range a device is using? | 39,797,245 | <p>This is kind of a weird problem, basically I have a computer connected to a machine via ethernet cable. There is no other network or internet access. The machine sets up a network which allows you to telnet into it. </p>
<p>I need the simplest way possible to determine the ip range the device is using. This would b... | 0 | 2016-09-30T17:48:08Z | 39,797,482 | <p>Try this </p>
<pre><code>import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
get_ip_address('... | 0 | 2016-09-30T18:03:32Z | [
"python",
"networking"
] |
How do I determine what ip range a device is using? | 39,797,245 | <p>This is kind of a weird problem, basically I have a computer connected to a machine via ethernet cable. There is no other network or internet access. The machine sets up a network which allows you to telnet into it. </p>
<p>I need the simplest way possible to determine the ip range the device is using. This would b... | 0 | 2016-09-30T17:48:08Z | 39,798,412 | <p>The IPv4 Link-Local range of <code>169.254.0.0/16</code> is used by APIPA for hosts to assign IP addresses when an interface has no other way to obtain an address. There are some rules about this range, e.g. you cannot subnet the range, it can't be routed, etc. See <a href="https://tools.ietf.org/html/rfc3927" rel="... | 0 | 2016-09-30T19:01:22Z | [
"python",
"networking"
] |
How can I properly parse a string into grapheme clusters using python 2.7? | 39,797,261 | <p>I'm trying to find a way using python 2.7.1 to parse a string into grapheme clusters. For example, the string:</p>
<pre><code>details = u"Hello í ¼í·¦í ¼í·¹í ¼í·»í ¼í·ª"
</code></pre>
<p>I believe should be parsed as:</p>
<pre><code>[u"H", u"e", u"l", u"l", u"o", u"\U0001f1e6\U0001f1f9", u"\U0001f1fb\U0001f1ea"]... | 2 | 2016-09-30T17:49:26Z | 39,797,574 | <p>This behavior used to be correct, but the rules changed.</p>
<p>As of uniseg version 0.7.1 (current as of this post), the uniseg documentation refers to an outdated version of the Unicode grapheme cluster boundary rules, given in <a href="http://www.unicode.org/reports/tr29/tr29-21.html" rel="nofollow">Unicode Stan... | 2 | 2016-09-30T18:10:03Z | [
"python",
"python-2.7",
"python-3.x",
"unicode"
] |
python, multthreading, safe to use pandas "to_csv" on common file? | 39,797,340 | <p>I've got some code that works pretty nicely. It's a while-loop that goes through a list of dates, finds files on my HDD that corresponds to those dates, does some calculations with those files, and then outputs to a "results.csv" file using the command:</p>
<pre><code>my_df.to_csv("results.csv",mode = 'a')
</code>... | 0 | 2016-09-30T17:53:45Z | 39,797,512 | <p>Writing the file in multiple threads is not safe. But you can create a <a href="https://docs.python.org/3.6/library/threading.html#threading.Lock" rel="nofollow">lock</a> to protect that one operation while letting the rest run in parallel. Your <code>to_csv</code> isn't shown, but you could create the lock</p>
<pr... | 1 | 2016-09-30T18:05:58Z | [
"python",
"multithreading",
"pandas"
] |
Python's string count function doesn't use regex | 39,797,369 | <p>when trying to count all letters in a string using the count function and the regex [A-Za-z], it returns a a value of zero.</p>
<p>For instance:</p>
<pre><code>string="Hi, everybody. Let's dance!"
string.count('[A-Za-z]') ## prints 0
</code></pre>
<p>any suggestions?</p>
| -3 | 2016-09-30T17:56:15Z | 39,797,394 | <p>Use regular expressions:</p>
<pre><code>len(re.findall('[A-Za-z]', string))
</code></pre>
| 3 | 2016-09-30T17:57:57Z | [
"python",
"regex",
"python-2.7",
"function"
] |
Python's string count function doesn't use regex | 39,797,369 | <p>when trying to count all letters in a string using the count function and the regex [A-Za-z], it returns a a value of zero.</p>
<p>For instance:</p>
<pre><code>string="Hi, everybody. Let's dance!"
string.count('[A-Za-z]') ## prints 0
</code></pre>
<p>any suggestions?</p>
| -3 | 2016-09-30T17:56:15Z | 39,797,472 | <p>Because that's not how count works,look at this link <a href="https://www.tutorialspoint.com/python/string_count.htm" rel="nofollow">count</a></p>
<p>In that statement you are telling how much substrings of '[A-Za-z]' are in string
if you want to count all the letters in a string use len()</p>
| -1 | 2016-09-30T18:02:58Z | [
"python",
"regex",
"python-2.7",
"function"
] |
Python's string count function doesn't use regex | 39,797,369 | <p>when trying to count all letters in a string using the count function and the regex [A-Za-z], it returns a a value of zero.</p>
<p>For instance:</p>
<pre><code>string="Hi, everybody. Let's dance!"
string.count('[A-Za-z]') ## prints 0
</code></pre>
<p>any suggestions?</p>
| -3 | 2016-09-30T17:56:15Z | 39,798,039 | <p>As indicated in brianpcks comment, there are alternatives that do not require using regular expressions:</p>
<pre><code>len(c for c in string if c.isalpha())
</code></pre>
<p>or</p>
<pre><code>from string import ascii_lowercase
len(c for c in string if c in string.ascii_lowercase)
</code></pre>
<p>Although these... | 0 | 2016-09-30T18:38:18Z | [
"python",
"regex",
"python-2.7",
"function"
] |
Code wars : Title Case with python | 39,797,434 | <pre><code>def title_case(title, minor_words = 0):
title = title.lower().split(" ")
title_change = []
temp = []
if minor_words != 0 :
minor_words = minor_words.lower().split(" ")
for i in range(len(title)):
if (i != 0 and title[i] not in minor_words) or (i == 0 and title[i] i... | 2 | 2016-09-30T18:00:17Z | 39,797,608 | <p>Your code will break if <code>title</code> has leading or trailing spaces, or two consecutive spaces, such as <code>"foo bar"</code>. It will also break on an empty string. That's because <code>title.lower().split(" ")</code> on any of those kinds of titles will give you an empty string as one of your "words", and ... | 2 | 2016-09-30T18:13:05Z | [
"python",
"indexing"
] |
Code wars : Title Case with python | 39,797,434 | <pre><code>def title_case(title, minor_words = 0):
title = title.lower().split(" ")
title_change = []
temp = []
if minor_words != 0 :
minor_words = minor_words.lower().split(" ")
for i in range(len(title)):
if (i != 0 and title[i] not in minor_words) or (i == 0 and title[i] i... | 2 | 2016-09-30T18:00:17Z | 39,797,727 | <p>Just as a supplement to @Blckknght's explanation, here is an illuminating console session that steps through what's happening to your variable.</p>
<pre><code>>>> title = ''
>>> title = title.lower().split(' ')
>>> title
['']
>>> temp = list(title[0])
>>> temp
[]
>>... | 0 | 2016-09-30T18:20:41Z | [
"python",
"indexing"
] |
a valid element not in np.arange, though print() does show it, dtypes are also same | 39,797,454 | <pre><code>a = 1.25
if a in np.arange(1,2,0.05):
print(a)
</code></pre>
<p>but this if condition doesn't holds true,though</p>
<pre><code>print(np.arange(1,2,0.05))
[ 1. 1.05 1.1 1.15 1.2 1.25 1.3 1.35 1.4 1.45 1.5 1.55 1.6 1.65 1.7 1.75 1.8 1.85 1.9 1.95]
</code></pre>
<p>does have... | 2 | 2016-09-30T18:01:51Z | 39,797,661 | <p>That's because there is no <code>1.25</code> in that range it's actually <code>1.2500000000000002</code> and that's because numpy considers a double precision float for float numbers by default and in cases that decimal fractions cannot be represented exactly as binary fractions, they can hold the more accurate valu... | 1 | 2016-09-30T18:16:38Z | [
"python",
"numpy"
] |
a valid element not in np.arange, though print() does show it, dtypes are also same | 39,797,454 | <pre><code>a = 1.25
if a in np.arange(1,2,0.05):
print(a)
</code></pre>
<p>but this if condition doesn't holds true,though</p>
<pre><code>print(np.arange(1,2,0.05))
[ 1. 1.05 1.1 1.15 1.2 1.25 1.3 1.35 1.4 1.45 1.5 1.55 1.6 1.65 1.7 1.75 1.8 1.85 1.9 1.95]
</code></pre>
<p>does have... | 2 | 2016-09-30T18:01:51Z | 39,798,698 | <p>Using <code>item</code> to print values in full splendor:</p>
<pre><code>In [83]: for i in np.arange(1,2,0.05):print(i.item())
1.0
1.05
1.1
1.1500000000000001
1.2000000000000002
1.2500000000000002
1.3000000000000003
1.3500000000000003
1.4000000000000004
1.4500000000000004
1.5000000000000004
1.5500000000000005
1.600... | 0 | 2016-09-30T19:22:52Z | [
"python",
"numpy"
] |
Glassdoor API Not Printing Custom Response | 39,797,495 | <p>I have the following problem when I try to print something from this api. I'm trying to set it up so I can access different headers, then print specific items from it. But instead when I try to print soup it gives me the entire api response in json format. </p>
<pre><code>import requests, json, urlparse, urllib2
fr... | 0 | 2016-09-30T18:04:37Z | 39,799,536 | <p>You can load the JSON response into a dict then look for the values you want like you would in any other dict.</p>
<p>I took your data and saved it in an external JSON file to do a test since I don't have access to the API. This worked for me.</p>
<pre><code>import json
# Load JSON from external file
with open (r... | 0 | 2016-09-30T20:23:15Z | [
"python",
"json",
"api"
] |
Glassdoor API Not Printing Custom Response | 39,797,495 | <p>I have the following problem when I try to print something from this api. I'm trying to set it up so I can access different headers, then print specific items from it. But instead when I try to print soup it gives me the entire api response in json format. </p>
<pre><code>import requests, json, urlparse, urllib2
fr... | 0 | 2016-09-30T18:04:37Z | 39,800,521 | <pre><code>import json, urlib2
url = "http..."
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(url, headers=hdr)
response = urllib2.urlopen(req)
data = json.loads(response.read())
# Print the values
print 'numberOfRatings:', data['response']['employers'][0]['numberOfRatings']
</code></pre>
| 0 | 2016-09-30T21:47:07Z | [
"python",
"json",
"api"
] |
Basic Anagram VS more advanced one | 39,797,552 | <p>I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; <em>two words are an anagram if you can rearrange the letters from one to spell the other</em>).</p>
<p>The easier solution that comes to mind is:</p>
<pre><code>def is_anagram(a, ... | 2 | 2016-09-30T18:08:47Z | 39,797,628 | <p>Try that:</p>
<pre><code>def is_anagram(a, b):
word = [filter(lambda x: x in a, sub) for sub in b]
return ''.join(word)[0:len(a)]
</code></pre>
<p>Example:</p>
<pre><code>>>> is_anagram('some','somexcv')
'some'
</code></pre>
<p><strong>Note:</strong> This code returns the <code>common word</code... | 0 | 2016-09-30T18:14:18Z | [
"python",
"python-2.7",
"python-3.x"
] |
Basic Anagram VS more advanced one | 39,797,552 | <p>I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; <em>two words are an anagram if you can rearrange the letters from one to spell the other</em>).</p>
<p>The easier solution that comes to mind is:</p>
<pre><code>def is_anagram(a, ... | 2 | 2016-09-30T18:08:47Z | 39,797,740 | <p>If you need to check if <code>a</code> word could be created from <code>b</code> you can do this</p>
<pre><code>def is_anagram(a,b):
b_list = list(b)
for i_a in a:
if i_a in b_list:
b_list.remove(i_a)
else:
return False
return True
</code></pre>
<p><strong>UPDATE... | 1 | 2016-09-30T18:21:29Z | [
"python",
"python-2.7",
"python-3.x"
] |
Basic Anagram VS more advanced one | 39,797,552 | <p>I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; <em>two words are an anagram if you can rearrange the letters from one to spell the other</em>).</p>
<p>The easier solution that comes to mind is:</p>
<pre><code>def is_anagram(a, ... | 2 | 2016-09-30T18:08:47Z | 39,797,746 | <pre><code>def is_anagram(a, b):
test = sorted(a) == sorted(b)
testset = b in a
testset1 = a in b
if testset == True:
return True
if testset1 == True:
return True
else:
return False
</code></pre>
<p>No better than the other solution. But if you like verbose code, here's ... | 0 | 2016-09-30T18:21:45Z | [
"python",
"python-2.7",
"python-3.x"
] |
Basic Anagram VS more advanced one | 39,797,552 | <p>I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; <em>two words are an anagram if you can rearrange the letters from one to spell the other</em>).</p>
<p>The easier solution that comes to mind is:</p>
<pre><code>def is_anagram(a, ... | 2 | 2016-09-30T18:08:47Z | 39,798,160 | <p>Since the other answers do not, at time of writing, support reversing the order:</p>
<p>Contains <a href="https://www.python.org/dev/peps/pep-0484/" rel="nofollow">type hints</a> for convenience, because why not?</p>
<pre><code># Just strip hints out if you're in Python < 3.5.
def is_anagram(a: str, b: str) -&g... | 1 | 2016-09-30T18:45:40Z | [
"python",
"python-2.7",
"python-3.x"
] |
Basic Anagram VS more advanced one | 39,797,552 | <p>I'm currently working my way through a "List" unit and in one of the exercises we need to create an anagram (for those who don't know; <em>two words are an anagram if you can rearrange the letters from one to spell the other</em>).</p>
<p>The easier solution that comes to mind is:</p>
<pre><code>def is_anagram(a, ... | 2 | 2016-09-30T18:08:47Z | 39,798,666 | <p>I think all this sorting is a red herring; the letters should be counted instead.</p>
<pre><code>def is_anagram(a, b):
return all(a.count(c) <= b.count(c) for c in set(a))
</code></pre>
<p>If you want efficiency, you can construct a dictionary that counts all the letters in <code>b</code> and decrements the... | 0 | 2016-09-30T19:20:34Z | [
"python",
"python-2.7",
"python-3.x"
] |
scipy.optimize compact constraints | 39,797,606 | <p>I have a np.array A of length 9 and it is the variable in the objective function. </p>
<pre><code>A = [ a1, a2, a3,
b1, b2, b3,
c1, c2, c3], where a1...c3 are real numbers.
with constraints: a1 > a2, a2 > a3,
b1 > b2, b2 > b3,
c1 > c2, c2 > c3
</c... | 2 | 2016-09-30T18:12:52Z | 39,798,108 | <p>I would imagine scipy likes a numeric output from each of these functions rather than boolean, so that rules out more than two inputs per function... (degrees of freedom and all that isht) what you can do is write a list comprehension to make the functions for you...</p>
<pre><code>cons = ({'type':'ineq', 'fun': la... | 0 | 2016-09-30T18:42:35Z | [
"python",
"optimization",
"scipy"
] |
scipy.optimize compact constraints | 39,797,606 | <p>I have a np.array A of length 9 and it is the variable in the objective function. </p>
<pre><code>A = [ a1, a2, a3,
b1, b2, b3,
c1, c2, c3], where a1...c3 are real numbers.
with constraints: a1 > a2, a2 > a3,
b1 > b2, b2 > b3,
c1 > c2, c2 > c3
</c... | 2 | 2016-09-30T18:12:52Z | 39,798,604 | <p>Apparently, your constraint is that each column of <code>A</code> should be (element-wise) greater than or equal to the column to its right. </p>
<p>You can formulate a single, vector-outpur constraint as follows:</p>
<pre><code>def cons_fun(x):
A = x.reshape(3,3) # change "(3,3)" according to the dimensions o... | 1 | 2016-09-30T19:15:39Z | [
"python",
"optimization",
"scipy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.