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
How can I reverse a section of a list using a loop in Python?
37,461,321
<p>I'm in need of a little help reversing a section of a list in Python <strong>using a loop.</strong></p> <p>I have a list: <code>mylist = ['a', 'b', 'c', 'd', 'e', 'f']</code></p> <p>Also have an index number, this number will tell where to start the reversing. For example, if the reverse-index number is 3, it need...
2
2016-05-26T12:47:29Z
37,462,176
<p>The pythonic solution: </p> <pre><code>list1[reverse_index::-1] + list1[reverse_index+1:] </code></pre> <p>Now, that's not using loops like you asked. Well, not explicitly... Instead we can break down the above into its constituent for loops.</p> <pre><code>def list_section_reverse(list1, reverse_index): if r...
2
2016-05-26T13:24:46Z
[ "python", "list", "function", "loops", "reverse" ]
How can I reverse a section of a list using a loop in Python?
37,461,321
<p>I'm in need of a little help reversing a section of a list in Python <strong>using a loop.</strong></p> <p>I have a list: <code>mylist = ['a', 'b', 'c', 'd', 'e', 'f']</code></p> <p>Also have an index number, this number will tell where to start the reversing. For example, if the reverse-index number is 3, it need...
2
2016-05-26T12:47:29Z
37,462,453
<p>Is it allowed to make a copy of the list?</p> <pre><code>def list_section_reverse(list1, reverse_index): print("In function reverse()") n_list = [ element for element in list1 ] for item in range( reverse_index + 1 ): n_list[ item ] = list1[ reverse_index - item ] item += 1 return...
0
2016-05-26T13:35:26Z
[ "python", "list", "function", "loops", "reverse" ]
How can I reverse a section of a list using a loop in Python?
37,461,321
<p>I'm in need of a little help reversing a section of a list in Python <strong>using a loop.</strong></p> <p>I have a list: <code>mylist = ['a', 'b', 'c', 'd', 'e', 'f']</code></p> <p>Also have an index number, this number will tell where to start the reversing. For example, if the reverse-index number is 3, it need...
2
2016-05-26T12:47:29Z
37,462,716
<p>You can modify the list inplace using a slice.</p> <pre><code>mylist[:4] = mylist[:4][::-1] </code></pre>
0
2016-05-26T13:46:48Z
[ "python", "list", "function", "loops", "reverse" ]
scrapy CONCURRENT_REQUESTS ignored when DOWNLOAD_DELAY set?
37,461,327
<p>Looking at the scrapy stats (<code>Crawled X pages (at X pages/min)</code>) seems to me that as soon as, e.g.:</p> <pre><code>DOWNLOAD_DELAY = 4.5 </code></pre> <p>is set the requests become sequential no matter what the <code>CONCURRENT_REQUESTS</code> setting is.</p> <p>From my understanding, shouldn't the dela...
0
2016-05-26T12:47:39Z
37,464,077
<p><code>CONCURRENT_REQUESTS</code> is just a way to hold requests in general, so if you are using any other settings (which are usually enforced by domain), there is no problem on setting <code>CONCURRENT_REQUESTS</code> to a high number.</p> <p>The <code>DOWNLOAD_DELAY</code> is used by domain which is correct as th...
1
2016-05-26T14:42:02Z
[ "python", "scrapy" ]
Seaborn despine with two y-scales (twinx)
37,461,434
<p>How can I keep <code>seaborn.despine</code> from putting both of my y-scales onto the left side of my plot? The best I've come up with so far is:</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns import numpy as np sns.set_style("white") fig, ax = plt.subplots() ax.plot(np.random.rand(10)) ax2 ...
0
2016-05-26T12:52:05Z
37,464,017
<p>I guess that's what you want then.</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns import numpy as np sns.set_style("white") fig, ax = plt.subplots() ax.plot(np.random.rand(10)) ax2 =ax.twinx() ax2.plot(100*np.random.rand(10)) sns.despine(ax=ax, right=True, left=True) sns.despine(ax=ax2, left...
1
2016-05-26T14:40:00Z
[ "python", "matplotlib", "seaborn" ]
trying to assign a variable in an if statement using buttons as the entrance condition
37,461,493
<p>This is my code for trying to get the price of a venue:</p> <pre><code># number of people header = "Number of People" people = ["10-25", "26-50", "51-100", "101-500", "501-1000", "1000+"] button = buttonbox("around how many people will attend",title= header,choices=people) # choosing the venue if button == people[...
1
2016-05-26T12:54:53Z
37,462,834
<p><code>button</code> can't equal both <code>people[0]</code> and <code>venueZero[0]</code> at the same time, therefore the condition in the if statement will never be met so <code>venuePrice</code> won't be set.</p> <p>You could use a different variable name for the second choice:</p> <pre><code># number of people ...
0
2016-05-26T13:50:50Z
[ "python", "python-2.7" ]
Python inheritance dilemma for plugin
37,461,620
<p><em>Although this question is in the context of a Sublime Text plugin, it is actually a question about Python object orientated design.</em></p> <p>Writing a Sublime Text plugin which contains 2 complimentary commands (with some shared functionality) has led me to a Python inheritance dilemma. Both options work per...
2
2016-05-26T12:59:59Z
37,565,740
<p>Implementing r-stein's suggestion provides a solution to the plugin inheritance dilemma by using a non-OO design.</p> <pre class="lang-py prettyprint-override"><code>import sublime, sublime_plugin def copy_line(view): sels = view.sel() # Do some stuff return line_region class CopyLineCommand(sublime_p...
0
2016-06-01T10:13:01Z
[ "python", "inheritance", "sublime-text-plugin" ]
Python Custom Formatters
37,461,693
<p>I'm writing a program that processes contracts that expire different months.</p> <p>For example, a corn futures contract which expires in December 2016 would be called:</p> <pre><code>CZ2016 </code></pre> <p>where C means 'corn', Z means December (it's custom).</p> <p>Internally I represent everything as <code>(...
0
2016-05-26T13:03:16Z
37,463,098
<p>Here's something quick(ish):</p> <pre><code>#!python3 import collections import time class FuturesContract: Commodity = collections.namedtuple('Commodity', 'symbol future exchange delivery_months') Commodities = [ # Source: http://www.mrci.com/web/online-explanation-pages/symbols-a-cod...
3
2016-05-26T14:01:26Z
[ "python", "python-3.x" ]
Redis blpop sometimes return tuple, sometime not?
37,461,737
<p>I use the following code to place/retrieve items in my Redis queue but I sometime get an error when decoding the json dump, because the item returned is not a tuple but the full json.</p> <p>Here's the class :</p> <pre><code>class RedisQueue(object): """Simple Queue with Redis Backend""" def __init__(self,...
2
2016-05-26T13:05:32Z
37,473,940
<p>Because you are issuing two different commands, and each command returns something different.</p> <p><a href="http://redis.io/commands/blpop" rel="nofollow"><code>LPOP</code></a> returns the item popped. It only takes a single key. <a href="http://redis.io/commands/blpop" rel="nofollow"><code>BLPOP</code></a> howev...
1
2016-05-27T02:36:31Z
[ "python", "json", "redis" ]
pip freeze: show only packages installed via pip
37,461,798
<p>I want to know which python packages are installed via pip and which are installed via rpm.</p> <p>I run <strong>outside</strong> any virtualenv, and want to know if there are some packages installed via pip. </p> <p>Background: Our policy is to use RPM at "root level". I want to find places where the policy was b...
5
2016-05-26T13:08:05Z
37,560,183
<p>Assumptions:</p> <ul> <li>I'm not sure about red-hat, but for debian/ubuntu.</li> <li>I'm assuming you are using system python.</li> <li>I don't think it matters, but you might have to check <code>pip install --user &lt;package_name&gt;</code> for local user package installs.</li> </ul> <p>By default on debian sys...
1
2016-06-01T05:33:16Z
[ "python", "pip" ]
pip freeze: show only packages installed via pip
37,461,798
<p>I want to know which python packages are installed via pip and which are installed via rpm.</p> <p>I run <strong>outside</strong> any virtualenv, and want to know if there are some packages installed via pip. </p> <p>Background: Our policy is to use RPM at "root level". I want to find places where the policy was b...
5
2016-05-26T13:08:05Z
37,641,344
<p>How about turn the question around slightly, and just check what belongs to rpms and what doesn't. Try:</p> <pre><code>import os, sys, subprocess, glob def type_printed(pth, rpm_dirs=False): if not os.path.exists(pth): print(pth + ' -- does not exist') return True FNULL = open(os.d...
2
2016-06-05T11:29:16Z
[ "python", "pip" ]
Odoo/Python: modules dependencies gone wrong?
37,461,841
<p>I have these modules:</p> <p><code>base_module</code>, <code>module_1</code> <code>base_module_extend</code>, <code>module_2</code>.</p> <p>These modules have such dependencies:</p> <ul> <li><code>module_1</code> depends on <code>base_module</code>. </li> <li><code>base_module_extend</code> depends on <code>base...
3
2016-05-26T13:09:58Z
37,900,182
<p><em>super()</em> tends to choose wrong(unexpected) parent in Python. As an alternative you can use direct call of Python function from the desired superclass, instead of using <em>super()</em>, this is much more reliable way. </p> <p>I do not know a directory structure and source file names of your Odoo module, so ...
0
2016-06-18T18:15:10Z
[ "python", "python-2.7", "dependencies", "openerp", "python-module" ]
python interactive plot newest line in color, rest in black
37,462,003
<p>I am trying to plot multiple lines in Python using <code>matplotlib</code> using <code>plt.waitforbuttonpress(-1)</code> so that I can analyse each new line separately. But when doing this I would like the newest line to have a color and the rest to be black. I know how to give a new line a color, but I can't seem t...
3
2016-05-26T13:17:18Z
37,462,319
<p>You could loop over the old lines and set the line color, before plotting the new one with a certain color. Unfortunately <code>plt.waitforbuttonpress()</code> doesn't seem to work on my computer, but something like this:</p> <pre><code>import numpy as np import matplotlib.pylab as pl pl.figure() ax=pl.subplot(111...
3
2016-05-26T13:30:15Z
[ "python", "matplotlib", "colors", "reset", "interactive" ]
python interactive plot newest line in color, rest in black
37,462,003
<p>I am trying to plot multiple lines in Python using <code>matplotlib</code> using <code>plt.waitforbuttonpress(-1)</code> so that I can analyse each new line separately. But when doing this I would like the newest line to have a color and the rest to be black. I know how to give a new line a color, but I can't seem t...
3
2016-05-26T13:17:18Z
37,462,324
<p>You can use <code>line.set_color('k')</code> to set the colour of the line after plotting it, where <code>line</code> is a matplotlib <code>Line2D</code> instance. Luckily we can access all the lines from a <code>Axes</code> instance in the list <code>ax.lines</code>, so its just a case of looping over that list and...
1
2016-05-26T13:30:25Z
[ "python", "matplotlib", "colors", "reset", "interactive" ]
Write unbuffered on python 3
37,462,011
<p>I'm trying to create a file on python without buffer, so its written at the same time I use write(). But for some reason I got an error.<br/> This is the line I'm using:<br/><br/> <code>my_file = open("test.txt", "a", buffering=0) my_file.write("Testing unbuffered writing\n")</code><br/><br/> And this is the error I...
0
2016-05-26T13:17:33Z
37,462,310
<p>use </p> <pre><code>my_file = open("test.txt", "a") my_file.write("Testing unbuffered writing\n") my_file.flush() </code></pre> <p>Always call flush immediately after the write and it will be "as if" it is unbuffered</p>
2
2016-05-26T13:29:50Z
[ "python", "pycharm" ]
Write unbuffered on python 3
37,462,011
<p>I'm trying to create a file on python without buffer, so its written at the same time I use write(). But for some reason I got an error.<br/> This is the line I'm using:<br/><br/> <code>my_file = open("test.txt", "a", buffering=0) my_file.write("Testing unbuffered writing\n")</code><br/><br/> And this is the error I...
0
2016-05-26T13:17:33Z
37,462,452
<p>The error isn't from Pycharm.</p> <p>The Python doc says:</p> <blockquote> <p>buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off <strong>(only allowed in binary mode)</strong></p> </blockquote> <p>Your code will work in <strong>Python 2</strong> but not in <stron...
3
2016-05-26T13:35:17Z
[ "python", "pycharm" ]
Confusing about StringIO, cStringIO and ByteIO
37,462,075
<p>I have googled and also search on SO for the difference between these buffer modules. However, I still don't understand very well and I think some of the posts I read are out of date.</p> <p>In Python 2.7.11, I downloaded a binary file of a specific format using <code>r = requests.get(url)</code>. Then I passed <co...
4
2016-05-26T13:20:29Z
37,463,095
<p>You should use <code>io.StringIO</code> or <code>io.BytesIO</code>, depending on whether your data is binary, in both python 2 and 3, for forwards-compatibility (this is all 3 has to offer).</p> <hr> <p>Here's a better test (for python 2 and 3), that doesn't include conversion costs from numpy to <code>str</code>/...
4
2016-05-26T14:01:22Z
[ "python", "stringio", "bytesio", "cstringio" ]
Subtract an image from an other one
37,462,127
<p>I am trying to subtract an average image from an other. Here is what I did :</p> <pre><code>Avv=Image.open("Average.tiff") os.chdir("D://ESSAI_1//Bulle") dir_bubble=os.listdir("D://ESSAI_1//Bulle") tiff_bubble=[filename for filename in dir_bubble if filename[-5:] ==".tiff"] new_image = ImageChops.subtract(tiff_bub...
0
2016-05-26T13:22:46Z
37,462,394
<p><code>new_image = ImageChops.subtract(tiff_bubble, Avv)</code></p> <p><code>subtract</code>'s first argument should be an Image object. <code>tiff_bubble</code> is not an Image object, it is a list of strings.</p> <p>Try making <code>tiff_bubble</code> an Image.</p> <pre><code>possible_filenames = [filename for f...
1
2016-05-26T13:33:38Z
[ "python", "image" ]
Rotate a figure but not the legend
37,462,130
<p>I have a figure that I want to rotate by 90 degrees. The problem is that also the legend rotates. </p> <p>Is there a way to rotate only the figure? Even be able to set the rotation attribute of the legend to 90 degrees would be fine. </p> <p>For the xticks for example I am using <code>plt.xticks(range(len(mu_mse....
3
2016-05-26T13:22:51Z
37,467,828
<p>You can check the demo example about <a href="http://matplotlib.org/examples/axes_grid/demo_floating_axes.html" rel="nofollow">floating axes</a> for several uses of rotation. In this case you will only rotate the axes and than make the normal call for a legend.</p> <p>You'll need to make the adjustments for positio...
2
2016-05-26T17:49:30Z
[ "python", "matplotlib", "rotation" ]
Python in AzureML fail to pass dataframe without changes
37,462,268
<p>when trying to pass data without doing anything in python, getting this error:</p> <pre><code>Error 0085: The following error occurred during script evaluation, please view the output log for more information: ---------- Start of error message from Python interpreter ---------- Caught exception while executing func...
3
2016-05-26T13:28:21Z
38,290,105
<p>after talking to Microsoft support, the problem was that the "Execute Python Script" module cannot return empty values. this can be solved by adding a "Clean Missing Data" module before reading it from python: <a href="http://i.stack.imgur.com/BzCUZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/BzCUZ.png" a...
0
2016-07-10T08:36:14Z
[ "python", "python-2.7", "pandas", "cortana-intelligence", "azure-ml" ]
Confused by using too many for loops, if and else statements
37,462,274
<p>I am developing a plugin for the GIS software, QGIS. I created a <code>QTableWidget</code> and wish to extract values from it:</p> <p><a href="http://i.stack.imgur.com/WE78I.png" rel="nofollow"><img src="http://i.stack.imgur.com/WE78I.png" alt="Image"></a></p> <p>Problem is, I use a lot of <code>for</code> loops a...
2
2016-05-26T13:28:36Z
37,462,989
<p>My sincere thanks to the commenters who directed me to a much more efficient solution, here is the working code which works (I'm sure it can be refined further):</p> <pre><code>qTable = self.dockwidget.tableWidget example_group = root.findGroup('Main group') all_items = [] gis_map = QgsMapLayerRegistry.instance().m...
2
2016-05-26T13:57:20Z
[ "python", "qgis" ]
is it possible to restart the already terminated process in python multiprocessing?
37,462,370
<p>Here is the example code for my question:</p> <pre><code>import multiprocessing, time def nopr(): i=0 while 1: i = i+1 print i time.sleep(1) p = multiprocessing.Process(target = nopr) print "process started" p.start() time.sleep(04) print "process en...
2
2016-05-26T13:32:24Z
37,462,587
<p>No you cannot start a terminated process, you would have to recreate it :</p> <pre><code>import multiprocessing, time def nopr(): i=0 while 1: i = i+1 print i time.sleep(1) p = multiprocessing.Process(target = nopr) print "process started" p.start() time.sleep(04) print "process en...
3
2016-05-26T13:41:27Z
[ "python", "python-multiprocessing" ]
Removing nth row in Pandas
37,462,473
<p>I have a Pandas df with a time series that goes by 34 milliseconds and I only need a 5 second resolution. I initially created a time stamp and tried to both setting the time stamp as an index and resample and .iloc. </p> <pre><code># Defining file path file = "C:/file/path/data.csv" # Read in data and parse date/t...
3
2016-05-26T13:36:25Z
37,462,549
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tseries.resample.Resampler.first.html" rel="nofollow"><code>first</code></a>:</p> <pr...
5
2016-05-26T13:39:24Z
[ "python", "datetime", "pandas", "resampling" ]
Calculating the x & y coordinates in cm from the pixelcoordinates
37,462,484
<p>Heyho!<br> I've got an image of a flat surface (taken from above and with an angle of 30°) and I want the x &amp; y coordinates of a specific pixel but in cm (with the coordinate system being in the surface).<br> Is there a method to archive this?<br> I'm using python but any help is appreciated! :)</p> <p>Edit: ...
1
2016-05-26T13:36:52Z
37,470,248
<p>One approach is to estimate the homography between the plane of your flat surface and your image plane. A simple way to estimate the homography:</p> <ol> <li>get the coordinates in cm of four (non collinear) points on your flat surface;</li> <li>find the same four point in the image and get their coordinates in pix...
1
2016-05-26T20:20:05Z
[ "python", "opencv", "computer-vision" ]
Sqlite Efficiency
37,462,537
<p>I took a class on python, sql, and datascience where I was taught to read or download a datafile/table off the web and store it in a sqlite database by going through the file line by line and and extracting data from columns and storing them in corresponding sqlite tables. My project did this with MTA subway usage d...
0
2016-05-26T13:38:55Z
37,476,268
<p>Personally, I would not create a table having just a single meaningful field . The way Dates and Times are implemented will just cause headache and extra work. Rather put the date /time stamp values directly on the table to which they correspond . </p> <p>You could consider putting index and the station name, sinc...
1
2016-05-27T06:26:12Z
[ "python", "sqlite", "pandas", "relational-database" ]
Send form content using Python on Google App Engine
37,462,656
<p>I'm trying to implement a subscribe button on my website that will send whatever the user writes to one of my mails. I'm trying to write a Python script that would do that. My website is static and hosted on app engine.</p> <p><strong>My form</strong></p> <pre><code> &lt;form method="post" action="a...
0
2016-05-26T13:44:13Z
37,491,149
<p>Add these lines to your app.yaml:</p> <pre><code>handlers: - url: /subscribe/.* script: subscribe.app libraries: - name: webapp2 version: "2.5.2" </code></pre> <p>Then rename your Python script to subscribe.py and change its contents to this:</p> <pre><code>#!/usr/bin/env python import cgi import webapp2 fr...
0
2016-05-27T19:43:20Z
[ "python", "forms", "google-app-engine", "cgi" ]
How to unittest Python Lock is acquired with 'with' statement?
37,462,673
<p>Using Python 2.6.6</p> <p>So I just learned that the following:</p> <pre><code>myLock.acquire() doStuff() myLock.release() </code></pre> <p>can be replaced with:</p> <pre><code>with myLock: doStuff() </code></pre> <p>My quandry is that with the former code I could unittest that the lock was being used to prot...
3
2016-05-26T13:44:57Z
37,462,896
<p>The <code>with</code> statement internally calls the <code>__enter__</code> and <code>__exit__</code> magic methods at the beginning and end (respectively). You can mock out these methods either by using a <code>MagicMock</code> or by explicitly setting <code>mock.__enter__ = Mock();mock.__exit__ = Mock()</code>.</p...
5
2016-05-26T13:53:34Z
[ "python", "multithreading", "python-unittest" ]
I cant figure out how to write this list to a csv file how i want it, python
37,462,884
<p>This is my code:</p> <pre><code>geometries = [[a, b, c], [d, e, f]] #Note I have lists within a list, this is required with open("./datafiles/" + name, 'wb') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n') writer.writerow(geomet...
0
2016-05-26T13:53:12Z
37,463,026
<p>You want to use <a href="https://docs.python.org/2/library/csv.html#csv.csvwriter.writerows" rel="nofollow"><code>.writerows()</code></a> not <code>writerow()</code>.</p> <p>By using the correct function, it'll output your CSV file as you expect. </p> <p>The issue you have with the lines showing on the same row in...
1
2016-05-26T13:58:38Z
[ "python", "csv", "rows" ]
I cant figure out how to write this list to a csv file how i want it, python
37,462,884
<p>This is my code:</p> <pre><code>geometries = [[a, b, c], [d, e, f]] #Note I have lists within a list, this is required with open("./datafiles/" + name, 'wb') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n') writer.writerow(geomet...
0
2016-05-26T13:53:12Z
37,463,027
<p><a href="https://docs.python.org/2/library/csv.html#csv.csvwriter.writerow" rel="nofollow"><code>.writerow()</code></a> expects a flat list as a parameter. To write a list of rows at once use <a href="https://docs.python.org/2/library/csv.html#csv.csvwriter.writerows" rel="nofollow"><code>.writerows()</code></a>:</p...
1
2016-05-26T13:58:40Z
[ "python", "csv", "rows" ]
Selecting rows in a DataFrame that are not in a Series
37,462,906
<p>So I have a DataFrame called <code>trips</code> containing the following information:</p> <pre><code>route_id service_id shape_id trip_id 0 BX12 GH_B6-Weekday BX120805 GH_B6-Weekday-004000_BX12_1 1 BX12 GH_B6-Weekday BX120809 GH_B6-Weekday-009000_BX12_1 2 BX12 GH_B6-Week...
0
2016-05-26T13:53:54Z
37,462,937
<p><strong>UPDATE:</strong></p> <p>try <code>isin()</code> function and <code>~</code> operator</p> <p>as per @EdChum's correction in the comment - if <code>invalid_trips</code> is of Series type:</p> <pre><code>trips[~trips.trip_id.isin(invalidTrips.index)] </code></pre> <p><strong>TEST:</strong></p> <pre><code>I...
2
2016-05-26T13:55:13Z
[ "python", "pandas", "dataframe", "series" ]
Multiplication in a variable
37,463,035
<p>I am writing a piece of code that needs to multiply numbers by different values, all the code for the entering and validation of the 7 digit number works however the multiplication doesn't work. This is my code.</p> <pre><code>while True: try: num = int(input("enter a 7 digit number: ")) check ...
0
2016-05-26T13:59:01Z
37,463,191
<p>When you convert the input number to an integer you can not use indexing on that object since integers don't support indexing. If you want to multiply your digits by a specific number you better do this before converting to integer.</p> <p>So first off replace the following part:</p> <pre><code>num = int(input("en...
1
2016-05-26T14:05:13Z
[ "python" ]
Multiplication in a variable
37,463,035
<p>I am writing a piece of code that needs to multiply numbers by different values, all the code for the entering and validation of the 7 digit number works however the multiplication doesn't work. This is my code.</p> <pre><code>while True: try: num = int(input("enter a 7 digit number: ")) check ...
0
2016-05-26T13:59:01Z
37,463,331
<p>If you're bound to use an integer instead of a list for the input, you can do one of the following:</p> <p>You could access the individual digits using a combination of integer division and modulo, for example:</p> <pre><code>first_digit = num // 1000000 * 3 second_digit = num // 100000 % 10 * 1 # and so on </code...
1
2016-05-26T14:10:25Z
[ "python" ]
Multiplication in a variable
37,463,035
<p>I am writing a piece of code that needs to multiply numbers by different values, all the code for the entering and validation of the 7 digit number works however the multiplication doesn't work. This is my code.</p> <pre><code>while True: try: num = int(input("enter a 7 digit number: ")) check ...
0
2016-05-26T13:59:01Z
37,463,406
<p>Of course, your code might be written in a number of ways, optimized (check @Kasravand answer, it's awesome) or not, but with a minimal effort this is what I get:</p> <pre><code>while True: try: num = input("enter a 7 digit number: ") check = len(num) int(num) # will trigger ValueError i...
2
2016-05-26T14:13:38Z
[ "python" ]
Multiplication in a variable
37,463,035
<p>I am writing a piece of code that needs to multiply numbers by different values, all the code for the entering and validation of the 7 digit number works however the multiplication doesn't work. This is my code.</p> <pre><code>while True: try: num = int(input("enter a 7 digit number: ")) check ...
0
2016-05-26T13:59:01Z
37,463,579
<p>This code will works:</p> <pre><code>while True: try: num = int(input("enter a 7 digit number: ")) except ValueError: print("you must enter an integer") else: if len(str(num)) != 7: print("enter a number that is only 7 digits") else: ...
0
2016-05-26T14:21:48Z
[ "python" ]
Multiplication in a variable
37,463,035
<p>I am writing a piece of code that needs to multiply numbers by different values, all the code for the entering and validation of the 7 digit number works however the multiplication doesn't work. This is my code.</p> <pre><code>while True: try: num = int(input("enter a 7 digit number: ")) check ...
0
2016-05-26T13:59:01Z
37,464,993
<p>This should help</p> <pre><code> num = '' check = 0 while True: try: num = raw_input("enter a 7 digit number: ") check = len(num) if check == 7: print("This code is valid") break else: print "enter a...
0
2016-05-26T15:22:02Z
[ "python" ]
How to create a Manhattan plot with matplotlib in python?
37,463,184
<p>Unfortunately, I have not found a solution myself. How do I create a Manhattan plot [1] within python using, e.g., matplotlib / pandas. The problem is that in these plots the x-axis is discrete. </p> <pre><code>from pandas import DataFrame from scipy.stats import uniform from scipy.stats import randint import numpy...
7
2016-05-26T14:05:00Z
37,464,042
<pre><code>import matplotlib.pyplot als plt from numpy.random import randn, random_sample g = random_sample(int(1e5))*10 # uniform random values between 0 and 10 p = abs(randn(int(1e5))) # abs of normally distributed data """ plot g vs p in groups with different colors colors are cycled automatically by matplotlib us...
6
2016-05-26T14:40:49Z
[ "python", "pandas", "matplotlib", "plot", "genetics" ]
How to create a Manhattan plot with matplotlib in python?
37,463,184
<p>Unfortunately, I have not found a solution myself. How do I create a Manhattan plot [1] within python using, e.g., matplotlib / pandas. The problem is that in these plots the x-axis is discrete. </p> <pre><code>from pandas import DataFrame from scipy.stats import uniform from scipy.stats import randint import numpy...
7
2016-05-26T14:05:00Z
37,464,420
<p>You can use something like this:</p> <pre class="lang-python prettyprint-override"><code>from pandas import DataFrame from scipy.stats import uniform from scipy.stats import randint import numpy as np import matplotlib.pyplot as plt # some sample data df = DataFrame({'gene' : ['gene-%i' % i for i in np.arange(1000...
6
2016-05-26T14:55:24Z
[ "python", "pandas", "matplotlib", "plot", "genetics" ]
Open a word document with python using windows
37,463,506
<p>I am trying to open a word document with python in windows, but I am unfamiliar with windows.</p> <p>My code is as follows.</p> <pre><code>import docx as dc doc = dc.Document(r'C:\Users\justin.white\Desktop\01100-Allergan-UD1314-SUMMARY OF WORK.docx') </code></pre> <p>Through another post, I learned that I had to...
2
2016-05-26T14:18:32Z
37,463,660
<p>try this</p> <pre><code>import StringIO from docx import Document file = r'H:\myfolder\wordfile.docx' with open(file) as f: source_stream = StringIO(f.read()) document = Document(source_stream) source_stream.close() </code></pre> <p><a href="http://python-docx.readthedocs.io/en/latest/user/documents.html" r...
1
2016-05-26T14:25:04Z
[ "python", "io", "ms-word", "etl", "python-docx" ]
Multiple exceptions and code coverage when unit testing python
37,463,561
<p><strong>The Problem:</strong></p> <p>Here is an artificial example of the code under test:</p> <pre><code>from datetime import datetime def f(s): try: date = s.split(":")[1] return datetime.strptime(date, "%Y%m%d") except (ValueError, IndexError) as e: # some code here rais...
8
2016-05-26T14:21:08Z
37,464,114
<p>I think you can try with two separate excepts for the two exceptions. In that case, line coverage shows that you haven't tested one condition.</p> <pre><code>from datetime import datetime def f(s): try: date = s.split(":")[1] return datetime.strptime(date, "%Y%m%d") except ValueError as e: ...
1
2016-05-26T14:43:23Z
[ "python", "unit-testing", "testing", "code-coverage", "coverage.py" ]
Multiple exceptions and code coverage when unit testing python
37,463,561
<p><strong>The Problem:</strong></p> <p>Here is an artificial example of the code under test:</p> <pre><code>from datetime import datetime def f(s): try: date = s.split(":")[1] return datetime.strptime(date, "%Y%m%d") except (ValueError, IndexError) as e: # some code here rais...
8
2016-05-26T14:21:08Z
37,473,190
<p>Coverage.py can only measure which execution paths (statements or branches) were run. It has no means of tracking what values were used, including what exception types were raised.</p> <p>As I see it, your options are:</p> <ol> <li><p>Separate the exception clauses. In the code you've shown, the two exceptions c...
7
2016-05-27T00:53:05Z
[ "python", "unit-testing", "testing", "code-coverage", "coverage.py" ]
Folium program not running
37,463,751
<p>I'm trying to make a python program that generate a leaflet web map with some point data as heatmap as well as some boundary data as GeoJson. When I run the code below in python I get some errors as follows:</p> <pre><code>Traceback (most recent call last): File "pollingstations.py", line 12, in &lt;module&gt; ...
0
2016-05-26T14:28:34Z
37,477,948
<p>try <code>open('pollstations.geojson', encoding="utf-8")</code> or <code>open('pollstations.geojson', encoding = "ISO-8859-1")</code>, plus check the tag names, county or country? </p>
0
2016-05-27T07:57:58Z
[ "python", "leaflet", "folium" ]
Cannot retrieve proxmox node notes
37,463,782
<p>I am using proxmoxer to manipulate machines on ProxMox (create, delete etc). Every time I am creating a machine, I provide a description which is being written in ProxMox UI in section "Notes".</p> <p>I am wondering how can I retrieve that information?</p> <p>Best would be if it can be done with ProxMox, but if th...
1
2016-05-26T14:29:48Z
37,565,566
<p>The description parameter is only a message to show in proxmox UI, and it's not related to any function</p>
0
2016-06-01T10:05:25Z
[ "python", "virtual-machine", "virtualization", "proxmox" ]
Cannot retrieve proxmox node notes
37,463,782
<p>I am using proxmoxer to manipulate machines on ProxMox (create, delete etc). Every time I am creating a machine, I provide a description which is being written in ProxMox UI in section "Notes".</p> <p>I am wondering how can I retrieve that information?</p> <p>Best would be if it can be done with ProxMox, but if th...
1
2016-05-26T14:29:48Z
38,233,270
<p>You could use <a href="https://github.com/baseblack/Proxmoxia" rel="nofollow">https://github.com/baseblack/Proxmoxia</a> to get started, <a href="https://forum.proxmox.com/threads/how-to-export-all-vm-ids-name-and-notes.27596/" rel="nofollow">I asked this very same question on the forum</a> as I need to generate som...
0
2016-07-06T20:32:48Z
[ "python", "virtual-machine", "virtualization", "proxmox" ]
Django static files 404 not found nginx
37,463,842
<p>I am developing a Django application and I want to put it online on DigitalOcean so I can show it to a remote future user. I am quite new to django and python and I have never in my life touched the deployment of web applications, so I'm a bit lost in all that.</p> <p>I used the one-click install of a django drople...
1
2016-05-26T14:32:00Z
37,488,877
<blockquote> <p>I assume that you don't use nginx to serve static assets in development? Runserver can serve static files, but very much slower than nginx, which becomes a problem once you have more than a single web site visitor at a time. You can remove the nginx alias for static and reload nginx to let run...
0
2016-05-27T17:02:12Z
[ "python", "django", "nginx", "django-staticfiles" ]
add 15 days to every date in a pandas DatetimeIndex
37,463,877
<p>I have a pandas DateTimeIndex. I want to add fifteen days to every date.</p> <pre><code>import pandas as pd tidx = pd.date_range(end='2016-04-30', freq='M', periods=2) tidx DatetimeIndex(['2016-03-31', '2016-04-30'], dtype='datetime64[ns]', freq='M') </code></pre> <p>I want:</p> <pre><code>DatetimeIndex([...
4
2016-05-26T14:33:47Z
37,463,936
<p>I think you can use <code>offsets</code>, see <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#using-offsets-with-series-datetimeindex" rel="nofollow">docs</a>:</p> <pre><code>print (tidx + pd.offsets.Day(15)) DatetimeIndex(['2016-04-15', '2016-05-15'], dtype='datetime64[ns]', freq=None) </code>...
4
2016-05-26T14:36:24Z
[ "python", "pandas", "python-datetime" ]
add 15 days to every date in a pandas DatetimeIndex
37,463,877
<p>I have a pandas DateTimeIndex. I want to add fifteen days to every date.</p> <pre><code>import pandas as pd tidx = pd.date_range(end='2016-04-30', freq='M', periods=2) tidx DatetimeIndex(['2016-03-31', '2016-04-30'], dtype='datetime64[ns]', freq='M') </code></pre> <p>I want:</p> <pre><code>DatetimeIndex([...
4
2016-05-26T14:33:47Z
37,464,113
<p>alternatively you can use <a href="http://pandas.pydata.org/pandas-docs/stable/timedeltas.html" rel="nofollow">Timedelta()</a>:</p> <pre><code>In [49]: tidx + pd.Timedelta('15d') Out[49]: DatetimeIndex(['2016-04-15', '2016-05-15'], dtype='datetime64[ns]', freq=None) In [50]: tidx + pd.Timedelta(days=15) Out[50]: D...
2
2016-05-26T14:43:23Z
[ "python", "pandas", "python-datetime" ]
Compare Histogram to Poisson Distribution and Gauss-Curve
37,463,916
<p>I got 100 experimental values:</p> <pre><code>N = np.array([ 6080, 5604, 5972, 5566, 5683, 5619, 5582, 5912, 5614,5837, 5961, 5972, 5807, 5829, 5881, 5757, 5725, 5809, 5626, 5995, 5793, 5608, 5880, 5982, 5748, 6071, 6181, 6034, 6117, 5903, 6190, 5735, 6109, 6126, 6012, 5948, 6139, 6103, 6108, 6031, 6200, 6091, 6199...
2
2016-05-26T14:35:26Z
37,464,329
<p>In your plot there is a red line...it's the Poisson curve. What lambda are you using? It's very likely too small and you get only zeroes. Anyway I suggest you to use: <a href="http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.stats.poisson.html#scipy.stats.poisson" rel="nofollow">poisson</a> function ...
1
2016-05-26T14:52:13Z
[ "python", "histogram", "poisson" ]
Better way to create fit functions with changing number of parameters in Python with Scipy curve_fit
37,463,993
<p>I am looking for a better way to use scipy's <a href="http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow">curve_fit()</a></p> <p>I am currently using it to fit linear combinations of the parameters and a vector x.</p> <p>For example, here is a fitting function I...
0
2016-05-26T14:38:39Z
37,470,803
<p>You are fitting a multivariate linear model to your data. This can be expressed as a dot product between your <code>x</code> vector, with shape <code>(npoints, nparams)</code>, and a single <code>(nparams,)</code> vector of coefficients, say <code>m</code>:</p> <pre><code>def linear(x, m): return x.dot(m) x = ...
2
2016-05-26T20:54:16Z
[ "python", "scipy", "curve-fitting" ]
How to plot longitudinal data / repeated measures in python using matplotlib?
37,464,054
<p>How do I plot longitudinal data in python using, e.g., matplotlib.</p> <pre><code>from pandas import DataFrame from scipy.stats import norm from scipy.stats import randint import numpy as np import pandas as pd # some sample data df = DataFrame({ 'one' : norm.rvs(loc=12, size=10), 'two' : norm.rvs(loc=5, s...
0
2016-05-26T14:41:23Z
37,464,462
<p>I didn't understand the part of the connecting line, but perhaps this what you want is something similar to this:</p> <pre><code>fig, ax = plt.subplots( 1, 1 ) ax.plot( np.zeros(len(df.one))+1, df.one, '.' ) ax.plot( np.zeros(len(df.two)) + 2, df.two, '.' ) ax.plot( np.zeros(len(df.three)) + 3 , df.three, '.' ) ax...
0
2016-05-26T14:57:20Z
[ "python", "pandas", "matplotlib", "plot", "seaborn" ]
Is there any way to call python code in android develop without installing sl4a?
37,464,116
<p>I have found some ways to using python to build android app.But all of them need to install sl4a and pythonforandroid. It is so complicated,so is there any way to package sl4a to my android app project,and once I install the apk,I needn't install sl4a any more.</p>
5
2016-05-26T14:43:29Z
37,464,663
<p>You can use Kivy at following link :</p> <p><a href="https://github.com/kivy/python-for-android" rel="nofollow">Python for Android</a></p> <p>It will can help u have a look to the following topic :</p> <p><a href="https://www.quora.com/How-can-I-integrate-a-Python-code-in-the-Android-Java-app" rel="nofollow">How ...
3
2016-05-26T15:06:24Z
[ "java", "android", "python" ]
Is there any way to call python code in android develop without installing sl4a?
37,464,116
<p>I have found some ways to using python to build android app.But all of them need to install sl4a and pythonforandroid. It is so complicated,so is there any way to package sl4a to my android app project,and once I install the apk,I needn't install sl4a any more.</p>
5
2016-05-26T14:43:29Z
37,481,682
<p>You <em>can</em> do this. What it comes down to is packaging the Python interpreter (compiled by the NDK) in your app, and starting it via the standard NDK mechanisms. This is the same thing that e.g. Kivy does, but you'd be adding the code to your own app rather than (like Kivy) using a java bootstrap then letting ...
1
2016-05-27T10:56:27Z
[ "java", "android", "python" ]
Loop through form POST store data in python variable
37,464,256
<p>I have a form that holds multiple inputs... Within the <code>request.POST</code>, I'm looping through all of the input values. But I'd like to store them within a variable.. How do I do that?</p> <pre><code>for key, value in request.POST.items(): print(key, value) # how can I store instead of print? </code></pr...
1
2016-05-26T14:49:01Z
37,464,547
<p>You have couple of ways to store the POST data in a local variable. The question is: why would you want to do that when you have access to <code>request.POST</code> anyway?</p> <pre><code># Note: all keys and values in these structures are strings # easiest, but immutable QueryDict d = request.POST # dict d = d...
1
2016-05-26T15:00:57Z
[ "python", "django" ]
Loop through form POST store data in python variable
37,464,256
<p>I have a form that holds multiple inputs... Within the <code>request.POST</code>, I'm looping through all of the input values. But I'd like to store them within a variable.. How do I do that?</p> <pre><code>for key, value in request.POST.items(): print(key, value) # how can I store instead of print? </code></pr...
1
2016-05-26T14:49:01Z
37,464,610
<p>This might not directly answer your question, but I don't recommend accessing <code>request.POST</code> directly since you already had a form. Form is good that it abstracts away a lot of the raw data that you need to handle by encapsulating them in the form object, so I would suggest check the form itself for data:...
0
2016-05-26T15:03:35Z
[ "python", "django" ]
blosc compression in hdf5 via h5py
37,464,262
<p>I'm using h5py to create hdf5 files in python, and I'd like to use blosc as a compression filter. I first installed c-blosc from source via:</p> <pre><code>wget https://github.com/Blosc/c-blosc/archive/v1.9.1.tar.gz tar -xvf c-blosc-v1.9.1.tar.gz cd c-blosc-v1.9.1 mkdir build cd build cmake -DCMAKE_INSTALL_PREFIX=/...
3
2016-05-26T14:49:08Z
37,658,992
<p>I found that the easiest way to get this working is to install <a href="http://www.pytables.org/" rel="nofollow">pytables</a> and load that at the outset of your python script. You don't need to use pytables at all afterwards, but loading it clearly calls something that registers the blosc filter.</p>
1
2016-06-06T13:38:31Z
[ "python", "hdf5", "h5py" ]
Splitting a stack (python)
37,464,323
<p>How is it done in order to split a stack into separate stacks in an alternative manner?</p> <p>For an instance, I want to split stack <code>[1, 2, 3, 4, 5, 6, 7, 8, 9]</code> to <code>[1, 3, 5, 7, 9]</code> and <code>[2, 4, 6, 8]</code>. </p>
0
2016-05-26T14:52:04Z
37,464,354
<p>You can use <a href="https://docs.python.org/2.3/whatsnew/section-slices.html" rel="nofollow">step size on the slice</a> of the stack:</p> <pre><code>In [11]: lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(lst[::2]) print(lst[1::2]) [1, 3, 5, 7, 9] [2, 4, 6, 8] </code></pre> <p>So the syntax here <code>::2</code> transl...
7
2016-05-26T14:53:14Z
[ "python", "python-3.x" ]
Splitting a stack (python)
37,464,323
<p>How is it done in order to split a stack into separate stacks in an alternative manner?</p> <p>For an instance, I want to split stack <code>[1, 2, 3, 4, 5, 6, 7, 8, 9]</code> to <code>[1, 3, 5, 7, 9]</code> and <code>[2, 4, 6, 8]</code>. </p>
0
2016-05-26T14:52:04Z
37,464,453
<p>I assume you want to separate odd and even</p> <pre><code> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] odd = [ i for i in lst if i%2] even= [ i for i in lst if i%2 == 0 ] </code></pre>
1
2016-05-26T14:57:02Z
[ "python", "python-3.x" ]
Numpy finding element index in another array
37,464,393
<p>I have an array/set with unique positive integers, i.e.</p> <pre><code>&gt;&gt;&gt; unique = np.unique(np.random.choice(100, 4, replace=False)) </code></pre> <p>And an array containing multiple elements sampled from this previous array, such as</p> <pre><code>&gt;&gt;&gt; A = np.random.choice(unique, 100) </code>...
4
2016-05-26T14:54:30Z
37,464,740
<p>You can use standard python <code>dict</code> with <code>np.vectorize</code></p> <pre><code>inds = {e:i for i, e in enumerate(unique)} B = np.vectorize(inds.get)(A) </code></pre>
1
2016-05-26T15:10:06Z
[ "python", "arrays", "numpy", "indexing" ]
Numpy finding element index in another array
37,464,393
<p>I have an array/set with unique positive integers, i.e.</p> <pre><code>&gt;&gt;&gt; unique = np.unique(np.random.choice(100, 4, replace=False)) </code></pre> <p>And an array containing multiple elements sampled from this previous array, such as</p> <pre><code>&gt;&gt;&gt; A = np.random.choice(unique, 100) </code>...
4
2016-05-26T14:54:30Z
37,467,048
<p>The table approach described in your question is the best option when <code>unique</code> if pretty dense, but <code>unique.searchsorted(A)</code> should produce the same result and doesn't require <code>unique</code> to be dense. <code>searchsorted</code> is great with ints, if anyone is trying to do this kind of t...
4
2016-05-26T17:03:59Z
[ "python", "arrays", "numpy", "indexing" ]
Numpy finding element index in another array
37,464,393
<p>I have an array/set with unique positive integers, i.e.</p> <pre><code>&gt;&gt;&gt; unique = np.unique(np.random.choice(100, 4, replace=False)) </code></pre> <p>And an array containing multiple elements sampled from this previous array, such as</p> <pre><code>&gt;&gt;&gt; A = np.random.choice(unique, 100) </code>...
4
2016-05-26T14:54:30Z
37,468,543
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) contains a vectorized equivalent of list.index, which does not require memory proportional to the max element, but only proportional to the input itself:</p> <pre><code>impor...
2
2016-05-26T18:31:15Z
[ "python", "arrays", "numpy", "indexing" ]
running unittests \ integration tests in python
37,464,470
<p>I have a Django project with multiple apps. Each app has a set of unittests. I'm using pytest as my test runner. We have gotten to a point that we want to start writing integration tests. I was wondering if there is any way to keep the naming convention and thus the auto discovery of pytest but still be able (via fl...
0
2016-05-26T14:57:43Z
37,464,552
<p>You can <a href="https://pytest.org/latest/example/markers.html#marking-test-functions-and-selecting-them-for-a-run" rel="nofollow">mark test functions</a>.</p> <pre><code>import pytest @pytest.mark.unittest def test_my_test(self): # do some testing @pytest.mark.integration def test_my_integration_test(self):...
2
2016-05-26T15:01:10Z
[ "python", "django", "integration-testing", "py.test" ]
Send MySQL blob content as a json response
37,464,600
<p>I have the following code of a GET method which takes a photo which is stored in a blob type field in MySql and return. I want to return it to the client inside a JSON string in a type it can display the image in an angularjs application.</p> <pre><code> def GET(self,r): user_data = CC.get_data(query) # holds t...
1
2016-05-26T15:03:06Z
37,464,776
<p>First how to work with blob:</p> <p><a href="http://www.mysqltutorial.org/python-mysql-blob/" rel="nofollow">http://www.mysqltutorial.org/python-mysql-blob/</a></p> <p>To send your image to your template:</p> <p>def imageResponseView(...) .... return response</p> <p>bind url to this view</p> <p>show image using...
0
2016-05-26T15:11:31Z
[ "python", "mysql", "json", "rest", "blob" ]
Send MySQL blob content as a json response
37,464,600
<p>I have the following code of a GET method which takes a photo which is stored in a blob type field in MySql and return. I want to return it to the client inside a JSON string in a type it can display the image in an angularjs application.</p> <pre><code> def GET(self,r): user_data = CC.get_data(query) # holds t...
1
2016-05-26T15:03:06Z
37,464,826
<p>To prevent data loss, the best thing you can do to send binary data is encode as <code>base64</code>.</p> <pre><code>import base64 def GET(self,r): user_data = CC.get_data(query) # holds the content of the blob field. data = {'name': 'test', 'photo': base64.b64encode(user_data)} return json....
2
2016-05-26T15:13:31Z
[ "python", "mysql", "json", "rest", "blob" ]
How to delete models using button and GET request in Django?
37,464,606
<p>Here's the problem: in my rendered html-page I have multiple what I call 'thumbnails' of text data aka Notes (Note is my Model in Django). I decided it would be good idea to bind button "Delete" to every thumbnail: User clicks "Delete" on some Note —> it's get deleted. What I've come to (in my views.py):</p> <pre...
0
2016-05-26T15:03:23Z
37,464,909
<p><code>request.GET.get(x for x in buttons)</code> doesn't do what you think at all. It tries to get a single parameter, consisting of a list of all the button names. That can never work.</p> <p>But this is a very inefficient way of doing things anyway. Rather than iterating over every ID and seeing if it's in the GE...
2
2016-05-26T15:17:41Z
[ "python", "html", "django" ]
pandas dataframe contain list
37,464,656
<p>suppose i have a dataframe like this :</p> <pre><code>lst1 = [[1,3,4,5],[1,2,3,3],[2,3,4,5],[3,4,5,5]] lst2 = [[1,2,3,1],[1,4,1,2],[3,3,1,5],[2,4,1,5]] lst3 = [[1,2,3,3],[3,2,1,2],[1,3,1,4],[2,4,3,5]] percentile_list = pd.DataFrame({'lst1Tite' : lst1, 'lst2Tite' : lst2, 'lst3Tite':lst3 }) &gt; precentile_list ...
1
2016-05-26T15:06:02Z
37,464,685
<p>You can use <code>apply</code> and apply the <code>Series</code> ctor on the row:</p> <pre><code>In [17]: percentile_list.iloc[0].apply(pd.Series) Out[17]: 0 1 2 3 lst1Tite 1 3 4 5 lst2Tite 1 2 3 1 lst3Tite 1 2 3 3 </code></pre> <p>If you're particularly enamoured with the desired output:...
0
2016-05-26T15:07:34Z
[ "python", "pandas", "matrix", "data-cleaning" ]
Provide a list of methods in a class for use outside of it
37,464,720
<p>How can I provide a list of methods in a class for use outside of it?</p> <h3>What I'm looking for</h3> <p>When I create an object from a class extending a higher class, I want to get a list of specific methods, some "meta data" of them, and to able to call them outside the class.</p> <p>Example:</p> <pre><code>...
0
2016-05-26T15:09:07Z
37,464,999
<pre><code>def get_extra_fns(self): fns = {} for i in self.extra_methods: fns['i'] = self.__getattribute__(i) return fns </code></pre>
0
2016-05-26T15:22:27Z
[ "python", "python-3.x" ]
Provide a list of methods in a class for use outside of it
37,464,720
<p>How can I provide a list of methods in a class for use outside of it?</p> <h3>What I'm looking for</h3> <p>When I create an object from a class extending a higher class, I want to get a list of specific methods, some "meta data" of them, and to able to call them outside the class.</p> <p>Example:</p> <pre><code>...
0
2016-05-26T15:09:07Z
37,465,773
<p>Python 3:</p> <pre><code>import types import inspect class A: def a(self): pass class B(A): def b(self, bool_param, int_param): pass b = B() for member_name in dir(B): member = getattr(B, member_name) if isinstance(member, types.FunctionType): member(b, True) # as il...
0
2016-05-26T15:57:21Z
[ "python", "python-3.x" ]
Provide a list of methods in a class for use outside of it
37,464,720
<p>How can I provide a list of methods in a class for use outside of it?</p> <h3>What I'm looking for</h3> <p>When I create an object from a class extending a higher class, I want to get a list of specific methods, some "meta data" of them, and to able to call them outside the class.</p> <p>Example:</p> <pre><code>...
0
2016-05-26T15:09:07Z
37,475,115
<p>You don't need a wrapper for your decorated methods, since you only set attributes of the method-object. To identify your methods, I would suggest to set a special attribute for these methods, iterate over all class methods and pick those, that have this special method set:</p> <pre><code>def special(**kw): def...
1
2016-05-27T04:54:38Z
[ "python", "python-3.x" ]
Fast outer tensor product in numpy
37,464,737
<p>I have two numpy arrays: </p> <pre><code>x of shape ((d1,...,d_m)) y of shape ((e_1,...e_n)) </code></pre> <p>I would like to form the outer tensor product, that is the numpy array </p> <pre><code>z of shape ((d1,...,d_m,e_1,...,e_n)) </code></pre> <p>such that </p> <pre><code>z[i_1,...,i_n,i_{n+1}...,i_{m+n}...
0
2016-05-26T15:10:03Z
37,465,484
<p>You want <a href="https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ufunc.outer.html" rel="nofollow"><code>np.multiply.outer</code></a>:</p> <pre><code>z = np.multiply.outer(x, y) </code></pre>
2
2016-05-26T15:43:31Z
[ "python", "arrays", "numpy", "linear-algebra" ]
Fast outer tensor product in numpy
37,464,737
<p>I have two numpy arrays: </p> <pre><code>x of shape ((d1,...,d_m)) y of shape ((e_1,...e_n)) </code></pre> <p>I would like to form the outer tensor product, that is the numpy array </p> <pre><code>z of shape ((d1,...,d_m,e_1,...,e_n)) </code></pre> <p>such that </p> <pre><code>z[i_1,...,i_n,i_{n+1}...,i_{m+n}...
0
2016-05-26T15:10:03Z
37,466,482
<p>An alternative to <code>outer</code> is to explicitly expand the dimensions. For 1d arrays this would be</p> <pre><code>x[:,None]*y # y[None,:] is automatic. </code></pre> <p>For 10x10 arrays, and generalizing the dimension expansion, I get the same times</p> <pre><code>In [74]: timeit x[[slice(None)]*x.ndim +...
2
2016-05-26T16:33:15Z
[ "python", "arrays", "numpy", "linear-algebra" ]
Odoo in stock quant lot_id column sorting wrong by clicking on column name
37,464,844
<p>I have one column that don't appear to be sorting correctly. I can't sort by serial number by clicking on column name. It appears sorting random. Talking about other columns like quantity or product_creation_date or product everything is alright I can sort desc/asc by clicking on quantity or product_creation_date c...
1
2016-05-26T15:14:35Z
37,475,949
<p>If I know well, you can not sort relation fields (o2m, m2o, m2m).</p>
0
2016-05-27T06:05:00Z
[ "python", "sorting", "openerp" ]
Fixing request entity too large error under django/apache/mod_wsgi for file uploads
37,464,886
<p>I after much gnashing of teeth found out my uploads were working just that I was getting a request entity to large 413 error I wasn't seeing. The django app is running under apache mod_wsgi, and I am no apache guru so i am not sure what I need to set to handle larger files. I tried to google online but it was uncl...
0
2016-05-26T15:16:33Z
37,495,881
<p>That would indicate that you have <code>LimitRequestBody</code> directive set to a very small value in the Apache configuration. This directive wouldn't normally be set at all if using standard Apache. Even if you happen to be using <code>mod_wsgi-express</code> the default there is 10MB. So it must have been overri...
0
2016-05-28T06:17:10Z
[ "python", "django", "apache", "mod-wsgi", "django-filer" ]
Python 3: Iterating over a dictionary
37,465,087
<p>I would've created a more specific title but I'm not sure how to formulate my question. </p> <pre><code>{ "playerStatSummaries": [ { "playerStatSummaryType": "AramUnranked5x5", "aggregatedStats": { "totalChampionKills": 2250, "totalAssists": 6199, "tota...
0
2016-05-26T15:25:46Z
37,465,208
<p>Try something like:</p> <pre><code>for item in ranked_stats_json['playerStatSummaries']: ##This iterates the list if 'wins' in item and item['wins'] == 44: ##This checks your condition ##Do whatever here, or break or whatever you want #Put your action here </code></pre> <p>Consider this example:</p> <pr...
0
2016-05-26T15:31:29Z
[ "python", "json", "dictionary" ]
Python 3: Iterating over a dictionary
37,465,087
<p>I would've created a more specific title but I'm not sure how to formulate my question. </p> <pre><code>{ "playerStatSummaries": [ { "playerStatSummaryType": "AramUnranked5x5", "aggregatedStats": { "totalChampionKills": 2250, "totalAssists": 6199, "tota...
0
2016-05-26T15:25:46Z
37,465,235
<p>You can iterate through the stats using a <a href="https://docs.python.org/2/tutorial/datastructures.html" rel="nofollow">List Comprehension</a></p> <pre><code>wins = [x['wins'] for x in data['playerStatSummaries']] print(wins) &gt;&gt;&gt; [211, 44, 10] </code></pre>
0
2016-05-26T15:32:25Z
[ "python", "json", "dictionary" ]
Python 3: Iterating over a dictionary
37,465,087
<p>I would've created a more specific title but I'm not sure how to formulate my question. </p> <pre><code>{ "playerStatSummaries": [ { "playerStatSummaryType": "AramUnranked5x5", "aggregatedStats": { "totalChampionKills": 2250, "totalAssists": 6199, "tota...
0
2016-05-26T15:25:46Z
37,465,404
<p>Use a <code>if</code> condition on a list comprehension:</p> <pre><code>win_dict = [{'wins': x['wins']} for x in json_data['playerStatSummaries'] if x['playerStatSummaryType'] == 'RankedSolo5x5'] # [{'wins': 44}] </code></pre>
0
2016-05-26T15:40:22Z
[ "python", "json", "dictionary" ]
Python 3: Iterating over a dictionary
37,465,087
<p>I would've created a more specific title but I'm not sure how to formulate my question. </p> <pre><code>{ "playerStatSummaries": [ { "playerStatSummaryType": "AramUnranked5x5", "aggregatedStats": { "totalChampionKills": 2250, "totalAssists": 6199, "tota...
0
2016-05-26T15:25:46Z
37,465,681
<p>In this syntax, a <code>{}</code> indicates a dictionary, while a <code>[]</code> indicates a list or array.</p> <p>You have a <code>{</code> to start with, so your outer data item is a dictionary. The main key seems to be <code>"playerStatSummaries"</code> so let's access that directly:</p> <pre><code>data['playe...
0
2016-05-26T15:52:37Z
[ "python", "json", "dictionary" ]
Python 3: Iterating over a dictionary
37,465,087
<p>I would've created a more specific title but I'm not sure how to formulate my question. </p> <pre><code>{ "playerStatSummaries": [ { "playerStatSummaryType": "AramUnranked5x5", "aggregatedStats": { "totalChampionKills": 2250, "totalAssists": 6199, "tota...
0
2016-05-26T15:25:46Z
37,466,363
<p>You can use a recursive function like this:</p> <pre><code>def get_wins(obj): wins = [] if isinstance(obj, list): for val in obj: if isinstance(val, (dict, list)): return_val = get_win(val) if return_val: wins.extend(return_val) elif...
0
2016-05-26T16:27:18Z
[ "python", "json", "dictionary" ]
Pairing bluetooth devices with Passkey/Password in python - RFCOMM (Linux)
37,465,157
<p>I am working on a Python script to search for bluetooth devices and connect them using <em>RFCOMM</em>. This devices has Passkey/Password. I am using PyBlueZ and, as far as I know, this library cannot handle Passkey/Password connections (<a href="http://stackoverflow.com/questions/17089786/python-pybluez-connecting-...
0
2016-05-26T15:29:04Z
37,487,500
<p>Finally I am able to connect to a device using PyBlueZ. I hope this answer will help others in the future. I try the following:</p> <p>First, import the modules and discover the devices.</p> <pre><code>import bluetooth, subprocess nearby_devices = bluetooth.discover_devices(duration=4,lookup_names=True, ...
0
2016-05-27T15:40:30Z
[ "python", "linux", "bluetooth", "pybluez" ]
How to use BeautifulSoup Python to scrap a webpage url?
37,465,172
<p>I get started with web scraping and I would like to get the URLs from certain page provided below. </p> <pre><code>import requests from bs4 import BeautifulSoup as Soup page = "http://www.zillow.com/homes/for_sale/fore_lt/2-_beds/any_days/globalrelevanceex_sort/57.610107,-65.170899,15.707662,-128.452149_rect/3_z...
0
2016-05-26T15:29:45Z
37,473,393
<p>The issue is that the request you send doesn't get the URLs. In fact, if I look at the response (using e.g. jupyter) I get: <a href="http://i.stack.imgur.com/YrJ1l.png" rel="nofollow"><img src="http://i.stack.imgur.com/YrJ1l.png" alt="Missing the important part"></a></p> <p><strong>I would suggest a different st...
1
2016-05-27T01:28:19Z
[ "python", "web-scraping", "beautifulsoup" ]
reindex pandas MultiIndex on specific level
37,465,176
<h3>Setup</h3> <pre><code>import pandas as pd import numpy as np from string import ascii_lowercase tidx = pd.date_range(end='2016-04-30', freq='M', periods=3) tidx2 = tidx + pd.offsets.MonthBegin(-1) + pd.offsets.Day(15) + pd.offsets.BDay(-1) np.random.seed([3,1415]) df1 = pd.DataFrame(np.random.rand(9, 1), column...
1
2016-05-26T15:29:54Z
37,465,855
<p><strong>Edit</strong>: New solution, probably more in the spirit of the question:</p> <pre><code>def func(dfg): return dfg.reset_index(level=1, drop=True).reindex(df1.index.levels[0], method='ffill') df2.groupby(level=1).apply(func).swaplevel(i=0, j=1).sortlevel(0) </code></pre> <p>The idea is to group by the...
1
2016-05-26T16:01:44Z
[ "python", "pandas" ]
counting number with 3 csvs python
37,465,269
<p>I have 3 csv that i will like to change one column to a running number that depends on the number on rows in the file. For exmaple, file 1 got 400 rows, file 2 got 240, and file 3 got 100. so the added column for file 1 will be running number from 1 to 400. so the added column for file 2 will be running number from ...
0
2016-05-26T15:34:13Z
37,466,540
<p>@roganjosh I have fixed my code. I know what is the lenght on the file, now i need to add a column with running numbers like:</p> <p>file1 1 to 400</p> <p>file2 401 to 641</p> <p>file 3</p> <p>642 to 742</p> <p>Thanks alot!</p>
0
2016-05-26T16:36:01Z
[ "python", "csv", "row" ]
counting number with 3 csvs python
37,465,269
<p>I have 3 csv that i will like to change one column to a running number that depends on the number on rows in the file. For exmaple, file 1 got 400 rows, file 2 got 240, and file 3 got 100. so the added column for file 1 will be running number from 1 to 400. so the added column for file 2 will be running number from ...
0
2016-05-26T15:34:13Z
37,467,327
<p>Looking at your previous questions that are left open, the common theme is fundamental issue with understanding in how to use functions in Python that isn't being addressed. I will try and unpick part of this to prevent similar questions arising. I'm assuming you come from a scientific background like me so I'll sti...
0
2016-05-26T17:19:40Z
[ "python", "csv", "row" ]
python: pandas - order of data frame column
37,465,303
<p>I have following code to output a dataFrame:</p> <pre><code>output = pd.DataFrame({"id":id_test, "hum":y_pred}) output.to_csv("myOutput.csv", index=False) </code></pre> <p>Then in myOutput.csv, I got <code>hum</code> as the first column, <code>id</code> as the second column. Is there a way to make <code>id</code> ...
2
2016-05-26T15:35:38Z
37,465,325
<p>Just reorder the columns:</p> <pre><code>output.ix[:,['id','hum']].to_csv("myOutput.csv", index=False) </code></pre> <p>Because you used a dict as the data, the column order is not necessarily the same order as the key creation order in the dict</p>
2
2016-05-26T15:36:33Z
[ "python", "pandas" ]
How to reformat a .csv file with in pandas dataframe?
37,465,333
<p>Just a quick question, with pandas <code>to_csv()</code> function I saved a pandas dataframe as a .csv file with this structure:</p> <p>In:</p> <pre><code>df.to_csv(output_file, sep = '|') </code></pre> <p>Out:</p> <pre><code>|id|column2|column3 0|id_1|bla bla bla bla|more strings 1|id_2|bla bla bla bla|more str...
0
2016-05-26T15:37:01Z
37,465,380
<p>Try:</p> <pre><code>df.set_index('id') </code></pre> <p>Where <code>df</code> is your dataframe</p> <hr> <h3>Edit</h3> <p>IIUC</p> <p>What you've provided is a the text from a csv file and you are importing it into a pandas dataframe. It's confusing when you say:</p> <blockquote> <p>How can I restructure t...
2
2016-05-26T15:39:20Z
[ "python", "python-2.7", "python-3.x", "pandas" ]
How to reformat a .csv file with in pandas dataframe?
37,465,333
<p>Just a quick question, with pandas <code>to_csv()</code> function I saved a pandas dataframe as a .csv file with this structure:</p> <p>In:</p> <pre><code>df.to_csv(output_file, sep = '|') </code></pre> <p>Out:</p> <pre><code>|id|column2|column3 0|id_1|bla bla bla bla|more strings 1|id_2|bla bla bla bla|more str...
0
2016-05-26T15:37:01Z
37,465,437
<pre><code>print df.to_string(index=False) </code></pre> <p>This will print your dataframe without the indexes. </p> <pre><code>&gt;&gt;&gt; print df id column2 column3 0 id_1 bla bla bla bla more strings 1 id_2 bla bla bla bla more strings 2 id_3 bla bla bla bla more strings &gt;&gt;&gt...
2
2016-05-26T15:41:37Z
[ "python", "python-2.7", "python-3.x", "pandas" ]
How to reformat a .csv file with in pandas dataframe?
37,465,333
<p>Just a quick question, with pandas <code>to_csv()</code> function I saved a pandas dataframe as a .csv file with this structure:</p> <p>In:</p> <pre><code>df.to_csv(output_file, sep = '|') </code></pre> <p>Out:</p> <pre><code>|id|column2|column3 0|id_1|bla bla bla bla|more strings 1|id_2|bla bla bla bla|more str...
0
2016-05-26T15:37:01Z
37,465,745
<p>It looks like you have a blank string for one of the columns, you can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html#pandas.DataFrame.drop" rel="nofollow"><code>drop</code></a> it:</p> <pre><code>In [47]: df = pd.DataFrame(np.random.randn(5,2), columns=['','asd']) df Out[...
1
2016-05-26T15:56:03Z
[ "python", "python-2.7", "python-3.x", "pandas" ]
Open scrapy output in browser tab or ipython window
37,465,387
<p>I'm working on my first spider after doing the scrapy tut:</p> <pre><code>class My_Spider(scrapy.Spider): name = "My_Spider" def start_requests(self): for i in range(1): yield Request('my_url', method="post", headers= headers, body=payload, callback=self.parse_method) def parse_...
2
2016-05-26T15:39:42Z
37,465,445
<p>Yes, there is an <a href="http://doc.scrapy.org/en/latest/topics/debug.html#open-in-browser" rel="nofollow"><code>open_in_browser()</code></a> built into Scrapy utility function:</p> <pre><code>from scrapy.utils.response import open_in_browser open_in_browser(response) </code></pre>
3
2016-05-26T15:41:59Z
[ "python", "scrapy" ]
How store a base64 image into user session in Flask
37,465,628
<p>Good day. I'm starting with Flask in Python. Everything goes fine, but I have a problem with the session. The idea is to store the base64 avatar of the user into his session after he logged in. Then, in the layout just access to his avatar by <code>&lt;img src="data:image/png;base64,{{session.user.photo}}" /&gt;</co...
0
2016-05-26T15:49:41Z
37,465,801
<p>I am sorry you shouldn't store a big image in the session.</p> <p>A good way to achieve it is to store unique image id, and call url with this unique ID. Like this:</p> <pre><code>&lt;img src = "//myview?id=513654534343543543" /&gt; </code></pre>
0
2016-05-26T15:59:03Z
[ "python", "session", "flask" ]
Print output only separated by commas
37,465,633
<p>Hi I'm trying to print write on a .csv file on python and I want my output to only be separated by commas. I removed the brackets from print() so that no parenthesis were present but this also cleared out commas. How can I fix this? This is my code:</p> <pre><code>print self.t, len(self.sAgentList), len(self.iAgent...
0
2016-05-26T15:49:51Z
37,465,784
<p>The <em>best</em> solution is to use a <code>csv.writer</code> to write the data.</p> <pre><code>import csv import sys writer = csv.writer(sys.stdout) writer.writerow(['1', '2', '3']) </code></pre> <p>Here I write to <code>sys.stdout</code>, but you can write to whatever file-like object that you like. Note that ...
1
2016-05-26T15:58:12Z
[ "python", "csv", "python-2.x" ]
Why my tree view is not loading in Odoo 9?
37,465,782
<p>These following snippets are from my two XML files. I want to create a new tree view for the <code>res.partner</code> model.</p> <pre class="lang-xml prettyprint-override"><code>&lt;record id="distance_range_search_view_tree"model="ir.ui.view"&gt; &lt;field name="name"&gt;distance_range_search_view_tree&lt;/fi...
0
2016-05-26T15:58:01Z
37,472,156
<p>Try this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;record id="distance_range_search_action" model="ir.actions.act_window"&gt; &lt;field name="name"&gt;Account Proximity Search&lt;/field&gt; &lt;field name="type"&gt;ir.actions.act_window&lt;/field&gt; &lt;field name="res_model"&gt;res.par...
0
2016-05-26T22:37:58Z
[ "python", "xml", "odoo-9" ]
"async with" in Python 3.4
37,465,816
<p>The Getting Started docs for aiohttp give the following client example:</p> <pre><code>import asyncio import aiohttp async def fetch_page(session, url): with aiohttp.Timeout(10): async with session.get(url) as response: assert response.status == 200 return await response.read() ...
5
2016-05-26T15:59:34Z
37,466,076
<p>Just don't use the result of <code>session.get()</code> as a context manager; use it as a coroutine directly instead. The request context manager that <code>session.get()</code> produces would normally <a href="http://pythonhosted.org/aiohttp/client_reference.html#aiohttp.ClientResponse.release" rel="nofollow"><em>r...
5
2016-05-26T16:12:26Z
[ "python", "python-3.x", "async-await", "python-asyncio", "aiohttp" ]
"async with" in Python 3.4
37,465,816
<p>The Getting Started docs for aiohttp give the following client example:</p> <pre><code>import asyncio import aiohttp async def fetch_page(session, url): with aiohttp.Timeout(10): async with session.get(url) as response: assert response.status == 200 return await response.read() ...
5
2016-05-26T15:59:34Z
37,467,388
<p><code>aiohttp</code>'s <a href="https://github.com/KeepSafe/aiohttp/tree/master/examples" rel="nofollow">examples</a> implemented using 3.4 syntax. Based on <a href="https://github.com/KeepSafe/aiohttp/blob/master/examples/client_json.py" rel="nofollow">json client example</a> your function would be:</p> <pre><code...
3
2016-05-26T17:23:10Z
[ "python", "python-3.x", "async-await", "python-asyncio", "aiohttp" ]
Module ggplot installed but cannot be imported
37,465,839
<p>I installed <code>ggplot</code> for python 2.7 in a Win64 env using <code>conda</code> via the command line:</p> <pre><code>$conda install -c https://conda.binstar.org/bokeh ggplot </code></pre> <p>since: </p> <pre><code>$pip install -U ggplot </code></pre> <p>could not locate the package (see pevious <a href="h...
1
2016-05-26T16:01:03Z
37,493,044
<p>I am posting the resolution I arrived to. It is not linear, although it may benefit others who may encounter a similar issue. </p> <p>First step: activated the environment <code>envx</code> where the <code>ggplot</code> module was said to reside in. </p> <p>Importing module again:</p> <pre><code>$python -c "impor...
0
2016-05-27T22:18:14Z
[ "python", "python-2.7", "conda", "python-ggplot" ]
How would I incorporate colliderect into a Snake Game?
37,465,950
<p>Let me start off by saying I'm not an amazing coder so the code is not the prettiest. I'm working on a really basic version of snake right now. Currently I'm stumped on the collision between the snake and the food. (x,y for snake and foodx, foody for the food). The Collision Detection is just flat out not working ri...
0
2016-05-26T16:06:14Z
37,469,089
<p>Change x=x+xd to snakecol.x += xd and the same for the y part. Then in the draw part use snakecol as the rect rather than x,y,20,20 as now. The problem is that you never update the snake rect position. Sorry for formatting, am at work and on tablet.</p>
1
2016-05-26T19:03:50Z
[ "python", "pygame" ]
How to efficiently unfold query results into a dictionary
37,466,036
<p>(I will state this is for learning purposes).<br> I have a query which returns <code>('a',) , ('b',) , ('c',)</code> Which I translate to a dictionary which is <code>{a: '',b: '', c: ''}</code> I am doing it the simple way:</p> <pre><code> for(results) in MySQL_CLASS.cursor: MyDict[results[0]] = '' </cod...
0
2016-05-26T16:10:06Z
37,466,131
<p><a href="http://stackoverflow.com/a/37466142/771848">Dict comprehension based approach</a> should be preferred, but, for educational purposes, here is an another option that involves using <a href="https://docs.python.org/3/library/stdtypes.html#dict.fromkeys" rel="nofollow"><code>dict.fromkeys()</code></a> with <co...
0
2016-05-26T16:15:22Z
[ "python", "mysql", "list", "python-3.x", "dictionary" ]
How to efficiently unfold query results into a dictionary
37,466,036
<p>(I will state this is for learning purposes).<br> I have a query which returns <code>('a',) , ('b',) , ('c',)</code> Which I translate to a dictionary which is <code>{a: '',b: '', c: ''}</code> I am doing it the simple way:</p> <pre><code> for(results) in MySQL_CLASS.cursor: MyDict[results[0]] = '' </cod...
0
2016-05-26T16:10:06Z
37,466,142
<p>You could use <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dict comprehension</a>:</p> <pre><code>&gt;&gt;&gt; results = (('a',) , ('b',) , ('c',)) &gt;&gt;&gt; {x[0]: '' for x in results} {'a': '', 'c': '', 'b': ''} </code></pre>
1
2016-05-26T16:15:51Z
[ "python", "mysql", "list", "python-3.x", "dictionary" ]
Python - Return a unique list of objects
37,466,068
<p>I am trying to get a unique list of objects, I have some code that pulls data from an API and then puts that data into an object. I then put those objects in a list. however some of the objects are duplicates and I would like to know how to remove them?</p> <p>sample list data:</p> <pre><code>[ Policy: 'SQL', Sec...
1
2016-05-26T16:11:40Z
37,466,244
<p><strong>For Python 2.x</strong></p> <p>I think you'll want to implement <code>__cmp__</code> for your class that stores the API data.</p> <p><strong>For Python 3.x</strong></p> <p>I think you'll want to implement <code>__eq__</code> for your class that stores the API data.</p> <p>Regardless of which version of P...
1
2016-05-26T16:20:53Z
[ "python" ]
Python - Return a unique list of objects
37,466,068
<p>I am trying to get a unique list of objects, I have some code that pulls data from an API and then puts that data into an object. I then put those objects in a list. however some of the objects are duplicates and I would like to know how to remove them?</p> <p>sample list data:</p> <pre><code>[ Policy: 'SQL', Sec...
1
2016-05-26T16:11:40Z
37,466,544
<p>How about using dictionaries and then a <code>pandas.DataFrame</code>?</p> <p>Something like:</p> <pre><code>d1 = { 'Policy': 'SQL', 'SecondaryPolicy': 'ORACLE', 'Level': 'Primary On Call Engineer', 'LevelNo': 1, 'StartDate': None, 'EndDate': None, 'StartTime': None, 'EndTime': None, 'Name': 'Fred', 'Mobil...
0
2016-05-26T16:36:13Z
[ "python" ]
Python - Return a unique list of objects
37,466,068
<p>I am trying to get a unique list of objects, I have some code that pulls data from an API and then puts that data into an object. I then put those objects in a list. however some of the objects are duplicates and I would like to know how to remove them?</p> <p>sample list data:</p> <pre><code>[ Policy: 'SQL', Sec...
1
2016-05-26T16:11:40Z
37,466,803
<p>You could subclass the <code>User</code> class and implement <code>__eq__</code> and <code>__hash__</code> method, then just add those to a <code>set</code>, like this:</p> <pre><code>class UserUnique(User): def __hash__(self): return hash(self.Name) def __eq__(self, o): return self.Name == ...
0
2016-05-26T16:49:59Z
[ "python" ]
Copy an itertools cycle object
37,466,115
<p>I want to make a shallow copy of an <code>itertools.cycle</code> object, but I don't know how because it has no builtin copy method. I want to achieve something like the following, where I create a copy of the cycle, iterate through it a few times, then copy the original again, and iterate a few more times <em>start...
2
2016-05-26T16:14:30Z
37,466,233
<p><code>copy</code> should do the trick: </p> <pre><code>&gt;&gt;&gt; from copy import copy &gt;&gt;&gt; cyc_copy = copy(cyc) &gt;&gt;&gt; next(cyc_copy) 'A' &gt;&gt;&gt; next(cyc_copy) 'B' &gt;&gt;&gt; cyc_copy = copy(cyc) &gt;&gt;&gt; next(cyc_copy) 'A' &gt;&gt;&gt; next(cyc_copy) 'B' </code></pre>
0
2016-05-26T16:20:15Z
[ "python", "itertools" ]
Copy an itertools cycle object
37,466,115
<p>I want to make a shallow copy of an <code>itertools.cycle</code> object, but I don't know how because it has no builtin copy method. I want to achieve something like the following, where I create a copy of the cycle, iterate through it a few times, then copy the original again, and iterate a few more times <em>start...
2
2016-05-26T16:14:30Z
37,466,755
<p>Copying the cycle itself is going to run into problems. For example, <a href="http://ideone.com/sLSmjK" rel="nofollow"><code>copy.copy</code>ing it doesn't produce independent copies</a>.</p> <p>Instead of trying to copy the cycle, I recommend recreating it from your original object:</p> <pre><code>new_cyc = itert...
1
2016-05-26T16:47:23Z
[ "python", "itertools" ]