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 |
|---|---|---|---|---|---|---|---|---|---|
Copy a paragraph into the same document(python 3.x, docx) | 38,077,616 | <p>Let's say I have a certain paragraph in my docx document with certain text formatting, for example: <br>
"Foo <strong>bar</strong>" <br>
I want to make something like a template of this paragraph to copy it into the same document multiple times.<br>
Copying text like in the example means loosing text formatting.<br>... | 1 | 2016-06-28T13:29:14Z | 38,083,355 | <p>In your simple example, you could do something like this:</p>
<pre><code>def clone_run_props(tmpl_run, this_run):
this_run.bold = tmpl_run.bold
... maybe other possible run properties ...
template_paragraph = ... however you get this ...
new_paragraph = document.add_paragraph()
for run in template_paragrap... | 0 | 2016-06-28T18:07:52Z | [
"python",
"docx",
"python-docx"
] |
Truncate dictionary list values | 38,077,634 | <p>I'm trying to find the keys for the matching values in a dictionary. But to get any kind of valid match I need to truncate the values in the lists.</p>
<p>I want to truncate down the the tenths spot (e.g. "2.21" to "2.2").</p>
<pre><code>dict1 = {'red':[1.98,2.95,3.83],'blue':[2.21,3.23,4.2333],'orange':[3.14,4.1,... | 2 | 2016-06-28T13:30:00Z | 38,077,820 | <pre><code>d = {'green': [3.11, 4.12, 5.2]}
>>> map(int, d['green'])
[3, 4, 5]
</code></pre>
<p>You need to map the list items to integers before you compare</p>
<pre><code>for key2 in dict2:
if map(int, dict1[key1]) == map(int, dict2[key2]):
matches.append((key1, key2))
</code></pre>
<p>I'm as... | 3 | 2016-06-28T13:37:27Z | [
"python",
"list",
"dictionary",
"truncate"
] |
Truncate dictionary list values | 38,077,634 | <p>I'm trying to find the keys for the matching values in a dictionary. But to get any kind of valid match I need to truncate the values in the lists.</p>
<p>I want to truncate down the the tenths spot (e.g. "2.21" to "2.2").</p>
<pre><code>dict1 = {'red':[1.98,2.95,3.83],'blue':[2.21,3.23,4.2333],'orange':[3.14,4.1,... | 2 | 2016-06-28T13:30:00Z | 38,077,898 | <p>You can use <code>zip</code> on the lists and compare values, but you should set a tolerance <code>tol</code> for which a pair of values from two list will be considered the same:</p>
<pre><code>dict1 = {'red':[1.98,2.95,3.83],'blue':[2.21,3.23,4.2333],'orange':[3.14,4.1,5.22]}
dict2 = {'green':[3.11,4.12,5.2],'yel... | 2 | 2016-06-28T13:41:35Z | [
"python",
"list",
"dictionary",
"truncate"
] |
Truncate dictionary list values | 38,077,634 | <p>I'm trying to find the keys for the matching values in a dictionary. But to get any kind of valid match I need to truncate the values in the lists.</p>
<p>I want to truncate down the the tenths spot (e.g. "2.21" to "2.2").</p>
<pre><code>dict1 = {'red':[1.98,2.95,3.83],'blue':[2.21,3.23,4.2333],'orange':[3.14,4.1,... | 2 | 2016-06-28T13:30:00Z | 38,077,937 | <p>You can add some list comprehensions in between your loops to convert the floats to integers, like this:</p>
<pre><code>dict1 = {'red':[1.98,2.95,3.83],'blue':[2.21,3.23,4.2333],'orange':[3.14,4.1,5.22]}
dict2 = {'green':[3.11,4.12,5.2],'yellow':[2.2,3.2,4.2],'red':[5,2,6]}
matches = []
for key1 in dict1:
for... | 2 | 2016-06-28T13:42:57Z | [
"python",
"list",
"dictionary",
"truncate"
] |
Truncate dictionary list values | 38,077,634 | <p>I'm trying to find the keys for the matching values in a dictionary. But to get any kind of valid match I need to truncate the values in the lists.</p>
<p>I want to truncate down the the tenths spot (e.g. "2.21" to "2.2").</p>
<pre><code>dict1 = {'red':[1.98,2.95,3.83],'blue':[2.21,3.23,4.2333],'orange':[3.14,4.1,... | 2 | 2016-06-28T13:30:00Z | 38,077,951 | <p>If all you care about is truncation, and not actual rounding, you could convert the values to a string and slice off the excess:</p>
<pre><code>for key1 in dict1:
for key2 in dict2:
# I'm pulling these values out so you can look at them:
a = str(dict1[key1])
b = str(dict1[key2])
... | 2 | 2016-06-28T13:43:35Z | [
"python",
"list",
"dictionary",
"truncate"
] |
Getting the topic of a channel in a twisted IRC bot | 38,077,886 | <p>I am having trouble getting the topic of a channel using the twisted irc framework. My bot joins one channel and I want it to be able to query the topic of another channel. I send a LIST message using <code>topic('#channelname)</code> and I thought I would get the response by overriding the <code>topicUpdated()</cod... | 0 | 2016-06-28T13:40:56Z | 38,534,061 | <p>RFC 1459 <a href="https://tools.ietf.org/html/rfc1459#section-6.2" rel="nofollow">states</a> that when using LIST, each channel and its topic are sent with the numeric 332 (aka. RPL_LIST).</p>
<p>I don't know how Twisted works, but you should be able to get them with a method named <code>irc_RPL_LIST</code>, <code>... | 1 | 2016-07-22T19:32:55Z | [
"python",
"twisted",
"irc"
] |
Type hint for "hashable" | 38,077,896 | <p>Sometimes an argument to a function I write can be of any type as long as it is a <a href="https://docs.python.org/3/glossary.html#term-hashable" rel="nofollow">hashable</a> - for instance, because my function adds it to a set or uses it as a dictionary key.</p>
<p>Is there a way to type-hint this fact using the PE... | 2 | 2016-06-28T13:41:26Z | 38,078,003 | <p>The <code>typing</code> module <em>does</em> in fact contain a <code>Hashable</code> type, which simply isn't documented in the current version of <a href="https://docs.python.org/3/library/typing.html" rel="nofollow">the docs</a>. It's an alias for <a href="https://docs.python.org/3/library/collections.abc.html#col... | 4 | 2016-06-28T13:46:04Z | [
"python",
"type-hinting"
] |
Unpack the list element of DataFrame | 38,078,029 | <p>I have this df:</p>
<pre><code>l1 = ['a', 'b', 'c']
l2 = ['x', ['y1', 'y2', 'y3'], 'z']
df = pd.DataFrame(list(zip(l1, l2)), columns = ['l1', 'l2'])
</code></pre>
<p>result:</p>
<pre><code> l1 l2
0 a x
1 b [y1, y2, y3]
2 c z
</code></pre>
<p>What i need is to unpack the in... | 2 | 2016-06-28T13:47:05Z | 38,078,863 | <p>You could use a nested list comprehension with <a href="https://docs.python.org/3.5/library/itertools.html#itertools.zip_longest" rel="nofollow">itertools.zip_longest</a>.</p>
<pre><code>import pandas as pd
from itertools import zip_longest
l1 = ['a', 'b', 'c']
l2 = ['x', ['y1', 'y2', 'y3'], 'z']
expanded = [(le... | 2 | 2016-06-28T14:23:23Z | [
"python",
"list",
"pandas",
"unpack"
] |
Unpack the list element of DataFrame | 38,078,029 | <p>I have this df:</p>
<pre><code>l1 = ['a', 'b', 'c']
l2 = ['x', ['y1', 'y2', 'y3'], 'z']
df = pd.DataFrame(list(zip(l1, l2)), columns = ['l1', 'l2'])
</code></pre>
<p>result:</p>
<pre><code> l1 l2
0 a x
1 b [y1, y2, y3]
2 c z
</code></pre>
<p>What i need is to unpack the in... | 2 | 2016-06-28T13:47:05Z | 38,078,893 | <p>Brute force, looping over the dataframe:</p>
<pre><code>for idx in df.index:
# This transforms the item in "l2" into an iterable list
item = df.loc[idx, "l2"] if isinstance(df.loc[idx, "l2"], (list, tuple)) else [df.loc[idx, "l2"]]
for element in item:
print(df.loc[idx, "l1"], element)
</code></... | 1 | 2016-06-28T14:24:20Z | [
"python",
"list",
"pandas",
"unpack"
] |
Need help to modify xml with python | 38,078,032 | <p>I have an XML string where I want to modify the model type for specific interface. </p>
<pre><code><domain type='kvm'>
<devices>
<interface type='network'>
<mac address='52:54:00:a8:fe:3d'/>
<source network='ovirtmgmt'/>
<model type='virtio'/>
&l... | 0 | 2016-06-28T13:47:24Z | 38,079,830 | <p>Here's some crude ElementTree code that does the job. In a real program you'd probably want some error checking. But if you're sure your XML data will always be perfect, and that every <code>interface</code> tag will always contain a <code>source</code> tag and a <code>model</code> tag, then this code will do the jo... | 0 | 2016-06-28T15:04:08Z | [
"python",
"xml"
] |
Need help to modify xml with python | 38,078,032 | <p>I have an XML string where I want to modify the model type for specific interface. </p>
<pre><code><domain type='kvm'>
<devices>
<interface type='network'>
<mac address='52:54:00:a8:fe:3d'/>
<source network='ovirtmgmt'/>
<model type='virtio'/>
&l... | 0 | 2016-06-28T13:47:24Z | 38,081,542 | <p>Thanks for your answers, but this is also worked for me</p>
<pre><code>root = ET.fromstring(xml)
for interface in root.findall('devices/interface'):
if interface.find('source/[@network="nat"]') != None:
model = interface.find('model')
model.set('type', 'e1000')
new_xml = ET.tostring(root)
</code></... | 0 | 2016-06-28T16:26:53Z | [
"python",
"xml"
] |
Need help to modify xml with python | 38,078,032 | <p>I have an XML string where I want to modify the model type for specific interface. </p>
<pre><code><domain type='kvm'>
<devices>
<interface type='network'>
<mac address='52:54:00:a8:fe:3d'/>
<source network='ovirtmgmt'/>
<model type='virtio'/>
&l... | 0 | 2016-06-28T13:47:24Z | 38,086,303 | <p>You don't need multiple <code>find*()</code> calls. You can do it in one call:</p>
<pre><code>from xml.etree import ElementTree as ET
tree = ET.parse('input.xml')
for model in tree.findall(".//source[@network='nat']/../model"):
model.set('type', 'e1000')
tree.write('output.xml')
</code></pre>
| 1 | 2016-06-28T21:07:20Z | [
"python",
"xml"
] |
How to mock the input dir for my unit test? | 38,078,042 | <p>Related to a earlier question of mine: <a href="http://stackoverflow.com/questions/38076616/how-to-unit-test-a-method-that-calculates-the-size-of-a-dir?noredirect=1#comment63591038_38076616">How to unit test a method that calculates the size of a dir?</a>
I want to unit test this function: </p>
<pre><code>def get... | 0 | 2016-06-28T13:48:02Z | 38,078,285 | <p>Ok, I was heading down the wrong path. Should have mocked the <code>os.path.getsize()</code> method. Plus, the return value needs to be provided like this <code>.return_value = 5000</code></p>
<pre><code>@mock.patch('threedi_utils.files.os.path.getsize')
def test_get_dir_size_can_get_dir_size(self, mock_size):
... | -1 | 2016-06-28T13:58:49Z | [
"python",
"python-2.7",
"unit-testing",
"mocking"
] |
Splitting Data Frames Dynamically in Python | 38,078,051 | <p>I'm trying to split a data frame dynamically but it's not working (here's a simple example):</p>
<pre><code>e = {'cat' : pd.Series(['A', 'B', 'C', 'D'])}
cat = pd.DataFrame(e)
cat.head(5)
def splitter(val, outval):
outval = pd.DataFrame(cat['cat'] == "val")
</code></pre>
<p>What i'm hoping to do is create a d... | 0 | 2016-06-28T13:48:22Z | 38,078,357 | <p>You can access dataframes in an easier way:</p>
<pre><code>cata = cat[cat['cat'] == 'A']
catb = cat[cat['cat'] == 'B']
</code></pre>
<p>Note that pandas gives you a view or a copy, which depends on context. This is explained in: <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versu... | 0 | 2016-06-28T14:02:01Z | [
"python"
] |
Splitting Data Frames Dynamically in Python | 38,078,051 | <p>I'm trying to split a data frame dynamically but it's not working (here's a simple example):</p>
<pre><code>e = {'cat' : pd.Series(['A', 'B', 'C', 'D'])}
cat = pd.DataFrame(e)
cat.head(5)
def splitter(val, outval):
outval = pd.DataFrame(cat['cat'] == "val")
</code></pre>
<p>What i'm hoping to do is create a d... | 0 | 2016-06-28T13:48:22Z | 38,078,517 | <p>There are a few problems with what you have. Mainly, you aren't doing your function properly, and you're trying to call the string "val", not the variable <code>val</code> in your equality. Try this:</p>
<pre><code>data = {'cat' : ['A', 'B', 'C', 'D'], 'dog' : ['e', 'f', 'g', 'h']}
df = pd.DataFrame(data)
print(d... | 1 | 2016-06-28T14:08:46Z | [
"python"
] |
Convert array of records to JSON in Postgresql | 38,078,145 | <p>I'm having problems with converting an array of records into JSON with Postgresql.</p>
<p><strong>Version:</strong> psql (PostgreSQL) 9.5.3</p>
<p>Current query:</p>
<pre><code>SELECT c.id, (select array(
select (cp.id,cp.position)
from contactposition cp
where cp.contact_id_id = c.id -- ... | 0 | 2016-06-28T13:52:33Z | 38,078,625 | <p>Use <a href="https://www.postgresql.org/docs/9.5/static/functions-json.html" rel="nofollow"><code>jsonb_build_object()</code></a> and <a href="https://www.postgresql.org/docs/9.5/static/functions-aggregate.html" rel="nofollow"><code>jsonb_agg()</code></a>:</p>
<pre><code>select c.id, jsonb_agg(jsonb_build_object('i... | 4 | 2016-06-28T14:12:53Z | [
"python",
"sql",
"json",
"postgresql",
"jsonb"
] |
Map different functions to data | 38,078,208 | <p>Is there a way to make several functions map to the same data producing a list of results?</p>
<p>Something like</p>
<pre><code>mapfunc([sin, cos, tan], data)
</code></pre>
<p>to produce a map object essentially mapping</p>
<pre><code>[array(sin(data)),
array(cos(data)),
array(tan(data))]
</code></pre>
<p>?... | 0 | 2016-06-28T13:55:18Z | 38,078,896 | <p>You will need a helper function if you want to stick with map, e.g.</p>
<pre><code>map(lambda f: f(data), [sin, cos, tan])
</code></pre>
| 0 | 2016-06-28T14:24:38Z | [
"python"
] |
Implicit DAE Mass Matrix Python | 38,078,299 | <p>I have a problem M*y' = f(y) that are going to be solved in Python, where M is the mass matrix, y' the derivative and y is a vector, such that y1, y2 etc. refers to different points in r.
Have anyone used a mass matrix on a similar problem in Python? </p>
<p>The problem is a 2D-problem in r- and z-direction. The... | 0 | 2016-06-28T13:59:21Z | 38,833,074 | <p>Since the mass matrix is singular, this is a "differential-algebraic equation". You can find off-the-shelf solvers for DAEs, such as the IDA solver from the SUNDIALS library. SUNDIALS has python bindings in the scikit.odes package.</p>
| 0 | 2016-08-08T15:24:20Z | [
"python",
"matrix",
"ode"
] |
How can I make python sleep in real time? | 38,078,304 | <p>I have code that looks like:</p>
<pre><code>while True:
do things over the internet:
time.sleep(3600)
</code></pre>
<p>I would like <code>time.sleep()</code> to run even if my computer is asleep or I'm not logged on. For example, if I start the program, wait half an hour, log off (or put the machine to sle... | 0 | 2016-06-28T13:59:37Z | 38,078,507 | <p>You can have it save the time and check against that every minute or so, e.g. (pseudocode)</p>
<pre><code>lastDone = None # Avoid unbound local errors
while True:
if lastDone is None or is_one_hour_ago(lastDone): # Write is_one_hour_ago()
# Do things
lastDone = time.now() # Not a real function... | 3 | 2016-06-28T14:08:30Z | [
"python",
"sleep"
] |
How can I make python sleep in real time? | 38,078,304 | <p>I have code that looks like:</p>
<pre><code>while True:
do things over the internet:
time.sleep(3600)
</code></pre>
<p>I would like <code>time.sleep()</code> to run even if my computer is asleep or I'm not logged on. For example, if I start the program, wait half an hour, log off (or put the machine to sle... | 0 | 2016-06-28T13:59:37Z | 38,078,752 | <p>You should see, but it is possible that time.sleep() breaks when your machine goes to sleep.</p>
<p>It breaks when some other stuff happens, like KeyboardInterrupt.</p>
<p>So, put sleep() into try statement, and use time.clock() or time.time() to see how much time has passed between sleep() interruption and next o... | 1 | 2016-06-28T14:18:22Z | [
"python",
"sleep"
] |
python-social-auth with Django: ImportError: No module named 'openid.association' | 38,078,340 | <p>I am trying to use <code>python-social-auth</code> with Django 1.9 and Python 3. As far as I can tell, I have installed all the necessary requirements, and have all the required settings in my <code>settings.py</code>. However, when I try to run migrations, or run the Django dev server, I get the following error:</p... | 0 | 2016-06-28T14:01:07Z | 38,747,205 | <p>I just had the exact same problem (Python 3.5, Django 1.9.8) and could actually resolve the issue by uninstalling <em>all</em> versions of python-openid and afterwards removing <em>and reinstalling</em> python-social-auth.</p>
<p>Seemingly something went wrong when installing PSA whilst python-openid was still avai... | 1 | 2016-08-03T15:01:01Z | [
"python",
"django",
"python-3.x",
"python-social-auth",
"python-openid"
] |
How to avoid Python Popen communicate() function with sqlplus from returning same headers multiple times | 38,078,407 | <p>Am using Python Popen API to connect to Oracle database via sqlplus.</p>
<p>My code:</p>
<pre><code>prodMirrSession = Popen(['sqlplus','-S',prodMirrConnectString], stdin=PIPE, stdout=PIPE, stderr=PIPE)
prodMirrSession.stdin.write(sqlCommand)
prodQueryResult, prodErrorMsg = prodMirrSession.communicate()
</code><... | 1 | 2016-06-28T14:04:28Z | 38,078,583 | <p>I believe this is due to pagesize. You can either set the page size to some very high number that exceeds your number of rows: </p>
<pre><code>set pagesize 1000000
</code></pre>
<p>Or you can turn off headers entirely (and add them by hand or handle it by position): </p>
<pre><code>set pagesize 0
</code></pre>
<... | 1 | 2016-06-28T14:11:18Z | [
"python",
"sqlplus",
"popen"
] |
How can I write a math quiz, with random numbers, in python 2? | 38,078,562 | <p>The best math quiz I have currently is:</p>
<pre><code>answer = ''
while not (answer == '75'):
answer = raw_input('What is 5 x 15? ')
if answer == '75':
print ' '
print 'You are correct'
answer1 = ''
while not (answer1 == '72'):
answer1 = raw_input('What is 8 x 9? ')
if answer1... | -2 | 2016-06-28T14:10:28Z | 38,079,014 | <p>You can generate the questions dynamically like this: </p>
<pre><code>from random import randint
q = ''
while not q.capitalize() == 'N':
num1 = randint(0, 100)
num2 = randint(0, 100)
answer = input("What is " + str(num1) + " x " + str(num2) + " ? ")
if answer == (num1 * num2):
print "Correct... | 1 | 2016-06-28T14:29:36Z | [
"python",
"python-2.7"
] |
Unable to view the page source of a website | 38,078,723 | <p>I wrote a simple python script just to view the page source of a website.The website is <code>https://kissanime.to</code>. I am using the following small piece of code.</p>
<pre><code> import urllib2
url = 'https://kissanime.to'
link = urllib2.urlopen(url)
print link
</code></pre>
<p>However the abo... | 0 | 2016-06-28T14:17:02Z | 38,079,987 | <p>Checked out the website, it makes you wait for 5 seconds while it does something before displaying any of it's main content. </p>
<p>I used the <code>requests</code> module, to get at this initial page that says "Wait 5 seconds":</p>
<pre><code>import requests
r = requests.get("https://kissanime.to/")
# Throws a... | 0 | 2016-06-28T15:10:45Z | [
"python",
"urllib2",
"http-error"
] |
Calculate count of rows matching a condition in a pandas frame (if possible using sortedness of the data) | 38,078,753 | <p><strong>Dataset Description:</strong></p>
<p>I have a dataset that looks like this (sorted by key, which also means it is sorted by offset_time_stamp):</p>
<pre><code>key offset_time_stamp person 7_sec_count
1 0 A 0
2 0 ... | 2 | 2016-06-28T14:18:23Z | 38,079,946 | <p><strong>Edit:</strong> Using the sortedness of the timestamps as suggested, and the fact that <code>searchsorted</code> is vectorised, I was able to cut the execution time in 3.</p>
<pre><code>def get_count(dfg):
return pd.Series(
np.arange(len(dfg)) - dfg.offset_time_stamp.searchsorted(dfg.offset_time_... | 2 | 2016-06-28T15:08:55Z | [
"python",
"pandas"
] |
Repeat string in one element in a set using Python3 | 38,078,774 | <p>I was making the difference between two sets to see what had changed when I noticed that whenever I had one element which was a repeated sequence it would be represented as only one char. </p>
<p>Example:</p>
<pre><code>>>> set("aaaa")
{'a'}
</code></pre>
<p>How can I represent it as {'aaaa'} so I can m... | 0 | 2016-06-28T14:19:23Z | 38,078,847 | <p>If you're trying to set a variable to <code>{'aaaa'}</code> like in your example, simply change the <code>set</code> assignment from <code>set("aaaa")</code> to <code>set(['aaaa'])</code>.</p>
| 1 | 2016-06-28T14:22:31Z | [
"python",
"python-3.x"
] |
Repeat string in one element in a set using Python3 | 38,078,774 | <p>I was making the difference between two sets to see what had changed when I noticed that whenever I had one element which was a repeated sequence it would be represented as only one char. </p>
<p>Example:</p>
<pre><code>>>> set("aaaa")
{'a'}
</code></pre>
<p>How can I represent it as {'aaaa'} so I can m... | 0 | 2016-06-28T14:19:23Z | 38,078,891 | <p>You don't call <code>set</code> on a single <code>str</code> unless you want to treat the <code>str</code> as a sequence of individual characters to be uniquified (that is, <code>set('aaaa')</code> is equivalent to <code>set(['a', 'a', 'a', 'a'])</code>, because Python <code>str</code> are iterables of their own cha... | 2 | 2016-06-28T14:24:18Z | [
"python",
"python-3.x"
] |
possible Python integer overflow error | 38,078,835 | <p>Below is my code that I'm trying to run to solve for a maximum prioritized product problem i.e. return a maximum value for a product of two numbers in a list. My issue is that the product that is being computed is incorrect when the numbers in the input list are large. I was of the opinion that there will be no inte... | 0 | 2016-06-28T14:22:10Z | 38,079,153 | <p>Using <code>np.random.randint</code> will create an array of 32 bits integers:</p>
<pre><code>>>> alist = np.random.randint(100000, size = n)
>>> alist.dtype
dtype('int32')
</code></pre>
<p>Sorting it will preserve that type, creating a list of <code>numpy.int32</code> objects instead of converti... | 1 | 2016-06-28T14:35:38Z | [
"python",
"numpy"
] |
Why are deterministic profilers called 'deterministic'? | 38,078,872 | <p>I'm currently doing some profiling tasks in Python using cProfile (among others). In the <a href="https://docs.python.org/3.5/library/profile.html" rel="nofollow">documentation</a> it says:</p>
<blockquote>
<p>cProfile and profile provide deterministic profiling of Python programs</p>
</blockquote>
<p>During pro... | 0 | 2016-06-28T14:23:46Z | 38,079,239 | <p>The question is answered in the <a href="https://docs.python.org/3.5/library/profile.html#what-is-deterministic-profiling" rel="nofollow">documentation</a>:</p>
<blockquote>
<p>27.4.5. What Is Deterministic Profiling?</p>
<p>Deterministic profiling is meant to reflect the fact that all function call, functio... | 0 | 2016-06-28T14:39:04Z | [
"python",
"profiling",
"profiler",
"deterministic"
] |
Matplotlib errorbar plot does not use marker cycling | 38,078,905 | <p>In the following example, the error bar plot does not use the marker cycle specified in the <code>axes</code> rc, although it does use the color cycle. Specifying <code>fmt</code> rather than <code>marker</code> in the <code>cycler</code> throws an <code>AttributeError: Unknown property fmt</code>. How can I use the... | 0 | 2016-06-28T14:24:51Z | 38,078,907 | <p>Although this doesn't answer the question as posed, there are two ways to get around this using a <code>prop_cycle</code>. One is to simply use a <code>for</code> loop to construct the graphs. If you'd rather not use a <code>for</code> loop, you can define a generator function to <code>yield</code> values of the mar... | 0 | 2016-06-28T14:24:51Z | [
"python",
"matplotlib"
] |
Why is my Frame subclass throwing an error in init? | 38,078,997 | <p>My program is as follows:</p>
<pre><code>from Tkinter import *
class TFrame(Frame):
def __init__(self, master=None, cnf={}, **kw):
Frame.__init__(self, master, cnf, kw)
if __name__ == '__main__':
root = Tk()
tf = TFrame(root)
tf.pack()
root.mainloop()
</code></pre>
<p>and I get this er... | 2 | 2016-06-28T14:29:05Z | 38,079,087 | <p>You need to unpack <code>kw</code> in the call to <code>Frame.__init__</code>.</p>
<p>This should work for you.</p>
<pre><code>from Tkinter import *
class TFrame(Frame):
def __init__(self, master=None, cnf={}, **kw):
Frame.__init__(self, master, cnf, **kw)
if __name__ == '__main__':
root = Tk()
... | 3 | 2016-06-28T14:32:37Z | [
"python",
"inheritance",
"constructor",
"tkinter",
"arguments"
] |
How to run an ADFuller test on timeseries data using statsmodels library? | 38,079,072 | <p>I am completely new to programming languages and I have picked up Python for backtesting a trading strategy (because I heard it is relatively easy). I have made some progress in learning the basics, however I am currently stuck at performing an ADFuller tests on a timeseries dataframe.</p>
<p><a href="http://i.stac... | 0 | 2016-06-28T14:31:50Z | 38,079,715 | <p>If you have to do it for so many, I would try putting the results in a dict, like this:</p>
<pre><code>import statsmodels.tsa.stattools as tsa
df = ... #load your dataframe
adf_results = {}
for col in df.columns.values: #or edit this for a subset of columns first
adf_results[col] = tsa.adfuller(df[col])
</co... | 0 | 2016-06-28T14:59:17Z | [
"python",
"statsmodels"
] |
How to get a full website path from a relative website path using BeautifulSoup | 38,079,120 | <p>I am implementing a web crawler and I am trying to parse the links in HTML. I can follow full website paths, but some relative paths get a little weird.</p>
<p>I can follow full paths, ie <code>http://foo.com/bar/baz</code> and I was able to find a way to follow relative paths, ie <code>/qux</code> by using the fol... | 1 | 2016-06-28T14:34:04Z | 38,079,192 | <p>What I always do and it worked for me so far is to call <a href="https://docs.python.org/2/library/urlparse.html#urlparse.urljoin" rel="nofollow"><code>urljoin()</code></a> with the current page URL:</p>
<pre><code>>>> from urlparse import urljoin
>>> urljoin("http://foo.com/bar/baz", "/bar/qux")
... | 1 | 2016-06-28T14:37:05Z | [
"python",
"html",
"beautifulsoup",
"python-requests"
] |
parsing a text file for integers on a given line with python | 38,079,194 | <p>I've got this test suite that outputs test results as a text file.
Here is a sample:</p>
<pre><code> File Opened: Tuesday, June 26, 2016, 10:17:13 AM
File Opened: Tuesday, June 26, 2016, 10:17:29 AM
Radio Test BER LOOP BACK successful
Radio Test PAUSE successful
Radio Test BER LOOP BACK successful
File Opened:... | 0 | 2016-06-28T14:37:07Z | 38,079,359 | <p>Create two arrays, once for the <code>received</code> data and one for the <code>error</code> data, then just loop through the file and parse:</p>
<pre><code>receivedData = []
errorData = []
with open("data.txt") as f:
for line in f:
if line.startswith("Bits received"):
receivedData.append(i... | 3 | 2016-06-28T14:43:47Z | [
"python",
"parsing",
"matplotlib"
] |
parsing a text file for integers on a given line with python | 38,079,194 | <p>I've got this test suite that outputs test results as a text file.
Here is a sample:</p>
<pre><code> File Opened: Tuesday, June 26, 2016, 10:17:13 AM
File Opened: Tuesday, June 26, 2016, 10:17:29 AM
Radio Test BER LOOP BACK successful
Radio Test PAUSE successful
Radio Test BER LOOP BACK successful
File Opened:... | 0 | 2016-06-28T14:37:07Z | 38,079,587 | <p>Another easy way would be to use the regex library <code>re</code>. (<a href="https://docs.python.org/2/library/re.html" rel="nofollow">https://docs.python.org/2/library/re.html</a>)</p>
<pre><code>import re
pattern1 = re.compile(r'Bits received\s+(\d+)') # \d means any digit character
pattern2 = re.compile(r'Bit... | 1 | 2016-06-28T14:53:37Z | [
"python",
"parsing",
"matplotlib"
] |
How can I disable ExtDeprecationWarning for external libs in flask | 38,079,200 | <p>When I run my script, I get this output:</p>
<pre><code>/app/venv/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.sqlalchemy is deprecated, use flask_sqlalchemy instead.
.format(x=modname), ExtDeprecationWarning
/app/venv/lib/python2.7/site-packages/flask/exthook.py:71:... | 5 | 2016-06-28T14:37:18Z | 38,080,580 | <p>First, you <em>should</em> care about this because the packages you're using aren't up to date. Report a bug that they should switch to using direct import names, such as <code>flask_sqlalchemy</code>, rather than the <code>flask.ext</code> import hook.</p>
<p>Add a <a href="https://docs.python.org/3.5/library/war... | 9 | 2016-06-28T15:37:53Z | [
"python",
"flask"
] |
Join and reshape two ndarrays | 38,079,255 | <p>Here's a working example of what I want by combining two arrays <code>a</code> and <code>b</code> to make array <code>c</code>:</p>
<pre><code>import numpy as np
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10,11,12]])
b = -a
c = np.reshape(np.array(zip(np.ravel(a), np.ravel(b))), (4,3,2))
</code></pre>
<hr>
<pre><... | 1 | 2016-06-28T14:39:26Z | 38,079,699 | <p>You can use the function dstack from numpy to achieve what you want: </p>
<pre><code> np.dstack((a,b)).reshape((4,3,2))
</code></pre>
<p>Hope it helps!</p>
| 0 | 2016-06-28T14:58:41Z | [
"python"
] |
Flask file not detecting on upload | 38,079,288 | <p>I made a flask_wtf Form with this field:</p>
<p><code>logo_image = FileField('logo_image', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Images only!')])</code></p>
<p>My form looks like this:</p>
<pre><code><form action="" method="POST" name="app_branding" enctype="multipart/form-data">
{{ f... | 1 | 2016-06-28T14:40:55Z | 38,080,410 | <p><code>request.form</code> only contains form input data. <code>request.files</code> contains file upload data. You need to pass the combination of both to the form. Since you're using Flask-WTF, it will handle this automatically if you don't pass anything to the form.</p>
<pre><code>form = BrandForm()
if form.v... | 1 | 2016-06-28T15:30:04Z | [
"python",
"flask",
"flask-wtforms"
] |
can lxml/requests select dropdown options then parse resulting ajax? | 38,079,481 | <p>I have a site I'm trying to test and although I can get a list of options in a dropdown I am not sure how select it? There is no submit button so if I select it then it will load an ajax table below. </p>
<p>I'm just not sure if lxml/requests can do this or how it could be done? I would appreciate it if anyone co... | 1 | 2016-06-28T14:48:36Z | 38,081,914 | <p>With <code>lxml</code>+<code>requests</code> setup, you operate on a different level, a lower level. There are no dropdowns for <code>requests</code>, <em>it is not a browser</em>.</p>
<p>The general approach to your problem is to:</p>
<ul>
<li>open Browser Developer Tools in your browser of choice, Network tab</l... | 2 | 2016-06-28T16:45:11Z | [
"python",
"web-scraping",
"python-requests",
"lxml"
] |
Transform cURL command to Python Requests command | 38,079,564 | <p>I'm new with cURL and Requests and I have a doubt on how I can transform a cURL petition to a Requests command in Python.</p>
<p>Looking at Apache Stratos documentation <a href="https://cwiki.apache.org/confluence/display/STRATOS/4.1.x+Session+Authentication+via+REST+API" rel="nofollow">Doc Page</a> to perform a lo... | 0 | 2016-06-28T14:52:49Z | 38,079,687 | <p>You are using your localhost which almost certainly doesn't have a valid certificate.</p>
<p>For testing purposes disable ssl verification (it is still encrypted just not verifying certificate)</p>
<pre><code>req = requests.post('https://localhost:9443/api/session', headers=headers, params=data, verify=False)
</co... | 2 | 2016-06-28T14:58:06Z | [
"python",
"django",
"ssl",
"curl",
"python-requests"
] |
Transform cURL command to Python Requests command | 38,079,564 | <p>I'm new with cURL and Requests and I have a doubt on how I can transform a cURL petition to a Requests command in Python.</p>
<p>Looking at Apache Stratos documentation <a href="https://cwiki.apache.org/confluence/display/STRATOS/4.1.x+Session+Authentication+via+REST+API" rel="nofollow">Doc Page</a> to perform a lo... | 0 | 2016-06-28T14:52:49Z | 38,079,735 | <p>You can <a href="http://docs.python-requests.org/" rel="nofollow">turn off SSL cert verification</a> with the <code>verify</code> flag, and use <a href="http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification" rel="nofollow">basic authentication</a> by specifying <code>auth</code>.</p>
<pre><... | 1 | 2016-06-28T15:00:14Z | [
"python",
"django",
"ssl",
"curl",
"python-requests"
] |
Transform cURL command to Python Requests command | 38,079,564 | <p>I'm new with cURL and Requests and I have a doubt on how I can transform a cURL petition to a Requests command in Python.</p>
<p>Looking at Apache Stratos documentation <a href="https://cwiki.apache.org/confluence/display/STRATOS/4.1.x+Session+Authentication+via+REST+API" rel="nofollow">Doc Page</a> to perform a lo... | 0 | 2016-06-28T14:52:49Z | 38,079,964 | <p>After the @Sam solution and looking on the <a href="http://docs.python-requests.org/en/master/user/authentication/" rel="nofollow">Requests Auth Doc Page</a> I found the solution:</p>
<p>The Python Resquest code it's:</p>
<pre><code>requests.get('https://localhost:9443/api/session', headers=headers, auth=HTTPBasic... | 0 | 2016-06-28T15:09:36Z | [
"python",
"django",
"ssl",
"curl",
"python-requests"
] |
Creating a program that compares two lists | 38,079,600 | <p>I am trying to create a program that checks whether items from one list are not in another. It keeps returning lines saying that x value is not in the list. Any suggestions? Sorry about my code, it's quite sloppy.</p>
<h1>Searching Within an Array</h1>
<h1>Putting .txt files into arrays</h1>
<pre><code>with open(... | 0 | 2016-06-28T14:54:21Z | 38,079,774 | <p>Instead of lists, read the files as sets:</p>
<pre><code>with open('Barcodes', 'r') as f:
barcodes = {line.strip() for line in f}
with open('EAN Staging', 'r') as f:
EAN_staging = {line.strip() for line in f}
</code></pre>
<p>Then all you need to do is to calculate the symmetric difference between them:</... | 3 | 2016-06-28T15:01:56Z | [
"python",
"arrays",
"if-statement"
] |
Creating a program that compares two lists | 38,079,600 | <p>I am trying to create a program that checks whether items from one list are not in another. It keeps returning lines saying that x value is not in the list. Any suggestions? Sorry about my code, it's quite sloppy.</p>
<h1>Searching Within an Array</h1>
<h1>Putting .txt files into arrays</h1>
<pre><code>with open(... | 0 | 2016-06-28T14:54:21Z | 38,079,818 | <p>Your code doesn't seem to quite answer your question. If all you want to do is see which elements aren't shared, I think <code>set</code>s are the way to go.</p>
<pre><code>set1 = set(list1)
set2 = set(list2)
in_first_but_not_in_second = set1.difference(set2) # outputs a set
not_in_both = set1.symmetric_differenc... | 0 | 2016-06-28T15:03:36Z | [
"python",
"arrays",
"if-statement"
] |
Python: An integer is required. Where? Why? | 38,079,705 | <p>I am having trouble with this brief code snippet:</p>
<pre><code>for i, row in enumerate(rows):
row["last_check"] = last_check_ts
row_filtered = {
k: v.replace('\r', '') for k, v in row.iteritems() if v is not None
}
</code></pre>
<p>It gives me the following error:</p>
<pre><code>k: v.replace... | 0 | 2016-06-28T14:58:55Z | 38,079,799 | <p>Move this line:</p>
<pre><code>row["last_check"] = last_check_ts
</code></pre>
<p>Below your dict comprehension. You can reproduce this as follows:</p>
<pre><code>from datetime import datetime
rows = {'a': None, 'b': 'some_str\r', 'c': datetime.utcnow()}
{k: v.replace('\r', '') for k, v in rows.items() if v is no... | 6 | 2016-06-28T15:03:08Z | [
"python"
] |
How do I extract data from unspaced strings? | 38,079,727 | <p>I need to extract data from four strings that have been parsed in BeautifulSoup. They are:</p>
<pre><code>Arkansas72.21:59 AM76.29:04 AM5.22977.37:59 AM
Ashley71.93:39 AM78.78:59 AM0.53678.78:59 AM
Bradley72.64:49 AM77.28:59 AM2.41877.28:49 AM
Chicot-40.19:04 AM-40.19:04 AM2.573-40.112:09 AM
</code></pre>
<p>Th... | 1 | 2016-06-28T14:59:44Z | 38,080,207 | <p>Just improve the way you extract the tabular data. I would use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html" rel="nofollow"><code>pandas.read_html()</code></a> to read it into the <em>dataframe</em> which, I'm pretty sure, you would find convenient to work with:</p>
<pre><cod... | 2 | 2016-06-28T15:19:56Z | [
"python",
"beautifulsoup",
"urllib2",
"bs4"
] |
How do I extract data from unspaced strings? | 38,079,727 | <p>I need to extract data from four strings that have been parsed in BeautifulSoup. They are:</p>
<pre><code>Arkansas72.21:59 AM76.29:04 AM5.22977.37:59 AM
Ashley71.93:39 AM78.78:59 AM0.53678.78:59 AM
Bradley72.64:49 AM77.28:59 AM2.41877.28:49 AM
Chicot-40.19:04 AM-40.19:04 AM2.573-40.112:09 AM
</code></pre>
<p>Th... | 1 | 2016-06-28T14:59:44Z | 38,080,398 | <p>You need to use beautifulsoup to parse the html page and retrieve your data:</p>
<pre><code>url1 = 'http://170.94.200.136/weather/Inversion.aspx'
#opens url and parses HTML into Unicode
page1 = urlopen(url1)
soup1 = BeautifulSoup(page1)
# get the table
table = soup1.find(id='MainContent_GridView1')
# find the h... | 1 | 2016-06-28T15:29:16Z | [
"python",
"beautifulsoup",
"urllib2",
"bs4"
] |
Delete GoogleTag from BeautifulSoup | 38,079,825 | <p>I'm crawling a news website with the folliwing code:</p>
<pre><code>-*- coding: utf-8 -*-
archivo = open("News_Content.txt","w")
import urllib
import re
from BeautifulSoup import BeautifulSoup
links = open("MyFileWithLinks.txt").readlines()
i = 0
while i< len(links):
conn = urllib.urlopen(links[i])
html ... | 0 | 2016-06-28T15:03:55Z | 38,080,462 | <p>Can't you use <a href="http://beautiful-soup-4.readthedocs.io/en/latest/#css-selectors" rel="nofollow">CSS Selectors</a> and then use <a href="http://beautiful-soup-4.readthedocs.io/en/latest/#get-text" rel="nofollow"><code>get_text()</code></a> method on each of the objects returned?</p>
<p>E.g.</p>
<pre><code>w... | 1 | 2016-06-28T15:31:55Z | [
"python",
"google-tag-manager"
] |
How can I implement incremental training for xgboost? | 38,079,853 | <p>The problem is that my train data could not be placed into RAM due to train data size. So I need a method which first builds one tree on whole train data set, calculate residuals build another tree and so on (like gradient boosted tree do). Obviously if I call <code>model = xgb.train(param, batch_dtrain, 2)</code> i... | 2 | 2016-06-28T15:05:08Z | 38,260,557 | <p>Disclaimer: I'm new to xgboost as well, but I think I figured this out.</p>
<p>Try saving your model after you train on the first batch. Then, on successive runs, provide the xgb.train method with the filepath of the saved model. </p>
<p>Here's a small experiment that I ran to convince myself that it works:</p>
<... | 2 | 2016-07-08T06:50:56Z | [
"python",
"machine-learning",
"xgboost"
] |
Get dataframe result to a variable | 38,079,856 | <p>How to get the value only from a dataframe from a query?</p>
<p>I have this dataframe</p>
<pre><code>In [78]: dfSYS1vsPHDTags
Out[78]:
Machine System 1 Description Segment ID Converted PHD Tag
0 C-1185 Compressor Speed 54322 PI370
1 C-1185 Comp O/B Horz ... | 0 | 2016-06-28T15:05:18Z | 38,082,506 | <p>This is the answer for the question</p>
<p>Using the Dataframe.loc</p>
<pre><code>dfSYS1vsPHDTags.loc[dfSYS1vsPHDTags['Segment ID'] == int('54322'), 'Converted PHD Tag'].values[0]
</code></pre>
| 1 | 2016-06-28T17:19:02Z | [
"python",
"dataframe"
] |
'int' object is not callable only appears randomly | 38,079,862 | <p>Sometimes this code works just fine and runs through, but other times it throws the int object not callable error. I am not real sure as to why it is doing so.</p>
<pre><code>for ship in ships:
vert_or_horz = randint(0,100) % 2
for size in range(ship.size):
if size == 0:
ship.location.ap... | -2 | 2016-06-28T15:05:39Z | 38,080,224 | <p>You are trying to call (use the <code>..(...)</code> syntax) on an integer here:</p>
<pre><code>ship.location[size][1]((ship.location[0][0], \
ship.location[0][1] - size))
</code></pre>
<p><code>ship.location[size][1]</code> is an integer, and you are trying to call it by passing in the tup... | 0 | 2016-06-28T15:20:39Z | [
"python",
"runtime-error"
] |
'int' object is not callable only appears randomly | 38,079,862 | <p>Sometimes this code works just fine and runs through, but other times it throws the int object not callable error. I am not real sure as to why it is doing so.</p>
<pre><code>for ship in ships:
vert_or_horz = randint(0,100) % 2
for size in range(ship.size):
if size == 0:
ship.location.ap... | -2 | 2016-06-28T15:05:39Z | 38,132,517 | <p>In any spot where the code looks like this:</p>
<pre><code>ship.location[size][1]((ship.location[0][0], \
ship.location[0][1] - size))
</code></pre>
<p>The simple solution was that I needed to assign it to the location: </p>
<pre><code>ship.location[size] = ((ship.location[0][0],ship.location[0][1] ... | 0 | 2016-06-30T20:19:08Z | [
"python",
"runtime-error"
] |
Efficient query pandas dataset | 38,079,887 | <p>Given a pandas dataset contains 8 million rows and 20 columns.</p>
<p>Program queries the dataset to find an average of certain column.</p>
<p>The average based on selections from other columns</p>
<p>Need a help to get fast response on bundle of 10k queries and reduce the query execution time</p>
<p>Setup :</p>... | 2 | 2016-06-28T15:06:28Z | 38,080,220 | <p>The columns A through D could be converted into categories as the values are non-unique and limited.</p>
<p>The sample below is based on the df you provided in your OP.</p>
<pre><code># Original data frame
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 5 c... | 3 | 2016-06-28T15:20:37Z | [
"python",
"pandas",
"dataframe"
] |
Efficient query pandas dataset | 38,079,887 | <p>Given a pandas dataset contains 8 million rows and 20 columns.</p>
<p>Program queries the dataset to find an average of certain column.</p>
<p>The average based on selections from other columns</p>
<p>Need a help to get fast response on bundle of 10k queries and reduce the query execution time</p>
<p>Setup :</p>... | 2 | 2016-06-28T15:06:28Z | 38,081,713 | <p>The answer from @Kristof is a good place to start with. I noted a speedup of just under 2x with that suggestion. Some additional things to keep in mind for large DataFrames is the order of expressions used (eg, do you need to create a new DataFrame to select a Series or can you generate the new Series directly). Als... | 2 | 2016-06-28T16:35:12Z | [
"python",
"pandas",
"dataframe"
] |
How to close the connection | 38,079,916 | <p>I'm migrating a simple toolset from python 2.7 to 3.5 and one of the tools is a simple web server using web.py.</p>
<p>Unfortunately web.py is not available for 3.5 yet so I switched to bottle.py for this.</p>
<p>According to the specification of the interface I'm creating I need to close the connection which I ca... | -2 | 2016-06-28T15:07:51Z | 38,086,773 | <p>I'm not sure so take what I write with a grain of salt.</p>
<p>The bottle development server is a lightly modified wsgiref server which is a sligthly modified http.server server. It has no easy methods or configurations to send "unusual" headers. You can though subclass it and write some custom code. I think it sho... | 1 | 2016-06-28T21:41:21Z | [
"python",
"http-headers",
"bottle"
] |
Sum of values with same month | 38,080,070 | <pre><code>data = {'dates': ['2010-01-29', '2011-06-14', '2012-01-18'], 'values': [4, 3, 8]}
df = pd.DataFrame(data)
df.set_index('dates')
df.index = df.index.astype('datetime64[ns]')
</code></pre>
<p>Having a dataframe where the index is a date, how would I go about adding a new column caled 'Month' that is the sum o... | 2 | 2016-06-28T15:14:27Z | 38,080,281 | <p>There are several ways you could do this. The first would be to resample to monthly using <code>df.resample(...).sum()</code>.</p>
<p>You could also create a month column from the index, using <code>df['month'] = df.index.month</code>, then perform a groupby operation, <code>df.groupby('month').sum()</code> - whic... | 0 | 2016-06-28T15:23:41Z | [
"python",
"pandas"
] |
Sum of values with same month | 38,080,070 | <pre><code>data = {'dates': ['2010-01-29', '2011-06-14', '2012-01-18'], 'values': [4, 3, 8]}
df = pd.DataFrame(data)
df.set_index('dates')
df.index = df.index.astype('datetime64[ns]')
</code></pre>
<p>Having a dataframe where the index is a date, how would I go about adding a new column caled 'Month' that is the sum o... | 2 | 2016-06-28T15:14:27Z | 38,080,288 | <p>You can use pandas <code>TimeGrouper</code></p>
<pre><code>df.groupby(pd.TimeGrouper('M')).sum()
</code></pre>
| 4 | 2016-06-28T15:24:20Z | [
"python",
"pandas"
] |
Sum of values with same month | 38,080,070 | <pre><code>data = {'dates': ['2010-01-29', '2011-06-14', '2012-01-18'], 'values': [4, 3, 8]}
df = pd.DataFrame(data)
df.set_index('dates')
df.index = df.index.astype('datetime64[ns]')
</code></pre>
<p>Having a dataframe where the index is a date, how would I go about adding a new column caled 'Month' that is the sum o... | 2 | 2016-06-28T15:14:27Z | 38,082,081 | <p><code>apply</code> is your friend here</p>
<pre><code>def sum_from_months_prior(row, df):
'''returns sum of values in row month,
from all dates in df prior to row date'''
month = pd.to_datetime(row).month
all_dates_prior = df[df.index <= row]
same_month = all_dates_prior[all_dates_prior.in... | 2 | 2016-06-28T16:54:27Z | [
"python",
"pandas"
] |
wxpython: how to make a popup window stay on top of the current application | 38,080,092 | <p>I have an application that produces a popup window containing a progress bar. The code related to the popup window is below. I would like to force this popup window to stay on top of the application that produces this window. I tried using <code>wx.STAY_ON_TOP</code>, but using this style forces the popup window to ... | 1 | 2016-06-28T15:15:16Z | 38,080,127 | <p>use style <code>wx.FRAME_FLOAT_ON_PARENT</code></p>
<pre><code>class ProgressBar(wx.Frame):
def __init__(self, parent): # you must set the parent ...
wx.Frame.__init__(self, parent, title="In progress...",
size=(300, 125),style=wx.FRAME_FLOAT_ON_PARENT)
...
</code>... | 0 | 2016-06-28T15:16:57Z | [
"python",
"wxpython"
] |
Pandas Frequency Conversion | 38,080,184 | <p>I'm trying to find if is possible to use <code>data.asfreq(MonthEnd())</code> with no <code>date_range</code> created data.
What I'm trying to achive. I run csv query with the following code:</p>
<pre><code>import numpy as np
import pandas as pd
data = pd.read_csv("https://www.quandl.com/api/v3/datasets/FRED/GDPC1.... | 1 | 2016-06-28T15:18:59Z | 38,082,833 | <p>Use a <code>TimeGrouper</code>:</p>
<pre><code>import pandas as pd
periods = ['1948-07-01', '1948-04-01', '1948-01-01', '1947-10-01',
'1947-07-01', '1947-04-01', '1947-01-01']
integs = [2033.2, 2021.9, 1989.5, 1960.7, 1930.3, 1932.3, 1934.5]
df = pd.DataFrame({'period': pd.to_datetime(periods), 'integ':... | 2 | 2016-06-28T17:37:44Z | [
"python",
"pandas"
] |
FloatingPointError in calculating standard deviation? | 38,080,286 | <p>Using <code>pandas/numpy</code>, I sometimes get the floating point error when trying to calculate a standard deviation:</p>
<blockquote>
<p>FloatingPointError: invalid value encountered in less</p>
</blockquote>
<p>My code looks something like this:</p>
<pre><code>def historical_volatility(p):
return p.pct... | 0 | 2016-06-28T15:24:02Z | 38,081,484 | <p>Computing standard deviation likely involves doing a square root of the variance. The latter can only be negative if there's some precision loss. If this is the case, you likely don't care if your variance is of the order of 1e-16 or zero. If you do, you likely need to use extended precision (not easy), or switch to... | 0 | 2016-06-28T16:23:44Z | [
"python",
"numpy",
"pandas"
] |
How to add custom HTTP response header in Flask-RESTful? | 38,080,310 | <p>I am using Flask-RESTful and would like to handle certain errors by adding a custom HTTP header to my response. Is there a standard Flask or Flask-RESTful way of doing this?</p>
| -1 | 2016-06-28T15:25:28Z | 38,080,661 | <p>Turns out I skipped over that part of the docs: </p>
<pre><code>class Todo3(Resource):
def get(self):
# Set the response code to 201 and return custom headers
return {'task': 'Hello world'}, 201, {'Etag': 'some-opaque-string'}
</code></pre>
| 1 | 2016-06-28T15:41:37Z | [
"python",
"flask",
"flask-restful"
] |
Dynamically check if a slug exists | 38,080,311 | <p>On a legacy app, I need to check if a URL exists, and if it does not, to redirect it to another location. The problem is that I need to check if that url is present in a set of values, in the urls file and I'm not clear on how best to do that.</p>
<p>For example, both projects and cities are sharing the same url pa... | 1 | 2016-06-28T15:25:28Z | 38,082,330 | <p>You can dynamically generate a url with all of the city names, but the url will be cached once django accesses it the first time, so in order to modify the url regex, you'd have to restart the django process. If that's fine for your purposes, you can generate the url like this:</p>
<pre><code>url(r'^projects/(?P<... | 2 | 2016-06-28T17:08:48Z | [
"python",
"regex",
"django",
"url",
"slug"
] |
How to find the position of a word in a string / list? | 38,080,394 | <p>I'm writing a function where the user inputs a word, then inputs a string, and the function identifies all occurrences and the position of that word in a string (although it's actually converted to a list halfway through). </p>
<p>The code I have currently is only identifying the first occurrence of the word, and n... | -1 | 2016-06-28T15:28:57Z | 38,080,632 | <p>Try this:</p>
<pre><code>def wordlocator(word):
yourWord = word
print("You have chosen the following word: " +yourWord)
aString = raw_input("What string would you like to search for the given word?")
aString = aString.lower()
aString = aString.split()
b = [(i+1, j) for i, j in enumerate(aStr... | 1 | 2016-06-28T15:40:24Z | [
"python",
"string",
"list",
"position",
"word"
] |
How can I install the latest Anaconda with wget | 38,080,407 | <p>I'm looking at installing anaconda via wget on my server. I've come across <a href="http://askubuntu.com/questions/505919/installing-anaconda-python-on-ubuntu">http://askubuntu.com/questions/505919/installing-anaconda-python-on-ubuntu</a> and <a href="http://ericjonas.com/anaconda.html" rel="nofollow">http://ericjon... | 0 | 2016-06-28T15:29:38Z | 38,080,641 | <p>wget just downloads the file...</p>
<pre><code>wget http://repo.continuum.io/archive/Anaconda3-4.0.0-Linux-x86_64.sh
</code></pre>
<p>This is a shell script that guides you though the install. </p>
<p>Run the following line inside of the folder of the downloaded file to start the guided install...</p>
<pre><code... | 2 | 2016-06-28T15:40:56Z | [
"python",
"linux",
"wget",
"anaconda"
] |
Add value of a dict to a variable | 38,080,642 | <p>I have a dictionary that binds an integer to every character in the alphabet like so:</p>
<p><code>letter_values = {'a': 1, 'b': 3, 'c': 3}</code> and so on</p>
<p>My program asks the user for an input, iterates over each character of the string and adds the respecting value from the dictionary to a variable calle... | 0 | 2016-06-28T15:40:58Z | 38,080,738 | <p><code>values()</code> returns a list, not the specific value. Dictionary values can be accessed by square brackets, though. Try:</p>
<pre><code>for letter in word:
score += letter_values[letter]
</code></pre>
| 3 | 2016-06-28T15:45:30Z | [
"python",
"dictionary"
] |
How to submit multiple values using ajax and django | 38,080,651 | <p>Question I want to be able to submit multiple records with my ajax form submission. This form is a partial and I want to be able to submit multiples of this form each time. This is what I have so far I can't get my textbox.vals anymore using a serialized string. Any help would be greatly appreciated.</p>
<p>Here is... | 0 | 2016-06-28T15:41:18Z | 38,080,806 | <p>You need to concat correctly your data string like:</p>
<pre><code>data: $('#form').serialize() + "&description=" + $('#id_description').val() + "&style=" + $('#id_style').val(); // ...
</code></pre>
| 0 | 2016-06-28T15:48:24Z | [
"javascript",
"jquery",
"python",
"ajax",
"django"
] |
How to submit multiple values using ajax and django | 38,080,651 | <p>Question I want to be able to submit multiple records with my ajax form submission. This form is a partial and I want to be able to submit multiples of this form each time. This is what I have so far I can't get my textbox.vals anymore using a serialized string. Any help would be greatly appreciated.</p>
<p>Here is... | 0 | 2016-06-28T15:41:18Z | 38,765,373 | <p>Just do it this way </p>
<pre><code>function SaveDim() {
$.ajax({
type: "POST",
url: "/sheet/sheet_form_create.html/_dim",
//dataType: "json",
//make sure you give your form an id of "dim_form"
data: $('#dim_form').serialize()
success: function (json) {
... | 0 | 2016-08-04T10:53:48Z | [
"javascript",
"jquery",
"python",
"ajax",
"django"
] |
multidimensional hierarchical clustering - python | 38,080,769 | <p>is there something out there that does multidimensional hierarchical clustering?</p>
<p>I have looked in these places:</p>
<ul>
<li><a href="http://docs.scipy.org/doc/scipy/reference/cluster.hierarchy.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/cluster.hierarchy.html</a></li>
<li><a href="http:/... | 0 | 2016-06-28T15:46:54Z | 38,082,098 | <p>Here's a quick example. Here, this is clustering 4 random variables with hierarchical clustering:</p>
<pre><code>%matplotlib inline
import matplotlib.pylab as plt
import seaborn as sns
import pandas as pd
import numpy as np
df = pd.DataFrame({"col" + str(num): np.random.randn(50) for num in range(1,5)})
sns.cluste... | 1 | 2016-06-28T16:55:37Z | [
"python",
"multidimensional-array",
"cluster-analysis"
] |
Django Runserver - moving from running locally | 38,080,807 | <p>I want to move from local host to a static IP address (I have it already) with specific DNS name, I'm confused on how to do that? and how to make my app working just by accessing this IP or DNS names from a web browser? Should any machine install all the requirements like Python, Django, IDE etc? not sure how this w... | 0 | 2016-06-28T15:48:27Z | 38,085,144 | <p>I'm fairly new to Django but I got my website up and running on PythonAnywhere. It was easy to setup and they provide domain name as <code>[username].pythonanywhere.com</code>. I followed this tutorial in order to set it up: <a href="http://tutorial.djangogirls.org/en/deploy/" rel="nofollow">http://tutorial.djangogi... | 2 | 2016-06-28T19:52:47Z | [
"python",
"django",
"server",
"static-ip-address"
] |
Copying data from excel spreadsheet into list with python | 38,080,841 | <p>I'm trying to copy data from particular cells in an excel spreadsheet to a list. I would like to do some simple calculations on the data after, however I cannot seem to get the data to append into a list. I get an error saying "AttributeError: 'list' object attribute 'insert' is read-only"</p>
<pre><code>import ope... | 0 | 2016-06-28T15:50:25Z | 38,080,900 | <p>You can't append to a list in python by saying <code>client.append() = xyz</code></p>
<p>Try the following</p>
<pre><code>client.append(cellObj.value)
</code></pre>
| 3 | 2016-06-28T15:53:00Z | [
"python",
"excel"
] |
Draw a map based on values from the source point | 38,080,867 | <p>I want to make a map. So I have values in an array and I want to use those values to make a map. So the values are from 1 to 250 and there are 120 of them (one for 3 degrees). So how do I calculate where should I put my points based on the values in the right order (from 0 to 360 degrees)?</p>
<p>Here is my code so... | 0 | 2016-06-28T15:51:42Z | 38,082,769 | <p>So full size of your field is <code>2w=500</code>, and half-size is <code>w=250</code></p>
<p>Center of field has coordinates <code>(cx, cy)</code> = <code>(w, w)</code></p>
<p>Distance are already normalized in you case (max value 250 = w)</p>
<p>If your objects are point in the center angle of the sector, then ... | 0 | 2016-06-28T17:34:08Z | [
"python",
"python-3.x",
"geometry",
"pygame"
] |
python - How can I separate a single object file into multiple iterator | 38,080,923 | <p>There is a large file called <code>/tmp/largefile</code>, and I want to handle the file line by line. My idea is as follow:</p>
<pre><code> |---- Process-001 (largefile-part1)
|
|---- Process-002 (lar... | -1 | 2016-06-28T15:53:51Z | 38,081,059 | <p>you can use <code>itertools.tee</code> to return 2 copies of an iterator</p>
<pre><code>f = open("/tmp/largefile")
for i in range(5):
f,f_copy = itertools.tee(f)
proc = multiprocessing.Process(target=demo, args=(f_copy, ))
processes.append(proc)
</code></pre>
<p>I guess ... this probably isnt really w... | 0 | 2016-06-28T16:01:01Z | [
"python",
"parallel-processing",
"multiprocessing"
] |
Python: SWIG: Wrap Access to a Struct | 38,080,961 | <p>Assume I've got a simple structure with a single field:</p>
<pre><code>typedef struct {
MY_UNICODE value[512];
} TEST_STRUCTURE
</code></pre>
<p>Where <code>MY_UNICODE</code> is a custom unicode implementation.
Additionally I've got two methods:</p>
<pre><code>int UTF8ToMyUnicode(char *utf8, MY_UNICODE *unico... | 1 | 2016-06-28T15:56:01Z | 38,104,446 | <p>I've solved the problem myself. The important thing is that the typemaps need to be defined BEFORE the structures are defined in the interface. The documentation is not clear about that (or I have not seen it). Additionally the "in" and "out" typemaps can than be used to transform the values.
This example works for ... | 2 | 2016-06-29T15:47:36Z | [
"python",
"c",
"swig"
] |
Need return to match what print is showing me | 38,080,970 | <p>I need return to give what the last print line is giving me.
At the bottom I have invoked class with values. Also, pointers to improve the code are welcome.</p>
<pre><code>class Building:
def __init__(self, south, west, width_WE, width_NS, height=10):
# making variables non-local
self.south=int(... | -1 | 2016-06-28T15:56:37Z | 38,081,152 | <p>Use <code>__str__</code> instead:</p>
<pre><code> def __str__(self):
return "Building({0},{1},{2},{3},{4})".format(self.south, self.west, self.width_WE, self.width_NS,"10")
def __repr__(self):
__str__()
</code></pre>
<p>Also you should probably not be setting <code>height</code> explicit... | 1 | 2016-06-28T16:05:23Z | [
"python",
"python-3.x",
"return",
"repr"
] |
Is it possible to start a TCP socket connection without a handshake? | 38,080,972 | <p>I am making a SSL server, and I don't use python's library as I want to make some unorthodox changes to the process. Because of that, I cannot simply start a TCP connection since I need to transfer the encryption details with the handshake, which I can't do over sockets. So I am using scapy to make the handshake its... | 1 | 2016-06-28T15:56:39Z | 38,081,248 | <p>If I understand your question correctly, you exchanged a few segments using scapy and now want to manufacture a normal full-blown socket out of them.</p>
<p>This is not easily possible: for all practical purposes your TCP is oblivious to whatever you sent in your packets and it doesn't keep any state for this TCP c... | 0 | 2016-06-28T16:10:31Z | [
"python",
"sockets",
"tcp",
"scapy"
] |
How to access files in a project's virtual env that are not installed in the virtual env | 38,081,015 | <p>I have a flask app with the following structure (using a shared virtual environment):</p>
<pre><code>|-Directory
|----venv/lib/python2.7/site-packages/example-package
|----------module.py
|----app
|----------static
|----------templates
|----------models.py
|--------------...
</code></pre>
<p>I need to access some ... | 0 | 2016-06-28T15:58:30Z | 38,103,420 | <p>The answer to my question was simple (and I was steered in the right direction by @jonrsharpe). As per <a href="http://stackoverflow.com/questions/3765222/monkey-patch-python-class">monkey-patch-python-class</a> I added the desired class to the root of the library with the module that needed the override and used th... | 0 | 2016-06-29T15:04:05Z | [
"python",
"flask",
"module",
"virtualenv"
] |
Handle exception raised in except clause | 38,081,034 | <p>In what I have written, <code>NoResultException</code> can be raised either in my <code>try</code> block or my <code>except UnexpectedAlertPresentException</code> block. I would like to go to the <code>except NoResultException</code> block in either case, but it only does this if <code>NoResultException</code> is ra... | 0 | 2016-06-28T15:59:33Z | 38,081,254 | <pre><code>try:
try:
# do things
except UnexpectedAlertPresentException:
# do other things, including possibly raise NoResultException
except NoResultException:
# handle exception
</code></pre>
<p>Try not to go overboard with the exception-handling control flow. The logic can get really har... | 1 | 2016-06-28T16:10:55Z | [
"python"
] |
Facecolor changing edgecolor in matplotlib | 38,081,037 | <p>I am trying to remove the edge color in the plot of a cylinder where I have set an alpha and facecolors. However, if I also set the facecolors, I can still see the edge colors. If I remove the <code>alpha = 0.5</code> statement then the problem is resolved, however I need the alpha to be <1 . Here is an example:<... | 0 | 2016-06-28T15:59:37Z | 38,082,786 | <p>Setting <code>linewidth=0</code> in <code>plot_surface()</code> solves this problem: </p>
<pre><code>ax.plot_surface(X, Y, Z, edgecolor=None, facecolors=col1, alpha=0.5, linewidth=0)
</code></pre>
<p><a href="http://i.stack.imgur.com/4PUAW.png" rel="nofollow"><img src="http://i.stack.imgur.com/4PUAW.png" alt="ente... | 1 | 2016-06-28T17:35:11Z | [
"python",
"matplotlib"
] |
Flask-edits: AttributeError: 'TokenStream' object has no attribute 'next' | 38,081,040 | <p>I am trying to test the flask-edits package (<a href="https://github.com/nathancahill/Flask-Edits" rel="nofollow">https://github.com/nathancahill/Flask-Edits</a>) </p>
<p>Can anyone help with this error: AttributeError: 'TokenStream' object has no attribute 'next' </p>
<pre><code>@app.route('/')
def hello_wo... | 0 | 2016-06-28T15:59:40Z | 38,081,312 | <p>Assuming Flask-Edits wants to support Python 3, this is a bug in Flask-Edits. It should use the builtin <a href="https://docs.python.org/3/library/functions.html#next" rel="nofollow"><code>next</code></a> function to advance iterators: <code>next(parser.stream)</code>. The method on the iterator changed from <code... | 0 | 2016-06-28T16:14:03Z | [
"python",
"flask"
] |
how to ignore a field data while comparing 2 files in python | 38,081,143 | <p>Input files are as below with fields schema <code>asMode|Date|Count|timestamp|status|insertTimeStamp</code></p>
<pre><code>test1.txt:
HR|06/08/2016|3000|Thu Jun 09 2016|Complete|20160627020300
HR|06/08/2016|2000|Thu Jun 09 2016|Complete|20160627020400
HR|06/08/2016|1000|Thu Jun 09 2016|Complete|20160627020500
test2... | 1 | 2016-06-28T16:04:56Z | 38,081,339 | <p>You could potentially just slice off the last element in each line before passing them into the diff function</p>
<pre><code>diff = difflib.unified_diff(
['|'.join(x.split('|')[:-1]) for x in hosts0.readlines()],
['|'.join(x.split('|')[:-1]) for x in hosts1.readlines()],
fromfile='hosts0',
tofile='h... | 1 | 2016-06-28T16:15:32Z | [
"python"
] |
Passing file name locations (arguments) using VBscript to Python | 38,081,192 | <p>I need to execute a python script & pass it a input file & location, also a output location.</p>
<p>This is my attempt...</p>
<pre><code>strPathAndFile = file name and path.
Set WSHShell = CreateObject("Wscript.Shell")
Return = WSHShell.Run("""CMD /C python c:\filepath\python.py"" " & -i strPathAndFil... | 0 | 2016-06-28T16:07:25Z | 38,085,638 | <p>Problems like this are more easily solved, if you approach them systematically:</p>
<pre><code>Option Explicit
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Function qq(s) : qq = """" & s & """" : End Function
' Trying to identify the parts from the question
' """CMD /C python
' c:\fil... | 0 | 2016-06-28T20:24:04Z | [
"python",
"vbscript"
] |
Printing a dictionary with print | 38,081,237 | <p>Why does </p>
<pre><code> d = {"A":10,"B":20}
print(*d, sep=" ")
</code></pre>
<p>Output <code>A B</code> and not <code>10 20</code>?</p>
<p>And how do i get <code>10 20</code>?</p>
| 0 | 2016-06-28T16:09:55Z | 38,081,482 | <p>simply write</p>
<pre><code>print (*d.values() )
</code></pre>
| 2 | 2016-06-28T16:23:41Z | [
"python",
"python-3.x"
] |
Printing a dictionary with print | 38,081,237 | <p>Why does </p>
<pre><code> d = {"A":10,"B":20}
print(*d, sep=" ")
</code></pre>
<p>Output <code>A B</code> and not <code>10 20</code>?</p>
<p>And how do i get <code>10 20</code>?</p>
| 0 | 2016-06-28T16:09:55Z | 38,081,519 | <p>Assuming what you want is to print the keys <em>together</em> with the values you could use a generator expression:</p>
<pre><code>print(' '.join('{}={}'.format(k,v) for k,v in d.items()))
</code></pre>
<p>or if you prefer to keep the <code>sep</code> argument instead of using <code>str.join</code>:</p>
<pre><cod... | 3 | 2016-06-28T16:25:19Z | [
"python",
"python-3.x"
] |
Printing a dictionary with print | 38,081,237 | <p>Why does </p>
<pre><code> d = {"A":10,"B":20}
print(*d, sep=" ")
</code></pre>
<p>Output <code>A B</code> and not <code>10 20</code>?</p>
<p>And how do i get <code>10 20</code>?</p>
| 0 | 2016-06-28T16:09:55Z | 38,081,835 | <p>Please see a demo for print introduction:</p>
<pre><code>>>> def demo(p, *args, **kwargs):
... print(args)
... print(kwargs)
...
>>> demo(0, 1, 2, 3, 4, callback='demo_callback')
(1, 2, 3, 4)
{'callback': 'demo_callback'}
</code></pre>
<ol>
<li><p>The <code>*</code> syntax requires a tupl... | 1 | 2016-06-28T16:40:40Z | [
"python",
"python-3.x"
] |
Stream Output of Predictions in Keras | 38,081,263 | <p>I have an LSTM in Keras that I am training to predict on time series data. I want the network to output predictions on each timestep, as it will receive a new input every 15 seconds. So what I am struggling with is the proper way to train it so that it will output h_0, h_1, ..., h_t, as a constant stream as it rec... | 4 | 2016-06-28T16:11:29Z | 38,086,965 | <p>You can enable statefulness in your LSTM layers by setting <a href="http://keras.io/layers/recurrent/#recurrent" rel="nofollow"><code>stateful=True</code></a>. This changes the behavior of the layer to always use the state of the previous invocation of the layer instead of resetting it for each <code>layer.call(x)</... | 3 | 2016-06-28T21:56:38Z | [
"python",
"keras",
"recurrent-neural-network"
] |
Storing multiple objects in an HDFStore group | 38,081,274 | <p>I want to store multiple objects in an HDFStore, but I want to organize it by grouping. Something along the lines of:</p>
<pre><code>import pandas as pd
my_store = pd.HDFStore('my_local_store.h5')
my_store._handle.createGroup('/', 'data_source_1') # this works, but I'm not sure what it does
my_store['/data_source_1... | 1 | 2016-06-28T16:11:54Z | 38,081,316 | <p>try this:</p>
<pre><code>my_store['/data_source_1/part-1'] = ...
</code></pre>
<p>demo:</p>
<pre><code>In [13]: store = pd.HDFStore('c:/temp/stocks.h5')
In [15]: store['/aaa/bbb'] = df
In [17]: store.groups
Out[17]:
<bound method HDFStore.groups of <class 'pandas.io.pytables.HDFStore'>
File path: c:/te... | 1 | 2016-06-28T16:14:12Z | [
"python",
"pandas",
"hdfstore"
] |
Django: Is there a way to add a foreign key field to "unique_together"? | 38,081,310 | <p>I want to be able to make a model unique on a value that comes from a foreign key model. Not sure if that's possible in django.</p>
<p>Example: I have a model A as:</p>
<pre><code>class modelA(models.Model):
fieldA1 = models.AutoField(primary_key=True)
fieldA2 = models.CharField(max_length=20)
</code></pre... | 0 | 2016-06-28T16:14:02Z | 38,081,616 | <p>you cannot. database constraints cannot contain those kind of data. you will have to check it programmatically before creating instances or write some validator</p>
| 1 | 2016-06-28T16:30:55Z | [
"python",
"django",
"database"
] |
Fabric nonzero return code 137 | 38,081,313 | <p>I have the following task in fabric, designed to brute force kill all celery workers in an emergency</p>
<pre><code>def brute_kill_cel_workers():
with settings(sudo_user="operatore"):
sudo("sudo ps aux|grep 'celery worker'|awk '{print $2}'|xargs sudo kill -9")
</code></pre>
<p>It fails with</p>
<pre><c... | 0 | 2016-06-28T16:14:10Z | 38,084,736 | <p>As you killed Celery with SIGKILL (kill -9) you get that return code: 128 + 9 (see <a href="http://www.tldp.org/LDP/abs/html/exitcodes.html" rel="nofollow">this list of exit codes</a>).</p>
<p>If you check the return code when you run that command with ssh, you'll see the code is identical, but just not handled: wh... | 1 | 2016-06-28T19:28:59Z | [
"python",
"linux",
"celery",
"fabric"
] |
Iterating on a file and comparing values using python | 38,081,334 | <p>I have a section of code that opens files containing information with wavenumber and intensity like this:</p>
<pre><code>500.21506 -0.00134
500.45613 0.00231
500.69720 -0.00187
500.93826 0.00129
501.17933 -0.00049
501.42040 0.00028
501.66147 0.00114
501.90253 -0.00036
502.14360 0.00247
</code></pre>
<p>My code att... | 0 | 2016-06-28T16:15:11Z | 38,081,366 | <p>The problem is that when you iterate over the file <code>g</code> you are effectively moving its "file pointer". So the second loop finds the file at the beginning and doesn't produce any value.</p>
<p>Secondly, you are producing all these <code>nums</code> lists, but every iteration of the lop shadows the previous... | 1 | 2016-06-28T16:17:39Z | [
"python",
"comparison",
"iteration"
] |
Iterating on a file and comparing values using python | 38,081,334 | <p>I have a section of code that opens files containing information with wavenumber and intensity like this:</p>
<pre><code>500.21506 -0.00134
500.45613 0.00231
500.69720 -0.00187
500.93826 0.00129
501.17933 -0.00049
501.42040 0.00028
501.66147 0.00114
501.90253 -0.00036
502.14360 0.00247
</code></pre>
<p>My code att... | 0 | 2016-06-28T16:15:11Z | 38,082,298 | <p>Split each line by white space, unpack the split list to two names <code>wavelength</code> and <code>intensity</code>. </p>
<p><code>[line.split() for line in r]</code> makes</p>
<pre><code>500.21506 -0.00134
500.45613 0.00231
</code></pre>
<p>to</p>
<pre><code>[['500.21506', '-0.00134'], ['500.45613', '0.00231... | 0 | 2016-06-28T17:07:25Z | [
"python",
"comparison",
"iteration"
] |
Issue with requests module in python for AWS Lambda | 38,081,350 | <p>I am writing a lambda function with an intent that uses requests to pull information from a <em>Wolfram</em> CloudObject. Here is the relevant part of the code:</p>
<pre><code>from __future__ import print_function
import requests
.
.
.
def on_intent(intent_request, session):
print("on_intent requestID=" + int... | 2 | 2016-06-28T16:16:15Z | 38,085,325 | <p>You can read more about requests' use of certificates here:</p>
<p><a href="http://docs.python-requests.org/en/master/user/advanced/" rel="nofollow">http://docs.python-requests.org/en/master/user/advanced/</a></p>
<p>There are two ways to get around this problem:</p>
<ul>
<li>Find the certificate that you are mis... | 1 | 2016-06-28T20:04:34Z | [
"python",
"amazon-web-services",
"aws-lambda"
] |
Issue with requests module in python for AWS Lambda | 38,081,350 | <p>I am writing a lambda function with an intent that uses requests to pull information from a <em>Wolfram</em> CloudObject. Here is the relevant part of the code:</p>
<pre><code>from __future__ import print_function
import requests
.
.
.
def on_intent(intent_request, session):
print("on_intent requestID=" + int... | 2 | 2016-06-28T16:16:15Z | 38,187,866 | <p>The lambda environment does not include the certifi module, unless you upload it with your function.</p>
<p>I would do this:</p>
<pre><code>cd <directory with your lambda>
pip install certifi -t .
zip ../lambda *
</code></pre>
<p>Then upload the ../lambda.zip to Amazon.</p>
| 1 | 2016-07-04T15:12:15Z | [
"python",
"amazon-web-services",
"aws-lambda"
] |
How to shared data between instances classes (backend) and Kivy graphical elements (frontend)? | 38,081,375 | <p>I'm a beginner with Kivy and I'm trying to create gui for a python app.
I have a backend programmed in python, working alone (keyboard as input) and now I want frontend with kivy. I have two questions:
- How can I run both components (back and front end) at once?
- How can I share objects of existing classes in my... | 1 | 2016-06-28T16:18:06Z | 38,084,567 | <p>It won't update because... of a loop :P Kivy for each <code>App().run()</code> or a similar "run" command launches a loop and your:</p>
<pre><code>for u in users:
test = classtest.Test(u)
</code></pre>
<p>is written <em>after</em> that loop. So basically it won't even execute while your app is running. Just pu... | 0 | 2016-06-28T19:17:56Z | [
"python",
"kivy"
] |
Bokeh server + reverse-proxying with Nginx gives 404 | 38,081,389 | <p>I'm trying to set up a Bokeh server and reverse proxy it with Nginx.</p>
<p>My p-website.conf now looks like:</p>
<pre><code>server {
listen 80;
server_name website.com;
client_max_body_size 25M;
access_log /var/www/logs/p-website.access.nginx.log;
error_log /var/www/logs/p-website.error.nginx.log error;
root... | 0 | 2016-06-28T16:18:42Z | 38,505,205 | <p>I figured it out, apparently you need to add --prefix= with same location to the Bokeh command:</p>
<pre><code>bokeh serve bokehserver.py --port 5100 --prefix=/plot/ --host website.com:80
</code></pre>
<p>And the location block in p-website.conf will look like:</p>
<pre><code>location /plot/ {
proxy_pass http... | 1 | 2016-07-21T13:10:19Z | [
"python",
"nginx",
"proxy",
"bokeh"
] |
Python - drop rate in games, random with assigned probability | 38,081,402 | <p>Lets say I 30 numbers<br/>
I need to assign them random but with drop chances<br/>
Ex: There's 2% for number 1, 1.5% for number 2, 1.1% for number 3, 1.7% for number 4 etc...<br/>
I'm genereting random numbers with this<br/></p>
<pre><code>from random import randint
import string
import random
print(randint(1,30))... | 1 | 2016-06-28T16:19:31Z | 38,081,476 | <p>This would work it allows you to choose the numbers and your probabilities </p>
<pre><code>from scipy import stats
numbers = (1,2,3)
probability = (0.02, 0.015, 0.011)
test1 = stats.rv_discrete(name='test1', values=(numbers, probability))
test1_results = test1.rvs(size=30)
</code></pre>
<p>Here is how to get non-r... | 2 | 2016-06-28T16:23:13Z | [
"python",
"python-2.7"
] |
Python - drop rate in games, random with assigned probability | 38,081,402 | <p>Lets say I 30 numbers<br/>
I need to assign them random but with drop chances<br/>
Ex: There's 2% for number 1, 1.5% for number 2, 1.1% for number 3, 1.7% for number 4 etc...<br/>
I'm genereting random numbers with this<br/></p>
<pre><code>from random import randint
import string
import random
print(randint(1,30))... | 1 | 2016-06-28T16:19:31Z | 38,081,497 | <pre><code>from numpy.random import choice
items = "common","uncommon","rare","super rare"
probabilities = [0.5,0.35,0.1,0.05]
N_TESTS = 10
for i in range(N_TESTS):
print choice(items,p=probabilities)
</code></pre>
<p>you could then abstract this out to where each of those was a "category"</p>
<pre><code>items = ... | 2 | 2016-06-28T16:24:11Z | [
"python",
"python-2.7"
] |
Installing mongo-db via a python script. Subprocess calls fail | 38,081,451 | <p>I'm trying to install mongo-db on an ubuntu machine via a python script.
If I were to do it manually, using the following steps found <a href="https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/" rel="nofollow">here</a>, it works perfectly.</p>
<pre><code>sudo apt-key adv --keyserver hkp://keyserver... | 0 | 2016-06-28T16:22:23Z | 38,148,938 | <p>The obvious difference: <code>sudo</code> and the absence of the shell that would interpret <code>|</code> (pipe). See <a href="http://stackoverflow.com/q/295459/4279">How do I use subprocess.Popen to connect multiple processes by pipes?</a></p>
| 0 | 2016-07-01T15:21:18Z | [
"python",
"mongodb",
"ubuntu",
"subprocess"
] |
Is there a way to know if Tkinter optionmenu dropdown is active ? | 38,081,470 | <p>I'm writing a Tkinter program where I have an option menu with other UI elements. I have a requirement that if optionmenu drop down remains active for a particular time (say 1 minute), I need to close drop down menu and cancel the selection. I was wondering if there is a way to know if an optionmenu dropdown is acti... | 4 | 2016-06-28T16:22:55Z | 38,253,137 | <p>First define a variable,(for example: ddo = 0)
Then Trigger a click on your dropdownlist, when clicked, toggle ddo = 1(if ddo == 1 then ddo = 0)
and when ddo == 1 a timer start to count for 1second, after that 1second if ddo == 1, then close selectbox(for example by focusing on another element) and do what ever you ... | 1 | 2016-07-07T18:47:18Z | [
"python",
"tkinter"
] |
Is there a way to know if Tkinter optionmenu dropdown is active ? | 38,081,470 | <p>I'm writing a Tkinter program where I have an option menu with other UI elements. I have a requirement that if optionmenu drop down remains active for a particular time (say 1 minute), I need to close drop down menu and cancel the selection. I was wondering if there is a way to know if an optionmenu dropdown is acti... | 4 | 2016-06-28T16:22:55Z | 38,289,976 | <p>Keeping track of whether the menu is closed or open is easily done with a command and click binding. The hard part is forcing the menu to close. Either a physical mouse click off the widget or press of Escape will do so. But generating events does not do. The #commented_out bits below are failed experiments.</p>... | 1 | 2016-07-10T08:16:43Z | [
"python",
"tkinter"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.