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
Using a shift() function within an apply function to compare rows in a Pandas Dataframe
37,967,070
<p>I would like to use <code>shift()</code> to pull in data from the previous index, provided values in one of the columns, <code>Letter</code>, is the same.</p> <pre><code>import pandas as pd df = pd.DataFrame(data=[['A', 'one'], ['A', 'two'], ['B', 'three'], ...
2
2016-06-22T11:43:53Z
37,967,747
<p>You are trying to apply .shift() to a value of a given column of a given row instead of a Series. I would do this, using groupby: </p> <pre><code>In [6]: df['Previous letter'] = df.groupby('Letter').value.shift() In [7]: df Out[7]: Letter value Previous letter 0 A one NaN 1 A two ...
1
2016-06-22T12:15:26Z
[ "python", "python-2.7", "pandas" ]
plot the relationship between two variables with pandas
37,967,151
<p>I am new to python but am aware about the usefulness of <strong>pandas</strong>, thus I would like to kindly ask if someone can help me to use pandas in order to address the below problem. </p> <p>I have a dataset with buses, which looks like:</p> <pre><code>BusModel;BusID;ModeName;Value;Unit;UtcTime Alpha;0001;En...
2
2016-06-22T11:47:20Z
37,967,860
<p>Start with the following interactive mode</p> <pre><code>import pandas as pd df = pd.read_csv('bus.csv', sep=";", parse_dates=['UtcTime']) </code></pre> <p>You should be able to start playing around with the <code>DataFrame</code> and discovering functions you can directly use with the data. To get a list of buse...
2
2016-06-22T12:20:07Z
[ "python", "pandas", "data-visualization" ]
plot the relationship between two variables with pandas
37,967,151
<p>I am new to python but am aware about the usefulness of <strong>pandas</strong>, thus I would like to kindly ask if someone can help me to use pandas in order to address the below problem. </p> <p>I have a dataset with buses, which looks like:</p> <pre><code>BusModel;BusID;ModeName;Value;Unit;UtcTime Alpha;0001;En...
2
2016-06-22T11:47:20Z
37,968,120
<p>If you really want to use pandas, remember this simple thing: <strong>never use a loop</strong>. Loops aren't scalable, so try to use built-in functions. First let's read your dataframe:</p> <pre><code>import pandas as pd data = pd.read_csv('bus.csv',sep = ';') </code></pre> <p>Here is the weak point of my answer,...
1
2016-06-22T12:32:36Z
[ "python", "pandas", "data-visualization" ]
'Graph' object has no attribute 'SerializeToString' on Windows Docker
37,967,170
<p>I'm trying to run tutorials : <a href="https://www.tensorflow.org/versions/master/tutorials/mnist/tf/index.html" rel="nofollow">https://www.tensorflow.org/versions/master/tutorials/mnist/tf/index.html</a></p> <p>I got below error message:</p> <pre><code>root@db411995c219:~/pjh# python fully_connected_feed.py Extr...
0
2016-06-22T11:48:07Z
37,981,423
<p>I found the solution by myself.</p> <pre><code>FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd vdocker') DO %i docker run -it tensorflow/tensorflow:r0.9-devel </code></pre> <p>And the tag list is on this site: <br> <a href="https://hub.docker.com/r/tensorflow/tensorflow/" rel="nofollow">https://hub.do...
0
2016-06-23T02:37:38Z
[ "python", "windows", "docker", "tensorflow" ]
How to extract specific content, like name or DOB, from a document using NLP and python?
37,967,282
<p>I want to extract very specific content like name, address and dob from a document (say for example, a resume). Assuming I have 1000 of such documents, I want to automate it using machine learning and natural language processing. And preferably python.<br> How can I do that? or Where do I start?</p> <p>Update: I am...
0
2016-06-22T11:52:43Z
37,968,406
<p>I think that what you are looking for, is what is known in NLP as Named Entity recognition (NER). </p> <p>Actually, an Entity can be the a person name, a place name a campany name etc..</p> <p>You can look at this stackOverFlow <a href="http://stackoverflow.com/questions/37853877/python-frameworks-for-nlp/37863761...
0
2016-06-22T12:43:55Z
[ "python", "machine-learning", "nlp" ]
Find entries of one text file in another file in python
37,967,337
<p>I have two files. File <strong>A</strong> has some entries in each line and I need to find if any entry is found in File <strong>B</strong>. Here is my script (using two functions):</p> <pre><code>def readB(x): with open('B.txt') as resultFile: for line in resultFile: if x in line: print x ...
0
2016-06-22T11:55:52Z
37,967,510
<p>You don't necessarily need to define functions to do this</p> <pre><code>with open('a.txt') as a, open('b.txt') as b: result = set(a.readlines()) &amp; set(b.readlines()) </code></pre> <p>If they both have the same line, it will return them in a set.</p> <p>If you <em>really</em> wanted a function, you could ...
0
2016-06-22T12:04:27Z
[ "python", "string", "compare", "readfile" ]
Find entries of one text file in another file in python
37,967,337
<p>I have two files. File <strong>A</strong> has some entries in each line and I need to find if any entry is found in File <strong>B</strong>. Here is my script (using two functions):</p> <pre><code>def readB(x): with open('B.txt') as resultFile: for line in resultFile: if x in line: print x ...
0
2016-06-22T11:55:52Z
37,970,855
<h1>Strip the entries from newlines</h1> <p>Python includes newlines when you read lines - your first entry is read as <code>1223232\n</code>. Strip the newline and it will work.</p> <pre><code>def readA(): with open('A.txt') as bondNumberFile: for line in bondNumberFile: readB(line.rstrip()) ...
0
2016-06-22T14:20:50Z
[ "python", "string", "compare", "readfile" ]
Pressing button in QFileDialog popup exits application
37,967,390
<p>I made the transition from <code>PyQt4</code>to <code>PyQt5</code>. My app (created with QtDesigner) has a checkbox which enables a "Save" button, in case you want to save your file. In <code>PyQt4</code> the dialog would open, I'd choose my file, press OK, done. I implemented a check on the OK button of the main ap...
0
2016-06-22T11:58:52Z
38,048,658
<p>I finally found the (very small) error:</p> <p>While <code>PyQt4</code> apparently writes the path automatically as <code>string</code>, <code>PyQt5</code> does not. </p> <p>I changed</p> <pre><code>self.ui.savepath_label.setText(path) </code></pre> <p>into </p> <pre><code>self.ui.savepath_label.setText(str(pat...
0
2016-06-27T08:00:11Z
[ "python", "qt", "pyqt", "pyqt5", "qfiledialog" ]
Pressing button in QFileDialog popup exits application
37,967,390
<p>I made the transition from <code>PyQt4</code>to <code>PyQt5</code>. My app (created with QtDesigner) has a checkbox which enables a "Save" button, in case you want to save your file. In <code>PyQt4</code> the dialog would open, I'd choose my file, press OK, done. I implemented a check on the OK button of the main ap...
0
2016-06-22T11:58:52Z
38,049,396
<p>The PyQt4 provides two different APIs:</p> <ul> <li>API v1 uses the Qt types for objects, so you have to pass things like <code>QString</code> to the <code>setText</code> method</li> <li>API v2 instead uses python types and the methods of the Qt objects automatically convert those python types into their Qt variant...
0
2016-06-27T08:42:46Z
[ "python", "qt", "pyqt", "pyqt5", "qfiledialog" ]
Why there are two different results on different metrics in Sklearn
37,967,391
<p>what are the difference between (recall, precison, fi-score) in metrics.classification_report and same metriceses when I use them separately by metrics.precision_score, metrics.recall_score, metrics.f1 score. </p> <p>Can please someone look at this code and explain the difference</p> <pre><code>from sklearn.svm im...
0
2016-06-22T11:58:58Z
37,969,612
<p>precision_score <strong>is not an average</strong>, it is precision where one of the classes is the positive one (in your case - Diabetes), this is why your call to precision corresponds to precision of Diabetes in the summary, and similarly - recall and f1 of these guys. Taking an average of the asymetric metric is...
1
2016-06-22T13:30:47Z
[ "python", "python-2.7", "python-3.x", "scikit-learn", "confusion-matrix" ]
Why there are two different results on different metrics in Sklearn
37,967,391
<p>what are the difference between (recall, precison, fi-score) in metrics.classification_report and same metriceses when I use them separately by metrics.precision_score, metrics.recall_score, metrics.f1 score. </p> <p>Can please someone look at this code and explain the difference</p> <pre><code>from sklearn.svm im...
0
2016-06-22T11:58:58Z
37,984,504
<p>See the <a href="http://scikit-learn.org/stable/modules/model_evaluation.html#precision-recall-f-measure-metrics" rel="nofollow">documentation on these metrics</a>.</p>
0
2016-06-23T07:07:05Z
[ "python", "python-2.7", "python-3.x", "scikit-learn", "confusion-matrix" ]
How can I find a URL in a span that in a div?
37,967,407
<p>I am trying to find a URL thats in a span, which is in a div. </p> <p>In this case, its the link with the class "company_url" that I'm after.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override">...
1
2016-06-22T11:59:47Z
37,967,893
<p>You need to use two <code>//</code>:</p> <pre><code>'.//span[@class="link"]/a[@class="company_url"]/@href' </code></pre> <p>Once you do you will get your url:</p> <pre><code>In [2]: from lxml import html In [3]: x = html.fromstring(h) In [4]: d = x.xpath('//div[@class="links standard"]')[0] In [5]: d Out[5]: &...
1
2016-06-22T12:21:50Z
[ "python", "xpath", "scrapy" ]
How can I change the linecolor if y-value changes
37,967,521
<p>I'm using pylab to plot some graphs Say I want to plot this:</p> <pre><code>x = [0,1,2,3,4,5,6,7,8,9,10] y = [0,0,0,1,1,0,0,1,0,0,0] plt.plot(x,y,'g') plt.show() </code></pre> <p>But every time [y = 1] I want to change the color of the line to red. </p> <p>Is this possible?</p> <p><a href="http://i.stack.imgur....
4
2016-06-22T12:05:11Z
37,970,353
<p>Inspired by <a href="http://stackoverflow.com/questions/21352580/matplotlib-plotting-numerous-disconnected-line-segments-with-different-colors">this answer</a>:</p> <pre><code>from matplotlib import collections as mc from matplotlib import pyplot as plt x = [0,1,2,3,4,5,6,7,8,9,10] y = [0,0,0,1,1,0,0,1,0,0,0] de...
2
2016-06-22T14:01:23Z
[ "python", "python-3.x", "matplotlib" ]
How can I change the linecolor if y-value changes
37,967,521
<p>I'm using pylab to plot some graphs Say I want to plot this:</p> <pre><code>x = [0,1,2,3,4,5,6,7,8,9,10] y = [0,0,0,1,1,0,0,1,0,0,0] plt.plot(x,y,'g') plt.show() </code></pre> <p>But every time [y = 1] I want to change the color of the line to red. </p> <p>Is this possible?</p> <p><a href="http://i.stack.imgur....
4
2016-06-22T12:05:11Z
37,970,552
<p>Good answer by @michael_j_ward (+1). Just to give an alternative using the normal plot commands this is also a possible solution.</p> <p>The first thing you need to take into account is that you need to transform your data from what you have:</p> <pre><code>x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y = [0, 0, 0, 1, 1...
0
2016-06-22T14:09:31Z
[ "python", "python-3.x", "matplotlib" ]
Python. How to find all occurrences of matched substring?
37,967,613
<p>I have a big string - html page. I need to find all names of flash drives, i.e. I need to get content between double quotes: <code>data-name="USB Flash-drive Leef Fuse 32Gb"&gt;</code>. So I need a string between <code>data-name="</code> and <code>"&gt;</code>. Please, don't mention BeautifulSoup, I need to do it wi...
-2
2016-06-22T12:09:17Z
37,968,090
<p>py2: <a href="https://docs.python.org/2/library/htmlparser.html" rel="nofollow">https://docs.python.org/2/library/htmlparser.html</a></p> <p>py3: <a href="https://docs.python.org/3/library/html.parser.html" rel="nofollow">https://docs.python.org/3/library/html.parser.html</a></p> <hr> <pre><code>from html.parser ...
2
2016-06-22T12:31:16Z
[ "python", "regex", "python-3.x", "html-parsing" ]
Python. How to find all occurrences of matched substring?
37,967,613
<p>I have a big string - html page. I need to find all names of flash drives, i.e. I need to get content between double quotes: <code>data-name="USB Flash-drive Leef Fuse 32Gb"&gt;</code>. So I need a string between <code>data-name="</code> and <code>"&gt;</code>. Please, don't mention BeautifulSoup, I need to do it wi...
-2
2016-06-22T12:09:17Z
37,968,407
<p>If you want to do it with basic python string parsing here is a way</p> <pre><code>s="html string" start = s.find('data-name="') end = s.find('"&gt;') output = s[start:end] </code></pre> <p>This is what happens in my python shell</p> <pre><code>&gt;&gt;&gt; s='junk...data-name="USB Flash-drive Leef Fuse 32Gb"&gt;...
0
2016-06-22T12:43:57Z
[ "python", "regex", "python-3.x", "html-parsing" ]
Folium: Circle Marker from GeoJson
37,967,664
<p>I would like to represent points from geojson file on a map as circle markers, not as simple markers, which are shown by default. </p> <p>The following command would add simple markers:</p> <pre><code>folium.GeoJson(geojson_file).add_to(map) </code></pre> <p>How should I change them to circle markers. I don't wan...
0
2016-06-22T12:11:10Z
38,013,995
<p>You can try something like this (using example from Leaflet API) More on that topic here <a href="http://leafletjs.com/reference.html#geojson" rel="nofollow">http://leafletjs.com/reference.html#geojson</a></p> <pre><code> function style (feature, latlng) { return L.circleMarker(latlng, { ...
0
2016-06-24T12:56:33Z
[ "python", "circle", "geojson", "marker", "folium" ]
How can I count coherent values that are less than a specific number?
37,967,740
<p>I need to handle some hourly weather data from CSV files with 8,760 values per column. For example I need to plot a histogram with the longest coherent calms of wind speed, which means less than 3 m/s. I have already created a histogram with the wind speed distribution but this one is way harder. So I need some kin...
0
2016-06-22T12:15:05Z
37,992,315
<p>I didn't expect somebody would write the code for me, sorry if it seems like that. I just asked for an idea but I think I almost got it. Here is my code so far, it should create a vector for every calm and put it into a dictionary. It works but every key is filled by the same vector and I'm not sure how to fix this...
0
2016-06-23T12:56:32Z
[ "python" ]
Infinite Web Scrapping Twitter
37,967,778
<p>I'm trying to web scrap Twitter using Python 3.X but I only collect the last 20 tweets of my request. I would like to collect whole data of a request between 2006 and now. For this I think to have create two more function : one which will collect the last tweets and one which will collect the current tweets ? And ...
0
2016-06-22T12:16:48Z
38,585,571
<p>I found a good solution based on this webpage:</p> <p><a href="http://ataspinar.com/2015/11/09/collecting-data-from-twitter/" rel="nofollow">http://ataspinar.com/2015/11/09/collecting-data-from-twitter/</a></p> <p>What I did was creating a variable called max_pos where I stored this string:</p> <pre><code>'&amp;m...
0
2016-07-26T09:07:03Z
[ "python", "twitter", "web-scraping" ]
Short way to do os.path.join()
37,967,815
<p>I'm really tired of typing <code>os.path.join()</code> each time I have to construct a path and I was thinking of defining a shortcut like this one:</p> <pre><code>def pj(*args): from os.path import join return join(args) </code></pre> <p>But it throws <code>TypeError: join() argument must be str or bytes,...
0
2016-06-22T12:18:30Z
37,967,847
<p>You should <em>unpack</em> the arguments to <code>.join</code>:</p> <pre><code>join(*args) # ^ </code></pre> <p>Like so:</p> <pre><code>&gt;&gt;&gt; import os.path.join &gt;&gt;&gt; args = ('/usr/main/', 'etc/negate/') &gt;&gt;&gt; os.path.join(*args) '/usr/main/etc/negate/' </code></pre> <p>P.S.: Using <code...
3
2016-06-22T12:19:50Z
[ "python", "python-2.7", "python-3.x", "os.path" ]
Short way to do os.path.join()
37,967,815
<p>I'm really tired of typing <code>os.path.join()</code> each time I have to construct a path and I was thinking of defining a shortcut like this one:</p> <pre><code>def pj(*args): from os.path import join return join(args) </code></pre> <p>But it throws <code>TypeError: join() argument must be str or bytes,...
0
2016-06-22T12:18:30Z
37,968,344
<p>If you're using Python 3.4, you could give <a href="https://docs.python.org/3/library/pathlib.html" rel="nofollow">pathlib</a> a try.</p> <p>From the doc:</p> <pre><code>&gt;&gt;&gt; p = Path('/etc') &gt;&gt;&gt; q = p / 'init.d' / 'reboot' &gt;&gt;&gt; q PosixPath('/etc/init.d/reboot') </code></pre>
1
2016-06-22T12:41:32Z
[ "python", "python-2.7", "python-3.x", "os.path" ]
How to add a column to a Pandas dataframe made of arrays of the n-preceding values of another column?
37,967,824
<p>I am new to python and pandas. I don't know how to solve the following problem <em>in an elegant way</em>.</p> <p>Let's say we have a simple pandas dataframe.</p> <pre><code>import numpy as np import pandas as pd from pandas import DataFrame, Series df = pd.DataFrame(np.arange(0,60,10), columns=['Value']) </code><...
2
2016-06-22T12:18:49Z
37,969,355
<p>We can use a <code>df.shift</code> to generate the offset columns and a list comprehension to group them together then <code>map</code> to generate a <code>list</code> of <code>lists</code> for the <code>dataframe</code>. However, the <code>list</code> of <code>lists</code> generated will need to be transposed first...
1
2016-06-22T13:21:06Z
[ "python", "arrays", "pandas", "dataframe" ]
How to add a column to a Pandas dataframe made of arrays of the n-preceding values of another column?
37,967,824
<p>I am new to python and pandas. I don't know how to solve the following problem <em>in an elegant way</em>.</p> <p>Let's say we have a simple pandas dataframe.</p> <pre><code>import numpy as np import pandas as pd from pandas import DataFrame, Series df = pd.DataFrame(np.arange(0,60,10), columns=['Value']) </code><...
2
2016-06-22T12:18:49Z
37,969,435
<p>This is a little gnarly to wrangle but the following works:</p> <pre><code>In [63]: def func(x): return pd.Series(df['Value'], index=np.arange(x.name-3,x.name)).values.tolist() df['ArrayValues'] = df[['Value']].apply(lambda x: func(x), axis=1) df ​ Out[63]: Value ArrayValues 0 0 [nan, nan, nan...
1
2016-06-22T13:23:46Z
[ "python", "arrays", "pandas", "dataframe" ]
Using CodeDeploy ValidateService Hook with Python Application
37,967,838
<p>I have an heavy app hosted on AWS. I use CodeDeploy &amp; Code Pipeline (updating from github) to update the servers when a new release is ready (currently running 6 ec2 instances on production environment).</p> <p>I've setup the codedeploy to operate one-by-one and also defined a 300 seconds connection draining on...
0
2016-06-22T12:19:23Z
37,980,335
<p>I would loop in the <code>ValidateService</code> hook, checking for the condition you expect, <strong>OR</strong> just sleep for 60 seconds, assuming that is the normal initialization time.</p> <p>The <code>ValidateService</code> hook should do just that: make sure the service is fully running before continuing/fin...
0
2016-06-23T00:26:17Z
[ "python", "amazon-web-services", "amazon-ec2", "aws-code-deploy", "aws-codepipeline" ]
Plot multiple lines at once, but all according to the current cycler state
37,967,940
<p>When I plot three lines in one go, matplotlib samples through three steps of the current cycler, giving each its own style:</p> <pre><code>In [11]: x = linspace(0, 5, 50) In [12]: y = vstack([x**2, x**3, x**4]).T In [13]: plot(x, y) Out[13]: [&lt;matplotlib.lines.Line2D at 0x7edfa9144550&gt;, &lt;matplotlib.lin...
1
2016-06-22T12:23:42Z
38,018,391
<p>Here via getting the current state: (Not pleasant, but not too cumbersome.)</p> <pre><code>In [94]: plt.plot(x, y[:,1:], c=plt.plot(x, y[:,0])[0].get_c()) </code></pre>
1
2016-06-24T16:45:38Z
[ "python", "matplotlib" ]
Issue saving post data with ajax and django
37,967,953
<p>Question I want to be able to save my partial '_dim' while viewing the main template 'sheet_form_create.html' for some reason I keep getting this error when posting the data to be saved for my '_dim' partial. Any help would be greatly appreciated. </p> <h1>Here is my error</h1> <pre><code>VariableDoesNotExist at /...
-1
2016-06-22T12:24:33Z
37,969,026
<p>When your <code>form</code> is <strong>invalid</strong>, you are not sending any <strong>context</strong> to the template:</p> <pre><code> dim_form = DimForm(request.POST) if dim_form.is_valid(): #... else: data = 'fail' return render(request, 'app/sheet_form_create.html') </code></pre> <p>S...
0
2016-06-22T13:08:46Z
[ "javascript", "python", "ajax", "django" ]
Issue saving post data with ajax and django
37,967,953
<p>Question I want to be able to save my partial '_dim' while viewing the main template 'sheet_form_create.html' for some reason I keep getting this error when posting the data to be saved for my '_dim' partial. Any help would be greatly appreciated. </p> <h1>Here is my error</h1> <pre><code>VariableDoesNotExist at /...
-1
2016-06-22T12:24:33Z
38,077,537
<p>Update your add_dimension() in views.py to this *this will take care of the sheet_form key and will also save correctly :)</p> <pre><code>def add_dimensions(request): if request.method == 'POST': c_date = datetime.now() u_date = datetime.now() description = request.POST.get('description') style = ...
1
2016-06-28T13:25:44Z
[ "javascript", "python", "ajax", "django" ]
Probability density function for a set of values using numpy
37,968,051
<p>Below is the data for which I want to plot the PDF. <a href="https://gist.github.com/ecenm/cbbdcea724e199dc60fe4a38b7791eb8#file-64_general-out" rel="nofollow">https://gist.github.com/ecenm/cbbdcea724e199dc60fe4a38b7791eb8#file-64_general-out</a></p> <p>Below is the script</p> <pre><code>import numpy as np import ...
0
2016-06-22T12:29:21Z
37,969,778
<ol> <li><p>It is a legit way of <em>approximating</em> the PDF. Since np.histogram uses various techniques for binning the values you won't get the exact frequency of each number in your input. For a more exact approximation you should count the occurrence of each number and divide it by the total count. Also, since t...
1
2016-06-22T13:36:52Z
[ "python", "numpy", "matplotlib", "statistics", "probability-density" ]
Run python script only if it's not running
37,968,080
<p>I want to launch a python script from another python script. I know how to do it. But I should launch this script only if it is not running already.</p> <p><strong>code:</strong></p> <pre><code>import os os.system("new_script.py") </code></pre> <p>But I'm not sure how to check if this script is already running or...
0
2016-06-22T12:30:49Z
37,968,403
<p>Try this:</p> <pre><code>import subprocess import os p = subprocess.Popen(['pgrep', '-f', 'your_script.py'], stdout=subprocess.PIPE) out, err = p.communicate() if len(out.strip()) == 0: os.system("new_script.py") </code></pre>
1
2016-06-22T12:43:49Z
[ "python", "linux", "python-2.7" ]
ValueError in ConfigParser in python3
37,968,161
<p>I am trying to update my <code>configuration.ini</code> file's, <code>[Financial Times: Financial-Services]</code> section's <code>last_entry_id</code> with the following string:<br><br> <code>http://www.ft.com/cms/s/0/46858280-36f4-11e6-a780-b48ed7b6126f.html?ftcamp=published_links%2Frss%2Fcompanies_financial-serv...
3
2016-06-22T12:34:36Z
37,968,507
<p>The exception refers to an invalid <code>interpolation syntax</code></p> <p>This is because in Python you're able to <em>interpolate</em> strings with the following syntax:</p> <pre><code>mystring = "Hello, my name is %s" print(mystring % 'StackOverflow') </code></pre> <p>I think that at some point in <code>confi...
1
2016-06-22T12:48:05Z
[ "python", "configparser" ]
Similar Function envelope Matlab in Python
37,968,221
<p>I would like to know if there is a function <code>envelope</code> in Python to have the same result as this </p> <p><img src="http://i.stack.imgur.com/o0bhO.png" alt="picture"> </p> <p>I have already tried an <code>envelope</code> function in Python but there is this result and it doesn't correspond with what I w...
1
2016-06-22T12:37:00Z
37,968,477
<p>Though you don't mention exactly what function you use, it seems like you are using two different kinds of envelopes.</p> <p>The way you call envelope in matlab, the relevant description is:</p> <blockquote> <p>[yupper,ylower] = envelope(x) returns the upper and lower envelopes of the input sequence, x, as the...
0
2016-06-22T12:46:26Z
[ "python", "matlab", "pycharm", "anaconda" ]
How to write at the same time to Different excel Using Python
37,968,272
<p>I try to write to all files, that I have at the same time. I have some files </p> <pre><code>izzymonroe@mail.ru.xlsx, lucky-frog@mail.ru.xlsx, lucky-frog@mail.ru.xlsx, izzymonroe@mail.ru.xlsx, Yubodrova@ya.ru.xlsx, lucky-frog@mail.ru.xlsx, Ant.karpoff2011@yandex.ru.xlsx 9rooney9@list.ru.xlsx </code></pre> <p>an...
1
2016-06-22T12:38:41Z
37,969,160
<p>The problem was solved with <code>df.groupby('col_name').apply(lambda x: add_xlsx_sheet(x, x.name, path='{}.xlsx'.format(x.name)))</code></p>
0
2016-06-22T13:13:40Z
[ "python", "excel", "pandas" ]
Entering the url in the browser, downloads the image automatically. How to write a python script to download such images?
37,968,289
<p>url="https://images.data.gov.sg/api/traffic-images/2016/02/96128cfd-ab9a-4959-972e-a5e74bb149a9.jpg"</p> <p>I am trying this: import urllib <br/> url="https://images.data.gov.sg/api/traffic-images/2016/02/96128cfd-ab9a-4959-972e-a5e74bb149a9.jpg" <br/> IMAGE=url.rsplit("/")[-1] <br/> urllib.urlretrieve(url,IMAGE) <...
0
2016-06-22T12:39:19Z
37,968,460
<p>It might be because the domain that you are trying to reach has restrictions over download policy. Check this one out, hope it helps! <a href="http://stackoverflow.com/a/8389368/2539771">http://stackoverflow.com/a/8389368/2539771</a></p>
0
2016-06-22T12:45:39Z
[ "python", "image", "urllib" ]
Check successive similar values and replacement
37,968,408
<p>I have a list of index values like [1,1,2,2,2,3,3,4,4,4,5,5] and another list comprising a characteristic value for each of those indexes like [3,14,6,13,15,3,7,18,4,12,17,2,9]. For the first index of same sequence (e.g. first 2 of [2,2,2]), the characteristic value is always the minimum (e.g. here it is 6), and inc...
1
2016-06-22T12:43:58Z
37,971,260
<p>Give a try to this code:</p> <pre><code>from itertools import groupby from operator import itemgetter indices = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5] values = [3, 14, 6, 13, 15, 3, 7, 18, 4, 12, 17, 2, 9] pairs = zip(indices, values) sequences = [[v for (i, v) in group] for (_, group) in groupby(pairs, itemgetter...
1
2016-06-22T14:37:51Z
[ "python", "python-3.x" ]
How to make appended plots continous in python
37,968,432
<p>I am using the below python code to append the plots from different subplots into one [sixth] subplot. There is break between the consecutive plots in the sixth subplot (the line is not continuous). How do you eliminate the break between these consecutive plots and make them continuous? </p> <p>Could anyone help me...
-1
2016-06-22T12:44:39Z
37,969,555
<p>Just plot one line with the data appended.</p> <pre><code>plt.subplot(6,1,6) x6 = np.concatenate((x1, x2, x3, x4, x5)) y6 = np.concatenate((y1, y2, y3, y4, y5)) plt.plot(x6, y6) instead of calling 5 times </code></pre> <p>Now you are just plotting one continuous line.</p>
2
2016-06-22T13:28:30Z
[ "python", "numpy", "matplotlib" ]
Controls inside tabs not showing in PyQt
37,968,440
<p>My problem is probably a quite naive one; anyway I am a little bit confused with PyQt's proper arrangement and displaying of controls inside a tabbed control (tabWidget).</p> <p>Here is my test code:</p> <pre><code>import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class tabdemo(QMainWindow): def ...
1
2016-06-22T12:44:51Z
37,968,718
<p>You have to set the <code>self.tabs</code>widget as central widget in your class</p> <pre><code>class tabdemo(QMainWindow): def __init__(self): super(tabdemo, self).__init__() self.setAttribute(Qt.WA_DeleteOnClose) self.tabs = QTabWidget() self.tab1 = QWidget() self.tab2 =...
1
2016-06-22T12:56:35Z
[ "python", "pyqt" ]
Controls inside tabs not showing in PyQt
37,968,440
<p>My problem is probably a quite naive one; anyway I am a little bit confused with PyQt's proper arrangement and displaying of controls inside a tabbed control (tabWidget).</p> <p>Here is my test code:</p> <pre><code>import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class tabdemo(QMainWindow): def ...
1
2016-06-22T12:44:51Z
37,968,831
<p>You only missed one step. You need to set a <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qmainwindow.html#centralWidget" rel="nofollow"><code>centralWidget</code></a> to your QMainWindow. You can do this by adding this line to the end of your <code>__init__</code> method:</p> <pre><code>self.setCentralWidget(sel...
2
2016-06-22T13:00:23Z
[ "python", "pyqt" ]
How do I use a keyword as a variable name?
37,968,516
<p>I have the following class with the variables <code>from</code>, <code>to</code> and <code>rate</code>. <code>from</code> is a keyword. If I want to use it in the init method below, what's the correct way to write it?</p> <p>More context: The class needs the <code>from</code> variable explicitly as it's part of a j...
-1
2016-06-22T12:48:28Z
37,968,813
<p>Use a synonym. Try "origin" or "source" instead.</p>
0
2016-06-22T12:59:53Z
[ "python", "keyword" ]
How do I use a keyword as a variable name?
37,968,516
<p>I have the following class with the variables <code>from</code>, <code>to</code> and <code>rate</code>. <code>from</code> is a keyword. If I want to use it in the init method below, what's the correct way to write it?</p> <p>More context: The class needs the <code>from</code> variable explicitly as it's part of a j...
-1
2016-06-22T12:48:28Z
37,970,214
<p>As mentioned in the comments, <code>from</code> is a Python keyword so you can't use it as a variable name, or an attribute name. So you need to use an alternative name, and do a conversion when reading or writing the JSON data. </p> <p>To do the output conversion you can supply a new encoder for <code>json.dumps</...
2
2016-06-22T13:55:36Z
[ "python", "keyword" ]
Scraping XML element attributes with beautifulsoup
37,968,565
<p>I have the following code:</p> <pre><code>from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("https://api.stlouisfed.org/fred/...") bsObj = BeautifulSoup(html.read(), "lxml"); print(bsObj) </code></pre> <p>It returns something like this:</p> <pre><code>&lt;?xml version="1.0" encoding...
1
2016-06-22T12:50:13Z
37,973,241
<p>Find all the attribute tags and just extract the attributes you want:</p> <pre><code>x = """&lt;?xml version="1.0" encoding="utf-8" ?&gt;&lt;html&gt;&lt;body&gt;&lt;observations count="276" file_type="xml" limit="100000" observation_end="9999-12-31" observation_start="1776-07-04" offset="0" order_by="observation_da...
1
2016-06-22T16:08:21Z
[ "python", "python-3.x", "csv", "beautifulsoup", "elementtree" ]
Scraping XML element attributes with beautifulsoup
37,968,565
<p>I have the following code:</p> <pre><code>from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("https://api.stlouisfed.org/fred/...") bsObj = BeautifulSoup(html.read(), "lxml"); print(bsObj) </code></pre> <p>It returns something like this:</p> <pre><code>&lt;?xml version="1.0" encoding...
1
2016-06-22T12:50:13Z
37,986,915
<p>The above works great! If you want to use URL instead of local file the code will look like this:</p> <pre><code>from bs4 import BeautifulSoup from urllib.request import urlopen html = urlopen("https://api.stlouisfed.org/fred/series/.......") bsObj = BeautifulSoup(html.read(), "lxml"); for ob in bsObj.find_all("ob...
0
2016-06-23T09:02:04Z
[ "python", "python-3.x", "csv", "beautifulsoup", "elementtree" ]
Set index name of pandas DataFrame
37,968,730
<p>I have a pandas dataframe like this: </p> <pre><code> '' count sugar 420 milk 108 vanilla 450 ... </code></pre> <p>The first column has no header and I would like to give it the name: 'ingredient'. </p> <p>I created the dataframe from a csv file: </p> <pre><code>df = pd.read_csv('./data/file...
1
2016-06-22T12:56:59Z
37,968,994
<p>if ingredients is the name of the index then you can set it by</p> <pre><code>df.index.name='ingredient' </code></pre> <p>With the current solutions you have 'ingredient' as name of the index, which is printed in different row to that of column names. This cannot be changed as is. Try the modified solution below,...
1
2016-06-22T13:07:27Z
[ "python", "csv", "pandas", "dataframe" ]
Set index name of pandas DataFrame
37,968,730
<p>I have a pandas dataframe like this: </p> <pre><code> '' count sugar 420 milk 108 vanilla 450 ... </code></pre> <p>The first column has no header and I would like to give it the name: 'ingredient'. </p> <p>I created the dataframe from a csv file: </p> <pre><code>df = pd.read_csv('./data/file...
1
2016-06-22T12:56:59Z
37,969,996
<p>Try this:</p> <pre><code>cols_ = df.columns cols[0] = 'ingredient' df.columns = cols_ </code></pre>
1
2016-06-22T13:46:14Z
[ "python", "csv", "pandas", "dataframe" ]
Using type annotations at package level
37,968,767
<p>I want to use annotations to have better auto-completion in IDEs, and maybe later type testing in automated tests. But how can you add type annotations to many methods without introducing a lot of extra code?</p> <p>For example, imagine that you have a big code base which uses the Django framework, including about ...
1
2016-06-22T12:58:35Z
37,972,777
<p>You could use a custom <a href="https://docs.djangoproject.com/en/dev/topics/http/middleware/" rel="nofollow">middleware</a> (untested):</p> <pre><code>from django.http import HttpRequest class RequireHttpRequest(): def process_view(request, view_func, view_args, view_kwargs): require_http_request = vi...
0
2016-06-22T15:45:17Z
[ "python", "django", "python-3.x", "type-hinting" ]
Using type annotations at package level
37,968,767
<p>I want to use annotations to have better auto-completion in IDEs, and maybe later type testing in automated tests. But how can you add type annotations to many methods without introducing a lot of extra code?</p> <p>For example, imagine that you have a big code base which uses the Django framework, including about ...
1
2016-06-22T12:58:35Z
38,306,428
<p>If my understanding is correct, this sounds like a use-case for <em>stub files</em> which, as described in <a href="https://www.python.org/dev/peps/pep-0484/#stub-files" rel="nofollow"><strong><code>PEP 484</code></strong></a>: </p> <blockquote> <p>Stub files are files containing type hints that are only for use ...
5
2016-07-11T12:00:41Z
[ "python", "django", "python-3.x", "type-hinting" ]
Merging two one DataFrames
37,968,785
<p>I have 2 dataframes which I would like to merge (i think). I have looked at the documentation and tried to perform the following operation but an getting confused as to how to do it. Let me explain. Like I said I have 2 dataframes</p> <p>Df1:</p> <pre><code> id name type currency 0 BTA.S Applewo...
1
2016-06-22T12:59:03Z
37,968,873
<p>You need to convert <code>df2</code> <code>.to_frame()</code> as <code>.merge()</code> needs a <code>pd.DataFrame()</code> input (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow">see docs</a>):</p> <pre><code>Df1.merge(Df2[['*.S']].to_frame(), left_on='id', ...
2
2016-06-22T13:02:14Z
[ "python", "pandas" ]
Merging two one DataFrames
37,968,785
<p>I have 2 dataframes which I would like to merge (i think). I have looked at the documentation and tried to perform the following operation but an getting confused as to how to do it. Let me explain. Like I said I have 2 dataframes</p> <p>Df1:</p> <pre><code> id name type currency 0 BTA.S Applewo...
1
2016-06-22T12:59:03Z
37,968,937
<p>This error means that one of your objects is <strong>not</strong> a pandas Data Frame.</p> <pre><code>ValueError: can not merge DataFrame with instance of type &lt;class 'pandas.core.series.Series'&gt; </code></pre> <p>To prove this to yourself,</p> <pre><code>print(type(df2)) </code></pre> <p>And that should ou...
1
2016-06-22T13:04:54Z
[ "python", "pandas" ]
Merging two one DataFrames
37,968,785
<p>I have 2 dataframes which I would like to merge (i think). I have looked at the documentation and tried to perform the following operation but an getting confused as to how to do it. Let me explain. Like I said I have 2 dataframes</p> <p>Df1:</p> <pre><code> id name type currency 0 BTA.S Applewo...
1
2016-06-22T12:59:03Z
37,969,175
<p>You can simply add df2 (which is a Series, not a DataFrame) as a new column</p> <pre><code>df['price']=df2 </code></pre>
0
2016-06-22T13:14:13Z
[ "python", "pandas" ]
Parse JSON string with Python
37,968,936
<p>I've got such string from JSON request:</p> <pre><code>[{"foo": "100100000024635"}] </code></pre> <p>here are the request:</p> <pre><code>list = json.dumps(bar.json()['result']) </code></pre> <p>and I can't get it by <code>list['foo']</code></p>
-2
2016-06-22T13:04:50Z
37,968,978
<p>what you get in the response is a list of dictionaries.</p> <p>iterate the list and then read the value for key 'foo'</p> <pre><code>for obj in list: print obj['foo'] </code></pre>
1
2016-06-22T13:06:52Z
[ "python", "json", "python-2.7", "parsing" ]
python-docx installation on windows
37,969,041
<p>When I try to install python-docx on my machine, I get errors that I haven't seen in other questions... here's the command prompt code-</p> <pre><code>C:\windows\system32&gt;pip install python-docx Collecting python-docx Using cached python-docx-0.8.5.tar.gz Collecting lxml&gt;=2.3.2 (from python-docx) Using ca...
0
2016-06-22T13:09:13Z
37,976,305
<p>libxml2 and libxslt are C-code libraries that lxml depends on. You might try installing lxml from a binary distribution and see if that gets you past this.</p>
0
2016-06-22T19:02:57Z
[ "python", "libxml2", "python-docx", "libxslt" ]
How to slice Numpy datetime64 array
37,969,061
<p>I have a python zip with 2 arrays</p> <p>zipped = zip(array1[], array2[])</p> <p>Where array1 is of type numpy.datetime64[] adn array2 is a temperature</p> <p>I want to make a time window in 1st array so i can have fixed array len (because i have other zipped arrays but they differ in array length)</p> <p>this i...
0
2016-06-22T13:10:09Z
37,993,565
<p>You can use <code>pandas</code> indexing which is designed for this. 'series' is a 1d array with an index attached. With reference to Wes McKinney's Python for Data Analysis:</p> <pre><code>import pandas as pd temp = np.random.randn(366) time_series = pd.Series(temp,index=np.arange(np.datetime64('2015-12-19'),np.da...
1
2016-06-23T13:49:17Z
[ "python", "arrays", "datetime", "numpy" ]
Tensorflow, best way to save state in RNNs?
37,969,065
<p>I currently have the following code for a series of chained together RNNs in tensorflow. I am not using MultiRNN since I was to do something later on with the output of each layer.</p> <pre><code> for r in range(RNNS): with tf.variable_scope('recurent_%d' % r) as scope: state = [tf.zeros((BATCH_SIZE, s...
0
2016-06-22T13:10:15Z
38,053,807
<p>I am now saving the RNN states using the tf.control_dependencies. Here is an example.</p> <pre><code> saved_states = [tf.get_variable('saved_state_%d' % i, shape = (BATCH_SIZE, sz), trainable = False, initializer = tf.constant_initializer()) for i, sz in enumerate(rnn.state_size)] W = tf.get_variable('W', ...
0
2016-06-27T12:18:36Z
[ "python", "tensorflow" ]
Tensorflow, best way to save state in RNNs?
37,969,065
<p>I currently have the following code for a series of chained together RNNs in tensorflow. I am not using MultiRNN since I was to do something later on with the output of each layer.</p> <pre><code> for r in range(RNNS): with tf.variable_scope('recurent_%d' % r) as scope: state = [tf.zeros((BATCH_SIZE, s...
0
2016-06-22T13:10:15Z
38,325,103
<p>These two links are also related and useful for this question:</p> <p><a href="https://github.com/tensorflow/tensorflow/issues/2695" rel="nofollow">https://github.com/tensorflow/tensorflow/issues/2695</a> <a href="https://github.com/tensorflow/tensorflow/issues/2838" rel="nofollow">https://github.com/tensorflow/ten...
0
2016-07-12T09:37:10Z
[ "python", "tensorflow" ]
What is the best way to remove duplicate objects from the Django database
37,969,101
<p>I am mining the Twitter Search API for tweets of a certain hashtag and storing them to a Postgresql database using the Django ORM. </p> <p>Here is the code from my <code>tasks.py</code> file that handles this routine.</p> <pre><code>"""Get some tweets and store them to the database using Djano's ORM.""" import tw...
1
2016-06-22T13:11:22Z
37,970,275
<p>You can let your model manager do the job for you</p> <pre><code>from django.db import IntegrityError for i, j, k in zip(tweets_date, tweets_id, tweets_text): try: Tweet.objects.create( tweet_date=i, tweet_id=j, tweet_text=k ) except IntegrityError: ...
1
2016-06-22T13:58:26Z
[ "python", "django", "postgresql", "celery" ]
Math behind scipy.ndimage.convolve
37,969,197
<p>While I have already found the documentation on scipy.ndimage.convolve function and I "practically know what it does", when I try to calculate the resulting arrays I can't follow the mathematical formula. Let's take for example: </p> <pre><code>a = np.array([[1, 2, 0, 0],` [5, 3, 0, 4], [0...
1
2016-06-22T13:14:56Z
37,978,737
<p>Just to warm up consider </p> <p>k = np.array([[1,0,0],[0,1,0],[0,0,0]])</p> <p>instead of your k, then if you</p> <p>ndimage.convolve(a, k, mode='constant', cval=0.0)</p> <p>you get</p> <pre><code>array([[4, 2, 4, 0], [5, 3, 7, 4], [3, 0, 0, 7], [9, 3, 0, 0]]) </code></pre> <p>and note th...
0
2016-06-22T21:39:54Z
[ "python", "scipy" ]
How to run a piece of code inside _handle_PacketIn function of pox,at time intervals? the maximum recursion depth exceeded error in python
37,969,198
<p>I’m a beginner in python and pox controller. I want to add a code to the pox, to categorize the received packets. I want it to count IP packets travelling between a source &amp; a destination IP/port pair and with identical protocols within a certain period of time. I want a list like this:</p> <p>[ [Src ip , ...
0
2016-06-22T13:14:57Z
37,976,162
<p>In order to have a recurring function you need the Timer class from the recoco module. First import Timer</p> <pre><code>from pox.lib.recoco import Timer </code></pre> <p>Create a function that will print the list. This function belongs in the </p> <blockquote> <p>class LearningSwitch (object):</p> </blockquote...
0
2016-06-22T18:54:52Z
[ "python", "list", "recursion", "timer", "pox" ]
Windows Subsystem for Linux DISPLAY variable setup
37,969,262
<p>I'm experimenting with Windows Subsystem for Linux and am trying to create python plots using Matplotlib. But get the following error</p> <p><code>RuntimeError: Invalid DISPLAY variable</code></p> <p><code>echo DISPLAY</code> shows nothing. How can I setup the display variable? </p>
-1
2016-06-22T13:17:49Z
39,783,034
<p>The Windows Subsystem for Linux doesn’t officially support graphical GNU/Linux desktop applications, so we have no <em>guarantee</em> that the calls made by our graphical program of choice will be implemented as windows system calls.</p> <p>The main issue you are running into is the lack of a graphical interface ...
0
2016-09-30T03:07:39Z
[ "python", "linux", "display" ]
Trouble with riffleshuffling, function won't find list
37,969,280
<p>In need of help, I'm trying to do a perfect riffleshuffle or "Faro shuffle". Been trying myself around, I made another thread but broke against rules so hopefully my question this time is better. </p> <p>This is how my code looks right now:</p> <pre><code>def shuffle(n): r=[] for (a, b) in zip(lista[0:int(...
1
2016-06-22T13:18:19Z
37,969,686
<p>There are a few problems here:</p> <ol> <li>The list <code>r</code> in riffel is never initialized.</li> <li>You never pass <code>n</code> to <code>r.shuffle()</code></li> <li>(As R Nar's comment says, the state of <code>r</code> in shuffle is lost since it's scope is local.</li> <li>Calling <code>r.shuffle()</code...
1
2016-06-22T13:33:27Z
[ "python", "list", "function" ]
Pearson correlation for all rows in Data Frames Pandas
37,969,282
<p>I have a dataframe in Pandas and its shape is (136, 1445). I try to create correlation(Pearson) matrix for my 136 rows. So in the result, i need a matrix with size 136x136.</p> <p>I tried two different ways but i cannot get a results from them or when i create a 136x136 correlation matrix, i lost the columns name...
0
2016-06-22T13:18:25Z
37,969,485
<p>To get the correlation matrix containing pairwise correlation between all rows, you can:</p> <pre><code>gene_expression.T.corr() </code></pre> <p>Using a toy example:</p> <pre><code>df = pd.DataFrame(np.random.randint(0, high=100, size=(5, 10)), index=list(string.ascii_lowercase[:5])) </code></pre> <p>with 5 lab...
1
2016-06-22T13:25:35Z
[ "python", "pandas", "correlation", "feature-extraction" ]
Generate Picking from invoice openerp
37,969,293
<p>I want to make a order picking_out of the invoice in the openerp I found this <a href="https://www.odoo.com/apps/modules/7.0/picking_from_invoice/" rel="nofollow">https://www.odoo.com/apps/modules/7.0/picking_from_invoice/</a></p> <p>But they do create every item in a delivery order Is there a solution of his own ...
1
2016-06-22T13:18:52Z
37,972,090
<p>Actually you only need to let the for loop for the invoice lines run later, like:</p> <pre class="lang-py prettyprint-override"><code>for invoice in wzr_brw.invoice_ids: if invoice.type in ('in_invoice', 'out_invoice'): # name... picking_id = self.pool.get('stock.picking').create(cr, uid, {#... ...
1
2016-06-22T15:14:57Z
[ "python", "openerp" ]
Django - filter objects by number of related objects which meet a condition
37,969,363
<p>Given the following model:</p> <pre><code>class EmailVerification(models.Model): user = models.ForeignKey(User, related_name='email_verifications') token = models.CharField(max_length=30) email = models.CharField(max_length=200) expiry = models.DateTimeField() verified = models.BooleanField(defa...
0
2016-06-22T13:21:27Z
37,969,477
<p>You're overcomplicating the query a bit: all you want is Users who have at least one EmailVerification with verified=True. That can be done with a simple join:</p> <pre><code> User.objects.filter(email_verifications__verified=True) </code></pre> <p>If you did need to filter on the actual number of verified emails,...
0
2016-06-22T13:25:29Z
[ "python", "sql", "django" ]
TypeError: 'int' object is not iterable in odoo
37,969,367
<p>all</p> <p>I recieved error when add data to table:</p> <pre><code>2016-06-22 12:14:59,292 21364 ERROR odoov8 openerp.addons.webvisitorcalc.controllers: prevouseURLsearchEngine: {'search_marker': u'q', 'id': 1, 'uniq_part_in_host': u'google'} 2016-06-22 12:14:59,292 21364 ERROR odoov8 openerp.addons.webvisitorcal...
0
2016-06-22T13:21:31Z
37,971,018
<p>Here is what I would try:</p> <pre><code>createParam = {} if prevouseURLsearchEngine: _logger.error("prevouseURLsearchEngine: %r", prevouseURLsearchEngine) _logger.error("search_engine_id: %r", prevouseURLsearchEngine['id']) # the search_engine field is a `OneToMany` so we are expecting an array not a s...
0
2016-06-22T14:27:43Z
[ "python", "orm", "openerp", "typeerror", "odoo-8" ]
TypeError: 'int' object is not iterable in odoo
37,969,367
<p>all</p> <p>I recieved error when add data to table:</p> <pre><code>2016-06-22 12:14:59,292 21364 ERROR odoov8 openerp.addons.webvisitorcalc.controllers: prevouseURLsearchEngine: {'search_marker': u'q', 'id': 1, 'uniq_part_in_host': u'google'} 2016-06-22 12:14:59,292 21364 ERROR odoov8 openerp.addons.webvisitorcal...
0
2016-06-22T13:21:31Z
37,973,838
<p>Thanks all for answers. I wrote wrong relations. Relations in my classes must be change places.</p>
0
2016-06-22T16:38:22Z
[ "python", "orm", "openerp", "typeerror", "odoo-8" ]
Anaconda and OpenMDAO
37,969,393
<p>I'm new in Python and am trying to use <a href="https://nwtc.nrel.gov/WISDEM" rel="nofollow">WISDEM</a> that is designed as a OpenMDAO plugin-in. I'd like to use Anaconda (with OS X). Which Anaconda's version(2.7/3.5) will work with OpenMDAO?</p> <p>Thanks,</p> <p>-Luis</p>
0
2016-06-22T13:22:31Z
37,969,660
<p>Which version of OpenMDAO/WISDEM are you using? If its tied to OpenMDAO &lt;= V0.0.13 then you can't use anaconda. </p> <p>OpenMDAO >= V1 will work with anaconda though. There was a major change in OpenMDAO between 0.0.13 and 1.0 and support for anaconda was introduced there. </p>
0
2016-06-22T13:32:28Z
[ "python", "anaconda", "openmdao" ]
Text classification performance
37,969,425
<p>So i am using textblob python library, but the performance is lacking.</p> <p>I already serialize it and load it before the loop( using pickle ).</p> <p>It currently takes ~ 0.1( for small training data ) and ~ 0.3 on 33'000 test data. I need to make it faster, is it even possible ?</p> <h1><strong>Some code:</st...
1
2016-06-22T13:23:27Z
38,040,580
<p>You can use feature selection for your data. some good feature selection can reduce features up to 90% and persist the classification performance. In feature selection you select top feature(in <strong>Bag Of Word</strong> model, you select top influence words), and train model based on these words(features). this r...
3
2016-06-26T16:21:16Z
[ "python", "performance", "machine-learning", "textblob" ]
Why are li's not showing up with python requests response?
37,969,536
<p>I have a homework project with web scraping and am suppose to collect all the even information for a month from a school website. I am using Python with Requests and Beautiful Soup. I have written some code to grab a url and am trying to grab all of the li's from the page that hold the event information. However, wh...
1
2016-06-22T13:27:50Z
37,971,050
<p>I looked at the source of the page, and in the plain HTML, there are 25 <code>&lt;a&gt;</code> elements that have an href attribute. These are the 25 links that your script is finding.</p> <p>Also, I'm not sure which events on that page are the ones that you're actually looking for, but I'm gonna guess that many (i...
1
2016-06-22T14:28:52Z
[ "python", "html", "beautifulsoup", "python-requests" ]
Why are li's not showing up with python requests response?
37,969,536
<p>I have a homework project with web scraping and am suppose to collect all the even information for a month from a school website. I am using Python with Requests and Beautiful Soup. I have written some code to grab a url and am trying to grab all of the li's from the page that hold the event information. However, wh...
1
2016-06-22T13:27:50Z
37,974,266
<p>Some of the links are generated with js but you can get all the event data from the ten events in json format just using requests:</p> <pre><code>import requests params = {"pageNum": "1", "date": "06012016", "type": "day", "isSearch": "false", "pubCalId": "GRP1322"} r = req...
1
2016-06-22T17:01:13Z
[ "python", "html", "beautifulsoup", "python-requests" ]
select groups having more than x members
37,969,561
<p>Is there a way in pandas to select, out of a grouped dataframe, the groups with more than x members ?</p> <p>something like:</p> <pre><code>grouped = df.groupby(['a', 'b']) dupes = [g[['a', 'b', 'c', 'd']] for _, g in grouped if len(g) &gt; 1] </code></pre> <p>I can't find a solution in the docs or on SO. Thanks<...
0
2016-06-22T13:28:48Z
37,969,636
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration" rel="nofollow"><code>filter</code></a>:</p> <pre><code>grouped.filter(lambda x: len(x) &gt; 1) </code></pre> <p>Example:</p> <pre><code>In [64]: df = pd.DataFrame({'a':[0,0,1,2],'b':np.arange(4)}) df Out[64]: a b 0 0 0 1 0 ...
1
2016-06-22T13:31:39Z
[ "python", "pandas", "select", "group" ]
How to format Scrapy exports
37,969,629
<p>I currently store my scraped data in an item to export in .csv format:</p> <pre><code>item = HobbyItem() item['name'] = user.getName() item['hobbies'] = user.getHobbies() </code></pre> <p>The item is declared as follows:</p> <pre><code>name = scrapy.Field() hobbies = scrapy.Field() </code></pre> <p>This results ...
0
2016-06-22T13:31:25Z
37,970,802
<p>You did not let enough code or explanation for me to be sure that this will work in your particular code but</p> <p>Try : </p> <pre><code>for element in user.getHobbies(): item['name'] = user.getName() item['hobbies'] = element[0] </code></pre> <p>This will create 1 element per hobby, using getName multip...
0
2016-06-22T14:19:00Z
[ "python", "scrapy" ]
How to format Scrapy exports
37,969,629
<p>I currently store my scraped data in an item to export in .csv format:</p> <pre><code>item = HobbyItem() item['name'] = user.getName() item['hobbies'] = user.getHobbies() </code></pre> <p>The item is declared as follows:</p> <pre><code>name = scrapy.Field() hobbies = scrapy.Field() </code></pre> <p>This results ...
0
2016-06-22T13:31:25Z
37,978,468
<pre><code>name = user.getName() for hobby in user.getHobbies(): if hobby: item = HobbyItem() item['name'] = name item['hobbies'] = hobby[0] yield item </code></pre>
0
2016-06-22T21:21:31Z
[ "python", "scrapy" ]
Running script via subprocess.Popen with return value
37,969,707
<p>I have a simple script which is having the structure of: </p> <pre><code>if __name__ =='main': #do some logic #print to console the result </code></pre> <p>Now, I ran the script via the code using <code>subprocess.Popen()</code> method like this: </p> <pre><code>p = subprocess.Popen( ["python", path_...
-1
2016-06-22T13:34:05Z
37,969,884
<p>You can capture the output in the calling script using <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_output" rel="nofollow"><code>subprocess.check_output()</code></a>:</p> <pre><code>from subprocess import check_output result = check_output(args).decode() </code></pre> <p>To also cap...
0
2016-06-22T13:40:59Z
[ "python", "subprocess" ]
Running script via subprocess.Popen with return value
37,969,707
<p>I have a simple script which is having the structure of: </p> <pre><code>if __name__ =='main': #do some logic #print to console the result </code></pre> <p>Now, I ran the script via the code using <code>subprocess.Popen()</code> method like this: </p> <pre><code>p = subprocess.Popen( ["python", path_...
-1
2016-06-22T13:34:05Z
37,969,887
<p>Use <a href="https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow"><code>communicate()</code></a> to retrieve output of your script. And <a href="https://docs.python.org/2/library/subprocess.html#subprocess.Popen.returncode" rel="nofollow"><code>returncode</code></a> to get t...
0
2016-06-22T13:41:05Z
[ "python", "subprocess" ]
Pyodbc is not updating MS Access table
37,969,801
<p>Basically I'm trying to update Column1_mbgl field data in Table1, all based in MS Access database. The script gets executed without any errors, but when the table is checked no update occurred. I have tried two options as shown in the code without any success. The second option is the SQL code generated directly fr...
1
2016-06-22T13:37:46Z
37,971,452
<p>You forgot to <code>conn.commit()</code> after executing your UPDATE query. The <a href="https://www.python.org/dev/peps/pep-0249/" rel="nofollow">Python database API</a> specifies that connections open with "autocommit" off by default, so an explicit <code>commit</code> is needed.</p>
3
2016-06-22T14:46:15Z
[ "python", "ms-access", "pyodbc" ]
how to augment sqlalchemy relationship by custom setter and/or getter
37,969,904
<p>I need create relationship with custom getter and setter. It would be nice to define setter/getter parameters on relationship declaration Also I need alter relation getter even if no data are joined (i.e. change None to something more complex)</p> <p>Here is roughly what I need:</p> <pre><code>class Address(Base)...
0
2016-06-22T13:41:49Z
38,266,246
<p>Best solution is to use <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/associationproxy.html" rel="nofollow">association_proxy</a> </p> <p>For provided example solution looks as follows:</p> <pre><code>class AddressAssociation: some_data = {} def setter(self, AddressObject, value): ...
0
2016-07-08T12:07:16Z
[ "python", "sqlalchemy", "relationship" ]
Creating Properly-Nested XML Output in Python
37,969,942
<p>I'm attempting to save data from several lists in XML format, but I cannot understand how to make the XML display properly. An example of my code right now is as follows:</p> <pre><code>from lxml import etree #Create XML Root articles = etree.Element('root') #Create Lists &amp; Data t_list = ['title1', 'title2', ...
0
2016-06-22T13:43:17Z
37,970,755
<p>I've only used the base ET module in Python and can't find an lxml download for python 3.5 (which I'm on) in order to test it, but the <em>b</em> before the line indicates bytes and a quick glance at the documentation indicates that tostring() has an encoding keyword, so you should just need to set that to unicode o...
0
2016-06-22T14:17:27Z
[ "python", "xml", "output" ]
Creating Properly-Nested XML Output in Python
37,969,942
<p>I'm attempting to save data from several lists in XML format, but I cannot understand how to make the XML display properly. An example of my code right now is as follows:</p> <pre><code>from lxml import etree #Create XML Root articles = etree.Element('root') #Create Lists &amp; Data t_list = ['title1', 'title2', ...
0
2016-06-22T13:43:17Z
37,970,771
<p>Your "Current Output" is the <em>representation</em> (internal python representation) of the bytestring generated by <code>etree.tostring()</code>, and seems that in Python3 <code>print(somebytestring)</code> prints the representation instead of the actual string.</p> <p>Hopefully the solution is quite simple: just...
0
2016-06-22T14:17:52Z
[ "python", "xml", "output" ]
Split data into train/ test files such that at least one sample is picked for both the files
37,969,945
<p>I have a csv file which is read into a dataframe. I split the it into training and test files based on the values of one column.</p> <blockquote> <p>Let us say the column is called "category" and it has several category names as column values such as cat1,cat2,cat3 and so on which repeat more than once.</p> </...
0
2016-06-22T13:43:23Z
37,971,078
<p>I tried to use it according to the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html" rel="nofollow">docs</a> and couldn't get <code>stratify</code> to work.</p> <h3>Setup</h3> <pre><code>from sklearn.cross_validation import train_test_split import pandas as p...
0
2016-06-22T14:29:44Z
[ "python", "pandas", "scikit-learn", "sklearn-pandas" ]
Split data into train/ test files such that at least one sample is picked for both the files
37,969,945
<p>I have a csv file which is read into a dataframe. I split the it into training and test files based on the values of one column.</p> <blockquote> <p>Let us say the column is called "category" and it has several category names as column values such as cat1,cat2,cat3 and so on which repeat more than once.</p> </...
0
2016-06-22T13:43:23Z
38,037,930
<p>Accoding to that post:</p> <p><a href="http://stackoverflow.com/questions/29438265/stratified-train-test-split-in-scikit-learn">Stratified Train/Test-split in scikit-learn</a> <strong>StratifiedKFold</strong> will balance the groups equally, maybe thats exactly what you want.</p> <hr> <p><a href="http://scikit-le...
0
2016-06-26T11:14:15Z
[ "python", "pandas", "scikit-learn", "sklearn-pandas" ]
How to use django.contrib.humanize in a model
37,970,001
<p>I would like to use the <code>django.contrib.humanize</code> outside of a template, actually inside a model to humanize some dates in some text messages.</p> <p>Is it possible? How can I do this?</p>
0
2016-06-22T13:46:31Z
37,970,086
<p>You can import the functions in the model:</p> <pre><code>from django.contrib.humanize.templatetags.humanize import naturalday natural_day = naturalday(value) </code></pre>
0
2016-06-22T13:50:13Z
[ "python", "django", "humanize" ]
How to add tons of attributes in an Element with Python and Elementtree?
37,970,006
<p>Is it OK to use the following ?</p> <pre><code>ET.Element.attrib={'a': '1', 'b': '2', 'c': '3'} </code></pre> <p>Or do I have to make a <code>for</code> loop using <code>ET.Element.set('x','y')</code> ?</p>
-1
2016-06-22T13:46:39Z
38,053,556
<p>jonrsharpe comment above is the answer. Just a detail though, I had to use <code>ET.Element.attrib=myDict.copy()</code> otherwise all my elements were pointing to the same dict in memory.</p>
0
2016-06-27T12:06:38Z
[ "python", "elementtree" ]
What is the pythonic way of instantiating a class, calling one of its methods, and returning it from a lambda function?
37,970,032
<p>I am dealing widgets and signals and I want to bind a signal to a certain callback. Since I don't really need to create a named callback function in the case of interest, I am defining it as a lambda function. However, the way it integrates with other classes is best described by the following minimal working exampl...
2
2016-06-22T13:47:53Z
37,970,134
<p>The most pythonic solution is to not use a lambda:</p> <pre><code>def foo(): x = Foo() x.parse("All set") return x print(foo().bar) </code></pre> <p>Lambdas in python are a syntactic convenience and are strictly less powerful than named functions.</p>
9
2016-06-22T13:52:10Z
[ "python", "lambda" ]
What is the pythonic way of instantiating a class, calling one of its methods, and returning it from a lambda function?
37,970,032
<p>I am dealing widgets and signals and I want to bind a signal to a certain callback. Since I don't really need to create a named callback function in the case of interest, I am defining it as a lambda function. However, the way it integrates with other classes is best described by the following minimal working exampl...
2
2016-06-22T13:47:53Z
37,970,149
<p>based on @Vaibhav Sagar answer, a bit modified:</p> <pre><code>class Foo(): def parse(self, what): self.bar = what def foo_factory(what): instance = Foo() instance.parse(what) return instance all_set = foo_factory('All set') ok = foo_factory('Ok') ready = foo_factory('ready') print(all_...
0
2016-06-22T13:52:57Z
[ "python", "lambda" ]
What is the pythonic way of instantiating a class, calling one of its methods, and returning it from a lambda function?
37,970,032
<p>I am dealing widgets and signals and I want to bind a signal to a certain callback. Since I don't really need to create a named callback function in the case of interest, I am defining it as a lambda function. However, the way it integrates with other classes is best described by the following minimal working exampl...
2
2016-06-22T13:47:53Z
37,970,382
<p>A factory function achieves the goal of avoiding a separate named function in the code that wires the callback. I would consider this pythonic. Using a lambda function that does what you have to do ist definitely not pythonic.</p> <pre><code>def create_callback(data): def callback(): x = Foo() x...
2
2016-06-22T14:02:34Z
[ "python", "lambda" ]
What is the pythonic way of instantiating a class, calling one of its methods, and returning it from a lambda function?
37,970,032
<p>I am dealing widgets and signals and I want to bind a signal to a certain callback. Since I don't really need to create a named callback function in the case of interest, I am defining it as a lambda function. However, the way it integrates with other classes is best described by the following minimal working exampl...
2
2016-06-22T13:47:53Z
37,970,459
<p>What about</p> <pre><code>def callback(): x = Foo() x.parse("All set") return x widget.bind('some_signal', callback) </code></pre> <hr> <p><strong>Note</strong> that your lambda will instanciate <code>Foo()</code> only the first time the code is interpreted.</p> <p>Indeed,</p> <pre><code>foo = lamb...
0
2016-06-22T14:05:55Z
[ "python", "lambda" ]
Matplotlib subplots not happy unpacking
37,970,096
<p>I'm using a Jupyter notebook and I'd like a grid of subplots that is 6 plots high by 4 plots deep.</p> <p>Before adding any data or manipulating the plots at all I've tried to run just the following line in isolation:</p> <pre><code>f, (ax1, ax2) = plt.subplots(6, 4, sharex=True, figsize=(13, 7)) </code></pre> <p...
0
2016-06-22T13:50:31Z
37,970,247
<p>If I don't say mistakes, you have to write something like that :</p> <pre><code>f, (ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9, ax10) = plt.subplots(6, 4, sharex=True, figsize=(13, 7)) </code></pre> <p>Because you had 6 high plots and 4 deep plots.</p> <p>Im' not really sure, but it will be interesting to try th...
1
2016-06-22T13:57:13Z
[ "python", "matplotlib" ]
Matplotlib subplots not happy unpacking
37,970,096
<p>I'm using a Jupyter notebook and I'd like a grid of subplots that is 6 plots high by 4 plots deep.</p> <p>Before adding any data or manipulating the plots at all I've tried to run just the following line in isolation:</p> <pre><code>f, (ax1, ax2) = plt.subplots(6, 4, sharex=True, figsize=(13, 7)) </code></pre> <p...
0
2016-06-22T13:50:31Z
37,972,784
<p>You are trying to create a grid of 6x4 (=24) subplots, but you have only named 2 subplots to catch what is returned from <code>plt.subplots</code>, so it is trying to unpack 24 subplots into two variables (<code>ax1</code> and <code>ax2</code>).</p> <p>You have a couple of options: </p> <ol> <li><p>Catch all subpl...
1
2016-06-22T15:45:49Z
[ "python", "matplotlib" ]
Saving Python 3-dimensional variable size array in matlab format
37,970,148
<p>I am trying to save a Python 3D int array, in which the third dimension is of variable length, in matlab format. The solution that I came up is </p> <pre><code>array = np.empty((FirstDim, SecondDim), dtype = object) for i in range(FirstDim): for j in range(SecondDim): array[i][j] = ... scipy.io.savemat...
0
2016-06-22T13:52:51Z
37,970,511
<p>Because you save your 3D array as a 2D array of object (each object being a 1D array), Matlab loads it as a cell array, where each cell is a 1D array. You can access value in a cell array using the following syntax:</p> <pre><code>array{1,1}(2) </code></pre>
2
2016-06-22T14:07:56Z
[ "python", "arrays", "matlab", "numpy", "scipy" ]
Bring variables with increasing number in the name into a numpy array in Python
37,970,224
<p>I have a big number of variables that have an increasing number in their name:</p> <pre><code>var0 = 2 var1 = 6 ... var999 = 19 </code></pre> <p>Is there an easy way (maybe with a loop) to create a numpy array that contains the values of the variables as elements?</p> <pre><code>list[0] = 2 list[1] = 6 ... list[9...
0
2016-06-22T13:56:10Z
37,970,484
<p>This should work, using <code>vars()</code> and assuming that no other variable name in the environment starts with "var":</p> <pre><code>{int(x[0][3:]) : x[1] for x in vars().items() if x[0].startswith('var')} </code></pre> <p>Example:</p> <pre><code>&gt;&gt;&gt; var1 = 8 &gt;&gt;&gt; var2 = 98 &gt;&gt;&gt; {int...
0
2016-06-22T14:06:46Z
[ "python", "arrays", "numpy" ]
Bring variables with increasing number in the name into a numpy array in Python
37,970,224
<p>I have a big number of variables that have an increasing number in their name:</p> <pre><code>var0 = 2 var1 = 6 ... var999 = 19 </code></pre> <p>Is there an easy way (maybe with a loop) to create a numpy array that contains the values of the variables as elements?</p> <pre><code>list[0] = 2 list[1] = 6 ... list[9...
0
2016-06-22T13:56:10Z
37,970,528
<p>If you have a file, say <code>test.txt</code> that looks like that:</p> <pre><code>var0 = 1 var1 = 2 var3 = 15 </code></pre> <p>you can do:</p> <pre><code>t = open('test.txt',r) data = t.readlines() t.close() for line in data: name,value = line.split('=') name.strip() value = int(value.strip()) </code...
1
2016-06-22T14:08:37Z
[ "python", "arrays", "numpy" ]
Bring variables with increasing number in the name into a numpy array in Python
37,970,224
<p>I have a big number of variables that have an increasing number in their name:</p> <pre><code>var0 = 2 var1 = 6 ... var999 = 19 </code></pre> <p>Is there an easy way (maybe with a loop) to create a numpy array that contains the values of the variables as elements?</p> <pre><code>list[0] = 2 list[1] = 6 ... list[9...
0
2016-06-22T13:56:10Z
37,970,542
<p>you can use the globals or locals function like below:</p> <p><code>a1 = 5 a2 = 6 alist = [] for i in range(1,3,1): alist.append(globals()['a'+str(i)])</code></p>
0
2016-06-22T14:09:06Z
[ "python", "arrays", "numpy" ]
Bring variables with increasing number in the name into a numpy array in Python
37,970,224
<p>I have a big number of variables that have an increasing number in their name:</p> <pre><code>var0 = 2 var1 = 6 ... var999 = 19 </code></pre> <p>Is there an easy way (maybe with a loop) to create a numpy array that contains the values of the variables as elements?</p> <pre><code>list[0] = 2 list[1] = 6 ... list[9...
0
2016-06-22T13:56:10Z
37,970,546
<p>Variables in Python are always available through your <code>locals</code> (or <code>globals</code>, if in a narrower scope than their definition) dictionary:</p> <pre><code>&gt;&gt;&gt; x = 2 &gt;&gt;&gt; y = 'Hello !' &gt;&gt;&gt; 'x' in locals() True &gt;&gt;&gt; locals()['x'] 2 &gt;&gt;&gt; locals()['y'] 'Hello ...
0
2016-06-22T14:09:18Z
[ "python", "arrays", "numpy" ]
Bring variables with increasing number in the name into a numpy array in Python
37,970,224
<p>I have a big number of variables that have an increasing number in their name:</p> <pre><code>var0 = 2 var1 = 6 ... var999 = 19 </code></pre> <p>Is there an easy way (maybe with a loop) to create a numpy array that contains the values of the variables as elements?</p> <pre><code>list[0] = 2 list[1] = 6 ... list[9...
0
2016-06-22T13:56:10Z
37,970,557
<p>Is it a python file (<code>.py</code>)? You can try this workaround:</p> <p>Add the following lines to the end of where you have the variables:</p> <pre><code>from operator import itemgetter # this should go up d = {k[3:]:v for k, v in locals().items() if k.startswith('var')} sorted_d = sorted(d.items(), key=item...
0
2016-06-22T14:09:40Z
[ "python", "arrays", "numpy" ]
Bring variables with increasing number in the name into a numpy array in Python
37,970,224
<p>I have a big number of variables that have an increasing number in their name:</p> <pre><code>var0 = 2 var1 = 6 ... var999 = 19 </code></pre> <p>Is there an easy way (maybe with a loop) to create a numpy array that contains the values of the variables as elements?</p> <pre><code>list[0] = 2 list[1] = 6 ... list[9...
0
2016-06-22T13:56:10Z
37,977,411
<p>If the variables are in a file in valid Python syntax, they can be imported and parsed from there. </p> <pre><code>from file.py import * </code></pre> <p>puts them into the local name space. But if we don't use <code>*</code> we can isolate them</p> <pre><code>In [1313]: import stack3797 as varN In [1314]: valu...
0
2016-06-22T20:12:55Z
[ "python", "arrays", "numpy" ]
Trying to read a file in a subdirectory through a module I imported from that subdirectory
37,970,287
<p>So I have a program with one main module that is in a folder with two other folders. Each of those two folders has a module in it that I've imported successfully, but each of those modules is supposed to be able to open and read a file from their respective folders, but it is unable to find the file it is supposed t...
0
2016-06-22T13:58:56Z
37,970,842
<p>My suggestion is to consider using the <code>os.path</code> module to ensure that you are using the correct paths when you open files. Here are a few operations that you might find helpful:</p> <ul> <li><code>os.path.abspath(path)</code> transforms <code>path</code> into an absolute path.</li> <li><code>os.path.dir...
0
2016-06-22T14:20:26Z
[ "python" ]
Trying to read a file in a subdirectory through a module I imported from that subdirectory
37,970,287
<p>So I have a program with one main module that is in a folder with two other folders. Each of those two folders has a module in it that I've imported successfully, but each of those modules is supposed to be able to open and read a file from their respective folders, but it is unable to find the file it is supposed t...
0
2016-06-22T13:58:56Z
37,970,936
<p>If i understand the question correctly, you want the ability to import a file from any directory in the system? If that is the case you can use libraries (depending on your version of python) such as importlib.util, or imp for python 2. </p> <p>You can find documentation here: <a href="https://docs.python.org/3/lib...
0
2016-06-22T14:23:59Z
[ "python" ]
Trying to read a file in a subdirectory through a module I imported from that subdirectory
37,970,287
<p>So I have a program with one main module that is in a folder with two other folders. Each of those two folders has a module in it that I've imported successfully, but each of those modules is supposed to be able to open and read a file from their respective folders, but it is unable to find the file it is supposed t...
0
2016-06-22T13:58:56Z
37,971,800
<p>It sounds like there's probably a better way of doing what you're trying to do, but absent additional information, a module's location can be found (for use in file operations) in its <code>__file__</code> variable:</p> <pre><code>mydir = os.path.dirname(__file__) </code></pre>
0
2016-06-22T15:01:37Z
[ "python" ]
Plot a function vertically in Python
37,970,298
<p><strong>Question:</strong> How do I to plot a function "in a vertical way" in Python.</p> <p><strong>Explanation/Clarification:</strong> Plotted already is function 1 (red in the figure below). This is a normal "horizontal plot". I need to insert a function plotted vertically as is shown as the blue line in the fig...
-2
2016-06-22T13:59:18Z
37,970,438
<pre><code>matplotlib.pyplot.hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, bottom=None, histtype=u'bar', align=u'mid', ...
1
2016-06-22T14:04:54Z
[ "python", "matplotlib", "plot" ]
Which Python 2.7.x Version contains the fix for issue1625
37,970,305
<p>I think I have a Python2.7 installation where this issue is still alive:</p> <p><a href="http://bugs.python.org/issue1625" rel="nofollow">http://bugs.python.org/issue1625</a> (bz2.BZ2File doesn't support multiple streams)</p> <p>Which Python 2.7 version contains the fix? I could not find it on above page.</p>
1
2016-06-22T13:59:26Z
37,970,415
<p>According to <a href="https://hg.python.org/cpython/rev/ad20324229f4" rel="nofollow">https://hg.python.org/cpython/rev/ad20324229f4</a>, you should be using the bz2file module on pypi to get this fix.</p>
1
2016-06-22T14:03:57Z
[ "python" ]
Remove only overlapping ticks in subplots grid
37,970,334
<p>I have created a subplots grid without any spaces between the subplots, with shared x,y-axes. I only show the ticks and labels for the outer subplots. The problem is that the tick numbers overlap at the borders of the subplots. With MaxNLocator, I can remove the upper or lower ticks, but only for all plots at once.<...
0
2016-06-22T14:00:34Z
37,992,850
<p>As @AndrasDeak pointed out, I cannot modify individual subplot ticks as long as I have set sharex=True,sharey=True. <strong>The solution is to set them to false</strong></p> <pre><code>f, ax_grid = plt.subplots(numPlotsY,numPlotsX,sharex=False,sharey=False) </code></pre> <p><strong>and changing the conditional sta...
0
2016-06-23T13:18:52Z
[ "python", "matplotlib" ]
What is the difference between drawing plots using plot, axes or figure in matplotlib?
37,970,424
<p>I'm kind of confused what is going at the backend when I draw plots in matplotlib, tbh, I'm not clear with the hierarchy of plot, axes and figure. I read the documentation and it was helpful but I'm still confused...</p> <p>The below code draws the same plot in three different ways - </p> <pre><code>#creating the ...
4
2016-06-22T14:04:10Z
37,970,713
<p><strong>The first way</strong> let to plot just one figure with (x,y) coordinates. If you just want to get one graphic, you can use this way.</p> <p><strong>The second way</strong> let to plot one or several figure(s) in the same window. As you write it, you will plot just one figure, but you can make something lik...
1
2016-06-22T14:16:04Z
[ "python", "matplotlib" ]