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
Python 2.7 encoding from csv file
40,103,127
<p>I have a problem with Python 2.7 encoding I have a csv file with some french characters (mangé, parlé, prêtre ...), the code I'm using is the following:</p> <pre><code>import pandas as pd path_dataset = 'P:\\Version_python\\Dataset\\data_set - Copy.csv' dataset = pd.read_csv(path_dataset, sep=';') for lab, row ...
1
2016-10-18T08:21:55Z
40,103,412
<p>Here is a list of standard python encodings</p> <p><a href="https://docs.python.org/2/library/codecs.html" rel="nofollow">Standard Python 2.7 encodings</a></p> <p><code>utf-8</code> does not work but you can try some other encodings on the link above.</p> <p>Just tested <code>latin_1</code> works. So the code sho...
2
2016-10-18T08:37:34Z
[ "python", "python-2.7", "pandas" ]
Generator that yields subpatterns of an original pattern with zeros introduced
40,103,182
<p>I have the following problem in which I want to generate patterns with a 0 introduced. The problem is that this should be space efficient, and thus I would like to use a generator that creates and returns one of the patterns at a time (i.e. I do not want to create a list and return it.) I am at a loss here because I...
0
2016-10-18T08:25:05Z
40,105,619
<p>Not being an numpy expert, this part looks a bit weird to me:</p> <pre><code>for i in listnonzero: .... if i == len(listnonzero): break </code></pre> <p>Your for loop assigns elements of listnonzero to i, and then you test that against the length of the list. If the listnonzero had five elements ...
0
2016-10-18T10:20:39Z
[ "python", "generator", "yield" ]
kNN - How to locate the nearest neighbors in the training matrix based on the calculated distances
40,103,226
<p>I am trying to implement k-nearest neighbor algorithm using python. I ended up with the following code. However, I am struggling with finding the index of the items that are the nearest neighbors. The following function will return the distance matrix. However I need to get the indices of these neighbors in the <cod...
0
2016-10-18T08:27:45Z
40,103,836
<p>I will suggest to use the python library <code>sklearn</code> that has a <code>KNeighborsClassifier</code> from which, once fitted, you can retrieve the nearest neighbors you are looking for :</p> <p>Try this out:</p> <pre><code># Import from sklearn.neighbors import KNeighborsClassifier # Instanciate your classi...
1
2016-10-18T08:58:54Z
[ "python", "numpy", "machine-learning", "knn" ]
IronPython add Unicode characters at the start of a file
40,103,241
<p>I use a script to update the version of each AssemblyVersion.cs file of a .NET project. It always worked perfectly, but since a format my PC, it adds unicode character at the start of each .cs file edited. Like this:</p> <pre><code>using System.Reflection; using System.Runtime.InteropServices; usi...
0
2016-10-18T08:28:33Z
40,105,368
<p>It seems that the files at your file system are using ISO-8859-1 encoding, while you are adding the UT8 BOM marker at the beginning of each file. </p> <p>After your code does it's job, you get a file with UTF-8 BOM + ISO-8859-1 meta at the beginning.</p> <p>I would check the encoding of your input files before mod...
0
2016-10-18T10:08:35Z
[ "c#", "python", "unicode", "encoding", "ironpython" ]
Recursive dictionary walking in python
40,103,514
<p>I am new to python and trying to create a recursive dictionary walker that outputs a path to each item in the dictionary.</p> <p>Below is my code including some sample data. The goal is to import weather data from weather underground and publish into mqtt topics on a raspberry pi. (The mqtt code all runs fine and...
0
2016-10-18T08:42:34Z
40,103,951
<p>Just mix-in a regular for-loop into that recursion to iterate over the lists. </p> <pre><code>def print_path(root, data, path): for element, val in data.items(): if isinstance(val, dict): print_path(root, val, element+"/") elif isinstance(val, list): list_path = path+ele...
0
2016-10-18T09:04:13Z
[ "python", "json", "dictionary", "recursion", "python-2.x" ]
python post request not working with Minio server import
40,103,817
<p>I have a problem with POST request with Python/Django and Minio server, this is the code</p> <pre><code>from django.http import HttpResponse import json from minio import Minio minioClient = Minio('mypath:9000', access_key='mykey', secret_key='mysecret', secure=False...
0
2016-10-18T08:58:08Z
40,105,405
<p>From docs for urllib3: </p> <blockquote> <p>request(method, url, fields=None, headers=None, **urlopen_kw)¶ Make a request using urlopen() with the appropriate encoding of fields based on the method used.</p> </blockquote> <p>Maybe you could try something like this:</p> <pre><code>r = http.request('POST', "...
1
2016-10-18T10:10:45Z
[ "python", "django", "post", "request", "minio" ]
Why am I unable to correctly retrieve and use a QTableWidgetItem?
40,103,845
<p>I looked up the documentation for creating QTableWidgetItems, and it says that I need to use the <code>item()</code> method. "Returns the item for the given row and column if one has been set; otherwise returns 0." Here is how I used it:</p> <p><code>self.table.item(item.row(),1)</code></p> <p>There definitely is...
1
2016-10-18T08:59:30Z
40,120,594
<p>If you look at the qt docs for QTableWidgetItem, you will see that it can only be constructed from another item, from a string, from an icon and a string, or from an integer representing the type id of the item. You are giving the constructor the student ID directly, so it is using that last constructor, which creat...
0
2016-10-19T01:26:16Z
[ "python", "pyqt" ]
Alternative for matshow()
40,103,855
<p>I have a <code>101x101</code> matrix that I want to visualize graphically. So far I used the function <code>matshow</code> from <code>matplotlib.pyplot</code> as below:</p> <pre><code>import numpy as np import random import matplotlib.pyplot as plt A = np.zeros((101,101)) # do stuff to randomly change some values ...
2
2016-10-18T08:59:52Z
40,109,202
<p>This should do the trick:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def old_graph(A): plt.matshow(A,cmap='PuBuGn') plt.colorbar() plt.title(r"abs$\left(\left[\mathbf{A}_{ij} \right ] \right )$ ; SIS=%d"%(sis,), va='bottom') plt.show() def new_graph(A, sis_list=np.zeros(0,in...
3
2016-10-18T13:08:31Z
[ "python", "matrix", "matplotlib" ]
Python delete a value from dictionary and not the key
40,103,876
<p>Is it possible to delete a value from a dictionary and not the key? For instance, I have the following code in which the user selects the key corresponding to the element that he wants to delete it , but I want do delete only the value and not the key ( the value is a list): </p> <pre><code>if (selection == 2): ...
-1
2016-10-18T09:01:04Z
40,103,910
<p>No, it is not possible. Dictionaries consist of key/value pairs. You cannot have a key without a value. The best you can do is set that key's value to <code>None</code> or some other sentinel value, or use a different data structure that better suits your needs.</p>
4
2016-10-18T09:02:26Z
[ "python" ]
Python delete a value from dictionary and not the key
40,103,876
<p>Is it possible to delete a value from a dictionary and not the key? For instance, I have the following code in which the user selects the key corresponding to the element that he wants to delete it , but I want do delete only the value and not the key ( the value is a list): </p> <pre><code>if (selection == 2): ...
-1
2016-10-18T09:01:04Z
40,103,960
<pre><code>dictionar = {} elem = int(input("Please select the KEY that you want to be deleted: ")) if dictionar.has_key(elem) dictionar[elem] = "" else: print("The KEY is not present") </code></pre> <p>This code checks if elem is in dictionar then turns the value into a blank string.</p>
-1
2016-10-18T09:04:50Z
[ "python" ]
Python delete a value from dictionary and not the key
40,103,876
<p>Is it possible to delete a value from a dictionary and not the key? For instance, I have the following code in which the user selects the key corresponding to the element that he wants to delete it , but I want do delete only the value and not the key ( the value is a list): </p> <pre><code>if (selection == 2): ...
-1
2016-10-18T09:01:04Z
40,104,263
<p>Dictionaries are data structures with <code>{key:value}</code> pairs.</p> <p>To work with values, you can do replace the value with some other value or <code>None</code> like below:</p> <pre><code>dic = {} e = int(input("KEY to be deleted/replaced: ")) if dic.has_key(e): r = int(input("New value to put in...
0
2016-10-18T09:18:57Z
[ "python" ]
SqlAlchemy+pymssql. Will raw parametrized queries use same execution plan?
40,103,917
<p>In my application I have parametrized queries like this:</p> <pre><code>res = db_connection.execute(text(""" SELECT * FROM Luna_gestiune WHERE id_filiala = :id_filiala AND anul=:anul AND luna = :luna """), id_filiala=6, anul=2010, luna=7).fetchone() </code></pre> <p>Will such query use same ...
1
2016-10-18T09:02:41Z
40,118,291
<p>I'm guessing that it's unlikely, because pymssql performs the parameter substitution <em>before</em> sending the query to the server, unlike some other mechanisms that send the query "template" and the parameters separately (e.g., pyodbc, as described in <a href="http://stackoverflow.com/a/40065211/2144390">this ans...
0
2016-10-18T21:21:53Z
[ "python", "sqlalchemy", "pymssql" ]
Move console cursor up
40,103,919
<p>I tried to create a simple clock up the top-left corner of the screen, updating every second:</p> <pre><code>def clock(): threading.Timer(1.0, clock).start() print('\033[0;0H' + time.asctime(time.localtime())) </code></pre> <p>I've used threading and the colorama module, but it seems the escape code just m...
0
2016-10-18T09:02:50Z
40,104,556
<p>The line and column start at 1 not 0.</p> <pre><code>print('\033[1;1H' + time.asctime(time.localtime())) </code></pre> <p>or shorter</p> <pre><code>print('\033[H' + time.asctime(time.localtime())) </code></pre> <p>You might also need to save and restore position using ESC-7 and ESC-8.</p> <p>See <a href="http:/...
1
2016-10-18T09:31:47Z
[ "python", "shell", "printing", "console", "cursor" ]
Serializing a JSON object for a Django URL
40,104,130
<p>I have a JSON object that looks like this:</p> <pre><code>var obj = { "selection":[ { "author":"John Doe", "articles":[ "Article One", "Article Two" ] } ] } </code></pre> <p>I want to pass this object to Django to render a view that displ...
0
2016-10-18T09:12:42Z
40,104,486
<p>You are not properly serializing the object to JSON, even if you say you do. The correct way would be to use <code>JSON.stringify()</code>, as @dunder states.</p> <p>Than you parse it back to an object with <code>JSON.parse(strignifiedJson)</code>.</p> <pre><code>var obj = { "selection":[ { ...
0
2016-10-18T09:29:00Z
[ "javascript", "python", "json", "django" ]
How can i run a command on the command prompt with a batch file and keep running it for 'n' seconds?
40,104,259
<p>How can i run a command on the command prompt with a batch file and keep running it for 'n' seconds ? and then close it automatically ? (All in Background i.e without opening the console)</p>
-1
2016-10-18T09:18:53Z
40,104,432
<p>Use the <code>subprocess</code> module. You may be interested in <code>subprocess.run</code> and its <code>timeout</code> argument if you are using a newer version of Python (i.e. 3.5.x). If not, take a look at <code>subprocess.Popen</code>.</p> <blockquote> <p>The timeout argument is passed to Popen.communicate(...
0
2016-10-18T09:26:45Z
[ "python", "python-2.7", "python-3.x", "command-line", "subprocess" ]
How can i run a command on the command prompt with a batch file and keep running it for 'n' seconds?
40,104,259
<p>How can i run a command on the command prompt with a batch file and keep running it for 'n' seconds ? and then close it automatically ? (All in Background i.e without opening the console)</p>
-1
2016-10-18T09:18:53Z
40,104,485
<p>Create any python(.py) file and run it like</p> <p><code>c:\python27\python.exe &lt;path_of_the_file&gt;/filename.py</code></p> <p>To keep running it over say, 1000 times:</p> <p><code>for /l %x in (1, 1, 1000) do c:\python27\python.exe &lt;path_of_the_file&gt;/filename.py</code></p> <p>Note: Assuming your pytho...
2
2016-10-18T09:28:55Z
[ "python", "python-2.7", "python-3.x", "command-line", "subprocess" ]
Django admin foreign key values custom form
40,104,291
<p>So, I have a model Puzzle and a model Piece. Piece has as foreignKey to Puzzle. And on the admin, on puzzle form to add a new element, i have a stackedInLine for pieces. But i can only add more if I enter all the data from the piece. Is there a way to add new Pieces to the puzzle by choosing from a dropdown with the...
0
2016-10-18T09:20:07Z
40,104,657
<p>What if you create a new model, say:</p> <pre><code>from django.dispatch import receiver class PieceSelector(models.Model): piece = models.ForeignKey(Piece) def __unicode__(self): return piece.some_field @receiver(post_save, sender=Piece) def piece_post_save_signal_receiver(sender, **kwargs): ...
1
2016-10-18T09:36:24Z
[ "python", "django" ]
Issiue with implementation of 2D Discrete Cosine Transform in Python
40,104,377
<p>I'm trying to rewrite Zhao Koch steganography method from matlab into python and I am stuck right at the start.</p> <p>The first two procedures as they are in matlab:</p> <p>Step 1:</p> <pre><code>A = imread(casepath); # Reading stegonography case image and aquiring it's RGB values. In my case it's a 400x400 PNG ...
0
2016-10-18T09:24:28Z
40,109,427
<p>Your code works fine, but it is designed to only accept a 2D array, just like <a href="https://uk.mathworks.com/help/images/ref/dct2.html" rel="nofollow"><code>dct2()</code></a> in Matlab. Since your <code>arr</code> is a 3D array, you want to do</p> <pre><code>D = dct2(arr[...,2]) </code></pre> <p>As mentioned in...
1
2016-10-18T13:18:59Z
[ "python", "matlab", "dct" ]
how to access GET query string multidimensional arrays in bottle python
40,104,438
<p>I know how to get individual values from keys such as:</p> <pre><code>some_val = request.query.some_key </code></pre> <p>But how do you access values when you have a url like this.</p> <p>Sample url : <a href="http://blahblah.com/what?draw=1&amp;columns%5B0%5D%5Bdata%5D=source_url&amp;columns%5B0%5D%5Bname%5D...
0
2016-10-18T09:26:58Z
40,122,808
<p>Since this question pertains to using <a href="https://datatables.net/" rel="nofollow">https://datatables.net/</a> with a bottle python backend. What i ended up doing is formatting the args on the client side like so. Maybe you'll find it useful.</p> <pre><code>$('#performance-table').DataTable( { "...
0
2016-10-19T05:24:16Z
[ "python", "get", "query-string", "bottle" ]
Pandas - Calculating daily differences relative to earliest value
40,104,449
<p>This is probably pretty easy, but for some reason I am finding it quite difficult to complete. Any tips would be greatly appreciated. I have some time series data consisting of 5-minute intervals each day, ala:</p> <pre><code>Date Values 2012-12-05 09:30:00 5 2012-12-05 09:35:00 7 2012-12-05...
2
2016-10-18T09:27:38Z
40,104,518
<p>You can use broadcasting:</p> <pre><code>df.Values - df.Values.iloc[0] </code></pre>
1
2016-10-18T09:30:09Z
[ "python", "pandas", "resampling" ]
Pandas - Calculating daily differences relative to earliest value
40,104,449
<p>This is probably pretty easy, but for some reason I am finding it quite difficult to complete. Any tips would be greatly appreciated. I have some time series data consisting of 5-minute intervals each day, ala:</p> <pre><code>Date Values 2012-12-05 09:30:00 5 2012-12-05 09:35:00 7 2012-12-05...
2
2016-10-18T09:27:38Z
40,104,547
<p>You need substract by <code>Series</code> created <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow"><code>transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><cod...
1
2016-10-18T09:31:07Z
[ "python", "pandas", "resampling" ]
How to create a field with a list of foreign keys in SQLAlchemy?
40,104,502
<p>I am trying to store a list of models within the field of another model. Here is a trivial example below, where I have an existing model, <code>Actor</code>, and I want to create a new model, <code>Movie</code>, with the field <code>Movie.list_of_actors</code>:</p> <pre><code>import uuid from sqlalchemy import Boo...
0
2016-10-18T09:29:23Z
40,104,800
<p>If you want many actors to be associated to a movie, and many movies be associated to an actor, you want a many-to-many. This means you need an association table. Otherwise, you could chuck away normalisation and use a NoSQL database.</p> <p>An association table solution might resemble:</p> <pre><code>class Actor(...
1
2016-10-18T09:42:26Z
[ "python", "postgresql", "sqlalchemy", "foreign-keys", "foreign-key-relationship" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and dele...
0
2016-10-18T09:29:44Z
40,104,686
<p>You should use <code>del</code> to delete list item. Also you should iterate from end to the beginning because if you will go from the beginning and delete let say <code>1st</code> element the element that was on the <code>3rd</code> place will be now on the <code>2nd</code></p> <p>It should look like</p> <pre><co...
0
2016-10-18T09:37:43Z
[ "python", "list", "python-3.x" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and dele...
0
2016-10-18T09:29:44Z
40,104,774
<p>You can take advantage of the fact that assigning to a slice modifies the list:</p> <pre><code>la[:] = latemp lb[:] = lbtemp </code></pre>
-2
2016-10-18T09:41:33Z
[ "python", "list", "python-3.x" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and dele...
0
2016-10-18T09:29:44Z
40,104,814
<p>Generally, when you're mutating a list while iterating over it. It's good practice to iterate over a copy instead. Below is an example of what you would do to mutate one list.</p> <pre><code>list = [] list_copy = list[:] for i in list_copy: list.remove(i) return list </code></pre> <p>This allows you to maintai...
0
2016-10-18T09:42:53Z
[ "python", "list", "python-3.x" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and dele...
0
2016-10-18T09:29:44Z
40,104,979
<p>This will solve your problem. I think it's easier than all other solutions.</p> <pre><code>def modi(la, lb): new_la = [] new_lb = [] for a, b in zip(la, lb): if a == b: continue if a &gt; b: new_lb.append(b) if a &lt; b: new_la.append(a) re...
0
2016-10-18T09:50:48Z
[ "python", "list", "python-3.x" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and dele...
0
2016-10-18T09:29:44Z
40,105,516
<p>In your own code <code>la = latemp</code> and <code>lb = lbtemp</code> create <em>references</em> to the two new lists that are local to the function, they have no bearing on the lists that you pass in to the function. According to your specs, you should be mutating the lists passed in not reassigning or creating ne...
0
2016-10-18T10:15:53Z
[ "python", "list", "python-3.x" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and dele...
0
2016-10-18T09:29:44Z
40,105,794
<p>Essentially, you need to keep track of how many times you've deleted from each list, and offset your indexing by that amount. Here's a basic approach:</p> <pre><code>&gt;&gt;&gt; a ['bear', 'tiger', 'wolf', 'whale', 'elephant'] &gt;&gt;&gt; b ['swan', 'cat', 'dog', 'duck', 'rabbit'] &gt;&gt;&gt; i = j = 0 &gt;&gt;&...
0
2016-10-18T10:28:40Z
[ "python", "list", "python-3.x" ]
Why does my plot not disappear on exit in ipython mode?
40,104,587
<p>I'm showing some plots using <code>matplotlib</code> in the <code>ipython</code> prompt. When closing the plot window it does not disappear but gets "stuck" in the background and does not respond to user actions. You can try it out yourself with the following code: </p> <pre><code># test.py import matplotlib.pyplot...
0
2016-10-18T09:33:11Z
40,106,566
<p>You should be a bit careful with using pyplot in ipython. Especially <code>plt.show()</code> is blocking the ipython terminal. You should use <code>fig.show()</code>, since it does not block ipython. If you really want to use pyplot, one work-around is to use <code>plt.gcf().show()</code>, which will get the curr...
0
2016-10-18T11:06:28Z
[ "python", "matplotlib", "ipython" ]
Why does my plot not disappear on exit in ipython mode?
40,104,587
<p>I'm showing some plots using <code>matplotlib</code> in the <code>ipython</code> prompt. When closing the plot window it does not disappear but gets "stuck" in the background and does not respond to user actions. You can try it out yourself with the following code: </p> <pre><code># test.py import matplotlib.pyplot...
0
2016-10-18T09:33:11Z
40,129,300
<p>Try running <code>%matplotlib</code> before plotting, so that IPython integrates with the GUI event loop showing the plots.</p> <p>This shouldn't be necessary once matplotlib 2.0 is released, because it has some code to detect when it's running inside IPython.</p>
0
2016-10-19T10:50:56Z
[ "python", "matplotlib", "ipython" ]
Remove HTML tags in script
40,104,592
<p>I've found this piece of code on the internet. It takes a sentence and makes every single word into link with this word. But it has weak side: if a sentence has HTML in it, this script doesn't remove it.</p> <p>For example: it replaces '<code>&lt;b&gt;asserted&lt;/b&gt;</code>' with '<code>http://www.merriam-webste...
-1
2016-10-18T09:33:28Z
40,104,675
<pre><code>function stripAllHtml(str) { if (!str || !str.length) return '' str = str.replace(/&lt;script.*?&gt;.*?&lt;\/script&gt;/igm, '') let tmp = document.createElement("DIV"); tmp.innerHTML = str; return tmp.textContent || tmp.innerText || ""; } stripAllHtml('&lt;a&gt;test&lt;/a&gt;') </code></pre> ...
0
2016-10-18T09:37:08Z
[ "javascript", "python", "regex", "replace" ]
Remove HTML tags in script
40,104,592
<p>I've found this piece of code on the internet. It takes a sentence and makes every single word into link with this word. But it has weak side: if a sentence has HTML in it, this script doesn't remove it.</p> <p>For example: it replaces '<code>&lt;b&gt;asserted&lt;/b&gt;</code>' with '<code>http://www.merriam-webste...
-1
2016-10-18T09:33:28Z
40,105,685
<p>This regex /&lt;{1}[^&lt;>]{1,}>{1}/g should replace any text in a string that is between two of these &lt;> and the brackets themselves with a white space. This</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code...
1
2016-10-18T10:23:10Z
[ "javascript", "python", "regex", "replace" ]
Logging into a AWS instance using boto3 library of python
40,104,641
<p>I am attempting to write a python code that would few of my manual steps in logging into the AWS platform. </p> <p>In Ubuntu terminal , I used to write the command</p> <pre><code>ssh -A ec2-user@&lt;ip-address&gt; </code></pre> <p>and then again log into another instance using</p> <pre><code>ssh ec2-user@&lt;ip....
-1
2016-10-18T09:35:29Z
40,104,858
<p>There are 2 ways mostly to configure the boto3 library.</p> <ol> <li><p>You need to configure it first on your system and use the same configuration everywhere. You can use <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html" rel="nofollow"><strong>AWS CLI</strong></a> for this by...
2
2016-10-18T09:45:01Z
[ "python", "amazon-web-services", "amazon-ec2", "boto3" ]
Logging into a AWS instance using boto3 library of python
40,104,641
<p>I am attempting to write a python code that would few of my manual steps in logging into the AWS platform. </p> <p>In Ubuntu terminal , I used to write the command</p> <pre><code>ssh -A ec2-user@&lt;ip-address&gt; </code></pre> <p>and then again log into another instance using</p> <pre><code>ssh ec2-user@&lt;ip....
-1
2016-10-18T09:35:29Z
40,105,117
<p>If you want to perform actions on a running instance, boto3 is not what you're looking for. What you're asking about is more in the realm of what's called <em>configuration management</em>.</p> <p>While you could write something yourself using an SSH library like <a href="http://www.paramiko.org/" rel="nofollow">P...
0
2016-10-18T09:57:06Z
[ "python", "amazon-web-services", "amazon-ec2", "boto3" ]
Vertical Bar chart using rotation='vertical' not working
40,104,730
<p>From the matplot lib example <a href="http://matplotlib.org/examples/lines_bars_and_markers/barh_demo.html" rel="nofollow">lines_bars_and_markers</a> using <code>rotation='vertical'</code> does not make it vertical. What am I doing wrong?</p> <pre><code>""" Simple demo of a horizontal bar chart. """ import matplotl...
0
2016-10-18T09:39:05Z
40,104,887
<p><code>barh</code> is for horizontal bar charts, change to <code>bar</code> and then swap around the data for the axes. You can't simply write <code>rotation='vertical'</code> because that isn't telling the <code>matplotlib</code> library anything, it's just creating a string that is never used. </p> <pre><code>impo...
3
2016-10-18T09:46:01Z
[ "python", "numpy", "matplotlib" ]
scrapy starting a new project
40,104,737
<p>I have installed python 2.7.12 version on a Windows 7 system. I have also installed pywin32 and Visual C++. When I enter the command <code>pip --version</code> it does not generate any output, the cursor moves to the next line and blinks.</p> <p>But when I use the command <code>python -m pip --version</code> the ve...
0
2016-10-18T09:39:18Z
40,122,499
<p>Using the alternative command <code>python -m scrapy.cmdline &lt;command&gt; &lt;arguments&gt;</code> (e.g. python -m scrapy.cmdline version -v) worked</p> <p>thanks Paul</p>
0
2016-10-19T05:00:41Z
[ "python", "python-2.7", "web-scraping", "scrapy", "scrapy-spider" ]
django required file field validation
40,104,831
<p>Working with django form in which i have two file uploads fields one for artist image and another for event poster, both of these fields are required. </p> <pre><code>class CreateEventStepFirstForm(forms.Form): event_title = forms.CharField(required = True, max_length=20, widget=forms.TextInput(attrs={ ...
0
2016-10-18T09:43:44Z
40,105,110
<p>You need to add <code>request.FILES</code> as follows:</p> <pre><code>form = CreateEventStepFirstForm(request.POST, request.FILES) </code></pre>
1
2016-10-18T09:56:54Z
[ "python", "django" ]
How to get date after subtracting days in pandas
40,104,946
<p>I have a dataframe:</p> <pre><code>In [15]: df Out[15]: date day 0 2015-10-10 23 1 2015-12-19 9 2 2016-03-05 34 3 2016-09-17 23 4 2016-04-30 2 </code></pre> <p>I want to subtract the number of days from the date and create a new column.</p> <pre><code>In [16]: df.dtypes Out[16]: date dat...
1
2016-10-18T09:49:11Z
40,105,235
<pre><code>import dateutil.relativedelta def calculate diff(v): return v['date'] - dateutil.relativedelta.relativedelta(day=v['day']) df['date1']=df.apply(calculate_diff, axis=1) </code></pre> <p>given that v['date'] is datetime object</p>
1
2016-10-18T10:02:06Z
[ "python", "pandas" ]
How to get date after subtracting days in pandas
40,104,946
<p>I have a dataframe:</p> <pre><code>In [15]: df Out[15]: date day 0 2015-10-10 23 1 2015-12-19 9 2 2016-03-05 34 3 2016-09-17 23 4 2016-04-30 2 </code></pre> <p>I want to subtract the number of days from the date and create a new column.</p> <pre><code>In [16]: df.dtypes Out[16]: date dat...
1
2016-10-18T09:49:11Z
40,105,381
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>to_timedelta</code></a>:</p> <pre><code>df['date1'] = df['date'] - pd.to_timedelta(df['day'], unit='d') print (df) date day date1 0 2015-10-10 23 2015-09-17 1 2015-12-19 9 2...
3
2016-10-18T10:09:10Z
[ "python", "pandas" ]
Reg ex remove non alpha characters keeping spaces
40,105,027
<p>I've written a simple function that strips a string of all non-alpha characters keeping spaces in place.</p> <p>Currently it relies on using two regular expressions. However, in in interest of brevity I'd like to reduce those two reg exs into one. Is this possible?</p> <pre><code>import re def junk_to_alpha(s): ...
1
2016-10-18T09:52:51Z
40,105,089
<p>You may enclose the <code>[^a-zA-Z]+</code> with <code>\s*</code>:</p> <pre><code>import re def junk_to_alpha(s): s = re.sub(r"\s*[^A-Za-z]+\s*", " ", s) return s print junk_to_alpha("Spoons! 12? \/@# ,.1 12 Yeah? {[]}") </code></pre> <p>See the <a href="https://ideone.com/N1pz8v" rel="nofollow">online Pytho...
1
2016-10-18T09:55:39Z
[ "python", "regex", "string", "python-2.7" ]
how to delete youtube's watch later video in selenium?
40,105,029
<p>I want to delete youtube's watch later videos. but my codes don't work.</p> <pre><code>&lt;button class="yt-uix-button yt-uix-button-size-default yt-uix-button-default yt-uix-button-empty yt-uix-button-has-icon no-icon-markup pl-video-edit-remove yt-uix-tooltip" type="button" onclick=";return false;" title="Remove"...
0
2016-10-18T09:52:52Z
40,105,849
<p>The element that you are trying to click is not visible normally. It is only visible when you hover the mouse on it. So either you fire a mouseover event before clicking and try if it works.</p> <p>The other solution is that you can try executing the JavaScript.</p> <pre><code> driver.execute_script("document.g...
0
2016-10-18T10:31:25Z
[ "python", "selenium", "youtube" ]
Creating a Datastore Entry results in encrypted properties when viewing with the browser
40,105,116
<p>I manage to create or modify a datastore entity fine with google.cloud.datastore in python, but when I log in into my Cloud Platform project in the browser and check the entry, it looks like all of its properties are encrypted (They look like <code>"Rm9vIEJhcg=="</code> and such - If I create it from the browser I c...
0
2016-10-18T09:57:05Z
40,132,794
<p>The value is not really encrypted, rather encoded with Base64. The reason for this is the value is stored as a Blob (raw bytes), instead of Text/Character String. The Console displays Blob fields in Base64 format. The value, Rm9vIEJhcg==, when decoded with Base64, is Foo Bar. </p> <p>I don't have much knowledge in...
0
2016-10-19T13:27:29Z
[ "python", "google-cloud-datastore", "google-cloud-python", "gcloud-python" ]
Why if Python flask route has more arguments, it returns an errormistakes?
40,105,148
<pre><code>@app.route("/ufname/&lt;uname&gt;/friend/&lt;fname&gt;") def v_ufname(uname,fname): return "s%\'s friend - %s\'s profile" % (uname,fname) </code></pre> <p><img src="https://i.stack.imgur.com/dHjad.png" alt="enter image description here"></p> <p>and i try add more %%%s%%\'s, the page write "<strong>%mary...
-5
2016-10-18T09:58:05Z
40,105,525
<p>Use</p> <pre><code>return "%s\'s friend - %s\'s profile" % (uname,fname) </code></pre> <p>Check out <a href="https://pyformat.info/" rel="nofollow">https://pyformat.info/</a></p>
2
2016-10-18T10:16:17Z
[ "python", "flask" ]
Python: How to execute a JavaScript Function (with lxml)?
40,105,271
<p>I'd like to parse a website where I need to make a JavaScript call before parsing the code, because exeuting the JavaScript function unfolds more informations that I need to parse.</p> <p>This is the part where the JavaScript gets called:</p> <pre><code>&lt;a href="javascript:StartUpdate(DIV_TS_4828_5899,41611,589...
-1
2016-10-18T10:04:00Z
40,107,589
<p>No, it is not possible to execute JavaScript language by using parser of eXtensible Markup Language, even with module for parsing HyperText Markup Language.</p> <p>You need to use JavaScript interpreter to execute JavaScript code.</p> <p>If you really don't like Selenium you may try to use <a href="https://code.go...
0
2016-10-18T11:55:04Z
[ "javascript", "python", "lxml" ]
How to split an RDD into two RDDs and save the result as RDDs with PySpark?
40,105,328
<p>I'm looking for a way to split an RDD into two or more RDDs, and save the results obtained as two separated RDDs. Given for exemple :</p> <pre><code>rdd_test = sc.parallelize(range(50), 1) </code></pre> <p>My code :</p> <pre><code>def split_population_into_parts(rdd_test): N = 2 repartionned_rdd = rdd_te...
0
2016-10-18T10:07:08Z
40,109,361
<p>I got the solutions.</p> <pre><code>def get_testab_populations_tables(rdds_for_testab_populations): i = 0 while i &lt; len(rdds_for_testab_populations.collect()): for testab_table in rdds_for_testab_populations.toLocalIterator(): namespace = globals() namespace['tAB_%d' % i] = sc.parallelize(tes...
0
2016-10-18T13:15:45Z
[ "python", "list", "pyspark", "rdd", "pyspark-sql" ]
create list for for-loop
40,105,332
<p>I have a script that creates a number of console links (with an html body built around) to VMs for faster access, the console links are put together by a number of strings and variables. </p> <p>I want to create a list the contains all the links created. </p> <p><strong>Nevermind I already created a list of all li...
0
2016-10-18T10:07:12Z
40,105,521
<p>You may use <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_output" rel="nofollow"><code>subprocess.check_output()</code></a> which runs command with arguments and return its output as a byte string. For example:</p> <pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; my_var = subproc...
1
2016-10-18T10:16:00Z
[ "python" ]
create list for for-loop
40,105,332
<p>I have a script that creates a number of console links (with an html body built around) to VMs for faster access, the console links are put together by a number of strings and variables. </p> <p>I want to create a list the contains all the links created. </p> <p><strong>Nevermind I already created a list of all li...
0
2016-10-18T10:07:12Z
40,105,713
<p>Probably you would want to modify your script to store the links in a data-structure like a list:</p> <pre><code>links = list() ... # iteration happens here link = 'https://' + host + ':' + console_port + '...' print link links.append(link) # script done here; return or use links </code></pre> <p>In the end you c...
2
2016-10-18T10:24:29Z
[ "python" ]
Execute HTTP request to an external server when any CouchDB Data changes
40,105,366
<p>I am fairly new in CouchDB but successfully performed create, update, delete data using Fauxton UI. I have some PouchDB clients which will directly sync with this CouchDB database using HTTP Protocol. This PouchDB client will be authenticated with another ASP.NET Identity server and send a Bearer Token with each of...
0
2016-10-18T10:08:27Z
40,107,036
<p>Two JS modules that could solve parts of your issues:</p> <ul> <li><a href="https://www.npmjs.com/package/follow" rel="nofollow">follow</a>, to execute a function everytime a change happen on the followed CouchDB database</li> <li><a href="https://github.com/ryanramage/couch2elastic4sync" rel="nofollow">couch2elast...
0
2016-10-18T11:28:26Z
[ "python", "asp.net", "oauth", "couchdb", "httprequest" ]
Decoding Byte/Bits to Binary
40,105,393
<p>I am using a Prologix GPIB-USB adaptor in a LISTEN only mode to decipher communication between two equipments (Semiconductor related namely Tester and Prober).</p> <p>I am able to decode most of the information as stated in the Manual , But unable to convert one of the Data namely BIN Category.</p> <p>Sample Data ...
0
2016-10-18T10:10:13Z
40,105,990
<p>You can use struct.unpack to decode byte values to numbers. You need to know the length (in this case 8 bytes) and whether the number is big or little endian (test if you don't know). And whether the number is signed or unsigned. </p> <p>If your string is "C@A@@@@@@@" and the binary data is in bytes 3-10, you cou...
0
2016-10-18T10:38:35Z
[ "python", "byte", "decoding", "bits", "gpib" ]
Why is there a trailing none when reading text in python?
40,105,412
<p>I'm trying to write a text reader program that can differ a text into three parts: title, tag, and content.</p> <p>what happen is that it's giving me a 'None' value at each end of the content.</p> <p>here is the content reader code:</p> <pre><code>#counting lines in the text def bufcount(file): file.seek(0) ...
0
2016-10-18T10:11:06Z
40,105,595
<p>You are printing the return value for the function:</p> <pre><code>print(searchForTheContent(file)) </code></pre> <p><code>searchForTheContent()</code> has no explicit <code>return</code> statement, so <code>None</code> is returned, and you are printing that. You'd get the same result with an empty function:</p> ...
3
2016-10-18T10:19:26Z
[ "python" ]
python - 'the truth value of an array with more than one element is ambiguous' - what truth value?
40,105,414
<p>first post! I've looked through a lot of other posts on this problem but can't find anything that applies to my code.</p> <p>I'm trying to read an audio file and then find the max and min values of the array of samples, <code>x</code>.<br> <code>wavread()</code> is a function defined in another module that I've imp...
0
2016-10-18T10:11:13Z
40,107,303
<p>Have you noticed that if your WAV file has more than one channel, say it is stereo, min_val and max_val will be arrays themselves?</p> <p>Such a code would trigger the error you encounter:</p> <pre><code>min, max = minMaxAudio('acdc.wav') # Assuming floats if max &gt; 1: print('saturation') </code></pre> <p>W...
0
2016-10-18T11:41:53Z
[ "python", "arrays", "numpy" ]
Python Django Template cannot get name from model function
40,105,470
<p>While I understood that I can call a function definition from our models, I can't seem to extract the file name of my uploaded document. Below I tried the following template format but either results from my desired output:</p> <p><strong><em>.html Version 1</em></strong></p> <pre><code>&lt;form action="." method=...
2
2016-10-18T10:14:06Z
40,105,590
<p>I think you got pretty close with <code>{{ document.filename }}</code>, except in your models you need to change </p> <pre><code>def filename(self): return os.path.basename(self.file.name) </code></pre> <p>into</p> <pre><code>def filename(self): # try printing the filename here to see if it works prin...
4
2016-10-18T10:18:56Z
[ "python", "django", "file", "filefield" ]
Custom python editor
40,105,483
<p>I am looking for such python editors which suggest inputs(mentioned in file/database) while using custom modules and functions during writing programs.</p> <p>Is there similar type of editor already exists that I can build something upon? Can I develop such editor? If yes, how?</p>
0
2016-10-18T10:14:38Z
40,105,820
<p>Try PyCharm, probably this software will cover all your needs</p>
1
2016-10-18T10:29:48Z
[ "python", "editor" ]
Custom python editor
40,105,483
<p>I am looking for such python editors which suggest inputs(mentioned in file/database) while using custom modules and functions during writing programs.</p> <p>Is there similar type of editor already exists that I can build something upon? Can I develop such editor? If yes, how?</p>
0
2016-10-18T10:14:38Z
40,105,839
<p>You can use vim editor by including this line in your ~/.vimrc file.</p> <pre><code>:h ins-completion </code></pre> <p>Now you can use the below keyboard shortcut for auto complete feature for your custom functions. </p> <p>Completion can be done for:</p> <ol> <li>Whole lines ...
0
2016-10-18T10:30:50Z
[ "python", "editor" ]
Custom python editor
40,105,483
<p>I am looking for such python editors which suggest inputs(mentioned in file/database) while using custom modules and functions during writing programs.</p> <p>Is there similar type of editor already exists that I can build something upon? Can I develop such editor? If yes, how?</p>
0
2016-10-18T10:14:38Z
40,106,098
<p>I would suggest, that you use the PyDev plugin for eclipse. PyDev has a lot of stuff, that increases the efficiency. You find it under: <a href="http://www.pydev.org/" rel="nofollow">http://www.pydev.org/</a></p> <p>Best Regards 1574ad6</p>
0
2016-10-18T10:44:19Z
[ "python", "editor" ]
python two dimensional recursion
40,105,513
<p>I have list pairs of keys and their possible values that are parsed from command line. eg:</p> <p><code>[('-a',['1','2','3']), ('-b',['1','2'])]</code></p> <p>my goal is to produce combinations as follows:</p> <pre><code>prefix -a=1 -b=1 suffix prefix -a=1 -b=2 suffix prefix -a=2 -b=1 suffix prefix -a=2 -b=2 suff...
0
2016-10-18T10:15:48Z
40,105,729
<p>You want to do <a href="https://en.wikipedia.org/wiki/Cartesian_product" rel="nofollow">cartesian product</a> of two list. Use <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product()</code></a> for doing that. For example:</p> <pre><code>&gt;&gt;&gt; my_...
3
2016-10-18T10:25:10Z
[ "python", "recursion", "combinations" ]
I want to read back a line from a specific line/string in python
40,105,536
<p>this is the code that has me really confused:</p> <pre><code>if search in open('test.txt').read(): print("product is found") </code></pre> <p>i am trying to re-read a line fro my text file using the .read() function however i do not know how this would work from searching a single string. EG: if search is 1234...
0
2016-10-18T10:16:36Z
40,105,663
<p>try:</p> <pre><code>s = input("enter") file = open("test.txt","r") for line in file: if s in open('test.txt').read(): print("product is found") </code></pre>
-2
2016-10-18T10:22:29Z
[ "python" ]
I want to read back a line from a specific line/string in python
40,105,536
<p>this is the code that has me really confused:</p> <pre><code>if search in open('test.txt').read(): print("product is found") </code></pre> <p>i am trying to re-read a line fro my text file using the .read() function however i do not know how this would work from searching a single string. EG: if search is 1234...
0
2016-10-18T10:16:36Z
40,105,696
<p>If I understood you right, you want to get the line which matches the <code>search</code>. If so, you just need to read file line by line which can be done like this</p> <pre><code>for line in open('test.txt'): if search in line: print("Product is found on line", line.strip()) </code></pre>
1
2016-10-18T10:23:37Z
[ "python" ]
Cannot find dynamic library when running a Python script from Bazel
40,105,625
<p>I am trying to setup CUDA enabled Python &amp; TensorFlow environment on OSx 10.11.6</p> <p>Everything went quite smoothly. First I installed following:</p> <ul> <li>CUDA - 7.5</li> <li>cuDNN - 5.1</li> </ul> <p>I ensured that the LD_LIBRARY_PATH and CUDA_HOME are set properly by adding following into my ~/.bash_...
0
2016-10-18T10:20:50Z
40,111,416
<p>Use </p> <pre><code>export LD_LIBRARY_PATH=/usr/local/cuda/lib64/ </code></pre> <p>before launching bazel. Double check in the directory above if there is such a file.</p> <pre><code>ls /usr/local/cuda/lib64/libcudart.7.5.dylib </code></pre> <p>Note that in Macosx the name is different:</p> <pre><code>export D...
0
2016-10-18T14:47:49Z
[ "python", "osx", "tensorflow", "bazel" ]
How to get custom object from callfunc in cx_Oracle?
40,105,683
<p>I have an PL/SQL function <code>my_function</code> that returns custom defined object:</p> <pre><code>CREATE OR REPLACE TYPE "TP_ACTION" AS OBJECT (   stop_time timestamp,   user_name varchar2(64),   error_msg tp_message_l, CONSTRUCTOR FUNCTION TP_ACTION(    usrnm in varchar2 := null ) RETURN SE...
0
2016-10-18T10:23:08Z
40,112,328
<p>The ability to bind Oracle objects is only available in the unreleased (development) version of cx_Oracle. This is needed for calling a function that returns an object. If you can make use of the development version your code will work; otherwise, please wait for the official release.</p>
0
2016-10-18T15:31:26Z
[ "python", "plsql", "cx-oracle" ]
FFT removal of periodic noise
40,105,777
<p>This a much discussed topic, but I happen to have an issue that has not been answered yet. My problem is not the method it self but rather it's applicability: My image's f(x,y) represent physical values that can be <strong>negative or positive</strong>. When I mask the peaks corresponding with, say the median, i get...
1
2016-10-18T10:27:39Z
40,106,070
<p>You could try two different approaches: Either you scale your image between the original values first, and rescale later, somewhat like this:</p> <pre><code>max_val = max(max(A)) min_val = min(min(A)) % normalize to [0,1] image = norm(image) % do your stuff here % then rescale to original values image = min_val + (...
1
2016-10-18T10:43:06Z
[ "python", "image-processing", "fft" ]
Python complete newbie, JSON formatting
40,105,864
<p>I have never used Python before but am trying to use it due to some restrictions in another (proprietary) language, to retrieve some values from a web service and return them in json format to a home automation processor. The relevant section of code below returns :</p> <pre><code>[u'Name:London', u'Mode:Auto', u'N...
-2
2016-10-18T10:32:13Z
40,106,351
<p>I wasn't able to test the code as the link you mentioned is not a live link but your solution should be something like this</p> <p>It looks like you are looking for JSON format with key value pair. you need to pass a dict object into json.dumps() which will return you string in required JSON format.</p> <pre><code...
0
2016-10-18T10:56:23Z
[ "python", "json" ]
Finding solution to a crypt equation in python
40,105,929
<p>Consider the equation ABCBA = D * BE * BFFA.The task is to determine where A, B, C, D, E and F which are distinct digits. The equation with numerical values is 91819 = 7 * 13 * 1009, hence the program should print {'A':9, 'B':1, 'C':8 , 'D':7,'E':3, 'F':0}. Here is the code i did</p> <pre><code>result=[] for A in r...
-2
2016-10-18T10:35:51Z
40,107,147
<p>If you only need your last output and want to discard everything else you can just overwrite the same variable over and over again:</p> <pre><code>result = {} for B in range(10): for C in range(10): for D in range(10): for E in range(10): for F in range(10): ...
0
2016-10-18T11:34:14Z
[ "python", "python-3.x", "cryptography", "combinations" ]
Finding solution to a crypt equation in python
40,105,929
<p>Consider the equation ABCBA = D * BE * BFFA.The task is to determine where A, B, C, D, E and F which are distinct digits. The equation with numerical values is 91819 = 7 * 13 * 1009, hence the program should print {'A':9, 'B':1, 'C':8 , 'D':7,'E':3, 'F':0}. Here is the code i did</p> <pre><code>result=[] for A in r...
-2
2016-10-18T10:35:51Z
40,107,441
<p>I don't think @Khris's answer is 100% correct, as you do need a loop for <code>A</code>, and your original question listed that first digit of any number could not be 0; hence <code>A</code>, <code>B</code>, and <code>D</code> cannot be 0, so <code>if A and D and B:</code> is added for this.</p> <p>which then resul...
0
2016-10-18T11:49:13Z
[ "python", "python-3.x", "cryptography", "combinations" ]
Scrapy Request url must be str or unicode, got NoneType:
40,105,949
<p>I try to create my first spider scrapper using scrapy I use Dmoz as test, I get an error message: TypeError: Request url must be str or unicode, got NoneType But in the Debug I can see the right url</p> <p>Code:</p> <pre><code>import scrapy import urlparse class DmozSpider(scrapy.Spider): name = "dmoz" ...
0
2016-10-18T10:36:37Z
40,106,256
<p>The error is in your code here:</p> <pre><code>if next_page is not None: next_page = response.urljoin(next_page) yield scrapy.Request(next_page, callback=self.parse) </code></pre> <p>As Padraic Cunningham mentions in his commit: you <code>yield</code> the <code>Request</code> regardless of <code>nex...
1
2016-10-18T10:52:16Z
[ "python", "web-scraping", "scrapy", "scrapy-spider" ]
Have an index error I don't know how to correct
40,106,053
<p>I found this code elsewhere on the site, but for some reason I keep getting the same error message:</p> <pre><code>products[row[0]] = [row[1], row[2], row[3]] IndexError: list index out of range. </code></pre> <p>I am unsure how to correct this, any help is appreciated, thanks. </p> <p>This is the code:</p> <pre...
0
2016-10-18T10:42:12Z
40,112,696
<p>Please check your input file 'stockfile.txt', at least one line of your file don't have 3 or more ",". Or you have some blank lines between your data.</p>
0
2016-10-18T15:47:32Z
[ "python", "indexoutofboundsexception" ]
remove control character whitespaces from dataframe
40,106,074
<p>I have a dataframe df by which I am getting list of list by using this</p> <pre><code>data = [list(map(str,n.tolist())) for n in df.values] </code></pre> <p>after that I replace specific control character from data like this </p> <pre><code>data = [ [e.replace(u'\xa0', u'') for e in tempval ] for tempval in data ...
1
2016-10-18T10:43:15Z
40,106,421
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>DataFrame.replace</code></a>:</p> <pre><code>df = pd.DataFrame({'A':['\xa0','s','w'], 'B':['s','w','v'], 'C':['e','d','\xa0']}) print (df) A B C ...
0
2016-10-18T10:59:39Z
[ "python", "list", "pandas", "replace", "dataframe" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,138
<p>Basic approach:</p> <pre><code>&gt;&gt;&gt; a = [[0,1],[2,3]] &gt;&gt;&gt; b = [[5,6],[7,8]] &gt;&gt;&gt; c = [] &gt;&gt;&gt; for pair in zip(a,b): ... c.extend(pair) ... &gt;&gt;&gt; c [[0, 1], [5, 6], [2, 3], [7, 8]] &gt;&gt;&gt; </code></pre> <p>This breaks if the lengths aren't equal. But you can deal with...
6
2016-10-18T10:46:38Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,170
<p>Consider:</p> <pre><code>merged = [] for a_element, b_element in zip(a, b): merged.append(a_element) merged.append(b_element) </code></pre> <p>Unless you have very stringent performance requirements, the simplest approach is the right approach.</p>
1
2016-10-18T10:48:09Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,178
<p>You could <code>zip</code> the two lists and then reduce them to a flat list:</p> <pre><code>import operator c = reduce(operator.concat, zip(a, b)) </code></pre>
2
2016-10-18T10:48:25Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,269
<p>Assuming len(a) == len(b) and you're adding them one by one in turn:</p> <pre><code>for i in range(len(a)): c.append(a[i]) c.append(b[i]) </code></pre> <p>However, I would recommend to use <code>c = deque()</code>. Since deques are much quicker if you are making a lot of appends.</p>
0
2016-10-18T10:52:46Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,413
<p>Assuming the two lists are the same length, the most compact way to do this uses <code>itertools.chain</code> and <code>zip</code>.</p> <pre><code>from itertools import chain a = [[0,1],[2,3],[10,11],[12,13]] b = [[5,6],[7,8],[15,16],[17,18]] c = [*chain(*zip(a, b))] print(c) </code></pre> <p><strong>output</str...
2
2016-10-18T10:59:10Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,860
<p>Another very simple approach using <em>string slicing</em> (and <strong>most performance efficient</strong>) as:</p> <pre><code>&gt;&gt;&gt; a = [[0,1],[2,3]] &gt;&gt;&gt; b = [[5,6],[7,8]] &gt;&gt;&gt; c = a + b # create a list with size = len(a) + len(b) &gt;&gt;&gt; c[::2], c[1::2] = a, b # alternately insert t...
2
2016-10-18T11:20:54Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,120,558
<p>Using <a href="https://pythonhosted.org/more-itertools/api.html" rel="nofollow"><code>more_itertools</code></a> which implements the <code>itertools</code> <a href="https://docs.python.org/2/library/itertools.html#recipes" rel="nofollow"><code>roundrobin</code> recipe</a></p> <pre><code>&gt;&gt;&gt; from more_itert...
0
2016-10-19T01:21:42Z
[ "python", "list", "append" ]
How to bind the return key to a function on the frame/form itself
40,106,166
<p>I'm making an app which has a sort of splash screen made in tkinter, and I would like it to close and call and run another part of the app, however i cannot for the life of me figure out why my bind won't work.</p> <p>Do keep in mind I started python about 2 weeks ago so I'm still very much a learner, any help woul...
1
2016-10-18T10:47:53Z
40,109,836
<p>This time as an answer and I hope it helps.</p> <p>The following works for me:</p> <pre><code>import Tkinter as tk class simpleapp_tk(tk.Tk): def __init__(self, parent): ## class derives from Tkinter --&gt; call its constructor tk.Tk.__init__(self, parent) ## keep track of the parent ...
0
2016-10-18T13:37:13Z
[ "python", "user-interface", "tkinter", "binding", "key" ]
How can I make this loop stop at a certain variable occurs
40,106,179
<p>I need to write a script that generates random numbers between 1-257000 and stops when a certain number occurs telling me how many numbers it generated so far.</p> <p>i manged to get this far but can't seem to get it to stop or count</p> <pre><code>x=1 while x &lt; 257000: import itertools import random ...
-1
2016-10-18T10:48:30Z
40,106,427
<p>Huh. A few flaws (or at least unclear spots) in your code.</p> <ol> <li><p>You run your loop max 257000 times. Even though the probability is low, there is a chance that you don't hit the number you seek in the loop.</p></li> <li><p>Move your <code>import</code> statements out of your loop, no need to have python c...
2
2016-10-18T10:59:44Z
[ "python", "python-2.7", "loops", "random" ]
How can I make this loop stop at a certain variable occurs
40,106,179
<p>I need to write a script that generates random numbers between 1-257000 and stops when a certain number occurs telling me how many numbers it generated so far.</p> <p>i manged to get this far but can't seem to get it to stop or count</p> <pre><code>x=1 while x &lt; 257000: import itertools import random ...
-1
2016-10-18T10:48:30Z
40,106,475
<p>First, put your <code>import</code> statements and your function definitons <em>outside</em> your while-loop. That's being <strong>super</strong> redundant.</p> <pre><code>&gt;&gt;&gt; def random_gen(low,high): ... while True: ... yield random.randrange(low,high) ... &gt;&gt;&gt; lucky = 7 &gt;&gt;&gt; rg = ...
0
2016-10-18T11:02:12Z
[ "python", "python-2.7", "loops", "random" ]
Python Import specific file or directory
40,106,345
<p>I want to import file 'a' into file 'b' how to do it ? I tried with os,sys etc but it doesnt work for me. I just want to go 2 folders up and go into file a. I hope that its understable.</p> <p>file a : C:\Web\Tests\Current\Automated tests\Common\extensions\file.py</p> <p>file b: C:\Web\Tests\Current\Automated test...
0
2016-10-18T10:56:18Z
40,106,771
<p>At top of file b, append file a path into sys.path</p> <p>For your case, added line below into file_b.py</p> <pre><code>sys.path.append(r'C:\Web\Tests\Current\Automated tests\Common\extensions') import file_a </code></pre>
0
2016-10-18T11:16:19Z
[ "python", "file", "import", "directory" ]
Python Import specific file or directory
40,106,345
<p>I want to import file 'a' into file 'b' how to do it ? I tried with os,sys etc but it doesnt work for me. I just want to go 2 folders up and go into file a. I hope that its understable.</p> <p>file a : C:\Web\Tests\Current\Automated tests\Common\extensions\file.py</p> <p>file b: C:\Web\Tests\Current\Automated test...
0
2016-10-18T10:56:18Z
40,130,997
<pre><code>import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..' , 'Common' , 'extensions')) import library </code></pre> <p>this resolved my problem thanks !</p>
0
2016-10-19T12:07:08Z
[ "python", "file", "import", "directory" ]
How do I declare a line in a text file as a variable?
40,106,389
<p>For example, I have opened a text file and found a product that the user wants to "buy". The products are listed on a notepad text file, with the product name then a new line then the cost of the product, for example</p> <pre><code>radiators 0.50 fridge 0.50 </code></pre> <p>This is what I have done so far:</p> <...
0
2016-10-18T10:58:00Z
40,106,495
<p>Try this out :</p> <p>product = input("What product would you like?")</p> <pre><code>userfile = open ("products.txt","r") lines = userfile.readlines() for line in lines: line = line.rstrip('\n') if product in line: found = True print("Found " + line) print("This product is " + lines[...
0
2016-10-18T11:03:20Z
[ "python", "file", "lines", "readlines" ]
Python IndexError handling
40,106,437
<pre><code>def kindDetector(list): for i in range(0,len(list)): if type(list[i]) != type('a'): return 0 return 1 def findWords(list,i): if i == 0: return list[0] if list[i] &lt; findWords(list,i-1): return list.pop(i) else: return list.pop(i-1) def sortW...
1
2016-10-18T11:00:16Z
40,106,977
<p>You have mixed <em>BubbleSort</em> (i.e. comparing neighbors and trying to shift them one at a time until the list is sorted) with <em>SelectionSort</em> (i.e. find the <em>smallest</em> item from an unsorted list and append it to the front of a resulting list).</p> <p>And, there are a few more problems here:</p> ...
3
2016-10-18T11:26:09Z
[ "python", "python-3.x" ]
Python escape sequence complex output
40,106,468
<p>When I am writing the following command in Python IDLE it will give you the output with quotes, I want to know why it is giving such output.</p> <pre><code>x='''''abc\'abcddd''''' print x </code></pre> <p>This is output of the written code.</p> <pre><code>''abc'abcddd </code></pre>
3
2016-10-18T11:01:36Z
40,106,599
<p>It is due to pythons triple quoted strings:</p> <pre><code>''' ''' </code></pre> <p>It interprets everything in between as a character. So in your string:</p> <pre><code>'''''abc\'abcddd''''' </code></pre> <p>The first three quotes 'open' the string. Than it encounters 2 quotes, which it interprets as characters...
2
2016-10-18T11:08:16Z
[ "python", "string", "escaping", "sequence" ]
Theano shared variable constructor error
40,106,537
<p>weights is a list of Numpy ndarray </p> <pre><code>WEIGHTS = [] for weight in weights: WEIGHTS.append(Theano.shared(Numpy.array(weight), dtype = Theano.config.floatX)) </code></pre> <p>Error:</p> <pre><code> No suitable SharedVariable constructor could be found. Are you sure all kwargs are supported? We ...
0
2016-10-18T11:05:02Z
40,106,793
<p>The shared function don't support the dtype parameter. It is numpy that support it. Error Resolved!</p>
0
2016-10-18T11:17:27Z
[ "python", "numpy", "theano" ]
KeyError in JSON request Python - NYT API
40,106,794
<p>I am trying to extract the URL of specific articles from NYT API. This is my code:</p> <pre><code>import requests for i in range(0,100): page=str(i) r = requests.get("http://api.nytimes.com/svc/search/v2/articlesearch.json?begin_date=20100101&amp;q=terrorist+attack&amp;page="+page+"&amp;api-key=***") ...
-1
2016-10-18T11:17:37Z
40,111,097
<p>You are assuming that there are at least 101 pages to make requests (0 to 100).</p> <p>If you make a request to page 100, do you still get the same JSON structure with a <code>response</code> key?</p> <p>What you should instead use is a while loop that breaks when you get a <code>KeyError</code>.</p>
0
2016-10-18T14:34:14Z
[ "python" ]
How to make nested xml structure flat with python
40,106,821
<p>I have XML with huge nested structure. Like this one </p> <pre><code>&lt;root&gt; &lt;node1&gt; &lt;subnode1&gt; &lt;name1&gt;text1&lt;/name1&gt; &lt;/subnode1&gt; &lt;/node1&gt; &lt;node2&gt; &lt;subnode2&gt; &lt;name2&gt;text2&lt;/name2&gt; &lt;/subnode2&gt; &lt;/node2&gt; &lt;/root&gt; </cod...
0
2016-10-18T11:19:07Z
40,110,597
<p>A few points to mention here: </p> <p>Firstly, your test <code>element.text is not None</code> always returns <code>True</code> if you parse your XML file as given above using <code>xml.etree.Elementree</code> since at the end of each node, there is a new line character, hence, the text in each supposedly not-havin...
1
2016-10-18T14:12:54Z
[ "python", "xml" ]
'QuerySet' object doesn't support item deletion Error
40,106,858
<p>I am trying to delete an Item in the QuerySet by Index. I am able to display the items of the QuerySet using <code>print q_set[code_id - 1]</code> but can not delete it using <code>del q_set[code_id - 1]</code>. I want to permanently delete the item and not filter excluding that item.</p> <p>I am getting this error...
0
2016-10-18T11:20:48Z
40,107,130
<p>To <em>permanently</em> get rid of the entry, you don't want to remove the item from the queryset (which is just a volatile view onto your data), but <a href="https://docs.djangoproject.com/en/1.10/ref/models/instances/#deleting-objects" rel="nofollow">delete the row</a> from the database:</p> <pre><code>q_set[code...
4
2016-10-18T11:33:28Z
[ "python", "django" ]
How to plot one column in different graphs?
40,106,923
<p>I have the following problem. I have this kind of a dataframe:</p> <pre><code>f = pd.DataFrame([['Meyer', 2], ['Mueller', 4], ['Radisch', math.nan], ['Meyer', 2],['Pavlenko', math.nan]]) </code></pre> <p>is there an elegant way to split the DataFrame up in several dataframes by the first collumn? So, I would like ...
1
2016-10-18T11:23:53Z
40,107,149
<p>You can loop by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unique.html" rel="nofollow"><code>unique</code></a> values of column <code>A</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:<...
0
2016-10-18T11:34:19Z
[ "python", "pandas", "dataframe" ]
Calculate the equation given a string
40,106,976
<p>Given a random equation (with plus and multiply), calculate the result. </p> <p>For example, given, "5 + 3 * 4 * 2 + 1", return 30.</p> <p>This was a question I was given on a programming interview (a year ago) and was told to do it in at least 0(n) time. </p> <p>I attempted to do it in python. </p>
-1
2016-10-18T11:26:09Z
40,107,056
<p>Built-in function <code>eval()</code> <strong><em>not recommended</em></strong> as a go-to, but is rather quite helpful in this particular case:</p> <pre><code>string = "5 + 3 * 4 * 2 + 1" print (eval(string)) # 30 </code></pre> <p>Though there are quite an amount of side-effects and risks using <code>eval()</code...
2
2016-10-18T11:29:24Z
[ "python", "math", "equation" ]
Calculate the equation given a string
40,106,976
<p>Given a random equation (with plus and multiply), calculate the result. </p> <p>For example, given, "5 + 3 * 4 * 2 + 1", return 30.</p> <p>This was a question I was given on a programming interview (a year ago) and was told to do it in at least 0(n) time. </p> <p>I attempted to do it in python. </p>
-1
2016-10-18T11:26:09Z
40,107,125
<p>You can write your expression in the form</p> <p><code>expression = term + term + ... + term</code></p> <p>and a term as</p> <p><code>term = value * value * ... * value</code></p> <p>This is an informal way of specifying the <em>grammar</em> for your expression. You ought to recognise that the evaluation of an e...
0
2016-10-18T11:32:55Z
[ "python", "math", "equation" ]
Calculate the equation given a string
40,106,976
<p>Given a random equation (with plus and multiply), calculate the result. </p> <p>For example, given, "5 + 3 * 4 * 2 + 1", return 30.</p> <p>This was a question I was given on a programming interview (a year ago) and was told to do it in at least 0(n) time. </p> <p>I attempted to do it in python. </p>
-1
2016-10-18T11:26:09Z
40,107,396
<p>Another solution would be to convert your (infix) math expression to postfix, which is easy to evaluate using a stack. If you're interested here's a nice site describing the conversion as well as the evaluation/calcuation of a postfix-expression:</p> <p><a href="http://interactivepython.org/runestone/static/pythond...
0
2016-10-18T11:46:39Z
[ "python", "math", "equation" ]
Calculate the equation given a string
40,106,976
<p>Given a random equation (with plus and multiply), calculate the result. </p> <p>For example, given, "5 + 3 * 4 * 2 + 1", return 30.</p> <p>This was a question I was given on a programming interview (a year ago) and was told to do it in at least 0(n) time. </p> <p>I attempted to do it in python. </p>
-1
2016-10-18T11:26:09Z
40,109,390
<p>Assuming you didn't want to use eval, you can try and do this inline. </p> <p>A good problem solving technique for this kind of question is to write out what you would want to happen. </p> <p>If you are looking at this item by item, you will notice that when we have addition, you can safely add all the previous re...
2
2016-10-18T13:17:20Z
[ "python", "math", "equation" ]
Changing Basemap projection causes beach balls / data to disappear (obspy)
40,107,244
<p>There's a very similar problem to my problem <a href="http://stackoverflow.com/questions/28776931/changing-basemap-projection-causes-data-to-disappear">here</a>, but the solution recommended on this page does not work in my case. For projection 'cyl', beach balls are plotted. Changing this projection to 'robin' (ro...
0
2016-10-18T11:38:56Z
40,127,045
<p>The problem lies it seems with the projection and the axis or data coordinates transformation. When the width was changed from 10 to 1000000, then this resolves the issue:</p> <pre><code>b = beach(focmecs[i], facecolor=beachball_color, xy=(x[i], y[i]), width=1000000, linewidth=1, alpha=0.85) </code></pre>
0
2016-10-19T09:14:10Z
[ "python", "matplotlib-basemap" ]
pip install paramiko failed with error code 1
40,107,369
<p>While trying to install paramiko on my fedora I get the following error:</p> <pre><code>[mmorasch@michimorasch ~]$ sudo pip install paramiko Collecting paramiko Using cached paramiko-2.0.2-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): pyasn1&gt;=0.1.7 in /usr/lib/python2.7/site-p...
0
2016-10-18T11:45:23Z
40,107,429
<p>Try</p> <pre><code>sudo dnf install redhat-rpm-config sudo yum install python-devel sudo yum install libevent-devel </code></pre> <p>and finally:</p> <pre><code>easy_install gevent </code></pre>
1
2016-10-18T11:48:36Z
[ "python", "fedora", "paramiko" ]
How to convert this Python code to R?
40,107,428
<p>,I need help with translating a python code into an R code.</p> <p>I have a data frame df, that contains the column IndicatorOfDefault and I would like too generate a column named indvalues.</p> <p>Example:</p> <pre><code>row number IndicatorOfDefault indvalues 823602 P 0 8...
-2
2016-10-18T11:48:21Z
40,114,085
<p>Since R does not have the dictionary object, the best translation will be a named list. Do note: R does not allow zero-length names, so <em>N0</em> is used. From there you can use R's <code>vapply()</code> and <code>strsplit()</code> to string split the column and find its corresponding max value. Specifically, <cod...
0
2016-10-18T17:02:02Z
[ "python", "dataframe" ]
Python tkinter change variable label state and statusbar
40,107,452
<p>I do have a little problem here. It's about the exchange of variables of a label in TKinter. My program won't refresh the value's.</p> <pre><code>class Application(Frame): def __init__(self,parent,**kw): Frame.__init__(self,parent,**kw) self.x = None self.directory = None sel...
0
2016-10-18T11:49:43Z
40,108,270
<p>Below is an example program that should help you figure out how to change the text of labels. They key thing is creating a StringVar and pointing the label towards this so that the label is updated when the StringVar is.</p> <pre><code>from Tkinter import * class Application(Frame): def __init__(self,parent,**...
0
2016-10-18T12:28:08Z
[ "python", "class", "tkinter" ]
Python tkinter change variable label state and statusbar
40,107,452
<p>I do have a little problem here. It's about the exchange of variables of a label in TKinter. My program won't refresh the value's.</p> <pre><code>class Application(Frame): def __init__(self,parent,**kw): Frame.__init__(self,parent,**kw) self.x = None self.directory = None sel...
0
2016-10-18T11:49:43Z
40,108,341
<p>The error is in the <code>Label</code> arguments: a tekst arguments is <em>not</em> updated if the input-variable is updated. You should assign the <code>stateVar</code> to the <code>Label</code>'s <code>textvariable</code> keyword argument and use no <code>text</code> argument.</p>
0
2016-10-18T12:31:34Z
[ "python", "class", "tkinter" ]
Indexing and slicing dataframe by date and time in python
40,107,591
<p>I have time a series datasets. I can select data from march to may by this code: </p> <pre><code>df[(df.index.month &gt;=3) &amp; (df.index.month&lt;=5)] </code></pre> <p>But the problem is how to select the data from <code>march-15</code> to <code>may-15</code>? Any help will be highly appreciated.</p> <p>and m...
1
2016-10-18T11:55:08Z
40,108,250
<p>You can use helper <code>Series</code> <code>s</code> where all years are replaced to same - e.g. <code>2000</code>:</p> <pre><code>print (df) A 2001-02-25 0.01 2002-02-26 0.03 2003-02-27 1.00 2004-02-28 1.52 2005-03-29 0.23 2006-03-01 0.45 2007-03-05 2.15 2008-03-06 1.75 s = pd.Series(df.in...
2
2016-10-18T12:26:45Z
[ "python", "pandas", "numpy", "dataframe" ]
Open file to read from web form
40,107,604
<p>I am working on a project where I have to upload a file from file storage (via web form) to MongoDB. In order to achieve this, I need to open the file in "rb" mode, then encode the file and finally upload to MongoDb. I am stuck when opening the file "rb" mode.</p> <pre><code> if form.validate(): for inFi...
1
2016-10-18T11:55:46Z
40,107,680
<p>The <code>FileStorage</code> object is already file-like so you can use as a file. You don't need to use <code>open</code> on it, just call <code>inFile.read()</code>.</p> <p>If this doesn't work for you for some reason, you can save the file to disk first using <code>inFile.save()</code> and open it from there.</p...
0
2016-10-18T11:59:17Z
[ "python", "flask" ]
(possibly grouped) Row Values to Columns
40,107,657
<p>Let's say, after some groupby operation I have a dataframe like this:</p> <pre><code>data = pd.DataFrame(columns=['Key', 'Subkey', 'Value']) data.loc[0] = ['foo1', 'bar1', 20] data.loc[1] = ['foo1', 'bar2', 10] data.loc[2] = ['foo1', 'bar3', 5] data.loc[3] = ['foo2', 'bar1', 50] data.loc[4] = ['foo2', 'bar2', 100] ...
1
2016-10-18T11:58:19Z
40,107,752
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a>:</p> <pre><code>print (data.pivot(index='Key', columns='Subkey', values='Value')) Subkey bar1 bar2 bar3 Key foo1 20.0 10.0 5.0 foo2 50.0 ...
2
2016-10-18T12:02:30Z
[ "python", "pandas" ]
finding a special path string in HTML text in python
40,107,690
<p>I'm trying to extract a path in an HTML file that I read. In this case the path that I'm looking for is a logo from google's main site.</p> <p>I'm pretty sure that the regular expression I defined is right, but I guess I'm missing something.</p> <p>The code is:</p> <pre><code>import re import urllib a=urllib.urlo...
2
2016-10-18T11:59:35Z
40,107,854
<p>this can help you:</p> <pre><code>re.search(r'\"\/.+\"',Text).group(0) </code></pre> <p>result:</p> <pre><code>&gt;&gt;&gt; re.search(r'\"\/.+\"',Text).group(0) '"/images/branding/googleg/1x/googleg_standard_color_128dp.png"' </code></pre>
0
2016-10-18T12:07:53Z
[ "python", "regex", "expression" ]