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
django unittest import error
37,530,792
<p>Microsoft Windows [Version 6.0.6002] Copyright (c) 2006 Microsoft Corporation. All rights reserved.</p> <pre><code>C:\Users\mech10&gt;cd superlists C:\Users\mech10\superlists&gt;python manage.py test Creating test database for alias 'default'... E ==================================================================...
0
2016-05-30T17:12:31Z
37,531,951
<p>I have found my mistake. I started to use backspace for all the lines and clear all the irrelevant spaces in tests.py and the problem is solved now.</p>
0
2016-05-30T18:42:21Z
[ "python", "django", "unit-testing", "importerror" ]
Troubles managing attributes in python's class
37,530,796
<p>I am a python beginner and it is my first time dealing with OOP. Could you help me to figure out what I am doing wrong whit the code below:</p> <pre><code>class Example(object): def __init__(self, a, b): self.a = a self.b = b self.c = self.a + self.b/2 def property1(self): ...
-1
2016-05-29T10:09:11Z
37,530,929
<p>As at when <code>get_obs1</code> was called the attribute <code>obs1</code> was not yet defined and not yet bounded to your class instance. Your question already gives a hint at using <code>property</code>, so use this instead and define your <em>private</em> variables in <code>__init__</code>:</p> <pre><code>class...
0
2016-05-30T17:23:30Z
[ "python" ]
Slow processing time of a list
37,530,819
<p>Why is my code so sluggish (inefficient)? I need to make two methods to record the time it takes to process a list of a given size. I have a <code>search_fast</code> and <code>search_slow</code> method. Even though there is a difference between those two search times. <code>Search_fast</code> is still pretty slow. I...
2
2016-05-30T17:14:22Z
37,530,950
<p>The fastest way is using <code>in</code> operator, which tests membership of a value in a sequence.</p> <pre><code>if value in some_container: … </code></pre> <p>Reference: <a href="https://docs.python.org/3/reference/expressions.html#membership-test-operations" rel="nofollow">https://docs.python.org/3/refer...
1
2016-05-30T17:25:18Z
[ "python", "list", "for-loop", "timeit" ]
Slow processing time of a list
37,530,819
<p>Why is my code so sluggish (inefficient)? I need to make two methods to record the time it takes to process a list of a given size. I have a <code>search_fast</code> and <code>search_slow</code> method. Even though there is a difference between those two search times. <code>Search_fast</code> is still pretty slow. I...
2
2016-05-30T17:14:22Z
37,530,995
<p>Adding the following code to above:</p> <pre><code>t = Timer(lambda: 10 in l) print(t.timeit()) </code></pre> <p>produces the following on my system:</p> <pre><code>0.6166538814701169 3.884095008084452 0.29087270299795875 &gt;&gt;&gt; </code></pre> <p>Hope this helps. The basic idea is to tap into underlying C c...
1
2016-05-30T17:28:06Z
[ "python", "list", "for-loop", "timeit" ]
Slow processing time of a list
37,530,819
<p>Why is my code so sluggish (inefficient)? I need to make two methods to record the time it takes to process a list of a given size. I have a <code>search_fast</code> and <code>search_slow</code> method. Even though there is a difference between those two search times. <code>Search_fast</code> is still pretty slow. I...
2
2016-05-30T17:14:22Z
37,532,229
<p>I managed to find out what made the code sluggish. It was a simple mistake of adding to the list by<code>extend</code> instead of <code>append</code>. </p> <pre><code>def fillList(l, n): l.**append**(range(1, n + 1)) l = [] fillList(l, 100) </code></pre> <p>Now <code>search_slow</code>clocks in at <code>3.9182...
0
2016-05-30T19:04:57Z
[ "python", "list", "for-loop", "timeit" ]
Getting input dimensions in pymc3 correct
37,530,828
<p>Say I have 10 coins from the same mint, I flip them each 50 times, now I want to estimate bias of the mint as well as the individual bias of all the coins.</p> <p>The way I want to do this is like this:</p> <pre><code># Generate a list of 10 arrays with 50 flips in each test = [bernoulli.rvs(0.5, size=50) for x in...
0
2016-05-30T17:15:12Z
37,548,156
<p>If you are new to Python may be you are not familiar with the concept of <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html" rel="nofollow">broadcasting</a>, that is used when working with NumPy arrays, and is also useful for defining PyMC3 models. Broadcasting enables us to operate arithm...
1
2016-05-31T14:13:28Z
[ "python", "bayesian", "pymc", "mcmc", "pymc3" ]
Going character by character in a string and swapping whitespaces with python
37,530,842
<p>Okay so I have to switch ' ' to *s. I came up with the following</p> <pre><code>def characterSwitch(ch,ca1,ca2,start = 0, end = len(ch)): while start &lt; end: if ch[start] == ca1: ch[end] == ca2 start = start + 1 sentence = "Ceci est une toute petite phrase." print characterSwitch(s...
5
2016-05-30T17:16:46Z
37,530,885
<p>Are you looking for <code>replace()</code> ?</p> <pre><code>sentence = "Ceci est une toute petite phrase." sentence = sentence.replace(' ', '*') print sentence # Ceci*sest*sune*stoute*spetite*sphrase. </code></pre> <p>See <a href="http://ideone.com/zeyfVb" rel="nofollow"><strong>a demo on ideone.com</strong></a> a...
4
2016-05-30T17:19:36Z
[ "python", "string", "whitespace" ]
Going character by character in a string and swapping whitespaces with python
37,530,842
<p>Okay so I have to switch ' ' to *s. I came up with the following</p> <pre><code>def characterSwitch(ch,ca1,ca2,start = 0, end = len(ch)): while start &lt; end: if ch[start] == ca1: ch[end] == ca2 start = start + 1 sentence = "Ceci est une toute petite phrase." print characterSwitch(s...
5
2016-05-30T17:16:46Z
37,531,161
<p>Assuming you have to do it character by character you could do it this way:</p> <pre><code>sentence = "this is a sentence." replaced = "" for c in sentence: if c == " ": replaced += "*" else: replaced += c print replaced </code></pre>
1
2016-05-30T17:41:26Z
[ "python", "string", "whitespace" ]
How do I do extract information from two different indices in two different data frames in Python?
37,530,872
<p>I have two data frames of different length: </p> <pre><code> Df1 Df2 11 A12 11 B72 11 E17 12 F15 11 B72 13 C12 11 E15 11 C12 11 B2 43 C11 </code></pre> <p><br/></p> <p>...
0
2016-05-30T17:19:05Z
37,532,130
<p>I'm going to guess a bit since you didn't provide an output for your example (also try to provide the data in source code, so that its easily applicable by other people for testing purposes).</p> <p>In any case try and see if the following recipe does what you wish. It relies on nested loops and <code>if</code> sta...
0
2016-05-30T18:56:02Z
[ "python", "python-2.7", "pandas", "dataframe" ]
Loop gets stuck on 1st iteration
37,530,907
<p>While trying to create a web crawler, I'm trying to define this function:</p> <pre><code>#a and b are lists. def union(a, b): i = 0 while i &lt;= len(b): if b[i] in a : a = a.append(b[i]) i = i + 1 return a </code></pre> <p>then testing it, I input:</p> <pre><code>a ...
-1
2016-05-30T17:21:26Z
37,531,760
<p>See the updated and commented code below</p> <pre><code>#a and b are lists. def union(a, b): i = 0 while i &lt;= len(b): if b[i] in a : # the problem lies here. append returns None # a = a.append(b[i]) # this should work a.append(b[i]) i = i...
0
2016-05-30T18:27:50Z
[ "python", "list", "if-statement", "for-loop", "web-crawler" ]
Last 10 minutes per day
37,530,911
<p>I'm trying to obtain how much of the transaction volume of a business is done of the last each 10 minutes of each day</p> <p>The data I have is the following:</p> <pre><code>DF_Q Out[97]: LongTime 2016-01-04 09:30:00 35077034 2016-01-04 09:30:11 1119 2016-01-04 09:30:21 12295250 2016-01-04 09:30:...
2
2016-05-30T17:21:49Z
37,531,535
<p>after resampling your Series/DF you can do it this way:</p> <pre><code>DF_Qmin.ix[DF_Qmin.index.minute == 50] </code></pre>
0
2016-05-30T18:11:49Z
[ "python", "pandas", "group-by", "resampling", "days" ]
Last 10 minutes per day
37,530,911
<p>I'm trying to obtain how much of the transaction volume of a business is done of the last each 10 minutes of each day</p> <p>The data I have is the following:</p> <pre><code>DF_Q Out[97]: LongTime 2016-01-04 09:30:00 35077034 2016-01-04 09:30:11 1119 2016-01-04 09:30:21 12295250 2016-01-04 09:30:...
2
2016-05-30T17:21:49Z
37,531,666
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><code>date</code></a> and aggregating <a href="http://pan...
1
2016-05-30T18:20:46Z
[ "python", "pandas", "group-by", "resampling", "days" ]
find zero blocks greater than 32KB in files
37,530,935
<p>what is the fastest way to check if are blocks of zeros in a lot of files. The blocks should be greater than 32000 bytes of zeros. The following code is to slow:</p> <pre><code>empty_blocks = [] min_length = 32000 block = False begin = -1 data = open(file_name,'rb').read() for i,byte in enumerate(data): byt...
2
2016-05-30T17:24:07Z
37,539,278
<p>So, assuming the block size of 32768 bytes, I came up with something along the lines:</p> <pre><code>from functools import partial BLOCKSIZE = 32 * 1024 with open('testfile.bin', 'rb') as f: for block_number, data in enumerate(iter(partial(f.read, BLOCKSIZE), b'')): if not any(data): print...
3
2016-05-31T07:19:58Z
[ "python", "file", "io" ]
find zero blocks greater than 32KB in files
37,530,935
<p>what is the fastest way to check if are blocks of zeros in a lot of files. The blocks should be greater than 32000 bytes of zeros. The following code is to slow:</p> <pre><code>empty_blocks = [] min_length = 32000 block = False begin = -1 data = open(file_name,'rb').read() for i,byte in enumerate(data): byt...
2
2016-05-30T17:24:07Z
37,540,382
<p>Start by mmapping the file:</p> <pre><code>import mmap, os, re f = open(filename) m = mmap.mmap(f.fileno(), os.fstat(f.fileno()).st_size, prot=mmap.PROT_READ) </code></pre> <p>Using regular expressions is convenient:</p> <pre><code>for match in re.findall(b'\0{32768}, m): print(match.start()) </code></pre> <...
0
2016-05-31T08:17:36Z
[ "python", "file", "io" ]
Python: interpreter says "None" after parsing file
37,530,960
<p>I've written a simple interpreter with Python for a programming language I've created. I have a little problem though: when I try to read a file, so the code can be interpreted, Python says <code>None</code>.</p> <p>Here's the interpreter code:</p> <pre><code>import sys class Interpret: def read(self, cmd): ...
3
2016-05-30T17:25:36Z
37,531,008
<p>You're just <em>calling</em> <code>self.parse</code> and not using its return value and, given that <code>self.parse</code> doesn't output anything and <code>read</code> returns nothing (<code>None</code>), you're getting <code>None</code> as a result.</p> <p>You may want your <code>read</code> to <code>yield self....
3
2016-05-30T17:28:59Z
[ "python", "command-line-arguments", "interpreter" ]
Python: interpreter says "None" after parsing file
37,530,960
<p>I've written a simple interpreter with Python for a programming language I've created. I have a little problem though: when I try to read a file, so the code can be interpreted, Python says <code>None</code>.</p> <p>Here's the interpreter code:</p> <pre><code>import sys class Interpret: def read(self, cmd): ...
3
2016-05-30T17:25:36Z
37,531,652
<p>One of your problems is this line:</p> <pre><code>code = open(sys.argv[1], 'r') </code></pre> <p><code>open</code> returns a file object, not the content of the file. Instead, do:</p> <pre><code>with open(sys.argv[1], 'r') as f: code = f.read() </code></pre> <hr> <p>On to the next issue:</p> <pre><code>for...
1
2016-05-30T18:19:48Z
[ "python", "command-line-arguments", "interpreter" ]
Calculation involving two DataFrames
37,530,976
<p>I have two <code>DataFrame</code></p> <p>df1:</p> <pre><code> mat inv 0 100 23 1 101 35 2 102 110 </code></pre> <p>df2:</p> <pre><code> mat sale 0 100 45 1 101 100 2 102 90 </code></pre> <p>I merged the <code>DataFrame</code> in <code>df</code>:</p> <pre><code> mat inv sale 0 ...
2
2016-05-30T17:27:00Z
37,531,096
<p>surely <code>df1['days'] = df1['inv'] / df2['sale'] * 30</code> works?</p>
0
2016-05-30T17:37:22Z
[ "python", "pandas", "merge" ]
Calculation involving two DataFrames
37,530,976
<p>I have two <code>DataFrame</code></p> <p>df1:</p> <pre><code> mat inv 0 100 23 1 101 35 2 102 110 </code></pre> <p>df2:</p> <pre><code> mat sale 0 100 45 1 101 100 2 102 90 </code></pre> <p>I merged the <code>DataFrame</code> in <code>df</code>:</p> <pre><code> mat inv sale 0 ...
2
2016-05-30T17:27:00Z
37,531,135
<p>You can create the new column directly if you make sure the <code>mat</code> columns align properly:</p> <pre><code>df1 = df1.set_index('mat') df2 = df2.set_index('mat') df2['days'] = df1.inv.div(df2.sale).mul(30) sale days mat 100 4 15.33 101 100 10.50 102 90 36.67 </co...
2
2016-05-30T17:39:37Z
[ "python", "pandas", "merge" ]
Calculation involving two DataFrames
37,530,976
<p>I have two <code>DataFrame</code></p> <p>df1:</p> <pre><code> mat inv 0 100 23 1 101 35 2 102 110 </code></pre> <p>df2:</p> <pre><code> mat sale 0 100 45 1 101 100 2 102 90 </code></pre> <p>I merged the <code>DataFrame</code> in <code>df</code>:</p> <pre><code> mat inv sale 0 ...
2
2016-05-30T17:27:00Z
37,531,765
<p>you can also do it this way:</p> <pre><code>In [181]: df1['days'] = (df1.inv / df1['mat'].map(df2.set_index('mat')['sale']) * 30).astype(int) In [182]: df1 Out[182]: mat inv days 0 100 23 15 1 101 35 10 2 102 110 36 </code></pre>
1
2016-05-30T18:28:02Z
[ "python", "pandas", "merge" ]
Removing extra characters from python string
37,531,032
<p><strong>Information I want to extract:</strong> The Locations Al Bayan and Nepal in a list <code>['Al Bayan' , 'Nepal']</code></p> <pre><code>&lt;div class="location"&gt; &lt;div class="listing-location"&gt;Location&lt;/div&gt; &lt;div class="location-areas"&gt; &lt;span class="location"&gt;Al Bayan&lt;/span&gt; â€...
0
2016-05-30T17:30:56Z
37,531,495
<p>I'd assume <code>soup</code> is a <code>BeautifulSoup</code> instance, as such <code>soup = BeautifulSoup(html_string, "html.parser")</code> where <code>html_string</code> is your <code>html markup</code>.</p> <p>Try this out:</p> <p><code>area_list = [area.get_text().strip().encode('utf-8') for area in soup.find_...
0
2016-05-30T18:07:53Z
[ "python", "python-2.7", "python-3.x", "web-scraping", "bs4" ]
Python requests - Attempt to get presto documentation returns sslv3 alert handshake failure
37,531,043
<p>I'm trying to get the content of <a href="https://prestodb.io/docs/current/functions/logical.html" rel="nofollow">Presto public documentation</a> for some analysis using Python requests:</p> <pre><code>import requests requests.get('https://prestodb.io/docs/current/functions/logical.html') </code></pre> <p>This re...
1
2016-05-30T17:31:57Z
37,558,871
<p>Thanks to Lukas Graf and I resolved this based on <a href="https://github.com/kennethreitz/requests/issues/2022" rel="nofollow">https://github.com/kennethreitz/requests/issues/2022</a>. What I actually did is to install OpenSSL from Homebrew, then install a new version of Python 2 from Homebrew which will automatica...
1
2016-06-01T03:23:28Z
[ "python", "python-requests" ]
Python SQLALCHEMY query using MID()
37,531,050
<p>I have a database and am trying to query information using the MID() function. In normal SQL I would use MID such as (From W3 example website)..</p> <pre><code>SELECT MID(City,1,4) AS ShortCity FROM Customers; </code></pre> <p>Converting this to sqlalchemy has been a bit of a challenge. I am able to perform the ...
1
2016-05-30T17:32:50Z
37,532,022
<p>I can see that you're missing a comma <code>,</code> between the parentheses in</p> <pre><code>func.mid(Item.title.like, 1, 3)('%' +search_term + '%') </code></pre> <p>which makes the 2nd expression in parentheses an argument to the first. That is the source of the exception</p> <pre><code>TypeError: 'Function' o...
1
2016-05-30T18:48:15Z
[ "python", "sql", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Ordering dict objects based on multiple key values and comparison rules
37,531,055
<p>I have an array of dict objects that I should have to order based on multiple rules. </p> <p>This is how the sample dicts looks like:</p> <pre><code>dict1 = {'key1': '85', 'key2': '163', 'key3': '3'} dict2 = {'key1': '3', 'key2': '23', 'key3': '1'} dict3 = {'key1': '88', 'key2': '153', 'key3': '6'} </code></pre> ...
-1
2016-05-30T17:33:20Z
37,531,125
<p>If I understand correctly you want to add key 1 and key 2 and subtract key 3 and order them on this number from high to low? If so, do this:</p> <pre><code>list_dicts = sorted(list_dicts, key=lambda x:int(x['key3'])-int(x['key2'])-int(x['key1'])) </code></pre> <p>What this does is map your values to integers and s...
2
2016-05-30T17:39:12Z
[ "python", "dictionary" ]
Using Agg to find most frequent user per day
37,531,059
<p>I have some twitter data</p> <pre><code>username time RamiAlLolah 2016-03-11 grezz10 2016-02-19 DawlaWitness11 2016-04-08 murasil1 2016-04-29 mustaklash 2016-02-19 </code></pre> <p>I'd like to be able to determine who was the most frequent tweeter on each day. I can group the dataframe in terms of day...
1
2016-05-30T17:33:38Z
37,531,365
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><code>dt.date</code></a> with aggregating <a href="htt...
0
2016-05-30T17:58:01Z
[ "python", "pandas", "dataframe", "group-by" ]
Using Agg to find most frequent user per day
37,531,059
<p>I have some twitter data</p> <pre><code>username time RamiAlLolah 2016-03-11 grezz10 2016-02-19 DawlaWitness11 2016-04-08 murasil1 2016-04-29 mustaklash 2016-02-19 </code></pre> <p>I'd like to be able to determine who was the most frequent tweeter on each day. I can group the dataframe in terms of day...
1
2016-05-30T17:33:38Z
37,533,344
<p>Another solution is to take the mode of each time and concat solutions</p> <pre><code>r = pd.concat([df[df.time == i].mode() for i in df.time.unique()]) </code></pre> <p><em>optional</em> for the index you could do (as you prefer your results)</p> <pre><code>r = r.reset_index(drop=True) </code></pre> <p>or</p> ...
0
2016-05-30T20:35:43Z
[ "python", "pandas", "dataframe", "group-by" ]
BeautifulSoup not downloading files as expected
37,531,063
<p>I'm trying to download all the .txt files from <a href="http://m-selig.ae.illinois.edu/props/volume-1/data/" rel="nofollow">this</a> website with the following code:</p> <pre><code>from bs4 import BeautifulSoup as bs import urllib import urllib2 baseurl = "http://m-selig.ae.illinois.edu/props/volume-1/data/" sou...
1
2016-05-30T17:33:52Z
37,531,228
<p>Maybe you should use link['href'] instead of the text. In this way you would not have the space which is in the presentation:</p> <pre><code>&lt;li&gt;&lt;a href="ance_8.5x6_2850cm_5004.txt"&gt; ance_8.5x6_2850cm_5004.txt&lt;/a&gt;&lt;/li&gt; </code></pre> <p>In the text you have: " ance_8.5x6_2850cm_5004.txt" and...
1
2016-05-30T17:46:56Z
[ "python", "beautifulsoup" ]
BeautifulSoup not downloading files as expected
37,531,063
<p>I'm trying to download all the .txt files from <a href="http://m-selig.ae.illinois.edu/props/volume-1/data/" rel="nofollow">this</a> website with the following code:</p> <pre><code>from bs4 import BeautifulSoup as bs import urllib import urllib2 baseurl = "http://m-selig.ae.illinois.edu/props/volume-1/data/" sou...
1
2016-05-30T17:33:52Z
37,531,250
<p>You are reading the text of the links, not the href, and the text contains an extra space. This retrieves the hrefs:</p> <pre><code>links = soup.findAll("a", href=True) for link in links: print link['href'] urllib.urlretrieve(baseurl+link['href'], link['href']) </code></pre> <blockquote> <p>I would actua...
2
2016-05-30T17:48:21Z
[ "python", "beautifulsoup" ]
BeautifulSoup not downloading files as expected
37,531,063
<p>I'm trying to download all the .txt files from <a href="http://m-selig.ae.illinois.edu/props/volume-1/data/" rel="nofollow">this</a> website with the following code:</p> <pre><code>from bs4 import BeautifulSoup as bs import urllib import urllib2 baseurl = "http://m-selig.ae.illinois.edu/props/volume-1/data/" sou...
1
2016-05-30T17:33:52Z
37,531,332
<p>You need to pull the href to get the link, you can also get just links that contain <code>geom.txt</code> using a css selector:</p> <pre><code>from bs4 import BeautifulSoup as bs import urllib import urllib2 from urlparse import urljoin baseurl = "http://m-selig.ae.illinois.edu/props/volume-1/data/" soup = bs...
1
2016-05-30T17:55:06Z
[ "python", "beautifulsoup" ]
BeautifulSoup not downloading files as expected
37,531,063
<p>I'm trying to download all the .txt files from <a href="http://m-selig.ae.illinois.edu/props/volume-1/data/" rel="nofollow">this</a> website with the following code:</p> <pre><code>from bs4 import BeautifulSoup as bs import urllib import urllib2 baseurl = "http://m-selig.ae.illinois.edu/props/volume-1/data/" sou...
1
2016-05-30T17:33:52Z
37,531,401
<pre><code>from bs4 import BeautifulSoup as bs import urllib import urllib2 baseurl = "http://m-selig.ae.illinois.edu/props/volume-1/data/" soup = bs(urllib2.urlopen(baseurl), 'lxml') links = soup.findAll("a") for link in links: print link.text data = urllib.urlopen(baseurl+link.text.strip()) with open(l...
0
2016-05-30T18:00:24Z
[ "python", "beautifulsoup" ]
Python: how to prevent Unicode representation for Latin1 characters?
37,531,067
<p>How can I prevent Flask from returning Latin characters as Unicode representation? For example, for this sort of characters: <a href="http://graphemica.com/%C3%91" rel="nofollow">http://graphemica.com/%C3%91</a></p> <p>My FlaskApp performs a SELECT inside a MySQL database, retrieves row by row, adding them to a lis...
-1
2016-05-30T17:34:19Z
37,543,383
<p><code>"Ñ"</code> and <code>"\u00d1"</code> json strings represent the same <a href="http://codepoints.net/U+00D1" rel="nofollow">U+00D1</a> Unicode character:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; json.loads(u'"Ñ"') == json.loads(u'"\\u00d1"') True </code></pre> <p>Note: the backslash is escaped b...
1
2016-05-31T10:38:50Z
[ "python", "json", "unicode", "flask", "latin1" ]
takewhile in itertools takes one value too much
37,531,131
<p>I have the following code to stop the iterator on a certain value, save the state until the value and return both the saved state and the original state. I am using takewhile from itertools to get the values till the given break_point, and then I use chain on the saved iterator until the break_point and the initial ...
0
2016-05-30T17:39:30Z
37,531,374
<p><code>it</code> is not just missing the breakpoint value, it's missing all the values before it because it's just an iterator created with <code>iter</code> and not a list, so <code>iter_sample</code> uses up values as it iterates over them with <code>takewhile</code>. This includes the breakpoint itself because <co...
3
2016-05-30T17:58:30Z
[ "python", "python-2.7", "itertools" ]
string indices must be integers error with json
37,531,214
<p>I am trying to parse out following json using pythong:</p> <pre><code>{ "document_tone":{ "tone_categories":[ { "tones":[ { "score":0.044115, "tone_id":"anger", "tone_name":"Anger" }, ...
-2
2016-05-30T17:45:44Z
37,531,255
<pre><code>tone_analyzer.tone(text='I am very happy') </code></pre> <p>returns a dictionary, there is no need to use <code>json</code> to modify the data in any way, just do</p> <pre><code>X = tone_analyzer.tone(text='I am very happy') </code></pre> <p>Note that you have already <a href="http://stackoverflow.com/a/3...
2
2016-05-30T17:48:41Z
[ "python", "json" ]
Using itertools.combinations with columns
37,531,215
<p>I have a Dataframe df with 3 columns. A,B and C</p> <pre><code>A B C 2 4 4 5 2 5 6 9 5 </code></pre> <p>My goal is to use itertools.combinations to find all non-repeating column pairs and to put the first column pair in one DataFrame and the second in the other. So all pairs of this would give A:B,A:C,B:C.</p> <...
0
2016-05-30T17:45:44Z
37,534,869
<p>Utilize the <code>zip</code> function to group the columns to be used in each DataFrame separately, and then use <code>pandas.concat</code> to construct your new DataFrames:</p> <pre><code>from itertools import combinations df1_cols, df2_cols = zip(*combinations(df.columns,2)) df1 = pd.concat([df[col] for col in ...
0
2016-05-30T23:45:58Z
[ "python", "pandas", "combinations" ]
Total Downloads of Module Missing on PyPi
37,531,231
<p>Up until recently, it was possible to see how many times a python module indexed on <a href="https://pypi.python.org/pypi" rel="nofollow">https://pypi.python.org/pypi</a> had been downloaded (each module listed downloads for the past 24hrs, week and month). Now that information seems to be missing.</p> <p>Download ...
1
2016-05-30T17:47:05Z
37,531,550
<p>Don't know what happened (although it <a href="http://stackoverflow.com/questions/10376429/number-of-installations-statistics-for-pypi-packages">happened before</a>, <a href="http://stackoverflow.com/questions/9648015/pypi-download-counts-seem-unrealistic">i.e.</a>) but you might wan't to try the <a href="http://pyp...
1
2016-05-30T18:12:46Z
[ "python", "pypi" ]
Total Downloads of Module Missing on PyPi
37,531,231
<p>Up until recently, it was possible to see how many times a python module indexed on <a href="https://pypi.python.org/pypi" rel="nofollow">https://pypi.python.org/pypi</a> had been downloaded (each module listed downloads for the past 24hrs, week and month). Now that information seems to be missing.</p> <p>Download ...
1
2016-05-30T17:47:05Z
37,540,056
<p>This <a href="https://mail.python.org/pipermail/distutils-sig/2016-May/028967.html" rel="nofollow">email</a> from Donald Stufft (PyPI maintainer) from <code>distutils</code> mailing list says:</p> <blockquote> <p>Just an FYI, I've <a href="https://bitbucket.org/pypa/pypi/commits/f54a11a2842e687e8de01761a8ff8ceac0...
4
2016-05-31T07:58:57Z
[ "python", "pypi" ]
Wait until Gmail email received
37,531,292
<p>Currently have a gmail account with no emails in the inbox. I want to be able to display a popup with the current number of emails. If there are no emails, then no message is displayed.</p> <p>So I'm choosing to use Explicit Waits &amp; Xpath to do this. It's to my understanding that this allows me define a time pe...
0
2016-05-30T17:52:05Z
37,532,694
<p>You should use:</p> <pre><code>wait.until(EC.presence_of_element_located((By.XPATH, "//*[@id=':3s']/div/div[1]/span/a")) </code></pre> <p>In selenium-python doc, there is no method <code>element_to_be_present_in_element</code> to check if there is any element as expected in the page, however doc refs the method <c...
1
2016-05-30T19:42:21Z
[ "python", "email", "selenium", "xpath" ]
Why can't I append a string object to a dictionary
37,531,366
<p>I am new to python and was just creating a program that manages student records like a database but for some reason I am not able to append a string object into a dictionary data structure. Any reason why?</p> <pre><code>def main(): # Create an empty dictionary database = {'FIRST_NAME':'Default', 'LAST_NAME':'Def...
0
2016-05-30T17:58:02Z
37,531,476
<p>You cannot "append" to a dictionary, you can update or add by using its key:value.</p> <p>update:</p> <pre><code>dict_name.update({'item1': 1}) </code></pre> <p>add:</p> <pre><code>dict_name['item3'] = 3 </code></pre>
1
2016-05-30T18:06:18Z
[ "python", "dictionary" ]
MultiLabel Classification using Conditional Random Field
37,531,532
<p>Is it possible to use Conditional Random Field for MultiLabel Classification? I saw a python CRF implementation at <a href="https://pystruct.github.io/user_guide.html" rel="nofollow">https://pystruct.github.io/user_guide.html</a>, but couldn't figure a way to do multilabel classification.</p>
1
2016-05-30T18:11:31Z
39,191,869
<p>The basic CRF doesn't support multilabel classification. However, some extensions have been explored, such as the Collective Multi-label (CML) and the Collective Multi-label with Features (CMLF). From (1):</p> <blockquote> <p>A conditional random field (CRF) based model is presented in [21] where two multi-labe...
0
2016-08-28T13:39:28Z
[ "python", "machine-learning", "classification", "multilabel-classification", "crf" ]
Issue in extracting value from xml(apple rating xml) using BEAUTIFULSOUP python
37,531,542
<p>I am trying to extract the text for </p> <pre><code>&lt;im:rating&gt;5&lt;/im:rating&gt; &lt;im:version&gt;1.14&lt;/im:version&gt; </code></pre> <p>from xml of apple xml for app store review using BeautifulSoup.</p> <p>my code is </p> <pre><code>def getReview(): url = "https://itunes.apple.com/rss/customerr...
0
2016-05-30T18:12:05Z
37,533,614
<p>If you are just trying to get those tags, a simple pyparsing parser will get them without the BeautifulSoup hoops to jump through. By just parsing for the given tags (pyparsing's tag matching is pretty comprehensive), you can skip the overhead of parsing the entire HTML and just getting at the pieces that you want, ...
-1
2016-05-30T20:59:35Z
[ "python", "xml", "parsing", "beautifulsoup" ]
ec2 instace type: ami-e0efab88 has python installed but don't recognize it while installing libxml2-2.9.4
37,531,551
<p>I'm trying to install <a href="ftp://xmlsoft.org/libxml2/libxml2-2.9.4.tar.gz" rel="nofollow">libxml2-2.9.4</a> (XML SUPPORT) on an ec2 instance with debian-wheezy-amd64-hvm-2015-01-28-ebs (ami-e0efab88) </p> <p><code>./configure</code> ran successfully</p> <p>running <code>make</code> fails with an error: <code>f...
1
2016-05-30T18:12:54Z
37,531,637
<p>You also need to install all the required python development libraries, to be able to build it on your operating system.</p> <p>Ubuntu / Debian</p> <pre><code>apt-get install python-dev libxml2-dev libxslt1-dev </code></pre> <p>CentOS / RedHat</p> <pre><code>yum install python-devel libxml2-devel libxslt-devel <...
0
2016-05-30T18:18:39Z
[ "python", "amazon-web-services", "amazon-ec2", "libxml2" ]
Strange HTML code when scraping IEEEXPLORE
37,531,567
<p>I am scraping the IEEEXplore for some data PDF, tile and links.</p> <p>So recently when I scraping this site (with Python and twill module) I get similar this content:</p> <pre><code>��7���j��/�5�,X��]����O�s˟�����U|]�l ��c��qLE�[����:yg�u%��_�...
0
2016-05-30T18:13:50Z
37,531,894
<p>It would be interesting to look at the rest of the output, but my guess is that all of that jumbled up stuff that's hard to read is actually an image file or a video file or something. Image and video files look very very weird when we try to HTTP GET them and print them out as text. My guess is that the normal webs...
0
2016-05-30T18:37:39Z
[ "python", "web-scraping", "ieee" ]
Strange HTML code when scraping IEEEXPLORE
37,531,567
<p>I am scraping the IEEEXplore for some data PDF, tile and links.</p> <p>So recently when I scraping this site (with Python and twill module) I get similar this content:</p> <pre><code>��7���j��/�5�,X��]����O�s˟�����U|]�l ��c��qLE�[����:yg�u%��_�...
0
2016-05-30T18:13:50Z
37,532,296
<p>I found the answer i removed th:is part of its header:</p> <pre><code> t_com.add_extra_header('Accept-Encoding', 'gzip, deflate') </code></pre> <p>this Data ore Gziped data.!!!</p> <p>i de ziped data by this codes:</p> <pre><code> content1 = t_brw.result.page # print 'debug twill p...
0
2016-05-30T19:10:07Z
[ "python", "web-scraping", "ieee" ]
Mock urlilb+json in Python
37,531,640
<p>looking for a way to correctly mock this piece of code:</p> <pre><code>import json from urllib import urlopen a_url = "http://blabla" my_response= urlopen(a_url) a_dict = json.loads(my_response.read()) </code></pre> <p>It reads from an URL, then the response uses json.loads to store everything in a dict. Ideas?</...
0
2016-05-30T18:18:53Z
37,531,785
<p><code>urlopen</code> should return a mock object where <code>.read()</code> returns a string containing JSON, e.g. <code>'{"a": "b"}'</code>.</p> <p>Then throw it all away and use <code>requests</code>.</p>
1
2016-05-30T18:29:51Z
[ "python", "mocking" ]
Python and Arduino Serial Communication: send and receive
37,531,676
<p>What I want to do is actually query Arduino to get data. When I send a command from Python to Arduino, Arduino will send back some data depending on what the query keyword is. I am able to do this but with a very low speed, I wish to have a more efficient way to do this, for example, query at least 100 times per sec...
0
2016-05-30T18:21:28Z
37,548,852
<p>It looks like your python code does this:</p> <ol> <li>Send a command</li> <li>Sleep for some time (presumably to give the arduino time to reply)</li> <li>Read the reply</li> <li>If no reply, repeat from step 1</li> </ol> <p>You mentioned that it doesn't work if the sleep period is too short. I wonder if the follo...
0
2016-05-31T14:45:04Z
[ "python", "arduino", "pyserial" ]
i want to write contents of my variable into a file
37,531,806
<p>I have stored the output of my <code>curl</code> command into a string variable using Python. and now after this I want to transfer this to a file. Can you please help me in this?</p> <p>My string variable is as below</p> <pre><code>&gt;&gt;&gt; print result health status index pri rep docs.co...
-3
2016-05-30T18:31:53Z
38,155,636
<p>This will write the result to a file called 'write_file.txt' and the stings matching 'logstash-xxx-xxxx.xx.xx' line-by-line to a file called 'write_logs.txt':</p> <pre><code>result = """health status index pri rep docs.count docs.deleted store.size pri.store.size yellow open logstash-xxx-201...
0
2016-07-02T01:25:26Z
[ "python", "string", "text-files" ]
Tasks being repeated in Celery
37,531,811
<p>After a couple days, my celery service will repeat a task over and over indefinitely. This is somewhat difficult to reproduce, but happens regularly once a week or more frequently depending on the tasks volume being processed.</p> <p>I will appreciate any tips on how to get more data about this issue, since I don't...
1
2016-05-30T18:32:15Z
39,438,204
<p>Solved by using rabbitmq broker instead of redis.</p>
0
2016-09-11T16:24:34Z
[ "python", "celery", "celery-task" ]
How to create a progress bar using flask?
37,531,829
<p>Just want to insert a progress bar in my html page. It should load from a for in my app.py. That's what I did so far...</p> <p>app.py</p> <pre><code>from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/progress') def aja...
1
2016-05-30T18:33:10Z
37,532,011
<p>this is pretty simple: poll your api and update the progress bar width and valuenow until finished:</p> <pre><code>var interval = setInterval(update_progress, 1000); function update_progress() { $.get('/progress').done(function(n){ n = n / 5; // percent value if (n == 100) { clea...
0
2016-05-30T18:47:26Z
[ "python", "flask", "progress-bar" ]
`django.request` logger not logging 4xx and 5xx responses from views
37,532,042
<p>I am trying to log all 4xx and 5xx responses with the <code>django.request</code> logger but this is only working when an exception is raised or a URL is not matched in the urlconf.</p> <p>My <code>settings.py</code> is as follows:</p> <pre><code>import logging.config LOGGING_CONFIG = None LOGGING = { 'versi...
1
2016-05-30T18:50:12Z
37,536,179
<p>I ran into this issue myself some time ago. Here is what happens:</p> <ul> <li><p><code>500</code> errors are only logged if they are the result of an uncaught exception. If you set a <code>500</code> status manually then it will not be logged. Here's the <a href="https://github.com/django/django/blob/40b69607c751c...
2
2016-05-31T03:01:46Z
[ "python", "django", "logging" ]
`django.request` logger not logging 4xx and 5xx responses from views
37,532,042
<p>I am trying to log all 4xx and 5xx responses with the <code>django.request</code> logger but this is only working when an exception is raised or a URL is not matched in the urlconf.</p> <p>My <code>settings.py</code> is as follows:</p> <pre><code>import logging.config LOGGING_CONFIG = None LOGGING = { 'versi...
1
2016-05-30T18:50:12Z
37,536,379
<p>If you only need to see the errors and you are using apache2.4 server, you can find it at /var/log/apache2/error.log</p> <p>The access log can be found at /var/log/apache2/access.log</p>
-1
2016-05-31T03:30:37Z
[ "python", "django", "logging" ]
Is there a way to split a line more than once in a text file?
37,532,076
<p>I have this text file called log.txt.</p> <pre><code>1.a Receiver Type : REC-1 Satellite System : GPS Serial Number : A123 1.b Receiver Type : REC-2 Satellite System : GPS Serial Number : B456 1.c Receiver Type : REC-3 ...
1
2016-05-30T18:52:03Z
37,532,198
<p>It is the .strip() that messes things up and not the .split(":"), but you can do it like this:</p> <pre><code>with open('log.txt', 'r') as Log: for line in Log: header = line.split(':')[0] if 'Satellite System' in header: sat_sys = line.split(':')[1].strip() print sat_sys...
0
2016-05-30T19:01:40Z
[ "python", "python-2.7", "python-3.x" ]
Python Changing Array Values in While Loop
37,532,095
<p>I am working on a project where I have the following while loop:</p> <pre><code>i = 0 while i &lt;= length: u[:,i] = u[:,i] - u_val y[:,i] = y[:,i] - y_val i = i + 1 </code></pre> <p>The goal is to subtract u_val and y_val from their respective arrays along the entire length of each array. Both y and ...
0
2016-05-30T18:53:01Z
37,533,474
<p><code>data[1:1+ni,0]</code> is a <code>view</code> of data. So is <code>data[1:1+ni]</code> (which also can be expressed as <code>data[1:1+ni, :]</code>). If you change an element of one view (as in <code>u[:,i] = u[:,i] - u_val</code>), you change the corresponding element in <code>data</code>, and in any other v...
0
2016-05-30T20:46:55Z
[ "python", "arrays", "loops", "numpy" ]
Split data set into training and test but not randomly
37,532,098
<p>I have dataset with 1000 rows like this </p> <pre><code> Date, Cost, Quantity(in ton), Source, Unloading Station 01/10/2015, 7, 5.416, XYZ, ABC </code></pre> <p>i want to split the data on the base of date. For e.g. till date 20.12.2016 is a training...
0
2016-05-30T18:53:19Z
37,532,935
<p>assuming that your data set is pandas data frame and that <code>Date</code> column is of <code>datetime</code> dtype:</p> <pre><code>split_date = pd.datetime(2016,12,20) df_training = df.loc[df['Date'] &lt;= split_date] df_test = df.loc[df['Date'] &gt; split_date] </code></pre>
1
2016-05-30T20:01:26Z
[ "python", "dataset" ]
Finite State Machine: Explain what the following line of code does
37,532,099
<p>I'm currently trying to understand the <a href="http://www.python-course.eu/finite_state_machine.php" rel="nofollow">implementation</a> of finite state machine in Python.</p> <pre><code>while True: (newState, cargo) = handler(cargo) #(this line) if newState.upper() in self.endStates: pr...
0
2016-05-30T18:53:23Z
37,533,636
<p><code>handlers</code> is a mapping from state names to transition functions. <code>handler</code> is the transition function for the current state.</p> <p>Initially <code>handler</code> is set to the transition function for the start state. At each iteration of the loop, the current <code>handler</code> function ...
1
2016-05-30T21:01:45Z
[ "python", "dictionary", "finite-state-machine" ]
Python changing outside dictionary from inside function
37,532,111
<p>I am experiencing a behavior that from what I've hear is common in Python, but I'd like to know this is the default, and how to prevent this. Consider the following code:</p> <pre><code>dic1 = {'a':1, 'b':2} lis1 = [1, 2] def somefunc(dic): dic.update({'b':20}) return dic def otherfunc(lis): lis.appen...
2
2016-05-30T18:54:23Z
37,532,257
<p>on Python, lists are mutable, this means that lis2 is just another name for lis1, thus they are the same object</p> <p>here are 2 ways to make a copy of lis1 on lis2:</p> <pre><code>lis2 = lis1[:] lis2 = list(lis1) </code></pre> <p>I'd prefer using <code>list()</code> since it's more readable.</p>
1
2016-05-30T19:07:25Z
[ "python", "pointers", "dictionary", "copy" ]
Delete object on click
37,532,140
<p>I am trying to make a todo app, I have a form with a table where the user can add "todo" to this form.</p> <p>I would like to be able to delete the added "todo" from database by clicking on a button without having to redirect the user to another page, is there any way to do this with Django?</p> <p><a href="http:/...
-2
2016-05-30T18:56:32Z
37,534,159
<p>Yes. Using ajax, with a simple call to your delete view, you can hit the database and delete the entry. Just remove it client-side with javascript. </p> <p>Or you could consider using <a href="http://www.django-rest-framework.org/" rel="nofollow">django-rest-framework</a> with <a href="https://angularjs.org/" rel=...
1
2016-05-30T22:06:18Z
[ "python", "django" ]
Assigning length of a list in the parameters of a function
37,532,164
<p>So I would like to set the length of a list to a variable in my function, but it says my list is not defined:</p> <pre><code>def maxElement(list, start=0, end = len(serie)): return max(serie[start:end]) serie = [9, 3, 6, 1, 7, 5, 4, 8, 2] print maxElement(serie) </code></pre>
0
2016-05-30T18:59:06Z
37,532,221
<p>At the time of your function definition, <code>serie</code> is not yet defined. Also, default parameters are evaluated and bound at module loading time, not when the the function is called. So, you CANNOT refer to another argument either a la <code>maxElement(lst, start=0, end=len(lst))</code> or have any other dyna...
3
2016-05-30T19:04:27Z
[ "python", "function", "parameters", "arguments" ]
Assigning length of a list in the parameters of a function
37,532,164
<p>So I would like to set the length of a list to a variable in my function, but it says my list is not defined:</p> <pre><code>def maxElement(list, start=0, end = len(serie)): return max(serie[start:end]) serie = [9, 3, 6, 1, 7, 5, 4, 8, 2] print maxElement(serie) </code></pre>
0
2016-05-30T18:59:06Z
37,532,564
<p>There are several problems with your code. </p> <p>Firstly, you don't actually use the <code>list</code> argument of the function. Instead, you are using the global list <code>serie</code>. BTW, you shouldn't use <code>list</code> as a variable name as that shadows (overwrites) the built-in <code>list</code> type, ...
2
2016-05-30T19:32:03Z
[ "python", "function", "parameters", "arguments" ]
What is the advantage of using a lambda:None function?
37,532,208
<p>I saw the following <a href="https://github.com/sunqm/pyscf/blob/master/mcscf/mc1step_uhf.py#L531" rel="nofollow">code</a>:</p> <pre><code>eris = lambda:None eris.jkcpp = np.einsum('iipq-&gt;ipq', eriaa[:ncore[0],:ncore[0],:,:]) eris.jc_PP = np.einsum('iipq-&gt;pq', eriab[:ncore[0],:ncore[0],:,:]) </code></pre> <p...
15
2016-05-30T19:02:38Z
37,532,492
<p>This looks like a trick to create a simple object to hold values in one line. Most built-in objects don't allow you to set arbitrary attributes on them:</p> <pre><code>&gt;&gt;&gt; object().x = 0 Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; AttributeError: 'object' object has...
11
2016-05-30T19:27:35Z
[ "python", "lambda", "namespaces", "names" ]
What is the advantage of using a lambda:None function?
37,532,208
<p>I saw the following <a href="https://github.com/sunqm/pyscf/blob/master/mcscf/mc1step_uhf.py#L531" rel="nofollow">code</a>:</p> <pre><code>eris = lambda:None eris.jkcpp = np.einsum('iipq-&gt;ipq', eriaa[:ncore[0],:ncore[0],:,:]) eris.jc_PP = np.einsum('iipq-&gt;pq', eriab[:ncore[0],:ncore[0],:,:]) </code></pre> <p...
15
2016-05-30T19:02:38Z
37,546,793
<blockquote> <h1>What is the advantage of using a lambda:None function?</h1> </blockquote> <p>What's going on here</p> <pre><code>eris = lambda:None eris.jkcpp = ... </code></pre> <p>is that the writer is creating a namespace using a function object. </p> <p><strong>A namespace</strong> is a domain where legal Py...
6
2016-05-31T13:14:12Z
[ "python", "lambda", "namespaces", "names" ]
Does RxPy have a `flatten` operator?
37,532,250
<p>Does RxPy have a convenient <code>flatten</code> operator which is equivalent to <code>flat_map(identity)</code>? Or have <code>flat_map</code>'s <code>selector</code> default to <code>identity</code>?</p>
0
2016-05-30T19:06:49Z
37,532,253
<p>From <a href="https://github.com/ReactiveX/RxPY/issues/98" rel="nofollow">Dag Brattli</a></p> <blockquote> <p>You can use .merge_all(). </p> </blockquote>
1
2016-05-30T19:07:15Z
[ "python", "reactive-programming", "rx-py" ]
Django Passing objects from template to view
37,532,259
<p>I really like the django template language, but when it comes to passing more than a string from templates to views I have no clue. Therefore I want to figure out which modern tool to use.</p> <p>What would you suggest to learn next to tackle such tasks or is there a way in django which I haven't discovered yet?</p...
-1
2016-05-30T19:07:28Z
37,537,035
<p>Without seeing what the <code>foo</code> object actually looks like, I'm going to assume that the following is happening:</p> <ol> <li>You're only specifying <code>foo</code> within the template.</li> <li>Since that's all you're specifying, Django will attempt to print the object as a string, calling either the obj...
0
2016-05-31T04:48:13Z
[ "javascript", "python", "django", "object", "django-models" ]
Add results from a for loop in a dict, Python
37,532,260
<p>I have a txt file which contains a lot of information. In my script I open this file and remove unnecessary stuff by using in-built functions and regex, which is done in a for-loop.</p> <p>Consider the txt file looking like this:</p> <p>Monkey OFF OFF</p> <p>Elephant ON ON</p> <p>and so on...</p> <hr> <p>My sc...
0
2016-05-30T19:07:30Z
37,532,326
<p>Put the code where you add to the dictionary inside the loop, next to the <code>print</code>. <code>name</code> and <code>value</code> can only hold one value at a time, they can't magically remember everything they've ever been and know the correct way to be inserted into your dict.</p>
3
2016-05-30T19:12:45Z
[ "python" ]
Add results from a for loop in a dict, Python
37,532,260
<p>I have a txt file which contains a lot of information. In my script I open this file and remove unnecessary stuff by using in-built functions and regex, which is done in a for-loop.</p> <p>Consider the txt file looking like this:</p> <p>Monkey OFF OFF</p> <p>Elephant ON ON</p> <p>and so on...</p> <hr> <p>My sc...
0
2016-05-30T19:07:30Z
37,532,452
<p>In case the to the point guess and concise advice from @alex-hall is not explicit enough for the OP. Maybe something like this:</p> <pre><code>#! /usr/bin/env python from __future__ import print_function import re def open_func_file(args): functionality_file_context = '' func_file = '' for func_file i...
1
2016-05-30T19:23:55Z
[ "python" ]
PyQt5 how to set QLineEdit behaviour like '\n'
37,532,272
<p>The answer is probably really simple but I searched like 30 mins and couldn't find anything. I just want to set QLineEdit like what does <code>\n</code> do. To be more specific, when I start to type in QLineEdit, if it's a long sentence and bigger than the width of QLineEdit, it's going straight like forever. I want...
-1
2016-05-30T19:08:32Z
37,532,313
<p>The "Line" is right there in its name, so yes, it supports "only 1 row".</p> <blockquote> <p>The <a href="http://doc.qt.io/qt-5/qlineedit.html#details" rel="nofollow">QLineEdit</a> widget is a one-line text editor.</p> </blockquote> <p>What you want is <a href="http://doc.qt.io/qt-5/qplaintextedit.html" rel="nof...
0
2016-05-30T19:11:52Z
[ "python", "python-3.4", "pyqt5", "qlineedit" ]
Flask flash not working after redirect
37,532,286
<p>I'm having an issue in which the flash messages aren't showing the messages set before a redirect. I created a simple project to reproduce the problem. The redirect flash message doesn't show with or without the SERVER_NAME config file but the regular flash message always shows.</p> <pre><code>import sys import os....
0
2016-05-30T19:09:25Z
37,535,122
<p>The problem turns out to be related to the SERVER_NAME. It should not contain the subdomain name.</p> <p>Changing the config to the following makes it work with the Cloud9 domain name:</p> <pre><code>class TestConfig: DEBUG = True SERVER_NAME = 'project-username.c9users.io' </code></pre>
1
2016-05-31T00:25:48Z
[ "python", "flask", "cloud9-ide", "cloud9" ]
emacs Python files backspace not working
37,532,303
<p>Whenever I am in a buffer of an opened python file and press <code>RET</code>, it goes to the next line and indents by <code>16</code> (!) spaces. I don't know how it gets to that number internally, but whenever that happens, I cannot simply press <code>backspace</code> multiple times to undo the non-sense. Instead ...
0
2016-05-30T19:11:02Z
37,621,063
<p>Most modes (major or minor) will not redefine the <code>&lt;backspace&gt;</code> key, but they're all technically free to (See <a href="https://www.gnu.org/software/emacs/manual/html_node/elisp/Key-Binding-Conventions.html" rel="nofollow">https://www.gnu.org/software/emacs/manual/html_node/elisp/Key-Binding-Conventi...
0
2016-06-03T18:18:42Z
[ "python", "emacs", "key-bindings", "backspace" ]
python request | construct POST request body
37,532,409
<p>I am trying to construct below POST request using python requests.</p> <p><strong>Request header</strong></p> <pre><code>Host: www.example.com User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:46.0) Gecko/20100101 Firefox/46.0 Accept: */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br X-CSRF...
2
2016-05-30T19:19:16Z
37,533,008
<p>Your error is as per the comments to this answer from using an ancient version of requestes <code>1.1.0</code> from 2013, so <code>pip install -U requests</code> will fix that. </p> <p>To do the post you don't need to hardcode anything, you create a session and get whatever you need i.e the csrf token and requests ...
2
2016-05-30T20:07:47Z
[ "python", "python-requests" ]
How to visualize a SVM using Matplotlib in python?
37,532,410
<p>Is there any way to visualize svm model in Opencv using matplotlib in python like this one <a href="http://scikit-learn.org/stable/auto_examples/svm/plot_iris.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/svm/plot_iris.html</a> .</p>
0
2016-05-30T19:19:17Z
37,532,462
<p>In order to visualize decision boundary of SVM your data has to be <strong>two dimensional</strong>. If this is a case, you can just use scikit-learns code, and just substitute call to <code>.predict</code> with analogous predict from your own library (like opencv). </p>
1
2016-05-30T19:24:47Z
[ "python", "opencv", "matplotlib", "machine-learning", "computer-vision" ]
How can I keep a number as root out of x
37,532,430
<p>So my code looks like this , with comments :</p> <pre><code>import math #I want to do this : If the figure is a triangle it's side , noted with l = r(Stands for radius) square root 3 #another thing(Which I don't know how to spell in english) , noted with a = r/2 , it's area based on the side(noted with Al) # = (...
0
2016-05-30T19:21:44Z
37,533,115
<p>Its absurd to take <code>float()</code> of the string <code>" Square root of 3"</code>. I guess you are trying to use the square root sign, then i think you have to use the sympy library, and your code follows</p> <pre><code>from sympy import * figure = input("What is the figure?") figure = figure.lower() r = int(i...
0
2016-05-30T20:17:21Z
[ "python", "math", "geometry" ]
How can I keep a number as root out of x
37,532,430
<p>So my code looks like this , with comments :</p> <pre><code>import math #I want to do this : If the figure is a triangle it's side , noted with l = r(Stands for radius) square root 3 #another thing(Which I don't know how to spell in english) , noted with a = r/2 , it's area based on the side(noted with Al) # = (...
0
2016-05-30T19:21:44Z
37,533,124
<p>I may be confused about what you're getting at here -- are you saying you just want to do basically </p> <pre><code>root3 = math.sqrt(3) </code></pre> <p>or something else?</p>
0
2016-05-30T20:17:55Z
[ "python", "math", "geometry" ]
Django ) AttributeError : 'datetime.date' object when trying to get an object of model
37,532,439
<p>I need to update a model object and save so that this result can be reflected.</p> <p>But when I try to get an object of this model <strong>that I checked already this object exists</strong>,</p> <pre><code>modelOne = lkmModel.objects.get(id=1) </code></pre> <p>I got an error :</p> <blockquote> <p>AttributeErr...
1
2016-05-30T19:22:20Z
37,532,993
<p>First, your model cannot have a field named <code>id</code> without it being declared as a <code>primary_key</code>. Secondly, while creating django models use <code>django.utils.timezone.now</code> instead of <code>datetime</code>.</p> <p>The root cause of the problem you have is that you're giving <code>datetime....
1
2016-05-30T20:06:25Z
[ "python", "django", "datetime", "django-models" ]
Django ) AttributeError : 'datetime.date' object when trying to get an object of model
37,532,439
<p>I need to update a model object and save so that this result can be reflected.</p> <p>But when I try to get an object of this model <strong>that I checked already this object exists</strong>,</p> <pre><code>modelOne = lkmModel.objects.get(id=1) </code></pre> <p>I got an error :</p> <blockquote> <p>AttributeErr...
1
2016-05-30T19:22:20Z
37,536,564
<p>The first thing is do not use id in models. Django adds that automatically as the primary key.</p> <p>The other thing is that you are trying to fill date object in a Datetime field. Datetime is different from Date.</p> <pre><code>matchingDate = models.DateTimeField(default=datetime.date.today()) </code></pre> <p>...
0
2016-05-31T03:55:27Z
[ "python", "django", "datetime", "django-models" ]
Is it ok to create and place a tkinter widget at the same time?
37,532,447
<p>I am new in Python and in tkinter so the question may seems naive: is it ok to create and place widgets at the same time if I don't need to change them? It works but is it a good practice? And if not why?</p> <p>An example of what I mean:</p> <pre><code>import tkinter as tk window=tk.Tk() tk.Label(window,text='Lo...
1
2016-05-30T19:23:10Z
37,532,572
<p>There is nothing wrong with that approach and I have already seen it quite a few times. You don't have to keep a reference to every widget in your GUI.</p>
1
2016-05-30T19:32:46Z
[ "python", "tkinter" ]
Is it ok to create and place a tkinter widget at the same time?
37,532,447
<p>I am new in Python and in tkinter so the question may seems naive: is it ok to create and place widgets at the same time if I don't need to change them? It works but is it a good practice? And if not why?</p> <p>An example of what I mean:</p> <pre><code>import tkinter as tk window=tk.Tk() tk.Label(window,text='Lo...
1
2016-05-30T19:23:10Z
37,532,615
<p>To expand upon @Skynet's <a href="http://stackoverflow.com/a/37532572/355230">answer</a>....</p> <p>Whenever you do <code>Widget(*args, **kwargs).pack()</code> the <code>pack()</code> method returns <code>None</code> as would other geometry managers, so if you tried to assign this to a variable the variable would b...
2
2016-05-30T19:36:49Z
[ "python", "tkinter" ]
Is it ok to create and place a tkinter widget at the same time?
37,532,447
<p>I am new in Python and in tkinter so the question may seems naive: is it ok to create and place widgets at the same time if I don't need to change them? It works but is it a good practice? And if not why?</p> <p>An example of what I mean:</p> <pre><code>import tkinter as tk window=tk.Tk() tk.Label(window,text='Lo...
1
2016-05-30T19:23:10Z
37,532,690
<p>For example you're creating a <code>Button</code> widget.</p> <pre><code>btn = Button(blabla, text="Button1") </code></pre> <p>This returns a button object and if you need later to configure it or get information about it you can do it by through the <code>btn</code> variable. But if you use something like <code>b...
2
2016-05-30T19:42:01Z
[ "python", "tkinter" ]
Numpy slicing result different than for loop
37,532,456
<p>I have some question regarding numpy/slicing in Python.</p> <p>Can anyone explain, why the following for loop and the slicing approach don't result in the same B?</p> <pre><code>for n in range(1,N-1): B[n,i] = -(2*x[n,i] - x[n-1,i] - x[n+1,i]) B[1:N-2,i] = -(2*x[1:N-2,i] - x[0:N-3,i] - x[2:N-1,i]) </code></pr...
2
2016-05-30T19:24:22Z
37,532,571
<p>Because the ranges are non-inclusive on the right side, I assume you'd have to change your numpy code to</p> <pre class="lang-py prettyprint-override"><code>B[1:N-1,i] = -(2*x[1:N-1,i] - x[0:N-2,i] - x[2:N,i]) </code></pre> <p>to make it match the loop version.</p>
2
2016-05-30T19:32:36Z
[ "python", "numpy", "slice" ]
TensorFlow: Network output has not expected shape
37,532,464
<p>I am implementing a network using TensorFlow. The network take as input a binary feature vector, and it should predict a float value as output. I am expecting a (1,1) tensor object as output for my function <code>multilayer_perceptron()</code>, instead, when running <code>pred</code>, it returns a vector of the sam...
0
2016-05-30T19:24:51Z
37,535,975
<p>Your <code>pred</code> should be of shape <code>[n_input, n_class]</code> because you define <code>weights['out']</code> and <code>biases['out']</code> in that way. The only way you get a (1,1) tensor from <code>pred</code> is your <code>n_class = 1</code>...</p>
0
2016-05-31T02:35:57Z
[ "python", "tensorflow" ]
Correct way to use Django's ORM and Django Rest Framework to serialize a queryset of nested relationships?
37,532,510
<p>What is the correct way to build a queryset that I can pass into a Django Rest Framework Serializer so as to get a data/json result of related nested objects. </p> <p>For example, I have two models:</p> <pre><code>class Topping(models.Model): name = models.CharField(max_length=50) class Pizza(models.Model): ...
0
2016-05-30T19:29:17Z
37,532,723
<p>First of all you need to use <a href="http://www.django-rest-framework.org/api-guide/serializers/#modelserializer" rel="nofollow"><code>ModelSerializer</code></a> instead of <code>Serializer</code>, and provide <a href="http://www.django-rest-framework.org/api-guide/serializers/#specifying-which-fields-to-include" r...
2
2016-05-30T19:45:17Z
[ "python", "json", "django", "django-rest-framework", "django-orm" ]
Correct way to use Django's ORM and Django Rest Framework to serialize a queryset of nested relationships?
37,532,510
<p>What is the correct way to build a queryset that I can pass into a Django Rest Framework Serializer so as to get a data/json result of related nested objects. </p> <p>For example, I have two models:</p> <pre><code>class Topping(models.Model): name = models.CharField(max_length=50) class Pizza(models.Model): ...
0
2016-05-30T19:29:17Z
37,533,882
<p>For completeness, and others finding this page, below are two different ways to achieve the similar result.</p> <p>Thanks to Sardorbek for originally answering the question.</p> <p>The view:</p> <pre><code>class PizzaList(APIView): """ View for the Serializer not using ModelSerializer """ def get(...
0
2016-05-30T21:33:44Z
[ "python", "json", "django", "django-rest-framework", "django-orm" ]
Python/Pandas: create summary table
37,532,525
<p>In a python pandas dataframe "df", I have the following columns: </p> <pre><code>user_id | song_id | song_duration | song_title | artist | listen_count </code></pre> <p>Many users might have listened to the same song - therefore the song is not unique in this table. I would like to create a second dataframe with j...
2
2016-05-30T19:30:05Z
37,532,566
<p>IIUC try omit <code>.df</code>:</p> <pre><code>df.groupby('song_id')['song_title','artist'].first() </code></pre>
1
2016-05-30T19:32:17Z
[ "python", "pandas", "dataframe", "pivot" ]
Python/Pandas: create summary table
37,532,525
<p>In a python pandas dataframe "df", I have the following columns: </p> <pre><code>user_id | song_id | song_duration | song_title | artist | listen_count </code></pre> <p>Many users might have listened to the same song - therefore the song is not unique in this table. I would like to create a second dataframe with j...
2
2016-05-30T19:30:05Z
37,532,881
<p>You could just drop the duplicates of selected columns</p> <pre><code>song_df = df[['song_id','song_title','artist']].drop_duplicates() </code></pre>
0
2016-05-30T19:57:20Z
[ "python", "pandas", "dataframe", "pivot" ]
Using socket code and changing it to python 3.5.0 and getting TypeError: a bytes-like object is required, not 'str' error
37,532,625
<p>Got code from <a href="http://www.binarytides.com/python-socket-programming-tutorial/" rel="nofollow">http://www.binarytides.com/python-socket-programming-tutorial/</a> and changed it to work in python 3.5. It looks like this:</p> <pre><code>#Socket client example in python import socket #for sockets import sys ...
0
2016-05-30T19:37:24Z
37,532,728
<p>The <code>socket().sendall</code> method expects a "bytes-like object", which means a <code>bytes</code> object (or a bunch of other types like <code>memoryview</code>). You are passing a <code>str</code> object, which represents a unicode string, to that method.</p> <p>To fix this error, you need to encode your me...
0
2016-05-30T19:45:55Z
[ "python", "sockets" ]
dumpsys grep options "-i"
37,532,647
<p>I tried to get the brightness level of android device using dumpsys. "<strong>dumpsys power | grep -i mScreenBrightness=</strong>" which returns the required output .</p> <p>What does "-i" resembles here where as "<strong>dumpsys power | grep mScreenBrightness=</strong>" .. also returns same value.</p>
-1
2016-05-30T19:38:34Z
37,532,711
<p><code>grep -i</code> stands for case insensitive</p>
1
2016-05-30T19:44:00Z
[ "android", "python", "windows", "grep" ]
Trying to understand why a nested for loop is called only the first time
37,532,747
<p>I have the following code:</p> <pre><code>def get_preds(train,test,x_ranges,y_ranges): global total_scores global num_scores for x_min, x_max in x_ranges: for y_min, y_max in y_ranges: ... </code></pre> <p>When I run this method on python 2.7, it behaves as expected. The nest for loo...
3
2016-05-30T19:46:58Z
37,533,554
<p>In Python 3, <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip()</code></a> returns an iterator. You can only iterate through the elements of an iterator once. To replicate the Python 2 behavior, use <code>list(zip(...))</code> in place of <code>zip(...)</code>.</p>
2
2016-05-30T20:53:53Z
[ "python", "python-3.x", "for-loop", "nested-loops" ]
How to implement a RabbitMQ consumer using Pyspark Streaming module?
37,532,813
<p>I have an Apache Spark cluster and a RabbitMQ broker and I want to consume messages and compute some metrics using the <code>pyspark.streaming</code> module.</p> <p>The problem is I only found <a href="https://github.com/Stratio/Spark-RabbitMQ" rel="nofollow">this package</a>, but is implemented in <em>Java</em> an...
3
2016-05-30T19:52:09Z
39,373,945
<p>This solution uses <a href="https://pika.readthedocs.io/en/0.10.0/examples/asynchronous_consumer_example.html" rel="nofollow">pika asynchronous consumer example</a> and <code>socketTextStream</code> method from <em>Spark Streaming</em></p> <ol> <li>Download the example and save it as a <code>.py</code> file</li> <l...
0
2016-09-07T15:28:02Z
[ "python", "rabbitmq", "pyspark", "spark-streaming", "pika" ]
cannot print and listen at the same time
37,532,879
<p>I am writing a basic talking tom like code which listens to the person and repeats its audio along side i want it to display the text which the speaker has spoken. the problem I'm facing is i am not able to use the print and listen command simultaneously. I need to speak the phrase twice i.e, once for printing it o...
0
2016-05-30T19:56:53Z
37,532,932
<pre><code>speak("Say something!") text = listen() speak("I heard you say " + text) </code></pre>
2
2016-05-30T20:01:14Z
[ "python", "printing", "speech-recognition", "listen", "pyttsx" ]
cannot print and listen at the same time
37,532,879
<p>I am writing a basic talking tom like code which listens to the person and repeats its audio along side i want it to display the text which the speaker has spoken. the problem I'm facing is i am not able to use the print and listen command simultaneously. I need to speak the phrase twice i.e, once for printing it o...
0
2016-05-30T19:56:53Z
37,552,180
<p>Write:</p> <pre><code>print(audio) </code></pre> <p>Under:</p> <pre><code>return recognizer.recognize_google(audio) </code></pre>
0
2016-05-31T17:32:58Z
[ "python", "printing", "speech-recognition", "listen", "pyttsx" ]
Replace division by zero numpy
37,532,919
<p>I'm doing a matrix by matrix pointwise division however there are some zeros in the divisor matrix. This results in a warning and in some NaNs. I want these to map to 0, which I can do like this:</p> <pre><code>edge_map = (xy/(x_norm*y_norm)) edge_map[np.isnan(edge_map)] = 0 </code></pre> <p>However there are two ...
6
2016-05-30T20:00:30Z
37,533,202
<p>This is probably the fastest solution, but the <code>where</code> function does trigger the error as it precalculates the solutions:</p> <pre><code>import numpy as np n = 4 xy = np.random.randint(4, size=(n,n)).astype(float) x_norm = np.random.randint(4, size=(n,n)).astype(float) y_norm = np.random.randint(4, siz...
4
2016-05-30T20:24:24Z
[ "python", "performance", "numpy", "matrix" ]
Hiding fields in Flask-Admin depending on logged in user?
37,532,988
<p>I have <code>Users</code> and <code>Roles</code> in my Flask app thanks to Flask-Security.</p> <p>For some roles I would like to hide certain fields in the forms created by Flask-Admin.</p> <p>I know about customizing ModelViews with eg. <code>form_create_rules = ('title', 'file')</code> but while instantiating a ...
0
2016-05-30T20:05:43Z
37,554,001
<p>One way of achieving this is to create multiple view classes and register these view classes against their appropriate roles. See this <a href="http://stackoverflow.com/a/33653754/2800058">answer</a> on how to register roles to views. Using view inheritance you can keep common functionality in the "base" class.</p> ...
2
2016-05-31T19:21:53Z
[ "python", "flask", "flask-admin", "flask-security" ]
Getting ASK price on Bloomberg using Python API
37,533,131
<p>I am trying to get the ASK price from Bloomberg using Excel's DataNitro. </p> <p>I am calling this function from excel:</p> <p>main()</p> <pre><code>def main(): options = parseCmdLine() # Fill SessionOptions sessionOptions = blpapi.SessionOptions() sessionOptions.setServerHost(options.host) s...
0
2016-05-30T20:18:35Z
37,533,193
<p>How long does the price take to return? DataNitro UDF's time out after 3 seconds to prevent long-running functions from freezing Excel. You can modify the timeout duration in DataNitro's Settings.</p>
0
2016-05-30T20:23:44Z
[ "python", "excel-2010", "bloomberg", "datanitro", "blpapi" ]
Plot Window Hangs or is Empty in Python
37,533,159
<p>I am having trouble with plots in a Jupyter Notebook in Python 3.5 on Mac OSX. The following code will hang when executed:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt #%matplotlib inline myfig = plt.plot(range(5)) plt.show() </code></pre> <p>If I restart the kernel and un-comment '%matplotlib...
0
2016-05-30T20:20:45Z
37,533,629
<p>There is a <a href="https://github.com/matplotlib/matplotlib/issues/3470" rel="nofollow">post on GitHub</a> mentioning that using Qt4Agg as backend worked... If it is not available (and if you can), you might want to try using Hombrew to install Python (instead of Anaconda), Qt and/or Gtk with which you'll be able t...
0
2016-05-30T21:01:02Z
[ "python", "osx", "matplotlib", "plot" ]
Selecting rows based on criteria from another dataframe
37,533,170
<p>I have two <code>DataFrames</code> with different numbers of rows and columns, but which have at least one column containing some common information. Specifically, <code>StationCode</code> is always a <code>LocationCode</code>:</p> <pre><code>dataframe1.head() DistanceToPrev LineCode SeqNum StationCode ...
2
2016-05-30T20:21:55Z
37,533,410
<p>Simple solution would be:</p> <pre><code>df2 = df2.merge(df1[['StationCode', 'RailTime']], left_on='LocationCode', right_on='StationCode') df2 = df2[df2.Min&lt;df2.RailTime] </code></pre>
0
2016-05-30T20:41:19Z
[ "python", "pandas" ]
Can't execute Python Pandas set_value
37,533,200
<p>Got a problem with Pandas in Python 3.5</p> <p>I read local csv using Pandas, the csv contains pure data, no header involved. Then I assigned column name using </p> <pre><code>df= pd.read_csv(filePath, header=None) df.columns=['XXX', 'XXX'] #for short, totally 11 cols </code></pre> <p>The csv has 11 columns, one ...
0
2016-05-30T20:24:16Z
37,540,842
<p>well, now when you made it lot clearer, it's easier to answer your question...</p> <p>assuming your DF looks like this:</p> <pre><code>In [164]: df Out[164]: a b c d e city 0 6 55 3 48 11 Kiev 1 5 29 42 95 69 Munich 2 53 79 60 80 89 Berlin 3 6 70 87...
0
2016-05-31T08:40:46Z
[ "python", "csv", "pandas" ]
Can't execute Python Pandas set_value
37,533,200
<p>Got a problem with Pandas in Python 3.5</p> <p>I read local csv using Pandas, the csv contains pure data, no header involved. Then I assigned column name using </p> <pre><code>df= pd.read_csv(filePath, header=None) df.columns=['XXX', 'XXX'] #for short, totally 11 cols </code></pre> <p>The csv has 11 columns, one ...
0
2016-05-30T20:24:16Z
37,743,230
<p>The cause of the original error:</p> <p>Pandas DataFrame set_value(index, col, value) method will return the posted obscure AttributeError: 'BlockManager' object has no attribute 'T' when the dataframe being modified has duplicate column names.</p> <p>The error can be reproduced using the code above by @Windtalker...
1
2016-06-10T08:14:44Z
[ "python", "csv", "pandas" ]
Joining two lists in Python:
37,533,333
<p>I have two arrays (A &amp; B). I would like to calculate the % of users of array A , who are included in array B. I have tried but I can´t find the solution.</p>
1
2016-05-30T20:33:43Z
37,533,356
<pre><code>100.0 * sum((x in B) for x in A) / len(A) </code></pre> <p>If <code>B</code> is large, use a set for efficiency:</p> <pre><code>100.0 * len(set(B).intersection(A)) / len(A) </code></pre>
9
2016-05-30T20:37:04Z
[ "python", "arrays" ]
Joining two lists in Python:
37,533,333
<p>I have two arrays (A &amp; B). I would like to calculate the % of users of array A , who are included in array B. I have tried but I can´t find the solution.</p>
1
2016-05-30T20:33:43Z
37,533,487
<p>The most pyhtonic way is like Rogalski above commented. </p> <p>Python in my opinion is very strong at sets: <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">https://docs.python.org/2/library/sets.html</a></p> <p>you can make an intersection in two ways </p> <p>set(A) &amp; set(B) or set(A).i...
5
2016-05-30T20:48:00Z
[ "python", "arrays" ]
Joining two lists in Python:
37,533,333
<p>I have two arrays (A &amp; B). I would like to calculate the % of users of array A , who are included in array B. I have tried but I can´t find the solution.</p>
1
2016-05-30T20:33:43Z
37,534,379
<p>You only need to create one set and sum the times an element in a is in the set of the members in b:</p> <pre><code>st = set(b) perc = sum((ele in st for ele in a),0.0) / len(a) * 100 </code></pre> <p>If you actually have numpy arrays:</p> <pre><code>import numpy as np a, b = [1, 3], [1, 4,3] perc = np.in1d(a,...
0
2016-05-30T22:31:27Z
[ "python", "arrays" ]
Arabic stemmer doesn't work for sentences
37,533,577
<p>I have python 2.7 and i installed <a href="http://www.arabicstemmer.com/" rel="nofollow">this</a> , I have this code : </p> <pre><code>from snowballstemmer import stemmer ar_stemmer = stemmer("arabic") stem = ar_stemmer.stemWord(u"مكتبة لمعالجةالكلمات العربية وتجذيعها ") print s...
3
2016-05-30T20:55:45Z
37,533,723
<p>Split the sentence on words like this:</p> <pre><code>from snowballstemmer import stemmer ar_stemmer = stemmer("arabic") sentence = u"مكتبة لمعالجة الكلمات العربية وتجذيعها" for word in sentence.split(" "): stem = ar_stemmer.stemWord(word) print stem </code></pre>
4
2016-05-30T21:12:49Z
[ "python", "arabic", "stemming" ]
pip: "/Volumes/HD: bad interpreter: No such file or directory
37,533,613
<p>After I activated my Virtualenv i received this message:</p> <blockquote> <p>Francos-MBP:BV francoe$source bin/activate</p> <p>(BV) Francos-MBP:BV francoe$ pip freeze</p> <p>-bash: /Volumes/HD 2/Projects/PythonProjects/BV/bin/pip: "/Volumes/HD: bad interpreter: No such file or directory</p> <p>(BV)...
0
2016-05-30T20:59:32Z
37,534,734
<p>The space in the name of your disk ("HD 2") is tripping things up. The path to the Python interpreter (which is going to be <code>/Volumes/HD 2/Projects/PythonProjects/BV/bin/python</code>) is getting split on the space, and the system is trying to execute <code>/Volumes/HD</code>.</p> <p>You'd think that in 2016 ...
0
2016-05-30T23:23:42Z
[ "python", "pip", "python-3.5" ]
Why is statistics.mean() so slow?
37,533,666
<p>I compared the performance of the <code>mean</code> function of the <code>statistics</code> module with the simple <code>sum(l)/len(l)</code> method and found the <code>mean</code> function to be very slow for some reason. I used <code>timeit</code> with the two code snippets below to compare them, does anyone know ...
42
2016-05-30T21:05:05Z
37,533,712
<p>According to that post: <a href="http://stackoverflow.com/questions/7716331/calculating-arithmetic-mean-average-in-python">Calculating arithmetic mean (average) in Python</a></p> <p>It should be "due to a particularly precise implementation of the sum operator in statistics". </p> <p>The mean function is coded wi...
2
2016-05-30T21:11:35Z
[ "python", "performance", "mean" ]