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
Applying same code to multiple files within multiple folders
37,818,553
<p>I have a folder with numerous subdirectories (more folders) and in each subdirectory are csv files. I want to apply the same code to all the csv files in the subdirectories. If I did this for just one folder I would do it like this:</p> <pre><code>list1=[] pth=r'G:\Stefano\Ecoregion_assessment\csv_by_ecoregion_...
0
2016-06-14T17:30:13Z
37,819,016
<p>Just add an extra loop. I have tried to rewrite your code, even if some parts are missing and I cannot test it but I'm quite confident about it:</p> <pre><code>pth=r'G:\Stefano\Ecoregion_assessment\csv_by_ecoregion_crp' # upper dir out=r'G:\Stefano\Ecoregion_assessment\final_files' # out of the loop for d in os...
1
2016-06-14T17:57:39Z
[ "python", "csv", "pandas" ]
How to install ipywidgets offline (from file)
37,818,584
<p>So I am trying to install ipywidgets-0.0.1 into my Anaconda environment. I am running Anaconda3. Unfortunately, the machine I need to install it on does not have internet access.</p> <p>The basic way to install the package is to run <code>conda install ipywidgets</code>, but of course this gives the following error...
0
2016-06-14T17:32:20Z
37,818,940
<p>Download the whole package <strong>and its dependencies</strong> to some local directory You can get it from PYPI <a href="https://pypi.python.org/pypi/ipywidgets" rel="nofollow">ipywidgets</a></p> <p>Let's consider you donwloaded from PYPI and you have <code>~/src/ipywidgets</code> with <code>~/src/ipywidgets/setu...
1
2016-06-14T17:53:03Z
[ "python", "cmd", "anaconda", "jupyter-notebook", "ipywidgets" ]
How to install ipywidgets offline (from file)
37,818,584
<p>So I am trying to install ipywidgets-0.0.1 into my Anaconda environment. I am running Anaconda3. Unfortunately, the machine I need to install it on does not have internet access.</p> <p>The basic way to install the package is to run <code>conda install ipywidgets</code>, but of course this gives the following error...
0
2016-06-14T17:32:20Z
37,822,451
<p>If you want to use <code>conda</code> for this, might as well if you are already using anaconda, you should also be able to do:</p> <pre><code>conda install --offline PATH_TO_FILE/ipywidgets-0.0.1-np19py34_0.tar.bz2 </code></pre> <p>Where, of course, <code>PATH_TO_FILE</code> is just the path to the file you've do...
0
2016-06-14T21:29:20Z
[ "python", "cmd", "anaconda", "jupyter-notebook", "ipywidgets" ]
Penalty function method
37,818,596
<p>I am trying to implement penalty function method for minimizing function. I need to find the minimum of <a href="https://en.wikipedia.org/wiki/Rosenbrock_function" rel="nofollow">Rosenbrok's function</a>.</p> <p>I am using this penalty function:</p> <p><a href="http://i.stack.imgur.com/UgHju.png" rel="nofollow"><i...
1
2016-06-14T17:32:53Z
37,825,941
<p>The problem you have is that the <code>h_i</code> in your formula are for <em>equality</em> constraints, whereas the problem you are solving is for <em>inequality</em> constraints, which correspond to the <code>g_i</code> in your formula. Hence, your penalty function should be using terms like <code>min(0, h_1(x))**...
1
2016-06-15T04:06:37Z
[ "python", "math" ]
Cannot setup Scrapy on windows
37,818,606
<p>I tried to setup Scrapy on Windows 7 by steps described at <a href="http://doc.scrapy.org/en/latest/intro/install.html" rel="nofollow">http://doc.scrapy.org/en/latest/intro/install.html</a> . On my PC was installed Python 3.5.1. Although Scrapy not support this python version it was installed successfully with lates...
0
2016-06-14T17:33:26Z
37,818,668
<p>On this blog: </p> <p><a href="https://blog.scrapinghub.com/2016/05/25/data-extraction-with-scrapy-and-python-3/" rel="nofollow">https://blog.scrapinghub.com/2016/05/25/data-extraction-with-scrapy-and-python-3/</a></p> <p>it says Scrapy on Python 3 doesn't work in Windows environments yet</p> <p>Edit: I recently...
1
2016-06-14T17:36:14Z
[ "python", "windows", "python-3.x", "scrapy" ]
Cannot setup Scrapy on windows
37,818,606
<p>I tried to setup Scrapy on Windows 7 by steps described at <a href="http://doc.scrapy.org/en/latest/intro/install.html" rel="nofollow">http://doc.scrapy.org/en/latest/intro/install.html</a> . On my PC was installed Python 3.5.1. Although Scrapy not support this python version it was installed successfully with lates...
0
2016-06-14T17:33:26Z
37,820,028
<p>Try to create a virtual env: </p> <p>pip install virtualenv (instalation) virtualenv -p python3.3.5 envName (creation with specific python version) source ./envName/bin/activate (activate virtual env)</p> <p>This way you can guarantee that's the right python version. Also scrapy has some requirements that can't...
0
2016-06-14T18:56:31Z
[ "python", "windows", "python-3.x", "scrapy" ]
Cannot setup Scrapy on windows
37,818,606
<p>I tried to setup Scrapy on Windows 7 by steps described at <a href="http://doc.scrapy.org/en/latest/intro/install.html" rel="nofollow">http://doc.scrapy.org/en/latest/intro/install.html</a> . On my PC was installed Python 3.5.1. Although Scrapy not support this python version it was installed successfully with lates...
0
2016-06-14T17:33:26Z
38,442,511
<p>I add the follow package and it works:</p> <pre><code>pip install twisted-win==0.5.5 </code></pre>
0
2016-07-18T17:16:34Z
[ "python", "windows", "python-3.x", "scrapy" ]
Import Cython exposed class from another directory
37,818,610
<p>I have a Python project in which I want to make use of a <code>C++</code> class that I exposed through Cython (really, I just need a specific instance of the class, as the code below will demonstrate). Because there were a bunch of files associated with the class I decided to put it in its own package.</p> <p>In th...
0
2016-06-14T17:33:32Z
37,824,699
<p>I don't think this has anything to do with <code>Cython</code> per se, rather, this issue is due to the fact that when you execute <code>main.py</code> in the top level directory, <code>Python</code> will execute <code>__init__.py</code> and search in the same directory failing to locate the <code>foo</code> module ...
1
2016-06-15T01:30:50Z
[ "python", "cython", "python-import" ]
How to get accurate predictions from Neural Network?
37,818,648
<p>I'm doing a project on water quality prediction using Artificial Neural Network. I implemented this using python. I have completed my prediction model but the generated predictions are not much accurate.</p> <p>What I'm doing is I have collected data from a river for past 4 and half years on daily basis and I'm pre...
0
2016-06-14T17:35:28Z
37,840,624
<p>Some of the comments suggest scaling the output sigmoidal layer to match the correct data. If you look at your predictions, you will see that with some scaling they are pretty accurate. I advise against scaling a sigmoidal function, however.</p> <p>A sigmoidal output is meant to be interpreted as a probability (giv...
1
2016-06-15T16:10:42Z
[ "python", "scikit-learn", "neural-network", "prediction" ]
tkinter image segfault
37,818,666
<p>I am creating a simple gui with an image using Tkinter and the following gives me a segmentation fault:</p> <pre><code>from Tkinter import* from PIL import ImageTk, Image import os window=Tk(); window.geometry("500x500") testimg="Argentina.png" img=ImageTk.PhotoImage(Image.open(testimg)) </code></pre> <p>From br...
0
2016-06-14T17:36:11Z
37,824,546
<p>Partial resolution in <a href="https://github.com/conda/conda/issues/2471" rel="nofollow">this</a> GitHub thread. The problem comes from the frameworks directories being improperly linked through Anaconda. Currently not resolvable, but Anaconda devs are aware of the issue. </p>
0
2016-06-15T01:07:25Z
[ "python", "tkinter", "segmentation-fault", "python-imaging-library" ]
How to type lower bar in a string by python plot?
37,818,749
<p>I want to add some text to a python plot. I'm using <strong>r'$\bar{p}$'</strong>, but I want the bar to be at the bottom. I tried to use latex package accent and write <strong>r'$\usepackage{accents} \underaccent{\bar}{p}$'</strong>. But it doesn't work.</p> <p>Any idea how to do that? Thanks in advance.</p>
0
2016-06-14T17:41:26Z
37,819,152
<p>This is not ideal, since the <code>\underline</code> produces a slightly different line than <code>\underaccent</code>, but you could still use it the way mentioned in <a href="http://stackoverflow.com/a/10727730/5829566">this answer</a>.<br> To give the letter p the same font as in latex formula, you can use <code>...
0
2016-06-14T18:05:18Z
[ "python", "mathematical-expressions" ]
KeyError: 'Level None not found'
37,818,766
<p>I have a <code>dataframe</code> derived from <code>pivot_table</code> in the following format:</p> <p><a href="http://i.stack.imgur.com/yJ4nG.png" rel="nofollow"><img src="http://i.stack.imgur.com/yJ4nG.png" alt="enter image description here"></a></p> <p>I would like to use <code>crosstab</code> on it for performi...
0
2016-06-14T17:42:21Z
37,819,563
<p>I finally had to get rid of the <code>pivot_table</code> and its indices by using the following code:</p> <pre><code>ConceptTab = pd.DataFrame({'Q1': ConceptTemp.ix[:,5].values, 'CategoricalScore': ConceptTemp.ix[:,171].values}) </code></pre> <p>After the indices go away, the code for <code>crosstab</code> works f...
0
2016-06-14T18:29:20Z
[ "python", "pandas", "keyerror" ]
tkFileDialog AttributeError
37,818,815
<p>I am having trouble using <code>tkFileDialog.askopenfile()</code> in Python 2.7.11</p> <p>The following code produces the error.</p> <pre><code>import Tkinter print Tkinter.TkVersion Tkinter.tkFileDialog.askopenfile(filetypes=[('csvfiles','.csv')]) </code></pre> <p>The Python Shell output is:</p> <pre><code>8.5...
-1
2016-06-14T17:45:29Z
37,818,889
<p>for <code>python 2.7</code> its a separate module:</p> <pre><code>from tkFileDialog import askopenfilename </code></pre> <p>In <code>python 3</code> its included in <code>tkinter</code> :</p> <pre><code>from tkinter import filedialog as fd </code></pre>
1
2016-06-14T17:49:55Z
[ "python", "python-2.7", "tkinter", "filedialog" ]
Running Sphinx html make gets stuck after reading sources
37,818,923
<p>I am trying to use Sphinx for the first time to get documentation from docstrings in my code. I am currently using pycharm to run a sphinx task but I did not have luck with the command line either. The problem is that the process gets struck without returning any error: </p> <pre><code>Running Sphinx v1.2.2 loading...
0
2016-06-14T17:51:50Z
37,838,870
<p>Solved. It appears that any <strong><em>wait-like function</em></strong> in a module will cause Sphinx to hang when importing it if it is executed at import time. I was using ROS and <strong>rospy.wait_for_service</strong> was causing the problem.</p>
0
2016-06-15T14:52:22Z
[ "python", "pycharm", "python-sphinx" ]
PyCharm change working directory of console
37,818,938
<p>How do I change the default working directory when I open a new Python Console? I have multiple projects open in my PyCharm view and the Python Console seems to be defaulting to an arbitrary one. Of course I can work around by modifying sys.path but I want a definite solution :) </p>
1
2016-06-14T17:52:51Z
37,819,230
<p>Settings -> Build Execution Deployment -> Console -> Python Console</p>
3
2016-06-14T18:09:59Z
[ "python", "ide", "pycharm" ]
Populating a dataframe by looking up another dataframe in pandas
37,818,947
<p>I have a pandas dataframe (df) like below:</p> <pre><code>AccountName AccountName2 DateTime abc guest 2016-06-10 20:46 guest 2016-06-10 21:32 def 2016-06-10 23:11 2016-06-10 23:31 ghi 2016-06-10 24...
1
2016-06-14T17:53:41Z
37,819,257
<p>I think you can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>replace</code></a> strings with spaces <code>' '</code> to <code>NaN</code> and then <code>apply</code> custom function <code>f</code> with <a href="http://pandas.pydata.org/panda...
0
2016-06-14T18:11:01Z
[ "python", "pandas", "dataframe", "ipython", null ]
Populating a dataframe by looking up another dataframe in pandas
37,818,947
<p>I have a pandas dataframe (df) like below:</p> <pre><code>AccountName AccountName2 DateTime abc guest 2016-06-10 20:46 guest 2016-06-10 21:32 def 2016-06-10 23:11 2016-06-10 23:31 ghi 2016-06-10 24...
1
2016-06-14T17:53:41Z
37,822,679
<p>You could use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.select.html" rel="nofollow"><code>np.select</code></a>. It is a multi-conditional generalization of <code>np.where</code>:</p> <pre><code>import numpy as np import pandas as pd df = pd.DataFrame( {'AccountName': ['abc', ' ',...
0
2016-06-14T21:49:28Z
[ "python", "pandas", "dataframe", "ipython", null ]
How would you setup a "context" type object in django
37,818,962
<p>In Rails if I want to setup a "context" which is basically objects that every view will need like the user object for a logged in user, or say a store/account/location object, how would I have this available on every view in the django framework?</p> <p>In Rails I would do something like this:</p> <pre><code>class...
1
2016-06-14T17:54:40Z
37,819,251
<p>You can write your own context processor:</p> <p><strong>Study :</strong><br/><br/> <a href="https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors</a><br/> <a href="htt...
2
2016-06-14T18:10:41Z
[ "python", "django" ]
How would you setup a "context" type object in django
37,818,962
<p>In Rails if I want to setup a "context" which is basically objects that every view will need like the user object for a logged in user, or say a store/account/location object, how would I have this available on every view in the django framework?</p> <p>In Rails I would do something like this:</p> <pre><code>class...
1
2016-06-14T17:54:40Z
37,819,271
<p>If I understand your question correctly, I think you're trying to do something like this. I'm still fairly inexperienced with Django myself, so take this with a grain of salt.</p> <p>Basic example:</p> <p>views.py</p> <pre><code>from django.shortcuts import render from exampleapp.models import User # User object...
0
2016-06-14T18:11:42Z
[ "python", "django" ]
Python script to duplicate .tex files with small changes
37,818,978
<p>I have a letter in LaTeX format. I'd like to write a short script in python that takes one argument (the addressee) and creates a .tex file with the general letter format and the addressee.</p> <pre><code> from sys import argv script, addressee = argv file = open('newletter.tex', 'w') file.write("\be...
-1
2016-06-14T17:55:33Z
37,819,304
<p>If you directly enter <code>print "\begin..."</code> into your interpreter, you will notice the result will omit the <code>\b</code> on the front of the string. This is because <code>\b</code> is a character that the print statement (or function if you're in 3.x) recognizes (it happens to be a backspace).</p> <p>T...
1
2016-06-14T18:13:38Z
[ "python", "scripting", "latex" ]
Python script to duplicate .tex files with small changes
37,818,978
<p>I have a letter in LaTeX format. I'd like to write a short script in python that takes one argument (the addressee) and creates a .tex file with the general letter format and the addressee.</p> <pre><code> from sys import argv script, addressee = argv file = open('newletter.tex', 'w') file.write("\be...
-1
2016-06-14T17:55:33Z
37,820,408
<p>I'd take the approach of creating the tex files first as letter.tex with the addressee set to something like QXQ_ADDRESSEE_QXQ.</p> <p>The in the python script I'd read the entire file into memory. When you read from a file, it gets treated as a raw string with proper escaping. </p> <pre><code>with open('lette...
1
2016-06-14T19:18:48Z
[ "python", "scripting", "latex" ]
Constantly Updating a File
37,819,025
<p>I have a file that holds the number of each fruit I possess. I then need to edit it every minute to keep it up to date.</p> <pre><code>apples: 3 bananas: 6 oranges: 12 total: 21 fruits </code></pre> <p>I want to use python to edit this file. However, I have encountered several problems:</p> <p>1) I am currently u...
0
2016-06-14T17:58:17Z
37,819,490
<p>Your best option is to read in the file and parse the number of fruits into variables. Then do your math (Add 3 apples or whatever) and then rewrite the file. </p> <p>You could probably do this best with a dictionary where the keys are your fruit names and the values are the numbers of fruits. Simply write a fun...
0
2016-06-14T18:25:22Z
[ "python", "unix", "design" ]
Constantly Updating a File
37,819,025
<p>I have a file that holds the number of each fruit I possess. I then need to edit it every minute to keep it up to date.</p> <pre><code>apples: 3 bananas: 6 oranges: 12 total: 21 fruits </code></pre> <p>I want to use python to edit this file. However, I have encountered several problems:</p> <p>1) I am currently u...
0
2016-06-14T17:58:17Z
37,821,779
<p>You can use 'w+' or 'r+' mode to read and write. when you open a file in text mode it's fully buffered by default. To see the live update, you have to <code>flush</code> every write or open the file in line buffered mode (<code>buffering=1</code>).<br> Furthermore, you can't use <code>tail -f</code> because the file...
1
2016-06-14T20:46:12Z
[ "python", "unix", "design" ]
How do I send a base64 string to a Django template
37,819,066
<p>My python code gets a file from an aws s3 bucket like so then is rendered in an django html template following normal conventions: </p> <pre><code> context_dict = {} conn = S3Connection(djangoSettings.AWS_ACCESS_KEY_ID, djangoSettings.AWS_SECRET_ACCESS_KEY) b = conn.get_bucket(djangoSettings.AWS_STORAGE_...
0
2016-06-14T18:00:20Z
37,820,249
<p>Can you try to escape the content of "bytes"?</p> <pre><code>&lt;html&gt;&lt;body&gt; {{ otherdata }} {{ bytes|force_escape }} &lt;/body&gt;&lt;/html&gt; </code></pre> <p>Normally if I need to return the file to the client I would either redirect the url of the file or just simply return the json with the ur...
0
2016-06-14T19:09:14Z
[ "python", "html", "django", "amazon-s3", "base64" ]
Error reached while attempting to create a numpy array
37,819,082
<p>Here's my code: </p> <pre><code>import numpy as np x = np.array[[1,2]] print x </code></pre> <p>Here's the output:</p> <pre><code>Traceback (most recent call last): File "Shear_Moment_Test.py", line 2, in &lt;module&gt; x = np.array[[1,2]] TypeError: 'builtin_function_or_method' object has no attribute '__g...
-4
2016-06-14T18:01:09Z
37,819,114
<p>The syntax which you used is wrong. Use this <code>x = np.array([1,2])</code></p>
1
2016-06-14T18:03:06Z
[ "python", "arrays", "numpy" ]
Twitter API query using python Twitter gives few results
37,819,166
<p>I am using Python Twitter to download data from tweets about youTube videos : <a href="https://github.com/bear/python-twitter/blob/master/doc/index.rst" rel="nofollow">https://github.com/bear/python-twitter/blob/master/doc/index.rst</a></p> <pre><code>def TW(): return twitter.Api(consumer_key='X',consumer_secre...
0
2016-06-14T18:05:59Z
37,987,891
<p>Found the answer here : <a href="http://stackoverflow.com/questions/24080405/can-i-use-twitter-api-to-search-tweets-one-week-before">Can I use twitter api to search tweets one week before?</a></p> <blockquote> <p>Also note that the search results at twitter.com may return historical results while the Search API u...
0
2016-06-23T09:42:02Z
[ "python", "twitter", "python-twitter" ]
matplotlib arrowheads and aspect ratio
37,819,215
<p>If I run this script:</p> <pre><code>import matplotlib.pyplot as plt import pylab as plab plt.figure() plt.plot([0,2], [2,0], color='c', lw=0.5) plt.plot([1,2], [2,1], color='k', lw=0.5) plt.arrow(1,1,0.5,0.5, head_width=0.1, width=0.01, head_length=0.1, color='r') plt.arrow(1.25,0.75,0.5,0.5, head_width=0.1, widt...
2
2016-06-14T18:08:58Z
37,821,925
<p>I've been annoyed with that problem for (almost) ever, and mostly end up using <code>annotate()</code> to draw arrows. For example (lacking a lot of tweaking to end up with the identical result as your plot...):</p> <pre><code>import matplotlib.pyplot as plt import pylab as plab plt.figure() ax=plt.subplot(211) pl...
2
2016-06-14T20:56:05Z
[ "python", "matplotlib", "plot" ]
Need for m.initial_state.eval() in TensorFlow PTB tutorial
37,819,341
<p>In the PTB language model tutorial at <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/rnn/ptb/ptb_word_lm.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/rnn/ptb/ptb_word_lm.py</a>. I don't understand the need for line 248 (and the passing of ...
1
2016-06-14T18:15:45Z
37,841,596
<p>Okay, I figured it out. The RNN is called multiple times, and each time it is called you want it to start with a clean initial state. If you were to just call it once, you wouldn't need to pass in a clean initial state to <code>sess.run()</code>.</p>
1
2016-06-15T17:05:10Z
[ "python", "tensorflow" ]
PyQt: Getting the amount of lines from QTextEdit
37,819,455
<p>I am trying to make a chat application, so i added the QTextEdit widget where user types the content, maximum height of widget is <strong>30</strong> pixels, so basically <strong>one</strong> line.</p> <pre><code> self.msgtext = QtGui.QTextEdit(self) self.msgtext.setObjectName('msgtext') self.msgtext.set...
0
2016-06-14T18:23:08Z
37,819,885
<p>You can use <code>blockCount()</code> but don't forget to also resize whatever parent you are using for your <code>QTextEdit</code>. Here is an example:</p> <pre><code>import sys from PyQt5 import QtGui, QtWidgets, QtCore class Window(QtWidgets.QWidget): def __init__(self): QtWidgets.QWidget.__init__(s...
1
2016-06-14T18:48:31Z
[ "python", "pyqt" ]
How to start a command with subprocess with output in some file, unblocked?
37,819,497
<p>I am trying to use <code>subprocess</code> to start a command on the command-line for which I want to have the output written into some file. So, in other words, I want to have e.g. the following command executed within python:</p> <pre><code>python my_code.py --arg1 &gt; output.txt </code></pre> <p>I tried the fo...
0
2016-06-14T18:25:42Z
37,820,283
<p><code>sys.stdout</code> is buffered by default. You can disable it by passing <code>-u</code> to <code>python</code>. </p> <pre><code>import subprocess cwd = "/home/path/to/the/executable" cmd = "python -u my_code.py --arg1" with open('output.txt', "w") as outfile: subprocess.Popen(cmd.split(), stdout=outfile,...
2
2016-06-14T19:10:56Z
[ "python" ]
PyCurl - error with libcurl
37,819,504
<p>I am using pycurl - actually wants to use it - in my python scripts. I install it pip install pycurl - it pull version 7.43.0</p> <p>When executing <code>import pycurl</code> I have error 'Incompatible library version: pycurl.so requires version 8.0.0 or later, but libcurl.4.dylib provides version 7.0.0'</p> <p>I ...
0
2016-06-14T18:26:15Z
37,840,357
<p>I have installed pycurl just like you with <code>sudo pip install pycurl</code> and get <code>Successfully installed pycurl-7.43.0</code>, after which <code>import pycurl</code> is ok. and my <code>libcurl.4.dylib</code> is provided with version 8. I would recommand remove libcurl, and reinstall it with pycurl, refe...
0
2016-06-15T15:56:35Z
[ "python", "python-2.7", "curl", "pycurl" ]
Lambda function to make simple HTTP request
37,819,525
<p>I want to use AWS lambda to make a cronjob-style HTTP request. Unfortunately I don't know Python.</p> <p>I found they had a "Canary" function which seems to be similar to what I want. How do I simplify this to simply make the HTTP request? I just need to trigger a PHP file.</p> <pre><code>from __future__ import pr...
0
2016-06-14T18:27:44Z
37,819,699
<p>This program will "simply make the HTTP request."</p> <pre><code>from urllib2 import urlopen SITE = 'https://www.amazon.com/' # URL of the site to check def lambda_handler(event, context): urlopen(SITE) </code></pre>
2
2016-06-14T18:37:38Z
[ "php", "python", "lambda", "cron", "crontab" ]
Lambda function to make simple HTTP request
37,819,525
<p>I want to use AWS lambda to make a cronjob-style HTTP request. Unfortunately I don't know Python.</p> <p>I found they had a "Canary" function which seems to be similar to what I want. How do I simplify this to simply make the HTTP request? I just need to trigger a PHP file.</p> <pre><code>from __future__ import pr...
0
2016-06-14T18:27:44Z
37,819,915
<p>You can use Requests (<a href="http://docs.python-requests.org/en/master/" rel="nofollow">http://docs.python-requests.org/en/master/</a>) to work with the response in a easier way.</p> <pre><code>import requests URL = 'https://www.amazon.com/' def lambda_handler(event, context): requests.get(URL) </code></pre>...
1
2016-06-14T18:50:04Z
[ "php", "python", "lambda", "cron", "crontab" ]
Searching for a term in a text file using python
37,819,580
<p>I'm really desperate for some help on this python code please. I need to search for a variable (string), return it and the data present on the same line as the variable data. </p> <p>I've managed to create a variable and then search for the variable in a text file, however if the data contained in the variable is f...
0
2016-06-14T18:30:20Z
37,819,639
<p>See my changes below:</p> <pre><code>number = input("Please enter the number of the item that you want to find:") f = open("file.txt", "r") lines = f.read() for line in lines: # check each line instead if number in line: # if the number you're looking for is present print(line) # print it </code></pr...
2
2016-06-14T18:33:51Z
[ "python" ]
Searching for a term in a text file using python
37,819,580
<p>I'm really desperate for some help on this python code please. I need to search for a variable (string), return it and the data present on the same line as the variable data. </p> <p>I've managed to create a variable and then search for the variable in a text file, however if the data contained in the variable is f...
0
2016-06-14T18:30:20Z
37,819,705
<p>It goes like </p> <pre><code>lines_containg_number = [line for line in lines if number in line] </code></pre> <p>What this'll do is give you all the lines in the text file in the form of a list and then you can simply print out the contents of the list...</p>
0
2016-06-14T18:37:50Z
[ "python" ]
Searching for a term in a text file using python
37,819,580
<p>I'm really desperate for some help on this python code please. I need to search for a variable (string), return it and the data present on the same line as the variable data. </p> <p>I've managed to create a variable and then search for the variable in a text file, however if the data contained in the variable is f...
0
2016-06-14T18:30:20Z
37,819,908
<p>If you use 'with' loop, you don't have to close file. It will be handled by with. Otherwise you have to use f.close(). Solution: </p> <pre><code>number = input("Please enter the number of the item that you want to find:") with open('file.txt', 'r') as f: for line in f: if number in line: pri...
0
2016-06-14T18:49:43Z
[ "python" ]
ValueError: too many values to unpack when using itertuples() on pandas dataframe
37,819,622
<p>I am trying to convert a simple pandas dataframe into a nested JSON file based on the answer I found here: <a href="http://stackoverflow.com/questions/24374062/pandas-groupby-to-nested-json">pandas groupby to nested json</a></p> <p>My grouped dataframe looks like this:</p> <pre><code> firstname l...
0
2016-06-14T18:33:03Z
37,819,852
<p>As I understand itertuples, it will return a tuple with the first value being the index and the remaining values being all of the columns. You only have for <code>index, value in grouped.itertuples()</code> which means it's trying to unpack all of the columns into a single variable, which won't work. The <code>gro...
0
2016-06-14T18:46:15Z
[ "python", "json", "pandas", "nested" ]
ValueError: too many values to unpack when using itertuples() on pandas dataframe
37,819,622
<p>I am trying to convert a simple pandas dataframe into a nested JSON file based on the answer I found here: <a href="http://stackoverflow.com/questions/24374062/pandas-groupby-to-nested-json">pandas groupby to nested json</a></p> <p>My grouped dataframe looks like this:</p> <pre><code> firstname l...
0
2016-06-14T18:33:03Z
37,819,973
<p>When using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.itertuples.html" rel="nofollow"><code>itertuples()</code></a>, the index is included as part of the tuple, so the <code>for index, value in grouped.itertuples():</code> doesn't really make sense. In fact, <code>itertuples()</...
1
2016-06-14T18:53:48Z
[ "python", "json", "pandas", "nested" ]
AttributeError at /edit/ 'RequestContext' object has no attribute 'flatten' (Django 1.6.7)
37,819,739
<p>I have working project on Django 1.7 and now I had to downgrade Django version to 1.6.7. Now all seems work ok except one page where I get above mentioned error. The issue traceback pointed to crispy-forms and it exactly due to django version because as soon as I upgrade to django==1.7 all works again. Anybody knows...
0
2016-06-14T18:40:07Z
37,819,928
<p>It seems like the flatten property was introduced to the Context object in the version Django==1.7.</p> <p><a href="https://docs.djangoproject.com/en/1.7/ref/templates/api/#django.template.Context.flatten" rel="nofollow">https://docs.djangoproject.com/en/1.7/ref/templates/api/#django.template.Context.flatten</a></p...
1
2016-06-14T18:50:48Z
[ "python", "django", "django-crispy-forms" ]
Programatically Send Notification Email for an Office 365 Hosted Email Using REST or Python
37,819,828
<p>I am starting work on a project that will involve sending an auto generated email to a user. I am (most likely) going to build the application using Python and Django and host it as an Azure web app. The outgoing email address (hello@example.com) is hosted on Office 365. After some digging it looks like the recommen...
-1
2016-06-14T18:44:55Z
37,824,759
<p>You can create an app only following <a href="https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx" rel="nofollow">Client Credentials Grant flow</a>, leveraging which you can authenticate and authorize for AAD in backend.</p> <p>Here is a code sample on GitHub <a href="https://github.com/Azure-Samples/activ...
0
2016-06-15T01:41:28Z
[ "python", "email", "azure", "active-directory", "office365" ]
How to use boost::numpy::from_data in boost-numpy library
37,819,829
<p>I'm using boost.numpy and trying to make ndarray wrapper. I'm trying to send ndarray from python to c++ and c++ to python. When I sent ndarray from python to c++, the problem has occured. What is incorrect?</p> <pre><code>+++mod2.cpp+++ 1 #include"boost/numpy.hpp" 2 #include&lt;iostream&gt; 3 4 boost::numpy::ndarr...
1
2016-06-14T18:44:58Z
38,723,364
<p>I couldn't understand why, but if you use:</p> <pre><code>int *arr; arr = new int[5]; arr[0] = 5; arr[1] = 4; arr[2] = 3; arr[3] = 2; arr[4] = 1; </code></pre> <p>instead of <code>int arr[]={5,4,3,2,1}</code>, it will return the right array to python code.</p>
0
2016-08-02T14:32:47Z
[ "python", "c++", "numpy", "boost", "multidimensional-array" ]
What is the correct way to arrange unwieldy imports
37,819,881
<p>I'm fairly new to python and looking for the best (most preferred) way to handle imports in a project.</p> <p>I've been given the task to cleanup a python project and noticed there are the same includes in many modules throughout the project. Here is an example of what I am seeing.</p> <p>File my_main_file.py</p>...
3
2016-06-14T18:48:22Z
37,820,019
<p>If one or two specific things are imported, then:</p> <pre><code>from Tkinter import END, Toplevel, ... </code></pre> <p>If pretty much everything in that module is imported, then:</p> <pre><code>from Tkinter import * </code></pre> <p>If more than a bunch of functions and classes are imported, then:</p> <pre><c...
0
2016-06-14T18:56:17Z
[ "python", "python-2.7", "import" ]
What is the correct way to arrange unwieldy imports
37,819,881
<p>I'm fairly new to python and looking for the best (most preferred) way to handle imports in a project.</p> <p>I've been given the task to cleanup a python project and noticed there are the same includes in many modules throughout the project. Here is an example of what I am seeing.</p> <p>File my_main_file.py</p>...
3
2016-06-14T18:48:22Z
37,820,070
<p>I am not sure if we can have common file to import all common modules. I think, for all of the files which you mentioned in question, you need to have separate imports. </p> <p>About your side question, it is better to import specific function, method from class. You should import only those methods, functions whic...
0
2016-06-14T18:59:31Z
[ "python", "python-2.7", "import" ]
What is the correct way to arrange unwieldy imports
37,819,881
<p>I'm fairly new to python and looking for the best (most preferred) way to handle imports in a project.</p> <p>I've been given the task to cleanup a python project and noticed there are the same includes in many modules throughout the project. Here is an example of what I am seeing.</p> <p>File my_main_file.py</p>...
3
2016-06-14T18:48:22Z
37,820,212
<p>The way I've solved this in the past is to have an <code>__init__.py</code> file in each folder where the sources exist, then all your imports can go in there</p> <p>There are even better ways of organizing python files. For more information on how to organize modules, see the <a href="https://docs.python.org/3/tut...
0
2016-06-14T19:06:52Z
[ "python", "python-2.7", "import" ]
What is the correct way to arrange unwieldy imports
37,819,881
<p>I'm fairly new to python and looking for the best (most preferred) way to handle imports in a project.</p> <p>I've been given the task to cleanup a python project and noticed there are the same includes in many modules throughout the project. Here is an example of what I am seeing.</p> <p>File my_main_file.py</p>...
3
2016-06-14T18:48:22Z
37,820,360
<p>According to <a href="https://www.python.org/dev/peps/pep-0008/#imports" rel="nofollow">the PEP8 styleguide</a> (one of the most authoritative sources on what is pythonic) using wildcard imports (<code>from ... import *</code>) should be avoided unless you are republishing an interface, which is not your intent.</p>...
4
2016-06-14T19:15:46Z
[ "python", "python-2.7", "import" ]
What is the correct way to arrange unwieldy imports
37,819,881
<p>I'm fairly new to python and looking for the best (most preferred) way to handle imports in a project.</p> <p>I've been given the task to cleanup a python project and noticed there are the same includes in many modules throughout the project. Here is an example of what I am seeing.</p> <p>File my_main_file.py</p>...
3
2016-06-14T18:48:22Z
37,821,913
<p>Agree that <strong>from Tkinter import *</strong> is best avoided.</p> <p>One way I found to deal with long imports on any given module. Not totally clean, but less wordy than the 1 per line repeats you have.</p> <p>I would have done it with your TKinter import list, but I don't have it installed, so using <stron...
0
2016-06-14T20:55:26Z
[ "python", "python-2.7", "import" ]
Strict consumption of JSON, how to reorder key:values to specific JSON schema for Open Refine
37,819,935
<p>Trying to use Open Refine to analyze a data set of messy JSON strings (40k lines), however due to JSONs' nature of being unordered, some of the lines of JSON objects were mixed up when returned and recorded to a file. </p> <p>Some objects are missing keys, some objects have incorrect order. Example:</p> <pre><code...
0
2016-06-14T18:51:16Z
37,843,772
<p>"Importing the data into Open Refine, the program asks for a specific schema to compare to when it reads the file."</p> <p>This sounds like it accidentally detected it as XML rathar than as JSON or even Lines.</p> <p>However, You can choose which importer you wish to use (like Line based or JSON), not just the aut...
0
2016-06-15T19:03:25Z
[ "python", "json", "openrefine", "google-refine" ]
Strict consumption of JSON, how to reorder key:values to specific JSON schema for Open Refine
37,819,935
<p>Trying to use Open Refine to analyze a data set of messy JSON strings (40k lines), however due to JSONs' nature of being unordered, some of the lines of JSON objects were mixed up when returned and recorded to a file. </p> <p>Some objects are missing keys, some objects have incorrect order. Example:</p> <pre><code...
0
2016-06-14T18:51:16Z
38,247,738
<p>Not sure if you resolved this.</p> <p>The JSON needs to be valid before it can be successfully imported - at the moment the text you've posted in the Q above doesn't validate with a tool such as <a href="http://jsonlint.com" rel="nofollow">http://jsonlint.com</a>.</p> <p>The issue you have in terms of importing th...
0
2016-07-07T14:12:53Z
[ "python", "json", "openrefine", "google-refine" ]
Finding a string within an stdout_lines array
37,819,942
<p>I am trying to find whether a certain letter exists in an stdout_lines array. </p> <p>I want the role to run if there is a 'P' found in the stdout_output.</p> <p>The stdout_lines array looks like this:</p> <pre><code>"stdout": "P\r\nA\r\nS\r\nI\r\n", "stdout_lines": ["P", "A", "S", "I"] </code></pre> <p>myrole.y...
0
2016-06-14T18:52:04Z
37,820,230
<p>The error message is strange and I can not reproduce it in Ansible 2. But your condition still will not work, a list does not have a find method. In Ansible you can search a list with <code>in</code>:</p> <pre><code>roles: - all_servers - {role: production_server, when: '"P" in prod_fact'} </code></pre>
0
2016-06-14T19:07:55Z
[ "python", "ansible", "stdout", "jinja2", "ansible-playbook" ]
SQLAlchemy caching now() in execute query
37,820,071
<p>Minimal test case:</p> <pre><code>db = sqlalchemy.create_engine('postgres://foo@localhost/bar') con=db.connect() con.execute("select now();").first() sleep(60) con.execute("select now();").first() </code></pre> <p>The two execute statements return the same value, even though what time "now" is has changed. I thin...
0
2016-06-14T18:59:32Z
37,820,202
<p>There are <a href="https://www.postgresql.org/docs/9.1/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT" rel="nofollow">different functions</a> for the current timestamp in PostgreSQL. From the docs:</p> <blockquote> <pre><code>transaction_timestamp() statement_timestamp() clock_timestamp() timeofday() now...
2
2016-06-14T19:06:05Z
[ "python", "postgresql", "sqlalchemy" ]
Efficiently reshape numpy array
37,820,107
<p>I am working with NumPy arrays.</p> <p>I have a <code>2N</code> length vector <code>D</code> and want to reshape part of it into an <code>N x N</code> array <code>C</code>.</p> <p>Right now this code does what I want, but is a bottleneck for larger <code>N</code>:</p> <p>```</p> <pre><code>import numpy as np M =...
1
2016-06-14T19:01:27Z
37,820,199
<p>You can use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> to remove those nested loops -</p> <pre><code>C = D[N + np.arange(N)[:,None] - np.arange(N)] </code></pre> <p>One can also use <a href="http://docs.scipy.org/doc/numpy-1.10.0/refer...
3
2016-06-14T19:06:03Z
[ "python", "arrays", "performance", "numpy", "vectorization" ]
Why are my python scripts not updating even though that are saved?
37,820,108
<p>Fair warning, I'm a relatively inexperienced programmer, so my terminology may not be perfect.</p> <p>First off, I cloned a repository from Github that has a directory with the following structure:</p> <pre><code>main -&gt; dir1 -&gt; script1.py -&gt; dir2 -&gt; script2.py </code></pre> <p...
1
2016-06-14T19:01:28Z
37,820,521
<p>I think the problem is with your directory structure.</p> <p>If you have the main directory, i.e. the repo you cloned, let's call it <code>main_repo</code>, and a script <code>script1.py</code>, and you want to import stuff from <code>script2.py</code> in another folder, it should look like</p> <p><code>main_repo ...
0
2016-06-14T19:27:13Z
[ "python", "import", "permissions", "directory", "save" ]
python io.open() integer required error
37,820,111
<p>I'm getting the following error when attempting to open a new file with today's date.</p> <pre><code>Traceback (most recent call last): File "C:\BenPi\stacking\pi3\red_RTS\iotest.py", line 6, in &lt;module&gt; f = io.open('%s',today, 'w') TypeError: an integer is required </code></pre> <p>Here is my code</p> <pre...
0
2016-06-14T19:01:30Z
37,820,179
<p>You're not formatting correctly, you're using <code>,</code> instead of <code>%</code>:</p> <pre><code>f = io.open('%s'%today, 'w') </code></pre> <p>Besides, you can just do:</p> <pre><code>f = io.open(today, 'w') </code></pre>
-1
2016-06-14T19:05:08Z
[ "python" ]
python io.open() integer required error
37,820,111
<p>I'm getting the following error when attempting to open a new file with today's date.</p> <pre><code>Traceback (most recent call last): File "C:\BenPi\stacking\pi3\red_RTS\iotest.py", line 6, in &lt;module&gt; f = io.open('%s',today, 'w') TypeError: an integer is required </code></pre> <p>Here is my code</p> <pre...
0
2016-06-14T19:01:30Z
37,820,323
<p>The line f = io.open('%s',today, 'w') should have '%s' first argument the first argument must be the file name. If you write it like:</p> <pre><code>f = io.open(today, 'w') </code></pre> <p>Just works. Also consider using the "with" statment so in case of an exception the stream will be close anyway such as:</...
0
2016-06-14T19:13:18Z
[ "python" ]
how to get the shifted index value of a dataframe in Pandas?
37,820,130
<p>Consider the simple example below: </p> <pre><code>date = pd.date_range('1/1/2011', periods=5, freq='H') df = pd.DataFrame({'cat' : ['A', 'A', 'A', 'B', 'B']}, index = date) df Out[278]: cat 2011-01-01 00:00:00 A 2011-01-01 01:00:00 A 2011-01-01 02:00:00 A 2011-0...
1
2016-06-14T19:02:34Z
37,820,171
<p>What's wrong with <code>df['index_shifted']=df.index.shift(-1)</code>?</p> <p>(Genuine question, not sure if I missed something)</p>
1
2016-06-14T19:04:48Z
[ "python", "pandas", "dataframe", "date-range", "shift" ]
how to get the shifted index value of a dataframe in Pandas?
37,820,130
<p>Consider the simple example below: </p> <pre><code>date = pd.date_range('1/1/2011', periods=5, freq='H') df = pd.DataFrame({'cat' : ['A', 'A', 'A', 'B', 'B']}, index = date) df Out[278]: cat 2011-01-01 00:00:00 A 2011-01-01 01:00:00 A 2011-01-01 02:00:00 A 2011-0...
1
2016-06-14T19:02:34Z
37,820,178
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.shift.html" rel="nofollow"><code>Index.shift</code></a> with <code>-1</code>:</p> <pre><code>df['index_shifted']= df.index.shift(-1) print (df) cat index_shifted 2011-01-01 00:00:00 A 2010-12-31 ...
2
2016-06-14T19:05:02Z
[ "python", "pandas", "dataframe", "date-range", "shift" ]
Error installing kivyMD (kivy material design)
37,820,146
<p>I'm trying to install kivyMD, which is a kivy material theme, on my ubuntu computer. <a href="https://gitlab.com/kivymd/KivyMD" rel="nofollow">https://gitlab.com/kivymd/KivyMD</a></p> <p>I have installed kivy, and the example from kivy website run fine.</p> <p>I have installed kivyMD with these command from their ...
0
2016-06-14T19:03:28Z
37,822,357
<p>I found it.</p> <p>I forgot to add the ppa before installing kivy.</p> <pre><code>sudo add-apt-repository ppa:kivy-team/kivy </code></pre>
1
2016-06-14T21:22:12Z
[ "python", "material-design", "kivy", "kivy-language" ]
Python urllib2 connecting with proxy
37,820,201
<p>It doesn't seem to connect to a website with a proxy. I'm trying to print my IP from this website to confirm that it is in fact using the proxy.</p> <pre><code>import urllib2 import re proxy = urllib2.ProxyHandler({'http': '59.66.82.200:1080'}) opener = urllib2.build_opener(proxy) urllib2.install_opener(opener) f...
0
2016-06-14T19:06:04Z
37,820,423
<p>Line 154 of urllib2:</p> <p>return opener.open(url, data, timeout)</p> <p>Try changing your opener variable.</p>
0
2016-06-14T19:19:57Z
[ "python", "proxy", "urllib2", "urllib" ]
Python urllib2 connecting with proxy
37,820,201
<p>It doesn't seem to connect to a website with a proxy. I'm trying to print my IP from this website to confirm that it is in fact using the proxy.</p> <pre><code>import urllib2 import re proxy = urllib2.ProxyHandler({'http': '59.66.82.200:1080'}) opener = urllib2.build_opener(proxy) urllib2.install_opener(opener) f...
0
2016-06-14T19:06:04Z
37,867,658
<p>If I were you, I would take advantage of using the APIs available at <a href="https://www.proxicity.io/api" rel="nofollow">https://www.proxicity.io/api</a>. The proxies served by the Rotating Proxy API are tested and verified constantly, so you do not get a stale proxy.. Try this</p> <pre><code>import urllib2 impor...
0
2016-06-16T19:16:24Z
[ "python", "proxy", "urllib2", "urllib" ]
Recognize user returning to URL from same device
37,820,234
<p>I'm new to web programming, so I guess my question would seem very stupid :)</p> <p>I have simple website on Python/Django. There is some url, which users may open without any authentication. I need to remember this user somehow and recognize him when he re-opens this url once again (not for a long time - say, for ...
0
2016-06-14T19:08:16Z
37,820,294
<p>Coookies are your answer. They will work for any URL for the same browser. assuming your user has agreed to use them. An alternative would be to tag the links with parameters, but that is specific to the link and could be shared with others.</p>
0
2016-06-14T19:11:30Z
[ "python", "django", "session", "web" ]
socket.gaierror while connecting to remote server
37,820,285
<p>I am trying to connect to a remote database as follows:</p> <pre><code>with SSHTunnelForwarder( ssh_address=('10.160.1.24', 22), ssh_username='Administrator', ssh_password=ssh_password, remote_bind_address=('127.0.0.1', 5432)) as server: print("test") </code></pre> <p>But I am encountering this...
0
2016-06-14T19:11:00Z
38,000,816
<p>The problem was because of the lack of the local_bind_address parameter. The method seems to expect this parameter even though it is optional.</p>
0
2016-06-23T20:02:47Z
[ "python", "sockets", "ssh", "proxy" ]
Slicing without views (or: shuffling multiple arrays)
37,820,345
<p>I have two different numpy arrays and I would like to shuffle them in asynchronized way. </p> <p>The current solution is taken from <a href="https://www.tensorflow.org/versions/r0.8/tutorials/mnist/pros/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.8/tutorials/mnist/pros/index.html</a> and proce...
2
2016-06-14T19:14:39Z
37,820,844
<p>One way to permute two large arrays in-place in a synchronized way is to save the state of the random number generator and then shuffle the first array. Then restore the state and shuffle the second array.</p> <p>For example, here are my two arrays:</p> <pre><code>In [48]: a Out[48]: array([ 0, 1, 2, 3, 4, 5...
1
2016-06-14T19:48:03Z
[ "python", "arrays", "numpy", "memory-leaks", "slice" ]
Slicing without views (or: shuffling multiple arrays)
37,820,345
<p>I have two different numpy arrays and I would like to shuffle them in asynchronized way. </p> <p>The current solution is taken from <a href="https://www.tensorflow.org/versions/r0.8/tutorials/mnist/pros/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.8/tutorials/mnist/pros/index.html</a> and proce...
2
2016-06-14T19:14:39Z
37,840,855
<p>Actually I don't think that there is any issue with numpy or python. Numpy uses the system <code>malloc</code> / <code>free</code> to allocate the array and this leads to memory fragmentation (see <a href="http://stackoverflow.com/questions/3770457/what-is-memory-fragmentation">Memory Fragmentation on SO</a>).</p> ...
0
2016-06-15T16:24:27Z
[ "python", "arrays", "numpy", "memory-leaks", "slice" ]
How to get maximum 3 tensor in TensorFlow?
37,820,392
<p>I am building my own attention model in seq2seq based on TensorFlow. I was wondering how can I do something as following pseudo-code in TensorFlow:</p> <pre><code>att = [0.2,0.3,0.5,0.1,0.9,0.2]# This is a tensor or a list of tensors result = maximum3numbers(att) </code></pre> <p>Acceptable result could be:</p> <...
0
2016-06-14T19:17:40Z
37,824,672
<p>I think the top_k operator should do what you need:</p> <p><a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/nn.html#top_k" rel="nofollow">https://www.tensorflow.org/versions/r0.9/api_docs/python/nn.html#top_k</a></p>
0
2016-06-15T01:26:16Z
[ "python", "tensorflow" ]
Python Detect Screensaver Start/Stop Event on Windows
37,820,411
<p>How can a Python 2.7 script detect the start/stop event of a Windows Screensaver?</p>
1
2016-06-14T19:19:06Z
38,036,197
<p>You can actually do that with <a href="https://pypi.python.org/pypi/pywin32" rel="nofollow">Pywin32</a>. Pywin provides Python bindings for the Win32 API and for COM.</p> <p>Regarding your question, it allows you to "listen" to windows events - such as start/stop event of a Windows ScreenSaver.</p> <p>You should b...
1
2016-06-26T07:31:31Z
[ "python", "python-2.7" ]
Difference between "wrapper" and "method" descriptors?
37,820,527
<p>I was writing a code that finds "unbound methods" of a class using introspection and was surprised to see two different kinds of descriptors for builtin types:</p> <pre><code>&gt;&gt;&gt; type(list.append), list.append (&lt;class 'method_descriptor'&gt;, &lt;method 'append' of 'list' objects&gt;) &gt;&gt;&gt; type(...
7
2016-06-14T19:27:40Z
37,820,831
<p>It's an implementation detail. At C level, a built-in type like <code>list</code> defines methods like <code>append</code> by name through an array of <code>PyMethodDef</code> structs, while special methods like <code>__add__</code> are defined more indirectly.</p> <p><code>__add__</code> corresponds to a function ...
1
2016-06-14T19:47:05Z
[ "python" ]
Difference between "wrapper" and "method" descriptors?
37,820,527
<p>I was writing a code that finds "unbound methods" of a class using introspection and was surprised to see two different kinds of descriptors for builtin types:</p> <pre><code>&gt;&gt;&gt; type(list.append), list.append (&lt;class 'method_descriptor'&gt;, &lt;method 'append' of 'list' objects&gt;) &gt;&gt;&gt; type(...
7
2016-06-14T19:27:40Z
37,820,866
<p>It seems that <code>method_descriptor</code> and <code>wrapper_descriptor</code> are a kind of callables that are available in CPython. The difference between them seems to be simple <code>method_descriptor</code> is apparently used for the methods of built-in (implemented in C) objects:</p> <pre><code>set.__dict_...
0
2016-06-14T19:48:54Z
[ "python" ]
Finding JSON POST format of an API
37,820,551
<p>I'm trying to figure out the format to post data to an old undocumented API built with django python. </p> <p>The API using the following code to extract the POST:</p> <pre><code>ids = json.loads(request.POST.get("data", "[]")) </code></pre> <p>The <code>ids</code> is a array of ints</p> <p>The following script ...
0
2016-06-14T19:29:13Z
37,821,228
<pre><code>In[2]: import json In[3]: data = dict(data="[1,3]") In[4]: data Out[4]: {'data': '[1,3]'} In[5]: json.dumps(data) Out[5]: '{"data": "[1,3]"}' </code></pre> <p>json.dumps(data) returns string.</p> <p>From <a href="https://github.com/kennethreitz/requests/blob/master/requests/api.py" rel="nofollow">requests ...
1
2016-06-14T20:11:48Z
[ "python", "json", "django", "api" ]
Create dictionary of statistics for several lists in Python?
37,820,584
<p>I would like to create some basic statistics for several lists of data and store them in a dictionary:</p> <pre><code>&gt;&gt;&gt; from statistics import mean,median &gt;&gt;&gt; a,b,c=[1,2,3],[4,5,6],[7,8,9] </code></pre> <p>The following list comprehension works and outputs stats for "a":</p> <pre><code>&gt;&gt...
0
2016-06-14T19:31:17Z
37,820,726
<p>Do not quote the <code>k</code> in the inner <code>eval</code>:</p> <pre><code>{k:[eval("{}({})".format(op,eval(k))) for op in ['mean','median','min','max']] for k in ['a','b','c']} ^ </code></pre> <p>Or drop <code>eval</code> altogether:</p> <pre><code>[[mean(k), median(k), min(k...
2
2016-06-14T19:39:40Z
[ "python", "dictionary", "dictionary-comprehension" ]
Create dictionary of statistics for several lists in Python?
37,820,584
<p>I would like to create some basic statistics for several lists of data and store them in a dictionary:</p> <pre><code>&gt;&gt;&gt; from statistics import mean,median &gt;&gt;&gt; a,b,c=[1,2,3],[4,5,6],[7,8,9] </code></pre> <p>The following list comprehension works and outputs stats for "a":</p> <pre><code>&gt;&gt...
0
2016-06-14T19:31:17Z
37,820,971
<p>Try removing the quotation marks around k in your call to eval in the format function.</p> <p>I ran the following commands:</p> <pre><code>&gt; from statistics import mean,median &gt; a,b,c=[1,2,3],[4,5,6],[7,8,9] &gt; {k:[eval("{}({})".format(op,eval(k))) for op in ['mean','median','min','max']] for k in ['a','b'...
0
2016-06-14T19:56:09Z
[ "python", "dictionary", "dictionary-comprehension" ]
MD5 Bruteforce, Issue translating from Python to Javascript
37,820,589
<p>I prototyped this function yesterday in python to bruteforce an md5 hash and it works beautifully. In this case it will print <code>Match: aa</code> and <code>4124bc0a9335c27f086f24ba207a4912</code>. Since this is the hash for the string "aa".</p> <pre class="lang-python prettyprint-override"><code>import hashlib ...
0
2016-06-14T19:31:34Z
37,820,853
<p>Your loop iterator <code>i</code> is a global variable. Make it local with <code>var</code> or <code>let</code>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> function crack(chars, st, h...
3
2016-06-14T19:48:24Z
[ "javascript", "python", "recursion", "hash", "md5" ]
Combine multiple .csv files with python from different directory paths
37,820,620
<p>I am trying to combine multiple .csv files into one .csv file using the dataframe in pandas. the tricky part about this is, i need to grab multiple files from multiple days. Please let me know if this does not make sense. As it currently stands i cannot figure out how to loop through the directory. Could you offer s...
0
2016-06-14T19:33:13Z
37,820,772
<p>IIUC you can create <code>list</code> <code>all_files</code> and in loop append output from <code>glob</code> to <code>all_files</code>:</p> <pre><code>all_files = [] for x in xrange(dateRange): print startDate startDate = startDate + 1 filePath = os.path.join(r"\\export\path", startDate, "preprocessed"...
0
2016-06-14T19:43:28Z
[ "python", "pandas" ]
Check if some elements are missing and some are not python
37,820,628
<p>I have a list of animal names:</p> <pre><code>aList = [animal_lionAnimal, animal_elephantAnimal_1, animal_elephantAnimal_2, animal_elephantAnimal_3, animal_pandaAnimal_1, animal_pandaAnimal_2] </code></pre> <p>Then I have a file which also contains these animal names. I read the file by argumentparser and then u...
0
2016-06-14T19:33:41Z
37,820,964
<p>In general, you can check if all elements of list <code>A</code> are contained within list <code>B</code> by the following:</p> <pre><code>all(a in B for a in A) </code></pre> <p>This will return <code>True</code> if each element of <code>A</code> is within <code>B</code> or if <code>A</code> is empty. It will re...
0
2016-06-14T19:55:52Z
[ "python" ]
centerline of a polygonal blob (binary image)
37,820,629
<p>I have a binary image of a worm (blob extraction which works well). I am interested in fitting a centerline on the blowb (worm).</p> <p>So far I came up with this: starting from a polygon (after outline extraction of blob in the image) I applied a voronoi computation and discarded all vertices which are outside of ...
3
2016-06-14T19:33:41Z
38,000,630
<p>I have found a better solution:</p> <ul> <li><a href="http://scikit-image.org/docs/dev/api/skimage.morphology.html#medial-axis" rel="nofollow">skeltonize</a> the binary blob</li> <li>build the <a href="https://networkx.github.io/" rel="nofollow">graph</a> (without cycles) of the skeleton by tracing pixel lines and ...
0
2016-06-23T19:52:35Z
[ "python", "polygon", "computational-geometry", "curve-fitting", "voronoi" ]
Annonymous sympy expression
37,820,643
<p>I have code like this, where sympy functions are passed into a list:</p> <pre><code> if name == "sqrt": func.append(sympy.sqrt) elif name == "abs": funcs.append(sympy.Abs) elif name == "sin": funcs.append(sympy.sin) elif name == "cos": funcs.append(sympy.cos) elif ...
3
2016-06-14T19:34:23Z
37,821,081
<p>Use lambda expressions: <code>funcs.append(lambda x: sympy.Min(1, sympy.exp(x)))</code></p>
0
2016-06-14T20:01:42Z
[ "python", "sympy" ]
How to identify a colored string inside of an array?
37,820,692
<p>I have a 2-D array I use as a map for a text based game I've written in Python. I want to restrict users from walking on certain tiles. This is an easy fix when it comes to the border, as it is represented with <code>'#'</code>'s along the edges. However, in-game geography uses termcolor's colored module, e.g. mo...
0
2016-06-14T19:37:44Z
37,820,778
<p>Your conditional is wrong. You want to check if <code>USERPOSITION</code> is equal to <code>'#'</code> or if it is equal to <code>colored('^', 'red')</code>.</p> <p>To do so, write out each condition explicitly and check if either is true using <code>or</code>:</p> <p><code>if USERPOSITION == '#' or USERPOSITION =...
2
2016-06-14T19:43:39Z
[ "python", "arrays" ]
Website that pulls information from a running desktop application
37,820,892
<p>So, I have a website which I'm using Javascript on and a desktop application written in python. I am wanting the web page to pull data from the python app when it's loaded without having to go through too many loops. So, if possible, how could I setup Python to send the page information when it requests it? I know t...
-1
2016-06-14T19:50:10Z
37,821,052
<p>Since you said <code>without having to go through too many loops</code> I'm assuming this means you want it simple. The easiest way I can think of is setting 2 endpoints (urls):</p> <ul> <li>One for asking if it's time to send the information</li> <li>Another one for actually sending it</li> </ul> <p>In this case ...
0
2016-06-14T20:00:16Z
[ "javascript", "python", "website" ]
Creating a Multiplying Function - Python
37,820,896
<p>I don't understand how to make a function and then make it work which will allow me to multiply. For E.g.</p> <pre><code>def Multiply(answer): num1,num2 = int(2),int(3) answer = num1 * num2 return answer print(Multiply(answer)) </code></pre> <p>I Had a go at making one and didnt work so the one belo...
-1
2016-06-14T19:50:31Z
37,820,979
<p>I believe you have your parameter as your return value and you want your paramters to be inputs to your function. So try</p> <pre><code>def Multiply(num1, num2): answer = num1 * num2 return answer print(Multiply(2, 3)) </code></pre> <p>As for the second script, it looks fine to me. You can just print the ...
4
2016-06-14T19:56:30Z
[ "python", "function", "multiplying" ]
Creating a Multiplying Function - Python
37,820,896
<p>I don't understand how to make a function and then make it work which will allow me to multiply. For E.g.</p> <pre><code>def Multiply(answer): num1,num2 = int(2),int(3) answer = num1 * num2 return answer print(Multiply(answer)) </code></pre> <p>I Had a go at making one and didnt work so the one belo...
-1
2016-06-14T19:50:31Z
37,821,025
<p>I believe this is what you're looking for:</p> <pre><code>def Multiply( num1, num2 ): answer = num1 * num2 return answer print(Multiply(2, 3)) </code></pre> <p>The function Multiply will take two numbers as arguments, multiply them together, and return the results. I'm having it print the return value of...
0
2016-06-14T19:58:57Z
[ "python", "function", "multiplying" ]
Print time value in python
37,820,900
<p>I am trying to print the contents of my dictionary with actual time values (for example, '6:00 AM') from my workbook. I get a different time format when I print from 'TimeSheet' than I do 'From'. How can I get the actual time value to print.</p> <p><a href="http://i.stack.imgur.com/XPHRA.jpg" rel="nofollow"><img sr...
0
2016-06-14T19:50:35Z
37,821,461
<p>You're looking for <code>strftime</code> (string-format-time).</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; datetime.now() datetime.datetime(2016, 6, 14, 17, 24, 27, 735835) &gt;&gt;&gt; datetime.now().strftime("%Y %m %d") '2016 06 14' </code></pre> <p>The <a href="https://docs.python.o...
2
2016-06-14T20:25:12Z
[ "python" ]
Print time value in python
37,820,900
<p>I am trying to print the contents of my dictionary with actual time values (for example, '6:00 AM') from my workbook. I get a different time format when I print from 'TimeSheet' than I do 'From'. How can I get the actual time value to print.</p> <p><a href="http://i.stack.imgur.com/XPHRA.jpg" rel="nofollow"><img sr...
0
2016-06-14T19:50:35Z
37,821,528
<p>As others already stated, you can use <code>strftime</code> to modify the formatting of your time, like so:</p> <pre><code>format = '%H:%M %p' # Hour, Minute, AM or PM TimeSheet = {'From': From.strftime(format), 'To': To.strftime(format), 'Activity': Activity} # {'From': '6:00 AM', 'To': '6:15 AM', 'Activity': Non...
0
2016-06-14T20:29:27Z
[ "python" ]
Use more than one thread when calling intel's mkl directly from python
37,820,918
<p>I call intel's math kernel library from python. So far, it is using just one cpu, instead of all 12 cpu, according to linux's top command. How to make it use all 12 cpu?</p> <p>I have tried setting three environmental variables (OMP_NUM_THREADS, MKL_NUM_THREADS, MKL_DOMAIN_NUM_THREADS) to 12.</p> <p>I have also tr...
0
2016-06-14T19:51:37Z
37,821,320
<p>It seems some of the python distributions (e.g., <a href="https://www.continuum.io/why-anaconda" rel="nofollow">anaconda</a>) will respond to the environmental variables, while others (CentOS 7 default) not. Never dig into it further.</p>
1
2016-06-14T20:16:34Z
[ "python", "numpy", "scipy", "intel", "intel-mkl" ]
How to get python script return value in Makefile?
37,820,920
<p>Can somebody help me to find a way to capture the return value from a python script in Makefile.I have a scenario where the source code is getting build through the Makefile and it should throw a build error when python script reruns a failure.</p> <p><strong>myMakefile.mak</strong></p> <p><code>python mySample.py...
0
2016-06-14T19:51:45Z
37,821,199
<p>One way to do it would be to have your python script write the value you want to use in the makefile to an output file. Then your makefile could read in the value from that intermediary file.</p> <p>Example: </p> <pre><code>with open("intermediary.tmp", "wb") as h: h.write(SUCCESS) </code></pre>
0
2016-06-14T20:09:46Z
[ "python", "makefile" ]
How to get python script return value in Makefile?
37,820,920
<p>Can somebody help me to find a way to capture the return value from a python script in Makefile.I have a scenario where the source code is getting build through the Makefile and it should throw a build error when python script reruns a failure.</p> <p><strong>myMakefile.mak</strong></p> <p><code>python mySample.py...
0
2016-06-14T19:51:45Z
37,821,628
<p>If your python script exits with a non-zero code, <code>make</code> will detect this and tell you that an error occurred. So you don't need to do anything more.</p> <p>Example, if I have a program <code>foo.py</code> that does this:</p> <pre><code>print 'running foo' exit(1) </code></pre> <p>And a <code>Makefile<...
0
2016-06-14T20:35:15Z
[ "python", "makefile" ]
Python MySQLdb - Getting a ValueError
37,820,937
<p>Trying to import a list into MySQL through Python with MySQLdb...code below.</p> <p>I get a ValueError when I run it - </p> <pre><code>query = query % tuple([db.literal(item) for item in args]) ValueError: unsupported format character ',' (0x2c) at index 51 </code></pre> <p>Code_</p> <pre><code>import MySQLdb im...
1
2016-06-14T19:53:09Z
37,821,157
<p><a href="https://www.python.org/dev/peps/pep-0249/#id14" rel="nofollow"><code>.execute</code></a> expect 2 arguments when using with wildcards or string replacement in the following manner:</p> <ul> <li>query_string with value placeholders <code>%s</code></li> <li>a tuple of values that will replace the above <code...
1
2016-06-14T20:06:40Z
[ "python", "mysql", "mysql-python" ]
Else condition never reached in pandas dataframe
37,820,981
<p>I have a populateResult function that populates the field ResultAccount. If df3.AccounName2 is empty, then df3["ResultAccount"] is df3.AccountName. Else df3["ResultAccount"] is df3.AccountName2. </p> <p>In my code, that elif condition is never reached. Only the if condition gets evaluated and it populates the Resul...
0
2016-06-14T19:56:35Z
37,821,023
<p>I think you need double <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a>:</p> <pre><code>df3["ResultAccount"] = np.where(df3.AccountName2.isnull(), df3.AccountName, np.w...
0
2016-06-14T19:58:43Z
[ "python", "pandas", "ipython" ]
RethinkDB, query with map and filter
37,820,991
<p>I have rethinkdb 'competition' table. At the second level I got runners and each runner have a list of results:</p> <pre><code>"total_results": { "433915": [ #runner_id { "judge": "15561671", "result": 5, "round": "1" }, { "judge": "08136a59", "result": 4, "round":...
1
2016-06-14T19:57:15Z
37,822,863
<p>I think you want your second <code>map</code> to be a <code>concat_map</code>. (Alternatively, if you like the existing output format, you can put the <code>filter</code> inside a <code>map</code> like <code>.map(lambda x: x.filter(...))</code>.)</p>
0
2016-06-14T22:03:30Z
[ "python", "rethinkdb" ]
Python constrained linear optimization
37,821,049
<p>Hello I'm trying to solve a linear system of equations with two sideconstraints, one which is succesfully implemented, that the result should sum up to 1, but I need another, that each solution should be nonnegative. Anyone who know how to add this constraint? Thanks</p> <pre><code>import numpy as np import numpy.l...
0
2016-06-14T20:00:05Z
37,865,715
<p>I am assuming that this is the system of equations you are trying to solve:</p> <pre><code>.5x1 + .3x2 + .2x3 = 0 .4x1 + 6x2 + .3x3 = 0 .2x1 + .3x2 + .5x3 = 0 x1 + x2 + x3 =1 x1, x2, x3 &gt;=0 </code></pre> <p>This can be solved easily using <code>scipy.optimize.linprog</code>. Here as you do not have an objective...
0
2016-06-16T17:24:58Z
[ "python", "scipy" ]
Vectorized matrix selection based on array
37,821,065
<p>I have a <code>S x n</code> array <code>DATA</code> with data. I have a <code>(S x 1)</code> array <code>ARRAY</code> with integer values <code>&lt;=n</code>. For each row <code>i</code> in <code>DATA</code>, I want to </p> <pre><code>DATA[i, ARRAY[i]:] = np.nan </code></pre> <p>Here's how I'm doing it right now</...
2
2016-06-14T20:01:01Z
37,821,136
<p>You can use <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean-array-indexing" rel="nofollow"><code>boolean indexing</code></a> -</p> <pre><code>DATA[ARRAY &lt;...
2
2016-06-14T20:04:59Z
[ "python", "performance", "numpy", "scipy", "vectorization" ]
What is windows doing when a command like python is run in a terminal?
37,821,264
<p>This is more of a question about the general processes that windows performs when a command is run in powershell</p> <p>My understanding is that when the command</p> <pre><code>C:\&gt;python </code></pre> <p>is run in powershell, it references a python executable stored somewhere else. This path was added for me ...
-1
2016-06-14T20:13:45Z
37,821,369
<p>If you open up python.exe in IDA Pro or another disassembler or debugger, you can trace the execution and see that it has multiple paths depending on how it is run. </p> <p>It is not referencing a different executable, it is looking at how it was executed (does it have arguments passed or not? what are those argu...
0
2016-06-14T20:19:09Z
[ "python", "powershell", "path" ]
What is windows doing when a command like python is run in a terminal?
37,821,264
<p>This is more of a question about the general processes that windows performs when a command is run in powershell</p> <p>My understanding is that when the command</p> <pre><code>C:\&gt;python </code></pre> <p>is run in powershell, it references a python executable stored somewhere else. This path was added for me ...
-1
2016-06-14T20:13:45Z
37,822,039
<p>The shell (not only powershell, but cmd.exe, bash etc) parses the command line, takes the first token, tryes to find an internal command or an executable that matches the token, and in case of success executes what was found passing to it the command line as an argument.</p> <p>In your case the shell splits <code>p...
1
2016-06-14T21:02:43Z
[ "python", "powershell", "path" ]
Why can't I find elements on a pop-up window using selenium webdriver for python after successfully switching windows in firefox?
37,821,319
<p><strong>I cannot find any elements in a new window, even after applying a long wait</strong></p> <p>Using a firefox browser, I am able to use selenium to click on a link that opens a new window.Then I switch to the new window after looking up the window handle.</p> <pre><code>winHandles = browser.window_handles Ne...
-1
2016-06-14T20:16:34Z
37,887,542
<p>As sagarwadhwa1 suggested in their comment, the window may switch without switching to the expected frame. You can find the correct frame by name or index and switch to it.</p> <pre><code> browser.switch_to.frame(1) </code></pre>
0
2016-06-17T17:54:22Z
[ "python", "selenium", "firefox" ]
Test Suite for Python selenium does not work
37,821,345
<p>I have created a test suite however only first test case runs and then execution stops. Second test cases (class) doesn't execute. I am writing these tests in Eclipse.</p> <p><code>TestSuite.py</code></p> <pre><code>class Test_Suite(unittest.TestCase): def test_main(self): # suite of TestCa...
0
2016-06-14T20:17:34Z
37,821,443
<p>According to the <code>unittest</code> <a href="https://docs.python.org/2.7/library/unittest.html#basic-example" rel="nofollow">documentation</a>, your test cases must start with the letters <code>test</code>.</p> <p>Change your tests to <code>test1_DisabledLoginButton</code> and <code>test2_WrongUserName</code>; y...
1
2016-06-14T20:23:57Z
[ "python", "eclipse", "selenium", "webdriver" ]
Insert column specific NaN and drop rows depending on value
37,821,394
<p>I have performed several hypothetical tests on insects. I want to drop rows with low <strong>result_1 values of 'less than 10'</strong> which I consider not to be significant, but would like to leave a NaN in value a <strong>single row</strong> to show which test was performed and on which insect.</p> <pre><code>fr...
1
2016-06-14T20:20:23Z
37,821,692
<p>I think you can use:</p> <pre><code>#add NaN by condition df.loc[df.result_1 &lt; 10, ['result_1','result_2']] = np.nan #drop duplicated by column insect df[df.result_1.isnull()] = df[df.result_1.isnull()].drop_duplicates(subset='insect') df = df.dropna(how='all') print (df) test insect result_1 result_2 0 ...
2
2016-06-14T20:40:29Z
[ "python", "pandas", "dataframe", "insert", null ]
Different test objects pass individually but have error running together. [Does Python nosetests run different test classes in parallel?]
37,821,521
<p>I have several test objects that I am connecting to DB in each of their setups. Apparently, my DB connection limits number of accesses per IP, since I am getting this error telling me that a connection is already established when I run all the tests/ folder, but if I run them separately, they all pass. So, I'm wonde...
-1
2016-06-14T20:29:01Z
37,824,188
<p>Nose shouldn't run your tests in parallel by default; it should require you to explicitly pass in the <code>--processes</code> flag. What else is going in your DB, How many connections does it have? How many does it support? Where are the connections coming from?</p>
2
2016-06-15T00:19:28Z
[ "python", "unit-testing", "nose" ]
Different test objects pass individually but have error running together. [Does Python nosetests run different test classes in parallel?]
37,821,521
<p>I have several test objects that I am connecting to DB in each of their setups. Apparently, my DB connection limits number of accesses per IP, since I am getting this error telling me that a connection is already established when I run all the tests/ folder, but if I run them separately, they all pass. So, I'm wonde...
-1
2016-06-14T20:29:01Z
37,869,289
<p>We figured the problem out. It was not about nose running tests in parallel. It was one of tests changing an attribute of sys, which was not used in that particular test but was affecting others.</p>
-1
2016-06-16T21:02:14Z
[ "python", "unit-testing", "nose" ]
accessing two list elements to get results
37,821,540
<p>I have two lists. One list name 'date' has dates in it which are related to persons birth date.</p> <pre><code>data = [ datetime.datetime(1958, 3, 15, 0, 0), datetime.datetime(1958, 9, 15, 0, 0), datetime.datetime(1930, 10, 23, 0, 0), datetime.datetime(1928, 9, 15, 0, 0), datetime.datetime(1928, 1, 23, 0, 0), datet...
-1
2016-06-14T20:30:12Z
37,821,644
<p>This assumes that the marriage and birth dates are in the same order (i.e., the first two birth dates correspond to the first marriage date and the next 2 birth dates correspond to the second marriage date)</p> <pre><code>for i in range(len(marriage)): if marriage[i] &gt; data[i*2] and marriage[i] &gt; data[(i*...
-1
2016-06-14T20:36:34Z
[ "python" ]
accessing two list elements to get results
37,821,540
<p>I have two lists. One list name 'date' has dates in it which are related to persons birth date.</p> <pre><code>data = [ datetime.datetime(1958, 3, 15, 0, 0), datetime.datetime(1958, 9, 15, 0, 0), datetime.datetime(1930, 10, 23, 0, 0), datetime.datetime(1928, 9, 15, 0, 0), datetime.datetime(1928, 1, 23, 0, 0), datet...
-1
2016-06-14T20:30:12Z
37,821,680
<pre><code>for i in range(len(data)): if data[i] &lt; marriage[i]: print "birthdate is lt marriage date" else: print "birthdate is gt or eq to marriage date" </code></pre> <p>I'm not sure what you are trying to accomplish here... Also you don't need re for date comparison, you can use normal <code>&lt; &gt...
0
2016-06-14T20:39:26Z
[ "python" ]
Loop through table and remove rows without using object index
37,821,606
<p>I've been teaching myself python, and currently I'm trying to loop through an astropy table and replace any rows that have a certain value in the second column. I can write a script that accomplishes this, but not without using a dummy index to keep track of what row I'm on. </p> <pre><code>for value in my_list: ...
0
2016-06-14T20:33:39Z
37,914,674
<p>Someone pointed out to me that this can be done using <code>enumerate()</code></p> <pre><code>for value in my_list: for row in enumerate(data_table): if value == row[1][1]: data_table.remove_row(row[0]) data_table.add_row([replacement_row]) </code></pre>
0
2016-06-20T04:33:55Z
[ "python", "loops", "table" ]
Filling missing middle values in pandas dataframe
37,821,653
<p>I have a pandas dataframe <code>df</code> as</p> <pre><code>Date cost NC 20 5 NaN 21 7 NaN 23 9 78.0 25 6 80.0 </code></pre> <p>Now what I need to do is fillup the missing dates and hence fill the column with a value say <code>x</code> only if there is number in the previous row. That is ...
1
2016-06-14T20:37:07Z
37,822,851
<p>I don't think there is a way to pad just the "middle" values, but here's a way to do it (using <code>ffill</code>, <code>bfill</code> and <code>fillna</code>):</p> <pre><code>In [11]: df1 # assuming Date is the index via df.set_index("Date") Out[11]: cost NC Date 20 5 NaN 21 7 NaN 23 ...
1
2016-06-14T22:02:43Z
[ "python", "pandas", "dataframe" ]