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
Split jupyter notebook into several files
38,183,603
<p>I am currently creating many tables in python and most of the cells need their own SQL query. I am ending up with a long list of SQL querys. Ideally I would put the table creation of each table in its own file and load the files from a main notebook. </p> <p>Is there a way to run sub-notebooks (containing the table...
0
2016-07-04T11:26:52Z
38,184,107
<p>I don't believe this is currently possible in Jupyter to have "child" notebooks in the same way you can with knitr. </p> <p>Fernando Perez wrote a <a href="https://gist.github.com/fperez/e2bbc0a208e82e450f69" rel="nofollow">script to merge together multiple notebooks</a> which may be helpful in your case to avoid h...
0
2016-07-04T11:53:10Z
[ "python", "jupyter-notebook" ]
Converting Epoch DateTime to Byte Array in Python
38,183,676
<p>I am trying to convert epoch datetime to byte array in python but it is coming as 10 Byte, it should come in 4 Byte.</p> <pre><code>from time import time curTime = int(time.time()) b = bytearray(str(curTime)) len(b) #comming as 10 </code></pre> <p>Can any one help where i am wrong</p>
1
2016-07-04T11:30:58Z
38,183,832
<p>You are converting the string representation of the timestamp, not the integer.</p> <p>What you need is this function:</p> <p>struct.pack_into(fmt, buffer, offset, v1, v2, ...) It's documented at <a href="http://docs.python.org/library/struct.html" rel="nofollow">http://docs.python.org/library/struct.html</a> near...
2
2016-07-04T11:39:05Z
[ "python", "epoch" ]
Filter tests after discover
38,183,678
<p>I'm currently running my tests like this:</p> <pre><code>tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner().run(tests) </code></pre> <p>Now I want to run a specific test knowing his name (like <code>test_valid_user</code>) but not knowing his class. If there is more than one test with such n...
3
2016-07-04T11:31:03Z
38,184,300
<p>There are two ways to run a single test method:</p> <p><strong>Command line:</strong></p> <pre><code>$ python -m unittest test_module.TestClass.test_method </code></pre> <p><strong>Using Python script:</strong></p> <pre><code>import unittest class TestMyCode(unittest.TestCase): def setUp(self): pas...
0
2016-07-04T12:03:52Z
[ "python", "python-unittest" ]
Filter tests after discover
38,183,678
<p>I'm currently running my tests like this:</p> <pre><code>tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner().run(tests) </code></pre> <p>Now I want to run a specific test knowing his name (like <code>test_valid_user</code>) but not knowing his class. If there is more than one test with such n...
3
2016-07-04T11:31:03Z
38,184,605
<p>Another simpler way, would be to use <a href="http://pytest.org/latest/getting-started.html" rel="nofollow" title="Installation and Getting Started">py.test</a> with the <code>-k</code> option which does a test name keyword scan. It will run any tests whose name matches the keyword expression.</p> <p>Although that ...
1
2016-07-04T12:18:28Z
[ "python", "python-unittest" ]
Filter tests after discover
38,183,678
<p>I'm currently running my tests like this:</p> <pre><code>tests = unittest.TestLoader().discover('tests') unittest.TextTestRunner().run(tests) </code></pre> <p>Now I want to run a specific test knowing his name (like <code>test_valid_user</code>) but not knowing his class. If there is more than one test with such n...
3
2016-07-04T11:31:03Z
38,185,487
<p>You can use the <code>unittest.loader.TestLoader.testMethodPrefix</code> instance variable to change the test methods filter according to a different prefix than "test".</p> <p>Say you have a <code>tests</code> directory with this king of unit tests:</p> <pre><code>import unittest class MyTest(unittest.TestCase)...
1
2016-07-04T13:04:39Z
[ "python", "python-unittest" ]
How to auto answer prompts via SSH connection in python
38,183,684
<p>I want to call an application on a remote machine using python paramiko; this application waits till you enter a specific string and then succeeds. How can I send requested string over SSH connection to it?</p> <p>The application call is like: </p> <pre><code>./app --init This option will delete the database and ...
0
2016-07-04T11:31:21Z
38,185,780
<p>I found the solution in one of the un-accepted answers in <a href="http://stackoverflow.com/questions/373639/running-interactive-commands-in-paramiko">this question</a>.</p> <p>This is what I've finally tried and succeeded:</p> <pre><code>cmd = 'cd app_address;./app --init' answer = 'I KNOW THAT THIS OPTION DESTRO...
0
2016-07-04T13:19:04Z
[ "python", "ssh", "prompt", "paramiko" ]
Annotate each row with percent of total for group by, in pandas?
38,183,699
<p>I have a dataframe that looks like this:</p> <pre><code>Company Speciality Payment AcmeCorp Roofing 50.00 AcmeCorp Grounding 50.00 LolCorp Roofing 106.00 LolCorp Grounding 94.00 </code></pre> <p>I'd like to add a percentage column like this:</p> <pre><c...
2
2016-07-04T11:32:06Z
38,183,748
<p>Use <code>groupby/transform</code> to produce a column of the same length as the original DataFrame. This allows you to avoid calling <code>pd.merge</code>.</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame({'Company': ['AcmeCorp', 'AcmeCorp', 'LolCorp', 'LolCorp'], 'Payment': [50.0, 50.0, 1...
3
2016-07-04T11:34:41Z
[ "python", "pandas" ]
Wrong colors after scaling an image in pygame
38,183,713
<p>I have a 64*64px image of a tree:</p> <p><a href="http://i.stack.imgur.com/RuScO.png" rel="nofollow"><img src="http://i.stack.imgur.com/RuScO.png" alt="small image of a tree"></a></p> <p>I wanted to resize this image for a full screen mode during runtime. I have tried to write some code for this (see below). After...
3
2016-07-04T11:32:31Z
38,184,015
<p>First: have a look at pygame.image.load():</p> <blockquote> <p>For alpha transparency, like in .png images use the convert_alpha() method after loading so that the image has per pixel transparency.</p> </blockquote> <p><a href="http://www.pygame.org/docs/ref/image.html#pygame.image.load" rel="nofollow">http://...
3
2016-07-04T11:48:55Z
[ "python", "pygame" ]
Wrong colors after scaling an image in pygame
38,183,713
<p>I have a 64*64px image of a tree:</p> <p><a href="http://i.stack.imgur.com/RuScO.png" rel="nofollow"><img src="http://i.stack.imgur.com/RuScO.png" alt="small image of a tree"></a></p> <p>I wanted to resize this image for a full screen mode during runtime. I have tried to write some code for this (see below). After...
3
2016-07-04T11:32:31Z
38,184,268
<p>Your source Surface (from the image) and your target Surface don't use the same <strong>colorkeys</strong>.</p> <p>Using the default constructor <code>pygame.Surgafe</code> you get a Surface without default colokeys.</p> <blockquote> <p>Surfaces can have many extra attributes like alpha planes, colorkeys, source...
0
2016-07-04T12:02:05Z
[ "python", "pygame" ]
Python call a function inside another function
38,183,866
<p>How to call a function inside another function in python (not to write a function within another function). </p> <pre><code>class OrderDetails(Document): def validate(self): # Remove duplicates found={} #global nfound i=-1 #msgprint(_("00000")) #msgprint(_(found)) #frappe.errprint(fou...
-4
2016-07-04T11:41:05Z
38,183,935
<p>Since you haven't specified <code>edit_quantity_on_hand</code> as a static method, you need to reference it as an instance method with <code>self.edit_quantity_on_hand</code>. Also, that function needs a parameter that includes the instance itself - which it does, but it's <code>data</code> at the moment. Use <code>...
3
2016-07-04T11:44:32Z
[ "python" ]
Catch errors in pyinotify ProcessEvent
38,184,002
<p>I have problems to catch errors inside an event handler from pyinotify. I am trying to do some processing on files that have just been closed after being written to.</p> <p>Here is a simplified version of my script:</p> <pre><code>import pyinotify import asyncore mask = pyinotify.IN_CLOSE_WRITE class EventHandle...
1
2016-07-04T11:48:01Z
38,186,580
<p>I had to create a custom AsyncNotifier:</p> <pre><code>class CustomAsyncNotifier(pyinotify.AsyncNotifier): def handle_error(self): print "Handling error!" print "Guru meditiation #00000025.65045338" print "" print "Continuing anyway..." </code>...
0
2016-07-04T14:01:23Z
[ "python", "pyinotify" ]
tkinter display output in message box
38,184,023
<p>I would like to display the result of the entry that I asked. I managed to display result in the console but not the message opened by tkMessageBox.showinfo. Instead I get sme numerical values. which is quite strange since </p> <p>Below is my code. </p> <pre><code> #!/usr/bin/env python from Tkinter import * im...
1
2016-07-04T11:49:08Z
38,184,995
<p>There are 2 things you need to fix:</p> <p>First of all, do not delete the content of those entries. This means <strong>you must remove away these 3 lines</strong>: </p> <pre><code> ChamploginS3.delete(0,END) ChampsecretpasseS3.delete(0,END) ChampsendpointS3.delete(0,END) </code></pre> <p>Secondly, the cont...
0
2016-07-04T12:39:24Z
[ "python", "tkinter", "messagebox", "display" ]
Fetch youtube video title and category from url using youtube api v3
38,184,132
<p>I'm a total beginner at this! I want to fetch the title of a youtube video and also it's category from the Url in python.</p> <pre><code>import lxml from lxml import etree youtube = etree.HTML(urllib.urlopen("http://www.youtube.com/watch?v=KQEOBZLx-Z8").read()) video_title = youtube.xpath("//span[@id='eow-title']/@...
1
2016-07-04T11:54:20Z
38,185,485
<p>You can access the data using the <a href="https://developers.google.com/api-client-library/python/start/installation" rel="nofollow">google-api-client</a> lib, simple example:</p> <pre><code>from apiclient.discovery import build from apiclient.errors import HttpError from oauth2client.tools import argparser # Se...
0
2016-07-04T13:04:34Z
[ "python", "youtube" ]
Fetch youtube video title and category from url using youtube api v3
38,184,132
<p>I'm a total beginner at this! I want to fetch the title of a youtube video and also it's category from the Url in python.</p> <pre><code>import lxml from lxml import etree youtube = etree.HTML(urllib.urlopen("http://www.youtube.com/watch?v=KQEOBZLx-Z8").read()) video_title = youtube.xpath("//span[@id='eow-title']/@...
1
2016-07-04T11:54:20Z
38,187,966
<p>I've tried this:</p> <pre><code>import gdata.youtube import gdata.youtube.service yt_service = gdata.youtube.service.YouTubeService() yt_service.developer_key = "" #KEY yt_service.client_id = "" #ID entry = yt_service.GetYouTubeVideoEntry(video_id='KQEOBZLx-Z8') def PrintEntryDetails(entry): print 'Video title: ...
0
2016-07-04T15:17:26Z
[ "python", "youtube" ]
Make extension using Cython, with a different name than the source file
38,184,272
<p>I know how to make C code from Python using <code>cythonize -o mymodule.c mymodule.py</code> or using the <code>cython</code> command. The resulting C file has to be compiled to an Python extension using gcc or any other C compiler, and I'm also able doing that. If I want it really simple, I just use <code>distutils...
0
2016-07-04T12:02:29Z
38,210,701
<p>Try this in your <code>setup.py</code></p> <pre><code>try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy as np # if it requires numpy e...
-1
2016-07-05T18:57:05Z
[ "python", "gcc", "cython" ]
How to write String template file with multiple loop elements?
38,184,340
<p>I have small issue in writing for loop elements in string template as follows: when I try to make a string templete from three loop elements I can able to print only the last element not the first two elements. I beleive that the error is because of some issues in writing file but I couldnt get what is the actual p...
1
2016-07-04T12:05:44Z
38,184,925
<p>Your template is getting its substitution values from the last values of <code>i</code> and <code>j</code> from the <code>for</code> loop. You need to persist values from the previous iteration. How? You could use a dictionary and a count to store and distinguish values at each iteration.</p> <p>You can <a href="ht...
1
2016-07-04T12:35:52Z
[ "python", "string", "templates", "file-handling", "stringtemplate" ]
return value = undefined when i try to call a Ajax-function inside another Ajax-function
38,184,463
<p>i have a function with a XML-HTTP-Request. Unfortunately i don't get back my DB-result when i call this function <em>getUserdataByToken()</em> &lt;-- working, via a second Function <em>sendPost(wall)</em>.</p> <p>I just want to have the return value (array) inside my second function but the value is always "undefin...
0
2016-07-04T12:10:56Z
38,184,562
<p>The userdata value only exists within the anonymous Ajax callback function, and you only return it from there. That is pointless because there is nowhere for it to be returned to; certainly the value does not get returned from <code>getUserdataByToken</code>. Don't forget that Ajax calls are <em>asynchronous</em>; w...
2
2016-07-04T12:15:51Z
[ "javascript", "python", "ajax" ]
How to implement left outer join in python pandas?
38,184,554
<p>I have been trying to implement left outer join in python.I see that there is slight difference between left join and left outer join.</p> <p>As in this link : <a href="http://stackoverflow.com/questions/406294/left-join-and-left-outer-join-in-sql-server">LEFT JOIN and LEFT OUTER JOIN in SQL Server</a></p> <p>I co...
2
2016-07-04T12:15:22Z
38,184,587
<p>set param <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>indicator=True</code></a>, this will add a column <code>_merge</code> you then filter just the rows that are <code>left_only</code>:</p> <pre><code>In [46]: df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'...
2
2016-07-04T12:17:18Z
[ "python", "pandas" ]
Why does the op integer not change when the buttons are pressed?
38,184,585
<p>I'm new to python so this code is a mess but I have found a bug I can't fix. The program is meant to give you maths sums to solve and I was using buttons that sent an int as a value from 1 to 4 then that is tested in the guess function to generate the next question. The problem is that the int is not changing when t...
0
2016-07-04T12:17:00Z
38,184,632
<p>Because <code>op</code> is a local variable in every function.</p> <p>You should add <code>global op</code>:</p> <pre><code>def plus(*args): global op op = 1 . . . </code></pre> <p>But be aware that this is a very sub-optimal way of doing it. It makes much more sense to have a class, then have these fun...
1
2016-07-04T12:19:53Z
[ "python", "math", "tkinter" ]
Turtlebot subscriber pointcloud2 shows color in Gazebo simulator but not in robot
38,184,655
<p>I am subscribing to topic <code>"/camera/depth/points"</code> and message <code>PointCloud2</code> on a turtlebot (deep learning version) with ASUS Xtion PRO LIVE camera.</p> <p>I have used the python script below under the gazebo simulator environment and i can receive x, y, z and rgb values successfully.</p> <p>...
5
2016-07-04T12:21:01Z
38,308,971
<p>The contents of Published topics are determined by the software that provides them - i.e. the drivers for your camera. To fix this you therefore need to get the right driver and use the topic that it says contains the required information.</p> <p>You can find recommended drivers for your cameras on the <a href="ht...
2
2016-07-11T14:03:57Z
[ "python", "rgb", "point-cloud-library", "ros", "point-clouds" ]
How to access variable of other user Class(blender python)?
38,184,777
<p>I want to access variable of other Class. Static variable of other Class was very good accessed. But dynimic changed variable value of ther Class was not good accessed.</p> <p>Why I can't get the changed variable value?</p> <hr> <pre><code>bl_info = { "name": "New Object", "author": "Your Name Here", ...
0
2016-07-04T12:28:28Z
38,189,170
<p>I assume that</p> <blockquote> <p>testInstance = SelectFace() # why not work?</p> </blockquote> <p>is the real question.</p> <p>see: <a href="https://www.blender.org/api/blender_python_api_2_60a_release/info_overview.html" rel="nofollow">https://www.blender.org/api/blender_python_api_2_60a_release/info_overv...
0
2016-07-04T16:37:21Z
[ "python", "blender", "bpy" ]
How to access variable of other user Class(blender python)?
38,184,777
<p>I want to access variable of other Class. Static variable of other Class was very good accessed. But dynimic changed variable value of ther Class was not good accessed.</p> <p>Why I can't get the changed variable value?</p> <hr> <pre><code>bl_info = { "name": "New Object", "author": "Your Name Here", ...
0
2016-07-04T12:28:28Z
38,199,959
<p>An operator in blender is used to perform an action. While we use a class to define that action and related properties, we shouldn't treat them as normal python classes. The properties of an operator should be used to adjust the action peformed, not to hold variable data.</p> <p>As the operators properties control ...
0
2016-07-05T09:35:28Z
[ "python", "blender", "bpy" ]
How to click on a href link by using python scripts and selenium?
38,184,788
<p>I am trying to get Selenium to click on a specific href such as</p> <pre><code>&lt;a href="publications.html"&gt;Publications&lt;/a&gt; </code></pre> <p>I tried doing</p> <pre><code>driver.find_element_by_link_text('Publications.html').click() </code></pre> <p>but it gives me the error: </p> <blockquote> <p>A...
0
2016-07-04T12:29:01Z
38,184,839
<p>Change</p> <pre><code>find_element_by_link_text('Publications.html') </code></pre> <p>to</p> <pre><code>find_element_by_link_text('Publications') </code></pre>
1
2016-07-04T12:31:26Z
[ "python", "html", "selenium", "selenium-webdriver", "href" ]
How to click on a href link by using python scripts and selenium?
38,184,788
<p>I am trying to get Selenium to click on a specific href such as</p> <pre><code>&lt;a href="publications.html"&gt;Publications&lt;/a&gt; </code></pre> <p>I tried doing</p> <pre><code>driver.find_element_by_link_text('Publications.html').click() </code></pre> <p>but it gives me the error: </p> <blockquote> <p>A...
0
2016-07-04T12:29:01Z
38,188,801
<p><code>.find_element_by_link_text()</code> finds an <code>A</code> tag by the text inside the <code>A</code> tag, e.g.</p> <pre><code>&lt;a href="publications.html"&gt;Publications&lt;/a&gt; </code></pre> <p>You can find this tag using</p> <pre><code>driver.find_element_by_link_text("Publications") </code></pre> ...
0
2016-07-04T16:10:46Z
[ "python", "html", "selenium", "selenium-webdriver", "href" ]
Generate values with np.random
38,184,886
<p>I try to add new column to df, where all values there 0 or 1. I use </p> <pre><code>df['name'] = np.random.randint(0, 1) </code></pre> <p>But it returns column with all <code>0</code>.</p>
1
2016-07-04T12:33:43Z
38,184,926
<p>Use the shape specifier to let it create an array of random integers in the interval <code>[0,2)</code> that is <code>0</code> or <code>1</code> and of length same as the number of rows in the <code>dataframe</code> with <code>np.random.randint(0, 2,(df.shape[0]))</code> and then assign as the new column. Thus, the ...
3
2016-07-04T12:35:53Z
[ "python", "numpy", "pandas" ]
Generate values with np.random
38,184,886
<p>I try to add new column to df, where all values there 0 or 1. I use </p> <pre><code>df['name'] = np.random.randint(0, 1) </code></pre> <p>But it returns column with all <code>0</code>.</p>
1
2016-07-04T12:33:43Z
38,184,941
<p><strong>Hint :</strong> The upper bound is exclusive with this <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html" rel="nofollow">function</a>.</p> <hr> <p>You should consider using :</p> <pre><code>np.random.randint(0, 2, nb_col) </code></pre> <p>Where <code>nb_col</code> is ...
3
2016-07-04T12:36:46Z
[ "python", "numpy", "pandas" ]
Django-Monitor - get_model() takes at most 3 arguments (4 given)
38,184,889
<p>I have been trying to find a way to moderate items going into the database so that a super user must approve before things are displayed. I found that Django-monitor manages to do pretty much all of that, I have been reading and following the documentation (<a href="http://django-monitor.readthedocs.io/en/latest/int...
0
2016-07-04T12:33:47Z
38,185,021
<p>That looks like a lib problem. if you are certain that it is caused on that line, then the lib's work is getting the error. I doubt that it's a lib error, so a full traceback would help a lot, and the models declaration as well. Also, see if your django version is supported by the lib.</p> <p>By the way, that error...
0
2016-07-04T12:40:31Z
[ "python", "django" ]
Django-Monitor - get_model() takes at most 3 arguments (4 given)
38,184,889
<p>I have been trying to find a way to moderate items going into the database so that a super user must approve before things are displayed. I found that Django-monitor manages to do pretty much all of that, I have been reading and following the documentation (<a href="http://django-monitor.readthedocs.io/en/latest/int...
0
2016-07-04T12:33:47Z
38,185,168
<p>It seems like it's incompatible with your django version. Looking at the <a href="https://bitbucket.org/rajeesh/django-monitor/src/fc82464982b83da23727923d454b1bd3aef438a9/django_monitor/__init__.py?at=default&amp;fileviewer=file-view-default#__init__.py-48" rel="nofollow">repo source</a> it seems like it was fixed:...
0
2016-07-04T12:47:33Z
[ "python", "django" ]
Django-Monitor - get_model() takes at most 3 arguments (4 given)
38,184,889
<p>I have been trying to find a way to moderate items going into the database so that a super user must approve before things are displayed. I found that Django-monitor manages to do pretty much all of that, I have been reading and following the documentation (<a href="http://django-monitor.readthedocs.io/en/latest/int...
0
2016-07-04T12:33:47Z
38,186,304
<p><code>get_model()</code> was changed in 1.7 as explained in the <a href="https://docs.djangoproject.com/en/1.9/releases/1.7/#introspecting-applications" rel="nofollow">release notes</a>:</p> <blockquote> <p>The app registry has preserved some features of the old app cache. Even though the app cache was a privat...
0
2016-07-04T13:47:07Z
[ "python", "django" ]
Why does this Python if condition always return false?
38,184,969
<p>Can anyone tell me why this always returns 'no mortgage'? </p> <pre><code>job = input('do you have a job?, Y or N ') wage = int(input('how much do you earn a year? ')) if job == 'Y' and wage&lt;20000 : print ('you can have a mortgage') else: print('no mortgage') </code></pre>
0
2016-07-04T12:38:21Z
38,185,368
<p>If the users input is lowercase it will return 'no mortage'. To make sure the user's input is always uppercase use</p> <pre><code>if job.upper() == 'Y' </code></pre>
-1
2016-07-04T12:57:15Z
[ "python", "python-3.x", "if-statement" ]
exporting feature importance to csv from random forest
38,185,014
<p>Hi I would like to create a .csv with 2 columns: the feature importance of a random forest model and the name of that feature. And to be sure that the match between numeric value and variable name is correct</p> <p>Here it's an example but I cannot export to .csv correclty</p> <pre><code>test_features = test[["are...
0
2016-07-04T12:40:25Z
38,197,064
<p>Use this</p> <pre><code>x = list(zip(my_forest.feature_importances_,list of features you are using)) x = pandas.DataFrame(x,columns=["Importance","Feature_Name"]) </code></pre>
0
2016-07-05T06:58:38Z
[ "python", "csv", "pandas", "scikit-learn", "random-forest" ]
Finding hourly averages of CSV file using python
38,185,022
<p>So I have a code where I am inputting a CSV file that has two columns. The first is the date and time which is by minutes and its about a month and a half long (4/20/2016 2:39:00 PM - 5/29/2016 11:59:00 PM) and the second is my data, each point ranges from 0-360. I have 36,044 points of data. So I am trying to org...
0
2016-07-04T12:40:33Z
38,185,624
<p>Pandas is exactly what you want</p> <pre><code>import pandas as pd data = pd.read_csv('Rmyoung_date_wind_dir.csv', index_col=0, squeeze=True, parse_dates=True, header=None) data.resample('H', how='mean') </code></pre>
1
2016-07-04T13:11:38Z
[ "python", "csv", "numpy" ]
Checking if any letters in my ddict has a value greater than one, if so print some text, if not convert to a list
38,185,051
<p>I am trying to recreate the enigma code in python, currently I am working on getting the switchboard settings and to do this I want to make sure no letters are repeated in the input (which format is "AB CD EF GH" etc.) currently I am checking how many of each letter is in the inputted string by using a default dict....
0
2016-07-04T12:41:46Z
38,185,565
<p>You question is a little broad and not very precise so I hope I'm right in this code example.</p> <pre><code>from string import ascii_letters input_ok = 'AB CD EF gh ij' input_nok = 'AB CD EF gh ij Ag' # Searches for repeated characters for ch in ascii_letters: count = input_nok.count(ch) if count &gt; 1:...
0
2016-07-04T13:08:56Z
[ "python", "python-3.x" ]
Divide numpy array Python
38,185,119
<p>I have this piece of code:</p> <pre><code>n = np.load(matrix)["arr_0"] shape = n.shape ##colsums and rowsums rows = {} cols = {} for i in xrange(shape[0]): #row rows[i] = np.sum(n[i,:]) for j in xrange(shape[1]): #cols cols[j] = np.sum(n[:,j]) ##looping over bins for i in xrange(shape[0]): #row print i ...
0
2016-07-04T12:44:53Z
38,185,205
<p>You can simply take the sums individually on each axis, then take the outer product, then the square root. This can be condensed a bit but it gives you an idea how to vectorize it.</p> <pre><code># Sum of rows and columns a = numpy.sum(data, axis=1) b = numpy.sum(data, axis=0) # Product of sum and columns c = nump...
2
2016-07-04T12:49:42Z
[ "python", "numpy" ]
Divide numpy array Python
38,185,119
<p>I have this piece of code:</p> <pre><code>n = np.load(matrix)["arr_0"] shape = n.shape ##colsums and rowsums rows = {} cols = {} for i in xrange(shape[0]): #row rows[i] = np.sum(n[i,:]) for j in xrange(shape[1]): #cols cols[j] = np.sum(n[:,j]) ##looping over bins for i in xrange(shape[0]): #row print i ...
0
2016-07-04T12:44:53Z
38,185,352
<p>Here's a one-liner solution using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a> and <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> -</p> <pre><code>np.where((rows[:,N...
1
2016-07-04T12:56:27Z
[ "python", "numpy" ]
Save log files in the user home directory
38,185,266
<p>I have a logging.conf [1] file to configure the logging in my python application.</p> <pre><code>... [handler_file_log_handler] class=logging.handlers.TimedRotatingFileHandler level=INFO formatter=simple args=('/var/log/myapp/myapp.log',) </code></pre> <p>As you can see, I'm storing the log file in /var/log/myapp ...
1
2016-07-04T12:52:41Z
38,185,478
<p>The user's home directory can be found (on any OS) using:</p> <pre><code>os.path.expanduser("~") </code></pre>
1
2016-07-04T13:04:00Z
[ "python", "logging" ]
Python search mutiple hard drives
38,185,268
<p>I'm trying to write a simple script that searches my local drive C: and my two external drives E: and F: for all .docx files and write them to a log. I have the search part down right but can only search one hard drive at a time and can not figure out how to write the results to a .log or .txt file. Here is my start...
0
2016-07-04T12:52:49Z
38,185,655
<pre><code>import fnmatch import os drives = ['C:\\','E:\\','F:\\'] pattern = "*.docx" for rootPath in drives: print "Now searching in: ",rootPath for root, dirs, files in os.walk(rootPath) : for filename in fnmatch.filter(files, pattern) : print os.path.join(root, filename) </code></pre> ...
0
2016-07-04T13:13:21Z
[ "python", "search", "drive" ]
pandas dataframe data retrieval
38,185,311
<p>Here is my sample pandas data frame</p> <pre><code> icd_code from_date paid_amount claim_id CKEY-7724339 719.43 2015-09-26 300.09 CKEY-5008998 722.2 2015-04-21 11.65 CKEY-7896598 722 2015-02-23 17.19 CKEY-7758556 850.9 2...
0
2016-07-04T12:54:33Z
38,185,747
<p>Using the code below gave me the expected ouput:</p> <pre><code>$&gt;&gt;&gt; indexed_data.loc[['CKEY-8369057']] </code></pre> <p>Passing single value to .loc will return a Dataframe when multiple rows exist and a Series if only one row exists. But passing a list to .loc will always return a Dataframe.</p> <p>Co...
0
2016-07-04T13:17:21Z
[ "python", "pandas", "dataframe" ]
py2exe import numpy and scipy
38,185,329
<p>I used py2exe to build an exe of a program that uses scipy and numpy and I get the next error in the log file when I tried to run the program.</p> <pre><code>Traceback (most recent call last): File "GLP2-e Admin.pyw", line 24, in &lt;module&gt; File "C:\Python34\lib\site-packages\scipy\ndimage\__init__.py", line 16...
0
2016-07-04T12:55:25Z
38,185,708
<p>I have been solve the issue adding in the "includes" section of my setup.py all the files that the log file return me as missing. After 7 files, the program run without any error.</p>
0
2016-07-04T13:15:24Z
[ "python", "numpy", "scipy", "py2exe" ]
Filter data using pandas
38,185,404
<p>I have data</p> <pre><code> id date sec buy 5211153 2016-06-13 18:48:55 119 1 5211153 2016-06-13 18:50:54 66 0 5211153 2016-06-13 18:57:09 2 1 5211154 2016-06-13 18:57:12 118 0 5211154 2016-06-13 18:59:08 ...
-1
2016-07-04T12:59:36Z
38,185,582
<p><strong>UPDATE:</strong> this should work for your current sample DF, but i'm not sure what would you like to have for alternate ones and zeroes in the <code>buy</code> column (for example if you have the following sequence in the <code>buy</code> column belonging to the same <code>id</code>: 1,0,1,1,0 - what would...
1
2016-07-04T13:09:26Z
[ "python", "pandas" ]
python: how to properly pass arguments to executable via commandline
38,185,470
<p>i'm trying to write a small python script, which will allow me to pass parameters to a command line dialog, in order to run a setup file. i want to be able to pass parameters to the executable file, for example: "setup.exe --uninstall --delete-profile --force-uninstall"</p> <p>i've tried to use the "os.system" modu...
0
2016-07-04T13:03:43Z
38,185,861
<p>Use this :</p> <pre><code>subprocess.Popen(['hostname', '-f'], stdout=subprocess.PIPE).communicate()[0] </code></pre> <p>You can also add other parameters :</p> <pre><code>subprocess.Popen(['hostname', '-f', '-anotherparam', 'onemoreparam'], stdout=subprocess.PIPE).communicate()[0] </code></pre>
0
2016-07-04T13:23:23Z
[ "python", "command-line", "parameters", "subprocess" ]
How to obtain detailed device / partition info from file path on Linux (like UUID, hard drive serial etc.)
38,185,473
<p>Starting with an absolute file path, I want to obtain the following information:</p> <ol> <li>The mount point of the filesystem on which the file is stored (in order to compute the path relative to the mount point)</li> <li>The UUID and label of the file system </li> <li>The type (or vendor name) and the serial nu...
10
2016-07-04T13:03:46Z
39,546,516
<p>That would imply some utilities and anlyze output. Launched using os.popen, you can use <code>bklkid</code> to find uuids, reading <code>/etc/mtab</code> file permits to know which filesystem are mounted in your system and thus mountpoints. <code>sfdisk -l</code> output gives you disk anatomy.<code>hdparm -I /dev/xx...
0
2016-09-17T11:53:54Z
[ "python", "linux", "filesystems", "system-calls" ]
How to obtain detailed device / partition info from file path on Linux (like UUID, hard drive serial etc.)
38,185,473
<p>Starting with an absolute file path, I want to obtain the following information:</p> <ol> <li>The mount point of the filesystem on which the file is stored (in order to compute the path relative to the mount point)</li> <li>The UUID and label of the file system </li> <li>The type (or vendor name) and the serial nu...
10
2016-07-04T13:03:46Z
39,552,267
<p>This is a <a href="https://github.com/nsmfoo/antivmdetection" rel="nofollow">script on GitHub</a> I came across earlier today that uses Python to fetch information about drive make and model (and lots of others).</p> <p><code>/proc/partitions</code> holds info on partitions; for more detailed information you'll hav...
2
2016-09-17T22:24:03Z
[ "python", "linux", "filesystems", "system-calls" ]
How to obtain detailed device / partition info from file path on Linux (like UUID, hard drive serial etc.)
38,185,473
<p>Starting with an absolute file path, I want to obtain the following information:</p> <ol> <li>The mount point of the filesystem on which the file is stored (in order to compute the path relative to the mount point)</li> <li>The UUID and label of the file system </li> <li>The type (or vendor name) and the serial nu...
10
2016-07-04T13:03:46Z
39,559,022
<p>The best way to do that is via <code>pyparted</code>. Pyparted are python bindings to Parted maintained by one of the Parted developers. You can find the source code <a href="https://github.com/rhinstaller/pyparted" rel="nofollow">on github</a>. Unfortunately UUID's cannot be found from parted so you have to parse <...
2
2016-09-18T14:56:15Z
[ "python", "linux", "filesystems", "system-calls" ]
Sum same column in different ways depending on other column - Django ORM
38,185,580
<p>I have the following table assignment structure:</p> <pre><code>| employee | product | process | qty | | Swati | PROD1 | issue | 60 | | Rohit | PROD1 | issue | 30 | | Rohit | PROD2 | issue | 40 | | Swati | PROD1 | receive | 40 | | Swati | PROD2 | issue | 70 | </code></pre> <p>...
-1
2016-07-04T13:09:22Z
38,187,021
<p>I guess your Model name is '<strong>Assignment</strong>'. You can use the below query</p> <pre><code>from django.db.models import Case, Value, When, Sum, IntegerField, Count result = Assignment.objects.filter(employee="Swati").values('product').annotate( sum_issued=Sum( Case(When(process='issue', then=...
1
2016-07-04T14:24:57Z
[ "python", "mysql", "django" ]
Theano: using dot "T" at the end of a dot product where number of dimensions is greater than one
38,185,601
<p>I was going through an LSTM code by Jonathan Raiman and I encountered this line of code in "Layer" class</p> <pre><code>if x.ndim &gt; 1: return T.nnet.sigmoid(T.dot(self.linear_matrix,x.T) + self.bias_matrix[:,None]).T </code></pre> <p><code>T</code> is <code>"import theano.tensor as T"</code></p> <p>x i...
0
2016-07-04T13:10:22Z
38,185,754
<p><code>x.T</code> is the transpose of the matrix <code>x</code>.</p> <p><code>.T</code> is a notation that applies transpose to numpy matrices, which is the same as <code>numpy.transpose(x)</code>. It should not be confused with the name <code>T</code> from <code>import theano.tensor as T</code></p> <p>And </p> <...
0
2016-07-04T13:17:38Z
[ "python", "theano" ]
Select rows containing certain values from pandas dataframe
38,185,688
<p>I have a pandas dataframe whose entries are all strings:</p> <pre><code> A B C 1 apple banana pear 2 pear pear apple 3 banana pear pear 4 apple apple pear </code></pre> <p>etc. I want to select all the rows that contain a certain string, say, 'banana'. I don't know which column it will appear i...
3
2016-07-04T13:14:31Z
38,185,709
<p>You can create a boolean mask from comparing the entire df against your string and call <code>dropna</code> passing param <code>how='all'</code> to drop rows where your string doesn't appear in all cols:</p> <pre><code>In [59]: df[df == 'banana'].dropna(how='all') Out[59]: A B C 1 NaN banana ...
3
2016-07-04T13:15:25Z
[ "python", "pandas" ]
Select rows containing certain values from pandas dataframe
38,185,688
<p>I have a pandas dataframe whose entries are all strings:</p> <pre><code> A B C 1 apple banana pear 2 pear pear apple 3 banana pear pear 4 apple apple pear </code></pre> <p>etc. I want to select all the rows that contain a certain string, say, 'banana'. I don't know which column it will appear i...
3
2016-07-04T13:14:31Z
38,186,202
<p>With NumPy, it could be vectorized to search for as many strings as you wish, like so -</p> <pre><code>def select_rows(df,search_strings): unq,IDs = np.unique(df,return_inverse=True) unqIDs = np.searchsorted(unq,search_strings) return df[((IDs.reshape(df.shape) == unqIDs[:,None,None]).any(-1)).all(0)] <...
2
2016-07-04T13:41:05Z
[ "python", "pandas" ]
Select rows containing certain values from pandas dataframe
38,185,688
<p>I have a pandas dataframe whose entries are all strings:</p> <pre><code> A B C 1 apple banana pear 2 pear pear apple 3 banana pear pear 4 apple apple pear </code></pre> <p>etc. I want to select all the rows that contain a certain string, say, 'banana'. I don't know which column it will appear i...
3
2016-07-04T13:14:31Z
38,187,746
<p>For single search value </p> <pre><code>df[df.values == "banana"] </code></pre> <p>or </p> <pre><code> df[df.isin(['banana'])] </code></pre> <p>For multiple search terms: </p> <pre><code> df[(df.values == "banana")|(df.values == "apple" ) ] </code></pre> <p>or</p> <pre><code>df[df.isin(['banana', "apple"]...
1
2016-07-04T15:06:21Z
[ "python", "pandas" ]
the output of re.split in python doesn't make sense to me
38,185,696
<pre><code>print (re.split(r'[a-fA-F]','finqwenlaskdjriewasFSDFddsafsafasa',re.I|re.M)) print (re.split(r'[a-fA-Z]','finqwenlaskdjriewasFSDFddsafsafasa',re.I|re.M)) print (re.split(r'\d*','sdfsfdsfds123212fdsf2')) print (re.split(r'\d','sdfsfdsfds123212fdsf2')) print (re.split(r'\w+','dsfsf sdfdsf sdfsdf sfsfd')) ['',...
-1
2016-07-04T13:14:54Z
38,185,990
<blockquote> <p>The pattern that split the string are turned to <code>''</code> in the output list sometimes, but disappear other time.</p> </blockquote> <p>No, the pattern (or what it matched) is <strong>never</strong> included in your outputs there. Those <code>''</code> are what's <strong>between</strong> the mat...
3
2016-07-04T13:29:56Z
[ "python" ]
the output of re.split in python doesn't make sense to me
38,185,696
<pre><code>print (re.split(r'[a-fA-F]','finqwenlaskdjriewasFSDFddsafsafasa',re.I|re.M)) print (re.split(r'[a-fA-Z]','finqwenlaskdjriewasFSDFddsafsafasa',re.I|re.M)) print (re.split(r'\d*','sdfsfdsfds123212fdsf2')) print (re.split(r'\d','sdfsfdsfds123212fdsf2')) print (re.split(r'\w+','dsfsf sdfdsf sdfsdf sfsfd')) ['',...
-1
2016-07-04T13:14:54Z
38,185,992
<p>The output isn't weird, it's intentional. <a href="https://docs.python.org/3/library/re.html#re.split" rel="nofollow">From the docs</a>:</p> <blockquote> <p>If there are capturing groups in the separator and it matches at the start of the string, the result will start with an empty string. The same holds for the ...
0
2016-07-04T13:30:04Z
[ "python" ]
the output of re.split in python doesn't make sense to me
38,185,696
<pre><code>print (re.split(r'[a-fA-F]','finqwenlaskdjriewasFSDFddsafsafasa',re.I|re.M)) print (re.split(r'[a-fA-Z]','finqwenlaskdjriewasFSDFddsafsafasa',re.I|re.M)) print (re.split(r'\d*','sdfsfdsfds123212fdsf2')) print (re.split(r'\d','sdfsfdsfds123212fdsf2')) print (re.split(r'\w+','dsfsf sdfdsf sdfsdf sfsfd')) ['',...
-1
2016-07-04T13:14:54Z
38,186,769
<p>First of all, you're essentially providing the <em><code>maxsplit=10</code></em> argument instead of <code>flags=re.I|re.</code></p> <p>Secondly, the separators are <em>not</em> turned into <code>''</code>; instead that is the string <em>between</em> the separators:</p> <pre><code>&gt;&gt;&gt; re.split(r':', 'foo:...
1
2016-07-04T14:11:09Z
[ "python" ]
Python 2.7 Tkinter Code
38,185,801
<p>My Tkinter code is showing no problems but When I run it Nothing Shows Up. What is Wrong?</p> <p>I'M using Python 2.7. It's Supposed to be a pizzeria Game by the way </p> <p>Here is my code:</p> <pre><code>import Tkinter as tk from Tkinter import StringVar import ttk from random import randint , choice ,uniform ...
-3
2016-07-04T13:20:24Z
38,189,167
<p>This does nothing, since it just a reference to <code>mainloop</code> method of <code>Window</code> class</p> <pre><code>Window.mainloop </code></pre> <p>You need to create an instance of <code>Window</code> class before you call <code>mainloop</code></p> <pre><code>w = Window() w.mainloop() </code></pre>
0
2016-07-04T16:37:02Z
[ "python", "python-2.7", "tkinter", "tk" ]
What's the maximum size of a image to send using MQTT
38,185,812
<p>I'm trying to send some images using MQTT in two R-pi. I wonder what's the maximum size of image to send. I think 1MB is the maximum size however, 26.5KB image could not be sended. Please give an answer of my question thank you.</p>
1
2016-07-04T13:21:02Z
38,185,988
<p>MQTT doc Mosquito:</p> <p><strong>message_size_limit limit</strong></p> <blockquote> <p>This option sets the maximum publish payload size that the broker will allow. Received messages that exceed this size will not be accepted by the broker. The default value is 0, which means that all valid MQTT messages ...
2
2016-07-04T13:29:49Z
[ "python", "raspberry-pi", "mqtt", "mosquitto" ]
Django Form Wizard persistent initial data between steps
38,186,132
<p>I'm using <a href="https://django-formwizard.readthedocs.io/en/latest/" rel="nofollow">Django Form Wizard</a> in project. I want to allow users to provide initial data for specific field and I also want to make field with initial data provided disabled.</p> <blockquote> <p>Problem is that when user clicks back bu...
1
2016-07-04T13:37:36Z
38,187,845
<p>The way I was able to solve it was by removing extra fields for <code>ChoiceField</code> type objects.</p> <pre><code> for field in initial: try: field_o = form.fields[field] # Remove extra choices if Choice field if type(field_o) == forms.fields.ChoiceFie...
1
2016-07-04T15:11:12Z
[ "python", "django", "django-formwizard" ]
scrapy DEFAULT_REQUEST_HEADERS not work
38,186,221
<p>I change the default request headers in <code>settings.py</code> as below:</p> <pre><code>DEFAULT_REQUEST_HEADERS = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,applicati...
1
2016-07-04T13:42:10Z
38,186,702
<p>I see User-Agent header is indeed not set properly when using default headers middleware and this particular site refuses connections without some expected user-agent header. </p> <p>Recommended way to set user-agent for your crawler is by using USER_AGENT setting key:</p> <p>e.g. </p> <pre><code># settings.py US...
1
2016-07-04T14:07:37Z
[ "python", "scrapy" ]
simple-salesforce not recognizing custom object
38,186,262
<p>I am using simple_salesforce and get all records of a custom object called "SER__Condition__c". I know for a fact that that is the name because I got a list of table names from our administrator.<br> "api" is an instance of "simple_salesforce.Salesforce".<br> This is the command I'm executing:</p> <pre><code>pprint...
0
2016-07-04T13:44:30Z
38,277,573
<p>It probably is a permissions issue. Make sure the SER__Condition__c object is visible to the user you are running the query as.</p>
0
2016-07-09T02:04:46Z
[ "python", "python-3.x", "salesforce", "soql" ]
Python convert list of one element into string with bracket
38,186,365
<p>How to convert python list containing one element to string with bracket? For more than one element, its easy for me to just just use <code>tuple(list['a','b'])</code> which returns as tuple <code>('a','b')</code> but if element is one, it returns as <code>('a',)</code> but rather I want to return <code>('a')</code>...
1
2016-07-04T13:50:21Z
38,186,418
<p>Avoid relying on default <code>__repr__()</code> method, to format strings, they might change.</p> <p>Be explicit about your intent instead </p> <pre><code> print "('" + "', '".join(mylist) + "')" </code></pre>
3
2016-07-04T13:53:22Z
[ "python" ]
Python convert list of one element into string with bracket
38,186,365
<p>How to convert python list containing one element to string with bracket? For more than one element, its easy for me to just just use <code>tuple(list['a','b'])</code> which returns as tuple <code>('a','b')</code> but if element is one, it returns as <code>('a',)</code> but rather I want to return <code>('a')</code>...
1
2016-07-04T13:50:21Z
38,186,422
<pre><code>&gt;&gt;&gt; ('a') == 'a' True </code></pre> <p>If you're not going to use a single element tuple, then the parenthesis are only grouping parenthesis (not a container), and they won't <em>stick</em> like you want them to, except you include them as part of the string with <code>a</code> or define a custom p...
1
2016-07-04T13:53:28Z
[ "python" ]
Looping through a folder to merge several excel sheets into one column
38,186,374
<p>I have several workbooks, each with three sheets. I want to loop through each workbook and merge all the data from <code>sheet_1</code> into a new workbook_1 file, <code>sheet_2</code> into workbook_2 file &amp; <code>sheet_3</code> into workbook_3.</p> <p>As far as I can tell the script below does everything I nee...
2
2016-07-04T13:50:45Z
38,186,473
<p>You can also easilly append data like:</p> <pre><code>df = [] for f in ['c:\\file1.xls', 'c:\\ file2.xls']: data = pd.read_excel(f, 'Sheet1').iloc[:-2] data.index = [os.path.basename(f)] * len(data) df.append(data) df = pd.concat(df) </code></pre> <p>From: <a href="http://stackoverflow.com/questions/2...
0
2016-07-04T13:55:45Z
[ "python", "excel", "pandas", "merge", "glob" ]
Fibonacci sequence program in python working fine except for input 0
38,186,403
<p>This program is showing correct output except for input n=0.</p> <pre><code>def fib(n): f=list() i=0 while(i&lt;=n): f.append(i) i+=1 f[0]=0 f[1]=1 for i in range(2,n+1): f[i]=f[i-1]+f[i-2] i+=1 return f[n] n=int(input()) print(fib(n)) </code></pre> <p>wh...
-1
2016-07-04T13:52:24Z
38,186,493
<p>Two lines in the middle are not necessary due to you initializing those elements during while loop. And error comes from the fact, that for <code>n=0</code>, you were only adding one elemnt to list. And after that changing value of first and second element. There is no second element.</p> <pre><code>def fib(n): ...
1
2016-07-04T13:56:46Z
[ "python", "fibonacci" ]
Fibonacci sequence program in python working fine except for input 0
38,186,403
<p>This program is showing correct output except for input n=0.</p> <pre><code>def fib(n): f=list() i=0 while(i&lt;=n): f.append(i) i+=1 f[0]=0 f[1]=1 for i in range(2,n+1): f[i]=f[i-1]+f[i-2] i+=1 return f[n] n=int(input()) print(fib(n)) </code></pre> <p>wh...
-1
2016-07-04T13:52:24Z
38,186,571
<p>Either duck type it:</p> <pre><code>def fib(n): if n in [0, 1]: return n . . </code></pre> <p>Or change <code>f[0] = 0</code> and <code>f[1] = 1</code> to <code>f.append(0)</code> and <code>f.append(1)</code> respectively.</p>
0
2016-07-04T14:01:07Z
[ "python", "fibonacci" ]
Fibonacci sequence program in python working fine except for input 0
38,186,403
<p>This program is showing correct output except for input n=0.</p> <pre><code>def fib(n): f=list() i=0 while(i&lt;=n): f.append(i) i+=1 f[0]=0 f[1]=1 for i in range(2,n+1): f[i]=f[i-1]+f[i-2] i+=1 return f[n] n=int(input()) print(fib(n)) </code></pre> <p>wh...
-1
2016-07-04T13:52:24Z
38,186,642
<p>You don't need this two lines.</p> <pre><code>f[0]=0 f[1]=1 </code></pre> <p>Remove them and everything will work.</p>
0
2016-07-04T14:04:40Z
[ "python", "fibonacci" ]
Fibonacci sequence program in python working fine except for input 0
38,186,403
<p>This program is showing correct output except for input n=0.</p> <pre><code>def fib(n): f=list() i=0 while(i&lt;=n): f.append(i) i+=1 f[0]=0 f[1]=1 for i in range(2,n+1): f[i]=f[i-1]+f[i-2] i+=1 return f[n] n=int(input()) print(fib(n)) </code></pre> <p>wh...
-1
2016-07-04T13:52:24Z
38,186,645
<p>Corrections to your code:</p> <pre><code>def fib(n): f=list() i=0 while(i&lt;=n): f.append(i) i+=1 # HERE WAS THE MISTAKE f.append(0) f.append(1) for i in range(2,n+1): f[i]=f[i-1]+f[i-2] i+=1 return f[n] </code></pre> <p>Outputs:</p> <pre><code>&gt;...
0
2016-07-04T14:04:57Z
[ "python", "fibonacci" ]
Fibonacci sequence program in python working fine except for input 0
38,186,403
<p>This program is showing correct output except for input n=0.</p> <pre><code>def fib(n): f=list() i=0 while(i&lt;=n): f.append(i) i+=1 f[0]=0 f[1]=1 for i in range(2,n+1): f[i]=f[i-1]+f[i-2] i+=1 return f[n] n=int(input()) print(fib(n)) </code></pre> <p>wh...
-1
2016-07-04T13:52:24Z
38,186,676
<p>The problem in your code was that the loop did not create the item indexed 1, so after the loop you were able to change this item because it did not exist. I would suggest "hardcode" 0 and 1 at the beginning, then using a recursion to define fibonacci function</p> <pre><code>def fib(n): if 0&lt;=n&lt;2: return ...
0
2016-07-04T14:06:23Z
[ "python", "fibonacci" ]
Able to run Pytest from PyCharm but not through Command Line
38,186,505
<p>I am trying this on Ubuntu. So when I run PyTest from PyCharm it worked perfectly but when I tried to run the same command I am getting different errors. Surely I am not building my Command correctly.</p> <p>So here is what it looks like in PyCharm</p> <pre><code>target = /some_path/test_xxx.py options= --serv...
0
2016-07-04T13:57:30Z
38,189,005
<p>yeah I think PyTest don't have a server argument. probably it`s missing some plugin</p> <p>you can see the args list by typing</p> <pre><code>py.test --help </code></pre> <p>check it out the plugin list <a href="https://pytest.org/dev/plugins_index/index.html" rel="nofollow">https://pytest.org/dev/plugins_index/...
0
2016-07-04T16:25:32Z
[ "python", "pycharm", "py.test" ]
python padding decimals with zeros
38,186,526
<p>I'm looking for a way to pad the float decimals with zeros:</p> <p>This one is my reference:</p> <pre><code>In [37]: '{:5.5}'.format(round(4.123456, 5)) Out[37]: '4.1235' </code></pre> <p>I have this: </p> <pre><code>In [38]: '{:5.5}'.format(4.1) Out[38]: ' 4.1' </code></pre> <p>But I would like to have this...
-3
2016-07-04T13:58:56Z
38,186,593
<pre><code> '{:5.5f}'.format(4.1) </code></pre> <p>The f in the format string makes the difference here. You can read more about the formatters in <a href="https://docs.python.org/2/library/string.html#format-specification-mini-language" rel="nofollow">here</a>, important for this task is </p> <blockquote> <p>'f' ...
1
2016-07-04T14:01:54Z
[ "python", "format" ]
python padding decimals with zeros
38,186,526
<p>I'm looking for a way to pad the float decimals with zeros:</p> <p>This one is my reference:</p> <pre><code>In [37]: '{:5.5}'.format(round(4.123456, 5)) Out[37]: '4.1235' </code></pre> <p>I have this: </p> <pre><code>In [38]: '{:5.5}'.format(4.1) Out[38]: ' 4.1' </code></pre> <p>But I would like to have this...
-3
2016-07-04T13:58:56Z
38,186,610
<p>For formatting floating point numbers you should use the <code>"f"</code> <a href="https://docs.python.org/3.5/library/string.html#format-specification-mini-language" rel="nofollow">specifier</a>:</p> <pre><code>&gt;&gt;&gt; '{:f}'.format(4.1) '4.100000' </code></pre> <p>Now <code>":5.5f"</code> uses 5 decimal pla...
1
2016-07-04T14:02:42Z
[ "python", "format" ]
python padding decimals with zeros
38,186,526
<p>I'm looking for a way to pad the float decimals with zeros:</p> <p>This one is my reference:</p> <pre><code>In [37]: '{:5.5}'.format(round(4.123456, 5)) Out[37]: '4.1235' </code></pre> <p>I have this: </p> <pre><code>In [38]: '{:5.5}'.format(4.1) Out[38]: ' 4.1' </code></pre> <p>But I would like to have this...
-3
2016-07-04T13:58:56Z
38,186,665
<pre><code>'{:5.5f}'.format(4.1) </code></pre> <p><a href="http://www.pyformat.info" rel="nofollow">pyformat.info</a></p>
1
2016-07-04T14:05:53Z
[ "python", "format" ]
File cannot be found using open()
38,186,527
<p>The code is not finding the notepad document, please help</p> <pre><code>SEND_REPORT_TUPLE = ('wet', 'water', 'liquid') #make a list from the input input_list = answer.split(" ") #And then the use any function with comprehension list if any(e in SEND_REPORT_TUPLE for e in input_list): file = open('Notepad', 'r'...
-5
2016-07-04T13:58:59Z
38,188,337
<p>Make sure that your file is in the same directory as your python script or put a full path to it. You should also put the file extension in the name</p> <p>i.e.</p> <p>file = open('Notepad.txt', 'r')</p>
1
2016-07-04T15:39:22Z
[ "python", "file" ]
How do I get the largest 2d slice of a numpy array?
38,186,630
<p>I have a 3d numpy array where the dimensions are different. I would like to plot a slice parallel to the largest 2 dimensions and midway through the smallest. How do I get the slice?</p> <p>e.g. if my original data is </p> <pre><code>np.ones(3*4*5).reshape(3,4,5) </code></pre> <p>I would like to get the dataset</...
1
2016-07-04T14:04:04Z
38,186,997
<p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html" rel="nofollow"><code>np.rollaxis</code></a> for such a task and that would work for any multi-dimensional ndarray, like so -</p> <pre><code>def ndim_largest_slice(arr): shp = arr.shape return np.rollaxis(arr, np....
1
2016-07-04T14:23:49Z
[ "python", "numpy" ]
django modelformset_factory POST request data retrieval
38,186,657
<p>I currently got django 1.9 and I found out modelformset_factory very useful as I can setup forms without major afford.</p> <p>Now I came to realise upon submitting the form (POST method)I need to figure out which objects I have added and removed .</p> <p>This is the view I got :</p> <pre><code>def def_accounts(re...
-1
2016-07-04T14:05:29Z
38,188,308
<p>When you <a href="https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#saving-objects-in-the-formset" rel="nofollow">save a model formset</a> by calling <code>formset.save()</code>, you get three attributes <code>formset.changed_objects</code>, <code>formset_deleted_objects</code> and <code>formset.new_obj...
0
2016-07-04T15:37:19Z
[ "python", "django" ]
Advanced URLs in Django
38,186,663
<p>The task is to write two url patterns.</p> <p>The first one will take a single argument <code>&lt;path&gt;</code>, which can be any url with random depth:</p> <p><code>test/dorogi/</code></p> <p>or</p> <p><code>test/foo/bar/as/deep/as/you/want</code></p> <p>The second one will be the same as the first one, but ...
0
2016-07-04T14:05:45Z
38,186,779
<p>Just add the second parameter to the regex for the first pattern:</p> <pre><code>r'^(?P&lt;path&gt;.*)/(?P&lt;pk&gt;\d+)/$' </code></pre> <p>But make sure to put that <em>before</em> the first one in your list of URLs.</p> <p>(Note that you should definitely terminate your pattern with a $, as I did above.)</p>
1
2016-07-04T14:11:42Z
[ "python", "django", "url", "django-urls", "django-mptt" ]
Create Pandas Time Serie from multiple Time Series with Python
38,186,797
<p>I have multiple Time Series like this :</p> <pre><code>DATE 2015-10-10 01:00:00 955.0 2015-10-11 01:00:00 702.0 2015-10-12 01:00:00 597.0 2015-10-13 01:00:00 516.0 2015-10-14 01:00:00 554.0 DATE 2015-10-10 02:00:00 972.0 2015-10-11 02:00:00 646.0 2015-10-12 02:00:00 529.0 2015-10-13 02:00:0...
1
2016-07-04T14:12:30Z
38,186,950
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> to concatenate row-wise and call <code>sort_index()</code> on the result to achieve the result you want:</p> <pre><code>pd.concat(list_of_series).sort_index() </code></pre>
1
2016-07-04T14:20:40Z
[ "python", "pandas", "time-series" ]
How can you plot two lists of different 'first dimension' using matplotlib?
38,186,810
<p>I am trying to write some code that plots a graph whilst going through a for loop and updates the graph with each iteration using matplotlib. I am plotting the voltage_trim[0:index] in order to avoid the problem of having two lists of different size but I still get an error that x and y must have same first dimensio...
0
2016-07-04T14:12:56Z
38,188,897
<p>Your idea of trimming the x values is good. To make it work use <code>voltage_trim[:index+1]</code>.</p> <p>The index you get from enumerate starts at zero, but for the first returned element you want to already select one x value. Therefore you need to get all the values up to index+1.</p>
0
2016-07-04T16:17:09Z
[ "python", "matplotlib" ]
Appending more datasets into an existing Hdf5 file without deleting other groups and datasets
38,186,816
<p>I have an HDF5 file which contains groups and subgroups inside which there are datasets. I want to open the file and add some datasets to the groups. I took the following approach which is quite simple in python. </p> <pre><code> import h5py f = h5py.File('filename.h5','w') f.create_dataset('/Group1/subg...
0
2016-07-04T14:13:11Z
38,189,251
<p>Just like with the Python open() function, 'w' will truncate any existing file. Use the 'a' mode to add content to the file:</p> <pre><code>import h5py f = h5py.File('filename.h5','a') f.create_dataset('/Group1/subgroup1/dataset4', data=pngfile) f.close() </code></pre>
0
2016-07-04T16:43:10Z
[ "python", "dataset", "hdf5", "groups", "h5py" ]
Python line.replace returns UnicodeEncodeError
38,186,847
<p>I have a tex file that was generated from rst source using Sphinx, it is encoded as UTF-8 without BOM (according to Notepad++) and named <code>final_report.tex</code>, with following content: </p> <pre class="lang-latex prettyprint-override"><code>% Generated by Sphinx. \documentclass[letterpaper,11pt,english]{sphi...
2
2016-07-04T14:14:54Z
38,186,887
<p>You need to specify the correct encoding with the <code>encoding="the_encoding"</code>:</p> <pre><code>with open(oldFil, "rt", encoding="utf-8") as fin, open(newFil, "wt", encoding="utf-8") as fout: </code></pre> <p>If you don't the preferred encoding will be used.</p> <p><a href="https://docs.python.org/3/libra...
2
2016-07-04T14:17:00Z
[ "python", "python-unicode" ]
Decoding UTF-8 to URL with Python
38,186,925
<p>I have the following url encoded in utf-8.</p> <pre><code>url_input = u'https://www.gumtree.com//p/uk-holiday-rentals/1bedroon-flat-\xa3250pw-all-bills-included-/1174092955' </code></pre> <p>I need to scrap this webpage and to do so I need to have the following url_output (unicode is not read).</p> <pre><code>url...
2
2016-07-04T14:19:10Z
38,187,316
<p>When you print <code>url_input</code> you get the desired <code>url_output</code> only because your terminal understand UTF-8 and can represents <code>\xa3</code> correctly.</p> <p>You can encode the string in ASCII with <code>str.encode</code>, but you have to replace (with a <code>?</code>) or ignore the chars th...
1
2016-07-04T14:41:21Z
[ "python", "encoding", "utf-8" ]
Decoding UTF-8 to URL with Python
38,186,925
<p>I have the following url encoded in utf-8.</p> <pre><code>url_input = u'https://www.gumtree.com//p/uk-holiday-rentals/1bedroon-flat-\xa3250pw-all-bills-included-/1174092955' </code></pre> <p>I need to scrap this webpage and to do so I need to have the following url_output (unicode is not read).</p> <pre><code>url...
2
2016-07-04T14:19:10Z
38,188,417
<p>After some tests, I can confirm that the server accepts the URL in different formats:</p> <ul> <li><p>raw utf8 encoded URL:</p> <pre><code>url_output = url_input.encode('utf8') </code></pre></li> <li><p>%encoded latin1 URL</p> <pre><code>url_output = urllib.quote_plus(url_input.encode('latin1'), '/:') </code></pr...
1
2016-07-04T15:44:22Z
[ "python", "encoding", "utf-8" ]
Arithmetic accuracy issues while testing for intersection of two line segments
38,186,936
<p>I wrote a code testing for the intersection of two line segments in the plane. I won't bother you with all the details. </p> <p>The code takes two line segments, each described by two end-points, then fits each segment to a line by fitting the <code>a</code> and <code>b</code> in <code>y = a*x + b</code>. Then it f...
1
2016-07-04T14:19:36Z
38,187,066
<p>This is a problem/feature of floating point arithmetic. There are ways to minimise the error, by ordering instructions certain ways, but in the end, you will get approximate answers, because you're representing possibly infinite numbers with a finite number of bits.</p> <p>You need to define whatever functions you ...
5
2016-07-04T14:27:28Z
[ "python", "floating-point", "precision" ]
Why is the class passed to a function being called inside a class function when using self in Python?
38,186,953
<p>So, I have this code snippet.</p> <pre><code>class LogObserver(object): def write_log(...): self.logger.log(self, level, message, *args, **kwargs) ... </code></pre> <p>Looking into the debugger and the error messages as well, I noticed that the variable <code>level</code> contains <code>LogObserver</c...
0
2016-07-04T14:20:46Z
38,187,023
<p>If you call an instance method (<em>not</em> staticmethod or classmethod), the instance is implicitly passed as the first parameter. That is why method definitions take <code>self</code> as the first parameter; the name <code>self</code> is just a convention, by the way. For example, <code>foo.bar()</code> will be t...
3
2016-07-04T14:25:01Z
[ "python", "python-3.x" ]
import Python plugins from a folder
38,187,037
<p>I want to put a python script with module script PIL on a server. The server might not have PIL installed. (This is why I want to load the file myself)</p> <p>If possible, how can I have the python script import Image Library from the current directory of the script without having it installed on the machine?</p> ...
2
2016-07-04T14:25:46Z
38,187,179
<p>One option is to import modules from a relative path as described <a href="http://stackoverflow.com/questions/279237/import-a-module-from-a-relative-path">here</a>.</p> <p>It is also possible to use virtual environments where you pack everything you need and don´t mess with python installations on the server. Look...
3
2016-07-04T14:33:57Z
[ "python", "import", "python-imaging-library" ]
How Do I Keep Total Time with Multiple Duplicate Entries?
38,187,040
<p>I will attach my code, but basically I am importing a csv file with start times/end times for picking cases of a particular item. All the cases go to a "cart", which is identified by an ID number. I want to find the total time to pick all the cases. The format of the time is hh:mm:ss and, initially, I was using the ...
1
2016-07-04T14:25:58Z
38,190,330
<p>There is an obvious problem in this section:</p> <pre><code>duration = end - start if duration &gt;= 0: duration = duration elif duration &lt; 0: duration = -1*duration </code></pre> <p>If your start point is 22:00:00 and end point is 21:00:00 your duration will be 1 hour instead of 23 hours.</p>
0
2016-07-04T18:16:13Z
[ "python" ]
Kivy/Python rotates the display (test,buttons, pictures). Test programs that worked, are now rotated
38,187,041
<p>I am learning Python &amp; Kivy: (Life was a lot easier using assembly for embedded controllers).<br> Now the whole display is rotated 90 degrees CCW. Demo programs that used to work are now displayed rotated. Presumably I did something that set a permanent "rotate display" flag while running Python. Where and how...
0
2016-07-04T14:26:05Z
38,187,111
<p>I ran into this problem a while back when I was learning Kivy. I even left a frustrated comment on <a href="https://www.youtube.com/watch?v=oQdGWeN51EE" rel="nofollow">a youtube video</a>.</p> <p>There's a file at <code>c:\users\[username]\.kivy\config.ini</code> which you need to modify or delete.</p>
1
2016-07-04T14:29:48Z
[ "python", "rotation", "kivy" ]
how to use If to compare a number with an interval in python?
38,187,112
<p>When I compile the Python code below, I do not have any output! my .csv file include numbers. like (80,100,50,40,250,300).</p> <pre><code>import csv with open("duration.csv") as f: d1 = [row[0] for row in csv.reader(f)] for x in d1: if 0&lt;= x &lt;200: print("0&lt;=x&lt;200") </code></pre> <p>any solution??...
-4
2016-07-04T14:29:50Z
38,187,166
<p>By default, csv.reader() reads all values as string. You have to type cast them.</p> <pre><code>import csv with open("duration.csv") as f: d1 = [float(row[0]) for row in csv.reader(f)] </code></pre>
1
2016-07-04T14:33:20Z
[ "python" ]
how to use If to compare a number with an interval in python?
38,187,112
<p>When I compile the Python code below, I do not have any output! my .csv file include numbers. like (80,100,50,40,250,300).</p> <pre><code>import csv with open("duration.csv") as f: d1 = [row[0] for row in csv.reader(f)] for x in d1: if 0&lt;= x &lt;200: print("0&lt;=x&lt;200") </code></pre> <p>any solution??...
-4
2016-07-04T14:29:50Z
38,187,172
<p>The values from your rows are read as strings by the <code>csv</code> module. You should convert <code>x</code> to integer and then apply some formatting:</p> <pre><code>if 0 &lt;= int(x) &lt; 200: print("0&lt;={}&lt;200".format(x)) </code></pre>
0
2016-07-04T14:33:36Z
[ "python" ]
Plotting a curve from numpy array with large values
38,187,133
<p>I am trying to plot a curve from molecular dynamics potential energies data stored in numpy array. As you can see from my figure attached, on the top left of the figure, a large number appears which is related to the label on y-axis. Look at it. <a href="http://i.stack.imgur.com/U6ZsW.png" rel="nofollow"><img src="h...
1
2016-07-04T14:30:58Z
38,187,469
<p>It seems your data is displayed in exponential form like: 1e+10, 2e+10, etc. This question here might help:</p> <p><a href="http://stackoverflow.com/questions/14711655/how-to-prevent-numbers-being-changed-to-exponential-form-in-python-matplotlib-fi">How to prevent numbers being changed to exponential form in Python...
-1
2016-07-04T14:50:56Z
[ "python", "arrays", "matplotlib" ]
Plotting a curve from numpy array with large values
38,187,133
<p>I am trying to plot a curve from molecular dynamics potential energies data stored in numpy array. As you can see from my figure attached, on the top left of the figure, a large number appears which is related to the label on y-axis. Look at it. <a href="http://i.stack.imgur.com/U6ZsW.png" rel="nofollow"><img src="h...
1
2016-07-04T14:30:58Z
38,188,316
<p>This is likely happening because your data is a small value offset by a large one. That's what the <code>-</code> sign means at the front of the number, "take the plotted y-values and subtract this number to get the actual values". You can remove it by plotting with the mean subtracted. Here's an example:</p> <p...
1
2016-07-04T15:37:51Z
[ "python", "arrays", "matplotlib" ]
Plotting a curve from numpy array with large values
38,187,133
<p>I am trying to plot a curve from molecular dynamics potential energies data stored in numpy array. As you can see from my figure attached, on the top left of the figure, a large number appears which is related to the label on y-axis. Look at it. <a href="http://i.stack.imgur.com/U6ZsW.png" rel="nofollow"><img src="h...
1
2016-07-04T14:30:58Z
38,189,338
<p>You can remove the offset by using:</p> <pre><code>plt.ticklabel_format(useOffset=False) </code></pre>
0
2016-07-04T16:51:37Z
[ "python", "arrays", "matplotlib" ]
Python BeautifulSoup can't select specific tag
38,187,213
<p>My problem is when parsing a website and then loading the data tree with BS. How can I look for the content of an <code>&lt;em&gt;</code> Tag? I tried </p> <pre><code>for first in soup.find_all("li", class_="li-in"): print first.select("em.fl.in-date").string #or print first.select("em....
-3
2016-07-04T14:35:07Z
38,187,312
<pre><code> first.select("em.fl.in-date").text </code></pre> <p>Assuming your selector is correct. You didn't provide which URL you're scraping, so I can't be sure.</p> <pre><code>&gt;&gt;&gt; url = "http://stackoverflow.com/questions/38187213/python-beautifulsoup" &gt;&gt;&gt; from bs4 import BeautifulSoup &gt;&gt;...
-1
2016-07-04T14:41:11Z
[ "python", "beautifulsoup" ]
Stripping multiple characters from the start of a string
38,187,220
<p>I'm trying to trim a sub-string from the beginning of a string based on a condition:</p> <p>For instance, if the input is a domain name prefixed with <em>http</em>, <em>https</em> and/or <em>www</em>, it needs to strip these and return only the domain.</p> <p>Here's what I have so far:</p> <pre><code>if my_domain...
0
2016-07-04T14:35:24Z
38,187,300
<p>I know regex is computationally slower than a lot of the built in methods but it is a lot easier to write code wise :)</p> <pre><code>import re re.sub("http[s]*://|www\." , "", my_domain) </code></pre> <p>edit: As mentioned by @Dunes a more correct way of answering this problem is. </p> <pre><code>re.sub(r"^https...
2
2016-07-04T14:40:04Z
[ "python", "python-2.7", "if-statement", "conditional" ]
Stripping multiple characters from the start of a string
38,187,220
<p>I'm trying to trim a sub-string from the beginning of a string based on a condition:</p> <p>For instance, if the input is a domain name prefixed with <em>http</em>, <em>https</em> and/or <em>www</em>, it needs to strip these and return only the domain.</p> <p>Here's what I have so far:</p> <pre><code>if my_domain...
0
2016-07-04T14:35:24Z
38,189,064
<p>Use <a href="https://docs.python.org/3.5/library/urllib.parse.html#urllib.parse.urlsplit" rel="nofollow"><code>urllib.parse</code></a> (Python 3). </p> <pre><code>&gt;&gt;&gt; from urllib import parse &gt;&gt;&gt; components = parse.urlsplit('http://stackoverflow.com/questions/38187220/stripping-multiple-characters...
0
2016-07-04T16:30:23Z
[ "python", "python-2.7", "if-statement", "conditional" ]
Get Python stack trace while using cx_freeze
38,187,235
<p>I have a data acquisition program written in Python that I distribute to my collaboration as an executable (using <a href="http://cx-freeze.sourceforge.net/" rel="nofollow">cx_freeze</a>), as I don't want to bother them with installing Python and installing all the software dependencies. The program has been working...
2
2016-07-04T14:36:02Z
38,188,492
<p>I learned that I could use <code>procdump</code>. It can be downloaded from <a href="https://technet.microsoft.com/en-us/sysinternals/dd996900.aspx?f=255&amp;MSPPError=-2147217396" rel="nofollow">here</a>. It's a very simple program that can log stack trace. You can use it with:</p> <pre><code>C:\&gt;procdump -ma -...
0
2016-07-04T15:49:19Z
[ "python", "python-3.4", "stack-trace", "cx-freeze", "faulthandler" ]
discriminate basic and advanced slicing of numpy array
38,187,280
<p>I'm reading the doc about <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow">numpy array indexing</a>, but still unclear about how to discriminate basic and advanced slicing.</p> <p>Thanks if someone could explain a bit.</p> <blockquote> <p><code>x[(1,2,3),]...
3
2016-07-04T14:38:18Z
38,189,353
<p>Start with a simple 1d array:</p> <pre><code>In [326]: x=np.arange(10) </code></pre> <p>These 2 expressions do the same thing - select 3 elements from the array. I could also verify that they return a copy, where as <code>x[1:4]</code> returns a view. </p> <pre><code>In [327]: x[(1,2,3),] Out[327]: array([1, 2,...
3
2016-07-04T16:52:50Z
[ "python", "arrays", "numpy" ]
Find unique pairs in list of pairs
38,187,286
<p>I have a (large) list of lists of integers, e.g.,</p> <pre><code>a = [ [1, 2], [3, 6], [2, 1], [3, 5], [3, 6] ] </code></pre> <p>Most of the pairs will appear twice, where the order of the integers doesn't matter (i.e., <code>[1, 2]</code> is equivalent to <code>[2, 1]</code>). I'd now li...
12
2016-07-04T14:38:41Z
38,187,443
<pre><code>ctr = Counter(frozenset(x) for x in a) b = [ctr[frozenset(x)] == 1 for x in a] </code></pre> <p>We can use Counter to get counts of each list (turn list to frozenset to ignore order) and then for each list check if it only appears once.</p>
13
2016-07-04T14:48:59Z
[ "python", "list" ]
Find unique pairs in list of pairs
38,187,286
<p>I have a (large) list of lists of integers, e.g.,</p> <pre><code>a = [ [1, 2], [3, 6], [2, 1], [3, 5], [3, 6] ] </code></pre> <p>Most of the pairs will appear twice, where the order of the integers doesn't matter (i.e., <code>[1, 2]</code> is equivalent to <code>[2, 1]</code>). I'd now li...
12
2016-07-04T14:38:41Z
38,187,459
<p>You could scan the list from start to end, while maintaining a <code>map</code> of encountered pairs to their first position. Whenever you process a pair, you check to see if you've encountered it before. If that's the case, both the first encounter's index in b and the current encounter's index must be set to False...
2
2016-07-04T14:49:38Z
[ "python", "list" ]
Find unique pairs in list of pairs
38,187,286
<p>I have a (large) list of lists of integers, e.g.,</p> <pre><code>a = [ [1, 2], [3, 6], [2, 1], [3, 5], [3, 6] ] </code></pre> <p>Most of the pairs will appear twice, where the order of the integers doesn't matter (i.e., <code>[1, 2]</code> is equivalent to <code>[2, 1]</code>). I'd now li...
12
2016-07-04T14:38:41Z
38,187,507
<pre><code>#-*- coding : utf-8 -*- a = [[1, 2], [3, 6], [2, 1], [3, 5], [3, 6]] result = filter(lambda el:(a.count([el[0],el[1]]) + a.count([el[1],el[0]]) == 1),a) bool_res = [ (a.count([el[0],el[1]]) + a.count([el[1],el[0]]) == 1) for el in a] print result print bool_res </code></pre> <p>wich gives : </p> <pre><code...
2
2016-07-04T14:52:57Z
[ "python", "list" ]
Find unique pairs in list of pairs
38,187,286
<p>I have a (large) list of lists of integers, e.g.,</p> <pre><code>a = [ [1, 2], [3, 6], [2, 1], [3, 5], [3, 6] ] </code></pre> <p>Most of the pairs will appear twice, where the order of the integers doesn't matter (i.e., <code>[1, 2]</code> is equivalent to <code>[2, 1]</code>). I'd now li...
12
2016-07-04T14:38:41Z
38,191,360
<p>Here's a numpythonic solution:</p> <pre><code>a = numpy.array(a) a.sort(axis=1) b = numpy.ascontiguousarray(a).view( numpy.dtype((numpy.void, a.dtype.itemsize * a.shape[1])) ) _, inv, ct = numpy.unique(b, return_inverse=True, return_counts=True) print(ct[inv] == 1) </code></pre> <ul> <li><p>Sorti...
3
2016-07-04T19:44:44Z
[ "python", "list" ]
Find unique pairs in list of pairs
38,187,286
<p>I have a (large) list of lists of integers, e.g.,</p> <pre><code>a = [ [1, 2], [3, 6], [2, 1], [3, 5], [3, 6] ] </code></pre> <p>Most of the pairs will appear twice, where the order of the integers doesn't matter (i.e., <code>[1, 2]</code> is equivalent to <code>[2, 1]</code>). I'd now li...
12
2016-07-04T14:38:41Z
38,286,942
<p>Use a dictionary for an O(n) solution.</p> <pre><code>a = [ [1, 2], [3, 6], [2, 1], [3, 5], [3, 6] ] dict = {} boolList = [] # Iterate through a for i in range (len(a)): # Assume that this element is not a duplicate # This 'True' is added to the corresponding index i of boolList boolList += [True] ...
-1
2016-07-09T22:38:55Z
[ "python", "list" ]
Run script from main script in spyder-project
38,187,330
<p>I have a spyder-project with two scripts: "mainScript.py" and "subScript.py". How can I run "subScript.py" from "mainScript.py" to do some thing with current workspace-variables? What kind of command i must to use?</p>
0
2016-07-04T14:42:04Z
38,197,809
<p>You should be able to call <code>subScript.py</code> from within the <code>mainScript.py</code> like you would call another file from a library. But it would definitely be easier if the contents of `subScript.py' is within some function.</p> <p>e.g. if your setup is:</p> <pre><code>Project File - mainScript.py - s...
0
2016-07-05T07:39:42Z
[ "python", "spyder" ]