title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
python error:list.remove(x) x not in list
38,593,206
<p>I was trying to compare integer from a list and remove it from the list and append it on an array with python. Every time I run my code there is an error occured. "list.remove(x) x not in list". I can't figure it out whats happening on such an error. Can anybody give me some advice? Thank you.</p> <pre><code>def ma...
-1
2016-07-26T14:50:57Z
38,593,724
<p> <li> If you're trying to map to a 2D (or greater dimensional) array, it won't work because some of what you split will necessarily contain brackets. You can't take the <code>int</code> of brackets. <li> So given that lis is necessarily 1D, lis will never contain maxnum because that would imply that lis is a 2D arra...
0
2016-07-26T15:13:31Z
[ "python", "python-2.7" ]
Clustering with DBSCAN is surprisingly slow
38,593,322
<p>I am experimenting with clustering and I am surprised how slow it seems to be. I have produced a random graph with 30 communities each containing 30 nodes. Nodes in a communities have a 90% chance of being connected and edges between nodes not in the same community have a 10% chance of being connected. I am measuri...
1
2016-07-26T14:56:31Z
38,682,426
<p>Here a solution that speeds up the DBSCAN call about 1890-fold on my machine:</p> <pre><code># the following code should be added to the question's code (it uses G and db) import igraph # use igraph to calculate Jaccard distances quickly edges = zip(*nx.to_edgelist(G)) G1 = igraph.Graph(len(G), zip(*edges[:2])) D...
2
2016-07-31T09:05:25Z
[ "python", "scikit-learn" ]
How to read video stream as input in OpenCV python?
38,593,332
<p>i have a nikon d90 camera. I want to get realtime video to my pc. And i want to read that streaming video using OpenCV python for processing the video frames.how to do that?.pls help me.</p>
-6
2016-07-26T14:57:08Z
38,602,117
<p>I agree with the comments above, more details are needed to know exactly how you are planning connect your camera. Here's a working example for a webcam, notice that you should replace the <code>input_id</code> with your camera's. You would work on <code>frame</code> for further processing.</p> <pre><code>import cv...
0
2016-07-27T01:00:45Z
[ "python", "opencv" ]
Django - create a class instance in AppConfig.ready() only once
38,593,444
<p>I need to create a class instance (lets say backend requests session) on the app startup(runserver), and I don't want to rewrite this session after running other management command. How can I achieve this? I tried several approaches and I'm not sure why something like this doesn't work. </p> <pre><code># app/apps.p...
0
2016-07-26T15:01:17Z
38,608,883
<p>I <em>think</em> it should work if you use an instance variable instead of a class variable:</p> <pre><code># app/apps.py class MyConfig(AppConfig): def __init__(self, app_name, app_module): super(MyConfig, self).__init__(app_name, app_module) self.requests_session = None def ready(self): ...
0
2016-07-27T09:23:44Z
[ "python", "django" ]
Initialize instance with mother class attributes
38,593,456
<p>I am working with fits files that I read with fits.open() from the astropy lib. I get a hdu (header data unit), which is an instance of astropy.io.fits.hdu.image.PrimaryHDU.</p> <p>Now, for a specific project, I want to work on the data in this hdu, by writing specific methods. A good way on doing it, I thought, is...
0
2016-07-26T15:01:47Z
38,593,608
<blockquote> <p>how can I initialize my new object with all the attribute of the parent object?</p> </blockquote> <p>You can't. You don't inherit from an instance (ie object), you inherit from a class.</p> <p>What you should be doing is pass all the arguments you need in order to init both the parent and the subcla...
0
2016-07-26T15:08:27Z
[ "python", "class", "inheritance" ]
Unable to submit python files to HTCondor- placed in 'held'
38,593,488
<p>I am attempting to run a python 2.7 program on HTCondor, however after submitting the job and using 'condor_q' to assess the job status, I see that the job is put in 'held'. </p> <p>After querying using 'condor_q -analyse jobNo.' the error message is "Hold reason: Error from Ubuntu: Failed to execute '/var/lib/cond...
0
2016-07-26T15:03:36Z
38,618,691
<p>Update, managed to solve my problem. I needed to make sure that all directory paths were correct as I found that HTCondor was looking within its own files for the resources my submission program used. I therefore needed to define a variable in the .py file that contains the directory to the resource</p>
0
2016-07-27T16:36:48Z
[ "python", "ubuntu" ]
Remove duplicates from list of dictionaries within list of dictionaries
38,593,527
<p>I have list:</p> <pre><code>my_list = [{'date': '10.06.2016', 'account': [{'name': 'a'}, {'name': 'a'}, {'name': 'b'}, {'name': 'b'}]}, {'date': '22.06.2016', 'account': [{'name': 'a'}, ...
1
2016-07-26T15:05:19Z
38,593,726
<p>Sets can only have <a href="https://docs.python.org/2/glossary.html#term-hashable" rel="nofollow">hashable</a> members and neither lists nor dicts are - but they can be checked for equality.</p> <p>you can do</p> <pre><code>def without_duplicates(inlist): outlist=[] for e in inlist: if e not in out...
0
2016-07-26T15:13:42Z
[ "python", "python-2.7", "dictionary" ]
Remove duplicates from list of dictionaries within list of dictionaries
38,593,527
<p>I have list:</p> <pre><code>my_list = [{'date': '10.06.2016', 'account': [{'name': 'a'}, {'name': 'a'}, {'name': 'b'}, {'name': 'b'}]}, {'date': '22.06.2016', 'account': [{'name': 'a'}, ...
1
2016-07-26T15:05:19Z
38,594,797
<p>This structure is probably over complicated, but it gets the job done.</p> <pre><code>my_list = [{'date': '10.06.2016', 'account': [{'name': 'a'}, {'name': 'a'}, {'name': 'b'}, {'name': 'b'}]}, {'date': '22.06.2016',...
1
2016-07-26T16:03:29Z
[ "python", "python-2.7", "dictionary" ]
Remove duplicates from list of dictionaries within list of dictionaries
38,593,527
<p>I have list:</p> <pre><code>my_list = [{'date': '10.06.2016', 'account': [{'name': 'a'}, {'name': 'a'}, {'name': 'b'}, {'name': 'b'}]}, {'date': '22.06.2016', 'account': [{'name': 'a'}, ...
1
2016-07-26T15:05:19Z
38,594,855
<p>Give this code a try:</p> <pre><code>for d in my_list: for k in d: if k == 'account': v = [] for d2 in d[k]: if d2 not in v: v.append(d2) d[k] = v </code></pre> <p>This is what you get after running the snippet above:</p> <pre><co...
0
2016-07-26T16:07:05Z
[ "python", "python-2.7", "dictionary" ]
Remove duplicates from list of dictionaries within list of dictionaries
38,593,527
<p>I have list:</p> <pre><code>my_list = [{'date': '10.06.2016', 'account': [{'name': 'a'}, {'name': 'a'}, {'name': 'b'}, {'name': 'b'}]}, {'date': '22.06.2016', 'account': [{'name': 'a'}, ...
1
2016-07-26T15:05:19Z
38,595,456
<pre><code>def deduplicate_account_names(l): for d in l: names = set(map(lambda d: d.get('name'), d['account'])) d['account'] = [{'name': name} for name in names] # even shorter: # def deduplicate_account_names(l): # for d in l: # d['account'] = [{'name': name} for name in set(map(lambd...
0
2016-07-26T16:38:40Z
[ "python", "python-2.7", "dictionary" ]
Link to Django Admin
38,593,722
<p>Being relatively new to Django and despite studying the documentation I am somewhat stuck and would greatly appreciate any help.</p> <p>I have a template for a list view that is only available for staff.</p> <p>I want to be able to click on the indidvidual link in the list and be taken through to the individual it...
0
2016-07-26T15:13:29Z
38,595,366
<p>To go to a particular contact's edit page use:</p> <pre><code>&lt;a href="{% url 'admin:contacts_contact_change' contact.id %}"&gt;link name&lt;/a&gt; </code></pre> <p>This is described in the <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#admin-reverse-urls" rel="nofollow">documentation</a>.</p...
0
2016-07-26T16:34:13Z
[ "python", "django" ]
Unexpected socket.getaddrinfo behavior in Python using SOCK_STREAM
38,593,744
<ul> <li>I'm busy trying to use <code>socket.getaddrinfo()</code> to resolve a domain name. When I pass in:</li> </ul> <p><code>host = 'www.google.com', port = 80, family = socket.AF_INET, type = 0, proto = 0, flags = 0</code> </p> <p>I get a pair of socket infos like you'd expect, one with SocketKind.SOCK_DGRAM (for...
0
2016-07-26T15:14:39Z
38,660,201
<p><code>socket.SOCK_STREAM</code> should be passed in the <code>type</code> field. Using it in the <code>proto</code> field probably has a very random effect, which is what you're seeing. Proto only takes the <code>IPPROTO</code> constants. For a raw socket, you should use <code>type = socket.SOCK_RAW</code>. I'm not ...
0
2016-07-29T13:30:54Z
[ "python", "sockets", "python-3.x", "getaddrinfo" ]
Numerically Representing Mathematica's Root Object in Open-Source Language
38,593,771
<h2>Question</h2> <p>I would like to reproduce a <code>Root[]</code> object, <em>ideally</em> in a <code>python</code> function.</p> <p>Is there any particular library that would be suited for this process?</p> <h2>Attempts</h2> <p>If I understand the <code>Root[]</code> function properly, it is simply finding the ...
0
2016-07-26T15:15:48Z
38,596,170
<p>If you are interested in symbolic calculations, you can use <a href="http://www.sympy.org/en/index.html" rel="nofollow">SymPy</a>. In particular, SymPy has polynomial objects and the classes <code>RootOf</code> and <code>CRootOf</code> to represent the roots of polynomials.</p> <p>For example,</p> <pre><code>In [...
2
2016-07-26T17:17:52Z
[ "python", "numpy", "scipy", "wolfram-mathematica", "solver" ]
Rosalind consensus and profile python
38,593,923
<p>I'm working on the problem "Consensus nd Profile" on the Rosalind Bioinformatics website (<a href="http://rosalind.info/problems/cons/" rel="nofollow">http://rosalind.info/problems/cons/</a>). I tried my code using the sample input on the website and my output matches the sample output. But when I tried the larger d...
1
2016-07-26T15:22:39Z
38,624,216
<p>Your algorithm is totally fine. As @C_Z_ pointed out "make sure your format matches the sample output exactly" which is unfortunately not the case.</p> <pre><code>print k + ":" + " ".join(str(x) for x in v) </code></pre> <p>should be</p> <pre><code>print k + ": " + " ".join(str(x) for x in v) </code></pre> <p>an...
1
2016-07-27T22:28:09Z
[ "python", "python-2.7", "bioinformatics", "rosalind" ]
Warning messages when importing matplotlib.pyplot
38,593,969
<p>When importing matplotlib:</p> <pre><code>from matplotlib import pyplot as plt </code></pre> <p>I get an User Warning:</p> <pre><code>~/.virtualenvs/cv/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment. </code></pre...
1
2016-07-26T15:24:11Z
38,633,199
<p>I deleted fontList.cache and tex.cach as advised on <a href="http://stackoverflow.com/questions/34771191/matplotlib-taking-time-when-being-imported">answer to the question</a> linked by whrrgarbl. I addition, I created a file <code>~/.matplotlib/matplotlibrc</code> and added line: <code>backend: TkAgg</code> as sugg...
1
2016-07-28T10:03:44Z
[ "python", "matplotlib" ]
Fail in test of function, it doesn't update database
38,593,978
<p>There is my function:</p> <p>views.py</p> <pre><code>def save(request): data = {'mark':request.POST.get('mark'), 'task':request.POST.get('task')} Task.objects.filter(id=request.POST.get('s')).update(mark=data['mark'], task=data['task']) return redirect(list) </code></pre> <p>What is wrong in my test?I...
-1
2016-07-26T15:24:24Z
38,595,460
<p>Your view expects <code>request.POST['s']</code> to contain the id</p> <pre><code>Task.objects.filter(id=request.POST.get('s')) </code></pre> <p>but you have forgotten to include it in your data.</p> <pre><code>data = {'mark': False, 'task': '1'} </code></pre> <p>An easy way to debug problems like this is to add...
1
2016-07-26T16:39:04Z
[ "python", "django", "django-testing", "django-tests" ]
Getting the maximum mode per group using groupby
38,594,027
<p>I have generated a table that shows the mode values of my dataset. The dataset was originally grouped by "date", "hour" and "room" in order to be able to get the mode value of foot traffic. The groupby was performed as follows:</p> <pre><code>dataframe = df.groupby([df['date'], df['hour'], df['room']]) </code></pre...
0
2016-07-26T15:26:04Z
38,594,308
<p>I was looking for something like this. FYI you can get this with <code>df.head(n=10).to_csv(path, index=False)</code></p> <pre><code>room,time,capacity,areaName,hour,date,traffic room1,Mon Nov 02 09:00:00,40,area01,9,2,14 room1,Mon Nov 02 09:05:00,40,area01,9,2,15 room1,Mon Nov 02 09:10:00,80,area01,9,2,23 room...
0
2016-07-26T15:38:44Z
[ "python", "python-3.x", "pandas", "dataframe", "lambda" ]
Error running tests with Conda and Tox
38,594,047
<p>I am having trouble running tests with Tox while having virtual environments created with Conda. The steps to reproduce the error are below.</p> <p>Download the repository (it is small) and <code>cd</code> to it:</p> <pre><code>git clone https://github.com/opensistemas-hub/osbrain.git cd osbrain </code></pre> <p>...
1
2016-07-26T15:27:09Z
38,731,951
<p>Virtualenv and conda/conda-env do not currently play nice together. See <a href="https://github.com/conda-forge/staged-recipes/issues/1139" rel="nofollow">https://github.com/conda-forge/staged-recipes/issues/1139</a> and <a href="https://groups.google.com/a/continuum.io/forum/#!topic/conda/63B0jnPR-V4" rel="nofollo...
1
2016-08-02T23:20:28Z
[ "python", "conda", "tox" ]
Run library module as a script by cron (python -m)
38,594,059
<p>I created python library. In order to avoid install of executable python scripts I allowed library modules to work as executables. It is possible to run module as script with -m opion (python -m). Manually everything works:</p> <pre><code>$ python -m Library.Core.Runner runFirst </code></pre> <p>But when I try to ...
0
2016-07-26T15:27:41Z
38,654,211
<p>Add user name to let cron run the task on behalf of him:</p> <pre><code>*/5 * * * * &lt;username&gt; /usr/bin/python -m Library.Core.Runner runFirst &gt;&gt; /var/log/MyProject/runFirst.log 2&gt;&amp;1 */5 * * * * igor /usr/bin/python -m Library.Core.Runner runFirst &gt;&gt; /var/log/MyProject/runFirst.log 2&gt;&am...
0
2016-07-29T08:36:16Z
[ "python", "cron" ]
subprocess.call() or subprocess.Popen for generating/using output files
38,594,141
<p>I am trying to write a Python code to interact with another software that uses command line prompts. Once the command line prompt is executed, multiple output files are generated in the directory and the software uses those output files to do some calculations. Plus, the rest of my program utilizes those output file...
0
2016-07-26T15:32:03Z
38,594,599
<p>give this a try: <code>subprocess.call('sfit4Layer0.py -bv5 -fs', shell=True)</code></p>
0
2016-07-26T15:53:34Z
[ "python", "subprocess" ]
subprocess.call() or subprocess.Popen for generating/using output files
38,594,141
<p>I am trying to write a Python code to interact with another software that uses command line prompts. Once the command line prompt is executed, multiple output files are generated in the directory and the software uses those output files to do some calculations. Plus, the rest of my program utilizes those output file...
0
2016-07-26T15:32:03Z
38,594,664
<p>If you are trying to call another python script from your python script the subprocess.call() method is suited for your operation.</p> <p>I would suggest you to turn </p> <pre><code>subprocess.call(['sfit4Layer0.py', '-bv5', '-fs'], shell=True) </code></pre> <p>Hope this solution works.</p> <p>Popen is generally...
0
2016-07-26T15:56:16Z
[ "python", "subprocess" ]
subprocess.call() or subprocess.Popen for generating/using output files
38,594,141
<p>I am trying to write a Python code to interact with another software that uses command line prompts. Once the command line prompt is executed, multiple output files are generated in the directory and the software uses those output files to do some calculations. Plus, the rest of my program utilizes those output file...
0
2016-07-26T15:32:03Z
38,595,732
<pre><code>subprocess.call(['sfit4Layer0.py', '-bv5', '-fs'], shell=False) </code></pre> <ol> <li>assumes that sfit4Layer0.py is executable, which it may not be</li> <li>assumes that sfit4Layer0.py includes the #!/usr/bin/python shebang, which it may not. </li> </ol> <p>if the script does contain a shebang and is ...
0
2016-07-26T16:52:39Z
[ "python", "subprocess" ]
pandas convert string columns to datetime, allowing missing but not invalid
38,594,246
<p>I have a <code>pandas</code> data frame with multiple columns of strings representing dates, with empty strings representing missing dates. For example</p> <pre><code>import numpy as np import pandas as pd # expected date format is 'm/%d/%Y' custId = np.array(list(range(1,6))) eventDate = np.array(["06/10/1992",...
1
2016-07-26T15:36:24Z
38,595,584
<p><code>pandas</code> doesn't have an option that exactly replicates what you want, here's one way to do it, which should be relatively efficient.</p> <pre><code>In [4]: dfBad Out[4]: custId eventDate registerDate 0 1 06/10/1992 06/08/2002 1 2 08/24/2012 20/08/2012 2 3 04/24/2015 04/2...
1
2016-07-26T16:44:53Z
[ "python", "numpy", "pandas", "python-datetime" ]
pandas convert string columns to datetime, allowing missing but not invalid
38,594,246
<p>I have a <code>pandas</code> data frame with multiple columns of strings representing dates, with empty strings representing missing dates. For example</p> <pre><code>import numpy as np import pandas as pd # expected date format is 'm/%d/%Y' custId = np.array(list(range(1,6))) eventDate = np.array(["06/10/1992",...
1
2016-07-26T15:36:24Z
38,596,497
<p>Just to take the accepted answer a little further, I replaced the columns of all valid or missing strings with their parsed datetimes, and then raised an error for the remaining unparsed columns:</p> <pre><code>dtCols = ['eventDate', 'registerDate'] dts = dfBad[dtCols].apply(lambda x: pd.to_datetime(x, errors='coer...
1
2016-07-26T17:37:37Z
[ "python", "numpy", "pandas", "python-datetime" ]
how to compute quantile bins in Pandas when there are ties in the data?
38,594,277
<p>Consider the following simple example. I am interested in getting a categorical variable that contains categories corresponding to quantiles.</p> <pre><code> df = pd.DataFrame({'A':'foo foo foo bar bar bar'.split(), 'B':[0, 0, 1]*2}) df Out[67]: A B 0 foo 0 1 foo 0 2 foo 1 3 b...
0
2016-07-26T15:37:47Z
38,596,578
<p>IIUC, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html" rel="nofollow"><code>numpy.digitize</code></a></p> <pre><code>df['C'] = df.groupby(['A'])['B'].transform(lambda x: np.digitize(x,bins=np.array([0,1,2]))) A B C 0 foo 0 1 1 foo 0 1 2 foo 1 2 3 bar 0...
1
2016-07-26T17:42:06Z
[ "python", "pandas", "scipy", "statistics", "stata" ]
How to use logging, pytest fixture and capsys?
38,594,296
<p>I am trying to unit-test some algorithm that uses logging library.</p> <p>I have a fixture that creates a logger.</p> <p>In my <strong>1st test case</strong>, I do not use this fixture and uses a print to log to stdout. This test case <strong>passes</strong>.</p> <p>In my <strong>2nd test case</strong>, I use thi...
1
2016-07-26T15:38:21Z
38,609,291
<p>I'm guessing the logger gets created (via the fixture) before the <code>capsys</code> fixture is set up.</p> <p>Some ideas:</p> <ul> <li>Use the <a href="https://pypi.python.org/pypi/pytest-catchlog" rel="nofollow">pytest-catchlog</a> plugin</li> <li>Maybe reverse <code>logger, capsys</code></li> <li>Make <code>lo...
1
2016-07-27T09:41:49Z
[ "python", "unit-testing", "logging", "py.test" ]
How to use logging, pytest fixture and capsys?
38,594,296
<p>I am trying to unit-test some algorithm that uses logging library.</p> <p>I have a fixture that creates a logger.</p> <p>In my <strong>1st test case</strong>, I do not use this fixture and uses a print to log to stdout. This test case <strong>passes</strong>.</p> <p>In my <strong>2nd test case</strong>, I use thi...
1
2016-07-26T15:38:21Z
38,614,135
<p>Thanks a lot for your ideas!</p> <p>Reverse <code>logger, capsys</code>, make <code>logger</code> request the <code>capsys</code> fixture and use <code>capfd</code> do not change anything.</p> <p>I tried <a href="https://pypi.python.org/pypi/pytest-catchlog" rel="nofollow">pytest-catchlog</a> plugin and it <strong...
1
2016-07-27T13:17:55Z
[ "python", "unit-testing", "logging", "py.test" ]
Converting Excel to CSV python
38,594,352
<p>I am using xlrd to convert my .xls Excel file to a CSVfile yet when I try to open the workbook my program crashes sending an error message</p> <pre><code>bof_error('Expected BOF record; found %r' % self.mem[savpos:savpos+8]) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/xlrd/...
-1
2016-07-26T15:40:56Z
38,595,058
<p>I would use <code>[openpyxl]</code><a class='doc-link' href="https://stackoverflow.com/documentation/python/2986/python-and-excel#t=20160726160750581884">1</a> for this.</p> <pre><code>import openpyxl wb = openpyxl.load_workbook(file_name) ws = wb.worksheets[page_number] table = [] for row_num in range(ws.get_highe...
0
2016-07-26T16:17:20Z
[ "python" ]
Does django's URL Conf support mapping an argument to strings?
38,594,396
<h2>The Problem</h2> <p>I'm unsure of the best way to phrase this, but here goes: (note some of this may not be syntactically/semantically correct, as it's not my actual code, but I needed it to help explain what I'm asking) </p> <p>Say I have a model the model <code>Album</code>:</p> <pre><code>Class Album(models.M...
1
2016-07-26T15:43:11Z
38,594,770
<p>I would change the field to a <code>CharField</code>, and use the URL slug as the actual value rather than the display value:</p> <pre><code>Class Album(models.Model): ALBUM_TYPE_SINGLE = 'singles' ALBUM_TYPE_DEMO = 'demos' ALBUM_TYPE_GREATEST_HITS = 'greatest-hits' ALBUM_CHOICES = ( (ALBUM_...
2
2016-07-26T16:01:55Z
[ "python", "django" ]
Smartsheet CHECKBOX Cells Always Returned as Empty
38,594,429
<p>Whenever I retrieve a SmartSheet row and loop through the cells within it, all cells of type CHECKBOX always have a displayValue or value of Null, regardless of the status of the checkbox on the sheet. Has anyone else experienced this? (I am using their python sdk)</p>
1
2016-07-26T15:44:40Z
38,619,885
<p>It's possible for the value of any cell to be null if the cell has never had any value set (e.g. if you add a value to a cell in a new row, all the other cells will be null). I'm guessing that's what you're seeing.</p> <p>If you check one of those checkbox cells, save, then uncheck it, you should see its value as ...
0
2016-07-27T17:45:46Z
[ "python", "smartsheet-api" ]
Smartsheet CHECKBOX Cells Always Returned as Empty
38,594,429
<p>Whenever I retrieve a SmartSheet row and loop through the cells within it, all cells of type CHECKBOX always have a displayValue or value of Null, regardless of the status of the checkbox on the sheet. Has anyone else experienced this? (I am using their python sdk)</p>
1
2016-07-26T15:44:40Z
38,623,660
<p>I believe you've found a bug with the Python SDK.</p> <p>Kevin's answer correctly describes the behavior of the API itself, as I verified (using Postman), via the following request / response.</p> <p><strong>Get Row - Request:</strong></p> <pre><code>GET https://api.smartsheet.com/2.0/sheets/7359436428732292/rows...
2
2016-07-27T21:40:20Z
[ "python", "smartsheet-api" ]
Smartsheet CHECKBOX Cells Always Returned as Empty
38,594,429
<p>Whenever I retrieve a SmartSheet row and loop through the cells within it, all cells of type CHECKBOX always have a displayValue or value of Null, regardless of the status of the checkbox on the sheet. Has anyone else experienced this? (I am using their python sdk)</p>
1
2016-07-26T15:44:40Z
39,716,751
<p>in the cell.py file of the smartsheet library, replace the old:</p> <pre><code>@value.setter def value(self, value): if isinstance(value, six.string_types): self._value = value </code></pre> <p>with:</p> <pre><code>@value.setter def value(self, value): if isinstance(value, six.string_types) or val...
0
2016-09-27T05:38:49Z
[ "python", "smartsheet-api" ]
pyVmomi start service on virtual machine
38,594,473
<p>I am trying to start a service within the client virtual machine through pyVmomi. I couldn't find much in the official documentation on this, and I searched the net to no avail. I then modified the code I have used to successfully launch a silent MSI install, to simply run cmd.exe with the argument 'net start' plus ...
0
2016-07-26T15:47:19Z
38,954,175
<p>In the end I couldn't find an answer so instead I simply wrote a batch file with the net start command inside it, then executed this using the processManager above.</p>
0
2016-08-15T11:25:24Z
[ "python", "pyvmomi" ]
Trouble calling R function from Python with rpy2
38,594,515
<p>I am trying to use rpy2 to call the R package MatchIt. I am having difficulty seeing the outcome of the matched pairs from the $match.matrix. Here is the R code I am trying to execute in python.</p> <pre><code>matched &lt;- cbind(lalonde[row.names(foo$match.matrix),"re78"],lalonde[foo$match.matrix,"re78"]) </code><...
0
2016-07-26T15:50:16Z
38,600,758
<p>Here <code>lalonde</code> is defined elsewhere (but thanks to @Parfait's question we know that this is a data frame). Now you'll have to break down your one-liner triggering the error to pinpoint the exact place of trouble (and we can't do that for you - the thing about self-contained and reproducible examples is th...
2
2016-07-26T22:15:57Z
[ "python", "rpy2", "cbind" ]
Use Scrapy to get information from a website that generates data using java script
38,594,544
<p>I am trying to crawl a website using Scrapy, however the website URL doesn't change, the pages are loaded using java script. </p> <p>This is how the site and URL look before I perform a search: <a href="http://i.stack.imgur.com/nBx7H.png" rel="nofollow"><img src="http://i.stack.imgur.com/nBx7H.png" alt="image 1"></...
1
2016-07-26T15:51:14Z
38,602,655
<ul> <li>You need analyse the website how to load the data. Maybe you can read the URL and HTTP header.</li> <li>Use some tools (like POSTman) to simulate the process about loading data.</li> <li>Use scrapy to implement the process.</li> </ul>
0
2016-07-27T02:18:42Z
[ "python", "web-scraping", "scrapy", "scrapy-spider" ]
python query with mongo
38,594,616
<p>I'm beginner in python. However in my python code I'm querying mongodb.</p> <pre><code>from pymongo import MongoClient import sys client = MongoClient() db = client.customer-care cursor = db.interactions.find() for document in cursor: sys.stdout=open("test.txt","w") print(document) sys.stdout.close(...
-1
2016-07-26T15:54:08Z
38,595,031
<p>Python <a href="https://docs.python.org/3/reference/lexical_analysis.html#identifiers" rel="nofollow">identifiers</a> cannot include the dash character. </p> <p>If you must use a database name with a dash in it (I would advise that you consider camel-case), use this syntax:</p> <pre><code>db = client['customer-car...
1
2016-07-26T16:16:13Z
[ "python", "mongodb" ]
How to integrate a SK-Learn Naive Bayes trained model in Python Flask prediction web app?
38,594,624
<p>I'm trying to build a prediction tool using SK-Learn's Naive Bayes Classifier and the Python Flask micro-framework. From what I have googled, I can pickle the model and then unpickle the model when I load the app on the browser, but how can I do that exactly?</p> <p>My app should receive user input values, then pas...
0
2016-07-26T15:54:24Z
38,620,244
<p>I think the problem with your code is that the data from your form is being read as a string. For example, in <code>input_aqi = request.form['aqi']</code>, <code>input_aqi</code> has a string. Therefore, in <code>output_acute_bronchitis = model_acute_bronchitis.predict(input_list)</code>, you end up passing <code>pr...
1
2016-07-27T18:08:06Z
[ "python", "flask", "scikit-learn", "prediction", "naivebayes" ]
How to feature-ize timeseries data in Pandas?
38,594,625
<p>I have data that are structured as below:</p> <pre><code>Group, ID, Time, Feat1, Feat2, Feat3 A, 1, 0, 1.52, 2.94, 3.1 A, 1, 2, 1.67, 2.99, 3.3 A, 1, 4, 1.9, 3.34, 5.6 </code></pre> <p>In this data, there are individuals who have been measured repeatedly.</p> <p>I'd like to restructure the data such that each fea...
1
2016-07-26T15:54:25Z
38,595,389
<pre><code>df = pd.DataFrame({'Group': {0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'A', 5: 'A'}, 'Time': {0: 0, 1: 2, 2: 4, 3: 0, 4: 2, 5: 4}, 'ID': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2}, 'Feat1': {0: 1.52, 1: 1.6699999999999999, 2: 1.8999999999999999, 3: 1.52, 4: 1.66999...
1
2016-07-26T16:35:30Z
[ "python", "pandas" ]
Python Lambda function can't execute HTTPS cURL command
38,594,627
<p>I have a Lambda function which is defined by the following simple script which directs my EC2 instance to perform a backup:</p> <pre><code>def lambda_handler(event, context): import subprocess result = subprocess.call("curl -k https://loadbalancer.stuff.domain.com/backup/", shell=True) return result </c...
-1
2016-07-26T15:54:33Z
38,600,602
<p>Your Lambda function is executing outside of your VPC.</p> <p>But your load balancer is inside your VPC, and not publicly accessible. So the Lambda function does not have a network path to the load balancer.</p> <p>There are 2 possible resolutions:</p> <ol> <li>Put your Lambda function inside your VPC, or</li> <l...
1
2016-07-26T22:03:03Z
[ "python", "amazon-web-services", "curl", "amazon-lambda" ]
How do I run "windows features" through Python?
38,594,634
<p>I'm trying to run <code>tftp</code> from a python script. I enabled it as a Windows 10 feature (<a href="http://www.trishtech.com/2014/10/enable-tftp-telnet-in-windows-10/" rel="nofollow">http://www.trishtech.com/2014/10/enable-tftp-telnet-in-windows-10/</a>) so I am able to run it via the command line. But when I t...
-1
2016-07-26T15:54:46Z
38,600,996
<p>See response from: @eryksun for the correct answer. Quoted here:</p> <p>"To work in either case, use system32 = 'SysNative' if platform.architecture()[0] == '32bit' else 'System32'. Then create the fully qualified path as tftp_path = os.path.join(os.environ['SystemRoot'], system32, 'TFTP.EXE')"</p>
0
2016-07-26T22:40:34Z
[ "python", "windows", "command-line" ]
Pylint is reporting false-positive error
38,594,658
<pre><code>error zb1.buildup 1 0 Unable to import 'application' </code></pre> <p>Here is the screenshot of my structure. It's screaming about all my imports from my current project. Does it not add the project as a path?</p> <p>I know pylint is a static code checker but this feels obviously wrong. Let me k...
1
2016-07-26T15:55:53Z
38,668,697
<p>You're having an issue with the python search path. A relatively simple solution is to define the PYTHONPATH environment variable. Assuming that you're trying to invoke pylint from within zb1, the following should work:</p> <pre><code>PYTHONPATH=`pwd` pylint --output-format=html ../zb1 &gt; pylint.html </code></pre...
1
2016-07-29T23:10:16Z
[ "python", "python-3.x", "pylint" ]
What kind of monitor has Python?
38,594,673
<p>What kind of monitors (concurrent programming) has Python? Brinch Hansen, Hoare or Lampson / Redell (like Java)?</p> <ul> <li>Brinch Hansen: the notifier thread exits the monitor, and the notified continues.</li> <li>Hoare: the notifier thread enters in a special queue, and the notified continues.</li> <li>Lampson ...
-1
2016-07-26T15:56:36Z
38,594,836
<p>This is answered in the official <a href="https://docs.python.org/2/library/threading.html#condition-objects" rel="nofollow">documentation</a>:</p> <blockquote> <p>The wait() method releases the lock, and then blocks until it is awakened by a notify() or notifyAll() call for the same condition variable in ano...
1
2016-07-26T16:05:46Z
[ "python", "concurrency" ]
Extract Json without property names in Python
38,594,688
<p>I am trying to extract location data from a json API service. This is how far i got:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; import urllib &gt;&gt;&gt; from urllib import urlopen &gt;&gt;&gt; url = urlopen('THE API URL').read() &gt;&gt;&gt; print url [["244630489","53.099040","6.040552","0","0","99","2...
-1
2016-07-26T15:57:39Z
38,594,850
<p>You're getting an array represented as a list of list, do the following:</p> <pre><code>import json import urllib from urllib import urlopen url = urlopen('THE API URL').read() print url print url[0][1:3] </code></pre> <p>Which will print:</p> <pre><code>['53.099040', '6.040552'] </code></pre> <p>Or similarly wi...
0
2016-07-26T16:06:37Z
[ "python", "json" ]
Extract Json without property names in Python
38,594,688
<p>I am trying to extract location data from a json API service. This is how far i got:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; import urllib &gt;&gt;&gt; from urllib import urlopen &gt;&gt;&gt; url = urlopen('THE API URL').read() &gt;&gt;&gt; print url [["244630489","53.099040","6.040552","0","0","99","2...
-1
2016-07-26T15:57:39Z
38,594,853
<p>If you want to get a part of <code>result</code>, you would do</p> <pre><code>part = result[0][1:3] </code></pre> <p>or</p> <pre><code>a=result[0][1] b=result[0][2] </code></pre> <p>as <code>result</code>is a nested list in your case</p>
0
2016-07-26T16:06:58Z
[ "python", "json" ]
object not iterable - how do I fix this?
38,594,695
<p>Right, I have changed a whole load of things and hopefully corrected some errors. The error message is now: <code>&gt;&gt; for row in teacherbooklist: TypeError: 'int' object is not iterable</code></p> <pre class="lang-py prettyprint-override"><code>username = input("Enter Username: ") password = input("Enter Passw...
-5
2016-07-26T15:58:07Z
38,595,254
<p>The documentation does not specify any return value of either the <code>writerow</code> or the <code>writerows</code> method of <a href="https://docs.python.org/2.7/library/csv.html#writer-objects" rel="nofollow">Writer objects</a> so you should not rely on that.</p> <p><code>teacherbooklist</code> seems to be an i...
0
2016-07-26T16:27:55Z
[ "python", "csv" ]
Python 2 Notebook in JuliaBox and Plotting Graphs
38,594,706
<p>I am using a Python 2 notebook in JuliaBox. I am attempting to plot some data, but I keep getting the error:</p> <pre><code>TclError: no display name and no $DISPLAY environment variable </code></pre> <p>Julia itself has the capabilities to plot via python in a Julia notebook. I've tested this myself. The PyPlo...
0
2016-07-26T15:58:38Z
38,596,040
<p>Julia doesn't ask you to do so explicitly, but when using matplotlib in python, you need to instruct it to <em>show</em> the resulting plot.</p> <p>i.e. in python add the line:</p> <pre><code>plt.show() </code></pre> <p>I will also point out that the arguments you passed are lists, not numpy arrays. Your example ...
1
2016-07-26T17:09:07Z
[ "python", "matplotlib", "julia-lang" ]
Django nested admin: how to set foreign key to grandparents'id?
38,594,707
<p>I have a django project where I use <a href="https://github.com/theatlantic/django-nested-admin" rel="nofollow">nested-admin</a>, and I'm trying to figure out how to set the foreign key of an element to its grandparents' id.</p> <p>I have the following <code>model.py</code>:</p> <pre><code>class Person(models.Mode...
0
2016-07-26T15:58:40Z
38,673,789
<h3>Answer to the question asked</h3> <p>I managed to get something working using the <a href="https://github.com/s-block/django-nested-inline/blob/master/nested_inline/admin.py#L45" rel="nofollow">nested_admin</a> source code.</p> <p>First, exclude the <code>person</code> field from the <code>project</code> form:</p...
0
2016-07-30T12:09:34Z
[ "python", "python-3.x", "django-models", "django-forms" ]
How do I push new files to GitHub?
38,594,717
<p>I created a new repository on github.com and then cloned it to my local machine with</p> <pre><code>git clone https://github.com/usrname/mathematics.git </code></pre> <p>I added 3 new files under the folder <code>mathematics</code></p> <pre><code>$ tree . ├── LICENSE ├── numerical_analysis │   â”...
9
2016-07-26T15:59:16Z
38,595,049
<pre><code>import subprocess p = subprocess.Popen("git rev-parse HEAD".split(), stdout=subprocess.PIPE) out, err = p.communicate() sha = out.strip() </code></pre> <p>There's probably a way to do this with PyGithub, but this should work for a quick hack.</p>
0
2016-07-26T16:17:03Z
[ "python", "git", "github", "pygithub" ]
How do I push new files to GitHub?
38,594,717
<p>I created a new repository on github.com and then cloned it to my local machine with</p> <pre><code>git clone https://github.com/usrname/mathematics.git </code></pre> <p>I added 3 new files under the folder <code>mathematics</code></p> <pre><code>$ tree . ├── LICENSE ├── numerical_analysis │   â”...
9
2016-07-26T15:59:16Z
38,595,057
<p>If you do not need pygithub specifically, the dulwich git-library offers <a href="https://www.dulwich.io/docs/tutorial/porcelain.html" rel="nofollow">high level git commands</a>. For the commands have a look at <a href="https://www.dulwich.io/apidocs/dulwich.porcelain.html" rel="nofollow">https://www.dulwich.io/apid...
0
2016-07-26T16:17:20Z
[ "python", "git", "github", "pygithub" ]
How do I push new files to GitHub?
38,594,717
<p>I created a new repository on github.com and then cloned it to my local machine with</p> <pre><code>git clone https://github.com/usrname/mathematics.git </code></pre> <p>I added 3 new files under the folder <code>mathematics</code></p> <pre><code>$ tree . ├── LICENSE ├── numerical_analysis │   â”...
9
2016-07-26T15:59:16Z
39,616,681
<p>I can give you some information support, but also one concrete solution. </p> <p><a href="https://github.com/gitpython-developers/GitPython/blob/db44286366a09f1f65986db2a1c8b470fb417068/git/test/test_index.py" rel="nofollow">Here</a> you can find examples of adding new files to your repository, and <a href="https:/...
1
2016-09-21T12:33:37Z
[ "python", "git", "github", "pygithub" ]
How do I push new files to GitHub?
38,594,717
<p>I created a new repository on github.com and then cloned it to my local machine with</p> <pre><code>git clone https://github.com/usrname/mathematics.git </code></pre> <p>I added 3 new files under the folder <code>mathematics</code></p> <pre><code>$ tree . ├── LICENSE ├── numerical_analysis │   â”...
9
2016-07-26T15:59:16Z
39,620,098
<p>I tried to use the <a href="https://developer.github.com/v3/" rel="nofollow">GitHub API</a> to commit multiple files. This page for the <a href="https://developer.github.com/v3/git/" rel="nofollow">Git Data API</a> says that it should be "pretty simple". For the results of that investigation, see <a href="http://sta...
2
2016-09-21T14:59:19Z
[ "python", "git", "github", "pygithub" ]
How do I push new files to GitHub?
38,594,717
<p>I created a new repository on github.com and then cloned it to my local machine with</p> <pre><code>git clone https://github.com/usrname/mathematics.git </code></pre> <p>I added 3 new files under the folder <code>mathematics</code></p> <pre><code>$ tree . ├── LICENSE ├── numerical_analysis │   â”...
9
2016-07-26T15:59:16Z
39,623,010
<p>If PyGithub's documentation is not usable (and it doesn't look so), and you just want to push a commit (not doing anything fancy with issues, repo configuration, etc.), you would probably be better off directly interfacing with git, either calling the <code>git</code> executable or using a wrapper library such as <a...
1
2016-09-21T17:30:54Z
[ "python", "git", "github", "pygithub" ]
How do I push new files to GitHub?
38,594,717
<p>I created a new repository on github.com and then cloned it to my local machine with</p> <pre><code>git clone https://github.com/usrname/mathematics.git </code></pre> <p>I added 3 new files under the folder <code>mathematics</code></p> <pre><code>$ tree . ├── LICENSE ├── numerical_analysis │   â”...
9
2016-07-26T15:59:16Z
39,627,647
<p><strong>Note:</strong> This version of the script was called from inside the GIT repository because I removed the repository name from the file paths.</p> <p>I finally figured out how to use <a href="https://github.com/PyGithub/PyGithub" rel="nofollow">PyGithub</a> to commit multiple files:</p> <pre><code>import b...
1
2016-09-21T22:45:25Z
[ "python", "git", "github", "pygithub" ]
Access actual Features after a Feature Selection Pipeline in SciKit-Learn
38,594,734
<p>I use a feature selection in combination with a pipeline in SciKit-Learn. As a feature selection strategy I use <code>SelectKBest</code>.</p> <p>The pipeline is created and executed like this:</p> <pre><code>select = SelectKBest(k=5) clf = SVC(decision_function_shape='ovo') parameters = dict(feature_selection_...
0
2016-07-26T15:59:51Z
38,596,968
<p>For your example, you can get the scores of all your features using <code>cv.best_estimator_.named_steps['feature_selection'].scores_</code>. This will give you the scores for all of your features and using them you should be able to see which were the chosen features. Similarly, you can also get the pvalues by <cod...
1
2016-07-26T18:05:33Z
[ "python", "machine-learning", "scikit-learn", "feature-detection" ]
python/matplotlib boxplot on a x axis
38,594,753
<p>My data set is a list with 6 numbers: <code>[23948.30, 23946.20, 23961.20, 23971.70, 23956.30, 23987.30]</code></p> <p>I want them to be in a horizontal box plot, line on the x axis, with <code>23855</code> and <code>24472</code> as the limit of the x axis, so the box plot will be in the middle of the line. If this...
1
2016-07-26T16:01:02Z
38,595,812
<p>I'm not sure I understood everything in your post, but here are my corrections to your code:</p> <pre><code>l = [23948.30, 23946.20, 23961.20, 23971.70, 23956.30, 23987.30] def box_plot(circ_list): fig, ax = plt.subplots() plt.boxplot(circ_list, 0, 'rs', 0, showmeans=True) plt.ylim((0.75, 1.25)) ax...
0
2016-07-26T16:56:23Z
[ "python", "matplotlib", "boxplot" ]
Coercing to Unicode: need string or buffer, function found on Django form
38,594,814
<p>I'm new on Django and I'm making a formwhen I press submit I'm getting this error that I haven't seen before: <code>TypeError at /catalog/ coercing to Unicode: need string or buffer, function found</code></p> <p>My <code>forms.py</code> looks like:</p> <pre><code>class AppsForm(forms.Form): def __init__(self, ...
0
2016-07-26T16:04:32Z
38,594,942
<p>One of the things you're including in that string concatenation is <code>deploy</code>. Since that isn't defined within the current scope, Python will look for the nearest declaration of that name, which is the current function itself, hence the error.</p> <p>I don't know where that name is actually supposed to be ...
1
2016-07-26T16:11:17Z
[ "python", "django", "forms", "unicode" ]
Process stops immediately after start
38,594,892
<p>Hope you can help me. I'm coding on a Raspberry Pi with MonoDevelop.</p> <p>I want to execute a python script with C# and read from it.</p> <pre><code>class Program { public static void Main(string[] args) { Process p = new Process(); p.OutputDataReceived += new DataReceivedEventHandler(Ou...
0
2016-07-26T16:08:50Z
39,074,371
<p>As @Gusman said, the problem was the sudo. And as recommended i am using now the <a href="https://github.com/cypherkey/RaspberryPi.Net" rel="nofollow">DLL</a> to access the GPIO Pins. Even if the Raspberry Pi is not fully supported.</p>
0
2016-08-22T08:14:07Z
[ "c#", "python", "linux", "process", "monodevelop" ]
Clicking buttons and filling forms with Selenium and PhantomJS
38,594,900
<p>I have a simple task that I want to automate. I want to open a URL, click a button which takes me to the next page, fills in a search term, clicks the "search" button and prints out the url and source code of the results page. I have written the following.</p> <pre><code>from selenium import webdriver import time ...
1
2016-07-26T16:09:21Z
38,595,944
<p>The <code>WebDriverWait</code> approach actually works for me as is:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.PhantomJS() dri...
1
2016-07-26T17:03:50Z
[ "python", "selenium", "automation", "phantomjs" ]
Django REST Framework Foreign Key - NOT NULL constraint failed
38,594,960
<p>I have the following setup in Django REST Framework:</p> <p><strong>models.py:</strong></p> <pre><code>class Device(models.Model): name = models.CharField() latitude = models.FloatField() longitude = models.FloatField() altitude = models.FloatField() class Event(models.Model): id_device = mode...
0
2016-07-26T16:12:06Z
38,596,738
<p>You haven't a key pointing to device in your EventSerializer. You miss the id_device.</p> <pre><code>class EventSerializer(serializers.ModelSerializer): values = ValuesSerializer(many=True) class Meta: model = Event fields = ('id_device', 'url', 'id', 'name', 'date', 'time', 'values') </co...
0
2016-07-26T17:53:09Z
[ "python", "django", "django-models", "django-rest-framework" ]
Tkinter : Syntax highlighting for Text widget
38,594,978
<p>Can anyone explain how to add syntax highlighting to a Tkinter <code>Text</code> widget ?</p> <p>Every time the program finds a matching word, it would color that word to how I want. Such as : Color the word <code>tkinter</code> in pink and <code>in</code> in blue. But when I type in <code>Tkinter</code>, it color ...
0
2016-07-26T16:13:21Z
38,595,955
<p>You can use a <code>tag</code> to do this. You can configure the tag to have certain backgrounds, fonts, text sizes, colors etc. And then add these tags to the text you want to configure.</p> <p>All of this is in the <a href="http://effbot.org/tkinterbook/text.htm" rel="nofollow">documentation</a>.</p>
0
2016-07-26T17:04:24Z
[ "python", "text", "syntax", "tkinter" ]
Tkinter : Syntax highlighting for Text widget
38,594,978
<p>Can anyone explain how to add syntax highlighting to a Tkinter <code>Text</code> widget ?</p> <p>Every time the program finds a matching word, it would color that word to how I want. Such as : Color the word <code>tkinter</code> in pink and <code>in</code> in blue. But when I type in <code>Tkinter</code>, it color ...
0
2016-07-26T16:13:21Z
38,597,111
<p>Use <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/text-tag.html" rel="nofollow">tags</a>. I am going to implement the notions given there.</p> <p><strong>Example:</strong></p> <pre><code>import tkinter as tk root = tk.Tk() root.title("Begueradj") text = tk.Text(root) # Insert some text text.insert(t...
-1
2016-07-26T18:14:12Z
[ "python", "text", "syntax", "tkinter" ]
Adding the previous n rows as columns to a numpy array
38,595,035
<p>I want to add the previous n rows as columns to a numpy array. Here is an example:</p> <pre><code>For n=2 this: [[ 1, 2] [ 3, 4] [ 5, 6] [ 7, 8] [ 9, 10] [11, 12]] Should be turned into this: [[ 1, 2, 0, 0, 0, 0] [ 3, 4, 1, 2, 0, 0] [ 5, 6, 3, 4, 1, 2] [ 7, 8, 5, 6, 3, 4] [ 9, 10, 7, 8, 5, 6] [11, 12, 9,...
3
2016-07-26T16:16:28Z
38,595,430
<p>Here is a way to pad 0 in the beginning of the array and then column stack them:</p> <pre><code>import numpy as np n = 2 def mypad(myArr, n): if n == 0: return myArr else: return np.pad(myArr, ((n,0), (0,0)), mode = "constant")[:-n] np.column_stack(mypad(arr, i) for i in range(n + 1)) # ar...
1
2016-07-26T16:37:20Z
[ "python", "arrays", "numpy" ]
Adding the previous n rows as columns to a numpy array
38,595,035
<p>I want to add the previous n rows as columns to a numpy array. Here is an example:</p> <pre><code>For n=2 this: [[ 1, 2] [ 3, 4] [ 5, 6] [ 7, 8] [ 9, 10] [11, 12]] Should be turned into this: [[ 1, 2, 0, 0, 0, 0] [ 3, 4, 1, 2, 0, 0] [ 5, 6, 3, 4, 1, 2] [ 7, 8, 5, 6, 3, 4] [ 9, 10, 7, 8, 5, 6] [11, 12, 9,...
3
2016-07-26T16:16:28Z
38,596,465
<p>Here's a vectorized approach -</p> <pre><code>def vectorized_app(a,n): M,N = a.shape idx = np.arange(a.shape[0])[:,None] - np.arange(n+1) out = a[idx.ravel(),:].reshape(-1,N*(n+1)) out[N*(np.arange(1,M+1))[:,None] &lt;= np.arange(N*(n+1))] = 0 return out </code></pre> <p>Sample run -</p> <p...
3
2016-07-26T17:35:54Z
[ "python", "arrays", "numpy" ]
how to scrape website in which page url is not changed but the next button add data below the same url page
38,595,084
<p>I have a URL:</p> <pre><code>http://www.goudengids.be/qn/business/advanced/where/Provincie%20Antwerpen/what/restaurant </code></pre> <p>On that page there is a "next results" button which loads another 20 data point while still showing first dataset, without updating the URL. I wrote a script to scrape this page i...
2
2016-07-26T16:18:42Z
38,595,715
<p>Instead of focusing on scraping HTML I think you should look at the JSON that is retrieved via AJAX. I think the JSON is less likely to be changed in the future as opposed to the page's markup. And on top of that, it's way easier to traverse a JSON structure than it is to scrape a DOM.</p> <p>For instance, when you...
1
2016-07-26T16:51:33Z
[ "python", "csv", "beautifulsoup" ]
how to scrape website in which page url is not changed but the next button add data below the same url page
38,595,084
<p>I have a URL:</p> <pre><code>http://www.goudengids.be/qn/business/advanced/where/Provincie%20Antwerpen/what/restaurant </code></pre> <p>On that page there is a "next results" button which loads another 20 data point while still showing first dataset, without updating the URL. I wrote a script to scrape this page i...
2
2016-07-26T16:18:42Z
38,595,764
<p>If you were to solve it with <code>requests</code>, you need to mimic what browser does when you click the "Load More" button - it sends an <em>XHR request</em> to the <code>http://www.goudengids.be/q/ajax/business/results.json</code> endpoint, simulate it in your code <a class='doc-link' href="http://stackoverflow....
2
2016-07-26T16:53:56Z
[ "python", "csv", "beautifulsoup" ]
Find the name of an instance of a class from within the class
38,595,149
<p>If I had this Python script:</p> <pre><code>class my_class(object): def __init__(self): pass def get_name(self): return [name of self] this_is_the_name_im_looking_for = my_class() print ('the name is: ' + this_is_the_name_im_looking_for.get_name()) </code></pre> <p>What would I have to...
0
2016-07-26T16:21:54Z
38,595,586
<p>The built-in python method <code>id</code> <a href="https://docs.python.org/3/library/functions.html#id" rel="nofollow">returns</a></p> <blockquote> <p>an integer which is guaranteed to be unique and constant for this object during its lifetime.</p> </blockquote> <p>This doesn't return the 'name' of the object p...
0
2016-07-26T16:45:03Z
[ "python", "class", "module" ]
Tornado web sockets and long-running Celery tasks
38,595,184
<p>I have a Tornado server that's used to submit long-running (~minutes) calculations by submitting tasks to some Celery workers with a RabbitMQ back-end. The tasks that are submitted are yielded in a Tornado coroutine inside a <code>WebSocketHandler</code>:</p> <pre><code>class MainWSHandler(WebSocketHandler): de...
0
2016-07-26T16:23:29Z
38,603,646
<p>It seems like I may have jumped the gun assuming that there's a structural solution to this problem inherent in this long-running-task-with-a-web-socket system.</p> <p>It's enough to store the currently opened web socket in a class attribute</p> <pre><code>class MainWSHandler(WebSocketHandler): self.clients = ...
0
2016-07-27T04:19:55Z
[ "python", "sockets", "websocket", "celery", "tornado" ]
Join items of a list with '+' sign in a string
38,595,362
<p>I would like my output to be :</p> <pre><code>Enter a number : n List from zero to your number is : [0,1,2,3, ... , n] 0 + 1 + 2 + 3 + 4 + 5 ... + n = sum(list) </code></pre> <p>Yet my actual output is :</p> <pre><code>Enter a number : 5 List from zero to your number is : [0, 1, 2, 3, 4, 5] [+0+,+ +1+,+ +2+,+ +3...
4
2016-07-26T16:33:51Z
38,595,413
<p>You don't need to call <code>str</code> on your list. That returns the str representation of your list and the output of that is joined with <code>'+'</code>. </p> <p>You can instead use <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow"><code>map</code></a> to convert each item in your l...
4
2016-07-26T16:36:28Z
[ "python", "list", "python-3.x" ]
Join items of a list with '+' sign in a string
38,595,362
<p>I would like my output to be :</p> <pre><code>Enter a number : n List from zero to your number is : [0,1,2,3, ... , n] 0 + 1 + 2 + 3 + 4 + 5 ... + n = sum(list) </code></pre> <p>Yet my actual output is :</p> <pre><code>Enter a number : 5 List from zero to your number is : [0, 1, 2, 3, 4, 5] [+0+,+ +1+,+ +2+,+ +3...
4
2016-07-26T16:33:51Z
38,595,425
<p>Change each individual <code>int</code> element in the <code>list</code> to a <code>str</code> inside the <code>.join</code> call instead by using a <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/739/generator-expressions#t=201607261724021165396"><code>generator expression...
6
2016-07-26T16:37:05Z
[ "python", "list", "python-3.x" ]
Join items of a list with '+' sign in a string
38,595,362
<p>I would like my output to be :</p> <pre><code>Enter a number : n List from zero to your number is : [0,1,2,3, ... , n] 0 + 1 + 2 + 3 + 4 + 5 ... + n = sum(list) </code></pre> <p>Yet my actual output is :</p> <pre><code>Enter a number : 5 List from zero to your number is : [0, 1, 2, 3, 4, 5] [+0+,+ +1+,+ +2+,+ +3...
4
2016-07-26T16:33:51Z
38,595,483
<p>What you need to do is concatenate a <strong>string</strong> element with ' + ' for <em>each</em> element in your list. All you need from there is to have some string formatting. </p> <pre><code>def sum_of_input(): n = int(raw_input("Enter a number : ")) # Get our raw_input -&gt; int l = range(n + 1) # C...
5
2016-07-26T16:40:04Z
[ "python", "list", "python-3.x" ]
In place replacement of text in a file in Python
38,595,400
<p>I am using the following code to upload a file on server using FTP after editing it:</p> <pre><code>import fileinput file = open('example.php','rb+') for line in fileinput.input('example.php'): if 'Original' in line : file.write( line.replace('Original', 'Replacement')) file.close() </code></pre>...
0
2016-07-26T16:36:05Z
38,595,650
<p>Replacing stuff in a file <strong>only</strong> works well if original and replacement have the same size (in bytes) then you can do </p> <pre><code>with open('example.php','rb+') as f: pos=f.tell() line=f.readline() if b'Original' in line: f.seek(pos) f.write(line.replace(b'Original',b'...
-1
2016-07-26T16:48:07Z
[ "python", "file", "python-3.x", "python-3.5" ]
In place replacement of text in a file in Python
38,595,400
<p>I am using the following code to upload a file on server using FTP after editing it:</p> <pre><code>import fileinput file = open('example.php','rb+') for line in fileinput.input('example.php'): if 'Original' in line : file.write( line.replace('Original', 'Replacement')) file.close() </code></pre>...
0
2016-07-26T16:36:05Z
38,595,733
<p>1) <strong>The code adds the replaced text at the end and the text in original place is unchanged.</strong></p> <p>You can't replace in the body of the file because you're opening it with the <code>+</code> signal. This way it'll append to the end of the file.</p> <pre><code>file = open('example.php','rb+') </cod...
0
2016-07-26T16:52:39Z
[ "python", "file", "python-3.x", "python-3.5" ]
In place replacement of text in a file in Python
38,595,400
<p>I am using the following code to upload a file on server using FTP after editing it:</p> <pre><code>import fileinput file = open('example.php','rb+') for line in fileinput.input('example.php'): if 'Original' in line : file.write( line.replace('Original', 'Replacement')) file.close() </code></pre>...
0
2016-07-26T16:36:05Z
38,595,858
<p>The second error is how the <a href="https://docs.python.org/3/library/stdtypes.html#str.replace" rel="nofollow"><code>replace()</code></a> method works. </p> <p>It returns the <em>entire</em> input string, with only the specified substring replaced. See example <a href="http://www.tutorialspoint.com/python/string_...
0
2016-07-26T16:59:25Z
[ "python", "file", "python-3.x", "python-3.5" ]
How to prevent printing predict_proba() output in Keras?
38,595,547
<p>I am using <code>predict_proba()</code> in Keras for thousand of times, and after each use it prints the following:</p> <pre><code>1/1 [==============================] - 0s </code></pre> <p>I wonder how I can prevent it from printing this. Thank you :)</p>
0
2016-07-26T16:43:35Z
38,595,692
<p>Pass <code>verbose=0</code> to <code>predict_proba</code> to turn off verbose output.</p>
0
2016-07-26T16:50:29Z
[ "python", "deep-learning", "keras" ]
Python pandas - construct multivariate pivot table to display count of NaNs and non-NaNs
38,595,578
<p>I have a dataset based on different weather stations for several variables (Temperature, Pressure, etc.),</p> <pre><code>stationID | Time | Temperature | Pressure |... ----------+------+-------------+----------+ 123 | 1 | 30 | 1010.5 | 123 | 2 | 31 | 1009.0 | 202 | ...
2
2016-07-26T16:44:44Z
38,596,301
<p><strong>UPDATE:</strong> thanks to <a href="http://stackoverflow.com/questions/38595578/python-pandas-construct-multivariate-pivot-table-to-display-count-of-nans-and/38596301?noredirect=1#comment64580792_38596301">@root</a>:</p> <pre><code>In [16]: df.groupby('stationID')[['Temperature','Pressure']].agg([nans, notn...
3
2016-07-26T17:25:25Z
[ "python", "pandas", "dataframe", "pivot-table", null ]
Python pandas - construct multivariate pivot table to display count of NaNs and non-NaNs
38,595,578
<p>I have a dataset based on different weather stations for several variables (Temperature, Pressure, etc.),</p> <pre><code>stationID | Time | Temperature | Pressure |... ----------+------+-------------+----------+ 123 | 1 | 30 | 1010.5 | 123 | 2 | 31 | 1009.0 | 202 | ...
2
2016-07-26T16:44:44Z
38,596,333
<p>I'll admit this is not the prettiest solution, but it works. First define two temporary columns <code>TempNaN</code> and <code>PresNaN</code>:</p> <pre><code>df['TempNaN'] = df['Temperature'].apply(lambda x: 'NaN' if x!=x else 'NonNaN') df['PresNaN'] = df['Pressure'].apply(lambda x: 'NaN' if x!=x else 'NonNaN') </...
0
2016-07-26T17:27:24Z
[ "python", "pandas", "dataframe", "pivot-table", null ]
Python pandas - construct multivariate pivot table to display count of NaNs and non-NaNs
38,595,578
<p>I have a dataset based on different weather stations for several variables (Temperature, Pressure, etc.),</p> <pre><code>stationID | Time | Temperature | Pressure |... ----------+------+-------------+----------+ 123 | 1 | 30 | 1010.5 | 123 | 2 | 31 | 1009.0 | 202 | ...
2
2016-07-26T16:44:44Z
38,596,508
<pre><code>d = {'stationID':[], 'nanStatus':[], 'Temperature':[], 'Pressure':[]} for station_id, data in df.groupby(['stationID']): temp_nans = data.isnull().Temperature.mean()*data.isnull().Temperature.count() pres_nans = data.isnull().Pressure.mean()*data.isnull().Pressure.count() d['stationID'].append...
0
2016-07-26T17:38:26Z
[ "python", "pandas", "dataframe", "pivot-table", null ]
python/matplotlib/seaborn- boxplot on an x axis with data points
38,595,612
<p>My data set is like this: a python list with 6 numbers [23948.30, 23946.20, 23961.20, 23971.70, 23956.30, 23987.30]</p> <p>I want them to be be a horizontal box plot above an x axis with[23855 and 24472] as the limit of the x axis (with no y axis). </p> <p>The x axis will also contain points in the data.</p> <p>(...
1
2016-07-26T16:46:20Z
38,596,113
<p>I answered this question in the other post as well, but I will paste it here just in case. I also added something that I feel might be closer to what you are looking to achieve.</p> <pre><code>l = [23948.30, 23946.20, 23961.20, 23971.70, 23956.30, 23987.30] def box_plot(circ_list): fig, ax = plt.subplots() ...
0
2016-07-26T17:14:22Z
[ "python", "matplotlib", "plot", "boxplot", "seaborn" ]
Python division operator gives different results
38,595,613
<p>In Python I am trying to divide an integer by half and I came across two different results based on the sign of the number.</p> <p>Example:</p> <pre><code>5/2 gives 2 and -5/2 gives -3 </code></pre> <p>How to get -2 when I divide -5/2 ? </p>
1
2016-07-26T16:46:22Z
38,595,701
<pre><code>&gt;&gt;&gt; import math &gt;&gt;&gt; math.ceil(float(-5)/2) -2.0 </code></pre>
0
2016-07-26T16:50:57Z
[ "python", "integer-division", "floor", "ceil" ]
Python division operator gives different results
38,595,613
<p>In Python I am trying to divide an integer by half and I came across two different results based on the sign of the number.</p> <p>Example:</p> <pre><code>5/2 gives 2 and -5/2 gives -3 </code></pre> <p>How to get -2 when I divide -5/2 ? </p>
1
2016-07-26T16:46:22Z
38,595,710
<p>This happens due to python rounding <strong>integer division</strong>. Below are a few examples. In python, the <code>float</code> type is the <em>stronger</em> type and expressions involving <code>float</code> and <code>int</code> evaluate to <code>float</code>.</p> <pre><code>&gt;&gt;&gt; 5/2 2 &gt;&gt;&gt; -5/2 ...
1
2016-07-26T16:51:21Z
[ "python", "integer-division", "floor", "ceil" ]
Python division operator gives different results
38,595,613
<p>In Python I am trying to divide an integer by half and I came across two different results based on the sign of the number.</p> <p>Example:</p> <pre><code>5/2 gives 2 and -5/2 gives -3 </code></pre> <p>How to get -2 when I divide -5/2 ? </p>
1
2016-07-26T16:46:22Z
38,595,711
<p>You should enclose division in expression like below</p> <pre><code>print -(5/2) </code></pre>
2
2016-07-26T16:51:26Z
[ "python", "integer-division", "floor", "ceil" ]
Python division operator gives different results
38,595,613
<p>In Python I am trying to divide an integer by half and I came across two different results based on the sign of the number.</p> <p>Example:</p> <pre><code>5/2 gives 2 and -5/2 gives -3 </code></pre> <p>How to get -2 when I divide -5/2 ? </p>
1
2016-07-26T16:46:22Z
38,595,747
<p>You need to use float division and then use <code>int</code> to truncate the decimal</p> <pre><code>&gt;&gt;&gt; from __future__ import division &gt;&gt;&gt; -5 / 2 -2.5 &gt;&gt;&gt; int(-5 / 2) -2 </code></pre> <p>In Python 3, float division is the default, and you don't need to include the <code>from __future__ ...
1
2016-07-26T16:53:14Z
[ "python", "integer-division", "floor", "ceil" ]
Python division operator gives different results
38,595,613
<p>In Python I am trying to divide an integer by half and I came across two different results based on the sign of the number.</p> <p>Example:</p> <pre><code>5/2 gives 2 and -5/2 gives -3 </code></pre> <p>How to get -2 when I divide -5/2 ? </p>
1
2016-07-26T16:46:22Z
38,595,815
<p>As of <a href="http://stackoverflow.com/questions/19919387/in-python-what-is-a-good-way-to-round-towards-zero-in-integer-division">this accepted answer</a>:</p> <pre><code>&gt; int(float(-5)/2) -2 &gt; int(float(5)/2) 2 </code></pre>
1
2016-07-26T16:56:49Z
[ "python", "integer-division", "floor", "ceil" ]
How to remove line when variable is not defined in jinja2 template
38,595,674
<p>I have a simple jinja2 template:</p> <pre><code>{% for test in tests %} {{test.status}} {{test.description}}: {{test.message}} Details: {% for detail in test.details %} {{detail}} {% endfor %} {% endfor %} </code></pre> <p>Which work really good when all of variable of 'test' object...
2
2016-07-26T16:49:33Z
39,208,689
<p>You can put a if condition inside the for loop to avoid blank line if there is no message.</p> <pre><code>{% for test in tests %} {{test.status}} {{test.description}}: {% if test.message %} {{test.message}} {% endif %} Details: {% for detail in test.details %} {{detail}} ...
1
2016-08-29T14:27:49Z
[ "python", "templates", "jinja2" ]
How can we get lmfit parameters after fitting?
38,595,676
<p>I wrote a program to fit some Raman spectra peaks. I need to return the fitted parameters (position, amplitude, HWHM).</p> <p>I used the modul lmfit to create a lorentzian peak with constraints.</p> <p>I have a good agreement between the fitted peak and the raw data according to my figure plot. But when it comes t...
0
2016-07-26T16:49:40Z
38,627,608
<p>Your script could be a lot shorter to illustrate the question. But, the final Parameters are held in <code>result_150.params</code> and so forth. The parameters passed into <code>minimize()</code> are not altered in the fit. </p> <p>Well, that's true for lmfit version 0.9.0 and later. Perhaps your colleague has...
0
2016-07-28T05:17:20Z
[ "python", "windows", "parameters", "lmfit" ]
Why registerTempTable removes some rows from the data-frame?
38,595,679
<p>I try to create a pandas data-frame using a Spark data-frame on HDInsight in the following way:</p> <pre><code>tmp = sqlContext.createDataFrame(sparkDf) tmp.registerTempTable('temp') </code></pre> <p>It looks like the <code>registerTempTable</code> removes some rows from the data-frame. </p> <p>The following com...
0
2016-07-26T16:49:43Z
38,599,020
<p>I am assuming you're using Jupyter notebooks, and that you're getting your data from a SQL query, i.e.</p> <pre><code>%%sql -o tmp SELECT * FROM temp </code></pre> <p>This is happening because the <code>%%sql</code> query transparently limits the size of the result dataframe <code>tmp</code> to 2500 rows. You can...
5
2016-07-26T20:09:38Z
[ "python", "azure", "apache-spark", "pyspark", "hdinsight" ]
not valid JSON python-instagram
38,595,698
<p>I just can't start using instagram api.</p> <p>The code from github <a href="https://github.com/facebookarchive/python-instagram" rel="nofollow">https://github.com/facebookarchive/python-instagram</a></p> <pre><code>from instagram.client import InstagramAPI access_token = "***" client_secret = "***" scope = 'publ...
0
2016-07-26T16:50:53Z
38,596,332
<p>I suspect this has something to do with recent enforcement of permission reviews (which I think changes authentication) that Instagram laid down on June 1st. <a href="https://www.instagram.com/developer/changelog/" rel="nofollow">https://www.instagram.com/developer/changelog/</a></p> <p>Given that the python-instag...
0
2016-07-26T17:27:22Z
[ "python", "json", "instagram-api" ]
Times tables in python
38,595,929
<p>I decided to write software to make my little brother do his times tables, So I wrote the following code: </p> <pre><code>for i in range(13): for j in range(13): print(i, '*', j, '=') A = input(" ") while A != i*j: print(i, '*', j, '=') A ...
-1
2016-07-26T17:03:09Z
38,596,098
<p>It is failing because of this line:</p> <pre><code>while A != i*j: </code></pre> <p><code>A</code> is a string. <code>i*j</code> is not a string. This will cause the conditional to fail. It is doing this comparison:</p> <pre><code>&gt;&gt;&gt; 0 == "0" False </code></pre> <p>To fix this, you can cast <code>A</co...
1
2016-07-26T17:13:19Z
[ "python", "loops", "multiplication" ]
Adding multiple facets to one variable
38,595,961
<p>I'm playing around with the following class to just practice my Python skills:</p> <pre><code>class Scene(object): def __init__(self, settings, actors): self.settings = int(settings) self.actors = actors actors = [] new_setting = settings = settings + 1 class Actor(object): ...
0
2016-07-26T17:04:35Z
38,596,272
<p>The best approach is to define another class for <code>Actor</code>, see example below</p> <pre><code>class Actor(object): def __init__(self, name, age, wage): self.name = name self.age = age self.wage = wage class Scene(object): def __init__(self, settings): self.settings =...
2
2016-07-26T17:23:57Z
[ "python" ]
How to create a new list from other two lists, apply a function and append the output to each list?
38,596,004
<p>thank you in advance for the help.</p> <p>I need to retrieve some data (clients and products) from a WebService. This code gets the data and transforms it into lists with dictionaries within them.</p> <pre><code> consumidores = requests.get(url + 'all_consumers', headers=custom_header) # lista con = consum...
0
2016-07-26T17:07:13Z
38,596,544
<p>Your loops all appear to do nothing, e.g.</p> <pre><code>for key in con: c = [key['genero'], key['complexion'], key['tallaCamisa'], key['tallaPantalon'], key['edad'], key['ubicacion'], key['valorComercial'], key['valorCompra']] </code></pre> <p>replaces <code>c</code> every time, and you only get the ...
0
2016-07-26T17:40:10Z
[ "python" ]
How to change the starting index of iterrows()?
38,596,056
<p>We can use the following to iterate rows of a data frame.</p> <pre><code>for index, row in df.iterrows(): </code></pre> <p>What if I want to begin from a different row index? (not from first row)?</p>
3
2016-07-26T17:10:27Z
38,596,090
<p>Sure:</p> <pre><code>for i,(index,row) in enumerate(df.iterrows()): if i == 0: continue # skip first row </code></pre> <p>Or something like:</p> <pre><code>for i,(index,row) in enumerate(df.iterrows()): if i &lt; 5: continue # skip first 5 rows </code></pre>
0
2016-07-26T17:12:44Z
[ "python", "pandas", "dataframe" ]
How to change the starting index of iterrows()?
38,596,056
<p>We can use the following to iterate rows of a data frame.</p> <pre><code>for index, row in df.iterrows(): </code></pre> <p>What if I want to begin from a different row index? (not from first row)?</p>
3
2016-07-26T17:10:27Z
38,596,091
<p>Try using <code>itertools.islice</code></p> <pre><code>from itertools import * for index, row in islice(df.iterrows(), 1, None): </code></pre>
3
2016-07-26T17:12:48Z
[ "python", "pandas", "dataframe" ]
How to change the starting index of iterrows()?
38,596,056
<p>We can use the following to iterate rows of a data frame.</p> <pre><code>for index, row in df.iterrows(): </code></pre> <p>What if I want to begin from a different row index? (not from first row)?</p>
3
2016-07-26T17:10:27Z
38,596,799
<p>i know this has an answer, but why not just do:</p> <pre><code>for i, r in df.iloc[1:].iterrows(): </code></pre>
2
2016-07-26T17:56:31Z
[ "python", "pandas", "dataframe" ]
Python: prevent signals to propagate to child threads
38,596,069
<pre><code>import threading import time def worker(i): while True: try: print i time.sleep(10) break except Exception, msg: print msg threads = [] for i in range(10): t1 = threading.Thread(target=worker, args=(i,)) threads.append(t1) for ...
1
2016-07-26T17:11:27Z
38,596,898
<p>As referred in <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">Python's docs</a>, you should use the attribute <strong>daemon</strong>:</p> <blockquote> <p>daemon: A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() i...
0
2016-07-26T18:01:37Z
[ "python", "multithreading", "signals" ]
Python listing last 10 modified files and reading each line of all 10 files
38,596,080
<p>I need some help listing files in a directory and reading through each file using Python. I know how to do this using shell commands but is there a Pythonic way to do it?</p> <p>I would like to:</p> <p>1.) List all files in a directory.</p> <p>2.) Grab the last 10 modified/latest files (preferably using a wildca...
2
2016-07-26T17:11:55Z
38,596,492
<p>it looks alike you almost did everything already</p> <pre><code>import os.path, glob files = glob.glob("data_event_log.*") files.sort(key=os.path.getmtime) latest=files[-10:] # last 10 entries print("\n".join(latest)) lineRegex = re.compile(r'\d{4}-\d{2}-\d{2}') for fn in latest: with open(fn) as f: fo...
3
2016-07-26T17:37:24Z
[ "python", "text-parsing" ]
Python listing last 10 modified files and reading each line of all 10 files
38,596,080
<p>I need some help listing files in a directory and reading through each file using Python. I know how to do this using shell commands but is there a Pythonic way to do it?</p> <p>I would like to:</p> <p>1.) List all files in a directory.</p> <p>2.) Grab the last 10 modified/latest files (preferably using a wildca...
2
2016-07-26T17:11:55Z
38,596,547
<p>What you are looking for is a fixed-size sorted buffer. <code>collections.deque</code> does this, albeit without the sorting. So, here's a buffer that'll do what you need, and <code>main</code> shows you how to use it</p> <pre><code>import bisect import glob import operator import os class Buffer: def __init_...
0
2016-07-26T17:40:28Z
[ "python", "text-parsing" ]
Python listing last 10 modified files and reading each line of all 10 files
38,596,080
<p>I need some help listing files in a directory and reading through each file using Python. I know how to do this using shell commands but is there a Pythonic way to do it?</p> <p>I would like to:</p> <p>1.) List all files in a directory.</p> <p>2.) Grab the last 10 modified/latest files (preferably using a wildca...
2
2016-07-26T17:11:55Z
38,596,864
<p>pythonic answer: </p> <p>use <code>sorted()</code> with a lambda function, then use list slicing to get the 10 earliest or 10 latest or what have you.</p> <pre><code>from glob import glob from os import stat files = glob("*") sorted_list = sorted(files, key=lambda x: stat(x).st_mtime) truncated_list = sorted_lis...
0
2016-07-26T17:59:32Z
[ "python", "text-parsing" ]
Python equivalent of Excel's PERCENTILE.EXC
38,596,100
<p>I am using Pandas to compute some financial risk analytics, including Value at Risk. In short, to compute Value at Risk (VaR), you take a time series of simulated portfolio changes in value, and then compute a specific tail percentile loss. For example, 95% VaR is the 5th percentile figure in that time series.</p...
3
2016-07-26T17:13:27Z
38,597,170
<p>EDIT: I just saw your edit. I think you are making a mistake. The value -77.4 is actually the 99.5% percentile of your data. Try <code>test_pd.quantile(.005)</code>. I believe that you must have made a mistake in Excel when specifying your percentile.</p> <p>EDIT 2: I just tested it myself in Excel. For the 50-th p...
2
2016-07-26T18:17:05Z
[ "python", "pandas" ]
Python equivalent of Excel's PERCENTILE.EXC
38,596,100
<p>I am using Pandas to compute some financial risk analytics, including Value at Risk. In short, to compute Value at Risk (VaR), you take a time series of simulated portfolio changes in value, and then compute a specific tail percentile loss. For example, 95% VaR is the 5th percentile figure in that time series.</p...
3
2016-07-26T17:13:27Z
38,597,798
<p>It won't be as efficient as Pandas' own percentile but it should work:</p> <pre><code>def quantile_exc(ser, q): ser_sorted = ser.sort_values() rank = q * (len(ser) + 1) - 1 assert rank &gt; 0, 'quantile is too small' rank_l = int(rank) return ser_sorted.iat[rank_l] + (ser_sorted.iat[rank_l + 1] ...
1
2016-07-26T18:54:44Z
[ "python", "pandas" ]
How can a Facebook app read its own posts?
38,596,125
<p>I'm developing a Django application that can also post to Facebook. I have a problem reading the posts that the application itself created.</p> <p>Given that the permissions requested using <code>django-allauth</code> includes <code>publish_actions</code>, check the example code:</p> <pre><code>import open_faceboo...
0
2016-07-26T17:15:20Z
39,397,613
<p>I am able to retrieve single posts as follows. I have installed facebook-sdk==2.0.0 and I've authorized the user_posts permission for my application. The is of the form usernum_postnum.</p> <pre><code>import facebook graph_api = facebook.GraphAPI(access_token=access_token, version='2.7') graph_api.request('&lt;fa...
0
2016-09-08T18:12:23Z
[ "python", "facebook-graph-api", "django-facebook" ]