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
Print specific line (Beautifulsoup)
37,860,039
<p>Currently, my code is parsing through the link and printing all of the information from the website. I only want to print <strong><em>a single specific line from the website</em></strong>. How can I go about doing that?</p> <p>Here's my code:</p> <pre><code>from bs4 import BeautifulSoup import urllib.request r = ...
0
2016-06-16T13:01:12Z
37,864,746
<p>Don't use pretty print to try and parse tds, select the tag specifically, if the attribute is unique then use that, if the class name is unique then just use that:</p> <pre><code>td = soup.select_one("td.content") td = soup.select_one("td[colspan=3]") </code></pre> <p>If it was the fourth td:</p> <pre><code>td = ...
2
2016-06-16T16:31:48Z
[ "python", "beautifulsoup" ]
Converting RGB to Grayscale manually tensorflow
37,860,136
<p>I wanted to convert an RGB image to grayscale manually without library usage in tensorflow. So I wrote the following...</p> <pre><code>import tensorflow as tf import matplotlib.image as mpimg import matplotlib.pyplot as plt # First, load the image again filename = "MarshOrchid.jpg" raw_image_data = mpimg.imread(fi...
2
2016-06-16T13:04:43Z
37,860,726
<p>From the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow" rel="nofollow">doc</a> of plt.imshow(X):</p> <blockquote> <p>X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)</p> </blockquote> <p>Here you have an input of shape [None, None, 1]. You just need to remove the last dimensio...
0
2016-06-16T13:28:33Z
[ "python", "numpy", "rgb", "tensorflow", "grayscale" ]
How to generate and apply a square mask in numpy
37,860,142
<p>I really just can't grok how masks work in Numpy.</p> <p>I create a mask like</p> <pre><code>import numpy def make_mask(center_x,center_y,len_x,len_y): x,y = numpy.ogrid[:len_x, :len_y] mask = (center_x-x)**2 + (center_y-y)**2 return mask </code></pre> <p>Then I attempt to use it</p> <pre><code...
-1
2016-06-16T13:04:50Z
37,860,937
<p>Your mask is setting the 2nd, 5th and 8th rows to 0; the array is being flattened since it does not have the same shape as the array it is masking. It is being applied as:</p> <pre><code>a[2] = 0 a[5] = 0 a[8] = 0 </code></pre> <p>I think you were expecting something more like:</p> <pre><code>mask = numpy.ones_li...
2
2016-06-16T13:37:26Z
[ "python", "python-2.7", "numpy" ]
How to generate and apply a square mask in numpy
37,860,142
<p>I really just can't grok how masks work in Numpy.</p> <p>I create a mask like</p> <pre><code>import numpy def make_mask(center_x,center_y,len_x,len_y): x,y = numpy.ogrid[:len_x, :len_y] mask = (center_x-x)**2 + (center_y-y)**2 return mask </code></pre> <p>Then I attempt to use it</p> <pre><code...
-1
2016-06-16T13:04:50Z
37,861,071
<p>If you take a look at what your <code>make_mask</code> function does, when written like this:</p> <pre><code>def make_mask(index_x,index_y,len_x,len_y): x,y = numpy.ogrid[:len_x, :len_y] mask = (index_x-x)**2 + (index_y-y)**2 return mask </code></pre> <p>you will see that you get</p> <pre><code>...
0
2016-06-16T13:42:54Z
[ "python", "python-2.7", "numpy" ]
How to get a user's email from an access token using the Facebook Python SDK
37,860,278
<p>I am trying to implement Facebook login for an application I am developing.</p> <p>I am getting an access token like this:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;script&gt; window.fbAsyncInit = function() { FB.init({ appId : '[Redacted]', ...
0
2016-06-16T13:09:51Z
37,865,202
<p>Make sure that</p> <p>a) the user has actually granted the permission to your app (request <code>/me/permissions</code> to confirm, using the same access token), and</p> <p>b) that their e-mail address is verified with Facebook. (Apparently not automatically the case with the e-mail address used to register.)</p>
0
2016-06-16T16:56:55Z
[ "python", "facebook", "email", "facebook-graph-api" ]
Regex make a match must end with a number
37,860,303
<p>I'm trying to make a regex that captures a certain word can have a certain number of spaces after it and have a number right after.</p> <p>Example</p> <p>Created 100 images</p> <p>I tried</p> <pre><code>/(created\s*\d*)/ </code></pre> <p>Which matches what I want but also matches </p> <p>'Created '</p> <p>^N...
-1
2016-06-16T13:10:46Z
37,860,320
<p>Change <code>\d*</code> to <code>\d+</code>. <code>*</code> means zero or more, where <code>+</code> means one or more.</p> <p><a href="https://regex101.com/r/rK7wJ6/1" rel="nofollow">Try it here</a></p>
3
2016-06-16T13:11:41Z
[ "python", "regex" ]
How to make urllib.urlencode use double quotes instead of single quotes?
37,860,368
<p>I have a question regarding urlencode. Here is an example:</p> <pre><code>urllib.urlencode({"action":"task_exam_save_result","examid":5,"t2],False,2]],"spendTime":911},"submit":"true","summary":{"correct":0,"wrong":2}}) </code></pre> <p>So, I get this:</p> <pre><code>examresult=%7B%27spendTime%27%3A+911%2C+%27ch...
0
2016-06-16T13:13:34Z
37,860,508
<p>I would not use <code>urlencode here</code>, but convert to JSON using <code>json.dumps()</code> and then use <code>urlencode</code> or b64encode to make it safe for use in an url.</p>
2
2016-06-16T13:19:50Z
[ "python" ]
How to make urllib.urlencode use double quotes instead of single quotes?
37,860,368
<p>I have a question regarding urlencode. Here is an example:</p> <pre><code>urllib.urlencode({"action":"task_exam_save_result","examid":5,"t2],False,2]],"spendTime":911},"submit":"true","summary":{"correct":0,"wrong":2}}) </code></pre> <p>So, I get this:</p> <pre><code>examresult=%7B%27spendTime%27%3A+911%2C+%27ch...
0
2016-06-16T13:13:34Z
37,860,724
<h1>A quote is not part of a string</h1> <p>It's up to you which quote you use and it is up to Python which quote it uses.</p> <pre><code>&gt;&gt;&gt; 'asdf' 'asdf' &gt;&gt;&gt; "asdf" 'asdf' &gt;&gt;&gt; "as'df" "as'df" </code></pre>
0
2016-06-16T13:28:31Z
[ "python" ]
Is it possible to define a function that takes a different form based on the sign of the parameter in Theano
37,860,400
<p>I need to define the following function. Is it possible to do in Theano? <a href="http://i.stack.imgur.com/Uy3lW.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Uy3lW.jpg" alt="enter image description here"></a></p> <p><strong>UPDATE:</strong></p> <p>To clarify I'm asking about defining a theano symbolic va...
0
2016-06-16T13:15:14Z
37,861,673
<p>Without knowing specifics about Theano, I remember that one way to turn an <code>if-else</code> statement into a linear equation is to make your <code>if</code> check into a variable itself, setting it as <code>0</code> or <code>1</code>. Then, you can do something like:</p> <pre><code>sign = (R_t &gt; 0) ## this ...
1
2016-06-16T14:10:27Z
[ "python", "theano" ]
Issue calling a method on a parent class
37,860,599
<p>I am new to Python classes and trying to understand the concept of inheritance. I have a class called <code>Math</code> which inherits from <code>Calc</code>. From <code>Math.product()</code> I am trying to invoke the base class method <code>mul()</code> as below:</p> <pre><code>class Calc(object): def mul(a, ...
0
2016-06-16T13:23:28Z
37,860,645
<p>You need to include <code>self</code> as a parameter in </p> <pre><code>class Calc(object): def mul(a, b): return a * b </code></pre> <p>Either that or use the <code>staticmethod</code> decorator.</p> <p>For example:</p> <pre><code>class Calc(object): @staticmethod def mul(a, b): retu...
8
2016-06-16T13:25:10Z
[ "python", "inheritance" ]
reshape python concatenate text irregular dataframe
37,860,776
<p>I'm very new to Python and pandas in particular. I've got an irregular reshape problem where I want to concatenate all strings from one column of the dataframe where an id variable matches from the other column. It is an irregular reshape problem because the number of concatenations that need to be done may differ d...
1
2016-06-16T13:30:37Z
37,860,799
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with aggregating <code>join</code>:</p> <pre><code>print (df.groupby('id')['text'].apply(' '.join).reset_index()) id text 0 1 ABC BCD 1 2 CDE DEF EFG 2 3 ...
3
2016-06-16T13:31:40Z
[ "python", "pandas", "group-by", "reshape", "string-concatenation" ]
Python regex issue with strings
37,860,938
<p>Hi wonder if someone can help I've converted to Python from Perl and for the most part I love it. However I struggle with regex in Python this is not as strong or easy as perl for anyway. How do I use a list of exemption values(exemptions_list) to search another list which is being iterated in a for loop. Problem...
-1
2016-06-16T13:37:39Z
37,861,482
<p>Strips last <code>_\d\d</code> from string</p> <pre><code>re.sub(r'_\d\d$', '', string) </code></pre> <p>So to check for exemption do</p> <pre><code>&gt;&gt;&gt; re.sub(r'_\d\d$', '', "none_20") in exemption_list True </code></pre> <hr> <p>If searched words are in more general format than <code>name_\d\d</code>...
0
2016-06-16T14:01:27Z
[ "python", "regex" ]
self.ids.clayout.ids give empty dictionary even though it contains widgets
37,860,941
<p>In this code, <code>self.ids</code> returns me the dictionary with child elements which include <code>id: clayout</code>. In the <code>__init__()</code>, I have added five buttons to <code>BoxLayout(id:clayout)</code> . But when I get <code>self.ids.clayout.ids</code> it gives me empty dictionary. Small mistake whic...
0
2016-06-16T13:37:44Z
37,886,589
<p>The <code>ids</code> dictionary is only populated by the kv lang parser. You have to keep track of dynamically created widgets yourself. You could store widgets in a <code>ListProperty</code>, for example.</p>
0
2016-06-17T16:48:37Z
[ "python", "dictionary", "kivy" ]
Seaborn Plot including different distributions of the same data
37,861,021
<p>I wish to create a <code>seaborn</code> <code>pointplot</code> to display the full data distribution in a column, alongside the distribution of the lowest 25% of values, and the distribution of the highest 25% of values, and all side by side (on the x axis). My attempt so far provides me with the values, but they ar...
4
2016-06-16T13:40:58Z
37,861,840
<p>You could <code>.join()</code> the new distributions to your existing <code>df</code> and then <code>.plot()</code> using wide format:</p> <pre><code>lower, upper = df.total_bill.quantile([.25, .75]).values.tolist() df = df.join(df.loc[df.total_bill &lt; lower, 'total_bill'], rsuffix='_lower') df = df.join(df.loc[d...
3
2016-06-16T14:17:34Z
[ "python", "pandas", "matplotlib", "machine-learning", "seaborn" ]
Seaborn Plot including different distributions of the same data
37,861,021
<p>I wish to create a <code>seaborn</code> <code>pointplot</code> to display the full data distribution in a column, alongside the distribution of the lowest 25% of values, and the distribution of the highest 25% of values, and all side by side (on the x axis). My attempt so far provides me with the values, but they ar...
4
2016-06-16T13:40:58Z
37,862,207
<p>I would think along the lines of adding a "group" and then plot as a single DataFrame.</p> <pre><code>import seaborn as sns import pandas as pd import matplotlib.pyplot as plt %matplotlib notebook df = sns.load_dataset('tips') df = df.append(df) df.loc[(df.total_bill &lt; df.total_bill.quantile(.25)),'group'] = '...
2
2016-06-16T14:32:17Z
[ "python", "pandas", "matplotlib", "machine-learning", "seaborn" ]
SQLAlchemy query for returning grouped products from a sale based on timestamp
37,861,079
<p>So I am a little stuck on coming up with the logic needed to return the following:</p> <pre><code>+--------------+------------+------------+------------+ | Product Name | 2016-05-10 | 2016-05-11 | 2016-05-12 | +--------------+------------+------------+------------+ | Big Chair | 29.00 | 78.00 | 900.0...
0
2016-06-16T13:43:18Z
37,866,129
<p>What you're missing is <a href="https://www.postgresql.org/docs/9.5/static/tablefunc.html#TABLEFUNC-FUNCTIONS" rel="nofollow"><code>crosstab</code></a> (a.k.a. "pivot table"). It allows to you turn values in a column into multiple columns.</p> <p>Let's work backwards and come up with the data we need to give to <co...
1
2016-06-16T17:50:25Z
[ "python", "sql", "postgresql", "sqlalchemy" ]
Installing module in python Annoconda "python setup.py egg_info" failed with error code 1
37,861,139
<p>I am trying to install skdata module in Annoconda 2.2 verison using</p> <pre><code>conda install skdata </code></pre> <p>But its throwing error as follows,</p> <blockquote> <p>Error: Package missing in current linux-32 channels: - skdata</p> </blockquote> <p>Also its the same when I tried with </p> <pre>...
1
2016-06-16T13:45:59Z
37,893,193
<p>There's not right now any <code>skdata</code> packages in the default conda channels or even on .</p> <p>Pretty sure your the core issue is that <code>skdata</code> assume you're using python2, and you're trying to install in a python3 environment.</p> <p>Try this:</p> <pre><code>conda create -y -n skdata-env pyt...
0
2016-06-18T04:19:23Z
[ "python", "anaconda", "conda" ]
Tensorflow, MultiRNN, why are there so many cells?
37,861,147
<p>I am trying to build a sequence to sequence model in tensorflow and I am using the MultiRNN class to chain together 3 GRUs for my encoder. </p> <pre><code>with tf.variable_scope('encoder') as encode_scope: encoder_rnn = rnn.MultiRNNCell([rnn.GRUCell(1024)] * 3) encoder_state = tf.zeros((BATCH_SIZE, encoder...
0
2016-06-16T13:46:13Z
37,893,402
<p>What is the value of <code>TIME_STEPS</code>? Is it perhaps 64?</p>
0
2016-06-18T04:56:11Z
[ "python", "neural-network", "tensorflow", "tensorboard" ]
Get by condition column values
37,861,160
<p>I have following <code>DataFrame</code>:</p> <pre><code> A B 0 1 5 1 2 3 2 3 2 3 4 0 4 5 1 </code></pre> <p>How I can get by condition values of column <code>A</code> ?</p> <p>For example all values that great then 3 and less then 6.</p>
2
2016-06-16T13:46:36Z
37,861,198
<p>You can use <code>boolean indexing</code>, either with conditions for the endpoints of your interval</p> <pre><code>df[(df.A &gt; 3) &amp; (df.A &lt; 6)] </code></pre> <p>or the convenience method <code>.between()</code>, which behind the scenes translates to the above (and hence is a very very tiny bit slower) wh...
0
2016-06-16T13:47:30Z
[ "python", "pandas", "dataframe", "condition" ]
Get by condition column values
37,861,160
<p>I have following <code>DataFrame</code>:</p> <pre><code> A B 0 1 5 1 2 3 2 3 2 3 4 0 4 5 1 </code></pre> <p>How I can get by condition values of column <code>A</code> ?</p> <p>For example all values that great then 3 and less then 6.</p>
2
2016-06-16T13:46:36Z
37,861,210
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.between.html" rel="nofollow"><code>between</code></a> (is possible use parameter <code>inclusive=False</code>) with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexi...
0
2016-06-16T13:48:14Z
[ "python", "pandas", "dataframe", "condition" ]
Error when plotting whole array using matplotlib and numpy
37,861,171
<p>I am trying to plot a scatter chart using numpy and matplotlib. It is very simple, I have 2 data files, each contains single column set of data. Both files have same number of data (I've checked this over and over again to make sure). </p> <p>This is what I've done:</p> <pre><code>import numpy as np import pylab a...
0
2016-06-16T13:46:52Z
37,861,427
<p>It is attempting to plot x and y variables, as in a scatter plot. The two vectors need to have the same length, which is why you see that you are able to plot up to the smallest of the two lengths. There's no getting around it. The length of the two arrays is clearly not equal.</p>
1
2016-06-16T13:58:58Z
[ "python", "arrays", "numpy", "matplotlib", "plot" ]
Python Google Contacts API - Deleting contacts
37,861,206
<p>Reading the Developer's Guide I found how to delete single contact:</p> <pre><code>def delete_contact(gd_client, contact_url): # Retrieving the contact is required in order to get the Etag. contact = gd_client.GetContact(contact_url) try: gd_client.Delete(contact) except gdata.client.RequestError, e: ...
0
2016-06-16T13:48:08Z
37,913,862
<p>If you are performing a lot of operations, use the batch requests. You can have the server perform multiple operations with a single HTTP request. Batch requests are limited to 100 operations at a time. You can find more information about batch operations in the <a href="https://developers.google.com/gdata/docs/batc...
0
2016-06-20T02:26:59Z
[ "python", "gdata", "google-contacts" ]
Install Atom for Python on Windows 10
37,861,223
<p>I just encountered the problem that Atom could not find the Python path. A lot of posts are about setting the paths, etc., which will sometimes not work for everybody. Can anybody help here?</p>
-3
2016-06-16T13:49:24Z
37,861,605
<p>I found the solution to my problem.</p> <p>If this does not work uninstall Python and Atom. While reinstalling Python make sure you click on "Add Python to Path" so you will not have any problems with setting the paths at all!</p> <p><img src="http://i.stack.imgur.com/CCXQG.jpg" alt="Problem solved"></p>
0
2016-06-16T14:06:53Z
[ "python", "windows", "variables", "path", "atom" ]
my tkinter window doesn't open up when I add the sleep() part
37,861,238
<p>I am trying to make a ball go to one side of the screen turn around, then come back. Whenever I try running this program the tkinter window doesn't show up, but when i get rid of the sleep(0.5) part it shows up when the ball is already off the screen. Can someone tell my what I did wrong?</p> <pre><code>from tkinte...
0
2016-06-16T13:50:10Z
37,861,648
<p>In windows, Tkinter frame shows up only after you call mainloop(). In your case, the for loop might be blocking it. Keep the for loop in a function and then call that function using threads so that it won't block the main loop.</p>
0
2016-06-16T14:08:51Z
[ "python", "tkinter", "sleep" ]
Python - installing a library using homebrew?
37,861,296
<p>I'm pretty new to the OSX environment and homebrew. I downloaded the QJson python library using <code>brew install qjson</code>.</p> <p>What are the next steps i need to take in order to be able to work with it in PyCharm?</p>
0
2016-06-16T13:52:58Z
37,861,362
<p>In pycharm you can go to the project interpreter page and click the + icon. Just like this <a href="https://www.jetbrains.com/help/pycharm/2016.1/installing-uninstalling-and-upgrading-packages.html#d127687e164" rel="nofollow">guide</a> how to install libraries. I think you cannot do it with homebrew and this is cer...
-1
2016-06-16T13:56:48Z
[ "python", "homebrew" ]
Python - installing a library using homebrew?
37,861,296
<p>I'm pretty new to the OSX environment and homebrew. I downloaded the QJson python library using <code>brew install qjson</code>.</p> <p>What are the next steps i need to take in order to be able to work with it in PyCharm?</p>
0
2016-06-16T13:52:58Z
37,862,696
<p>As others mentioned already: It's not the best idea - at least not in general - to install python packages via your systems package manager. It's better to use pip (ideally in conjunction with virtualenvs).</p> <p>Apart from that, it should be possible to use the package you installed using homebrew from pycharm / ...
0
2016-06-16T14:54:49Z
[ "python", "homebrew" ]
PyODBC, cursor.execute() won't insert parameters into SQL String
37,861,319
<p>I am using pypyodbc to insert data into a database and when I use the cursor.execute() command I try to put the sql string and the parameters, but I get the following error:</p> <pre> SELECT uid FROM HP_DATA WHERE( hpName = ? AND processID = ? AND ipAddress = ? AND port = ? AND usernameTried = ? AND passwordTr...
0
2016-06-16T13:54:18Z
37,866,362
<p>Use <a href="https://docs.python.org/3.5/library/datetime.html#strftime-strptime-behavior" rel="nofollow">datetime.strptime()</a> to convert the <code>attack_datetime</code> value to a <a href="https://docs.python.org/3.5/library/datetime.html#datetime-objects" rel="nofollow">datetime</a> object <em>before</em> pass...
2
2016-06-16T18:03:59Z
[ "python", "sql-server", "database", "pyodbc", "pypyodbc" ]
Python : How does `while` loop work in python when reading lines?
37,861,347
<p>How does <code>while</code> loop work in python when reading lines?</p> <pre><code>state=True #can be set to {anyInterger,True,False} while state: #do a task #if task done change state to exit loop </code></pre> <p>so depending on the <code>state</code> variable while loop is executed, and <code>type(state...
1
2016-06-16T13:56:02Z
37,861,392
<p>Whenever you use a variable as a condition to an <code>if</code> or a <code>while</code> loop it is evaluated as a boolean value. In Python an empty string is treated as <code>False</code>, therefore the <code>while</code> loop terminates.</p> <blockquote> <p>reason for not using while loop for this purpose would...
1
2016-06-16T13:58:08Z
[ "python", "while-loop" ]
Python : How does `while` loop work in python when reading lines?
37,861,347
<p>How does <code>while</code> loop work in python when reading lines?</p> <pre><code>state=True #can be set to {anyInterger,True,False} while state: #do a task #if task done change state to exit loop </code></pre> <p>so depending on the <code>state</code> variable while loop is executed, and <code>type(state...
1
2016-06-16T13:56:02Z
37,861,452
<p><code>f.readline()</code> is a generator object that returns <code>''</code> at the end of the file. But <code>''</code> has a falsy value:</p> <pre><code>&gt;&gt;&gt; f.readline() '' &gt;&gt;&gt; bool('') False </code></pre> <p>Hence, when the <code>while</code> evaluates the line at EOF (End Of File), the value ...
0
2016-06-16T14:00:13Z
[ "python", "while-loop" ]
Python : How does `while` loop work in python when reading lines?
37,861,347
<p>How does <code>while</code> loop work in python when reading lines?</p> <pre><code>state=True #can be set to {anyInterger,True,False} while state: #do a task #if task done change state to exit loop </code></pre> <p>so depending on the <code>state</code> variable while loop is executed, and <code>type(state...
1
2016-06-16T13:56:02Z
37,861,455
<p>Empty string is treated as <strong>False</strong> in python. So, it won't enter the loop. FYI the better way of looping over the lines is </p> <pre><code>line_data = [] for line in f.readlines(): line_data.append(line) </code></pre> <p>You can even do like this also.</p> <pre><code>with open('test.txt', 'r') ...
0
2016-06-16T14:00:18Z
[ "python", "while-loop" ]
Python : How does `while` loop work in python when reading lines?
37,861,347
<p>How does <code>while</code> loop work in python when reading lines?</p> <pre><code>state=True #can be set to {anyInterger,True,False} while state: #do a task #if task done change state to exit loop </code></pre> <p>so depending on the <code>state</code> variable while loop is executed, and <code>type(state...
1
2016-06-16T13:56:02Z
37,861,464
<p>There are a few implicit boolean conversions in Python.<br> 1) <code>bool(0)</code> evaluates to False, any other integers evaluate to <code>True</code><br> 2) <code>bool('')</code>, <code>bool([])</code>, <code>bool({})</code> also evaluate to <code>False</code>. This is useful to test whether a container has any i...
2
2016-06-16T14:00:37Z
[ "python", "while-loop" ]
Python : How does `while` loop work in python when reading lines?
37,861,347
<p>How does <code>while</code> loop work in python when reading lines?</p> <pre><code>state=True #can be set to {anyInterger,True,False} while state: #do a task #if task done change state to exit loop </code></pre> <p>so depending on the <code>state</code> variable while loop is executed, and <code>type(state...
1
2016-06-16T13:56:02Z
37,861,484
<p>You can add:</p> <pre><code>if len(line) &lt; 2: break </code></pre> <p>or alternatively:</p> <pre><code>if line == "''": break </code></pre>
-1
2016-06-16T14:01:37Z
[ "python", "while-loop" ]
extracting certain strings from a a file using python
37,861,439
<p>I have a file with some lines. Out of those lines I will choose only lines which starts with <code>xxx</code>. Now the lines which starts with <code>xxx</code> have pattern as follows:</p> <pre><code>xxx:(12:"pqrs",223,"rst",-90) xxx:(23:"abc",111,"def",-80) </code></pre> <p>I want to extract only the string whic...
0
2016-06-16T13:59:31Z
37,861,533
<p>Your code is wrongly indented. Your <code>f = f.readlines()</code> has 9 spaces in front while <code>for line in f:</code> has 4 spaces. It should look like below.</p> <pre><code>import re list_of_prefixes = ["xxx","aaa"] resulting_list = [] with open("raw.txt","r") as f: f = f.readlines() for line ...
0
2016-06-16T14:03:26Z
[ "python" ]
extracting certain strings from a a file using python
37,861,439
<p>I have a file with some lines. Out of those lines I will choose only lines which starts with <code>xxx</code>. Now the lines which starts with <code>xxx</code> have pattern as follows:</p> <pre><code>xxx:(12:"pqrs",223,"rst",-90) xxx:(23:"abc",111,"def",-80) </code></pre> <p>I want to extract only the string whic...
0
2016-06-16T13:59:31Z
37,861,868
<pre><code>results = [] with open("log.txt","r") as f: f = f.readlines() for line in f: if line.startswith("xxx"): line = line.split(":") # line[1] will be what is after : result = line[1].split(",")[0][1:-1] # will be pqrs results.append(result) </code></pre> <p>Yo...
0
2016-06-16T14:18:45Z
[ "python" ]
extracting certain strings from a a file using python
37,861,439
<p>I have a file with some lines. Out of those lines I will choose only lines which starts with <code>xxx</code>. Now the lines which starts with <code>xxx</code> have pattern as follows:</p> <pre><code>xxx:(12:"pqrs",223,"rst",-90) xxx:(23:"abc",111,"def",-80) </code></pre> <p>I want to extract only the string whic...
0
2016-06-16T13:59:31Z
37,861,909
<p>Well you are heading in the right direction.</p> <p>If the input is this simple, you can use regex groups.</p> <pre><code>with open("log.txt","r") as f: f = f.readlines() for line in f: line=line.rstrip() m = re.match('^xxx:\(\d*:("[^"]*")',line) if m is not None: print(...
0
2016-06-16T14:20:06Z
[ "python" ]
extracting certain strings from a a file using python
37,861,439
<p>I have a file with some lines. Out of those lines I will choose only lines which starts with <code>xxx</code>. Now the lines which starts with <code>xxx</code> have pattern as follows:</p> <pre><code>xxx:(12:"pqrs",223,"rst",-90) xxx:(23:"abc",111,"def",-80) </code></pre> <p>I want to extract only the string whic...
0
2016-06-16T13:59:31Z
37,862,058
<p>To check if a line starts with <em>xxx</em> do</p> <pre><code>line.startswith('xxx') </code></pre> <p>To find the text in first double-quotes do</p> <pre><code>re.search(r'"(.*?)"', line).group(1) </code></pre> <p>(as <code>match.group(1)</code> is the first parenthesized subgroup)</p> <p>So the code will be<...
0
2016-06-16T14:26:40Z
[ "python" ]
django-cms plugin edit css background image 'placeholder_attr' is not a valid tag library error
37,861,518
<p>i have istalled djangocms-css-background 1.0.3, run migrations and included <code>djangocms-css-background</code> in <code>settings.py</code></p> <p>in my template, i have the code below.</p> <pre><code>{% load placeholder_attr %} &lt;div style="{% placeholder_attr 'My Background Css Placeholder' 'CssBackground' ...
0
2016-06-16T14:03:05Z
37,861,765
<p>Your <code>load</code> statement should look:</p> <pre><code>{% load placeholder_tags placeholder_attr %} </code></pre> <p>Then do <code>pip install djangocms-placeholder-attr</code> and put <code>'djangocms-placeholder-attr'</code> in <code>INSTALLED_APPS</code></p>
0
2016-06-16T14:14:33Z
[ "python", "django", "django-cms" ]
django-cms plugin edit css background image 'placeholder_attr' is not a valid tag library error
37,861,518
<p>i have istalled djangocms-css-background 1.0.3, run migrations and included <code>djangocms-css-background</code> in <code>settings.py</code></p> <p>in my template, i have the code below.</p> <pre><code>{% load placeholder_attr %} &lt;div style="{% placeholder_attr 'My Background Css Placeholder' 'CssBackground' ...
0
2016-06-16T14:03:05Z
38,237,081
<p>djangocms-css-background depends on djangocms-placeholder-attr which has been <a href="https://github.com/WnP/djangocms-placeholder-attr" rel="nofollow">deprecated</a> Use <a href="https://pypi.python.org/pypi/cmsplugin-css-background/0.1.0" rel="nofollow">cmsplugin-css-background</a> instead. </p> <pre><code>{% wi...
1
2016-07-07T03:19:47Z
[ "python", "django", "django-cms" ]
Python alias/pointer file creation
37,861,587
<p>I have multiple directories that require the same large <code>json</code> file. Rather than storing the <code>json</code> file multiple times, I would like to store it in one directory and create an <code>alias</code> that points to the actual file in the other directories.</p> <p>How do I create a shortcut/alias f...
2
2016-06-16T14:05:50Z
37,861,627
<p>You can create a symlink to the file. In python this looks like:</p> <pre><code>import os os.symlink("my_json_file.json", "the_link"); </code></pre>
2
2016-06-16T14:07:53Z
[ "python", "directory" ]
Python sendemail() MIMEMultipart not working
37,861,598
<p>I have been trying step by step to create a python (v3.4) script to send a email with attachments. I already succesfully send one without attachmente using smtplib library. However, to add an attachment it seems that I need to create an MIMEMultipart object. Nothing weird until here.</p> <p>Based on examples I crea...
0
2016-06-16T14:06:38Z
37,862,646
<p>The problem is that your variable <code>toaddrs</code> is a list. </p> <p>You need to have the list of addresses as a string with the addresses separated by commas e.g.</p> <pre><code>msg['To'] = ",".join(toaddrs) </code></pre> <p>Everything should work fine after that. See here for more details: <a href="http:/...
0
2016-06-16T14:52:42Z
[ "python", "email", "python-3.4" ]
Generating random sparse data in the range 0-1
37,861,602
<p>I am trying to generate sparse 3 dimensional nonparametric datasets in the range 0-1, where the dataset should contain zeros as well. I tried to generate this using:</p> <pre><code>training_matrix = numpy.random.rand(3000, 3) </code></pre> <p>but it is not printing the data as 0.00000 in any of the rows.</p>
0
2016-06-16T14:06:47Z
37,861,982
<p>Since you want all 5 numbers to be zero, the probability of that occurring is 1/10^5 = 0.00001, with replacement. The probability of getting that is still negligible, even if you have 3000*3=9000 values. Something else you can try doing for your peace of mind is to generate random numbers and truncate them at a cert...
0
2016-06-16T14:23:21Z
[ "python", "apache-spark" ]
Generating random sparse data in the range 0-1
37,861,602
<p>I am trying to generate sparse 3 dimensional nonparametric datasets in the range 0-1, where the dataset should contain zeros as well. I tried to generate this using:</p> <pre><code>training_matrix = numpy.random.rand(3000, 3) </code></pre> <p>but it is not printing the data as 0.00000 in any of the rows.</p>
0
2016-06-16T14:06:47Z
37,862,462
<p>We start by creating an array of zeros of <code>nrows</code> rows by <code>3</code> columns:</p> <pre><code>import numpy as np nrows = 3000 # total number of rows training_matrix = np.zeros((nrows, 3)) </code></pre> <p>Then we randomly draw (without replacement) <code>nz</code> integers from <code>range(nrows)</...
0
2016-06-16T14:43:44Z
[ "python", "apache-spark" ]
GNU Parallel - Multiple arguments
37,861,665
<p>Using GNU <strong>parallel</strong>, I am trying to run a sub-sampling script that inputs two files and outputs a specific subsampled file. I am using this command:</p> <pre><code>parallel -j+0 --eta python sub_sample_.2.py ::: file1 file2 ::: file3 file4 ::: file5 file6 </code></pre> <p>But there's no ETA on the...
1
2016-06-16T14:10:13Z
37,973,015
<pre><code>parallel -j+0 --eta python sub_sample_.2.py ::: file1 file2 ::: file3 file4 ::: file5 file6 </code></pre> <p>2*2*2 = 8 jobs in total.</p> <pre><code>Computer:jobs running/jobs completed/%of started jobs/Average seconds to complete ETA: 0s Left 8 AVG:0.00s local:8/0/1005/0.0 </code></pre> <p>The ETA is com...
1
2016-06-22T15:56:13Z
[ "python", "shell", "gnu-parallel", "subsampling" ]
Deserializing a huge json string to python objects
37,861,698
<p>I am using simplejson to deserialize json string to python objects. I have a custom written object_hook that takes care of deserializing the json back to my domain objects.</p> <p>The problem is, when my json string is huge (i.e. the server is returning around 800K domain objects in the form of a json string), my p...
8
2016-06-16T14:11:23Z
37,901,596
<p>I don't know of any framework that offers what you seek out of the box, but you may apply a few optimizations to the way your class instance is setup.</p> <p>Since unpacking the dictionary into keyword arguments and applying them to your class variables is taking the bulk of the time, you may consider passing the <...
6
2016-06-18T21:03:16Z
[ "python", "json", "performance", "python-2.7", "simplejson" ]
SQL with regular expressions in python
37,861,848
<p>I am running this query in python. I do get the error "Invalid string literal" in the regular expression part. I know this regex is, not sure what syntax is missing here. Any help would be appreciated.</p> <pre><code>import pandas as pd import numpy as np import datetime from time import gmtime, strftime import smt...
-2
2016-06-16T14:17:50Z
37,861,922
<p>You're missing an <code>r</code></p> <p><code>REGEXP_EXTRACT(path, r'ActName:([\s\S\w\W]*?)ActDomain:') AS ActName</code></p>
1
2016-06-16T14:20:43Z
[ "python", "sql", "google-bigquery" ]
How to unit test a method that returns a JSON object?
37,861,935
<p>I have two Python scripts: let's call them program.py and program_utils.py.</p> <p>program.py looks like this:</p> <pre><code>from flask import Flask, request, jsonify import program_utils app = Flask(__name__) @app.route('/mypage') def my_func(): # Do some stuff here and get a URL parameter my_var = request....
2
2016-06-16T14:21:06Z
37,862,186
<p>You use the test client to test Flask views. Create it with <code>app.test_client()</code> and then use it to simulate requests to your routes. The response only has the raw data, if you want to compare it as JSON you'll need to load it.</p> <pre><code>c = app.test_client() rv = c.get('/mypage', query_string={'my...
4
2016-06-16T14:31:09Z
[ "python", "json", "unit-testing", "flask" ]
Adding a description label to native QFileDialog
37,861,941
<p>I want a description text(Qlabel) to be added to the native QFileDialog just like this <a href="http://i.stack.imgur.com/9eLXs.jpg" rel="nofollow">eclipse browse funtionality</a>. Though we can add widgets by subclassing and adding to the default layout it works only if DontUseNativeDialog is set. But I want this to...
0
2016-06-16T14:21:17Z
37,865,147
<p>It won't be a separate <code>QLabel</code>, but you can set the dialog title text to be a description. I'm not sure how it appears on macs though (like it does in that eclipse dialog).</p> <pre><code>QtGui.QFileDialog.getSaveFileName(parent, 'This is a description') </code></pre>
0
2016-06-16T16:54:06Z
[ "python", "qt", "pyqt", "qfiledialog" ]
tornado server : Nameerror global name not defined
37,861,946
<p>I am rendering a HTML page from Tornado server:</p> <pre><code>class IndexHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): self.render("neo4j-panama_tornado.html") class WebSocketHandler(tornado.websocket.WebSocketHandler): def open(self): print("WebSocket o...
0
2016-06-16T14:21:34Z
37,862,564
<p>Tornado is attempting to render your HTML file as a template; hence it's looking up "var" in the template namespace and doesn't find it. You need to use a static file handler for "/" instead:</p> <pre><code>app = tornado.web.Application([ (r"/?()", web.StaticFileHandler, {'path': 'templates', ...
0
2016-06-16T14:48:40Z
[ "python", "html", "angularjs", "tornado" ]
Is there an operation for not less than or not greater than in python?
37,862,030
<p>Consider a following snippet:</p> <pre><code>a = 0 if a == 0 or a &gt; 0: print(a) </code></pre> <p>Essentially, I want to do something when <code>a</code> is not negative. If instead of this, I had wanted to do something when <code>a</code> is not <code>0</code>, I would have simply written:</p> <pre><code>i...
-4
2016-06-16T14:25:38Z
37,862,059
<p>Well, instead of <code>a==0 or a&gt;0</code> you could just use <code>a&gt;=0</code>. That should be close to what you're looking for :P</p>
6
2016-06-16T14:26:41Z
[ "python", "comparison-operators" ]
Is there an operation for not less than or not greater than in python?
37,862,030
<p>Consider a following snippet:</p> <pre><code>a = 0 if a == 0 or a &gt; 0: print(a) </code></pre> <p>Essentially, I want to do something when <code>a</code> is not negative. If instead of this, I had wanted to do something when <code>a</code> is not <code>0</code>, I would have simply written:</p> <pre><code>i...
-4
2016-06-16T14:25:38Z
37,862,104
<blockquote> <p>I was surprised to see that this particular operation does not exist in Python!</p> </blockquote> <p>I'm not familiar with any language that does have this operator. It is simply not needed.</p> <p>As for your snippets:</p> <p><code>if a == 0 or a &gt; 0</code></p> <p>It is exactly the same as <co...
2
2016-06-16T14:28:16Z
[ "python", "comparison-operators" ]
Is there an operation for not less than or not greater than in python?
37,862,030
<p>Consider a following snippet:</p> <pre><code>a = 0 if a == 0 or a &gt; 0: print(a) </code></pre> <p>Essentially, I want to do something when <code>a</code> is not negative. If instead of this, I had wanted to do something when <code>a</code> is not <code>0</code>, I would have simply written:</p> <pre><code>i...
-4
2016-06-16T14:25:38Z
37,862,105
<p>You can use the equal or greater than operator:</p> <pre><code>if a &gt;= 0: print(a) </code></pre>
2
2016-06-16T14:28:18Z
[ "python", "comparison-operators" ]
convert dictionary to sparse matrix
37,862,139
<p>I have a dictionary with keys as user_ids and values as list of movie_ids liked by that user with #unique_users = 573000 and # unique_movies =16000. </p> <blockquote> <p>{1: [51, 379, 552, 2333, 2335, 4089, 4484], 2: [51, 379, 552, 1674, 1688, 2333, 3650, 4089, 4296, 4484], 5: [783, ...
2
2016-06-16T14:29:43Z
37,862,364
<p>I think you can construct an empty <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.sparse.dok_matrix.html" rel="nofollow">dok_matrix</a> and fill the values. Then transpose it and convert it to <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.sparse.csr_matrix.html"...
1
2016-06-16T14:39:54Z
[ "python", "dictionary", "matrix" ]
convert dictionary to sparse matrix
37,862,139
<p>I have a dictionary with keys as user_ids and values as list of movie_ids liked by that user with #unique_users = 573000 and # unique_movies =16000. </p> <blockquote> <p>{1: [51, 379, 552, 2333, 2335, 4089, 4484], 2: [51, 379, 552, 1674, 1688, 2333, 3650, 4089, 4296, 4484], 5: [783, ...
2
2016-06-16T14:29:43Z
37,862,976
<pre><code>df = {1: [51, 379, 552, 2333, 2335, 4089, 4484], 2: [51, 379, 552, 1674, 1688, 2333, 3650, 4089, 4296, 4484], 5: [783, 909, 1052, 1138, 1147, 2676], 7: [171, 321, 959], 9: [3193], 10: [959], 11: [131,567,897,923],..........} df2 = pd.DataFrame.from_dict(df, orient='index') df2 = df2.stack().reset_index() df2...
0
2016-06-16T15:07:25Z
[ "python", "dictionary", "matrix" ]
convert dictionary to sparse matrix
37,862,139
<p>I have a dictionary with keys as user_ids and values as list of movie_ids liked by that user with #unique_users = 573000 and # unique_movies =16000. </p> <blockquote> <p>{1: [51, 379, 552, 2333, 2335, 4089, 4484], 2: [51, 379, 552, 1674, 1688, 2333, 3650, 4089, 4296, 4484], 5: [783, ...
2
2016-06-16T14:29:43Z
37,864,318
<p>You can create <code>csr_matrix</code> at once (like this format: <code>csr_matrix((data, (row_ind, col_ind))</code>). Here is a snippet on how to do that.</p> <pre><code>import scipy.sparse as sp d = {0: [0,1], 1: [1,2,3], 2: [3,4,5], 3: [4,5,6], 4: [5,6,7], 5: [7], 6: [7,8,9]} row_ind = [k for k...
0
2016-06-16T16:10:15Z
[ "python", "dictionary", "matrix" ]
Error while converting tuples to Pandas DataFrame
37,862,141
<p>When i try to convert tuples to pandas dataframe i get the following error:</p> <blockquote> <p>DataFrame constructor not properly called!</p> </blockquote> <p>I am using the following code</p> <pre><code>columnlist=["Timestamp","Price","Month","Day","DayofWeek","tDaysleftMonth","tDayinMonth","tDayinWeek"] tick...
1
2016-06-16T14:29:45Z
37,862,313
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html" rel="nofollow"><code>DataFrame.from_records</code></a> with converting <code>tuples</code> to <code>list</code>:</p> <pre><code>import pandas as pd tuples = ((1,2,3),(4,6,7),(7,3,6),(8,2,7),(4,6,3...
0
2016-06-16T14:37:25Z
[ "python", "pandas", "dataframe", "tuples" ]
Error while converting tuples to Pandas DataFrame
37,862,141
<p>When i try to convert tuples to pandas dataframe i get the following error:</p> <blockquote> <p>DataFrame constructor not properly called!</p> </blockquote> <p>I am using the following code</p> <pre><code>columnlist=["Timestamp","Price","Month","Day","DayofWeek","tDaysleftMonth","tDayinMonth","tDayinWeek"] tick...
1
2016-06-16T14:29:45Z
37,862,563
<p>According to the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">Dataframe documentation page</a>, data is required to be</p> <blockquote> <p>numpy ndarray (structured or homogeneous), dict, or DataFrame</p> </blockquote> <p>The easiest way to resolve your pro...
0
2016-06-16T14:48:37Z
[ "python", "pandas", "dataframe", "tuples" ]
Spark tunables specially executor-memory
37,862,385
<p><code>time ../bin/spark-submit --master yarn --deploy-mode cluster --driver-memory 2g --executor-memory 3G --num-executors 100 /var/tmp/learning/Movie-Similarities-1m-hdfs.py 260</code>​​ </p> <p>took: 6m5.293s​</p> <p><code>time ../bin/spark-submit --master yarn --deploy-mode cluster --driver-memory 2g ...
0
2016-06-16T14:40:55Z
37,863,947
<blockquote> <p>Any observations on these results?</p> </blockquote> <p>Your code is running faster with more executors (with less memory) than fewer executors (with more memory). There generally is an optimal balance that will be dependent on the workflow and the cluster's hardware. The only way to really find this...
0
2016-06-16T15:53:27Z
[ "python", "hadoop", "apache-spark" ]
Object is not recognized while performing a mapreduce job
37,862,394
<p>Im trying to run a simple map reduce job and got the following datasets:</p> <p>bike.txt</p> <pre><code>1 Bike 1 2 Bike 2 3 Bike 4 4 Bike 4 5 Bike 4 </code></pre> <p>bikenames.txt</p> <pre><code>1,Aap 2,Noot 3,Greet 4,Mies 5,Gazelle </code></pre> <p>My aim is to write a mapreduce job that out the name...
0
2016-06-16T14:41:13Z
37,862,511
<p><code>bikeNames</code> is only defined in <code>reducer_init()</code>, so this function must not be getting called. Anyway, it's not really an initialization function for each step; it looks more like initialization for the job.</p> <p>Change the function name from <code>reducer_init</code> to <code>__init__</code>...
1
2016-06-16T14:45:58Z
[ "python", "mapreduce" ]
calling multiple functions to main issue
37,862,433
<p>Okay, so I am having a little issue with calling 4 function to the main. I have been sitting here for over an hour and cannot figure it out.</p> <p>I keep on getting this error: </p> <p><code>(total) = total(num, num2) UnboundLocalError: local variable 'total' referenced before assignment</code></p> <pre><code>de...
-2
2016-06-16T14:42:43Z
37,896,970
<p>Your function describes what you are trying to do, there is no reason to create local variables in your functions if you won't even use them. </p> <pre><code>def total(num, num2): return num+num2 def difference(num, num2): return abs(num - num2) def product(num, num2): return num*num2 def quotient(nu...
0
2016-06-18T12:30:42Z
[ "python", "function" ]
How can I read the docstring/help of a python module from cmd?
37,862,444
<p>Consider that you are in the Windows command prompt or similar command line environment. How can you get info about a Python module from its docstring printed to the console?</p>
1
2016-06-16T14:43:14Z
37,862,445
<h2><strong>The Shortut (Hack)</strong></h2> <p>Generally (in 2.7):</p> <pre><code>python -c"print 'Hello world'" </code></pre> <p>(in 3.x):</p> <pre><code>python -c"print('Hello world')" </code></pre> <p>will output: <code>Hello world</code></p> <p>But if you pass <code>-c</code> as an argument into a module, so...
0
2016-06-16T14:43:14Z
[ "python", "cmd", "command-line-arguments", "manual" ]
How can I read the docstring/help of a python module from cmd?
37,862,444
<p>Consider that you are in the Windows command prompt or similar command line environment. How can you get info about a Python module from its docstring printed to the console?</p>
1
2016-06-16T14:43:14Z
37,863,008
<p>If you mean print interactively, just start python without any arguments to get a REPL (read–eval–print loop).</p> <pre><code>python import mypackage help(mypackage) dir(mypackage) </code></pre> <p>executed one after another and so forth.</p> <p>If you mean programmatically, see @noumenal's answer. </p>
0
2016-06-16T15:08:44Z
[ "python", "cmd", "command-line-arguments", "manual" ]
How can I read the docstring/help of a python module from cmd?
37,862,444
<p>Consider that you are in the Windows command prompt or similar command line environment. How can you get info about a Python module from its docstring printed to the console?</p>
1
2016-06-16T14:43:14Z
38,074,632
<p>We should follow coding standards like proper commenting for individual line of code, so that each user can understand the working/functionality of automation script code. Docstring in Python is helpful text to get info about the module or method. For example: We have a file name as "addio.py" placed in E drive fold...
0
2016-06-28T11:11:51Z
[ "python", "cmd", "command-line-arguments", "manual" ]
Controlling a CLI program with Python
37,862,459
<p>I'm using Python 3.5 and I'd like to run a program that is normally run within cmd.exe or powershell. This program is not in the environment PATH, and I'd like to avoid adding it.</p> <p>I need to start the program and then just pass two or three word commands within the program.</p> <p>I've looked on Stack Excha...
0
2016-06-16T14:43:42Z
37,867,276
<p>You might look into the experimental support for Windows that was recently added to the pexpect package:</p> <p><a href="http://pexpect.readthedocs.io/en/stable/overview.html#windows" rel="nofollow">http://pexpect.readthedocs.io/en/stable/overview.html#windows</a></p> <p>If that doesn't meed your needs, the winpex...
0
2016-06-16T18:55:08Z
[ "python", "shell", "powershell", "command-line", "automation" ]
Stripping HTML tags form string keeping/removing the text in between
37,862,521
<p>I'd like to clean up some html in python 3 where I used some span tags to mark inserted text with a color and strikethrough deleted text. An example:</p> <pre><code>&lt;p&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed...
0
2016-06-16T14:46:21Z
37,863,883
<p>You are almost right. You just need to use the <a href="https://docs.python.org/3/library/html.parser.html#html.parser.HTMLParser.handle_starttag" rel="nofollow"><code>handle_starttag()</code></a> and <a href="https://docs.python.org/3/library/html.parser.html#html.parser.HTMLParser.handle_endtag" rel="nofollow"><co...
0
2016-06-16T15:50:26Z
[ "python", "python-3.x", "text-processing", "python-textprocessing" ]
Copy command postgres append to csv file
37,862,601
<p>I have a COPY command in psycopg2 which I am running in a loop. I wanted to know how can I append to CSV rather than performing fresh copy everytime.</p> <p>code: </p> <pre><code>while True: cur.execute("COPY (SELECT id,a,b,c,d from t1,t2 WHERE date&gt;= TIMESTAMP TIMESTAMP %(t)s AND date &lt; TIMESTAMP %(t)s...
0
2016-06-16T14:50:36Z
37,865,085
<p>This is an ugly hack (only works on unix)</p> <pre><code>COPY table_one(id) TO PROGRAM 'cat - &gt;/tmp/onetwo.out' ; COPY table_two(id) TO PROGRAM 'cat - &gt;&gt;/tmp/onetwo.out' ; </code></pre>
0
2016-06-16T16:51:09Z
[ "python", "postgresql", "psycopg2" ]
Pass window.location to Flask url_for
37,862,640
<p>I'm using python.On my page when an anonymous user goes to the sign in page, I want to pass a variable to the backend so it indicates where the user is coming from ( send the URL).</p> <p>So when the user clicks on this anchor link: </p> <pre><code>&lt;a href="{{ url_for('account.signin') }}"&gt;Sign in&lt;/a&gt; ...
2
2016-06-16T14:52:23Z
37,862,785
<p>Assuming you're using Django.</p> <p>In your view you can return the previous location that the User can from:</p> <pre><code>from django.http import HttpResponseRedirect def foo(request, *a, **kw): # sign in user return HttpResponseRedirect(request.META.get('HTTP_REFERER')) </code></pre> <p>Or with Jque...
3
2016-06-16T14:58:56Z
[ "javascript", "python", "url", "flask" ]
Pass window.location to Flask url_for
37,862,640
<p>I'm using python.On my page when an anonymous user goes to the sign in page, I want to pass a variable to the backend so it indicates where the user is coming from ( send the URL).</p> <p>So when the user clicks on this anchor link: </p> <pre><code>&lt;a href="{{ url_for('account.signin') }}"&gt;Sign in&lt;/a&gt; ...
2
2016-06-16T14:52:23Z
37,863,301
<p>Use <a href="http://flask.pocoo.org/docs/0.11/api/#flask.Request.path" rel="nofollow"><code>request.path</code></a> to get the path while rendering the template.</p> <pre><code>&lt;a href="{{ url_for('account.signin') }}?next={{ request.path }}"&gt;Sign in&lt;/a&gt; </code></pre>
4
2016-06-16T15:21:56Z
[ "javascript", "python", "url", "flask" ]
Pass window.location to Flask url_for
37,862,640
<p>I'm using python.On my page when an anonymous user goes to the sign in page, I want to pass a variable to the backend so it indicates where the user is coming from ( send the URL).</p> <p>So when the user clicks on this anchor link: </p> <pre><code>&lt;a href="{{ url_for('account.signin') }}"&gt;Sign in&lt;/a&gt; ...
2
2016-06-16T14:52:23Z
37,870,026
<p>I think you should use the <code>request</code> object at its best, since it does provide a <a href="http://flask.pocoo.org/docs/0.11/api/#flask.Request.headers" rel="nofollow"><code>headers</code></a> dictionary which has all request headers, quoting from flask's Docs:</p> <blockquote> <p><code>headers</code></p...
1
2016-06-16T21:58:20Z
[ "javascript", "python", "url", "flask" ]
Sorting/Deleting File Lines - Python
37,862,666
<p>I was wanting to get rid of lines in a file that were less than 6 characters, and delete the whole line that had a string less than 6 characters. I tried running this code, but it ended up deleting the whole text file. How would I go about this?</p> <p>Code:</p> <pre><code>import linecache i = 1 while i &lt; 5: ...
0
2016-06-16T14:53:39Z
37,863,105
<p>You'll want to use the open method instead of the linecache:</p> <pre><code>def deleteShortLines(): text = 'file.txt' f = open(text) output = [] for line in f: if len(line) &gt;= 6: output.append(line) f.close() f = open(text, 'w') f.writelines(output) f.close() </code></pre>
2
2016-06-16T15:12:59Z
[ "python", "string", "file", "line" ]
Sorting/Deleting File Lines - Python
37,862,666
<p>I was wanting to get rid of lines in a file that were less than 6 characters, and delete the whole line that had a string less than 6 characters. I tried running this code, but it ended up deleting the whole text file. How would I go about this?</p> <p>Code:</p> <pre><code>import linecache i = 1 while i &lt; 5: ...
0
2016-06-16T14:53:39Z
37,863,155
<p>Done with iterators instead of lists to support very long files:</p> <pre><code>with open('file.txt', 'r') as input_file: # iterating over a file object yields its lines one at a time # keep only lines with at least 6 characters filtered_lines = (line for line in input_file if len(line) &gt;= 6) #...
1
2016-06-16T15:15:48Z
[ "python", "string", "file", "line" ]
Django 1.9 how to import in __init__.py
37,862,725
<p>I've updated from Django 1.8 to 1.9.</p> <p><strong>apps/comment/__init__.py (in 1.8)</strong></p> <pre><code>from .models import Mixin </code></pre> <p>In Django 1.9 this no longer works but I still want to import <code>Mixin</code> in the same way. </p> <p>So I tried this:</p> <p><strong>apps/comment/__init__...
1
2016-06-16T14:56:14Z
37,863,256
<p>Adding <code>from .models import CommentMixin</code> imports <code>CommentMixin</code> so that you can use it inside the <code>ready()</code> method. It does not magically add it to the <code>comment</code> module so that you can access it as <code>comments.CommentMixin</code></p> <p>You could assign it to the <cod...
1
2016-06-16T15:20:00Z
[ "python", "django", "django-1.9" ]
How would I be able to convert table structured data to a dict/graph structure in python/pandas, to be used for force graphs in D3?
37,862,834
<p>I'm stuck in converting this csv:</p> <pre><code>"","Destination","Source" "1","New York","Chicago" "2","Denver","Chicago" "3","Los Angeles","Boston" "4","Colorado","Indianapolis" </code></pre> <p>to a format like this:</p> <pre><code>[ { "name": "Chicago", "target": [ 1, ...
2
2016-06-16T15:01:29Z
37,863,518
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html" rel="nofollow"><code>to_dict</code></a>, but before need create proper <code>df</code>:</p> <pre><code>df['nan'] = 'none' df['Source'] = df.Source.astype(str) df.reset_index(inplace=True) df = pd.lreshape(df,...
0
2016-06-16T15:32:08Z
[ "python", "pandas", "d3.js", "graph", "dataframe" ]
How would I be able to convert table structured data to a dict/graph structure in python/pandas, to be used for force graphs in D3?
37,862,834
<p>I'm stuck in converting this csv:</p> <pre><code>"","Destination","Source" "1","New York","Chicago" "2","Denver","Chicago" "3","Los Angeles","Boston" "4","Colorado","Indianapolis" </code></pre> <p>to a format like this:</p> <pre><code>[ { "name": "Chicago", "target": [ 1, ...
2
2016-06-16T15:01:29Z
37,864,619
<p>Check if this does what you want</p> <pre><code>import csv reader=csv.reader(open("data.csv","rb")) next(reader) x,y={},set() for r in reader: a,b,c=r x.update({a:c}) y.update([b,c]) anss =dict((new_key,[k for k,v in x.iteritems() if new_key==v]) for new_key in y) result=[{"name":k,"target":v} for k,v ...
0
2016-06-16T16:24:57Z
[ "python", "pandas", "d3.js", "graph", "dataframe" ]
Subtree Extraction NLTK Tree
37,862,845
<p>I need a little help with NLTK trees.</p> <p>I am trying to extract some subtrees from this french tree:</p> <p><img src="http://i.stack.imgur.com/T1Oac.png" alt="Original Tree"></p> <pre class="lang-none prettyprint-override"><code>(SENT (NP-SUJ↓ (PRO=H Personne)) (VN=H (ADV* ne) (V=H sait)) (ADV* exactement) ...
2
2016-06-16T15:01:56Z
37,870,525
<p>I can't say I understand your complaint about <code>parent()</code> (perhaps you meant <code>subtrees()</code>?), but there are easier ways to get your hands on subtrees:</p> <ol> <li><p>Superficial improvement: The <code>subtrees()</code> function accepts a <code>filter</code> argument, so you don't have to check ...
2
2016-06-16T22:41:06Z
[ "python", "nltk", "subtree" ]
Sum of Squares - np.inner vs squaring first, then summing
37,863,087
<p>I was surprised that calling <code>np.inner</code> to compute a sum of squares was about 5x faster than calling <code>np.sum</code> on a pre-computed array of squares:</p> <p><a href="http://i.stack.imgur.com/9ns9A.png"><img src="http://i.stack.imgur.com/9ns9A.png" alt="sum of squares code"></a></p> <p>Any insight...
7
2016-06-16T15:12:21Z
37,910,111
<p>To check in which modules <code>np.inner</code> and <code>np.sum</code> are implemented I type</p> <pre><code>&gt;&gt;&gt; np.inner.__module__ 'numpy.core.multiarray' &gt;&gt;&gt; np.sum.__module__ 'numpy.core.fromnumeric' &gt;&gt;&gt; np.__file__ '/Users/uweschmitt/venv_so/lib/python3.5/site-packages/numpy/__init_...
5
2016-06-19T17:48:48Z
[ "python", "numpy" ]
SQL Server temp table not available in pyodbc code
37,863,125
<p>I'm running a series of complex sql queries in python and it involves temp tables. My auto-commit method doesn't seem to be working to retrieve the data from the temp table. The code snippet I'm using below and this is the output I'm getting: </p> <pre><code>testQuery=""" Select top 10 * INTO #Temp1 FRO...
2
2016-06-16T15:13:54Z
37,865,618
<p>I asked a colleague about this live and his suggestions worked. So I went and changed the testQuery to create a global temp table instead of a local (##Temp1 instead of #Temp1). And went to sql server to test whether the temp table was actually being created-it was. So I isolated that the problem was the second curs...
1
2016-06-16T17:19:23Z
[ "python", "sql", "sql-server", "database-connection", "pyodbc" ]
SQL Server temp table not available in pyodbc code
37,863,125
<p>I'm running a series of complex sql queries in python and it involves temp tables. My auto-commit method doesn't seem to be working to retrieve the data from the temp table. The code snippet I'm using below and this is the output I'm getting: </p> <pre><code>testQuery=""" Select top 10 * INTO #Temp1 FRO...
2
2016-06-16T15:13:54Z
39,257,181
<p>Best way to go about this is to start your SQL query with:</p> <p>"SET NOCOUNT ON"</p> <p>This will output the desired data</p>
0
2016-08-31T19:03:30Z
[ "python", "sql", "sql-server", "database-connection", "pyodbc" ]
SQL Server temp table not available in pyodbc code
37,863,125
<p>I'm running a series of complex sql queries in python and it involves temp tables. My auto-commit method doesn't seem to be working to retrieve the data from the temp table. The code snippet I'm using below and this is the output I'm getting: </p> <pre><code>testQuery=""" Select top 10 * INTO #Temp1 FRO...
2
2016-06-16T15:13:54Z
39,278,050
<p>Even though this question has a "solution", i.e., using global temp table instead of a local temp table, future readers might benefit from understanding why the problem happened in the first place.</p> <p>A temporary table is automatically dropped when the last connection using said table is closed. The difference ...
0
2016-09-01T17:56:07Z
[ "python", "sql", "sql-server", "database-connection", "pyodbc" ]
Image and Sound (Media) not showing on django
37,863,197
<p>I am trying to play an audio in django but it cannot find the audio file. I have setup the MEDIA_URL and MEDIA_ROOT but it still doesn't work. Please help me. Below is the code snippet</p> <p>settings.py</p> <pre><code>STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join...
0
2016-06-16T15:17:50Z
37,863,270
<p>You're not actually requesting those elements under MEDIA_URL, as you can see from the log file.</p> <p>That's because you haven't actually passed those variables to the template, so they are being ignored. </p>
0
2016-06-16T15:20:33Z
[ "python", "django", "media" ]
Image and Sound (Media) not showing on django
37,863,197
<p>I am trying to play an audio in django but it cannot find the audio file. I have setup the MEDIA_URL and MEDIA_ROOT but it still doesn't work. Please help me. Below is the code snippet</p> <p>settings.py</p> <pre><code>STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join...
0
2016-06-16T15:17:50Z
37,864,236
<p>You need to add media template context processor in your settings.py file:</p> <pre><code>TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'django.template.context_processors.media', ], }, }, ] </code></pre> <p>Then...
0
2016-06-16T16:06:54Z
[ "python", "django", "media" ]
Image and Sound (Media) not showing on django
37,863,197
<p>I am trying to play an audio in django but it cannot find the audio file. I have setup the MEDIA_URL and MEDIA_ROOT but it still doesn't work. Please help me. Below is the code snippet</p> <p>settings.py</p> <pre><code>STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join...
0
2016-06-16T15:17:50Z
37,864,320
<p>I got the answer from this thread <a href="http://stackoverflow.com/questions/5517950/django-media-url-and-media-root">Django MEDIA_URL and MEDIA_ROOT</a></p> <p>What I did is added this line "django.core.context_processors.media" in settings.py inside Template Context_Processor. </p> <p>Here </p> <pre><code>TEMP...
0
2016-06-16T16:10:18Z
[ "python", "django", "media" ]
What's the difference between for w in words[:] and for w in words[] in Python
37,863,246
<p>①</p> <pre><code>words = ['Hello','Python','Java'] for item in words: if len(item) &gt; 4: words.insert(0,item) </code></pre> <p>②</p> <pre><code>words = ['Hello','Python','Java'] for item in words[:]: if len(item) &gt; 4: words.insert(0,item) </code></pre> <p>The ① source can't r...
-2
2016-06-16T15:19:31Z
37,864,023
<p>I'm working off the assumption that you meant your first one to read <code>for item in words:</code>.</p> <p><code>words[:]</code> makes a copy of the list words and then iterates over that copy. Then, your code modifies the original list.</p> <p>The first one iterates over the original list and modifies the list ...
0
2016-06-16T15:56:44Z
[ "python" ]
Reverse a python dictionary ordered pairs
37,863,253
<p>This question has been asked many times, and I searched diligently to no avail. Here is an example of my question:</p> <p><code>dict = {"a":"1", "b":"2", "c":"3"}</code></p> <p>The output I am looking for is as below:</p> <p><code>dict = {"c":"3", "b":"2", "a":"1"}</code></p> <p>I am really unsure how to attack...
-3
2016-06-16T15:19:54Z
37,863,333
<p>A <a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary</a> is unordered <em>by definition</em>:</p> <blockquote> <p>It is best to think of a dictionary as an <strong>unordered set of key: value pairs</strong>, with the requirement that the keys are unique (within...
0
2016-06-16T15:23:43Z
[ "python", "python-2.7", "sorting", "dictionary", "reverse" ]
Reverse a python dictionary ordered pairs
37,863,253
<p>This question has been asked many times, and I searched diligently to no avail. Here is an example of my question:</p> <p><code>dict = {"a":"1", "b":"2", "c":"3"}</code></p> <p>The output I am looking for is as below:</p> <p><code>dict = {"c":"3", "b":"2", "a":"1"}</code></p> <p>I am really unsure how to attack...
-3
2016-06-16T15:19:54Z
37,884,169
<p>Firstly, the <code>dict</code> object of python is a hashtable, so It have no order. but if you only want to get a list is order you can use <code>sorted(iterable, key=None, reverse=False)</code> method. <code> def order(dic): return sorted(dic.items(),key=lambda x:x[1],reverse=True) </code></p>
0
2016-06-17T14:30:07Z
[ "python", "python-2.7", "sorting", "dictionary", "reverse" ]
3D *.stl surface model convert to 2D image stack?
37,863,327
<p>OK to start with let me be clear, I am not interested in converting an image stack into a 3D model.</p> <p>I have an *.stl file (a triangulated surface mesh) &amp; I would like to slice it back into an image stack. I've had a look at Slic3r &amp; Meshmixer but they both only give out Gcode.</p> <p>So given I have ...
0
2016-06-16T15:23:17Z
37,880,049
<p>For example if you got your mesh to render with <strong>OpenGl</strong> (by any means inside your app) then to get your slice you would simply:</p> <ol> <li><strong>set your camera so screen projection plane is parallel to the slice...</strong></li> <li><strong>clear screen buffer as usual with <code>glClearColor</...
1
2016-06-17T11:07:43Z
[ "python", "c++", "graphics", "3d", "imaging" ]
I am unable to clone a bitbucket repository that I have write access level
37,863,354
<p>I have multiple ssh on my computer (not really sure how to say this), and believe this could be the reason I cannot pull, push, or clone using pycharm. </p> <p>when I type this code into terminal: </p> <pre><code>git clone ssh://git@bitbucket.org:#####/#######.git </code></pre> <p>I get the error: </p> <pre><cod...
0
2016-06-16T15:24:28Z
37,864,219
<p>Maybe you could try in another way, it would be easier to clone a repository</p> <p>try this:</p> <pre><code>git clone https://example@bitbucket... </code></pre> <p>in this way u could clone the repository without ssh keys</p> <p>what's more, you could check the website below:</p> <p><a href="https://confluence...
1
2016-06-16T16:06:05Z
[ "python", "git", "ssh", "pycharm", "bitbucket" ]
Reading items with multiple items in same line
37,863,365
<p>I'm trying to get my program to read an infile and plot it out on a graph. It worked when the infile contained only one item per line, but in this new file, there are multiple items in the same line:</p> <blockquote> <p>Line 1: -4.6653184e-01 -3.9003953e-01 -1.3689525e+00 -2.9784036e-01 -1.2366933e+00 -1.44...
1
2016-06-16T15:25:02Z
37,863,586
<p>That's because <code>.readlines()</code> is doing just that; it will take all of the values that it finds on a single line and append it to your list as a single item. Instead, in each of your lines, you need an additional step that separates out each number in the line based on the delimiter. For this we can use <...
0
2016-06-16T15:34:59Z
[ "python", "file-io", "rows" ]
Reading items with multiple items in same line
37,863,365
<p>I'm trying to get my program to read an infile and plot it out on a graph. It worked when the infile contained only one item per line, but in this new file, there are multiple items in the same line:</p> <blockquote> <p>Line 1: -4.6653184e-01 -3.9003953e-01 -1.3689525e+00 -2.9784036e-01 -1.2366933e+00 -1.44...
1
2016-06-16T15:25:02Z
37,863,621
<p>It depends on what you want to do. From the lines you've pasted, if you want to pick all the values as a <strong>single dataset</strong> you could substitute what you have with: </p> <pre><code>lines = [] [lines.extend(_.split()) for _ in fd.readlines()] print lines </code></pre> <p>This will give you one value pe...
0
2016-06-16T15:36:20Z
[ "python", "file-io", "rows" ]
Reading items with multiple items in same line
37,863,365
<p>I'm trying to get my program to read an infile and plot it out on a graph. It worked when the infile contained only one item per line, but in this new file, there are multiple items in the same line:</p> <blockquote> <p>Line 1: -4.6653184e-01 -3.9003953e-01 -1.3689525e+00 -2.9784036e-01 -1.2366933e+00 -1.44...
1
2016-06-16T15:25:02Z
37,863,677
<p>If all the values are separated by whitespace, you can simply use</p> <pre><code>for line in lines: items = line.split() </code></pre> <p>If they are separated by something else, use <code>line.split(separator)</code>. This will split the string at every occurence of <code>separator</code> (if no separator is ...
0
2016-06-16T15:39:17Z
[ "python", "file-io", "rows" ]
Is panda's DataFrame suitable for this?
37,863,410
<p>Let's depict my scenario:</p> <p>I'm trying to make an analysis on several APIs for a given set of samples. Thus, in the end, I'm picturing this as follows in my mind:</p> <p>A 2D table where each row is the name of each sample, and where each column is the name of each API. On each of this table, I will end up ha...
1
2016-06-16T15:27:17Z
37,863,889
<p>Yes, you would want to use a <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html" rel="nofollow"><code>MultiIndex</code></a> where the <code>index</code> levels contain a <code>sample_id</code> and the <code>api_id</code>, and then you have two columns containing the <code>tag</code> and the associate...
1
2016-06-16T15:50:45Z
[ "python", "pandas", "dataframe", "multi-index" ]
On a Mac how do I remove Openpyxl when it has already been installed before using sudo pip install openpyxl?
37,863,438
<p>Previously openpyxl was installed on a mac. I need to remove it or fix it because it seems to be broken and then I want to reinstall it. Every time i try <code>easy_install -m openpyxl</code> it doesn't work or doing a new install doesn't work. I receive a syntax error. </p> <pre><code>/Library/Frameworks/Python.fr...
0
2016-06-16T15:28:25Z
37,863,522
<p>You can try uninstalling it first using pip with the command <code>sudo pip uninstall openpyxl</code>.</p> <p>Having said that, it looks like the error is because you're using Python 2.5 and "as" became a reserved keyword in Python 2.6. Your best bet is to install a new version of Python and install openpyxl, or fi...
2
2016-06-16T15:32:19Z
[ "python", "pip", "openpyxl" ]
Efficient way to untranspose the bit of an integer array?
37,863,458
<p>Consider 3 integers of 2 bits, stored in an array</p> <pre><code>x1 = [ ad, be, cf, ] </code></pre> <p>The integers are shown above with their bits, but they are stored as regular <code>int</code>.<br> The array <code>x1</code> is the transpose of the integer <code>x = abcdef</code>.</p> <p>How to un...
1
2016-06-16T15:29:27Z
37,864,653
<p>Here is one way:</p> <pre><code>def untranspose(arr): x,y,z = arr a,d = divmod(x,2) b,e = divmod(y,2) c,f = divmod(z,2) return f + 2*e + 4*d + 8*c + 16*b + 32*a </code></pre> <p>For example,</p> <pre><code>&gt;&gt;&gt; untranspose([1,3,2]) 30 </code></pre> <p><code>[1,3,2]</code> corresponds ...
2
2016-06-16T16:27:05Z
[ "python", "bit-manipulation" ]
why use both os.path.abspath and os.path.realpath
37,863,476
<p>In multiple open source projects, I have seen people do <code>os.path.abspath(os.path.realpath(__file__))</code> to get the absolute path to the current file. However, I find that <code>os.path.abspath(__file__)</code> and <code>os.path.realpath(__file__)</code> produce the same result. <code>os.path.abspath(os.path...
2
2016-06-16T15:30:30Z
37,863,619
<p><code>os.path.realpath</code> derefences symbolic links on those operating systems which support them.</p> <p><code>os.path.abspath</code> simply removes things like '~' (Home directory), '.' and '..' from the path giving a full path from the root of the directory tree to the named file (or symlink)</p> <p>For exa...
5
2016-06-16T15:36:12Z
[ "python" ]
Why is subplot changing the color of my image?
37,863,493
<p>I am trying to extract a frame from video and display each frame as an image. For comparison I tried subplotting. The read RGB image is different when plotted. Where could I be possibly wrong?</p> <pre><code>vid = cv2.VideoCapture(file1) num_frames = int(vid.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT)) fig, ax = plt.subplo...
0
2016-06-16T15:31:06Z
37,863,760
<p>Try </p> <pre><code>ax[0].imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) </code></pre>
0
2016-06-16T15:43:32Z
[ "python", "subplot" ]
TypeError while creating a pandas dataframe
37,863,542
<p>I have written the following python code using the pandas package.</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd import numpy as np from pandas import Series csv = pd.read_csv('train.csv') df_csv = pd.DataFrame(csv) PassengerId = np.array(df_csv['PassengerId']) Age = np.array(df_csv['Age']) P...
1
2016-06-16T15:32:58Z
37,865,656
<p>Try replacing </p> <pre><code>new_df = pd.DataFrame[ 'PassengerId': Series(PassengerId), 'Age': Series(Age), 'Pclass': Series(Pclass), 'Sex': Series(Sex) ] </code></pre> <p>with </p> <pre><code>new_df = pd.DataFrame({ 'PassengerId': Series(PassengerId), 'Age': Series(Age), 'Pclass': Series(Pclass), ...
0
2016-06-16T17:21:36Z
[ "python", "arrays", "numpy", "pandas" ]
Python - curve_fit gives incorrect coefficients
37,863,558
<p>I'm trying to pass two arrays for a fitting function, that takes both values.</p> <p>Data file: </p> <p>Column 1: Time Column 2: Temperature Column 3: Volume Column 4: Pressure</p> <pre><code>0.000,0.946,4.668,0.981 0.050,0.946,4.668,0.981 0.100,0.946,4.669,0.981 0.150,0.952,4.588,0.996 0.200,1.025,4.008,1.117 0....
1
2016-06-16T15:33:42Z
37,879,832
<p><strong>Caveat</strong>: the result obtained here for <code>gamma</code> (about 1.7) still deviates from the postulated 1.2. This answer merely highlights the source of possible errors and illustrates what a good fit might look like.</p> <p>You are trying to fit data where the dependent variable is related to the i...
1
2016-06-17T10:56:18Z
[ "python", "numpy", "scipy", "curve-fitting" ]
Fill nulls in columns with non-null values from other columns
37,863,569
<p>Given a dataframe with similar columns having null values in between. How to dynamically fill nulls in the columns with non-null values from other columns without explicitly stating the names of other column names e.g. select first column <code>category1</code> and fill the null rows with values from other columns o...
2
2016-06-16T15:34:07Z
37,863,613
<p>IIUC you can do it this way:</p> <pre><code>In [369]: df['category1'] = df['category1'].fillna(df['category2']) In [370]: df Out[370]: category1 category2 category3 year 2010 10.0 10.0 10.0 2011 21.0 21.0 21.0 2012 20.0 20.0 20.0 2013 10.0 1...
1
2016-06-16T15:35:53Z
[ "python", "pandas", "dataframe", null ]
Fill nulls in columns with non-null values from other columns
37,863,569
<p>Given a dataframe with similar columns having null values in between. How to dynamically fill nulls in the columns with non-null values from other columns without explicitly stating the names of other column names e.g. select first column <code>category1</code> and fill the null rows with values from other columns o...
2
2016-06-16T15:34:07Z
37,863,620
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.first_valid_index.html" rel="nofollow"><code>first_valid_index</code></a> with condition if all values are <code>NaN</code>:</p> <pre><code>def f(x): if x.first_valid_index() is None: return None else: ...
0
2016-06-16T15:36:18Z
[ "python", "pandas", "dataframe", null ]
Fill nulls in columns with non-null values from other columns
37,863,569
<p>Given a dataframe with similar columns having null values in between. How to dynamically fill nulls in the columns with non-null values from other columns without explicitly stating the names of other column names e.g. select first column <code>category1</code> and fill the null rows with values from other columns o...
2
2016-06-16T15:34:07Z
37,864,428
<p>Try This: </p> <pre><code>df['category1']= df['category1'].fillna(df.median(axis=1)) </code></pre>
0
2016-06-16T16:15:59Z
[ "python", "pandas", "dataframe", null ]
Vim Flake8 ignoring project config file
37,863,594
<p>vim-flake8 seems to be ignoring my project-specific config file. If I run flake8 from the command line in my project root, it works, but when I open vim and try to run flake8 against my files, its not picking up that setting. I know this because its using a default line-length of 79, instead of my project-specific...
0
2016-06-16T15:35:20Z
39,021,374
<p>Had the same problem too on my OSX, and partially solved it. Had the latest versions of syntastic (git clone today) and flake8 3.0.4. Vim 7.4.</p> <p>flake8 ran fine from command line and picked my global ~/.config/flake8. Vim did not output anything if I had the config file, but worked fine without the flake8 conf...
0
2016-08-18T14:53:16Z
[ "python", "vim", "flake8" ]