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
listlengths
1
5
How to remove a dict objects(letter) that remain in another str?
38,418,765
<p>Suppose I have this dictionary:</p> <pre><code>x = {'a':2, 'b':5, 'g':7, 'a':3, 'h':8}` </code></pre> <p>And this input string:</p> <pre><code>y = 'agb' </code></pre> <p>I want to delete the keys of <code>x</code> that appear in <code>y</code>, such as, if my input is as above, output should be:</p> <pre><code>...
-3
2016-07-17T07:07:37Z
38,418,977
<p>You can also implement like </p> <pre><code>def remove_(x,y) for i in y: try: del x[i] except: pass return x </code></pre> <p>Inputs <code>x = {'a': 1, 'b': 2, 'c':3}</code> and <code>y = 'ac'</code>.</p> <p><strong>Output</strong></p> <pre><code>{'b': 2} </code></pr...
0
2016-07-17T07:40:18Z
[ "python", "python-2.7", "dictionary" ]
Confused with XML Parsing in Python
38,418,824
<p>Im Working on a little application for Android Development in Python and i need to Parse the AndroidManifest.xml to know the different activites and fetch their "roles" in the application , especially the Startup (LAUNCHER) activities Here is an example of a dummy AndroidManifest.xml :</p> <pre><code>&lt;?xml versi...
0
2016-07-17T07:18:10Z
38,418,958
<p>This can be done in a few lines using <code>lxml</code> and the following XPath :</p> <pre><code>//activity[ .//category/@android:name = 'android.intent.category.LAUNCHER' ]/@android:name </code></pre> <p>The above XPath expression reads : find <code>&lt;activity&gt;</code> element containing <code>&lt;categor...
3
2016-07-17T07:37:42Z
[ "python", "xml", "android-manifest" ]
Confused with XML Parsing in Python
38,418,824
<p>Im Working on a little application for Android Development in Python and i need to Parse the AndroidManifest.xml to know the different activites and fetch their "roles" in the application , especially the Startup (LAUNCHER) activities Here is an example of a dummy AndroidManifest.xml :</p> <pre><code>&lt;?xml versi...
0
2016-07-17T07:18:10Z
38,418,961
<pre><code>from __future__ import print import xml.sax class AndroidManifestHandler(xml.sax.ContentHandler): def startElement(self, name, attrs): if name == 'category': attr = attrs.get('android:name') print('Category: {0}'.format(attr)) elif name == 'activity': ...
1
2016-07-17T07:38:17Z
[ "python", "xml", "android-manifest" ]
Python Turtle : How to open a drawing
38,418,922
<p>I have a project that draws turtle on a <code>Canvas</code> widget. I already know how to save the drawing but how do you open them. This is an example of what I'm trying to say :</p> <pre><code>from tkinter import * root = Tk() ... #Just creating widgets def openDrawing: ...#What goes in here ? fileMenu.add_com...
0
2016-07-17T07:31:59Z
38,423,780
<p>PostScript file formats containing image data are <a href="http://infohost.nmt.edu/tcc/help/pubs/pil/pil.pdf" rel="nofollow">supported</a> by the <a href="http://www.pythonware.com/products/pil/" rel="nofollow"><code>PIL</code></a> library. So you can open your turtle <code>.ps</code> file like this:</p> <pre><c...
0
2016-07-17T17:06:28Z
[ "python", "graphics", "tkinter", "drawing", "turtle-graphics" ]
Trouble accessing a value from a dictionary
38,418,984
<p>I have the following dictionary</p> <pre><code>Dict = {'Manu':{u'ID0020879.07': [{'ID': u'ID0020879.07', 'log': u'log-123-56', 'owner': [Manu], 'item': u'WRAITH', 'main_id': 5013L, 'status': u'noticed', 'serial': u'89980'}]}} </code></pre> <p>How can I access the serial from this dictionary? I tried <code>Dict['M...
-2
2016-07-17T07:41:07Z
38,419,006
<p>Your dictionary is very nested one.Try like this.</p> <pre><code>In [1]: Dict['Manu']['ID0020879.07'][0]['serial'] Out[1]: u'89980' </code></pre>
2
2016-07-17T07:44:54Z
[ "python", "dictionary" ]
Trouble accessing a value from a dictionary
38,418,984
<p>I have the following dictionary</p> <pre><code>Dict = {'Manu':{u'ID0020879.07': [{'ID': u'ID0020879.07', 'log': u'log-123-56', 'owner': [Manu], 'item': u'WRAITH', 'main_id': 5013L, 'status': u'noticed', 'serial': u'89980'}]}} </code></pre> <p>How can I access the serial from this dictionary? I tried <code>Dict['M...
-2
2016-07-17T07:41:07Z
38,419,046
<p>Here is the restructured dictionary. </p> <pre><code>{ 'Manu': { u'ID0020879.07': [{ 'ID': u'ID0020879.07', 'log': u'log-123-56', 'owner': [Manu], 'item': u'WRAITH', 'main_id': 5013L, 'status': u'noticed', 'serial': u'89...
1
2016-07-17T07:50:30Z
[ "python", "dictionary" ]
Pass Python's stdout to a C function to which write
38,418,993
<p>I want to unit testing a C function which prints to the stdout but after I searched I reached to <code>os.dup</code>, <code>os.pip</code> and other stuff which isn't the coolest way to capture the stdout of a C shared library function. so I figured to pass Python's stdout to the C function after it writes to it then...
0
2016-07-17T07:42:27Z
38,636,280
<p>Hope it'd help others.</p> <pre><code>import os import sys from tempfile import TemporaryFile from io import TextIOWrapper, SEEK_SET from contextlib import contextmanager from ctypes import c_void_p @contextmanager def capture(stream, libc): osfd = sys.stdout.fileno() fd = os.dup(osfd) try: tf...
0
2016-07-28T12:23:57Z
[ "python", "c", "unit-testing", "stdout", "ctypes" ]
How to calculate sum of path's weight in N allowable moves defined in graph but the destination node is not fixed using Python
38,419,011
<pre><code>gr = {'0': {'4': 4, '6': 6}, '4': {'3': 7, '9': 13, '0':4}, '6': {'1': 7, '7':13,'0':6}, '3': {'4': 7, '8': 11}, '9': {'4': 13, '2': 11}, '1': {'6': 7, '8': 9}, '7': {'2': 9, '6': 13}, '8': {'1': 9, '3': 11}, '2': {'9': 11, '7': 9}} </code></pre> <p>This is th...
3
2016-07-17T07:45:29Z
38,420,454
<p>Since you need only the sum, the solution is much easier.</p> <p>Start with a dictionary with only <code>{start_node: 0}</code>; this is your starting position. </p> <p>For a new position after a move:</p> <ul> <li><p>make a <em>new</em> empty <code>defaultdict(int)</code>. </p></li> <li><p>then for for each <cod...
1
2016-07-17T10:54:21Z
[ "python", "algorithm", "python-3.x", "graph" ]
How to calculate sum of path's weight in N allowable moves defined in graph but the destination node is not fixed using Python
38,419,011
<pre><code>gr = {'0': {'4': 4, '6': 6}, '4': {'3': 7, '9': 13, '0':4}, '6': {'1': 7, '7':13,'0':6}, '3': {'4': 7, '8': 11}, '9': {'4': 13, '2': 11}, '1': {'6': 7, '8': 9}, '7': {'2': 9, '6': 13}, '8': {'1': 9, '3': 11}, '2': {'9': 11, '7': 9}} </code></pre> <p>This is th...
3
2016-07-17T07:45:29Z
38,422,175
<p>Here's a diagram of the graph that I created using some Python code and Graphviz. </p> <p><img src="http://i.stack.imgur.com/x7mkN.png" alt="graph diagram"></p> <p>In the code you posted you have a <code>visited</code> list. The purpose of that list is to prevent a node from being visited more than once. However, ...
3
2016-07-17T14:15:31Z
[ "python", "algorithm", "python-3.x", "graph" ]
Code complexity when iterating inside python dictionaries
38,419,019
<p>Data from file read, are stored in a dictionary with file titles as keys, and as value, there is another dictionary, which has words as keys and their occurrence as value. An example of the structure is below:</p> <pre><code>data = { 'file1.txt': { 'word1': 45, 'word2': 23, ... } ...
0
2016-07-17T07:46:23Z
38,419,257
<p>Big Oh notation represents the worst case complexity of the code. If I represent files as F1, F2, F3....Fn and words inside each file as W1 as number of words in 1st file and so on, the time would be like - </p> <blockquote> <p>F1*W1 + F2*W2....Fn*Wn</p> </blockquote> <p>So if the number of files are n and the ...
1
2016-07-17T08:22:25Z
[ "python", "dictionary", "iteration", "big-o", "complexity-theory" ]
How to apply Butterworth filter to my code?
38,419,117
<p>I want to filter out noises from a voicerecording and normalize it. Currently I am struggeling with a Butterworth bandpass filter.</p> <p>How do I apply this in my code? (I'm new to Python)</p> <pre><code>from numpy import nditer from pydub.audio_segment import AudioSegment from scikits.audiolab import wavread fr...
0
2016-07-17T08:01:28Z
38,420,414
<p>You may first want to check that you have numpy, pydub, scikits and scipy installed. You could then create a function with this code and put your audio file as the input.</p>
0
2016-07-17T10:49:17Z
[ "python", "audio", "wav", "wave", "scikits" ]
Catch custom Exception that is raised by a function inside the try-block
38,419,194
<p>I've been trying to catch an exception that should be caused by clicking a hotkey, unfortunately adding a hotkey requires to add a function that should be called when said hotkey is pressed.</p> <p>Now I know that exceptions will only be caught if they're raised inside the <code>try-catch</code> block, but this doe...
1
2016-07-17T08:13:47Z
38,419,259
<p>I am no expert, but it seems to me that the problem is your <code>def resetRun(event)</code> bit. The <code>try...except</code> instruction set cannot dig into a function definition. What happens if you create resetRun(event) outside of <code>try...except</code>? Does it work then?</p>
-1
2016-07-17T08:22:31Z
[ "python" ]
Catch custom Exception that is raised by a function inside the try-block
38,419,194
<p>I've been trying to catch an exception that should be caused by clicking a hotkey, unfortunately adding a hotkey requires to add a function that should be called when said hotkey is pressed.</p> <p>Now I know that exceptions will only be caught if they're raised inside the <code>try-catch</code> block, but this doe...
1
2016-07-17T08:13:47Z
38,419,290
<p>That's because the exception inside your function doesn't raised at <strong>run-time</strong>. The fact is that a <a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions" rel="nofollow"><code>try-except</code> expression</a> will catch the exceptions in run-time, for example:</p> <pre><code>&gt;...
0
2016-07-17T08:27:35Z
[ "python" ]
Catch custom Exception that is raised by a function inside the try-block
38,419,194
<p>I've been trying to catch an exception that should be caused by clicking a hotkey, unfortunately adding a hotkey requires to add a function that should be called when said hotkey is pressed.</p> <p>Now I know that exceptions will only be caught if they're raised inside the <code>try-catch</code> block, but this doe...
1
2016-07-17T08:13:47Z
38,419,305
<p>The problem is that you're out of the main thread's context. This is a multi-threaded environment which is hinted by you binding keys to callbacks.</p> <p>There is probably an eventloop with a thread (or threads) waiting to handle your key callbacks once a user presses a key.</p> <p>What you need to do is put the ...
1
2016-07-17T08:29:00Z
[ "python" ]
Python scrape webpage after POST to get url not present in the page source
38,419,213
<p>Basically I want to download mp3 from youtube thanks to this online conversion service.</p> <pre><code>http://www.youtube-mp3.org/it </code></pre> <p>You fill in the form with the youtube video url to convert and you get a page with the download link.</p> <p>The html form is something like this:</p> <p><div clas...
0
2016-07-17T08:16:14Z
38,419,260
<p>There is also Selenium package for python.</p> <p>Some html content is created on loading by something like javascript. Selenium simulates this process and returns the final content.</p>
-1
2016-07-17T08:22:37Z
[ "python", "html", "post", "beautifulsoup", "python-requests" ]
Append variables on XML string which is stored in a variable
38,419,236
<p>I am using Python and <code>requests</code> library to send <code>POST</code> requests with an XML file. My XML file looks like this:</p> <pre><code>property_name = """&lt;wfs:Property&gt; &lt;wfs:Name&gt;Adm2_NAME&lt;/wfs:Name&gt; &lt;wfs:Value&gt;fff&lt;/wfs:Value&gt; &lt;/wfs:Property&gt;""" xml = """&lt;wf...
1
2016-07-17T08:19:12Z
38,423,366
<p>Consider <a href="https://www.w3.org/Style/XSL/" rel="nofollow">XSLT</a>, the special purpose language to transform XML files, to append parts of other XMLs into main XML file. Python's third-party module, <a href="http://lxml.de/" rel="nofollow">lxml</a>, can process XSLT 1.0 scripts. XSLT maintains the <a href="h...
1
2016-07-17T16:22:56Z
[ "python", "xml" ]
Dot product of two sparse matrices affecting zero values only
38,419,271
<p>I'm trying to compute a simple dot product but leave nonzero values from the original matrix unchanged. A toy example:</p> <pre><code>import numpy as np A = np.array([[2, 1, 1, 2], [0, 2, 1, 0], [1, 0, 1, 1], [2, 2, 1, 0]]) B = np.array([[ 0.54331039, 0.41018682, 0.15821...
6
2016-07-17T08:24:13Z
38,419,723
<p>Cracked it! Well, there's a lot of scipy stuffs specific to sparse matrices that I learnt along the way. Here's the implementation that I could muster -</p> <pre><code># Find the indices in output array that are to be updated R,C = ((A!=0).dot(B!=0)).nonzero() mask = np.asarray(A[R,C]==0).ravel() R,C = R[mask],C[...
3
2016-07-17T09:20:55Z
[ "python", "numpy", "matrix", "scipy", "sparse-matrix" ]
Dot product of two sparse matrices affecting zero values only
38,419,271
<p>I'm trying to compute a simple dot product but leave nonzero values from the original matrix unchanged. A toy example:</p> <pre><code>import numpy as np A = np.array([[2, 1, 1, 2], [0, 2, 1, 0], [1, 0, 1, 1], [2, 2, 1, 0]]) B = np.array([[ 0.54331039, 0.41018682, 0.15821...
6
2016-07-17T08:24:13Z
38,423,798
<p>A possibly cleaner and faster version of your <code>naive</code> code:</p> <pre><code>In [57]: r,c=A.nonzero() # this uses A.tocoo() In [58]: C=A*B In [59]: Cl=C.tolil() In [60]: Cl[r,c]=A.tolil()[r,c] In [61]: Cl.tocsr() </code></pre> <p><code>C[r,c]=A[r,c]</code> gives an efficiency warning, but I think that...
3
2016-07-17T17:09:12Z
[ "python", "numpy", "matrix", "scipy", "sparse-matrix" ]
Dot product of two sparse matrices affecting zero values only
38,419,271
<p>I'm trying to compute a simple dot product but leave nonzero values from the original matrix unchanged. A toy example:</p> <pre><code>import numpy as np A = np.array([[2, 1, 1, 2], [0, 2, 1, 0], [1, 0, 1, 1], [2, 2, 1, 0]]) B = np.array([[ 0.54331039, 0.41018682, 0.15821...
6
2016-07-17T08:24:13Z
38,425,251
<p>Python isn't my main language, but I thought this was an interesting problem and I wanted to give this a stab :)</p> <p>Preliminaries:</p> <pre><code>import numpy import scipy.sparse # example matrices and sparse versions A = numpy.array([[1, 2, 0, 1], [1, 0, 1, 2], [0, 1, 2 ,1], [1, 2, 1, 0]]) B = numpy.array([[1...
0
2016-07-17T19:41:54Z
[ "python", "numpy", "matrix", "scipy", "sparse-matrix" ]
Subtracting multiple columns and appending results in pandas DataFrame
38,419,286
<p>I have a table of sensor data, for which some columns are measurements and some columns are sensor bias. For example, something like this:</p> <pre><code>df=pd.DataFrame({'x':[1.0,2.0,3.0],'y':[4.0,5.0,6.0], 'dx':[0.25,0.25,0.25],'dy':[0.5,0.5,0.5]}) </code></pre> <blockquote> <pre><code> dx ...
0
2016-07-17T08:27:07Z
38,419,468
<p>DataFrames generally align operations such as arithmetic on column and row indices. Since <code>df[['x','y']]</code> and <code>df[['dx','dy']]</code> have different column names, the <code>dx</code> column is not subtracted from the <code>x</code> column, and similiarly for the <code>y</code> columns.</p> <p>In co...
3
2016-07-17T08:49:41Z
[ "python", "pandas" ]
What index should I use to convert a numpy array into a pandas dataframe?
38,419,314
<p>I am trying to convert a simple numpy array into a pandas dataframe. </p> <p><code>x</code> is my array, <code>nam</code> is the list of the columns names.</p> <pre><code>x = np.array([2,3,1,0]) nam = ['col1', 'col2', 'col3', 'col4'] </code></pre> <p>I use <code>pd.DataFrame</code> to convert <code>x</code> <...
3
2016-07-17T08:30:29Z
38,419,348
<p>you should reshape your input array:</p> <pre><code>In [6]: pd.DataFrame(x.reshape(1,4), columns=nam) Out[6]: col1 col2 col3 col4 0 2 3 1 0 </code></pre> <p>or bit more flexible:</p> <pre><code>In [11]: pd.DataFrame(x.reshape(len(x) // len(nam), len(nam)), columns=nam) Out[11]: col1 col2...
4
2016-07-17T08:33:54Z
[ "python", "arrays", "numpy", "pandas", "dataframe" ]
What index should I use to convert a numpy array into a pandas dataframe?
38,419,314
<p>I am trying to convert a simple numpy array into a pandas dataframe. </p> <p><code>x</code> is my array, <code>nam</code> is the list of the columns names.</p> <pre><code>x = np.array([2,3,1,0]) nam = ['col1', 'col2', 'col3', 'col4'] </code></pre> <p>I use <code>pd.DataFrame</code> to convert <code>x</code> <...
3
2016-07-17T08:30:29Z
38,419,655
<p>Another simplier solution with <code>[]</code>:</p> <pre><code>x = np.array([2,3,1,0]) nam = ['col1', 'col2', 'col3', 'col4'] print (pd.DataFrame([x], columns=nam)) col1 col2 col3 col4 0 2 3 1 0 </code></pre>
7
2016-07-17T09:13:49Z
[ "python", "arrays", "numpy", "pandas", "dataframe" ]
Extract grocery list out of free text
38,419,395
<p>I am looking for a python library / algorithm / paper to extract a list of groceries out of free text.</p> <p>For example:</p> <blockquote> <p>"One salad and two beers"</p> </blockquote> <p>Should be converted to:</p> <pre><code>{'salad':1, 'beer': 2} </code></pre>
6
2016-07-17T08:39:56Z
38,419,504
<pre><code>In [1]: from word2number import w2n In [2]: print w2n.word_to_num("One") 1 In [3]: print w2n.word_to_num("Two") 2 In [4]: print w2n.word_to_num("Thirty five") 35 </code></pre> <p>You can convert to number with using this package and rest of things you can implement as your needs.</p> <p>Installation of thi...
3
2016-07-17T08:55:05Z
[ "python", "nlp", "nltk" ]
Extract grocery list out of free text
38,419,395
<p>I am looking for a python library / algorithm / paper to extract a list of groceries out of free text.</p> <p>For example:</p> <blockquote> <p>"One salad and two beers"</p> </blockquote> <p>Should be converted to:</p> <pre><code>{'salad':1, 'beer': 2} </code></pre>
6
2016-07-17T08:39:56Z
38,422,173
<p>I suggest using <a href="https://wordnet.princeton.edu/" rel="nofollow">WordNet</a>. You can call it from java (JWNL library), etc. Here is the suggestion: for each single word, check it's hypernym. For edibles at the top level of the hypernymy hierarchy you will find " food, nutrient". Which is probably what you wa...
2
2016-07-17T14:15:13Z
[ "python", "nlp", "nltk" ]
Web-scraping advice/suggestions
38,419,528
<p>This is my first attempt at scraping. There is a website with a search function that I would like to use. </p> <p>When I do a search, the search details aren't shown in the website url. When I inspect the element and look at the Network tab, the request url stays the same (<strong><code>method:post</code></strong>)...
0
2016-07-17T08:57:25Z
38,419,620
<p>scraping is bad practice, but in some cases it is the only way to get something.<br> If you are scraping some website consider be gentle and don't make 1m requests in a day.</p> <p>Basically you will need to use php curl fucntion and pass post fields</p> <pre><code>&lt;?php $ch = curl_init(); curl_setopt($ch, CUR...
1
2016-07-17T09:10:19Z
[ "php", "python", "web-scraping" ]
Web-scraping advice/suggestions
38,419,528
<p>This is my first attempt at scraping. There is a website with a search function that I would like to use. </p> <p>When I do a search, the search details aren't shown in the website url. When I inspect the element and look at the Network tab, the request url stays the same (<strong><code>method:post</code></strong>)...
0
2016-07-17T08:57:25Z
38,419,736
<h1>Ethics</h1> <p>Using a bot to get at the content of sites can be beneficial to you and the site you're scraping. You can use the data to refer to content of the site, like search engines do. Sometimes you might want to provide a service to user that the original website doesn't offer. </p> <p>However, sometimes s...
1
2016-07-17T09:22:31Z
[ "php", "python", "web-scraping" ]
Web-scraping advice/suggestions
38,419,528
<p>This is my first attempt at scraping. There is a website with a search function that I would like to use. </p> <p>When I do a search, the search details aren't shown in the website url. When I inspect the element and look at the Network tab, the request url stays the same (<strong><code>method:post</code></strong>)...
0
2016-07-17T08:57:25Z
38,421,909
<p>You can use simple html dom <a href="http://simplehtmldom.sourceforge.net/" rel="nofollow">http://simplehtmldom.sourceforge.net/</a></p> <pre><code>&lt;?php include_once("simple_html_dom.php"); $request = array( 'http' =&gt; array( 'method' =&gt; 'POST', 'content' =&gt; http_...
1
2016-07-17T13:46:17Z
[ "php", "python", "web-scraping" ]
Automation scripts using Python API for OpenStack Swift
38,419,554
<p>I am running OpenStack Swift cluster on my machines as a private cloud network, and it is working well (GET, PUT, POST, DELETE) using cURL as well CLI.</p> <p>Want to write automation script for those actions, but I am not getting where/how to start.</p> <p>Any suggestion for a start. Thank you!</p>
0
2016-07-17T09:01:16Z
38,419,639
<p>You should be able to use the python unittest framework. Or you can use a more declarative testing tool like <a href="https://github.com/svanoort/pyresttest" rel="nofollow">https://github.com/svanoort/pyresttest</a>.</p>
0
2016-07-17T09:12:01Z
[ "python", "openstack", "openstack-swift" ]
Automation scripts using Python API for OpenStack Swift
38,419,554
<p>I am running OpenStack Swift cluster on my machines as a private cloud network, and it is working well (GET, PUT, POST, DELETE) using cURL as well CLI.</p> <p>Want to write automation script for those actions, but I am not getting where/how to start.</p> <p>Any suggestion for a start. Thank you!</p>
0
2016-07-17T09:01:16Z
38,487,847
<p>I find that the easiest way to interact with OpenStack Swift is the <a href="http://docs.openstack.org/developer/python-swiftclient/" rel="nofollow">python swiftclient</a>. Check it out.</p>
0
2016-07-20T18:10:04Z
[ "python", "openstack", "openstack-swift" ]
"socket.error: [Errno 11] Resource temporarily unavailable" appears randomly
38,419,606
<p>I wanted to make a more complex server in Python, reciving lists of commands and returning lists of values, so I can send more unsing a socket. Sometimes it works, and sometimes it crashes, and as I am new to socket programming, I have no explnation why this is the case?</p> <p>Here is the Server:</p> <pre><code>i...
0
2016-07-17T09:08:02Z
38,526,115
<p>Ok, I solved it, the Problem was in the server, I needed to handle the error, by adding a try and except:</p> <pre><code>import socket import errno import pickle def Main(): host = 'localhost' port = 12345 all_text = ['text1', 'text2', 'text3'] music_text = ['Konzert1', 'Konzert2', 'Konzert3'] ...
0
2016-07-22T12:10:55Z
[ "python", "sockets" ]
Automating installation of tripwire via python in Linux
38,419,629
<p>I am trying to automate installation of tripwire via apt-get through Python's subprocess module in Ubuntu Linux. The problem I have is that during the installation process, Tripwire is prompting me for Postfix mail configuration, setting site.key and local.key through different set of configuration pages (see pictur...
1
2016-07-17T09:11:02Z
38,419,752
<p>Launch the install with auto-confirm and quiet mode enabled and set <a href="http://serverfault.com/questions/227190/how-do-i-ask-apt-get-to-skip-any-interactive-post-install-configuration-steps">this flag</a>:</p> <p><code>export DEBIAN_FRONTEND=noninteractive</code></p> <p><code>apt-get install -y -q tripwire</c...
1
2016-07-17T09:24:23Z
[ "python", "linux", "apt-get", "apt" ]
Proper type annotation of Python functions with yield
38,419,654
<p>After reading Eli Bendersky's article <a href="http://eli.thegreenplace.net/2009/08/29/co-routines-as-an-alternative-to-state-machines/">on implementing state machines via Python coroutines</a> I wanted to...</p> <ul> <li>see his example run under Python3</li> <li>and also add the appropriate type annotations for t...
8
2016-07-17T09:13:46Z
38,423,388
<p>I figured out the answer on my own. </p> <p>I searched, but found no documentation for the 3 type parameters of <code>Generator</code> in the <a href="https://docs.python.org/3/library/typing.html">official typing documentation for Python 3.5.2</a> - beyond a truly cryptic mention of...</p> <pre><code>class typing...
7
2016-07-17T16:25:17Z
[ "python", "generator", "coroutine", "static-typing", "mypy" ]
PyGObject: Gtk.Fixed Z-order
38,419,662
<p>I'm using Gtk.Fixed and a viewport putting images that, sometimes, overlaps. How can I set the z-index like in html?</p>
0
2016-07-17T09:14:28Z
38,427,465
<p><code>Gtk.Fixed</code> doesn't support setting the z-order. It's not meant for overlapping widgets, so the z-order is arbitrary and probably depends on what order the widgets were added in.</p> <p>It's not clear from your question what your intention is; if you are purposely overlapping widgets, use <code>Gtk.Overl...
1
2016-07-18T01:28:18Z
[ "python", "gtk3", "pygobject" ]
PyGObject: Gtk.Fixed Z-order
38,419,662
<p>I'm using Gtk.Fixed and a viewport putting images that, sometimes, overlaps. How can I set the z-index like in html?</p>
0
2016-07-17T09:14:28Z
38,430,240
<p>Like ptomato said, I had to use the <code>Gtk.Overlay</code>. I used an overlay with 3 <code>Gtk.Layout</code>, like layers and it works fine.</p>
0
2016-07-18T06:52:32Z
[ "python", "gtk3", "pygobject" ]
TypeError: function missing 4 required positional arguments
38,419,853
<p>I've hit a problem calling a function inside a class. The code fragment is:</p> <pre><code> class CharacterGenerator(GridLayout): def printcharacter(self,my_sb,my_cr,my_scm,my_scb): printable_stats = print_stats(my_sb) printable_rolls = print_rolls(my_cr) printable_sc...
0
2016-07-17T09:37:28Z
38,419,897
<p>Use <strong><code>self</code></strong> to call function, in code <code>CharacterGenerator.printcharacter(self, ...</code>- you aren't passing self as first argument, so proper <code>printcharacter</code> call suppose to be:</p> <pre><code>self.printcharacter(statblock, characteristic_rolls, skill_category_modifiers...
-1
2016-07-17T09:41:45Z
[ "python", "kivy" ]
TypeError: function missing 4 required positional arguments
38,419,853
<p>I've hit a problem calling a function inside a class. The code fragment is:</p> <pre><code> class CharacterGenerator(GridLayout): def printcharacter(self,my_sb,my_cr,my_scm,my_scb): printable_stats = print_stats(my_sb) printable_rolls = print_rolls(my_cr) printable_sc...
0
2016-07-17T09:37:28Z
38,419,923
<p>Your error seems to be in your charactergenerator.kv on line 36.</p> <p>There you call the function, "on_press: root.printcharacter()" without parameters. </p> <p>So call the function with parameters.</p> <p>And change this line </p> <p><code>def printcharacter(self,my_sb,my_cr,my_scm,my_scb):</code></p> <p>to ...
0
2016-07-17T09:44:59Z
[ "python", "kivy" ]
Training Dataset of N-dimension in Logistic Regression using scikit-model
38,419,898
<p>I have training dataset of 200 images with dimension 28 x 28.I stored it in train_dataset with shape 200 x (28 *28).Labels are one dimension of shape 200. i.e. <strong>Training: (200, 28, 28) (200,)</strong><br><br> I need to fit this training data in scikit-model of logistic regression.i.e. <strong>fit(train_datase...
0
2016-07-17T09:41:54Z
38,419,957
<p>In case if dealing with images its always a nice idea to apply <code>PCA</code> or Principal Component Analysis to reduce the dimension of your data set. </p> <p><code>.fit()</code> accepts a 2D array so <strong>you have</strong> to ravel it down so that the function accepts it but you can apply PCA to get like 60 ...
0
2016-07-17T09:48:41Z
[ "python", "scikit-learn", "logistic-regression" ]
Using webix with flask
38,419,927
<p>I am trying to understand the webix framework and use it with my flask application. All the documentation deals with either static data in the html file or php examples.</p> <p>A simple html file to populate a datatable looks like this (according to the documentation</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&g...
0
2016-07-17T09:45:46Z
38,420,536
<p>first you need to try it without using Flask</p> <p><code>index.html</code></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head lang="en"&gt; &lt;meta charset="UTF-8"&gt; &lt;link rel="stylesheet" href="http://cdn.webix.com/edge/webix.css" type="text/css" charset="utf-8"&gt; &lt;script src="http...
1
2016-07-17T11:05:00Z
[ "python", "flask", "webix" ]
Pandas select closest date in past
38,420,024
<p>Being a beginner with <code>pandas</code>, I wonder how I can select the <em>closest</em> date in the past? E.g. I have a <code>dataframe</code> as follows:</p> <pre><code> Terminart Info Datum Ergebnis 0 Hauptversammlung NaN 22.06.16 N...
2
2016-07-17T09:58:29Z
38,420,134
<p>You can convert <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> column <code>Datum</code> and then first filter lower as no difference (timedelta=0) and then find index of max value by <a href="http://pandas.pydata.org/pandas-docs/st...
2
2016-07-17T10:13:38Z
[ "python", "pandas", "dataframe" ]
Pandas select closest date in past
38,420,024
<p>Being a beginner with <code>pandas</code>, I wonder how I can select the <em>closest</em> date in the past? E.g. I have a <code>dataframe</code> as follows:</p> <pre><code> Terminart Info Datum Ergebnis 0 Hauptversammlung NaN 22.06.16 N...
2
2016-07-17T09:58:29Z
38,420,462
<p>First you convert your column 'Datum' to a date field with <code>to_datetime()</code> then you can just sort your dataframe by date with <code>sort_values()</code> and then print out the first row:</p> <pre><code>df['Datum'] = pd.to_datetime(df['Datum'], format='%d.%m.%y') df.sort_values('Datum') print(df.iloc[0]) ...
1
2016-07-17T10:54:51Z
[ "python", "pandas", "dataframe" ]
How to plot a cylinder with non-constant radius
38,420,073
<p>I have written code to generate a cylinder with a constant fixed radius:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from math import sin, cos, pi fig = plt.figure() ax = fig.add_subplot(111, projection='3d') theta = np.linspace(-2*pi,2*pi, 600) Z...
3
2016-07-17T10:05:29Z
38,420,142
<p>Changed <code>R = np.linspace(0,1,700)</code></p> <pre><code>import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from math import sin, cos, pi fig = plt.figure() ax = fig.add_subplot(111, projection='3d') theta = np.linspace(-2*pi,2*pi, 600) Z = np.linspace(0,1,700) Z,...
3
2016-07-17T10:14:38Z
[ "python", "matplotlib" ]
'module' object has no attribute error
38,420,102
<p>I'm new to django. I'm trying to build an app. But the problem is that there is function defined in views.py still when i try to start server it says 'module' object has no attribute.</p> <p>stock/urls.py</p> <pre><code>from django.conf.urls import url from stock import views urlpatterns = [ url(r'^stocks/$',...
-1
2016-07-17T10:09:31Z
38,420,162
<p>As written, <code>stock_list</code> is a method inside the <code>JSONResponse</code> class (and <code>request</code> is expected to be of type <code>JSONResponse</code>, conventionally called <code>self</code>). Obviously it's not what you meant. It should be a simple module-level function. Simply dedent once.</p> ...
0
2016-07-17T10:16:27Z
[ "python", "django", "django-rest-framework" ]
Data Cleanup with Regex
38,420,113
<p>I have a very large number of very large files.</p> <p>Each file contains lines Like this:</p> <pre><code>uuid1 (tab) data1 (vtab) data2 ... dataN uuid2 (tab) data1' (vtab) data2' (vtab) data3' (vtab) ... dataN' .... </code></pre> <p>where N will be different for every line. The result needs to look like:</p> ...
0
2016-07-17T10:10:48Z
38,420,710
<p>This is an implementation in Python (tested in 3.5). I haven't tried this on a large data set, I'll leave that for you to try out.</p> <pre><code>import uuid in_filename = 'test.txt' out_filename = 'parsed.txt' with open(in_filename) as f_in: with open(out_filename, 'w') as f_out: for line in f_in: ...
1
2016-07-17T11:28:41Z
[ "python", "regex", "awk", "sed", "data-cleaning" ]
Data Cleanup with Regex
38,420,113
<p>I have a very large number of very large files.</p> <p>Each file contains lines Like this:</p> <pre><code>uuid1 (tab) data1 (vtab) data2 ... dataN uuid2 (tab) data1' (vtab) data2' (vtab) data3' (vtab) ... dataN' .... </code></pre> <p>where N will be different for every line. The result needs to look like:</p> ...
0
2016-07-17T10:10:48Z
38,420,794
<p>You can use an awk script:</p> <p><strong>script.awk:</strong></p> <pre><code>BEGIN { FS="[\t\v]" } { for(i=2 ; i &lt;= NF; i++ ) printf("%s\t%s\n",$1,$i) } </code></pre> <p>like this: <code>awk -f script.awk yourfile</code></p> <p>(I have not tried this with a large dataset and I am really interested how ...
2
2016-07-17T11:39:41Z
[ "python", "regex", "awk", "sed", "data-cleaning" ]
Data Cleanup with Regex
38,420,113
<p>I have a very large number of very large files.</p> <p>Each file contains lines Like this:</p> <pre><code>uuid1 (tab) data1 (vtab) data2 ... dataN uuid2 (tab) data1' (vtab) data2' (vtab) data3' (vtab) ... dataN' .... </code></pre> <p>where N will be different for every line. The result needs to look like:</p> ...
0
2016-07-17T10:10:48Z
38,423,151
<p>Here's an awk script that will also check the uuid. </p> <p>It ignores lines without a valid uuid. </p> <pre><code>BEGIN { FS="\v"; OFS="\t" } { split($1,a,/\s+/); if (match(a[1], /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/, m)) { print a[1],a[2]; for (i=2;i&lt;=NF;i++) print a[1],$i; } } </code...
1
2016-07-17T15:57:45Z
[ "python", "regex", "awk", "sed", "data-cleaning" ]
Make python process name more explicit
38,420,116
<p>When I run the taskmanager, the process name for all Python scripts are the same : <code>python.exe</code>. It makes it difficult to know which is which. </p> <p><strong>How to change the process name displayed by Windows task manager?</strong></p> <p><em>Note: <a href="http://stackoverflow.com/questions/2255444/c...
1
2016-07-17T10:10:57Z
38,420,755
<p>Create a new file named <code>python-by-name.bat</code> in the python directory with the following contents:</p> <pre class="lang-bat prettyprint-override"><code>set PYTHON_HOME=%~dp0 set PYTHON_NAME=%1.exe copy "%PYTHON_HOME%\python.exe" "%PYTHON_HOME%\%PYTHON_NAME%" set args=%* set args=%args:* =% "%PYTHON_HOME%\...
1
2016-07-17T11:34:22Z
[ "python", "windows" ]
In a Django Model, how can I set values for Django validators based on another field?
38,420,172
<p>I'm trying to track pay in a Djando Model, but this could be annual, daily or hourly, so values for <code>RangeMinValueValidator</code> and <code>RangeMaxValueValidator</code> should depend on <code>pay_type</code>, but I'm not sure how to do this. What I have so far:</p> <pre><code>PAY_TYPE = Choices( ('annual...
0
2016-07-17T10:18:00Z
38,420,329
<p>You can't do that with a field validator. Instead, define the <a href="https://docs.djangoproject.com/en/1.9/ref/models/instances/#django.db.models.Model.clean" rel="nofollow"><code>clean</code></a> method on the model to check the field values and raise ValidationError if required.</p>
1
2016-07-17T10:38:32Z
[ "python", "django", "django-models", "django-validation" ]
Verifying external data using model determined using cross validation
38,420,323
<p>I am learning data mining in Python. I am trying out cross validation.</p> <pre><code>import numpy as np from sklearn.cross_validation import KFold X = np.array([0.1, 0.2, 0.3, 0.4]) Y = np.array([False,True,True,False]) kf=KFold(4,n_folds=2) for train_index, test_index in kf: X_train, X_test = X[train_index], X...
-1
2016-07-17T10:37:17Z
38,420,381
<p>The <code>KFold</code> function has nothing to do with model determination. </p> <p>It just splits the data and labels to folds. </p> <p>If you add to the loop:</p> <pre><code> print(X_train, X_test) print(Y_train, Y_test) </code></pre> <p>You can see the folds at each iteration:</p> <pre><code># Iterati...
1
2016-07-17T10:44:00Z
[ "python", "cross-validation" ]
Python turtle : Create a redo function
38,420,358
<p>I know how to undo a drawing step in python turtle with <code>turtle.undo()</code>. But how can I make a Redo function ?</p> <pre><code>from tkinter import * ...#Just some other things def undoStep(): turtle.undo() def redoStep(): #What to put here root.mainloop() </code></pre>
0
2016-07-17T10:41:53Z
38,421,233
<p>To make a <code>redo</code> function, you need to keep track of the each action, in a list <code>actions</code> for example. You will also need a variable <code>i</code> that tells you where you are in that list and each time you call <code>undoStep</code>, decrease <code>i</code> by one. Then <code>redoStep</code> ...
0
2016-07-17T12:33:17Z
[ "python", "tkinter", "turtle-graphics", "undo-redo" ]
How do I read a video from Minoru 3d webcam in OpenCV Python?
38,420,407
<p>I am working on opencv python installed on Windows 10 (64 bit) I am using Minoru 3D webcam.I wrote a code on reading a video from 2 lens camera.I am here with the following error:</p> <pre><code>Traceback (most recent call last): File "C:/Python27/pythoncode/reading a video from two lens", line 6, in &lt;module&g...
-3
2016-07-17T10:47:48Z
38,420,562
<p>Your code and error messages were incredibly hard to read; please put four spaces before every line of code, or select all of the code and press Ctrl+K, turning</p> <p>Traceback (most recent call last): File "C:/Python27/pythoncode/reading a video from two lens", line 6, in if(cap &amp; cap1): TypeError: unsupporte...
0
2016-07-17T11:07:54Z
[ "java", "python", "c", "opencv", "video" ]
Retrieving data from xml.
38,420,471
<p>I have an xml file through which I have to retrieve xml document. Below is the xml document i have.</p> <pre><code>-&lt;orcid-message&gt; -&lt;orcid-profile type="user"&gt; -&lt;orcid-activities&gt; -&lt;orcid-works&gt; -&lt;orcid-work put-code="23938140" visibility="public"&gt; ...
-1
2016-07-17T10:56:49Z
38,421,531
<blockquote> <p><em>"<code>TypeError: list indices must be integers, not str</code> : I get this error"</em></p> </blockquote> <p>The error message suggests that the problem was due to the XML containing multiple <code>contributor</code> elements, hence your code up to <code>['contributor']</code> part will return a...
0
2016-07-17T13:04:27Z
[ "python", "xml", "python-3.x", "xmltodict" ]
In Django, how can I prevent my signals import in AppConfig.ready() from running more than once?
38,420,496
<p>To keep signals organised:</p> <p><code>__init__.py</code></p> <pre><code>default_app_config = 'posts.apps.PostsConfig' </code></pre> <p><code>apps.py</code></p> <pre><code>from django.apps import AppConfig class PostsConfig(AppConfig): name = 'posts' def ready(self): import posts.signals </co...
1
2016-07-17T11:00:35Z
38,980,450
<pre><code>from django.apps import AppConfig class PostsConfig(AppConfig): name = 'posts' ready_has_run = False def ready(self): if self.ready_has_run: return import posts.signals self.ready_has_run = True </code></pre>
0
2016-08-16T16:52:01Z
[ "python", "django", "signals", "django-signals" ]
Python re.findall float return unable to sum returned values
38,420,525
<p>I'm using re.findall to return the float from a specific line in a file:</p> <pre><code>mealReturnValue = re.findall("\d+\.\d+",lines[2]) </code></pre> <p>Example file line it pulls from: "The total bill was 400.00 "</p> <p>This will return a list of numbers as follows:</p> <pre><code>[['400.00'], ['210.0'], ['4...
0
2016-07-17T11:03:52Z
38,420,551
<p>Try this.</p> <pre><code>In [1]: sum([float(i[0]) for i in a]) Out[1]: 1010.0 </code></pre> <p>Considered <code>a</code> as your result. You are trying to perform <code>sum</code> operation on list of list. And it's in string format. You need to convert to <code>float</code> and make it as a single list. Then you ...
0
2016-07-17T11:06:27Z
[ "python", "floating-point", "sum", "string-conversion" ]
Python re.findall float return unable to sum returned values
38,420,525
<p>I'm using re.findall to return the float from a specific line in a file:</p> <pre><code>mealReturnValue = re.findall("\d+\.\d+",lines[2]) </code></pre> <p>Example file line it pulls from: "The total bill was 400.00 "</p> <p>This will return a list of numbers as follows:</p> <pre><code>[['400.00'], ['210.0'], ['4...
0
2016-07-17T11:03:52Z
38,420,555
<p>You are trying to sum a list of lists of strings. </p> <p>When summing, you should sum the values as floats:</p> <pre><code>sum(float(num[0]) for num in mealReturnValue) &gt;&gt; 1010.0 </code></pre>
0
2016-07-17T11:06:36Z
[ "python", "floating-point", "sum", "string-conversion" ]
Convert a string with the name of a variable to a dictionary
38,420,538
<p>I have a string which is little complex in that, it has some objects embedded as values. I need to convert them to proper dict or json.</p> <pre><code>foo = '{"Source": "my source", "Input": {"User_id": 18, "some_object": this_is_a_variable_actually}}' </code></pre> <p>Notice that the last key <code>some_object</c...
2
2016-07-17T11:05:04Z
38,421,919
<p>It's a bit of a kludge using the <a href="https://pypi.python.org/pypi/demjson" rel="nofollow">demjson</a> module which allows you to parse most of a somewhat non-confirming JSON syntax string and lists the errors... You can then use that to replace the invalid tokens found and put quotes around it just so it parses...
2
2016-07-17T13:47:46Z
[ "python", "string", "dictionary" ]
Dimension mismatch for applying indices from one df to another df
38,420,556
<p>I have df1 whose index has <code>df1.index.shape</code> of <code>(80,)</code>. I have an numpy array <code>df2</code> which has <code>df2.shape</code> of <code>(80,2)</code>. However, when I try to convert <code>df2</code> to dataframe, <code>df2 = pd.DataFrame(df2,index=df1.index)</code>, I get the following error...
1
2016-07-17T11:06:38Z
38,420,592
<p>For me it works nice:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6]}, index=['a','b','c']) print (df1) A B a 1 4 b 2 5 c 3 6 print (df1.index.shape) (3,) df2 = df1.values print (df2) [[1 4] [2 5] [3 6]] print (df2.shape) (3, 2) print (pd.DataF...
0
2016-07-17T11:12:36Z
[ "python", "numpy", "pandas" ]
Dimension mismatch for applying indices from one df to another df
38,420,556
<p>I have df1 whose index has <code>df1.index.shape</code> of <code>(80,)</code>. I have an numpy array <code>df2</code> which has <code>df2.shape</code> of <code>(80,2)</code>. However, when I try to convert <code>df2</code> to dataframe, <code>df2 = pd.DataFrame(df2,index=df1.index)</code>, I get the following error...
1
2016-07-17T11:06:38Z
38,420,597
<p>Please provide a sample data sets, because everything is working in this simple example:</p> <pre><code>In [15]: df1 = pd.DataFrame(np.random.randint(0, 1000, (5, 4))) In [16]: df2 = np.random.rand(5, 2) In [17]: df1 Out[17]: 0 1 2 3 0 724 639 288 169 1 49 271 75 161 2 728 329 78 23 ...
0
2016-07-17T11:13:12Z
[ "python", "numpy", "pandas" ]
Importing all needed modules in one main file that has all needed libraries for modules imported
38,420,797
<p>I for example i have 2 files, mother.py and child.py, child.py is module that is imported in mother.py </p> <p>Code in mother.py is:</p> <pre><code>from tkinter import * from tkinter import ttk from modules.child import LoginWindow root = Tk() window = LoginWindow(root) root.mainloop() </code></pre> <p>Code in c...
0
2016-07-17T11:39:53Z
38,421,183
<p>An import in Python isn't like an "include" in other languages. The entire module is contained inside an object named after the module you imported. So, when you do this:</p> <pre><code>from modules.child import LoginWindow </code></pre> <p>The entire module is contained inside the object/variable <code>LoginWindo...
1
2016-07-17T12:28:15Z
[ "python", "class", "module", "libraries" ]
Don't work Scrapy spider
38,420,798
<p>I parse one site and i have a spider:</p> <pre><code># -*- coding: utf-8 -*- from quoka.items import QuokaItem from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.loader.processors import TakeFirst from scrapy.loader import XPathItemLoader from scrapy.selector...
-1
2016-07-17T11:39:56Z
38,422,559
<p>You should use the name property of your spider, <br>Instead of following:</p> <pre><code>sudo scrapy crawl quoka_spider.py </code></pre> <p>Enter:</p> <pre><code>scrapy crawl quoka </code></pre>
0
2016-07-17T14:55:02Z
[ "python", "python-3.x", "ubuntu", "scrapy", "lxml" ]
Variable column name in SQL lite and Python
38,420,829
<p>my question is, as the title says, how I can create a variable column in SQL lite used in Pyhton.</p> <p>Here's my code, to show you what exactly I mean:</p> <pre><code>#Table with variables def dynamic_data_entry(list_name, num, column): element_name = list_name[num] cur.execute("INSERT INTO myliltable (c...
0
2016-07-17T11:44:43Z
38,420,859
<p>You need to use the string's <code>format()</code> method to <em>insert</em> the column name into the SQL string:</p> <pre><code>cur.execute("INSERT INTO myliltable ({}) VALUES (?)".format(column), element_name) </code></pre> <p>You can find more information in the <a href="https://docs.python.org/3.5/...
2
2016-07-17T11:48:36Z
[ "python", "sqlite3" ]
Apply StandardScaler on a partial part of a data set
38,420,847
<p>I want to use severals methods from StandardScaler from sklearn. Is it possible to use these methods on some columns/features of my set instead of apply them to the entire set.</p> <p>For instance the set is <code>data</code> : </p> <pre><code>data = pd.DataFrame({'Name' : [3, 4,6], 'Age' : [18, 92,98], 'Weight' :...
0
2016-07-17T11:47:07Z
38,420,977
<p>First create a copy of your dataframe:</p> <pre><code>scaled_features = data.copy() </code></pre> <p>Don't include the Name column in the transformation:</p> <pre><code>col_names = ['Age', 'Weight'] features = scaled_features[col_names] scaler = StandardScaler().fit(features.values) features = scaler.transform(fe...
2
2016-07-17T12:03:00Z
[ "python", "pandas", "scikit-learn", "scale", "data-science" ]
Apply StandardScaler on a partial part of a data set
38,420,847
<p>I want to use severals methods from StandardScaler from sklearn. Is it possible to use these methods on some columns/features of my set instead of apply them to the entire set.</p> <p>For instance the set is <code>data</code> : </p> <pre><code>data = pd.DataFrame({'Name' : [3, 4,6], 'Age' : [18, 92,98], 'Weight' :...
0
2016-07-17T11:47:07Z
38,422,081
<p>A more pythonic way to do this - </p> <pre><code>from sklearn.preprocessing import StandardScaler data[['Age','Weight']] = data[['Age','Weight']].apply( lambda x: StandardScaler().fit_transform(x)) data </code></pre> <p>Output - </p> <pre><code> Age Name Weight 0 -1.411004 ...
0
2016-07-17T14:07:38Z
[ "python", "pandas", "scikit-learn", "scale", "data-science" ]
Receiving IndexError: string index out of range when using apply
38,420,922
<p>I want to pick the most used nouns from a data frame by </p> <ol> <li>Segregating the nouns from each rows of my data.</li> <li>Storing them a new column called train['token']</li> </ol> <p>For this I am passing my function to the apply function but I am receiving this error </p> <p><strong>IndexError: string ind...
1
2016-07-17T11:56:35Z
38,444,940
<p>Your input contains two or more consecutive spaces in some places. When you split it with <code>x.split(" ")</code>, you get zero-length "words" between adjacent spaces.</p> <p>Fix it by splitting with <code>x.split()</code>, which will treat any run of consecutive whitespace characters as a token separator.</p>
2
2016-07-18T19:52:52Z
[ "python", "nltk" ]
PyQt: widget for listing by in clickable rows
38,420,969
<p>I am looking for a widget that would help me in building a GUI for a python program using PyQt5.</p> <p>I need to display a list of data, row by row. When clicking on one of the rows it will open a a different window.</p> <p>I have looked into <code>QLabel</code>, <code>QTableView</code> but they do not seem to do...
0
2016-07-17T12:01:44Z
38,422,881
<p><a href="http://doc.qt.io/qt-5/qlistwidget.html" rel="nofollow"><code>QListWidget</code></a> with the <a href="http://doc.qt.io/qt-5/qlistwidget.html#itemClicked" rel="nofollow"><code>itemClicked</code></a> signal should be enough.</p> <p>Hope it helps!</p>
1
2016-07-17T15:30:58Z
[ "python", "pyqt", "pyqt5" ]
Python search CSV file and return result in Tkinter
38,420,985
<p>Question has been updated since I've received an answer. The question that now raises is how to get the values from the csv file when I have two "Players" next to each other. </p> <p>from Tkinter import * import csv</p> <pre><code>master = Tk() b1 = StringVar() v1 = StringVar() v2 = StringVar() v3 = StringVar...
0
2016-07-17T12:03:54Z
38,435,793
<pre><code>from tkinter import * import csv master = Tk() b1 = StringVar() v1 = StringVar() v2 = StringVar() v3 = StringVar() a = Label(master, text="Player 1", font="Verdana 10 bold").grid(row=8, column=1, columnspan=2, pady=15) b = Label(master, text="Player Name").grid(row=9, column=1, sticky='w') c = Label(master, ...
1
2016-07-18T11:39:30Z
[ "python", "python-2.7", "tkinter" ]
Python search CSV file and return result in Tkinter
38,420,985
<p>Question has been updated since I've received an answer. The question that now raises is how to get the values from the csv file when I have two "Players" next to each other. </p> <p>from Tkinter import * import csv</p> <pre><code>master = Tk() b1 = StringVar() v1 = StringVar() v2 = StringVar() v3 = StringVar...
0
2016-07-17T12:03:54Z
38,436,992
<p>Here I am not using v1,v2 and v3 text variables. Appending second player values beside first player values. Enter "Andy Murray" hit Run next Enter "Novak Djokovic" hit run. you will see results of second player beside first player values. </p> <pre><code>from tkinter import * import csv master = Tk() b1 = StringV...
1
2016-07-18T12:40:40Z
[ "python", "python-2.7", "tkinter" ]
Python: Remove words from a given string
38,420,987
<p>I'm quite new to programming (and this is my first post to stackoverflow) however am finding this problem quite difficult. I am supposed to remove a given string in this case (WUB) and replace it with a space. For example: <code>song_decoder(WUBWUBAWUBWUBWUBBWUBC)</code> would give the output: <code>A B C</code>. Fr...
2
2016-07-17T12:04:06Z
38,421,020
<p>You're close! <a href="https://docs.python.org/2/library/stdtypes.html#str.replace" rel="nofollow"><code>str.replace()</code></a> does not work "in-place"; it returns a new string that has had the requested replacement performed on it.</p> <blockquote> <p><strong>Return a copy of the string</strong> with all occu...
3
2016-07-17T12:08:28Z
[ "python" ]
Python: Remove words from a given string
38,420,987
<p>I'm quite new to programming (and this is my first post to stackoverflow) however am finding this problem quite difficult. I am supposed to remove a given string in this case (WUB) and replace it with a space. For example: <code>song_decoder(WUBWUBAWUBWUBWUBBWUBC)</code> would give the output: <code>A B C</code>. Fr...
2
2016-07-17T12:04:06Z
38,421,041
<p>Do the both steps in a single line.</p> <pre><code>def song_decoder(song): return ' '.join(song.replace('WUB',' ').split()) </code></pre> <p><strong>Result</strong></p> <pre><code>In [95]: song_decoder("WUBWUBAWUBWUBWUBBWUBC") Out[95]: 'A B C' </code></pre>
1
2016-07-17T12:10:58Z
[ "python" ]
Python: Remove words from a given string
38,420,987
<p>I'm quite new to programming (and this is my first post to stackoverflow) however am finding this problem quite difficult. I am supposed to remove a given string in this case (WUB) and replace it with a space. For example: <code>song_decoder(WUBWUBAWUBWUBWUBBWUBC)</code> would give the output: <code>A B C</code>. Fr...
2
2016-07-17T12:04:06Z
38,421,053
<p>Strings are immutable in Python. So changing a string (like you try to do with the "replace" function) does not change your variable "song". It rather creates a new string which you immediately throw away by not assigning it to something. You could do</p> <pre class="lang-python prettyprint-override"><code>def song...
3
2016-07-17T12:12:06Z
[ "python" ]
Google search - Python
38,421,055
<p>I would like to get top ten result from google search engine. I wrote:</p> <pre><code>from google import search for i in search('python', stop=10): print i </code></pre> <p>It returns more than 10 results. What is a proper way to get top n results? When I change stop=10 to stop=2 it returns exact the same numb...
0
2016-07-17T12:12:24Z
38,421,114
<p>You can use the googlescraper module here . </p> <h1>How many urls did we get on all pages?</h1> <pre><code>print(sum(len(page['results']) for page in results)) </code></pre> <h1>How many hits has google found with our keyword (as shown on the first page)?</h1> <pre><code>print(results[0]['num_results_for_kw'])...
1
2016-07-17T12:21:29Z
[ "python", "search-engine" ]
Google search - Python
38,421,055
<p>I would like to get top ten result from google search engine. I wrote:</p> <pre><code>from google import search for i in search('python', stop=10): print i </code></pre> <p>It returns more than 10 results. What is a proper way to get top n results? When I change stop=10 to stop=2 it returns exact the same numb...
0
2016-07-17T12:12:24Z
38,421,212
<p>From reading <a href="http://pythonhosted.org/google/google-pysrc.html#search" rel="nofollow">the source code for <code>search</code></a>, it looks like the real behavior is that it returns pages full of results until it reaches (or passes) <code>stop</code>. So if there are 14 links on the first page of results, yo...
1
2016-07-17T12:30:45Z
[ "python", "search-engine" ]
Dynamical adding a "real" method to an object in python
38,421,117
<p>I have the following code (python 3):</p> <pre><code>import inspect def get_class_for_method(method): if inspect.ismethod(method): for cls in inspect.getmro(method.__self__.__class__): if cls.__dict__.get(method.__name__) is method: return cls method = method.__func...
2
2016-07-17T12:21:41Z
38,424,559
<p>You don't have enough information to reliably figure out what class the function has been assigned to. The information you available is: the function, its name and the module it was defined it. However, you don't know anything about the class or even if the class and the function were defined in the same module. It ...
1
2016-07-17T18:27:33Z
[ "python", "python-3.x" ]
Dynamical adding a "real" method to an object in python
38,421,117
<p>I have the following code (python 3):</p> <pre><code>import inspect def get_class_for_method(method): if inspect.ismethod(method): for cls in inspect.getmro(method.__self__.__class__): if cls.__dict__.get(method.__name__) is method: return cls method = method.__func...
2
2016-07-17T12:21:41Z
38,426,900
<p>There's no simple way to do exactly what you want.</p> <p>The main reason for this is aliasing. In Python, it's perfectly legal for the same function to be a method of multiple classes:</p> <pre><code>class A(object): def method(self): return "foo" class B(object): method = A.method </code></pre> ...
2
2016-07-17T23:29:25Z
[ "python", "python-3.x" ]
How to group values from a list of tuples?
38,421,143
<p>I have a list of tuples.</p> <p>[(1,2),(2,3),(4,5),(4,7),(7,9),(3,5),(5,6),(11,17)]</p> <p><strong>The relation is</strong> </p> <p>If (1,2) belongs to a domain and (2,3) belongs to a domain then [1,2,3] belongs to same domain.</p> <p><strong>Output should be</strong></p> <p>{'c1': {1, 2, 3, 5, 4, 7, 9, 6}, 'c1...
-2
2016-07-17T12:24:59Z
38,421,255
<p>It sounds like you're trying to implement a <a href="https://en.wikipedia.org/wiki/Disjoint-set_data_structure" rel="nofollow">disjoint set</a>. If so, a quick Google search will provide you with various implementations in Python.</p>
0
2016-07-17T12:34:52Z
[ "python", "python-3.x" ]
Combine multiple different images from a directory into a canvas sized 3x6
38,421,160
<p>I itirate to images of a directory. I want from those images to create a 3x6 canvas, a new image that will display the images of that directory side by side into a single image / canvas. Each image must be a different image. Side by side. –</p> <p>I have the following code. It tries to read the image filenames fr...
-1
2016-07-17T12:26:39Z
38,421,611
<p>Do not iterate over the image list for every position, consume the list instead:</p> <pre><code>for i in xrange(0, 2100, 700): for j in xrange(0, 2400, 400): try: filepath = npath.pop(0) except IndexError: break im = Image.open(filepath) im.thumbnail((1000...
3
2016-07-17T13:12:30Z
[ "python", "canvas", "python-imaging-library" ]
Combine multiple different images from a directory into a canvas sized 3x6
38,421,160
<p>I itirate to images of a directory. I want from those images to create a 3x6 canvas, a new image that will display the images of that directory side by side into a single image / canvas. Each image must be a different image. Side by side. –</p> <p>I have the following code. It tries to read the image filenames fr...
-1
2016-07-17T12:26:39Z
38,471,675
<p>I think what you're trying to do could be solved in a very general way by using coroutines as described in <a href="https://www.python.org/dev/peps/pep-0342/" rel="nofollow">PEP 342 — Coroutines via Enhanced Generators</a>. Below is code to handle creating and laying-out thumbnail images onto a grid of any size. ...
0
2016-07-20T03:09:25Z
[ "python", "canvas", "python-imaging-library" ]
Can't set index of a pandas data frame - getting "KeyError"
38,421,170
<p>I generate a data frame that looks like this (<code>summaryDF</code>):</p> <pre><code> accuracy f1 precision recall 0 0.494 0.722433 0.722433 0.722433 0 0.290 0.826087 0.826087 0.826087 0 0.274 0.629630 0.629630 0.629630 0 0.278 0.628571 0.628571 0.628571 0 0.288 0....
1
2016-07-17T12:27:16Z
38,421,196
<p>You need assign <code>list</code> to <code>summaryDF.index</code>, if <code>length</code> of <code>list</code> is same as <code>length</code> of <code>DataFrame</code>:</p> <pre><code>summaryDF.index = ['A','B','C', 'D','E','F','G','H','I','J','K','L'] print (summaryDF) accuracy f1 precision recall A ...
1
2016-07-17T12:29:18Z
[ "python", "pandas", "dataframe", "set", "row" ]
Can't set index of a pandas data frame - getting "KeyError"
38,421,170
<p>I generate a data frame that looks like this (<code>summaryDF</code>):</p> <pre><code> accuracy f1 precision recall 0 0.494 0.722433 0.722433 0.722433 0 0.290 0.826087 0.826087 0.826087 0 0.274 0.629630 0.629630 0.629630 0 0.278 0.628571 0.628571 0.628571 0 0.288 0....
1
2016-07-17T12:27:16Z
38,421,223
<p>I guess you and @jezrael misunderstood an example from the pandas docs:</p> <pre><code>df.set_index(['A', 'B']) </code></pre> <p><code>A</code> and <code>B</code> are column names / labels in this example:</p> <pre><code>In [55]: df = pd.DataFrame(np.random.randint(0, 10, (5,4)), columns=list('ABCD')) In [56]: d...
1
2016-07-17T12:32:05Z
[ "python", "pandas", "dataframe", "set", "row" ]
Python : Graph suggesting path with minimum number of paths
38,421,226
<p><a href="http://i.stack.imgur.com/PPfIs.png" rel="nofollow"><img src="http://i.stack.imgur.com/PPfIs.png" alt="Image for describing the test case of problem statement"></a></p> <p>I have implemented <a href="http://rosettacode.org/wiki/Dijkstra%27s_algorithm#Python" rel="nofollow">Dijkstra's Algorithm</a> and modif...
1
2016-07-17T12:32:23Z
38,421,512
<p>You can modify the graph so there will be an edge from each early vertex on a route to a later one (change lines 49-51 in the linked code):</p> <pre><code>for route,path in routes.iteritems(): for i in range(len( path)-1): for j in range(i, len(path)): data.append( (path[i] , path[j] , 1 , r...
1
2016-07-17T13:02:58Z
[ "python", "graph" ]
Python : Graph suggesting path with minimum number of paths
38,421,226
<p><a href="http://i.stack.imgur.com/PPfIs.png" rel="nofollow"><img src="http://i.stack.imgur.com/PPfIs.png" alt="Image for describing the test case of problem statement"></a></p> <p>I have implemented <a href="http://rosettacode.org/wiki/Dijkstra%27s_algorithm#Python" rel="nofollow">Dijkstra's Algorithm</a> and modif...
1
2016-07-17T12:32:23Z
38,422,403
<p>You can replace multi-edges with one weight edge, weight being number of edges. <br>Then do the Dijkstra algorithm on it. In you example graph weight of your <strong>desired path is going to be 5</strong>, and the path that Dijkstra algorithm on <strong>unweighted graph returns is going to be 6</strong>.</p>
1
2016-07-17T14:38:00Z
[ "python", "graph" ]
Python pandas generating first day of month from array of datetime
38,421,454
<p>I am trying to obtain the first day of month from array of datetime i.e. change all days to <code>1</code> and all hours to <code>0</code>:</p> <pre><code>import pandas as pd z1 = [datetime(2025, 10, 1, 3, 0),datetime(2025, 1, 6, 7, 0)] pd.DatetimeIndex(z1).normalize() DatetimeIndex(['2025-10-01', '2025-01-06'], dt...
2
2016-07-17T12:55:55Z
38,421,517
<p>You can first create <code>Series</code> from <code>z1</code>, then <code>replace</code> <code>day</code> and convert to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><code>date</code></a>:</p> <pre><code>print (pd.DatetimeIndex(pd.Series(z1).apply(lambda ...
1
2016-07-17T13:03:20Z
[ "python", "datetime", "pandas", "replace", "datetimeindex" ]
Python pandas generating first day of month from array of datetime
38,421,454
<p>I am trying to obtain the first day of month from array of datetime i.e. change all days to <code>1</code> and all hours to <code>0</code>:</p> <pre><code>import pandas as pd z1 = [datetime(2025, 10, 1, 3, 0),datetime(2025, 1, 6, 7, 0)] pd.DatetimeIndex(z1).normalize() DatetimeIndex(['2025-10-01', '2025-01-06'], dt...
2
2016-07-17T12:55:55Z
38,421,641
<p>Another way would be to form a NumPy array of dtype <code>datetime64[M]</code> (a datetime64 with monthly resolution)</p> <pre><code>In [31]: np.array(z1, dtype='datetime64[M]') Out[31]: array(['2025-10', '2025-01'], dtype='datetime64[M]') </code></pre> <p>Passing it to <code>pd.DatetimeIndex</code> returns </p> ...
3
2016-07-17T13:16:39Z
[ "python", "datetime", "pandas", "replace", "datetimeindex" ]
List entries in for loop not changing
38,421,491
<p>I know its generally not recommended to iterate over a changing list, but why is this not working? I am trying to get <code>boxes</code> to change</p> <pre><code>boxes = [["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"], ["A4", "A5", "A6", "B4", "B5", "B6", "C4", "C5", "C6"], ["A7", "A8", "A9", "B7", "B8...
-1
2016-07-17T13:00:50Z
38,421,548
<p><code>positions</code> in each iteration is just a string. At this point it has no concept of container where it belongs. And since strings are immutable you cannot change it in-place.</p> <pre><code>l = ["A1"] for e in l: print(e, type(e)) # A1 &lt;class 'str'&gt; </code></pre> <p>To change container you nee...
1
2016-07-17T13:06:13Z
[ "python", "python-3.x" ]
Cross-validating an ordinal logistic regression in R (using rpy2)
38,421,618
<p>I'm trying to create a predictive model in Python, comparing several different regression models through cross-validation. In order to fit an ordinal logistic model (<code>MASS.polr</code>), I've had to interface with R through <code>rpy2</code> as follows:</p> <pre><code>from rpy2.robjects.packages import importr ...
0
2016-07-17T00:05:50Z
38,571,330
<p>Problem eventually solved by refitting the model using <code>rms.lrm</code>, which provides a <code>validate()</code> function (interpreted following <a href="http://stats.stackexchange.com/questions/23238/cross-validation-and-ordinal-logistic-regression">this example</a>).</p>
2
2016-07-25T15:06:40Z
[ "regression", "cross-validation", "python", "scikit-learn" ]
Python - Scipy linear regression with nan values
38,421,624
<p>I would like to obtain the slopes of the linear regression of my data, but the Y contains some nan values...thus it perturbs linregress function... For example :</p> <pre><code>from scipy import stats import numpy as np X = np.array([0,1,2,3,4,5]) Y = np.array([np.NaN,4, 5, 10, 2, 5]) stats.linregress(X,Y) </code>...
0
2016-07-17T13:14:09Z
38,421,700
<p>Try the following:</p> <pre><code>Y=Y[np.logical_not(np.isnan(Y))] X=X[np.logical_not(np.isnan(Y))] </code></pre> <p>upd: as Warren noticed, <code>Y</code> will be updated, so the <code>nans</code> are gone. You can feed <code>Y[np.logical_not(np.isnan(Y))]</code> and <code>X=X[np.logical_not(np.isnan(Y))] </code>...
1
2016-07-17T13:23:26Z
[ "python", "scipy", "linear-regression" ]
Python - Scipy linear regression with nan values
38,421,624
<p>I would like to obtain the slopes of the linear regression of my data, but the Y contains some nan values...thus it perturbs linregress function... For example :</p> <pre><code>from scipy import stats import numpy as np X = np.array([0,1,2,3,4,5]) Y = np.array([np.NaN,4, 5, 10, 2, 5]) stats.linregress(X,Y) </code>...
0
2016-07-17T13:14:09Z
38,424,142
<p>To remove (x, y) pairs where y is <code>nan</code> or <code>inf</code>, you can do this:</p> <pre><code>finiteYmask = np.isfinite(Y) Yclean = Y[finiteYmask] Xclean = X[finiteYmask] </code></pre> <p>If you are only using these "cleaned" arrays for <code>linregress</code>, you can do just:</p> <pre><code>finiteYmas...
2
2016-07-17T17:42:47Z
[ "python", "scipy", "linear-regression" ]
How to center text horizontally in a kivy text input?
38,421,741
<p>I want to center a single line text in kivt text input. I'm going to use padding</p> <pre><code>widget.padding = [ (self.textinput.width - width of line) / 2, 20, 0, 0] </code></pre> <p>but i can't find width of the line. how can i calculate or reach width of the line? <a href="http://i.stack.imgur.com/eXkji.png" ...
3
2016-07-17T13:28:02Z
38,422,826
<p>You could make a textinput behind a button, and make the button visualize as the text input. </p> <p>When pushing the button, put the focus to the textinput, and update the buttons text.</p> <p>I have made an example here. <br></p> <pre><code>from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import...
1
2016-07-17T15:25:12Z
[ "python", "kivy" ]
How to center text horizontally in a kivy text input?
38,421,741
<p>I want to center a single line text in kivt text input. I'm going to use padding</p> <pre><code>widget.padding = [ (self.textinput.width - width of line) / 2, 20, 0, 0] </code></pre> <p>but i can't find width of the line. how can i calculate or reach width of the line? <a href="http://i.stack.imgur.com/eXkji.png" ...
3
2016-07-17T13:28:02Z
38,423,102
<p>There is an internal <code>TextInput._get_text_width</code> method you can use to calculate proper padding:</p> <pre><code>from kivy.app import App from kivy.uix.floatlayout import FloatLayout from kivy.lang import Builder Builder.load_string(''' &lt;MyWidget&gt;: TextInput: multiline: False o...
2
2016-07-17T15:53:58Z
[ "python", "kivy" ]
Ordering a GROUP BY query
38,421,760
<p>I'm using sqlite3 database in my very simple program written in python. Table I have a problem with contains three columns:</p> <pre><code>id, software_version, place </code></pre> <p>Now I would like to count the frequency of a particular software version, so I created this query:</p> <pre><code>SELECT software_...
1
2016-07-17T13:29:52Z
38,421,775
<p>Add an <code>ORDER BY</code> on the <code>COUNT</code> results; give that result an alias:</p> <pre><code>SELECT software_ssh, COUNT (software_ssh) as freq FROM simple_table GROUP BY software_ssh ORDER BY freq </code></pre> <p>Use <code>ORDER BY freq DESC</code> if you need the rows ordered from most freq...
1
2016-07-17T13:31:06Z
[ "python", "sqlite3" ]
Tensorflow can't find libcuda.so (CUDA 7.5)
38,421,840
<p>I've installed CUDA 7.5 toolkit, and Tensorflow inside anaconda env. The CUDA driver is also installed. The folder containing the <code>so</code> libraries is in <code>LD_LIBRARY_PATH</code>. When I import tensorflow I get the following error:</p> <blockquote> <p>Couldn't open CUDA library libcuda.so. LD_LIBRARY_...
0
2016-07-17T13:38:11Z
38,431,444
<p>For future reference, here is what I found out and what I did to solve this problem. The system is Ubuntu 14.04 64 bit. The NVIDIA driver version that I was trying to install was 367.35. The installation resulted in an error towards the end, with message:</p> <blockquote> <p>ERROR: Unable to load the kernel modul...
1
2016-07-18T08:01:20Z
[ "python", "cuda", "tensorflow" ]
variable's scope after visiting a page with Selenium
38,421,918
<p>Noob here: I have a small script to collect all product links from an user Ebay product list and then open them one by one. It populates the list correctly, it opens the first link as expected, waits a bit and then returns to the previous page (the product list).</p> <p>When trying to open the next link in the lis...
0
2016-07-17T13:47:17Z
38,422,645
<p>When you leave the current page, or even if the DOM is refreshed, the <code>driver</code> "losses" the web elements and you get <code>StaleElementReferenceException</code>.</p> <p>To iterate over several pages you need to relocate the list each iteration, and you can use indexes to keep your location in the list</p...
0
2016-07-17T15:05:40Z
[ "python", "selenium" ]
How to pass two user-defined arguments to a scrapy spider
38,421,954
<p>Following <a href="http://stackoverflow.com/questions/15611605/how-to-pass-a-user-defined-argument-in-scrapy-spider">How to pass a user defined argument in scrapy spider</a>, I wrote the following simple spider:</p> <pre><code>import scrapy class Funda1Spider(scrapy.Spider): name = "funda1" allowed_domains...
2
2016-07-17T13:52:01Z
38,421,984
<p>When providing multiple arguments you need to prefix <code>-a</code> for <strong>every</strong> argument.</p> <p>The correct line for your case would be:</p> <p><code>scrapy crawl funda1 -a place=rotterdam -a page=2</code></p>
3
2016-07-17T13:54:51Z
[ "python", "scrapy" ]
Define common files for GAE projects
38,421,955
<p>I have two different projects in Google app engine account. The folders structure in my computer is as following:</p> <ul> <li>parent_folder <ul> <li>common_folder</li> <li>project1_folder</li> <li>project2_folder</li> </ul></li> </ul> <p>I have few python classes in common_folder that I want to use in both proje...
0
2016-07-17T13:52:15Z
38,422,963
<p>The reason for the error you see is that nothing above the module/service dir (or app dir for single module apps) is uploaded to GAE during deployment. </p> <p>You can symlink the necessary file(s) inside your app dirs, see <a href="http://stackoverflow.com/a/34291789/4495081">http://stackoverflow.com/a/34291789/44...
0
2016-07-17T15:39:11Z
[ "python", "google-app-engine", "google-app-engine-python" ]
Disable argparse choices message
38,421,964
<p><code>Argparse</code> displays message about the list of choices, like in this example:</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument('--styles', choices=long_list_of_styles) </code></pre> <p>As I'm passing a long list, help message does not look good, in fact it looks confu...
1
2016-07-17T13:53:25Z
38,423,350
<p>The proposed duplicate, <a href="http://stackoverflow.com/questions/11272806/pythons-argparse-choices-constrained-printing">Python&#39;s argparse choices constrained printing</a> presents a relatively complicated solution - a custom <code>HelpFormatter</code>. Or a custom <code>type</code>.</p> <p>A higher vote qu...
2
2016-07-17T16:21:20Z
[ "python", "python-3.x", "argparse" ]
pandas.DataFrame corrwith() method
38,422,001
<p>I recently start working with <code>pandas</code>. Can anyone explain me difference in behaviour of function <code>.corrwith()</code> with <code>Series</code> and <code>DataFrame</code>?</p> <p>Suppose i have one <code>DataFrame</code>:</p> <pre><code>frame = pd.DataFrame(data={'a':[1,2,3], 'b':[-1,-2,-3], 'c':[10...
1
2016-07-17T13:56:40Z
38,422,030
<p>corrwith defined as <code>DataFrame.corrwith(other, axis=0, drop=False)</code>, so the <code>axis=0</code> per default - i.e. <code>Compute pairwise correlation between columns of two **DataFrame** objects</code></p> <p>So the column names / labels must be the same in both DFs:</p> <pre><code>In [134]: frame.drop(...
4
2016-07-17T14:00:26Z
[ "python", "pandas", "dataframe" ]
pandas.DataFrame corrwith() method
38,422,001
<p>I recently start working with <code>pandas</code>. Can anyone explain me difference in behaviour of function <code>.corrwith()</code> with <code>Series</code> and <code>DataFrame</code>?</p> <p>Suppose i have one <code>DataFrame</code>:</p> <pre><code>frame = pd.DataFrame(data={'a':[1,2,3], 'b':[-1,-2,-3], 'c':[10...
1
2016-07-17T13:56:40Z
38,422,321
<h3>What I think you're looking for:</h3> <p>Let's say your frame is:</p> <pre><code>frame = pd.DataFrame(np.random.rand(10, 6), columns=['cost', 'amount', 'day', 'month', 'is_sale', 'hour']) </code></pre> <p>You want the <code>'cost'</code> and <code>'amount'</code> columns to be correlated with all other columns i...
4
2016-07-17T14:30:30Z
[ "python", "pandas", "dataframe" ]
accessing function's local variables in another project
38,422,053
<pre><code>#project login.py def login(): username = input() password = input() #did some stuff! #now a new project... #project access.py from login import login if login.username=='ABC' and login.password=='XYZ': #Cool...gained access! </code></pre> <p>My problem is I am not getting how to ac...
1
2016-07-17T14:02:55Z
38,422,101
<pre><code>#project login.py def login(): username = input() password = input() #did some stuff! return username, password #now a new project... #project access.py from login import login username, password = login() if username=='ABC' and password=='XYZ': #Cool...gained access! </code></p...
0
2016-07-17T14:09:09Z
[ "python", "function" ]
Discrepancy between formatted numeric value and rounded value
38,422,170
<p>I found this weird behavior using python and numpy:</p> <pre><code>print('%10.3f' %0.4975) </code></pre> <p>returns 0.497, while</p> <pre><code>numpy.round(0.4975,3) </code></pre> <p>returns 0.498 as expected. With other similar numbers I always get the print statement to deliver the correctly rounded value (for...
1
2016-07-17T14:15:02Z
38,423,500
<p>In double precision, 0.4975 is 8962163258467287/18014398509481984 which is slightly <strong>less</strong> than the real number 0.4975. Hence, Python's <code>round</code> function rounds it to 0.497. </p> <p>In contrast, 0.5975 becomes 5381801554707743/9007199254740992 which is slightly <strong>more</strong> than th...
6
2016-07-17T16:37:58Z
[ "python", "numpy", "rounding", "number-formatting" ]
The def function I called doesn't implement
38,422,286
<p>So, I'm basically trying to make a program to calculate the mean of five numbers. I called a def function but it doesn't do anything. I run the project on cmd and just it sits there and makes another input line. Bam, no calculation, no anything. There doesn't seem to be a problem with the code because the compiler d...
-6
2016-07-17T14:27:28Z
38,422,355
<p>First your indentation looks wrong. Then you don't want to have <code>operation</code> as argument since you are computing it, the arguments should be your numbers. Or probably nothing, and instead put your number inputs inside your function (and you need to call it after you define it). Finally no <code>;</code> in...
0
2016-07-17T14:34:24Z
[ "python", "function" ]
The def function I called doesn't implement
38,422,286
<p>So, I'm basically trying to make a program to calculate the mean of five numbers. I called a def function but it doesn't do anything. I run the project on cmd and just it sits there and makes another input line. Bam, no calculation, no anything. There doesn't seem to be a problem with the code because the compiler d...
-6
2016-07-17T14:27:28Z
38,422,371
<ol> <li><p>Your indentation is wrong.</p></li> <li><p>You are never actually calling the function.</p></li> <li><p><code>input</code> returns a string, so you will have to convert the numbers to float. </p></li> <li><p>Since <code>operation</code> is a float, you can't simply concat it to create the <code>final</cod...
0
2016-07-17T14:35:28Z
[ "python", "function" ]