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
Defining functions for multiple data sets
39,839,029
<p>I have bunch of data sets and their names are like;</p> <pre><code>df_a df_b df_c df_d ... </code></pre> <p>All the data sets have the same columns, My question is, I want to apply some functions all the data sets.</p> <p>The functions are like:</p> <pre><code>df.fillna(0, inplace=True) df['day_of_week'] = df.da...
0
2016-10-03T19:29:35Z
39,839,128
<pre><code>dfs = [df_a, df_b, ...] for dataset in dfs: do_thing(dataset) </code></pre>
0
2016-10-03T19:36:10Z
[ "python", "function", "pandas" ]
haskell, figuring use some defined function to draw the mandelbrot, need explanation
39,839,033
<p>I've write several function that need to used in function mandelbrot to draw it, here are these:</p> <pre><code># sp that takes integer n, element y, list xs. insert the specified element y after every n elements. sp 1 'a' ['b','c','d'] = ['b','a','c','a','d','a'] # plane that gives (x/r,y/r) where x and y are int...
0
2016-10-03T19:29:46Z
39,883,645
<p>I figure it out.</p> <p>So what I need to do is:</p> <pre><code>-- find all points using plane r -- using orbit list comprehension to take the orbit with one point at index i -- using norm(x,y) to calculate the distance of orbit to the original -- using find to give the list of char -- finally using sp to put char...
0
2016-10-05T21:04:07Z
[ "python", "python-3.x", "haskell", "mandelbrot" ]
Python, tuple indices must be integers, not tuple?
39,839,034
<p>So, I'm not entirely sure what's going on here, but for whatever reason Python is throwing this at me. For reference, it's part of a small neural network I'm building for fun, but it uses a lot of np.array and such, so there's a lot of matrices being thrown around, so I think it's creating some sort of data type cla...
0
2016-10-03T19:29:49Z
39,839,092
<p>Your <code>output</code> variable is not a <code>N x 4</code> matrix, at least not in <strong>python types</strong> sense. It is a <strong>tuple</strong>, which can only be indexed by a single number, and you try to index by tuple (2 numbers with coma in between), which works only for numpy matrices. Print your outp...
3
2016-10-03T19:33:47Z
[ "python", "indexing", "types", "tuples" ]
Script for extracting information of specific pattern from a text file
39,839,065
<p>Hi I am working on a project which deals with large amount of data. I have a text file of around 2 GB with key value pairs and each key has multiple values. I need to extract all the keys in a different file, as I need the keys for testing a particular feature.</p> <p>The format of the file is:</p> <pre><code>:k...
-2
2016-10-03T19:31:57Z
39,852,319
<p>Assuming a file like</p> <pre><code>:k: k1 :v: {XYZ:{id: :k2: k1 :v: {XYZ:{id: :k: k1 :v: {XYZ:{id: :k3: k1 :v: {XYZ:{id: :k: k1 :v: {XYZ:{id: </code></pre> <p>You can easily do (in 1 pass), and with no memory restrictions</p> <pre><code>awk '{fName=$1; gsub(/:/,"",fName); print &gt;&gt; fName ; close(fName)}' in...
0
2016-10-04T12:26:05Z
[ "python", "bash", "shell", "pattern-matching", "data-processing" ]
How to process a date diference using same id elements in a list
39,839,067
<p><strong>I have the following data structure:</strong></p> <pre><code>[ (19L, datetime.datetime(2015, 2, 11, 12, 3, 43)), (19L, datetime.datetime(2015, 2, 12, 16, 28, 48)), (19L, datetime.datetime(2014, 9, 17, 11, 58, 19)), (80L, datetime.datetime(2014, 9, 15, 12, 54, 36)), (80L, datetime.datetime(2014, 9, 1...
0
2016-10-03T19:32:07Z
39,839,232
<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby()</code></a> to group by user id (assuming the list is sorted by the grouping key - which looks like it is), then, you can use "pairwise" iteration and calculate an average day difference:<...
0
2016-10-03T19:43:38Z
[ "python", "list", "loops", "counting" ]
How to process a date diference using same id elements in a list
39,839,067
<p><strong>I have the following data structure:</strong></p> <pre><code>[ (19L, datetime.datetime(2015, 2, 11, 12, 3, 43)), (19L, datetime.datetime(2015, 2, 12, 16, 28, 48)), (19L, datetime.datetime(2014, 9, 17, 11, 58, 19)), (80L, datetime.datetime(2014, 9, 15, 12, 54, 36)), (80L, datetime.datetime(2014, 9, 1...
0
2016-10-03T19:32:07Z
39,839,357
<p>I would sort the timestamps into a dictionary where each key is a user's ID and the value is a list of access times. then after sorting that list of timestamps, find the difference between each visit time and find the average. the <code>datetime.timedelta</code> object can be used to simplify math operations on time...
-1
2016-10-03T19:52:27Z
[ "python", "list", "loops", "counting" ]
Python Celery - Permission Issue - Unable to upload files from a download task
39,839,084
<p>I have a Celery task whose job is to download files to a local directory, and then upload to a S3 bucket when download is complete.</p> <p>My issue is that with a recent update of the workers, I'm getting permission denied errors when accessing the folder to upload. The code was fundamentally unchanged other than ...
0
2016-10-03T19:33:26Z
39,839,531
<p>The CELERY_CREATE_DIR only tells celery create its operational directories:</p> <blockquote> <p>Always create directories (log directory and pid file directory). Default is to only create directories when no custom logfile/pidfile set.</p> </blockquote> <p>I believe your problem is with the <code>os.mkdirs</code...
0
2016-10-03T20:03:50Z
[ "python", "django", "celery" ]
Rank of a Permutation
39,839,119
<p>so there was a question I wasn't able to solve mainly because of computing power or lack thereof. Was wondering how to code this so that I can actually run it on my computer. The gist of the questions is:</p> <p>Let's say you have a string <code>'xyz'</code>, and you want to find all unique permutations of this str...
4
2016-10-03T19:35:32Z
39,839,283
<p>This problem can be easily solved by first simplifying it and thinking recursively.</p> <p>So let's first assume that all the elements in the input sequence are unique, then the set of "unique" permutations is simply the set of permutations.</p> <p>Now to find the rank of the sequence <code>a_1, a_2, a_3, ..., a_n...
1
2016-10-03T19:46:38Z
[ "python", "algorithm", "performance", "permutation", "combinatorics" ]
Rank of a Permutation
39,839,119
<p>so there was a question I wasn't able to solve mainly because of computing power or lack thereof. Was wondering how to code this so that I can actually run it on my computer. The gist of the questions is:</p> <p>Let's say you have a string <code>'xyz'</code>, and you want to find all unique permutations of this str...
4
2016-10-03T19:35:32Z
39,839,340
<p>Here's some Ruby code I wrote to do exactly this. You'd need to modify it if you have repeated elements (and decide how you want to handle them). </p> <p>This takes advantage that if we have n elements, each selection of k elements will show up exactly (n-k)! times. E.g., [a,b,c,d] -- if we look at all permutations...
0
2016-10-03T19:51:16Z
[ "python", "algorithm", "performance", "permutation", "combinatorics" ]
Rank of a Permutation
39,839,119
<p>so there was a question I wasn't able to solve mainly because of computing power or lack thereof. Was wondering how to code this so that I can actually run it on my computer. The gist of the questions is:</p> <p>Let's say you have a string <code>'xyz'</code>, and you want to find all unique permutations of this str...
4
2016-10-03T19:35:32Z
39,839,381
<p><strong>Let's see how index of string can be calculated without finding all permutation of the string.</strong> </p> <p>Consider string <code>s = "cdab".</code> Now, before string <code>s</code> (in lexical order), strings <code>"a***",</code> <code>"b***"</code> would be there. (<code>*</code> denotes remaining ch...
0
2016-10-03T19:53:52Z
[ "python", "algorithm", "performance", "permutation", "combinatorics" ]
How to Define a Piecewise Function in Python with Multiple Variables
39,839,138
<p>I am trying to develop a plot for my helioseismology class and the question had provided a piecewise function describing the dynamics of the "fluids" in a star as if it is one thing its this and if its another its that. I am receiving over and over again this <code>'Mul' object cannot be interpreted as an integer</c...
1
2016-10-03T19:37:05Z
39,859,692
<p>There are quite a few issues here:</p> <ul> <li><p>None of the keyword arguments (Constant, Variable, unit, Real) that you are passing to Symbol are things that are recognized by SymPy. The only one that is close is <code>real</code>, which should be lowercase (like <code>Symbol('x', real=True)</code>). The rest do...
1
2016-10-04T18:52:26Z
[ "python", "for-loop", "sympy", "bessel-functions" ]
The difference between applying permissions to separate object and list of objects in django rest framework
39,839,156
<p>In my code permissions result differently to object and list of objects.</p> <p>Let's say we have one model of <code>User</code>:</p> <pre><code>class User(auth.AbstractBaseUser, auth.PermissionsMixin): name = models.CharField(max_length=255, blank=True, null=True) profile_status = models.CharField(max_len...
0
2016-10-03T19:38:12Z
39,839,545
<p>It is expensive computationally to do this for every user. Imagine if you had hundreds of thousands of them. In the <a href="http://www.django-rest-framework.org/api-guide/permissions/#limitations-of-object-level-permissions" rel="nofollow">docs</a>:</p> <blockquote> <p><strong>Limitations of object level permiss...
1
2016-10-03T20:04:58Z
[ "python", "django", "permissions", "django-rest-framework" ]
TypeError: unsupported operand type(s) for *: 'PCA' and 'float'
39,839,310
<p>EDIT:</p> <p>Here is the head of the data csv:</p> <pre><code> Fresh Milk Grocery Frozen Detergents_Paper Delicatessen 0 12669 9656 7561 214 2674 1338 1 7057 9810 9568 1762 3293 1776 2 6353 8808 7684 2405 3516 7844 3 13265 1196 4221 6404 507 1...
0
2016-10-03T19:48:31Z
39,839,691
<p><code>PCA.fit()</code> tansforms the model in-place and returns <code>self</code> so that you can chain other model operations. So, after</p> <pre><code>pca_samples = pca.fit(log_data) </code></pre> <p><code>pca_samples</code> is just another reference to <code>pca</code>.</p>
0
2016-10-03T20:15:51Z
[ "python", "scikit-learn", "sklearn-pandas" ]
When plotting with Bokeh, how do you automatically cycle through a color pallette?
39,839,409
<p>I want to use a loop to load and/or modify data and plot the result within the loop using Bokeh (I am familiar with <a href="http://matplotlib.org/1.2.1/examples/api/color_cycle.html" rel="nofollow">Matplotlib's <code>axes.color_cycle</code></a>). Here is a simple example</p> <pre><code>import numpy as np from bok...
2
2016-10-03T19:56:25Z
39,840,381
<p>It is probably easiest to just get the list of colors and cycle it yourself using <a href="https://docs.python.org/3.5/library/itertools.html" rel="nofollow"><code>itertools</code></a>: </p> <pre><code>import numpy as np from bokeh.plotting import figure, output_file, show # select a palette from bokeh.palettes im...
3
2016-10-03T21:02:42Z
[ "python", "plot", "bokeh" ]
Python user input file path
39,839,450
<p>I am working on an easy project which requires user input a path for program and goes to this path Here, I Worte on OSX: </p> <pre><code>from pathlib import Path def main(): user_input_path = Path(input()) </code></pre> <p>And debug like this</p> <pre><code>&gt;&gt;&gt; /Users/akrios/Desktop/123 SyntaxError:...
0
2016-10-03T19:58:41Z
39,840,693
<p>The <code>input()</code> function reads in the input, and then tries to parse it as if it's something in Python notation. Instead, use the <code>raw_input()</code> function, it does not parse anything and returns the input as a string.</p>
0
2016-10-03T21:28:13Z
[ "python" ]
My function closest_power(base, num) failing some test cases
39,839,535
<pre><code>def closest_power(base, num): ''' base: base of the exponential, integer &gt; 1 num: number you want to be closest to, integer &gt; 0 Find the integer exponent such that base**exponent is closest to num. Note that the base**exponent may be either greater or smaller than num. In case o...
2
2016-10-03T20:04:12Z
39,840,248
<p>Your first condition is always true until while condition violated. For example if <code>exp=1</code> => <code>4**1 &lt;= 64 &lt; 4**(1+1)</code> yields to true. If <code>exp=2</code> => <code>4**2 &lt;= 64 &lt; 4**(2+1)</code> also yields to true.</p> <p>And when condition violated result is always equals to small...
4
2016-10-03T20:54:04Z
[ "python", "python-3.x" ]
My function closest_power(base, num) failing some test cases
39,839,535
<pre><code>def closest_power(base, num): ''' base: base of the exponential, integer &gt; 1 num: number you want to be closest to, integer &gt; 0 Find the integer exponent such that base**exponent is closest to num. Note that the base**exponent may be either greater or smaller than num. In case o...
2
2016-10-03T20:04:12Z
39,840,284
<p>I suppose <code>elif</code> is extra. If condition is satisfied, you should return the value.</p> <pre><code>def closest_power2(base, num): exp=1 while base**exp&lt;=num: if base**exp &lt;= num &lt;= base**(exp+1): num_low = base**exp num_high = base**(exp+1) return ...
0
2016-10-03T20:56:16Z
[ "python", "python-3.x" ]
My function closest_power(base, num) failing some test cases
39,839,535
<pre><code>def closest_power(base, num): ''' base: base of the exponential, integer &gt; 1 num: number you want to be closest to, integer &gt; 0 Find the integer exponent such that base**exponent is closest to num. Note that the base**exponent may be either greater or smaller than num. In case o...
2
2016-10-03T20:04:12Z
39,861,647
<p>this works.</p> <pre><code>def closest_power(base, num): bevaluate = True exponent = 0 vale = 0 older = 0 olders = 0 while bevaluate: vale = base ** exponent if vale &lt; num: older = num - vale exponent+=1 else: olders = vale - nu...
0
2016-10-04T20:59:53Z
[ "python", "python-3.x" ]
depth first search in an undirected, weighted graph using adjacency matrix?
39,839,695
<p>I don't want the answer, but I'm having trouble keeping track of the nodes. Meaning, say I have nodes 0, 1, 2, 3,4, 5, 6, 7, where 0 is start, and 7 is goal, I made an adjacency matrix like so: </p> <pre><code>[ [0, 3, 0, 0, 4, 0, 0, 0], [3, 0, 0, 0, 5, 0, 8, 0], [0, 0, 0, 4, 0, 5, 0, 0], [0, 0, 4, ...
0
2016-10-03T20:15:57Z
39,840,165
<p>Maintain a <code>path variable</code> to store the vertex as u encounter them. When u found <code>end</code> vertex, the path variable will have the path. </p> <p>Find the pseudo code for reference. Pardon any minor mistake in the code</p> <pre><code>DFS (vertex start, vertex end, Graph G, list path): if(...
1
2016-10-03T20:47:53Z
[ "python", "algorithm", "search", "graph", "tree" ]
IPython: Does "%matplotlib inline" required before importing matplotlib?
39,839,721
<p>I am using IPython. Got confused that the codes can't execute if I don't add</p> <pre><code>%matplotlib </code></pre> <p>before </p> <pre><code>import matplotlib.pyplot as plt </code></pre> <p>Could someone enlighten me by explaining why the magic function call in IPython is needed for matplotlib usage?</p>
0
2016-10-03T20:17:29Z
39,839,811
<p>I believe it's needed because normally matplotlib opens additional windows for graphs using a default toolkit. The %inline lets you load graphs in the IPython notebook, instead of using an external toolkit.</p>
3
2016-10-03T20:23:40Z
[ "python", "matplotlib", "ipython" ]
How to sort a dict by key of versions
39,839,726
<p>Input:</p> <pre><code>foo = { 'testing-1.30.5': ['The', 'quick'], 'testing-1.30.12': ['fox', 'jumped', 'over'], 'testing-1.30.13': ['the'], 'testing-1.30.4': ['lazy', 'dog'], 'testing-1.30.1': ['brown'], 'testing-1.30.3': ['the'], 'testing-1.30.6': ['brown'], 'testing-1.30.2': ['fox'...
0
2016-10-03T20:17:48Z
39,839,831
<p>Got it! nevermind, found LooseVersion / strict versions</p> <pre><code>from distutils.version import LooseVersion from collections import OrderedDict orderedKeys = sorted(foo, key=LooseVersion) odict = OrderedDict((key, foo[key]) for key in orderedKeys) for item in odict: print '{}: {}'.format(item, odict[i...
0
2016-10-03T20:24:58Z
[ "python", "sorting", "dictionary", "key", "versions" ]
How to sort a dict by key of versions
39,839,726
<p>Input:</p> <pre><code>foo = { 'testing-1.30.5': ['The', 'quick'], 'testing-1.30.12': ['fox', 'jumped', 'over'], 'testing-1.30.13': ['the'], 'testing-1.30.4': ['lazy', 'dog'], 'testing-1.30.1': ['brown'], 'testing-1.30.3': ['the'], 'testing-1.30.6': ['brown'], 'testing-1.30.2': ['fox'...
0
2016-10-03T20:17:48Z
39,839,834
<p>Sort <code>foo</code> with an appropriate sort key. You'd have to chop off the "testing-" part, then split the rest on the periods, then turn each of those into an integer. Also, the result will be a list of keys, so look up those items in the original dictionary.</p> <pre><code>&gt;&gt;&gt; bar = sorted(foo, key=l...
1
2016-10-03T20:25:23Z
[ "python", "sorting", "dictionary", "key", "versions" ]
How to sort a dict by key of versions
39,839,726
<p>Input:</p> <pre><code>foo = { 'testing-1.30.5': ['The', 'quick'], 'testing-1.30.12': ['fox', 'jumped', 'over'], 'testing-1.30.13': ['the'], 'testing-1.30.4': ['lazy', 'dog'], 'testing-1.30.1': ['brown'], 'testing-1.30.3': ['the'], 'testing-1.30.6': ['brown'], 'testing-1.30.2': ['fox'...
0
2016-10-03T20:17:48Z
39,839,839
<p>In the sort function, split the key on <code>'.'</code> and cast the last item in the <em>splitted</em> list to integer:</p> <pre><code>for k in sorted(foo, key=lambda x: int(x.rsplit('.')[-1])): print('{}: {}'.format(k, foo[k])) </code></pre> <hr> <p>Output:</p> <pre><code>testing-1.30.0: ['The', 'quick'] t...
0
2016-10-03T20:25:35Z
[ "python", "sorting", "dictionary", "key", "versions" ]
Pandas: Summing arrays as as an aggregation with multiple groupby columns
39,839,748
<p>I'm using Python 3.5.1 and Pandas 0.18.0.</p> <p>Let's say I have a Pandas dataframe with multiple columns. The dataframe has one column that includes a numpy array. Here is an example:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; import numpy as np &gt;&gt;&...
1
2016-10-03T20:19:15Z
39,839,979
<p><code>pd.concat</code> separate groupbys is a workaround</p> <pre><code>g = df.groupby(['A', 'B']) pd.concat([g.C.apply(np.sum), g.D.sum()], axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/HzryQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/HzryQ.png" alt="enter image description here"></a></p>...
0
2016-10-03T20:36:32Z
[ "python", "pandas", "numpy" ]
How to display a terminal-like environment, that shows the output of Python scripts, within a web browser?
39,839,795
<p>I've recently finished my courses in HTML and CSS, and am now sailing into Javascript. I have a decent background in Python at the moment, and would like to utilize my experience for web programming. </p> <p>My question being, how could I go about creating a terminal environment that could display my python code w...
0
2016-10-03T20:22:49Z
39,839,976
<p>Leaving aside the security problems, you can do this in several ways.</p> <p>You can pursue a "stateless, sort of" approach, which is simpler, by displaying a fake user prompt in CSS and supplying a textarea or input area that manages to emulate a command line. When the user hits ENTER you would get the input, send...
0
2016-10-03T20:36:21Z
[ "python", "html", "web" ]
Compose a function that sorts a list known to have exactly three values efficiently (Sage(python))
39,839,823
<p>First of all I am not allow to use any of the internal command that sort the list not any of the other sorted method such as Selection, buble. Compose a function that sorts a list known to have exactly two values this is what I have done : </p> <pre><code>def sort_Two_values(list): Sorted_List=[] Sorted_List.appen...
0
2016-10-03T20:24:16Z
39,840,015
<p>All you needs is to push <code>0 to beginning, 2 to last</code> of list and <code>1 will remain wherever it is</code>. By the end of the loop, you will have a sorted list. </p>
0
2016-10-03T20:39:09Z
[ "python", "sage" ]
Interger being decremented too much in for loop in Python
39,839,832
<p>This is a school project and I'm having slight trouble with one piece of the code. This is a background: I'm making a hangman game, and it works fine, but I'm trying to make the loop decrement an integer only if the if statement above it is false. This, seems to be a problem as it decrements the integer way too much...
0
2016-10-03T20:24:58Z
39,840,144
<p>Without seeing more of your code I would think that you are going to need a separate block that defines when the player input is incorrect instead of trying to use the same block that defines when the player input is correct.</p> <p>Your current block is iterating once for every letter in <code>randomWord</code> w...
0
2016-10-03T20:46:57Z
[ "python", "for-loop", "while-loop" ]
AttributeError: '<class 'praw.objects.MoreComments'>' has no attribute 'score'
39,839,968
<p>Not sure how to fix this? Please guide:</p> <pre><code>import praw r = praw.Reddit(user_agent="getting top posts from a subredit and its submissions", site_name='lamiastella') subreddit = r.get_subreddit('iama') top_year_subreddit = subreddit.get_top_from_year submissions = top_year_subreddit(limit=50) for submiss...
0
2016-10-03T20:36:05Z
39,841,375
<p>Here's the correct answer:</p> <pre><code>import praw subreddit_name = 'nostalgia' num_submissions = 2 num_top_comments = 10 num_comments_per_submission = 500 r = praw.Reddit(user_agent="getting top posts from a subredit and its submissions", site_name='lamiastella') subreddit = r.get_subreddit(subreddit_name) top...
0
2016-10-03T22:27:07Z
[ "python", "reddit", "praw", "reddit-api" ]
SSH into VM and run "git pull" using Paramiko - Python
39,839,975
<p>I'm trying to SSH into my VM and did perform a <code>git pull</code> </p> <ul> <li>the SSH seems to be working fine </li> <li>the git pull seem to be executed</li> <li>but when I provide password, it doesn't seem to take it </li> <li>Am I missing something ? </li> </ul> <hr> <p>I have </p> <pre><code>import para...
0
2016-10-03T20:36:20Z
39,840,140
<p>It looks like your SSH Rsa Key pair has been setup up with a pass phrase for root on 111.111.111.111. You can recreate the ssh rsa key with:</p> <pre><code>ssh-keygen -t rsa </code></pre> <p>and just leave pass phrase blank.</p>
0
2016-10-03T20:46:49Z
[ "python", "git", "ssh", "paramiko" ]
Finding first event in one table that occurred after event in a second table, per row
39,840,012
<p>I have a pandas DataFrame that looks like this:</p> <pre><code>email signup_date a@a.com 7/21/16 b@b.com 6/6/16 d@d.com 5/5/16 b@b.com 4/4/16 </code></pre> <p>I have a second pandas DataFrame with related events, when a signup actually got followed through on, that looks like this:</p> <pre><code>e...
0
2016-10-03T20:38:50Z
39,845,781
<p><strong><em>setup</em></strong></p> <pre><code>from StringIO import StringIO import pandas as pd txt1 = """email signup_date a@a.com 7/21/16 b@b.com 6/6/16 d@d.com 5/5/16 b@b.com 4/4/16""" df1 = pd.read_csv(StringIO(txt1), parse_dates=[1], delim_whitespace=True) txt2 = """email call_date a@...
1
2016-10-04T06:44:29Z
[ "python", "pandas" ]
Finding first event in one table that occurred after event in a second table, per row
39,840,012
<p>I have a pandas DataFrame that looks like this:</p> <pre><code>email signup_date a@a.com 7/21/16 b@b.com 6/6/16 d@d.com 5/5/16 b@b.com 4/4/16 </code></pre> <p>I have a second pandas DataFrame with related events, when a signup actually got followed through on, that looks like this:</p> <pre><code>e...
0
2016-10-03T20:38:50Z
39,846,934
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>sort_values</code></a> and aggregate <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollow"><code>first</code></a...
1
2016-10-04T07:50:11Z
[ "python", "pandas" ]
Distance between point and a line (from two points)
39,840,030
<p>I'm using Python+Numpy (can maybe also use Scipy) and have three 2D points (P1, P2, P3); I am trying to get the distance from P3 perpendicular to a line drawn between P1 and P2. Call P1 (x1,y1), P2 (x2,y2) and P3 (x3,y3)</p> <p>In vector notation this would be pretty easy, but I'm fairly new to python/numpy and can...
-2
2016-10-03T20:40:11Z
39,840,218
<p>Try using the <em>norm</em> function from <code>numpy.linalg</code></p> <pre><code>d = norm(np.cross(p2-p1, p1-p3))/norm(p2-p1) </code></pre>
0
2016-10-03T20:51:44Z
[ "python", "numpy", "vector", "scipy", "point" ]
Python code crashes with "cannot connect to X server" when detaching ssh+tmux session
39,840,184
<p>I run Python code on a remote machine (which I ssh into) and then use Tmux. The code runs fine UNTIL I disconnect from the remote machine. The whole point of my connecting via Tmux is so that the code continues to run even when I'm not connected to the remote machine. When I reconnect later, I have the error message...
0
2016-10-03T20:49:08Z
39,840,271
<pre><code>cannot connect to X server localhost:11.0 </code></pre> <p>...means that your code is trying (and failing) to connect to an X server -- a GUI environment -- presumably being forwarded over your SSH session. <code>tmux</code> provides session continuity for terminal applications; it can't emulate an X server...
1
2016-10-03T20:55:07Z
[ "python", "ssh", "tmux" ]
Azure deployment not installing Python packages listed in requirements.txt
39,840,209
<p>This is my first experience deploying a Flask web app to Azure. I followed this <a href="https://azure.microsoft.com/en-us/documentation/articles/web-sites-python-create-deploy-flask-app/" rel="nofollow">tutorial</a>. </p> <p>The default demo app they have works fine for me. </p> <p>Afterwards, I pushed my Flask ...
0
2016-10-03T20:50:58Z
39,845,489
<p>As Azure Web Apps will run a <code>deploy.cmd</code> script as the deployment task to control which commands or tasks will be run during the deployment. </p> <p>You can use the command of Azure-CLI <code>azure site deploymentscript --python</code> to get the python applications' deployment task script.</p> <p>And ...
0
2016-10-04T06:26:34Z
[ "python", "azure", "deployment", "flask", "requirements.txt" ]
mesos configuration error in centos7
39,840,267
<p>I am trying to install mesos 1.0.1 on centos 7 but i am running into _FORTIFY_SOURCE error. Has anyone found a fix/workaround? It seems there is a patch but i don't know where to get it from. I'd appreciate any help with this. Thanks! <br> </p> <pre><code>checking whether we can build usable Python eggs... In file...
0
2016-10-03T20:54:54Z
40,096,918
<p>Adarsh, seems like your error comes from building the Python eggs. Could you paste the full error log, so that we can better help you to triage your issue. BTW, installing Mesos is straight forward. You are not expected to handle issues with <code>_FORTIFY_SOURCE</code> or <code>optimization</code>. Please follow th...
-1
2016-10-17T22:55:34Z
[ "python", "centos7", "mesos" ]
Using Python to parse pdf and extract Author and Book name
39,840,333
<p>I have a Mailing Reference List in a form a pdf. The mailing list has a very general format i.e Author Name followed by the Name of the book. Consider the following examples:</p> <p><strong>American Reading List</strong></p> <p><strong>Democratic Theory</strong></p> <p>• Dahl, Preface to Democratic Theory</p> ...
0
2016-10-03T20:59:14Z
39,840,535
<p>Let's see what's going wrong here. I'm making some guesses, but hopefully they are the relevant ones.</p> <ol> <li>Your <code>convert_pdf_to_text()</code> function returns a single long string containing all the text of the PDF.</li> <li>You split the text on <code>", "</code> which results in a list of strings.</l...
2
2016-10-03T21:16:04Z
[ "python", "pdf", "split" ]
ConnectionRefusedError: [Errno 111] Connection refused
39,840,357
<p>I was trying to use <code>ftp</code> and I am getting the following error:</p> <pre><code>&gt;&gt;&gt; ftp = ftplib.FTP('192.168.248.108') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python3.5/ftplib.py", line 118, in __init__ self.connect(host) File "...
0
2016-10-03T21:01:04Z
39,840,788
<p>First of all check this ip to see if <code>ftp</code> service is available, and if it is check the <code>port</code> that it is listening on, cause it maybe (rare but possible) is configured to listen on a different port than the standard one - <strong>21</strong> . Also maybe the connection is blocked by a <strong>...
0
2016-10-03T21:35:11Z
[ "python", "ftp" ]
How to convert one column's all values to separate column name in DataFrame of Pandas
39,840,377
<p>Sample data are as follows:</p> <pre><code>df = pd.DataFrame([(2011, 'a', 1.3), (2012, 'a', 1.4), (2013, 'a', 1.6), (2011, 'b', 0.7), (2012, 'b', 0.9), (2013, 'b', 1.2),], columns=['year', 'district', 'price']) df.set_index(['year'], inplace=True) df.head(n=10) </code></pre> <p>which could produce data like:</p> ...
0
2016-10-03T21:02:17Z
39,840,429
<p>use pivot</p> <pre><code>In[122]: df.reset_index().pivot('year','district','price') Out[122]: district a b year 2011 1.3 0.7 2012 1.4 0.9 2013 1.6 1.2 </code></pre>
0
2016-10-03T21:06:49Z
[ "python", "pandas", "dataframe", "pivot" ]
Can I pass a file to Popen and still have it run asynchronously
39,840,484
<p>I have a Django based server and I'm calling a script which does a bunch of work. This needs to be asynchronous so I'm using Popen. However for debugging I want to redirect stdout and stderr from PIPE to a file. Will this affect the asynchronous performance?</p> <p>How should I make sure the file opens and closes p...
0
2016-10-03T21:12:24Z
39,840,622
<p><code>Popen</code> runs asynchronously by default.</p> <p>The <code>Popen</code> object can be stored and queried later.</p> <pre><code>p = subproccess.Popen(executable) # continue with other work p.poll() # returns None if p is still running, returncode otherwise p.terminate() # closes the process forcefully p...
1
2016-10-03T21:22:49Z
[ "python", "asynchronous", "subprocess" ]
Can I pass a file to Popen and still have it run asynchronously
39,840,484
<p>I have a Django based server and I'm calling a script which does a bunch of work. This needs to be asynchronous so I'm using Popen. However for debugging I want to redirect stdout and stderr from PIPE to a file. Will this affect the asynchronous performance?</p> <p>How should I make sure the file opens and closes p...
0
2016-10-03T21:12:24Z
39,840,658
<p>It depends on how asynchronous your program needs to be. Writes to stdout go to the operating system's file cache which is normally fast but may wait from time to time as data is flushed to the disk. Normally that's not a problem.</p> <p>Since stdout is not a console, it will do buffered writes and that can be a pr...
1
2016-10-03T21:25:38Z
[ "python", "asynchronous", "subprocess" ]
ValueError: shapes (2,2) and (4,6) not aligned: 2 (dim 1) != 4 (dim 0)
39,840,534
<p>Complaining about this line: </p> <pre><code>log_centers = pca.inverse_transform(centers) </code></pre> <p>Code:</p> <pre><code># TODO: Apply your clustering algorithm of choice to the reduced data clusterer = KMeans(n_clusters=2, random_state=0).fit(reduced_data) # TODO: Predict the cluster for each data point...
0
2016-10-03T21:16:00Z
39,847,481
<p>The problem is that <code>pca.inverse_transform()</code>should not take <code>clusters</code>as argument.</p> <p>Indeed, if you look at the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA.inverse_transform" rel="nofollow">documentation</a>, it shoul...
0
2016-10-04T08:22:44Z
[ "python", "scikit-learn", "pca", "sklearn-pandas" ]
Must produce aggregated value. I swear that I am
39,840,546
<p>consider the <code>pd.Series</code> <code>s</code></p> <pre><code>a = np.arange(4) mux = pd.MultiIndex.from_product([list('ab'), list('xy')]) s = pd.Series([a] * 4, mux) print(s) a x [0, 1, 2, 3] y [0, 1, 2, 3] b x [0, 1, 2, 3] y [0, 1, 2, 3] dtype: object </code></pre> <hr> <p><strong><em>pr...
0
2016-10-03T21:16:29Z
39,842,473
<p><a href="http://stackoverflow.com/questions/16975318/pandas-aggregate-when-column-contains-numpy-arrays">from this well explained answer</a> you could transform your ndarray to list because pandas seems to be checking if the output is a ndarray and this is why you are getting this error raised :</p> <pre><code>s.gr...
1
2016-10-04T00:30:28Z
[ "python", "pandas" ]
Tweepy Get List of Favorites for a Specific User
39,840,571
<p>I am attempting to get a list of favorited tweets made by a specific user. Their twitter account indicates that they have favorited nearly 20k tweets but the list of favorites being returned through the API is only ~2,300 favorited tweets. Below is a sample of my python code:</p> <pre><code>api = tweepy.API(auth) t...
0
2016-10-03T21:18:56Z
39,840,991
<p>From a bit more digging on the twitter API, it looks like there is a cap on the number of tweets we can query. See <a href="https://twittercommunity.com/t/tweet-index-limits/49653" rel="nofollow">this question</a> from the twitter developer forum.</p>
0
2016-10-03T21:52:48Z
[ "python", "api", "twitter", "tweepy" ]
SyntaxError: invalid syntax with Chicken coop door script
39,840,615
<p>I am new to python, I have been trying to get a piece of code working to control a chicken coop door. The github link is <a href="https://github.com/ryanrdetzel/CoopControl" rel="nofollow">https://github.com/ryanrdetzel/CoopControl</a></p> <p>The problem I have is that if I run server.py it does not get the MAILGUN...
-1
2016-10-03T21:22:19Z
39,840,741
<p>You are mixing up shell script syntax and Python syntax. Your problem is not at all related to Python.</p> <p>To set environment variables for single invocation of binary, correct form is:</p> <pre class="lang-sh prettyprint-override"><code>ENV1=VAL1 ENV2=VAL2 /path/to/bin some args </code></pre> <p>So in your ca...
1
2016-10-03T21:31:44Z
[ "python", "syntax-error", "sh" ]
Python - Need to extract the first and last letter from a word string
39,840,625
<p>I've been stuck with this for a while. basically the <code>get_text_value(text)</code> code below is passed a string of words and it extracts the first and last letter of each word, matches it up with <code>letter_values</code> and gives the final value based on the sum of the numbers the first and last words matche...
2
2016-10-03T21:23:00Z
39,840,755
<p>First of all: store the values in a dictionary, that's way less work.</p> <p>Then, just iterate over the words in the text and add the values:</p> <pre><code>def get_text_value(text): lv = {'a': 1, 'b': 4, 'c': 2, 'd': 3, 'e': 1, 'f': 4, 'g': 3, 'h': 4, 'i': 1, 'j': 7, 'k': 7, 'l': 4, 'm': 6, 'n': 6, 'o': 1, '...
0
2016-10-03T21:32:49Z
[ "python", "string", "list", "python-3.x" ]
Python - Need to extract the first and last letter from a word string
39,840,625
<p>I've been stuck with this for a while. basically the <code>get_text_value(text)</code> code below is passed a string of words and it extracts the first and last letter of each word, matches it up with <code>letter_values</code> and gives the final value based on the sum of the numbers the first and last words matche...
2
2016-10-03T21:23:00Z
39,844,035
<p>Looks like you're just getting started with Python. Welcome! Couple things that might be worth getting more familiar with.</p> <ol> <li>Dictionaries</li> </ol> <p>Dictionaries are good for storing a key value pair. In your case, a dictionary would work really well as you have a letter (your key) and a numerical va...
0
2016-10-04T04:10:19Z
[ "python", "string", "list", "python-3.x" ]
Python - Need to extract the first and last letter from a word string
39,840,625
<p>I've been stuck with this for a while. basically the <code>get_text_value(text)</code> code below is passed a string of words and it extracts the first and last letter of each word, matches it up with <code>letter_values</code> and gives the final value based on the sum of the numbers the first and last words matche...
2
2016-10-03T21:23:00Z
39,844,229
<p>do like this:</p> <pre><code>def get_text_value2(text): letters = [chr(i) for i in range(ord('a'), ord('z')+1)] letter_values = [1, 4, 2, 3, 1, 4, 3, 4, 1, 7, 7, 4, 6, 6, 1, 3, 9, 2, 2, 2, 1, 8, 5, 9, 9, 9] alpha_value_dict = dict(zip(letters, letter_values)) formatted_text = text.lower() return...
0
2016-10-04T04:35:34Z
[ "python", "string", "list", "python-3.x" ]
Launch Python script in new terminal
39,840,632
<p>I want to launch a python script in a new macOS terminal window from another script. I'm currently using this code:</p> <pre><code>subprocess.call(['open', '-a', 'Terminal.app', '/usr/bin/python']) </code></pre> <p>which launches a python prompt in a new terminal window. But when I try to run a python script with ...
0
2016-10-03T21:23:22Z
39,840,688
<p>Don't use the <code>open -a terminal.app</code>, just use the python executable</p> <pre><code>subprocess.call(['/usr/bin/python', 'test.py']) </code></pre>
0
2016-10-03T21:27:52Z
[ "python", "osx", "python-2.7", "subprocess", "terminal.app" ]
Parsing pyparsing group of mixed character words
39,840,633
<p>I'm trying to parse data fields from a Wikipedia infobox using pyparsing. To start with, the following code works:</p> <pre><code>from pyparsing import * test_line = """{{Infobox company | name = Exxon Mobil Corp | num_employees_year = 2015 }}""" data_group = Group( Suppress("|") + OneOrMo...
1
2016-10-03T21:23:37Z
39,841,822
<p>Just a couple of things. Most significantly, pyparsing does not do the same kind of backtracking the way regex does. That is, something like this won't work:</p> <pre><code>data = '{' + OneOrMore(Word(printables))("data") + '}' print(data.parseString('{ this is some data }')) </code></pre> <p>Why? Because the term...
1
2016-10-03T23:12:38Z
[ "python", "pyparsing" ]
Update mayavi plot in loop
39,840,638
<p>What I want to do is to update a mayavi plot in a loop. I want the updating of the plot to be done at a time specified by me (unlike, e.g., the animation decorator).</p> <p>So an example piece of code I would like to get running is:</p> <pre><code>import time import numpy as np from mayavi import mlab V = np.rand...
2
2016-10-03T21:24:05Z
39,982,817
<p>I thin Mayavi uses <code>generators</code> to animate data. This is working for me:</p> <pre><code>import time import numpy as np from mayavi import mlab f = mlab.figure() V = np.random.randn(20, 20, 20) s = mlab.contour3d(V, contours=[0]) @mlab.animate(delay=10) def anim(): i = 0 while i &lt; 5: ...
1
2016-10-11T17:07:30Z
[ "python", "interactive", "mayavi" ]
Update mayavi plot in loop
39,840,638
<p>What I want to do is to update a mayavi plot in a loop. I want the updating of the plot to be done at a time specified by me (unlike, e.g., the animation decorator).</p> <p>So an example piece of code I would like to get running is:</p> <pre><code>import time import numpy as np from mayavi import mlab V = np.rand...
2
2016-10-03T21:24:05Z
40,025,839
<p>If you use the <code>wx</code> backend, you can call <code>wx.Yield()</code> periodically if you want to interact with your data during some long-running function. In the following example, <code>wx.Yield()</code> is called for every iteration of some "long running" function, <code>animate_sleep</code>. In this case...
1
2016-10-13T16:02:07Z
[ "python", "interactive", "mayavi" ]
Add threads to a Sudoku checker
39,840,676
<p>I have just created a simple function in Python which checks whether or not a Sudoku board (input is given as a list) is valid or not. The way I did it is pretty straight forward:</p> <ul> <li><p>check if the sudoku board is 9x9</p></li> <li><p>check that each number appears only once per row</p></li> <li>check tha...
0
2016-10-03T21:26:55Z
39,843,103
<p>So to give some general pointers on how to achieve this, without taking away any challenge. Lets start by import Threading:</p> <pre><code>import threading </code></pre> <p>Which will let us use thread objects! Also, in order to know if the Sudoku grid will be valid after the fact, we need a variable to store the ...
2
2016-10-04T02:00:52Z
[ "python", "multithreading", "python-3.x" ]
AttributeError: '<class 'praw.objects.MoreComments'>' has no attribute 'body'
39,840,686
<p>How can I fix this error?</p> <pre><code>import praw subreddit_name = 'relationships' num_submissions = 30 r = praw.Reddit(user_agent="getting top posts from a subredit and its submissions", site_name='lamiastella') subreddit = r.get_subreddit(subreddit_name) top_submissions = subreddit.get_top_from_year(limit = n...
0
2016-10-03T21:27:48Z
39,841,039
<p>stupid mistake but should have had <code>submission.replace_more_comments(limit=None, threshold=0)</code> above <code>all_comments = praw.helpers.flatten_tree(submission.comments)</code> line:</p> <pre><code>import praw subreddit_name = 'nostalgia' num_submissions = 2 r = praw.Reddit(user_agent="getting top po...
0
2016-10-03T21:57:33Z
[ "python", "attributeerror", "reddit", "praw", "reddit-api" ]
How to detect if script ran from Django or command prompt?
39,840,736
<p>I have a Python script that pauses for user input (using <code>raw_input</code>, recently I created a Django web UI for this script. Now when I execute the script via Django is pauses as it's waiting for input in the backend. </p> <p>How can I determine if the script was ran from Django or terminal/cmd/etc? I don't...
1
2016-10-03T21:31:23Z
39,840,766
<p>Just ask!</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; import sys &gt;&gt;&gt; os.isatty(sys.stdin.fileno()) True </code></pre> <p>if true, you are attached to a console.</p>
1
2016-10-03T21:33:40Z
[ "python", "django" ]
How to detect if script ran from Django or command prompt?
39,840,736
<p>I have a Python script that pauses for user input (using <code>raw_input</code>, recently I created a Django web UI for this script. Now when I execute the script via Django is pauses as it's waiting for input in the backend. </p> <p>How can I determine if the script was ran from Django or terminal/cmd/etc? I don't...
1
2016-10-03T21:31:23Z
39,844,217
<p>Why not use <code>__main__</code>: <a href="https://docs.python.org/3/library/__main__.html" rel="nofollow">https://docs.python.org/3/library/<strong>main</strong>.html</a></p> <pre><code>if __name__ == '__main__': print ('running as a script') else: print ('running as a web app') </code></pre> <p>Works on...
1
2016-10-04T04:34:07Z
[ "python", "django" ]
How to detect if script ran from Django or command prompt?
39,840,736
<p>I have a Python script that pauses for user input (using <code>raw_input</code>, recently I created a Django web UI for this script. Now when I execute the script via Django is pauses as it's waiting for input in the backend. </p> <p>How can I determine if the script was ran from Django or terminal/cmd/etc? I don't...
1
2016-10-03T21:31:23Z
39,844,257
<p>Explicit is better than implicit. Wrap your interactivity in a function that's called only if the <code>__name__ == "__main__"</code> part was executed. From the django parts, just use it as a library. Most ways of doing these kinds of checks are semi-magical and hence flaky.</p>
0
2016-10-04T04:38:54Z
[ "python", "django" ]
Call module.Functionname from user input
39,840,807
<p>I'm trying to call module(.)functionname from a image lirary upon user input. For instance a user types in "GaussianBlurr"</p> <p>I want to be able to replace (<em>ImagerFilter.user_input</em>) and call that filter.(Line 3)</p> <pre><code>def ImageFilterUsingPil(): im = Image.open('hotdog.jpg') im.filter(I...
0
2016-10-03T21:36:58Z
39,840,876
<p>You are looking to use <a href="https://docs.python.org/3/library/functions.html#getattr" rel="nofollow">getattr</a> here. </p> <pre><code>call = getattr(ImageFilter, user_input) call() </code></pre> <p>More explicit to your code, you can do this: </p> <pre><code>im.filter(getattr(ImageFilter, user_input)()) </c...
0
2016-10-03T21:42:36Z
[ "python", "function" ]
Exiting a tkinter app with Ctrl-C and catching SIGINT
39,840,815
<p>Ctrl-C/SIGTERM/SIGINT seem to be ignored by tkinter. Normally it can be <a href="http://stackoverflow.com/questions/1112343/how-do-i-capture-sigint-in-python">captured again with a callback</a>. This doesn't seem to be working, so I thought I'd run tkinter <a href="http://stackoverflow.com/a/1835036/1888983">in anot...
0
2016-10-03T21:37:43Z
39,843,743
<p>Since your tkinter app is running in another thread, you do not need to set up the signal handler in the main thread and just use the following code block after the <code>app.start()</code> statement:</p> <pre><code>import time while app.is_alive(): try: time.sleep(0.5) except KeyboardInterrupt: ...
1
2016-10-04T03:34:54Z
[ "python", "multithreading", "tkinter", "signals" ]
python generate a infinite list with certain condition
39,840,845
<p>I know there is generator yield in python like:</p> <pre><code>def f(n): x = n while True: yield x x = x+1 </code></pre> <p>So I try to convert this haskell function into python without using iterate: <a href="http://stackoverflow.com/questions/39809592/haskell-infinite-recursion-in-list-c...
2
2016-10-03T21:39:37Z
39,840,885
<p>I dont see where you're getting the <code>p</code> from. As far as I can see you can almost literally translate it from Haskell:</p> <pre><code>def orbit(x, y): u, v = 0, 0 while True: u, v = u**2 − v**2 + x, 2*u*v + y yield u, v </code></pre> <p>In their example, calling the function as ...
3
2016-10-03T21:43:16Z
[ "python", "list", "python-3.x", "yield" ]
Using a global static variable server wide in Django
39,840,874
<p>I have a very long list of objects that I would like to only load from the db once to memory (Meaning not for each session) this list WILL change it's values and grow over time by user inputs, The reason I need it in memory is because I am doing some complex searches on it and want to give a quick answer back.</p> ...
1
2016-10-03T21:42:24Z
39,844,237
<p>The answer is that this is bad idea, you are opening a pandora's box specially since you need write access as well. However all is not lost. You can quite easily use <a href="https://redis-py.readthedocs.io/en/latest/" rel="nofollow">redis</a> for this task.</p> <p>Redis is a peristent data store but at the same ti...
0
2016-10-04T04:36:27Z
[ "python", "django" ]
Cannot access sub-keys in OrderedDict
39,840,875
<p>I'm trying to define my ordinary dictionary as an OrderedDict, but I can't seem to access keys are the inner level.</p> <pre><code>my_dict = \ { 'key1': { 'subkey1':value1, 'subkey2':value2 } } my_ordered_dict = OrderedDict\ ([( 'key1', ( ('subkey1',value1), ('su...
0
2016-10-03T21:42:24Z
39,841,285
<p>The dictionary with 'subkey1' should also be defined as a OrderedDict ,if thats what you want. So it should be something like this</p> <pre><code>import collections my_ordered_dict = collections.OrderedDict() sub_dict=collections.OrderedDict() sub_dict['subkey1']=1 sub_dict['subkey2']=2 my_ordered_dict['key1']=sub_...
1
2016-10-03T22:18:35Z
[ "python", "ordereddictionary" ]
Cannot access sub-keys in OrderedDict
39,840,875
<p>I'm trying to define my ordinary dictionary as an OrderedDict, but I can't seem to access keys are the inner level.</p> <pre><code>my_dict = \ { 'key1': { 'subkey1':value1, 'subkey2':value2 } } my_ordered_dict = OrderedDict\ ([( 'key1', ( ('subkey1',value1), ('su...
0
2016-10-03T21:42:24Z
39,841,839
<p>If you want the inner level to also be an <code>OrderedDict</code> you need to explicitly define it as one. Since argument order matters when constructing <code>OrderedDict</code>s, in order to preserve it, you need to pass the keys and values as a sequence of <code>key, value</code> pairs as shown in the <a href="h...
0
2016-10-03T23:14:01Z
[ "python", "ordereddictionary" ]
How does one control whitespace around a figure in matplotlib?(plt.tight_layout does not work)
39,840,882
<p>I have a matplotlib figure with 3 sub-plots. The consensus from stackexchange seems to be to use the plt.tight_layout in order to get rid of the whitespace around the figure. This does not solve the problem in my case.</p> <p>My code is as follows:</p> <pre><code>import numpy as np import os import pandas as pd im...
0
2016-10-03T21:43:07Z
39,840,932
<p>The <code>tight_layout</code> option places the images closer to the borders. However, in your case, there is nothing to fill this empty space with, so it doesn't work.</p> <p>If you want a narrower figure, you should change the horizontal dimension, e.g.:</p> <pre><code>plt.figure(..., tight_layout=True, figsize=...
0
2016-10-03T21:48:59Z
[ "python", "numpy", "matplotlib", "plot" ]
How to Use Lagged Time-Sereis Variables in a Python Pandas Regression Model?
39,840,890
<p>I'm creating time-series econometric regression models. The data is stored in a Pandas data frame.</p> <p><strong>How can I do lagged time-series econometric analysis using Python</strong>? I have used Eviews in the past (which is a standalone econometric program i.e. not a Python package). To estimate an ols equa...
0
2016-10-03T21:44:16Z
39,840,944
<p>pandas allows you to shift your data without moving the index such has</p> <pre><code>df.shift(-1) </code></pre> <p>will create a 1 index lag behing</p> <p>or</p> <pre><code>df.shift(1) </code></pre> <p>will create a forward lag of 1 index</p> <p>so if you have a daily time series, you could use df.shift(1) to...
0
2016-10-03T21:49:54Z
[ "python", "pandas", "time-series", "regression" ]
How to replace all spaces by underscores and remove all the parentheses without using replace() function?
39,840,897
<p>Here is what I did. I know this is definitely wrong. I'd like to know how to make this one work? Thx!</p> <pre><code>import re def demicrosoft (fn): """Clean up a file name. Remove all parentheses and replace all spaces by underscores. Params: fn (string): Returns: (string) clean version of fn """ fn = re.sub(...
0
2016-10-03T21:45:03Z
39,840,972
<p>You can use <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>join</code></a> combined with a generator that iterates over the characters in your string while handling the logic for filtering out parentheses and replacing spaces with underscores:</p> <pre><code>PARENS = {'(', '...
1
2016-10-03T21:51:42Z
[ "python", "replace", "removeall" ]
How to replace all spaces by underscores and remove all the parentheses without using replace() function?
39,840,897
<p>Here is what I did. I know this is definitely wrong. I'd like to know how to make this one work? Thx!</p> <pre><code>import re def demicrosoft (fn): """Clean up a file name. Remove all parentheses and replace all spaces by underscores. Params: fn (string): Returns: (string) clean version of fn """ fn = re.sub(...
0
2016-10-03T21:45:03Z
39,841,009
<pre><code>import re def demicrosoft (fn): return '_'.join((''.join(re.split(r'[()]', fn)).split())) </code></pre>
1
2016-10-03T21:54:29Z
[ "python", "replace", "removeall" ]
How to replace all spaces by underscores and remove all the parentheses without using replace() function?
39,840,897
<p>Here is what I did. I know this is definitely wrong. I'd like to know how to make this one work? Thx!</p> <pre><code>import re def demicrosoft (fn): """Clean up a file name. Remove all parentheses and replace all spaces by underscores. Params: fn (string): Returns: (string) clean version of fn """ fn = re.sub(...
0
2016-10-03T21:45:03Z
39,841,086
<p>From Zen of Python: Readability counts!</p> <pre><code>def demicrosoft (fn): dest = "" for char in fn: if char == ' ': dest += '_' elif char not in '()': dest += char return dest </code></pre>
0
2016-10-03T22:01:11Z
[ "python", "replace", "removeall" ]
How to replace all spaces by underscores and remove all the parentheses without using replace() function?
39,840,897
<p>Here is what I did. I know this is definitely wrong. I'd like to know how to make this one work? Thx!</p> <pre><code>import re def demicrosoft (fn): """Clean up a file name. Remove all parentheses and replace all spaces by underscores. Params: fn (string): Returns: (string) clean version of fn """ fn = re.sub(...
0
2016-10-03T21:45:03Z
39,841,125
<pre><code>newString = re.sub("([\s\(\)])",lambda m:"_" if b.group(0) not in "()" else "",targetString) </code></pre> <p>im guessing its for a performance reasons and they want <code>O(N)</code> the generator expression should work ... here is an <code>re</code> solution</p>
0
2016-10-03T22:04:04Z
[ "python", "replace", "removeall" ]
Add variable of same index and add to list
39,840,995
<p>So I want to add a variable of the same index of another list and add that variable to a total. In this case I am trying to make the points be equal to the letters in a game of scrabble.</p> <p><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', ...
-3
2016-10-03T21:53:04Z
39,841,139
<p>Is this what you want?</p> <pre><code>wordlist = ['why', 'are', 'you', 'doing', 'this'] letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, ...
0
2016-10-03T22:05:28Z
[ "python", "indexing" ]
Add variable of same index and add to list
39,840,995
<p>So I want to add a variable of the same index of another list and add that variable to a total. In this case I am trying to make the points be equal to the letters in a game of scrabble.</p> <p><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', ...
-3
2016-10-03T21:53:04Z
39,841,521
<p>Below is the simplified version of your code:</p> <pre><code>&gt;&gt;&gt; letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] &gt;&gt;&gt; point_values = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8,...
2
2016-10-03T22:40:04Z
[ "python", "indexing" ]
Escaping with backslash or quoting in the shell?
39,841,083
<p>When starting a program via the command line using <code>os.system(program file_argument))</code> and where the argument is a file (which might have whitespace in it) what is the best way to send the argument to the other program?</p> <p>I've looked at these options:</p> <ul> <li>Using <code>pipes.quote(file_name)...
0
2016-10-03T22:00:49Z
39,843,906
<pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; subprocess.call(['cat', 'file with space.txt']) </code></pre> <p>Using <code>os.system</code>, while simple to get started, breaks down when trying to do more complicated tasks.</p> <p>I wish I had given up on <code>os.system</code> much earlier and just got fami...
2
2016-10-04T03:54:46Z
[ "python", "shell" ]
Under what circumstances must I use py-files option of spark-submit?
39,841,084
<p>Just poking around spark-submit, I was under the impression that if my application has got dependencies on other .py files then I have to distribute them using the py-files option (see <a href="http://spark.apache.org/docs/latest/submitting-applications.html#bundling-your-applications-dependencies" rel="nofollow">bu...
0
2016-10-03T22:00:58Z
39,841,219
<p>You must be submitting this in local environment where your driver and executors runs on the same machine , that is the the reason it worked ,but if you deploy in cluster and try to run from there you have to use --pf-files option.</p> <p>Please check the <a href="http://spark.apache.org/docs/latest/#running-the-e...
1
2016-10-03T22:11:35Z
[ "python", "apache-spark" ]
Parsing floating number from ping output in text file
39,841,200
<p>So I am writing this python program that must extract the round trip time from a text file that contains numerous pings, whats in the text file I previewed below:</p> <pre><code> 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=1 ttl=60 time=12.6ms 64 bytes from a104-...
-3
2016-10-03T22:09:59Z
39,841,279
<p>I don't know of a way to do that in RegEx, but if you add the following line before the sort, it should take care of it for you:</p> <pre><code>roundtriptimes[:] = [float(x) for x in roundtriptimes] </code></pre>
1
2016-10-03T22:18:19Z
[ "python", "regex", "ping", "text-parsing" ]
Parsing floating number from ping output in text file
39,841,200
<p>So I am writing this python program that must extract the round trip time from a text file that contains numerous pings, whats in the text file I previewed below:</p> <pre><code> 64 bytes from a104-100-153-112.deploy.static.akamaitechnologies.com (104.100.153.112): icmp_seq=1 ttl=60 time=12.6ms 64 bytes from a104-...
-3
2016-10-03T22:09:59Z
39,841,298
<h1>Non-regex:</h1> <p>Simply performing splits on space, grabbing the last entry, then split on <code>=</code>, grab the second part of the list and omit the last two components (ms). Cast to a float. </p> <p>All of that is done in a list-comprehension:</p> <p>Note that <code>readlines</code> is used to have a list...
1
2016-10-03T22:20:15Z
[ "python", "regex", "ping", "text-parsing" ]
How to "melt" `pandas.DataFrame` objects? (Python 3)
39,841,204
<p>I'm trying to <code>melt</code> certain columns of a <code>pd.DataFrame</code> while preserving columns of the other. In this case, I want to <code>melt</code> <code>sine</code> and <code>cosine</code> columns into <code>values</code> and then which column they came from (i.e. <code>sine</code> or <code>cosine</cod...
2
2016-10-03T22:10:08Z
39,842,057
<p>allright so I had to create a similar df because I did not have access to your <code>a</code> variable. I change your <code>a</code> variable for a list from 0 to 99... so t will be 0 to 99</p> <p>you could do this :</p> <pre><code>a = range(0, 100) DF_data = pd.DataFrame([a, [np.sin(x)for x in a], [np.cos(x)for x...
1
2016-10-03T23:38:43Z
[ "python", "pandas", "matrix", "dataframe", "melt" ]
django 1.10 render template html class
39,841,233
<p>After a user fills out a form on my site, I user render(request, html, context). I'd like to return the user to the same part of the page after they register. I am not using any front end frameworks (like angular - thats my next project). How would I go about doing this?</p> <p>views.py:</p> <pre><code>def homepag...
0
2016-10-03T22:13:26Z
39,841,808
<p>To do this, you need to differentiate the default GET request to access the page and the POST of the form. </p> <p>E.g. You could do:</p> <pre><code>contact_form = EmailUpdatesForm() if request.method == 'POST': contact_form = EmailUpdatesForm(request.POST) if contact_form.is_valid(): contact = cont...
0
2016-10-03T23:10:44Z
[ "python", "django", "django-templates", "django-email" ]
Need help multiplying positive numbers in a list by 3, and leaving other numbers unmodified
39,841,265
<p>My goal is to multiply all positive numbers in a list by 3. I think I've almost got the solution but I'm not sure what is causing it not to work. It currently just returns back the original numbers and does not multiply any numbers by 3.</p> <pre><code>def triple_positives(xs): List = [] product = 3 for...
-4
2016-10-03T22:17:17Z
39,841,322
<p>You're iterating over an empty list, and that loop would be trying to access elements that don't exist, change the <code>product</code>, and append unchanged elements from the original list to the new list. And then you return the original, unchanged list anyway. Basically, almost every line in your code is wrong.</...
0
2016-10-03T22:22:29Z
[ "python", "list", "numbers", "multiplying" ]
Need help multiplying positive numbers in a list by 3, and leaving other numbers unmodified
39,841,265
<p>My goal is to multiply all positive numbers in a list by 3. I think I've almost got the solution but I'm not sure what is causing it not to work. It currently just returns back the original numbers and does not multiply any numbers by 3.</p> <pre><code>def triple_positives(xs): List = [] product = 3 for...
-4
2016-10-03T22:17:17Z
39,841,359
<p>Modifying your function it should be something like this. 0 is not a positive number.So using > instead of >=.</p> <pre><code>def triple_positives(xs): List = [] product = 3 for i in xs: if i &gt; 0: i=i*product List.append(i) return List </code></pre> <p>But this can be...
0
2016-10-03T22:25:20Z
[ "python", "list", "numbers", "multiplying" ]
Need help multiplying positive numbers in a list by 3, and leaving other numbers unmodified
39,841,265
<p>My goal is to multiply all positive numbers in a list by 3. I think I've almost got the solution but I'm not sure what is causing it not to work. It currently just returns back the original numbers and does not multiply any numbers by 3.</p> <pre><code>def triple_positives(xs): List = [] product = 3 for...
-4
2016-10-03T22:17:17Z
39,841,377
<p>In your code, there are multiple issues. Below is the updated version of it with fixes:</p> <pre><code>&gt;&gt;&gt; def triple_positives(xs): ... List = [] ... product = 3 ... for i in range (len(xs)): ... if xs[i] &gt;= 0: ... List.append(xs[i]*3) ... else: ... L...
0
2016-10-03T22:27:33Z
[ "python", "list", "numbers", "multiplying" ]
Why might this link not be working...?
39,841,276
<p>I'm rendering a bunch of posts on a page where a user can browse listings and click on one of them and be sent to a 'singles page' for more information on whatever product they clicked. This method works for every link EXCEPT for the first one. </p> <p>Anytime I click on the very first link of the page, I get a <st...
-1
2016-10-03T22:17:46Z
39,841,485
<p>There is no need to build URLs manually. The best way it to use flask's built-in function <a href="http://flask.pocoo.org/docs/0.11/api/#flask.url_for" rel="nofollow"><code>url_for</code></a>:</p> <pre><code>{{url_for('single2', num=i)}} </code></pre> <p>There is also no need for calculating the <code>i</code> man...
2
2016-10-03T22:37:42Z
[ "python", "flask", "jinja2" ]
How to Count Number of Data Points?
39,841,333
<p>I have 200 data points scattered from this loop:</p> <pre><code>import math plt.figure() for i in range(200): r=random.uniform(-1,1) x=random.uniform(-1,1) if math.sqrt(x**2+r**2)&lt;1: plt.plot(x,r,'r.') else: plt.plot(x,r,'k.') redraw() </code></pre> <p>So there will be a number ...
0
2016-10-03T22:23:13Z
39,841,445
<p>You would just need to increment a counter when the condition is met:</p> <pre><code>import math plt.figure() good_samples = 0 for i in range(200): r=random.uniform(-1,1) x=random.uniform(-1,1) if math.sqrt(x**2+r**2)&lt;1: plt.plot(x,r,'r.') good_samples += 1 else: plt.plot...
3
2016-10-03T22:33:06Z
[ "python", "python-2.7" ]
How to fix python program that appears to be doing an extra loop?
39,841,451
<p>A portion of a python program I am writing seems to be looping an extra time. The part of the program that isn't working is below. It is supposed to ask for a string from the user and create a two-dimensional list where each distinct character of the string is put in its own sub-list. (Hopefully that makes sense... ...
0
2016-10-03T22:33:57Z
39,841,663
<p>Your mistake lies in this part:</p> <pre><code>if currentElement != compareTo: ... compareTo = listA[i] </code></pre> <p>It should be:</p> <pre><code>if currentElement != compareTo: ... compareTo = listA[elementsCounted] </code></pre> <p>It's an overly complex function for such a simple task.</p>...
1
2016-10-03T22:53:28Z
[ "python", "list", "loops", "if-statement", "while-loop" ]
How to fix python program that appears to be doing an extra loop?
39,841,451
<p>A portion of a python program I am writing seems to be looping an extra time. The part of the program that isn't working is below. It is supposed to ask for a string from the user and create a two-dimensional list where each distinct character of the string is put in its own sub-list. (Hopefully that makes sense... ...
0
2016-10-03T22:33:57Z
39,841,744
<p>If you want a simpler approach:</p> <pre><code>&gt;&gt;&gt; def make_lists(inp): ... i = 0 ... indices = {} ... result = [] ... for c in sorted(inp): ... if c not in indices: ... result.append([c]) ... indices[c] = i ... i += 1 ... else: ... result[indices[c]].append(c) ... ...
1
2016-10-03T23:04:35Z
[ "python", "list", "loops", "if-statement", "while-loop" ]
cannot import name multiarray Django Apache2
39,841,540
<p>I am currently running a django app on an ec2 with apache. The app works fine when I run it using djangos runserver command. However I receive a 'cannot import name multiarray' when I run it using apache. I have tried reinstalling numpy and various packages many times and have still not had any luck. Below is my .co...
0
2016-10-03T22:41:17Z
39,885,673
<p>I can possibly spot three issues that may effect your setup.</p> <p>Your virutalenv is placed inside your project itself, this in my experience sometimes leads to conflicts. Virtualenvs and the project should always be separated. May I suggest a structures such as:</p> <p>/home/ubuntu/site - django project files ...
0
2016-10-06T00:25:26Z
[ "python", "django", "apache", "numpy", "python-3.4" ]
matplotlib histogram: how to display the count over the bar?
39,841,733
<p>With matplotlib's <code>hist</code> function, how can one make it display the count for each bin over the bar?</p> <p>For example,</p> <pre><code>import matplotlib.pyplot as plt data = [ ... ] # some data plt.hist(data, bins=10) </code></pre> <p>How can we make the count in each bin display over its bar?</p>
0
2016-10-03T23:02:09Z
39,842,288
<p>it seems <code>hist</code> can't do this,you can write some like :</p> <pre><code>your_bins=20 data=[] arr=plt.hist(data,bins=your_bins) for i in range(your_bins): plt.text(arr[1][i],arr[0][i],str(arr[0][i])) </code></pre>
1
2016-10-04T00:06:55Z
[ "python", "matplotlib" ]
Values Within range of if statement not printing (Runge-Kutta Fourth Order in Python)
39,841,772
<p>I am writing a code to perform a Fourth Order Runge-Kutta numerical approximation with adaptive step size. </p> <pre><code>def f(x, t): #integrating function return -x def exact(t): #exact solution return np.exp(-t) def Rk4(x0, t0, dt): #Runge-Kutta Fourth Order t = np.arange(0, 1+dt,...
1
2016-10-03T23:07:13Z
39,841,813
<p><code>^</code> is <a href="https://docs.python.org/2/reference/expressions.html#binary-bitwise-operations" rel="nofollow">bitwise exclusive or</a> in Python, not exponentiation; that's <code>**</code>. So <code>10^-5</code> (10 xor -5) is -15, and none of your errors is less than -15.</p> <p>You probably want the s...
3
2016-10-03T23:11:41Z
[ "python", "if-statement", "runge-kutta" ]
I'm writing the follow python script as a way to implement a slot machine type game using random numbers
39,841,804
<pre><code>from getch import getch, pause from random import randint def wheel_spin(): tokens = 100 while tokens &gt; 0: num_input= getch() if num_input == ' ': print "You Hit Space Bar" draw1 = randint(1,6) draw2 = randint(1,6) draw3 = randint(1,6)...
0
2016-10-03T23:10:17Z
39,841,820
<p><code>tokens</code> is undefined in the <code>winning</code> method. It's declared in the <code>spin_wheel</code> and is scope-limited to only that method. You either want to pass it in or make it global.</p> <pre><code>tokens = 10 def spin_wheel(): global tokens ... def winning(): global tokens ...
0
2016-10-03T23:12:09Z
[ "python", "function" ]
If Statement Syntax in Python
39,841,887
<p>I get an error with the below code on the line that says, <code>if (str(listGroup) == "FTPDST"):</code>. I'm pretty sure my if, elif, else statement is correct syntax. Please let me know if my syntax is wrong on that line or anywhere else I get errors because the below code won't run, and it throws an <code>SyntaxEr...
0
2016-10-03T23:19:38Z
39,841,920
<p>You're missing a <code>)</code> in all <code>.append(str(m.group(0))</code>.</p>
4
2016-10-03T23:24:23Z
[ "python", "if-statement" ]
Separate joined words in a string using python
39,841,918
<pre><code>"10JAN2015AirMail standard envelope from HyderabadAddress details:John Cena Palm DriveAdelaide.Also Contained:NilAction Taken:Goods referred to HGI QLD for further action.Attachments:Nil34FEB2004" </code></pre> <p>What I want to do is to read this string in python and separate the joined words. What I exact...
-1
2016-10-03T23:23:52Z
39,842,705
<p>I know that this solution can be done pretty much simpler classifying chars in sets (upper, lower, numeric) but I preferred to do a much more verbose solution:</p> <pre><code>test_text = "10JAN2015AirMail standard envelope from HyderabadAddress details:John Cena Palm DriveAdelaide.Also Contained:NilAction Taken:Goo...
0
2016-10-04T01:00:29Z
[ "python" ]
conditionally parsing json
39,842,046
<p>I am trying to extract a value from a json array using python. How do I get the value for <code>"energy"</code> on a specific day? Here is what the json looks like:</p> <pre><code>{ "emeter": { "get_daystat": { "day_list": [ { "year": 2016, "month": 10, "day": 1, "energy": 0.651000 }, { ...
-1
2016-10-03T23:37:26Z
39,842,135
<p><code>parsed_json</code> will have a python dict. You can access the <code>day_list</code> array with a simple linear search.</p> <pre><code>def get_energy_value_by_date(obj, year, month, day): for value in obj['emeter']['get_daystat']['day_list']: if value['year'] == year and value['month'] == month...
2
2016-10-03T23:46:28Z
[ "python", "json" ]
conditionally parsing json
39,842,046
<p>I am trying to extract a value from a json array using python. How do I get the value for <code>"energy"</code> on a specific day? Here is what the json looks like:</p> <pre><code>{ "emeter": { "get_daystat": { "day_list": [ { "year": 2016, "month": 10, "day": 1, "energy": 0.651000 }, { ...
-1
2016-10-03T23:37:26Z
39,842,215
<p>You could do a linear search through the data:</p> <pre><code>def get_energy(data, year, month, day): for date in data['emeter']['get_daystat']['day_list']: if(date['year'] == year and date['month'] == month and date['day'] == day): return date['energy'] json_data = { ...
0
2016-10-03T23:56:18Z
[ "python", "json" ]
How can i avoid the getting this error in pyomo "Error retrieving component Pd[1]: The component has not been constructed."
39,842,072
<p>I am new to pyomo. I am trying to run a simple maximization problem, but i keep getting this error message: <code>Error retrieving component Pd[1]: The component has not been constructed.</code> . Only the last 5 constraints give me this problem, the first three constraints work fine. I'm using this command on the I...
-1
2016-10-03T23:39:59Z
39,853,933
<p>You shouldn't need the very first "import pyomo" line. The only import line you should need is the "from pyomo.environ import *". If this doesn't solve your problem then you should post the data file you're using (or a simplified version of it). Seems like the data isn't being loaded into the Pyomo model correctly.<...
0
2016-10-04T13:43:02Z
[ "python", "pyomo" ]
How can i avoid the getting this error in pyomo "Error retrieving component Pd[1]: The component has not been constructed."
39,842,072
<p>I am new to pyomo. I am trying to run a simple maximization problem, but i keep getting this error message: <code>Error retrieving component Pd[1]: The component has not been constructed.</code> . Only the last 5 constraints give me this problem, the first three constraints work fine. I'm using this command on the I...
-1
2016-10-03T23:39:59Z
39,856,737
<p>In some of the constraints listed above, the argument in the rule is "module", when "model" is used in the expression e.g.,</p> <pre><code>def Dlim_rule(module,i): return model.Pd[i] &lt;= model.SOC[i] - model.SOCmin model.Dlim = Constraint(model.T,rule=Dlim_rule) </code></pre> <p>The definition of the rule an...
2
2016-10-04T15:51:39Z
[ "python", "pyomo" ]
Split and Combine Date
39,842,074
<p>I am trying to write a python script that will compare dates from two different pages. The format of date in one page is Oct 03 2016 whereas on other page is (10/3/2016). My goal is to compare these two dates. I was able to convert Oct to 10 but don't know how to make it 10/3/2016.</p>
1
2016-10-03T23:40:08Z
39,842,136
<p>You should really be using the <code>dateutil</code> library for this.</p> <pre><code>&gt;&gt;&gt; import dateutil.parser &gt;&gt;&gt; first_date = dateutil.parser.parse('Oct 03 2016') &gt;&gt;&gt; second_date = dateutil.parser.parse('10/3/2016') &gt;&gt;&gt; first_date datetime.datetime(2016, 10, 3, 0, 0) &gt;&gt...
6
2016-10-03T23:46:41Z
[ "python" ]
Split and Combine Date
39,842,074
<p>I am trying to write a python script that will compare dates from two different pages. The format of date in one page is Oct 03 2016 whereas on other page is (10/3/2016). My goal is to compare these two dates. I was able to convert Oct to 10 but don't know how to make it 10/3/2016.</p>
1
2016-10-03T23:40:08Z
39,842,147
<p>Use <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow"><code>datetime</code></a> module to convert your string to <code>datetime</code> object and then compare both. For example:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; date1 = datetime.strptime('Oct 03 2016', '%b...
3
2016-10-03T23:48:01Z
[ "python" ]
Topic 12 10 Pyschool Regular Expression
39,842,141
<p>Below is an example from the exercise of regular expression.</p> <pre><code>re.search(regex1, 'a1b22c333d4444').groups() </code></pre> <p>The above expression's required result is </p> <p>('22', '333')</p> <p>What would be the complete expression of <code>regex1 = r"([ ]{2})[^ ]([ ]{ })"</code>?</p>
-2
2016-10-03T23:47:31Z
39,842,966
<p>This looks like you're asking for help on HW. So instead of writing the code for you in the format that is expected, here is another way to get to the solution, so that you can work on it yourself. <code>(\d{2}).+(\d{3})</code>. You can practice your regular expressions here -> <a href="http://pythex.org/" rel="no...
1
2016-10-04T01:41:16Z
[ "python", "regex", "python-3.x" ]
Parsing text file in python
39,842,165
<p>So I am trying to python program that will extract the round trip time from a web server ping stored in a text file. So what I basically have is a text file with this:</p> <pre><code> PING e11699.b.akamaiedge.net (104.100.153.112) 56(84) bytes of data. 64 bytes from a104-100-153-112.deploy.static.akamaitechn...
0
2016-10-03T18:55:37Z
39,842,166
<p>Since this seems to come from <a href="/questions/tagged/ping" class="post-tag" title="show questions tagged &#39;ping&#39;" rel="tag">ping</a> command, you could use <a href="/questions/tagged/grep" class="post-tag" title="show questions tagged &#39;grep&#39;" rel="tag">grep</a> like this :</p> <pre><code>grep -oP...
5
2016-10-03T19:02:48Z
[ "text-processing", "python" ]
Parsing text file in python
39,842,165
<p>So I am trying to python program that will extract the round trip time from a web server ping stored in a text file. So what I basically have is a text file with this:</p> <pre><code> PING e11699.b.akamaiedge.net (104.100.153.112) 56(84) bytes of data. 64 bytes from a104-100-153-112.deploy.static.akamaitechn...
0
2016-10-03T18:55:37Z
39,842,167
<p>Since you asked for Python, here it is:</p> <pre><code>$ ping -c 4 8.8.8.8 | python -c 'import sys;[ sys.stdout.write(l.split("=")[-1]+"\n") for l in sys.stdin if "time=" in l]' 10.5 ms 9.22 ms 9.37 ms 9.71 ms </code></pre> <p>Note, this has stdout buffering, so you may want to add <code>sys.stdout....
1
2016-10-03T19:53:31Z
[ "text-processing", "python" ]
Parsing text file in python
39,842,165
<p>So I am trying to python program that will extract the round trip time from a web server ping stored in a text file. So what I basically have is a text file with this:</p> <pre><code> PING e11699.b.akamaiedge.net (104.100.153.112) 56(84) bytes of data. 64 bytes from a104-100-153-112.deploy.static.akamaitechn...
0
2016-10-03T18:55:37Z
39,847,805
<p>You specified that your data is already in a text file. So asuming that your text file is called <code>data.txt</code></p> <pre><code>#we will be using the regular expression library for this example import re #open the "data.txt" (named data_file in a scope) with open("data.txt") as data_file: #read the tex...
0
2016-10-04T08:41:50Z
[ "text-processing", "python" ]
pip install for Python 3 in virtualenv on Mac OSX?
39,842,197
<p>I can <code>pip install</code> and <code>import</code> just about any package on my Mac in a virtual environment, doing the following:</p> <p>Setting up the virtual environment:</p> <pre><code>Last login: Mon Oct 3 18:47:06 on ttys000 me-MacBook-Pro-3:~ me$ cd /Users/me/Desktop/ me-MacBook-Pro-3:Desktop me$ virtu...
0
2016-10-03T23:53:49Z
39,842,683
<p>Try using <code>virtualenv --python=$(which python3) env</code> to create the virtual environment. </p> <p>When you create a virtualenv by default it uses the python binary it was installed with. So if you did <code>pip install virtualenv</code> on a system where python2.7 was installed first, then virtualenv will ...
2
2016-10-04T00:58:03Z
[ "python", "osx", "pip" ]