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
Append dataframes in pandas
39,352,725
<p>I have two dataframes in pandas (copy from Spyder Variable Explorer)</p> <p>df1</p> <pre><code>index 0 1 2 3 4 5 6 0 Loc 0.0 0.0 0.0 0.25 0.0 light 1 Loc 0.0 0.0 0.0 0.25 0.0 light 2 Loc 0.0 0.0 0.0 0.25 0.0 light 3 Loc 0.0 0.0 0.0 0.25 0.0 light </code></...
1
2016-09-06T15:27:11Z
39,353,187
<p><strong>Disclaimer</strong>: I do not have 50 rep points to comment. So this answer is just a comment as <a href="http://stackoverflow.com/users/704848/edchum">EdChum</a> has given the correct answer.</p> <p>You should take a look at the documentation of the various types of concat, merge and join <a href="http://p...
1
2016-09-06T15:54:48Z
[ "python", "pandas", "formatting" ]
xlwings import error in python 2.7: Can't import name Workbook
39,352,768
<p>(I know there is an original question regarding this issue but it differs a bit by having command run in home directory. Also no specific solution is mentioned)</p> <p>I am using Anaconda2 python 2.7 (64bit) distribution. I have installed xlwings (version 0.9.3) on it using </p> <pre><code>pip install xlwings </c...
0
2016-09-06T15:29:52Z
39,354,167
<p><code>Workbook</code> has been renamed into <code>Book</code> with the 0.9 release, see the <a href="http://docs.xlwings.org/en/stable/migrate_to_0.9.html#cheat-sheet" rel="nofollow">migration guide</a>, follow the <a href="http://docs.xlwings.org/en/stable/quickstart.html" rel="nofollow">quickstart</a> or simply lo...
1
2016-09-06T16:53:12Z
[ "python", "python-2.7", "xlwings" ]
Lines to separate groups in seaborn heatmap
39,352,932
<p>I am plotting data as a Seaborn heatmap in Python. My data is intrinsically grouped into categories, and I'd like to have lines on the plot to indicate where the groups lie on the map. As a simple example, suppose I wanted to modify this plot from the documentation...</p> <pre><code>import seaborn as sns; sns.set()...
1
2016-09-06T15:39:44Z
39,353,190
<p>You want <code>ax.hlines</code>:</p> <p><code>ax.hlines([3, 6, 9], *ax.get_xlim()) </code></p>
4
2016-09-06T15:54:57Z
[ "python", "matplotlib", "heatmap", "seaborn" ]
Return list element by the value of one of its attributes
39,352,979
<p>There is a list of objects</p> <pre><code>l = [obj1, obj2, obj3] </code></pre> <p>Each <code>obj</code> is an object of a class and has an <code>id</code> attribute. </p> <p>How can I return an <code>obj</code> from the list by its <code>id</code>?</p> <p>P.S. <code>id</code>s are unique. and it is guaranteed th...
2
2016-09-06T15:42:13Z
39,353,030
<p>Assuming the <code>id</code> is a hashable object, like a string, you should be using a dictionary, not a list.</p> <pre><code>l = [obj1, obj2, obj3] d = {o.id:o for o in l} </code></pre> <p>You can then retrieve objects with their keys, e.g. <code>d['ID_39A']</code>.</p>
9
2016-09-06T15:45:30Z
[ "python", "python-3.x" ]
Pie and bar charts in Python
39,353,072
<p>I have a pandas dataframe like below:</p> <pre><code>Group id Count G1 412 52 G1 413 34 G2 412 2832 G2 413 314 </code></pre> <p>I am trying to build a pie chart in Python – for each Group and id, I need to display the respective count. It should have two splits - one for...
2
2016-09-06T15:47:49Z
39,355,610
<p>Have you checked out <a href="https://plot.ly/python/getting-started/" rel="nofollow">plotly</a>?</p> <p>Pie Chart Specific: <a href="https://plot.ly/python/pie-charts/#pie-chart-using-pie-object" rel="nofollow">Pie Charts with Plotly</a></p> <p>I will say you <em>do</em> have to make an account but its free and e...
1
2016-09-06T18:28:57Z
[ "python", "pandas", "visualization" ]
Pie and bar charts in Python
39,353,072
<p>I have a pandas dataframe like below:</p> <pre><code>Group id Count G1 412 52 G1 413 34 G2 412 2832 G2 413 314 </code></pre> <p>I am trying to build a pie chart in Python – for each Group and id, I need to display the respective count. It should have two splits - one for...
2
2016-09-06T15:47:49Z
39,355,803
<p>Panda also integrates with matplotlib, which is somewhat ugly but very convient. <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#pie-plot" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/visualization.html#pie-plot</a></p> <p>Some complicated examples <a href="http://stackoverflow...
1
2016-09-06T18:41:43Z
[ "python", "pandas", "visualization" ]
Pie and bar charts in Python
39,353,072
<p>I have a pandas dataframe like below:</p> <pre><code>Group id Count G1 412 52 G1 413 34 G2 412 2832 G2 413 314 </code></pre> <p>I am trying to build a pie chart in Python – for each Group and id, I need to display the respective count. It should have two splits - one for...
2
2016-09-06T15:47:49Z
39,358,505
<p>Tried to comment to agree with MattR - Plotly is great! I've got a few tutorials for how to use it on my website, you can PM me if you'd like a look.</p>
0
2016-09-06T22:02:22Z
[ "python", "pandas", "visualization" ]
Different results with thread in Python 2/3
39,353,181
<p>Below is the code in Python 3. It always can get 100000. Why it is wrong? I think it should have different results.</p> <pre><code>import time, _thread global count count = 0 def test(): global count for i in range(0, 10000): count += 1 for i in range(0, 10): _thread.start_new_thread(test, ()...
4
2016-09-06T15:54:18Z
39,353,531
<p>CPython 2 allowed threads to switch after a certain number of byte codes had executed; CPython 3.2 changed to allow threads to switch after a certain amount of time has passed. Your <code>test()</code> executes plenty of byte codes, but consumes little time. On my box, under Python 3 the displayed result becomes u...
5
2016-09-06T16:14:47Z
[ "python", "python-3.x", "python-2.x" ]
Trouble downloading xlsx file from website - Scraping
39,353,191
<p>I'm trying to write some code which download the two latest publications of the Outage Weeks found at the bottom of <a href="http://www.eirgridgroup.com/customer-and-industry/general-customer-information/outage-information/" rel="nofollow">http://www.eirgridgroup.com/customer-and-industry/general-customer-informati...
1
2016-09-06T15:55:05Z
39,353,663
<p>Just use <em>contains</em> to find the <em>hrefs</em> and slice the first two:</p> <pre><code> tree.xpath('//p/a[contains(@href, "/site-files/library/EirGrid/Outage-Weeks")]/@href')[:2] </code></pre> <p>Or doing it all with the xpath using <code>[position() &lt; 3]</code>:</p> <pre><code>tree.xpath'(//p/a[contain...
0
2016-09-06T16:22:52Z
[ "python", "vba", "xpath", "import", "web-scraping" ]
Selenium webdriver unable to restart after unexpected exit
39,353,210
<p>I haven't been able to start up an instance of python's selenium webdriver after my last use a few days ago. According to the error messages, it unexpectedly quit last time I was using it, and now, after restarting my macbook, uninstalling and reinstalling chromedriver/selenium:<br><br> <code>brew rmtree chromedrive...
0
2016-09-06T15:55:58Z
39,473,114
<p>I discovered that homebrew chromedriver was throwing an error related to symlinking the correct dylib. I fixed the issue by following the steps in <a href="http://stackoverflow.com/questions/17643509/conflict-between-dynamic-linking-priority-in-osx#answer-35070568">this</a> answer to get chromedriver running again, ...
0
2016-09-13T14:56:37Z
[ "python", "selenium", "selenium-webdriver", "selenium-chromedriver" ]
How to smartly match two data frames using Python (using pandas or other means)?
39,353,215
<p>I have one pandas dataframe composed of the names of the world's cities as well as countries, to which cities belong,</p> <pre><code>city.head(3) city country 0 Qal eh-ye Now Afghanistan 1 Chaghcharan Afghanistan 2 Lashkar Gah Afghanistan </code></pre> <p>and another data frame consisting of addres...
4
2016-09-06T15:56:18Z
39,427,730
<p>I would suggest to use <code>apply</code></p> <pre><code>city_list = city.tolist() def match_city(row): for city in city_list: if city in row['university']: return city return 'None' df['city'] = df.apply(match_city, axis=1) </code></pre> <p>I assume the addresses of university data is clean enou...
2
2016-09-10T15:42:15Z
[ "python", "pandas", "dataframe", "match" ]
How to smartly match two data frames using Python (using pandas or other means)?
39,353,215
<p>I have one pandas dataframe composed of the names of the world's cities as well as countries, to which cities belong,</p> <pre><code>city.head(3) city country 0 Qal eh-ye Now Afghanistan 1 Chaghcharan Afghanistan 2 Lashkar Gah Afghanistan </code></pre> <p>and another data frame consisting of addres...
4
2016-09-06T15:56:18Z
39,462,320
<p>In order to deal with the inconsistent structure of your strings, a good solution is to use regular expressions. I mocked up some data based on your description and created a function to capture the city from the strings. </p> <p>In my solution I used numpy to output NaN values when there wasn't a match, but you co...
2
2016-09-13T04:40:27Z
[ "python", "pandas", "dataframe", "match" ]
How to smartly match two data frames using Python (using pandas or other means)?
39,353,215
<p>I have one pandas dataframe composed of the names of the world's cities as well as countries, to which cities belong,</p> <pre><code>city.head(3) city country 0 Qal eh-ye Now Afghanistan 1 Chaghcharan Afghanistan 2 Lashkar Gah Afghanistan </code></pre> <p>and another data frame consisting of addres...
4
2016-09-06T15:56:18Z
39,462,597
<p>My suggestion is that after a few pre-processing that reduce address into city level information (we don't need to be exact, but try your best; like removing numbers etc), and then merge the dataframes based on text similarities.</p> <p>You may consider text similarity measures like levenshtein distance or jaro-win...
2
2016-09-13T05:14:26Z
[ "python", "pandas", "dataframe", "match" ]
How to smartly match two data frames using Python (using pandas or other means)?
39,353,215
<p>I have one pandas dataframe composed of the names of the world's cities as well as countries, to which cities belong,</p> <pre><code>city.head(3) city country 0 Qal eh-ye Now Afghanistan 1 Chaghcharan Afghanistan 2 Lashkar Gah Afghanistan </code></pre> <p>and another data frame consisting of addres...
4
2016-09-06T15:56:18Z
39,513,162
<p>I think one simple idea would be to create a mapping from any word or sequence of word of any address to the full address the word is part of, with the assumption that one of those address words is the cites. In a second step we match this with the set of known cities that you have, and anything that is not a known ...
1
2016-09-15T14:03:56Z
[ "python", "pandas", "dataframe", "match" ]
How to smartly match two data frames using Python (using pandas or other means)?
39,353,215
<p>I have one pandas dataframe composed of the names of the world's cities as well as countries, to which cities belong,</p> <pre><code>city.head(3) city country 0 Qal eh-ye Now Afghanistan 1 Chaghcharan Afghanistan 2 Lashkar Gah Afghanistan </code></pre> <p>and another data frame consisting of addres...
4
2016-09-06T15:56:18Z
39,576,732
<p>Partial match is prevented in the below function. Information of countries also considered while matching cities. To use this function university dataframe need to be split into list data type, such that every piece of address split into list of strings.</p> <pre><code>In [22]: def get_city(univ_name_split): ......
0
2016-09-19T15:22:18Z
[ "python", "pandas", "dataframe", "match" ]
Color gradient on scatter plot based on values
39,353,287
<p>I would like to define a color gradient for this image: <a href="http://i.stack.imgur.com/xjtq5.png" rel="nofollow"><img src="http://i.stack.imgur.com/xjtq5.png" alt="enter image description here"></a></p> <p>For each direction, I want to define a color gradient from red to blue depending on the density of values o...
-1
2016-09-06T16:00:31Z
39,353,738
<p>First, for each data point compute the desired color. The provide the color specification sequence as <code>c</code> parameter of the <code>scatter</code> function (<a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter" rel="nofollow">http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot...
0
2016-09-06T16:26:53Z
[ "python", "matplotlib", "scatter-plot" ]
How to extract nouns from dataframe
39,353,348
<p>I want to extract nouns from dataframe. Only nouns. I do as below</p> <pre><code>import pandas as pd import nltk from nltk.tag import pos_tag from nltk import word_tokenize df = pd.DataFrame({'noun': ['good day', 'good night']}) </code></pre> <p>I want to get</p> <pre><code> noun 0 day 1 night </code></pre...
1
2016-09-06T16:04:13Z
39,355,909
<p>The problem is that in your loop, <code>row</code> is a pandas <code>Series</code> rather than a list. You can access the list of words by writing <code>row[0]</code> instead:</p> <pre><code>&gt;&gt;&gt; for index, row in df.iterrows(): &gt;&gt;&gt; noun.append([word for word,pos in pos_tag(row[0]) if pos == '...
1
2016-09-06T18:47:38Z
[ "python", "nltk", "pos-tagger" ]
Count of unique values in nested dict python
39,353,428
<p>I have a dict like:</p> <pre><code>dict = { "a": {"Azerbaijan": 20006.0, "Germany": 20016.571428571428}, "b": {"Chad": 13000.0, "South Africa": 3000000.0}, "c": {"Chad": 200061.0, "South Africa": 3000000.0} } </code></pre> <p>And I am trying to get a dict of the counts of the occurrences of each unique...
1
2016-09-06T16:08:29Z
39,353,620
<pre><code>from collections import Counter seen_countries = Counter() seen_values = Counter() for data in your_dicts.itervalues(): seen_countries += Counter(data.keys()) seen_values += Counter(data.values()) </code></pre>
4
2016-09-06T16:20:17Z
[ "python", "dictionary", "iterator", "set" ]
Error string to float
39,353,705
<p>This is my code. I am doing a beginer execise. When I run the program </p> <p>I can put the values, but when I go out of the loop the following error message appears:</p> <pre><code> a + = float (input ("Enter the product cost")) </code></pre> <p>ValueError: could not convert string to float:</p> <p>Can someone ...
1
2016-09-06T16:25:13Z
39,353,915
<p>You're trying to convert a float to a string by doing <code>if a == ""</code>. Try the following:</p> <pre><code>while True: a_input = input("Enter the product cost: ") if a_input == "": break try: a += float(a_input) except ValueError: break </code></pre> <p>This check...
0
2016-09-06T16:37:01Z
[ "python", "python-3.x" ]
Error string to float
39,353,705
<p>This is my code. I am doing a beginer execise. When I run the program </p> <p>I can put the values, but when I go out of the loop the following error message appears:</p> <pre><code> a + = float (input ("Enter the product cost")) </code></pre> <p>ValueError: could not convert string to float:</p> <p>Can someone ...
1
2016-09-06T16:25:13Z
39,353,972
<p>There are a couple of issues:</p> <ol> <li>the check for a being an empty string <code>("")</code> comes <em>after</em> the attempt to add it to the <code>float</code> value <code>a</code>. You should handle this with an exception to make sure that the input is numerical.</li> <li>If someone doesn't enter an empty ...
0
2016-09-06T16:41:15Z
[ "python", "python-3.x" ]
Error string to float
39,353,705
<p>This is my code. I am doing a beginer execise. When I run the program </p> <p>I can put the values, but when I go out of the loop the following error message appears:</p> <pre><code> a + = float (input ("Enter the product cost")) </code></pre> <p>ValueError: could not convert string to float:</p> <p>Can someone ...
1
2016-09-06T16:25:13Z
39,357,599
<p>You are combining two operations on the same line: the input of a string, and the conversion of the string to a <code>float</code>. If you enter the empty string to end the program, the conversion to <code>float</code> fails with the error message you see; the error contains the string it tried to convert, and it is...
1
2016-09-06T20:48:42Z
[ "python", "python-3.x" ]
Import function from a file in root directory
39,353,717
<p>My file where I am working is at : <code>folder/src/views/basics.py</code>.</p> <p>I want to import function in file where is present at : <code>folder/src/server.py</code>.</p> <p>How to <strong>import function from server.py to basics.py</strong> ? Note: I have made a __ init __.py file in <code>folder/src/</cod...
-1
2016-09-06T16:25:37Z
39,353,927
<pre><code>from ..server import Function Function() </code></pre> <p>or</p> <pre><code>from .. import server server.Function() </code></pre>
0
2016-09-06T16:37:56Z
[ "python" ]
pandas pivot table of sales
39,353,758
<p>I have a list like below:</p> <pre><code> saleid upc 0 155_02127453_20090616_135212_0021 02317639000000 1 155_02127453_20090616_135212_0021 00000000000888 2 155_01605733_20090616_135221_0016 00264850000000 3 155_01072401_20090616_135224_0010 02316877000000 4 155_010...
4
2016-09-06T16:28:14Z
39,353,909
<p><strong><em>Option 1</em></strong></p> <pre><code>df.groupby(['saleid', 'upc']).size().unstack(fill_value=0) </code></pre> <p><a href="http://i.stack.imgur.com/6yvfj.png" rel="nofollow"><img src="http://i.stack.imgur.com/6yvfj.png" alt="enter image description here"></a></p> <p><strong><em>Option 2</em></strong><...
4
2016-09-06T16:36:40Z
[ "python", "csv", "pandas", "numpy" ]
pandas pivot table of sales
39,353,758
<p>I have a list like below:</p> <pre><code> saleid upc 0 155_02127453_20090616_135212_0021 02317639000000 1 155_02127453_20090616_135212_0021 00000000000888 2 155_01605733_20090616_135221_0016 00264850000000 3 155_01072401_20090616_135224_0010 02316877000000 4 155_010...
4
2016-09-06T16:28:14Z
39,355,438
<p>simple <code>pivot_table()</code> solution:</p> <pre><code>In [16]: df.pivot_table(index='saleid', columns='upc', aggfunc='size', fill_value=0) Out[16]: upc 00000000000888 00264850000000 02316877000000 02317639000000 05051969277205 saleid 155_01072401_20090616_135224_0010 ...
2
2016-09-06T18:18:08Z
[ "python", "csv", "pandas", "numpy" ]
Deleting Object from QuerySet List in Django with ManyToMany relationship
39,353,856
<p>I am having trouble deleting an object from a list of objects while using <code>ForeignKey</code> and <code>ManyToMany</code> relationships in Django.</p> <p>Here is the models I have set up for an Item, List, and the Order (an intermediary model).</p> <pre><code>class Item(models.Model): title_english = model...
2
2016-09-06T16:33:45Z
39,363,262
<p>if your target is the item referenced to from 'pk' you could just use List.objects.get(pk).delete(). </p> <p>Be sure to put this inside a try: except List.DoesNotExist: to avoid people trigerring 500s by manually inputting random strings in the URL.</p> <pre><code>try: List.objects.get(pk).delete() except List.D...
3
2016-09-07T07:04:28Z
[ "python", "django", "postgresql" ]
Inheriting from numpy.recarray, __unicode__ issue
39,353,917
<p>I have made a subclass of a numpy.recarray. The purpose of the class is to provide pretty printing for record arrays while maintaining the record array functionality. </p> <p>Here is the code:</p> <pre><code>import numpy as np import re class TableView(np.recarray): def __new__(cls,array): return np....
0
2016-09-06T16:37:14Z
39,354,284
<p>Your diagnosis is right. A single element of this class is a <code>record</code>, not an <code>Tableview</code> array. </p> <p>And indexing with a slice or list, <code>[0:1]</code> or <code>[[0]]</code>, is the immediate solution.</p> <p>Trying to subclass <code>np.record</code> and changing the elements of the ...
1
2016-09-06T17:00:55Z
[ "python", "numpy", "recarray" ]
String after last hypen with 1-N Hypens in Regex (Python)
39,353,919
<p>Given a pattern (<a href="https://regex101.com/r/iN9hG6/2" rel="nofollow">https://regex101.com/r/iN9hG6/2</a>) which can have N # of hypens where I want the text after the last one, how would I request that as I always get the first:</p> <p><code>&lt;details&gt;Fiction - Mystery - Duvall&lt;/details&gt;</code></p> ...
0
2016-09-06T16:37:27Z
39,353,992
<p>Judging by the provided sample input data, this is an XML and should be parsed with <em>specialized</em> tools like <a href="https://docs.python.org/2/library/xml.etree.elementtree.html" rel="nofollow"><code>xml.etree.ElementTree</code></a> or <a href="http://lxml.de/" rel="nofollow"><code>lxml</code></a>. To get to...
0
2016-09-06T16:42:06Z
[ "python", "regex" ]
String after last hypen with 1-N Hypens in Regex (Python)
39,353,919
<p>Given a pattern (<a href="https://regex101.com/r/iN9hG6/2" rel="nofollow">https://regex101.com/r/iN9hG6/2</a>) which can have N # of hypens where I want the text after the last one, how would I request that as I always get the first:</p> <p><code>&lt;details&gt;Fiction - Mystery - Duvall&lt;/details&gt;</code></p> ...
0
2016-09-06T16:37:27Z
39,353,997
<p>I think what you're looking for is this:</p> <pre><code>&lt;details&gt;(?:\w+ - *)*(\w+)&lt;\/details&gt; </code></pre> <p>The idea is to match as much as possible inside the (?: ) group, which doesn't cause a backreference to be made, then match the thing you actually care about - the last token. The example belo...
0
2016-09-06T16:42:21Z
[ "python", "regex" ]
String after last hypen with 1-N Hypens in Regex (Python)
39,353,919
<p>Given a pattern (<a href="https://regex101.com/r/iN9hG6/2" rel="nofollow">https://regex101.com/r/iN9hG6/2</a>) which can have N # of hypens where I want the text after the last one, how would I request that as I always get the first:</p> <p><code>&lt;details&gt;Fiction - Mystery - Duvall&lt;/details&gt;</code></p> ...
0
2016-09-06T16:37:27Z
39,354,020
<p>Sometimes the split() function is easier to use than RegEx. </p> <pre><code>test_string = "&lt;details&gt;Fiction - Mystery - Horror - Duvall&lt;/details&gt;" author = test_string.split("-")[-1][2:-10] </code></pre>
0
2016-09-06T16:44:11Z
[ "python", "regex" ]
Getting the error unorderable types: int() >= list()
39,353,947
<p>I am new to python. I am trying to write the python code for mergesort and i unable to locate the error.</p> <pre><code>import math t = int(input()) def merge(lf,rf): p=0 q= 0 b=[] for i in range(len(rf)+len(lf)): if (p&gt;=len(lf)): b.append(rf[q:]) break ...
-1
2016-09-06T16:39:09Z
39,354,060
<p>When you do either <code>b.append(rf[q:])</code> or <code>b.append(lf[p:])</code>, you adding a <em>list</em> as an element to the list <code>b</code>, which looks like it should be a list of integers.</p>
1
2016-09-06T16:46:21Z
[ "python" ]
Getting the error unorderable types: int() >= list()
39,353,947
<p>I am new to python. I am trying to write the python code for mergesort and i unable to locate the error.</p> <pre><code>import math t = int(input()) def merge(lf,rf): p=0 q= 0 b=[] for i in range(len(rf)+len(lf)): if (p&gt;=len(lf)): b.append(rf[q:]) break ...
-1
2016-09-06T16:39:09Z
39,354,097
<p>This line</p> <pre><code>b.append(rf[q:]) </code></pre> <p>appends the list <code>rf[q:]</code> to <code>b</code> as a single item. But that's not what you really want, because <code>b</code> ends up containing sublists of numbers as well as the numbers it's supposed to contain. So you need to add the <em>contents...
2
2016-09-06T16:48:30Z
[ "python" ]
Python: StopIteration error being raised iterating through blank csv
39,353,985
<p>I'm a new python user and have an issue. I apologize in advance if the solution is obvious.</p> <p>I intend to be able to take a potentially large amount of csv files and jam them into a database which I can then use sql to query for reporting and other sweet stuff and I have the following code:</p> <pre><code>imp...
1
2016-09-06T16:41:48Z
39,354,128
<p>You have exhausted the <code>csvObj</code> iterator on the line before:</p> <pre><code>rowCount = sum(1 for row in csvObj) </code></pre> <p>Once an iterator is exhausted, you can't call <code>next()</code> on it anymore without that raising <code>StopIteration</code>; you have reached the end of the iterator alrea...
0
2016-09-06T16:50:26Z
[ "python", "sqlite", "csv", "error-handling", "sqlite3" ]
How to download a gmail attachment?
39,353,989
<p>I am trying to download email attachments from Gmail using python using code shared on link</p> <p><a href="https://gist.github.com/baali/2633554" rel="nofollow">https://gist.github.com/baali/2633554</a></p> <p>I want to apply time filter + subject filter and download the attachment. For example all files received...
2
2016-09-06T16:41:55Z
39,354,450
<p>Based on the script you linked, add the following lines to filter emails on date and subject:</p> <pre><code>from datetime import datetime day = '2016-09-06' subject = 'Your command is available' look_for = '(SENTSINCE {0} SUBJECT "{1}")'.format( datetime.strptime(day, '%Y-%m-%d').strftime('%d-%b-%Y'), subject...
1
2016-09-06T17:12:22Z
[ "python", "gmail", "attachment" ]
merge two dataframes by row with same index pandas
39,354,031
<p>let's say i have the following two dataframes X1 and X2. I would like to merge those 2 dataframes by row so that each index from each dataframe being the same combines the corresponding rows from both dataframes.</p> <pre><code> A B C D DATE1 a1 b1 c1 d1 DATE2 a2 b2 c2 d2 DATE3 a3 b3 c3 d3 A B C...
4
2016-09-06T16:44:53Z
39,354,165
<p><strong><em>Option 1</em></strong></p> <pre><code>df3 = df1.stack().to_frame('df1') df3.loc[:, 'df2'] = df2.stack().values df3 = df3.stack().unstack(1) df3 </code></pre> <p><a href="http://i.stack.imgur.com/ZfKUu.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZfKUu.png" alt="enter image description here"><...
6
2016-09-06T16:53:05Z
[ "python", "pandas", "dataframe", "append", "concatenation" ]
merge two dataframes by row with same index pandas
39,354,031
<p>let's say i have the following two dataframes X1 and X2. I would like to merge those 2 dataframes by row so that each index from each dataframe being the same combines the corresponding rows from both dataframes.</p> <pre><code> A B C D DATE1 a1 b1 c1 d1 DATE2 a2 b2 c2 d2 DATE3 a3 b3 c3 d3 A B C...
4
2016-09-06T16:44:53Z
39,379,720
<p>maybe this solution too could solve your problem:</p> <pre><code>df3 = pd.concat([df1,df2]).sort_index() print df3 Out[42]: A B C D DATE1 a1 b1 c1 d1 DATE1 f1 g1 h1 i1 DATE2 a2 b2 c2 d2 DATE2 f2 g2 h2 i2 DATE3 a3 b3 c3 d3 DATE3 f3 g3 h3 i3 </code></pre>
0
2016-09-07T22:06:06Z
[ "python", "pandas", "dataframe", "append", "concatenation" ]
Nested if statement returns nothing in list of lists
39,354,036
<p>Here is my list (of lists):</p> <pre><code>mylist = [ [1, "John", None, "Doe"], [2, "Jane", "group1", "Zee"], [3, "Lex", "group2", "Fee"]] y = 2 for sublist in mylist: if sublist[0] == y: # meaning the third list if sublist[2] == None: print(sublist[2]) # this should print nothing ...
1
2016-09-06T16:45:00Z
39,354,279
<blockquote> <p>I am trying to do a check for situations where I have a None value in my list (of lists)</p> </blockquote> <p>Then just check for membership with <code>in</code> for every sub list:</p> <pre><code>for sublist in mylist: if None in sublist: # do your check print("None in list: ", ...
4
2016-09-06T17:00:34Z
[ "python", "python-3.x", "python-3.4" ]
Nested if statement returns nothing in list of lists
39,354,036
<p>Here is my list (of lists):</p> <pre><code>mylist = [ [1, "John", None, "Doe"], [2, "Jane", "group1", "Zee"], [3, "Lex", "group2", "Fee"]] y = 2 for sublist in mylist: if sublist[0] == y: # meaning the third list if sublist[2] == None: print(sublist[2]) # this should print nothing ...
1
2016-09-06T16:45:00Z
39,354,435
<p>I think I understand what you are trying to accomplish. You like to enumerate through a list of lists, then check the <code>y</code>-th field to see if it contains <code>None</code>.</p> <p>The problem you are facing is that when you do:</p> <pre><code>y = 2 </code></pre> <p>indicating the third field and later ...
2
2016-09-06T17:10:47Z
[ "python", "python-3.x", "python-3.4" ]
Permission Denied for Python Keylogger
39,354,197
<p>I've created a simple python keylogger by following this tutorial: <a href="https://www.youtube.com/watch?v=8BiOPBsXh0g" rel="nofollow">https://www.youtube.com/watch?v=8BiOPBsXh0g</a></p> <pre><code>import pyHook, pythoncom, sys, logging file_log = 'C:\\log.txt' def OnKeyboardEvent(event): logging.basicConfig...
0
2016-09-06T16:54:56Z
39,355,017
<p><strong>Reposting as an answer for future use</strong></p> <p>The easiest and, arguably, safest way would be to not write the log to the root of C. Change the "file_log = 'C:\log.txt'" to something like "file_log = 'C:\Users\Adithya1\log.txt" instead.</p> <p>There are <a href="http://stackoverflow.com/questions/40...
1
2016-09-06T17:48:24Z
[ "python" ]
Python: How to change text of a message widget to a user input
39,354,205
<p>So I'm making a program which requires a user to enter in a value. I want the value to be displayed via the message widget (or label widget) and updates whenever a new input is enter.</p> <pre><code>def Enter(): s = v.get() print (v.get()) e.delete(0, END) e.insert(0, "") #Code, Code, Code ... # ...
2
2016-09-06T16:55:27Z
39,354,401
<p>Simply add:</p> <pre><code>m.configure(text=s) </code></pre> <p>to your function:</p> <pre><code>def Enter(): s = v.get() print (v.get()) m.configure(text=s) e.delete(0, END) e.insert(0, "") </code></pre> <hr> <p>As a side- note, you do not necessarily need the <code>StringVar()</code>. The...
3
2016-09-06T17:07:57Z
[ "python", "tkinter" ]
Unable to import a custom DLL in python
39,354,389
<p>I am trying to expose a C++ class to python with <code>boost::python</code>, so I am going through <a href="http://www.boost.org/doc/libs/1_61_0/libs/python/doc/html/tutorial/tutorial/exposing.html" rel="nofollow">this tutorial</a>. I created a visual studio <code>.dll</code> project, with this source code:</p> <pr...
1
2016-09-06T17:07:06Z
39,354,682
<p>I actually just figured out the answer shortly after posting the question. Thanks to <a href="http://mmmovania.blogspot.com/2013/01/running-c-code-from-python-using.html" rel="nofollow">this blog post</a> I found out that simply renaming the <code>hello.dll</code> to <code>hello.pyd</code> was enough. From some more...
0
2016-09-06T17:26:43Z
[ "python", "dll", "ctypes", "boost-python", "python-c-api" ]
Local CSV as criteria for SQL where clause against Network Netezza DB in Python
39,354,399
<p>In Python, I am querying against a Netezza database using SQL, and for one of the variables in the Netezza tables, I'd like to do an inner join from that to the same variable in an external CSV file. Is this possible? </p> <p>Here is an example shell of my Python code, using pandas <code>read_sql</code> module</p> ...
1
2016-09-06T17:07:48Z
39,417,016
<p>Since it's a CSV, your best option is to create an <a href="http://www.ibm.com/support/knowledgecenter/SSULQD_7.2.1/com.ibm.nz.load.doc/c_load_external_tables.html" rel="nofollow">external table</a> in Netezza and join to that.</p> <pre><code>create external table some_csv ( column1 varchar(10) ,column2 varchar...
0
2016-09-09T17:40:36Z
[ "python", "csv", "netezza" ]
django: link to detail page from list of returned results
39,354,430
<p>I'm creating a page that returns a list of movies with basic details after a user search. </p> <p><strong>After the search, I'd like the user to be able to click on a movie, and get more details about it.</strong> </p> <p>here's a link to the site: (be gentle, I only started learning this stuff 2 months ago! hah) ...
2
2016-09-06T17:10:20Z
39,369,899
<p>I think you should try by fixing the urls.py in this line:</p> <pre><code>url(r'^(?P&lt;movid&gt;[0-9])+$', views.get_movie, name='movies') </code></pre> <p>Move the "+" inside the brackets like that:</p> <pre><code>url(r'^(?P&lt;movid&gt;[0-9]+)$', views.get_movie, name='movies') </code></pre>
1
2016-09-07T12:23:50Z
[ "python", "html", "django" ]
django: link to detail page from list of returned results
39,354,430
<p>I'm creating a page that returns a list of movies with basic details after a user search. </p> <p><strong>After the search, I'd like the user to be able to click on a movie, and get more details about it.</strong> </p> <p>here's a link to the site: (be gentle, I only started learning this stuff 2 months ago! hah) ...
2
2016-09-06T17:10:20Z
39,396,718
<p>I was able to get this working by fixing the urlpattern per Roman's answer, along with a few needed tweaks.</p> <p>in the app urls.py I needed to change the order:</p> <pre><code>urlpatterns = [ url(r'^(?P&lt;movid&gt;[0-9]+)$', views.get_movie, name='movie_detail'), url(r'^', views.search_movie, name='com...
0
2016-09-08T17:11:19Z
[ "python", "html", "django" ]
Why Scrapy returns an Iframe?
39,354,465
<p>i want to crawl <a href="http://www.ooshop.com/courses-en-ligne/Home.aspx" rel="nofollow">this site</a> by Python-Scrapy</p> <p>i try this</p> <pre><code>class Parik(scrapy.Spider): name = "ooshop" allowed_domains = ["http://www.ooshop.com/courses-en-ligne/Home.aspx"] def __init__(self, idcrawl=None, ...
0
2016-09-06T17:13:11Z
39,354,581
<p>The website is protected by Incapsula, a website security service. It's providing your "browser" with a challenge that it must perform before being given a special cookie that gives you access to the website itself.</p> <p>Fortunately, it's not that hard to bypass. Install <a href="https://github.com/ziplokk1/incap...
2
2016-09-06T17:21:13Z
[ "python", "iframe", "web-scraping", "scrapy", "web-crawler" ]
Django model, Overriding the save method or custom method with property
39,354,500
<p>I'm working with some models that has to return a sum of model fields. Is it better to override the save method on the model or just create a custom method that returns the sum. Is there any performance issues with either of the solutions?</p> <p>Example 1, overriding the save method.</p> <pre><code>class SomeMode...
5
2016-09-06T17:15:22Z
39,354,942
<p>The answer depends on the way you are going to use sum_integers. If you keep it as a field in DB, you will be able to make a queries on it, and with property it would be very tricky. </p> <p>On other hand, if you aren't going to make a queries and this data does not valuable for you(in other words - you need sum_in...
2
2016-09-06T17:43:30Z
[ "python", "django", "django-models" ]
Django model, Overriding the save method or custom method with property
39,354,500
<p>I'm working with some models that has to return a sum of model fields. Is it better to override the save method on the model or just create a custom method that returns the sum. Is there any performance issues with either of the solutions?</p> <p>Example 1, overriding the save method.</p> <pre><code>class SomeMode...
5
2016-09-06T17:15:22Z
39,357,001
<p>Depends on whether you have to update the fields more or call the sum more.</p> <p>I am assuming, to make it more generic, that the operation is not only addition but multiple complex calculation involving large numbers.</p> <p>If you have to get the sum every now and then, then its better to create a model field ...
2
2016-09-06T20:04:58Z
[ "python", "django", "django-models" ]
Method to sort values in row in pandas Series?
39,354,531
<p>Consider the following <code>pandas.Series</code> object:</p> <pre><code>import pandas as pd s = pd.Series(["hello there you would like to sort me", "sorted i would like to be", "the yankees played the red sox", "apple apple banana fruit orange cucumber"]) </code></pre> <p>I would like to sort the values <strong>...
2
2016-09-06T17:17:30Z
39,354,601
<p>use the string accessor <code>str</code> and <code>split</code>. Then apply <code>sorted</code> and <code>join</code>.</p> <pre><code>s.str.split().apply(sorted).str.join(' ') 0 hello like me sort there to would you 1 be i like sorted to would 2 played red sox the the yankees ...
3
2016-09-06T17:22:09Z
[ "python", "pandas", "vector" ]
Method to sort values in row in pandas Series?
39,354,531
<p>Consider the following <code>pandas.Series</code> object:</p> <pre><code>import pandas as pd s = pd.Series(["hello there you would like to sort me", "sorted i would like to be", "the yankees played the red sox", "apple apple banana fruit orange cucumber"]) </code></pre> <p>I would like to sort the values <strong>...
2
2016-09-06T17:17:30Z
39,354,739
<p>I've experienced that Python lists perform better in these situations. Applying piRSquared's logic, a list comprehension would be:</p> <pre><code>[' '.join(sorted(sentence.split())) for sentence in s.tolist()] </code></pre> <p>For timings I've used Shakespeare's works from <a href="http://norvig.com/ngrams/" rel="...
4
2016-09-06T17:30:00Z
[ "python", "pandas", "vector" ]
What is the equivalent of np.std() in TensorFlow?
39,354,566
<p>Just looking for the equivalent of np.std() in TensorFlow to calculate the standard deviation of a tensor.</p>
1
2016-09-06T17:19:49Z
39,354,802
<p>To get the mean and variance just use tf.nn.moments.</p> <pre><code>mean, var = tf.nn.moments(x,axes=[1]) </code></pre> <p>for more on tf.nn.moments params see <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/nn.html#moments" rel="nofollow">docs</a></p>
2
2016-09-06T17:34:27Z
[ "python", "tensorflow" ]
Avoid to display the UserWarning message of bs4 library
39,354,567
<p>Every time I make soup a sourcecode of a page with bs4 in python, the terminal shows:</p> <pre><code>/usr/local/lib/python3.4/dist-packages/bs4/__init__.py:181: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html5lib"). This usually isn't a problem, bu...
-1
2016-09-06T17:19:49Z
39,354,857
<p>While the inclusion of the parser is optional, the warning is telling you that results may vary from system to system if you don't explicitly state which parser you want to use.</p> <p>The <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser" rel="nofollow">documentation</a> makes it ...
1
2016-09-06T17:37:33Z
[ "python", "python-3.x", "beautifulsoup", "warnings", "bs4" ]
Scraping google news with BeautifulSoup returns empty results
39,354,587
<p>I am trying to scrape google news using the following code:</p> <pre><code>from bs4 import BeautifulSoup import requests import time from random import randint def scrape_news_summaries(s): time.sleep(randint(0, 2)) # relax and don't let google be angry r = requests.get("http://www.google.co.uk/search?q=...
0
2016-09-06T17:21:32Z
39,354,870
<p>I tried running the code and it works fine on my computer.</p> <p>You could try printing the status code for the request, and see if it's anything other than 200.</p> <pre><code>from bs4 import BeautifulSoup import requests import time from random import randint def scrape_news_summaries(s): time.sleep(randi...
2
2016-09-06T17:38:12Z
[ "python", "web-scraping", "beautifulsoup", "google-news" ]
Installing MySQLdb on osx El Capitan for Python
39,354,602
<p>I am trying:</p> <pre><code>brew install mysql pip install mysql-python </code></pre> <p>I am getting this output:</p> <pre class="lang-none prettyprint-override"><code>Collecting mysql-python Using cached MySQL-python-1.2.5.zip Installing collected packages: mysql-python Running setup.py install for mysql-pyth...
0
2016-09-06T17:22:10Z
39,355,286
<p>The relevant error message is this:</p> <pre class="lang-none prettyprint-override"><code>error: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/_mysql.so </code></pre> <p>It can't copy to the target directory because of missing permissions.</p> <p>You can either install it to the local user site...
0
2016-09-06T18:09:17Z
[ "python", "osx", "python-2.7", "mysql-python", "osx-elcapitan" ]
Best way to read and write two files?
39,354,706
<p>Folks, looking to get the suggestions on the best way to deal with the following task: <br> 1. Read data off of a CSV file. <br> 2. Edit an XML file based on the data read in Step 1.</p> <p>I am a Python noob. So far I am able to read the data off of a CSV file. In my Java world, I would simply pass the "read" data...
-2
2016-09-06T17:28:10Z
39,354,786
<p>Very similar to your solution, just uses <code>enumerate</code> and <code>with</code> instead of <code>open</code> and <code>close</code>:</p> <pre><code>import csv with open('my-file.csv', 'rb') as ifile: reader = csv.reader(ifile) for rownum, row in enumerate(reader): #print row if rownum...
0
2016-09-06T17:33:23Z
[ "python", "xml", "csv", "scripting", "elementtree" ]
Best way to read and write two files?
39,354,706
<p>Folks, looking to get the suggestions on the best way to deal with the following task: <br> 1. Read data off of a CSV file. <br> 2. Edit an XML file based on the data read in Step 1.</p> <p>I am a Python noob. So far I am able to read the data off of a CSV file. In my Java world, I would simply pass the "read" data...
-2
2016-09-06T17:28:10Z
39,355,865
<p>Your question is missing a little bit of clarity (what is it that you are seeking). Anyway, from what I understood, you are looking for an easy way to read a <strong><em>csv</em></strong> file and and print the <strong><em>ith</em></strong> columns in a certain formatting (e.g. name: ... ). I am assuming that your ...
2
2016-09-06T18:44:55Z
[ "python", "xml", "csv", "scripting", "elementtree" ]
BeautifulSoup.find_all for nested divs without class attribute
39,354,804
<p>I am working with python2 and I wanted to get the content of a div in html page.</p> <pre><code>&lt;div class="lts-txt2"&gt; Some Content &lt;/div&gt; </code></pre> <p>If the div class is like above then I can get the content using</p> <pre><code>BeautifulSoup.find_all('div', attrs={"class": 'lts-txt2'}) </c...
-1
2016-09-06T17:34:29Z
39,354,875
<p>You can extract all text from the node <em>including nested nodes</em> with the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text" rel="nofollow"><code>Element.get_text()</code> method</a>:</p> <pre><code>[el.get_text() for el in soup.find_all('div', attrs={"class": 'lts-txt2'})] </code></pre...
0
2016-09-06T17:38:31Z
[ "python", "html", "beautifulsoup" ]
Extracting string before the quotations
39,354,823
<p>I am trying to parse a pdf in python and extract string in quotations. I am able to extract the text in quotations but I also want to extract the name before the quotation starts. For example: Consider this</p> <p>Ziblatt, Daniel. 2004. "Rethinking the Origins of Federalism: Puzzle, Theory, and Evidence from Ninete...
0
2016-09-06T17:35:25Z
39,354,923
<p>Capturing data before a double-quote should work:</p> <pre><code>def quotes(x): quoted = re.compile('(.+)"[^"]+"') for value in quoted.findall(x): print value.strip() </code></pre> <p>I get this ouput:</p> <pre><code>&gt;&gt;&gt; quotes(text) 'Ziblatt, Daniel. 2004.' </code></pre>
1
2016-09-06T17:42:40Z
[ "python", "extract", "quotes" ]
Cross-Origin Request Blocked on POST call to api
39,355,023
<p>I know there are many other articles on this topic but unfortunately none of the solutions worked for me.</p> <p>I am running linux red hat 7.2 with apache 2.4 (httpd). I am working on the server directly as localhost. The API is python based which i have little experience with - i downloaded the program from githu...
0
2016-09-06T17:48:54Z
39,355,142
<p>Out of curiosity, are you using a Javascript build environment like Ember or Angular on the client side? Because that will affect your hosted port, and could contribute to cross-origin related errors.</p> <p>Another thing you could do is to modify your ajax slightly and create a helpder function as so:</p> <pre><c...
0
2016-09-06T17:58:25Z
[ "jquery", "python" ]
Pony ORM - Order by specific order
39,355,048
<p>Performing a Pony ORM query and attempting to sort the query by three attributes that live on the model. First by song type, which can be one of the five values listed in <code>ssf_type_order_map</code>, then by duration (int), and uuid (string). </p> <p>For song type, I would like to have the songs sorted in the f...
3
2016-09-06T17:50:29Z
39,370,908
<p>At first, I want to say that Pony distinguishes two types of sub-expressions: external expressions and correlated expressions. External expressions don't depend on the value of a generator loop variable(s), while correlated expressions do. Consider the following example:</p> <pre class="lang-py prettyprint-override...
2
2016-09-07T13:13:29Z
[ "python", "sorting", "lambda", "ponyorm" ]
Jenkins git triggered build not blocking
39,355,230
<p>I am running a build on commit to <code>origin/master</code> on my jenkins server that is deploying resources to Amazon AWS. I am using the Execute Shell section to run a python script that handles all unit testing/linting/validation/deployment and everything blocks fine until it gets to the deployment (<code>deploy...
2
2016-09-06T18:05:08Z
39,357,587
<p>You can use api calls to aws to retrieve the status and wait until it become 'some status'.</p> <p>The below example is psuedo-code to illustrate the idea:</p> <pre><code>import time import boto3 ec2 = boto3.resource('ec2') while True: response = ec2.describe_instance_status(.....) if response == 'some st...
0
2016-09-06T20:48:02Z
[ "python", "amazon-web-services", "jenkins" ]
Paginating a DynamoDB query in boto3
39,355,377
<p>How can I loop through all results in a DynamoDB query, if they span more than one page? <a href="http://stackoverflow.com/a/13178258/526495">This answer</a> implies that pagination is built into the query function (at least in v2), but when I try this in v3, my items seem limited:</p> <pre><code>import boto3 from ...
1
2016-09-06T18:14:33Z
39,358,086
<p>ExclusiveStartKey is the name of the attribute which you are looking for. Use the value that was returned for LastEvaluatedKey in the previous operation.</p> <p>The data type for ExclusiveStartKey must be String, Number or Binary. No set data types are allowed.</p> <p><a href="http://boto3.readthedocs.io/en/latest...
0
2016-09-06T21:25:12Z
[ "python", "pagination", "aws-lambda", "boto3" ]
Searching within a datetime object python
39,355,483
<p>I am trying to locate where the years are within a specified bounds for a datetime object. I have tried doing a for loop a few different ways but unfortunately I cannot seem to get it to work. I know I am able to search for months and years when I convert a datetime object to a pandas array, but unfortunately the so...
1
2016-09-06T18:21:33Z
39,358,056
<p>Turns out I needed to use the following loop instead:</p> <pre><code>for i in range(len(time_converted)): if time_converted[i].year &gt;= 2006 and time_converted[i].year &lt; 2016: time.append(time_converted[i]) </code></pre>
0
2016-09-06T21:23:11Z
[ "python", "datetime", "search", "indexing" ]
Why the elements of numpy array not same as themselves?
39,355,556
<p>How do I explain the last line of these?</p> <pre><code>&gt;&gt;&gt; a = 1 &gt;&gt;&gt; a is a True &gt;&gt;&gt; a = [1, 2, 3] &gt;&gt;&gt; a is a True &gt;&gt;&gt; a = np.zeros(3) &gt;&gt;&gt; a array([ 0., 0., 0.]) &gt;&gt;&gt; a is a True &gt;&gt;&gt; a[0] is a[0] False </code></pre> <p>I always thought that ...
3
2016-09-06T18:25:37Z
39,355,706
<p>NumPy doesn't store array elements as Python objects. If you try to access an individual element, NumPy has to create a new wrapper object to represent the element, and it has to do this <em>every time</em> you access the element. The wrapper objects from two accesses to <code>a[0]</code> are different objects, so <...
7
2016-09-06T18:35:58Z
[ "python", "python-3.x", "numpy" ]
Speeding up Dijkstra's algorithm to solve a 3D Maze
39,355,587
<p>I'm trying to write a Python script that can solve 3D mazes and I'm doing it using Dijkstra's algorithm with a priority queue(included in the module heapq). Here is my main function code:</p> <pre><code>from heapq import * def dijkstra(start,end,vertices,obstacles): covered=[] s=vertices.index(s) curren...
1
2016-09-06T18:27:22Z
39,355,685
<p>Do you know about A* search ("A-star")? It's a modification of Dijkstra's algorithm that can help a great deal when you know something about the geometry of the situation. Unmodified Dijkstra's assumes that any edge could be the start of an astonishingly short path to the goal, but often the geometry of the situatio...
0
2016-09-06T18:34:18Z
[ "python", "algorithm", "3d", "dijkstra", "maze" ]
Speeding up Dijkstra's algorithm to solve a 3D Maze
39,355,587
<p>I'm trying to write a Python script that can solve 3D mazes and I'm doing it using Dijkstra's algorithm with a priority queue(included in the module heapq). Here is my main function code:</p> <pre><code>from heapq import * def dijkstra(start,end,vertices,obstacles): covered=[] s=vertices.index(s) curren...
1
2016-09-06T18:27:22Z
39,356,377
<p>I suspect that a lot of time will be spent in these two lines:</p> <pre><code>v=vertices.index(u) if v in covered:continue </code></pre> <p>both of these lines are O(n) operations where n is the number of vertices in your graph.</p> <p>I suggest you replace the first with a dictionary (that maps from your vertex ...
1
2016-09-06T19:21:16Z
[ "python", "algorithm", "3d", "dijkstra", "maze" ]
Speeding up Dijkstra's algorithm to solve a 3D Maze
39,355,587
<p>I'm trying to write a Python script that can solve 3D mazes and I'm doing it using Dijkstra's algorithm with a priority queue(included in the module heapq). Here is my main function code:</p> <pre><code>from heapq import * def dijkstra(start,end,vertices,obstacles): covered=[] s=vertices.index(s) curren...
1
2016-09-06T18:27:22Z
39,356,541
<p>My initial approach would be to use some basic backtracking:</p> <pre class="lang-java prettyprint-override"><code>boolean[][][] visited = new boolean[h][w][d]; boolean foundPath = false; public void path(int y, int x,int z) { visited[y][x][z] = true; if (x == targetx &amp;&amp; y == target &amp;&am...
0
2016-09-06T19:33:27Z
[ "python", "algorithm", "3d", "dijkstra", "maze" ]
Disable python in-built function
39,355,608
<p>How could I disable a python in-built function?</p> <p>For example, I note that it is possible to reassign or overwrite <code>len()</code> (like <code>len = None</code>), but it is not possible to reassign <code>list.__len__()</code> , which raises:</p> <blockquote> <p>TypeError: can't set attributes of built-in...
2
2016-09-06T18:28:54Z
39,356,040
<p><strong>Preface:</strong> given the various comment conversations... It should be noted that none of these things are sufficient protection for running un-trusted code, and to be absolutely safe, you need a different interpreter with sandboxing specifically built in. <a href="http://stackoverflow.com/a/3068475/32201...
1
2016-09-06T18:57:56Z
[ "python", "python-3.x" ]
Python conditionally remove whitespaces
39,355,693
<p>I want to remove whitespaces in a string that are adjacent to <code>/</code> while keeping the rest of the whitespaces.</p> <p>For instance, say I have a string <code>98 / 100 xx 3/ 4 and 5/6</code>. The desired result for my example would be <code>98/100 xx 3/4 and 5/6</code>. (So that I could use <code>.split(' '...
-1
2016-09-06T18:34:58Z
39,355,789
<p>You can remove whitespace before and after slashes with <code>str.replace</code> instead of regex:</p> <pre><code>&gt;&gt;&gt; '98 / 100 xx 3/ 4 and 5/6'.replace(' /','/').replace('/ ','/') '98/100 xx 3/4 and 5/6' </code></pre>
4
2016-09-06T18:40:33Z
[ "python", "regex" ]
Python conditionally remove whitespaces
39,355,693
<p>I want to remove whitespaces in a string that are adjacent to <code>/</code> while keeping the rest of the whitespaces.</p> <p>For instance, say I have a string <code>98 / 100 xx 3/ 4 and 5/6</code>. The desired result for my example would be <code>98/100 xx 3/4 and 5/6</code>. (So that I could use <code>.split(' '...
-1
2016-09-06T18:34:58Z
39,355,798
<p>A hint: A regular expression that will find any amount of whitespace (not just space characters, but also tabs, etc.) around a slash is: <code>r'\s*/\s*'</code>. The regex there is between the apostrophes. The period is just the end of my sentence, and the r tells Python to treat the string inside apostrophes as a "...
3
2016-09-06T18:41:23Z
[ "python", "regex" ]
Having issue summarising python dataframe to one line per record
39,355,717
<p>I've got a dataframe in the form:</p> <pre><code>df = pd.DataFrame({'id':['a', 'a', 'a', 'b','b'],'var':[1,2,3,5,9]}) </code></pre> <p>and I'm trying to reshape it so that there is one line per 'id' and the values 'var' are displayed across in one line, so 'a' would have 1,2,3 ... 'b' would have '5,9'</p> <p>I've...
3
2016-09-06T18:36:17Z
39,355,758
<p><strong>UPDATE:</strong></p> <pre><code>In [32]: df.groupby('id')['var'].apply(lambda x: x.astype(str).str.cat(sep=',')).reset_index() Out[32]: id var 0 a 1,2,3 1 b 5,9 </code></pre> <p>or having <code>var</code> as a list:</p> <pre><code>In [29]: df.groupby('id')['var'].apply(list).reset_index() Out[2...
2
2016-09-06T18:39:09Z
[ "python", "pandas", "dataframe", "pivot-table" ]
Having issue summarising python dataframe to one line per record
39,355,717
<p>I've got a dataframe in the form:</p> <pre><code>df = pd.DataFrame({'id':['a', 'a', 'a', 'b','b'],'var':[1,2,3,5,9]}) </code></pre> <p>and I'm trying to reshape it so that there is one line per 'id' and the values 'var' are displayed across in one line, so 'a' would have 1,2,3 ... 'b' would have '5,9'</p> <p>I've...
3
2016-09-06T18:36:17Z
39,355,875
<p>You must supply the correct arguments, like:</p> <pre><code>pd.crosstab(index=df['id'], columns=df['var']) var 1 2 3 5 9 id a 1 1 1 0 0 b 0 0 0 1 1 </code></pre>
3
2016-09-06T18:45:42Z
[ "python", "pandas", "dataframe", "pivot-table" ]
How to get current login time in Ubuntu/Linux using python?
39,355,742
<p>From current login time, I mean the time at which the user logged into the system.</p> <p>Edit : I only need to get the current login time in hh:mm format, not the username and all</p>
-1
2016-09-06T18:37:44Z
39,356,001
<pre><code>import subprocess print subprocess.check_output("who").split()[3] </code></pre> <p>Output:</p> <pre><code>22:23 </code></pre> <p>Which is in <code>hh:mm</code> format.</p>
0
2016-09-06T18:55:21Z
[ "python", "ubuntu", "login" ]
Select columns from a DataFrame based on values in a row in pandas
39,355,767
<p>Say I have the same dataframe from <a href="http://stackoverflow.com/questions/25479607/pandas-min-of-selected-row-and-columns">this question</a>:</p> <pre><code> A0 A1 A2 B0 B1 B2 C0 C1 0 0.84 0.47 0.55 0.46 0.76 0.42 0.24 0.75 1 0.43 0.47 0.93 ...
2
2016-09-06T18:39:35Z
39,355,809
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.filter.html">filter()</a> in conjunction with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmin.html">idxmin()</a> method:</p> <pre><code>In [40]: x Out[40]: A0 A1 A2 B0 ...
5
2016-09-06T18:41:59Z
[ "python", "pandas", "dataframe", "calculated-columns" ]
Finding "taxiNumber" program, want to exchange nested for loop for optimization reasons
39,355,781
<p>I just started programming 1 week ago so please forgive the chaos you are about to see I'm trying to find the first x taxi numbers but with my "nested for loop" the program takes ages to go through all possibilities. Taxi number: if there is a number a^3+b^3 that is equal to c^3+d^3 that sum is a taxinumber. Exampl...
0
2016-09-06T18:40:19Z
39,356,772
<p>The problem is that the <a href="https://en.wikipedia.org/wiki/Taxicab_number" rel="nofollow"><strong>Taxicab numbers</strong></a> are VERY far apart. You can do some math tricks to solve it. For example, you can be checking the <a href="https://en.wikipedia.org/wiki/Euler%27s_sum_of_powers_conjecture" rel="nofollow...
0
2016-09-06T19:50:42Z
[ "python", "for-loop", "nested" ]
Finding "taxiNumber" program, want to exchange nested for loop for optimization reasons
39,355,781
<p>I just started programming 1 week ago so please forgive the chaos you are about to see I'm trying to find the first x taxi numbers but with my "nested for loop" the program takes ages to go through all possibilities. Taxi number: if there is a number a^3+b^3 that is equal to c^3+d^3 that sum is a taxinumber. Exampl...
0
2016-09-06T18:40:19Z
39,377,634
<pre><code>import math def main(): numbersOfResultsToFind = getNumberOfTaxisToFind() foundResults = 0 numberToCheck = 1 while(foundResults &lt; numbersOfResultsToFind): result = getTaxi(numberToCheck) if len(result) &gt; 1: foundResults = foundResults + 1 ...
0
2016-09-07T19:24:09Z
[ "python", "for-loop", "nested" ]
Django model where field is based on another field unless specified otherwise
39,355,835
<p>Say I have a django model called <strong>Car</strong> and another called <strong>UserCar</strong> which has a related car object.</p> <pre><code>class Car(models.Model): name = models.CharField(max_length=100) mpg = models.DecimalField(max_digits=6, decimal_places=2, null=True) class UserCar(models.Model):...
2
2016-09-06T18:43:19Z
39,355,951
<p>Try using the following:</p> <pre><code>class UserCar(models.Model): ... # your fields here # Override the save function here def save(self, *args, **kwargs): if self.mpg is None: self.mpg = self.car.mpg super(UserCar, self).save(*args, **kwargs) </code></pre>
2
2016-09-06T18:51:06Z
[ "python", "django", "django-models" ]
function decorators to specify the first two lines of the def?
39,355,848
<p>I'm on python 3.5:</p> <p>I have a repeating pattern in some of my python functions. For a large collection of classes the first two lines are:</p> <pre><code>obj_a = &lt;..... obtain something I need.....&gt; obj_b = &lt;..... obtain another thing I need....&gt; </code></pre> <p>I'm simplifying it here, but the ...
2
2016-09-06T18:44:03Z
39,355,916
<p><code>obj_a</code> and <code>obj_b</code> sound a lot like state.</p> <pre><code>class Thing: def __init__(self): # These could also be class attributes instead # if they can be initialized when Thing is first # defined. self.obj_a = ... self.obj_b = ... def foo(self...
1
2016-09-06T18:48:24Z
[ "python", "python-3.x" ]
function decorators to specify the first two lines of the def?
39,355,848
<p>I'm on python 3.5:</p> <p>I have a repeating pattern in some of my python functions. For a large collection of classes the first two lines are:</p> <pre><code>obj_a = &lt;..... obtain something I need.....&gt; obj_b = &lt;..... obtain another thing I need....&gt; </code></pre> <p>I'm simplifying it here, but the ...
2
2016-09-06T18:44:03Z
39,355,941
<p>You can put those two objects in a base class as:</p> <pre><code>class TheBaseClass: obj1 = something obj2 = something_else </code></pre> <p>and inherit this in the functions of classes you need:</p> <pre><code>class Class1(TheBaseClass): def func1(self): a = self.obj1 # make use of it ...
-3
2016-09-06T18:50:11Z
[ "python", "python-3.x" ]
function decorators to specify the first two lines of the def?
39,355,848
<p>I'm on python 3.5:</p> <p>I have a repeating pattern in some of my python functions. For a large collection of classes the first two lines are:</p> <pre><code>obj_a = &lt;..... obtain something I need.....&gt; obj_b = &lt;..... obtain another thing I need....&gt; </code></pre> <p>I'm simplifying it here, but the ...
2
2016-09-06T18:44:03Z
39,357,241
<p>You could do something like the following which creates variables that will effectively become local to the function when it's called. This uses <code>eval()</code> which can be unsafe if used on untrusted input, but that is not the case here where it's being used to execute the compiled byte-code of a decorated fun...
-1
2016-09-06T20:22:33Z
[ "python", "python-3.x" ]
function decorators to specify the first two lines of the def?
39,355,848
<p>I'm on python 3.5:</p> <p>I have a repeating pattern in some of my python functions. For a large collection of classes the first two lines are:</p> <pre><code>obj_a = &lt;..... obtain something I need.....&gt; obj_b = &lt;..... obtain another thing I need....&gt; </code></pre> <p>I'm simplifying it here, but the ...
2
2016-09-06T18:44:03Z
39,357,412
<p>You may consider using <em>callable classes</em> instead of functions, this way you could keep the boilerplate in one place, and implement the other stuff as subclasses of that base. </p> <pre><code>class BaseFoo: def __init__(self): # self.obj_a = &lt;..... obtain something I need.....&gt; # ...
0
2016-09-06T20:34:14Z
[ "python", "python-3.x" ]
Is there a way to change a matching object returned from a regex.search() function?
39,355,887
<p>I am new to coding and made up a project for my self to start learning, but I could'nt get around this problem. i am trying to make a little tool which converts stuff from the clipboard(which for now I will simply use a string called <code>spam</code>) so that the sentences start with a capital letter, and in which ...
0
2016-09-06T18:46:15Z
39,356,587
<p>There are several errors (or awkwardnesses) in your code.</p> <p>Here is a quick code review:</p> <pre><code>import re spam = 'this is a string which i want to correct. as you can see.' def capital(lists): # finds out where to change the text. dot_regex = re.compile(r'\. ') question_regex = re.compil...
1
2016-09-06T19:37:38Z
[ "python", "regex" ]
How to use end="" snippet to create a bowling scoreboard
39,356,123
<p>I am trying to create a python program that will read in a Bowling score composed of number of pins knocked out for each toss. I am trying to create an output that looks similar to a bowling scoreboard like this:</p> <pre><code> 1 2 3 4 5 6 7 8 9 10 +---+---+---+---+---+---+---+---+---+-----+ |8...
0
2016-09-06T19:03:22Z
39,356,451
<p>Once you've invoked <code>\n</code>, you can never go back and modify that line again. What you want to do is build 4 strings, and then print all in succession at the end:</p> <pre><code>def addEndCaps(lines): lines[1] += "+" lines[2] += "|" lines[3] += "|" lines[4] += "+" lines = [ "", "", "", "",...
0
2016-09-06T19:27:39Z
[ "python" ]
How to remap ids to consecutive numbers quickly
39,356,279
<p>I have a large csv file with lines that looks like</p> <pre><code>stringa,stringb stringb,stringc stringd,stringa </code></pre> <p>I need to convert it so the ids are consecutively numbered from 0. In this case the following would work</p> <pre><code>0,1 1,2 3,0 </code></pre> <p>My current code looks like:</p> ...
6
2016-09-06T19:14:20Z
39,356,398
<p><strong>UPDATE:</strong> here is a memory saving solution, which converts all your string to numerical categories:</p> <pre><code>In [13]: df Out[13]: c1 c2 0 stringa stringb 1 stringb stringc 2 stringd stringa 3 stringa stringb 4 stringb stringc 5 stringd stringa 6 stringa stringb 7 st...
2
2016-09-06T19:23:04Z
[ "python", "pandas", "dataframe" ]
How to remap ids to consecutive numbers quickly
39,356,279
<p>I have a large csv file with lines that looks like</p> <pre><code>stringa,stringb stringb,stringc stringd,stringa </code></pre> <p>I need to convert it so the ids are consecutively numbered from 0. In this case the following would work</p> <pre><code>0,1 1,2 3,0 </code></pre> <p>My current code looks like:</p> ...
6
2016-09-06T19:14:20Z
39,356,454
<p>You can use <code>factorize</code> if you want an array of id's: </p> <pre><code>df = pd.read_csv(data, header=None, prefix='Col_') print (pd.factorize(np.hstack(df.values))) (array([0, 1, 1, 2, 3, 0]), array(['stringa', 'stringb', 'stringc', 'stringd'], dtype=object)) </code></pre> <hr> <p><strong>EDIT :</stron...
3
2016-09-06T19:27:51Z
[ "python", "pandas", "dataframe" ]
How to remap ids to consecutive numbers quickly
39,356,279
<p>I have a large csv file with lines that looks like</p> <pre><code>stringa,stringb stringb,stringc stringd,stringa </code></pre> <p>I need to convert it so the ids are consecutively numbered from 0. In this case the following would work</p> <pre><code>0,1 1,2 3,0 </code></pre> <p>My current code looks like:</p> ...
6
2016-09-06T19:14:20Z
39,356,608
<pre><code>df = pd.DataFrame([['a', 'b'], ['b', 'c'], ['d', 'a']]) v = df.stack().unique() v.sort() f = pd.factorize(v) m = pd.Series(f[0], f[1]) df.stack().map(m).unstack() </code></pre> <p><a href="http://i.stack.imgur.com/eTlHI.png"><img src="http://i.stack.imgur.com/eTlHI.png" alt="enter image description here">...
7
2016-09-06T19:38:55Z
[ "python", "pandas", "dataframe" ]
Urllib2: get content of html page
39,356,334
<p>I need to parse information from some urls:</p> <pre><code>http://novosibirsk.baza.drom.ru/personal/actual/bulletins http://drom.ru http://novosibirsk.baza.drom.ru http://moscow.drom.ru/volvo/xc70/21914186.html http://novosibirsk.baza.drom.ru/personal/actual/bulletins http://novosibirsk.baza.drom.ru/kolpaki-reno-r1...
0
2016-09-06T19:17:48Z
39,356,616
<p>Step 1: can you access site from browser? (if no, goto step 4)</p> <p>Step 2: can you access site from command-line such as wget, curl, etc.? (if no, goto step 4)</p> <p>Step 3: Check for proxy issues/try a different library like <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a></p> ...
0
2016-09-06T19:39:59Z
[ "python", "html", "urllib2" ]
Urllib2: get content of html page
39,356,334
<p>I need to parse information from some urls:</p> <pre><code>http://novosibirsk.baza.drom.ru/personal/actual/bulletins http://drom.ru http://novosibirsk.baza.drom.ru http://moscow.drom.ru/volvo/xc70/21914186.html http://novosibirsk.baza.drom.ru/personal/actual/bulletins http://novosibirsk.baza.drom.ru/kolpaki-reno-r1...
0
2016-09-06T19:17:48Z
39,360,830
<p>Using <code>requests</code> will make it more easier. If you dont have <code>requests</code> module installed, try to install it by <code>pip install requests</code></p> <pre><code>import requests if 'drom.ru' in url: r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') # lxml works faster ...
0
2016-09-07T03:35:17Z
[ "python", "html", "urllib2" ]
Submitting a form fails, but because views.auth_login (not related to my form) didn't return an HttpResponse object
39,356,355
<p>OK, so I have a functional auth_login setup. But it's unrelated to my <code>Articles</code> model, and <code>ArticleForm</code> ModelForm. However, when I try to create a new article on the local website, I get an error related to views.auth_login even though auth_login isn't referenced anywhere (to my knowledge) in...
1
2016-09-06T19:19:45Z
39,356,515
<p>Well your form is submitting to the root of your website, so that's why it's hitting <code>auth_login</code> instead of <code>add_article</code>.</p> <p>Change <code>&lt;form action="/" method="post"&gt;</code> to just <code>&lt;form method="POST"&gt;</code>. I assume the other error (no HttpResponse object) is jus...
2
2016-09-06T19:32:03Z
[ "python", "django" ]
How to add a custom CA Root certificate to the CA Store used by Python in Windows?
39,356,413
<p>I just installed Python3 from python.org and am having trouble installing packages with <code>pip</code>. By design, there is a man-in-the-middle packet inspection appliance on the network here that inspects all packets (ssl included) by resigning all ssl connections with its own certificate. Part of the GPO pushe...
2
2016-09-06T19:24:30Z
39,358,282
<p>Run: python -c "import ssl; print(ssl.get_default_verify_paths())" to check the current paths which are used to verify the certificate. Add your companies root certificate to one of those.</p> <p>The path openssl_capath_env points to the enviroment variable: 'SSL_CERT_DIR'. You need to create an environment variabl...
2
2016-09-06T21:43:16Z
[ "python", "windows", "ssl" ]
Write multiple values in a csv cell without brackets in python
39,356,469
<p>I have a list of objects. Each object have different attributes. One of which is a list I would like to export this objects to a csv file that looks like</p> <pre><code>a, "1,2,3" b,"1,2,3" </code></pre> <p>so that the csv is readable in a Excel program</p> <p>My code looks something like this:</p> <pre><code>fi...
1
2016-09-06T19:28:35Z
39,356,543
<p>if you do that:</p> <pre><code> final_list.append(first_value) final_list.append(list2) </code></pre> <p>you create a row with a value and a list.</p> <p>The <code>csv</code> module performs a <code>str</code> conversion when writing, which explains you see the string as it is printed when you debug in pyt...
2
2016-09-06T19:33:35Z
[ "python", "excel", "csv" ]
efficient filtering near/inside clusters after they found - python
39,356,509
<p>essentially I applied a <code>DBSCAN</code> algorithm (<code>sklearn</code>) with an euclidean distance on a subset of my original data. I found my clusters and all is fine: except for the fact that I want to keep only values that are far enough from those on which I did not run my analysis on. I have a new distance...
1
2016-09-06T19:31:43Z
39,358,875
<p>If you need exact answers, the fastest implementation should be sklearn's pairwise distance calculator: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distanc...
1
2016-09-06T22:47:01Z
[ "python", "scikit-learn", "cluster-computing", "dbscan" ]
efficient filtering near/inside clusters after they found - python
39,356,509
<p>essentially I applied a <code>DBSCAN</code> algorithm (<code>sklearn</code>) with an euclidean distance on a subset of my original data. I found my clusters and all is fine: except for the fact that I want to keep only values that are far enough from those on which I did not run my analysis on. I have a new distance...
1
2016-09-06T19:31:43Z
39,361,907
<p>Of course you can vectoriue this, but it will then still be O(n*m). Better neighbor search algorithms are not vectorized. e.g. kd-tree and ball-tree.</p> <p>Both are available in sklearn, and used by the DBSCAN module. Please see the <a href="http://scikit-learn.org/stable/modules/neighbors.html" rel="nofollow"><co...
1
2016-09-07T05:37:48Z
[ "python", "scikit-learn", "cluster-computing", "dbscan" ]
Obtain csv-like parse AND line length byte count?
39,356,610
<p>I'm familiar with the <code>csv</code> Python module, and believe it's necessary in my case, as I have some fields that contain the delimiter (<code>|</code> rather than <code>,</code>, but that's irrelevant) within quotes.</p> <p>However, I am also looking for the byte-count length of each original row, <em>prior<...
1
2016-09-06T19:39:20Z
39,358,339
<p>Depending on performance requirements and the size of the data, the low tech solution is to simply read the file twice. Make a first pass where you get the length of each line, and then then you can run the data through the csv parser. On my somewhat outdated Mac I can read and count the length of 2-3 million lines ...
2
2016-09-06T21:47:51Z
[ "python", "csv" ]
Obtain csv-like parse AND line length byte count?
39,356,610
<p>I'm familiar with the <code>csv</code> Python module, and believe it's necessary in my case, as I have some fields that contain the delimiter (<code>|</code> rather than <code>,</code>, but that's irrelevant) within quotes.</p> <p>However, I am also looking for the byte-count length of each original row, <em>prior<...
1
2016-09-06T19:39:20Z
39,358,721
<p>You can't subclass <code>_csv.reader</code>, but the <em><code>csvfile</code></em> argument to the <code>csv.reader()</code> <a href="https://docs.python.org/3/library/csv.html#csv.reader" rel="nofollow">constructor</a> only has to be a "file-like object". This means you could supply an instance of your own class th...
4
2016-09-06T22:29:20Z
[ "python", "csv" ]
Python script works in bash, but not when called from R via system
39,356,621
<p>I use Ubuntu 16.04. I'm trying to run a simple python script from R. The script is</p> <pre><code> import numpy as np x=1 print(x) </code></pre> <p>and is written in a file named code.py. It works fine if I call it in bash via</p> <pre><code> python3.5 code.py </code></pre> <p>However, when I call ...
1
2016-09-06T19:40:13Z
39,395,286
<p>The problem is that you have two versions of python3 on your computer: The system default (Ubuntu, I'm assuming), and the one you installed (Anaconda3).</p> <p>When you run it from the command-line, you are using the Anaconda3 environment (which includes numpy and all the other anaconda modules). When you run it fr...
1
2016-09-08T15:47:12Z
[ "python", "bash", "shell" ]
What is the purpose of using instance of a class as a super/base class?
39,356,625
<p>What is the purpose of subclassing an instance of a class in Python? Here's an example: </p> <pre><code>class A: def __init__(*args): print(args) base = A() class Test(base): pass </code></pre> <p>This code works properly under Python, but <code>base</code> is an instance of class <code>A</code> (1) <str...
0
2016-09-06T19:40:29Z
39,358,372
<p>Python actually uses <code>type(base)(classname, bases, body)</code> to produce the class object. This is the normal metaclass invocation (unless the class specifies a specific metaclass directly).</p> <p>For an <em>instance</em> (or a module, which is basically an instance too), that means the class <code>__new__<...
1
2016-09-06T21:50:25Z
[ "python", "class", "inheritance", "python-internals" ]
splitting string using regular expression in python
39,356,631
<p>Hi guys I want to split the following string that are parsed from a text file using perhaps regular expression in python.</p> <pre><code>Inside the text file(filename.txt) iPhone.Case.1.left=1099.0.2 new.phone.newwork=bla.jpg </code></pre> <p>I want a function that when looping through arrayOfStrings wii split it...
1
2016-09-06T19:41:10Z
39,356,901
<p>Try this :</p> <pre><code>% python &gt;&gt;&gt; import re &gt;&gt;&gt; arrayOfStrings =["iPhone.Case.1.left=1099.0.2", " new.phone.newwork=bla.jpg"] &gt;&gt;&gt; def printStuff(arg): ... for i,x in enumerate(arg): &gt;&gt;&gt; print(arg[i].split('=')[i].split('.') + [ arg[i].split('=')[1] ]) ... &gt;&gt...
0
2016-09-06T19:58:40Z
[ "python", "regex", "python-2.7" ]
splitting string using regular expression in python
39,356,631
<p>Hi guys I want to split the following string that are parsed from a text file using perhaps regular expression in python.</p> <pre><code>Inside the text file(filename.txt) iPhone.Case.1.left=1099.0.2 new.phone.newwork=bla.jpg </code></pre> <p>I want a function that when looping through arrayOfStrings wii split it...
1
2016-09-06T19:41:10Z
39,356,999
<p>If you have regular enough input data that you can always split first at the <code>=</code> character, then split the first half at every <code>.</code> character, I would skip regex entirely, as it is complicated and not very pretty to read.</p> <p>Here's an example of doing just that:</p> <pre><code>s = 'new.pho...
1
2016-09-06T20:04:51Z
[ "python", "regex", "python-2.7" ]
Is there a way to turn off Scientific Notation for Mpld3 plugins
39,356,654
<p>I want to use mpld3's MousePosition plugin to display the pixel location of my cursor. This works great, but I can't figure out how to turn off scientific notation in the plugin. Pixels > 1000 are displayed in scientific notation.</p> <p>My code: </p> <pre><code>import mpld3 from mpld3 import plugins mpld3.enabl...
0
2016-09-06T19:42:52Z
39,577,557
<p>There is a property for display format </p> <pre><code>plugins.connect(fig, plugins.MousePosition(fmt="f")) </code></pre> <p>This will display the mouse position in integer format (a float with no decimal units of precision). fmt=".1f" will display the location with 1 decimal place of precision.</p> <p>Ref: <a ...
0
2016-09-19T16:10:21Z
[ "python", "matplotlib", "jupyter-notebook", "mpld3" ]
Webscraping the Indian Patent Website for patent data
39,356,677
<p>I am trying to write a webscraper for the <a href="http://ipindiaservices.gov.in/publicsearch/" rel="nofollow">Indian patent search website</a> to get data about patents. Here is the code that I have so far.</p> <pre><code>#import the necessary modules import urllib2 #import the beautifulsoup functions to parse the...
2
2016-09-06T19:44:12Z
39,359,152
<p>You can do this with just <em>requests</em>. The post is to <em><a href="http://ipindiaservices.gov.in/publicsearch/resources/webservices/search.php" rel="nofollow">http://ipindiaservices.gov.in/publicsearch/resources/webservices/search.php</a></em> with one <em>param</em> <em>rc_</em> which is a timestamp that we c...
4
2016-09-06T23:22:29Z
[ "python", "python-2.7", "web-scraping", "beautifulsoup" ]
Call python script from vba with wsh
39,356,710
<p>I need to call a python script from vba which works fine by using the shell.</p> <pre><code>Sub CallPythonScript() Call Shell("C:\Program Files (x86)\Python27\python.exe C:\Users\Markus\BrowseDirectory.py") End Sub </code></pre> <p>But when I try using wsh (because of the wait funcionality) it just won't...
2
2016-09-06T19:46:29Z
39,356,767
<p>Did you verify that path takes you directly to the interpreter?</p> <p>Try this,</p> <pre><code>Dim myApp As String: myApp = "C:\""Program Files (x86)""\Python27\python.exe C:\Users\Markus\BrowseDirectory.py" </code></pre>
0
2016-09-06T19:50:33Z
[ "python", "vba", "excel-vba", "wsh" ]