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
DataFrame drop rows whose column has certain values
37,637,789
<p>For my question, I have found quite a few entries that explain how to drop rows with specific column values; however, I've not been able to find (I know a post might be out there) a post that addresses how to drop rows in a dataframe with specific column values across multiple columns (34 in this case).</p> <ol> <l...
0
2016-06-05T02:10:17Z
37,638,010
<p>Start by selecting all the columns after <code>age</code></p> <pre><code>df[df.columns[2:]] item1 item2 item3 item4 item5 item6 item7 item34 0 1 0 1 1 0 0 1 0 1 10 111 11 1 0 1 9 8 2 1 0 1 1 0 1 ...
0
2016-06-05T02:58:05Z
[ "python", "dataframe" ]
DataFrame drop rows whose column has certain values
37,637,789
<p>For my question, I have found quite a few entries that explain how to drop rows with specific column values; however, I've not been able to find (I know a post might be out there) a post that addresses how to drop rows in a dataframe with specific column values across multiple columns (34 in this case).</p> <ol> <l...
0
2016-06-05T02:10:17Z
37,638,047
<p>Try this: </p> <pre><code> print df zip age item1 item2 item3 item4 item5 item6 item7 item34 12345 10 1 0 1 1 0 0 1 0 23456 20 10 111 11 1 0 1 9 8 45678 60 1 0 1 1 0 1 0 1 dfSli...
0
2016-06-05T03:05:04Z
[ "python", "dataframe" ]
Difference between reverse and [::-1]
37,637,829
<p>Just wanted to know the difference between reverse() and [::-1] in terms of references. </p> <p>For example</p> <pre><code>p = [1,2,3] x = p[::-1] print(x) print(p) p.reverse() print(p ==p[::-1]) print(p == x) </code></pre> <p>so outputs are </p> <pre><code>[3,2,1] [1,2,3] False True </code></pre>
5
2016-06-05T02:19:44Z
37,637,857
<p><code>reverse</code> reverses the list <strong>in-place</strong>, see <a href="https://docs.python.org/3/tutorial/datastructures.html">the manual</a>, while <code>[::-1]</code> gives a new list in reversed order.</p> <p>Try <code>print(p)</code> after calling <code>p.reverse()</code>, you'll see the difference.</p>...
5
2016-06-05T02:25:00Z
[ "python", "python-3.x" ]
How to add Django ldap users to Django ModelBackend Groups
37,637,860
<p>I am running Django-1.7.7 with ModelBackend(default) with few users and 2 groups. </p> <p>Now i have implemented Ldap Backend too with Model Backend. But after that i have to add all of the Ldap Authenticated users to one of the Model group automatically, when the users Authenticated. </p> <p>Is there any way t...
-1
2016-06-05T02:25:15Z
37,639,851
<p>Look at this package: <a href="https://pythonhosted.org/django-auth-ldap/" rel="nofollow">https://pythonhosted.org/django-auth-ldap/</a></p> <p>and at this old post: <a href="https://www.djm.org.uk/posts/using-django-auth-ldap-active-directory-ldaps/" rel="nofollow">https://www.djm.org.uk/posts/using-django-auth-ld...
1
2016-06-05T08:22:00Z
[ "python", "django", "django-admin", "django-login" ]
How to add Django ldap users to Django ModelBackend Groups
37,637,860
<p>I am running Django-1.7.7 with ModelBackend(default) with few users and 2 groups. </p> <p>Now i have implemented Ldap Backend too with Model Backend. But after that i have to add all of the Ldap Authenticated users to one of the Model group automatically, when the users Authenticated. </p> <p>Is there any way t...
-1
2016-06-05T02:25:15Z
37,640,193
<p>You can avoid storing users in model, using Django LDAP features. You should "ask" to your LDAP server if that user´s credentials are correct and then you can your do your stuff: Store the username in a variable session, redirect to specific pages, in every page you can check if variable session with username is co...
0
2016-06-05T09:06:12Z
[ "python", "django", "django-admin", "django-login" ]
Sorting a dictionary by REVERSE VALUE then NON-REVERSE KEY
37,637,903
<p>I have a dictionary containing string keys and int values that I want to be sorted. I want it to first be sorted by decreasing value number, then in alphabetical order.</p> <p>For example if you had a dictionary containing:</p> <pre><code>my_dict = {'zebra':1, 'the':201, 'apple':1, 'chicken':58} </code></pre> <p>...
1
2016-06-05T02:35:38Z
37,637,930
<p>Just use negate the value and use it as primary key:</p> <pre><code>&gt;&gt;&gt; my_dict = {'zebra':1, 'the':201, 'apple':1, 'chicken':58} &gt;&gt;&gt; sorted(my_dict.items(), key=lambda x: (-x[1], x[0])) [('the', 201), ('chicken', 58), ('apple', 1), ('zebra', 1)] </code></pre>
4
2016-06-05T02:40:26Z
[ "python", "sorting", "dictionary" ]
Sorting a dictionary by REVERSE VALUE then NON-REVERSE KEY
37,637,903
<p>I have a dictionary containing string keys and int values that I want to be sorted. I want it to first be sorted by decreasing value number, then in alphabetical order.</p> <p>For example if you had a dictionary containing:</p> <pre><code>my_dict = {'zebra':1, 'the':201, 'apple':1, 'chicken':58} </code></pre> <p>...
1
2016-06-05T02:35:38Z
37,637,948
<p>As sorting is stable in Python, you can simply sort it twice: first by the secondary key, then by the primary key:</p> <pre><code>In [29]: from operator import itemgetter In [30]: my_dict = {'zebra':1, 'the':201, 'apple':1, 'chicken':58} In [31]: my_list = sorted(sorted(my_dict.iteritems(), key=itemgetter(0)), key=...
0
2016-06-05T02:45:42Z
[ "python", "sorting", "dictionary" ]
How do you find the top 3 probabilities from 10 columns in a row in Pandas DataFrame?
37,637,983
<p>I have a Pandas Dataframe with a probability for each column and I have 10 columns. Row represents a record. I'd like to select top 3 probabilities and return that column names (kind of like argmax). </p> <p>Since I have a large volume of rows, I don't want to use loop hopefully. Could someone help me do this?</p> ...
0
2016-06-05T02:52:34Z
37,638,256
<p>You should look into <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.nlargest.html" rel="nofollow">nlargest</a>. This might be enough to get you going:</p> <pre><code>df.T.nlargest(3, df.T.columns).T </code></pre>
0
2016-06-05T03:45:41Z
[ "python", "pandas", "argmax" ]
How do you find the top 3 probabilities from 10 columns in a row in Pandas DataFrame?
37,637,983
<p>I have a Pandas Dataframe with a probability for each column and I have 10 columns. Row represents a record. I'd like to select top 3 probabilities and return that column names (kind of like argmax). </p> <p>Since I have a large volume of rows, I don't want to use loop hopefully. Could someone help me do this?</p> ...
0
2016-06-05T02:52:34Z
37,638,291
<p>Given the df</p> <pre><code>df Out[145]: col0 col1 col2 col3 col4 col5 col6 col7 col8 \ 0 0.089659 0.0 0.0 0.0 0.228481 0.000000 0.0 0.575523 0.0 1 0.000000 0.0 0.0 0.0 0.000000 0.422125 0.0 0.516324 0.0 2 0.000000 0.0 0.0 0.0 0.000000 0.304416...
0
2016-06-05T03:51:33Z
[ "python", "pandas", "argmax" ]
how do tell with an if statement if there this index exists in a list or not?
37,638,088
<pre><code>for j in range(1, minimum): v=minimum/j if (v).is_integer()==True: llist.append(v) llist.append(j) else: pass if llist(j)==True: indexmin=llist(j) listofmulmin.append(minimum*indexmin) else: pass </code></pre> <p>this is not my full code</p...
0
2016-06-05T03:12:41Z
37,638,179
<p>Since list indexes go from (0, .., n-1), you can easily check a potential index by comparing it to the total size of the list. Here is an example 3 element list test</p> <pre><code>llist = [1,2,3] for i in range(5): if i &gt;= 0 and len(llist) &gt; i: print('{} is a valid index'.format(i)) else: ...
0
2016-06-05T03:28:50Z
[ "python" ]
Reduce rounding error in SVD of a matrix
37,638,274
<p>I have to do the SVD of a matrix, but it has some errors, in the following example <code>U[1][1]</code>, <code>U[2][1]</code> and <code>U[2][0]</code> should be <code>0</code>.</p> <p><a href="http://i.stack.imgur.com/zSZkV.png" rel="nofollow"><img src="http://i.stack.imgur.com/zSZkV.png" alt="enter image descripti...
1
2016-06-05T03:47:41Z
37,638,430
<p>By most standards <code>1e-17</code> is considered to be <code>0</code>.</p> <p>For example, it passes the <code>np.allclose</code> test</p> <pre><code>In [582]: A=np.array([1,-1,1,1,1,1]).reshape(3,2) In [583]: U,d,V=np.linalg.svd(A) In [584]: U Out[584]: array([[ -8.56248666e-17, 1.00000000e+00, -6.4088492...
2
2016-06-05T04:22:32Z
[ "python", "numpy", "matrix", "precision", "svd" ]
Google App Engine join results of two tables
37,638,286
<p>I am developing a blog project using jinja2 for templates, Google App Engine for hosting and running it and Python as the server side language.</p> <p>So, my <code>models.py</code> looks like this : </p> <p>from google.appengine.ext import ndb</p> <pre><code>class User(ndb.Model): fullname = ndb.StringPropert...
0
2016-06-05T03:50:46Z
37,701,350
<p>I used the following method to solve my problem : </p> <pre><code>class HomeHandler(BlogHandler): def get(self,user=None): posts = [] user_email = check_for_valid_cookie(self) loggedin_user = User.query(User.email == user_email).get() posts = Post.query().order(-Post.created) ...
-1
2016-06-08T11:33:46Z
[ "python", "google-app-engine", "join", "google-cloud-datastore" ]
Google App Engine join results of two tables
37,638,286
<p>I am developing a blog project using jinja2 for templates, Google App Engine for hosting and running it and Python as the server side language.</p> <p>So, my <code>models.py</code> looks like this : </p> <p>from google.appengine.ext import ndb</p> <pre><code>class User(ndb.Model): fullname = ndb.StringPropert...
0
2016-06-05T03:50:46Z
37,748,849
<p>I implemented an array of dictionaries like this : </p> <pre><code>class HomeHandler(BlogHandler): def get(self,user=None): posts = Post.query().order(-Post.created) all_users = User.query() likes = Likes.query() list_dict = [] for p in posts: p_dict = {} ...
-1
2016-06-10T12:54:52Z
[ "python", "google-app-engine", "join", "google-cloud-datastore" ]
API Coinbase ValueError from get_buy_price()
37,638,359
<p>python 3.4 and Coinbase V2 API </p> <hr> <p>I am working on some BTC data analysis and trying to make continuous requests to coinbase API. When running my script, it will always eventually crash on a calls to</p> <pre><code>r = client.get_spot_price() r = client.get_buy_price() r = client.get_sell_price() </code...
1
2016-06-05T04:08:50Z
37,646,769
<p>For me it could be something related with that issue <a href="https://github.com/coinbase/coinbase-python/issues/15" rel="nofollow">https://github.com/coinbase/coinbase-python/issues/15</a>. It seems in fact to be an <strong>internal library error</strong> (as the code does <code>raise build_api_error(response)</cod...
1
2016-06-05T21:05:37Z
[ "python", "json", "api", "coinbase" ]
Can't copy file sshing, and coping files in a directory
37,638,365
<p>I'm writing a small script to combine a number of steps but in the end i get : </p> <pre><code>scp: .: not a regular file cp: cannot stat ‘/path/to/dir/': No such file or directory </code></pre> <p>I've checked that the directory does in fact exist that it's the same one contained in <code>dir_[0][:-1]</code></p...
-1
2016-06-05T04:10:08Z
37,638,427
<p>Your call to <code>dir_[0][:-1]</code> is not returning a string, but instead a list</p> <pre><code>user_acc = 'alan' dir_ = [['src', 'main'],['opt', 'user']] dicom_dir = '/var/tmp' sub = '/subdir' print ('scp', '%s@sew.cwe.edu:' % user_acc, dir_[0][:-1], '%s//%s/dicom/' % (dicom_dir, sub)) &gt;&gt; scp alan@sew.c...
2
2016-06-05T04:22:25Z
[ "python", "ssh" ]
How do I know which URL is responsible for the call to a route function from inside of it in Python Flask
37,638,457
<p>So, </p> <p>I have several URL's being handled by the same route function in flask like this,</p> <pre><code>@app.route("/&lt;topic&gt;/", methods = ['GET']) @app.route("/search/&lt;tags&gt;", methods = ['GET']) @app.route("/bookmarks", methods = ['GET']) @app.route("/user/&lt;userid&gt;", methods = ['GET']) @app....
3
2016-06-05T04:27:35Z
37,638,530
<p>You can use the global flask <code>request</code> object. It contains everything you need. </p> <p><a href="http://flask.pocoo.org/docs/0.11/api/#incoming-request-data" rel="nofollow">http://flask.pocoo.org/docs/0.11/api/#incoming-request-data</a></p> <p>You can either use <code>request.url</code> or <code>request...
3
2016-06-05T04:42:25Z
[ "python", "flask" ]
Query data from a PostgreSQL dump
37,638,469
<p>I have a dump that was made from a PostgreSQL database. I want to check for some information in that dump, specifically checking if there are entries in a certain table with certain values in certain fields.</p> <p>This is for a Python program that should run automatically on many different inputs on customer machi...
1
2016-06-05T04:29:50Z
37,638,594
<p>Dump the database to a CSV file (or a CSV file for each table) and then you can load and query them using <a href="http://pandas.pydata.org/pandas-docs/version/0.18.1/" rel="nofollow">pandas</a>.</p>
1
2016-06-05T04:55:16Z
[ "python", "postgresql" ]
Query data from a PostgreSQL dump
37,638,469
<p>I have a dump that was made from a PostgreSQL database. I want to check for some information in that dump, specifically checking if there are entries in a certain table with certain values in certain fields.</p> <p>This is for a Python program that should run automatically on many different inputs on customer machi...
1
2016-06-05T04:29:50Z
37,641,152
<h2>Any dump format: restore and query</h2> <p>The most practical thing to do is restore them to a temporary PostgreSQL database then query the database. It's by far the simplest option. If you have a non-superuser with <code>createdb</code> rights you can do this pretty trivially and safely with <code>pg_restore</cod...
1
2016-06-05T11:09:22Z
[ "python", "postgresql" ]
Unexpected output using lxml `.xpath()` and `for`
37,638,500
<p>I have the following text</p> <pre><code>testing = """ &lt;div&gt; &lt;a&gt;11&lt;/a&gt; &lt;/div&gt; &lt;div&gt; &lt;a&gt;21&lt;/a&gt; &lt;a&gt;23&lt;/a&gt; &lt;/div&gt; """ </code></pre> <p>And I want to extract the text inside <code>&lt;a&gt;&lt;/a&gt;</code>. Below is my try,</p> <pre><code>testing = html.fro...
1
2016-06-05T04:34:26Z
37,638,503
<p><code>testing.xpath("//div")</code> returns you a list of matching <code>div</code> nodes. For every <code>div</code> node, you ask to find all <code>a</code> elements, but <code>//</code> at the beginning of the expression would start the search from the <em>root of the document tree</em>. You need to make the sear...
3
2016-06-05T04:35:46Z
[ "python", "xpath", "lxml" ]
How to optimize the python code (running time should be less than 10s)?
37,638,535
<p>I have to optimize the code, as the running time of the code goes above <code>10s</code>. The code works absolutely fine (less than <code>10s</code>) for small inputs if the input length increases then the output goes above <code>10s</code>.</p> <pre><code>import re, time #from collections import OrderedDict final...
2
2016-06-05T04:43:38Z
37,638,609
<p>Your primary culprit is the counting code, which unnecessarily scales with <code>O(m*n)</code>, if <code>n</code> is the number of inputs and <code>m</code> is the number of unique inputs. That is, this part:</p> <pre><code>i = 0 while i &lt; l: final_dict[AI_sort[i]] = cnt = AI_sort.count(AI_sort[i]) i += ...
3
2016-06-05T04:58:57Z
[ "python", "performance", "python-3.x", "optimization" ]
Python Tkinter Attribute Error When Using Two Classes
37,638,586
<p>Hi there in my code I'm am getting an the error <code>AttributeError: 'GUI' object has no attribute 'calculate_button'</code> And I don't know why its not working when I am using two classes. Also I don't want to make the class inherit each other nor make it an object.</p> <p>Here is my code:</p> <pre><code>from t...
0
2016-06-05T04:54:09Z
37,638,690
<p>unindent <code>calculate_button</code> 1 level. It should not be a function in the <strong>init</strong> function rather a function of the class <strong>GUI</strong>. Remove <code>()</code> as mentioned in comment.</p> <p>There is still a bug, </p> <blockquote> <p>NameError: name 'Logic' is not defined</p> </blo...
1
2016-06-05T05:13:51Z
[ "python", "python-3.x", "tkinter" ]
Python Tkinter Attribute Error When Using Two Classes
37,638,586
<p>Hi there in my code I'm am getting an the error <code>AttributeError: 'GUI' object has no attribute 'calculate_button'</code> And I don't know why its not working when I am using two classes. Also I don't want to make the class inherit each other nor make it an object.</p> <p>Here is my code:</p> <pre><code>from t...
0
2016-06-05T04:54:09Z
37,639,996
<p>There are few issues with your code:</p> <ol> <li>As @Tadhg McDonald-Jensen commented you, <code>calculate_button()</code> is wrongly intended and does not belong to <code>GUI()</code> class</li> <li>As @MotKohn answered, you must remove <code>()</code> from <code>calculate_button()</code> in <code>Convert_Button</...
2
2016-06-05T08:42:13Z
[ "python", "python-3.x", "tkinter" ]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() python dbscan 3 dimensions point
37,638,610
<p>I want to do clustering using DBSCAN algorithm with a dataset that contains 3 points. This is the dataset :</p> <pre><code>1 5 7 12 8 9 2 4 10 6 3 21 11 13 0 6 3 21 11 13 0 3 7 1 1 9 2 1 5 7 </code></pre> <p>I do clustering with this code :</p> <pre><code>from math import sqrt, ...
-1
2016-06-05T04:59:08Z
37,638,903
<p>The error emerges from these lines:</p> <pre><code> if point not in visited: visited.append(point) </code></pre> <p>The <code>in</code> operator calls <code>list.__contains__</code>, which iterates over the items in the <code>visited</code> list to see if any of them are equal to <code>point</code>. How...
1
2016-06-05T05:53:22Z
[ "python", "cluster-analysis", "value", "ambiguous", "dbscan" ]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() python dbscan 3 dimensions point
37,638,610
<p>I want to do clustering using DBSCAN algorithm with a dataset that contains 3 points. This is the dataset :</p> <pre><code>1 5 7 12 8 9 2 4 10 6 3 21 11 13 0 6 3 21 11 13 0 3 7 1 1 9 2 1 5 7 </code></pre> <p>I do clustering with this code :</p> <pre><code>from math import sqrt, ...
-1
2016-06-05T04:59:08Z
37,639,256
<p>If you use <code>numpy</code>, you should use masks instead of lists:</p> <pre><code>def cluster(data_points, eps=0.1, min_points=3): cluster_numbers = numpy.zeros(len(data_points), dtype=int) c = 0 for idx, point in enumerate(data_points): if cluster_numbers[idx] == 0: print point ...
0
2016-06-05T06:55:11Z
[ "python", "cluster-analysis", "value", "ambiguous", "dbscan" ]
Extract Number from Varying String
37,638,613
<p>Given this data frame:</p> <pre><code>import pandas as pd df = pd.DataFrame({'ID':['a','b','c','d','e','f','g','h','i','j','k'], 'value':['None',np.nan,'6D','7','10D','NONE','x','10D aaa','1 D','10 D aa',7] }) df ID value 0 a None 1 b NaN 2 c 6D 3 d 7 4 ...
2
2016-06-05T04:59:40Z
37,638,657
<p>Alternatively, you can apply a function to the dataframe via <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html" rel="nofollow"><code>applymap()</code></a> following the <a href="https://docs.python.org/2/glossary.html#term-eafp" rel="nofollow"><code>EAFP</code> principle</...
1
2016-06-05T05:06:40Z
[ "python", "string", "python-3.x", "pandas" ]
Extract Number from Varying String
37,638,613
<p>Given this data frame:</p> <pre><code>import pandas as pd df = pd.DataFrame({'ID':['a','b','c','d','e','f','g','h','i','j','k'], 'value':['None',np.nan,'6D','7','10D','NONE','x','10D aaa','1 D','10 D aa',7] }) df ID value 0 a None 1 b NaN 2 c 6D 3 d 7 4 ...
2
2016-06-05T04:59:40Z
37,638,678
<p>Try the following using <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#vectorized-string-methods" rel="nofollow">Series.str.replace</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="nofollow">fillna</a>:</p> <pre><code>import pandas as pd df...
1
2016-06-05T05:11:45Z
[ "python", "string", "python-3.x", "pandas" ]
Extract Number from Varying String
37,638,613
<p>Given this data frame:</p> <pre><code>import pandas as pd df = pd.DataFrame({'ID':['a','b','c','d','e','f','g','h','i','j','k'], 'value':['None',np.nan,'6D','7','10D','NONE','x','10D aaa','1 D','10 D aa',7] }) df ID value 0 a None 1 b NaN 2 c 6D 3 d 7 4 ...
2
2016-06-05T04:59:40Z
37,638,755
<p>Here is my approach of using <code>re.findall</code> and <code>apply</code></p> <pre><code>df['value'].apply(lambda x: 0 if not re.findall('\d+', str(x)) else re.findall('\d+', str(x))[0]) </code></pre>
1
2016-06-05T05:26:06Z
[ "python", "string", "python-3.x", "pandas" ]
install newest version of ONE private library in a requirements.txt file?
37,638,622
<p>I can run <code>pip install --upgrade -r requirements.txt</code>, and I can set a packagename to something like <code>package&gt;=0.42</code>, but is there a way to say "always attempt to upgrade this one package"? The problem with <code>--upgrade</code> on the entire file is it tries to upgrade all packages.</p> <...
2
2016-06-05T05:02:23Z
37,638,729
<p>I don't think the <code>--upgrade</code> flag can be currently specified on a package level inside the <code>requirements</code> file. </p> <p>One workaround would be to have a <em>separate requirements file</em> for these kind of packages.</p> <p><sup>There is also that <a href="https://pip.pypa.io/en/stable/refe...
0
2016-06-05T05:21:57Z
[ "python", "pip" ]
install newest version of ONE private library in a requirements.txt file?
37,638,622
<p>I can run <code>pip install --upgrade -r requirements.txt</code>, and I can set a packagename to something like <code>package&gt;=0.42</code>, but is there a way to say "always attempt to upgrade this one package"? The problem with <code>--upgrade</code> on the entire file is it tries to upgrade all packages.</p> <...
2
2016-06-05T05:02:23Z
37,638,815
<p>The simple solution is to remove the version pinning for the package, each time the requirements file is run - the latest version will be installed.</p>
0
2016-06-05T05:40:02Z
[ "python", "pip" ]
Can't load music into pygame
37,638,671
<p>please help if you can. Can't seem to be able to upload music into my game in progress. It comes up with the error of "can't load"... Would be great if someone got back to me quick, This is a major work due in 1 week</p> <pre><code>import sys, random, pygame, time from pygame.locals import * pygame.init() screen =...
-1
2016-06-05T05:09:16Z
37,639,135
<p>I guess your problem is due to the following reason:<br> 1)Go go to file > save as (shortcut : Ctrl+Shift+S) and try saving the python file in the same address in which your music is stored.</p> <p>Suggestion:<br> Try converting the mp3 to wav.It works better.</p>
0
2016-06-05T06:31:04Z
[ "python", "pygame" ]
Can't load music into pygame
37,638,671
<p>please help if you can. Can't seem to be able to upload music into my game in progress. It comes up with the error of "can't load"... Would be great if someone got back to me quick, This is a major work due in 1 week</p> <pre><code>import sys, random, pygame, time from pygame.locals import * pygame.init() screen =...
-1
2016-06-05T05:09:16Z
37,640,849
<p>Try to enter the full path of your mp3. For example</p> <pre><code> pygame.mixer.music.load('C:/Users/path/to/your/file/sddmusic.mp3') </code></pre>
0
2016-06-05T10:26:53Z
[ "python", "pygame" ]
Python class and method instantiation
37,638,739
<p>Here is my code:</p> <pre><code>class calculator: def addition(x,y): added=x+y print(added) def subtraction(x,y): sub=x-y print(sub) def multiplication(x,y): mult=x*y print(mult) def division(x,y): div= x/y print(div) calculator.ad...
0
2016-06-05T05:23:18Z
37,638,785
<p>So without going too much into the nitty-gritty, you should add <code>@staticmethod</code> decorators above each function, like I've done below:</p> <pre><code>class calculator: @staticmethod def addition(x,y): added=x+y print(added) @staticmethod def subtraction(x,y): sub=...
0
2016-06-05T05:33:28Z
[ "python", "class" ]
Difference between os.system("pwd") and os.getcwd()
37,638,740
<p>I have a basic doubt regarding the 3 families of functions below:</p> <p>Say for example, I would like to know the current working directory in Python. So some of the ways of achieving this could be :</p> <pre><code>os.system("pwd") os.getcwd() subprocess.Popen(['pwd'], stdout=PIPE, stderr=PIPE) </code></pre> <...
-1
2016-06-05T05:23:29Z
37,638,769
<p>The <code>os.getcwd()</code> call will be faster, as it doesn't rely on any external dependencies. Your first and last example both execute a separate process, the <code>pwd</code> system command, and return its output as a string. Well, your <code>Popen()</code> example will require you to get its output using anot...
3
2016-06-05T05:29:57Z
[ "python", "python-2.7", "subprocess", "os.system" ]
Difference between os.system("pwd") and os.getcwd()
37,638,740
<p>I have a basic doubt regarding the 3 families of functions below:</p> <p>Say for example, I would like to know the current working directory in Python. So some of the ways of achieving this could be :</p> <pre><code>os.system("pwd") os.getcwd() subprocess.Popen(['pwd'], stdout=PIPE, stderr=PIPE) </code></pre> <...
-1
2016-06-05T05:23:29Z
37,638,865
<p>The major difference between all three is that only one, <code>os.getcwd()</code> is guaranteed to work.</p> <p>The other two rely on <code>pwd</code> which is not available in all operating systems.</p> <p>As @Will mentioned in <a href="http://stackoverflow.com/a/37638769/790387">their answer</a>, spawning a sepa...
1
2016-06-05T05:48:07Z
[ "python", "python-2.7", "subprocess", "os.system" ]
Difference between os.system("pwd") and os.getcwd()
37,638,740
<p>I have a basic doubt regarding the 3 families of functions below:</p> <p>Say for example, I would like to know the current working directory in Python. So some of the ways of achieving this could be :</p> <pre><code>os.system("pwd") os.getcwd() subprocess.Popen(['pwd'], stdout=PIPE, stderr=PIPE) </code></pre> <...
-1
2016-06-05T05:23:29Z
37,639,326
<p>The best way of finding the performance issues is to measure it yourself. Python implementations vary. Equally, if you want to find out how they are implemented then read the source code.</p> <p>All these mechanisms will probably call the same underlying C library interface <code>getcwd(3)</code> on UNIX-like sys...
1
2016-06-05T07:04:10Z
[ "python", "python-2.7", "subprocess", "os.system" ]
Double counting in temporal difference learning
37,638,751
<p>I am working on a temporal difference learning example (<a href="https://www.youtube.com/watch?v=XrxgdpduWOU" rel="nofollow">https://www.youtube.com/watch?v=XrxgdpduWOU</a>), and I'm having some trouble with the following equation in my python implementation as I seem to be double counting rewards and Q. </p> <p>If...
2
2016-06-05T05:25:43Z
37,639,537
<p>The Q value represents an estimate of how much reward do ou expect to receive until the end of the episode. So, in a terminal state, maxQ = 0, because you won't receive any more rewards after then. So, the Q value at <code>t</code> will be 1, which is correct for your undiscounted problem. But you can't ignore the <...
1
2016-06-05T07:35:07Z
[ "python", "machine-learning", "reinforcement-learning", "temporal-difference" ]
Does tf.nn.softmax_cross_entropy_with_logits account for batch size?
37,638,777
<p><strong>Question: Does</strong> <code>tf.nn.softmax_cross_entropy_with_logits</code> <strong>account for batch size?</strong></p> <p>In my LSTM network I feed batches of different sizes and would like to know whether or not I should normalize error with respect to batch size before optimizing.</p>
0
2016-06-05T05:31:28Z
37,638,839
<p>In the <a href="https://www.tensorflow.org/versions/r0.8/api_docs/python/nn.html#softmax_cross_entropy_with_logits" rel="nofollow">documentation</a> it says that the softmax_cross_entropy_with_logits returns a vector with length equal to the batch size. To get a scalar cost you can do tf.reduce_mean on that vector. ...
1
2016-06-05T05:43:31Z
[ "python", "tensorflow", "softmax", "cross-entropy" ]
python selenium select one hidden item from dropdown list
37,638,833
<p>I have this xml code with a dropdown box with name "tp" which I sucessfully accessed by name "tp" and click() to pull down a list of options but unable to get into "Today" with value "919" as below</p> <pre><code>&lt;span id="sp_tp" class="dropdown select-container"&gt; &lt;select name="tp" rel="Timeperiod:" id...
0
2016-06-05T05:43:05Z
37,638,855
<blockquote> <p><code>select_Timeperiod.find_element_by_name('Today').click()</code></p> </blockquote> <p>For this to work, an element should have the <em><code>name</code>attribute</em> equal to <code>Today</code>. In your case the <code>option</code> element has the <code>Today</code> text.</p> <p>I would solve t...
1
2016-06-05T05:46:43Z
[ "python", "selenium", "dropdown" ]
python selenium select one hidden item from dropdown list
37,638,833
<p>I have this xml code with a dropdown box with name "tp" which I sucessfully accessed by name "tp" and click() to pull down a list of options but unable to get into "Today" with value "919" as below</p> <pre><code>&lt;span id="sp_tp" class="dropdown select-container"&gt; &lt;select name="tp" rel="Timeperiod:" id...
0
2016-06-05T05:43:05Z
37,641,025
<p>Alecxe has a good answer. If your application happens to be localized, you won't want to find by visible text though. Choosing by value would make this more robust in this situation:</p> <pre><code>select_Timeperiod = driver.find_element_by_name('tp') select_Timeperiod.click() select_Timeperiod.find_element_by_na...
0
2016-06-05T10:52:38Z
[ "python", "selenium", "dropdown" ]
python selenium select one hidden item from dropdown list
37,638,833
<p>I have this xml code with a dropdown box with name "tp" which I sucessfully accessed by name "tp" and click() to pull down a list of options but unable to get into "Today" with value "919" as below</p> <pre><code>&lt;span id="sp_tp" class="dropdown select-container"&gt; &lt;select name="tp" rel="Timeperiod:" id...
0
2016-06-05T05:43:05Z
37,647,122
<p>xe and Breaks Software, i tried both your answers without success with errors as below:<br> 1. select_Timeperiod.select_by_visible_text("Today") AttributeError: 'NoneType' object has no attribute 'select_by_visible_text' </p> <ol start="2"> <li>select_Timeperiod.find_element_by_name('Today').select_by_value("919")...
0
2016-06-05T21:51:09Z
[ "python", "selenium", "dropdown" ]
Extracting formulas from WIkipedia pages - Python
37,639,016
<p>I am extracting wikipedia pages and writing them in a file using python. Currently am doing this : code snippet : </p> <pre><code>keyWords = ["kinetic energy", "gravitational force"] for word in keyWords: topic = wikipedia.page(word) text = topic.content print text </code></pre> <p>But the content ha...
0
2016-06-05T06:11:37Z
37,639,225
<p>There is no LaTeX in the Wikipedia pages grabbed by the Wikipedia module. In order to extract all the equations from a Wikipedia page you can take advantage of the BeautifulSoup package.</p> <pre><code>import wikipedia from bs4 import BeautifulSoup topic = wikipedia.page('kinetic energy') equations = BeautifulSoup...
0
2016-06-05T06:48:38Z
[ "python", "web-scraping", "wikipedia-api" ]
Parsing Google API 'Address_Components' List/Dictionary Results Consistently in Python
37,639,089
<p>I am using Python 3 and the Google Geocoding API to gather address information. I am having a difficult time consistently parsing out the address components that I am getting back. The JSON structure for the <em>'address_components'</em> section does not seem to follow standard json formatting, and I can't find any ...
0
2016-06-05T06:22:10Z
37,644,125
<p>As discussed and shown in Python example in <a href="https://developers.google.com/maps/web-services/overview#ParsingJSON" rel="nofollow">Processing JSON with Javascript</a>, <code>json.load()</code> was used in parsing then results were displayed in <code>formatted_address</code> values to the user within an array....
0
2016-06-05T16:21:49Z
[ "python", "python-3.x", "google-maps-api-3" ]
Scapy TCP RST atack
37,639,137
<p>I tried to write TCP RST atack with Scapy,but my code doesn't work.Please,help me to solve my problem.</p> <pre><code> from scapy.all import * def poison(packet): packet[TCP].flags='RST' sendp(packet) sniff(filter='tcp',prn=poison) </code></pre> <p>There's something wrong with <co...
1
2016-06-05T06:31:51Z
37,641,012
<p> The correct way to set the TCP flags in Scapy is to use the short (one letter) form <code>packet[TCP].flags = 'R'</code>. With the current development version of Scapy, you can get the accepted flags using <code>ls()</code>:</p> <pre><code>&gt;&gt;&gt; ls(TCP, verbose=True) sport : ShortEnumField ...
1
2016-06-05T10:50:44Z
[ "python", "tcp", "scapy" ]
Explaining how NOAA UV Index forecast calculates hour in forecast file?
37,639,170
<p>I'm getting hourly UV index from the <a href="ftp://ftpprd.ncep.noaa.gov/pub/data/nccf/com/hourly/prod/uv.20160604/" rel="nofollow">ftp</a> site of NOAA. As mentioned <a href="http://www.cpc.ncep.noaa.gov/products/stratosphere/uv_index/uv_global.shtml" rel="nofollow">here</a>, the forecast time is present in the fil...
0
2016-06-05T06:37:00Z
37,639,310
<p>Values <code>hour, day, month, year</code> in GRIB file only indicate start time of a weather forecast (it is initial time from which forecast is produced). Date and time in this file is according to UTC. To get forecast date and time in UTC you need to add to initial time a value <code>XX</code>. Then to get your ...
0
2016-06-05T07:02:25Z
[ "python", "weather", "grib", "noaa" ]
Alter Django Form Fields based on User Selection
37,639,236
<p>I have three models: <code>Product</code>, <code>Product Class</code> and <code>Product Attributes</code>. Now when the user is shown a page to create a new product, he/she needs to select the <code>Product Class</code> from a dropdown. Based on this selection, <code>Product Attributes</code> will have to refresh dy...
1
2016-06-05T06:50:10Z
37,640,089
<p>When the user selects the <code>ProductClass</code>, you could sent (AJAX) the <code>pk</code> to Django and based on that, have Django return the appropriate input form fields HTML, using the regular <code>django.forms</code> to render it.</p> <p>Then insert that HTML into your original form, so it shows to the us...
0
2016-06-05T08:52:29Z
[ "jquery", "python", "django" ]
How I can insert a 3rd nested list in a already existing list in python?
37,639,327
<p>I have a list called <code>ilist</code> which looks like this:</p> <pre><code>['TCS', 1968, ['Mumbai', 'Delhi', 'Kochi', 'Banglore', 'Pune'], 'Wipro', 1981, ['Pune', 'Banagalore', 'Pune'], 'Infosys', 1945, ['Bangalore', 'Chandigarh', 'Pune']] </code></pre> <p>Now I want to insert some additional values in a form o...
2
2016-06-05T07:04:11Z
37,639,343
<p>You have to index the first list and then insert into the list at that index:</p> <pre><code>ilist[2].insert(3, ["ITPL","Vedhi","Electronic city"]) </code></pre>
4
2016-06-05T07:06:33Z
[ "python" ]
Deselect Bokeh tools by default
37,639,353
<p>When Bokeh tools are available, one is always selected by default (normally "pan"). Is there a way to have all tools be deselected while still making them available? This way the reader is less likely to mess up the plot by accident, especially on a small mobile device. </p>
0
2016-06-05T07:08:54Z
37,690,041
<p>As of Bokeh <code>0.11.1</code> this is an <a href="https://github.com/bokeh/bokeh/issues/3054" rel="nofollow">open feature request</a> hopefully to be resolved in the near future. </p>
0
2016-06-07T21:53:07Z
[ "python", "bokeh" ]
pandas plot hide x axis when subplots and secondary y
37,639,383
<p>I have a problem with pandas and couldn't figure out why. I want to create a figure with two subplots and plotting all the subplots x axis labels. Here is the data:</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame({'value A': np.random.random(10), 'value B': n...
1
2016-06-05T07:12:21Z
37,650,207
<p>Which version of pandas do you use?</p> <p>There is a bug with hidden ticklabels of x axis while secondary y axis is applied. Read here for detail: </p> <p><a href="https://github.com/pydata/pandas/pull/9164" rel="nofollow">https://github.com/pydata/pandas/pull/9164</a></p> <p><a href="https://github.com/pydata/p...
0
2016-06-06T05:39:12Z
[ "python", "pandas", "matplotlib", "plot" ]
Split values and store into a list
37,639,445
<p>I have below python script:</p> <pre><code>conn=boto.ec2.connect_to_region("us-west-1") result=collections.defaultdict(list) reservations = conn.get_all_instances() for res in reservations: for inst in res.instances: if 'clusters' in inst.tags: values = inst.tags['clu...
0
2016-06-05T07:20:44Z
37,639,475
<p>If the string that you want to split is already present in a variable, like <code>values</code>, you could try the following:</p> <pre><code>vl_list = [] # create a list for values for line in values.split("\n"): vl_list.extend(line.split(",")) </code></pre> <p>After this is complete, you'll have your values i...
2
2016-06-05T07:26:11Z
[ "python", "python-2.7" ]
Fastest way to vectorize Gaussian CDF (or erf/erfc/etc.) on PyPy (i.e. no SciPy)
37,639,492
<p>I'm trying to evaluate the CDFs of lots of Gaussians on PyPy, and it's slow doing this with <code>math.erf</code>.</p> <p>I don't have SciPy on PyPy so I can't use that. However, I have NumPy. </p> <p>What's the fastest way for me to do this on PyPy <strong>aside from writing my own C extension</strong>?</p>
0
2016-06-05T07:28:39Z
37,641,678
<p>If you have numpy, you can tabulate the error function, interpolate (<code>np.interp</code> or roll-your-own), and then use numpy vectorized operations to evaluate multiple values at once.</p> <p>Roughly (this is on CPython, I'm not sure if <code>np.interp</code> works in numpypy),</p> <pre><code>&gt;&gt;&gt; impo...
0
2016-06-05T12:05:19Z
[ "python", "numpy", "gaussian", "pypy", "cdf" ]
create a profile page with django
37,639,552
<p>I created a profile page with django to let users change their information that I gave in sing up form . (such as name, email, password)</p> <p>I have two problem on password field :</p> <p>1 - when user insert a password in text field, it's submitted in raw format, and I need django user's table format</p> <pre>...
1
2016-06-05T07:36:28Z
37,639,846
<p>From the documentation:</p> <blockquote> <p>Changing a user’s password will log out all their sessions if the SessionAuthenticationMiddleware is enabled.</p> </blockquote> <p>So you have to use <code>update_session_auth_hash(request, user)</code></p> <p>For more info, see <a href="https://docs.djangoproject.c...
2
2016-06-05T08:20:52Z
[ "python", "django", "hash", "change-password" ]
Import from YAML file
37,639,605
<p>I have a <code>config.yaml</code> file that I want to import in my <code>app.py</code>.</p> <p>This is my folder structure:</p> <pre><code> /root __init__.py app.py config.yaml </code></pre> <p><strong>App.py:</strong></p> <pre><code> import logging import config from flask import Flask...
-3
2016-06-05T07:43:38Z
37,639,650
<p>You cannot import YAML files directly into Python as you suggest in your example - only <code>*.py</code> files. You can import the <code>yaml</code> Python module and parse your file, as shown in these SO answers:</p> <p><a href="http://stackoverflow.com/questions/1773805/how-can-i-parse-a-yaml-file-in-python">How...
0
2016-06-05T07:49:12Z
[ "python", "flask", "yaml" ]
Import from YAML file
37,639,605
<p>I have a <code>config.yaml</code> file that I want to import in my <code>app.py</code>.</p> <p>This is my folder structure:</p> <pre><code> /root __init__.py app.py config.yaml </code></pre> <p><strong>App.py:</strong></p> <pre><code> import logging import config from flask import Flask...
-3
2016-06-05T07:43:38Z
37,639,654
<p>Why do you expect to be able to import a YAML file? It isn't Python, and it isn't an extension module, and these are the only things that Python will import.</p> <p>YAML (Yet Another Markup Language) is a data format, so you have to read the data with a suitable library: <a href="http://stackoverflow.com/questions/...
2
2016-06-05T07:49:32Z
[ "python", "flask", "yaml" ]
trouble connecting with thingspeak
37,639,618
<p>I am having trouble connecting a simple temp, humidity, dew point logger to Thingspeak, this code was working (I thought it was anyway) put this project down for a couple of weeks now having problems.</p> <p>when I run it I get the following</p> <pre><code>Traceback (most recent call last): File "DHH-test5.py", li...
0
2016-06-05T07:44:53Z
37,721,188
<p>Solved, for some reason my wifi connection was connected but couldn't get internet access, reinstalled raspbian and tried again and works</p>
0
2016-06-09T08:53:50Z
[ "python" ]
Python returning empty lists
37,639,634
<pre><code>class Map(): def returnWay(self, node1, node2): final_list = [] temp_list = [] self._returnWay(node1, node2, final_list, temp_list) return final_list def _returnWay(self, node1, node2, final_list, temp_list): if node1 not in temp_list: temp_list.a...
1
2016-06-05T07:47:13Z
37,639,878
<p>your code cannot run on my computer, because node1 is not defined.</p> <p>But I think I found the problem: In Python, if you append temp_list to final_list, all changes you do on temp_list apply also to final_list.</p> <p>I tried this out in the terminal, look here:</p> <pre><code>&gt;&gt;&gt; a = ['a', 'b', 'c']...
1
2016-06-05T08:25:25Z
[ "python", "list", "recursion", "graph" ]
Python: Kombu+RabbitMQ Deadlock - queues are either blocked or blocking
37,639,658
<h1>The problem</h1> <p>I have a <a href="https://www.rabbitmq.com/">RabbitMQ Server</a> that serves as a queue hub for one of my systems. In the last week or so, its producers come to a complete halt every few hours. </p> <h1>What have I tried</h1> <h2>Brute force</h2> <ul> <li>Stopping the consumers releases the ...
6
2016-06-05T07:49:42Z
37,641,042
<p>I'm writing this as an answer, partially because it may help and partially because it's too large to be a comment. </p> <p>First I'm sorry for missing this <code>message = queue.get(block=True)</code>. Also a disclaimer - I'm not familiar with python nor PIKA API.</p> <p><a href="http://www.rabbitmq.com/amqp-0-9-1...
1
2016-06-05T10:54:24Z
[ "python", "rabbitmq", "deadlock", "blockingqueue", "kombu" ]
Python: Kombu+RabbitMQ Deadlock - queues are either blocked or blocking
37,639,658
<h1>The problem</h1> <p>I have a <a href="https://www.rabbitmq.com/">RabbitMQ Server</a> that serves as a queue hub for one of my systems. In the last week or so, its producers come to a complete halt every few hours. </p> <h1>What have I tried</h1> <h2>Brute force</h2> <ul> <li>Stopping the consumers releases the ...
6
2016-06-05T07:49:42Z
37,906,157
<p>This is most likely caused by a memory leak in the management module for RabbitMQ 3.6.2. This has now been fixed in RabbitMQ 3.6.3, and is available <a href="https://github.com/rabbitmq/rabbitmq-server/releases/tag/rabbitmq_v3_6_3" rel="nofollow">here</a>.</p> <p>The issue itself is described <a href="https://githu...
4
2016-06-19T10:18:12Z
[ "python", "rabbitmq", "deadlock", "blockingqueue", "kombu" ]
PyInstaller: problems on update a json file from an EXE program file (-in the next relunch, json file it's not been update)
37,639,761
<p>I'm testing an EXE made by pyinstaller. In the project folder there is folder named config, which contains a json file where the user stores all the information he want about -for the GUI im using tkinter- But finally after I restart this application and reopen the json file, it's appearing the original file.</p> <...
0
2016-06-05T08:07:37Z
37,643,188
<p>First check that you pointing into a right path. Some operating systems responds differently for some system variables and function calls.</p> <pre><code>import sys import os if getattr(sys,'frozen',False): current_path = os.path.dirname(sys.executable) else: current_path = os.path.dirname(os.path.realpath(...
0
2016-06-05T14:46:17Z
[ "python", "json", "pyinstaller" ]
PyInstaller: problems on update a json file from an EXE program file (-in the next relunch, json file it's not been update)
37,639,761
<p>I'm testing an EXE made by pyinstaller. In the project folder there is folder named config, which contains a json file where the user stores all the information he want about -for the GUI im using tkinter- But finally after I restart this application and reopen the json file, it's appearing the original file.</p> <...
0
2016-06-05T08:07:37Z
37,843,763
<pre><code>import os import sys if getattr(sys, 'frozen', False): # we are running in a |PyInstaller| bundle base_path = sys._MEIPASS extDataDir = os.getcwd() print base_path print extDataDir else: # we are running in a normal Python environment base_path = os.getcwd() extDataDir = os.ge...
0
2016-06-15T19:02:57Z
[ "python", "json", "pyinstaller" ]
Process the lines in reverse order
37,639,789
<p>How do I process a log file (in my case nginx access.log) in reverse order?</p> <p><strong>Background</strong> I am developing a log file analyser script and I am just not able to get my head around on how to process huge log files from the end so I can sort out the time frames starting with the newest dates I need...
3
2016-06-05T08:11:52Z
37,640,254
<p>One way could be to access the end of the file using <code>seek</code> and then scanning the file in reverse from there. Example:</p> <pre><code>def Tail(filepath, nol=10, read_size=1024): """ This function returns the last line of a file. Args: filepath: path to file nol: number of lines to print ...
0
2016-06-05T09:13:43Z
[ "python", "nginx", "logfile", "logfile-analysis" ]
plt.contour in Python
37,639,849
<p>I would like to make a 2D contour plot given 3 numpy arrays of same size X Y Z with (X,Y) the coordinates and Z the value at (X,Y).</p> <p>Now, the function <code>plt.contour</code> seems to work only with a grid, and values at the intersection of the grid, and takes as input a rectangular grid only with 2D matrice...
1
2016-06-05T08:21:15Z
37,639,989
<p>Try to use <code>plt.tricontour</code>: <a href="http://matplotlib.org/api/pyplot_api.html?highlight=tricontour#matplotlib.pyplot.tricontour" rel="nofollow">http://matplotlib.org/api/pyplot_api.html?highlight=tricontour#matplotlib.pyplot.tricontour</a></p> <p>It draws contours on an unstructured triangular grid. </...
1
2016-06-05T08:41:31Z
[ "python", "matplotlib" ]
python multithread at output information
37,639,984
<p>Complete code (from below github linked page):</p> <pre><code>#!/usr/bin/python # -*- coding: UTF-8 -*- import threading import time import random import copy exitFlag = 0 class checkup (threading.Thread): #繼承thred 檢查流程 def __init__(self, threadID, patientList, patientStatus): threading.Thread...
-1
2016-06-05T08:40:28Z
37,640,514
<p>So as promised here is a PEP8 ok version (note also changed names in variables and keys to the used dicts). It should - besides answering the question - help the OP to grok the transformations (as @MoonCheesez suggested in comment) made.</p> <p>Note that I also already deleted the unsued exitFlag module level varia...
0
2016-06-05T09:46:20Z
[ "python", "multithreading" ]
Scrapy: Dynamically generate rules for each start_url
37,640,023
<p>I have created a spider which is supposed to crawl multiple websites and I need to define different rules for each URL in the start_url list.</p> <pre><code>start_urls = [ "http://URL1.com/foo" "http://URL2.com/bar" ] rules = [ Rule (LinkExtractor(restrict_xpaths=("//" + xpathString+"/a")), callback="p...
0
2016-06-05T08:44:23Z
37,640,634
<p>You can just override the <code>parse</code> method. This method will get a scrapy response object with full html content. You can run xpath on it. You will can also retrieve the url from the response object and depending on the url, you can run custom xpath. </p> <p>Please checkout the docs here: <a href="http://d...
0
2016-06-05T10:02:12Z
[ "python", "xpath", "scrapy" ]
Scrapy: Dynamically generate rules for each start_url
37,640,023
<p>I have created a spider which is supposed to crawl multiple websites and I need to define different rules for each URL in the start_url list.</p> <pre><code>start_urls = [ "http://URL1.com/foo" "http://URL2.com/bar" ] rules = [ Rule (LinkExtractor(restrict_xpaths=("//" + xpathString+"/a")), callback="p...
0
2016-06-05T08:44:23Z
37,654,662
<p>I assume you are using <code>CrawlSpider</code>. By default, <code>CrawlSpider</code> <code>rules</code> are applied for all pages (whatever the domain) your spider is crawling.</p> <p>If you are crawling multiple domains in start URLs, and want different rules for each domains, you wont be able to tell scrapy whic...
0
2016-06-06T10:05:55Z
[ "python", "xpath", "scrapy" ]
Checking grammar using a custom module for all possible combinations of words in string
37,640,057
<p>I am creating a software for a school, where students would actually type in sentence and then their grammar would be checked however they would be given random combination of words like</p> <pre><code> The brown quick fox fence over jumped the </code></pre> <p>from this they would have to figure out the senten...
0
2016-06-05T08:48:59Z
37,640,182
<p>One way to do this would be to turn your function into a generator.</p> <pre><code>def randm(text): text = text.split(" ") for i in itertools.permutations(text): yield " ".join(i) </code></pre> <p>Then all you have to do is</p> <pre><code>for word in randm(text): engrammar.grammar...
2
2016-06-05T09:04:04Z
[ "python", "parsing", "nltk", "permutation" ]
longest common subsequence of three integer sequences
37,640,082
<p>I've seen similar answers to this but not specific to the type of approach I'm using. I'm trying to find the longest common subsequence of the three sequences of integers. In this case a = [8, 3, 2, 1, 7] b = [8, 2, 1, 3, 8, 10, 7] c = [6, 8, 3, 1, 4, 7] and the output should be 3 where the longest common subsequenc...
-1
2016-06-05T08:50:55Z
37,640,475
<p>It is very similar to how we solve lcs question on two arrays. </p> <pre><code>def lcs3(a, b, c): n = len(a) m = len(b) l = len(c) if 0 in (n, m, l): return 0 E = [[[0] * (l + 1) for _ in range(m + 1)] for _ in range(n + 1)] for i in reversed(range(n + 1)): for j in revers...
0
2016-06-05T09:42:06Z
[ "python", "dynamic-programming" ]
How to output opencv to gstreamer in python?
37,640,104
<p>I want to process camera stream in opencv (that works fine), but then output the resulting processed frames over the network so I can see them as it's an embedded system without a monitor. I've spent days looking, but cannot work out how to push the frames to gstreamer in python. It looks like I should create an a...
0
2016-06-05T08:54:05Z
37,659,646
<p>I am no python expert .. but what about <a href="http://gstreamer-devel.966125.n4.nabble.com/appsrc-fed-data-python-td4665423.html" rel="nofollow">this</a> .. </p> <p>Suppose you have this code for connecting the appsrc need-data signal (like <a href="http://stackoverflow.com/q/7431245/3876138">here</a> ):</p> <pr...
0
2016-06-06T14:08:52Z
[ "python", "opencv", "raspberry-pi", "gstreamer" ]
How to read files from every zip folder present in a directory
37,640,140
<p>I have lots of zip files in a folder, say the folder contains 1.zip, 2.zip, 3.zip etc.<br/> Each of these zip folder contains many files. But each of them contains a file named ans.txt.<br/> Now the ans.txt have format like:<br/> Name= Devesh<br/> Marks= 20<br/> Age= 23<br/> RollNo.= 34343<br/> .<br/> .<br/> .<br/> ...
-1
2016-06-05T08:58:40Z
37,640,333
<p>Is this what you are trying to achieve?</p> <pre><code>import os import zipfile zipfiles = [z for z in os.listdir('.') if z.endswith('.zip')] for zfile in zipfiles: with zipfile.ZipFile(zfile) as z: with z.open('ans.txt') as f: if b'marks=' in f.read().lower(): print(z.fil...
1
2016-06-05T09:22:48Z
[ "python", "zipfile" ]
Setting variables in a function and importing them
37,640,171
<p>I'm writing an adventure game, and I'm writing functions in different files, such as the <code>saveGame</code> function and <code>read</code> function. There are 4 main files, all interconnected. The main one is <code>agMain.py</code>. My issue is that I've imported one of my other files <code>agRead.py</code>, and ...
1
2016-06-05T09:02:22Z
37,640,215
<p><a href="https://docs.python.org/3/tutorial/controlflow.html#defining-functions" rel="nofollow">https://docs.python.org/3/tutorial/controlflow.html#defining-functions</a>:</p> <blockquote> <p>More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable referen...
1
2016-06-05T09:09:08Z
[ "python" ]
Setting variables in a function and importing them
37,640,171
<p>I'm writing an adventure game, and I'm writing functions in different files, such as the <code>saveGame</code> function and <code>read</code> function. There are 4 main files, all interconnected. The main one is <code>agMain.py</code>. My issue is that I've imported one of my other files <code>agRead.py</code>, and ...
1
2016-06-05T09:02:22Z
37,640,236
<p>You need to understand a little more about <a href="http://python-textbok.readthedocs.io/en/latest/Variables_and_Scope.html" rel="nofollow"><em>scoping</em></a>. Inside a function, names that are bound by an assignment statement are created in the <em>local namespace</em> of the function call. This namespace is crea...
1
2016-06-05T09:11:02Z
[ "python" ]
Setting variables in a function and importing them
37,640,171
<p>I'm writing an adventure game, and I'm writing functions in different files, such as the <code>saveGame</code> function and <code>read</code> function. There are 4 main files, all interconnected. The main one is <code>agMain.py</code>. My issue is that I've imported one of my other files <code>agRead.py</code>, and ...
1
2016-06-05T09:02:22Z
37,640,315
<p>The variables are only visible from inside <code>read</code>.</p> <p>Contain the variables you want to use by doing something like this.</p> <p><code>agRead.py</code></p> <pre><code>class Conf(object): pass def read(): while True: try: file = open("agData.txt", "r") except: ...
0
2016-06-05T09:20:10Z
[ "python" ]
Setting variables in a function and importing them
37,640,171
<p>I'm writing an adventure game, and I'm writing functions in different files, such as the <code>saveGame</code> function and <code>read</code> function. There are 4 main files, all interconnected. The main one is <code>agMain.py</code>. My issue is that I've imported one of my other files <code>agRead.py</code>, and ...
1
2016-06-05T09:02:22Z
37,640,355
<p>Yes it's possible, but variable would be available only after function execution:</p> <pre><code>### file agRead.py ### def read(): # some code there read.my_super_var = 'value' ### file agMain.py ### import agRead agRead.read() print(agRead.read.my_super_var) # value </code></pre>
0
2016-06-05T09:25:16Z
[ "python" ]
Setting variables in a function and importing them
37,640,171
<p>I'm writing an adventure game, and I'm writing functions in different files, such as the <code>saveGame</code> function and <code>read</code> function. There are 4 main files, all interconnected. The main one is <code>agMain.py</code>. My issue is that I've imported one of my other files <code>agRead.py</code>, and ...
1
2016-06-05T09:02:22Z
37,640,594
<p>Okay, so I have worked this out. Thanks to everyone who answered, but holdenweb and nightcrawler especially. I have created a class in the agRead.py, and put all of the variables as a part of that class, before returning the class. Here is my agRead.py now:</p> <pre><code>import os import operator import sys impor...
0
2016-06-05T09:57:06Z
[ "python" ]
Setting variables in a function and importing them
37,640,171
<p>I'm writing an adventure game, and I'm writing functions in different files, such as the <code>saveGame</code> function and <code>read</code> function. There are 4 main files, all interconnected. The main one is <code>agMain.py</code>. My issue is that I've imported one of my other files <code>agRead.py</code>, and ...
1
2016-06-05T09:02:22Z
37,641,558
<p>By using chaining, you can reduce the number of lines used and increase readability. </p> <pre><code> class Conf(object): pass def read(): while True: try: file = open("agData.txt", "r") except: exec(open("agCreation.py").read()) break brea...
1
2016-06-05T11:51:28Z
[ "python" ]
unable to extract table data using beautifulsoup
37,640,226
<p>I have been trying to extract data from this table and having a lot of difficulty. any tips/help is appreciated <a href="http://finance.yahoo.com/options/lists/?mod_id=mediaquotesoptions&amp;tab=tab2&amp;rcnt=50" rel="nofollow">http://finance.yahoo.com/options/lists/?mod_id=mediaquotesoptions&amp;tab=tab2&amp;rcnt=5...
1
2016-06-05T09:10:26Z
37,640,587
<p>In order to do this type of tasks, a little bit of html code exploration is always needed. I use element inspector of Chrome. In order to download the source you have many options. The easiest is to download it manually using a regular browser (which I'd recommend if you don't need many htmls). If you want to downlo...
0
2016-06-05T09:56:36Z
[ "python", "web-scraping", "beautifulsoup" ]
unable to extract table data using beautifulsoup
37,640,226
<p>I have been trying to extract data from this table and having a lot of difficulty. any tips/help is appreciated <a href="http://finance.yahoo.com/options/lists/?mod_id=mediaquotesoptions&amp;tab=tab2&amp;rcnt=50" rel="nofollow">http://finance.yahoo.com/options/lists/?mod_id=mediaquotesoptions&amp;tab=tab2&amp;rcnt=5...
1
2016-06-05T09:10:26Z
37,641,546
<p>The content is inside the script tag so there is no table in the source you get back, it is dynamically created, if you look at the actual source not in developer tools or firebug for the script tag starting with:</p> <pre><code>&lt;script&gt;YMedia.use("media-rmp", "media-viewport-loader", function(Y){Y.Global.Me...
0
2016-06-05T11:50:12Z
[ "python", "web-scraping", "beautifulsoup" ]
How to Retrieve 10 first Google Search Results Using Python Requests
37,640,297
<p>I've seen lots of questions regarding this subject and i found out that Google has been updating the way its search engine APIs work. </p> <p>This link > <a href="http://stackoverflow.com/questions/4441812/get-the-first-10-google-results-using-googleapi">get the first 10 google results using googleapi</a> shows EXA...
0
2016-06-05T09:18:17Z
37,640,550
<p>Alternatively, you can use Python, Selenium and PhantomJS or other browsers to browse through Google's search results and grab the content. I haven't done that personally and don't know if there are challenges there. </p> <p>I believe the best way would be to use their search APIs. Please try the one you pointed ou...
0
2016-06-05T09:52:07Z
[ "python", "google-api", "urllib", "google-search-api" ]
How do I find the closest n numbers to a given number at x distance from it?
37,640,311
<p>For e.g. I have a list of number like</p> <pre><code>lst = [1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9] </code></pre> <p>And I need 2 numbers at 3 distance from a given number let's say 5, so the output list should look like this</p> <pre><code>output_lst = [2, 8] </code></pre> <p>Here by distance I mean the distance on nu...
2
2016-06-05T09:19:22Z
37,640,334
<p>You can use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> for that. See <a href="http://stackoverflow.com/q/34835951/4099593">this post</a> for more on list comprehensions. </p> <pre><code>&gt;&gt;&gt; lst = [1, 2, 3, 3, 4, 4, 5, 6, 7, 8...
3
2016-06-05T09:22:50Z
[ "python", "list", "python-3.x" ]
How do I find the closest n numbers to a given number at x distance from it?
37,640,311
<p>For e.g. I have a list of number like</p> <pre><code>lst = [1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9] </code></pre> <p>And I need 2 numbers at 3 distance from a given number let's say 5, so the output list should look like this</p> <pre><code>output_lst = [2, 8] </code></pre> <p>Here by distance I mean the distance on nu...
2
2016-06-05T09:19:22Z
37,640,352
<p>numpy approach:</p> <pre><code>import numpy as np check_number = 5 distance = 3 a = np.array([1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9]) a[np.absolute(a - check_number) == distance] </code></pre> <p>Check:</p> <pre><code>In [46]: a Out[46]: array([1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9]) In [47]: a[np.absolute(a-5) == 3] Out[4...
3
2016-06-05T09:24:44Z
[ "python", "list", "python-3.x" ]
Error in deleting excel sheet after exporting using python
37,640,312
<p>I am trying to save the chart from Excel as an image file in Python. I am using WIn32com, the chart is getting exported as required but when I am trying to delete the ActiveSheet,it is giving me the error.</p> <pre><code>excel.ActiveSheet().Delete() File "C:\Python27\lib\site-packages\win32com\client\dynamic.py",...
0
2016-06-05T09:19:27Z
37,641,389
<p>Is <code>ActiveSheet</code> a field, like you're using it here:</p> <pre><code>cht = excel.ActiveSheet.ChartObjects().Add(0,0,xl_range.Width, xl_range.Height) </code></pre> <p>Or a method like you're using it here:</p> <pre><code>excel.ActiveSheet().Delete() </code></pre> <p>Since the first call doesn't give you...
0
2016-06-05T11:34:46Z
[ "python", "windows", "excel", "winapi", "win32com" ]
how to filter users who are not being followed in django
37,640,382
<p>Friends, I am using django-friendship with django 1.9 to implement user follows. But on a 'users to follow' page, I want to filter those users who aren't being followed by the current user. How should I implement this?</p> <p>Here is my views.py</p> <pre><code>def users_to_follow(request): follow = Follow.obje...
1
2016-06-05T09:28:57Z
37,640,441
<p>The <code>follow</code> name (variable) is a list of user objects. You can get the IDs of those users like these: </p> <pre><code>follow = Follow.objects.following(request.user) follow_ids = [x.id for x in follow] </code></pre> <p>And then use <code>exclude</code> like this: </p> <pre><code>to_follow = User.objec...
1
2016-06-05T09:38:07Z
[ "python", "django" ]
how to filter users who are not being followed in django
37,640,382
<p>Friends, I am using django-friendship with django 1.9 to implement user follows. But on a 'users to follow' page, I want to filter those users who aren't being followed by the current user. How should I implement this?</p> <p>Here is my views.py</p> <pre><code>def users_to_follow(request): follow = Follow.obje...
1
2016-06-05T09:28:57Z
37,640,450
<p><code>exclude</code> does not work this way. You can try the following:</p> <pre><code>def users_to_follow(request): all_users = User.objects.exclude(following__follower=request.user) return render(request,"auths/users_to_follow.html",locals()) </code></pre>
0
2016-06-05T09:39:23Z
[ "python", "django" ]
how to filter users who are not being followed in django
37,640,382
<p>Friends, I am using django-friendship with django 1.9 to implement user follows. But on a 'users to follow' page, I want to filter those users who aren't being followed by the current user. How should I implement this?</p> <p>Here is my views.py</p> <pre><code>def users_to_follow(request): follow = Follow.obje...
1
2016-06-05T09:28:57Z
37,640,479
<p>According to Django QuerySet <a href="https://docs.djangoproject.com/ja/1.9/ref/models/querysets/#id4" rel="nofollow">documentation</a> (emphasis mine):</p> <blockquote> <p>Field lookups are how you specify the meat of an SQL WHERE clause. They’re specified as <strong>keyword arguments</strong> to the QuerySet ...
0
2016-06-05T09:42:31Z
[ "python", "django" ]
Image won't load on python-based webserver
37,640,460
<p>I've built a simple web server that gets a request and send a response. So when the server gets an invalid request, like "localhost/not-a-page", the server will send a response with the content of the HTML file "404.html" the webpage should display an image. So far, so good.</p> <p>But when the 404 page loads up, t...
0
2016-06-05T09:40:22Z
37,641,386
<p>Don't use relative paths for image like <code>../images/img.gif</code>. Rather use full url or url relative to the root. </p> <ul> <li><a href="http://localhost/images/img.gif" rel="nofollow">http://localhost/images/img.gif</a> - full url</li> <li>/images/img.gif - path relative to root url </li> </ul>
0
2016-06-05T11:34:43Z
[ "python", "html", "sockets", "webserver" ]
Image won't load on python-based webserver
37,640,460
<p>I've built a simple web server that gets a request and send a response. So when the server gets an invalid request, like "localhost/not-a-page", the server will send a response with the content of the HTML file "404.html" the webpage should display an image. So far, so good.</p> <p>But when the 404 page loads up, t...
0
2016-06-05T09:40:22Z
37,649,828
<p>Figured out my problem. After I saw the logs, I realized that the browser sends another request, for the image. And silly me, my code is:</p> <pre><code>if path ="/": status = 0 else: status = 1 </code></pre> <p>So for every request which is not root("/") the server will return 404.</p> <p>Oops </p>
0
2016-06-06T05:01:04Z
[ "python", "html", "sockets", "webserver" ]
Url pattern matching is confusing in django
37,640,484
<p>I have a url.py file as below - </p> <pre><code>app_name = "fronta" urlpatterns = [ url(r'^$', views.index, name='index'), url(r'home/', views.index, name='home'), url(r'lostform/', views.lostform, name='lostform'), url(r'submitlostform/',views.submitlostform, name="submitlostform"), ] </code></pre>...
1
2016-06-05T09:43:02Z
37,640,515
<p>Regular expressions.</p> <pre><code>url(r'lostform/', views.lostform, name='lostform'), </code></pre> <p>This matches <code>lostform/</code> but also <code>123lostform/</code> and <code>lostform/123</code> and <code>123lostform/321</code></p> <p>Change it to</p> <pre><code>url(r'^lostform/$', views.lostform, nam...
1
2016-06-05T09:46:25Z
[ "python", "django" ]
Scrapy XmlFeedSpider based on String Argument - How to Suppress Automatic Request
37,640,599
<p><strong>Aim:</strong> Trigger the execution of an XMLFeedSpider by passing the response as an argument (i.e. no need for start_urls). </p> <p>Example Command:</p> <pre><code>scrapy crawl spider_name -a response_as_string="&lt;xml&gt;&lt;sometag&gt;abc123&lt;/sometag&gt;&lt;/xml&gt;" </code></pre> <p>Example Spide...
1
2016-06-05T09:57:49Z
37,835,705
<p>Thanks Paul, you were spot on. Updated example code below. I stopped referring to the class as an XMLFeedSpider. Python script updated to be a class of type "object" with the ability to pass the url and body as arguments.</p> <pre><code>from scrapy.http import XmlResponse class ExampleXmlSpider(object): ...
0
2016-06-15T12:38:26Z
[ "python", "scrapy", "scrapy-spider" ]
When would the use of re.search over re.findall in Python Regex make sense?
37,640,602
<p>I understand the technical difference between using <code>re.search</code> and <code>re.findall</code> in Python, but would someone with more experience explain situations in which you might use <code>re.search</code> over just using <code>re.findall</code> for regex parsing?</p>
1
2016-06-05T09:58:06Z
37,640,818
<p>From documentation</p> <blockquote> <p>re.search(pattern, string, flags=0) :- Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that thi...
2
2016-06-05T10:22:34Z
[ "python", "regex" ]
Sum of medians (faster solution)
37,640,606
<p>We're given number N - length of the next list (1 &lt;= N &lt;= 10^5).</p> <p>Then there is a list of N numbers (1 &lt;= num &lt;= 10^9).</p> <p>The task is to find median on each iteration through 1 to N (on the i-th iteration we find median of sub-array lst[:i]) and then to find the sum of all N medians.</p> <h...
0
2016-06-05T09:58:25Z
37,642,011
<p>You can use two-heaps approach.</p> <p>Make two arrays with <code>length = N/2</code></p> <p>The first contains min <a href="https://en.wikipedia.org/wiki/Binary_heap" rel="nofollow">binary heap</a>, the second one - max binary heap. Min heap will store big values, max heap - small values</p> <p>At every iteratio...
1
2016-06-05T12:39:54Z
[ "python", "algorithm", "optimization", "binary-search-tree" ]
Sum of medians (faster solution)
37,640,606
<p>We're given number N - length of the next list (1 &lt;= N &lt;= 10^5).</p> <p>Then there is a list of N numbers (1 &lt;= num &lt;= 10^9).</p> <p>The task is to find median on each iteration through 1 to N (on the i-th iteration we find median of sub-array lst[:i]) and then to find the sum of all N medians.</p> <h...
0
2016-06-05T09:58:25Z
37,647,109
<p>Thanks to @MBo, I implemented solution for this problem using <strong>MinHeap</strong> and <strong>MaxHeap</strong>.</p> <p>In <strong>MinHeap</strong> there's the minimal value at the top and any child is bigger than its parent. On the contrary, <strong>MaxHeap</strong> contains all small elements with the biggest...
0
2016-06-05T21:48:38Z
[ "python", "algorithm", "optimization", "binary-search-tree" ]
Error with global variable
37,640,657
<p>Whenever I start my game and it loads my menu I get the error "SyntaxWarning: name 'finishes' is assigned to before global declaration". How do I fix this? I doesn't disrupt my game but any error should be fixed. I have cut down the below code to just show the essential code.</p> <pre><code>def load_level(level): ...
0
2016-06-05T10:04:33Z
37,640,728
<p>The problem here is that you are declaring <code>global</code> on variables more than once. Globals should be declared at the start of the function. Read more <a href="http://effbot.org/zone/syntaxwarning-name-assigned-to-before-global-declaration.htm" rel="nofollow">here</a>. To solve this, simply move <code>global...
4
2016-06-05T10:14:13Z
[ "python", "python-3.x", "pygame" ]
Python foreach from a MySQLdb
37,640,663
<p>I'm trying to fetch a list of timestamps in MySQL by Python. Once I have the list, I check the time now and check which ones are longer than 15min ago. Onces I have those, I would really like a final total number. This seems more challenging to pull off than I had originally thought.</p> <p>So, I'm using this to fe...
1
2016-06-05T10:05:06Z
37,640,704
<p>You could incorporate the 15min check directly into your SQL query. That way there is no need to mess around with timestamps and IMO it's far easier to read the code.</p> <p>If you need some date from other columns from your table: </p> <p><code>select * from machines where now() &gt; heartbeat_time + INTERVAL 15 ...
1
2016-06-05T10:10:54Z
[ "python", "mysql", "datetime" ]
Python foreach from a MySQLdb
37,640,663
<p>I'm trying to fetch a list of timestamps in MySQL by Python. Once I have the list, I check the time now and check which ones are longer than 15min ago. Onces I have those, I would really like a final total number. This seems more challenging to pull off than I had originally thought.</p> <p>So, I'm using this to fe...
1
2016-06-05T10:05:06Z
37,640,924
<p>I assume <code>heartbeat_time</code> field is a datetime field.</p> <pre><code>import datetime import MySQLdb import MySQLdb.cursors db = MySQLdb.connect(host=server, user=mysql_user, passwd=mysql_pwd, db=mysql_db, connect_timeout=10, cursorclass=MySQLdb.cursors.DictCursor) cur = db.cursor() ...
1
2016-06-05T10:37:10Z
[ "python", "mysql", "datetime" ]
Python match whitespaces
37,640,688
<p>Im trying to remove multiple white-spaces in a string. I've read about regular expressions in python langauge and i've tried to make it match all white-sapces in the string, but no success. The <code>return msg</code> part returns empty:</p> <p><strong>CODE</strong></p> <pre><code>import re def correct(string): ...
1
2016-06-05T10:08:49Z
37,640,722
<p><code>re.match</code> matches only at the beginning of the string. You need to use <code>re.search</code> instead.</p>
2
2016-06-05T10:13:06Z
[ "python" ]
Python match whitespaces
37,640,688
<p>Im trying to remove multiple white-spaces in a string. I've read about regular expressions in python langauge and i've tried to make it match all white-sapces in the string, but no success. The <code>return msg</code> part returns empty:</p> <p><strong>CODE</strong></p> <pre><code>import re def correct(string): ...
1
2016-06-05T10:08:49Z
37,640,741
<p>To accomplish this task, you can instead replace consecutive whitespaces with a single space character, for example, using <code>re.sub</code>.<br> Example:</p> <pre><code>import re def correct(string): fmatch = re.sub(r'\s+', ' ', string) return fmatch print correct("This is very funny and cool.In...
3
2016-06-05T10:15:07Z
[ "python" ]
Python match whitespaces
37,640,688
<p>Im trying to remove multiple white-spaces in a string. I've read about regular expressions in python langauge and i've tried to make it match all white-sapces in the string, but no success. The <code>return msg</code> part returns empty:</p> <p><strong>CODE</strong></p> <pre><code>import re def correct(string): ...
1
2016-06-05T10:08:49Z
37,640,923
<p>Maybe this code helps you?</p> <pre><code>import re def correct(string): return " ".join(re.split(' *', string)) </code></pre>
0
2016-06-05T10:37:06Z
[ "python" ]
Python match whitespaces
37,640,688
<p>Im trying to remove multiple white-spaces in a string. I've read about regular expressions in python langauge and i've tried to make it match all white-sapces in the string, but no success. The <code>return msg</code> part returns empty:</p> <p><strong>CODE</strong></p> <pre><code>import re def correct(string): ...
1
2016-06-05T10:08:49Z
37,641,292
<p>One line no direct import</p> <pre><code>ss= "This is very funny and cool.Indeed!" ss.replace(" ", " ") #ss.replace(" ", " "*2) #'This is very funny and cool.Indeed!' </code></pre> <p>Or, as the question states:</p> <pre><code>ss= "This is very funny and cool.Indeed!" ss.replace(" ", "") #'Thisisveryfun...
0
2016-06-05T11:24:08Z
[ "python" ]
How to make a 3D plot in matplotlib from data z=f(x,y) read from file
37,640,969
<p>I need to create a 3D plot in matplotlib. I am reading Z values from a text file formated as 1D array. This data represents value for every point on a 50x50 square. So first 50 values are for points (0,0),(1,0)..(49,0), next 50 are for (0,1),(1,1) and so on. So far i have written the following code:</p> <pre clas...
1
2016-06-05T10:44:14Z
37,641,355
<p>First, you forgot to import Axes3D: <code>import matplotlib.pyplot as plt</code>.</p> <p>Second, you code has strange meaningless line: <code>values[50*50*nb:50*50*(nb+1)]</code> and indentation is wrong in your code.</p> <p>Third, to plot regularly gridded data you do not need plot_trisurf, use plot_surface:</p> ...
1
2016-06-05T11:30:37Z
[ "python", "matplotlib", "plot", "3d" ]
Is there a way to add sections to QListView in PySide or PyQt?
37,641,030
<p>This question is an exact duplicate of <a href="http://stackoverflow.com/questions/25560547/is-there-a-way-to-add-sections-to-qlistview">this</a> unanswered question, except that I'm using Python.</p> <p>I've got this.</p> <p><a href="http://i.stack.imgur.com/5qOhq.png" rel="nofollow"><img src="http://i.stack.imgu...
1
2016-06-05T10:53:15Z
37,654,903
<p>What you want is a <code>QTreeWidget</code> (or <code>QTreeView</code> if you want separate model/views, but you'll have to create your own model for that to work).</p> <pre><code>tree = QtGui.QTreeWidget() tree.setHeaderLabels(['Name']) data = ({"label": "Ben", "section": "Human"}, {"label": "Steve", "sec...
2
2016-06-06T10:18:39Z
[ "python", "qt", "pyqt", "pyside" ]
Is there a way to add sections to QListView in PySide or PyQt?
37,641,030
<p>This question is an exact duplicate of <a href="http://stackoverflow.com/questions/25560547/is-there-a-way-to-add-sections-to-qlistview">this</a> unanswered question, except that I'm using Python.</p> <p>I've got this.</p> <p><a href="http://i.stack.imgur.com/5qOhq.png" rel="nofollow"><img src="http://i.stack.imgu...
1
2016-06-05T10:53:15Z
37,664,196
<p>Ok, you intend to connect the other views (such as the Pie chart) to a <code>QAbstractListModel</code> descendant. I guess this is possible but it is not that common. Hence the confusion. IHMO the Qt Model classes are not that great and I wouldn't use them if I didn't have a table or tree view. Nothing stops you fro...
1
2016-06-06T18:15:32Z
[ "python", "qt", "pyqt", "pyside" ]