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
Issue with pattern program using loops
39,931,798
<p>I'm writing a program that takes two inputs, number of lines and number of cheers as input. The number of lines is how many lines the user wants to print out and the number of cheers are in the format that 1 cheer is the word "GO" and two cheers are two "GO" s ...and their is the word "BUDDY" within two neighboring GO's. And each new line has to be indented 3 spaces more then the one before. And this is the program I've come up with:</p> <pre><code>lines = input("Lines= ") cheers = input("Cheers= ") if cheers == 1: i = 1 space = 0 S = "" while i&lt;=lines: S=S+(" "*space)+"GO \n" i += 1 space+=3 print S else: n = 1 cheer1 = "GO BUDDY " cheer2 = "GO" space = 0 while n&lt;= cheers: print (" "*space)+(cheer1*cheers)+cheer2 space+=3 n += 1 </code></pre> <p>But the problem with this is that it doesn't print out the right number of GO's in the number of cheers. How can I modify my code to fix this problem? This is the output format I want to get :</p> <p><a href="http://i.stack.imgur.com/7ynbB.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/7ynbB.jpg" alt="This is the format of the ouput I want to get"></a></p>
0
2016-10-08T11:27:11Z
39,931,979
<p>Often in Python you don't need any loops</p> <pre><code>lines = int(input('Lines= ')) cheers = int(input('Cheers= ')) line = ' BUDDY '.join(['GO']*cheers) for i in range(cheers): print(' '*(i*3) + line) </code></pre>
1
2016-10-08T11:48:58Z
[ "python", "python-2.7", "design-patterns" ]
Issue with pattern program using loops
39,931,798
<p>I'm writing a program that takes two inputs, number of lines and number of cheers as input. The number of lines is how many lines the user wants to print out and the number of cheers are in the format that 1 cheer is the word "GO" and two cheers are two "GO" s ...and their is the word "BUDDY" within two neighboring GO's. And each new line has to be indented 3 spaces more then the one before. And this is the program I've come up with:</p> <pre><code>lines = input("Lines= ") cheers = input("Cheers= ") if cheers == 1: i = 1 space = 0 S = "" while i&lt;=lines: S=S+(" "*space)+"GO \n" i += 1 space+=3 print S else: n = 1 cheer1 = "GO BUDDY " cheer2 = "GO" space = 0 while n&lt;= cheers: print (" "*space)+(cheer1*cheers)+cheer2 space+=3 n += 1 </code></pre> <p>But the problem with this is that it doesn't print out the right number of GO's in the number of cheers. How can I modify my code to fix this problem? This is the output format I want to get :</p> <p><a href="http://i.stack.imgur.com/7ynbB.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/7ynbB.jpg" alt="This is the format of the ouput I want to get"></a></p>
0
2016-10-08T11:27:11Z
39,932,051
<p>Try this.</p> <pre><code>def greet(lines, cheers): for i in range (lines): output = (" ") * i + "Go" for j in range (cheers): if cheers == 1: print output break output += "Budddy Go" print output </code></pre> <p>Hope this helps.</p>
1
2016-10-08T11:57:14Z
[ "python", "python-2.7", "design-patterns" ]
JSON sub for loop produces KeyError, but key exists
39,931,910
<p>I'm trying to add the JSON output below into a dictionary, to be saved into a SQL database.</p> <pre><code>{'Parkirisca': [ { 'ID_Parkirisca': 2, 'zasedenost': { 'Cas': '2016-10-08 13:17:00', 'Cas_timestamp': 1475925420, 'ID_ParkiriscaNC': 9, 'P_kratkotrajniki': 350 } } ]} </code></pre> <p>I am currently using the following code to add the value to a dictionary:</p> <pre><code>import scraperwiki import json import requests import datetime import time from pprint import pprint html = requests.get("http://opendata.si/promet/parkirisca/lpt/") data = json.loads(html.text) for carpark in data['Parkirisca']: zas = carpark['zasedenost'] free_spaces = zas.get('P_kratkotrajniki') last_updated = zas.get('Cas_timestamp') parking_type = carpark.get('ID_Parkirisca') if parking_type == "Avtomatizirano": is_automatic = "Yes" else: is_automatic = "No" scraped = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') savetodb = { 'scraped': scraped, 'id': carpark.get("ID_Parkirisca"), 'total_spaces': carpark.get("St_mest"), 'free_spaces': free_spaces, 'last_updated': last_updated, 'is_automatic': is_automatic, 'lon': carpark.get("KoordinataX_wgs"), 'lat': carpark.get("KoordinataY_wgs") } unique_keys = ['id'] pprint savetodb </code></pre> <p>However when I run this, it gets stuck at <code>for zas in carpark["zasedenost"]</code> and outputs the following error:</p> <pre><code>Traceback (most recent call last): File "./code/scraper", line 17, in &lt;module&gt; for zas in carpark["zasedenost"]: KeyError: 'zasedenost' </code></pre> <p>I've been led to believe that <code>zas</code> is in fact now a string, rather than a dictionary, but I'm new to Python and JSON, so don't know what to search for to get a solution. I've also searched here on Stack Overflow for <code>KeyErrror when key exist</code> questions, but they didn't help, and I believe that this might be due to the fact that's a sub for loop.</p> <p>Update: Now, when I swapped the double quotes for single quotes, I get the following error:</p> <pre><code>Traceback (most recent call last): File "./code/scraper", line 17, in &lt;module&gt; free_spaces = zas.get('P_kratkotrajniki') AttributeError: 'unicode' object has no attribute 'get' </code></pre>
0
2016-10-08T11:40:30Z
39,932,458
<p>I fixed up your code:</p> <ol> <li>Added required imports.</li> <li>Fixed the <code>pprint savetodb</code> line which isn't valid Python.</li> <li>Didn't try to iterate over <code>carpark['zasedenost']</code>.</li> </ol> <p>I then added another <code>pprint</code> statement in the <code>for</code> loop to see what's in <code>carpark</code> when the <code>KeyError</code> occurs. From there, the error is clear. (Not all the elements in the array in your JSON contain the <code>'zasedenost'</code> key.)</p> <p>Here's the code I used:</p> <pre><code>import datetime import json from pprint import pprint import time import requests html = requests.get("http://opendata.si/promet/parkirisca/lpt/") data = json.loads(html.text) for carpark in data['Parkirisca']: pprint(carpark) zas = carpark['zasedenost'] free_spaces = zas.get('P_kratkotrajniki') last_updated = zas.get('Cas_timestamp') parking_type = carpark.get('ID_Parkirisca') if parking_type == "Avtomatizirano": is_automatic = "Yes" else: is_automatic = "No" scraped = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') savetodb = { 'scraped': scraped, 'id': carpark.get("ID_Parkirisca"), 'total_spaces': carpark.get("St_mest"), 'free_spaces': free_spaces, 'last_updated': last_updated, 'is_automatic': is_automatic, 'lon': carpark.get("KoordinataX_wgs"), 'lat': carpark.get("KoordinataY_wgs") } unique_keys = ['id'] pprint(savetodb) </code></pre> <p>And here's the output on the iteration where the <code>KeyError</code> occurs:</p> <pre><code>{u'A_St_Mest': None, u'Cena_dan_Eur': None, u'Cena_mesecna_Eur': None, u'Cena_splosno': None, u'Cena_ura_Eur': None, u'ID_Parkirisca': 7, u'ID_ParkiriscaNC': 72, u'Ime': u'P+R Studenec', u'Invalidi_St_mest': 9, u'KoordinataX': 466947, u'KoordinataX_wgs': 14.567929171694901, u'KoordinataY': 101247, u'KoordinataY_wgs': 46.05457609543313, u'Opis': u'2,40 \u20ac /dan', u'St_mest': 187, u'Tip_parkirisca': None, u'U_delovnik': u'24 ur (ponedeljek - petek)', u'U_sobota': None, u'U_splosno': None, u'Upravljalec': u'JP LPT d.o.o.'} Traceback (most recent call last): File "test.py", line 14, in &lt;module&gt; zas = carpark['zasedenost'] KeyError: 'zasedenost' </code></pre> <p>As you can see, the error is quite accurate. There's no key <code>'zasedenost'</code> in the dictionary. If you look through your JSON, you'll see that's true for a number of the elements in that array.</p> <p>I'd suggest a fix, but I don't know what you want to do in the case where this dictionary key is absent. Perhaps you want something like this:</p> <pre><code>zas = carpark.get('zasedenost') if zas is not None: free_spaces = zas.get('P_kratkotrajniki') last_updated = zas.get('Cas_timestamp') else: free_spaces = None last_updated = None </code></pre>
1
2016-10-08T12:39:40Z
[ "python", "json", "list", "for-loop", "dictionary" ]
How do I convert a list to an integer?
39,931,912
<p>This my code:</p> <pre><code>snumA = random.sample([4,8,3], 1) snumB = random.sample([7,2,6], 1) snumC = random.sample([1,5,9], 1) sgnA = random.choice(['+','-','/','*']) sgnB = random.choice(['+','-','/','*']) sgnC = random.choice(['+','-','/','*']) if sgnA == '-' : sum1 = snumA - bnumA print 'minus' if sgnA == '/' : sum1 = snumA / bnumA print 'divide' </code></pre> <p>Whenever I run this code I get an error message telling me that my operands are lists and not integers. I've looked everywhere and I still don't know what to do. Could I have some help, please?</p>
0
2016-10-08T11:40:36Z
39,931,942
<p>Change to :</p> <pre><code>snumA = random.choice([4,8,3]) </code></pre> <p>which will give you an <code>int</code> instead of a <code>list</code>. To understand better the error here is that you try to use lists (cause <code>random.sample</code> returns a list type result) as integers to make arithmetic operations which is false. On the other hand <code>random.choice</code> does what you want but returns an <code>int</code> type result - so you won't get an error.</p>
4
2016-10-08T11:44:13Z
[ "python" ]
How do I convert a list to an integer?
39,931,912
<p>This my code:</p> <pre><code>snumA = random.sample([4,8,3], 1) snumB = random.sample([7,2,6], 1) snumC = random.sample([1,5,9], 1) sgnA = random.choice(['+','-','/','*']) sgnB = random.choice(['+','-','/','*']) sgnC = random.choice(['+','-','/','*']) if sgnA == '-' : sum1 = snumA - bnumA print 'minus' if sgnA == '/' : sum1 = snumA / bnumA print 'divide' </code></pre> <p>Whenever I run this code I get an error message telling me that my operands are lists and not integers. I've looked everywhere and I still don't know what to do. Could I have some help, please?</p>
0
2016-10-08T11:40:36Z
39,932,129
<p>The problem is: <code>snumA = random.sample([4,8,3], 1)</code> returns a list of one element (for example: [3] ). What you can do instead is: Either use <code>snumA = random.choice([4,8,3])</code> which returns directly an integer. Or you get hold of the first element of your list with <code>snumA[0]</code> or directly <code>snumA = random.sample([4,8,3], 1)[0]</code></p>
2
2016-10-08T12:05:17Z
[ "python" ]
How do I convert a list to an integer?
39,931,912
<p>This my code:</p> <pre><code>snumA = random.sample([4,8,3], 1) snumB = random.sample([7,2,6], 1) snumC = random.sample([1,5,9], 1) sgnA = random.choice(['+','-','/','*']) sgnB = random.choice(['+','-','/','*']) sgnC = random.choice(['+','-','/','*']) if sgnA == '-' : sum1 = snumA - bnumA print 'minus' if sgnA == '/' : sum1 = snumA / bnumA print 'divide' </code></pre> <p>Whenever I run this code I get an error message telling me that my operands are lists and not integers. I've looked everywhere and I still don't know what to do. Could I have some help, please?</p>
0
2016-10-08T11:40:36Z
39,932,182
<ol> <li>As suggested before, use random.choice</li> <li>bnumA is not defined. The code below assumes you meant snumB</li> </ol> <p>So the code you are looking for might be:</p> <pre><code>import random snumA = random.choice([4,8,3]) snumB = random.choice([7,2,6]) snumC = random.choice([1,5,9]) operators = {'+':'Plus', '-':'Minus', '/':'Division','*':'Multiplication'} sgnA = random.choice(list(operators.keys())) sgnB = random.choice(list(operators.keys())) sgnC = random.choice(list(operators.keys())) print(eval(str(snumA)+sgnA+str(snumB))) print(operators[sgnA]) </code></pre>
1
2016-10-08T12:10:34Z
[ "python" ]
Old (sklearn 0.17) GMM, DPGM, VBGMM vs new (sklearn 0.18) GaussianMixture and BayesianGaussianMixture
39,931,922
<p>In previous scikit-learn version (0.1.17) I used the following code to automatically determine best Gaussian mixture models and optimize hyperparameters (alpha, covariance type, bic) for unsupervised clustering.</p> <pre><code># Gaussian Mixture Model try: # Determine the most suitable covariance_type lowest_bic = np.infty bic = [] cv_types = ['spherical', 'tied', 'diag', 'full'] for cv_type in cv_types: # Fit a mixture of Gaussians with EM gmm = mixture.GMM(n_components=NUMBER_OF_CLUSTERS, covariance_type=cv_type) gmm.fit(transformed_features) bic.append(gmm.bic(transformed_features)) if bic[-1] &lt; lowest_bic: lowest_bic = bic[-1] best_gmm = gmm best_covariance_type = cv_type gmm = best_gmm except Exception, e: print 'Error with GMM estimator. Error: %s' % e # Dirichlet Process Gaussian Mixture Model try: # Determine the most suitable alpha parameter alpha = 2/math.log(len(transformed_features)) # Determine the most suitable covariance_type lowest_bic = np.infty bic = [] cv_types = ['spherical', 'tied', 'diag', 'full'] for cv_type in cv_types: # Fit a mixture of Gaussians with EM dpgmm = mixture.DPGMM(n_components=NUMBER_OF_CLUSTERS, covariance_type=cv_type, alpha = alpha) dpgmm.fit(transformed_features) bic.append(dpgmm.bic(transformed_features)) if bic[-1] &lt; lowest_bic: lowest_bic = bic[-1] best_dpgmm = dpgmm best_covariance_type = cv_type dpgmm = best_dpgmm except Exception, e: print 'Error with DPGMM estimator. Error: %s' % e # Variational Inference for Gaussian Mixture Model try: # Determine the most suitable alpha parameter alpha = 2/math.log(len(transformed_features)) # Determine the most suitable covariance_type lowest_bic = np.infty bic = [] cv_types = ['spherical', 'tied', 'diag', 'full'] for cv_type in cv_types: # Fit a mixture of Gaussians with EM vbgmm = mixture.VBGMM(n_components=NUMBER_OF_CLUSTERS, covariance_type=cv_type, alpha = alpha) vbgmm.fit(transformed_features) bic.append(vbgmm.bic(transformed_features)) if bic[-1] &lt; lowest_bic: lowest_bic = bic[-1] best_vbgmm = vbgmm best_covariance_type = cv_type vbgmm = best_vbgmm except Exception, e: print 'Error with VBGMM estimator. Error: %s' % e </code></pre> <p>How to accomplish same or similar behaviour with new Gaussian Mixture/ Bayesian GAussian Mixture models introduced in scikit-learn 0.1.18?</p> <p>According to scikit-learn documents, there is no "alpha" parameter anymore, but there is "weight_concentration_prior" parameter instead. Are these the same or not? <a href="http://scikit-learn.org/stable/modules/generated/sklearn.mixture.BayesianGaussianMixture.html#sklearn.mixture.BayesianGaussianMixture" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.mixture.BayesianGaussianMixture.html#sklearn.mixture.BayesianGaussianMixture</a></p> <blockquote> <p>weight_concentration_prior : float | None, optional. The dirichlet concentration of each component on the weight distribution (Dirichlet). The higher concentration puts more mass in the center and will lead to more components being active, while a lower concentration parameter will lead to more mass at the edge of the mixture weights simplex. The value of the parameter must be greater than 0. If it is None, it’s set to 1. / n_components.</p> </blockquote> <p><a href="http://scikit-learn.org/0.17/modules/generated/sklearn.mixture.VBGMM.html" rel="nofollow">http://scikit-learn.org/0.17/modules/generated/sklearn.mixture.VBGMM.html</a></p> <blockquote> <p>alpha: float, default 1 : Real number representing the concentration parameter of the dirichlet distribution. Intuitively, the higher the value of alpha the more likely the variational mixture of Gaussians model will use all components it can.</p> </blockquote> <p>If those two parameters (alpha and weight_concentration_prior) are the same, does it mean that the formula alpha = 2/math.log(len(transformed_features)) still aplies for the weight_concentration_prior = 2/math.log(len(transformed_features))?</p>
0
2016-10-08T11:41:11Z
39,935,265
<p>The BIC score is still available for the classical / EM implementation of GMMs as implemented in the GaussianMixture class.</p> <p>The BayesianGaussianMixture class can automatically tune the number of effective components (n_components should just be big enough) for a given value of <code>alpha</code>.</p> <p>You can also use standard cross validation on the loglikelihood (using the <code>score</code> method of the model).</p>
0
2016-10-08T17:27:08Z
[ "python", "scikit-learn", "cluster-analysis", "gaussian", "unsupervised-learning" ]
Create a DTM from large corpus
39,931,941
<p>I have a set of texts contained in a list, which I loaded from a csv file</p> <p><code>texts=['this is text1', 'this would be text2', 'here we have text3']</code></p> <p>and I would like to create a document-term matrix, by using <em>stemmed words</em>. I have also stemmed them to have:</p> <p><code>[['text1'], ['would', 'text2'], ['text3']]</code></p> <p>What I would like to do is to create a DTM that counts all the stemmed terms (then I would need to do some operations on the rows). </p> <p>For what concerns the unstemmed texts, I am able to make the DTM for short texts, by using the function fn_tdm_df reported <a href="http://stackoverflow.com/questions/15899861/efficient-term-document-matrix-with-nltk">here</a>. What would be more practical for me, though, is to make a DTM of the stemmed words. Just to be clearer, the output I have from applying "fn_tdm_df":</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> be have here is text1 text2 text3 this we would 0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1 1.0 1.0 1 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1 0.0 0.0</code></pre> </div> </div> </p> <p>First, I do not know why I have only two rows, instead of three. Second, my desired output would be something like:</p> <pre><code> text1 would text2 text3 0 1 0 0 0 1 0 1 1 0 2 0 0 0 1 </code></pre> <p>I am sorry but I am really desperate on this output. I also tried to export and reimport the stemmed texts on R, but it doesn't encode correctly. I would probably need to handle DataFrames, as for the huge amount of data. What would you suggest me?</p> <p>----- UPDATE</p> <p>Using CountVectorizer I am not fully satisfied, as I do not get a tractable matrix in which I can normalize and sum rows/columns easily.</p> <p>Here is the code I am using, but it is blocking Python (dataset too large). How can I run it efficiently?</p> <pre><code>vect = CountVectorizer(min_df=0., max_df=1.0) X = vect.fit_transform(texts) print(pd.DataFrame(X.A, columns=vect.get_feature_names()).to_string()) df = pd.DataFrame(X.toarray().transpose(), index = vect.get_feature_names()) </code></pre>
1
2016-10-08T11:44:08Z
39,933,594
<p>Why don't you use <code>sklearn</code>? The <code>CountVectorizer()</code> method <strong>converts a collection of text documents to a matrix of token counts</strong>. What's more it gives a sparse representation of the counts using <code>scipy</code>.</p> <p>You can either give your raw entries to the method or preprocess it as you have done (stemming + stop words).</p> <p>Check this out : <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html" rel="nofollow">CountVectorizer()</a></p>
1
2016-10-08T14:31:50Z
[ "python", "pandas", "scikit-learn", "nltk" ]
How to build python code for mac os x using cx_freeze on windows?
39,932,044
<p>I have installed cx_freeze and it works like a charm to build .exe but I want to make executable file of my python program for mac os x using windows 7. Can you guide me how I can do it using cx_freeze or any other application.</p> <p>I use following code to build .exe</p> <pre><code>from cx_Freeze import setup, Executable build_exe_options = { "packages": [], 'includes': ['lxml.etree', 'lxml._elementpath', 'gzip'], 'excludes' : ['boto.compat.sys', 'boto.compat._sre', 'boto.compat._json', 'boto.compat._locale', 'boto.compat._struct', 'collections.abc', 'boto.compat.array'], "include_files": []} setup( name = "xyz", version = "0.1", description = "", author = "Dengar", options = {"build_exe": build_exe_options}, executables = [Executable("xyz.py")] ) </code></pre>
0
2016-10-08T11:56:20Z
39,932,119
<p>There is no simple way. You need to compile your app on OS X to include the OS X specific libraries (the shared libraries and other dependencies). </p> <p>You need to do this on OS X. </p>
0
2016-10-08T12:04:33Z
[ "python", "windows", "osx", "cx-freeze" ]
How to build python code for mac os x using cx_freeze on windows?
39,932,044
<p>I have installed cx_freeze and it works like a charm to build .exe but I want to make executable file of my python program for mac os x using windows 7. Can you guide me how I can do it using cx_freeze or any other application.</p> <p>I use following code to build .exe</p> <pre><code>from cx_Freeze import setup, Executable build_exe_options = { "packages": [], 'includes': ['lxml.etree', 'lxml._elementpath', 'gzip'], 'excludes' : ['boto.compat.sys', 'boto.compat._sre', 'boto.compat._json', 'boto.compat._locale', 'boto.compat._struct', 'collections.abc', 'boto.compat.array'], "include_files": []} setup( name = "xyz", version = "0.1", description = "", author = "Dengar", options = {"build_exe": build_exe_options}, executables = [Executable("xyz.py")] ) </code></pre>
0
2016-10-08T11:56:20Z
39,932,192
<p>Install VirtalBox.</p> <p>Then follow this guide to install an OS X virtual machine: <a href="http://lifehacker.com/5938332/how-to-run-mac-os-x-on-any-windows-pc-using-virtualbox" rel="nofollow">http://lifehacker.com/5938332/how-to-run-mac-os-x-on-any-windows-pc-using-virtualbox</a></p> <p>Then you will be able to install Python tooling and build your project.</p> <p>You can also find a friend who has OS X and the Python tooling…</p> <p>Here is a guide for OS X : <a href="https://pythonschool.net/pyqt/distributing-your-application-on-mac-os-x/" rel="nofollow">https://pythonschool.net/pyqt/distributing-your-application-on-mac-os-x/</a></p>
0
2016-10-08T12:11:20Z
[ "python", "windows", "osx", "cx-freeze" ]
Mongodb aggregate out of memory
39,932,096
<p>I'm using mongodb aggregate to sample documents from a large collection.</p> <p><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sample/" rel="nofollow">https://docs.mongodb.com/manual/reference/operator/aggregation/sample/</a></p> <p>After making several consecutive calls, I see the memory of mongodb climbing up, and after around the 12th call, it crashes with OutOfMemory error.</p> <p>How can I tell Mongodb to free up the memory after it has finished processing a query?</p>
1
2016-10-08T12:02:29Z
39,934,310
<p>The reason you are asking this is because you don't know how the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sample/" rel="nofollow"><code>$sample</code></a> operator works. As mentioned in the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sample/#behavior" rel="nofollow">documentation</a>, </p> <blockquote> <p>In order to get N random documents:</p> <ul> <li><p>If N is greater than or equal to 5% of the total documents in the collection, $sample performs a collection scan, performs a sort, and then select the top N documents. As such, the $sample stage is subject to the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sort/#sort-memory-limit" rel="nofollow">sort memory restrictions</a>.</p></li> <li><p>If N is less than 5% of the total documents in the collection, If using WiredTiger Storage Engine, $sample uses a pseudo-random cursor over the collection to sample N documents. If using MMAPv1 Storage Engine, $sample uses the _id index to randomly select N documents.</p></li> </ul> </blockquote> <p>So I think the number of random documents you want to get is greater than 5%. What you need is set <code>allowDiskUse</code> to <code>True</code>.</p> <pre><code>collection.aggregate(pipeline, allowDiskUse=True) </code></pre>
1
2016-10-08T15:46:23Z
[ "python", "mongodb", "pymongo", "aggregation-framework" ]
Mongodb aggregate out of memory
39,932,096
<p>I'm using mongodb aggregate to sample documents from a large collection.</p> <p><a href="https://docs.mongodb.com/manual/reference/operator/aggregation/sample/" rel="nofollow">https://docs.mongodb.com/manual/reference/operator/aggregation/sample/</a></p> <p>After making several consecutive calls, I see the memory of mongodb climbing up, and after around the 12th call, it crashes with OutOfMemory error.</p> <p>How can I tell Mongodb to free up the memory after it has finished processing a query?</p>
1
2016-10-08T12:02:29Z
39,934,839
<p>It turns out the issue was the storage engine cache. I'm using an EC2 instance, and it resulted in OOM error there. I've been able to solve it by assigning a smaller cache size like this:</p> <pre><code>mongod --dbpath /a/path/to/db --logpath /a/path/to/log --storageEngine wiredTiger --wiredTigerEngineConfigString="cache_size=200M" --fork </code></pre>
0
2016-10-08T16:43:33Z
[ "python", "mongodb", "pymongo", "aggregation-framework" ]
Global variables code confusion
39,932,120
<p>I am having trouble getting data input from one class to another and I cant seem to get the global function to work. The part i need help with is in the last function but it only works if you have the whole code.</p> <pre><code>import tkinter as tk import os self = tk TITLE_FONT = ("AmericanTypewriter", 18, "bold") #exit function def Exit(): os._exit(0) #Functions end class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) # the container is where we'll stack a bunch of frames # on top of each other, then the one we want visible # will be raised above the others container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (Home, Population, Survival, Birth,NEW, data, Quit): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame # put all of the pages in the same location; # the one on the top of the stacking order # will be the one that is visible. frame.grid(row=0, column=0, sticky="nsew") self.show_frame("Home") def show_frame(self, page_name): '''Show a frame for the given page name''' frame = self.frames[page_name] frame.tkraise() class Home(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Home", font=TITLE_FONT) label.pack(side="top", fill="x", pady=10) button1 = tk.Button(self, text="Population", command=lambda: controller.show_frame("Population")) button5 = tk.Button(self, text = "Quit", command=lambda: controller.show_frame("Quit")) button1.pack() button5.pack() class Population(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Enter Generation 0 Values", font=TITLE_FONT) label.pack(side="top", fill="x", pady=10) #Function def EnterPopulation(): b1 = populationa.get() print (str(populationa.get())) bj = populationj.get() print (str(populationj.get())) bs = populations.get() print (str(populations.get())) def cal(*args): total = population_juveniles + population_adults + population_seniles #Population population = tk.Label(self, text="Value for the Populations") population.pack() labela= tk.Label(self, text= 'Population of Adults') populationa = tk.Entry(self) labela.pack() populationa.pack() population3 = tk.Button(self, text="Enter", command = EnterPopulation) population3.pack() labelj= tk.Label(self, text= 'Population of Juvenile') populationj = tk.Entry(self) labelj.pack() populationj.pack() population5 = tk.Button(self, text="Enter", command = EnterPopulation) population5.pack() labels= tk.Label(self, text= 'Population of Seniles') populations = tk.Entry(self) labels.pack() populations.pack() population6 = tk.Button(self, text="Enter", command = EnterPopulation) population6.pack() buttonS = tk.Button(self, text = "Survival Rates", command=lambda: controller.show_frame("Survival")) buttonS.pack() class Survival(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Survival Rates", font=TITLE_FONT) label.pack(side="top", fill="x", pady=10) def EnterSurvival(*self): S = survivalaa.get() ss = survivalj.get() sss =survivals.get() print(str(survivalaa.get())) #Survival Survival = tk.Label(self, text="Value of Survival Rates between 0-1") Survival.pack() survivala= tk.Label(self, text= 'Survival rates of Adults') survivalaa = tk.Entry(self) survivala.pack() survivalaa.pack() survival69= tk.Button(self, text="Enter", command = EnterSurvival) survival69.pack() survivaljj= tk.Label(self, text= 'Survival rates of Juvenile') survivalj = tk.Entry(self) survivaljj.pack() survivalj.pack() survival5 = tk.Button(self, text="Enter", command = EnterSurvival) survival5.pack() labelss= tk.Label(self, text= 'Survival rates of Seniles') survivals = tk.Entry(self) labelss.pack() survivals.pack() survival6 = tk.Button(self, text="Enter", command = EnterSurvival) survival6.pack() buttonS = tk.Button(self, text = "Birth Rates", command=lambda: controller.show_frame("Birth")) buttonS.pack() class Birth(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Birth Rates", font=TITLE_FONT) label.pack(side="top", fill="x", pady=10) def EnterBirth(*args): Birth1 = Birth2.get() Birtha = tk.Label(self, text="Birth rates") Birtha.pack() Birth2 = tk.Entry(self) Birth2.pack() Birth3 = tk.Button(self, text="OK", command = EnterBirth) Birth3.pack() buttonB = tk.Button(self, text = "New Generatons", command=lambda: controller.show_frame("NEW")) buttonB.pack() #Number of New Generations To Model class NEW(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="New Generations", font=TITLE_FONT) label.pack(side="top", fill="x", pady=10) def EnterNew(*args): print (New2.get()) news = New2.get() New = tk.Label(self, text="Number of New Generatiions 5 - 25") New.pack() New2 = tk.Entry(self) New2.pack() New3 = tk.Button(self, text="OK", command = EnterNew) New3.pack() button = tk.Button(self, text="BACK To Home", command=lambda: controller.show_frame("data")) button.pack() class data(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Data", font=TITLE_FONT) label.pack(side="top", fill="x", pady=10) no = tk.Button(self, text = "No", command = lambda: controller.show_frame("Home")) no.pack() global Birth1 global s global ss global sss global b1 global bj global bs global news spja= b1 * s spjb = bj * ss spjs= bs * sss st = spja + spjb + spjs born = spja* rebirth old = b1 + bj + bs labelold = tk.Label(self, text = 'Orignal populaton'+str(old)) labelold.pack() labelto = tk.Label(self, text='Adults that survived = '+str(spja)+ 'Juveniles = ' +str(spjb)+ 'Seniles = '+str(spjs)+ '/n Total= '+str(st)) labelto.pack() Labelnew= tk.Label(self, text='New Juveniles = '+str(born)) Labelnew.pack() # function for export data class Quit(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller label = tk.Label(self, text="Are you sure you want to quit?", font=TITLE_FONT) label.pack(side="top", fill="x", pady=10) yes = tk.Button(self, text="Yes", command = Exit) yes.pack() no = tk.Button(self, text = "No", command = lambda: controller.show_frame("Home")) no.pack() if __name__ == "__main__": app = SampleApp() app.mainloop( </code></pre>
-3
2016-10-08T12:04:40Z
39,932,375
<p>If you want to use global variables, you need to do this:</p> <pre><code>var1 = &lt;some value&gt; var2 = &lt;some other value&gt; s1 = &lt;yet another value here&gt; # then create your classes class Whatever(tk.whatever_you_want): def __init__(self, arg1, arg2, whatever_arg): global var1 #whis tells the function to use the variable you defined already in the module scope local_var_1 = var1 * 100 # </code></pre> <p>Of course, perhaps you don't know this already, global variables are usually considered bad to start with, but I don't think it matters much for you. It's going to matter when you modify and read the variables from waaay too many places to keep track of, but I'm not sure you're building that big of a script.</p>
0
2016-10-08T12:31:12Z
[ "python", "python-3.x", "global-variables" ]
Django Custom Admin Form bulk save implmentation
39,932,134
<p>I am trying to implement a CSV Import in Django Admin and save bulk data corresponding to the CSV file's rows.</p> <p>This is my Admin class:</p> <pre><code>class EmployeeAdmin(admin.ModelAdmin): list_display = ('user', 'company', 'department', 'designation', 'is_hod', 'is_director') search_fields = ['user__email', 'user__first_name', 'user__last_name'] form = EmployeeForm </code></pre> <p>This is my Form class:</p> <pre><code>class EmployeeForm(forms.ModelForm): company = forms.ModelChoiceField(queryset=Companies.objects.all()) file_to_import = forms.FileField() class Meta: model = Employee fields = ("company", "file_to_import") def save(self, commit=True, *args, **kwargs): try: company = self.cleaned_data['company'] records = csv.reader(self.cleaned_data['file_to_import']) for line in records: # Get CSV Data. # Create new employee. employee = CreateEmployee(...) except Exception as e: raise forms.ValidationError('Something went wrong.') </code></pre> <p>My Employee class is:</p> <pre><code>class Employee(models.Model): user = models.OneToOneField(User, primary_key=True) company = models.ForeignKey(Companies) department = models.ForeignKey(Departments) mobile = models.CharField(max_length=16, default="0", blank=True) gender = models.CharField(max_length=1, default="m", choices=GENDERS) image = models.ImageField(upload_to=getImageUploadPath, null=True, blank=True) designation = models.CharField(max_length=64) is_hod = models.BooleanField(default=False) is_director = models.BooleanField(default=False) </code></pre> <p>When I upload my file and click <code>save</code>, it shows me this error:</p> <p><code>'NoneType' object has no attribute 'save'</code></p> <p>with exception location at:</p> <p><code>/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py in save_model, line 1045</code></p> <p><strong>EDIT</strong> I understand I need to put a call to <code>super.save</code>, but I am unable to figure out where to put the call, because the <a href="https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/#the-save-method" rel="nofollow">doc</a> says that the save method saves and returns the instance. But in my case, there is no single instance that the superclass can save and return. Wham am I missing here?</p> <p>TIA.</p>
0
2016-10-08T12:05:38Z
39,932,272
<p>You should just add the <code>super().save()</code> to the the end of the function:</p> <pre><code>def save(self, *args, commit=True, **kwargs): try: company = self.cleaned_data['company'] records = csv.reader(self.cleaned_data['file_to_import']) for line in records: # Get CSV Data. # Create new employee. employee = CreateEmployee(...) super().save(*args, **kwargs) except Exception as e: raise forms.ValidationError('Something went wrong.') </code></pre>
1
2016-10-08T12:19:23Z
[ "python", "django", "csv" ]
Make the background of an image transparant in Pygame with convert_alpha
39,932,138
<p>I am trying to make the background of an image transparant in a Pygame script. Now the background in my game is black, instead of transparant. I read somewhere else that I could use <code>convert_alpha</code>, but it doesn't seem to work.</p> <p>Here is (the relevant part of) my code:</p> <pre><code>import PIL gameDisplay = pygame.display.set_mode((display_width, display_height)) img = pygame.image.load('snakehead1.bmp').convert_alpha(gameDisplay) </code></pre> <p>What am I doing wrong? Thanks in advance!</p>
0
2016-10-08T12:06:16Z
39,938,626
<p>To make an image transparent you first need an image with alpha values. Be sure that it meets this criteria! I noticed that my images doesn't save the alpha values when saving as bmp. Apparently, <a href="http://www.ehow.com/how_12224322_make-bmp-transparent.html" rel="nofollow">the bmp format do not have native transparency support</a>.</p> <p><strong>If it does contain alpha</strong> you should be able to use the method <code>convert_alpha()</code> to return a Surface with per-pixel alpha. You don't need to pass anything to this method; if no arguments are given <a href="http://www.pygame.org/docs/ref/surface.html#pygame.Surface.convert_alpha" rel="nofollow">the new surface will be optimized for blitting to the current display</a>.</p> <p>Here's an example code demonstrating this:</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode((100, 100)) image = pygame.image.load("temp.png").convert_alpha() while True: screen.fill((255, 255, 255)) for event in pygame.event.get(): if event.type == pygame.QUIT: quit() screen.blit(image, (0, 0)) pygame.display.update() </code></pre> <p>And my image (<em>"temp.png"</em>): </p> <p><a href="http://i.stack.imgur.com/WVlsf.png" rel="nofollow"><img src="http://i.stack.imgur.com/WVlsf.png" alt="enter image description here"></a></p> <p><strong>If it doesn't contain alpha</strong> there are two easy fixes.</p> <ol> <li>Save the image with a different file format, like png.</li> <li>Use colorkeys. This works if you only need to remove the background. It is as easy as putting the line of code <code>image.set_colorkey((0, 0, 0))</code>, which will make all black colors transparent.</li> </ol> <p>You can read more about pygame Surfaces and transparency at <a class='doc-link' href="http://stackoverflow.com/documentation/pygame/7079/drawing-on-the-screen/23788/transparency#t=201610082359454420873">Stack overflows pygame documentation</a>.</p>
1
2016-10-09T00:00:41Z
[ "python", "pygame" ]
How modules know each other
39,932,230
<p>I can plot data from a CSV file with the following code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(x='Column1', y='Column3') plt.show() </code></pre> <p>But I don't understand one thing. How <code>plt.show()</code> knows about <code>df</code>? I'll make more sense to me seeing, somewhere, an expression like:</p> <pre><code>plt = something(df) </code></pre> <p>I have to mention I'm just learning Python.</p>
2
2016-10-08T12:15:48Z
39,932,312
<p>According to <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show" rel="nofollow">http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show</a> , the <code>plt.show()</code> itself doesn't know about the data, you need to pass the data as parameters.</p> <p>What you are seeing should be the plot of pandas library, according to the usage <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#basic-plotting-plot" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/visualization.html#basic-plotting-plot</a>.</p> <p>Hope this solves your question.</p>
1
2016-10-08T12:23:17Z
[ "python", "python-2.7" ]
How modules know each other
39,932,230
<p>I can plot data from a CSV file with the following code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(x='Column1', y='Column3') plt.show() </code></pre> <p>But I don't understand one thing. How <code>plt.show()</code> knows about <code>df</code>? I'll make more sense to me seeing, somewhere, an expression like:</p> <pre><code>plt = something(df) </code></pre> <p>I have to mention I'm just learning Python.</p>
2
2016-10-08T12:15:48Z
39,932,362
<p>From the pandas docs on <a href="https://github.com/pydata/pandas/blob/cebc70cc277462176edea73bb71eaad9f83e9f47/doc/source/visualization.rst#basic-plotting-plot" rel="nofollow">plotting</a>:</p> <blockquote> <p>The <code>plot</code> method on Series and DataFrame is just a simple wrapper around :meth:<code>plt.plot() &lt;matplotlib.axes.Axes.plot&gt;</code></p> </blockquote> <p>So as is, the <code>df.plot</code> method is an highlevel call to <code>plt.plot</code> (using a <em>wrapper</em>), and thereafter, calling <a href="https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/pyplot.py#L240" rel="nofollow"><code>plt.show</code></a> will simply:</p> <blockquote> <p>display all figures and block until the figures have been closed</p> </blockquote> <p>as it would with for all figures plotted with <code>plt.plot</code>.</p> <hr> <p>Therefore, you don't see <code>plt = something(df)</code> as you would expect, because <code>matpotlib.pyplot.plot</code> is being called <em>behind the scene</em> by <code>df.plot</code>.</p>
2
2016-10-08T12:29:36Z
[ "python", "python-2.7" ]
How modules know each other
39,932,230
<p>I can plot data from a CSV file with the following code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') df.plot(x='Column1', y='Column3') plt.show() </code></pre> <p>But I don't understand one thing. How <code>plt.show()</code> knows about <code>df</code>? I'll make more sense to me seeing, somewhere, an expression like:</p> <pre><code>plt = something(df) </code></pre> <p>I have to mention I'm just learning Python.</p>
2
2016-10-08T12:15:48Z
39,932,541
<p>Matplotlib has two "interfaces": a <a href="http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut1.html" rel="nofollow">Matlab-style interface</a> and an <a href="http://jakevdp.github.io/mpl_tutorial/tutorial_pages/tut2.html" rel="nofollow">object-oriented interface</a>. </p> <p>Plotting with the Matlab-style interface looks like this:</p> <pre><code>import matplotlib.pyplot as plt plt.plot(x, y) plt.show() </code></pre> <p>The call to <code>plt.plot</code> implicitly creates a figure and an axes on which to draw. The call to <code>plt.show</code> displays all figures.</p> <p>Pandas is supporting the Matlab-style interface by implicitly creating a figure and axes for you when <code>df.plot(x='Column1', y='Column3')</code> is called.</p> <p>Pandas can also use the more flexible object-oriented interface, in which case your code would look like this:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('test0.csv',delimiter='; ', engine='python') fig, ax = plt.subplots() df.plot(ax=ax, x='Column1', y='Column3') plt.show() </code></pre> <p>Here the axes, <code>ax</code>, is explicitly created and passed to <code>df.plot</code>, which then calls <code>ax.plot</code> under the hood.</p> <p>One case where the object-oriented interface is useful is when you wish to use <code>df.plot</code> more than once while still drawing on the same axes:</p> <pre><code>fig, ax = plt.subplots() df.plot(ax=ax, x='Column1', y='Column3') df2.plot(ax=ax, x='Column2', y='Column4') plt.show() </code></pre>
3
2016-10-08T12:47:15Z
[ "python", "python-2.7" ]
Merge two arrays into an list of arrays
39,932,444
<p>Hi I am trying compile a bunch of arrays that I have in a dictionary using a for loop and I cant seem to find proper solution for this.</p> <p>Essentially what I have in a simplified form:</p> <pre><code>dict['w1']=[1,2,3] dict['w2']=[4,5,6] dict['w3']=[7,8] x = [] for i in range(3): x = np.concatenate([x],[dict['w'+str(i+1)].values],axis=0) </code></pre> <p>what it gives:</p> <pre><code>x = [1,2,3,4,5,6,7,8] </code></pre> <p>what I want:</p> <pre><code>x = [[1,2,3],[4,5,6],[6,7]] </code></pre> <p>I want to use the for loop because I have too many arrays to 'compile' and cant key in them one by one would be very inefficient. This way I can use the created array to plot a boxplot directly.</p> <p>A simiiliar question exists with no loop requirement but still does not have proper solution. <a href="http://stackoverflow.com/questions/12020872/array-of-arrays-python-numpy">Link</a></p>
2
2016-10-08T12:38:15Z
39,932,508
<p>Just <code>append</code> the item to the list. Note, BTW, that <code>range</code> starts with <code>0</code> if you don't specify the start value and treats the end value as an <strong>exclusive</strong> border:</p> <pre><code>x = [] for i in range(1, 4): x.append(dict['w' + str(i)]) </code></pre>
0
2016-10-08T12:43:44Z
[ "python", "arrays", "python-3.x", "numpy", "jupyter" ]
Merge two arrays into an list of arrays
39,932,444
<p>Hi I am trying compile a bunch of arrays that I have in a dictionary using a for loop and I cant seem to find proper solution for this.</p> <p>Essentially what I have in a simplified form:</p> <pre><code>dict['w1']=[1,2,3] dict['w2']=[4,5,6] dict['w3']=[7,8] x = [] for i in range(3): x = np.concatenate([x],[dict['w'+str(i+1)].values],axis=0) </code></pre> <p>what it gives:</p> <pre><code>x = [1,2,3,4,5,6,7,8] </code></pre> <p>what I want:</p> <pre><code>x = [[1,2,3],[4,5,6],[6,7]] </code></pre> <p>I want to use the for loop because I have too many arrays to 'compile' and cant key in them one by one would be very inefficient. This way I can use the created array to plot a boxplot directly.</p> <p>A simiiliar question exists with no loop requirement but still does not have proper solution. <a href="http://stackoverflow.com/questions/12020872/array-of-arrays-python-numpy">Link</a></p>
2
2016-10-08T12:38:15Z
39,932,509
<p>One approach would be to get the argsort indices based on the keys and sort the elements/values out of the dictionary using those indices, like so -</p> <pre><code>np.take(dict.values(),np.argsort(dict.keys())) </code></pre> <p>If you need a list as the output, add <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html" rel="nofollow"><code>.tolist()</code></a>.</p> <p>Sample run -</p> <pre><code>In [84]: dict Out[84]: {'w1': [4, 8, 2, 1], 'w2': [1, 3, 8], 'w3': [3, 2]} In [85]: np.take(dict.values(),np.argsort(dict.keys())) Out[85]: array([[4, 8, 2, 1], [1, 3, 8], [3, 2]], dtype=object) In [86]: np.take(dict.values(),np.argsort(dict.keys())).tolist() Out[86]: [[4, 8, 2, 1], [1, 3, 8], [3, 2]] </code></pre>
1
2016-10-08T12:43:46Z
[ "python", "arrays", "python-3.x", "numpy", "jupyter" ]
Merge two arrays into an list of arrays
39,932,444
<p>Hi I am trying compile a bunch of arrays that I have in a dictionary using a for loop and I cant seem to find proper solution for this.</p> <p>Essentially what I have in a simplified form:</p> <pre><code>dict['w1']=[1,2,3] dict['w2']=[4,5,6] dict['w3']=[7,8] x = [] for i in range(3): x = np.concatenate([x],[dict['w'+str(i+1)].values],axis=0) </code></pre> <p>what it gives:</p> <pre><code>x = [1,2,3,4,5,6,7,8] </code></pre> <p>what I want:</p> <pre><code>x = [[1,2,3],[4,5,6],[6,7]] </code></pre> <p>I want to use the for loop because I have too many arrays to 'compile' and cant key in them one by one would be very inefficient. This way I can use the created array to plot a boxplot directly.</p> <p>A simiiliar question exists with no loop requirement but still does not have proper solution. <a href="http://stackoverflow.com/questions/12020872/array-of-arrays-python-numpy">Link</a></p>
2
2016-10-08T12:38:15Z
39,932,524
<p>Comprehension:</p> <pre><code># using name as "dict" is not proper use "_dict" otherwise. dict['w1']=[1,2,3] dict['w2']=[4,5,6] dict['w3']=[7,8] x = [dict["w"+str(i)] for i in range(1, 4)] </code></pre> <p>gives output:</p> <pre><code>[[1, 2, 3], [4, 5, 6], [7, 8]] </code></pre>
2
2016-10-08T12:45:37Z
[ "python", "arrays", "python-3.x", "numpy", "jupyter" ]
Merge two arrays into an list of arrays
39,932,444
<p>Hi I am trying compile a bunch of arrays that I have in a dictionary using a for loop and I cant seem to find proper solution for this.</p> <p>Essentially what I have in a simplified form:</p> <pre><code>dict['w1']=[1,2,3] dict['w2']=[4,5,6] dict['w3']=[7,8] x = [] for i in range(3): x = np.concatenate([x],[dict['w'+str(i+1)].values],axis=0) </code></pre> <p>what it gives:</p> <pre><code>x = [1,2,3,4,5,6,7,8] </code></pre> <p>what I want:</p> <pre><code>x = [[1,2,3],[4,5,6],[6,7]] </code></pre> <p>I want to use the for loop because I have too many arrays to 'compile' and cant key in them one by one would be very inefficient. This way I can use the created array to plot a boxplot directly.</p> <p>A simiiliar question exists with no loop requirement but still does not have proper solution. <a href="http://stackoverflow.com/questions/12020872/array-of-arrays-python-numpy">Link</a></p>
2
2016-10-08T12:38:15Z
39,932,565
<p>If you mean lists and not dictionarys, then you're looking for the zip command.</p> <p>Zip (w1,w2,w3)</p>
0
2016-10-08T12:50:04Z
[ "python", "arrays", "python-3.x", "numpy", "jupyter" ]
How do I write a program out of provided unittest
39,932,472
<p>I have a unittests for a program. Being new to test driven development, how can I generate a program from the given tests</p> <p>For example I have this test:</p> <pre><code>class MaxMinTest(TestCase): """docstring for MaxMinTest""" def test_find_max_min_four(self): self.assertListEqual([1, 4], find_max_min([1, 2, 3, 4]), msg='should return [1,4] for [1, 2, 3, 4]') def test_find_max_min_one(self): self.assertListEqual([4, 6], find_max_min([6, 4]), msg='should return [4, 6] for [6, 4]') def test_find_max_min_two(self): self.assertListEqual([2, 78], find_max_min([4, 66, 6, 44, 7, 78, 8, 68, 2]), msg='should return [2, 78] for [4, 66, 6, 44, 7, 78, 8, 68, 2]') def test_find_max_min_three(self): self.assertListEqual([1, 4], find_max_min([1, 2, 3, 4]), msg='should return [1,4] for [1, 2, 3, 4]') def test_find_max_min_identity(self): self.assertListEqual([4], find_max_min([4, 4, 4, 4]), msg='Return the number of elements in the list in a new list if the `min` and `max` are equal') </code></pre> <p>Thanks in advance. Please also share resources for learning test driven development for a beginner like me.</p>
0
2016-10-08T12:41:02Z
39,932,582
<p>Without giving you the answer to the code that would make these tests pass, your approach can be something like this:</p> <ul> <li><p>What are you testing? </p></li> <li><p>What does this function take, and what does it return?</p></li> <li><p>How do I make <strong>one</strong> test pass? Once I make one test pass, how do I make the other test pass, while ensuring the previous test still passes. And so on, until all tests pass with the code you have written in your function. </p></li> </ul> <p>So, to answer your questions at a high level. </p> <p>You are testing something that is called <code>MinMax</code>, which hints out at finding the minimum and maximum of something. This <em>something</em> is a function called <code>find_max_min</code> takes as input a <code>list</code>, and returns a list with two values. These two values are in order, the <code>min</code> and the <code>max</code> of the <code>list</code> you are passing to your function. </p> <p>Documentation to look at: </p> <ul> <li><p><a href="https://docs.python.org/3/library/unittest.html" rel="nofollow">Official documentation on the unittest module in Python 3</a></p></li> <li><p><a href="http://docs.python-guide.org/en/latest/writing/tests/" rel="nofollow">Tutorial on unittesting</a></p></li> <li><p><a href="http://python-3-patterns-idioms-test.readthedocs.io/en/latest/UnitTesting.html" rel="nofollow">Unittesting and TDD</a></p></li> </ul>
1
2016-10-08T12:51:24Z
[ "python", "python-2.7", "unit-testing", "tdd" ]
Comparing two columns in different file and printing match if difference between record in a columns less than or equal to 0.001
39,932,484
<p>I have two text files, say file1.txt contains something like </p> <pre><code>100.145 10.0728 100.298 10.04 100.212 10.0286 </code></pre> <p>and file2.txt contains something like </p> <pre><code>100.223 8.92739 100.209 9.04269 100.084 9.08411 </code></pre> <p>I want to compare column 1 and column 2 of both files and print match if the difference of both columns in file1.txt and in file2.txt is less or equal to 0.001.</p>
0
2016-10-08T12:41:59Z
39,932,607
<p>Just read both files, split by line break, split those lines by spaces and then loop over the first files lines and for each line check whether the second files line at this position matches your condition.</p> <pre class="lang-py prettyprint-override"><code>with open("file1.txt", "r") as f: f1_content = f.read() with open("file2.txt", "r") as f: f2_content = f.read() f1_lines = [line.split() for line in f1_content.split("\n")] f2_lines = [line.split() for line in f2_content.split("\n")] for i, line in enumerate(f1_lines): if abs(float(line[0]) - float(f2_lines[i][0])) &lt;= 0.001 and abs(float(line[1]) - float(f2_lines[i][1])) &lt;= 0.001: print("Match at line {0}".format(i)) </code></pre> <p>Solution using <code>zip</code> as proposed by @BrianCain:</p> <pre class="lang-py prettyprint-override"><code>with open("file1.txt", "r") as f: f1_content = f.read() with open("file2.txt", "r") as f: f2_content = f.read() f1_lines = [line.split() for line in f1_content.split("\n") if line != ""] f2_lines = [line.split() for line in f2_content.split("\n") if line != ""] for line in zip(f1_lines, f2_lines): if abs(float(line[0][0]) - float(line[1][0])) &lt;= 0.001 and abs(float(line[0][1]) - float(f2_lines[1][1])) &lt;= 0.001: print("Match at line {0}".format(line)) </code></pre> <p><strong>Requested Explanation</strong> of the solution using <code>zip</code>: First we open both file (using with, as this closes the file after the block) and save the content to some variables. We use <code>read()</code> instead of <code>readlines()</code> bacause the latter doesnt remove an <code>\n</code> when splitting at linebreaks. So i usually just use read() and split by <code>\n</code>, as this does the job.</p> <p>We then create ourselves for each file a list of tuples. Each entry in the list represents one line, each tuple (which is one of those entries) contains one entry per column. This is done using <a href="http://www.python-course.eu/list_comprehension.php" rel="nofollow">list comprehensions</a>:</p> <pre class="lang-py prettyprint-override"><code>f1_lines = [line.split() for line in f1_content.split("\n") if line != ""] </code></pre> <p>now we can iterate over the lines. <code>zip</code> is pretty useful for that, as it can combine two lists of equal length to one list, containing tuples of the entries of the lists at the same index. Example:</p> <pre class="lang-py prettyprint-override"><code>zip([1, 2, 3], [4, 5, 6]) </code></pre> <p>would produce</p> <pre class="lang-py prettyprint-override"><code>[(1, 4), (2, 5), 3, 6)] </code></pre> <p>For more look here: <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow">zip</a></p> <p>So now we have a list, containing tuples for the lines with an entry for each file. Each entry itself contains two entries for the columns:</p> <pre class="lang-py prettyprint-override"><code>[(['100.145', '10.0728'], ['100.223', '8.92739']), (['100.298', '10.04'], ['100.2985', '10.04001']), (['100.212', '10.0286'], ['100.084', '9.08411']), (['100.212', '100.2125'], ['100.084', '100.0845'])] </code></pre> <p>if we iterate over this list we can access files via the first [x] as in line[0] and columns via the second [y] as in line<a href="http://www.python-course.eu/list_comprehension.php" rel="nofollow">0</a> (accessing the first file at line at the second column). Now we simply subtract at each line the second files first column value from the first files first column value, take the absolute value (to only get positive floats) and check if its less than or equal to 0.001. The same is done for the second column, and if both are true (or one, if you use OR) then we print our message.</p>
1
2016-10-08T12:54:18Z
[ "python", "awk" ]
Comparing two columns in different file and printing match if difference between record in a columns less than or equal to 0.001
39,932,484
<p>I have two text files, say file1.txt contains something like </p> <pre><code>100.145 10.0728 100.298 10.04 100.212 10.0286 </code></pre> <p>and file2.txt contains something like </p> <pre><code>100.223 8.92739 100.209 9.04269 100.084 9.08411 </code></pre> <p>I want to compare column 1 and column 2 of both files and print match if the difference of both columns in file1.txt and in file2.txt is less or equal to 0.001.</p>
0
2016-10-08T12:41:59Z
39,932,947
<p>I would use <code>paste</code> to combine the files and then let <code>awk</code> do the rest:</p> <pre><code>paste file1.txt file2.txt | awk ' function abs(v) {return v &lt; 0 ? -v : v} abs($1-$3) &lt;= lim &amp;&amp; abs($2-$4) &lt;= lim ' lim=0.001 </code></pre> <p><code>abs</code> function definition copied from <a href="http://unix.stackexchange.com/a/220590/17666">an answer by Stéphane Chazelas</a></p>
0
2016-10-08T13:28:43Z
[ "python", "awk" ]
relation between tuple values in a list according to their position
39,932,488
<p>Consider a list containing tuples like:</p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] </code></pre> <p>How can i match corresponding tuple positions.For ex for <code>'d'</code>:</p> <pre><code>(d, 'has_val', 11) (d, 'has_val', 6) </code></pre> <p>i have tried the following:</p> <pre><code>str = 'has_val' for i in tuplelist: rel = (i[3],str,i[3]) </code></pre> <p>but this doesn't give me the desired output</p>
2
2016-10-08T12:42:13Z
39,932,532
<p>Sounds like <code>zip</code> is your friend:</p> <pre><code>&gt;&gt;&gt; zip(*tuplelist) [('a', 6, 0), ('b', 3, 4), ('c', 9, 5), ('d', 11, 6)] </code></pre> <p>You can use <code>zip</code> a little bit like a matrix transpose in math. Anyway, for your situation, we can do:</p> <pre><code>for x in zip(*tuplelist): for y in x[1:]: print (x[0], 'has_val', y) </code></pre> <p>Gives:</p> <pre><code>('a', 'has_val', 6) ('a', 'has_val', 0) ('b', 'has_val', 3) ('b', 'has_val', 4) ('c', 'has_val', 9) ('c', 'has_val', 5) ('d', 'has_val', 11) ('d', 'has_val', 6) </code></pre> <p>You can do this in a giant one-liner, too:</p> <pre><code>&gt;&gt;&gt; [(x[0], 'has_val', y) for x in zip(*tuplelist) for y in x[1:]] [('a', 'has_val', 6), ('a', 'has_val', 0), ('b', 'has_val', 3), ('b', 'has_val', 4), ('c', 'has_val', 9), ('c', 'has_val', 5), ('d', 'has_val', 11), ('d', 'has_val', 6)] </code></pre>
3
2016-10-08T12:46:26Z
[ "python", "list", "python-3.x", "tuples" ]
relation between tuple values in a list according to their position
39,932,488
<p>Consider a list containing tuples like:</p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] </code></pre> <p>How can i match corresponding tuple positions.For ex for <code>'d'</code>:</p> <pre><code>(d, 'has_val', 11) (d, 'has_val', 6) </code></pre> <p>i have tried the following:</p> <pre><code>str = 'has_val' for i in tuplelist: rel = (i[3],str,i[3]) </code></pre> <p>but this doesn't give me the desired output</p>
2
2016-10-08T12:42:13Z
39,932,592
<p>Just simpley use tuple and list indices. If you only want one value from one specfic place in a container, don't use a loop, just use indices.</p> <pre><code>res = (tuplelist[0][3],'has_val', tuplelist[1][3]) </code></pre> <p>Full program:</p> <pre><code>tuplelist = [('a', 'b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] res = (tuplelist[0][3],'has_val', tuplelist[1][3]) print(res) </code></pre> <p>Explanation:</p> <ul> <li><code>(tuplelist[0][3]</code>: Begin a tuple by using <code>(</code>. from the first tuple in <code>tuplelist</code> get the last item in that tuple and insert it in our current tuple.</li> <li><code>,'has_val',</code>: add the string 'has_val' to our tuple...</li> <li><code>tuplelist[1][3])</code>: for the last element in the current tuple, get the last element in the second tuple in <code>tuplelist</code>, and end our tuple with a <code>)</code>.</li> </ul>
1
2016-10-08T12:52:54Z
[ "python", "list", "python-3.x", "tuples" ]
relation between tuple values in a list according to their position
39,932,488
<p>Consider a list containing tuples like:</p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] </code></pre> <p>How can i match corresponding tuple positions.For ex for <code>'d'</code>:</p> <pre><code>(d, 'has_val', 11) (d, 'has_val', 6) </code></pre> <p>i have tried the following:</p> <pre><code>str = 'has_val' for i in tuplelist: rel = (i[3],str,i[3]) </code></pre> <p>but this doesn't give me the desired output</p>
2
2016-10-08T12:42:13Z
39,932,645
<p>Firstly, Don't name your variable as <code>str</code> as it shadows the builtin function. </p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] s = 'has_val' </code></pre> <p>Now coming to your issue, It's aesthetic to have the first row out as a header row. Also note that, I've used the <code>index</code> function to find the index instead of directly hard coding <code>3</code>. This is helpful if there is a change in the number of columns. </p> <pre><code>header_row = tuplelist[0] column_name = 'd' column_index = header_row.index(column_name) </code></pre> <p>Now for the logic, Loop from the second element using slices. </p> <pre><code>for i in tuplelist[1:]: print(column_name,s,i[column_index]) </code></pre> <p>This would give you the desired output. </p>
3
2016-10-08T12:58:21Z
[ "python", "list", "python-3.x", "tuples" ]
relation between tuple values in a list according to their position
39,932,488
<p>Consider a list containing tuples like:</p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] </code></pre> <p>How can i match corresponding tuple positions.For ex for <code>'d'</code>:</p> <pre><code>(d, 'has_val', 11) (d, 'has_val', 6) </code></pre> <p>i have tried the following:</p> <pre><code>str = 'has_val' for i in tuplelist: rel = (i[3],str,i[3]) </code></pre> <p>but this doesn't give me the desired output</p>
2
2016-10-08T12:42:13Z
39,932,651
<p>zip() can work for your problem</p> <pre><code>tuplelist = [('a','b', 'c', 'd'), (6, 3, 9, 11), (0, 4, 5, 6)] tuplelist_withposition=zip(tuplelist[0],tuplelist[1],tuplelist[2]) s = 'has_val' for i in tuplelist_withposition: rel = (i[0],s,i[1]) print rel rel=(i[0],s,i[2]) print rel </code></pre> <p>output:</p> <pre><code>('a', 'has_val', 6) ('a', 'has_val', 0) ('b', 'has_val', 3) ('b', 'has_val', 4) ('c', 'has_val', 9) ('c', 'has_val', 5) ('d', 'has_val', 11) ('d', 'has_val', 6) </code></pre>
2
2016-10-08T12:58:30Z
[ "python", "list", "python-3.x", "tuples" ]
Dynamically updating the PYTHONPATH prevents .pyc update
39,932,498
<p>To allow myself to have a clear filestructure in my project i am using the following code snippet to dynamically add the project main folder to the PYTHONPATH and therefore assure that I can import files even from above a files location.</p> <pre class="lang-py prettyprint-override"><code>import sys import os sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), ".")) </code></pre> <p>Since I did this, when I start my main file, changes to the modules aren't recognized anymore until i manually delete any .pyc files. Thus I assume this for some reason prevented python from checking if the pyc files are up to date. Can I overcome this issue in any way?</p>
0
2016-10-08T12:43:06Z
39,932,583
<p>You could try to make python not write those *.pyc files.</p> <p><a href="http://stackoverflow.com/questions/154443/how-to-avoid-pyc-files">How to avoid .pyc files?</a></p> <p>For large projects this would matter slightly from a performance perspective. It's possible that you don't care about that, and then you can just not create the pyc files.</p>
1
2016-10-08T12:51:50Z
[ "python", "pythonpath", "pyc" ]
Dynamically updating the PYTHONPATH prevents .pyc update
39,932,498
<p>To allow myself to have a clear filestructure in my project i am using the following code snippet to dynamically add the project main folder to the PYTHONPATH and therefore assure that I can import files even from above a files location.</p> <pre class="lang-py prettyprint-override"><code>import sys import os sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), ".")) </code></pre> <p>Since I did this, when I start my main file, changes to the modules aren't recognized anymore until i manually delete any .pyc files. Thus I assume this for some reason prevented python from checking if the pyc files are up to date. Can I overcome this issue in any way?</p>
0
2016-10-08T12:43:06Z
39,932,711
<p>Adding the path of an already imported module can get you into trouble if module names are no longer unique. Consider that you do <code>import foo</code>, which adds its parent package <code>bar</code> to <code>sys.path</code> - it's now possible to also do <code>import bar.foo</code>. Python will consider both to be different modules, which can mess up anything relying on module identity.</p> <p>You should really consider why you need to do this hack in the first place. If you have an executable placed inside your package, you should not do</p> <pre><code>cd bardir/bar python foo </code></pre> <p>but instead call it as part of the package via</p> <pre><code>cd bardir python -m bar.foo </code></pre>
0
2016-10-08T13:05:49Z
[ "python", "pythonpath", "pyc" ]
Calling a method within a Class
39,932,679
<p>I have the following class however when i try calling the method in an object, nothing happens</p> <pre><code>class parentClass: def test(self): if 3 &gt; 2: print "This is true" else: print "This is false" object1 = parentClass() object1.test </code></pre> <p>Can someone please tel me what i am doing wrong?</p>
-3
2016-10-08T13:02:37Z
39,932,689
<p>You forget "()":</p> <pre><code> object1.test() </code></pre> <p>Remember the methods need to be called with the brackets, for example in the propierties are not need it.</p>
1
2016-10-08T13:03:50Z
[ "python", "python-2.7", "python-3.x" ]
Calling a method within a Class
39,932,679
<p>I have the following class however when i try calling the method in an object, nothing happens</p> <pre><code>class parentClass: def test(self): if 3 &gt; 2: print "This is true" else: print "This is false" object1 = parentClass() object1.test </code></pre> <p>Can someone please tel me what i am doing wrong?</p>
-3
2016-10-08T13:02:37Z
39,932,705
<p>specifying a method with the parentheses just returns a reference to it. In order to call it, you need to have <code>()</code> (and optionally, any arguments) after it:</p> <pre><code>object1.test() </code></pre>
1
2016-10-08T13:05:11Z
[ "python", "python-2.7", "python-3.x" ]
Calling a method within a Class
39,932,679
<p>I have the following class however when i try calling the method in an object, nothing happens</p> <pre><code>class parentClass: def test(self): if 3 &gt; 2: print "This is true" else: print "This is false" object1 = parentClass() object1.test </code></pre> <p>Can someone please tel me what i am doing wrong?</p>
-3
2016-10-08T13:02:37Z
39,932,726
<p>add parentheses '()' to the method name where you're calling it.</p> <p>object1.test()</p>
1
2016-10-08T13:08:25Z
[ "python", "python-2.7", "python-3.x" ]
Calling a method within a Class
39,932,679
<p>I have the following class however when i try calling the method in an object, nothing happens</p> <pre><code>class parentClass: def test(self): if 3 &gt; 2: print "This is true" else: print "This is false" object1 = parentClass() object1.test </code></pre> <p>Can someone please tel me what i am doing wrong?</p>
-3
2016-10-08T13:02:37Z
39,932,755
<p>To call a function it requires '()'. Without these it's just a reference not a call.</p> <pre><code>object1.test () </code></pre> <p>Hope this helps.</p>
1
2016-10-08T13:11:07Z
[ "python", "python-2.7", "python-3.x" ]
pandas unique values multiple columns different dtypes
39,932,685
<p>Similar to <a href="http://stackoverflow.com/questions/26977076/pandas-unique-values-multiple-columns">pandas unique values multiple columns</a> I want to count the number of unique values per column. However, as the dtypes differ I get the following error: <a href="http://i.stack.imgur.com/78Fd5.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/78Fd5.jpg" alt="enter image description here"></a></p> <p>The data frame looks like <a href="http://i.stack.imgur.com/8NF69.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/8NF69.jpg" alt="enter image description here"></a> A <code>small[['TARGET', 'title']].apply(pd.Series.describe)</code> gives me the result, but only for the category types and I am unsure how to filter the index for only the last row with the unique values per column</p>
0
2016-10-08T13:03:17Z
39,933,598
<p>Use <code>apply</code> and <code>np.unique</code> to grab the unique values in each column and take its <code>size</code>:</p> <pre><code>small[['TARGET','title']].apply(lambda x: np.unique(x).size) </code></pre> <p>Thanks!</p>
1
2016-10-08T14:32:14Z
[ "python", "pandas", "unique" ]
Right code but still test case is not running in python
39,932,791
<p>Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere.</p> <pre><code>def array123(nums): for i in nums: if nums[i:i+3] == [1,2,3]: return True return False </code></pre> <p><a href="http://codingbat.com/prob/p193604" rel="nofollow">Coding bat problem</a></p> <p>my code is satisfying all the test cases except for nums=[1,2,3] can someone tell me whats wrong with my code</p>
-2
2016-10-08T13:14:36Z
39,932,832
<p>Your code is not completely right. You're slicing the list with the items in the list, not with indices. Luckily, this did not throw any error because the items in the list are within the bounds of the list's indices or rather <em>slicing</em> does not raise errors, when done correclty, irrespective of start and/or stop indices.</p> <p>You can use <code>range(len(...))</code> to generate the indices, and you may stop the search at <code>len(nums) - len(sublist)</code>, so you don't check for <em>slices</em> less than the length of the <em>sublist</em>. This comes more handy as the length of the <em>sublist</em> gets larger.</p> <pre><code>def array123(nums, sublist): j = len(sublist) for i in range(len(nums)-j): if nums[i:i+j] == sublist: return True return False # Call function array123(nums, [1,2,3]) </code></pre> <hr> <p>Useful reference:</p> <p><a href="http://stackoverflow.com/questions/509211/explain-pythons-slice-notation">Explain Python&#39;s slice notation</a></p>
1
2016-10-08T13:17:21Z
[ "python", "python-3.x" ]
Right code but still test case is not running in python
39,932,791
<p>Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere.</p> <pre><code>def array123(nums): for i in nums: if nums[i:i+3] == [1,2,3]: return True return False </code></pre> <p><a href="http://codingbat.com/prob/p193604" rel="nofollow">Coding bat problem</a></p> <p>my code is satisfying all the test cases except for nums=[1,2,3] can someone tell me whats wrong with my code</p>
-2
2016-10-08T13:14:36Z
39,932,862
<p>You're getting wrong result because you're iterating on the value of elements not on the index of elements of elements. Try following code</p> <pre><code>def array123(nums): for i in range(len(nums)-2): if nums[i:i+3] == [1,2,3]: return True return False </code></pre> <p>And remember to give the end index of list (range(len(nums)-2)) because suppose if length of your array is 4 then (range(len(nums)-2)) will be </p> <p>(range(2)) = [0,1]</p> <p>So the loop will iterate for 0,1 as starting index</p>
0
2016-10-08T13:20:56Z
[ "python", "python-3.x" ]
Right code but still test case is not running in python
39,932,791
<p>Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere.</p> <pre><code>def array123(nums): for i in nums: if nums[i:i+3] == [1,2,3]: return True return False </code></pre> <p><a href="http://codingbat.com/prob/p193604" rel="nofollow">Coding bat problem</a></p> <p>my code is satisfying all the test cases except for nums=[1,2,3] can someone tell me whats wrong with my code</p>
-2
2016-10-08T13:14:36Z
39,932,905
<p>It should be like this.</p> <pre><code>def array123(nums): for i in range(len(nums)): if nums[i:i+3] == [1,2,3]: return True return False </code></pre> <p>Try this. Hope this helps. :)</p>
1
2016-10-08T13:24:30Z
[ "python", "python-3.x" ]
Regular expression to extract data from news page
39,932,825
<p>Hi I'm running python regular expression to extract some data from news pages, however when it is displayed the code produces brackets and apostrophes in the output. For example this is my code:</p> <pre><code>description_title = findall('&lt;item&gt;[\s]*&lt;title[^&gt;]*&gt;(.*?)&lt;\/title&gt;[\s]*&lt;description&gt;', html_source)[:1] news_file.write('&lt;h3 align="Center"&gt;' + str(description_title) + ": " + '&lt;/h3\n&gt;') </code></pre> <p>but this code creates the output of ['Technology']:, ['Finance']: but i want Technology, Finance without the [''] around it. </p>
0
2016-10-08T13:16:56Z
39,932,856
<p>By using <a href="https://docs.python.org/2/library/functions.html#str" rel="nofollow"><code>str</code></a>, you're printing a Python string representation of <code>description_title</code> (which is a <code>list</code> of length 1). Try without the <code>str</code>:</p> <pre><code>'&lt;h3 align="Center"&gt;' + description_title[0] + ": " + '&lt;/h3\n&gt;' </code></pre>
1
2016-10-08T13:20:20Z
[ "python", "html", "regex" ]
Python redis rpop is resultng b'value' list structure
39,932,873
<p>I am working on a simple redis and flask project using docker compose. my flask manuplates redis list structure using lpush, rpop. It worked fine until i was playing with commands like brpop which now made all my results b'value'. I tried to work with the first commands only, but somehow the b'value' output keeps coming. Any idea on what might causing this?</p> <pre><code>**redis.lpush('moviestore','likemov') itle = redis.rpop('moviestore')** </code></pre>
0
2016-10-08T13:22:37Z
39,943,518
<p>It seems that redis strings are Python bytes strings (see the documentation about <a href="http://redis.io/topics/data-types" rel="nofollow">Data Types</a>).</p> <p>So, I think there is a automatic conversion from Unicode to Bytes in Python 3 (and maybe in Python 2 too).</p> <p>To work with Unicode string, you can encode/decode sting (using UTF8 encoding for instance):</p> <pre><code>redis.lpush('moviestore', u'likemov'.encode('utf8')) ... itle = redis.rpop('moviestore').decode('utf8') </code></pre> <p>In summary:</p> <ul> <li>to store Unicode string in Redis: you encode it,</li> <li>to retrieve Unicode string from Redis: you decode it.</li> </ul> <p>Notice the differences:</p> <ul> <li>by default, 'value' is a <code>str</code> which is a Bytes string in Python 2 and an Unicode string in Python 3.</li> <li>u'value' is an Unicode string: py2 <code>unicode</code> / py3 <code>str</code>;</li> <li>b'value' is a Bytes string: py2 <code>str</code> / py3 <code>bytes</code>.</li> </ul>
0
2016-10-09T12:17:07Z
[ "python", "list", "redis", "docker-compose" ]
Aide in modifying this code removing the ' * ' operator and using while loops instead?
39,932,875
<p>How can I modify my code and remove the ' * ' operator which I have used to multiply strings and use while loops instead of it to produce the same pattern?</p> <pre><code>i = 1 x = 1 while i &lt;= 4: print "v"*x print "v"*x x = x+1 i+=1 print "v"*5 b = 4 while b&gt;=1: print "v"*b print "v"*b b=b-1 </code></pre>
-3
2016-10-08T13:22:41Z
39,933,005
<p>Perhaps consider using the <code>range</code> function and a <code>for-loop</code> within your while loop? The <code>range(stop, end)</code> function returns an array with integers from <code>stop</code> (inclusive) to <code>end</code> (exclusive). For ex: <code>range(0,3)</code> returns <code>[0, 1, 2]</code>. So in a <code>for-loop</code>, you could print out <code>x</code> number of v's or <code>b</code> number of v's by printing a v for each member of the array returned from <code>range</code> with each iteration of the outer while loop. For example, it would look like this,</p> <pre><code>i = 1 x = 1 while i &lt;= 4: for y in range(0, x): print "v" print "v" x = x+1 i+=1 print "v"*5 b = 4 while b&gt;=1: for y in range(0, b): print "v" print "v" b=b-1 </code></pre>
0
2016-10-08T13:34:17Z
[ "python", "python-2.7", "while-loop" ]
Aide in modifying this code removing the ' * ' operator and using while loops instead?
39,932,875
<p>How can I modify my code and remove the ' * ' operator which I have used to multiply strings and use while loops instead of it to produce the same pattern?</p> <pre><code>i = 1 x = 1 while i &lt;= 4: print "v"*x print "v"*x x = x+1 i+=1 print "v"*5 b = 4 while b&gt;=1: print "v"*b print "v"*b b=b-1 </code></pre>
-3
2016-10-08T13:22:41Z
39,933,133
<p>Hey this is the simplest way of doing this.</p> <pre><code>length = 4 i = 0 output = "v" for j in range(length-1): print output + "\n" + output output += "v" print output for j in range(length): output = output[:-1] print output + "\n" + output </code></pre> <p>Try this out. Hope this helps.</p> <p>If want to use only while loop..here's the solution.</p> <pre><code>length = 4 i = 1 output = "v" flag = False while (i &lt; length): if i == 0: break if not flag: print output + "\n" + output output += "v" i+=1 else: output = output[:-1] print output + "\n" + output i-=1 if i == length: i-=1 print output flag = True </code></pre> <p>Hope this solves for query. :)</p>
1
2016-10-08T13:44:33Z
[ "python", "python-2.7", "while-loop" ]
python re.search quantifier
39,932,949
<p>I have this:-</p> <pre><code>re.search("^[47]{2:}$", '447447') </code></pre> <p>... and was expecting it to return True. But somehow it does not.</p> <p>How come? My understanding is that it was suppose to match any number which has any combination of 4 or 7, with at least 2 digits. Is that correct?</p>
-1
2016-10-08T13:28:52Z
39,932,990
<p>It should probably be <code>"^[47]{2,}$"</code>.</p> <p>I visit the <a href="https://docs.python.org/2/library/re.html#regular-expression-syntax" rel="nofollow">regular expression syntax</a> page quite often, because I find it hard to remember all of the little tricks for building regexes.</p>
3
2016-10-08T13:32:59Z
[ "python", "regex", "search" ]
python re.search quantifier
39,932,949
<p>I have this:-</p> <pre><code>re.search("^[47]{2:}$", '447447') </code></pre> <p>... and was expecting it to return True. But somehow it does not.</p> <p>How come? My understanding is that it was suppose to match any number which has any combination of 4 or 7, with at least 2 digits. Is that correct?</p>
-1
2016-10-08T13:28:52Z
39,933,011
<p>The syntax is <code>{m,n}</code> where <em>n</em> could be omitted.</p> <p>Fix:</p> <pre><code>re.search("^[47]{2,}$", '447447') </code></pre> <p>See RegEx syntax: <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">https://docs.python.org/3/library/re.html#regular-expression-syntax</a></p>
2
2016-10-08T13:34:56Z
[ "python", "regex", "search" ]
Python JWT and RSA
39,932,977
<p>I would like to learn about creating JWT using RSA public and private key. I am a beginner to learn securing my services. I am using pyjwt right now. I got something error with my testing, here it is:</p> <p>SAMPLEKEY:</p> <pre><code>privatekey = """-----BEGIN RSA PRIVATE KEY-----MIICXQIBAAKBgQCkC2AfenNMfrU4oMfMZt9aZGBbFjzBTjV9Yttp0GHeVjIKboTwLkiKNqSKrm2Jralbteii2J9h6BeUBpv3B/Os7M0eNeM8B+5Rzm44vcmkzdtufTuX2utjoz8BFjelXw5og2i67NtxgiSHv2x1KCHbGZG+jpDOgjorxFusKbeGjQIDAQABAoGADbMJfvd543x9Y9JBfTdmFaVmSpUL09TVMLhtvGNzmN635RkfrvMeibRQf2hbq3C+QPNrDxZqEQIR3gHDSpj2Z2tGrE95a5o8+I3NBARkKOz41lMFm2AnXZLsM0ma+8S61j8AtELgFuKZWyi2t9A3Otf1+vayZVS/F8pyof0wD10CQQDXDloBpki887jVXtnIauV3Z1744P/uvVkWZOMTMiNF5Xh8SRPn2mNR80vUAAN5SL7zjGyDQeoYKZMRJaLFGsaPAkEAw0bCyz2aA+aWaTM1iyK4XK9/dNPoztE0lmeaHXvI7d1Zp0ipbLwewt4gRbSL7UpxdRQy0ELep4HoSTLt2dQPIwJBANCtS2c4XHKFKIBa5oaUO4+OjdiAM7gMoeqaAMG6sAF99ljbbGZZQnDd3WGclcJVdXzMcOs4xZeml99WnsgWAD8CQAWIfsKFh1Su9voaIl1D6ZduvZzQ2Frr4KKWYu6M8F+VExJDY9GZ7wE0jBONjx11K4vWu63dBzQV4UAZulWexaMCQQCmfoq0l1JtnYhV3LhEN3E8gwUK/0456An5YKunwO8nPrBsrdt/TQ6ZAUzh7JkmabV3h2KXQ+H0/cvfWBOhYaov-----END RSA PRIVATE KEY-----""" publickey = """-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkC2AfenNMfrU4oMfMZt9aZGBbFjzBTjV9Yttp0GHeVjIKboTwLkiKNqSKrm2Jralbteii2J9h6BeUBpv3B/Os7M0eNeM8B+5Rzm44vcmkzdtufTuX2utjoz8BFjelXw5og2i67NtxgiSHv2x1KCHbGZG+jpDOgjorxFusKbeGjQIDAQAB-----END PUBLIC KEY-----""" </code></pre> <p>Here is my sample code:</p> <pre><code>@app.route('/token') def token(): encodedToken = jwt.encode({'userid':'1'}, publickey, algorithm = 'RS256') print(jwt.decode(encodedToken, privatekey, verify=True, algorithms='RS256')) return "OKE" </code></pre> <p>And, I am getting this error when running it:</p> <p><a href="http://i.stack.imgur.com/lJV5h.png" rel="nofollow"><img src="http://i.stack.imgur.com/lJV5h.png" alt="enter image description here"></a></p> <p>Is there any solution into this ?</p> <p>Thanks</p>
0
2016-10-08T13:31:47Z
39,933,122
<p>This issue is reported on GitHub here: <a href="https://github.com/jpadilla/pyjwt/issues/81" rel="nofollow">https://github.com/jpadilla/pyjwt/issues/81</a></p> <p>And marked as "closed". </p>
0
2016-10-08T13:43:48Z
[ "python", "rsa", "pyjwt" ]
Python JWT and RSA
39,932,977
<p>I would like to learn about creating JWT using RSA public and private key. I am a beginner to learn securing my services. I am using pyjwt right now. I got something error with my testing, here it is:</p> <p>SAMPLEKEY:</p> <pre><code>privatekey = """-----BEGIN RSA PRIVATE KEY-----MIICXQIBAAKBgQCkC2AfenNMfrU4oMfMZt9aZGBbFjzBTjV9Yttp0GHeVjIKboTwLkiKNqSKrm2Jralbteii2J9h6BeUBpv3B/Os7M0eNeM8B+5Rzm44vcmkzdtufTuX2utjoz8BFjelXw5og2i67NtxgiSHv2x1KCHbGZG+jpDOgjorxFusKbeGjQIDAQABAoGADbMJfvd543x9Y9JBfTdmFaVmSpUL09TVMLhtvGNzmN635RkfrvMeibRQf2hbq3C+QPNrDxZqEQIR3gHDSpj2Z2tGrE95a5o8+I3NBARkKOz41lMFm2AnXZLsM0ma+8S61j8AtELgFuKZWyi2t9A3Otf1+vayZVS/F8pyof0wD10CQQDXDloBpki887jVXtnIauV3Z1744P/uvVkWZOMTMiNF5Xh8SRPn2mNR80vUAAN5SL7zjGyDQeoYKZMRJaLFGsaPAkEAw0bCyz2aA+aWaTM1iyK4XK9/dNPoztE0lmeaHXvI7d1Zp0ipbLwewt4gRbSL7UpxdRQy0ELep4HoSTLt2dQPIwJBANCtS2c4XHKFKIBa5oaUO4+OjdiAM7gMoeqaAMG6sAF99ljbbGZZQnDd3WGclcJVdXzMcOs4xZeml99WnsgWAD8CQAWIfsKFh1Su9voaIl1D6ZduvZzQ2Frr4KKWYu6M8F+VExJDY9GZ7wE0jBONjx11K4vWu63dBzQV4UAZulWexaMCQQCmfoq0l1JtnYhV3LhEN3E8gwUK/0456An5YKunwO8nPrBsrdt/TQ6ZAUzh7JkmabV3h2KXQ+H0/cvfWBOhYaov-----END RSA PRIVATE KEY-----""" publickey = """-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkC2AfenNMfrU4oMfMZt9aZGBbFjzBTjV9Yttp0GHeVjIKboTwLkiKNqSKrm2Jralbteii2J9h6BeUBpv3B/Os7M0eNeM8B+5Rzm44vcmkzdtufTuX2utjoz8BFjelXw5og2i67NtxgiSHv2x1KCHbGZG+jpDOgjorxFusKbeGjQIDAQAB-----END PUBLIC KEY-----""" </code></pre> <p>Here is my sample code:</p> <pre><code>@app.route('/token') def token(): encodedToken = jwt.encode({'userid':'1'}, publickey, algorithm = 'RS256') print(jwt.decode(encodedToken, privatekey, verify=True, algorithms='RS256')) return "OKE" </code></pre> <p>And, I am getting this error when running it:</p> <p><a href="http://i.stack.imgur.com/lJV5h.png" rel="nofollow"><img src="http://i.stack.imgur.com/lJV5h.png" alt="enter image description here"></a></p> <p>Is there any solution into this ?</p> <p>Thanks</p>
0
2016-10-08T13:31:47Z
39,933,301
<p>Basically you'll want to switch the keys, use the private key for "encoding" (signing) and public for "decoding" (verification).</p>
0
2016-10-08T14:01:57Z
[ "python", "rsa", "pyjwt" ]
how to generalize/get base directory for Linux path for python script
39,933,116
<p>(Linux)in Bash I can use variableName= cd $BASEDIR./Desktop to replace HOME/userName/Destop. How can I achieve the same in Python?</p> <p>EXAMPLE: need to replace home/name to be generic so that I can run this from multiple hosts. f = open("home/name/directory/subdirectory/file.cfg", "r")</p>
-1
2016-10-08T13:43:12Z
39,933,164
<p>Try to use commands libray.</p> <pre><code>import commands commands.getoutput("cd $BASEDIR./Desktop") </code></pre>
0
2016-10-08T13:48:04Z
[ "python" ]
how to generalize/get base directory for Linux path for python script
39,933,116
<p>(Linux)in Bash I can use variableName= cd $BASEDIR./Desktop to replace HOME/userName/Destop. How can I achieve the same in Python?</p> <p>EXAMPLE: need to replace home/name to be generic so that I can run this from multiple hosts. f = open("home/name/directory/subdirectory/file.cfg", "r")</p>
-1
2016-10-08T13:43:12Z
39,933,181
<p>You might get some use out of <a href="https://docs.python.org/2/library/os.path.html#os.path.expanduser" rel="nofollow"><code>os.path.expanduser</code></a> or <a href="https://docs.python.org/2/library/os.path.html#os.path.expandvars" rel="nofollow"><code>os.path.expandvars</code></a>:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.expanduser('~/Desktop') '/home/userName/Desktop' </code></pre> <p>or, assuming that <code>$BASEDIR</code> is defined in your environment,</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.expandvars('$BASEDIR/Desktop') '/home/userName/Desktop' </code></pre> <p>Using the first option, maybe you can do what you want to do with:</p> <pre><code>f = open(os.path.expanduser("~/directory/subdirectory/file.cfg"), "r") </code></pre>
1
2016-10-08T13:49:37Z
[ "python" ]
how to generalize/get base directory for Linux path for python script
39,933,116
<p>(Linux)in Bash I can use variableName= cd $BASEDIR./Desktop to replace HOME/userName/Destop. How can I achieve the same in Python?</p> <p>EXAMPLE: need to replace home/name to be generic so that I can run this from multiple hosts. f = open("home/name/directory/subdirectory/file.cfg", "r")</p>
-1
2016-10-08T13:43:12Z
39,933,304
<p>You can read environment variables directly from <code>os.environ</code>:</p> <pre><code>import os basedir = os.environ.get('BASEDIR') </code></pre> <p>To construct a path reliably, the <code>os</code> module provides <code>os.path.join</code>. You should also provide a fallback if the variable is undefined. This could look like this:</p> <pre><code>import os my_path = os.path.expanduser(os.path.join( os.environ.get('BASEDIR', '~'), # default to HOME 'Desktop' ) </code></pre> <p>Note that environment variables may not be the most ideal solution. Have a look at arguments, for example via the <a href="https://docs.python.org/3.5/library/argparse.html#module-argparse" rel="nofollow"><code>argparse</code> module</a>.</p>
1
2016-10-08T14:02:07Z
[ "python" ]
Mac beeps when I type end parantheses in commented block of Python
39,933,160
<p>Why, when I type an end parantheses in a commented out area in IDLE, does mac sound the error beep, and how can I stop it?</p>
0
2016-10-08T13:47:47Z
39,938,365
<p>Various programs, including IDLE, sometimes ask the computer to 'beep' when the user does something that the program considers an error. In general, to not hear a beep, you can 1) stop doing whatever provokes the beep, 2) turn your speaker down or off, or 3) plug in earphones and not wear them while editing.</p>
0
2016-10-08T23:14:02Z
[ "python", "osx", "comments", "python-idle", "beep" ]
Selection Sort-array sorting
39,933,331
<p>When I run it only the first smallest number gets sorted. Is the problem somewhere in the loops?</p> <pre><code>def selectionSort(A): n=len(A) print(n) mini=0 for i in range(0,n-2): mini=i for j in range(i+1,n-1): if A[j]&lt;A[mini]: mini=j if i!=mini: temp=A[i] A[i]=A[mini] A[mini]=temp return A </code></pre>
-1
2016-10-08T14:04:31Z
39,933,403
<p>There are actually two issues:</p> <ol> <li>Your second <code>if</code> should be outside the inner <code>for</code> loop.</li> <li>And your outer and inner loop should be iterating till <code>n-1</code> and <code>n</code> respectively, instead of <code>n-2</code> and <code>n-1</code>.</li> </ol> <hr> <p>Hence, your code should be like:</p> <pre><code>def selectionSort(A): n=len(A) print(n) mini=0 for i in range(0,n-1): mini=i for j in range(i+1,n): if A[j]&lt;A[mini]: mini=j if i!=mini: temp=A[i] A[i]=A[mini] A[mini]=temp return A </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; selectionSort([2, 5, 7, 1, 3, 0, 10, 43, 21, 32]) 10 [0, 1, 2, 3, 5, 7, 10, 21, 32, 43] </code></pre> <p><em>Suggestion:</em> You do not need temp variable in python for swapping values. You can simply do it as:</p> <pre><code>&gt;&gt;&gt; a = 5 &gt;&gt;&gt; b = 3 &gt;&gt;&gt; a, b = b, a &gt;&gt;&gt; a 3 &gt;&gt;&gt; b 5 </code></pre> <p>In your swapping code, it would be as: <code>A[i], A[mini] = A[mini], A[i]</code></p>
0
2016-10-08T14:12:19Z
[ "python" ]
Selection Sort-array sorting
39,933,331
<p>When I run it only the first smallest number gets sorted. Is the problem somewhere in the loops?</p> <pre><code>def selectionSort(A): n=len(A) print(n) mini=0 for i in range(0,n-2): mini=i for j in range(i+1,n-1): if A[j]&lt;A[mini]: mini=j if i!=mini: temp=A[i] A[i]=A[mini] A[mini]=temp return A </code></pre>
-1
2016-10-08T14:04:31Z
39,933,409
<p>Yes the problem is in the swapping part of your code, it needs to placed after inner for-loop</p> <pre><code>def selectionSort(A): n = len(A) mini=0 for i in range(0,n-2): mini=i for j in range(i+1,n-1): if A[j]&lt;A[mini]: mini=j if i!=mini: temp=A[i] A[i]=A[mini] A[mini]=temp return A </code></pre>
0
2016-10-08T14:12:41Z
[ "python" ]
Is it possible to mix literal words and tags in NLTK regex
39,933,493
<p>I'm experimenting with NLTK to help me parse some text. As an example I have:</p> <pre><code>1 Robins Drive owned by Gregg S. Smith was sold to TeStER, LLC of 494 Bridge Avenue, Suite 101-308, Sheltville AZ 02997 for $27,000.00. </code></pre> <p>using:</p> <pre><code>words =pos_tag(word_tokenize(sentence)) </code></pre> <p>I get:</p> <pre><code>[('1', 'CD'), ('Robins', 'NNP'), ('Drive', 'NNP'), ('owned', 'VBN'), ('by', 'IN'), ('Gregg', 'NNP'), ('S.', 'NNP'), ('Smith', 'NNP'), ('was', 'VBD'), ('sold', 'VBN'), ('to', 'TO'), ('TeStER', 'NNP'), (',', ','), ('LLC', 'NNP'), ('of', 'IN'), ('494', 'CD'), ('Bridge', 'NNP'), ('Avenue', 'NNP'), (',', ','), ('Suite', 'NNP'), ('101-308', 'CD'), (',', ','), ('Sheltville', 'NNP'), ('AZ', 'NNP'), ('02997', 'CD'), ('for', 'IN'), ('$', '$'), ('27,000.00', 'CD'), ('.', '.')] </code></pre> <p>Assuming I want to extract the role of 'owner' (Gregg S. Smith), Is there a way to mix and match literals and tags perhaps of a format something like:</p> <pre><code>'owned by{&lt;NP&gt;+}' </code></pre> <p>There was a previous discussion of this at <a href="http://stackoverflow.com/questions/12755638/mixing-words-and-pos-tags-in-nltk-parser-grammars">Mixing words and PoS tags in NLTK parser grammars</a>, but I'm not sure I understood the provided answer. Is this possible, and if so could you provide a code example.</p>
0
2016-10-08T14:21:43Z
39,935,194
<p>if you combine each word and tag and then use <code>RegEx</code> to look for certain sequences of PoS tags you can get the results you are looking for.</p> <p>for example, using the <code>words</code> variable you have defined</p> <pre><code>joined = ' '.join([w+"&lt;"+t+"&gt;" for w,t in words]) </code></pre> <p>would produce</p> <pre><code>'1&lt;CD&gt; Robins&lt;NNP&gt; Drive&lt;NNP&gt; owned&lt;VBN&gt; by&lt;IN&gt; Gregg&lt;NNP&gt; S.&lt;NNP&gt; Smith&lt;NNP&gt; was&lt;VBD&gt; sold&lt;VBN&gt; to&lt;TO&gt; TeStER&lt;NNP&gt; ,&lt;,&gt; LLC&lt;NNP&gt; of&lt;IN&gt; 494&lt;CD&gt; Bridge&lt;NNP&gt; Avenue&lt;NNP&gt; ,&lt;,&gt; Suite&lt;NNP&gt; 101-308&lt;CD&gt; ,&lt;,&gt; Sheltville&lt;NNP&gt; AZ&lt;NNP&gt; 02997&lt;CD&gt; for&lt;IN&gt; $&lt;$&gt; 27,000.00&lt;CD&gt; .&lt;.&gt;' </code></pre> <p>Then you have to create a regular expression to find the sequence you are looking for depending on word/tag context.</p> <p>For example, using the python RegEx module <code>re</code></p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; m = re.match(r'.*owned&lt;VBN&gt; by&lt;IN&gt;.*?&lt;NNP&gt;', joined) &gt;&gt;&gt; m.group(0) '1&lt;CD&gt; Robins&lt;NNP&gt; Drive&lt;NNP&gt; owned&lt;VBN&gt; by&lt;IN&gt; Gregg&lt;NNP&gt;' </code></pre>
1
2016-10-08T17:20:39Z
[ "python", "nltk" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,555
<p>Given you are trying to alternate the sign you can use the fact that <code>(-1)**n</code> also alternates the sign. But you want a negative when <code>n</code> is even you will need <code>(-1)**(n-1)</code>:</p> <pre><code>&gt;&gt;&gt; list(n*(-1)**(n-1) for n in range(1, 11)) [1, -2, 3, -4, 5, -6, 7, -8, 9, -10] &gt;&gt;&gt; sum(n*(-1)**(n-1) for n in range(1, 11)) -5 </code></pre> <p>This can be turned into an explicit looping solution with:</p> <pre><code>t = 0 for n in range(1, 11): t += n*(-1)**(n-1) print(t) # -5 </code></pre>
2
2016-10-08T14:28:24Z
[ "python", "list" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,560
<p>You can use a generator expression like </p> <pre><code>&gt;&gt;&gt; sum(v if v%2 else -v for v in range(11)) -5 </code></pre> <p>Here we check if the index is even or odd and add the number accordingly. </p> <p>Another way can be using the <code>zip</code> builtin, But this works only for an even range. </p> <pre><code>&gt;&gt;&gt; sum(x-y for x,y in zip(l[::2],l[1::2])) -5 </code></pre> <p>You can avoid slices and reduce the code size by using <code>iter</code>. <code>iter</code> creates an iterator that'll be exhausted whenever it has been called. </p> <pre><code>&gt;&gt;&gt; i = iter(l) &gt;&gt;&gt; sum(x-y for x,y in zip(i,i)) -5 </code></pre>
2
2016-10-08T14:28:41Z
[ "python", "list" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,573
<p>your code need a very small change:</p> <pre><code>i = 1 sum = 0 sign = 1 while i&lt;= 10: sum = sum + sign * i sign = sign * -1 i = i + 1 print(sum) </code></pre> <p>There are more pythonic ways to do what you requested - but they will require a little more knowledge..</p>
1
2016-10-08T14:29:48Z
[ "python", "list" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,582
<p>You should do like:</p> <pre><code>i = 1 my_sum = 0 while i&lt;= 10: if i % 2: # True, if i is divisible by 2 my_sum -= i else: my_sum += i i += 1 # same as i = i + 1 </code></pre> <p>Some other alternative approaches:</p> <pre><code>&gt;&gt;&gt; sum((i if i % 2 else -i) for i in range(1, 11)) -5 &gt;&gt;&gt; sum(map(lambda x: x if x %2 else -x, range(1, 11))) -5 </code></pre>
1
2016-10-08T14:30:32Z
[ "python", "list" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,631
<p>It can also be seen as <code>sum of odd</code> minus <code>sum of even</code></p> <pre><code>sum(range(1, 11, 2)) - sum(range(2, 11, 2)) </code></pre>
1
2016-10-08T14:36:15Z
[ "python", "list" ]
Alternate between add and subtract on a list of numbers
39,933,509
<p>How to get the sum of the series 1-2+3-4+5-6+7-8+9-10 in python? </p> <p>I know how to get the sum of numbers from 1 to a particular number by using while loop in this way:</p> <pre><code>i = 1 sum = 0 while i&lt;= 10: sum = sum + i i = i + 1 print(sum) </code></pre>
1
2016-10-08T14:23:06Z
39,933,634
<p>To expand this to a much easier, linear solution that works for any n series like this:</p> <pre><code>def sum_subtract(n): return n // 2 * -1 + n % 2 * n </code></pre> <p>Every pair of numbers (1 - 2) + (3 - 4) + etc. equals -1, so you just floor divide by 2 and multiply by -1. Next if there is an odd number at the end (n % 2), you add that.</p>
1
2016-10-08T14:36:27Z
[ "python", "list" ]
Import serializer in models.py : Django rest framwork
39,933,538
<p>My one model class having following models,</p> <p><strong>NewsfeedModel.py</strong></p> <pre><code>class NewsFeed(models.Model): class NewsStatus(models.Model): class NewsImage(models.Model): </code></pre> <p>this is my serializers.py file</p> <pre><code>from MadhaparGamApps.AppModels.NewsfeedModel import NewsFeed, NewsStatus, NewsImage class NewsFeedSerializer(serializers.ModelSerializer): </code></pre> <p>Up to this, it's working fine I'm able to use models in serializer. Now I have to use serializer in my NewsfeedModel file, so I import serializer in NewsfeedModel file, but it's not allowing me to use.</p> <p>getting following error in the log:</p> <pre><code>ImportError: cannot import name NewsFeed </code></pre> <p>Is there any way to use serializer in model class?</p>
0
2016-10-08T14:25:51Z
39,934,309
<p>It seems like you are trying to Import NewsFeed model to itself.</p> <p>The flow of a django-rest-framework looks like this:</p> <p>Model > Serializer > View</p> <p>After getting your serializers done all you need to do Is to import the models and serializers into the views.py file, in which you will create classes/functions to handle the calls to the API. an example for such use will be:</p> <p>views.py</p> <pre><code>from newsfeedmodel.py import * from serializers.pi import * class NewsFeedViewSet(viewsets.ModelViewSet): queryset = NewsFeed.objects.all() serializer_class = NewsFeedSerializer </code></pre> <p>I would reccomend that you read the DRF documentation for better understanding:<br> <a href="http://django-rest-framework.org" rel="nofollow">http://django-rest-framework.org</a></p>
0
2016-10-08T15:46:17Z
[ "python", "django", "serialization", "django-models", "django-rest-framework" ]
Import serializer in models.py : Django rest framwork
39,933,538
<p>My one model class having following models,</p> <p><strong>NewsfeedModel.py</strong></p> <pre><code>class NewsFeed(models.Model): class NewsStatus(models.Model): class NewsImage(models.Model): </code></pre> <p>this is my serializers.py file</p> <pre><code>from MadhaparGamApps.AppModels.NewsfeedModel import NewsFeed, NewsStatus, NewsImage class NewsFeedSerializer(serializers.ModelSerializer): </code></pre> <p>Up to this, it's working fine I'm able to use models in serializer. Now I have to use serializer in my NewsfeedModel file, so I import serializer in NewsfeedModel file, but it's not allowing me to use.</p> <p>getting following error in the log:</p> <pre><code>ImportError: cannot import name NewsFeed </code></pre> <p>Is there any way to use serializer in model class?</p>
0
2016-10-08T14:25:51Z
40,043,340
<p>The way to work around a circular import is to remove one of the imports from the module level and do it inside the method where it is used. </p> <p>You haven't shown all the model code so I don't know where you use it, but if it's in <code>save</code> it would look like this:</p> <pre><code>def save(self, **kwargs): import serializers # rest of method </code></pre>
1
2016-10-14T12:36:36Z
[ "python", "django", "serialization", "django-models", "django-rest-framework" ]
Non-greedy matching of Word in pyparsing?
39,933,553
<p>I would like to match a word that ends with either <code>_foo</code> or <code>_bar</code>. I wrote this: </p> <pre><code>identifier = Word(alphanums + '_') string = identifier + Suppress('_') + oneOf('foo bar') </code></pre> <p>Unfortunately, I realized <code>identifier</code> is greedy and consume all the keyword. </p> <p>How do I force <code>identifier</code> to be not greedy?</p> <pre><code>$ string.parseString('a_keyword_foo') ParseException: Expected "_" (at char 13), (line:1, col:14) </code></pre> <p>Some valid keywords:</p> <pre><code>a_keyword_foo # ['a_keyword', 'foo'] foo_bar_foo # ['foo_bar', 'foo'] bar_bar # ['bar', 'bar'] </code></pre> <p>Some invalid keywords:</p> <pre><code>keyword_foo_foobar 2keywords_bar # The leading number is perhaps another question... foo _bar _foo </code></pre>
2
2016-10-08T14:28:01Z
39,934,768
<p>Once you know for what you're looking, you can use <a href="http://pyparsing.wikispaces.com/share/view/1552279" rel="nofollow"><code>pp.SkipTo</code></a>:</p> <pre><code>In [38]: foo_or_bar = Literal('foo') | Literal('bar') In [39]: string = SkipTo(Literal('_') + foo_or_bar) + Literal('_') + foo_or_bar In [42]: string.parseString('frumpy _foo') Out[42]: (['frumpy ', '_', 'foo'], {}) </code></pre> <hr> <p>Unfortunately, you also get this behavior, though:</p> <pre><code>In [44]: string.parseString('frumpy _foo _foo') Out[44]: (['frumpy ', '_', 'foo'], {}) </code></pre> <p>in case the pattern can appear more than once.</p> <p>The problem is that <code>pyparsing</code> doesn't do lookahead. If you're concerned about the second case too, you'll have to define it as one or more things ending with underscore + foo or bar (as above), and then take the last one.</p>
2
2016-10-08T16:35:44Z
[ "python", "pyparsing", "non-greedy" ]
Non-greedy matching of Word in pyparsing?
39,933,553
<p>I would like to match a word that ends with either <code>_foo</code> or <code>_bar</code>. I wrote this: </p> <pre><code>identifier = Word(alphanums + '_') string = identifier + Suppress('_') + oneOf('foo bar') </code></pre> <p>Unfortunately, I realized <code>identifier</code> is greedy and consume all the keyword. </p> <p>How do I force <code>identifier</code> to be not greedy?</p> <pre><code>$ string.parseString('a_keyword_foo') ParseException: Expected "_" (at char 13), (line:1, col:14) </code></pre> <p>Some valid keywords:</p> <pre><code>a_keyword_foo # ['a_keyword', 'foo'] foo_bar_foo # ['foo_bar', 'foo'] bar_bar # ['bar', 'bar'] </code></pre> <p>Some invalid keywords:</p> <pre><code>keyword_foo_foobar 2keywords_bar # The leading number is perhaps another question... foo _bar _foo </code></pre>
2
2016-10-08T14:28:01Z
39,935,874
<p>If you have to/can switch to the re api you can use non-greedy matching there:</p> <pre><code> import re p = re.compile (r"""([a-z_]+?) # lazy matching identifier _ (bar|foo) # _ with foo or bar """, re.VERBOSE) subject_string = 'a_hello_foo' m = p.match( subject_string ) print "groups:", m.groups() print "group 1:", m.group(1) </code></pre> <p>Within pyparsing there is also the possibility to use regex.</p>
1
2016-10-08T18:28:18Z
[ "python", "pyparsing", "non-greedy" ]
MultiProcessing slower with more processes
39,933,568
<p>I have a program written in python that reads 4 input text files and writes all of them into a list called <code>ListOutput</code> which is a shared memory between 4 processes used in my program (I used 4 processes so my program runs faster!)</p> <p>I also have a shared memory variable called <code>processedFiles</code> which stores the names of the already read input files by any of the processes so the current process does not read them again (I used lock so processes do not check the existence of a file inside <code>processedFiles</code> at the same time).</p> <p>When I only use one process my program runs faster(7 milliseconds) &mdash; my computer has 8 cores. Why is this?</p> <pre><code>import glob from multiprocessing import Process, Manager,Lock import timeit import os os.chdir("files") # Define a function for the Processes def print_content(ProcessName,processedFiles,ListOutput,lock): for file in glob.glob("*.txt"): newfile=0 lock.acquire() print "\n Current Process:",ProcessName if file not in processedFiles: print "\n", file, " not in ", processedFiles," for ",ProcessName processedFiles.append(file) newfile=1 #it is a new file lock.release() #if it is a new file if newfile==1: f = open(file,"r") lines = f.readlines() ListOutput.append(lines) f.close() #print "%s: %s" % ( ProcessName, time.ctime(time.time()) ) # Create processes as follows try: manager = Manager() processedFiles = manager.list() ListOutput = manager.list() start = timeit.default_timer() lock=Lock() p1 = Process(target=print_content, args=("Procees-1",processedFiles,ListOutput,lock)) p2 = Process(target=print_content, args=("Process-2",processedFiles,ListOutput,lock)) p3 = Process(target=print_content, args=("Process-3",processedFiles,ListOutput,lock)) p4 = Process(target=print_content, args=("Process-4",processedFiles,ListOutput,lock)) p1.start() p2.start() p3.start() p4.start() p1.join() p2.join() p3.join() p4.join() print "ListOutput",ListOutput stop = timeit.default_timer() print stop - start except: print "Error: unable to start process" </code></pre>
2
2016-10-08T14:29:19Z
39,933,783
<p>The problem is that what <em>looks</em> like multiprocessing often isn't. Just using more cores doesn't mean doing more work.</p> <p>The most glaring problem is that you synchronize everything. Selecting files is sequential because you lock, so there is zero gain here. While you are reading in parallel, every line read is written to a shared data structure - which will internally synchronize itself. So the only gain you <em>potentially</em> get is from reading in parallel. Depending on your media, e.g. an HDD instead of an SSD, the sum of multiple readers is actually slower than a single one.</p> <p>On top of that is the overhead from managing all those processes. Each one needs to be started. Each one needs to be passed its input. Each one must communicate with the others, which happens for practically every action. And don't be fooled, a <code>Manager</code> is nifty but heavyweight.</p> <p>So aside from gaining little, you add an additional cost. Since you start out with a very small runtime of just <code>7ms</code>, that additional cost can be pretty significant.</p> <p>In general, <code>multiprocessing</code> is only worth it if you are CPU-bound. That is, your CPU efficiency is close to 100%, i.e. there's more work than what can be done. Generally, this happens when you do lots of computation. Usually, doing mostly I/O is a good indicator that you are <em>not</em> CPU-bound.</p>
4
2016-10-08T14:51:32Z
[ "python", "multithreading", "multiprocessing" ]
MultiProcessing slower with more processes
39,933,568
<p>I have a program written in python that reads 4 input text files and writes all of them into a list called <code>ListOutput</code> which is a shared memory between 4 processes used in my program (I used 4 processes so my program runs faster!)</p> <p>I also have a shared memory variable called <code>processedFiles</code> which stores the names of the already read input files by any of the processes so the current process does not read them again (I used lock so processes do not check the existence of a file inside <code>processedFiles</code> at the same time).</p> <p>When I only use one process my program runs faster(7 milliseconds) &mdash; my computer has 8 cores. Why is this?</p> <pre><code>import glob from multiprocessing import Process, Manager,Lock import timeit import os os.chdir("files") # Define a function for the Processes def print_content(ProcessName,processedFiles,ListOutput,lock): for file in glob.glob("*.txt"): newfile=0 lock.acquire() print "\n Current Process:",ProcessName if file not in processedFiles: print "\n", file, " not in ", processedFiles," for ",ProcessName processedFiles.append(file) newfile=1 #it is a new file lock.release() #if it is a new file if newfile==1: f = open(file,"r") lines = f.readlines() ListOutput.append(lines) f.close() #print "%s: %s" % ( ProcessName, time.ctime(time.time()) ) # Create processes as follows try: manager = Manager() processedFiles = manager.list() ListOutput = manager.list() start = timeit.default_timer() lock=Lock() p1 = Process(target=print_content, args=("Procees-1",processedFiles,ListOutput,lock)) p2 = Process(target=print_content, args=("Process-2",processedFiles,ListOutput,lock)) p3 = Process(target=print_content, args=("Process-3",processedFiles,ListOutput,lock)) p4 = Process(target=print_content, args=("Process-4",processedFiles,ListOutput,lock)) p1.start() p2.start() p3.start() p4.start() p1.join() p2.join() p3.join() p4.join() print "ListOutput",ListOutput stop = timeit.default_timer() print stop - start except: print "Error: unable to start process" </code></pre>
2
2016-10-08T14:29:19Z
39,933,916
<p>Just to add to existing answer, there are certain cases where using <code>multiprocessing</code> really adds value and saves time:</p> <ol> <li>Your program does <em>N</em> tasks, which are independent of each other.</li> <li>Your program does extensive heavy mathematical calculations</li> <li>As a gotcha to second point, the computation time must be significantly larger. Otherwise, the cost of creation of new process will overshadow the advantage of multiprocessing and your parallel-processing designed program will run slower than a sequential version.</li> <li>In the ideal case, if your program does file I/O, network I/O operations, then don't parallelize your program, unless you have very strong reason to do so.</li> <li>To add to fourth point, if your requirement demands, then you can think of creating a <code>multiprocess.Pool</code>, which will be performing task for you, as needed and eliminates the overhead of creation and destruction of process every time.</li> </ol> <p>Hope it helps you.</p>
2
2016-10-08T15:05:37Z
[ "python", "multithreading", "multiprocessing" ]
Python - PyQt Signals - Emit and send argument to different class
39,933,593
<p>This is only my second question here so please do bear with me. I have a python script that currently contains two classes. One of which manages a GUI and the other is my 'worker thread' (a pyqt thread) . In order for me to be able to update the GUI from the 'worker thread' I understand that I can setup pyqt signals and emit these at different points. Back in the GUI thread I have set up connect statements which should connect to a function within the GUI thread which will update the GUI.</p> <p>In order for this GUI update function to know what it has to do with the GUI, the signal is also emitting an extra argument but this is not being picked up in the GUI thread. I think I know why this is happening but I can't work out how I can get it to work correctly.</p> <p>I would include some code but there are so many possible parts that could be included I thought I would wait and see what bits anyone specifically asks for.</p> <p>I hope someone can help me with this.</p> <p><strong>EDIT:</strong> Thank you for your answer farshed-. I should have put this in the original question, I am using PyQt 4. I know that a thread class should be run using 'start()' but when I do, the program crashes instantly and stops working. This has led me to use 'run()' to commence the thread after initializing it.</p> <p>Also, in your code segment the updateProgressBar method is called without being handed any arguments directly in the connect statement and only within the brackets where the method is defined, is it shown that the method will receive an argument. I have tried this with mine but it just tells me what you would expect to hear if you were calling any normal function and not providing the necessary number of arguments. Possibly this is because I am using PyQt 4 or it could be because I am directly calling 'run()' instead of 'start()'. Hopefully that can aid you to answer my question further if possible. Once again, please do mention if there are any code segments you would like me to include.</p> <p>Thanks,</p> <p>BoshJailey</p>
0
2016-10-08T14:31:46Z
39,933,960
<pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- import time import sys from PyQt5.QtWidgets import QApplication, QWidget, QProgressBar from PyQt5.QtCore import QThread, pyqtSignal class Thread(QThread): progress = pyqtSignal(int) def __init__(self): super(Thread, self).__init__() def __del__(self): self.wait() def run(self): for i in range(100): time.sleep(1); self.progress.emit(i) class Window(QWidget): def __init__(self): super(Window, self).__init__() self.initUI() def initUI(self): self.progressBar = QProgressBar(self) self.progressBar.setValue(0) self.thread = Thread() self.thread.progress.connect(self.updateProgressBar) self.thread.start() self.setGeometry(100, 100, 200, 200) self.setWindowTitle("Threading in PyQt5") self.show() def updateProgressBar(self, value): self.progressBar.setValue(value); if __name__ == "__main__": app = QApplication(sys.argv) window = Window() sys.exit(app.exec_()) </code></pre> <p>Let's see how threads work in PyQt5. So first you you need to create your custom Thread inherited from QThread. After ordinary initialization your main logic should be written in <code>run</code> method since this is the first method which will actually run after QThread.start() (right after initialization of course). So after you have written your custom thread you want to implement it in your application. So to do that we need to initialize your custom thread. Nothing special, this is just like initializing any <code>class</code> in python. But initializing your thread doesn't mean it's start. You should make it start. To do that we call <code>start()</code> method of QThread class. So still my example is the simplest way to use QThread. Our next goal is to get <code>message</code> from our custom thread. As we can see first we need to determine what kind of message our thread is supposed to send (in our case it is <code>int</code>). The <code>message</code> is said to be <code>signal</code> in PyQt5 so now we are to send our <code>message</code> through <code>pyqtSignal</code>. You can see how I created this signal before <code>__init__</code> in our custom <code>Thread</code>. So now to send any <code>signal</code> we just need to call <code>&lt;any_signal&gt;.emit(&lt;message&gt;)</code> method. Moreover don't forget to bind it with some method in our main logic. In our case we bind it to <code>self.updateProgressBar</code> method. So at every loop in <code>run</code> method our signal is sent to <code>self.updateProgressBar</code> method. A bit confusing thing is that we don't have to obviously declare that <code>self.updateProgressBar</code> method is going to get some parameters</p> <pre><code>self.thread.progress.connect(self.updateProgressBar) </code></pre> <p>But still it means that our thread is going to send some signal to this method. I know that it is a bit confusing and my answer is obviously not enough to understand this powerful tool. Hope I could help you at least to get basics. </p>
0
2016-10-08T15:10:04Z
[ "python", "multithreading", "signals-slots" ]
TypeError: relative imports require the package argument in python
39,933,604
<p>I just started learning Python(2.7) and facing an issue. I am using windows 10.</p> <p>I have created a virtual environment(c:\virtualenvs\testenv) and activated it. My app folder path is c:\pyprojects\pytest. This folder has got requirements.txt with all the packages listed.</p> <p>The prompt looks like</p> <pre><code>(testenv) c:\pyprojects\pytest\pip install -r requirements.txt </code></pre> <p>It installs all the required packages successfully under testenv. Then I ran the following command</p> <pre><code>(testenv) c:\pyprojects\pytest\python manage.py runserver </code></pre> <p>and got the following error--</p> <pre><code>Unhandled exception in thread started by &lt;function wrapper at 0x03ABF8F0&gt; Traceback (most recent call last): File "C:\virtualenvs\testenv\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\virtualenvs\testenv\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "C:\virtualenvs\testenv\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "C:\virtualenvs\testenv\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\virtualenvs\testenv\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\virtualenvs\testenv\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\virtualenvs\testenv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "c:\python27\Lib\importlib\__init__.py", line 30, in import_module raise TypeError("relative imports require the 'package' argument") TypeError: relative imports require the 'package' argument </code></pre> <p>Now I checked the file -- C:\Python27\Lib\importlib__init__.py and it says </p> <pre><code> if name.startswith('.'): if not package: raise TypeError("relative imports require the 'package' argument") level = 0 for character in name: if character != '.': break level += 1 name = _resolve_name(name[level:], package, level) __import__(name) return sys.modules[name] </code></pre> <p>There is no file in my app folder specially settings.py which starts with dot. Is it that my APP folder is not included in main python path? or I am missing something.</p> <p>Any help is highly appreciated.</p>
0
2016-10-08T14:33:07Z
39,934,050
<p>DJANGO_SETTINGS_MODULE is expected to be a Python module identifier, not a filesystem path. Looking at the django/conf/__init__py file, it seems that a relative path to your settings module won't work there. You will need to move it below a directory listed in your sys.path, or you should add a parent directory to your sys.path and reference your settings module from there.</p>
0
2016-10-08T15:19:10Z
[ "python", "django", "python-2.7" ]
how to check in a pandas DataFrame entry exists by (index, column)
39,933,630
<p>I have searched and searched but I can't find how to test whether a pandas data frame entry exists by (index, column).</p> <p>for example:</p> <pre><code>import pandas df = pandas.DataFrame() df.ix['apple', 'banana'] = 0.1 df.ix['apple', 'orange'] = 0.1 df.ix['kiwi', 'banana'] = 0.2 df.ix['kiwi', 'orange'] = 0.7 df banana orange apple 0.1 0.1 kiwi 0.2 0.7 </code></pre> <p>Now I want to test whether an entry exists</p> <pre><code>if (["apple", "banana"] in df) </code></pre> <p>.. should be <strong>True</strong></p> <p>and </p> <pre><code>if (["apple", "apple"] in df) </code></pre> <p>.. should be <strong>False</strong></p> <hr> <p>Actually the reason I'm testing for existence is because the following doesn't work</p> <pre><code>some loop .. df[wp] += some_value pass </code></pre> <p>It fails when df[wp] doesn't exist. This does work if the expression is</p> <pre><code>some loop .. df[wp] += some_value pass </code></pre> <p>because pandas does have the idea of extending an array through assignment.</p>
1
2016-10-08T14:36:11Z
39,933,808
<p>You can check for the existence in index and columns:</p> <pre><code>('kiwi' in df.index) and ('apple' in df.columns) </code></pre> <p>Or you can use a try/except block:</p> <pre><code>try: df.ix['kiwi', 'apple'] += some_value except KeyError: df.ix['kiwi', 'apple'] = some_value </code></pre> <p>Note that DataFrames' shapes are not meant to be dynamic. This may slow down your operations heavily. So it might be better to do these things with dictionaries and finally turn them into DataFrames.</p>
0
2016-10-08T14:54:22Z
[ "python", "pandas" ]
unorderable types: dict() <= int() in running OneVsRest Classifier
39,933,633
<p>I am running a multilabel classification on the input data with 330 features and about 800 records. I am leveraging RandomForestClassifier with following param_grid:</p> <pre><code>&gt; param_grid = {"n_estimators": [20], &gt; "max_depth": [6], &gt; "max_features": [80, 150], &gt; "min_samples_leaf": [1, 3, 10], &gt; "bootstrap": [True, False], &gt; "criterion": ["gini", "entropy"], &gt; "oob_score": [True, False]} </code></pre> <p>After cleaning up the data, this is how I am setting up the classifier and fit the model and apply a decision_fucntion:</p> <pre><code>classifier = OneVsRestClassifier(RandomForestClassifier(param_grid)) y_score = classifier.fit(X_train, y_train).descition_function(X_test) </code></pre> <p>X_train shape - (800, 334), Y_train shape - (800, 4). Number of classifications - 4. Running the code in sklearn 0.18</p> <p>However, runnning into the below error message:</p> <pre><code> --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-164-db76d3122db8&gt; in &lt;module&gt;() 1 classifier = OneVsRestClassifier(RandomForestClassifier(param_grid)) ----&gt; 2 y_score = classifier.fit(X_train, y_train).descition_function(X_test) 3 #clf = RandomForestClassifier() 4 #gr_search = grid_search.GridSearchCV(clf, param_grid02, cv=10, scoring = 'accuracy') /Users/ayada/anaconda/lib/python3.5/site-packages/sklearn/multiclass.py in fit(self, X, y) 214 "not %s" % self.label_binarizer_.classes_[i], 215 self.label_binarizer_.classes_[i]]) --&gt; 216 for i, column in enumerate(columns)) 217 218 return self /Users/ayada/anaconda/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in __call__(self, iterable) 756 # was dispatched. In particular this covers the edge 757 # case of Parallel used with an exhausted iterator. --&gt; 758 while self.dispatch_one_batch(iterator): 759 self._iterating = True 760 else: /Users/ayada/anaconda/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in dispatch_one_batch(self, iterator) 606 return False 607 else: --&gt; 608 self._dispatch(tasks) 609 return True 610 /Users/ayada/anaconda/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in _dispatch(self, batch) 569 dispatch_timestamp = time.time() 570 cb = BatchCompletionCallBack(dispatch_timestamp, len(batch), self) --&gt; 571 job = self._backend.apply_async(batch, callback=cb) 572 self._jobs.append(job) 573 /Users/ayada/anaconda/lib/python3.5/site-packages/sklearn/externals/joblib/_parallel_backends.py in apply_async(self, func, callback) 107 def apply_async(self, func, callback=None): 108 """Schedule a func to be run""" --&gt; 109 result = ImmediateResult(func) 110 if callback: 111 callback(result) /Users/ayada/anaconda/lib/python3.5/site-packages/sklearn/externals/joblib/_parallel_backends.py in __init__(self, batch) 320 # Don't delay the application, to avoid keeping the input 321 # arguments in memory --&gt; 322 self.results = batch() 323 324 def get(self): /Users/ayada/anaconda/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in __call__(self) 129 130 def __call__(self): --&gt; 131 return [func(*args, **kwargs) for func, args, kwargs in self.items] 132 133 def __len__(self): /Users/ayada/anaconda/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in &lt;listcomp&gt;(.0) 129 130 def __call__(self): --&gt; 131 return [func(*args, **kwargs) for func, args, kwargs in self.items] 132 133 def __len__(self): /Users/ayada/anaconda/lib/python3.5/site-packages/sklearn/multiclass.py in _fit_binary(estimator, X, y, classes) 78 else: 79 estimator = clone(estimator) ---&gt; 80 estimator.fit(X, y) 81 return estimator 82 /Users/ayada/anaconda/lib/python3.5/site-packages/sklearn/ensemble/forest.py in fit(self, X, y, sample_weight) 281 282 # Check parameters --&gt; 283 self._validate_estimator() 284 285 if not self.bootstrap and self.oob_score: /Users/ayada/anaconda/lib/python3.5/site-packages/sklearn/ensemble/base.py in _validate_estimator(self, default) 94 """Check the estimator and the n_estimator attribute, set the 95 `base_estimator_` attribute.""" ---&gt; 96 if self.n_estimators &lt;= 0: 97 raise ValueError("n_estimators must be greater than zero, " 98 "got {0}.".format(self.n_estimators)) TypeError: unorderable types: dict() &lt;= int() </code></pre>
0
2016-10-08T14:36:23Z
39,938,000
<p>Why are you trying to initialize RandomForestClassifier with parameter grid?</p> <p>If you want to do a Grid Search - look at examples here: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html#sklearn.model_selection.GridSearchCV</a></p>
1
2016-10-08T22:25:39Z
[ "python", "scikit-learn", "sklearn-pandas" ]
python raspberry pi digital dashboard for electric car
39,933,648
<p>For my master thesis we are building an electric car. For this I need to create a digital dash to show speed, rpm of the electric motor, temperatures,...</p> <p>I can program in python, but no experience in creating a interface like this. I searched on the internet for examples of digital dashes and found some nice ones. Most of the time they are programmed in qt5. Now is it possible to program qt5 in python? If yes could you help me to get started?</p>
0
2016-10-08T14:37:30Z
39,933,851
<p>Try wxpython for the UI design. Works great. Recently I've designed a UI for Raspi on wxpython itself.</p> <p>have a look</p> <p><a href="https://www.dropbox.com/s/f83dkc9hjhdbbdk/14632693_1206330069428934_64955080_o.png?dl=0" rel="nofollow">https://www.dropbox.com/s/f83dkc9hjhdbbdk/14632693_1206330069428934_64955080_o.png?dl=0</a></p> <p>Hope it inspires you. :)</p>
1
2016-10-08T14:59:00Z
[ "python", "raspberry-pi", "pyqt5" ]
Cassandra sometimes throws unauthorized error
39,933,659
<p>We have a multi-node Cassandra cluster and we use Cassandra python driver for our insert queries. Everything was fine till we removed one of our nodes from the cluster using following command:</p> <pre><code>nodetool removenode force </code></pre> <p>Now our driver meets following error not always but once in a while:</p> <pre><code>(&lt;class 'cassandra.Unauthorized'&gt;, Unauthorized(u'code=2100 [Unauthorized] message="User username has no MODIFY permission on &lt;table keyspace.tablename&gt; or any of its parents"',), &lt;traceback object at 0x7fe2447910e0&gt;) </code></pre> <p>We use same user for all our insert queries and it has all required permissions.</p> <p>What is our cluster's problem?</p> <p>More info: Cassandra version 3.0.0 Python driver version 3.0.0</p>
1
2016-10-08T14:38:17Z
39,936,452
<p>Since you forced a remove node data may now be inconsistent you should start with a repair on the <code>system_auth</code> keyspace.</p> <p>I would then follow up with a full repair of all the other keyspaces.</p>
2
2016-10-08T19:24:38Z
[ "python", "cassandra", "unauthorized" ]
Implementing raw input in a method
39,933,701
<p>I have the following class below but struggling to make the script work as intended. </p> <pre><code>class firstClass: def test(self): enter = raw_input() books = enter.split() books = [] for index in range(len(books)): print 'Current Books :', books[index] mybooks = firstClass() mybooks.test() </code></pre> <p>My end goal is to have a situation where if i enter <code>book1</code>, <code>book2</code> <code>book3</code> and so forth, i get a result like so ( I dont want to limit it to just three books)</p> <pre><code>Current Books, book1 Current Books, book2 Current Books, book3 </code></pre>
0
2016-10-08T14:42:04Z
39,933,759
<p>You are setting <code>books</code> properly with the line <code>books = enter.split()</code>. The next line <code>books = []</code> <em>overwrites</em> this value with an empty array, so the loop never happens. </p> <p>Removing that one line, it works as expected:</p> <pre><code>&gt;&gt;&gt; class firstClass: ... def test(self): ... enter = raw_input() ... books = enter.split() ... for index in range(len(books)): ... print 'Current Books :', books[index] ... &gt;&gt;&gt; mybooks = firstClass() &gt;&gt;&gt; mybooks.test() book1 book2 book3 Current Books : book1 Current Books : book2 Current Books : book3 </code></pre> <p>As you probably know, <code>split()</code> without any arguments will split on whitespace, so this assumes that the input is entered with spaces in between. You will have to specify another delimiter (like a comma) explicitly if that is the case.</p> <p>As another note, <code>index for range(len(arr))</code> is an anti-pattern in Python that should almost always be avoided. You for loop can be rewritten this way for readability:</p> <pre><code>for book in books: print 'Current Books :', book </code></pre>
1
2016-10-08T14:48:15Z
[ "python", "python-2.7" ]
Implementing raw input in a method
39,933,701
<p>I have the following class below but struggling to make the script work as intended. </p> <pre><code>class firstClass: def test(self): enter = raw_input() books = enter.split() books = [] for index in range(len(books)): print 'Current Books :', books[index] mybooks = firstClass() mybooks.test() </code></pre> <p>My end goal is to have a situation where if i enter <code>book1</code>, <code>book2</code> <code>book3</code> and so forth, i get a result like so ( I dont want to limit it to just three books)</p> <pre><code>Current Books, book1 Current Books, book2 Current Books, book3 </code></pre>
0
2016-10-08T14:42:04Z
39,933,770
<p>Just remove 5th line, your code will work fine.</p> <pre><code>class firstClass: def test(self): enter = raw_input() books = enter.split() for index in range(len(books)): print 'Current Books :', books[index] mybooks = firstClass() mybooks.test() </code></pre>
0
2016-10-08T14:49:52Z
[ "python", "python-2.7" ]
Selecting a pandas dataframe by name string generated within the code
39,933,704
<p>I'm writing up few lines in python where I have created 3 pandas dataframes DF_A, dF_B, dF_C. In the next step I do something &amp; read a string. If the string = 'A' then I want to go to dF_A(&amp; so on for B&amp;C). Any help on how this can be done?</p> <pre><code>DF = pd.ExcelFile('File.xlsx') DF_A = Dev.parse("A") DF_B = Dev.parse("B") DF_C = Dev.parse("C") tmp = ['B', 'A', 'C', 'A', 'A', 'B'] foo = {} for i in range(len(tmp)): table = 'DF_'+tmp[i] foo[tmp[i]] = table[0] </code></pre>
0
2016-10-08T14:42:23Z
39,933,791
<p>It is possible to use <code>vars()</code>, though it's hacky</p> <pre><code>for i in tmp: # do not iterate by index table = vars()['DF_' + i] </code></pre> <p>It is cleaner to just store tables in a dictionary in the first place</p> <pre><code>tables = {} for i in ['A', 'B', 'C']: tables[i] = Dev.parse(i) for i in tmp: table = tables['DF_' + i] </code></pre>
1
2016-10-08T14:52:21Z
[ "python", "pandas" ]
Consecutive values?
39,933,813
<p>Learning python, but having trouble telling function to find consecutive locations with same values. When I run the code, there's no errors but gives out the incorrect output. Suggestions on what to change?</p> <pre><code>def same_values(xs): same = False for i in (xs): if xs == xs[1:]: same = True else: return same same_values('Misses') # This should return as true </code></pre>
0
2016-10-08T14:55:08Z
39,933,877
<p>So you are looking for a consecutive pair in the list and returning true if you find one. </p> <pre><code>def same_values(xs): for i in range(len(xs)-1): if xs[i] == xs[i+1]: return True return False &gt;&gt;&gt; same_values('misses') True &gt;&gt;&gt; same_values('mises') False </code></pre> <p>Would give you the correct answer.<br> However python has a powerful iterator algebra. The advantage of this is that it would work with iterators (iterators don't generally support <code>len()</code>) as well as lists:</p> <pre><code>import itertools as it def same_values(xs): a, b = it.tee(xs) next(b, None) return any(x == y for x, y in zip(a, b)) </code></pre> <p>This pattern is described in the <code>itertools</code> recipes as <a href="https://docs.python.org/3.5/library/itertools.html?highlight=pairwise" rel="nofollow"><code>pairwise</code></a>:</p> <pre><code>import itertools as it def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = it.tee(iterable) next(b, None) return zip(a, b) def same_values(xs): return any(x == y for x, y in pairwise(xs)) </code></pre> <p>For example to check if any 2 consecutive lines in a file are the same (this wouldn't work with the <code>list</code> version):</p> <pre><code>with open('somefile') as f: print(same_values(f)) </code></pre>
3
2016-10-08T15:01:29Z
[ "python", "function" ]
Importing image into Tkinter - Python 3.5
39,933,831
<p>I'm majorly struggling to import an image into <strong>Tkinter</strong> for <strong>Python 3.5</strong>, this is for my A2 project and have hit a brick wall with every method of <strong>importing a .JPG file</strong> to my window. What I have below is my GUI layer for another window, based off another thread I found but didn't work at all. Any assistance appreciated.</p> <pre><code>import tkinter from tkinter import * root=Tk() root.geometry('1000x700') root.resizable(False, False) root.title("Skyrim: After Alduin") photo = PhotoImage(file="Skyrim_Map") map=Label(root, image=photo) map.photo=photo map.pack() root.mainloop() </code></pre> <p><strong>Here's the error I receive:</strong></p> <pre><code>Traceback (most recent call last): File "E:\Programming\Text_Adventure_Project\GUI_Interface-S_AA.py", line 14, in &lt;module&gt; photo = PhotoImage(file="Skyrim_Map") File "C:\Users\Harrison\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 3393, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Users\Harrison\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 3349, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't open "Skyrim_Map": no such file or directory </code></pre>
-1
2016-10-08T14:57:14Z
39,937,321
<p>First check the path if with the correct path still persist the error "no such file or directory" please edit and put the newest version of your code. If the error is "couldn't recognize data in image file" you can correct using PIL</p> <pre><code> [...] from PIL import ImageTk [...] photo = ImageTk.PhotoImage(file='Skyrim_Map.jpg') [...] </code></pre>
0
2016-10-08T21:00:45Z
[ "python", "image", "import", "tkinter", "tk" ]
trying to sort a user input list
39,933,862
<p>Im new at python. Im creating a script that allows a user to input three names and then the code should print the names and then print them sorted (alphabetically). I can get the code to return the sorted individual letters, but not the full names as strings. I really want to run AS A LOOP!!!here is what i have so far</p> <pre><code>print ('Enter three names, when done hit enter with a blank: ') a = (raw_input('enter first name: ')) b = (raw_input('enter first name: ')) c = (raw_input('enter first name: ')) while not raw_input == "": print a + b + c break srtd = a + b + c name = srtd for name in sorted(srtd): print name </code></pre>
0
2016-10-08T15:00:43Z
39,934,845
<pre><code>print "Enter three names\n" a = raw_input("Enter first name: ") b = raw_input("Enter second name: ") c = raw_input("Enter third name: ") names = [a, b, c] print a, b, c for name in sorted(names): print name </code></pre>
0
2016-10-08T16:44:05Z
[ "python", "loops", "sorting" ]
trying to sort a user input list
39,933,862
<p>Im new at python. Im creating a script that allows a user to input three names and then the code should print the names and then print them sorted (alphabetically). I can get the code to return the sorted individual letters, but not the full names as strings. I really want to run AS A LOOP!!!here is what i have so far</p> <pre><code>print ('Enter three names, when done hit enter with a blank: ') a = (raw_input('enter first name: ')) b = (raw_input('enter first name: ')) c = (raw_input('enter first name: ')) while not raw_input == "": print a + b + c break srtd = a + b + c name = srtd for name in sorted(srtd): print name </code></pre>
0
2016-10-08T15:00:43Z
39,935,093
<p>you can use a list in python it has a good function called sort you can call it from list code <br></p> <pre><code>print ('Enter three names, when done hit enter with a blank: ') a = (raw_input('enter first name: ')) b = (raw_input('enter first name: ')) c = (raw_input('enter first name: ')) my_list = [a,b,c] my_list.sort() print my_list </code></pre> <p>if you want to print without the brackets use loop hope this helpful </p>
1
2016-10-08T17:10:35Z
[ "python", "loops", "sorting" ]
variables not defined in if statements for change counting program
39,933,883
<p>I'm making a change counter and I'm having trouble printing the percentage for a grade, whenever I run the program I can enter as many inputs as I want, however, when I type done, which is supposed to terminate the program and leave the user with the percentage and letter grade, it just ends the program. If I could get any advice it would be greatly appreciated. here's my code:</p> <pre><code>grade="" total=0 count=1 scores='' while scores != 'done': scores=input("Enter Homework score: ") if scores.isdigit(): numeric=int(scores) percentage=(numeric*10/count) elif percentage &gt;= 92 and percentage &lt; 100: letter = 'A' elif percentage &gt;= 87 and percentage &lt; 92: letter = 'B+' elif percentage &gt;= 80 and percentage &lt; 87: letter = 'B' elif percentage &gt;=77 and percentage &lt; 80: letter = 'C+' elif percentage &gt;=70 and percentage &lt; 77: letter = 'C' elif percentage &gt;= 67 and percentage &lt; 70: letter = 'D+' elif percentage &gt;= 60 and percentage &lt; 67: letter = 'D' elif percentage &lt; 60 and percentage &gt;= 0: letter= 'F' elif (numeric) &lt; 0: print("Score must be between 0 and 10") elif (numeric) &gt; 10: print("Score must be between 0 and 10") elif (scores)== 'done': print(percentage,"% and you got an, ",letter) </code></pre>
1
2016-10-08T15:02:07Z
39,934,094
<p>Your conditional logic is flawed. You are never assessing the grade (<code>letter</code>) if the <code>score.isdigit()</code>:</p> <pre><code>while scores != 'done': scores=input("Enter Homework score: ") if scores.isdigit(): numeric=int(scores) percentage=(numeric*10/count) if percentage &gt;= 92 and percentage &lt; 100: letter = 'A' elif percentage &gt;= 87 and percentage &lt; 92: letter = 'B+' ... </code></pre> <p>It is often cleaner to jump out of the loop if the initial condition is false, e.g.:</p> <pre><code>while scores != 'done': scores=input("Enter Homework score: ") if not scores.isdigit(): continue numeric=int(scores) percentage=(numeric*10/count) if 92 &lt;= percentage &lt; 100: letter = 'A' elif 87 &lt;= percentage &lt; 92: letter = 'B+' ... </code></pre> <p>Also in python your shouldn't be afraid of exceptions. A common idiom in python is EAFP (Easier to Ask for Forgiveness than Permission):</p> <pre><code>while scores != 'done': scores=input("Enter Homework score: ") try: numeric = int(scores) except ValueError: continue </code></pre> <p>You might also want to think about better ways of doing the large grade <code>if</code> <code>elif</code> <code>elif</code> ... block. E.g. an alternative approach would be define a dictionary of the grades:</p> <pre><code>grades = {'A': (92, 100), 'B+': (87, 92)} # Etc.. score = 93 _, letter = max((low &lt;= score &lt; high, letter) for letter, (low, high) in grades.items()) print(letter) # 'A' </code></pre>
2
2016-10-08T15:24:44Z
[ "python" ]
variables not defined in if statements for change counting program
39,933,883
<p>I'm making a change counter and I'm having trouble printing the percentage for a grade, whenever I run the program I can enter as many inputs as I want, however, when I type done, which is supposed to terminate the program and leave the user with the percentage and letter grade, it just ends the program. If I could get any advice it would be greatly appreciated. here's my code:</p> <pre><code>grade="" total=0 count=1 scores='' while scores != 'done': scores=input("Enter Homework score: ") if scores.isdigit(): numeric=int(scores) percentage=(numeric*10/count) elif percentage &gt;= 92 and percentage &lt; 100: letter = 'A' elif percentage &gt;= 87 and percentage &lt; 92: letter = 'B+' elif percentage &gt;= 80 and percentage &lt; 87: letter = 'B' elif percentage &gt;=77 and percentage &lt; 80: letter = 'C+' elif percentage &gt;=70 and percentage &lt; 77: letter = 'C' elif percentage &gt;= 67 and percentage &lt; 70: letter = 'D+' elif percentage &gt;= 60 and percentage &lt; 67: letter = 'D' elif percentage &lt; 60 and percentage &gt;= 0: letter= 'F' elif (numeric) &lt; 0: print("Score must be between 0 and 10") elif (numeric) &gt; 10: print("Score must be between 0 and 10") elif (scores)== 'done': print(percentage,"% and you got an, ",letter) </code></pre>
1
2016-10-08T15:02:07Z
39,934,204
<p>Your code should look similar to the one below. Although I still cannot assess the logic behind your program (because you did not explain that in your question, e.g. <code>percentage=(numeric*10/count)</code> does not seem quite right to me, etc.), but the code below solves your current problem (based on your current question). </p> <pre><code>grade="" total=0 count=1 scores='' percentage = 0 while scores != 'done': scores=input("Enter Homework score: ") if scores.isdigit(): numeric=int(scores) if numeric &lt; 0: print("Score must be between 0 and 10") elif numeric &gt; 10: print("Score must be between 0 and 10") percentage=(numeric*10/count) if percentage &gt;= 92 and percentage &lt; 100: # I would change this to if percentage &gt;= 92 and percentage &lt;= 100: letter = 'A' elif percentage &gt;= 87 and percentage &lt; 92: letter = 'B+' elif percentage &gt;= 80 and percentage &lt; 87: letter = 'B' elif percentage &gt;=77 and percentage &lt; 80: letter = 'C+' elif percentage &gt;=70 and percentage &lt; 77: letter = 'C' elif percentage &gt;= 67 and percentage &lt; 70: letter = 'D+' elif percentage &gt;= 60 and percentage &lt; 67: letter = 'D' elif percentage &lt; 60 and percentage &gt;= 0: #I would change this to else: letter= 'F' print(percentage,"% and you got an, ",letter) </code></pre>
0
2016-10-08T15:36:10Z
[ "python" ]
Some cases cause my binary search to enter into an Infinite loop
39,933,884
<p>I'm stuck in an infinite loop when searching for anything that is not in the list (but within the range of the list) and anything that is greater than the highest number. For example, when searching for 2 in the list <code>[1,2,5,6]</code>, my function returns index 1, which is correct. If I search for -1, it returns <code>False</code> which is correct. However, if I search for 100 or 4, it gets stuck in an infinite loop. </p> <pre><code>def binary_search(a_list, item): if not a_list: return False mid = len(a_list)//2 print "Middle is: {}".format(a_list[mid]) print a_list while len(a_list) &gt; 0: if a_list[mid] == item: return mid elif a_list[mid] &gt; item: return binary_search(a_list[:mid], item) elif a_list[mid] &lt; item: return binary_search(a_list[mid:], item) + mid else: return False a = binary_search([1, 2, 3, 4, 6, 7, 8], 5) # infinite loop b = binary_search([1, 2, 3, 4, 6, 7, 8], 100) # infinite loop c = binary_search([1, 2, 3, 4, 6, 7, 8], 8) # works correctly d = binary_search([1, 2, 3, 4, 6, 7, 8], -2) # works correctly </code></pre>
2
2016-10-08T15:02:10Z
39,933,925
<p>In a return under condition <code>a_list[mid] &lt; item</code> change the line</p> <pre><code>return binary_search(a_list[mid:], item) + mid </code></pre> <p>To the line</p> <pre><code>return binary_search(a_list[mid+1:], item) </code></pre> <p>Now the <code>mid</code> element gets included to the new list</p> <p>UPD: also do not add <code>mid</code> to answer</p> <p>UPD2: if you need an index and not only true or false, use start and end indexes</p> <pre><code>def binary_search(a_list, item, start=0, end=None): end = end or len(a_list) if start == end: if a_list[start] == item: return start return False mid = start + ((end - start)//2) if a_list[mid] == item: return mid elif a_list[mid] &gt; item: return binary_search(a_list, item, start=start, end=mid) elif a_list[mid] &lt; item: return binary_search(a_list, item, start=mid+1, end=end) else: return False </code></pre>
1
2016-10-08T15:06:22Z
[ "python", "binary-search" ]
Some cases cause my binary search to enter into an Infinite loop
39,933,884
<p>I'm stuck in an infinite loop when searching for anything that is not in the list (but within the range of the list) and anything that is greater than the highest number. For example, when searching for 2 in the list <code>[1,2,5,6]</code>, my function returns index 1, which is correct. If I search for -1, it returns <code>False</code> which is correct. However, if I search for 100 or 4, it gets stuck in an infinite loop. </p> <pre><code>def binary_search(a_list, item): if not a_list: return False mid = len(a_list)//2 print "Middle is: {}".format(a_list[mid]) print a_list while len(a_list) &gt; 0: if a_list[mid] == item: return mid elif a_list[mid] &gt; item: return binary_search(a_list[:mid], item) elif a_list[mid] &lt; item: return binary_search(a_list[mid:], item) + mid else: return False a = binary_search([1, 2, 3, 4, 6, 7, 8], 5) # infinite loop b = binary_search([1, 2, 3, 4, 6, 7, 8], 100) # infinite loop c = binary_search([1, 2, 3, 4, 6, 7, 8], 8) # works correctly d = binary_search([1, 2, 3, 4, 6, 7, 8], -2) # works correctly </code></pre>
2
2016-10-08T15:02:10Z
39,934,083
<p>Try this.</p> <pre><code>def binary_search(a_list, item): if not a_list: return False mid = len(a_list)//2 print "Middle is: {}".format(a_list[mid]) print a_list while len(a_list) &gt; 0: if len(a_list) == 1 and a_list[mid] != item: return False elif a_list[mid] == item: return mid elif a_list[mid] &gt; item: return binary_search(a_list[:mid], item) ############################## ### isssue place ### #################### elif a_list[mid] &lt; item: index = binary_search(a_list[mid:], item) if not index: return False else: return index + mid else: return False ################################ </code></pre> <p>Hpoe this helps.</p>
0
2016-10-08T15:23:28Z
[ "python", "binary-search" ]
Some cases cause my binary search to enter into an Infinite loop
39,933,884
<p>I'm stuck in an infinite loop when searching for anything that is not in the list (but within the range of the list) and anything that is greater than the highest number. For example, when searching for 2 in the list <code>[1,2,5,6]</code>, my function returns index 1, which is correct. If I search for -1, it returns <code>False</code> which is correct. However, if I search for 100 or 4, it gets stuck in an infinite loop. </p> <pre><code>def binary_search(a_list, item): if not a_list: return False mid = len(a_list)//2 print "Middle is: {}".format(a_list[mid]) print a_list while len(a_list) &gt; 0: if a_list[mid] == item: return mid elif a_list[mid] &gt; item: return binary_search(a_list[:mid], item) elif a_list[mid] &lt; item: return binary_search(a_list[mid:], item) + mid else: return False a = binary_search([1, 2, 3, 4, 6, 7, 8], 5) # infinite loop b = binary_search([1, 2, 3, 4, 6, 7, 8], 100) # infinite loop c = binary_search([1, 2, 3, 4, 6, 7, 8], 8) # works correctly d = binary_search([1, 2, 3, 4, 6, 7, 8], -2) # works correctly </code></pre>
2
2016-10-08T15:02:10Z
39,934,554
<p>Here is the code I used to examine your program. <code>pdb</code> allows you to step through the code one command at a time using <code>s</code> or continue to the next <code>pdb.set_trace()</code> using <code>c</code>. You use it like this:</p> <pre><code>import pdb def binary_search(a_list, item): if not a_list: return False mid = len(a_list)//2 print "Middle is: {}".format(a_list[mid]) print a_list print a_list, item pdb.set_trace() while len(a_list) &gt; 0: if a_list[mid] == item: return mid elif a_list[mid] &gt; item: return binary_search(a_list[:mid], item) elif a_list[mid] &lt; item: return binary_search(a_list[mid:], item) + mid else: return False </code></pre> <p>Now, there are a number of problems with your program, most notably the combination of looping and recursion. That is rarely correct. I will also point out that every case in your <code>while</code> loop has a return statement, so the <code>while</code> loop only has the effect of causing a search with a list size of <code>0</code> to return nothing at all. I doubt this is what you want.</p> <p>The second problem is with you trying to return either the index of <code>mid</code> or <code>False</code>. There is no problem with what you're trying to do. The problem is with adding <code>binary_search(...)</code> to <code>mid</code>. The reason this is bad is that in Python, <code>False</code> evaluates to <code>0</code> when you use it like a number. Try running these in an interpreter:</p> <pre><code>False * 5 # =&gt; 0 False + 5 # =&gt; 5 False == 0 # =&gt; True False is 0 # =&gt; False </code></pre> <p>This means that if your code worked otherwise and there was an unsuccessful search, you would still end up returning an integer answer a lot of the time. The <code>False</code> value would be lost in the addition to <code>mid</code>. To avoid this, the code I give below does not use recursion, so a <code>return False</code> is final. It goes directly to whoever called <code>binary_search</code> in the first place and not to any previous recursive calls. You could still write a recursive solution, but you would almost certainly need to have a comparison like <code>if binary_search(...) is False:</code> somewhere in your code <em>then</em> you would need to worry about the difference between <code>is</code> and <code>==</code> <em>then</em> you might be tempted to use <code>is</code> more frequently, which is a bad idea.</p> <p>I also believe there are also some issues with <code>a_list[mid:]</code>. I did not confirm this, but I think you would want <code>a_list[mid+1:]</code> to exclude the middle element which you've confirmed is not the element you're looking for. Either way, the alternative code I have does not use slicing at all so I am not going to worry about it. </p> <p>Here is the code which I believe does what you want.</p> <pre><code>def binary_search(a_list, item): if not a_list: return False mid = len(a_list)//2 start = 0 # new and important end = len(a_list) # new and important while start &lt; end: # new and important if a_list[mid] &gt; item: end = mid mid = (end - start) // 2 # new and important elif a_list[mid] &lt; item: start = mid + 1 mid = start + (end - start) // 2 # new and important else: return mid return False </code></pre> <p>Note the removal of the recursive calls and the addition of <code>start</code> and <code>end</code>. These keep track of which part of the list you're searching in instead of the list slices you were using before. </p>
1
2016-10-08T16:14:03Z
[ "python", "binary-search" ]
UPLOAD file to django
39,934,078
<p>I try to upload a file to django from html through an ajax call.</p> <p>CLIENT SIDE:</p> <pre><code>&lt;input type="file" class="text-field" name="media"&gt; &lt;input type="button" class="btn" value="SEND"&gt; var files; $('.text-field').change(function(){ files = this.files; console.log(files); }); $('.btn').click(function(){ var data = new FormData(); $.each(files, function(key, value){ data.append(key, value); console.log(key + ' : ' + value); console.log(value); }); $.ajax({ type: 'POST', url: 'url', enctype: 'multipart/form-data', data: data, cache: false, dataType: 'json', processData: false, contentType: false, success: function(data){ console.log(data); } }); </code></pre> <p>BACK side:</p> <pre><code>@csrf_exempt def my_file(request): print request.POST print request.FILES </code></pre> <p>result:</p> <pre><code>MultiValueDict: {u'0': [TemporaryUploadedFile: about.php (application/octet-stream)]} </code></pre> <p>Please help me to understand how I can upload a file</p>
1
2016-10-08T15:21:56Z
39,934,230
<p>To upload a file through Django, you will most likely have to use django forms. Here is an example as for how to upload a file:</p> <pre><code>def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): instance = ModelWithFileField(file_field=request.FILES['file']) instance.save() return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) </code></pre> <p>As you can see the form validates your input, and then you can save the file in to your server. For more information about this topic please use the django documentation:</p> <p><a href="https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/</a></p>
0
2016-10-08T15:38:26Z
[ "python", "django", "file" ]
Object is not callable
39,934,169
<p>I make this condition:</p> <pre><code>if ((liste_mois[0]==3) or (liste_mois[0]==6) (liste_mois[0]==9) or (liste_mois[0]==12)) </code></pre> <p>i got: TypeError: 'bool' object is not callable</p>
0
2016-10-08T15:31:39Z
39,934,217
<p>you missed an "or" in between.</p>
1
2016-10-08T15:37:07Z
[ "python", "python-2.7", "odoo-8" ]
Object is not callable
39,934,169
<p>I make this condition:</p> <pre><code>if ((liste_mois[0]==3) or (liste_mois[0]==6) (liste_mois[0]==9) or (liste_mois[0]==12)) </code></pre> <p>i got: TypeError: 'bool' object is not callable</p>
0
2016-10-08T15:31:39Z
39,934,286
<p>You've got:</p> <blockquote> <p>TypeError: 'bool' object is not callable</p> </blockquote> <p>just because you're doing something like that:</p> <pre><code>(liste_mois[0]==6) (liste_mois[0]==9) </code></pre> <p>which could be represented as, let's say:</p> <pre><code>(True) (False) </code></pre> <p>and going further:</p> <pre><code>(True)() </code></pre> <p>so in your statement you treat boolean value <code>(liste_mois[0]==6)</code> as a function, because you're trying to invoke it. And because boolean value is not callable, that's the reason you see this error.</p> <p>Similar example to <code>(liste_mois[0]==6) (liste_mois[0]==9)</code> could be:</p> <pre><code>def something(): pass (something)() # &lt;-- this </code></pre> <p>So solution for you will be to put <code>or</code> in your <code>if</code> condition, so:</p> <pre><code>if ((liste_mois[0]==3) or (liste_mois[0]==6) or (liste_mois[0]==9) or (liste_mois[0]==12)) </code></pre> <p>and I think that is what you want.</p>
1
2016-10-08T15:44:02Z
[ "python", "python-2.7", "odoo-8" ]
Python: remove files older than X days
39,934,173
<p>I have this script to remove all images from a server directory:</p> <pre><code>import ftplib ftp = ftplib.FTP("server", "user", "pass") files = ftp.dir('/') ftp.cwd("/html/folder/") filematch = '*.jpg' target_dir = '/html/folder' import os for filename in ftp.nlst(filematch): ftp.delete(filename) </code></pre> <p>Any advice on how to add a filter for the file match "older than three days"?</p> <p>Thanks </p>
0
2016-10-08T15:32:29Z
39,934,341
<p>In python 3.3+ was added <code>mlsd</code> command support, which allows you to get the <code>facts</code> as well as list the directory.</p> <p>So your code should be like this:</p> <pre><code>filematch = '.jpg' target_dir = '/html/folder' import os for filename, create, modify in ftp.mlsd(target_dir, facts=['create', 'modify']): if filename.endswith(file_match) and create &gt; older_date: ftp.delete(filename) </code></pre> <p>Note that <code>mlsd</code> command is not supported in every server.</p> <p>More info available here:</p> <p><a href="https://docs.python.org/3/library/ftplib.html" rel="nofollow">https://docs.python.org/3/library/ftplib.html</a></p> <p><a href="https://tools.ietf.org/html/rfc3659.html" rel="nofollow">https://tools.ietf.org/html/rfc3659.html</a> </p>
0
2016-10-08T15:50:15Z
[ "python", "ftp" ]
fors in python list comprehension
39,934,187
<p>Consider I have nested for loop in python list comprehension</p> <pre><code>&gt;&gt;&gt; data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] &gt;&gt;&gt; [y for x in data for y in x] [0, 1, 2, 3, 4, 5, 6, 7, 8] &gt;&gt;&gt; [y for y in x for x in data] [6, 6, 6, 7, 7, 7, 8, 8, 8] </code></pre> <p>I can't explain why is that when i change the order of two <code>fors</code> </p> <pre><code>for y in x </code></pre> <p>What's <code>x</code> in second list comprehension?</p>
4
2016-10-08T15:34:25Z
39,934,209
<p>It's holding the value of the previous comprehsension. Try inverting them, you'll get an error</p> <pre><code>&gt;&gt;&gt; data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] &gt;&gt;&gt; [y for y in x for x in data] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined </code></pre> <p>To further test it out, print <code>x</code> and see </p> <pre><code>&gt;&gt;&gt; [y for x in data for y in x] [0, 1, 2, 3, 4, 5, 6, 7, 8] &gt;&gt;&gt; x [6, 7, 8] &gt;&gt;&gt; [y for y in x for x in data] [6, 6, 6, 7, 7, 7, 8, 8, 8] </code></pre>
6
2016-10-08T15:36:21Z
[ "python", "list", "python-2.7", "for-loop", "list-comprehension" ]
fors in python list comprehension
39,934,187
<p>Consider I have nested for loop in python list comprehension</p> <pre><code>&gt;&gt;&gt; data = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] &gt;&gt;&gt; [y for x in data for y in x] [0, 1, 2, 3, 4, 5, 6, 7, 8] &gt;&gt;&gt; [y for y in x for x in data] [6, 6, 6, 7, 7, 7, 8, 8, 8] </code></pre> <p>I can't explain why is that when i change the order of two <code>fors</code> </p> <pre><code>for y in x </code></pre> <p>What's <code>x</code> in second list comprehension?</p>
4
2016-10-08T15:34:25Z
39,934,236
<p>The list comprehensions are as:</p> <pre><code>[y for x in data for y in x] [y for y in x for x in data] </code></pre> <p>A <code>for</code> loop conversion of <code>[y for y in x for x in data]</code> is:</p> <pre><code>for y in x: for x in data: y </code></pre> <p>Here <code>x</code> is holding the last updated value of <code>x</code> of your previous list comprehension which is:</p> <pre><code>[6, 7, 8] </code></pre>
2
2016-10-08T15:38:41Z
[ "python", "list", "python-2.7", "for-loop", "list-comprehension" ]
Plotting Smith chart using PySmithPlot
39,934,233
<p>I'm trying to plot Smith chart in python using PySmithPlot, it has to be placed along some other items in frame, but i can't find a way to do so. I have managed to make plots with matplotlib, but didn't have any luck so far with Smiths chart. Can anyone give me a reference to a site where i could find explanation to my problem?</p> <pre><code>import matplotlib as mp from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg import tkinter as tk from tkinter import ttk from matplotlib import style from PIL import Image, ImageTk from matplotlib.figure import Figure from tkinter import Tk, W, E from tkinter.ttk import Frame, Button, Style, Entry from matplotlib import pyplot as plt import matplotlib.pylab as pl import smithplot from smithplot import SmithAxes mp.use("TkAgg") f = Figure(figsize=(5, 5), dpi=100) class Dizajn(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) tk.Tk.wm_title(self, "title") container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (Home, FirstPage): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(Home) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class Home(tk.Frame): def __init__(self, parent, cont): tk.Frame.__init__(self, parent) ax = f.add_subplot(111, projection="smith") pl.show() self.grid() app = Dizajn() app.mainloop() </code></pre> <p>And this is the last line of error report in transform_path_non_affine NotImplementedError: Value for 'path_interpolation' cannot be interpreted.</p>
-1
2016-10-08T15:38:31Z
39,935,375
<p><code>PySmithPlot</code> provides a new <code>projection</code> which you can pass to e.g. <code>subplot()</code> or <code>add_subplot()</code>:</p> <pre><code>import matplotlib.pylab as pl import smithplot from smithplot import SmithAxes fig = pl.figure() ax1 = fig.add_subplot(121) ax1.plot([(1, 2), (3, 4)], [(4, 3), (2, 3)]) ax2 = fig.add_subplot(122, projection='smith') pl.show() </code></pre> <p><a href="http://i.stack.imgur.com/nDK1m.png" rel="nofollow"><img src="http://i.stack.imgur.com/nDK1m.png" alt="enter image description here"></a></p>
0
2016-10-08T17:37:33Z
[ "python", "matplotlib" ]
Python Ephem sunset and sunrise
39,934,242
<p>I am trying to calculate the exact amount of daylight hours for a given day and location. I have been looking at the python module "Ephem" for the sunrise and set calculation. Here is the code below:</p> <pre><code>import ephem California_forest = ephem.Observer() California_forest.date = '2001/01/01 00:00' California_forest.pressure = 0 California_forest.horizon = '-0:34' California_forest.lat, California_forest.lon = '38.89525', '-120.63275' California_forest.altitude = 1280 print(California_forest.previous_rising(ephem.Sun())) 2000/12/31 15:21:06 print(California_forest.previous_rising(ephem.Sun())) 2001/1/1 00:50:46 </code></pre> <p>The module works just fine like its tutorial showed. However, I thought you could save the "sunrise" and "sunset" output as a string. When I saved the calculation to a variable, it gives me a floating number that I dont understand:</p> <pre><code>sunrise = California_forest.previous_rising(ephem.Sun()) sunrise 36890.13965508334 sunset = California_forest.next_setting(ephem.Sun()) sunset 36890.53525430675 </code></pre> <p>I was expecting a string that was the same as the print statement output, but I was mistaken. Does anyone have a suggestion as to how I can use these outputs and calculate the amount of daylight hours for a given location? It would be greatly appreciated!</p>
2
2016-10-08T15:39:02Z
39,934,363
<p>What you really what is the string representation of your object. If you must get the string representation of it, then call the <code>__str__()</code> special method as follows.</p> <pre><code>sunrise = California_forest.previous_rising(ephem.Sun()).__str__() sunrise '2000/12/31 15:21:06' sunset = California_forest.next_setting(ephem.Sun()).__str__() sunset '2001/1/1 00:50:46' </code></pre>
1
2016-10-08T15:53:29Z
[ "python", "pyephem" ]
Python Ephem sunset and sunrise
39,934,242
<p>I am trying to calculate the exact amount of daylight hours for a given day and location. I have been looking at the python module "Ephem" for the sunrise and set calculation. Here is the code below:</p> <pre><code>import ephem California_forest = ephem.Observer() California_forest.date = '2001/01/01 00:00' California_forest.pressure = 0 California_forest.horizon = '-0:34' California_forest.lat, California_forest.lon = '38.89525', '-120.63275' California_forest.altitude = 1280 print(California_forest.previous_rising(ephem.Sun())) 2000/12/31 15:21:06 print(California_forest.previous_rising(ephem.Sun())) 2001/1/1 00:50:46 </code></pre> <p>The module works just fine like its tutorial showed. However, I thought you could save the "sunrise" and "sunset" output as a string. When I saved the calculation to a variable, it gives me a floating number that I dont understand:</p> <pre><code>sunrise = California_forest.previous_rising(ephem.Sun()) sunrise 36890.13965508334 sunset = California_forest.next_setting(ephem.Sun()) sunset 36890.53525430675 </code></pre> <p>I was expecting a string that was the same as the print statement output, but I was mistaken. Does anyone have a suggestion as to how I can use these outputs and calculate the amount of daylight hours for a given location? It would be greatly appreciated!</p>
2
2016-10-08T15:39:02Z
39,934,407
<p>It looks like this is returning an <code>ephem._libastro.Date</code> object, which, when <a href="https://github.com/brandon-rhodes/pyephem/blob/master/extensions/_libastro.c#L502" rel="nofollow">convrted to <code>str</code></a> returns the nicely formatted string you see when printing it.</p> <p>If you just enter <code>sunrise</code> in the console, that actually does the same as <code>print(repr(sunrise))</code>, which does not produce the nice-looking string. It prints the underlying float value.</p> <p>If you want to save the string representation, simply convert it to <code>str</code>:</p> <pre><code>sunrise = str(California_forest.previous_rising(ephem.Sun())) </code></pre>
2
2016-10-08T15:58:24Z
[ "python", "pyephem" ]
Implementation of Divisive Clustering
39,934,252
<p>I'm referring to this <a href="http://www.cs.utexas.edu/users/inderjit/public_papers/hierdist.pdf" rel="nofollow">paper</a>. In that paper they are clustering words before classifying the document</p> <p>They say that from a document set with vocabulary size of 35000, they have been able to classify the documents at 78% accuracy by using only 50 clusters. (figure 5 of the paper)</p> <p>They are using divisive clustering algorithms for that. I've been searching for implementations of that algorithm. But I couldn't find any.</p> <p>Where can I find a implementation of that algorithm. (Prefer python. C/C++, java also fine)</p> <p>Thanks!!</p>
-2
2016-10-08T15:39:51Z
39,940,964
<p>Implement it yourself (questions asking for code/libraries are off-topic here!). Figure 1 is the pseudo-code of the proposed algorithm.</p>
0
2016-10-09T07:08:32Z
[ "python", "algorithm", "nlp", "cluster-analysis", "hierarchical-clustering" ]
How to divide file into several files using python
39,934,298
<p>I have a video file and i need to <strong>divide</strong> it into several smaller files of size <strong>256KB</strong> and save all files names in a text file then i need to read all the small files and <strong>merges</strong> them into the original file.</p> <p>is this possible to do it in <strong>python</strong> and how ?</p>
0
2016-10-08T15:45:30Z
39,934,510
<p>First stab at splitting:</p> <pre><code>input_file = open(input_filename, 'rb') blocksize = 4096 chunksize = 1024 * 256 buf = None chunk_num = 0 current_read = 0 output_filename = 'output-chunk-{:04d}'.format(chunk_num) output_file = open(output_filename, 'wb') while buf is None or len(buf) &gt; 0: buf = input_file.read(blocksize) current_read += len(buf) output_file.write(buf) if chunksize &lt;= current_read: output_file.close() current_read = 0 chunk_num += 1 output_filename = 'output-chunk-{:04d}'.format(chunk_num) output_file = open(output_filename, 'wb') output_file.close() input_file.close() </code></pre> <p>This might get you partway there; adapt as needed.</p> <p>Merging:</p> <pre><code>blocksize = 4096 chunk_num = 0 input_filename = 'output-chunk-{:04d}'.format(chunk_num) output_filename = 'reconstructed.bin' output_file = open(output_filename, 'wb') while True: try: input_file = open(input_filename, 'rb') except IOError: break buf = None while buf is None or len(buf) &gt; 0: buf = input_file.read(blocksize) output_file.write(buf) input_file.close() chunk_num += 1 input_filename = 'output-chunk-{:04d}'.format(chunk_num) output_file.close() </code></pre>
1
2016-10-08T16:08:43Z
[ "python", "python-2.7", "python-3.x" ]
Python 3 Beautiful Soup find tag with colon
39,934,304
<p>I am trying to scrape this site and get two separate tags. This is what the html looks like.</p> <pre><code>&lt;url&gt; &lt;loc&gt; http://link.com &lt;/loc&gt; &lt;lastmod&gt;date&lt;/lastmode&gt; &lt;changefreq&gt;daily&lt;/changefreq&gt; &lt;image:image&gt; &lt;image:loc&gt; https://imagelink.com &lt;image:loc&gt; &lt;image:title&gt;Item title&lt;/image:title&gt; &lt;image:image&gt; &lt;/url&gt; </code></pre> <p>the tags I am trying to get are the loc and image:title. The problem I am having is the colon in the title tag. The code I have so far is</p> <pre><code>r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') for item in soup.find_all('url'): print(item.loc) #print image title </code></pre> <p>i have also tried to do just </p> <pre><code>print(item.title) </code></pre> <p>but that doesn't work</p>
1
2016-10-08T15:45:59Z
39,934,355
<p>You should parse it in <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser" rel="nofollow">"xml" mode</a> instead (requires <code>lxml</code> to be installed as well):</p> <pre><code>from bs4 import BeautifulSoup data = """ &lt;url&gt; &lt;loc&gt; http://link.com &lt;/loc&gt; &lt;lastmod&gt;date&lt;/lastmod&gt; &lt;changefreq&gt;daily&lt;/changefreq&gt; &lt;image:image&gt; &lt;image:loc&gt; https://imagelink.com &lt;/image:loc&gt; &lt;image:title&gt;Item title&lt;/image:title&gt; &lt;/image:image&gt; &lt;/url&gt;""" soup = BeautifulSoup(data, 'xml') for item in soup.find_all('url'): print(item.title.get_text()) </code></pre> <p>Prints <code>Item title</code>.</p> <p>Note that I've applied several fixes to your XML string since it was initially non-well-formed.</p>
1
2016-10-08T15:52:38Z
[ "python", "python-3.x", "tags", "beautifulsoup", "bs4" ]
Construct a data structure with special requirements in python
39,934,347
<p>Requirements:</p> <ol> <li>There is a variable, for example, related_to_dict = 10</li> <li>Construct a key value pair data, for example, special_dict = {0 : ref_related_to_dict}</li> <li>When the variable of related_to_dict changed, the value of special_dict[0] also changed to the value of related_to_dict accordingly.</li> <li>When the value_of special_dict[0], e.g. ref_related_to_dict changed, the value of related_to_dict also changed to the value of special_dict[0] accordingly.</li> </ol> <p>Is there a way to achieve this task?</p>
0
2016-10-08T15:50:55Z
39,934,378
<p>You need to wrap the value in some sort of container. </p> <pre><code>class Ref: def __init__(self, v): self.val = v </code></pre> <p>And then:</p> <pre><code>related_to_dict = Ref(10) special_dict = {0: related_to_dict} </code></pre> <p>Then it works as desired:</p> <pre><code>related_to_dict.val = 40 print(special_dict[0].val) # 40 </code></pre>
1
2016-10-08T15:55:10Z
[ "python", "data-structures" ]
Python getting last line
39,934,453
<p>Working on a monitoring project, I need to count pulses from pulse meters. I've already found some solutions, which I've been trying to adapt to my needs. </p> <p>Here is the python script, running on a Raspberry Pi :</p> <pre><code>#!/usr/bin/env python import RPi.GPIO as GPIO import datetime import sys import signal from subprocess import check_output #verbose = True # global variable ############################################################################################################ ############################################################################################################ def printusage(progname): print progname + ' &lt;gpio-pin-number&gt; &lt;filename&gt; [debug]' print 'Example usage: ' print progname + ' 23 /path/to/mylogfile' print progname + ' 23 /path/to/mylogfile debug' sys.exit(-1) def signal_handler(signal, frame): if verbose: print('You pressed Ctrl+C, so exiting') GPIO.cleanup() sys.exit(0) def readvalue(myworkfile): try: f = open(myworkfile, 'ab+') # open for reading. If it does not exist, create it line=subprocess.check_output(['tail','-f','-1',f]) elmts=line.split(" ") value = int(elmts[2]) except: value = 0 # if something went wrong, reset to 0 #print "old value is", value f.close() # close for reading return value def writevalue(myworkfile,value): f = open(myworkfile, 'a') f.write((str(datetime.datetime.now())+' '+str(value)+'\r\n')) # timestamp f.close() ############################################################################################################ ############################################################################################################ ######### Initialization #### get input parameters: try: mygpiopin = int(sys.argv[1]) logfile = sys.argv[2] except: printusage(sys.argv[0]) verbose = False try: if sys.argv[3] == 'debug': verbose = True print "Verbose is On" else: printusage(sys.argv[0]) except: pass #### if verbose, print some info to stdout if verbose: print "GPIO is " + str(mygpiopin) print "Logfile is " + logfile print "Current value is " + str(readvalue(logfile)) #### setup GPIO.setmode(GPIO.BCM) GPIO.setup(mygpiopin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) signal.signal(signal.SIGINT, signal_handler) # SIGINT = interrupt by CTRL-C ########## Main Loop while True: # wait for pin going up GPIO.wait_for_edge(mygpiopin, GPIO.RISING) # read value from file counter=readvalue(logfile) + 1 if verbose: print "New value is", counter # write value to file writevalue(logfile,counter) # and wait for pin going down GPIO.wait_for_edge(mygpiopin, GPIO.FALLING) ############################################################################################################ ############################################################################################################ </code></pre> <p>I want to get the last index registered, and increment it, but everything I've tested so far leaves the loop stuck on an index of 1. </p> <p>I can't use a "heavier" method to find the last line, for instance browsing the entire file, because it will only get heavier and heavier as time passes, and I can't miss a pulse. </p> <p>I'm pretty new to programming, so thanks for your help !</p> <p>EDIT : the result file looks like this : </p> <pre><code>2016-10-08 16:54:23.072469 1 2016-10-08 16:54:23.462465 1 2016-10-08 16:54:23.777977 1 2016-10-08 16:54:24.010045 1 2016-10-08 16:54:24.194032 1 2016-10-08 16:54:24.388120 1 2016-10-08 16:54:24.549389 1 2016-10-08 16:54:24.737994 1 2016-10-08 16:54:24.959462 1 2016-10-08 16:54:25.164638 1 2016-10-08 16:54:25.351850 1 2016-10-08 16:54:25.536655 1 2016-10-08 16:54:25.716214 1 2016-10-08 16:54:25.794152 1 2016-10-08 17:06:13.506531 1 2016-10-08 17:06:14.097642 1 2016-10-08 17:06:14.211579 1 2016-10-08 17:06:15.237852 1 2016-10-08 17:06:15.752239 1 2016-10-08 17:06:16.320419 1 2016-10-08 17:06:16.842906 1 2016-10-08 17:06:17.391121 1 2016-10-08 17:06:17.851521 1 2016-10-08 17:06:18.444486 1 2016-10-08 17:06:18.858358 1 </code></pre>
0
2016-10-08T16:02:50Z
39,934,640
<p>To read the last line of a big file, pick a position near the end of the file and read. If there are no newlines there, go back a little and read again.</p> <p>Then find the last newline and the rest is your last line.</p> <pre><code>EXPECTED_MAX_LINE_SIZE = 500 # this should be both small enough and big enough def get_last_line(f): end = f.seek(0, os.SEEK_END) # detect file size pos = end-EXPECTED_MAX_LINE_SIZE if pos &lt; 0: pos = 0 f.seek(pos, os.SEEK_SET) end_of_file = f.read(EXPECTED_MAX_LINE_SIZE) # TODO: check if '\n' is not there and read some more return end_of_file.splitlines()[-1] </code></pre>
0
2016-10-08T16:21:52Z
[ "python", "search", "raspberry-pi", "pulse" ]
Python getting last line
39,934,453
<p>Working on a monitoring project, I need to count pulses from pulse meters. I've already found some solutions, which I've been trying to adapt to my needs. </p> <p>Here is the python script, running on a Raspberry Pi :</p> <pre><code>#!/usr/bin/env python import RPi.GPIO as GPIO import datetime import sys import signal from subprocess import check_output #verbose = True # global variable ############################################################################################################ ############################################################################################################ def printusage(progname): print progname + ' &lt;gpio-pin-number&gt; &lt;filename&gt; [debug]' print 'Example usage: ' print progname + ' 23 /path/to/mylogfile' print progname + ' 23 /path/to/mylogfile debug' sys.exit(-1) def signal_handler(signal, frame): if verbose: print('You pressed Ctrl+C, so exiting') GPIO.cleanup() sys.exit(0) def readvalue(myworkfile): try: f = open(myworkfile, 'ab+') # open for reading. If it does not exist, create it line=subprocess.check_output(['tail','-f','-1',f]) elmts=line.split(" ") value = int(elmts[2]) except: value = 0 # if something went wrong, reset to 0 #print "old value is", value f.close() # close for reading return value def writevalue(myworkfile,value): f = open(myworkfile, 'a') f.write((str(datetime.datetime.now())+' '+str(value)+'\r\n')) # timestamp f.close() ############################################################################################################ ############################################################################################################ ######### Initialization #### get input parameters: try: mygpiopin = int(sys.argv[1]) logfile = sys.argv[2] except: printusage(sys.argv[0]) verbose = False try: if sys.argv[3] == 'debug': verbose = True print "Verbose is On" else: printusage(sys.argv[0]) except: pass #### if verbose, print some info to stdout if verbose: print "GPIO is " + str(mygpiopin) print "Logfile is " + logfile print "Current value is " + str(readvalue(logfile)) #### setup GPIO.setmode(GPIO.BCM) GPIO.setup(mygpiopin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) signal.signal(signal.SIGINT, signal_handler) # SIGINT = interrupt by CTRL-C ########## Main Loop while True: # wait for pin going up GPIO.wait_for_edge(mygpiopin, GPIO.RISING) # read value from file counter=readvalue(logfile) + 1 if verbose: print "New value is", counter # write value to file writevalue(logfile,counter) # and wait for pin going down GPIO.wait_for_edge(mygpiopin, GPIO.FALLING) ############################################################################################################ ############################################################################################################ </code></pre> <p>I want to get the last index registered, and increment it, but everything I've tested so far leaves the loop stuck on an index of 1. </p> <p>I can't use a "heavier" method to find the last line, for instance browsing the entire file, because it will only get heavier and heavier as time passes, and I can't miss a pulse. </p> <p>I'm pretty new to programming, so thanks for your help !</p> <p>EDIT : the result file looks like this : </p> <pre><code>2016-10-08 16:54:23.072469 1 2016-10-08 16:54:23.462465 1 2016-10-08 16:54:23.777977 1 2016-10-08 16:54:24.010045 1 2016-10-08 16:54:24.194032 1 2016-10-08 16:54:24.388120 1 2016-10-08 16:54:24.549389 1 2016-10-08 16:54:24.737994 1 2016-10-08 16:54:24.959462 1 2016-10-08 16:54:25.164638 1 2016-10-08 16:54:25.351850 1 2016-10-08 16:54:25.536655 1 2016-10-08 16:54:25.716214 1 2016-10-08 16:54:25.794152 1 2016-10-08 17:06:13.506531 1 2016-10-08 17:06:14.097642 1 2016-10-08 17:06:14.211579 1 2016-10-08 17:06:15.237852 1 2016-10-08 17:06:15.752239 1 2016-10-08 17:06:16.320419 1 2016-10-08 17:06:16.842906 1 2016-10-08 17:06:17.391121 1 2016-10-08 17:06:17.851521 1 2016-10-08 17:06:18.444486 1 2016-10-08 17:06:18.858358 1 </code></pre>
0
2016-10-08T16:02:50Z
39,934,779
<p>Your logic is way over complicated, if you will be running the script different times just store the last index in a separate file constantly overwriting:</p> <pre><code> def next_index(index): with open(index, 'a+') as f: # open for reading. If it does not exist, create it val = int(next(f, -1)) + 1 # first run value will be 0 open(index,"w").write(str(val)) # overwrite return val </code></pre> <p>if the value is created elsewhere just do the writing there, just make sure you overwrite the previous value opening with <code>w</code>. </p>
0
2016-10-08T16:37:02Z
[ "python", "search", "raspberry-pi", "pulse" ]
Python getting last line
39,934,453
<p>Working on a monitoring project, I need to count pulses from pulse meters. I've already found some solutions, which I've been trying to adapt to my needs. </p> <p>Here is the python script, running on a Raspberry Pi :</p> <pre><code>#!/usr/bin/env python import RPi.GPIO as GPIO import datetime import sys import signal from subprocess import check_output #verbose = True # global variable ############################################################################################################ ############################################################################################################ def printusage(progname): print progname + ' &lt;gpio-pin-number&gt; &lt;filename&gt; [debug]' print 'Example usage: ' print progname + ' 23 /path/to/mylogfile' print progname + ' 23 /path/to/mylogfile debug' sys.exit(-1) def signal_handler(signal, frame): if verbose: print('You pressed Ctrl+C, so exiting') GPIO.cleanup() sys.exit(0) def readvalue(myworkfile): try: f = open(myworkfile, 'ab+') # open for reading. If it does not exist, create it line=subprocess.check_output(['tail','-f','-1',f]) elmts=line.split(" ") value = int(elmts[2]) except: value = 0 # if something went wrong, reset to 0 #print "old value is", value f.close() # close for reading return value def writevalue(myworkfile,value): f = open(myworkfile, 'a') f.write((str(datetime.datetime.now())+' '+str(value)+'\r\n')) # timestamp f.close() ############################################################################################################ ############################################################################################################ ######### Initialization #### get input parameters: try: mygpiopin = int(sys.argv[1]) logfile = sys.argv[2] except: printusage(sys.argv[0]) verbose = False try: if sys.argv[3] == 'debug': verbose = True print "Verbose is On" else: printusage(sys.argv[0]) except: pass #### if verbose, print some info to stdout if verbose: print "GPIO is " + str(mygpiopin) print "Logfile is " + logfile print "Current value is " + str(readvalue(logfile)) #### setup GPIO.setmode(GPIO.BCM) GPIO.setup(mygpiopin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) signal.signal(signal.SIGINT, signal_handler) # SIGINT = interrupt by CTRL-C ########## Main Loop while True: # wait for pin going up GPIO.wait_for_edge(mygpiopin, GPIO.RISING) # read value from file counter=readvalue(logfile) + 1 if verbose: print "New value is", counter # write value to file writevalue(logfile,counter) # and wait for pin going down GPIO.wait_for_edge(mygpiopin, GPIO.FALLING) ############################################################################################################ ############################################################################################################ </code></pre> <p>I want to get the last index registered, and increment it, but everything I've tested so far leaves the loop stuck on an index of 1. </p> <p>I can't use a "heavier" method to find the last line, for instance browsing the entire file, because it will only get heavier and heavier as time passes, and I can't miss a pulse. </p> <p>I'm pretty new to programming, so thanks for your help !</p> <p>EDIT : the result file looks like this : </p> <pre><code>2016-10-08 16:54:23.072469 1 2016-10-08 16:54:23.462465 1 2016-10-08 16:54:23.777977 1 2016-10-08 16:54:24.010045 1 2016-10-08 16:54:24.194032 1 2016-10-08 16:54:24.388120 1 2016-10-08 16:54:24.549389 1 2016-10-08 16:54:24.737994 1 2016-10-08 16:54:24.959462 1 2016-10-08 16:54:25.164638 1 2016-10-08 16:54:25.351850 1 2016-10-08 16:54:25.536655 1 2016-10-08 16:54:25.716214 1 2016-10-08 16:54:25.794152 1 2016-10-08 17:06:13.506531 1 2016-10-08 17:06:14.097642 1 2016-10-08 17:06:14.211579 1 2016-10-08 17:06:15.237852 1 2016-10-08 17:06:15.752239 1 2016-10-08 17:06:16.320419 1 2016-10-08 17:06:16.842906 1 2016-10-08 17:06:17.391121 1 2016-10-08 17:06:17.851521 1 2016-10-08 17:06:18.444486 1 2016-10-08 17:06:18.858358 1 </code></pre>
0
2016-10-08T16:02:50Z
39,941,876
<p>I don't think that was what Padraic Cunningham meant, but I've managed to solve my problem by using two files, one for logging the updated index value, and one for storing the values :</p> <pre><code>#!/usr/bin/env python import RPi.GPIO as GPIO import datetime import sys import signal #verbose = True # global debug variable ############################################################################################################ def printusage(progname): #show how to use the script print progname + ' &lt;gpio-pin-number&gt; &lt;index file&gt; &lt;store file&gt; [debug]' print 'Example usage: ' print progname + ' 23 /path/to/mylogfile /path/to/storefile' print progname + ' 23 /path/to/mylogfile /path/to/storefile debug' sys.exit(-1) def signal_handler(signal, frame): #exiting the script if verbose: print('You pressed Ctrl+C, so exiting') GPIO.cleanup() sys.exit(0) def readvalue(myworkfile): try: f = open(myworkfile, 'ab+') # open for reading. If it does not exist, create it line=f.readline() #read the first and only line of the file elmts=line.split(" ") # the format is &lt;yyyy-mm-dd hh:mm:ss.ssssss indexvalue&gt; value = int(elmts[2]) #get the index value except: value = 0 # if something went wrong, reset to 0 #print "old value is", value f.close() # close for reading return value def writevalue(myworkfile,value): f = open(myworkfile, 'w') #overwrite the value f.write((str(datetime.datetime.now())+' '+str(value))) # timestamp + data f.close() def store_value(index_file,index_value): f=open(index_file, 'a+') f.write(str(datetime.datetime.now())+' '+str(index_value)+'\r\n') #store timestamp + data f.close() ############################################################################################################ ######### Initialization #### get input parameters try: mygpiopin = int(sys.argv[1]) logfile = sys.argv[2] storefile=sys.argv[3] except: printusage(sys.argv[0]) verbose = False try: if sys.argv[4] == 'debug': verbose = True print "Verbose is On" else: printusage(sys.argv[0]) except: pass if verbose: #### if verbose, print some info to stdout print "GPIO is " + str(mygpiopin) print "Logfile is " + logfile print "Storefile is " + storefile print "Current value is " + str(readvalue(logfile)) #### SETUP GPIO.setmode(GPIO.BCM) GPIO.setup(mygpiopin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) signal.signal(signal.SIGINT, signal_handler) # SIGINT = interrupt by CTRL-C ########## Main Loop ##### while True: GPIO.wait_for_edge(mygpiopin, GPIO.RISING) # wait for pin going up counter=readvalue(logfile) + 1 # read value from file and increment index if verbose: print "New value is", counter writevalue(logfile,counter) # write value to logfile store_value(storefile,counter) # store value in storefile GPIO.wait_for_edge(mygpiopin, GPIO.FALLING) # and wait for pin going down ############################################################################################################ </code></pre> <p>Thanks for your help !</p>
0
2016-10-09T09:10:12Z
[ "python", "search", "raspberry-pi", "pulse" ]