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
Bokeh Doesn't Render Plot with Flask App
38,129,574
<p>My flask driven app works as expected with the high level Bar plot from Bokeh.</p> <p>I now want to change the plot to a horizontal bar plot and found <a href="http://stackoverflow.com/questions/33737079/how-to-plot-horizontal-bar-chart-in-bokeh-python">this</a> SO answer. </p> <p>My code minus the formatting for ...
0
2016-06-30T17:17:44Z
38,131,933
<p>Following Bigreddot's advice, I checked my version of Bokeh and adjusted the BokehJS version to match.</p> <p><code>conda list bokeh</code> yielded:</p> <pre><code>bokeh 0.10.0 py27_0 </code></pre> <p>I then changed my html and the minimal example works as expected.</p> <...
1
2016-06-30T19:43:47Z
[ "python", "flask", "bokeh" ]
Unable to scrape quote of the day from forbes
38,129,681
<p>I'm trying to use python + Beautiful Soup to scrape the quote of the day from the forbes website.</p> <pre><code>import requests from bs4 import BeautifulSoup import urllib.request url = requests.get('http://www.forbes.com/quotes/1/') url = url.text soup = BeautifulSoup(url,'html.parser') print(soup.find('p',{'cla...
0
2016-06-30T17:24:51Z
38,129,946
<p>The quote itself is <em>loaded dynamically</em> from a different resource URL. Make request to it instead parsing the JSON response:</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; &gt;&gt;&gt; url = "http://www.forbes.com/forbesapi/thought/uri.json?enrich=true&amp;query=1&amp;relatedlimit=5" &gt;&gt;&gt; ...
1
2016-06-30T17:40:54Z
[ "python", "web-scraping", "beautifulsoup" ]
Tkinter .after runs forever and .mainloop never runs
38,129,689
<p>I'm creating a python program on my RPi3 that changes the frequency of a GPIO pin depending on a Tkinter scale. <br/> <br/> Here is my code: <br/></p> <pre><code>import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) from Tkinter import * import time freq = 1.0 master = Tk() def update(): period = 1.0/float(fre...
0
2016-06-30T17:25:08Z
38,129,875
<p><code>mainloop()</code> is running, but <code>Tkinter</code> won't update views unless it is idle. <code>KeyboardInterrupt</code> will tell it to cleanup, at which point it finishes its event queue (which includes updating interface) and exits.</p> <p>Solution: Give mainloop time to be idle- you really just need to...
0
2016-06-30T17:36:13Z
[ "python", "python-2.7", "tkinter", "raspberry-pi", "raspberry-pi3" ]
Tkinter .after runs forever and .mainloop never runs
38,129,689
<p>I'm creating a python program on my RPi3 that changes the frequency of a GPIO pin depending on a Tkinter scale. <br/> <br/> Here is my code: <br/></p> <pre><code>import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) from Tkinter import * import time freq = 1.0 master = Tk() def update(): period = 1.0/float(fre...
0
2016-06-30T17:25:08Z
38,131,377
<h2>Processing events</h2> <p>You are making two somewhat common mistakes: you shouldn't do <code>after(0, ...)</code>, and you shouldn't call <code>sleep</code>. </p> <ol> <li><p><code>after(0, ...)</code> means that every time you process the event, you immediately add another event. The event loop never has a chan...
1
2016-06-30T19:06:10Z
[ "python", "python-2.7", "tkinter", "raspberry-pi", "raspberry-pi3" ]
Why the last node is not getting deleted Linked List?
38,129,691
<p>I have below code. I am trying to delete the last node. But the node is not getting deleted. The <code>temp</code> is still holding the all the <code>data</code>. I did not understand that, in Python the assignment means <code>deep copy or shallow copy</code>?</p> <pre><code>class ll: def __init__(self, data): ...
0
2016-06-30T17:25:13Z
38,129,846
<p>Instead of using <code>del</code>, you should unreference the last node.</p> <p>Replace</p> <pre><code>if root.next != None and myfrontptr.next == None: del myfrontptr </code></pre> <p>With</p> <pre><code>if root.next != None and myfrontptr.next == None: root.next = None </code></pre>
2
2016-06-30T17:34:26Z
[ "python", "python-2.7", "linked-list" ]
Why the last node is not getting deleted Linked List?
38,129,691
<p>I have below code. I am trying to delete the last node. But the node is not getting deleted. The <code>temp</code> is still holding the all the <code>data</code>. I did not understand that, in Python the assignment means <code>deep copy or shallow copy</code>?</p> <pre><code>class ll: def __init__(self, data): ...
0
2016-06-30T17:25:13Z
38,129,858
<p>You forgot to set <code>next</code> reference in element before last element when last element is removed:</p> <pre><code>def delete_last(root): temp = root myfrontptr = root.next while myfrontptr.next != None: root = root.next myfrontptr = myfrontptr.next if root.next != None and my...
1
2016-06-30T17:35:17Z
[ "python", "python-2.7", "linked-list" ]
Does returning numpy array always produce a view?
38,129,746
<p>I have noticed that , say, this function,</p> <pre><code>def f(x): return(x) </code></pre> <p>would always return a view of the numpy array. Is this generally true? Are there any weird corner-cases I have to take into consideration, or can I rely on the fact that when an array is an argument to the <em>return<...
0
2016-06-30T17:28:00Z
38,129,767
<p>No, you won't always get a view. In fact, with the function that you have defined (<code>f</code>), you'll only get a view if you pass a view into the function. Otherwise, you'll get the original array back (which, I suppose in a lot of ways <em>acts</em> like a view)...</p> <pre><code>&gt;&gt;&gt; def f(x): ... ...
2
2016-06-30T17:29:20Z
[ "python", "arrays", "numpy" ]
Defining a complex-valued, piecewise function
38,129,750
<p>I'm trying to define a function f(x) which yields 1.0 for x = 0 and 1.0/(2j pi x) otherwise. Here is a 'test' script I'm using:</p> <pre><code>import numpy as np def f(x): return np.piecewise(x,[x==0],[1.0, lambda x: 1.0/(2j*np.pi*x)]) x = np.linspace(-1,1,21) print(x) print(f(x)) </code></pre> <p>If the la...
0
2016-06-30T17:28:18Z
38,129,876
<p>From the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.piecewise.html" rel="nofollow"><code>piecewise</code></a> docstring:</p> <pre><code>The output is the same shape and type as x... </code></pre> <p>For complex output, pass in a complex array.</p> <p>Continuing your example with <code>f</c...
1
2016-06-30T17:36:14Z
[ "python", "numpy" ]
Python dispy - keep package names for dependencies
38,129,770
<p>Is there a way to keep the package names for python modules that are transmitted via dispy's depends feature? That would allow using packages/modules in the same way when called with and without a dispy context.</p> <p>Simple Example:</p> <p>Module mypackage.dispytestDepends:</p> <pre><code>def myFun(): retur...
0
2016-06-30T17:29:45Z
38,352,350
<p>This should work now with the current version of dispy. See also <a href="https://github.com/pgiri/dispy/issues/43" rel="nofollow">https://github.com/pgiri/dispy/issues/43</a>.</p>
1
2016-07-13T12:53:03Z
[ "python", "parallel-processing", "distributed-computing", "dispy" ]
Pandas - Graphing Unstacked DataFrame with Multiple Columns
38,129,840
<p>I have a DataFrame in Pandas that looks like this when unstacked</p> <pre><code> Unique Sessions Date 2016-06-21 2016-06-29 Name ABCD 995 4,088 EFGH 8 25 OPEF 1 1 </code></pre> <p>How do I get Pandas to plot a stacked bar chart from this DataFr...
4
2016-06-30T17:34:20Z
38,130,208
<h3>Setup</h3> <pre><code>df = pd.DataFrame([[995, 4088], [8, 25], [1, 1]], index=pd.Index(['ABCD', 'EFGH', 'OPEF'], name='Name'), columns=pd.MultiIndex.from_product([['Unique Sessions'], ['2016-06-21', '2016-06-29']], names=[None...
1
2016-06-30T17:56:59Z
[ "python", "python-3.x", "pandas", "matplotlib" ]
Pandas Panel Merge
38,129,958
<p>What is the current, best Pandas recipe for merging panel data, such as the following:</p> <pre><code>p = pd.Panel(np.random.randn(2,5,4), items=['IBM', 'AA'], major_axis=pd.date_range('1/1/2000', periods=5), minor_axis=['Open', 'High', 'Low', 'Close']) dp = pd.Panel(np.random.randn(2,1,1), items=['...
2
2016-06-30T17:41:25Z
38,130,072
<p>I'd convert to dataframe, <code>combine_first</code>, and back again</p> <pre><code>new = p.to_frame().combine_first(dp.to_frame()).to_panel() print new[:,:,'Close'] AA IBM Z major 2000-01-01 1.348884 0.472272 NaN 2000-01-02 1.599357 -0.2287...
1
2016-06-30T17:47:52Z
[ "python", "pandas", "merge" ]
A non-function __get__ attribute of a descriptor receives an additional argument when called, why?
38,129,976
<p>Can someone explain why a non-function <code>__get__</code> attribute of a descriptor seems to receive an additional argument when called - namely the descriptor object (which is implicitly passed as self in the case of a function)?</p> <p>In the example below both <code>B</code> and <code>C</code> are non-data des...
0
2016-06-30T17:42:26Z
38,130,193
<p>This has nothing to do with <code>__get__</code>. You'll see the same effect without involving descriptors:</p> <pre><code>&gt;&gt;&gt; class A(object): ... def __call__(self, arg): ... return arg ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; def b(arg): ... return arg ... &gt;&gt;&gt; a(3) 3 &gt;&gt;&gt; b...
1
2016-06-30T17:56:09Z
[ "python" ]
python3 ftplib: check if dir exists via mlsd()
38,129,981
<p>I'm working with Python3 and ftplib.</p> <p>I need to check if a directory on the ftp server exists. (if not, I can create it, than cwd into it, if it already exists i will directly cwd into it).</p> <p>I've seen the method from Marek Marecki here: <a href="http://stackoverflow.com/questions/1098218/how-to-make-py...
0
2016-06-30T17:42:50Z
38,131,275
<p>I don't have any server that support MLSD command, so i not sure how do this with mlsd. But this code should work even without MLSD support.</p> <pre><code> items = [] ftp.retrlines('LIST', items.append ) items = map( str.split, items ) directorys = [ item.pop() for item in items if item[0][0] == '...
0
2016-06-30T19:00:59Z
[ "python", "python-3.x", "ftp", "ftplib" ]
python3 ftplib: check if dir exists via mlsd()
38,129,981
<p>I'm working with Python3 and ftplib.</p> <p>I need to check if a directory on the ftp server exists. (if not, I can create it, than cwd into it, if it already exists i will directly cwd into it).</p> <p>I've seen the method from Marek Marecki here: <a href="http://stackoverflow.com/questions/1098218/how-to-make-py...
0
2016-06-30T17:42:50Z
38,185,904
<p>Also thanks to @arnial</p> <p>I cam up with following: (mlsd or nslt)</p> <pre><code>use_mlsd = 1 if(use_mlsd): # if ftp server supports mlsd, use it, nlst is maked as deprecated in ftplib # check if remotefoldername exists remotefoldername_exists = 0 for name, facts in f.mlsd(".",["type"]): if facts["...
1
2016-07-04T13:25:22Z
[ "python", "python-3.x", "ftp", "ftplib" ]
Python equivalent for matlab's perms
38,130,008
<p>Is there an equivalent method in numpy or scipy for matlab's perms function? In matlab, perms returns a matrix of all possible permutations of the input in reverse lexicographical order.</p>
0
2016-06-30T17:44:12Z
38,130,043
<p>Python has a built-in function called <code>itertools.permutations</code>. You can call it on any <code>iterable</code> in python and it returns all full length permutations. </p>
3
2016-06-30T17:46:22Z
[ "python", "matlab", "numpy", "scipy" ]
Need examples for numpy basic indexing with `non-ndarray sequence`
38,130,054
<p>In numpy doc about <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing" rel="nofollow">basic slicing</a>, there is a situation described as:</p> <blockquote> <p>basic slicing is also initiated if the selection object is any non-ndarray sequence (such as a list) conta...
2
2016-06-30T17:47:04Z
38,130,262
<p>This is an interesting convenience. Lets say that I have the following array:</p> <pre><code>arr = np.arange(100) </code></pre> <p>If I'm being silly, I can slice an array like this:</p> <pre><code>arr[:30, ..., np.newaxis] </code></pre> <p>(The <code>Ellipsis</code> doesn't do anything helpful here, but I <em>...
3
2016-06-30T17:59:34Z
[ "python", "numpy", "scipy" ]
Binary seach tree, remove node, need help here (reposting)
38,130,092
<p>My code is looking like this:</p> <pre><code>class Treenode: def __init__(self,data,left=None,right=None): self.data=data self.left=left self.right=right def __str__(self): return str(self.data) def delete(self): child=self.left grandchild=child.right ...
-1
2016-06-30T17:49:12Z
38,130,548
<p>I recommend you this material from algorithm Princeton: <a href="http://algs4.cs.princeton.edu/32bst/" rel="nofollow">http://algs4.cs.princeton.edu/32bst/</a></p> <p>The delete method is using this approach to delete a node from a bst.</p> <blockquote> <p>Delete. We can proceed in a similar manner to delete any ...
2
2016-06-30T18:16:34Z
[ "python", "methods", "binary-search-tree" ]
Boolean expression in column indexer (Pandas) 'is' operator not working
38,130,108
<p>When I use:</p> <pre><code>df = data2analyse.loc[data2analyse.bool_var1 | data2analyse.bool_var2 | data2analyse.bool_var3, 'some column'] </code></pre> <p>works properly. But if I use</p> <pre><code>df = data2analyse.loc[data2analyse.bool_var1 is True | data2analyse.bool_var2 is True | ...
2
2016-06-30T17:50:15Z
38,130,330
<p>you shouldn't use <code>is</code> operator in this case, because <code>is</code> tells you whether it's the same object, i.e. whether <code>id()</code> of both objects are equal.</p> <pre><code>In [43]: df Out[43]: a b c 0 False False False 1 True True True 2 True False False 3 False ...
2
2016-06-30T18:03:51Z
[ "python", "python-2.7", "pandas", "indexing" ]
Connect points from two different arrays in Python
38,130,143
<p>I'm trying to connect the points from two arrays with lines. I only want to connect points in the same position (the first from stapts with the first from endpts), not all points. </p> <p>Can anyone tell me how to do that? Many thanks. Below I'm only plotting two scatter plots. </p> <p><div class="snippet" data-la...
0
2016-06-30T17:52:44Z
38,130,363
<p>I believe the following should work, drawing a single line for each pair of points. I'm unsure if this is the most efficient way to do it, but if you don't have too many points, you should be alright.</p> <pre><code>toPlot = zip(staptsx, staptsy, endptsx, endptsy) for tuple in toPlot: plt.plot([tuple[0], tuple[2]...
0
2016-06-30T18:05:35Z
[ "python", "arrays", "lines" ]
Changing size of scattered points in matplotlib
38,130,168
<p>I am doing some plotting using cartopy and matplotlib, and I am producing a few images using the same set of points with a different domain size shown in each image. As my domain size gets bigger, the size of each plotted point remains fixed, so eventually as I zoom out, things get scrunched up, overlapped, and gene...
2
2016-06-30T17:54:29Z
38,130,241
<p><a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter" rel="nofollow">http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter</a> </p> <p>These are the parameters that plt.scatter take and the <code>s</code> parameter is the size of the scattered point so change <code>s</code> to ...
0
2016-06-30T17:58:21Z
[ "python", "matplotlib", "plot", "cartopy" ]
Changing size of scattered points in matplotlib
38,130,168
<p>I am doing some plotting using cartopy and matplotlib, and I am producing a few images using the same set of points with a different domain size shown in each image. As my domain size gets bigger, the size of each plotted point remains fixed, so eventually as I zoom out, things get scrunched up, overlapped, and gene...
2
2016-06-30T17:54:29Z
38,131,657
<p><code>scatter</code> has the option <code>set_sizes</code>, which you can use to set a new size. For example:</p> <pre><code>import matplotlib.pylab as pl import numpy as np x = np.random.random(10) y = np.random.random(10) s = np.random.random(10)*100 pl.figure() l=pl.scatter(x,y,s=s) s = np.random.random(10)*1...
1
2016-06-30T19:24:10Z
[ "python", "matplotlib", "plot", "cartopy" ]
How to optimize changing a value in a Pandas Data Frame column
38,130,221
<p>I'm trying to find how much a stock will change from a given day to n days in the future. The only problem is that it takes about a minute to run this on 1000 lines of data and I have millions of lines. I think the 'lag' is caused by the line:</p> <p><code>stocks[0][i][string][line[index]] = adjPctChange(line[adj...
2
2016-06-30T17:57:32Z
38,130,777
<p>IIUC:</p> <p>I started off with this dataframe:</p> <pre><code>print df date open close adjclose 0 19980102 20.3835 20.4417 0.984507 1 19980105 20.5097 20.5679 1.034904 2 19980106 20.1408 20.0826 0.994047 3 19980107 20.1408 20.9950 0.982926 4 19980108 21.1115 20.0244 0.989441 </...
1
2016-06-30T18:32:14Z
[ "python", "pandas" ]
How to optimize changing a value in a Pandas Data Frame column
38,130,221
<p>I'm trying to find how much a stock will change from a given day to n days in the future. The only problem is that it takes about a minute to run this on 1000 lines of data and I have millions of lines. I think the 'lag' is caused by the line:</p> <p><code>stocks[0][i][string][line[index]] = adjPctChange(line[adj...
2
2016-06-30T17:57:32Z
38,131,025
<p>You shouldn't loop over a DataFrame; just do everything with array functions.</p> <p>Before:</p> <pre><code>In [30]: df Out[30]: date open close adjClose closeShift1 closeShift2 0 19980102 20.3835 20.4417 NaN NaN 0.984507 1 19980105 20.5097 20.5679 NaN 0.984507 ...
2
2016-06-30T18:46:42Z
[ "python", "pandas" ]
Python offset column value with previous record value if the record meets a condition
38,130,233
<p>I'm brand new to Python and am stuck on how to conditionally offset values. I've successfully been able to use the shift function when I just need to create a new column. However, this doesn't seem to work with a function.</p> <p>Original df:</p> <pre><code>BEGIN SPEED SPEED_END 322 28 0 341 0 ...
4
2016-06-30T17:57:53Z
38,130,336
<p>I will propose a two-step solution that will SHOCK you.</p> <pre><code>df['begin_temp'] = df.begin.shift(1) df['begin_shifted'] = df.ix[( df.SPEED== 0) | (df.SPEED_END== 0), 'begin_temp'] </code></pre> <p>and then</p> <pre><code>df.ix[df.begin_shifted.isnull(),'begin_shifted'] = df.ix[df.begin_shifted.isnull(),'...
0
2016-06-30T18:04:17Z
[ "python", "python-2.7", "pandas" ]
Python offset column value with previous record value if the record meets a condition
38,130,233
<p>I'm brand new to Python and am stuck on how to conditionally offset values. I've successfully been able to use the shift function when I just need to create a new column. However, this doesn't seem to work with a function.</p> <p>Original df:</p> <pre><code>BEGIN SPEED SPEED_END 322 28 0 341 0 ...
4
2016-06-30T17:57:53Z
38,130,513
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="nofollow"><code>mask</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.ffill.html" rel="nofollow"><code>ffill</code></a>:</p> <pre><code>begin_cond = (df['SPEED'] == 0) ...
5
2016-06-30T18:14:15Z
[ "python", "python-2.7", "pandas" ]
Finding and replacing element in Python
38,130,252
<p>I am new to the python programming and wanted to know how can I iterate over elements below then replace strings and make my data list look like below. Thank you in advance. </p> <pre><code>[{u 'name': u 'xxx', u 'data': [ [u 'last_00_10', x], [u 'last_11_20', x], [u 'last_21_30', x], ], u 'id': x }] </...
0
2016-06-30T17:58:52Z
38,130,500
<p>first, why you put 1 dict on a list? you'll put other dicts inside?, but I'll use your structure.. you can do something like this(I named your list L): and x = "" to work..(it's a non defined yet variable..</p> <pre><code>x = "" L = [ { u'name': u'xxx', u'data': [ ...
0
2016-06-30T18:13:36Z
[ "python", "list", "python-3.x" ]
Finding and replacing element in Python
38,130,252
<p>I am new to the python programming and wanted to know how can I iterate over elements below then replace strings and make my data list look like below. Thank you in advance. </p> <pre><code>[{u 'name': u 'xxx', u 'data': [ [u 'last_00_10', x], [u 'last_11_20', x], [u 'last_21_30', x], ], u 'id': x }] </...
0
2016-06-30T17:58:52Z
38,130,511
<p>You have a list which contains a dictionary. The 'data' key in the dictionary contains a list. You want to iterate over that list and replace the first item in the list with different text.</p> <pre><code>x = 1 your_data = [{u'name': u'xxx', u'data': [ [u'last_00_10', x], [u'last_11_20', x], [u'last_2...
2
2016-06-30T18:14:12Z
[ "python", "list", "python-3.x" ]
Finding and replacing element in Python
38,130,252
<p>I am new to the python programming and wanted to know how can I iterate over elements below then replace strings and make my data list look like below. Thank you in advance. </p> <pre><code>[{u 'name': u 'xxx', u 'data': [ [u 'last_00_10', x], [u 'last_11_20', x], [u 'last_21_30', x], ], u 'id': x }] </...
0
2016-06-30T17:58:52Z
38,130,537
<p>This almost give what you want:</p> <pre><code>import re x = 42 stuff = [{u'name': u'xxx', u'data': [ [u'last_00_10', x], [u'last_11_20', x], [u'last_21_30', x], ], u'id': x }] for row in stuff[0]['data']: row[0] = re.sub(r'last_(\d+)_(\d+)', ...
0
2016-06-30T18:15:52Z
[ "python", "list", "python-3.x" ]
Not show form data in url django
38,130,378
<p>I am creating a password reset form after a user is authenticated they are presented with the reset page where they can enter the username and new password. However once they have set this new data and click the submit button the data is shown in the url of the next page that is shown. How do I need to configure my ...
0
2016-06-30T18:06:37Z
38,130,449
<p>That's how a GET action works. You should be using POST for this anyway.</p>
1
2016-06-30T18:11:13Z
[ "python", "django", "passwords" ]
Multilabel classification validation using tensorflow
38,130,428
<p>I have a multi-class classification problem where I would like to evaluate a correct prediction as if the models best prediction matches any of the labels in the image it's correct (True) otherwise incorrect (False). As an example here is the line from the (expert) MNIST example I would like to change:</p> <pre><co...
0
2016-06-30T18:09:57Z
38,133,472
<p>So there are several ways of doing this, I think this is one of the most simple solutions:</p> <pre><code>prediction = tf.one_hot(tf.argmax(y_conv, 1), NUM_CLASSES) correct_prediction = tf.not_equal(tf.argmax(tf.mul(prediction, y_), 1), False) </code></pre> <p>Thanks to Kendall Weihe and Peter Hawkins comments</p>...
1
2016-06-30T21:21:41Z
[ "python", "tensorflow" ]
find random number using divide and conquer
38,130,466
<p>This is my first post to the community and I am still very new to coding. I was hoping to get some help on finding x in the following code using divide and conquer, it doesn't seem to work for me.</p> <pre><code>import random x= random.randint(1,1000) ##set range high = (1000) low = (1) while x != high: mid =...
0
2016-06-30T18:11:50Z
38,130,527
<pre><code>mid = round(high//2, 0) </code></pre> <p>This doesn't look right to me. Shouldn't mid be the average of high and low?</p> <pre><code>mid = (high+low)//2 </code></pre>
1
2016-06-30T18:15:18Z
[ "python" ]
Error while installing Airflow using pip in windows- Unable to find vcvarsall.bat
38,130,483
<p>I was trying to install Airflow in windows through command prompt using pip. </p> <p>The python is 3.4.2, pip included. I am getting the below error.</p> <p><code>distutils.errors.DistutilsError: Setup script exited with error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat).</code></p> <p>I ...
0
2016-06-30T18:12:41Z
38,182,957
<p>Instead of setting <code>VS100COMNTOOLS=%VS110COMNTOOLS%</code> in cmd, i did <code>SET VS100COMNTOOLS=C:\Program Files\Microsoft Visual Studio 11.0\Common7\Tools\</code> and it was picking correctly but again thrown another pile of errors as VS11 compiler is different and cannot compile Python 3.4 code properly.</p...
0
2016-07-04T10:54:18Z
[ "python", "visual-studio", "visual-c++", "pip", "setup.py" ]
Python: Keep the existing line if not add a new line in a file?
38,130,535
<p>I want to keep the existing line if the existing value is present, or else add the line to the file. I'm writing the script for nagios host file.</p> <p><strong>Host file:</strong></p> <pre><code>define host{ use hoststatus host_name linuxhost1 alias linuxh...
1
2016-06-30T18:15:47Z
38,130,715
<p>You are not resetting the severity flag to true after each host. This means that the first host sets the flag to false, and then the later if statement checking for the flag can never be entered. You need to add logic to check for the beginning of a new host file to reset logic like your severity flag.</p>
0
2016-06-30T18:28:06Z
[ "python", "nagios" ]
Python: Keep the existing line if not add a new line in a file?
38,130,535
<p>I want to keep the existing line if the existing value is present, or else add the line to the file. I'm writing the script for nagios host file.</p> <p><strong>Host file:</strong></p> <pre><code>define host{ use hoststatus host_name linuxhost1 alias linuxh...
1
2016-06-30T18:15:47Z
38,131,330
<p>Here's what I would do:</p> <ul> <li>Read the entire file</li> <li>split it into blocks</li> <li>split each block into lines</li> <li>add any needed data</li> <li>remake the entire block</li> <li>remake the entire file</li> </ul> <hr> <pre><code>from collections import OrderedDict default_sev = 4 default_VM = "X...
1
2016-06-30T19:03:56Z
[ "python", "nagios" ]
BeautifulSoup timing out on instantiation?
38,130,579
<p>I'm just doing some web scraping with BeautifulSoup and I'm running into a weird error. Code:</p> <pre><code>print "Running urllib2" g = urllib2.urlopen(link + "about", timeout=5) print "Finished urllib2" about_soup = BeautifulSoup(g, 'lxml') </code></pre> <p>Here's the output:</p> <pre><code>Running urllib2 Fini...
1
2016-06-30T18:18:32Z
38,130,600
<p>This is <code>urllib2</code> part that causing the timeout.</p> <p>The reason you see it is failing on the <code>BeautifulSoup</code> instantiation line is that <code>g</code>, <a href="https://docs.python.org/2/library/urllib.html#urllib.urlopen" rel="nofollow">the file-like object</a>, <em>is being read by <code>...
2
2016-06-30T18:20:02Z
[ "python", "web-scraping", "beautifulsoup" ]
Error when getting options of Select element in Python Selenium
38,130,625
<p>I am trying to list the possible options in this Select element.</p> <pre><code>&lt;select id="sl_coursePage" onchange="document.frm.submit();" name="sl_coursePage"&gt; &lt;option selected="selected" value="0"&gt;&lt;/option&gt; &lt;option value="1"&gt;&lt;/option&gt; &lt;option value="2"&gt;&lt;/option...
1
2016-06-30T18:21:18Z
38,130,700
<p>It looks like there is an <em>another element with the same name</em> which is not <code>select</code> and get matched by the "by name" locator. Improve the way you locating the element <em>explicitly</em> asking for <code>select</code> element with the desired name:</p> <pre><code>elem = driver.find_element_by_css...
0
2016-06-30T18:27:05Z
[ "python", "html", "selenium", "select", "drop-down-menu" ]
Error when getting options of Select element in Python Selenium
38,130,625
<p>I am trying to list the possible options in this Select element.</p> <pre><code>&lt;select id="sl_coursePage" onchange="document.frm.submit();" name="sl_coursePage"&gt; &lt;option selected="selected" value="0"&gt;&lt;/option&gt; &lt;option value="1"&gt;&lt;/option&gt; &lt;option value="2"&gt;&lt;/option...
1
2016-06-30T18:21:18Z
38,130,736
<p>You are trying to fetch the element by name</p> <pre><code>elem = driver.get_element_by_name('sl_coursePage') </code></pre> <p>Try to fetch it from id or a css selector instead, something like </p> <pre><code>elem =driver.findElement(By.id('sl_coursePage')) </code></pre>
0
2016-06-30T18:29:37Z
[ "python", "html", "selenium", "select", "drop-down-menu" ]
dictionary values as column labels in matplotlib
38,130,655
<p>I have the following <code>dict</code>:</p> <pre><code>packetsNeeded = { u'hydrogen': 150, u'helium': 143, u'lithium': 122} </code></pre> <p>I am using <strong>matplotlib</strong> to plot a bar graph for each of the keys and the values of the dictionary above. I have managed to ...
0
2016-06-30T18:23:44Z
38,131,400
<p>Maybe you've meant something along the lines of</p> <pre><code>for key, x in zip(packetsNeeded.keys(), range(len(packetsNeeded))): pplot.text(x, packetsNeeded[key], packetsNeeded[key]) </code></pre>
1
2016-06-30T19:07:14Z
[ "python", "dictionary", "matplotlib" ]
Python LDAP TLS error when ldap.OPT_X_TLS_REQUIRE_CERT set to ldap.OPT_X_TLS_NEVER
38,130,767
<p>When using python-ldap I am setting ldap.OPT_X_TLS_REQUIRE_CERT set to ldap.OPT_X_TLS_NEVER, but I still get a TLS error. I've tried ldap.set_option and the version you see below. Both produce the same error.</p> <pre><code>class adldap_connection: def __init__(self, configuration, secure): self.configu...
0
2016-06-30T18:31:15Z
38,136,255
<p>From the python-ldap mailing list:</p> <blockquote> <p>If you want to set connection-specific TLS parameters you must use</p> <p><code>self.ld.set_option(ldap.OPT_X_TLS_NEWCTX, 0)</code></p> <p>as last call to setoption() with TLS parameter.</p> </blockquote> <p>I ended up with this, which works for bo...
0
2016-07-01T02:49:01Z
[ "python", "ssl", "ldap" ]
Python: absolute path issue
38,130,778
<p>I have several files stored in a folder called controlFiles. The path to this folder is Users/Desktop/myproject/controlFiles.</p> <p>I am attempting to run a subprocess command in my python script with the following code:</p> <pre><code>def codeml(codeml_location, control_location): runPath = codeml_location +...
2
2016-06-30T18:32:15Z
38,130,871
<p><code>os.listdir</code> does list the filenames in the directory <code>control_location</code> not in the current working path. So you have to join the filename with the path <code>control_location</code>:</p> <pre><code>for file in os.listdir(control_location): ctlPath = os.path.abspath(os.path.join(control_lo...
3
2016-06-30T18:37:43Z
[ "python", "subprocess", "absolute-path" ]
Python: absolute path issue
38,130,778
<p>I have several files stored in a folder called controlFiles. The path to this folder is Users/Desktop/myproject/controlFiles.</p> <p>I am attempting to run a subprocess command in my python script with the following code:</p> <pre><code>def codeml(codeml_location, control_location): runPath = codeml_location +...
2
2016-06-30T18:32:15Z
38,130,924
<p>Set the cwd in the subprocess:</p> <pre><code> for file in os.listdir(control_location): subprocess.call([runPath, file], cwd=control_location) </code></pre> <p><em>listdir</em> is just returning the basename, not the full path. Setting the cwd to where the files are will allow you to just pass file. If <em>l...
1
2016-06-30T18:40:37Z
[ "python", "subprocess", "absolute-path" ]
Python: absolute path issue
38,130,778
<p>I have several files stored in a folder called controlFiles. The path to this folder is Users/Desktop/myproject/controlFiles.</p> <p>I am attempting to run a subprocess command in my python script with the following code:</p> <pre><code>def codeml(codeml_location, control_location): runPath = codeml_location +...
2
2016-06-30T18:32:15Z
38,131,603
<p>I managed to resolve this using:</p> <pre><code>for file in os.listdir(control_location): filepath = os.path.dirname(os.path.realpath(file)) subprocess.call([runPath, filepath]) </code></pre>
0
2016-06-30T19:20:28Z
[ "python", "subprocess", "absolute-path" ]
Python: absolute path issue
38,130,778
<p>I have several files stored in a folder called controlFiles. The path to this folder is Users/Desktop/myproject/controlFiles.</p> <p>I am attempting to run a subprocess command in my python script with the following code:</p> <pre><code>def codeml(codeml_location, control_location): runPath = codeml_location +...
2
2016-06-30T18:32:15Z
38,148,165
<blockquote> <p>The script's function is to run a command line tool called codeml, with the first argument being the location of the codeml executable, and the second being a folder of control files that codeml uses. </p> </blockquote> <p>if <code>control_location</code> is the folder of control files that <code>cod...
0
2016-07-01T14:39:54Z
[ "python", "subprocess", "absolute-path" ]
conda version of pandas mismatch
38,130,808
<p>I use the Anaconda suite for python. I do</p> <p><code>import pandas as pd</code></p> <p>and then</p> <pre><code>pd.show_versions() </code></pre> <p>it shows</p> <blockquote> <p>pandas: 0.17.1</p> </blockquote> <p>but if I do </p> <pre><code>!conda list </code></pre> <p>it shows</p> <blockquote> <p>pand...
1
2016-06-30T18:34:11Z
38,306,857
<p>Eventually, fiddling with all the above answers and looking at other stackoverflow questions, I figured that 'pip-installed-packages' would not go in the same directory as 'conda-installed-packages'. Typically, pip-instlled go to C:\Anaconda3\Lib\site-packages while conda-installed go to C:\Anaconda3\pkgs.</p> <p>I...
1
2016-07-11T12:24:39Z
[ "python", "pandas", "anaconda" ]
Can't connect via python to rdp
38,130,811
<p>I want to create python script that connects to a RDP and execute cmd , but i have some problems:</p> <pre><code>ImportError: No module named win32com.client </code></pre> <p>I already installed <code>WMI</code> but i can't find any solution to install win32com.client module in linux , here is my code</p> <pre><c...
1
2016-06-30T18:34:17Z
38,150,127
<p>I'd recommend trying <a href="https://github.com/citronneur/rdpy" rel="nofollow">rdpy</a>, since it's a pure Python implementation of the RDP protocol.</p> <hr> <p>Here's a sample from their README:</p> <h3>Simple RDP Client</h3> <pre><code>from rdpy.protocol.rdp import rdp class MyRDPFactory(rdp.ClientFactory)...
0
2016-07-01T16:28:48Z
[ "python", "linux", "wmi", "rdp" ]
what's the easiest way to load array data from a file in Python?
38,130,852
<p>I know Matlab has some nice syntax where you can put into a file array definitions, like <code>A = [[1,2,3],...</code>, and then you can import that file and all those definitions are read automatically. I would like to do something similar in Python. Basically I'm looking for the easiest way to read tabular data fr...
1
2016-06-30T18:36:51Z
38,130,967
<p>file <strong>test1.py</strong>:</p> <pre><code>#!/usr/bin/python a=[1,2,3,4,5,6] </code></pre> <p>file <strong>test.py</strong>:</p> <pre><code>#!/usr/bin/python import test1 print test1.a </code></pre> <p>Now if you run test.py:</p> <pre><code>$ ./test.py [1, 2, 3, 4, 5, 6] </code></pre>
2
2016-06-30T18:42:50Z
[ "python", "file", "numpy", "io" ]
what's the easiest way to load array data from a file in Python?
38,130,852
<p>I know Matlab has some nice syntax where you can put into a file array definitions, like <code>A = [[1,2,3],...</code>, and then you can import that file and all those definitions are read automatically. I would like to do something similar in Python. Basically I'm looking for the easiest way to read tabular data fr...
1
2016-06-30T18:36:51Z
38,131,040
<p>What Jahid said below works well if you want to put your data in Python modules. </p> <p>If on the other hand you'd rather put your data in a separate file, e.g. a text file, and then read it in a script, you may want to use <code>numpy.loadtxt</code> (it's designed to automatically read matrix-like files into nump...
1
2016-06-30T18:47:29Z
[ "python", "file", "numpy", "io" ]
what's the easiest way to load array data from a file in Python?
38,130,852
<p>I know Matlab has some nice syntax where you can put into a file array definitions, like <code>A = [[1,2,3],...</code>, and then you can import that file and all those definitions are read automatically. I would like to do something similar in Python. Basically I'm looking for the easiest way to read tabular data fr...
1
2016-06-30T18:36:51Z
38,149,183
<p>What you probably want is to put your data in the <a href="https://en.wikipedia.org/wiki/YAML" rel="nofollow">yaml</a> file format. It is a text data format whose structure is based on higher-level scripting languages like Python. You can put multiple 2D arrays of arbitrary types in it. However, since it is just ...
0
2016-07-01T15:35:20Z
[ "python", "file", "numpy", "io" ]
In Django, remove options in a choice-field based on other fields in a model
38,130,853
<p>I'm new to Django and any help is appreciated, How can I restrict the choice option in one field based on a previous field. For example, if I select 'dog' for animal, I want to remove 'chocolate' from the FOOD_CHOICE, because I love dogs. Thanks!!! </p> <pre><code>ANIMAL_CHOICE = ( ('a','cat'), ('b','dog'...
1
2016-06-30T18:36:51Z
38,133,108
<p>you will do that from django forms, when youre cleaning the form, or you also can manipulate via javascript to remove that option from frontend</p>
0
2016-06-30T20:56:24Z
[ "python", "django", "dynamic", "django-models", "choicefield" ]
In Django, remove options in a choice-field based on other fields in a model
38,130,853
<p>I'm new to Django and any help is appreciated, How can I restrict the choice option in one field based on a previous field. For example, if I select 'dog' for animal, I want to remove 'chocolate' from the FOOD_CHOICE, because I love dogs. Thanks!!! </p> <pre><code>ANIMAL_CHOICE = ( ('a','cat'), ('b','dog'...
1
2016-06-30T18:36:51Z
38,133,276
<p>You can't do this unless you write a set of rules, which is really complicated to maintain.<br> The best solution here is use a separate model for food, and add the foreign key to the animal model:</p> <pre><code>ANIMAL_CHOICE = ( ('a','cat'), ('b','dog'), ('c','fish'), ) FOOD_CHOICE = ( ('a', ...
0
2016-06-30T21:06:10Z
[ "python", "django", "dynamic", "django-models", "choicefield" ]
In Python, is it possible to expose modules from subpackages at package level?
38,130,880
<p>I have the following conundrum. I'm trying to expose some modules from a subpackage of a package at the parent package level.</p> <p>The folder structure is the essentially like this:</p> <pre><code>script.py package/ __init__.py module1.py subpackage/ __init__.py submodule1.py ...
2
2016-06-30T18:38:12Z
38,130,998
<p>For your purpose, python modules are just namespaces. That is, everything in the globals of a module can be imported and used as <code>module.thingy</code>. You may have noticed that in many modules, you also find some builtins. For example, <code>logging.os</code> is just the regular <code>os</code> module.</p> <p...
4
2016-06-30T18:44:46Z
[ "python", "python-2.7", "python-import", "python-packaging" ]
In Python, is it possible to expose modules from subpackages at package level?
38,130,880
<p>I have the following conundrum. I'm trying to expose some modules from a subpackage of a package at the parent package level.</p> <p>The folder structure is the essentially like this:</p> <pre><code>script.py package/ __init__.py module1.py subpackage/ __init__.py submodule1.py ...
2
2016-06-30T18:38:12Z
38,152,738
<p>Yes It's possible.<br> Let's see what happens step by step; </p> <ol> <li>When you do <code>from package.submodule1 import foo</code>, <code>sys.modules</code> is checked if it has <code>package</code>. </li> <li>If not found <code>package/__init__.py</code> is run and loaded </li> <li>Again <code>sys.modules</c...
1
2016-07-01T19:27:54Z
[ "python", "python-2.7", "python-import", "python-packaging" ]
Extracting specific fields from python object
38,130,910
<p>This is a sample python object that I am working with. </p> <pre><code>class DataObj(object): def __init__(self, cvid, cvname, address, get_info): self.cvid = cvid self.cvname = cvname self.address = address self.prof = PROF("Honda", "Jason Jones") class PROF(object): def __init__...
1
2016-06-30T18:39:52Z
38,131,533
<p>All I did was simply add <code>__iter__</code> which basically says hey, you can iterate over me, if you cast the object to an iterabale container type. </p> <pre><code>class Proj(object): def __init__(self, projectname, projecttype): self.projectname = projectname self.projecttype = projectty...
2
2016-06-30T19:15:30Z
[ "python" ]
Extracting specific fields from python object
38,130,910
<p>This is a sample python object that I am working with. </p> <pre><code>class DataObj(object): def __init__(self, cvid, cvname, address, get_info): self.cvid = cvid self.cvname = cvname self.address = address self.prof = PROF("Honda", "Jason Jones") class PROF(object): def __init__...
1
2016-06-30T18:39:52Z
38,136,897
<p>Between <code>__getattr__</code> and <code>operator.attrgetter</code>, you could make this work fairly easily:</p> <pre><code>class DataObj(object): def __init__(self, cvid, cvname, address, get_info): self.cvid = cvid self.cvname = cvname self.address = address self.prof = PROF...
1
2016-07-01T04:08:14Z
[ "python" ]
What is the difference between StringIO and ByteIO?
38,130,962
<p>What is the difference between StringIO and ByteIO? And what sorts of use cases would you use each one for?</p>
0
2016-06-30T18:42:41Z
38,131,236
<p><code>StringIO</code> is for text. You use it when you have text in memory that you want to treat as coming from or going to a file. <code>BytesIO</code> is for bytes. It's used in similar contexts as <code>StringIO</code>, except with bytes instead of text.</p>
1
2016-06-30T18:58:29Z
[ "python" ]
What is the difference between StringIO and ByteIO?
38,130,962
<p>What is the difference between StringIO and ByteIO? And what sorts of use cases would you use each one for?</p>
0
2016-06-30T18:42:41Z
38,131,261
<p>As the name says, <code>StringIO</code> works with <code>str</code> data, while <code>BytesIO</code> works with <code>bytes</code> data. <code>bytes</code> are raw data, e.g. 65, while <code>str</code> interprets this data, e.g. using the ASCII encoding 65 is the letter 'A'.</p> <p><code>bytes</code> data is prefer...
2
2016-06-30T18:59:49Z
[ "python" ]
How to remove the legend in a seaborn stripplot? AttributeError: Unknown property legend
38,131,062
<p>The seaborn stripplot has a function which allows <code>hue</code>. </p> <p>Using the example from <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.stripplot.html" rel="nofollow">https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.stripplot.html</a></p> <pre><code>import seabo...
2
2016-06-30T18:48:27Z
38,136,752
<p>Use <code>ax.legend_.remove()</code> like here:</p> <pre><code>import seaborn as sns import matplotlib.pylab as plt sns.set_style("whitegrid") tips = sns.load_dataset("tips") ax = sns.stripplot(x="sex", y="total_bill", hue="day", data=tips, jitter=True) # remove legend from axis 'ax' ax.legend_.remove() plt.show(...
3
2016-07-01T03:49:14Z
[ "python", "matplotlib", "legend", "seaborn" ]
How can i set a default datetime value in eve?
38,131,089
<p>For example, for a key </p> <p><code>'joinDate' : {'type' : 'datetime'}</code></p> <p>How could i make it automatically get posted with the current date without being explicitly give in POST method.</p>
1
2016-06-30T18:49:49Z
38,131,121
<p>You can use the Python <code>datetime.datetime.now()</code> method like so:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.datetime.now() datetime.datetime(2016, 6, 30, 14, 51, 25, 977000) </code></pre>
-1
2016-06-30T18:51:58Z
[ "python", "eve" ]
How can i set a default datetime value in eve?
38,131,089
<p>For example, for a key </p> <p><code>'joinDate' : {'type' : 'datetime'}</code></p> <p>How could i make it automatically get posted with the current date without being explicitly give in POST method.</p>
1
2016-06-30T18:49:49Z
38,132,248
<p>You can set the <code>default</code> value for the <code>joinDate</code> field on the schema definition, like so:</p> <pre><code>from datetime import datetime your_schema = { 'joinDate': { 'type': 'datetime', 'default': datetime.utcnow() }, # rest of schema } </code></pre> <p>In the ex...
1
2016-06-30T20:01:00Z
[ "python", "eve" ]
how to retrieve text from anchor href attribute in python
38,131,115
<p>Let's say I have a link like this:</p> <pre><code>link = '&lt;a href="some text"&gt;...&lt;/a&gt;' </code></pre> <p>Is there any way I can retrieve the text from anchor href attribute so the result will be something like this:</p> <pre><code>hrefText = 'some text' </code></pre> <p>And thank you in advance</p>
1
2016-06-30T18:51:45Z
38,131,196
<p>This is a way:</p> <pre><code>import re print re.search('(?&lt;=&lt;a href=")[^"]+',link).group(0) </code></pre> <p>Or,</p> <pre><code>print re.search(r'&lt;a\s+href="([^"]+)',link).group(1) </code></pre>
2
2016-06-30T18:56:11Z
[ "python", "href" ]
how to retrieve text from anchor href attribute in python
38,131,115
<p>Let's say I have a link like this:</p> <pre><code>link = '&lt;a href="some text"&gt;...&lt;/a&gt;' </code></pre> <p>Is there any way I can retrieve the text from anchor href attribute so the result will be something like this:</p> <pre><code>hrefText = 'some text' </code></pre> <p>And thank you in advance</p>
1
2016-06-30T18:51:45Z
38,131,239
<p>Although you could split or use a regular expression, for a more <em>modular</em> and <em>powerful</em> tool set, you could use </p> <blockquote> <p>BeautifulSoup: <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/</a></p> </blockquote> <p>Sampl...
2
2016-06-30T18:58:42Z
[ "python", "href" ]
how to retrieve text from anchor href attribute in python
38,131,115
<p>Let's say I have a link like this:</p> <pre><code>link = '&lt;a href="some text"&gt;...&lt;/a&gt;' </code></pre> <p>Is there any way I can retrieve the text from anchor href attribute so the result will be something like this:</p> <pre><code>hrefText = 'some text' </code></pre> <p>And thank you in advance</p>
1
2016-06-30T18:51:45Z
38,131,521
<p>You can use bs4 and requests lib for this.</p> <pre><code>import requests from bs4 import BeautifulSoup url = 'https://examplesite.com/' source = requests.get(url) text = source.text soup = BeautifulSoup(text, "html.parser") for link in soup.findAll('a', {}): href = '' + link.get('href') title = link.string ...
1
2016-06-30T19:14:50Z
[ "python", "href" ]
Regular expression to match anything between combination of quotes
38,131,204
<p>[<em>Follow up from my old <a href="http://stackoverflow.com/questions/37928695/regular-expression-to-match-anything-between-two-symbols">question</a> with better description and links</em>]</p> <p>Trying to match any character (including newlines, tab characters, whitespaces, etc.) between two symbols, including t...
2
2016-06-30T18:56:44Z
38,132,206
<p>You're probably missing flags to make <code>.</code> match newline also</p> <pre><code>re.finditer(tok_regex, code, flags = re.DOTALL) </code></pre> <p>In this case the output is</p> <pre><code>('BOTH', '"""\n This class holds lhghdhdf hgh dhghd hdfh ghd fh.\n """') ('COM', '# sdasda fad fhs ghf dfh\n ...
1
2016-06-30T19:58:43Z
[ "python", "regex", "python-3.x", "quotes" ]
Logging and email not working for Django for 500
38,131,255
<p>I can't get logging to work in my Django web app. </p> <p>My settings file looks like this:</p> <pre><code>EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 465 EMAIL_HOST_USER = "paulhtremblay@gmail.com" EMAIL_HOST_PASSWORD = "password" EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = "paulhtremblay@gmail.com" SERVER_EMAIL = '...
3
2016-06-30T18:59:34Z
39,401,935
<p>This is my working setup. I have not added a <code>console logger</code>, as I am using it only to production. The inspiration came from the relevant <a href="https://docs.djangoproject.com/en/dev/topics/logging/#examples" rel="nofollow">Logging Examples</a> of Django docs.</p> <p>Here are my email and logging sett...
1
2016-09-09T00:11:46Z
[ "python", "django", "email" ]
Pandas: add column with the most recent values
38,131,287
<p>I have two pandas dataframes, both index with datetime entries. The <code>df1</code> has non-unique time indices, whereas <code>df2</code> has unique ones. I would like to add a column <code>df2.a</code> to <code>df1</code> in the following way: for every row in <code>df1</code> with timestamp <code>ts</code>, <code...
2
2016-06-30T19:01:24Z
38,131,683
<p>You are describing an <a href="http://stackoverflow.com/questions/12322289/kdb-like-asof-join-for-timeseries-data-in-pandas">asof-join</a>, which was just <a href="http://pandas.pydata.org/pandas-docs/version/0.19.0/whatsnew.html#whatsnew-0190-enhancements-asof-merge" rel="nofollow">released in pandas 0.19</a>.</p> ...
2
2016-06-30T19:25:44Z
[ "python", "datetime", "pandas" ]
Pandas: add column with the most recent values
38,131,287
<p>I have two pandas dataframes, both index with datetime entries. The <code>df1</code> has non-unique time indices, whereas <code>df2</code> has unique ones. I would like to add a column <code>df2.a</code> to <code>df1</code> in the following way: for every row in <code>df1</code> with timestamp <code>ts</code>, <code...
2
2016-06-30T19:01:24Z
38,131,733
<p>apply to rows of df1, reindex on df2 with ffill.</p> <pre><code>df1['df2.a'] = df1.apply(lambda x: pd.Series(df2.a.reindex([x.name]).ffill().values), axis=1) </code></pre>
2
2016-06-30T19:28:36Z
[ "python", "datetime", "pandas" ]
Python code to print a number's 10 times tables
38,131,307
<p>I am really new to python and have not been doing it long. I have tried running this code but it won't work- 'Invalid Syntax' comes up each time. Can anyone tell me where I went wrong? Thanks. </p> <pre><code>n=int(input('Enter a number to view it\'s 10 times tables:')) print(n, end=' ') print('x 1 =' n) print(n, e...
-1
2016-06-30T19:02:26Z
38,131,389
<p>You have a <code>SyntaxError</code> in each print statement. You want to print multiple items, so add a comma between each item when using <code>print</code>:</p> <pre><code>n=int(input('Enter a number to view it\'s 10 times tables:')) print(n, end=' ') print('x 1 =', n) print(n, end=' ') print('x 2 =', 2*n) print(...
1
2016-06-30T19:06:46Z
[ "python" ]
Python code to print a number's 10 times tables
38,131,307
<p>I am really new to python and have not been doing it long. I have tried running this code but it won't work- 'Invalid Syntax' comes up each time. Can anyone tell me where I went wrong? Thanks. </p> <pre><code>n=int(input('Enter a number to view it\'s 10 times tables:')) print(n, end=' ') print('x 1 =' n) print(n, e...
-1
2016-06-30T19:02:26Z
38,131,397
<p>You should check up on <a href="https://pyformat.info/" rel="nofollow">string formatting</a> in Python. The <code>print</code> statement (or function in Python 3) will print properly formatted strings. But as is, your strings are not properly formatted and hence not <em>printable</em>, and will raise a SyntaxError.<...
0
2016-06-30T19:07:04Z
[ "python" ]
Python code to print a number's 10 times tables
38,131,307
<p>I am really new to python and have not been doing it long. I have tried running this code but it won't work- 'Invalid Syntax' comes up each time. Can anyone tell me where I went wrong? Thanks. </p> <pre><code>n=int(input('Enter a number to view it\'s 10 times tables:')) print(n, end=' ') print('x 1 =' n) print(n, e...
-1
2016-06-30T19:02:26Z
38,131,415
<p>I would do it like this:</p> <pre><code>n = int(input("Enter a number to view it's 10 times tables:")) for x in range(11): print("{} x {} = {}".format(n, x, n*x)) </code></pre>
1
2016-06-30T19:08:13Z
[ "python" ]
How to use python beautifulsoup to get image description from html?
38,131,323
<p>I did not find this answer in other location, so seek your's help: I had a python code try to access <a href="http://news.yahoo.com/rss/entertainment" rel="nofollow">http://news.yahoo.com/rss/entertainment</a> To get the title and descriptions. but some is in image alt format: This is my code:</p> <pre><code> for ...
1
2016-06-30T19:03:37Z
38,132,332
<p>So you want all the text from the description and the <em>title</em> from any <em>img</em> tags, you can find all the decription tags then turn the description.text in a <em>BeautifulSoup</em> object then look for the img in that try to pull either the title or alt attribute, to find the matching title find the prev...
0
2016-06-30T20:06:11Z
[ "python", "html", "tags", "beautifulsoup" ]
How to increment paragraph object in word document using python-docx?
38,131,483
<p>I'm searching word documents to get descriptions of things that are written in the docs. However, these docs are not all formatted the same. But one thing that is consistent is the text block I want is always after the title 'Description'. So I'd search for 'Description' then hope to get the text of the next paragra...
2
2016-06-30T19:12:49Z
38,133,063
<p>If you're looking to extract text and search that way, <a href="https://github.com/ankushshah89/python-docx2txt" rel="nofollow">python-docx2txt</a> will give you less headaches. It was adapted from python-docx.</p>
1
2016-06-30T20:53:24Z
[ "python", "python-docx" ]
How to increment paragraph object in word document using python-docx?
38,131,483
<p>I'm searching word documents to get descriptions of things that are written in the docs. However, these docs are not all formatted the same. But one thing that is consistent is the text block I want is always after the title 'Description'. So I'd search for 'Description' then hope to get the text of the next paragra...
2
2016-06-30T19:12:49Z
38,134,387
<p>A simple approach would be:</p> <pre><code>paragraphs = list(doc.paragraphs) for i in range(len(paragraphs)): paragraph = paragraphs[i] if 'Description' in paragraph.text: print(paragraphs[i+1].text) </code></pre> <p>If you know for sure that the description label appears in a paragraph with <code...
2
2016-06-30T22:41:03Z
[ "python", "python-docx" ]
Start subthread with arbitrary function including parameters
38,131,504
<p>I would like to build a function, which checks if a subthread is already running and if not, start a subthread with any function and paramter given. As multithreading tool I use this post: <a href="http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python">Is there any way to kill a Threa...
0
2016-06-30T19:14:03Z
38,131,680
<p>Your problem is this line:</p> <pre><code>self.__Thread = ThreadEx(target=function(),args=(self,)) </code></pre> <p>Notice the parentheses behind function. It means not the function is assigned to target, but the result of <em>calling</em> said function. So, the function is executed, it does its printing etc., <em...
0
2016-06-30T19:25:31Z
[ "python", "multithreading", "parameter-passing" ]
SQLAlchemy look up and merge object before adding
38,131,512
<p>I have an object which has foreign keys to another object. Let's call the first object <code>A</code> and the second object <code>B</code>. <code>A</code> can be represented as <code>(integer id, integer b_id, integer some_data)</code> and <code>B</code> can be represented as <code>(integer id, integer datum_one, in...
0
2016-06-30T19:14:28Z
38,210,558
<p>I think you should just handle this yourself before inserting your object to the database. From the docs... <a href="http://docs.sqlalchemy.org/en/latest/core/events.html" rel="nofollow">http://docs.sqlalchemy.org/en/latest/core/events.html</a></p> <pre><code>from sqlalchemy import event # standard decorator style...
1
2016-07-05T18:48:28Z
[ "python", "sql", "sqlite", "sqlalchemy" ]
Django filter with OR condition using dict argument
38,131,563
<p>I have a function on my Django app where I perform some Queryset actions and set it's result to Memcache. Since it is a function it has to be of general usage. So in order to make it reusable I pass a dict as parameter for <code>filter</code> and <code>exclude</code> actions. This is the function:</p> <pre><code>de...
3
2016-06-30T19:17:40Z
38,132,037
<p>You can restructure your dictionary into a list of single key-value dictionaries and use unpacking on each <code>dict</code> inside the <code>Q</code> expression like so:</p> <pre><code>from functools import reduce import operator from django.db.models import Q # your dict is my_filter q = model.objects.filter(re...
3
2016-06-30T19:49:49Z
[ "python", "django" ]
Django filter with OR condition using dict argument
38,131,563
<p>I have a function on my Django app where I perform some Queryset actions and set it's result to Memcache. Since it is a function it has to be of general usage. So in order to make it reusable I pass a dict as parameter for <code>filter</code> and <code>exclude</code> actions. This is the function:</p> <pre><code>de...
3
2016-06-30T19:17:40Z
38,132,059
<p>You can use the bitwise <code>|</code> operator.</p> <pre><code>my_filter = Q() # Or the Q object with the ones remaining in the list my_or_filters = {'some_field__gte':3.5, 'another_field':'Dick Perch'} for item in my_or_filters: my_filter |= Q(**{item:my_or_filters[item]}) model.objects.filter(my_filter) #...
1
2016-06-30T19:50:47Z
[ "python", "django" ]
Django filter with OR condition using dict argument
38,131,563
<p>I have a function on my Django app where I perform some Queryset actions and set it's result to Memcache. Since it is a function it has to be of general usage. So in order to make it reusable I pass a dict as parameter for <code>filter</code> and <code>exclude</code> actions. This is the function:</p> <pre><code>de...
3
2016-06-30T19:17:40Z
38,134,219
<p>Based on @Moses Koledoye's answer I could solve the issue. This is how my function looks like now:</p> <pre><code> cached_query(key, model, my_filter=None, or_filter={}, exclude=None, order_by=None, sliced=50): """ :param key: string used as key reference to store on Memcached :param model: model refere...
0
2016-06-30T22:25:52Z
[ "python", "django" ]
No module name _tkinter windows python 2.7
38,131,592
<p>I have been searching for hours reading over various suggestions for this topic so please do not downvote me too fast. The closest thing i could find to a solution is here: <a href="http://stackoverflow.com/questions/5459444/tkinter-python-may-not-be-configured-for-tk">Tkinter: &quot;Python may not be configured for...
0
2016-06-30T19:19:26Z
38,131,885
<p>Your title says python2.7 but your error message says python2.5 ... I'm guessing you are accidentally running the wrong python installation. </p>
0
2016-06-30T19:40:31Z
[ "python", "windows", "python-2.7", "tkinter" ]
Redis: the best way to get all hash values
38,131,610
<p>I currently store about 50k hashes in my Redis table, every single one has 5 key/value pairs. Once a day I run a batch job which updates hash values, including setting some key values to the value of the other key in a hash.</p> <p>Here is my python code which iterates through keys and sets old_code to new_code if ...
5
2016-06-30T19:21:05Z
38,150,344
<p>There is no command like that, redis hashes work within the hash, so HMGET work inside one hash and give all the fields in that hash. <strong>There is no way to access all the fields in multiple hashes at ones</strong>.</p> <p>There are 2 options</p> <ol> <li>Using pipeline</li> <li>Using LUA</li> </ol> <p>Howeve...
0
2016-07-01T16:42:59Z
[ "python", "database", "hash", "redis" ]
Redis: the best way to get all hash values
38,131,610
<p>I currently store about 50k hashes in my Redis table, every single one has 5 key/value pairs. Once a day I run a batch job which updates hash values, including setting some key values to the value of the other key in a hash.</p> <p>Here is my python code which iterates through keys and sets old_code to new_code if ...
5
2016-06-30T19:21:05Z
38,204,696
<p>How about an unpside down change. Transpose the way you store the data. </p> <p>Instead of having <strong>50k hashes each with 5 values</strong>. Have <strong>5 hashes each with 50k values</strong>. </p> <p>For example your hash depends on eventid and you store new_code, old_code and other stuffs inside that hash<...
5
2016-07-05T13:26:20Z
[ "python", "database", "hash", "redis" ]
Redis: the best way to get all hash values
38,131,610
<p>I currently store about 50k hashes in my Redis table, every single one has 5 key/value pairs. Once a day I run a batch job which updates hash values, including setting some key values to the value of the other key in a hash.</p> <p>Here is my python code which iterates through keys and sets old_code to new_code if ...
5
2016-06-30T19:21:05Z
38,217,259
<p>For your first problem, using a Lua script will definitely improve performance. This is untested, but something like:</p> <pre><code>update_hash = r.register_script(""" local key = KEYS[1] local new_code = ARGS[1] local old_code = redis.call("HGET", key, "new_code") if old_code then redis.c...
2
2016-07-06T06:06:30Z
[ "python", "database", "hash", "redis" ]
Not able to build syntaxNet source?
38,131,612
<p>I did everything given in their <a href="https://github.com/tensorflow/models/tree/master/syntaxnet#installation" rel="nofollow">documentation</a> but I'm getting this error again and again....I tried googling and finding if anyone got the same error but nopes, didn't work out. Heres the command --</p> <pre><code>b...
0
2016-06-30T19:21:09Z
38,132,099
<p>Finally solved it, it was related to the <code>bazel</code> version. </p> <p>I had installed it before, so the version was 0.1.5. But in the docs, its written supported ones are 0.2 - 0.2.2b. I tried to upgrade it using brew but it didn't work. </p> <p>So I tried to directly install it using the 0.2.2b installer a...
0
2016-06-30T19:52:42Z
[ "python", "tensorflow", "syntaxnet" ]
Not able to build syntaxNet source?
38,131,612
<p>I did everything given in their <a href="https://github.com/tensorflow/models/tree/master/syntaxnet#installation" rel="nofollow">documentation</a> but I'm getting this error again and again....I tried googling and finding if anyone got the same error but nopes, didn't work out. Heres the command --</p> <pre><code>b...
0
2016-06-30T19:21:09Z
38,209,244
<p>here is a very useful script for installation on ubuntu-14.04 <a href="https://github.com/JoshData/models/blob/b72274d38f169f77e6a15e54834f463f627dc82a/syntaxnet/build/ubuntu-14.04_x64.sh" rel="nofollow">https://github.com/JoshData/models/blob/b72274d38f169f77e6a15e54834f463f627dc82a/syntaxnet/build/ubuntu-14.04_x64...
2
2016-07-05T17:25:01Z
[ "python", "tensorflow", "syntaxnet" ]
How to wait for a thread to finish before continuing
38,131,646
<p>I need to run a function in another thread, and get the return value of that function to save it to a variable in the main thread. Basically, my code calls the function, which communicates with a balance through a serial port, waits for and gets the response, parses the response, and returns the response as a float....
0
2016-06-30T19:23:22Z
38,131,729
<p>You can use <code>join()</code>. This will make the program to wait until the thread finish, and then will move next to show the result.</p>
2
2016-06-30T19:28:21Z
[ "python", "multithreading", "pyqt4", "multiprocess" ]
Barplot/line plot on same plot, but different axis and line plot in front of barplot
38,131,697
<p>I'm using pandas to plot some data. </p> <p>If I plot this:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'a': [100, 200, 150, 175], 'b': [430, 30, 20, 10]}) fig, ax1 = plt.subplots(figsize=(15, 10)) df['b'].plot(kind=...
2
2016-06-30T19:26:45Z
38,132,706
<p>you could put line on primary axis.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({'a': [100, 200, 150, 175], 'b': [430, 30, 20, 10]}) fig, ax1 = plt.subplots(figsize=(15, 10)) df['b'].plot(kind='bar', color='y') df['a'].plot(kind='line', marker='d', second...
1
2016-06-30T20:30:25Z
[ "python", "pandas", "matplotlib" ]
pocketsphinx installation error on windows
38,131,701
<p>I tried installing the latest pocketsphinx 0.1.0. For that I downloaded swigwin 3.0.10 unzipped it and added to the system variable "path" I also installed git which was mentioned as the requirement for installing pocketsphinx on "<a href="https://pypi.python.org/pypi/pocketsphinx" rel="nofollow">https://pypi.python...
1
2016-06-30T19:27:00Z
38,208,362
<p>This is a bug in pocketsphinx, it does not support compiler you have. You have few choices:</p> <ul> <li>Update the compiler to more recent version</li> <li>Update pocketsphinx, I've just fixed the code, you need to clone <a href="http://github.com/cmusphinx/pocketsphinx" rel="nofollow">pocketsphinx</a> and <a href...
2
2016-07-05T16:29:07Z
[ "python", "pocketsphinx" ]
Not able to write to file
38,131,723
<p>I am trying to make a string write in a text file, but only if that string is already not in the text file.</p> <pre><code>b = raw_input("IP Adress: ") os.system('cls') if(b == '0'): a = 0 c = raw_input("Player Name: ") if(c == '0'): a = 0 if(a != 0): line = "Text\IPs\{}.txt".format(b) output_filee ...
-3
2016-06-30T19:28:05Z
38,131,833
<p>The logic in your <code>for</code> loop is wrong. It's not checking whether the string is missing from the file, it's checking whether there's some line in the file that doesn't match the string. If the file is empty, the loop won't do anything, so it never sets <code>found = 1</code>.</p> <p>You need to invert the...
1
2016-06-30T19:36:47Z
[ "python", "file" ]
Not able to write to file
38,131,723
<p>I am trying to make a string write in a text file, but only if that string is already not in the text file.</p> <pre><code>b = raw_input("IP Adress: ") os.system('cls') if(b == '0'): a = 0 c = raw_input("Player Name: ") if(c == '0'): a = 0 if(a != 0): line = "Text\IPs\{}.txt".format(b) output_filee ...
-3
2016-06-30T19:28:05Z
38,132,169
<p>There are a couple of things I have noticed with your snippet.</p> <p>First of all, you are using the <code>os</code> module, but it isn't imported.</p> <p>Second, are you wanting this to only work on windows? Because os.system calls are at best 'meh', until you want to be cross platform and then they are almost w...
0
2016-06-30T19:56:36Z
[ "python", "file" ]
Not able to write to file
38,131,723
<p>I am trying to make a string write in a text file, but only if that string is already not in the text file.</p> <pre><code>b = raw_input("IP Adress: ") os.system('cls') if(b == '0'): a = 0 c = raw_input("Player Name: ") if(c == '0'): a = 0 if(a != 0): line = "Text\IPs\{}.txt".format(b) output_filee ...
-3
2016-06-30T19:28:05Z
38,132,204
<p>You could use a function like this one:</p> <pre><code>def add(filename, text): text += '\n' with open(filename, 'a+') as lines: if not any(text==l for l in lines): lines.write(text) ip_adress = raw_input("IP Adress: ") name = raw_input("Player Name: ") if ip_adress != '0' and name != '0': ...
0
2016-06-30T19:58:37Z
[ "python", "file" ]
Not able to write to file
38,131,723
<p>I am trying to make a string write in a text file, but only if that string is already not in the text file.</p> <pre><code>b = raw_input("IP Adress: ") os.system('cls') if(b == '0'): a = 0 c = raw_input("Player Name: ") if(c == '0'): a = 0 if(a != 0): line = "Text\IPs\{}.txt".format(b) output_filee ...
-3
2016-06-30T19:28:05Z
38,132,262
<p>Apart from the flawed logic mentioned in <a href="http://stackoverflow.com/a/38131833/1925388">Barmar's answer</a>, there are a few more problems: </p> <ul> <li>With the current setting, the new file will only contain the new player name, whereas what I think you want is the new file to contain all the previous na...
1
2016-06-30T20:01:58Z
[ "python", "file" ]
How to send emails through Django using a private domain email address?
38,131,738
<p>I registered a domain and a private email using namecheap.com. I am trying to send an email from this private email. However, I get the error in the title.</p> <p>In my settings.py, I have these settings:</p> <pre><code>EMAIL_HOST = 'mail.privateemail.com' EMAIL_HOST_USER = 'contact@mysite.com' EMAIL_HOST_PASSWORD...
0
2016-06-30T19:28:55Z
38,132,325
<p>Try using port 587 (TLS) instead of 465 (SSL): <a href="https://www.namecheap.com/support/knowledgebase/article.aspx/9183/2175/email-account-setup-in-microsoft-outlook-20072010-smtpimappop3" rel="nofollow">https://www.namecheap.com/support/knowledgebase/article.aspx/9183/2175/email-account-setup-in-microsoft-outlook...
0
2016-06-30T20:05:15Z
[ "python", "django", "django-email" ]
Same equation gives different values in Matlab and Numpy?
38,131,757
<p>I'm trying to convert a function from Matlab to Python. The Matlab function is: </p> <pre><code>function [f,df_dr1,df_dr2,g,dg_dr1,dg_dr2] = f_eval_2eq(r1,r2,r3,z1,z2,z3,n1,n2,n3) f = (r1)./sqrt(r1.^2 + z1.^2)... - (n2/n1)*(r2-r1)./sqrt((r2-r1).^2 + z2.^2); df_dr1 = 1./sqrt(r1.^2 + z1.^2)... - r1.^2./(r1.^2 ...
0
2016-06-30T19:30:36Z
38,131,818
<p>In Python 2.x, if you divide two integers (such as <code>2</code> and <code>3</code>) the result is cast as an integer as well:</p> <pre><code>x = 3/2 # 1 type(x) # &lt;type 'int'&gt; </code></pre> <p>You need to explicitly specify either the numerator or denominator to be a float rather than an integer using...
2
2016-06-30T19:35:51Z
[ "python", "matlab", "numpy" ]
Same equation gives different values in Matlab and Numpy?
38,131,757
<p>I'm trying to convert a function from Matlab to Python. The Matlab function is: </p> <pre><code>function [f,df_dr1,df_dr2,g,dg_dr1,dg_dr2] = f_eval_2eq(r1,r2,r3,z1,z2,z3,n1,n2,n3) f = (r1)./sqrt(r1.^2 + z1.^2)... - (n2/n1)*(r2-r1)./sqrt((r2-r1).^2 + z2.^2); df_dr1 = 1./sqrt(r1.^2 + z1.^2)... - r1.^2./(r1.^2 ...
0
2016-06-30T19:30:36Z
38,132,794
<p>You can also add </p> <pre><code>from __future__ import division </code></pre> <p>to the top of your file, if you're using Python 2, in order to get the Python 3 behavior, i.e. always using float division.</p>
2
2016-06-30T20:35:52Z
[ "python", "matlab", "numpy" ]
What is output from OpenCV's Dense optical flow (Farneback) function? How can this be used to build an optical flow map in Python?
38,131,822
<p>I am trying to use the output of Opencv's dense optical flow function to draw a quiver plot of the motion vectors but have not been able to find what the function actually outputs. Here is the code:</p> <pre><code>import cv2 import numpy as np cap = cv2.VideoCapture('GOPR1745.avi') ret, frame1 = cap.read() prvs =...
2
2016-06-30T19:35:56Z
38,139,195
<p>You were almost there. Lets first take a look at the <a href="http://docs.opencv.org/2.4/modules/video/doc/motion_analysis_and_object_tracking.html#calcopticalflowfarneback" rel="nofollow">calcOpticalFlowFarneback Documentation</a> it says there:</p> <blockquote> <p><code>flow</code> – computed flow image that ...
2
2016-07-01T07:11:01Z
[ "python", "python-2.7", "opencv", "motion-detection", "opticalflow" ]
Can I convert this loop to a map(lambda x: .. )) somehow?
38,131,855
<p>I'm trying to optimize a method that counts the number of <code>1</code>s in the binary representation of each number from <code>0 -&gt; num</code></p> <pre><code># Example of how the below works, for clarity # # base =&gt; [0,1,1,2,1,2,2] # index =&gt; 7 # # {7} -- # bin(7) : 111 # bin...
1
2016-06-30T19:38:07Z
38,133,977
<p>I found 2 (functional style) solutions, but they are hardly "in place". And, probably, both will work slower then loop. </p> <p>First not with map but with reduce:</p> <pre><code>def countBits2(num): from functools import reduce index = 1; base = reduce( lambda base, index: (base.append( base[(index &a...
0
2016-06-30T22:03:25Z
[ "python", "optimization", "lambda" ]
Can I convert this loop to a map(lambda x: .. )) somehow?
38,131,855
<p>I'm trying to optimize a method that counts the number of <code>1</code>s in the binary representation of each number from <code>0 -&gt; num</code></p> <pre><code># Example of how the below works, for clarity # # base =&gt; [0,1,1,2,1,2,2] # index =&gt; 7 # # {7} -- # bin(7) : 111 # bin...
1
2016-06-30T19:38:07Z
38,146,576
<p>Maybe you want something like this?</p> <pre><code>num = 11 base = [0] for _ in range(1, num): base.extend(map(lambda index: base[(index &amp; (index -1))] + 1, [_])) </code></pre> <p>Result:</p> <pre><code>[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2] </code></pre>
0
2016-07-01T13:22:17Z
[ "python", "optimization", "lambda" ]
How to increment variable in the middle of URL and output for multiple queries?
38,131,886
<p>I would like to modify the code below to allow for searching multiple stores at once (via the four digit store number in the 'data' section below). What is the best way to accomplish this? Preferably I would be able to limit the search to 50-100 stores. </p> <pre><code>import requests import json js = requests.pos...
-1
2016-06-30T19:40:34Z
38,132,215
<p>Your <code>data</code> object in the request.post call can be constructed like any other string. And then a variable that represents it can take the place of your "store=2516..." string. Like this, assuming <code>requests</code> is defined in the outer function someplace and can be reused:</p> <pre><code>var stores...
0
2016-06-30T19:59:17Z
[ "python", "json" ]
How to increment variable in the middle of URL and output for multiple queries?
38,131,886
<p>I would like to modify the code below to allow for searching multiple stores at once (via the four digit store number in the 'data' section below). What is the best way to accomplish this? Preferably I would be able to limit the search to 50-100 stores. </p> <pre><code>import requests import json js = requests.pos...
-1
2016-06-30T19:40:34Z
38,132,375
<p>The API does not support searching for multiple stores, so you need to make multiple requests.</p> <pre><code>import requests import json from collections import defaultdict results = defaultdict(list) stores = [2516, 1234, 5678] url = "http://www.walmart.com/store/ajax/search" query = "store={}&amp;size=18&amp;d...
0
2016-06-30T20:09:38Z
[ "python", "json" ]
Pylab - Change historgram colors based on RGB axis
38,132,019
<p>I have a python dictionary I'm using to get a histogram:</p> <pre><code>colors = {(97, 103, 105): 638059, (129, 140, 143): 562526, (55, 58, 62): 431610, (189, 193, 193): 460605} import pylab as pl import numpy as np dict_index = np.arange(len(colors)) pl.bar(dict_index, colors.values(), align='center', width=0.5) ...
0
2016-06-30T19:48:50Z
38,132,353
<p>Try the color option in pl.bar. Colors need to be normalized to 0-1.</p> <pre><code>colors = {(97, 103, 105): 638059, (129, 140, 143): 562526, (55, 58, 62): 431610, (189, 193, 193): 460605} normalizedcolors = [[i/256 for i in j] for j in colors.keys()] import pylab as pl import numpy as np dict_index = np.arange(l...
1
2016-06-30T20:07:32Z
[ "python", "matplotlib" ]
Python insert tab in string
38,132,076
<p>I just began learning Python. I'm not sure how to insert tab in string. For instance, how can i insert tab to the right of "World" in the strings below:</p> <pre><code>example = ' Hello World' </code></pre> <p>Everytime I use Tab after "World" a drop down menu appears, how can I avoid that? thanks! I tried usin...
-3
2016-06-30T19:51:22Z
38,132,273
<p>The dropdown error is because of the editor you are using. Just try using plain notepad++. It's working! I tried.</p> <pre><code>print "Hello World\t", print "hi" </code></pre> <p>Just to make sure that there is tab after the first print, print one more statement. you will come to visual it. Make sure to use comma...
1
2016-06-30T20:02:22Z
[ "python" ]