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 |
|---|---|---|---|---|---|---|---|---|---|
How to convert a string into a list without including a specific character plus without using replace and split methods? | 39,967,795 | <p>Let's say you have:</p>
<pre><code>x = "1,2,13"
</code></pre>
<p>and you want to achieve:</p>
<pre><code>list = ["1","2","13"]
</code></pre>
<p>Can you do it without the split and replace methods?</p>
<p>What I have tried:</p>
<pre><code>list=[]
for number in x:
if number != ",":
list.append(number... | 0 | 2016-10-10T22:36:56Z | 39,967,932 | <p>You could use a regular expression:</p>
<pre><code>>>> import re
>>> re.findall('(\d+)', '123,456')
['123', '456']
</code></pre>
| 2 | 2016-10-10T22:51:52Z | [
"python"
] |
How to make a list in python when the input file has multiple separators? | 39,967,799 | <p>The sample file looks like this:</p>
<pre><code> ['>1\n', 'TCCGGGGGTATC\n', '>2\n', 'TCCGTGGGTATC\n',
'>3\n', 'TCCGTGGGTATC\n', '>4\n', 'TCCGGGGGTATC\n',
'>5\n', 'TCCGTGGGTATC\n', '>6\n', 'TCCGTGGGTATC\n',
'>7\n', 'TCCGTGGGTATC\n', '>8\n', 'TCCGGGGGTATC\n','\n',
'$$$\n', '\n',
'>... | 0 | 2016-10-10T22:37:20Z | 39,968,005 | <pre><code>input = ['>1\n', 'TCCGGGGGTATC\n', '>2\n', 'TCCGTGGGTATC\n',
'>3\n', 'TCCGTGGGTATC\n', '>4\n', 'TCCGGGGGTATC\n',
'>5\n', 'TCCGTGGGTATC\n', '>6\n', 'TCCGTGGGTATC\n',
'>7\n', 'TCCGTGGGTATC\n', '>8\n', 'TCCGGGGGTATC\n', '\n',
'$$$\n', '\n',
'>B1... | 1 | 2016-10-10T22:58:57Z | [
"python",
"list",
"append"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do no... | 0 | 2016-10-10T22:38:38Z | 39,967,862 | <p>One way to do this would be by removing instances of your sub string and looking at the length...</p>
<pre><code>def nofsub(s,ss):
return((len(s)-len(s.replace(ss,"")))/len(ss))
</code></pre>
<p>alternatively you could use re or regular expressions,</p>
<pre><code>from re import *
def nofsub(s,ss):
return... | -1 | 2016-10-10T22:44:47Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do no... | 0 | 2016-10-10T22:38:38Z | 39,967,884 | <p>Your best bet is to use <code>Counter</code> (which does work on a string) and then sort on it's output.</p>
<pre><code>from collections import Counter
sentence = input("Enter a sentence b'y: ")
lowercase = sentence.lower()
# Counter will work on strings
p = Counter(lowercase)
count = Counter.items()
# count is no... | 0 | 2016-10-10T22:46:34Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do no... | 0 | 2016-10-10T22:38:38Z | 39,967,905 | <p>If you just want to format the Counter output differently:</p>
<pre><code>for key, value in Counter(list1).items():
print('%s: %s' % (key, value))
</code></pre>
| 0 | 2016-10-10T22:48:36Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do no... | 0 | 2016-10-10T22:38:38Z | 39,967,969 | <p>You could use the list function to break the words apart`from collections </p>
<pre><code>from collections import Counter
sentence=raw_input("Enter a sentence b'y: ")
lowercase=sentence.lower()
list1=list(lowercase)
list(list1)
length=len(list1)
list2=list1.count(list1)
print(list2)
p=Counter(list1)
print(p)
</... | -3 | 2016-10-10T22:55:52Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do no... | 0 | 2016-10-10T22:38:38Z | 39,968,126 | <p>Just call <a href="https://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>.most_common</code></a> and reverse the output with <a href="https://docs.python.org/3/library/functions.html#reversed" rel="nofollow"><em>reversed</em></a> to get the output from least to most... | 1 | 2016-10-10T23:12:33Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do no... | 0 | 2016-10-10T22:38:38Z | 39,968,144 | <p><a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a> objects provide a <a href="https://docs.python.org/3/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>most_common()</code></a> method that returns a list ... | 1 | 2016-10-10T23:14:50Z | [
"python",
"list",
"count"
] |
How to count number of occurrences of a chracter in a string (list) | 39,967,810 | <p>I'm trying to count the occurrence of each character for any given string input, the occurrences must be output in ascending order( includes numbers and exclamation marks)
I have this for my code so far, i am aware of the Counter function, but it does not output the answer in the format I'd like it to, and I do no... | 0 | 2016-10-10T22:38:38Z | 39,968,674 | <p>Another way to avoid using Counter.</p>
<pre><code>sentence = 'abc 11 222 a AAnn zzz?? !'
list1 = list(sentence.lower())
#If you want to remove the spaces.
#list1 = list(sentence.replace(" ", ""))
#Removing duplicate characters from the string
sentence = ''.join(set(list1))
dict = {}
for char in sentence:
di... | 0 | 2016-10-11T00:22:20Z | [
"python",
"list",
"count"
] |
django: side menu template visible everywhere | 39,967,812 | <p>I need to create a side menu in my django admin that should appear in all pages. Ideally my template should be a generic navigation.html file containing this code and parsing app_list param (the same that is used into index.html template populating the dashboard):</p>
<pre><code>{% block side_menu %}
{% if app_list... | 0 | 2016-10-10T22:38:45Z | 39,968,002 | <p>1) It looks like <a href="https://docs.djangoproject.com/en/1.10/ref/templates/language/#template-inheritance" rel="nofollow">you're on the right track</a> - you have <code>{% block %}</code>. You just need to have your other files extend that navigation file (you may want to just make it base.html, like the documen... | 1 | 2016-10-10T22:58:44Z | [
"python",
"django"
] |
Installing ggplot for python failed with error code 1 | 39,967,873 | <p>I am trying to install ggplot for Python using</p>
<pre><code>pip install ggplot
</code></pre>
<p>but I get an error message saying
<a href="http://i.stack.imgur.com/ZgiKU.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZgiKU.png" alt="enter image description here"></a></p>
<p>I am using Python2.7 on Windo... | 0 | 2016-10-10T22:45:35Z | 39,968,223 | <p>After trying all possible things suggested in various forums this is what worked for me:</p>
<ol>
<li>Download numpy-1.11.2+mkl-cp27-cp27m-win_amd64.whl and scipy-0.18.1-cp27-cp27m-win_amd64.whl files from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pytho... | 0 | 2016-10-10T23:23:55Z | [
"python",
"ggplot2"
] |
python pandas and locate values | 39,967,952 | <p>Let's say I've a DataSerie like this :</p>
<pre><code>df = pandas.DataFrame(numpy.random.randn(4,4),columns=list('ABCD'))
df['test'] = ['A','B','A','C']
</code></pre>
<p>I would like to extract the lines with the 'A' letter and retrieve the values of a Serie, let's say 'C' column. How is it possible to do this whi... | 2 | 2016-10-10T22:54:30Z | 39,968,024 | <p>How about</p>
<pre><code>df[df['test'].str.contains('A')]['C']
</code></pre>
| 1 | 2016-10-10T23:01:00Z | [
"python",
"pandas",
"locate"
] |
python pandas and locate values | 39,967,952 | <p>Let's say I've a DataSerie like this :</p>
<pre><code>df = pandas.DataFrame(numpy.random.randn(4,4),columns=list('ABCD'))
df['test'] = ['A','B','A','C']
</code></pre>
<p>I would like to extract the lines with the 'A' letter and retrieve the values of a Serie, let's say 'C' column. How is it possible to do this whi... | 2 | 2016-10-10T22:54:30Z | 39,968,053 | <p>Using pandas filtering:</p>
<pre><code>df[df["test"].str.contains("A")]["C"]
</code></pre>
| 0 | 2016-10-10T23:04:09Z | [
"python",
"pandas",
"locate"
] |
python pandas and locate values | 39,967,952 | <p>Let's say I've a DataSerie like this :</p>
<pre><code>df = pandas.DataFrame(numpy.random.randn(4,4),columns=list('ABCD'))
df['test'] = ['A','B','A','C']
</code></pre>
<p>I would like to extract the lines with the 'A' letter and retrieve the values of a Serie, let's say 'C' column. How is it possible to do this whi... | 2 | 2016-10-10T22:54:30Z | 39,968,896 | <p>If equal to 'A' is what you need</p>
<pre><code>df.loc[df.test.eq('A'), 'C']
</code></pre>
<p>Otherwise </p>
<pre><code>df.loc[df.test.str.contains('A'), 'C']
</code></pre>
| 0 | 2016-10-11T00:52:29Z | [
"python",
"pandas",
"locate"
] |
Basic python usage, calling a function | 39,968,122 | <p>I am working on leetcode but actually never wrote a file locally before. </p>
<pre><code>class Solution(object):
def singleNumber(self, nums):
for i in range(0,len(nums),2):
if (i != len(nums) - 1) and (nums[i] != nums[i+1]):
print (nums[i])
elif i == len(nums) -... | 0 | 2016-10-10T23:12:09Z | 39,968,147 | <p>Move your <strong>main</strong> function outside of the class, and then specifically execute it:</p>
<pre><code>class Solution(object):
def singleNumber(self, nums):
for i in range(0,len(nums),2):
if (i != len(nums) - 1) and (nums[i] != nums[i+1]):
print (nums[i])
... | 2 | 2016-10-10T23:15:36Z | [
"python"
] |
Basic python usage, calling a function | 39,968,122 | <p>I am working on leetcode but actually never wrote a file locally before. </p>
<pre><code>class Solution(object):
def singleNumber(self, nums):
for i in range(0,len(nums),2):
if (i != len(nums) - 1) and (nums[i] != nums[i+1]):
print (nums[i])
elif i == len(nums) -... | 0 | 2016-10-10T23:12:09Z | 39,968,231 | <p>Unlike many other programming languages, such as Java, Python does not require the <code>main</code> method to be inside a class. Even more, Python <strong>does not need to have a <code>main</code> method defined</strong>: it runs the whole file as an application. In your original post, Python performs this actions:... | 2 | 2016-10-10T23:25:08Z | [
"python"
] |
Python method not executed | 39,968,137 | <p>Total noob here. I'm trying to create a python object and execute methods in an instance therein and it seems the code block I want to execute just won't run. The code block in question is run_job which when called just seems to do nothing. What am I doing wrong?</p>
<pre><code>import datetime
import uuid
import pa... | 0 | 2016-10-10T23:13:57Z | 39,968,183 | <p>Your method contains a yield statement, which makes it a generator. Generators are evaluated lazily. Consider:</p>
<pre><code>>>> def gen():
... yield 10
... yield 3
... yield 42
...
>>> result = gen()
>>> next(result)
10
>>> next(result)
3
>>> next(result)
42
>... | 0 | 2016-10-10T23:18:45Z | [
"python",
"python-2.7"
] |
Python method not executed | 39,968,137 | <p>Total noob here. I'm trying to create a python object and execute methods in an instance therein and it seems the code block I want to execute just won't run. The code block in question is run_job which when called just seems to do nothing. What am I doing wrong?</p>
<pre><code>import datetime
import uuid
import pa... | 0 | 2016-10-10T23:13:57Z | 39,969,648 | <blockquote>
<p>Yield is a keyword that is used like return, except the function will
return a generator.</p>
</blockquote>
<p>To read more about generators:<br>
1) <a href="http://stackoverflow.com/questions/1756096/understanding-generators-in-python">Understanding Generators in Python</a><br>
2) <a href="http://... | 0 | 2016-10-11T02:30:28Z | [
"python",
"python-2.7"
] |
Django 1.9 form inheritance on UpdateView | 39,968,241 | <p>The problem i have is with a single field that i added. </p>
<p>I have my form:</p>
<pre><code>
class employeesForm(forms.ModelForm):
class Meta:
fields = [
'num_employee',
'id_ignition',
'fullName',
'shortName',
... | 0 | 2016-10-10T23:25:53Z | 39,980,993 | <p>I was doing it wrong, i had to add this code into my enhanced form:</p>
<pre><code>class Enhanced_employeesForm(employeesForm):
class Meta(employeesForm.Meta):
employeesForm.Meta.fields += ['antiquity']
</code></pre>
<p>and that made the thing.</p>
<p>if you need widgets you might noticed that everyth... | 0 | 2016-10-11T15:28:14Z | [
"python",
"inheritance",
"django-forms",
"django-views",
"django-1.9"
] |
Python Selenium Webpage Scraping Selecting Drop Down and entering text in html form | 39,968,269 | <p>I have a problem scraping data from the following site: <a href="https://arcc.sdcounty.ca.gov/Pages/Assessors-Roll-Tax.aspx" rel="nofollow">https://arcc.sdcounty.ca.gov/Pages/Assessors-Roll-Tax.aspx</a>. </p>
<p>I have to do these steps in order:</p>
<ol>
<li><p>Select a drop down option "Street Address'</p></li>
... | 1 | 2016-10-10T23:28:35Z | 39,968,527 | <p>Not sure if this is your situation. But one thing that jumped out from your question is the text box input... Often, when filling in a website text box, even though the text is clearly visible, the text is not actually read by the text-box method until after the focus (cursor) is clicked or tabbed out and away from ... | 0 | 2016-10-11T00:01:37Z | [
"python",
"html",
"selenium",
"selenium-webdriver"
] |
Python Selenium Webpage Scraping Selecting Drop Down and entering text in html form | 39,968,269 | <p>I have a problem scraping data from the following site: <a href="https://arcc.sdcounty.ca.gov/Pages/Assessors-Roll-Tax.aspx" rel="nofollow">https://arcc.sdcounty.ca.gov/Pages/Assessors-Roll-Tax.aspx</a>. </p>
<p>I have to do these steps in order:</p>
<ol>
<li><p>Select a drop down option "Street Address'</p></li>
... | 1 | 2016-10-10T23:28:35Z | 39,969,032 | <p>Just changed a few things in your code to make it work.</p>
<pre><code>mySelect = Select(driver.find_element_by_id("ctl00_ctl43_g_d30f33ca_a5a7_4f69_bb21_cd4abc25 ea12_ctl00_ddlSearch"))
</code></pre>
<p>To find_element_by_name(...):</p>
<pre><code>mySelect = Select(driver.find_element_by_name("ctl00$ctl43$g_d30... | 1 | 2016-10-11T01:11:43Z | [
"python",
"html",
"selenium",
"selenium-webdriver"
] |
How to use counters and zip functions with a list of lists in Python? | 39,968,360 | <p>I have a list of lists :</p>
<pre><code>results = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]
</code></pre>
<p>I create a counter that stores number number of characters in each element in each list, only if the characters are ATGC [NOT Z]</p>
<pre><code>The desired output is [[4,3],[4,2]]
</code></pre>
<p>**</p>
<p>C... | 0 | 2016-10-10T23:37:28Z | 39,969,273 | <p>The first part can be done like this:</p>
<pre><code>BASES = {'A', 'C', 'G', 'T'}
results = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]
counts = [[sum(c in BASES for c in s) for s in pair] for pair in results]
>>> counts
[[4, 3], [4, 2]]
</code></pre>
<p>Once you have the counts, the correction factor can also ... | 1 | 2016-10-11T01:42:08Z | [
"python",
"list",
"error-handling",
"append"
] |
How to use counters and zip functions with a list of lists in Python? | 39,968,360 | <p>I have a list of lists :</p>
<pre><code>results = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]
</code></pre>
<p>I create a counter that stores number number of characters in each element in each list, only if the characters are ATGC [NOT Z]</p>
<pre><code>The desired output is [[4,3],[4,2]]
</code></pre>
<p>**</p>
<p>C... | 0 | 2016-10-10T23:37:28Z | 39,970,108 | <p>First map traverse results.
Second map replace 'Z' and count element.</p>
<pre><code>map(lambda x:map(lambda y:len(y.replace('Z','')),x),l)
</code></pre>
| 0 | 2016-10-11T03:30:11Z | [
"python",
"list",
"error-handling",
"append"
] |
How to convert unicode array to string in Python | 39,968,414 | <p>I am very new with Python and I am trying to print a single object from a unicode array that I retrieved from my server. My array look like this when I print the results:</p>
<pre><code>{u'results': [{u'playerName': u'Sean Plott', u'score': u'12'}]
</code></pre>
<p>I would like to print the result in <code>playerN... | 0 | 2016-10-10T23:44:22Z | 39,968,456 | <p>You should spend some time looking up dictionaries and lists in python. You currently have a dictionary with a list in it, and a dictionary inside of that list.</p>
<p>Here's the official reference guide on Python data structures:</p>
<p><a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollo... | 3 | 2016-10-10T23:51:04Z | [
"python",
"arrays",
"string",
"unicode"
] |
XLRD/ Entrez: Search through Pubmed and extract the counts | 39,968,425 | <p>I am working on a project that requires me to search through <code>pubmed</code> using inputs from an <code>Excel</code> spreadsheet and print counts of the results. I have been using <code>xlrd</code> and <code>entrez</code> to do this job. Here is what I have tried.</p>
<ol>
<li><p>I need to search through <code>... | 1 | 2016-10-10T23:46:09Z | 39,972,453 | <p>You got most of the code in place. It just needed to be modified slightly.</p>
<p>Assuming your table looks like this:</p>
<pre><code>Jennifer Bunch |Southern Illinois University School of Medicine|Leonard P. Rybak
Philipp Robinson|Stanford University School of Medicine |Roger Kornberg
</code></pre>
<p>y... | 1 | 2016-10-11T07:39:08Z | [
"python",
"xlrd",
"biopython",
"pubmed"
] |
openpyxl: a better way to read a range of numbers to an array | 39,968,466 | <p>I am looking for a better (more readable / less hacked together) way of reading a range of cells using <code>openpyxl</code>. What I have at the moment works, but involves composing the excel cell range (e.g. <code>A1:C3</code>) by assembling bits of the string, which feels a bit rough.</p>
<p>At the moment this is... | 1 | 2016-10-10T23:53:02Z | 39,971,903 | <p>openpyxl provides functions for converting between numerical column indices (1-based index) and Excel's 'AA' style. See the <code>utils</code> module for details.</p>
<p>However, you'll have little need for them in general. You can use the <code>get_squared_range()</code> method of worksheets for programmatic acces... | 1 | 2016-10-11T06:57:37Z | [
"python",
"numpy",
"openpyxl"
] |
openpyxl: a better way to read a range of numbers to an array | 39,968,466 | <p>I am looking for a better (more readable / less hacked together) way of reading a range of cells using <code>openpyxl</code>. What I have at the moment works, but involves composing the excel cell range (e.g. <code>A1:C3</code>) by assembling bits of the string, which feels a bit rough.</p>
<p>At the moment this is... | 1 | 2016-10-10T23:53:02Z | 39,972,803 | <p>For completeness (and so I can find it later) the equivalent code using the <code>pandas</code> function <code>read_excel</code> suggested by @Rob in a comment would be:</p>
<pre><code>import pandas
import numpy as np
wsName = "Sheet1"
df = pandas.read_excel(open("worksheet.xlsx", "rb"), sheetname=wsName, header=No... | 0 | 2016-10-11T08:01:31Z | [
"python",
"numpy",
"openpyxl"
] |
Comparing a sequence of letters to a list of words in python | 39,968,554 | <p>I have a list of letters which is in a particular order (think of old school texting, so my sequence of buttons here is 4266532)</p>
<pre><code>letters = [['g', 'h', 'i'], ['a', 'b', 'c'], ['m', 'n', 'o'], ['m', 'n', 'o'], ['j', 'k', 'l'], ['d', 'e', 'f']]
</code></pre>
<p>and a list of words</p>
<pre><code>words... | -1 | 2016-10-11T00:05:07Z | 39,968,779 | <p>Not sure what your full criteria is but since your lists are going to be small you can do something like:</p>
<pre><code>from collections import Counter
from itertools import combinations, chain
letters = [['g', 'h', 'i'], ['a', 'b', 'c'], ['m', 'n', 'o'],['m', 'n', 'o'], ['j', 'k', 'l'], ['d', 'e', 'f']]
allowed =... | 1 | 2016-10-11T00:37:23Z | [
"python"
] |
How to tell when enter/return has been pressed in pyQt4 lineEdit | 39,968,562 | <p>I'm having a problem where I can't figure out how to tell if the user hits enter. All of the stackoverflow posts and docs I read all tell me to to add self.textEdit.returnPressed.connect, or something along the lines of that and none of the solutions work. I'm using pyQt 4. Here's the code:</p>
<pre><code># -*- cod... | 0 | 2016-10-11T00:06:09Z | 39,969,154 | <p>You have to mistakes </p>
<ul>
<li><code>returnPressed</code> works with <code>QtLineEdit</code> and you use <code>QtTextEdit</code></li>
<li>you don't have <code>self.pushButtonOK</code> but <code>self.saveButton</code> and <code>self.fontButton</code></li>
</ul>
<p>So you need</p>
<pre><code> self.fontSize =... | 1 | 2016-10-11T01:27:44Z | [
"python",
"python-3.x",
"pyqt",
"pyqt4"
] |
Beautiful Soup: get contents of search result tag | 39,968,593 | <p>Trying to get the contents of this type of html snippet using beautiful soup (it is a "tag" object).</p>
<pre><code><span class="font5"> arrives at this calculation from the Torahâs report that the deluge (rains) began on the 17<sup>th</sup> day of the second month </span>
</code></pre>... | 2 | 2016-10-11T00:09:01Z | 39,968,632 | <p><code>soup.find_all('span')</code> does work; returns all <code>span</code> tags.</p>
<p>If you want to get <code>span</code> tag with <code>font<N></code> class, specify the pattern as a keyword argument <code>class_</code>:</p>
<pre><code>soup.find_all('span', class_=re.compile('font[0-9]+'))
</code></pre>... | 2 | 2016-10-11T00:14:56Z | [
"python",
"beautifulsoup"
] |
Beautiful Soup: get contents of search result tag | 39,968,593 | <p>Trying to get the contents of this type of html snippet using beautiful soup (it is a "tag" object).</p>
<pre><code><span class="font5"> arrives at this calculation from the Torahâs report that the deluge (rains) began on the 17<sup>th</sup> day of the second month </span>
</code></pre>... | 2 | 2016-10-11T00:09:01Z | 39,969,119 | <p>If starting with <em>font</em> is unique enough you can use also use a <em>css selector</em> looking for the class starting with font:</p>
<pre><code>soup.select("span[class^=font]")
</code></pre>
| 0 | 2016-10-11T01:21:18Z | [
"python",
"beautifulsoup"
] |
Beautiful Soup: get contents of search result tag | 39,968,593 | <p>Trying to get the contents of this type of html snippet using beautiful soup (it is a "tag" object).</p>
<pre><code><span class="font5"> arrives at this calculation from the Torahâs report that the deluge (rains) began on the 17<sup>th</sup> day of the second month </span>
</code></pre>... | 2 | 2016-10-11T00:09:01Z | 39,980,164 | <pre><code>print ''.join(soup.findAll(text=True))
</code></pre>
<p>(answered <a href="http://stackoverflow.com/questions/2957013/beautifulsoup-just-get-inside-of-a-tag-no-matter-how-many-enclosing-tags-there">here</a>)</p>
| 0 | 2016-10-11T14:52:09Z | [
"python",
"beautifulsoup"
] |
Why can't I reference key in reduce logic? | 39,968,659 | <p>I want to have logic in my <code>combineByKey</code>/<code>reduceByKey</code>/<code>foldByKey</code> that relies on the key currently being operated on. From what I can tell by the method signatures, the only parameters passed to these methods are the values being combined/reduced/folded.</p>
<p>Using a simple exam... | 0 | 2016-10-11T00:18:46Z | 39,971,861 | <p>I think there is no strong reason not to pass keys.<br>
however, I feel <code>reduceByKey</code> API was designed for common use case -- compute sum of values for each key. So far I've never needed keys within the value computation. But that's just my opinion.</p>
<p>Also the problem that you solved seems to be s... | 0 | 2016-10-11T06:54:33Z | [
"python",
"mapreduce",
"pyspark"
] |
Checking if something is true in all iterations of a Python for loop | 39,968,669 | <p>I'm trying to find is a variable is an element of any lists in a list of lists. If it is an element of any of them, then I'm using <code>continue</code> to move onto the next block. If it's not a member of any lists I would like to then create a new list in the list of lists, with the variable as the only entry of... | 2 | 2016-10-11T00:21:09Z | 39,968,716 | <p>Why not just put the if statement outside of the loop?</p>
<pre><code>found = False
for group in groups:
if point in group:
found = True
break
if not found:
groups.append([point])
</code></pre>
| 1 | 2016-10-11T00:28:40Z | [
"python"
] |
Checking if something is true in all iterations of a Python for loop | 39,968,669 | <p>I'm trying to find is a variable is an element of any lists in a list of lists. If it is an element of any of them, then I'm using <code>continue</code> to move onto the next block. If it's not a member of any lists I would like to then create a new list in the list of lists, with the variable as the only entry of... | 2 | 2016-10-11T00:21:09Z | 39,968,721 | <p>Reverse your logic, and use the <code>else</code> clause of the <code>for</code> loop to create the new group.</p>
<pre><code>for group in groups:
if point in group:
break
else:
create_new_group(point)
</code></pre>
<p>Or just use <code>any()</code>.</p>
<pre><code>if not any(point in group for group in g... | 4 | 2016-10-11T00:28:58Z | [
"python"
] |
Checking if something is true in all iterations of a Python for loop | 39,968,669 | <p>I'm trying to find is a variable is an element of any lists in a list of lists. If it is an element of any of them, then I'm using <code>continue</code> to move onto the next block. If it's not a member of any lists I would like to then create a new list in the list of lists, with the variable as the only entry of... | 2 | 2016-10-11T00:21:09Z | 39,968,724 | <p>Make a function.</p>
<pre><code>def check_matches(point, groups):
for group in groups:
if point in group:
return true
return false
if not check_matches(point, groups):
groups.append([point])
</code></pre>
<p>You can leave it this simple, depending on what you are trying to do with ... | 1 | 2016-10-11T00:29:06Z | [
"python"
] |
Checking if something is true in all iterations of a Python for loop | 39,968,669 | <p>I'm trying to find is a variable is an element of any lists in a list of lists. If it is an element of any of them, then I'm using <code>continue</code> to move onto the next block. If it's not a member of any lists I would like to then create a new list in the list of lists, with the variable as the only entry of... | 2 | 2016-10-11T00:21:09Z | 39,968,735 | <p>Try using the built-in <code>any()</code> function.</p>
<pre><code>if not any(point in group for group in groups):
groups.append([point])
</code></pre>
| 1 | 2016-10-11T00:30:11Z | [
"python"
] |
Quick numpy array extension | 39,968,711 | <p>I wonder if there is a trick to extending a numpy array with consecutive
numbers in between each original values, up to a user controlled default length. Perhaps there is already a built-in function that turns x into y</p>
<pre><code>x=np.array([4,8,4,10])
y=np.array([4,5,6,7,8,9,10,11,4,5,6,7,10,11,12,13])
</code... | 0 | 2016-10-11T00:28:12Z | 39,968,794 | <p>Broadcasted addition is probably the fastest</p>
<pre><code>In [241]: (x[:,None]+np.arange(4)).ravel()
Out[241]: array([ 4, 5, 6, 7, 8, 9, 10, 11, 4, 5, 6, 7, 10, 11, 12, 13])
</code></pre>
<p>It gets trickier if adding different amounts for each sublist. </p>
<p><code>repeat</code> is useful:</p>
<pre>... | 1 | 2016-10-11T00:38:44Z | [
"python",
"arrays",
"numpy"
] |
Quick numpy array extension | 39,968,711 | <p>I wonder if there is a trick to extending a numpy array with consecutive
numbers in between each original values, up to a user controlled default length. Perhaps there is already a built-in function that turns x into y</p>
<pre><code>x=np.array([4,8,4,10])
y=np.array([4,5,6,7,8,9,10,11,4,5,6,7,10,11,12,13])
</code... | 0 | 2016-10-11T00:28:12Z | 39,968,798 | <p>I don't know a built-in function that does precisely that, but with some creativity you could do:</p>
<pre><code>>>> x=np.array([4,8,4,10])
>>> np.array([x+i for i in range(4)]).T.ravel()
array([ 4, 5, 6, 7, 8, 9, 10, 11, 4, 5, 6, 7, 10, 11, 12, 13])
</code></pre>
<p>For the second half ... | 0 | 2016-10-11T00:39:11Z | [
"python",
"arrays",
"numpy"
] |
Quick numpy array extension | 39,968,711 | <p>I wonder if there is a trick to extending a numpy array with consecutive
numbers in between each original values, up to a user controlled default length. Perhaps there is already a built-in function that turns x into y</p>
<pre><code>x=np.array([4,8,4,10])
y=np.array([4,5,6,7,8,9,10,11,4,5,6,7,10,11,12,13])
</code... | 0 | 2016-10-11T00:28:12Z | 39,968,805 | <p>This works on lists:</p>
<pre><code>def extend(myList, n):
extensions = [range(x, x + n) for x in myList]
return [item for sublist in extensions for item in sublist] # flatten
</code></pre>
<p>Use as follows:</p>
<pre><code>extend([4, 8, 4, 10], 4)
</code></pre>
| 0 | 2016-10-11T00:39:39Z | [
"python",
"arrays",
"numpy"
] |
Test for presence of specific text in tag with scrapy | 39,968,727 | <p>I'm interested in testing for the presence of specific text (an error message) on pages that I'm scraping. I have the following working statement:</p>
<pre><code> not_found=response.selector.xpath('//*[@id="Error"]/font[contains(text(),"is not found")]')
</code></pre>
<p>I can see that their is a boolean test me... | 0 | 2016-10-11T00:29:45Z | 39,968,824 | <p>Python doc: <a href="https://docs.python.org/2/reference/datamodel.html#object.__nonzero__" rel="nofollow"><code>__nonzero__</code></a></p>
<p>It is used automatically when you do <code>bool(not_found)</code><br>
and <code>bool()</code> is use automatically when you do <code>if not_found:</code></p>
<hr>
<p>You d... | 1 | 2016-10-11T00:41:20Z | [
"python",
"scrapy"
] |
"oauth2client.transport : Refreshing due to a 401" what exactly this log mean? | 39,968,806 | <p>I setup a job on google cloud dataflow, and it need more than 7 hours to make it done. My Job ID is 2016-10-10_09_29_48-13166717443134662621. It didn't show any error in pipeline. Just keep logging out "oauth2client.transport : Refreshing due to a 401". Is there any problem of my workers or there is something wrong.... | 0 | 2016-10-11T00:39:45Z | 39,970,763 | <p>As a general approach, you should try running the pipeline locally, using the <code>DirectPipelineRunner</code> on a small dataset to debug your custom transformations.</p>
<p>Once that passes, you can use the Google Cloud Dataflow UI to investigate the pipeline state. You can particularly look at <code>Elements Ad... | 2 | 2016-10-11T05:01:00Z | [
"python",
"google-cloud-dataflow"
] |
Python multiprocessing start more processes than cores | 39,968,808 | <p>Say I start 10 process in a loop using Process() but I only have 8 cores available. How does python handle this?</p>
| 0 | 2016-10-11T00:39:51Z | 39,969,183 | <p>While best practice is to use as many threads as you have virtual cores available, you don't have to stick to that. Using less means you could be under-utilizing your available processor capacity. Using more means you'll be over-utilizing your available processor capacity.</p>
<p>Both these situations mean you'll b... | 1 | 2016-10-11T01:31:18Z | [
"python",
"multiprocessing"
] |
How to write the dictionary key in a batch of text using python? | 39,968,817 | <p>I would be grateful for any help. I have a dictionary which looks like this:</p>
<p>TEST_versions = {'D14 2015' : 'X1', 'D12 2014' : 'X2'}</p>
<p>I want the key from the dictionary to be placed in my text (which I am appending to a file) so I have written:</p>
<pre><code>for v in TEST_versions.keys():
#prin... | 0 | 2016-10-11T00:40:38Z | 39,968,836 | <p>You need to <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">format</a> the string with the variable:</p>
<pre><code>for v in TEST_versions.keys():
#print(v)
add_code = open('make_all_ascii_files.txt','a')
add_code.write("""
SELECT IF (Version_selector = {}).""".format... | 0 | 2016-10-11T00:42:55Z | [
"python",
"dictionary"
] |
How to write the dictionary key in a batch of text using python? | 39,968,817 | <p>I would be grateful for any help. I have a dictionary which looks like this:</p>
<p>TEST_versions = {'D14 2015' : 'X1', 'D12 2014' : 'X2'}</p>
<p>I want the key from the dictionary to be placed in my text (which I am appending to a file) so I have written:</p>
<pre><code>for v in TEST_versions.keys():
#prin... | 0 | 2016-10-11T00:40:38Z | 39,968,905 | <p><em>v</em> is not replaced within string itself.
You can do something like following, for example (using named placeholders)</p>
<pre><code>for k in TEST_versions.keys():
add_code = open('make_all_ascii_files.txt','a')
add_code.write(
"SELECT IF (Version_selector = %(value)s)."
% { 'value': ... | 0 | 2016-10-11T00:53:17Z | [
"python",
"dictionary"
] |
I need to assume for an empty sequence in this code for python | 39,968,888 | <p>The function prints the keyword length, then prints a sorted list of all the dictionary keywords of the required length, which have the highest frequency, followed by the frequency. For example, the following code:</p>
<pre><code> word_frequencies = {"fish":9, "parrot":8, "frog":9, "cat":9, "stork":1, "dog":4... | 1 | 2016-10-11T00:51:08Z | 39,968,961 | <p>Simply add a fallback condition to the <code>max()</code> call so that it never tries to find the largest of an empty iterable:</p>
<pre><code>max_freq = max(right_length.values() or [0])
</code></pre>
<p>If <code>right_length.values()</code> is empty, <code>[0]</code> (which is not empty) will be used instead, an... | 1 | 2016-10-11T01:00:07Z | [
"python",
"list",
"function"
] |
Python 3 and b'\x92'.decode('latin1') | 39,968,891 | <p>I'm getting results I didn't expect from decoding b'\x92' with the latin1 codec. See the session below:</p>
<pre><code>Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
>>> b'\xa3'.decode('latin1').encode('ascii', 'namereplace')
b'\\N{POUND SIGN}'
>>> b... | 0 | 2016-10-11T00:51:40Z | 39,968,985 | <p>The error I made was to expect that the character 0x92 decoded to "RIGHT SINGLE QUOTATION MARK" in latin-1, it doesn't. The confusion was caused because it was present in a file that was specified as being in latin1 encoding. It now appears that the file was actually encoded in windows-1252. This is apparently a com... | 0 | 2016-10-11T01:04:11Z | [
"python",
"python-3.x",
"unicode",
"python-unicode"
] |
Python 3 and b'\x92'.decode('latin1') | 39,968,891 | <p>I'm getting results I didn't expect from decoding b'\x92' with the latin1 codec. See the session below:</p>
<pre><code>Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
>>> b'\xa3'.decode('latin1').encode('ascii', 'namereplace')
b'\\N{POUND SIGN}'
>>> b... | 0 | 2016-10-11T00:51:40Z | 39,968,989 | <p>I just want to make clear that you're not encoding anything here. </p>
<p><code>xa3</code> has a ordinal value of 163 (0xa3 in hexadecimal). Since that ordinal is not seven bits, it can't be encoded into ascii. Your handler for errors just replaces the Unicode Character into the name of the character. The Unicode C... | 1 | 2016-10-11T01:04:29Z | [
"python",
"python-3.x",
"unicode",
"python-unicode"
] |
Python 3 and b'\x92'.decode('latin1') | 39,968,891 | <p>I'm getting results I didn't expect from decoding b'\x92' with the latin1 codec. See the session below:</p>
<pre><code>Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
>>> b'\xa3'.decode('latin1').encode('ascii', 'namereplace')
b'\\N{POUND SIGN}'
>>> b... | 0 | 2016-10-11T00:51:40Z | 40,029,793 | <blockquote>
<p>I was expecting b'\x92'.decode('latin1') to result in U+2018</p>
</blockquote>
<p><code>latin1</code> is an alias for <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-1" rel="nofollow">ISO-8859-1</a>. In that encoding, byte 0x92 maps to character U+0092, an unprintable control character.</p>
<p>T... | 1 | 2016-10-13T19:53:51Z | [
"python",
"python-3.x",
"unicode",
"python-unicode"
] |
median of five points python | 39,968,904 | <p>My data frame (<code>df</code>) has a list of numbers (total 1773) and I am trying to find a median for five numbers (e.g. the <code>median of 3rd number = median (1st,2nd,3rd,4th,5th)</code>)</p>
<pre><code>num
10
20
15
34
...
...
...
def median(a, b, c,d,e):
I=[a,b,c,d,e]
return I[2]
num_median = [num... | 0 | 2016-10-11T00:53:10Z | 39,968,928 | <p>An example which will help:</p>
<pre><code>a = [0, 1, 2, 3]
print('Length={}'.format(len(a)))
print(a(4))
</code></pre>
<p>You are trying the same thing. The actual index of an element is one lower than the place it is. Keep in mind your exception shows you <em>exactly</em> where your problem is.</p>
<p>You need ... | 1 | 2016-10-11T00:56:16Z | [
"python",
"numpy",
"indexing",
"median"
] |
How to pack spheres in python? | 39,968,941 | <p>I am trying to model random closed packing spheres of uniform size in a square using python. <strong>And the spheres should not overlap</strong> but I do not know how to do this</p>
<p>I have so far:
<a href="http://i.stack.imgur.com/fwScD.png" rel="nofollow"><img src="http://i.stack.imgur.com/fwScD.png" alt="ente... | 1 | 2016-10-11T00:57:40Z | 39,969,076 | <p>This is a very hard problem (and probably <strong>np-hard</strong>). There should be a lot of ressources available.</p>
<p>Before i present some more general approach, check out <a href="https://en.wikipedia.org/wiki/Circle_packing_in_a_square" rel="nofollow">this wikipedia-site</a> for an overview of the currently... | 3 | 2016-10-11T01:16:16Z | [
"python",
"optimization",
"mathematical-optimization",
"packing"
] |
R lm versus Python sklearn linear_model | 39,968,999 | <p>When I study Python SKlearn, the first example that I come across is the linear regression.</p>
<p><a href="http://scikit-learn.org/stable/modules/linear_model.html" rel="nofollow">http://scikit-learn.org/stable/modules/linear_model.html</a></p>
<p>Code of its very first example:</p>
<pre><code>from sklearn impor... | 1 | 2016-10-11T01:06:23Z | 39,979,016 | <p>Both solutions are correct (assuming that NA behaves like a zero). Which solution is favored depends on the numerical solver used by the OLS estimator.</p>
<p><code>sklearn.linear_model.LinearRegression</code> is based on <code>scipy.linalg.lstsq</code> which in turn calls the LAPACK <code>gelsd</code> routine whic... | 3 | 2016-10-11T13:59:36Z | [
"python",
"scikit-learn",
"regression",
"linear"
] |
Two select query at a time python | 39,969,030 | <p>I want to calculate distance between two points. For that for each point in one table i have to calculate distance with all the other point in another table in same database. I am using python for that but I am not able to execute two query at a time. </p>
<pre><code>import mysql.connector
from haversine import hav... | 1 | 2016-10-11T01:11:16Z | 39,969,092 | <p>One trick you could use here would be to cross join the two tables together:</p>
<pre><code>SELECT t1.longitude,
t1.latitude,
t2.geo_coordinates_latitude,
t2.geo_coordinates_longitude
FROM
(
SELECT longitude, latitude
FROM roadData
LIMIT 5
) t1
CROSS JOIN
(
SELECT geo_coordinate... | 0 | 2016-10-11T01:17:38Z | [
"python",
"mysql",
"sql"
] |
Trying to build an Organizational Tree From a List | 39,969,031 | <p>I have an input file that's in the following format.</p>
<pre><code>Fred,Karl,Technician,2010--Karl,Cathy,VP,2009--Cathy,NULL,CEO,2007--
--Vince,Cathy,Technician,2010
</code></pre>
<p>I need to parse this information to where it ends up looking something like this in an output file:</p>
<pre><code>Cathy (CEO) 200... | 0 | 2016-10-11T01:11:41Z | 39,969,529 | <p>Cool question, it was fun to work on. I tried to be thorough, and it ended up getting kind of long, I hope it's still readable.</p>
<p>Code:</p>
<pre><code>##########################
#Input data cleaned a bit#
##########################
lines = ["Fred,Karl,Technician,2010",
"Karl,Cathy,VP,2009",
... | 0 | 2016-10-11T02:17:34Z | [
"python",
"algorithm",
"sorting",
"parsing"
] |
How to create pie chart? | 39,969,089 | <p>new to Python and stuck with a pie chart.
Apologies for the complexity but I am at a lost as how to proceed ..
I have this dataset in the form of a dictionary (part of it)</p>
<pre><code>{'Deaths5': 94, 'Deaths10': 379, 'Deaths12': 388, 'Deaths8': 138, 'Deaths25': None,
'IM_Deaths2': None, 'Deaths14': 511, 'Deat... | 2 | 2016-10-11T01:17:31Z | 39,969,548 | <p>You can use <a href="http://matplotlib.org/examples/pie_and_polar_charts/pie_demo_features.html" rel="nofollow">Matplotlib</a> for creating Pie charts in Python</p>
<p>Example Pie Chart:-</p>
<pre><code>import matplotlib.pyplot as plt
labels = 'A', 'B', 'C', 'D'
sizes = [40, 20, 20, 20]
colors = ['yellowgreen', '... | 1 | 2016-10-11T02:19:46Z | [
"python",
"python-3.x",
"dictionary",
"charts",
"pie-chart"
] |
How to create pie chart? | 39,969,089 | <p>new to Python and stuck with a pie chart.
Apologies for the complexity but I am at a lost as how to proceed ..
I have this dataset in the form of a dictionary (part of it)</p>
<pre><code>{'Deaths5': 94, 'Deaths10': 379, 'Deaths12': 388, 'Deaths8': 138, 'Deaths25': None,
'IM_Deaths2': None, 'Deaths14': 511, 'Deat... | 2 | 2016-10-11T01:17:31Z | 39,987,843 | <p>Full disclosure, I'm a member of the ZingChart team.</p>
<p>You can use <a href="https://www.zingchart.com/" rel="nofollow">ZingChart</a> for free to accomplish this. I'm not sure if you were looking for the answer to include how to parse the dictionary or just the data visualization portion. With some simple attri... | 4 | 2016-10-11T22:36:33Z | [
"python",
"python-3.x",
"dictionary",
"charts",
"pie-chart"
] |
adding accessing and deleting items from a python list | 39,969,124 | <p>Learning lists and arrays and I am not sure where I went wrong with this program. Keep in mind I am still new to python. Unsure if i am doing it right. Ive read a few tutorials and maybe Im not grasping list and arrays. Ive got it to where you can type a name but it doesnt transfer to a list and then i get list is e... | 0 | 2016-10-11T01:22:23Z | 39,969,299 | <p>For starting out, you've got the right ideas and you're making good progress. The main problem is how you defined <code>namelist = 0</code>, making it a number. Instead, <code>namelist</code> needs to be an actual <code>list</code> for you to add or append anything to it. Also, you're <code>append()</code> method is... | 0 | 2016-10-11T01:45:44Z | [
"python"
] |
adding accessing and deleting items from a python list | 39,969,124 | <p>Learning lists and arrays and I am not sure where I went wrong with this program. Keep in mind I am still new to python. Unsure if i am doing it right. Ive read a few tutorials and maybe Im not grasping list and arrays. Ive got it to where you can type a name but it doesnt transfer to a list and then i get list is e... | 0 | 2016-10-11T01:22:23Z | 39,969,314 | <p>You should consider initializing the list to be empty instead of zero (unless you want that element).</p>
<pre><code>namelist = list()
</code></pre>
<p>Also, your append method does not perform any actions. It's also pretty unnecessary since you can just use the append method of list.</p>
<pre><code>def addmember... | 0 | 2016-10-11T01:47:35Z | [
"python"
] |
adding accessing and deleting items from a python list | 39,969,124 | <p>Learning lists and arrays and I am not sure where I went wrong with this program. Keep in mind I am still new to python. Unsure if i am doing it right. Ive read a few tutorials and maybe Im not grasping list and arrays. Ive got it to where you can type a name but it doesnt transfer to a list and then i get list is e... | 0 | 2016-10-11T01:22:23Z | 39,969,349 | <p>After getting name from input, you call the append(name) method, yet your append method doesn't do anything yet.</p>
<p>In your append method you have to add the name you get to your namelist, like how you do in the editmember method.</p>
| 0 | 2016-10-11T01:53:08Z | [
"python"
] |
Convert to np.array, some values automatically being divided | 39,969,143 | <p>I'm converting a list of strings into a list of lists, and then converting that list into a np.array. The format of each list 5 element array within the np.array of arrays is [latitude, longitude, elevation, index, classifier]. The classifier is <code>1</code> if the elevation is above 0.00 (land) or <code>0</code... | 0 | 2016-10-11T01:25:51Z | 39,969,362 | <p>The <code>e</code> represents scientific notation. I am not sure why this only happens with the land case, but <a href="http://stackoverflow.com/questions/4205259/how-to-force-a-ndarray-show-in-normal-way-instead-of-scientific-notation">this StackOverflow question</a> could be helpful in setting up <code>numpy.set_p... | 1 | 2016-10-11T01:55:37Z | [
"python"
] |
python django id to hex | 39,969,151 | <p>I'm looking to take the default ID key from the django model turn it into hexadecimal and display it on a page when the user sumbits the post, I've tried several of methods with no success can anyone point me in the right direction?</p>
<p>views.py</p>
<pre><code>def post_new(request):
if request.method == "POST":... | 1 | 2016-10-11T01:27:19Z | 39,969,326 | <p>Python's hex function is all you need here, but the problem is you can't call it directly from your template. So the solution is to add a method to your model.</p>
<pre><code>class MyModel(models.Model):
def to_hex(self):
return hex(self.pk)
</code></pre>
<p>Then in your template</p>
<pre><code> {{ my_... | 0 | 2016-10-11T01:49:44Z | [
"python",
"django"
] |
Recommender engine in python - incorporate custom similarity metrics | 39,969,168 | <p>I am currently building a recommender engine in python and I faced the following problem.</p>
<p>I want to incorporate collaborative filtering approach, its user-user variant. To recap, its idea is that we have an information on different users and which items they liked (if applicable - which ratings these users a... | 0 | 2016-10-11T01:29:20Z | 40,001,529 | <p>I would keep it simple and separate:</p>
<p>Your focus is collaborative filtering, so your recommender should generate scores for the top N recommendations <em>regardless of location</em>.</p>
<p>Then you can <strong>re-score</strong> using distance among those top-N. For a simple MVP, you could start with an inv... | 1 | 2016-10-12T14:41:31Z | [
"python",
"machine-learning",
"recommendation-engine",
"data-science"
] |
Convert UPPERCASE string to sentence case in Python | 39,969,202 | <p>How does one convert an uppercase string to proper sentence-case? Example string:</p>
<pre><code>"OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE"
</code></pre>
<p>Using <code>titlecase(str)</code> gives me:</p>
<pre><code>"Operator Fail to Properly Remove Solid Waste"
</code></pre>
<p>What I need is:</p>
<pre><co... | 1 | 2016-10-11T01:33:30Z | 39,969,233 | <p>This will work for any sentence, or any paragraph. Note that the sentence must end with a <code>.</code> or it won't be treated as a new sentence. (Stealing <code>.capitalize()</code> which is the better method, hats off to brianpck for that)</p>
<pre><code>a = 'hello. i am a sentence.'
a = '. '.join(i.capitalize()... | 1 | 2016-10-11T01:37:50Z | [
"python"
] |
Convert UPPERCASE string to sentence case in Python | 39,969,202 | <p>How does one convert an uppercase string to proper sentence-case? Example string:</p>
<pre><code>"OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE"
</code></pre>
<p>Using <code>titlecase(str)</code> gives me:</p>
<pre><code>"Operator Fail to Properly Remove Solid Waste"
</code></pre>
<p>What I need is:</p>
<pre><co... | 1 | 2016-10-11T01:33:30Z | 39,969,258 | <p>Let's use an even more appropriate function for this: <a href="https://docs.python.org/2/library/string.html#string.capitalize" rel="nofollow"><code>string.capitalize</code></a></p>
<pre><code>>>> s="OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE"
>>> s.capitalize()
'Operator fail to properly remove... | 3 | 2016-10-11T01:40:23Z | [
"python"
] |
YTick overlapping in Matplotlib | 39,969,217 | <p>I have been trying to plot data on Matplotlib and I seem to have overlapping YTicks. I am not sure how to adjust them.</p>
<p><strong>Code</strong></p>
<pre><code>import matplotlib.pyplot as plt
data= [4270424, 4257372, 4100352, 4100356, 4100356]
plt.figure(figsize=(10,5))
plt.plot(data, 'ko-')
plt.ylabel('Data... | 2 | 2016-10-11T01:35:12Z | 39,996,352 | <p>If there are many close datapoints on y-axis, they overlap. You can avoid showing all of them. You can show only one of too close y-ticks. But the rest can be shown on the plot itself (not on y-axis).</p>
<p>Something like that can be used:</p>
<pre><code>import matplotlib.pyplot as plt
data= [4270424, 4257372, 4... | 2 | 2016-10-12T10:29:40Z | [
"python",
"matplotlib"
] |
How to check for a range of values in a pandas dataframe? | 39,969,219 | <p>I have a pandas dataframe in which I want to check if a future value is greater than the given value for a range of future dates.
For example</p>
<pre><code>np.where((df['Close'].shift(-1) - df['Close']) > 0 , 1, 0)
</code></pre>
<p>This will give me if next value is greater than current value, I want to check... | 1 | 2016-10-11T01:35:26Z | 39,969,284 | <p>You could use <code>pd.rolling_max</code> for this, something like</p>
<pre><code>window = 5
pd.rolling_max(df['Close'], window).shift(-window) - df['Close']) > 0
</code></pre>
| 1 | 2016-10-11T01:43:43Z | [
"python",
"numpy",
"dataframe"
] |
Read a text file into a pandas dataframe or numpy array | 39,969,302 | <p>I have a file that looks like this - <a href="http://pastebin.com/u1A7v1CV" rel="nofollow">http://pastebin.com/u1A7v1CV</a></p>
<p>It's just a sample of two rows from a file.
The rows contain <code>word_label_id</code> followed by <code>freq</code>.
For example, <code>word_label_id</code> 1237 occurs 1 time in th... | 0 | 2016-10-11T01:46:17Z | 39,969,403 | <p>Ok, it's not ideal but you can use notepad++.</p>
<p>It had a "find and replace" feature and you can use \t to replace tabs as \n</p>
<p>Then you can record a macro to move any given line to the previous, skipping lines.</p>
<p>Then you can use pandas, pd.from_csv but you have to define delimiters as tabs instead... | 0 | 2016-10-11T02:00:01Z | [
"python",
"numpy",
"text",
"dataframe"
] |
Read a text file into a pandas dataframe or numpy array | 39,969,302 | <p>I have a file that looks like this - <a href="http://pastebin.com/u1A7v1CV" rel="nofollow">http://pastebin.com/u1A7v1CV</a></p>
<p>It's just a sample of two rows from a file.
The rows contain <code>word_label_id</code> followed by <code>freq</code>.
For example, <code>word_label_id</code> 1237 occurs 1 time in th... | 0 | 2016-10-11T01:46:17Z | 39,969,916 | <p>Have you tried work separately with each item?</p>
<p>For example:</p>
<p>Open document:</p>
<pre><code>with open('delimiters.txt') as r:
lines = r.readlines()
linecontent = ' '.join(lines)
</code></pre>
<p>Create a list for each item:</p>
<pre><code>result = linecontent.replace(' ', ',').split(',')
</c... | 0 | 2016-10-11T03:07:00Z | [
"python",
"numpy",
"text",
"dataframe"
] |
Read a text file into a pandas dataframe or numpy array | 39,969,302 | <p>I have a file that looks like this - <a href="http://pastebin.com/u1A7v1CV" rel="nofollow">http://pastebin.com/u1A7v1CV</a></p>
<p>It's just a sample of two rows from a file.
The rows contain <code>word_label_id</code> followed by <code>freq</code>.
For example, <code>word_label_id</code> 1237 occurs 1 time in th... | 0 | 2016-10-11T01:46:17Z | 39,989,718 | <p>Here's what I did.
This creates a dictionary containing key-value pairs
from each row. </p>
<pre><code>data = []
with open('../data/input.mat', 'r') as file:
for i, line in enumerate(file):
l = line.split()
d = dict([(k, v) for k, v in zip(l[::2], l[1::2])])
data.append(d)
</code></pre... | 0 | 2016-10-12T02:45:59Z | [
"python",
"numpy",
"text",
"dataframe"
] |
Variable referenced before assignment error in prime factorization program? | 39,969,305 | <p>I am writing some code that is supposed to find the prime factorization of numbers. The main function increments through numbers; I'm doing that because I want to use the code to conduct timing experiments. I don't mind it not being super-efficient, part of the project for me will be making it more efficient myself.... | 0 | 2016-10-11T01:46:31Z | 39,969,376 | <p>Functions in python can only access variables declared outside of function scope read-only without the global keyword.</p>
<pre><code>import math
import time
primfac=[]
def primcheck(n):
for x in xrange(2, int(n**0.5)+1):
if n % x == 0:
return False
return True
def primes(n):
sie... | 1 | 2016-10-11T01:56:46Z | [
"python"
] |
Finding average of n numbers in a list | 39,969,308 | <p>Everything is working except when the user types N to end the while loop, it doesn't go to the For Statement (this happens when you run the program, works fine in the shell and in the py).</p>
<pre><code>potato = []
count = 0
avg = 0
question = input('Finding averages, continue? Y or N: ')
while question == 'Y' an... | -3 | 2016-10-11T01:47:09Z | 39,969,387 | <p>It was breaking for me until I changed the input to raw_input. Now it exits the while loop when input is not Y:</p>
<pre><code>question = raw_input('Finding averages, continue? Y or N: ')
</code></pre>
| -3 | 2016-10-11T01:57:48Z | [
"python",
"python-3.x",
"input"
] |
How can I get values from python file to my html? | 39,969,388 | <p>I'm trying to get values from my phython file to my html. </p>
<p>Here's my form: </p>
<pre><code><div class="form-group ">
<label class="col-sm-3 col-sm-3 control-label">Direccion IP: </label>
<div class="col-sm-9">
<input type="text" class="form-control" value="{{ addre... | 1 | 2016-10-11T01:57:58Z | 39,974,135 | <p>If you're sending the data to be served up on a webpage, using the HTML template, how about something like this?</p>
<pre><code>@app.route('/test')
def showPage():
# your code here
address = # however you assign it
return render_template('test.html', address=address)
</code></pre>
<p>In order to use a ... | 0 | 2016-10-11T09:23:18Z | [
"python",
"html",
"python-2.7",
"flask",
"debian"
] |
Update Access table with value from another table via INNER JOIN | 39,969,438 | <p>I'm trying to update a column using pyodbc with data from a column in another table in the same database. I've tried:</p>
<pre><code>cursor.execute('''
UPDATE Prospect_SC_Fin_102016
SET Prospect_SC_Fin_102016.Sym_Ky=Symbol_Ref_102016.Sym_Ky
FROM Prospect_SC_Fin_102016
... | 2 | 2016-10-11T02:04:05Z | 39,981,804 | <p>For an Access database you would want to use a query of the following form:</p>
<pre class="lang-sql prettyprint-override"><code>UPDATE Prospect_SC_Fin_102016
INNER JOIN Symbol_Ref_102016
ON Prospect_SC_Fin_102016.Symbol=Symbol_Ref_102016.Symbol
SET Prospect_SC_Fin_102016.Sym_Ky=Symbol_Ref_102016.Sym_Ky
</code>... | 2 | 2016-10-11T16:08:23Z | [
"python",
"sql",
"ms-access",
"pyodbc"
] |
checking if a random value exists from previous loop | 39,969,463 | <p>I'm trying to generate a random value for each loop and save it to variable <code>minimum</code> WHILE doing a check if that number has already been generated before in one of the previous loops. </p>
<p><code>listQ</code> basically contains <strong>6 lines</strong> that were randomly chosen from a file. The lines... | 3 | 2016-10-11T02:07:39Z | 39,969,921 | <p>Keep a list of all the previous values and check each subsequent iteration.</p>
<pre><code># sets have faster "val in set?" checks than lists
# do this once, somewhere in your program
previous_vals = set()
# other stuff here, including main program loop
for x in range(0, 10):
# find a unique, new random number... | 1 | 2016-10-11T03:07:22Z | [
"python",
"loops",
"random"
] |
Sort data within group - Pandas Dataframe | 39,969,493 | <p>I have the following data frame: </p>
<pre><code> As Comb Mu(+) Name Zone f´c
33 0.37 2 6.408225 Beam_13 Final 30.0
29 0.37 2 6.408225 Beam_13 Begin 30.0
31 0.94 2 16.408225 Beam_13 Middle 30.0
15 0.54 2 9.504839 Beam_7 Final 30.0
11 0.54 ... | 1 | 2016-10-11T02:12:50Z | 39,969,891 | <p>The cleanest way is to convert the <code>Name</code> and <code>Zone</code> columns to the category type, specifying the categories and order. </p>
<pre><code>from io import StringIO
data = """
As,Comb,Mu(+),Name,Zone,f´c
33,0.37,2,6.408225,Beam_13,Final,30.0
29,0.37,2,6.408225,Beam_13,Begin,30.0
31,0.94,2,16.4082... | 3 | 2016-10-11T03:03:53Z | [
"python",
"sorting",
"pandas",
"group"
] |
Django Sanity Test Reveals 404 is not 404 | 39,969,494 | <p>I was creating sanity checks in my django tests and came across an error I had accounted for. Unfortunately my test fails when it should be successful. I am testing when a page is not there (a 404 status code). The error message and code are below. When I added quotes I received 404 is not '404'.</p>
<p>Django-1.10... | 1 | 2016-10-11T02:12:53Z | 39,969,883 | <p>You're on the right track - but <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertIs" rel="nofollow"><code>assertIs</code></a> ensures you have the same instance of an object. You just want to make sure they are <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase... | 1 | 2016-10-11T03:02:59Z | [
"python",
"django",
"unit-testing",
"automated-tests",
"http-status-code-404"
] |
Conditionally update Data Frame column | 39,969,549 | <p>I'm trying to update a column from a value of 0 to a value of 1 if certain conditions are true. Here is my code:</p>
<pre><code>df_['win'] = 0
df_.loc[df_['predicted_spread'] > df_['vegas_spread'] and df_['actual_spread'] > df_['vegas_spread'], 'win'] = 1
</code></pre>
<p>This is the error I'm getting:</p>
... | 0 | 2016-10-11T02:20:05Z | 39,970,018 | <p>Try</p>
<pre><code>df_['win'] = 0
df_.loc[df_['predicted_spread'].gt(df_['vegas_spread']) and df_['actual_spread'].gt(df_['vegas_spread']), 'win'] = 1
</code></pre>
| 1 | 2016-10-11T03:19:39Z | [
"python",
"pandas"
] |
Conditionally update Data Frame column | 39,969,549 | <p>I'm trying to update a column from a value of 0 to a value of 1 if certain conditions are true. Here is my code:</p>
<pre><code>df_['win'] = 0
df_.loc[df_['predicted_spread'] > df_['vegas_spread'] and df_['actual_spread'] > df_['vegas_spread'], 'win'] = 1
</code></pre>
<p>This is the error I'm getting:</p>
... | 0 | 2016-10-11T02:20:05Z | 39,970,090 | <p>When doing boolean indexing you need to use the logical operator for <code>and</code> which is <code>&</code>. See the doc <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">here</a> for more info</p>
<pre><code>df['win'] = 0
cond_1 = df['predicted_spread'] > ... | 1 | 2016-10-11T03:28:24Z | [
"python",
"pandas"
] |
Why is this python code producing extremely large numbers? | 39,969,632 | <p>I have a python code which is the written below. What is disturbing to me is the large number that I am getting as output in the array <code>rhot</code>. This can't be true as <code>val</code> is mostly small number and these small numbers are further suppressed by the exponential factor as in the line</p>
<pre><co... | -1 | 2016-10-11T02:28:37Z | 39,969,828 | <p>I could be wrong, but when I run your code I get small values. Could it be that you're seeing things like <code>-3.53107108e-310</code> and confusing them for large numbers?
That's: </p>
<pre><code>-0.0 ... <307 '0's> ... 0353107108
</code></pre>
<p>See below for the full output:</p>
<pre><code>[[[ 1.2749... | 0 | 2016-10-11T02:55:15Z | [
"python",
"loops",
"random",
"iteration"
] |
How do I delete a substring from a string without using .replace()? | 39,969,686 | <p>For my CS class we try to focus on creating and using algorithms instead of just using built in methods. For this program I have to remove a substring from a string (if the substring is in the string), but I can't use .replace(). I can't figure out how to do this without 'hardcoding' and not coming up with an algori... | -2 | 2016-10-11T02:34:50Z | 39,969,868 | <p>You can do that:</p>
<pre><code>myString = myString[0:myString.index(mySubstring)] + myString[myString.index(mySubstring)+len(mySubstring):]
</code></pre>
<p>But of course it will replace just the first occurrence. So if mySubstring is <em>eph</em> and myString is <em>cephatelephant</em> and you would like to remo... | 0 | 2016-10-11T03:00:14Z | [
"python",
"python-2.7"
] |
How to process input and output shape for keras LSTM | 39,969,717 | <p>I am learning about RNN and I wrote this simple LSTM model in keras (theano) using a sample dataset generated using sklearn.</p>
<pre><code>from sklearn.datasets import make_regression
from keras.models import Sequential
from keras.layers import Dense,Activation,LSTM
#creating sample dataset
X,Y=make_regression(10... | 0 | 2016-10-11T02:39:27Z | 39,970,734 | <p>If I'm correct, then LSTM expects a 3D input.</p>
<pre><code>X = np.random.random((100, 10, 64))
y = np.random.random((100, 2))
model = Sequential()
model.add(LSTM(32, input_shape=(10, 64)))
model.add(Dense(2))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(X, Y, nb_epoch=1, batch_size=32)
... | 1 | 2016-10-11T04:57:43Z | [
"python",
"theano",
"keras"
] |
Exponentiation Recursive | 39,969,737 | <p>I am learning this Exponentiation Recursive algorithm, it works well.
But I don't understand why this works?
Because I expect that always returns 1,1,1...if <code>n</code> is even because a doesn't multiply in the <code>return</code>.<br>
When I try <code>recPower(3,2)</code>, and print the factor step by step, it w... | -2 | 2016-10-11T02:42:48Z | 39,969,808 | <p>Just follow it step by step:</p>
<pre><code>recPower(3, 2)
</code></pre>
<p><code>n != 0</code> so go down the else branch:</p>
<pre><code>factor = recPower(3, 2//2)
</code></pre>
<p>Which is:</p>
<pre><code>recPower(3, 1)
</code></pre>
<p>In this recursive step <code>n != 0</code> we follow the first else bra... | 0 | 2016-10-11T02:52:39Z | [
"python",
"python-3.x",
"computer-science"
] |
digest of a pandas Index | 39,969,773 | <p>I would like to <strong>efficiently</strong> compute a digest of a Pandas DataFrame that uniquely and reproducibly identifies its content (for versioning purposes). Assume for now that I don't worry about endianness, dtypes, types of the index nor columns. Also assume that both index and columns are already sorted... | 1 | 2016-10-11T02:47:51Z | 39,969,817 | <p>Sometimes the solution is right under our nose...</p>
<pre><code>from sklearn.externals import joblib
%%time
joblib.hash(df, hash_name='sha1')
>>> consistent value that depends on values and axes
Wall time: 1.66 s (for the (5000000,12) DataFrame mentioned above)
</code></pre>
| 1 | 2016-10-11T02:54:07Z | [
"python",
"pandas",
"digest"
] |
More memory efficient way of making a dictionary? | 39,969,798 | <p>VERY sorry for the vagueness, but I don't actually know what part of what I'm doing is inefficient. </p>
<p>I've made a program that takes a list of positive integers (example*):</p>
<pre><code>[1, 1, 3, 5, 16, 2, 4, 6, 6, 8, 9, 24, 200,]
</code></pre>
<p>*the real lists can be up to 2000 in length and the elemen... | 3 | 2016-10-11T02:50:40Z | 39,969,874 | <p>Well, you could <em>start</em> by not unnecessarily duplicating information.</p>
<p>Storing full tuples (number and index) for each multiple is inefficient when you already have that information available.</p>
<p>For example, rather than:</p>
<pre><code>(3, 2): [(16, 4), (6, 7), (6, 8), (9, 10), (24, 11)]
</code>... | 2 | 2016-10-11T03:01:22Z | [
"python",
"algorithm",
"dictionary"
] |
More memory efficient way of making a dictionary? | 39,969,798 | <p>VERY sorry for the vagueness, but I don't actually know what part of what I'm doing is inefficient. </p>
<p>I've made a program that takes a list of positive integers (example*):</p>
<pre><code>[1, 1, 3, 5, 16, 2, 4, 6, 6, 8, 9, 24, 200,]
</code></pre>
<p>*the real lists can be up to 2000 in length and the elemen... | 3 | 2016-10-11T02:50:40Z | 39,970,466 | <p>You rebuild tuples in places like <code>pair = (y, y2 + x2 + 1)</code> and <code>num_dict[(x, x2)].append(pair)</code> when you could build a canonical set of tuples early on and then just put references in the containers. I cobbled up a 2000 item test my machine that works. I have python 3.4 64 bit with a relativel... | 2 | 2016-10-11T04:21:57Z | [
"python",
"algorithm",
"dictionary"
] |
Import Eve, but upon running run.py, says there is no module named eve | 39,969,864 | <p>I have recently begun looking at Eve. </p>
<p>I have read the Eve <a href="http://python-eve.org/install.html" rel="nofollow">install guide</a> and imported it successfully. </p>
<p>Then, I tried the <a href="http://python-eve.org/quickstart.html" rel="nofollow">quick start guide</a>, and made a few changes to the... | 1 | 2016-10-11T02:59:34Z | 39,971,100 | <p>Looks like Eve is not installed (or you are not in the correct virtual environment). A <code>pip freeze</code> will tell you which modules are currently installed. If Eve is not listed, try <code>pip install eve</code>.</p>
| 0 | 2016-10-11T05:42:57Z | [
"python",
"mongodb",
"eve"
] |
Import Eve, but upon running run.py, says there is no module named eve | 39,969,864 | <p>I have recently begun looking at Eve. </p>
<p>I have read the Eve <a href="http://python-eve.org/install.html" rel="nofollow">install guide</a> and imported it successfully. </p>
<p>Then, I tried the <a href="http://python-eve.org/quickstart.html" rel="nofollow">quick start guide</a>, and made a few changes to the... | 1 | 2016-10-11T02:59:34Z | 40,002,657 | <p>I figured it out. I was not running the command </p>
<pre><code>python run.py
</code></pre>
<p>inside the virtual environment. I have now, and it works.</p>
| 0 | 2016-10-12T15:33:59Z | [
"python",
"mongodb",
"eve"
] |
ValueError: math domain error While Using Logarithms | 39,969,882 | <p>I am currently working on a code to find a value C which I will then compare against other parameters. However, whenever I try to run my code I receive this error: ValueError: math domain error. I am unsure why I am receiving this error, though I think it's how I setup my equation. Maybe there is a better way to wri... | 0 | 2016-10-11T03:02:28Z | 39,970,900 | <p>Try to check if the value inside the log is not a negative value as negative value to a log function is a domain error.</p>
<p>Hope this helps.</p>
| 0 | 2016-10-11T05:16:57Z | [
"python"
] |
Python removal of items after iteration | 39,969,896 | <p>Why is my code not working? I can't figure it out</p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
myList = []
for i in match_list:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
match_list.remove(j)
</code></pre>
<p>I ... | 0 | 2016-10-11T03:04:42Z | 39,969,923 | <p>You want: </p>
<pre><code>i.remove(j)
</code></pre>
<p>match_list is a list of lists</p>
| 2 | 2016-10-11T03:07:40Z | [
"python"
] |
Python removal of items after iteration | 39,969,896 | <p>Why is my code not working? I can't figure it out</p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
myList = []
for i in match_list:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
match_list.remove(j)
</code></pre>
<p>I ... | 0 | 2016-10-11T03:04:42Z | 39,970,028 | <pre><code>list_of_lists = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
first_list = ['i', 'am', 'an', 'old', 'man']
myList = []
for current_list in list_of_lists:
for item in current_list:
for word in first_list:
if item in word:
myList.append(item)
list_of_lists.r... | 0 | 2016-10-11T03:20:59Z | [
"python"
] |
Python removal of items after iteration | 39,969,896 | <p>Why is my code not working? I can't figure it out</p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
myList = []
for i in match_list:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
match_list.remove(j)
</code></pre>
<p>I ... | 0 | 2016-10-11T03:04:42Z | 39,970,191 | <p>Try this:</p>
<p><em>btw: you used <code>matchList</code> and <code>match_list</code> in your post. I corrected that for my answer to make it consistent.</em></p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c']]
myList = []
first_list = ['i', 'am', 'an', 'old', 'man']
for i in matchList:
for j in i:
... | 0 | 2016-10-11T03:41:41Z | [
"python"
] |
Python removal of items after iteration | 39,969,896 | <p>Why is my code not working? I can't figure it out</p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c'] ... ]]
myList = []
for i in match_list:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
match_list.remove(j)
</code></pre>
<p>I ... | 0 | 2016-10-11T03:04:42Z | 39,970,296 | <p>You could try a list comprehesion after iteration.</p>
<pre><code>matchList = [['g', 'h', 'i'], ['a', 'b', 'c']]
first_list = ['i', 'am', 'an', 'old', 'man']
myList = []
for i in matchList:
for j in i:
for word in first_list:
if j in word:
myList.append(j)
# Remove items fr... | 0 | 2016-10-11T03:57:55Z | [
"python"
] |
Python - KeyboardInterrupt or RuntimeError implementation | 39,970,040 | <p>New to python and programming. I have a program consist of several classes, module and functions. the program runs from a main class which calls several modules and function</p>
<p>My question is how to implement keyboardinterrupt if the user wants to terminate a running program at any point. Do I need to implement... | 0 | 2016-10-11T03:22:29Z | 39,970,073 | <p>You could do something like :</p>
<pre><code>try:
...
except KeyboardInterrupt:
Do something
</code></pre>
| 0 | 2016-10-11T03:26:19Z | [
"python"
] |
Python - KeyboardInterrupt or RuntimeError implementation | 39,970,040 | <p>New to python and programming. I have a program consist of several classes, module and functions. the program runs from a main class which calls several modules and function</p>
<p>My question is how to implement keyboardinterrupt if the user wants to terminate a running program at any point. Do I need to implement... | 0 | 2016-10-11T03:22:29Z | 39,970,215 | <p>Exceptions flow up the stack, terminating each function execution block as it goes. If all you want is a nice message, catch it at the top, in your main. This script has two mains - one that catches, one that doesnt. As you can see, the non-catcher shows a stack trace of where each function broke execution but its k... | 0 | 2016-10-11T03:45:40Z | [
"python"
] |
ValueError for comparison of np.arrays | 39,970,099 | <p>I have a list of lists of np.arrays, representing islands > island > geodesic point on the island.</p>
<p>I'm trying to use:</p>
<pre><code>if not groups:
createNewGroup(point)
else:
for group in groups:
if point in group:
continue
else:
createNewGroup(point)
</code></pre>
... | 0 | 2016-10-11T03:29:21Z | 39,972,291 | <p>This error arises when a boolean array is used in a scalar context, such as an <code>if</code> statement. Or maybe in the <code>in</code> part of the expression.</p>
<p>Is <code>point</code> an array, and <code>group</code> a list of arrays?</p>
<p>In general <code>in</code> is not a good test when working with ... | 0 | 2016-10-11T07:27:33Z | [
"python",
"numpy"
] |
Codec error when writing Python dictionary into CSV | 39,970,213 | <p>Below is a sample of my dictionary:</p>
<pre><code>dict = {'Croatia': '191', 'Cuba': '192', 'Curaçao': '531',
'Cyprus': '196', 'Czechia': '203', 'Czechoslovakia': '200',
"Côte d'Ivoire": '384', "Dem. People's Rep. of Korea": '408',
'Dem. Rep. of the Congo': '180', 'Denmark': '208'}
</co... | 0 | 2016-10-11T03:45:35Z | 39,970,241 | <p><a href="https://docs.python.org/2/library/csv.html" rel="nofollow">The docs</a> cover how to handle encoding. Trying to encode individual elements does not, as you have seen, work out well.</p>
| 0 | 2016-10-11T03:49:54Z | [
"python",
"csv",
"dictionary"
] |
Codec error when writing Python dictionary into CSV | 39,970,213 | <p>Below is a sample of my dictionary:</p>
<pre><code>dict = {'Croatia': '191', 'Cuba': '192', 'Curaçao': '531',
'Cyprus': '196', 'Czechia': '203', 'Czechoslovakia': '200',
"Côte d'Ivoire": '384', "Dem. People's Rep. of Korea": '408',
'Dem. Rep. of the Congo': '180', 'Denmark': '208'}
</co... | 0 | 2016-10-11T03:45:35Z | 39,970,270 | <p>Well, I recommend you to use <code>Pandas</code> for your purpose.</p>
<pre><code>import pandas as pd
country_name = dict.keys()
cnt = dict.values()
df = pd.DataFrame({'countryname':country_name,'count':cnt})
df.to_csv('result.csv',sep=',',encoding='utf-8')
</code></pre>
| 0 | 2016-10-11T03:53:25Z | [
"python",
"csv",
"dictionary"
] |
Python3 parse XML into dictionary | 39,970,288 | <p>It seems the original post was too vague, so I'm narrowing down the focus of this post. I have an XML file from which I want to pull values from specific branches, and I am having difficulty in understanding how to effectively navigate the XML paths. Consider the XML file below. There are several <code><mi>... | -1 | 2016-10-11T03:56:47Z | 39,982,781 | <p>Starting with:</p>
<pre><code>import xml.etree.cElementTree as ET # or with try/except as per your edit
xml_data1 = """<?xml version="1.0"?> and the rest of your XML here"""
tree = ET.fromstring(xml_data) # or `ET.parse(<filename>)`
xml_dict = {}
</code></pre>
<p>Now <code>tree</code> has the xml tr... | 1 | 2016-10-11T17:05:03Z | [
"python",
"xml",
"elementtree"
] |
why it is skipping the whole for loop? | 39,970,333 | <p>I have created a website scraper which will scrape all info from yellow pages (for educational purposes) </p>
<pre><code>def actual_yellow_pages_scrape(link,no,dir,gui,sel,ypfind,terminal,user,password,port,type):
print(link,no,dir,gui,sel,ypfind,terminal,user,password,port,type)
r = requests.get(link,headers=REQUE... | -2 | 2016-10-11T04:02:27Z | 39,971,098 | <p>Answer has been found,</p>
<p>I used a text visulaizer to find what is in "r.content" I soupified it and got a clean HTML and gone through the HTML file and finally found that the browser is unsupported so I removed the requests header and ran the code finally got what I wanted</p>
| 0 | 2016-10-11T05:42:43Z | [
"python"
] |
importing issues between modules | 39,970,364 | <pre><code>|--------FlaskApp
|----------------FlaskApp
|----------------__init__.py
|----------------view.py
|----------------models.py
|----------------db_create.py
|-----------------------static
|-----------------------templates
|-----------------------venv
|-----------------------__init__.py
|----------------flaskap... | -1 | 2016-10-11T04:07:58Z | 39,971,777 | <p>This is actually the most painful moment for a Flask learner. Basically, your <code>FlaskApp</code> is dependent on <code>FlaskApp.main</code> then <code>FlaskApp.models</code> and then back to <code>FlaskApp</code> which create a perfect case of circular dependency.</p>
<p>Here's the way which I think is elegant a... | 1 | 2016-10-11T06:49:06Z | [
"python",
"flask",
"flask-sqlalchemy",
"python-3.5"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.