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
Why is my Python script not running via command line?
40,138,529
<p>Thanks!</p> <pre><code>def hello(a,b): print "hello and that's your sum:" sum=a+b print sum import sys if __name__ == "__main__": hello(sys.argv[2]) </code></pre> <p>It does not work for me, I appreciate the help!!! Thanks!</p>
-1
2016-10-19T18:01:27Z
40,138,672
<ul> <li>Import <code>sys</code> in <strong>global scope</strong>, not in the end of the function.</li> <li>Send <strong>two arguments</strong> into <code>hello</code>, one is not enough. </li> <li>Convert these arguments to <strong>floats</strong>, so they can be added as numbers.</li> <li><strong>Indent</strong> prop...
2
2016-10-19T18:10:07Z
[ "python" ]
Python: How to develop a between_time similar method when on pandas 0.9.0?
40,138,573
<p>I am stick to pandas 0.9.0 as I'm working under python 2.5, hence I have no <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html" rel="nofollow">between_time</a> method available. </p> <p>I have a DataFrame of dates and would like to filter all the dates that are between...
1
2016-10-19T18:03:58Z
40,138,627
<p><strong>UPDATE:</strong></p> <p>try to use:</p> <pre><code>df.ix[df.index.indexer_between_time('08:00','09:50')] </code></pre> <p><strong>OLD answer:</strong></p> <p>I'm not sure that it'll work on Pandas 0.9.0, but it's worth to try it:</p> <pre><code>df[(df.index.hour &gt;= 8) &amp; (df.index.hour &lt;= 9)] <...
2
2016-10-19T18:06:52Z
[ "python", "pandas", "python-2.5" ]
Python: How to develop a between_time similar method when on pandas 0.9.0?
40,138,573
<p>I am stick to pandas 0.9.0 as I'm working under python 2.5, hence I have no <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html" rel="nofollow">between_time</a> method available. </p> <p>I have a DataFrame of dates and would like to filter all the dates that are between...
1
2016-10-19T18:03:58Z
40,139,164
<p>Here is a NumPy-based way of doing it:</p> <pre><code>import pandas as pd import numpy as np import datetime dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="10min") df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power']) epoch = np.datetime64('1970-01-01') start = np....
1
2016-10-19T18:37:35Z
[ "python", "pandas", "python-2.5" ]
Python find and replace dialog from Rapid GUI Programming error
40,138,639
<p>When building the find and replace dialog from "Rapid GUI Programming with Python and Qt (Chapter 07), by Prentice Hall (Mark Sumerfield)", I get the following error:</p> <pre><code> import ui_findandreplacedlg ImportError: No module named ui_findandreplacedlg </code></pre> <p>Depending on which version of pyth...
1
2016-10-19T18:07:41Z
40,138,698
<p>The code in question can be found here - <a href="https://github.com/suzp1984/pyqt5-book-code/blob/master/chap07/ui_findandreplacedlg.py" rel="nofollow">https://github.com/suzp1984/pyqt5-book-code/blob/master/chap07/ui_findandreplacedlg.py</a>. If that file is in the same directory as the code you're trying to run, ...
0
2016-10-19T18:12:02Z
[ "python", "qt", "pyqt", "importerror" ]
Theano's function() reports that my `givens` value is not needed for the graph
40,138,656
<p>Sorry for not posting entire snippets -- the code is very big and spread out, so hopefully this can illustrate my issue. I have these:</p> <pre><code>train = theano.function([X], output, updates=update_G, givens={train_mode=:np.cast['int32'](1)}) </code></pre> <p>and </p> <pre><code>test =...
0
2016-10-19T18:09:13Z
40,139,049
<p>why you use "=" sign? I think, it made train_mode not readable, my code works well by writing: <code>givens = {train_mode:1}</code></p>
0
2016-10-19T18:31:37Z
[ "python", "neural-network", "deep-learning", "theano", "conv-neural-network" ]
Concatenate string using .format
40,138,709
<p>I have some code similar to the following:</p> <pre><code>test_1 = 'bob' test_2 = 'jeff' test_1 += "-" + test_2 + "\n" </code></pre> <p>Output:</p> <pre><code>bob- jeff\n </code></pre> <p>I'd like to have the same functionality but using the <code>.format</code> method.</p> <p>This is what I have so far:</p> ...
0
2016-10-19T18:12:23Z
40,139,006
<p><code>''.join</code> is probably fast enough and efficient.</p> <pre><code>'-'.join((test_1,test_2)) </code></pre> <p>You can measure different methods using the <code>timeit</code> module. That can tell you which is fastest </p> <p>This is an example of how <code>timeit</code> can be used:-</p> <pre><code>&g...
1
2016-10-19T18:29:01Z
[ "python", "string", "python-2.7", "string-formatting", "string-concatenation" ]
Python - Return integer value for list enumeration
40,138,958
<p>Is there a cleaner way to get an integer value of the position of a list item in this code:</p> <pre><code>a = ['m', 'rt', 'paaq', 'panc'] loc = [i for i, x in enumerate(a) if x == 'rt'] loc_str = str(loc).strip('[]') loc_int = int(loc_str) id_list = a[loc_int + 1:] print id_list </code></pre> <p>Returns all items...
0
2016-10-19T18:26:48Z
40,138,998
<p>Yes, use <code>list.index()</code>.</p> <pre><code>a = ['m', 'rt', 'paaq', 'panc'] id_list = a[a.index('rt')+1:] assert id_list == ['paaq', 'panc'] </code></pre> <p>Or, to minimally change your program:</p> <pre><code>a = ['m', 'rt', 'paaq', 'panc'] loc_int = a.index('rt') id_list = a[loc_int + 1:] print id_list ...
5
2016-10-19T18:28:22Z
[ "python", "enumerate" ]
Python - Return integer value for list enumeration
40,138,958
<p>Is there a cleaner way to get an integer value of the position of a list item in this code:</p> <pre><code>a = ['m', 'rt', 'paaq', 'panc'] loc = [i for i, x in enumerate(a) if x == 'rt'] loc_str = str(loc).strip('[]') loc_int = int(loc_str) id_list = a[loc_int + 1:] print id_list </code></pre> <p>Returns all items...
0
2016-10-19T18:26:48Z
40,139,042
<pre><code>a[a.index('rt') + 1:] </code></pre> <p>What this is doing is <a href="https://docs.python.org/2.3/whatsnew/section-slices.html" rel="nofollow">slicing</a> the array, starting at where <code>a.index('rt')</code>. not specifying an end <code>:]</code> means we want until the end of the list.</p>
0
2016-10-19T18:31:08Z
[ "python", "enumerate" ]
Python - dividing a user input to display a range of answers
40,139,135
<p>I'm having problems with a Python question. The question is to write a function that shows all integers that are cleanly divisble by 13 in the range of (1:x) where x is a user input. I'm new to Python and am struggling with this question. I need to have a user input which Python then divides by 13 and displays the ...
0
2016-10-19T18:36:31Z
40,139,252
<p><code>x % 13 == 0</code> by itself does nothing; it evaluates to True or False, but you then ignore that result. If you want to do something with it, you need to use it in an if condition.</p> <p>Note also that indentation is important - the else needs to be lined up with the if. There's no need for <code>while</co...
0
2016-10-19T18:44:26Z
[ "python", "python-2.7", "python-3.x" ]
Python - dividing a user input to display a range of answers
40,139,135
<p>I'm having problems with a Python question. The question is to write a function that shows all integers that are cleanly divisble by 13 in the range of (1:x) where x is a user input. I'm new to Python and am struggling with this question. I need to have a user input which Python then divides by 13 and displays the ...
0
2016-10-19T18:36:31Z
40,139,287
<p>Can do this:</p> <pre><code>x = int(input("Enter your number here: ")) def divide(x): for i in range(1,x): if i % 13 == 0: print (i) divide(x) </code></pre>
0
2016-10-19T18:46:33Z
[ "python", "python-2.7", "python-3.x" ]
Python - dividing a user input to display a range of answers
40,139,135
<p>I'm having problems with a Python question. The question is to write a function that shows all integers that are cleanly divisble by 13 in the range of (1:x) where x is a user input. I'm new to Python and am struggling with this question. I need to have a user input which Python then divides by 13 and displays the ...
0
2016-10-19T18:36:31Z
40,139,338
<p>Instead you can do something like:</p> <pre><code>x = 27 / 13 print [13 * i for i in range(1,x+1)] </code></pre>
0
2016-10-19T18:49:44Z
[ "python", "python-2.7", "python-3.x" ]
Python - dividing a user input to display a range of answers
40,139,135
<p>I'm having problems with a Python question. The question is to write a function that shows all integers that are cleanly divisble by 13 in the range of (1:x) where x is a user input. I'm new to Python and am struggling with this question. I need to have a user input which Python then divides by 13 and displays the ...
0
2016-10-19T18:36:31Z
40,139,408
<p>Borrow the back-ported print function Python 3:</p> <pre><code>from __future__ import print_function </code></pre> <p>The following will print all numbers in the range [1..x] inclusive</p> <pre><code>print([y for y in range(1,x+1,1) if y%13==0]) </code></pre>
0
2016-10-19T18:54:25Z
[ "python", "python-2.7", "python-3.x" ]
Python - dividing a user input to display a range of answers
40,139,135
<p>I'm having problems with a Python question. The question is to write a function that shows all integers that are cleanly divisble by 13 in the range of (1:x) where x is a user input. I'm new to Python and am struggling with this question. I need to have a user input which Python then divides by 13 and displays the ...
0
2016-10-19T18:36:31Z
40,139,422
<p>I'd just show all multiples of 13 until x, dropping 0:</p> <pre><code>def divide(x): print range(0, x, 13)[1:] </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; divide(27) [13, 26] </code></pre>
0
2016-10-19T18:55:15Z
[ "python", "python-2.7", "python-3.x" ]
insert element in the start of the numpy array
40,139,167
<p>I have array </p> <pre><code>x=[ 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876 ] </code></pre> <p>I want to insert -1 to the start of the array to be like </p> <pre><code> x= [-1 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876] </code></pre> <p>I tried :</p> <pre><code>np.insert(x,0,-1,...
0
2016-10-19T18:37:42Z
40,139,221
<p>You can do the insert by ommiting the axis param:</p> <pre><code>x = np.array([0,0,0,0]) x = np.insert(x, 0, -1) x </code></pre> <p>That will give:</p> <pre><code>array([-1, 0, 0, 0, 0]) </code></pre>
2
2016-10-19T18:42:09Z
[ "python", "arrays", "numpy" ]
insert element in the start of the numpy array
40,139,167
<p>I have array </p> <pre><code>x=[ 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876 ] </code></pre> <p>I want to insert -1 to the start of the array to be like </p> <pre><code> x= [-1 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876] </code></pre> <p>I tried :</p> <pre><code>np.insert(x,0,-1,...
0
2016-10-19T18:37:42Z
40,139,294
<p>I'm not fully familiar with numpy, but it seems that the insert function does not affect the array you pass to it, but rather it returns a new array with the inserted value(s). You'll have to reassign to x if you really want x to change. </p> <pre><code>&gt;&gt;&gt; x= [-1, 0.30153836, 0.30376881, 0.29115761, 0...
2
2016-10-19T18:47:07Z
[ "python", "arrays", "numpy" ]
insert element in the start of the numpy array
40,139,167
<p>I have array </p> <pre><code>x=[ 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876 ] </code></pre> <p>I want to insert -1 to the start of the array to be like </p> <pre><code> x= [-1 0.30153836 0.30376881 0.29115761 0.29074261 0.28676876] </code></pre> <p>I tried :</p> <pre><code>np.insert(x,0,-1,...
0
2016-10-19T18:37:42Z
40,139,686
<p>From the <code>np.insert</code> documentation:</p> <pre><code>Returns out : ndarray A copy of `arr` with `values` inserted. Note that `insert` does not occur in-place: a new array is returned. </code></pre> <p>You can do the same with <code>concatenate</code>, joining the new value to the main value. <cod...
0
2016-10-19T19:11:41Z
[ "python", "arrays", "numpy" ]
Keeping 'key' column when using groupby with transform in pandas
40,139,184
<p>Finding a normalized dataframe removes the column being used to group by, so that it can't be used in subsequent groupby operations. for example (edit: updated):</p> <pre><code> df = pd.DataFrame({'a':[1, 1 , 2, 3, 2, 3], 'b':[0, 1, 2, 3, 4, 5]}) a b 0 1 0 1 1 1 2 2 2 3 3 3 ...
2
2016-10-19T18:39:08Z
40,139,517
<p>that is bizzare!</p> <p>I tricked it like this</p> <pre><code>df.groupby(df.a.values).transform(lambda x: x) </code></pre> <p><a href="https://i.stack.imgur.com/XcYxq.png" rel="nofollow"><img src="https://i.stack.imgur.com/XcYxq.png" alt="enter image description here"></a></p>
2
2016-10-19T19:01:01Z
[ "python", "pandas" ]
Is it possible to pass a single user input (an int) into an argument to match 2 ints in python?
40,139,187
<p>Basically I'm trying to write a tic tac toe game in python and I'm new to the language. At the moment I'm trying to get the user to input an int which I will then pass into an argument which requires two ints of the same number (as the grid will be a square), to make a grid for the game. If you look in the code belo...
0
2016-10-19T18:39:14Z
40,139,243
<p>I am not sure what exactly you want to do, but I guess there are multiple solutions to it. I will just give one possible solution:</p> <pre><code>def grid_maker(h,w=None): if w is None: w=h grid = [[" | " for _ in range(w)] for _ in range(h)] return grid </code></pre>
0
2016-10-19T18:43:40Z
[ "python", "python-3.x", "multidimensional-array", "grid", "arguments" ]
Reformat JSON file?
40,139,200
<p>I have two JSON files.</p> <p>File A:</p> <pre><code> "features": [ { "attributes": { "NAME": "R T CO", "LTYPE": 64, "QUAD15M": "279933", "OBJECTID": 225, "SHAPE.LEN": 828.21510830520401 }, "geometry": { "paths": [ [ [ -99.818614674337155, 27.78254267767...
1
2016-10-19T18:40:13Z
40,139,235
<p>What about:</p> <pre><code>cat &lt;file&gt; | python -m json.tool </code></pre> <p>This will reformat the contents of the file into a uniform human readable format. If you really need to change the names of the fields you could use sed.</p> <pre><code>cat &lt;file&gt; | sed -e 's/"properties"/"attributes"/' </cod...
-2
2016-10-19T18:43:14Z
[ "python", "json", "reformatting" ]
Reformat JSON file?
40,139,200
<p>I have two JSON files.</p> <p>File A:</p> <pre><code> "features": [ { "attributes": { "NAME": "R T CO", "LTYPE": 64, "QUAD15M": "279933", "OBJECTID": 225, "SHAPE.LEN": 828.21510830520401 }, "geometry": { "paths": [ [ [ -99.818614674337155, 27.78254267767...
1
2016-10-19T18:40:13Z
40,139,464
<p>Manipulating JSON in Python is a good candidate for the <a href="https://en.wikipedia.org/wiki/IPO_model" rel="nofollow">input-process-output model</a> of programming.</p> <p>For input, you convert the external JSON file into a Python data structure, using <a href="https://docs.python.org/2/library/json.html#json.l...
4
2016-10-19T18:58:03Z
[ "python", "json", "reformatting" ]
python/pandas/sklearn: getting closest matches from pairwise_distances
40,139,216
<p>I have a dataframe and am trying to get the closest matches using mahalanobis distance across three categories, like:</p> <pre><code>from io import StringIO from sklearn import metrics import pandas as pd stringdata = StringIO(u"""pid,ratio1,pct1,rsp 0,2.9,26.7,95.073615 1,11.6,29.6,96.963660 2,0.7,37....
0
2016-10-19T18:41:36Z
40,139,643
<pre><code>from io import StringIO from sklearn import metrics stringdata = StringIO(u"""pid,ratio1,pct1,rsp 0,2.9,26.7,95.073615 1,11.6,29.6,96.963660 2,0.7,37.9,97.750412 3,2.7,27.9,102.750412 4,1.2,19.9,93.750412 5,0.2,22.1,96.750412 """) stats = ['ratio1','pct1','rsp'] df = pd.read_csv...
1
2016-10-19T19:09:23Z
[ "python", "pandas", "scikit-learn" ]
iteration counter for GCD
40,139,296
<p>I have the following code for calulating the GCD of two numbers:</p> <pre><code>def gcd(m, n): r = m % n while r != 0: m = n n = r r = m % n return n print ("\n", "gcd (10, 35) = ", gcd(10, 35)) print ("\n", "gcd (735, 175) = ", gcd(735, 175)) print ("\n", "gcd (735, 350) = ", gcd(735,...
0
2016-10-19T18:47:11Z
40,139,335
<pre><code>def gcd(m, n): r = m % n counter = 0 while r != 0: m = n n = r r = m % n counter += 1 return n, counter </code></pre>
3
2016-10-19T18:49:34Z
[ "python", "iteration" ]
How to create a web crawler to get multiple pages from agoda,with python3
40,139,323
<p>I'm new to here. Recently, I want to get data from Agoda,and I got a problem that agoda.com don't provide the url(or href) of "next page". So I have no idea to change page. Now, I only get the data from page 1, but I need the data from page2, page3... Is anyone help me. I need some advise, tools or others. By the wa...
0
2016-10-19T18:48:58Z
40,141,606
<p>Examine closely in browser development tools what happens when you click next button. </p> <p>It has click event that sends xhr post request with a lot of parameters. One of the parameters is <code>PageNumber</code>. Most values for the parameters are straightforward to get, maybe except <code>SearchMessageID</code...
0
2016-10-19T21:11:37Z
[ "python", "scrapy", "web-crawler", "webpage" ]
Python Arguments and Passing Floats in Arguments
40,139,445
<p>I've run into a couple of issues using arguments within a python script. Can i please get some help or direction to get this code functional? Thank you in advance.</p> <p>First issue: I am unable to specify multiple arguments at once. For example I am able to pass a single argument fine:</p> <pre><code>$ ./my_arg...
1
2016-10-19T18:56:51Z
40,139,491
<p><s>You didn't actually provide the code you're using (aside from incidentally in the traceback),</s>(<strong>Update:</strong> Code added later) but the answer is: Stop messing around with parsing <code>sys.argv</code> manually and use <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">the <code...
3
2016-10-19T18:59:19Z
[ "python", "python-3.x", "int", "argv" ]
Django templates: why does __call__ magic method breaks the rendering of a non-model object?
40,139,493
<p>Today I faced a strange issue on one of my development. I reproduced it with a very minimal example. Have a look at these 2 dummy classes (non Django model subclasses):</p> <pre><code>class DummyClassA(object): def __init__(self, name): self.name = name def __repr__(self): return 'Dummy1 ob...
0
2016-10-19T18:59:23Z
40,139,679
<p>Because that's what the template language is designed to do. As <a href="https://docs.djangoproject.com/en/1.10/ref/templates/language/#variables" rel="nofollow">the docs state</a>:</p> <blockquote> <p>If the resulting value [of looking up a variable] is callable, it is called with no arguments. The result of the...
1
2016-10-19T19:11:16Z
[ "python", "django", "templates", "magic-methods" ]
Import error installing tlslite
40,139,501
<p>I'm trying to install tlslite. After installed the module I've tried to test it and I receive this error: </p> <pre><code>from .checker import Checker ImportError: No module named checker </code></pre> <p>I've checked on my pip module list and checker is installed... Any idea? Thanks!</p>
0
2016-10-19T18:59:53Z
40,139,728
<p>Assuming you installed tlslite correctly, try this:</p> <pre><code>&gt;&gt;&gt; from tlslite.checker import Checker </code></pre> <p>If that doesn't work, check that tlslite is in your site packages</p>
0
2016-10-19T19:14:06Z
[ "python" ]
Import error installing tlslite
40,139,501
<p>I'm trying to install tlslite. After installed the module I've tried to test it and I receive this error: </p> <pre><code>from .checker import Checker ImportError: No module named checker </code></pre> <p>I've checked on my pip module list and checker is installed... Any idea? Thanks!</p>
0
2016-10-19T18:59:53Z
40,139,824
<p>To work with <a href="https://pypi.python.org/pypi/tlslite/0.4.6" rel="nofollow">tlslite</a> I recommend to use a virtualenv and install TlsLite inside:</p> <pre><code>cd ~/virtualenv/ # &lt;- all my virtualenv are here virtualenv myvenv source ~/virtualenv/myvenv/bin/activate pip install -q -U pip setuptools # e...
0
2016-10-19T19:19:18Z
[ "python" ]
Scrape Yahoo Finance Financial Ratios
40,139,537
<p>I have been trying to scrap the value of the Current Ratio (as shown below) from Yahoo Finance using Beautiful Soup, but it keeps returning an empty value.</p> <p><a href="https://i.stack.imgur.com/SKunN.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/SKunN.jpg" alt="enter image description here"></a></p> ...
1
2016-10-19T19:02:15Z
40,140,199
<p>You can actually get the data is json format, there is a call to an api that returns a lot of the data including the current ratio:</p> <p><a href="https://i.stack.imgur.com/Zu7sP.png" rel="nofollow"><img src="https://i.stack.imgur.com/Zu7sP.png" alt="enter image description here"></a></p> <pre><code>import reques...
3
2016-10-19T19:41:41Z
[ "python", "beautifulsoup" ]
Scrape Yahoo Finance Financial Ratios
40,139,537
<p>I have been trying to scrap the value of the Current Ratio (as shown below) from Yahoo Finance using Beautiful Soup, but it keeps returning an empty value.</p> <p><a href="https://i.stack.imgur.com/SKunN.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/SKunN.jpg" alt="enter image description here"></a></p> ...
1
2016-10-19T19:02:15Z
40,140,593
<p>One thing I'd add to Padriac's answer is to except KeyErrors, since you'll probably be scraping more than one ticker. </p> <pre><code>import requests a = requests.get('https://query2.finance.yahoo.com/v10/finance/quoteSummary/GSB?formatted=true&amp;crumb=A7e5%2FXKKAFa&amp;lang=en-US&amp;region=US&amp;modules=defaul...
1
2016-10-19T20:07:15Z
[ "python", "beautifulsoup" ]
passing an array of COM pointers from Python to C++
40,139,573
<p>I've been reading a lot of docs, examples and StackOverflow topics, but still it doesn't work! I'm writing a Python interface to my C++ COM objects. This is not the first time I've done this. In the past I've successfully used comtypes to acquire individual interface pointers and passed them my COM classes, but this...
0
2016-10-19T19:04:59Z
40,141,084
<p>Once again, answering my own question. There is an additional level of indirection being introduced beyond what is required. Apparently, unlike a cast in C, ctypes.cast actually takes the address of the first argument.</p> <p>Change:</p> <pre><code>PointerArray = ctypes.c_void_p * len(exportLayers) </code></pre> ...
0
2016-10-19T20:37:25Z
[ "python", "windows", "types", "comtypes" ]
Characters from listbox are still recorded even when deleted from listbox
40,139,628
<p>So my little game is programmed to have two characters fight each other. One from the left side and one from the right side. After they fight both should be deleted regardless of who wins or loses. They are in fact deleted from listboxes, but after you have two more charachters from each side fight those previous ch...
1
2016-10-19T19:08:33Z
40,142,209
<p>Problem is because you use always <code>if left == 0: namel = "Rash" even if</code>"Rash"<code>was deleted from listbox and now</code>left == 0<code>means</code>"Untss".</p> <p>You have to get selected name instead of index </p> <pre><code> namel = lbox.get(lbox.curselection()[0]) namer = rbox.get(rbox.curs...
0
2016-10-19T21:59:32Z
[ "python", "tkinter", "listbox" ]
Percentage data from .csv to excel
40,139,709
<p>I read some data under percentage form (11.00%) from a .csv file. I copy them into an excel file and i want to represent them in a chart. The problem is, when i copy them into excel, data is automatically converted to string type and i cannot represent them in the chart correctly. I tried few methods but nothing suc...
-1
2016-10-19T19:13:00Z
40,139,789
<pre><code>for row in ws.iter_rows(row_offset=0): for i in reader: ws.append(float(i[2:-1])) code here </code></pre> <p>Float the value before you append it</p>
0
2016-10-19T19:17:08Z
[ "python", "python-2.7", "python-3.x", "openpyxl" ]
Attribute error for PersonalInfoForm
40,139,735
<p>I'm a little confused why is 'clickjacking middleware` <em>trowing</em> Attribute Error on my form.</p> <p>I'm making a simple application for collecting labor or user information, and I'm facing a small problem, can someone please help me and clarify what is wrong in this code</p> <p><a href="http://dpaste.com/37...
0
2016-10-19T19:14:39Z
40,139,929
<p>Your traceback is showing that you haven't used the view above at all, but the form. Presumably you've assigned the wrong thing in urls.py.</p> <p><strong>Edit</strong> Actually the problem is that your post method, when the form is not valid, returns the form itself and not an HttpResponse.</p> <p>However you sho...
1
2016-10-19T19:25:10Z
[ "python", "django", "django-forms", "django-views", "django-middleware" ]
Setting Image background for a line plot in matplotlib
40,139,770
<p>I am trying to set a background image to a line plot that I have done in matplotlib. While importing the image and using zorder argument also, I am getting two seperate images, in place of a single combined image. Please suggest me a way out. My code is -- </p> <p><div class="snippet" data-lang="js" data-hide="fals...
0
2016-10-19T19:16:14Z
40,139,937
<p>You're creating two separate figures in your code. The first one with <code>fig, ax = plt.subplots(1)</code> and the second with <code>plt.figure(2)</code></p> <p>If you delete that second figure, you should be getting closer to your goal</p>
0
2016-10-19T19:25:46Z
[ "python", "matplotlib" ]
Setting Image background for a line plot in matplotlib
40,139,770
<p>I am trying to set a background image to a line plot that I have done in matplotlib. While importing the image and using zorder argument also, I am getting two seperate images, in place of a single combined image. Please suggest me a way out. My code is -- </p> <p><div class="snippet" data-lang="js" data-hide="fals...
0
2016-10-19T19:16:14Z
40,141,461
<p>In order to overlay background image over plot, we need <code>imshow</code> and <code>extent</code> parameter from <code>matplotlib</code>.</p> <p>Here is an condensed version of your code. Didn't have time to clean up much.</p> <p>First a sample data is created for 11 countries as listed in your code. It is then ...
0
2016-10-19T21:00:57Z
[ "python", "matplotlib" ]
Is there a way to refer two attributes of an object in a list?
40,139,814
<p>I want to know who is the taller athlete (object) in a list of objects. If I want to print it, I tried to write this:</p> <pre><code>print ("The greater height is",max(x.height for x in athletes_list),"meters.") </code></pre> <p>It shows the height of the taller athlete, but I don't know how to get his name by thi...
1
2016-10-19T19:18:41Z
40,139,916
<p>Reread your question. The answer is still yes. Use the <code>format</code> method of strings:</p> <pre><code>print("The taller athlete is {0.name} with {0.height} meters.".format(max(athletes_list, key=lambda a: a.height))) </code></pre>
2
2016-10-19T19:24:21Z
[ "python" ]
Is there a way to refer two attributes of an object in a list?
40,139,814
<p>I want to know who is the taller athlete (object) in a list of objects. If I want to print it, I tried to write this:</p> <pre><code>print ("The greater height is",max(x.height for x in athletes_list),"meters.") </code></pre> <p>It shows the height of the taller athlete, but I don't know how to get his name by thi...
1
2016-10-19T19:18:41Z
40,139,934
<p>Use <code>max</code> over both values (with height first):</p> <pre><code>from future_builtins import map # Only on Py2, to get generator based map from operator import attrgetter # Ties on height will go to first name alphabetically maxheight, name = max(map(attrgetter('height', 'name'), athletes)) print("The ta...
1
2016-10-19T19:25:28Z
[ "python" ]
How do I return a nonflat numpy array selecting elements given a set of conditions?
40,139,826
<p>I have a multidimensional array, say of shape (4, 3) that looks like</p> <pre><code>a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)]) </code></pre> <p>If I have a list of fixed conditions</p> <pre><code>conditions = [True, False, False, True] </code></pre> <p>How can I return the list</p> <pre><code>array([(1,...
0
2016-10-19T19:19:34Z
40,139,884
<p>Let's define you variables:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)]) &gt;&gt;&gt; conditions = [True, False, False, True] </code></pre> <p>Now, let's select the elements that you want:</p> <pre><code>&gt;&gt;&gt; a[np.array(conditions)] array([...
1
2016-10-19T19:22:24Z
[ "python", "arrays", "numpy", "conditional", "slice" ]
How do I return a nonflat numpy array selecting elements given a set of conditions?
40,139,826
<p>I have a multidimensional array, say of shape (4, 3) that looks like</p> <pre><code>a = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)]) </code></pre> <p>If I have a list of fixed conditions</p> <pre><code>conditions = [True, False, False, True] </code></pre> <p>How can I return the list</p> <pre><code>array([(1,...
0
2016-10-19T19:19:34Z
40,139,895
<p>you can use simple list slicing and <code>np.where</code> It's more or less made specifically for this situation..</p> <pre><code>&gt;&gt;&gt; a[np.where(conditions)] array([[[ 1, 2, 3], [10, 11, 12]]]) </code></pre>
1
2016-10-19T19:23:08Z
[ "python", "arrays", "numpy", "conditional", "slice" ]
Is it possible to use FillBetweenItem to fill between two PlotCurveItem's in pyqtgraph?
40,139,984
<p>I'm attempting to fill between two curves that were created using PlotCurveItem in pyqtgraph.</p> <pre><code> phigh = self.p2.addItem(pg.PlotCurveItem(x, y, pen = 'k')) plow = self.p2.addItem(pg.PlotCurveItem(x, yy, pen = 'k')) pfill = pg.FillBetweenItem(phig...
0
2016-10-19T19:28:11Z
40,140,083
<p>This fixed it. </p> <pre><code> phigh = pg.PlotCurveItem(x, y, pen = 'k') plow = pg.PlotCurveItem(x, yy, pen = 'k') pfill = pg.FillBetweenItem(ph, plow, brush = br) self.p2.addItem(ph) self.p2.addItem(plow) self.p2....
0
2016-10-19T19:35:18Z
[ "python", "python-2.7", "pyqtgraph" ]
Try and Except (TypeError)
40,140,094
<p>What I'm trying to do is create a menu-style start in my program that let's the user choose whether they want to validate a code or generate one. The code looks like this:</p> <pre><code>choice = input("enter v for validate, or enter g for generate").lower() try: choice == "v" and "g" except TypeError: prin...
0
2016-10-19T19:35:50Z
40,140,163
<p>Try.</p> <pre><code>choice = input("enter v for validate, or enter g for generate").lower() if (choice == "v") or (choice == "g"): #do something else : print("Not a valid choice! Try again") restartCode() #pre-defined function, d/w about this* </code></pre> <p>However, if you really want to stick wit...
1
2016-10-19T19:39:57Z
[ "python", "try-catch", "typeerror", "except" ]
Try and Except (TypeError)
40,140,094
<p>What I'm trying to do is create a menu-style start in my program that let's the user choose whether they want to validate a code or generate one. The code looks like this:</p> <pre><code>choice = input("enter v for validate, or enter g for generate").lower() try: choice == "v" and "g" except TypeError: prin...
0
2016-10-19T19:35:50Z
40,140,231
<p>You are confused about what <code>try/except</code> does. <code>try/except</code> is used when an error is likely to be raised. No error will be raised because everything in your program is valid. Errors are raised only when there is an execution error in your code. Errors are not just raised when you need them to b...
0
2016-10-19T19:43:49Z
[ "python", "try-catch", "typeerror", "except" ]
Try and Except (TypeError)
40,140,094
<p>What I'm trying to do is create a menu-style start in my program that let's the user choose whether they want to validate a code or generate one. The code looks like this:</p> <pre><code>choice = input("enter v for validate, or enter g for generate").lower() try: choice == "v" and "g" except TypeError: prin...
0
2016-10-19T19:35:50Z
40,140,234
<p>The problem is not in your <code>try</code> and <code>except</code> but in the fact that you are using <code>try</code> and <code>except</code> at all. The code in your <code>try</code> block won't give you an error so <code>except</code> will never be triggered. You want to use an <code>if</code> statement.</p> <p...
2
2016-10-19T19:44:04Z
[ "python", "try-catch", "typeerror", "except" ]
if-else in python list comprehensions
40,140,202
<p>is it possible to write list comprehensions for the following python code:</p> <pre><code>for str in range(0,len(mixed_content)): if (mixed_content[str].isdigit()): num_list.append(mixed_content[str]) else: string_list.append(mixed_content[str]) </code></pre> <p>can we use else block in lis...
2
2016-10-19T19:41:45Z
40,140,261
<p>You can only construct one list at a time with list comprehension. You'll want something like:</p> <pre><code>nums = [foo for foo in mixed_list if foo.isdigit()] strings = [foo for foo in mixed_list if not foo.isdigit()] </code></pre>
2
2016-10-19T19:45:53Z
[ "python", "python-2.7", "python-3.x", "list-comprehension" ]
if-else in python list comprehensions
40,140,202
<p>is it possible to write list comprehensions for the following python code:</p> <pre><code>for str in range(0,len(mixed_content)): if (mixed_content[str].isdigit()): num_list.append(mixed_content[str]) else: string_list.append(mixed_content[str]) </code></pre> <p>can we use else block in lis...
2
2016-10-19T19:41:45Z
40,140,267
<p>It's not possible as-is, but if you're looking for one-liners you can do that with a ternary expression inside your loop (saves a test and is compact):</p> <pre><code>num_list=[] string_list=[] for s in ["45","hello","56","foo"]: (num_list if s.isdigit() else string_list).append(s) print(num_list,string_list) ...
6
2016-10-19T19:46:26Z
[ "python", "python-2.7", "python-3.x", "list-comprehension" ]
if-else in python list comprehensions
40,140,202
<p>is it possible to write list comprehensions for the following python code:</p> <pre><code>for str in range(0,len(mixed_content)): if (mixed_content[str].isdigit()): num_list.append(mixed_content[str]) else: string_list.append(mixed_content[str]) </code></pre> <p>can we use else block in lis...
2
2016-10-19T19:41:45Z
40,140,315
<p>You can accomplish what you want with two list comprehensions:</p> <pre><code>num_list = [num for num in mixed_content if num.isdigit()] string_list = [string for string in mixed_content if not string.isdigit()] </code></pre> <p>The else clause is not supported in list comprehensions:</p> <pre><code>&gt;&gt;&gt; ...
0
2016-10-19T19:49:30Z
[ "python", "python-2.7", "python-3.x", "list-comprehension" ]
if-else in python list comprehensions
40,140,202
<p>is it possible to write list comprehensions for the following python code:</p> <pre><code>for str in range(0,len(mixed_content)): if (mixed_content[str].isdigit()): num_list.append(mixed_content[str]) else: string_list.append(mixed_content[str]) </code></pre> <p>can we use else block in lis...
2
2016-10-19T19:41:45Z
40,140,324
<p>A super messy and unpractical way of doing is:</p> <pre><code>mixed_content = ['a','b','c',"4"] string_list = [] print [y for y in [x if mixed_content[x].isdigit() else string_list.append(mixed_content[x]) for x in range(0,len(mixed_content))] if y != None] print string_list </code></pre> <p>Returns: </p> <pre><...
0
2016-10-19T19:50:06Z
[ "python", "python-2.7", "python-3.x", "list-comprehension" ]
if-else in python list comprehensions
40,140,202
<p>is it possible to write list comprehensions for the following python code:</p> <pre><code>for str in range(0,len(mixed_content)): if (mixed_content[str].isdigit()): num_list.append(mixed_content[str]) else: string_list.append(mixed_content[str]) </code></pre> <p>can we use else block in lis...
2
2016-10-19T19:41:45Z
40,140,340
<p>Let's initialize variables:</p> <pre><code>&gt;&gt;&gt; mixed_content='ab42c1'; num_list=[]; string_list=[] </code></pre> <p>Let's create the lists that you want with a single list comprehension:</p> <pre><code>&gt;&gt;&gt; [num_list.append(c) if c.isdigit() else string_list.append(c) for c in mixed_content] [Non...
1
2016-10-19T19:51:06Z
[ "python", "python-2.7", "python-3.x", "list-comprehension" ]
if-else in python list comprehensions
40,140,202
<p>is it possible to write list comprehensions for the following python code:</p> <pre><code>for str in range(0,len(mixed_content)): if (mixed_content[str].isdigit()): num_list.append(mixed_content[str]) else: string_list.append(mixed_content[str]) </code></pre> <p>can we use else block in lis...
2
2016-10-19T19:41:45Z
40,140,383
<p>Here is an example of using <code>x if b else y</code> in a list comprehension.</p> <pre><code>mixed_content = "y16m10" num_list, string_list = zip( *[(ch, None) if ch.isdigit() else (None, ch) for ch in mixed_content]) num_list = filter(None, num_list) string_list = filter(None, string_list) print num_list, s...
2
2016-10-19T19:53:56Z
[ "python", "python-2.7", "python-3.x", "list-comprehension" ]
Python Print %s
40,140,288
<p>I've got a little Problem with my Python code.</p> <pre><code>elif option in ['2','zwei','two']: packagelist = os.popen("adb -d shell pm list packages").read() print packagelist print " " package = parseInput(PACKAGE_QST) packagelist.index %package print ("Your packag...
-5
2016-10-19T19:47:43Z
40,140,318
<p>You must pass a tuple when using <code>%</code>:</p> <pre><code># notice how package is wrapped in () print ("Your package is: %s" % (package)) # and do the same when you call os.system() os.system ("adb -d backup %s" % (package)) </code></pre>
-3
2016-10-19T19:49:43Z
[ "python", "string", "adb" ]
Matplotlib: Sharing axes when having 3 graphs 2 at the left and 1 at the right
40,140,397
<p>I have following graph: <a href="https://i.stack.imgur.com/Vqd85.png" rel="nofollow"><img src="https://i.stack.imgur.com/Vqd85.png" alt="enter image description here"></a></p> <p>However, I want that graphs 221 and 223 share the same x axis. I have the following code:</p> <pre><code>self.fig_part_1 = plt.figure() ...
0
2016-10-19T19:55:01Z
40,140,568
<p>Just use <code>plt.subplots</code> (different from <code>plt.subplot</code>) to define all your axes, with the option <code>sharex=True</code>:</p> <pre><code>f, axes = plt.subplots(2,2, sharex=True) plt.subplot(122) plt.show() </code></pre> <p>Note that the second call with larger subplot array overlay the preced...
1
2016-10-19T20:05:43Z
[ "python", "matplotlib" ]
POST XML file with requests
40,140,412
<p>I'm getting:</p> <pre><code>&lt;error&gt;You have an error in your XML syntax... </code></pre> <p>when I run this python script I just wrote (I'm a newbie)</p> <pre><code>import requests xml = """xxx.xml""" headers = {'Content-Type':'text/xml'} r = requests.post('https://example.com/serverxml.asp', data=xml) ...
0
2016-10-19T19:55:38Z
40,140,503
<p>You want to give the XML data from a file to <code>requests.post</code>. But, this function will not open a file for you. It expects you to pass a file object to it, not a file name. You need to open the file before you call requests.post.</p> <p>Try this:</p> <pre><code>import requests # Set the name of the XML ...
2
2016-10-19T20:01:58Z
[ "python", "python-requests" ]
How can I extend the unit selection logic in my RTS game to apply to multiple units?
40,140,432
<p>Currently if you left-click on the unit, it becomes 'selected' (or 'de-selected'), and a green square is drawn around it. Then when you right-click somewhere on the screen, the unit moves neatly into the square in the location that you clicked.</p> <p>Also if you use the up, down, left or right keys it will scroll ...
0
2016-10-19T19:57:17Z
40,142,078
<p>There are few things to do:</p> <ol> <li>Change variables <code>character_*</code> to object that holds all data about the unit.</li> <li>Create array of units / characters. That way each unit in array can have unique position, velocity ets. </li> <li>Everywhere in code where you check <code>character_*</code>, cha...
1
2016-10-19T21:48:59Z
[ "python", "python-3.x", "pygame", "2d-games" ]
Python Homework score of each name pair
40,140,498
<p>I've got an exercise to do and I don't know why, it is not working...</p> <p>I really hope someone could help me</p> <p>Thank you in advance</p> <blockquote> <p>Calculate and display the score of each name pair (using the lists list_2D = [“John”,“Kate”,“Oli”]and[“Green”, “Fletcher”,“Nels...
-2
2016-10-19T20:01:39Z
40,141,075
<p>I have changed some aspects because I am not going to do your homework for you, but I understand just starting out on Stack and learning to program. It isn't easy so here's some explanation.</p> <p>So what you will want to do is loop through all of the possible combinations of the first and last names.</p> <p>I wo...
0
2016-10-19T20:36:54Z
[ "python", "python-2.7", "python-3.x", "cloud9-ide", "cloud9" ]
Report progress to QProgressBar using variable from an imported module
40,140,531
<p>I have a PyQT GUI application <code>progress_bar.py</code>with a single progressbar and an external module <code>worker.py</code> with a <code>process_files()</code> function which does some routine with a list of files and reports current progress using <code>percent</code> variable.</p> <p>What I want to do is to...
1
2016-10-19T20:03:33Z
40,140,793
<p>Make the <code>process_files</code> function a generator function that <em>yields</em> a value (the progress value) and pass it as a callback to a method in your <code>Window</code> class that updates the progress bar value. I have added a <code>time.sleep</code> call in your function so you can observe the progress...
2
2016-10-19T20:19:41Z
[ "python", "callback", "pyqt" ]
Print random line from txt file?
40,140,660
<p>I'm using random.randint to generate a random number, and then assigning that number to a variable. Then I want to print the line with the number I assigned to the variable, but I keep getting the error:</p> <blockquote> <p>list index out of range</p> </blockquote> <p>Here's what I tried:</p> <pre><code>f = ope...
1
2016-10-19T20:11:11Z
40,140,722
<p>You want to use <code>random.choice</code></p> <pre><code>import random with open(filename) as f: lines = f.readlines() print(random.choice(lines)) </code></pre>
6
2016-10-19T20:14:51Z
[ "python", "random" ]
Print random line from txt file?
40,140,660
<p>I'm using random.randint to generate a random number, and then assigning that number to a variable. Then I want to print the line with the number I assigned to the variable, but I keep getting the error:</p> <blockquote> <p>list index out of range</p> </blockquote> <p>Here's what I tried:</p> <pre><code>f = ope...
1
2016-10-19T20:11:11Z
40,140,814
<p>This code is correct, assuming that you meant to pass a string to <code>open</code> function, and that you have no space after the dot... However, be careful to the indexing in Python, namely it starts at 0 and not 1, and then ends at <code>len(your_list)-1</code>.</p> <p>Using <code>random.choice</code> is better,...
0
2016-10-19T20:20:37Z
[ "python", "random" ]
Print random line from txt file?
40,140,660
<p>I'm using random.randint to generate a random number, and then assigning that number to a variable. Then I want to print the line with the number I assigned to the variable, but I keep getting the error:</p> <blockquote> <p>list index out of range</p> </blockquote> <p>Here's what I tried:</p> <pre><code>f = ope...
1
2016-10-19T20:11:11Z
40,140,827
<pre><code>f = open(filename. txt) lines = f.readlines() rand_line = random.randint(0, (len(lines) - 1)) # https://docs.python.org/2/library/random.html#random.randint print lines[rand_line] </code></pre>
0
2016-10-19T20:21:17Z
[ "python", "random" ]
Django get related objects ManyToMany relationships
40,140,733
<p>i have two models:</p> <pre><code>class CartToys(models.Model): name = models.CharField(max_length=350) quantity = models.IntegerField() class Cart(models.Model): cart_item = models.ManyToManyField(CartToys) </code></pre> <p>i want to get all related toys to this cart. how can i do this </p>
0
2016-10-19T20:15:31Z
40,140,796
<p>you would use...</p> <pre><code>cart = Cart.objects.first() objects = cart.cart_item.all() # this line return all related objects for CartToys # and in reverse cart_toy = CartToys.objects.first() carts = cart_toy.cart_set.all() # this line return all related objects for Cart </code></pre>
1
2016-10-19T20:19:46Z
[ "python", "django" ]
How do you look for a line in a text file, from a sentence a user has inputted, by using its keywords?
40,140,821
<pre><code>a=input("Please enter your problem?") problem= () with open('solutions.txt', 'r') as searchfile: for line in searchfile: if problem in line: print (line) </code></pre> <p>Can someone please help me on how to get the keywords from the inputed string by the user. Thanks. I need help o...
0
2016-10-19T20:21:01Z
40,141,002
<p>I assume your keywords is meant to be a list? </p> <p>Then you use <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow"><code>any()</code></a> to check if any word out of the keywords is in the line. </p> <pre><code>a=input("Please enter your problem?") problem= ['#keywords', 'not', 'sure'...
2
2016-10-19T20:31:51Z
[ "python", "python-3.x" ]
How do you look for a line in a text file, from a sentence a user has inputted, by using its keywords?
40,140,821
<pre><code>a=input("Please enter your problem?") problem= () with open('solutions.txt', 'r') as searchfile: for line in searchfile: if problem in line: print (line) </code></pre> <p>Can someone please help me on how to get the keywords from the inputed string by the user. Thanks. I need help o...
0
2016-10-19T20:21:01Z
40,141,278
<p>I am not sure I understood the question but is this what you want?. this will take the line containing the most words from the user input:</p> <pre><code>problem = a.split(' ') max_num, current_num = 0,0 #max_num count the maximum apparition of words from the input in the line| current_num count the current number...
0
2016-10-19T20:49:21Z
[ "python", "python-3.x" ]
Python creating objects from a class using multiple files
40,140,883
<p>I need to use a 'Student' class with 5 variables and create objects using more than one file. </p> <p>The text files: (Students.txt)</p> <pre><code>Last Name Midle Name First Name Student ID ---------------------------------------------- Howard Moe howar1m Howard ...
1
2016-10-19T20:24:35Z
40,141,068
<p>First read your student/course and create a dictionary: key=student, value=list of courses</p> <p>The format is strange but the code below has been tested and works (maybe not as robust as it should, though). Read line by line, course first, and list of students. Add to dictionary (create empty list if key doesn't ...
1
2016-10-19T20:36:21Z
[ "python", "file", "object" ]
Java like function getLeastSignificantBits() & getMostSignificantBits in Python?
40,140,892
<p>Can someone please help me out in forming an easy function to extract the leastSignificant &amp; mostSignificant bits in Python?</p> <p>Ex code in Java:</p> <pre><code>UUID u = UUID.fromString('a316b044-0157-1000-efe6-40fc5d2f0036'); long leastSignificantBits = u.getLeastSignificantBits(); private UUID(byte[] dat...
0
2016-10-19T20:25:10Z
40,141,219
<p><code>efe640fc5d2f0036</code> in decimal is 17286575672347525174. Substract <code>0x10000000000000000</code> from it &amp; negate: you get <code>-1160168401362026442</code></p> <pre><code>int("efe640fc5d2f0036",16)-0x10000000000000000 -&gt; -1160168401362026442 </code></pre> <p>Note that it's only guesswork but se...
1
2016-10-19T20:45:32Z
[ "python", "bitmap", "bit" ]
What do &=, |=, and ~ do in Pandas
40,140,933
<p>I frequently see code like this at work:</p> <pre><code>overlap &amp;= group['ADMSN_DT'].loc[i] &lt;= group['epi_end'].loc[j] </code></pre> <p>My question is what do operators such as <code>&amp;=</code>, <code>|=</code>, and <code>~</code> do in pandas?</p>
3
2016-10-19T20:27:27Z
40,141,039
<p>From the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">documentation</a></p> <blockquote> <p>The operators are: | for or, &amp; for and, and ~ for not. These must be grouped by using parentheses.</p> </blockquote> <p><a href="https://docs.python.org/3/refer...
2
2016-10-19T20:34:39Z
[ "python", "python-2.7", "pandas" ]
Numpy: How to vectorize parameters of a functional form of a function applied to a data set
40,140,942
<p>Ultimately, I want to remove all explicit loops in the code below to take advantage of numpy vectorization and function calls in C instead of python.</p> <p>Below is simplified for uses of numpy in python. I have the following quadratic function:</p> <pre><code>def quadratic_func(a,b,c,x): return a*x*x + b*x +...
4
2016-10-19T20:27:52Z
40,141,272
<p>One approach using a combination of <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> and <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p> <pre><code>np.einsum('ij,jk-&...
1
2016-10-19T20:48:48Z
[ "python", "numpy", "vectorization", "numpy-broadcasting" ]
Python/Spyder: General Working Directory
40,140,958
<p>So far I have code that opens a text file, manipulates it into a pandas data file, then exports to excel.</p> <p>I'm sharing this code with other people, and we all have the same working directory within Spyder. All the code works fine, the only lines I want to manipulate are the opening of the file, and the export...
1
2016-10-19T20:28:31Z
40,141,235
<p>The answer that you are technically looking for is using <code>os.chdir()</code> as follows</p> <pre><code>import os os.chdir('.', 'data') #THE REST OF THE CODE IS THE SAME with open(r'file.txt', 'r') as data_file: </code></pre> <p>A safer answer would however be </p> <pre><code>def doTheThing(fName): return ...
1
2016-10-19T20:46:39Z
[ "python", "python-3.x", "directory", "spyder" ]
HTML select options from a python list
40,141,000
<p>I'm writing a python cgi script to setup a Hadoop cluster. I want to create an HTML select dropdown where the options are taken from a python list. Is this possible?? I've looked around a lot. Couldn't find any proper answer to this.</p> <p>This is what i've found so far on another thread...</p> <pre><code>def m...
1
2016-10-19T20:31:39Z
40,141,433
<p>You need to generate a list of "option"s and pass them over to your javascript to make the list</p> <pre><code>values = {"A": "One", "B": "Two", "C": "Three"} options = [] for value in sorted(values.keys()): options.append("&lt;option value='" + value + "'&gt;" + values[value] + "&lt;/option&gt;") </code></pre...
1
2016-10-19T20:59:15Z
[ "python", "html", "cgi" ]
Use a xref of values to sub into tuple based on value - Python
40,141,134
<p>I have a list of xref values</p> <pre><code>internal_customer = {'01':'11', '03':'33', '05':'55', '07':'77', '08':'88', '06':'66', '09':'22', '11':'18', '12':'19'} </code></pre> <p>that I would like to use to sub a value in a tuple:</p> <pre><code>('03', 'S/N A1631703') </code></pre> <p>So my resulting tuple wou...
1
2016-10-19T20:41:05Z
40,141,206
<p>Unpack and access the dict using the first element, presuming you have an list of tuples:</p> <pre><code>internal_customer = {'01':'11', '03':'33', '05':'55', '07':'77', '08':'88', '06':'66', '09':'22', '11':'18', '12':'19'} lst = [('03', 'S/N A1631703'),('05', 'S/N A1631703')] lst[:] = ((internal_customer[a], b)...
2
2016-10-19T20:44:56Z
[ "python" ]
Python: Finding palindromes in a list
40,141,171
<pre><code>def num_sequence (num1, num2): #This function takes the lower and upper bound and builds a list. array = [] for i in range(num2 + 1): if i &gt;= num1: array.append(i) return array def inverted_sequence (array): #This function takes the previous and list inverts the numbers in...
0
2016-10-19T20:43:24Z
40,142,008
<p>I assume that you mean that you want the final list to contain the lowest palindrome in the sequence formed by the sum of the previous number in the sequence and the result of reversing the previous number in the sequence.</p> <p>If so, here is some code (not bulletproof):</p> <pre><code>#checks if a number is a p...
0
2016-10-19T21:44:04Z
[ "python", "python-3.x" ]
JavaScript double backslash in WebSocket messages
40,141,181
<p>I'm sending binary data over WebSocket to a Python application. This binary data is decoded by calling <code>struct.unpack("BH", data")</code> on it, requiring a 4-long bytes object.<br> The problem I'm currently facing is, that all data contains duplicate backslashes, even in <code>arraybuffer</code> mode and is th...
0
2016-10-19T20:44:07Z
40,141,584
<p>You should define the message as bytes and not as string:</p> <pre><code>var buffer = new Int8Array([5,0,0,0]) this.webSocket.send(buffer.buffer) </code></pre>
1
2016-10-19T21:09:56Z
[ "javascript", "python", "struct", "byte" ]
selenium run chrome on raspberry pi
40,141,260
<p>If your seeing this I guess you are looking to run chromium on a raspberry pi with selenium.</p> <p>like this <code>Driver = webdriver.Chrome("path/to/chomedriver")</code> or like this <code>webdriver.Chrome()</code></p>
1
2016-10-19T20:48:21Z
40,141,261
<p>I have concluded that after hours and a hole night of debugging that you can't because there is no chromedriver compatible with a raspberry pi processor. Even if you download the linux 32bit. You can confirm this by running this in a terminal window <code>path/to/chromedriver</code> it will give you this error </p> ...
1
2016-10-19T20:48:21Z
[ "python", "selenium", "raspberry-pi" ]
Convert multiple columns to one column
40,141,353
<p>I'm looking to merge multiple columns to one column.</p> <p>Here's my current dataset :</p> <pre><code>Column A Column B Column C a1 b1 c1 b2 a2 e2 </code></pre> <p>I am looking for the following as output</p> <pre><code>Column D a1 b1 c1 b2 a2 e2 </code></p...
1
2016-10-19T20:54:39Z
40,141,589
<p>With the data that you provided, in the format you provided, you could do this with:</p> <pre><code>data.frame(ColumnD=c(t(df))) ColumnD 1 a1 2 b1 3 c1 4 b2 5 a2 6 e2 </code></pre> <p>We transpose the data, then combine it.</p>
0
2016-10-19T21:10:23Z
[ "python", "list" ]
Easier way to check if a string contains only one type of letter in python
40,141,540
<p>I have a string <code>'829383&amp;&amp;*&amp;@&lt;&lt;&lt;&lt;&gt;&gt;&lt;&gt;GG'</code>. I want a way to measure if a string has only one type of letter. For example the string above would return True, because it only has two Gs, but this string, <code>'829383&amp;&amp;*&amp;@&lt;&lt;&lt;&lt;&gt;&gt;&lt;&gt;GGAa'</...
1
2016-10-19T21:06:36Z
40,141,601
<p>use <code>filter</code> with <code>str.isalpha</code> function to create a sublist containing only letters, then create a set. Final length must be one or your condition isn't met.</p> <pre><code>v="829383&amp;&amp;&amp;@&lt;&lt;&lt;&lt;&gt;&gt;&lt;&gt;GG" print(len(set(filter(str.isalpha,v)))==1) </code></pre>
1
2016-10-19T21:11:05Z
[ "python", "string", "python-3.x" ]
Easier way to check if a string contains only one type of letter in python
40,141,540
<p>I have a string <code>'829383&amp;&amp;*&amp;@&lt;&lt;&lt;&lt;&gt;&gt;&lt;&gt;GG'</code>. I want a way to measure if a string has only one type of letter. For example the string above would return True, because it only has two Gs, but this string, <code>'829383&amp;&amp;*&amp;@&lt;&lt;&lt;&lt;&gt;&gt;&lt;&gt;GGAa'</...
1
2016-10-19T21:06:36Z
40,142,143
<p>Jean-Francois's answer is what I'd actually use 99% of the time, but for cases where the string is <em>huge</em> you might want a solution that will return as soon as the second unique character is detected, instead of finishing processing:</p> <pre><code>from future_builtins import map, filter # Only on Py2, to g...
0
2016-10-19T21:55:01Z
[ "python", "string", "python-3.x" ]
Python regex : trimming special characters
40,141,572
<p>Is it possible to remove special characters using regex?</p> <p>I'm attempting to trim:</p> <pre><code>\n\t\t\t\t\t\t\t\t\t\tButte County High School\t\t\t\t\t\t\t\t\t </code></pre> <p>down to:</p> <pre><code>Butte County High School </code></pre> <p>using </p> <pre><code>regexform = re.sub("[A-Z]+[a-z]+\s*...
1
2016-10-19T21:09:07Z
40,141,588
<p>You do not need regex for this simple task. Use <a href="https://docs.python.org/2/library/string.html#string.lstrip" rel="nofollow"><code>string.strip()</code></a> instead. For example:</p> <pre><code>&gt;&gt;&gt; my_string = '\t\t\t\t\t\t\t\t\t\tButte County High School\t\t\t\t\t\t\t\t\t' &gt;&gt;&gt; my_string.s...
3
2016-10-19T21:10:19Z
[ "python", "regex", "expression" ]
Python regex : trimming special characters
40,141,572
<p>Is it possible to remove special characters using regex?</p> <p>I'm attempting to trim:</p> <pre><code>\n\t\t\t\t\t\t\t\t\t\tButte County High School\t\t\t\t\t\t\t\t\t </code></pre> <p>down to:</p> <pre><code>Butte County High School </code></pre> <p>using </p> <pre><code>regexform = re.sub("[A-Z]+[a-z]+\s*...
1
2016-10-19T21:09:07Z
40,141,636
<p>Except you have reasons to want to use regex, you can remove all edge white space with <code>.strip()</code> function in python</p>
0
2016-10-19T21:14:17Z
[ "python", "regex", "expression" ]
Python regex : trimming special characters
40,141,572
<p>Is it possible to remove special characters using regex?</p> <p>I'm attempting to trim:</p> <pre><code>\n\t\t\t\t\t\t\t\t\t\tButte County High School\t\t\t\t\t\t\t\t\t </code></pre> <p>down to:</p> <pre><code>Butte County High School </code></pre> <p>using </p> <pre><code>regexform = re.sub("[A-Z]+[a-z]+\s*...
1
2016-10-19T21:09:07Z
40,141,638
<p>If you're really set on using regular expressions:</p> <pre><code>re.sub(r'^\s+|\s+$', '', schoolstring) </code></pre> <p>This will work for:</p> <pre><code>' this is a test ' # multiple leading and trailing spaces ' this is a test ' # one leading and trailing space 'this is a test' # no leadi...
1
2016-10-19T21:14:25Z
[ "python", "regex", "expression" ]
Yes or No answer from user with Validation and restart option?
40,141,660
<p>(py) At the moment, the code below does not validate/output error messages when the user inputs something other than the two choices "y" and "n" because it's in a while loop. </p> <pre><code>again2=input("Would you like to calculate another GTIN-8 code? Type 'y' for Yes and 'n' for No. ").lower() #** while aga...
0
2016-10-19T21:16:09Z
40,141,714
<pre><code>def get_choice(prompt="Enter y/n?",choices=["Y","y","n","N"],error="Invalid choice"): while True: result = input(prompt) if result in choices: return result print(error) </code></pre> <p>is probably a nice generic way to approach this problem</p> <pre><code>result = get_choice("...
1
2016-10-19T21:20:36Z
[ "python", "validation", "loops", "while-loop", "restart" ]
Yes or No answer from user with Validation and restart option?
40,141,660
<p>(py) At the moment, the code below does not validate/output error messages when the user inputs something other than the two choices "y" and "n" because it's in a while loop. </p> <pre><code>again2=input("Would you like to calculate another GTIN-8 code? Type 'y' for Yes and 'n' for No. ").lower() #** while aga...
0
2016-10-19T21:16:09Z
40,141,720
<p>A recursive solution:</p> <pre><code>def get_input(): ans = input('Y/N? ') #Use raw_input in python2 if ans.lower() in ('y', 'n'): return ans else: print('Please try again.') return get_input() </code></pre> <p>If they're really stubborn this will fail when it reaches maximum re...
0
2016-10-19T21:21:20Z
[ "python", "validation", "loops", "while-loop", "restart" ]
Design: Google OAuth using AngularJS and Flask
40,141,705
<p>I am building a web application using AngularJS on the frontend and Python with Flask on the server side. I am trying to implement the OpenID/OAuth login feature following the documentation available on <a href="https://developers.google.com/identity/protocols/OpenIDConnect" rel="nofollow">google developers site</a>...
0
2016-10-19T21:19:34Z
40,141,944
<p>I gave up with manual implementation. There is a ready to use lib: <a href="https://github.com/sahat/satellizer" rel="nofollow">Satellizer</a> as well as server implementation (for Python example see the docs).</p>
0
2016-10-19T21:39:05Z
[ "javascript", "python", "angularjs", "google-app-engine", "oauth" ]
Sending Function as Argument to Another Function
40,141,729
<p>I have came across this logic:</p> <pre><code>def f2(f): def g(arg): return 2 * f(arg) return g def f1(arg): return arg + 1 f_2 = f2(f1) print f_2(3) </code></pre> <p>From a first glance it may seem it is a very simple code. But it takes some time to figure out what is going on here. Sending a func...
0
2016-10-19T21:22:00Z
40,141,769
<p>The passing of functions to other functions is a common idiom in so-called functional programming languages like LISP, Scheme, Haskell, etc. Python is sometimes referred to as a "multi-paradigm language" because it has some features of functional languages (as well as of imperative/structured and object-oriented lan...
2
2016-10-19T21:26:33Z
[ "python" ]
Getting combinations back from memoized subset-sum algorithm?
40,141,753
<p>I've been working on a pretty basic subset sum problem. Given a sum (say, s=6) and the numbers ((1:s), so, [1,2,3,4,5]), I had to find the total number of combinations that totalled s (so: [1,5], [2,4], [1,2,3]). It was quite easy to satisify the requirements of the problem by doing a brute-force approach. For my ow...
0
2016-10-19T21:23:57Z
40,142,157
<p>You may simplify your problem using <a href="https://docs.python.org/2/library/itertools.html#itertools.combinations" rel="nofollow"><code>itertools.combinations()</code></a> as:</p> <pre><code>&gt;&gt;&gt; from itertools import combinations &gt;&gt;&gt; s = 6 &gt;&gt;&gt; my_list = range(1, s) # Value of 'my_list'...
0
2016-10-19T21:55:43Z
[ "python", "algorithm", "memoization", "subset-sum" ]
Django ImportError No module named x.settings
40,141,828
<p>I have the following structure:</p> <pre><code>mysite -&gt; manage.py -&gt; mysite (again) -&gt; __init__.py -&gt; wsgi.py -&gt; settings.py etc -&gt; myapp -&gt; __init__.py -&gt; myscript.py -&gt; models.py etc </code></pre> <p>Wh...
0
2016-10-19T21:30:25Z
40,141,935
<p>You need to make sure the root of your project is in python path when you run the script. Something like this might help.</p> <pre> import os import sys projpath = os.path.dirname(__file__) sys.path.append(os.path.join(projpath, '..')) </pre>
0
2016-10-19T21:38:28Z
[ "python", "django" ]
How can I manipulate strings in a slice of a pandas MultiIndex
40,141,856
<p>I have a <code>MultiIndex</code> like this:</p> <pre><code> metric sensor variable side foo Speed Left Left speed Right Right speed bar Speed Left Left_Speed Right Right_Speed baz Speed Left ...
2
2016-10-19T21:31:52Z
40,142,490
<p>I found the following method, but i think/hope there must be a more elegant way to achieve that:</p> <pre><code>In [101]: index_saved = df.index </code></pre> <p>Let's sort index in order to get rid of <code>KeyError: 'MultiIndex Slicing requires the index to be fully lexsorted tuple len (3), lexsort depth (0)'</c...
1
2016-10-19T22:23:15Z
[ "python", "pandas" ]
pandas groupby transform behaving differently with seemingly equivalent representations
40,141,881
<p>consider the <code>df</code></p> <pre><code>df = pd.DataFrame(dict(A=['a', 'a'], B=[0, 1])) </code></pre> <p>I expected the following two formulations to be equivalent.</p> <p><strong><em>formulation 1</em></strong> </p> <pre><code>df.groupby('A').transform(np.mean) </code></pre> <p><a href="https://i.stack.im...
4
2016-10-19T21:34:18Z
40,142,095
<p>It looks like a bug to me:</p> <pre><code>In [19]: df.groupby('A').transform(lambda x: x.sum()) Out[19]: B 0 1 1 1 In [20]: df.groupby('A').transform(lambda x: len(x)) Out[20]: B 0 2 1 2 In [21]: df.groupby('A').transform(lambda x: x.sum()/len(x)) Out[21]: B 0 0 1 0 </code></pre> <p>PS Pandas vers...
3
2016-10-19T21:50:48Z
[ "python", "pandas" ]
How to do a substring using pandas or numpy
40,141,895
<p>I'm trying to do a substring on data from column "ORG". I only need the 2nd and 3rd character. So for 413 I only need 13. I've tried the following:</p> <pre><code>Attempt 1: dr2['unit'] = dr2[['ORG']][1:2] Attempt 2: dr2['unit'] = dr2[['ORG'].str[1:2] Attempt 3: dr2['unit'] = dr2[['ORG'].str([1:2]) </code></p...
1
2016-10-19T21:35:05Z
40,141,954
<p>Your square braces are not matching and you can easily slice with <code>[-2:]</code>.</p> <p><em>apply</em> <code>str.zfill</code> with a width of 2 to pad the items in the new series:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; ld = [{'REGION': '4', 'ORG': '413'}, {'REGION': '4', 'ORG': '414'}] &...
1
2016-10-19T21:40:24Z
[ "python", "pandas", "numpy" ]
Efficiently summing outer product for 1D NumPy arrays
40,142,004
<p>I have a function of the form</p> <p><a href="https://i.stack.imgur.com/MwLCs.gif" rel="nofollow"><img src="https://i.stack.imgur.com/MwLCs.gif" alt="enter image description here"></a></p> <p>One way to implement this function in numpy is to assemble a matrix to sum over:</p> <pre><code>y = a*b - np.sum(np.outer(...
1
2016-10-19T21:43:45Z
40,142,158
<p>You could use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> -</p> <pre><code>y = a*b - np.einsum('i,i,j-&gt;j',a,b,b) </code></pre> <p>We can also perform <code>a*b</code> and feed to <code>einsum</code> -</p> <pre><code>y = a*b - np.ei...
2
2016-10-19T21:55:43Z
[ "python", "numpy", "optimization" ]
Pandas df to dictionary with values as python lists aggregated from a df column
40,142,024
<p>I have a pandas df containing 'features' for stocks, which looks like this: </p> <p><a href="https://i.stack.imgur.com/fekQs.png" rel="nofollow"><img src="https://i.stack.imgur.com/fekQs.png" alt="features for stocks previous to training neural net"></a></p> <p>I am now trying to create a dictionary with <strong>u...
1
2016-10-19T21:44:57Z
40,142,613
<p>Wouldn't <code>f.set_index('ticker').groupby('sector').groups</code> be what you want?</p> <p>For example:</p> <pre><code>f = DataFrame({ 'ticker': ('t1', 't2', 't3'), 'sector': ('sa', 'sb', 'sb'), 'name': ('n1', 'n2', 'n3')}) groups = f.set_index('ticker').groupby('sector').groups # {'sa'...
2
2016-10-19T22:34:49Z
[ "python", "pandas", "dictionary" ]
How to fix "TypeError: len() of unsized object"
40,142,166
<p>I am getting:</p> <p><strong>TypeError: len() of unsized object</strong></p> <p>after running the following script:</p> <pre><code>from numpy import * v=array(input('Introduce un vector v: ')) u=array(input('Introduce un vector u: ')) nv= len(v) nu= len(u) diferenza= 0; i=0 if nv==nu: while i&lt;nv: ...
-1
2016-10-19T21:56:19Z
40,142,263
<p>Use the arrays' <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.size.html" rel="nofollow"><code>size</code></a> attribute instead:</p> <pre><code>nv = v.size nu = u.size </code></pre> <hr> <p>You also probably want to use <a href="https://docs.scipy.org/doc/numpy/reference/generated/nu...
1
2016-10-19T22:02:47Z
[ "python", "arrays", "numpy" ]
How to fix "TypeError: len() of unsized object"
40,142,166
<p>I am getting:</p> <p><strong>TypeError: len() of unsized object</strong></p> <p>after running the following script:</p> <pre><code>from numpy import * v=array(input('Introduce un vector v: ')) u=array(input('Introduce un vector u: ')) nv= len(v) nu= len(u) diferenza= 0; i=0 if nv==nu: while i&lt;nv: ...
-1
2016-10-19T21:56:19Z
40,142,305
<p>The problem is that a <code>numpy</code>-<strong>scalar</strong> has no length. When you use <code>input</code> it returns a string (assuming Python3 here) and that's just converted to a numpy-string when you pass it to <code>numpy.array</code>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.array('...
-2
2016-10-19T22:06:11Z
[ "python", "arrays", "numpy" ]
errors with webdriver.Firefox() with selenium
40,142,194
<p>I am using python 3.5, firefox 45 (also tried 49) and selenium 3.0.1</p> <p>I tried:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() </code></pre> <p>Then I got the error message:</p> <pre><code>C:\Users\A\AppData\Local\Programs\Python\Py...
1
2016-10-19T21:58:32Z
40,143,317
<p>If you are using firefox ver >47.0.1 you need to have the <code>[geckodriver][1]</code> executable in your system path. For earlier versions you want to turn marionette off. You can to so like this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver...
0
2016-10-19T23:50:04Z
[ "python", "selenium", "firefox" ]
Numbers separated by spaces in txt file into python list
40,142,236
<p>I am trying to convert a txt file containing lines of numbers separated by spaces into numbers separated by commas in lists, where each line is a new list of these numbers using Python 3.</p> <p>E.g. txt file contains </p> <blockquote> <p>1 2 3 4 5</p> <p>6 7 8 9 10</p> </blockquote> <p>and I want ...
-3
2016-10-19T22:01:05Z
40,142,467
<p>Following uses plain Python 3 (without NumPy)</p> <pre><code># open file with open('file.txt') as fp: # 1. iterate over file line-by-line # 2. strip line of newline symbols # 3. split line by spaces into list (of number strings) # 4. convert number substrings to int values # 5. convert map objec...
0
2016-10-19T22:21:22Z
[ "python" ]
Build a single list of element from bi-dimensional array list
40,142,259
<p>I'm totally noob to python so please forgive my mistake and lack of vocabulary. Long Story Short, I have the following list of array :</p> <pre><code>[url1, data1][url2, data2][url3, data3]etc... </code></pre> <p>I want to build a simple list of element by only keeping the url. So I'm doing this :</p> <pre><code>...
0
2016-10-19T22:02:40Z
40,142,433
<p>I'm bad at python but I think like this when you result.get('rows'): row is [url1] not url1 Why don't you try extend? Sorry about my silly English ( I'm bat at English too)</p>
-1
2016-10-19T22:18:29Z
[ "python", "arrays" ]
Build a single list of element from bi-dimensional array list
40,142,259
<p>I'm totally noob to python so please forgive my mistake and lack of vocabulary. Long Story Short, I have the following list of array :</p> <pre><code>[url1, data1][url2, data2][url3, data3]etc... </code></pre> <p>I want to build a simple list of element by only keeping the url. So I'm doing this :</p> <pre><code>...
0
2016-10-19T22:02:40Z
40,142,482
<p>If you just want the <code>url</code>, and your data is basically a list of lists then you can just use the <code>index</code> number, in this case <code>[0]</code> as url is the 1st element in a nested list</p> <pre><code>l = [['url1', 'data1'],['url2', 'data2'],['url3', 'data3']] endlist = [] for i in l: endl...
1
2016-10-19T22:22:50Z
[ "python", "arrays" ]
Build a single list of element from bi-dimensional array list
40,142,259
<p>I'm totally noob to python so please forgive my mistake and lack of vocabulary. Long Story Short, I have the following list of array :</p> <pre><code>[url1, data1][url2, data2][url3, data3]etc... </code></pre> <p>I want to build a simple list of element by only keeping the url. So I'm doing this :</p> <pre><code>...
0
2016-10-19T22:02:40Z
40,142,487
<p>If I understood you correctly, you need this:</p> <pre><code>results = [[url_1, data_1], [url_2, data_2], ...] urls = list() for r in results: # r = [url_i, data_i] urls.append(r[0]) </code></pre>
1
2016-10-19T22:23:02Z
[ "python", "arrays" ]
Why to use Lambda to send Function as Argument to Another Function
40,142,302
<p>While digging into <code>lambda</code> I defined this code below:</p> <pre><code>def f2(number, lambda_function): return lambda_function(number) def f1(number): return f2(number, lambda x: x*2) number = 2 print f1(number) </code></pre> <p>While I do agree the code like this looks pretty cool I wonder wh...
1
2016-10-19T22:05:58Z
40,142,356
<p><a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="nofollow"><code>lambda</code></a> functions work like normal function but are used in cases where they will be executed just once. Then, why to create the message body and define the function? For example, sorting the list of tuple...
3
2016-10-19T22:11:17Z
[ "python" ]
How to split files according to a field and edit content
40,142,380
<p>I am not sure if I can do this using unix commands or I need a more complicated code, like python.</p> <p>I have a big input file with 3 columns - id, different sequences (second column) grouped in different groups (3rd column).</p> <pre><code>Seq1 MVRWNARGQPVKEASQVFVSYIGVINCREVPISMEN Group1 Seq2 ...
0
2016-10-19T22:13:40Z
40,142,525
<p>This shell script should do the trick:</p> <pre><code>#!/usr/bin/env bash filename="data.txt" while read line; do id=$(echo "${line}" | awk '{print $1}') sequence=$(echo "${line}" | awk '{print $2}') group=$(echo "${line}" | awk '{print $3}') printf "&gt;${id}\n${sequence}\n" &gt;&gt; "${group}.txt...
0
2016-10-19T22:26:55Z
[ "python", "unix", "split" ]
How to split files according to a field and edit content
40,142,380
<p>I am not sure if I can do this using unix commands or I need a more complicated code, like python.</p> <p>I have a big input file with 3 columns - id, different sequences (second column) grouped in different groups (3rd column).</p> <pre><code>Seq1 MVRWNARGQPVKEASQVFVSYIGVINCREVPISMEN Group1 Seq2 ...
0
2016-10-19T22:13:40Z
40,142,998
<p>AWK will do the trick:</p> <pre><code>awk '{ print "&gt;"$1 "\n" $2 &gt;&gt; $3".txt"}' input.txt </code></pre>
0
2016-10-19T23:15:05Z
[ "python", "unix", "split" ]
Recursive functions : Inversing word
40,142,476
<p>I'm trying to make a simple function that inverses a string using recursion.</p> <p>this is what i tried : </p> <pre><code> def inverse(ch): if ch=='' : return '' else: return ch[len(ch)]+inverse(ch[1:len(ch)-1]) print inverse('hello') </code></pre> <p>And this is w...
1
2016-10-19T22:21:57Z
40,142,510
<p>Check this:</p> <pre><code>ch[len(ch)-1]+inverse(ch[0:len(ch)-1]) </code></pre>
1
2016-10-19T22:24:59Z
[ "python", "recursion" ]
Recursive functions : Inversing word
40,142,476
<p>I'm trying to make a simple function that inverses a string using recursion.</p> <p>this is what i tried : </p> <pre><code> def inverse(ch): if ch=='' : return '' else: return ch[len(ch)]+inverse(ch[1:len(ch)-1]) print inverse('hello') </code></pre> <p>And this is w...
1
2016-10-19T22:21:57Z
40,142,514
<p>You're indexing the string at its length, but remember that indexing is zero based so you'll have to slice at length minus 1 which is the maximum index you can safely use.</p> <p>You can however choose to be oblivious of the length by using <code>[-1]</code> to index the last item:</p> <pre><code>def inverse(ch): ...
3
2016-10-19T22:25:06Z
[ "python", "recursion" ]