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 |
|---|---|---|---|---|---|---|---|---|---|
Python, 'NoneType' object has no attribute 'get_text' | 39,982,524 | <p>The output says: </p>
<blockquote>
<p>'NoneType' object has no attribute 'get_text'</p>
</blockquote>
<p>How can I fix this?</p>
<pre><code>response = requests.get("https://www.exar.com/careers")
soup = BeautifulSoup(response.text, "html.parser")
data = []
table_main = soup.find_all("table", class_="table")
... | -4 | 2016-10-11T16:50:05Z | 39,982,552 | <p>Not sure why are you trying to find <code>td</code>s inside <code>td</code>s here:</p>
<pre><code>title = tds[0].find("td").get_text().strip()
location = tds[1].find("td").get_text().strip()
</code></pre>
<p>Replace it with just:</p>
<pre><code>title = tds[0].get_text().strip()
location = tds[1].get_text().strip(... | 2 | 2016-10-11T16:51:50Z | [
"python",
"beautifulsoup"
] |
how to change all the words in a sentence into a number, and also be able to change it back | 39,982,553 | <p>OK, so I have to make a program in python, that is able to make a number for each word in a sentence, and if the word is the same it will have the same number, but I have to be able to change it back to the original sentence as well.</p>
<p>For example, "today the cat sat on the mat" would be changed into 0 1 2 3 4... | -5 | 2016-10-11T16:51:51Z | 39,982,837 | <p>This sounds a lot like a school assignment. Since from my experience I can say that the best practice is to do it yourself, I'd suggest only looking at the hints I give first, and if you're really stuck, look at the code.</p>
<p>Hint 1: </p>
<blockquote class="spoiler">
<p> Separate the sentence into a list of w... | 1 | 2016-10-11T17:09:25Z | [
"python",
"python-3.x",
"variables",
"text",
"sentence"
] |
Getting key values from a dictionary | 39,982,612 | <p>I have a dictionary with indices as keys and timestamps as values. I wanted to get the keys for whose values there is a overlap.</p>
<p>ex:</p>
<pre><code>{1: 19-13-30
19-13-32
19-13-33
.
.
19-13-55,
2: 19-13-25
19-13-26
19-13-27
.
.
19-13-35,
3:19-13-10
19-13-31
... | 0 | 2016-10-11T16:55:24Z | 39,982,745 | <p>In keeping with your code, this should be a minimal modification:</p>
<pre><code>intervals= {1:[1,2], 2:[2,3], 3:[4,5], 4:[6,8], 5:[6.5,7]}
overlapping = [ [i,j,x,y] for i,x in intervals.iteritems() for j,y in intervals.iteritems() if x is not y and x[1]>y[0] and x[0]<y[0] ]
for x in overlapping:
print '{... | 0 | 2016-10-11T17:02:42Z | [
"python",
"dictionary"
] |
Getting key values from a dictionary | 39,982,612 | <p>I have a dictionary with indices as keys and timestamps as values. I wanted to get the keys for whose values there is a overlap.</p>
<p>ex:</p>
<pre><code>{1: 19-13-30
19-13-32
19-13-33
.
.
19-13-55,
2: 19-13-25
19-13-26
19-13-27
.
.
19-13-35,
3:19-13-10
19-13-31
... | 0 | 2016-10-11T16:55:24Z | 39,982,773 | <p>Instead of iterating over the intervals, you can iterate over the values (i.e. the positions in your interval list). Something like</p>
<pre><code>keys = range(len(intervals))
overlapping = [ [x,y] for x in keys for y in keys if x is not y and intervals[x][1]>intervals[y][0] and intervals[x][0]<intervals[y][0... | 0 | 2016-10-11T17:04:38Z | [
"python",
"dictionary"
] |
python try except yield combination | 39,982,763 | <p>I use function <code>f</code> to create generator but sometimes it can raise error. I would like two things to happen for the main code</p>
<ol>
<li>The <code>for</code> loop in the main block continues after catching the error</li>
<li>In the <code>except</code>, print out the index that generates the error (in re... | 2 | 2016-10-11T17:03:49Z | 39,982,860 | <p>You will have to catch the exception <em>inside</em> your generator if you want its loop to continue running. Here is a working example:</p>
<pre><code>def f(n):
for i in xrange(n):
try:
if i == 3:
raise ValueError('hit 3')
yield i
except ValueError:
... | 3 | 2016-10-11T17:10:32Z | [
"python",
"try-catch",
"yield",
"except"
] |
python try except yield combination | 39,982,763 | <p>I use function <code>f</code> to create generator but sometimes it can raise error. I would like two things to happen for the main code</p>
<ol>
<li>The <code>for</code> loop in the main block continues after catching the error</li>
<li>In the <code>except</code>, print out the index that generates the error (in re... | 2 | 2016-10-11T17:03:49Z | 39,983,439 | <p>As of OP clarifications, he wants to continue the <strong>outside</strong> main for loop in case of error inside the generator, showing at which index the error occurred.</p>
<p>An answer by brianpck takes the approach of modifying the generator so that it prints the error. This way the main loop doesn't know an er... | 1 | 2016-10-11T17:46:19Z | [
"python",
"try-catch",
"yield",
"except"
] |
python try except yield combination | 39,982,763 | <p>I use function <code>f</code> to create generator but sometimes it can raise error. I would like two things to happen for the main code</p>
<ol>
<li>The <code>for</code> loop in the main block continues after catching the error</li>
<li>In the <code>except</code>, print out the index that generates the error (in re... | 2 | 2016-10-11T17:03:49Z | 39,983,724 | <p>I suspect that, in general, you want to be able to catch values that result in error conditions. Without halting the loop inside the generator. Here's another approach that includes a Boolean in the result of the generator (as a 2-tuple) that indicates whether the calculation could be accomplished successfully.</p>
... | 1 | 2016-10-11T18:02:54Z | [
"python",
"try-catch",
"yield",
"except"
] |
Web Scraping from a Website with a Static URL | 39,982,772 | <p>So I am trying to extract postal code information from the <a href="https://www.canadapost.ca/cpo/mc/personal/postalcode/fpc.jsf?LOCALE=en" rel="nofollow">Canada Post Website</a>. The issue I am having here is the URL remains static regardless of what address you enter when trying to find a postal code. For instance... | -2 | 2016-10-11T17:04:34Z | 39,982,856 | <p>Since you need to perform actions prior to scraping, you need to use a headless browser like <a href="http://phantomjs.org" rel="nofollow">phantomjs</a>. It's a bit more challenging than basic scraping, but it will allow you to type in addresses programmatically and then scrape the resulting data of the page that is... | 0 | 2016-10-11T17:10:21Z | [
"python",
"html",
"url",
"static",
"web-scraping"
] |
Web Scraping from a Website with a Static URL | 39,982,772 | <p>So I am trying to extract postal code information from the <a href="https://www.canadapost.ca/cpo/mc/personal/postalcode/fpc.jsf?LOCALE=en" rel="nofollow">Canada Post Website</a>. The issue I am having here is the URL remains static regardless of what address you enter when trying to find a postal code. For instance... | -2 | 2016-10-11T17:04:34Z | 39,982,891 | <p>You could write a wrapper using something like <a href="http://scraping.pro/selenium-ide-and-web-scraping/" rel="nofollow">Selenium</a> to interact with the page dynamically. </p>
<p>Alternatively, you may want to look into their developer API, which should allow you to provide an address and get back a code (as we... | 1 | 2016-10-11T17:12:07Z | [
"python",
"html",
"url",
"static",
"web-scraping"
] |
Recursion in depth (Python) | 39,982,813 | <p>Check the following code:</p>
<pre><code>>>> def fib(x):
... if x == 0 or x == 1:
... return 1
... else:
... return fib(x-1) + fib(x-2)
>>> print(fib(4))
</code></pre>
<p>According to the comments in the SoloLearn Python tutorial (for Recursion), the code works like this:</p>... | 2 | 2016-10-11T17:07:17Z | 39,982,915 | <p>@MorganThrapp is correct. More specifically, the base case of the recursive function <code>fib</code> is:</p>
<pre><code>if x==0 or x==1:
return 1
</code></pre>
<p>This clause is triggered when <code>fib(1)</code> or <code>fib(0)</code> is called. In programming parlance, the function <em>evaluates</em> to its... | 2 | 2016-10-11T17:13:43Z | [
"python",
"recursion",
"return"
] |
Recursion in depth (Python) | 39,982,813 | <p>Check the following code:</p>
<pre><code>>>> def fib(x):
... if x == 0 or x == 1:
... return 1
... else:
... return fib(x-1) + fib(x-2)
>>> print(fib(4))
</code></pre>
<p>According to the comments in the SoloLearn Python tutorial (for Recursion), the code works like this:</p>... | 2 | 2016-10-11T17:07:17Z | 39,983,008 | <p>I believe the description of how the code works is misleading, since it seems to show that not every values are evaluated when going from one line to the next. If we replace everything by the functions it calls (or the value it returns) on the next line, and put parentheses like on your example, we get the following... | 3 | 2016-10-11T17:20:44Z | [
"python",
"recursion",
"return"
] |
Recursion in depth (Python) | 39,982,813 | <p>Check the following code:</p>
<pre><code>>>> def fib(x):
... if x == 0 or x == 1:
... return 1
... else:
... return fib(x-1) + fib(x-2)
>>> print(fib(4))
</code></pre>
<p>According to the comments in the SoloLearn Python tutorial (for Recursion), the code works like this:</p>... | 2 | 2016-10-11T17:07:17Z | 39,984,186 | <p>this is a double recursive function, so its call result a tree structure of calls with the base case of fib(1) and fib(0)</p>
<pre><code>fib(4) = fib(3) + fib(2)
/ \ / \
fib(4) = ( fib(2) + fib(1) ) + ( fib(1) + fib(... | 3 | 2016-10-11T18:27:40Z | [
"python",
"recursion",
"return"
] |
Using xpath to loop over all <h2> tags within a speciifc div | 39,982,929 | <p>I am trying to loop over every <code><h2></code> tag (get the text of it) that is inside div's with the <code>id="somediv"</code> using this code:</p>
<pre><code>for k,div1 in enumerate(tree.xpath('//div[@id="someid"]')):
print div1.xpath('.//h2['+str(k+1)+']/text()')
</code></pre>
<p>but it doesn't work. ... | 1 | 2016-10-11T17:14:53Z | 39,983,553 | <p><code>.//</code> will continue the search down the tree. A list of h2 text nodes subordinate to your div is just</p>
<pre><code>tree.xpath('//div[@id="someid"]/.//h2/text()'))
</code></pre>
| 1 | 2016-10-11T17:52:48Z | [
"python",
"xpath"
] |
Updating python IDLE to 3.5 | 39,982,981 | <p>I currently use python 3.2.3 in the IDLE (which I open from 'python 3', 'programming', 'menu') on my Raspberry Pi.
In an attempt to solve <a href="https://github.com/Zulko/moviepy/issues/322" rel="nofollow">this problem</a> I am trying to get my IDLE to run python 3.5.</p>
<p>I have got Python 3.5 to run if I enter... | 0 | 2016-10-11T17:19:12Z | 39,983,074 | <p>This is because Raspbian (or whatever OS you're using) depends on those pre-installed versions of Python and later versions are not available via <code>apt-get</code> for good reason. </p>
<p>Edit:</p>
<p>I see you've already got Python 3.5 installed. To get IDLE to use the appropriate version, you need to set IDL... | 0 | 2016-10-11T17:24:18Z | [
"python",
"linux",
"python-3.x",
"raspberry-pi"
] |
Python altering list item in iteration | 39,983,007 | <p>I am trying to get this python code to get rid of punctuation marks associated with words and count the unique words. For some reason it's still counting both "hello." and "hello". Any help would be most appreciated. </p>
<pre><code>def word_distribution(words):
word_dict = {}
words = words.... | 0 | 2016-10-11T17:20:39Z | 39,983,277 | <p>I don't know why you're adding 1 to count.</p>
<pre><code>def word_distribution(words):
word_dict = {}
words = words.lower().split()
for word in words:
if ord('a') <= ord(word[-1]) <= ord('z'):
pass
elif ord('A') <= ord(word[-1]) <= ord('Z'... | 1 | 2016-10-11T17:36:55Z | [
"python"
] |
Python altering list item in iteration | 39,983,007 | <p>I am trying to get this python code to get rid of punctuation marks associated with words and count the unique words. For some reason it's still counting both "hello." and "hello". Any help would be most appreciated. </p>
<pre><code>def word_distribution(words):
word_dict = {}
words = words.... | 0 | 2016-10-11T17:20:39Z | 39,983,294 | <p>You are making it too complicated, as Sohier Dane mentioned in the comments you can make use of the other post to remove punctuation and simplify the script to:</p>
<pre><code>import string
def word_distribution(words):
words = words.translate(None, string.punctuation).lower()
d = {}
for w in words.spli... | 1 | 2016-10-11T17:37:57Z | [
"python"
] |
Python altering list item in iteration | 39,983,007 | <p>I am trying to get this python code to get rid of punctuation marks associated with words and count the unique words. For some reason it's still counting both "hello." and "hello". Any help would be most appreciated. </p>
<pre><code>def word_distribution(words):
word_dict = {}
words = words.... | 0 | 2016-10-11T17:20:39Z | 39,983,304 | <p>There are certainly better way of achieving what you are trying to do but this answer fixes your code.</p>
<p>Strings are immutable and lists are mutable. Nowhere in your code you were modifying the list. and <code>words[-1]</code> wont have any impact because you were not re assigning it and string are immutable</... | 1 | 2016-10-11T17:38:37Z | [
"python"
] |
N/A in integer field | 39,983,051 | <p>I am importing Excel into postgreSQL using Python. Below is the field I am having problem with. Actual Sales Price had been an integer data type value which for a while but now this column contains an N/A value which is blowing up my Python script. Is there anything I can add to this script which will tell it to bri... | 0 | 2016-10-11T17:22:53Z | 39,983,115 | <pre><code>Actual_Sales_Price = None if not sheet.cell(r,61).value else sheet.cell(r,61).value
try:
float(Actual_Sales_Price)
except (ValueError, TypeError):
Actual_Sales_Price = None
</code></pre>
<p>If python fails to convert your actual sales price into a float (presumably, because it's not a number), we c... | 0 | 2016-10-11T17:26:37Z | [
"python",
"postgresql"
] |
Change .so, .pyc, and .py search order in python search path | 39,983,095 | <p>According to this post, python prioritizes .so and .pyc before .py files when searching for modules. Is there some way to make .py searched first?</p>
<p><a href="http://stackoverflow.com/questions/6584457/what-is-the-precedence-of-python-compiled-files-in-imports">What is the precedence of python compiled files in... | 0 | 2016-10-11T17:25:14Z | 39,983,250 | <p>You shouldn't be using the same package installations with two different version of the python interpreter, since they're bytecode won't be compatible. You should install the packages to each python installation separately.</p>
<p>In Python 3, this is less of an issue, since the interpreter version is hashed into ... | 0 | 2016-10-11T17:35:40Z | [
"python",
"import"
] |
python regex seperated elements of a string | 39,983,143 | <p><strong>Though I'd just update the start of this question for people that come accross it in future. Regex was not the optimal solution for my particular problem, but trying to regex complicated and separated patterns (my logic from the start) in one go wasn't ideal.
The answer to the question as stated would be to ... | 1 | 2016-10-11T17:28:44Z | 39,983,968 | <p>You have two parts in your data file. One is compact table:</p>
<pre><code> 1 3izo_F Fiber; pentameric pento 98.1 2.7E-09 7.3E-14 107.6 0.0 65 93-160 104-168 (581)
2 3izo_F Fiber; pentameric pento 97.6 1.3E-07 3.4E-12 95.6 0.0 156 156-317 210-388 (581)
3 1ocy_A Bacteriophage T4 short 97.6 ... | 1 | 2016-10-11T18:16:28Z | [
"python",
"regex",
"string"
] |
python regex seperated elements of a string | 39,983,143 | <p><strong>Though I'd just update the start of this question for people that come accross it in future. Regex was not the optimal solution for my particular problem, but trying to regex complicated and separated patterns (my logic from the start) in one go wasn't ideal.
The answer to the question as stated would be to ... | 1 | 2016-10-11T17:28:44Z | 40,001,898 | <p>It is possible to use <code>pandas.read_fwf</code> to read the tabular portion, but because your table headers are malformed (i.e. sometimes a space is part of a variable name, as in <code>Query HMM</code>, and sometimes it separates variable names, as in <code>SS</code> and <code>Cols</code>) you are going to have ... | 1 | 2016-10-12T14:58:57Z | [
"python",
"regex",
"string"
] |
Can anyone tell me what error msg "line 1182 in parse" means when I'm trying to parse and xml in python | 39,983,159 | <p>This is the code that results in an error message:</p>
<pre><code>import urllib
import xml.etree.ElementTree as ET
url = raw_input('Enter URL:')
urlhandle = urllib.urlopen(url)
data = urlhandle.read()
tree = ET.parse(data)
</code></pre>
<p>The error:</p>
<p><img src="https://i.stack.imgur.com/eMKS2.png" alt="... | -1 | 2016-10-11T17:30:05Z | 39,983,211 | <p>The error message indicates that your code is trying to open a file, who's name is stored in the variable source. </p>
<p>It's failing to open that file (IOError) because the variable source contains a bunch of XML, not a file name. </p>
| 0 | 2016-10-11T17:33:15Z | [
"python",
"xml",
"parsing",
"url",
"elementtree"
] |
Can anyone tell me what error msg "line 1182 in parse" means when I'm trying to parse and xml in python | 39,983,159 | <p>This is the code that results in an error message:</p>
<pre><code>import urllib
import xml.etree.ElementTree as ET
url = raw_input('Enter URL:')
urlhandle = urllib.urlopen(url)
data = urlhandle.read()
tree = ET.parse(data)
</code></pre>
<p>The error:</p>
<p><img src="https://i.stack.imgur.com/eMKS2.png" alt="... | -1 | 2016-10-11T17:30:05Z | 39,984,349 | <p><code>data</code> is a reference to the XML content as a string, but the <a href="https://docs.python.org/2.7/library/xml.etree.elementtree.html#xml.etree.ElementTree.parse" rel="nofollow"><code>parse()</code></a> function expects a filename or <a href="https://docs.python.org/2/glossary.html#term-file-object" rel="... | 0 | 2016-10-11T18:36:53Z | [
"python",
"xml",
"parsing",
"url",
"elementtree"
] |
Can anyone tell me what error msg "line 1182 in parse" means when I'm trying to parse and xml in python | 39,983,159 | <p>This is the code that results in an error message:</p>
<pre><code>import urllib
import xml.etree.ElementTree as ET
url = raw_input('Enter URL:')
urlhandle = urllib.urlopen(url)
data = urlhandle.read()
tree = ET.parse(data)
</code></pre>
<p>The error:</p>
<p><img src="https://i.stack.imgur.com/eMKS2.png" alt="... | -1 | 2016-10-11T17:30:05Z | 39,984,354 | <p>Consider using ElementTree's <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.fromstring" rel="nofollow"><code>fromstring()</code></a>:</p>
<pre><code>import urllib
import xml.etree.ElementTree as ET
url = raw_input('Enter URL:')
# http://feeds.bbci.co.uk/news/rss.xml?edi... | 0 | 2016-10-11T18:37:01Z | [
"python",
"xml",
"parsing",
"url",
"elementtree"
] |
QThread exception management and thread race | 39,983,224 | <p>I have a GUI (PySide) application that uses QThread. I have a signal in my QThread that is emitted when an exception occurs so that I can handle the exception in the main thread. However, the rest of the function starting the thread is still executed. I tried the <code>wait</code> function to block the execution but... | 0 | 2016-10-11T17:33:54Z | 39,988,499 | <p>In your <code>test</code> function, the sequence of events is this:</p>
<ol>
<li>The thread starts</li>
<li>The thread's <code>run</code> method is called</li>
<li>The <code>task_failed</code> signal is emitted <em>asynchronously</em> (i.e. it's posted to the receiver's event queue)</li>
<li>The thread's <code>run<... | 1 | 2016-10-11T23:52:25Z | [
"python",
"multithreading",
"qt",
"exception-handling",
"pyside"
] |
django left join with where clause subexpression | 39,983,237 | <p>I'm currently trying to find a way to do something with Django's (v1.10) ORM that I feel should be possible but I'm struggling to understand how to apply the documented methods to solve my problem.</p>
<p><strong>Edit:</strong> So here's the sql that I've hacked together to return the data that I'd like from the <c... | 1 | 2016-10-11T17:34:55Z | 39,983,720 | <p>Hope I correctly understood your problem. Try this:</p>
<pre><code>votes = Votes.objects.filter(voter__username='django').select_related('bill')
</code></pre>
<p>You can use this. But I think you do not need <code>select_related</code> in this case.</p>
<pre><code>bills_for_user = Bill.objects.filter(votes__voter... | 0 | 2016-10-11T18:02:35Z | [
"python",
"django",
"join",
"django-queryset",
"where-clause"
] |
Extracting value of an element using Selenium | 39,983,324 | <p>I'm using Python 3 and I need help with extracting the value of an element in a HTML code. The relevant part of the webpage code looks like this:</p>
<pre><code><span class="ng-isolate-scope" star-rating="4.61" size="22">
</code></pre>
<p>I'm currently using Selenium and the get_attribute function, but I hav... | -1 | 2016-10-11T17:39:57Z | 39,983,385 | <p>Get the <code>star-rating</code> attribute instead of a <code>value</code>:</p>
<pre><code>temp = y.get_attribute("star-rating"))
</code></pre>
<p>Note that you don't have to call <code>str()</code> on the result of <code>get_attribute()</code> - you'll get the attribute value as a string.</p>
<p>You can also imp... | 2 | 2016-10-11T17:43:12Z | [
"python",
"selenium",
"getattribute"
] |
reading from csv file in shell scripting | 39,983,349 | <p>I am running a script run.sh.
The script is executed as follows. $./run.sh read.csv
The contents of the script are as follows.</p>
<pre><code> tail -n +2 $1 | while IFS="," read -r A B C D E F;
do
python test.py ${A} ${B} ${C} ${D} ${E} ${F}
done
</code></pre>
<p>My question is "If i need to pas... | 0 | 2016-10-11T17:41:06Z | 39,983,406 | <p>Positional parameters is what you are after. This is how you can do it:</p>
<pre><code>tail -n +2 $4 | while IFS="," read -r A B C D E F;##note now you would pass $4 to tail command which is your file name
do
python test.py ${A} ${B} ${C} ${D} ${E} ${F}
done
</code></pre>
<p>You could access those values like ... | 1 | 2016-10-11T17:44:31Z | [
"python",
"bash",
"shell",
"csv"
] |
Looking for an efficient way to combine lines in Python | 39,983,405 | <p>I'm writing a program to aggregate strace output lines on a Linux host. When strace runs with the "-f" option it will intermix system calls line so:</p>
<pre><code>close(255 <unfinished ...>
<... rt_sigprocmask resumed> NULL, 8) = 0
<... close resumed> ) = 0
[pid 19199] close(255 <unfinis... | 0 | 2016-10-11T17:44:29Z | 39,983,924 | <p>Some iterators such as file objects can be nested. Assuming you are reading this from a file-like object, you could just create an inner loop to do the combining. I'm not sure what the formatting rules for <code>strace</code> logs are, but nominally, it could be something like</p>
<pre><code>def get_logs(filename):... | 0 | 2016-10-11T18:14:01Z | [
"python"
] |
Transform a base 64 encoded string into a downloadable pdf using django rest framework | 39,983,431 | <p>I have a django/python3 application that requests the Limesurvey API and gets a base 64 encoded string as result.
I'd like to return this result as a downloadable pdf file.</p>
<p>Here's my current implementation that's simply display the base 64 string into a blank page...</p>
<pre><code> data = limesurvey.exp... | 0 | 2016-10-11T17:45:40Z | 39,983,864 | <p>Three steps:</p>
<h2>Dump your base64 content into StringIO</h2>
<pre><code>import cStringIO as StringIO
buffer = StringIO.StringIO()
content.decode('base64')
buffer.write(content)
</code></pre>
<h2>Send response with proper header</h2>
<pre><code>from django.http import HttpResponse
from wsgiref.util import Fil... | 2 | 2016-10-11T18:10:39Z | [
"python",
"django",
"python-3.x",
"django-rest-framework"
] |
Exchanging out specific lines of a file | 39,983,500 | <p>I don't know if this should be obvious to the more tech savvy among us but is there a specific way to read a line out of a text file, then edit it and insert it back into the file in the original location? I have looked on the site but all the solutions I find seem to be for python 2.7. </p>
<p>Below is an example ... | 0 | 2016-10-11T17:49:36Z | 39,983,747 | <p>In 95% cases, replacing data (e.g. text) in a file usually means</p>
<ol>
<li>Read the file in chunks, e.g. line-by-line</li>
<li>Edit the chunk</li>
<li>Write the edited chunk to a new file</li>
<li>Replace the old file with a new file.</li>
</ol>
<p>So, a simple code will be:</p>
<pre><code>import os
with open... | 1 | 2016-10-11T18:04:09Z | [
"python",
"file",
"python-3.x"
] |
Exchanging out specific lines of a file | 39,983,500 | <p>I don't know if this should be obvious to the more tech savvy among us but is there a specific way to read a line out of a text file, then edit it and insert it back into the file in the original location? I have looked on the site but all the solutions I find seem to be for python 2.7. </p>
<p>Below is an example ... | 0 | 2016-10-11T17:49:36Z | 39,983,772 | <p>You could do this by using <code>fileinput</code> with <code>inplace</code> passed. You still cannot just do a one-line edit, you much conditionally change the line you need and let everything else as is.</p>
<p>In short with a file looking like:</p>
<pre><code>$ head example.txt
pass
pass
foo
pass
</code></pre>
... | 0 | 2016-10-11T18:05:48Z | [
"python",
"file",
"python-3.x"
] |
Why does my python tkinter GUI not show images when imported into another script? | 39,983,508 | <p>I am creating a GUI for a script. I first developed an empty GUI (code shown below). The images were not showing up but then I googled and realized references to the image were being garbage collected and fixed it according to this link (<a href="http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm" rel="... | 0 | 2016-10-11T17:50:01Z | 39,984,853 | <p>Where are your picture files? Did you make sure to put the images in your project folder? Make sure your path isn't different.</p>
| -1 | 2016-10-11T19:06:20Z | [
"python",
"user-interface",
"tkinter",
"module",
"pillow"
] |
Long path to Python script when executing it from c# | 39,983,544 | <p>I am trying to run Python script from C# program. I use official documentation from Microsoft: <a href="https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee" rel="nofollow">https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee</a> When I pass short file path t... | 0 | 2016-10-11T17:52:20Z | 39,984,320 | <p>This error can be caused by if your path is spelled wrong. For creating path dynamicly you can try the foling:</p>
<ol>
<li><p>You can try:</p>
<pre><code>Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments).
</code></pre>
<p>This will return the path to the documents folder
<em>(also if other users w... | 0 | 2016-10-11T18:35:02Z | [
"c#",
"python"
] |
run two python files in parallel from terminal | 39,983,585 | <p>If I have two python programs called <em>test1.py</em> and <em>test2.py</em>, How can I run them in parallel in terminal?
Does </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-overri... | 0 | 2016-10-11T17:54:31Z | 39,983,617 | <p>No, this will pipe the output from test1.py into test2.py.</p>
<p>Use this instead: <code>python test1.py &; python test2.py &</code></p>
<p>The <code>&</code> will fork the command into its own process.</p>
| 5 | 2016-10-11T17:56:38Z | [
"python",
"multithreading"
] |
How to restore tensorflow inceptions checkpoint file (ckpt)? | 39,983,591 | <p>I have <code>inception_resnet_v2_2016_08_30.ckpt</code> file which is a pre-trained inception model. I want to restore this model using</p>
<p><code>saver.restore(sess, ckpt_filename)</code></p>
<p>But for that, I will be required to write the set of variables that were used while training this model. Where can I ... | 1 | 2016-10-11T17:55:04Z | 39,989,069 | <p>I believe the <a href="https://www.tensorflow.org/versions/master/how_tos/meta_graph/index.html" rel="nofollow"><code>MetaGraph</code> mechanism</a> is what you need.</p>
<p>EDIT: additionally, take a look at <code>tf.train.NewCheckpointReader</code> -- it has a <code>get_variable_to_shape_map()</code> method. Se... | 0 | 2016-10-12T01:15:14Z | [
"python",
"tensorflow"
] |
Capturing WindowsError in template | 39,983,598 | <p>I'm coding on a Windows machine but I'm running my production site on Linux.</p>
<p>When trying to reach a page on my development machine using a database copied from the production system, I get errors while trying to list files if these files don't exist locally.
This is as expected, since I just copied the DB a... | 0 | 2016-10-11T17:55:26Z | 39,983,781 | <p>Not the best answer, but a workaround can be implemented as follows in <code>views.py</code> (not in the template):</p>
<pre><code>documents = Document.objects.all()
if documents:
exclude_list = []
for doc in documents:
try:
local_file = doc.data.file
except IOError:
... | 0 | 2016-10-11T18:06:07Z | [
"python",
"django"
] |
Convert to Dictionary Values that Contains a Set to a List | 39,983,611 | <p>I am trying to convert a set inside a list like</p>
<pre><code>x = [set(['Halo', 'Bye'])]
</code></pre>
<p>into a list:</p>
<pre><code>['Halo', 'Bye']
</code></pre>
<p>However when I typed list(x), the result still shows</p>
<pre><code>[set(['Halo', 'Bye'])]
</code></pre>
<p>Is there a way to do this?</p>
<p>... | -1 | 2016-10-11T17:56:01Z | 39,983,642 | <p><code>x</code> is a list already, but the set you that are trying to convert is an element of the list <code>x</code>.<br>So, do:</p>
<pre><code>print (list(x[0]))
</code></pre>
<p>instead of just <code>list(x)</code> as the set is the first and the only element in the list <code>x</code>.</p>
| 2 | 2016-10-11T17:57:57Z | [
"python",
"list",
"set"
] |
Convert to Dictionary Values that Contains a Set to a List | 39,983,611 | <p>I am trying to convert a set inside a list like</p>
<pre><code>x = [set(['Halo', 'Bye'])]
</code></pre>
<p>into a list:</p>
<pre><code>['Halo', 'Bye']
</code></pre>
<p>However when I typed list(x), the result still shows</p>
<pre><code>[set(['Halo', 'Bye'])]
</code></pre>
<p>Is there a way to do this?</p>
<p>... | -1 | 2016-10-11T17:56:01Z | 39,983,723 | <pre><code>[item for set_ in x for item in set_]
</code></pre>
<p>This will flatten a list of sets (or a list of lists) into just a list</p>
| 0 | 2016-10-11T18:02:44Z | [
"python",
"list",
"set"
] |
How to grab all lines after a match in Python | 39,983,679 | <p>I am very new to Python and I saw a post here:
<a href="http://stackoverflow.com/questions/4595197/how-to-grab-the-lines-after-a-matched-line-in-python">How to grab the lines AFTER a matched line in python</a></p>
<p>I have a file that has data in the following format:
DEFINE JOBPARM ID=(ns_ppprtg_notify,nj_pp... | 1 | 2016-10-11T18:00:09Z | 39,984,432 | <p>Here you go mate. Here's my attempt at your problem. I've given you three options in the data structure layout; <code>outDict</code> which maps the PARMs to the strings; <code>outListOfTups</code> which gives you the same data as a list of tuples; and <code>outList</code> which assumes you're not interested in the P... | 0 | 2016-10-11T18:41:25Z | [
"python"
] |
How to grab all lines after a match in Python | 39,983,679 | <p>I am very new to Python and I saw a post here:
<a href="http://stackoverflow.com/questions/4595197/how-to-grab-the-lines-after-a-matched-line-in-python">How to grab the lines AFTER a matched line in python</a></p>
<p>I have a file that has data in the following format:
DEFINE JOBPARM ID=(ns_ppprtg_notify,nj_pp... | 1 | 2016-10-11T18:00:09Z | 39,984,572 | <pre><code>if("DEFINE JOBPARM ID=" in currentLine):
tJobParmString=currentLine.partition("DEFINE JOBPARM ID=")[2].partition("SUBFILE")[0].strip()
tSubFileString=currentLine.partition("SUBFILE")[2].partition("SUBUSER")[0].strip()
tSubUserString=currentLine.partition("SUBUS... | 0 | 2016-10-11T18:49:29Z | [
"python"
] |
What is Truthy and Falsy in python ? How is it different from True and False? | 39,983,695 | <p>I just came to know there are <strong>Truthy</strong> and <strong>Falsy</strong> values in python which are different from the normal <code>True</code> and <code>False</code>?</p>
<p>Can someone please explain in depth what <em>truthy</em> and <em>falsy</em> values are? </p>
<p>Where should I use them?</p>
<p>Wha... | 0 | 2016-10-11T18:00:55Z | 39,983,806 | <p>As the comments described, it just refers to values which are evaluated to True or False.</p>
<p>For instance, to see if a list is not empty, instead of checking like this:</p>
<pre><code>if len(my_list) != 0:
print "Not empty!"
</code></pre>
<p>You can simply do this:</p>
<pre><code>if my_list:
print "Not... | 1 | 2016-10-11T18:07:49Z | [
"python"
] |
What is Truthy and Falsy in python ? How is it different from True and False? | 39,983,695 | <p>I just came to know there are <strong>Truthy</strong> and <strong>Falsy</strong> values in python which are different from the normal <code>True</code> and <code>False</code>?</p>
<p>Can someone please explain in depth what <em>truthy</em> and <em>falsy</em> values are? </p>
<p>Where should I use them?</p>
<p>Wha... | 0 | 2016-10-11T18:00:55Z | 39,984,041 | <p>In Python 2.7.x there is a special method on certain objects called <code>__nonzero__</code> which returns a boolean value. When defined, it allows you to call things like you would a boolean value:</p>
<pre><code>class Foo(object):
def __init__(self, x):
self.x = bool(x)
def __nonzero__(self):
return s... | 0 | 2016-10-11T18:20:27Z | [
"python"
] |
What is Truthy and Falsy in python ? How is it different from True and False? | 39,983,695 | <p>I just came to know there are <strong>Truthy</strong> and <strong>Falsy</strong> values in python which are different from the normal <code>True</code> and <code>False</code>?</p>
<p>Can someone please explain in depth what <em>truthy</em> and <em>falsy</em> values are? </p>
<p>Where should I use them?</p>
<p>Wha... | 0 | 2016-10-11T18:00:55Z | 39,984,051 | <p>All values are true except for:</p>
<ul>
<li><code>None</code></li>
<li><code>False</code></li>
<li><code>0</code></li>
<li><code>0.0</code></li>
<li><code>0j</code></li>
<li><code>[]</code></li>
<li><code>{}</code></li>
<li><code>()</code></li>
<li><code>''</code></li>
<li><code>set()</code></li>
<li>objects for w... | 0 | 2016-10-11T18:20:52Z | [
"python"
] |
How to describe string with only repeated characters groups in regular expression in Python | 39,983,712 | <p>i.e. <code>'aaeegggwwqqqqq', 'ttteeyyjjj'</code></p>
<p>I tried <code>r'(([a-z])\1*)+$'</code>, but get error said: cannot refer to open group.</p>
<p>Anyone can help me figure it out? Thanks!</p>
| -1 | 2016-10-11T18:01:54Z | 39,983,764 | <p>Does</p>
<pre><code>(([a-z])\2*)+$
</code></pre>
<p>work?</p>
<p>Just quickly looking, <code>(([a-z])\2*)</code> is the first group and <code>([a-z])</code> is the second group. It looks like you meant to reference the second group.</p>
| 0 | 2016-10-11T18:05:18Z | [
"python",
"regex"
] |
How to describe string with only repeated characters groups in regular expression in Python | 39,983,712 | <p>i.e. <code>'aaeegggwwqqqqq', 'ttteeyyjjj'</code></p>
<p>I tried <code>r'(([a-z])\1*)+$'</code>, but get error said: cannot refer to open group.</p>
<p>Anyone can help me figure it out? Thanks!</p>
| -1 | 2016-10-11T18:01:54Z | 39,984,371 | <p>You should use a non-capturing outer group:</p>
<pre><code>re.match(r'(?:([a-z])\1+)+$', s)
</code></pre>
<p>See the <a href="https://regex101.com/r/f186ye/1" rel="nofollow">regex demo</a></p>
<p>This way, you do not have to re-adjust the backreferences inside the pattern.</p>
<p>An alternative is to use a named... | 0 | 2016-10-11T18:37:51Z | [
"python",
"regex"
] |
Change file/folder tree structure based on name condition | 39,983,756 | <p>I've a folder/file tree like this:</p>
<pre><code>/source/photos/d831fae7-ed7f-44b1-8345-54fc54f0710f/car/1.jpg
/source/photos/20a33e40-8bb2-4ebe-b703-632115ba6714/house/
/source/photos/20a33e40-8bb2-4ebe-b703-632115ba6714/boat/b6a1b8bf-7f4c-45d6-84c1-37fbb8204328/2.jpg
/source/20dd7963-0d4a-4a80-83f8-4800de672087/... | 0 | 2016-10-11T18:04:42Z | 40,085,293 | <p>I don't have the time to give a full implementation, there are a lot of ways to do this as well, but here is an outline, which may provide you with a start.
Your question isn't very specific either unless you want a full solution handed to you, i.e. what specific problems you are running into and so on, but here goe... | 1 | 2016-10-17T11:32:37Z | [
"python",
"path",
"shutil"
] |
Change file/folder tree structure based on name condition | 39,983,756 | <p>I've a folder/file tree like this:</p>
<pre><code>/source/photos/d831fae7-ed7f-44b1-8345-54fc54f0710f/car/1.jpg
/source/photos/20a33e40-8bb2-4ebe-b703-632115ba6714/house/
/source/photos/20a33e40-8bb2-4ebe-b703-632115ba6714/boat/b6a1b8bf-7f4c-45d6-84c1-37fbb8204328/2.jpg
/source/20dd7963-0d4a-4a80-83f8-4800de672087/... | 0 | 2016-10-11T18:04:42Z | 40,091,468 | <p>Here is my ending solution (thank you Sushanta!)</p>
<pre><code>#!/usr/bin/python
import os
import uuid
from collections import Counter
import shutil
args = {}
args['rootdirOriginal'] = "/Users/xxx/Desktop/UploadDropbox"
args['uuid'] = str(uuid.uuid4())
args['rootdir'] = args['rootdirOriginal']+"/"+args['uuid']
p... | 0 | 2016-10-17T16:35:27Z | [
"python",
"path",
"shutil"
] |
RotatingFileHandler does not continue logging after error encountered | 39,983,860 | <pre><code>Traceback (most recent call last):
File "/usr/lib64/python2.6/logging/handlers.py", line 76, in emit
if self.shouldRollover(record):
File "/usr/lib64/python2.6/logging/handlers.py", line 150, in shouldRollover
self.stream.seek(0, 2) #due to non-posix-compliant Windows feature
ValueError: I/O ... | 0 | 2016-10-11T18:10:31Z | 39,984,369 | <p>I highly recommend you to use a configuration file. The configuration code below "logging.conf" has different handlers and formatters just as example: </p>
<pre><code>[loggers]
keys=root
[handlers]
keys=consoleHandler, rotatingFileHandler
[formatters]
keys=simpleFormatter, extendedFormatter
[logger_root]
level=D... | 0 | 2016-10-11T18:37:42Z | [
"python",
"logging"
] |
Python - writing and reading from a temporary file | 39,983,886 | <p>I am trying to create a temporary file that I write in some lines from another file and then make some objects from the data. I am not sure how to find and open the temp file so I can read it. My code:</p>
<pre><code>with tempfile.TemporaryFile() as tmp:
lines = open(file1).readlines()
tmp.writelines(lin... | 0 | 2016-10-11T18:11:45Z | 39,984,048 | <p>As per the <a href="https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile" rel="nofollow">docs</a>, the file is deleted when the <code>TemporaryFile</code> is closed and that happens when you exit the <code>with</code> clause. So... don't exit the <code>with</code> clause. Rewind the file and do you... | 1 | 2016-10-11T18:20:47Z | [
"python",
"temporary-files"
] |
Python - writing and reading from a temporary file | 39,983,886 | <p>I am trying to create a temporary file that I write in some lines from another file and then make some objects from the data. I am not sure how to find and open the temp file so I can read it. My code:</p>
<pre><code>with tempfile.TemporaryFile() as tmp:
lines = open(file1).readlines()
tmp.writelines(lin... | 0 | 2016-10-11T18:11:45Z | 39,984,066 | <p>You've got a scope problem; the file <code>tmp</code> only exists within the scope of the <code>with</code> statement which creates it. Additionally, you'll need to use a <code>NamedTemporaryFile</code> if you want to access the file later outside of the initial <code>with</code> (this gives the OS the ability to ac... | 0 | 2016-10-11T18:21:31Z | [
"python",
"temporary-files"
] |
How to filter datetime field +/- datetime using SQLalchemy | 39,983,887 | <p>I have a mysql table representing editorial articles and their metadata like title, author, and datecreated. </p>
<p>I have another table representing metrics (such as view counts) about those articles computed at different time points. Each row is a recording of these metrics for a particular article at a particul... | 1 | 2016-10-11T18:11:48Z | 39,984,868 | <p>Actually, this is harder than it looks. If you had done this in MySQL directly, this is what you would have written:</p>
<pre><code>SELECT ...
FROM ...
JOIN ...
WHERE tstamp BETWEEN DATE_ADD(created, INTERVAL 1 HOUR) AND DATE_ADD(created, INTERVAL 3 HOUR)
GROUP BY ...
</code></pre>
<p>And you have to do more or le... | 1 | 2016-10-11T19:07:10Z | [
"python",
"mysql",
"datetime",
"sqlalchemy"
] |
Tensorflow: Delay variable over training steps | 39,983,947 | <p>In Tensorflow, I want to use some of the variables of my network from the previous training step in the next training step. More specifically, I want to calculate a secondary cost function during training which utilizes some network tensors from the previous training step.</p>
<p>This question could be answered wit... | 1 | 2016-10-11T18:15:17Z | 39,988,777 | <p>How about making <code>h_old</code> a variable?</p>
<pre><code>h_old = tf.Variable(tf.zeros(<some-shape>))
.
.
h = tf.nn.relu(tf.matmul(h_previous,W_previous))
d = tf.sub(h,h_old)
h_old.assign(h)
</code></pre>
| 0 | 2016-10-12T00:34:03Z | [
"python",
"tensorflow",
"recurrent-neural-network"
] |
Retrieving values trimmed by ltrim in redis list | 39,983,954 | <p>A common design pattern in redis when handling lists is:</p>
<pre><code>redis_server.lpush(list_name, element)
redis_server.ltrim(list_name, 0, 99)
</code></pre>
<p>(used python syntax to illustate it)</p>
<p>What to do if one needs to retrieve all the values beyond index 99, before invoking <code>ltrim</code>? O... | 0 | 2016-10-11T18:15:33Z | 39,986,858 | <p>A first solution would be to get all extra items in one request, using <a href="http://redis.io/commands/lrange" rel="nofollow">LRANGE</a>:</p>
<p><code>
redis_server.lpush(list_name, element)
items = redis_server.lrange(list_name, 100, -1)
# do something with the items
redis_server.ltrim(list_name,... | 1 | 2016-10-11T21:15:42Z | [
"python",
"redis"
] |
Element wise multiplication of a 2D and 1D array in python | 39,983,977 | <p>Lets say I have two numpy arrays:</p>
<pre><code>import numpy as np
x = np.array([[1,2,3], [4,5,6], [7,8,9]])
y = np.array([-1, 1, -1])
</code></pre>
<p>I want to multiply x and y in such a way that I get z:</p>
<pre><code>z = np.array([[-1,2,-3], [-4,5,-6], [-7,8,-9]])
</code></pre>
<p>In other words, if elemen... | 0 | 2016-10-11T18:16:51Z | 39,984,016 | <p>Simply use the multiplication operator:</p>
<pre><code>x * y
Out[6]:
array([[-1, 2, -3],
[-4, 5, -6],
[-7, 8, -9]])
</code></pre>
| 3 | 2016-10-11T18:19:03Z | [
"python",
"numpy"
] |
How to get the message sender in yowsup cli echo? | 39,984,039 | <p>I'm using Yowsup cli to send and receive messages using whatsapp. I could register and send the messages. But when I execute this command to listen the incoming messages:</p>
<pre><code>yowsup-cli demos --login number:password --echo -E s40
</code></pre>
<p>I can see the message text, but I cannot see who is the m... | 0 | 2016-10-11T18:20:22Z | 40,130,133 | <p>Actually, this is a problem that occurs when python 3.5 is used. So, I used python 2.7 and it's solved. </p>
| 0 | 2016-10-19T11:27:04Z | [
"python",
"yowsup"
] |
Requirement already up-to-date: pip in | 39,984,046 | <p><a href="https://i.stack.imgur.com/hyCiv.png" rel="nofollow"><img src="https://i.stack.imgur.com/hyCiv.png" alt="enter image description here"></a></p>
<pre><code>Wameedhs-MacBook-Air:Desktop wameedh$ cd
Wameedhs-MacBook-Air:~ wameedh$ export PYTHONPATH=.
Wameedhs-MacBook-Air:~ wameedh$ python ~/Downloads/get-pip.p... | -1 | 2016-10-11T18:20:38Z | 40,054,354 | <p>Thanks all for the help. I fixed it! The problem was I didn't have the latest version of Xcode! I ran xcode-select --install before installing pip! that's it!!</p>
| 0 | 2016-10-15T02:31:25Z | [
"python",
"python-2.7",
"pip"
] |
Python memory allocation with pandas and pickle | 39,984,097 | <p>I am running a python script which can be roughly summed (semi-psuedo-coded) as follows:</p>
<pre><code>import pandas as pd
for json_file in json_files:
with open(json_file,'r') as fin:
data = fin.readlines()
data_str = '[' + ','.join(x.strip() for x in data) + ']'
df = pd.read_json(data_str)
... | 2 | 2016-10-11T18:23:07Z | 39,984,419 | <p>In python automatic garbage collection deallocates the variable (pandas DataFrame are also just another object in terms of python). There are different garbage collection strategies that can be tweaked (requires significant learning).</p>
<p>You can manually trigger the garbage collection using</p>
<pre><code>impo... | 1 | 2016-10-11T18:40:40Z | [
"python",
"memory-management",
"memory-leaks"
] |
Pycharm debugger shows the: "Variables are not available" message | 39,984,188 | <p>I am new to debugging, i simply want to see how the variables change as i run the program. I want to see what my program does and how.</p>
<p>But when i try to run the debugger, it shows the message: "Variables are not available (see picture). </p>
<p><a href="https://i.stack.imgur.com/XcPmy.png" rel="nofollow">Pi... | -1 | 2016-10-11T18:27:51Z | 39,985,395 | <ol>
<li>Position the cursor on a line in your code where you are interested to see your variables.</li>
<li>Press Ctrl-F8 to toggle a breakpoint.</li>
<li>Debug your code.</li>
</ol>
| 0 | 2016-10-11T19:41:12Z | [
"python",
"debugging",
"pycharm"
] |
Py Processing pixels[] array does not contain all pixels in large images | 39,984,255 | <p>I'm using Processing in Python mode to load an image and do a calculation on it. The general idea is:</p>
<pre><code>def setup():
global maxx, maxy
maxx = 0
maxy = 0
# load the image
global img
img = loadImage("img.jpg");
maxx = img.width
maxy = img.height
def draw():
image(im... | 0 | 2016-10-11T18:31:29Z | 39,984,708 | <p>In debugging, I found the problem. Calling loadPixel in the img gets the correct pixels ...</p>
<pre><code>def calc():
height = int(img.height)
width = int(img.width)
print "width: " + `width`
print "height: " + `height`
print "width*height: " + `width*height`
# iterate over the input image... | 0 | 2016-10-11T18:57:54Z | [
"python",
"processing",
"pixels",
"loadimage"
] |
Consolidate python dictionary list | 39,984,444 | <p>Original python dictionary list:</p>
<pre><code> [
{"keyword": "nike", "country":"usa"},
{"keyword": "nike", "country":"can"},
{"keyword": "newBalance", "country":"usa"},
{"keyword": "newBalance", "country":"can"}
]
</code></pre>
<p>I would like to consolidate the python dict list and ge... | -2 | 2016-10-11T18:42:27Z | 39,984,555 | <p>Here are some general pointers. I'm not going to code the whole thing for you. If you post more of what you've tried and specific code you need help with, I'd be happy to help more.</p>
<p>It looks like you're combining only those which have the same value for the "keyword" key. So loop over values of that key and ... | 0 | 2016-10-11T18:48:55Z | [
"python",
"python-2.7"
] |
Consolidate python dictionary list | 39,984,444 | <p>Original python dictionary list:</p>
<pre><code> [
{"keyword": "nike", "country":"usa"},
{"keyword": "nike", "country":"can"},
{"keyword": "newBalance", "country":"usa"},
{"keyword": "newBalance", "country":"can"}
]
</code></pre>
<p>I would like to consolidate the python dict list and ge... | -2 | 2016-10-11T18:42:27Z | 39,984,559 | <pre><code>L = [
{"keyword": "nike", "country":"usa"},
{"keyword": "nike", "country":"can"},
{"keyword": "newBalance", "country":"usa"},
{"keyword": "newBalance", "country":"can"}
]
def consolidate(L):
answer = {}
for d in L:
if d['keyword'] not in answer:
answer['k... | -2 | 2016-10-11T18:49:02Z | [
"python",
"python-2.7"
] |
How to make a string visible on a webpage using Django form fields | 39,984,508 | <p>I have a django page I've created and managed to pass values to it.
I am trying to make a text box which would contain some string.
this string can be edited and saved by the user if needed.</p>
<p>views.py</p>
<pre><code>form = EditProjectForm(project_name = project_name,store_id=store_id, `enter code here`start_... | 1 | 2016-10-11T18:46:09Z | 39,984,830 | <p>Try this with <code>initial</code></p>
<pre><code>forms.CharField(widget=forms.TextInput(attrs={'placeholder': self.project_name }), initial=self.project_name)
</code></pre>
<p><strong>OR</strong></p>
<pre><code>form = EditProjectForm(#your arguments, initial={'project_name': self.project_name})
</code></pre>
| 1 | 2016-10-11T19:04:59Z | [
"python",
"django",
"django-forms",
"django-views"
] |
Install graphlab-create in Python on Windws 10 | 39,984,524 | <p>All -- I see below which means graphlab is already installed (or not)? But help("modules") doesn't show graphlab as one of the installed packages, AND I am unable to run "import graphlab" as it results in "No module named graphlab".</p>
<pre><code>(gl-env) C:\Users>pip install graphlab-create
Requirement already... | 0 | 2016-10-11T18:47:25Z | 40,030,156 | <p>I suggest you use anaconda. If so, then you can just do within conda</p>
<pre><code>pip install --upgrade --no-cache-dir https://get.graphlab.com/GraphLab-Create/2.1/<YOUREMAILHERE>/<YOUR REGISTRATION CODE HERE- Should look like xxxx-yyyy-zzzz.../GraphLab-Create-License.tar.gz
</code></pre>
<p>Once you d... | 0 | 2016-10-13T20:15:27Z | [
"python",
"graphlab"
] |
what is the result of ( 4 > + 4 )? | 39,984,569 | <p>I need the explanation of this syntax , does this mean that (+4) is the same as (4) ? I have tried many other operands and it completely works as if I disregarded the plus sign before the number .</p>
| -2 | 2016-10-11T18:49:23Z | 39,984,624 | <p>The <code>+</code> in <code>+4</code> is the <a href="https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations" rel="nofollow">unary plus operator</a>:</p>
<blockquote>
<p>The unary <code>+</code> (plus) operator yields its numeric argument unchanged.</p>
</blockquote>
<p>So y... | 3 | 2016-10-11T18:52:32Z | [
"python",
"python-3.x"
] |
what is the result of ( 4 > + 4 )? | 39,984,569 | <p>I need the explanation of this syntax , does this mean that (+4) is the same as (4) ? I have tried many other operands and it completely works as if I disregarded the plus sign before the number .</p>
| -2 | 2016-10-11T18:49:23Z | 39,984,630 | <p>Yes, they're effectively the same. The unary <code>+</code> operator in <code>+4</code> is applied to the <code>4</code> and <code>4</code> is the result.</p>
| 0 | 2016-10-11T18:53:04Z | [
"python",
"python-3.x"
] |
what is the result of ( 4 > + 4 )? | 39,984,569 | <p>I need the explanation of this syntax , does this mean that (+4) is the same as (4) ? I have tried many other operands and it completely works as if I disregarded the plus sign before the number .</p>
| -2 | 2016-10-11T18:49:23Z | 39,984,641 | <p>Would you be confused by </p>
<pre><code>4 > -4
</code></pre>
<p>The only difference between that and</p>
<pre><code>4 > +4
</code></pre>
<p>is a different unary operator </p>
| 4 | 2016-10-11T18:53:40Z | [
"python",
"python-3.x"
] |
what is the result of ( 4 > + 4 )? | 39,984,569 | <p>I need the explanation of this syntax , does this mean that (+4) is the same as (4) ? I have tried many other operands and it completely works as if I disregarded the plus sign before the number .</p>
| -2 | 2016-10-11T18:49:23Z | 39,984,675 | <p><em>(In addition to the points pointed out by the other answers ...)</em></p>
<p>The comparison operations in Python <a href="https://docs.python.org/3/reference/expressions.html#comparisons" rel="nofollow">have lower precedence</a> than the <code>positive</code> unary operator (<code>+operand</code>):</p>
<blockq... | 2 | 2016-10-11T18:55:56Z | [
"python",
"python-3.x"
] |
what is the result of ( 4 > + 4 )? | 39,984,569 | <p>I need the explanation of this syntax , does this mean that (+4) is the same as (4) ? I have tried many other operands and it completely works as if I disregarded the plus sign before the number .</p>
| -2 | 2016-10-11T18:49:23Z | 39,984,924 | <p>To check if your variables are the same type them into your interpreter with the == operator between them. If they are the same, this will return True.</p>
<pre><code>>>> 4 == +4
True
</code></pre>
<p>This may seem daft or obvious in this case, but when working with more complex variables it can be more u... | 0 | 2016-10-11T19:11:02Z | [
"python",
"python-3.x"
] |
Python code to sum a series incrementally | 39,984,576 | <p>Great site, and I really appreciate all the answers and tips I get from here. I'm trying to calculate the sum of a series INCREMENTALLY of fractions, but cant seem to get the loop-in-a-function right. I have been able to write the program to calculate the total sum, and to calculate the individual fractions in the s... | 0 | 2016-10-11T18:49:35Z | 39,984,915 | <p>I don't know python at all, but it seems the step you have missed is to factor in the previous answer in each iteration. So you could do: </p>
<pre><code>def main():
count = 1
ans = 0
while count <= 20:
num = count
den = count +1
ans = ans + frac(num, den)
print(num, "... | 3 | 2016-10-11T19:10:29Z | [
"python",
"add",
"series"
] |
Python code to sum a series incrementally | 39,984,576 | <p>Great site, and I really appreciate all the answers and tips I get from here. I'm trying to calculate the sum of a series INCREMENTALLY of fractions, but cant seem to get the loop-in-a-function right. I have been able to write the program to calculate the total sum, and to calculate the individual fractions in the s... | 0 | 2016-10-11T18:49:35Z | 39,984,984 | <p>From what I can see you're not keeping track of your total sum anywhere, so just add a <code>total</code> variable before your loop and add to that (I also avoid while loops when a for loop will do the trick):</p>
<pre><code>def frac(n, d):
a = n / d
return a
def main():
total = 0
for num in range(... | 0 | 2016-10-11T19:16:03Z | [
"python",
"add",
"series"
] |
Python code to sum a series incrementally | 39,984,576 | <p>Great site, and I really appreciate all the answers and tips I get from here. I'm trying to calculate the sum of a series INCREMENTALLY of fractions, but cant seem to get the loop-in-a-function right. I have been able to write the program to calculate the total sum, and to calculate the individual fractions in the s... | 0 | 2016-10-11T18:49:35Z | 39,985,127 | <p>You can also use <code>itertools.accumulate</code> to generate these values:</p>
<pre><code>from itertools import accumulate
for i, ans in enumerate(accumulate(n/(n+1) for n in range(1, 21)), start=1):
print(str(i).ljust(4), format(ans, '.4f'))
</code></pre>
<p>Output:</p>
<pre><code>1 0.5000
2 1.1667
3... | 2 | 2016-10-11T19:25:56Z | [
"python",
"add",
"series"
] |
Python code to sum a series incrementally | 39,984,576 | <p>Great site, and I really appreciate all the answers and tips I get from here. I'm trying to calculate the sum of a series INCREMENTALLY of fractions, but cant seem to get the loop-in-a-function right. I have been able to write the program to calculate the total sum, and to calculate the individual fractions in the s... | 0 | 2016-10-11T18:49:35Z | 39,985,219 | <p>As many pointed out already, you missed out the accumulation of partial sums in your loop. Now, geeking out a little bit, and using list comprehensions, the same can be achieved like this:</p>
<pre><code>fractions = [ float(x)/(x+1) for x in range(1,21) ]
cumulatives = [sum(fractions[0:i+1]) for i,j in enumerate(fr... | 0 | 2016-10-11T19:31:52Z | [
"python",
"add",
"series"
] |
pip install python-dateutil does not work | 39,984,598 | <p>The command:</p>
<pre><code>pip install python-dateutil
</code></pre>
<p>Give this error:</p>
<pre><code>Collecting python-dateutil
Could not find a version that satisfies the requirement python-dateutil (from versions: )
No matching distribution found for python-dateutil
</code></pre>
<p>But easy_install python... | 0 | 2016-10-11T18:51:01Z | 39,987,004 | <p>I had an error in ~/.pip/pip.conf </p>
<p>it should have been like:</p>
<pre><code>[global]
index-url = https://pypi.python.org/simple
</code></pre>
<p>but I has it pointing to a different index</p>
| 0 | 2016-10-11T21:25:20Z | [
"python",
"pip",
"easy-install",
"python-dateutil"
] |
Automated Direct Message Response using Tweepy | 39,984,654 | <p>I currently am making use of the tweepy package in python for a DM listener. I wish to send a reply to the sender on reception of their message. I have the following:</p>
<pre><code>class StdOutListener( StreamListener ):
def __init__( self ):
self.tweetCount = 0
def on_connect( self ):
pri... | 1 | 2016-10-11T18:54:40Z | 40,022,648 | <p>UPDATE: Resolved - regenerated tokens and add conditional to check for sender, essentially blacklisting myself.</p>
| 0 | 2016-10-13T13:39:46Z | [
"python",
"twitter",
"wrapper",
"tweepy"
] |
Django with mod_wsgi: error importing sqlite3 | 39,984,681 | <p>I made a very simple project with django using python 3.4, django 1.10.2, and virtualenv all on FreeBSD. I cannot get mod_wsgi to work for the life of me, and I have done almost nothing beyond building the project and running manage.py migrate. It seems to be having a problem importing sqlite3 but in the virtualenv ... | 0 | 2016-10-11T18:56:18Z | 40,005,548 | <p>Thanks to @Graham Dumpleton for helping me in the comments. I had compiled mod_wsgi while python 2.7 was installed and I thought the virtualenv was enough for python 3.4, but I needed to remove python 2 and recompile mod_wsgi.</p>
<p>-gns</p>
| 0 | 2016-10-12T18:12:06Z | [
"python",
"django",
"sqlite",
"sqlite3",
"mod-wsgi"
] |
Run skipped python tests | 39,984,865 | <p>I would like to run all unittests in a module, including the skipped ones, from the command line, without using a test runner like <code>nose</code> etc.
Currently I have <code>python3 -m unittest discover</code>, but I don't see any option to override skipped tests. Is there a command for this?</p>
| 1 | 2016-10-11T19:07:02Z | 39,999,427 | <p>Looking at the <a href="https://hg.python.org/cpython/file/3.5/Lib/unittest/main.py#l48" rel="nofollow">code</a> for the command line utility there doesn't seem to be a sane way to avoid the skipping. A nasty workaround would be to monkey-patch <code>skip</code> before discovering tests:</p>
<pre><code>python -c "i... | 0 | 2016-10-12T13:08:19Z | [
"python",
"python-unittest"
] |
How to do Sort the occurences in descending order (alphabetically in case of ties /in this program | 39,984,919 | <pre><code>>>> words=input('enter your sensence:')
enter your sensence:it was the best of times it was the worst of times it was the age of wisdom it was the age of foolishnes
>>> wordcount={}
>>> for word in words.split():
if word not in wordcount:
wordcount[word] = 1
else:
... | -1 | 2016-10-11T19:10:34Z | 39,985,020 | <p>You already have your wordcounts. Here's how you would print them out in sorted order:</p>
<pre><code>def printout(wordcount):
for k in sorted(wordcount, key=lambda k: (wordcount[k], k)):
print(k, wordcount[k])
</code></pre>
| 0 | 2016-10-11T19:18:25Z | [
"python"
] |
Python 2.7 datetime object returning a value of 60 seconds | 39,984,922 | <p>I have the following bit of code I use to generate timestamps from a lot of instruments. The data gets logged into an initial SQLite database when it is read (w/o milliseconds), then logged into a second database when it's transmitted (w. milliseconds). After several days of data capture, I find that there are a c... | 1 | 2016-10-11T19:10:56Z | 39,985,166 | <p>Check python docs for time library, <a href="https://docs.python.org/2/library/time.html#time.strftime" rel="nofollow" title="time">here</a>.</p>
<p>In the notes, under 2, it says that the range for seconds is really [0, 61].</p>
| -1 | 2016-10-11T19:28:22Z | [
"python",
"sqlite",
"datetime"
] |
Text identification | 39,984,928 | <p>Let's say I have a list of some strings (movie names in my case) and now I have a new sentence which contains one of the string from the list of strings. How do I find that which string does the sentence has?
For eg:</p>
<pre><code>list_of_strings = ['20th century women', 'green is gold ', 'fire at sea']
sentence ... | 0 | 2016-10-11T19:11:42Z | 39,984,973 | <p>Not sure off the top of my head whether there's a faster solution, but the following shouldn't be too bad:</p>
<pre><code>lower = sentence.lower()
for sub in list_of_string:
if sub.lower() in sentence:
print sub
</code></pre>
<p>I've converted both the sentence and the list to lowercase since you indic... | 0 | 2016-10-11T19:15:03Z | [
"python",
"algorithm",
"text"
] |
Text identification | 39,984,928 | <p>Let's say I have a list of some strings (movie names in my case) and now I have a new sentence which contains one of the string from the list of strings. How do I find that which string does the sentence has?
For eg:</p>
<pre><code>list_of_strings = ['20th century women', 'green is gold ', 'fire at sea']
sentence ... | 0 | 2016-10-11T19:11:42Z | 39,984,976 | <p>I would turn your <code>list</code> into a <code>set</code> to improve performance. Then, you can do this:</p>
<pre><code>list_of_strings = ['20th century women', 'green is gold ', 'fire at sea']
set_of_strings = set(s.strip().lower() for s in list_of_strings)
sentence = 'Official Trailer | Green is gold | Releasi... | 0 | 2016-10-11T19:15:14Z | [
"python",
"algorithm",
"text"
] |
Text identification | 39,984,928 | <p>Let's say I have a list of some strings (movie names in my case) and now I have a new sentence which contains one of the string from the list of strings. How do I find that which string does the sentence has?
For eg:</p>
<pre><code>list_of_strings = ['20th century women', 'green is gold ', 'fire at sea']
sentence ... | 0 | 2016-10-11T19:11:42Z | 39,984,980 | <pre><code>for s in list_of_strings:
if s in sentence:
print 'found it!'
</code></pre>
<p>Your example sentence has a capital G in <code>Green is gold</code>, but the list of strings item has a lowercase g.</p>
| 0 | 2016-10-11T19:15:47Z | [
"python",
"algorithm",
"text"
] |
Text identification | 39,984,928 | <p>Let's say I have a list of some strings (movie names in my case) and now I have a new sentence which contains one of the string from the list of strings. How do I find that which string does the sentence has?
For eg:</p>
<pre><code>list_of_strings = ['20th century women', 'green is gold ', 'fire at sea']
sentence ... | 0 | 2016-10-11T19:11:42Z | 39,984,989 | <p>This solution will take care of all caps, spaces, tabs cases:</p>
<pre><code>for str in [str.lower().strip() for str in sentence.split(' | ')]:
if str in [str.lower().strip() for str in list_of_strings]:
print(str)
</code></pre>
| 0 | 2016-10-11T19:16:25Z | [
"python",
"algorithm",
"text"
] |
Text identification | 39,984,928 | <p>Let's say I have a list of some strings (movie names in my case) and now I have a new sentence which contains one of the string from the list of strings. How do I find that which string does the sentence has?
For eg:</p>
<pre><code>list_of_strings = ['20th century women', 'green is gold ', 'fire at sea']
sentence ... | 0 | 2016-10-11T19:11:42Z | 39,985,026 | <p>Its a slight modification of standard problem of finding occurrences of set of words in a given input text. This problem can be efficiently solved by <a href="https://en.wikipedia.org/wiki/Aho%E2%80%93Corasick_algorithm" rel="nofollow">Aho-Corasick</a> Algorithm. You can modify the source codes available for the alg... | 2 | 2016-10-11T19:18:49Z | [
"python",
"algorithm",
"text"
] |
Text identification | 39,984,928 | <p>Let's say I have a list of some strings (movie names in my case) and now I have a new sentence which contains one of the string from the list of strings. How do I find that which string does the sentence has?
For eg:</p>
<pre><code>list_of_strings = ['20th century women', 'green is gold ', 'fire at sea']
sentence ... | 0 | 2016-10-11T19:11:42Z | 39,985,171 | <p>Try iterating over the list of strings and seeing if one of them is in the sentence. If it is, then return its index from the list.</p>
<pre><code>for name in list_of_strings:
if name in sentence:
print list_of_strings.index(name)
</code></pre>
<p>Note you may want to analyse all strings (in list, and ... | 0 | 2016-10-11T19:28:42Z | [
"python",
"algorithm",
"text"
] |
Text identification | 39,984,928 | <p>Let's say I have a list of some strings (movie names in my case) and now I have a new sentence which contains one of the string from the list of strings. How do I find that which string does the sentence has?
For eg:</p>
<pre><code>list_of_strings = ['20th century women', 'green is gold ', 'fire at sea']
sentence ... | 0 | 2016-10-11T19:11:42Z | 39,985,489 | <p>As most of the answers here focus on string search part, I will consider the other interesting part of the problem, i.e. Spell Error. </p>
<p>Spell error case is an interesting and very practical in real data.</p>
<p>To deal with it, you can have a look at following metrics : </p>
<ol>
<li><p><a href="https://en.... | 1 | 2016-10-11T19:45:38Z | [
"python",
"algorithm",
"text"
] |
How to separate ethernet package to 32 bits per pice | 39,985,143 | <p>I am trying to write some data to some shared memory, and read from other side. but for some other reason, I can only write 32 bits(byte? not sure, should be bits)</p>
<p>this is for a test purpose, the package may just a simple ping package. how I can separate a package or object to many different pics and regroup... | -2 | 2016-10-11T19:26:39Z | 39,985,170 | <p>Python struct package is your friend to handle this
<a href="https://docs.python.org/2/library/struct.html" rel="nofollow">https://docs.python.org/2/library/struct.html</a></p>
| 0 | 2016-10-11T19:28:42Z | [
"python",
"shared-memory"
] |
Python - Pandas Combining parts of multiple files | 39,985,151 | <p>Have a list of 200 or so files in a folder. Each has the same amount of columns but there can be some variation in the naming. For instance, i can have Global ID or Global id or Global Id. Is there a way to control for case in pandas column names so that it doesnt matter what it equals? Currently it will get through... | 2 | 2016-10-11T19:26:58Z | 39,985,204 | <p>Use <code>header=None, names=[list of column names you want to use]</code> as additional argument to <code>read_table</code>to ignore the header row and to get consistent names.</p>
| 2 | 2016-10-11T19:30:36Z | [
"python",
"pandas"
] |
Interest Calculator In Python | 39,985,231 | <p><strong>Interest Calculator</strong> Let the user calculate the amount of money they will have in the bank after their interest has compounded for a certain number of years. </p>
<p>Note: A = P(1+r)^t where A = total amount, P = principal, r = rate, and t = time.</p>
<p>This is what I tried: </p>
<pre><code>princ... | -1 | 2016-10-11T19:32:32Z | 39,985,355 | <pre><code>import math
principal = input("How much money do you currently have in the bank?")
rate = input("What is your interest rate?")
time = input("Over how many years is the interest compounded?")
actual_principal = float(principal)
actual_rate = float(rate)
actual_time = int(time)
#TODO: Calculate the total amou... | 1 | 2016-10-11T19:39:04Z | [
"python",
"integer",
"calculator"
] |
how to loop over multiple lists in python | 39,985,271 | <p>Below, set1, set2, set3 are lists with len(setn) =len(index). I want to loop over each of these lists (setn) as follows, </p>
<pre><code>index = range(10)
set1 = range(10,20)
set2 = range(30,40)
set3 = range(40,50)
listset = [set1, set2, set3]
for i in listset:
for k, j in zip(index, i):
print k, j
Result:
... | 0 | 2016-10-11T19:34:54Z | 39,985,367 | <p>You can concatenate set1, 2 and 3 together, then use itertools.cycle(index) and zip the resulting two things together:
<code>zip(itertools.cycle(index), set1 + set2 + set3)</code></p>
| 1 | 2016-10-11T19:39:32Z | [
"python",
"list",
"loops"
] |
how to loop over multiple lists in python | 39,985,271 | <p>Below, set1, set2, set3 are lists with len(setn) =len(index). I want to loop over each of these lists (setn) as follows, </p>
<pre><code>index = range(10)
set1 = range(10,20)
set2 = range(30,40)
set3 = range(40,50)
listset = [set1, set2, set3]
for i in listset:
for k, j in zip(index, i):
print k, j
Result:
... | 0 | 2016-10-11T19:34:54Z | 39,985,376 | <p>You want to combine <code>enumerate</code> and <code>itertools.chain</code></p>
<pre><code>from itertools import chain
s1 = range(10)
s2 = range(10, 20)
s2 = range(20, 30)
c = chain(enumerate(s1), enumerate(s2), enumerate(s3))
for i, n in c:
print(str(i).ljust(4), n)
</code></pre>
| 1 | 2016-10-11T19:40:10Z | [
"python",
"list",
"loops"
] |
recursively iterate nested python dictionary | 39,985,300 | <p>I have nested python dictionary like this.</p>
<pre><code>d = {}
d[a] = b
d[c] = {1:2, 2:3}
</code></pre>
<p>I am trying to recursively convert the nested dictionary into an xml format since there can be more nested dictionary inside such as <code>d[e] = {1:{2:3}, 3:4}</code>. My desired XML format is like this</p... | 0 | 2016-10-11T19:36:41Z | 39,986,200 | <p>The way you recall encode does not look correct. Maybe this helps. For simplicity I just append stuff to a list (called <code>l</code>). Instead, you should do your <code>etree.SubElement(...)</code>.</p>
<pre><code>def encode(D, l=[]):
for k, v in D.items():
if isinstance(v, dict):
l2 = [k]... | 0 | 2016-10-11T20:30:44Z | [
"python",
"xml",
"dictionary",
"recursion",
"lxml"
] |
recursively iterate nested python dictionary | 39,985,300 | <p>I have nested python dictionary like this.</p>
<pre><code>d = {}
d[a] = b
d[c] = {1:2, 2:3}
</code></pre>
<p>I am trying to recursively convert the nested dictionary into an xml format since there can be more nested dictionary inside such as <code>d[e] = {1:{2:3}, 3:4}</code>. My desired XML format is like this</p... | 0 | 2016-10-11T19:36:41Z | 40,142,138 | <p>I found the bug in my code, which is I didn't return the recursive call back to the original loop. After going inside nested elements, it "returns" and doesn't get back to original loop. Instead of <code>return encode(subNode, val)</code>, saving in a variable <code>element = encode(subNode, val)</code> solves the p... | 0 | 2016-10-19T21:54:52Z | [
"python",
"xml",
"dictionary",
"recursion",
"lxml"
] |
CountTokenizing a field, turning into columns | 39,985,351 | <p>I'm working with data that look something like this:</p>
<pre><code>ID PATH GROUP
11937 MM-YT-UJ-OO GT
11938 YT-RY-LM TQ
11939 XX-XX-OT DX
</code></pre>
<p>I'd like to tokenize the PATH column into n-grams and then one-hot encode those into their own columns so I'd end up with s... | 1 | 2016-10-11T19:38:53Z | 39,985,571 | <p>A solution:</p>
<pre><code>df.set_index(['ID', 'GROUP'], inplace=True)
pd.get_dummies(df.PATH.str.split('-', expand=True).stack())\
.groupby(level=[0,1]).sum().reset_index()
</code></pre>
<hr>
<p>Isolate the ID and GROUP columns as index. Then convert the string to cell items</p>
<pre><code>df.PATH... | 1 | 2016-10-11T19:51:28Z | [
"python",
"pandas",
"numpy",
"scikit-learn"
] |
CountTokenizing a field, turning into columns | 39,985,351 | <p>I'm working with data that look something like this:</p>
<pre><code>ID PATH GROUP
11937 MM-YT-UJ-OO GT
11938 YT-RY-LM TQ
11939 XX-XX-OT DX
</code></pre>
<p>I'd like to tokenize the PATH column into n-grams and then one-hot encode those into their own columns so I'd end up with s... | 1 | 2016-10-11T19:38:53Z | 39,985,600 | <p>Maybe you can try something like that.</p>
<pre><code># Test data
df = DataFrame({'GROUP': ['GT', 'TQ', 'DX'],
'ID': [11937, 11938, 11939],
'PATH': ['MM-YT-UJ-OO', 'YT-RY-LM', 'XX-XX-OT']})
# Expanding data and creating on column by token
tmp = pd.concat([df.loc[:,['GROUP', 'ID']],
df['PATH'].s... | 0 | 2016-10-11T19:52:52Z | [
"python",
"pandas",
"numpy",
"scikit-learn"
] |
Raspberry Pi: Python try/except loop | 39,985,358 | <p>I've just picked up my first Raspberry Pi and 2 channel relay. I'm trying to learn how to code in Python so I figured a Pi to play with would be a good starting point. I have a question regarding the timing of my relays via the GPIO pins. </p>
<p>Firstly though, I'm using Raspbian Pixel and am editing my scripts... | 0 | 2016-10-11T19:39:09Z | 39,985,449 | <p>Just use a <code>while True</code> loop, something like:</p>
<pre><code># main loop
while True:
GPIO.output(14, GPIO.LOW)
print "open"
time.sleep(SleepTimeL);
GPIO.cleanup()
print "done"
</code></pre>
| 0 | 2016-10-11T19:43:21Z | [
"python",
"exception",
"try-catch",
"gpio"
] |
Raspberry Pi: Python try/except loop | 39,985,358 | <p>I've just picked up my first Raspberry Pi and 2 channel relay. I'm trying to learn how to code in Python so I figured a Pi to play with would be a good starting point. I have a question regarding the timing of my relays via the GPIO pins. </p>
<p>Firstly though, I'm using Raspbian Pixel and am editing my scripts... | 0 | 2016-10-11T19:39:09Z | 39,985,936 | <p>I agree with reptilicus, you just need to add a while loop. "while True" will run forever, until you hit ctrl-C to break. You just need to add a second delay to hold the relay off for 180 seconds before looping. You can create a different sleep time variable, or I just multiply the one you have by 2.</p>
<pre><c... | 0 | 2016-10-11T20:13:54Z | [
"python",
"exception",
"try-catch",
"gpio"
] |
Python - Tweepy - How to use lookup_friendships? | 39,985,434 | <p>I'm trying to figure out if I'm following a user from which the streaming API just received a tweet. If I don't, then I want to follow him.</p>
<p>I've got something like:</p>
<pre><code>def checkFollow(status):
relationship = api.lookup_friendships("Privacy_Watch_",status.user.id_str)
</code></pre>
<p>From t... | 0 | 2016-10-11T19:42:49Z | 40,015,567 | <p>The lookup_friendships method will return everyone you follow each time you call it, in blocks of 100 users. Provided you follow a lot of people, that will be highly inefficient and consume a lot of requests.</p>
<p>You can use instead the <a href="https://github.com/tweepy/tweepy/blob/master/tweepy/api.py#L461" re... | 0 | 2016-10-13T08:09:34Z | [
"python",
"twitter",
"tweepy"
] |
How to ignore capitalization BUT return same capitalization as input | 39,985,448 | <p>My code intends to identify the first non-repeating string characters, empty strings, repeating strings (i.e. <code>abba</code> or <code>aa</code>), but it's also meant to treat lower and upper case input as the same character while returning the accurate non-repeating character in it's orignial case input. </p>
<p... | 1 | 2016-10-11T19:43:21Z | 39,985,569 | <p>When comparing two letters, use lower() to compare the characters in a string. An example would be:</p>
<pre><code>string ="aabcC"
count = 0
while count < len(string) - 1:
if string[count].lower() == string[count + 1].lower():
print "Characters " + string[count] + " and " + string[count + 1] + " are ... | 0 | 2016-10-11T19:51:27Z | [
"python",
"string",
"case"
] |
How to ignore capitalization BUT return same capitalization as input | 39,985,448 | <p>My code intends to identify the first non-repeating string characters, empty strings, repeating strings (i.e. <code>abba</code> or <code>aa</code>), but it's also meant to treat lower and upper case input as the same character while returning the accurate non-repeating character in it's orignial case input. </p>
<p... | 1 | 2016-10-11T19:43:21Z | 39,985,741 | <p>The point is that <code>x</code> in <code>counts</code> is searched for in a case-insensitive way. You have to implement your own case insensitive Dictionary, or use regular expressions to detect repeating letters:</p>
<pre><code>import re
def first_non_repeat(string):
r = re.compile(r'([a-z])(?=.*\1)', re.I|re... | 0 | 2016-10-11T20:01:53Z | [
"python",
"string",
"case"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.