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
Pandas - Self reference of instances in column
39,883,232
<p>I have the following DF</p> <pre><code> SampleID ParentID 0 S10 S20 1 S10 S30 2 S20 S40 3 S30 4 S40 </code></pre> <p>How can I put the id of the other row in the column 'ParentID' instead of the string?</p> <p>Expected result:</p> <pre><code> SampleID P...
0
2016-10-05T20:37:35Z
39,883,828
<p>Use <code>replace</code> by passing along the mapping lists of values to replace:</p> <pre><code>df.ParentID.replace(df.SampleID.tolist(), df.index.tolist(), inplace=True) df Out[22]: SampleID ParentID 0 S10 2.0 1 S10 3.0 2 S20 4.0 3 S30 NaN 4 S40 NaN </co...
1
2016-10-05T21:17:35Z
[ "python", "pandas" ]
How to get a var out of beautifulsoup soup
39,883,332
<p>How would I get the variable out into like a json or any other way to just take out like challenge</p> <pre><code>&lt;html&gt;&lt;body&gt;&lt;p&gt;var rechallengeState = { challenge : '03AHJ_Vuv8ZHJfsjnR3ueIvm89Jfa6oUJ3-kuzA-VcQIaR30A9CZva7lMaBrYlvcGG4cOPCeKXfERQe_u-cMw_8ZVi6CipeJVAYAsrOeBHryWRCMIaMt4V-TQl...
-2
2016-10-05T20:45:29Z
39,884,339
<p>Description in code</p> <pre><code>from bs4 import BeautifulSoup html = '''&lt;html&gt;&lt;body&gt;&lt;p&gt;var rechallengeState = { challenge : '03AHJ_Vuv8ZHJfsjnR3ueIvm89Jfa6oUJ3-kuzA-VcQIaR30A9CZva7lMaBrYlvcGG4cOPCeKXfERQe_u-cMw_8ZVi6CipeJVAYAsrOeBHryWRCMIaMt4V-TQlTgyUA4ndejEgBGUCUw7rwM-ltDr-do8ry-MRv26qQTp...
-1
2016-10-05T21:56:14Z
[ "python", "html", "python-3.x", "web-scraping" ]
Creating an upside down asterisk triangle in Python using for loop
39,883,386
<p>I hate that I have to ask this, but I can't for the life of me figure out how to make this work. The program is supposed to ask for an input of an odd integer and then create an upside down pyramid with the first row containing the amount of asterisks as the number, and the last row having only one, centered asteri...
2
2016-10-05T20:48:52Z
39,883,497
<p>I don't think you can center them due to not being able to place characters between half-spaces. Maybe try inserting a space between all stars so you can center them better and produce something like this.</p> <pre><code>* * * * * * * * * * </code></pre> <p>Instead of:</p> <pre><code>**** *** ** * </co...
0
2016-10-05T20:55:27Z
[ "python", "python-3.x", "for-loop" ]
Creating an upside down asterisk triangle in Python using for loop
39,883,386
<p>I hate that I have to ask this, but I can't for the life of me figure out how to make this work. The program is supposed to ask for an input of an odd integer and then create an upside down pyramid with the first row containing the amount of asterisks as the number, and the last row having only one, centered asteri...
2
2016-10-05T20:48:52Z
39,883,562
<p>You need to set the 'step' of the <code>range</code> to <code>-2</code>, so that it only grabs odds ints in reverse. Then the number of white spaces needed to have a <code>+ 1</code> to work properly. </p> <pre><code>x=input('Enter an odd number width: ') x_int = int(x) print('Triangle:') for i in range(x_int, 0, ...
1
2016-10-05T20:59:29Z
[ "python", "python-3.x", "for-loop" ]
Creating an upside down asterisk triangle in Python using for loop
39,883,386
<p>I hate that I have to ask this, but I can't for the life of me figure out how to make this work. The program is supposed to ask for an input of an odd integer and then create an upside down pyramid with the first row containing the amount of asterisks as the number, and the last row having only one, centered asteri...
2
2016-10-05T20:48:52Z
39,883,601
<p>Apart from setting your step value to <code>-2</code>, you'll have a more readable code if you use Python's string <code>format</code> method. You can easily center your asterisks by using <em>center alignment</em> viz. <code>^</code>: </p> <pre><code>x = input('Enter an odd number width: ') x_int = int(x) print(...
2
2016-10-05T21:01:45Z
[ "python", "python-3.x", "for-loop" ]
Creating an upside down asterisk triangle in Python using for loop
39,883,386
<p>I hate that I have to ask this, but I can't for the life of me figure out how to make this work. The program is supposed to ask for an input of an odd integer and then create an upside down pyramid with the first row containing the amount of asterisks as the number, and the last row having only one, centered asteri...
2
2016-10-05T20:48:52Z
39,883,673
<p>Try something like:</p> <pre><code>x = int(input('Enter an odd number width: ')) print('Triangle:') for i in range(x_int, 0, -1): print('{:^{str_len}}'.format('* ' * i, str_len= x_int * 2)) </code></pre> <p>That should work not only for odd numbers.</p>
2
2016-10-05T21:06:32Z
[ "python", "python-3.x", "for-loop" ]
Limit Python Threads : Resource Temporarily Unavailable
39,883,387
<p>I use python threading.Thread to spawn threads that execute a small utility for every filename found in os.walk() and get its output. I tried limiting number of threads using:</p> <pre><code>ThreadLimiter = threading.BoundedSemaphore(3) </code></pre> <p>and </p> <pre><code>ThreadLimiter.acquire() </code></pre> ...
0
2016-10-05T20:48:58Z
39,883,674
<p>When <code>run</code> executes, the Thread has <em>already</em> started. Using a limit inside of <code>run</code> will not limit the number of <em>running</em> threads but of <em>finishing</em> threads - making the problem worse!</p> <p>Either:</p> <ul> <li>Modify <code>start</code> to delay launching the threads....
0
2016-10-05T21:06:33Z
[ "python", "multithreading" ]
Limit Python Threads : Resource Temporarily Unavailable
39,883,387
<p>I use python threading.Thread to spawn threads that execute a small utility for every filename found in os.walk() and get its output. I tried limiting number of threads using:</p> <pre><code>ThreadLimiter = threading.BoundedSemaphore(3) </code></pre> <p>and </p> <pre><code>ThreadLimiter.acquire() </code></pre> ...
0
2016-10-05T20:48:58Z
39,883,760
<p>Use a thread pool and save yourself a lot of work! Here I md5sum files:</p> <pre><code>import os import multiprocessing.pool import subprocess as subp def walker(path): """Walk the file system returning file names""" for dirpath, dirs, files in os.walk(path): for fn in files: yield os.p...
1
2016-10-05T21:13:22Z
[ "python", "multithreading" ]
Is there array_count_values() analogue for Python 3.x or best way to do this?
39,883,472
<p>Is there array_count_values() analogue or fastest way to do this in Python 3.x</p> <p>from</p> <pre><code>d = ["1", "this", "1", "is", "Sparta", "Sparta"] </code></pre> <p>to</p> <pre><code>{ '1': 2, 'this': 1, 'is': 1, 'Sparta': 2 } </code></pre>
0
2016-10-05T20:54:01Z
39,883,540
<p>You can count the occurrence of each element in a list using <code>Counter</code>:</p> <pre><code>from collections import Counter l = [1, "this", 1, "is", "Sparta", "Sparta"] print(Counter(l)) </code></pre> <p>This prints</p> <pre><code>Counter({1: 2, 'Sparta': 2, 'this': 1, 'is': 1}) </code></pre> <p><a href="...
2
2016-10-05T20:58:28Z
[ "python" ]
How do I make matplotlib generate a single plot instead of a plot for each data point?
39,883,478
<p>I am trying to generate three plots, each using the same inputs. When I run my code I generate a plot for each x input instead of three plots consisting of all of their data points.</p> <p>See my code below:</p> <pre><code>xlist = np.linspace(0, 2.5) for name, f, df in zip(func_names, funcs, diff_funcs): for x ...
1
2016-10-05T20:54:36Z
39,884,738
<p>So, I found out that plot() needs to have the entire x_list and y_list as arguments.</p> <p>which got me to this:</p> <pre><code> xlist = np.linspace(0, 2.5) for name, f in zip(func_names, funcs): ylist = [forwdiff(f, x, h=0.01) for x in xlist] plt.plot(xlist, ylist, 'g^') ylist = [diff(f, x, h=0....
0
2016-10-05T22:34:06Z
[ "python", "matplotlib", "plot" ]
How do I make matplotlib generate a single plot instead of a plot for each data point?
39,883,478
<p>I am trying to generate three plots, each using the same inputs. When I run my code I generate a plot for each x input instead of three plots consisting of all of their data points.</p> <p>See my code below:</p> <pre><code>xlist = np.linspace(0, 2.5) for name, f, df in zip(func_names, funcs, diff_funcs): for x ...
1
2016-10-05T20:54:36Z
39,885,579
<p>Going off your answer, you are looking for something like this:</p> <pre><code># axarr is an array of axes objects (1 row, 3 columns) fig, axarr = plt.subplots(1, 3) for ax, name, f in zip(ax, func_names, funcs): for df, dfname in zip((forwdiff, diff), ('forward', 'central')): ylist = [df(f, x, h=0.01) ...
0
2016-10-06T00:14:43Z
[ "python", "matplotlib", "plot" ]
How to pick one number of an Integer
39,883,517
<p>How can I pick one of the digits from an Integer like: 97723 and choose (for example) the number 2 from that number and check if its an odd or an even number?</p> <p>Also, can I print only the odd numbers from an Integer directly? (Is there any default function for that already?)</p> <p>Thanks in advance</p>
0
2016-10-05T20:56:37Z
39,883,577
<p>2 is the 4th digit.</p> <p>You can get the digits of a number using this construct.</p> <pre><code>digits = [int(_) for _ in str(97723)] </code></pre> <p>This expression will be <code>true</code> if the 4th digit is even.</p> <pre><code>digits[3] % 2 == 0 </code></pre>
2
2016-10-05T21:00:21Z
[ "python", "python-3.x" ]
How to pick one number of an Integer
39,883,517
<p>How can I pick one of the digits from an Integer like: 97723 and choose (for example) the number 2 from that number and check if its an odd or an even number?</p> <p>Also, can I print only the odd numbers from an Integer directly? (Is there any default function for that already?)</p> <p>Thanks in advance</p>
0
2016-10-05T20:56:37Z
39,883,751
<pre><code>even = lambda integer: int("".join([num for num in str(integer) if int(num) % 2 == 0])) </code></pre> <p>or</p> <pre><code>def even(integer): result = "" integer = str(integer) for num in integer: if int(num) % 2 == 0: result += num result = int(result) return(result...
0
2016-10-05T21:12:39Z
[ "python", "python-3.x" ]
How to pick one number of an Integer
39,883,517
<p>How can I pick one of the digits from an Integer like: 97723 and choose (for example) the number 2 from that number and check if its an odd or an even number?</p> <p>Also, can I print only the odd numbers from an Integer directly? (Is there any default function for that already?)</p> <p>Thanks in advance</p>
0
2016-10-05T20:56:37Z
39,883,830
<p>If you want to "parse" a number the easiest way to do this is to convert it to string. You can convert an int to string like this <code>s = string(500)</code>. Then use string index to get character that you want. For example if you want first character (number) then use this <code>string_name[0]</code>, for second ...
0
2016-10-05T21:17:40Z
[ "python", "python-3.x" ]
How to pick one number of an Integer
39,883,517
<p>How can I pick one of the digits from an Integer like: 97723 and choose (for example) the number 2 from that number and check if its an odd or an even number?</p> <p>Also, can I print only the odd numbers from an Integer directly? (Is there any default function for that already?)</p> <p>Thanks in advance</p>
0
2016-10-05T20:56:37Z
39,883,860
<pre><code># choose a digit (by index) integer = 97723 digit_3 = str(integer)[3] print(digit_3) # check if even: if int(digit_3) % 2 == 0: print(digit_3, "is even") # get all odd numbers directly odd_digits = [digit for digit in str(integer) if int(digit) % 2 == 1] print(odd_digits) </code></pre>
0
2016-10-05T21:19:40Z
[ "python", "python-3.x" ]
Hovertool callback source selection for multi-plot graph
39,883,625
<p>I currently use bokeh version 0.12.2. I am plotting a graph with two series of circles.</p> <pre><code>graph1 = figure(plot_width=800, plot_height=800) graph1.circle('fpr1', 'tpr1', color='red', source=source) graph1.circle('fpr2', 'tpr2', color='blue', source=source) </code></pre> <p>Now, I would like to add a Ho...
0
2016-10-05T21:02:58Z
39,884,251
<p>I'm afraid this is a <a href="https://github.com/bokeh/bokeh/issues/2136" rel="nofollow">known bug</a>. There is a <a href="https://github.com/bokeh/bokeh/pull/5158" rel="nofollow">"WIP" PR to fix it</a> but it will not go in this weeks <code>0.12.3</code> release. It should be in <code>0.12.4</code>, though. </p>
1
2016-10-05T21:48:18Z
[ "javascript", "python", "bokeh" ]
Combining dataframes in pandas with the same rows and columns, but different cell values
39,883,656
<p>I'm interested in combining two dataframes in pandas that have the same row indices and column names, but different cell values. See the example below:</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame({'A':[22,2,np.NaN,np.NaN], 'B':[23,4,np.NaN,np.NaN], ...
3
2016-10-05T21:04:53Z
39,883,694
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow"><code>combine_first</code></a>:</p> <pre><code>print (df1.combine_first(df2)) A B C D 0 22.0 23.0 24.0 25.0 1 2.0 4.0 6.0 8.0 2 56.0 58.0 59.0 60.0...
1
2016-10-05T21:07:49Z
[ "python", "pandas", "dataframe", "merge", "concat" ]
Combining dataframes in pandas with the same rows and columns, but different cell values
39,883,656
<p>I'm interested in combining two dataframes in pandas that have the same row indices and column names, but different cell values. See the example below:</p> <pre><code>import pandas as pd import numpy as np df1 = pd.DataFrame({'A':[22,2,np.NaN,np.NaN], 'B':[23,4,np.NaN,np.NaN], ...
3
2016-10-05T21:04:53Z
39,883,697
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow">combine_first</a></p> <pre><code>df1.combine_first(df2) </code></pre>
1
2016-10-05T21:07:57Z
[ "python", "pandas", "dataframe", "merge", "concat" ]
Selenium, Python, Can't Click Button by Checking the Table Items Name
39,883,704
<p>I am trying to improve my <code>Selenium</code> skills and for this task, I try to click a button the way that chooses it by table elements name.</p> <p>For example, in this case, I want to locate <code>EB Trial 2</code> then click the <code>import</code> button which is related to that.</p> <pre><code>&lt;tr ng-r...
1
2016-10-05T21:08:47Z
39,886,202
<blockquote> <p>I want to locate EB Trial 2 then click the import button which is related to that</p> </blockquote> <p>You should try using <code>xpath</code> as :</p> <pre><code>driver.find_element_by_xpath(".//td[descendant::a[text()='EB Trial2']]/following-sibling::td//a[normalize-space(.)='Import']").click() </...
0
2016-10-06T01:41:02Z
[ "python", "osx", "google-chrome", "selenium" ]
How to efficiently write a binary file containing mixed label and image data
39,883,715
<p>The <a href="https://github.com/tensorflow/tensorflow/tree/411f57e291839094108afdaa9c43094f44979eaa/tensorflow/models/image/cifar10" rel="nofollow">cifar10 tutorial</a> deals with binary files as input. Each record/example on these CIFAR10 datafiles contain mixed label (first element) and image data information. The...
0
2016-10-05T21:09:42Z
39,889,727
<p>When I write binary files I usually just use the python module <em>struct</em>, which works somehow like this:</p> <pre><code>import struct import numpy as np image = np.zeros([2, 300, 300], dtype=np.uint8) label = np.zeros([2, 1], dtype=np.uint16) with open('data.bin', 'w') as fo: s = image.shape for k i...
1
2016-10-06T07:12:42Z
[ "python", "io", "tensorflow" ]
web scraping with beautifulsoup
39,883,726
<p>I'm trying to parsing the website only particular part. Here is my code below. Is there anyway to do it more efficient.</p> <pre><code>from bs4 import BeautifulSoup import requests import urllib.request import json soup = BeautifulSoup(requests.get("http://www.example.com").content, "html.parser") for d in soup.s...
0
2016-10-05T21:10:45Z
39,884,013
<p>It can change on other page - (I didn't check it with other pages)</p> <pre><code>for d in soup.select("script[type=text/javascript]")[27].text.split('\n')[51:62]: print(d.strip()) </code></pre> <p>result </p> <pre><code>'page':'ProductPage', 'OAM':'False', 'storeNum':'029', 'brand':'Microsoft', 'productPri...
0
2016-10-05T21:30:20Z
[ "python", "parsing", "web-scraping" ]
Match two groups but none of them should be empty
39,883,786
<p>I want my regex to be able to match strings of random chars optionally followed by some digits - but if both matches are empty I want the match to fail. I am currently constructing the regex as in:</p> <pre><code>regex = u'^(.*)' if has_digits: regex += u'(\d*)' regex += ext + u'$' # extension group as in u'(\.exe)...
0
2016-10-05T21:14:58Z
39,884,080
<p>Regex:</p> <pre><code>^(.*?)(\d+)?(?&lt;=.)\.exe$ </code></pre> <p>Positive lookbehind assures that there is at least one character before extension part.</p> <p><strong><a href="https://www.regex101.com/r/CNBQyG/1" rel="nofollow">Live demo</a></strong></p> <p>Integrated:</p> <pre><code>regex = '^(.*?)' if has_...
2
2016-10-05T21:33:57Z
[ "python", "regex", "python-2.7", "regex-lookarounds" ]
Match two groups but none of them should be empty
39,883,786
<p>I want my regex to be able to match strings of random chars optionally followed by some digits - but if both matches are empty I want the match to fail. I am currently constructing the regex as in:</p> <pre><code>regex = u'^(.*)' if has_digits: regex += u'(\d*)' regex += ext + u'$' # extension group as in u'(\.exe)...
0
2016-10-05T21:14:58Z
39,884,234
<p>You can use this lookahead based regex:</p> <pre><code>ext = r'\.exe' regex = r'^(?=.+\.)(.*?)' if has_digits: regex += r'(\d*)' regex += ext + '$' rePattern = re.compile(regex, re.I | re.U) # ^(?=.+\.)(.*?)(\d*)\.exe$ </code></pre> <p><a href="https://regex101.com/r/DXv0ep/1" rel="nofollow">RegEx Demo</a></p> <...
1
2016-10-05T21:46:43Z
[ "python", "regex", "python-2.7", "regex-lookarounds" ]
__str__ returned non-string (type tuple)
39,883,950
<p>I have a form that keeps throwing me an error in django, Ive tried searching online tried str() on my models but wouldnt work at all. Googled a couple of times tried a couple different methods but none worked still get the same django error page everytime i click the link to the form.</p> <pre><code>TypeError: __st...
0
2016-10-05T21:26:04Z
39,884,000
<p>Those commas aren't actually doing what you think they do. The commas make your return value a <em>tuple</em> instead of a <em>string</em> which a <code>__str__</code> method is supposed to return.</p> <p>You can instead do:</p> <pre><code>def __str__(self): return '%s %s %s'%(self.soi_l1, self.soi_l2, self.st...
1
2016-10-05T21:29:24Z
[ "python", "django" ]
__str__ returned non-string (type tuple)
39,883,950
<p>I have a form that keeps throwing me an error in django, Ive tried searching online tried str() on my models but wouldnt work at all. Googled a couple of times tried a couple different methods but none worked still get the same django error page everytime i click the link to the form.</p> <pre><code>TypeError: __st...
0
2016-10-05T21:26:04Z
39,884,003
<p>The error is in your model:</p> <pre><code>class SourceOfInjuryLevel2(models.Model): ... def __str__(self): return self.soi_l1, self.soi_l2, self.status </code></pre> <p>I guess you were confused because the Python 2 print statement looks like it turns tuples into strings, but that's not actually...
1
2016-10-05T21:29:26Z
[ "python", "django" ]
How can I append this elements to an array in python?
39,883,994
<pre><code>input_elements = ["a", "b", "c", "d"] my_array = ["1", "2", "3", "4"] </code></pre> <p>the output I want is:</p> <pre><code>["1", "2", "3", "4", "a"] ["1", "2", "3", "4", "b"] ["1", "2", "3", "4", "c"] ["1", "2", "3", "4", "d"] </code></pre> <p>I tried:</p> <pre><code>for e in input_elements: my_array....
4
2016-10-05T21:29:01Z
39,884,043
<p>You can use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to solve your issue. </p> <pre><code>&gt;&gt;&gt; input_elements = ["a", "b", "c", "d"] &gt;&gt;&gt; my_array = ["1", "2", "3", "4"] &gt;&gt;&gt; [my_array+[i] for i in input_elem...
4
2016-10-05T21:31:59Z
[ "python", "list" ]
How can I append this elements to an array in python?
39,883,994
<pre><code>input_elements = ["a", "b", "c", "d"] my_array = ["1", "2", "3", "4"] </code></pre> <p>the output I want is:</p> <pre><code>["1", "2", "3", "4", "a"] ["1", "2", "3", "4", "b"] ["1", "2", "3", "4", "c"] ["1", "2", "3", "4", "d"] </code></pre> <p>I tried:</p> <pre><code>for e in input_elements: my_array....
4
2016-10-05T21:29:01Z
39,884,088
<p>You need to make a copy of the old list in the loop:</p> <pre><code>input_elements = ["a", "b", "c", "d"] my_array = ["1", "2", "3", "4"] new_list = [] for e in input_elements: tmp_list = list(my_array) tmp_list.append(e) new_list.append(tmp_list) print(new_list) </code></pre> <p>Output:</p> <pre><code>[['...
1
2016-10-05T21:34:46Z
[ "python", "list" ]
How can I append this elements to an array in python?
39,883,994
<pre><code>input_elements = ["a", "b", "c", "d"] my_array = ["1", "2", "3", "4"] </code></pre> <p>the output I want is:</p> <pre><code>["1", "2", "3", "4", "a"] ["1", "2", "3", "4", "b"] ["1", "2", "3", "4", "c"] ["1", "2", "3", "4", "d"] </code></pre> <p>I tried:</p> <pre><code>for e in input_elements: my_array....
4
2016-10-05T21:29:01Z
39,884,191
<p>I'm assuming the output you're getting is:</p> <pre><code>['1', '2', '3', '4', 'a', 'b', 'c', 'd'] </code></pre> <p>...because, that's what I'm getting.</p> <p>The problem is, in your loop, you're simply adding a new element to the existing array, then printing the "grand total." So, you add a, then you add b, t...
1
2016-10-05T21:42:48Z
[ "python", "list" ]
How does xarray broadcasting work with numpy functions?
39,884,068
<p>I am trying to do a coordinate transformation with my xarray coordinates so </p> <p>I have a DataArray like:</p> <pre><code>d = xr.DataArray(np.zeros((10, 10, 1)), dims=['x', 'y', 'z'] </code></pre> <p>and am doing operations like:</p> <pre><code>r = np.sqrt(d.x**2 + d.y**2 + d.z**2) theta = np.arctan2(np.sqrt(d...
2
2016-10-05T21:33:24Z
39,884,270
<p>Unfortunately, NumPy functions generally don't do appropriate broadcasting on xarray objects. But xarray does come with wrapped versions of many of these functions, including <code>arctan2</code>, in the <a href="http://xarray.pydata.org/en/stable/api.html#universal-functions" rel="nofollow"><code>xarray.ufuncs</cod...
2
2016-10-05T21:49:52Z
[ "python", "numpy", "python-xarray" ]
count certain words on html file by python
39,884,197
<p>I am a rookie in Python. I am trying to count some words or expressions on html files. For example,I have a piece of html with source codes as below:</p> <pre><code>&lt;div style="line-height:120%;text-align:justify;text-indent:24px;font-size:10.5pt;"&gt; &lt;font style="font-family:inherit;font-size:10.5pt;font-st...
0
2016-10-05T21:43:05Z
39,904,363
<p>You can apply a <em>partial string match</em> on an element's text when using <code>find()</code> or <code>find_all()</code>:</p> <pre><code>soup.find(text=lambda text: text and "liability" in text) </code></pre> <p>Or, a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-regular-expression" rel="no...
0
2016-10-06T19:39:44Z
[ "python", "beautifulsoup" ]
Variation of iterating through a single column
39,884,225
<p>I know there are a zillion ways to iterate through data in a data frame. I am acquiring data from a detector, power, frequency, time. The time and power columns have values in every row. The frequency changes with time <strong>but</strong> for each frequency 'segment' the frequency and duty cycle are only listed in ...
0
2016-10-05T21:45:56Z
39,884,514
<p>You want <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow"><code>fillna</code></a>:</p> <pre><code>data = '''time power frequency duty_cycle 1.4 1.2 500.0 45.0 2.1 49.9 NaN NaN 3.4 245.0 NaN NaN 4.5 323.0 NaN NaN 5.6 320.0 N...
1
2016-10-05T22:11:37Z
[ "python", "python-3.x", "numpy", "dataframe" ]
Efficient way to retrieve and merge returned arrays from multiprocess function call
39,884,292
<pre><code>def get_version_list(env): list = [] #do some intensive work return list if __name__ == '__main__': from multiprocessing import Pool pool = Pool() result1 = pool.apply_async(get_version_list, ['prod']) result2 = pool.apply_async(get_version_list, ['uat']) #etc, I have six environment to ch...
0
2016-10-05T21:52:06Z
39,884,539
<p>Use <code>map_async</code> instead of <code>apply_async</code>.</p> <pre><code>pool = Pool() env = ['uat', 'prod', 'lt', 'lt2', 'cert', 'sin'] x = pool.map_async(get_version_list, env) </code></pre> <p>And now <code>x</code> will be a list of the results.</p>
1
2016-10-05T22:14:29Z
[ "python", "multiprocessing", "python-multiprocessing" ]
Efficient way to retrieve and merge returned arrays from multiprocess function call
39,884,292
<pre><code>def get_version_list(env): list = [] #do some intensive work return list if __name__ == '__main__': from multiprocessing import Pool pool = Pool() result1 = pool.apply_async(get_version_list, ['prod']) result2 = pool.apply_async(get_version_list, ['uat']) #etc, I have six environment to ch...
0
2016-10-05T21:52:06Z
39,884,546
<p>You can take inspiration from <a href="https://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers" rel="nofollow">the documentation</a>:</p> <pre><code>def get_version_list(env): lst = [] #do some intensive work return lst if __name__ == '__main__': from multiprocessing import Pool p...
0
2016-10-05T22:15:19Z
[ "python", "multiprocessing", "python-multiprocessing" ]
Build 2D array using append
39,884,409
<p>Python: I would like to read set of data</p> <pre><code>(category, value): (0, 1) (0, 2) (1, 3) (1, 4) </code></pre> <p>To an array as</p> <pre><code>[[1, 2],[3, 4]] </code></pre> <p>Since max number of category is unknown, I would like to create 2D-array dynamically using "append" method.</p> <p>I wrote a samp...
1
2016-10-05T22:02:15Z
39,884,449
<p>You can use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to do this easily along with a <a href="https://docs.python.org/3/library/functions.html#iter" rel="nofollow"><code>iter</code></a>. </p> <pre><code>&gt;&gt;&gt; l = [(0, 1), (0, ...
1
2016-10-05T22:06:01Z
[ "python", "list", "append" ]
Build 2D array using append
39,884,409
<p>Python: I would like to read set of data</p> <pre><code>(category, value): (0, 1) (0, 2) (1, 3) (1, 4) </code></pre> <p>To an array as</p> <pre><code>[[1, 2],[3, 4]] </code></pre> <p>Since max number of category is unknown, I would like to create 2D-array dynamically using "append" method.</p> <p>I wrote a samp...
1
2016-10-05T22:02:15Z
39,884,532
<p>Use <code>itertools.groupby</code>:</p> <pre><code>import itertools a = [(0, 1), (0, 2), (1, 3), (1, 4)] g = itertools.groupby(a, key=lambda x: x[0]) g = [list(i[1]) for i in g] </code></pre>
1
2016-10-05T22:13:35Z
[ "python", "list", "append" ]
Delete blank columns from header row
39,884,456
<p>I'm pretty new to python and I'm having trouble deleting the header columns after the 25th column. There are 8 more extra columns that have no data so I'm trying to delete those columns. Columns 1-25 have like 50,000k of data and the rest of the columns are blank.How would I do this? My code for now is able to clean...
0
2016-10-05T22:06:44Z
39,885,791
<p>You've found the line with the problem - all you have to do is only print the headers you want. <code>next(cr)</code> reads the header line, but you pass the entire line to <code>writer.writerow()</code>.</p> <p>Instead of</p> <pre><code>writer.writerow(next(cr)) </code></pre> <p>you want:</p> <pre><code>writer...
1
2016-10-06T00:44:05Z
[ "python", "python-3.x" ]
Specify what Y labels to use
39,884,482
<p>Using python and Matplotlib, I am trying to explicitly control what Y labels are shown on Y axis:</p> <pre><code>def plot_sample_top(sample, chrom): ax = fig.add_subplot(23, 1, subplot_coord[sample]) ax.set_xlim([1, chrom_lengths[chrom]]) ax.set_ylim([-10, 10]) # scatter ax.scatter(df_strain['P...
0
2016-10-05T22:09:27Z
39,884,784
<p>You will want to use <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_yticks" rel="nofollow">axes.set_yticks</a> and/or <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_yticklabels" rel="nofollow">axes.set_yticklabels</a>.</p> <p>To set the ticks and labels as you s...
0
2016-10-05T22:40:39Z
[ "python", "matplotlib" ]
conda command will prompts error
39,884,499
<p>I'm using arch linux and I've installed Anaconda as per the instruction on the Anaconda site. When I'm attempting to run <code>conda info --envs </code> I get the following error:</p> <pre><code>bash: /home/lukasz/anaconda3/bin/conda: /opt/anaconda1anaconda2anaconda3/bin/python: bad interpreter: No such file or dir...
1
2016-10-05T22:10:27Z
39,884,767
<p>Something must have gone wrong during the installation, I suppose. The bad interpreter means that a script is looking for an interpreter that doesn't exist - as you rightfully pointed out.</p> <p>The problem is likely to be in the shebang <code>#!</code> statement of your conda script.</p> <blockquote> <p><em><a...
1
2016-10-05T22:38:04Z
[ "python", "linux", "anaconda" ]
Removing Duplicates conditional in Pandas based on all but on column?
39,884,561
<p>So I have a Pandas DataFrame loaded with a bunch of data, yet, there are some duplicates in the data. The way duplicates exist, make it hard to remove them. Imagine this:</p> <pre><code>1 |a |b |c |1232 2 | |b |c |1232 3 | |as ...
0
2016-10-05T22:16:52Z
39,885,121
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow">drop_duplicates</a>. If your column names are, let's say: <code>['A', 'B', 'C', 'D', 'E']</code> and your data frame is <code>df</code> and <code>row 0</code> and <code>row 1</code...
0
2016-10-05T23:16:59Z
[ "python", "database", "algorithm", "csv", "pandas" ]
Use context manager as a function
39,884,579
<p>I'd like to make a function which would also act as context manager if called with <code>with</code> statement. Example usage would be:</p> <pre><code># Use as function set_active_language("en") # Use as context manager with set_active_language("en"): ... </code></pre> <p>This is very similar to how the s...
2
2016-10-05T22:18:15Z
39,884,736
<p>Hopefully someone will prove me wrong, but I think the answer is <strong>no</strong>: there is no other way. And also, another short-coming of the method you chose is that it might misbehave when used along with other context managers in a <code>with a, b, c:</code> statement. The intended side-effect of the CM is e...
0
2016-10-05T22:34:00Z
[ "python" ]
Use context manager as a function
39,884,579
<p>I'd like to make a function which would also act as context manager if called with <code>with</code> statement. Example usage would be:</p> <pre><code># Use as function set_active_language("en") # Use as context manager with set_active_language("en"): ... </code></pre> <p>This is very similar to how the s...
2
2016-10-05T22:18:15Z
39,884,831
<p>Technically no, you cannot do this. But you can fake it well enough that people (who didn't overthink it) wouldn't notice.</p> <pre><code>def set_active_language(language): global active_language previous_language = active_language active_language = language class ActiveScope(object): def ...
2
2016-10-05T22:46:34Z
[ "python" ]
Comparing scipy.stats.t.sf vs GSL using Cython
39,884,665
<p>I would like to calculate the p values of a large 2D numpy t values array. However, this takes long time and I would like to improve its speed. I tried using GSL. Although a single gsl_cdf_tdist_P is much much faster than scipy.stats.t.sf, when iterating over the ndarray, the process is very slow. I would like help...
0
2016-10-05T22:26:32Z
39,898,055
<p>You can get some small gain in raw performance by using a raw special function instead of <code>stats.t.sf</code>. Looking at the source, you find (<a href="https://github.com/scipy/scipy/blob/master/scipy/stats/_continuous_distns.py#L3849" rel="nofollow">https://github.com/scipy/scipy/blob/master/scipy/stats/_cont...
1
2016-10-06T14:00:46Z
[ "python", "numpy", "scipy", "cython", "gsl" ]
iterate through number of columns, with variable columns
39,884,769
<p>For example, let's consider this toy code </p> <pre><code>import numpy as np import numpy.random as rnd a = rnd.randint(0,10,(10,10)) k = (1,2) b = a[:,k] for col in np.arange(np.size(b,1)): b[:,col] = b[:,col]+col*100 </code></pre> <p>This code will work when the size of <code>k</code> is bigger than 1. H...
2
2016-10-05T22:38:07Z
39,885,674
<p>If you index with a list or tuple, the 2d shape is preserved:</p> <pre><code>In [638]: a=np.random.randint(0,10,(10,10)) In [639]: a[:,(1,2)].shape Out[639]: (10, 2) In [640]: a[:,(1,)].shape Out[640]: (10, 1) </code></pre> <p>And I think <code>b</code> iteration can be simplified to:</p> <pre><code>a[:,k] += np....
0
2016-10-06T00:26:12Z
[ "python", "numpy", "for-loop", "matrix" ]
Communicate between two python app
39,884,815
<p>I have done two app's :</p> <ol> <li>The first one is a spider that extract all links from a website.<br></li> <li>The second one do some checks on each link sent by the first app.</li> </ol> <p>When the first app find a link, how can I send a notification or something else to the second app ?<br> The second app ...
0
2016-10-05T22:44:09Z
39,884,866
<p>You want to save one file as a "module" to be imported by the other file. Here this can be implemented with the the <code>import</code> keyword. For example, if you name the second part of your application <code>listener.py</code>, you can type <code>import listener</code> in your other file (remember to put them in...
0
2016-10-05T22:49:58Z
[ "python", "multithreading", "python-2.7", "queue" ]
Communicate between two python app
39,884,815
<p>I have done two app's :</p> <ol> <li>The first one is a spider that extract all links from a website.<br></li> <li>The second one do some checks on each link sent by the first app.</li> </ol> <p>When the first app find a link, how can I send a notification or something else to the second app ?<br> The second app ...
0
2016-10-05T22:44:09Z
39,885,079
<p>There are all sorts of ways to accomplish inter-process communication, but by far the simplest is to use the filesystem. Have your spider write it's output to a temp file. When it's finished, move it into a folder that your second process polls periodically and when it finds work, then process it.</p> <p>The <code...
0
2016-10-05T23:12:29Z
[ "python", "multithreading", "python-2.7", "queue" ]
Communicate between two python app
39,884,815
<p>I have done two app's :</p> <ol> <li>The first one is a spider that extract all links from a website.<br></li> <li>The second one do some checks on each link sent by the first app.</li> </ol> <p>When the first app find a link, how can I send a notification or something else to the second app ?<br> The second app ...
0
2016-10-05T22:44:09Z
39,885,092
<p>A <a href="https://en.wikipedia.org/wiki/Queue_%28abstract_data_type%29" rel="nofollow">Queue</a> is just a container into which items may be put and retrieved, often in <a href="https://en.wikipedia.org/wiki/FIFO_%28computing_and_electronics%29" rel="nofollow">FIFO</a> order. The <a href="https://docs.python.org/2/...
0
2016-10-05T23:13:55Z
[ "python", "multithreading", "python-2.7", "queue" ]
Converting and comparing 2 datetimes
39,884,856
<p>I need help trying to convert a string to datetime, then comparing it to see if it is less than 3 days old. I have tried both with the time class, as well as the datetime class, but I keep getting the same error:</p> <pre><code>TypeError: unsupported operand type(s) for -: 'str' and 'str' </code></pre> <p>here is ...
0
2016-10-05T22:48:46Z
39,885,249
<p>Indeed, don't convert back to strings and instead work with <code>datetime</code> objects. As noted in the error message <code>str - str</code> isn't an operation that's defined (what does it mean to subtract a string from another?):</p> <pre><code>"s" - "s" # TypeError </code></pre> <p>Instead, initialize <code>t...
1
2016-10-05T23:31:53Z
[ "python", "python-3.x", "datetime" ]
In Python Spyder interactive plotting. How do I link plots so that when I zoom in on a plot it zooms in on the rest
39,884,875
<p>In Python Spyder interactive plotting. How do I link plots so that when I zoom in on one plot in one figure, it zooms all the other plots that are on the same figure and different figure to the same scale? They are all plotted vs time which is mSec.</p> <p>Here is a sample of my current code that is still in the wo...
2
2016-10-05T22:50:41Z
39,885,682
<p><code>sharex</code> and <code>sharey</code> are your friends. Minimal example:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt fig1, (ax1, ax2) = plt.subplots(1,2,sharex=True, sharey=True) ax1.plot(np.random.rand(10)) ax2.plot(np.random.rand(11)) fig2 = plt.figure() ax3 = fig2.add_axes([0.1, 0.1...
1
2016-10-06T00:27:11Z
[ "python", "matplotlib", "spyder" ]
Large amount of multiprocessing.Process causing deadlock
39,884,898
<p><strong>Context</strong></p> <p>I need to run a multiprocessing.Process inside a multiprocessing.ThreadPool. It seems weird at first but it is the only way I found to deals with segfault that could occurs because I am using a c++ shared library. If a segfault append, the process is killed and I can check the proces...
0
2016-10-05T22:53:16Z
40,045,511
<p>The problem is also reproduced on the latest build of CPython - <code>Python 3.7.0a0 (default:4e2cce65e522, Oct 13 2016, 21:55:44)</code>.</p> <p>If you <a href="http://podoliaka.org/2016/04/10/debugging-cpython-gdb/" rel="nofollow">attach</a> to one of the stuck processes with gdb, you'll see that it's trying to a...
0
2016-10-14T14:21:46Z
[ "python", "multithreading", "multiprocessing", "deadlock" ]
How do I clear a ScatterPlotItem in PYQTGRAPH
39,884,931
<p>I am attempting to move a "cursor" around my graph using ScatterPlotItem and a '+' symbol as the cursor. The cursor updates its position perfectly but I cannot figure out how to clear the last instance. Here is the line that I use to plot the 'cursor'.</p> <pre><code>self.cursor2 = self.p2_3.addItem(pg.ScatterPlotI...
0
2016-10-05T22:56:04Z
39,889,712
<p>When you call addItem you add the plotdataitem, in this case a scatterplotitem to your plotitem. To remove it you call removeItem in the same way. But you need to keep a reference to the scatterplotitem to do that.</p> <p>Note that addItem doesn't return anything i.e. your self.cursor2 is None.</p> <p>If you want ...
1
2016-10-06T07:11:33Z
[ "python", "python-2.7", "pyqtgraph" ]
Mask an image (np.ndarray) section which lies between two curves
39,885,113
<p>Borrowing this example from astropy:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from astropy.io import fits from astropy.wcs import WCS from astropy.utils.data import download_file fits_file = 'http://data.astropy.org/tutorials/FITS-images/HorseHead.fits' image_file = download_file(fits...
2
2016-10-05T23:15:49Z
39,885,536
<p>A fairly straight forward way of generating such a mask would be to use the <code>numpy.mgrid</code> thingy that essentially gives you x and y-coordinate arrays (in that 2D case) that can then be used to compute the mask with the equation of the lines . </p> <p><strong>Edit :</strong> Provided you can express your ...
2
2016-10-06T00:08:49Z
[ "python", "numpy", "indexing", "mask", "scikit-image" ]
Mask an image (np.ndarray) section which lies between two curves
39,885,113
<p>Borrowing this example from astropy:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from astropy.io import fits from astropy.wcs import WCS from astropy.utils.data import download_file fits_file = 'http://data.astropy.org/tutorials/FITS-images/HorseHead.fits' image_file = download_file(fits...
2
2016-10-05T23:15:49Z
39,886,055
<p>The code snippet below creates a mask, sets all values outside the mask to nan, and then uses NumPy's <code>nanmedian</code> to calculate the desired quantity along the direction indicated.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib import gridspec from skimage.measure impor...
4
2016-10-06T01:19:50Z
[ "python", "numpy", "indexing", "mask", "scikit-image" ]
How can I see the RGB channels of a given image with python?
39,885,178
<p>Imagine a I have an image and I want to split it and see the RGB channels. How can I do it using python?</p>
0
2016-10-05T23:21:49Z
39,885,418
<p>My favorite approach is using <a href="http://scikit-image.org/" rel="nofollow">scikit-image</a>. It is built on top of numpy/scipy and images are internally stored within numpy-arrays.</p> <p>Your question is a bit vague, so it's hard to answer. I don't know exactly what you want to do but will show you some code....
0
2016-10-05T23:54:07Z
[ "python", "image", "image-processing", "rgb" ]
Access folder that a custom python function resides in
39,885,180
<p>How do I access a folder that a python function resides in?</p> <p>For example, lets say that I have a N by 2 array of data. First column is the independent variable, and second is the dependent variable. I need to interpolate this data with different array of independent variable who's range is contained in the or...
2
2016-10-05T23:22:35Z
39,885,367
<p>Like this: </p> <pre><code>import os my_dir = os.path.dirname(__file__) fname = 'file_path_in_the_function_folder.txt' filepath = os.path.join(my_dir, fname) </code></pre> <p>As explained in the <a href="https://docs.python.org/3/reference/datamodel.html?highlight=__file__" rel="nofollow">data model</a>, you can...
1
2016-10-05T23:48:04Z
[ "python" ]
urllib.request: Data Not Writing to Outfile
39,885,277
<p>I've got a script here which (ideally) iterates through multiple pages X of JSON data for each entity Y (in this case, multiple loans X for each team Y). The way that the api is constructed, I believe I must physically change a subdirectory within the URL in order to iterate through multiple entities. Here is the ex...
0
2016-10-05T23:34:24Z
39,885,812
<p>For others who may read this post, the script does in face write data to an outfile. It was simply test code logic that was wrong. Ignore the print statements I have put into place.</p>
0
2016-10-06T00:46:46Z
[ "python", "json", "rest", "python-3.x", "urllib" ]
GtkFileChooserDialog does not act as modal
39,885,351
<p>I have a <a href="https://paste.gnome.org/pvxwgixip/lyrvkg" rel="nofollow">custom</a> <code>GtkFileChooserDialog</code> created with Glade. The <code>Modal</code> property is marked. I also have a <code>GtkFileChooserButton</code> that uses this <code>GtkFileChooserDialog</code> as its dialog:</p> <pre><code>class ...
0
2016-10-05T23:45:18Z
39,919,924
<p>Would <a href="http://stackoverflow.com/a/39873728/1981374">grabbing</a> the pointer work for you?</p> <pre><code>//pass all events to window apart LEAVE_NOTIFY_MASK MainWindow-&gt;set_events(GDK_EXPOSURE_MASK | GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK | GDK_BUTTON_MOTION_MASK | GDK_BUTTON1_MOTION_MA...
0
2016-10-07T14:39:41Z
[ "python", "gtk", "gtk3", "pygobject" ]
Py installer, cannot add .txt files
39,885,354
<p>I'm fairly new with programming (and so with python) and the stackoverflow question/response system allowed me to resolve all my problems until now. However, I didn't find any post addressing directly my current issue, but have to admit that I don't really know what's wrong. Let me explain.</p> <p>I'm trying to mak...
0
2016-10-05T23:45:34Z
39,885,430
<p>after the line</p> <pre><code>a = Analysis( ... ) </code></pre> <p>add </p> <pre><code>a.datas += [ ("/absolute/path/to/some.txt","txt_files/some.txt","DATA"), ("/absolute/path/to/some2.txt","txt_files/some2.txt","DATA"), ("/absolute/path/to/some3.txt","txt_files/some3.txt","DATA"), ] </code></pre> <...
1
2016-10-05T23:54:45Z
[ "python", "python-3.x", "pyinstaller" ]
Beautifulsoup decompose()
39,885,359
<p>I'm trying to get rid of <code>&lt;script&gt;</code> tags and the content inside the tag utilizing beatifulsoup. I went to the documentation and seems to be a really simple function to call. More information about the function is <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#decompose" rel="nofollo...
0
2016-10-05T23:46:26Z
39,904,439
<blockquote> <p><code>soup.script.decompose()</code></p> </blockquote> <p>This would remove a <em>single script element</em> from the "Soup" only. Instead, I think you meant to decompose all of them:</p> <pre><code>for script in soup("script"): script.decompose() </code></pre>
0
2016-10-06T19:44:19Z
[ "python", "python-3.x", "beautifulsoup" ]
Get python tcp server to send and recive messages once that are sent?
39,885,364
<p>I have been experimenting with network programing with python. To teach myself how to do this I have been playing with multiple versions of TCP chat servers and clients. My newest attempt has left me wondering what is wrong with the code I have just written. Only when a message has been sent from the client I have j...
1
2016-10-05T23:47:33Z
39,936,234
<p>I am pretty new to socket programming, so this may be a shot in the darK:</p> <ul> <li>The client is generating a lot of threads reading and writing from a blocking socket. It looks like only a single operation can be performed at one time, a thread is blocking on a write or a thread is blocking on a read, since th...
0
2016-10-08T19:02:39Z
[ "python", "sockets", "tcp", "concurrency" ]
Pyinstaller not getting all modules - ImportError: No module named logilab.constraint
39,885,396
<p>I am trying to compile a python script into a .exe using Pyinstaller. I am using python 2.7, Pyinstaller 3.2 and windows 7.</p> <p>The script is using a module called "logilab", and another called "logilab.constraint".</p> <p>I have installed both modules succesfully using pip. The script runs fine, but when tryin...
0
2016-10-05T23:51:34Z
39,885,444
<p>on the first line of your script(schedule_maker.py) just add</p> <pre><code>import logilib import logilib.constraint </code></pre> <p>basically pyinstallers analysis probably didnt realize that you needed that package</p>
0
2016-10-05T23:56:53Z
[ "python", "python-2.7", "module", "pyinstaller" ]
Pyinstaller not getting all modules - ImportError: No module named logilab.constraint
39,885,396
<p>I am trying to compile a python script into a .exe using Pyinstaller. I am using python 2.7, Pyinstaller 3.2 and windows 7.</p> <p>The script is using a module called "logilab", and another called "logilab.constraint".</p> <p>I have installed both modules succesfully using pip. The script runs fine, but when tryin...
0
2016-10-05T23:51:34Z
39,909,502
<p>Apparently just installing the modules from their "setup.py" file was not enough, I had to </p> <pre><code>pip install --upgrade </code></pre> <p>on both of them. that fixed it.</p>
0
2016-10-07T04:39:42Z
[ "python", "python-2.7", "module", "pyinstaller" ]
Finding the same second elements in nested lists - recursive function
39,885,472
<p>I have nested lists looks like this;</p> <pre><code>[['CELTIC AMBASSASDOR', 'Warrenpoint'],['HAV SNAPPER', 'Silloth'],['BONAY', 'Antwerp'],['NINA', 'Antwerp'],['FRI SKIEN', 'Warrenpoint']] </code></pre> <p>and goes on. How can I find the lists that have same second elements, for example</p> <pre><code>['CELTIC AM...
-1
2016-10-05T23:59:57Z
39,885,526
<p>There's no need to use recursion here. Create a dictionary with a key of the second element and values of the whole sublist, then create a result that only includes the matches you're interested in:</p> <pre><code>import collections l = [['CELTIC AMBASSASDOR', 'Warrenpoint'],['HAV SNAPPER', 'Silloth'],['BONAY', 'An...
2
2016-10-06T00:07:46Z
[ "python", "list", "recursion", "python-3.4", "nested-lists" ]
Finding the same second elements in nested lists - recursive function
39,885,472
<p>I have nested lists looks like this;</p> <pre><code>[['CELTIC AMBASSASDOR', 'Warrenpoint'],['HAV SNAPPER', 'Silloth'],['BONAY', 'Antwerp'],['NINA', 'Antwerp'],['FRI SKIEN', 'Warrenpoint']] </code></pre> <p>and goes on. How can I find the lists that have same second elements, for example</p> <pre><code>['CELTIC AM...
-1
2016-10-05T23:59:57Z
39,886,638
<pre><code>filter(lambda x:x[1] in set(filter(lambda x:zip(*l)[1].count(x)==2,zip(*l)[1])),l) </code></pre>
0
2016-10-06T02:38:00Z
[ "python", "list", "recursion", "python-3.4", "nested-lists" ]
What is the meaning of single quote(') in matlab, and how to change it to python
39,885,495
<pre><code>grad = (1/m * (h-y)' * X) + lambda * [0;theta(2:end)]'/m; cost = 1/(m) * sum(-y .* log(h) - (1-y) .* log(1-h)) + lambda/m/2*sum(theta(2:end).^2); </code></pre> <p>How to change this two lines to python? I tried to use the <code>zip</code> to do the same job as '. But it shows the error. </p>
1
2016-10-06T00:02:59Z
39,902,500
<p><strong>Short answer:</strong></p> <p>The <code>'</code> operator in MATLAB is the <em>matrix</em> (conjugate) transpose operator. It flips the matrix around dimensions and takes the complex conjugate of the matrix (the second part being what trips people up) The short answer is that the equivalent of <code>a'</c...
8
2016-10-06T17:45:18Z
[ "python", "matlab", "matrix", "transpose" ]
Searching for value in a text file then printing the next line
39,885,496
<p>I am importing a txt file into Python 3, I am able to successfully print the item/line I am using as an identifier, however I am having difficulty printing the following line and retaining that value. </p> <p>I am using <code>'Anchor'</code> to find the line items which follow. The number of lines between each <cod...
1
2016-10-06T00:03:02Z
39,885,610
<p>You could introduce a variable representing the state of the last line, like this:</p> <pre><code>previous_line_was_anchor = False for line in f.readlines(): if 'Anchor' in line: previous_line_was_anchor = True else: if previous_line_was_anchor: print line previous_line...
0
2016-10-06T00:17:50Z
[ "python", "file", "python-3.x" ]
Searching for value in a text file then printing the next line
39,885,496
<p>I am importing a txt file into Python 3, I am able to successfully print the item/line I am using as an identifier, however I am having difficulty printing the following line and retaining that value. </p> <p>I am using <code>'Anchor'</code> to find the line items which follow. The number of lines between each <cod...
1
2016-10-06T00:03:02Z
39,914,720
<p>I would highly recommend using <a href="https://docs.python.org/2/library/stdtypes.html?highlight=iterator#iterator-types" rel="nofollow">python iterators</a>.</p> <p>It looks like your problem would be more suited to a custom iteration, rather than using a <code>for .. in ..</code> loop:</p> <pre><code>lines = it...
0
2016-10-07T10:09:00Z
[ "python", "file", "python-3.x" ]
Finding the max of each continguous subarray of a given size
39,885,520
<p>I'm trying to solve the following problem in Python</p> <blockquote> <p>Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.</p> </blockquote> <p>The idea is to use a double ended queue. This is my code:</p> <pre><code>def diff_sliding_window(arr, win): # max =...
0
2016-10-06T00:07:10Z
39,885,747
<p>What about this approach (which only needs one pass over the data):</p> <h3>Code</h3> <pre><code>def calc(xs, k): k_max = [] result = [] for ind, val in enumerate(xs): # update local maxes (all are active) for i in range(len(k_max)): if val &gt; k_max[i] : k...
0
2016-10-06T00:37:47Z
[ "python", "algorithm", "data-structures", "queue" ]
Finding the max of each continguous subarray of a given size
39,885,520
<p>I'm trying to solve the following problem in Python</p> <blockquote> <p>Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.</p> </blockquote> <p>The idea is to use a double ended queue. This is my code:</p> <pre><code>def diff_sliding_window(arr, win): # max =...
0
2016-10-06T00:07:10Z
39,885,772
<p>Here's a simple solution using <code>itertools</code> and <code>tee</code>:</p> <pre><code>def nwise(iterable, n): ''' Step through the iterable in groups of n ''' ts = it.tee(iterable, n) for c, t in enumerate(ts): next(it.islice(t, c, c), None) return zip(*ts) def max_slide(ns, l): re...
0
2016-10-06T00:41:08Z
[ "python", "algorithm", "data-structures", "queue" ]
Finding the max of each continguous subarray of a given size
39,885,520
<p>I'm trying to solve the following problem in Python</p> <blockquote> <p>Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.</p> </blockquote> <p>The idea is to use a double ended queue. This is my code:</p> <pre><code>def diff_sliding_window(arr, win): # max =...
0
2016-10-06T00:07:10Z
39,886,533
<p>It looks like you are trying to implement the O(n) algorithm for this problem, which would be better than the other two answers here at this time.</p> <p>But, your implementation is incorrect. Where you say <code>arr[i] &gt;= arr[len(Q)-1]</code>, you <em>should</em> say <code>arr[i] &gt;= arr[Q[len(Q)-1]]</code> ...
1
2016-10-06T02:24:43Z
[ "python", "algorithm", "data-structures", "queue" ]
getting scalar form dataframe
39,885,537
<p>how to retrieve single scalar from a pandas dataframe column using filtering on another. I am using .value[0] but I would like something better.</p> <pre><code>df['Age_in_years'][ df['Sample_id'] == id_sample ].values[0] df.loc[df['Sample_id'] == id_sample, 'Age_in_years'].values[0] </code></pre>
0
2016-10-06T00:08:52Z
39,885,620
<p>You can call <code>idxmax()</code> on the condition series, which returns:</p> <blockquote> <p>Index of first occurrence of maximum of values.</p> </blockquote> <p>Which in this case is the <em>Index of the first True</em>, and then use <code>loc</code> to find the corresponding value: </p> <pre><code>df = pd.D...
1
2016-10-06T00:19:20Z
[ "python", "pandas" ]
Combining paths using os.path.join
39,885,557
<p>I was wondering how you correctly use os.path. Basically what I'm trying to do is ask the user for a directory and after that, they type a letter (<code>N</code> in this case), and then a filename in the directory and it will combine the directory with the file.</p> <p>For example:</p> <pre><code>C:\Desktop </code...
0
2016-10-06T00:11:51Z
39,885,803
<p>Here, this should work.</p> <pre><code>def search_characteristics(directory): interesting = input() interesting = interesting.split(" ") if (interesting[0] == 'N'): directory += (os.sep + interesting[1]) print(directory) elif interesting.startswith('E'): return os.path.splite...
0
2016-10-06T00:45:34Z
[ "python", "python-3.4", "os.path" ]
How do I distribute all contents of root directory to a directory with that name
39,885,637
<p>I have a project named <code>myproj</code> structured like</p> <pre><code>/myproj __init__.py module1.py module2.py setup.py </code></pre> <p>my <code>setup.py</code> looks like this</p> <pre><code>from distutils.core import setup setup(name='myproj', version='0.1', description='Does ...
2
2016-10-06T00:20:38Z
39,885,719
<p>In your <code>myproj</code> root directory for this project, you want to move <code>module1.py</code> and <code>module2.py</code> into a directory named <code>myproj</code> under that, and if you wish to maintain Python &lt; 3.3 compatibility, add a <code>__init__</code>.py into there.</p> <pre><code>├── mypr...
1
2016-10-06T00:32:25Z
[ "python", "distutils", "setup.py" ]
Interpolating 2 numpy arrays
39,885,723
<p>Is there any numpy or scipy or python function to interpolate between two 2D numpy array's? I have two 2D numpy arrays, and I want to apply changes to the first numpy array to make it similar to the second 2D array. The constraint is that I want the changes to be smooth. e.g., let the arrays be:</p> <pre><code>A [[...
3
2016-10-06T00:33:07Z
39,898,561
<p>One way of smoothing could be to use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html" rel="nofollow">convolve2d</a>:</p> <pre><code>import numpy as np from scipy import signal B = np.array([[34, 100, 15], [62, 17, 87], [17, 34, 60]]) kernel = ...
1
2016-10-06T14:22:31Z
[ "python", "numpy" ]
Interpolating 2 numpy arrays
39,885,723
<p>Is there any numpy or scipy or python function to interpolate between two 2D numpy array's? I have two 2D numpy arrays, and I want to apply changes to the first numpy array to make it similar to the second 2D array. The constraint is that I want the changes to be smooth. e.g., let the arrays be:</p> <pre><code>A [[...
3
2016-10-06T00:33:07Z
40,050,430
<p>You've just described a Kalman Filtering / data fusion problem. You have an initial state <strong>A</strong> that has some errors and you have some observations <strong>B</strong> that also have some noise. You want to improve your estimate of state <strong>A</strong> by injecting some information from <strong>B</st...
1
2016-10-14T19:09:24Z
[ "python", "numpy" ]
Why do I only print the first letters of each item in the list?
39,885,741
<p>I was wondering why I only print the first letter of each item I input. I would like for it to loop through the list and print each item that starts with one of the letters in the first_letters variable. </p> <pre><code>phrase = input('Enter a list: ') first_letters = ['A','B','C','D'] for name in phrase: if na...
-3
2016-10-06T00:36:19Z
39,885,773
<p>What @idjaw meant to say was the input which is a string is an <code>iterable</code>.</p> <p>Which means when you run the for loop on <code>name</code> it iterates over each letter in the string passed.</p> <p>If you'd want to read a list or store the input as a list, it'd be best to store the result as a space or...
0
2016-10-06T00:41:27Z
[ "python" ]
Why do I only print the first letters of each item in the list?
39,885,741
<p>I was wondering why I only print the first letter of each item I input. I would like for it to loop through the list and print each item that starts with one of the letters in the first_letters variable. </p> <pre><code>phrase = input('Enter a list: ') first_letters = ['A','B','C','D'] for name in phrase: if na...
-3
2016-10-06T00:36:19Z
39,885,775
<p>If this is Python3, then the list you are entering is not actually a list but a string. So when you call,</p> <pre><code>for name in phrase: </code></pre> <p>you are calling each letter in that string. So the variable <code>name</code> is actually one letter so <code>name[0]</code> is equal to <code>name</code>.</...
0
2016-10-06T00:41:40Z
[ "python" ]
Why do I only print the first letters of each item in the list?
39,885,741
<p>I was wondering why I only print the first letter of each item I input. I would like for it to loop through the list and print each item that starts with one of the letters in the first_letters variable. </p> <pre><code>phrase = input('Enter a list: ') first_letters = ['A','B','C','D'] for name in phrase: if na...
-3
2016-10-06T00:36:19Z
39,885,855
<p>Considering your input as: </p> <pre><code>Alpha, Bravo, Charlie, Delta, Echo, Foxtrot </code></pre> <p>This complicates handling your input a bit. Because you are now going to have to deal with a space and a comma between each word.</p> <p>Upon entering your user input, handle all spaces, and then use <code>spli...
0
2016-10-06T00:52:25Z
[ "python" ]
Why do I only print the first letters of each item in the list?
39,885,741
<p>I was wondering why I only print the first letter of each item I input. I would like for it to loop through the list and print each item that starts with one of the letters in the first_letters variable. </p> <pre><code>phrase = input('Enter a list: ') first_letters = ['A','B','C','D'] for name in phrase: if na...
-3
2016-10-06T00:36:19Z
39,886,184
<p>For input Alpha,Bravo,Charlie,Delta,Echo,Foxtrot</p> <p>If you are entering comma after each name you enter use .split(',') if you are just using space between names use .split()</p> <p>.split() looks for an empty space and splits the user input after space and .split(',') looks for comma and splits the user input...
0
2016-10-06T01:39:08Z
[ "python" ]
Most efficient way to determine overlapping timeseries in Python
39,885,770
<p>I am trying to determine what percentage of the time that two time series overlap using python's pandas library. The data is nonsynchronous so the times for each data point do not line up. Here is an example:</p> <p><strong>Time Series 1</strong></p> <pre><code>2016-10-05 11:50:02.000734 0.50 2016-10-05 11:50:0...
6
2016-10-06T00:40:44Z
39,886,191
<p>Cool problem. I brute forced this w/out using pandas or numpy, but I got your answer (thanks for working it out). I have not tested it on anything else. I also don't know how fast it is since it only goes through each dataframe once, but does not do any vectorization.</p> <pre><code>import pandas as pd ############...
3
2016-10-06T01:39:39Z
[ "python", "performance", "pandas", "vector", "time-series" ]
Most efficient way to determine overlapping timeseries in Python
39,885,770
<p>I am trying to determine what percentage of the time that two time series overlap using python's pandas library. The data is nonsynchronous so the times for each data point do not line up. Here is an example:</p> <p><strong>Time Series 1</strong></p> <pre><code>2016-10-05 11:50:02.000734 0.50 2016-10-05 11:50:0...
6
2016-10-06T00:40:44Z
39,986,401
<p><strong><em>setup</em></strong><br> create 2 time series</p> <pre><code>from StringIO import StringIO import pandas as pd txt1 = """2016-10-05 11:50:02.000734 0.50 2016-10-05 11:50:03.000033 0.25 2016-10-05 11:50:10.000479 0.50 2016-10-05 11:50:15.000234 0.25 2016-10-05 11:50:37.000199 0.50 2016-10...
6
2016-10-11T20:43:21Z
[ "python", "performance", "pandas", "vector", "time-series" ]
Variable shape tensor
39,885,928
<p>I need to get a tensor that is variable shape as I do not know the vector size before hand. So far I tried: </p> <pre><code>hashtag_len = tf.placeholder(tf.int32) train_hashtag = tf.placeholder(tf.int32, shape=[hashtag_len]) </code></pre> <p>but I get the error <code>TypeError: int() argument must be a string, a b...
1
2016-10-06T01:03:04Z
39,886,448
<p>Use</p> <p><code>tf.placeholder(tf.int32)</code></p> <p>That creates placeholder of arbitrary shape</p>
2
2016-10-06T02:12:11Z
[ "python", "tensorflow" ]
Variable shape tensor
39,885,928
<p>I need to get a tensor that is variable shape as I do not know the vector size before hand. So far I tried: </p> <pre><code>hashtag_len = tf.placeholder(tf.int32) train_hashtag = tf.placeholder(tf.int32, shape=[hashtag_len]) </code></pre> <p>but I get the error <code>TypeError: int() argument must be a string, a b...
1
2016-10-06T01:03:04Z
39,893,341
<p>If you want a VECTOR for sure, you should do the following:</p> <pre><code>train_hashtag = tf.placeholder(tf.int32, shape=[None]) </code></pre> <p>This shape describes vector of arbitrary length.</p>
3
2016-10-06T10:15:29Z
[ "python", "tensorflow" ]
The bin count displayed by pyplot hist doesn't match the actual counts?
39,885,949
<p>I have a list of ints--I call it 'hours1'--ranging from 0-23. Now this list is for 'hours' of a day in a 24 hour clock. I, however, want to transform it to a different time zone (move up 7 hours). This is simple enough, and I do it so that now I have 2 lists: hours1 and hours2.</p> <p>I use the following code to ...
0
2016-10-06T01:05:46Z
39,887,514
<p>The issue was a binning one. In short, I wasn't paying attention/thinking about what I wanted to display. More specifically this was the correct code:</p> <pre><code>bins = range(25) plt.hist(hours, normed=0, facecolor='green', alpha=0.5, bins=bins) plt.axis([0, 24, 0, 1500]) </code></pre> <p>that is, there are ...
0
2016-10-06T04:26:11Z
[ "python", "matplotlib" ]
Preserving Rich Text Formatting in Excel via Python
39,885,978
<p>I'm trying to add rows to an Excel file via Python (need this to run and refresh daily). The Excel file is essentially a template, at the top of which has some cells for some of the words within a cell have specific formatting, i.e. cell value "That cat is <strong><em>fluffy</em></strong>". </p> <p>I can't quite fi...
1
2016-10-06T01:09:14Z
39,885,996
<p>Please refer to this link over here, as it may help you with keeping the formatting</p> <p><a href="http://stackoverflow.com/questions/3723793/preserving-styles-using-pythons-xlrd-xlwt-and-xlutils-copy">Preserving styles using python&#39;s xlrd,xlwt, and xlutils.copy</a></p> <p>though it doesn't keep the cell comm...
0
2016-10-06T01:13:20Z
[ "python", "excel" ]
Django not connecting to MySQL properly, throws "ImportError: cannot import name 'NULL'"
39,886,028
<p>I want to use Django (using Python 3) with MySQL. To do so, I installed <a href="https://pypi.python.org/pypi/mysqlclient" rel="nofollow">mysqlclient</a>. To first test the waters with MySQL, I also created a new Django project and app, changed the DATABASES configuration in "settings.py" to settings I prepared in M...
1
2016-10-06T01:16:51Z
39,887,369
<p>Ok, there are several problems here.</p> <p>First of all you cannot copy files from one python installation or virtual installation to another python installation or virtualenv. Please delete your current virtualenv and make a new one, detailed instructions are here: <a href="http://docs.python-guide.org/en/latest/...
0
2016-10-06T04:10:41Z
[ "python", "mysql", "django" ]
How to search datetime index and place None-values to another variables whenever it is weekend Python
39,886,037
<p>Say that I have a pandas <code>df</code> which contains financial time-series data with datetime index. An example: </p> <pre><code>x = ['10-06-2016', '10-07-2016', '10-10-2016', '10-11-2016', '10-12-2016'] y = [0,1,2,3,4] </code></pre> <p>Note that I don't have time-series values on weekends, which is why '10-0...
0
2016-10-06T01:17:44Z
39,886,270
<p>You can <code>reindex</code> the data frame which has a <code>datetimeIndex</code> with a wider range of date as follows, missing values will be filled with <code>NaN</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Value': y}, index=pd.to_datetime(x)) # Value #2016-10-06 0 #2016-10-07 1 #2016-...
0
2016-10-06T01:48:42Z
[ "python", "datetime", "pandas" ]
Writing to Multiple Files
39,886,038
<p>I'm sure many of us are familiar with the python file IO pattern to write data to an outfile, as seen below;</p> <pre><code>outfile = open("myFile", "w") data.dump() outfile.close() </code></pre> <p>This is all supposing that we already have the file and can access it. Now, I want to create something a bit more co...
-2
2016-10-06T01:17:53Z
39,886,057
<pre><code>&gt;&gt;&gt; my_list = [] &gt;&gt;&gt; for i in range(1, 1001): ... # do something with the data... in this case, simply appending i to a list ... my_list.append(i) ... if i % 100 == 0: ... # create a new file name... it's that easy! ... file = fname + str(i) + ".txt" ... ...
1
2016-10-06T01:20:15Z
[ "python", "file-io" ]
Overwriting Google Drive API v3 Argparse in Python
39,886,041
<p>I'm trying to use the Google Drive API (v3) with Python to obtain and upload files to my Google Drive account. </p> <p>I used this guide to setup my authentication: <a href="https://developers.google.com/drive/v3/web/quickstart/python" rel="nofollow">https://developers.google.com/drive/v3/web/quickstart/python</a><...
0
2016-10-06T01:18:35Z
39,886,896
<p>I think there have been other questions about <code>argparse</code> and the <code>google api</code>, but I haven't used the latter.</p> <p>Parsers are independent and can't be over written. But they all (as a default anyways) use <code>sys.argv[1:]</code>. So if your code runs before the other one, you can edit <...
0
2016-10-06T03:08:25Z
[ "python", "google-drive-sdk", "argparse", "oauth2" ]
Overwriting Google Drive API v3 Argparse in Python
39,886,041
<p>I'm trying to use the Google Drive API (v3) with Python to obtain and upload files to my Google Drive account. </p> <p>I used this guide to setup my authentication: <a href="https://developers.google.com/drive/v3/web/quickstart/python" rel="nofollow">https://developers.google.com/drive/v3/web/quickstart/python</a><...
0
2016-10-06T01:18:35Z
39,887,497
<p>Nevermind, I figured it out. hpaulj had it right.</p> <p>In the get_credentials() method, right before it called run_flow(), I simply had to add a line saying:</p> <pre><code>flags=tools.argparser.parse_args(args=[]) credentials=tools.run_flow(flow, store, flags) </code></pre> <p>And at the beginning when I read ...
0
2016-10-06T04:23:57Z
[ "python", "google-drive-sdk", "argparse", "oauth2" ]
Can I use a decorator to loop through nested list?
39,886,054
<p>I am having to loop through a 2-dimensional grid (rows and columns) repeatedly to execute various functions at each cell in the grid. Each time I want to apply another to the cells, I have to code the nested loop...</p> <pre><code>for row in rows: for col in row: func(col) </code></pre> <p>So to avoid re...
0
2016-10-06T01:19:47Z
39,886,168
<p>Sure, you can write a decorator to transform a function that works on a single element into one that works on a grid using a nested loop:</p> <pre><code>def gridfunc(func): def wrapper(grid): results = [] for row in grid: for col in row: results.append(func(col)) ...
0
2016-10-06T01:37:26Z
[ "python", "decorator" ]
I keep getting an attribute error 'int' object has no attribute 'dollars'
39,886,063
<p>Im working on this Money class and everything worked fine up until the multiplication. I keep getting an attribute error and can't figure out where I'm going wrong. The multiplication is of type float.</p> <pre><code>class Money: def __init__(self, d, c): self.dollars = d self.cents = c def...
0
2016-10-06T01:22:08Z
39,886,163
<p>In <code>m2.times(3)</code>, you're passing the <code>int</code> <code>3</code> to the <code>times</code> method. In the times method, though, you're trying to multiply by <code>mult.dollars</code>, and not the <code>dollars</code> (<code>3</code>) that you actually passed. </p> <p><code>mult.dollars</code> doesn't...
3
2016-10-06T01:36:26Z
[ "python", "class", "attributes" ]
Django How I can pass request.user(current logged user) in forms when I use class based view?
39,886,067
<p>I wanted to pass request.user to show current user in a form with ModelMultipleChoiceField. I could figure out my problem thanks to here <a href="http://stackoverflow.com/a/25184373/6568309">http://stackoverflow.com/a/25184373/6568309</a>. I fixed my code like below.</p> <p><strong>but I could get solution with onl...
0
2016-10-06T01:22:26Z
39,886,111
<p>You can override method <code>get_form_kwargs</code> from <code>FormView</code> class view in order to set inital data for your form. </p> <pre><code>class YouFormView(FormView): teplate_name = 'your template' form_class = YourForm def get_form_kwargs(self): user = self.request.user fo...
1
2016-10-06T01:28:19Z
[ "python", "django" ]
Is there a way to make selenium webdriver screenshot an entire page?
39,886,081
<p>The title is pretty self explanatory. I have a page with an iframe and two columns (left and right)</p> <p>Left has no scroll bar, while right has a scroll bar with a total of 600px to scroll. I need to screenshot the entirety of the right hand column. It doesn't matter if I get the entire page or not, as long as e...
0
2016-10-06T01:24:34Z
39,887,962
<p>There is workaround by following the steps described in <a href="http://www.ramandv.com/blog/angularjs-protractor-selenium-headless-end-end-testing/" rel="nofollow">http://www.ramandv.com/blog/angularjs-protractor-selenium-headless-end-end-testing/</a> and create a gaint virtual display for running your program.</p>...
0
2016-10-06T05:11:24Z
[ "python", "selenium", "selenium-webdriver", "webdriver" ]
Python Curses: Exiting a program fast
39,886,252
<p>What is the best way to quickly exit a Python program with an infinite loop that uses curses module? </p> <p>I've tried adding nodelay() method coupled with this at the end of the loop: </p> <pre><code>if screen.getch() == ord('q'): break </code></pre> <p>However, it takes 2-3 seconds to make all the function...
0
2016-10-06T01:46:51Z
39,886,654
<p>What's probably happening is that your <code>'q'</code> is coming in between the <code>getch()</code> and the <code>sleep</code> calls. Given that <code>getch()</code> takes a fraction of a second to execute and <code>sleep</code> locks the program for 5 seconds, it's very likely that any time you press a key you're...
0
2016-10-06T02:40:14Z
[ "python", "ncurses", "python-curses" ]
Python Curses: Exiting a program fast
39,886,252
<p>What is the best way to quickly exit a Python program with an infinite loop that uses curses module? </p> <p>I've tried adding nodelay() method coupled with this at the end of the loop: </p> <pre><code>if screen.getch() == ord('q'): break </code></pre> <p>However, it takes 2-3 seconds to make all the function...
0
2016-10-06T01:46:51Z
39,891,775
<p>Given that you have nodelay already, the usual approach is to use napms with a small (20-50 milliseconds) time, and addressing your 5-seconds goal, to run the functions after several (10-25) repetitions of the getch/napms loop.</p> <p>Mixing curses and standard I/O doesn't really work well unless you take care to f...
0
2016-10-06T08:58:33Z
[ "python", "ncurses", "python-curses" ]
Use a Dictionary generated from CSV to update values in .xlsx file using python
39,886,306
<p>Every day I am given an old Excel 95 file of data. It has columns up to the letter 'L' and hundreds of rows. Column 'B' is a customer reference number, it's unique to each customer. Column 'I' is a dollar value. </p> <p>Each morning I need to use this file to update another Excel file. I search for the customer re...
1
2016-10-06T01:53:01Z
39,950,895
<p>Simply the problem is a type mismatch. The keys read in from csv are in <code>string</code> format and the values read in from the Excel sheet are <code>float</code> values. So the <code>if</code> statement to match the two always return <em>false</em>.</p> <p>To align the data types, adjust following line in secon...
0
2016-10-10T03:26:54Z
[ "python", "python-3.x", "csv", "dictionary", "openpyxl" ]
How to change image format without writing it to disk using Python Pillow
39,886,326
<p>I got Pillow image that i got from the Internet:</p> <pre><code>response= urllib2.urlopen(&lt;url to gif image&gt;) img = Image.open(cStringIO.StringIO(response.read())) </code></pre> <p>I want to use it with tesserocr but it wont work with GIF images.</p> <p>If I save the image as PNG <code>img.save("tmp.png")</...
1
2016-10-06T01:56:12Z
39,899,744
<p>The solution was very simple:</p> <pre><code>response= urllib2.urlopen(&lt;url to gif image&gt;) img = Image.open(cStringIO.StringIO(response.read())) img = img.convert("RGB") </code></pre> <p>Note that you need to remove the alpha channel info to make image compatible with tesserocr</p>
0
2016-10-06T15:14:44Z
[ "python", "python-2.7", "pillow", "cstringio" ]
__main__.py Behavior Different Between Python 2 and 3
39,886,363
<p>I find it convenient to place my program entry point in a different file from <code>__main__.py</code>. Below are two example files located in the same package (<code>test_1</code>):</p> <p><code>__main__.py:</code></p> <pre><code>import sys from main import main as entry_point if __name__ == '__main__': scri...
0
2016-10-06T01:59:35Z
39,886,489
<p>For Python 3, the <code>__main__.py</code> needs to use an explicit relative import, so <code>from .main import main as entry_point</code> instead of <code>from main import main as entry_point</code>.</p>
0
2016-10-06T02:19:03Z
[ "python", "python-2.7", "python-3.x" ]
Input Validation loop / read file txt with Python
39,886,404
<p>My first issue is my file is not being read by the script and truthfully I do not know why.</p> <p>Second, the issue is my loop "y" or "Y" is not looping the question of account input for a user, it just continues to repeat until I hit "n" or "N" to exit....which works. (so I guess my loop works properly in that se...
-1
2016-10-06T02:07:14Z
39,886,514
<p>With regards to your loop, everything you want to be repeated needs to be inside of it. So think about what you've written, <code>while another == y:</code> the <em>body of the loop</em> will be repeated. So, my advice would be to think about <em>where you start looping</em>. </p> <p>Also, <code>accountNum in infil...
2
2016-10-06T02:22:42Z
[ "python", "loops", "readfile" ]
Argument 1 must be string, not datetime.datetime?
39,886,457
<p>I just took a Data Analysis course on Udacity. My code is:</p> <pre><code>enrollments_filename= '/Users/abc/Desktop/Udacity - Intro to Data Analysis/enrollments.csv' def open_file(filename): with open(filename, 'rb') as f: reader = unicodecsv.DictReader(f) return list(reader) enrollments = ope...
-1
2016-10-06T02:13:12Z
39,886,546
<p>I bet you ran this line twice in your shell/session:</p> <pre><code>enrollment['cancel_date'] = parse_date(enrollment['cancel_date']) </code></pre> <p>The first time works, but now enrollment['cancel_date'] is a date, not a string. Second time you ran it - error.</p>
0
2016-10-06T02:26:55Z
[ "python", "datetime" ]