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
Django: jinja2 code not working when iterated over the same list twice
39,456,156
<p>I have an html file in my django project as follows:</p> <pre><code>&lt;body&gt; &lt;div class="row"&gt; &lt;div class="col-sm-3"&gt; &lt;ul class="list-group"&gt; {% for image in images %} &lt;li class="list-group-item"&gt;{{ image.name}} &lt;img clas...
-1
2016-09-12T18:02:12Z
39,464,111
<p>You might be passing a <a href="http://stackoverflow.com/a/231855/1268926">generator object</a> instead of a list / tuple.</p> <p>The difference is that you can iterate over the generator object only once.</p> <p>For example (below is the last / equivalent line in your view that renders the template)</p> <pre><co...
0
2016-09-13T07:09:31Z
[ "python", "django" ]
How to search for a different string in a different file using Python 3.x
39,456,225
<p>I am trying to search a large group of text files (160K) for a specific string that changes for each file. I have a text file that has every file in the directory with the string value I want to search. Basically I want to use python to create a new text file that gives the file name, the string, and a 1 if the stri...
1
2016-09-12T18:07:04Z
39,456,940
<p>As I understand your question, the dictionary relates file names to strings</p> <pre><code>d = { "file1.txt": "widget", "file2.txt": "sprocket", #etc } </code></pre> <p>If each file is not too large you can read each file into memory: </p> <pre><code>for filename in os.listdir(os.getcwd()): string = d[filen...
0
2016-09-12T18:57:03Z
[ "python", "python-3.x" ]
Non orthonal to Orthogonal coordinates system conversion in Python
39,456,232
<p>I have a vector in a non-orthogonal coordinate system spanned by axes a,b,c and their Euler angles alpha(between b&amp;c),beta(between c&amp;a),gamma(between a&amp;b). I want to convert this vector to an orthogonal coordinate system spanned by x,y,z. I assume that axes a and x coincide while conversion. I can do it ...
0
2016-09-12T18:07:31Z
39,458,107
<p>The best coordinate system transformations function I've knowen in python is this one: <a href="http://www.lfd.uci.edu/~gohlke/code/transformations.py.html" rel="nofollow">http://www.lfd.uci.edu/~gohlke/code/transformations.py.html</a></p> <p>Take a look at the functions: euler_matrix and euler_from_matrix. It come...
0
2016-09-12T20:13:45Z
[ "python", "computational-geometry", "coordinate-systems", "coordinate-transformation" ]
Python 3 nested ordered dictionary key access
39,456,283
<p>I have a nested, ordered dictionary built in Python 3. It looks like this:</p> <pre><code>coefFieldDict = OrderedDict([(('AC_Type',), OrderedDict([('BADA_code', 0), ('n_engine', 1), ('eng_type', 2), 'wake_cate', 3)])), (('Mass',), OrderedDic([('m_ref', 4), ('m_min', 5), ('m_max', 6), ('m_pyld', 7), ('G_w'...
0
2016-09-12T18:11:27Z
39,456,422
<p>try <code>coefFieldDict[('Mass',)]</code></p> <p>...Since you are using tuples (why ?) instead of strings as key</p>
0
2016-09-12T18:20:32Z
[ "python", "key", "ordereddictionary" ]
Unbound name showing up in stack frame using inspect module
39,456,297
<p>I recently ran into a bug that was quite difficult to track down. I had accidentally re-used a class name as a variable (see code below), so when I tried to call the class I (understandably) got an error. The reason it was so hard to track down is that my debugger (Wing IDE 5.1.10) would execute the line successfull...
0
2016-09-12T18:12:30Z
39,456,778
<p>First, about the exception, I think your IDE doesn't respect the python specs :</p> <blockquote> <p>A scope defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block.</p> </blockquote> <p>[...]</p> <blockquote> <p>If a name is bound in a block, i...
1
2016-09-12T18:45:32Z
[ "python", "stack-trace" ]
Unbound name showing up in stack frame using inspect module
39,456,297
<p>I recently ran into a bug that was quite difficult to track down. I had accidentally re-used a class name as a variable (see code below), so when I tried to call the class I (understandably) got an error. The reason it was so hard to track down is that my debugger (Wing IDE 5.1.10) would execute the line successfull...
0
2016-09-12T18:12:30Z
39,457,035
<p>If a value is assigned to a variable within a function, that variable becomes a local variable within that function.</p> <p>That variable is treated as local from the moment the function is created, i.e. before it is called for the first time. Python actually optimizes access to local variables and does not make a ...
1
2016-09-12T19:03:07Z
[ "python", "stack-trace" ]
Using boto to invoke lambda functions how do I do so asynchronously?
39,456,309
<p>SO I'm using boto to invoke my lambda functions and test my backend. I want to invoke them asynchronously. I have noted that "invoke_async" is deprecated and should not be used. Instead you should use "invoke" with an InvocationType of "Event" to do the function asynchronously. </p> <p>I can't seem to figure out ...
0
2016-09-12T18:13:02Z
39,456,752
<p>An asynchronously executed AWS Lambda function doesn't return the result of execution. If an asynchronous invocation request is successful (i.e. there were no errors due to permissions, etc), AWS Lambda immediately returns the HTTP status code <a href="https://httpstatuses.com/202" rel="nofollow">202 ACCEPTED</a> an...
2
2016-09-12T18:43:25Z
[ "python", "amazon-web-services", "boto", "aws-lambda" ]
Using boto to invoke lambda functions how do I do so asynchronously?
39,456,309
<p>SO I'm using boto to invoke my lambda functions and test my backend. I want to invoke them asynchronously. I have noted that "invoke_async" is deprecated and should not be used. Instead you should use "invoke" with an InvocationType of "Event" to do the function asynchronously. </p> <p>I can't seem to figure out ...
0
2016-09-12T18:13:02Z
39,457,165
<p>There is a difference between an <em>'async AWS lambda invocation'</em> and <em>'async python code'</em>. When you set the <code>InvocationType</code> to <code>'Event'</code>, <a href="http://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html#API_Invoke_RequestSyntax" rel="nofollow">by definition</a>, it does not ...
0
2016-09-12T19:12:01Z
[ "python", "amazon-web-services", "boto", "aws-lambda" ]
Delete directories older than X days?
39,456,318
<p>I decided to go python for this because I am in the process of learning Python, so I use it over Powershell whenever I can.</p> <p>I have the theory down for this, but it seems <code>os.stat</code> cannot take a list, but only a string or <code>int</code>. Right now I'm just printing before I go and delete things....
-1
2016-09-12T18:13:33Z
39,456,407
<p>Your code problem is that you are passing <code>dirs</code> to <code>os.path.getmtime()</code>, and <code>dirs</code> is a <code>list</code> as specified in the <a href="https://docs.python.org/2/library/os.html">documentation</a> for <code>os.walk</code></p> <p>So you can address this by:</p> <pre><code>import os...
5
2016-09-12T18:19:31Z
[ "python" ]
Referencing named groups in look-around (Python 2.x)
39,456,607
<p>I have a pattern that matches for <em>multiple</em> key/value pairs, and the key/value strings can be delimited by any characters, then the groups of key/value can also be delimited, just <strong>not by the same character</strong>.</p> <p>I figured out how to allow dynamic delimiters, and restrict the same delimite...
3
2016-09-12T18:33:27Z
39,758,474
<p>Summing up what has already been said: the point is that the length of the pattern is unknown when you put backreferences into a lookbehind that <a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">must be fixed-width</a> at design time. The newer <a href="https://pypi.python....
0
2016-09-28T22:10:19Z
[ "python", "regex", "regex-lookarounds", "regex-greedy" ]
Python Serial Writes to Arduino is different from Arduino's Serial Monitor's Serial Writes
39,456,630
<p>I have a Python script that writes a string <code>test</code> to the Arduino serial port. If the arduino receives the <code>test</code> string, it should reply with a string <code>ok</code> and LED 13 should like up..</p> <p><strong>Problem:</strong> When the Arduino Serial Monitor is used to write <code>test</code...
1
2016-09-12T18:35:10Z
39,456,662
<pre><code>port = 'COM5' ser = serial.Serial( port=port, baudrate=9600, timeout=5 ) # you need to sleep after opening the port for a few seconds time.sleep(5) # arduino takes a few seconds to be ready ... #also you should write to your instance ser.write("test\r\n") # and give arduino time to respond time...
2
2016-09-12T18:37:26Z
[ "python", "arduino", "serial-port", "pyserial" ]
How to reload a configuration file on each request for Flask?
39,456,672
<p>Is there an idiomatic way to have Flask reload my configuration file on every request? The purpose of this would be so that I could change passwords or other configuration related items without having to shut down and restart the server in production.</p> <p>Edit: <code>app.run(debug=True)</code> is not acceptable ...
0
2016-09-12T18:38:11Z
39,457,189
<p>You cannot safely / correctly reload the config after the application begins handling requests. Config is <em>only</em> meant to be read during application setup. The main reason is because a production server will be running using multiple processes (or even distributed across servers), and the worker that handle...
2
2016-09-12T19:13:42Z
[ "python", "flask" ]
Evaluating the next line in a For Loop while in the current iteration
39,456,802
<p>Here is what I am trying to do: I am trying to solve an issue that has to do with wrapping in a text file. </p> <p>I want to open a txt file, read a line and if the line contains what I want it to contain, check the next line to see if it does not contain what is in the first line. If it does not, add the line to t...
0
2016-09-12T18:47:00Z
39,457,281
<p>I would try to do something like this, but this is invalid for triples of "From " and not elegant at all.</p> <pre><code>lines = open("file", 'r').readlines() lines2 = open("file2", 'w') counter_list=[] last_from = 0 for counter, line in enumerate(lines): if "From " in line and counter != last_from +1: ...
0
2016-09-12T19:20:00Z
[ "python", "python-2.7" ]
Evaluating the next line in a For Loop while in the current iteration
39,456,802
<p>Here is what I am trying to do: I am trying to solve an issue that has to do with wrapping in a text file. </p> <p>I want to open a txt file, read a line and if the line contains what I want it to contain, check the next line to see if it does not contain what is in the first line. If it does not, add the line to t...
0
2016-09-12T18:47:00Z
39,458,558
<p>Thank you Martjin for helping me reset my mind frame! This is what I came up with:</p> <pre><code> handle = open("my file") first = "" second = "" sent = "" for line in handle: line = line.rstrip() if len(first) &gt; 0: if line.startswith("From "): i...
0
2016-09-12T20:47:27Z
[ "python", "python-2.7" ]
Using conditional expressions and incrementing/decrementing a variable
39,456,952
<p>How do I to put the if statement into a conditional expression and how do I increment/ decrement a variable?</p> <pre><code>num_users = 8 update_direction = 3 num_users = if update_direction ==3: num_users= num_users + 1 else: num_users= num_users - 1 print('New value is:', num_users) </code></pre>
-1
2016-09-12T18:57:49Z
39,457,135
<p>I might be way off the mark and my Python is a bit rusty, but the code looks alright for the problem provided besides the formatting issues pointed out by James K. The if statement you have forms a part of the conditional expression (it is a condition). </p> <p>Essentially, a conditional expression follows this pat...
1
2016-09-12T19:09:26Z
[ "python" ]
Using conditional expressions and incrementing/decrementing a variable
39,456,952
<p>How do I to put the if statement into a conditional expression and how do I increment/ decrement a variable?</p> <pre><code>num_users = 8 update_direction = 3 num_users = if update_direction ==3: num_users= num_users + 1 else: num_users= num_users - 1 print('New value is:', num_users) </code></pre>
-1
2016-09-12T18:57:49Z
39,457,464
<p>The correct statement would be:</p> <pre><code>num_users = num_users + 1 if update_direction == 3 else num_users - 1 </code></pre> <p>For reference, see <a href="https://docs.python.org/2/reference/expressions.html#conditional-expressions" rel="nofollow">Conditional Expressions</a>.</p>
1
2016-09-12T19:30:34Z
[ "python" ]
How to mock nested / multiple layers of return objects in python
39,457,108
<p>I'm currently struggling to find a good way of mocking multiple layers / nested return values. In other words, I want to return a magic mock that in turn returns a magic mock with it's own set return values. I'm finding this relatively cumbersome and am looking for a more elegant and maintainable solution.</p> <p>...
2
2016-09-12T19:07:41Z
39,457,691
<p>Turns out this is easily possible and documented. However, the naming is not straightforward and needed to know what one is looking for. The referred to mocking is chained calls, which are in fact documented in the mock library.</p> <p>In this example, the mock_urlopen should look like this:</p> <pre><code> moc...
1
2016-09-12T19:44:29Z
[ "python", "nested", "mocking" ]
How to mock nested / multiple layers of return objects in python
39,457,108
<p>I'm currently struggling to find a good way of mocking multiple layers / nested return values. In other words, I want to return a magic mock that in turn returns a magic mock with it's own set return values. I'm finding this relatively cumbersome and am looking for a more elegant and maintainable solution.</p> <p>...
2
2016-09-12T19:07:41Z
39,458,013
<p>I have made this for you as a helper class:</p> <pre><code>from unittest.mock import Mock class ProxyMock: """Put me for easy referral""" def __init__(self, mock, _first=True): self._mock_ = mock self._first_ = _first def __getattr__(self, name): if self._first_: ne...
0
2016-09-12T20:07:02Z
[ "python", "nested", "mocking" ]
Pandas groupby object filtering
39,457,130
<p>i have a pandas dataframe</p> <pre><code>df.columns Index([u’car_id’,u’color’,u’make’,u’year’)] </code></pre> <p>I would like to create a new FILTERABLE object that has the count of each group (color,make,year);</p> <pre><code>grp = df[[‘color’,’make’,’year’]].groupby([‘color’,’m...
5
2016-09-12T19:09:07Z
39,457,171
<p>I think you need add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> and then output is <code>DataFrame</code>. Last use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><c...
3
2016-09-12T19:12:34Z
[ "python", "pandas", "indexing", "group-by", "condition" ]
Pandas groupby object filtering
39,457,130
<p>i have a pandas dataframe</p> <pre><code>df.columns Index([u’car_id’,u’color’,u’make’,u’year’)] </code></pre> <p>I would like to create a new FILTERABLE object that has the count of each group (color,make,year);</p> <pre><code>grp = df[[‘color’,’make’,’year’]].groupby([‘color’,’m...
5
2016-09-12T19:09:07Z
39,457,574
<p><strong><em>Option 1</em></strong><br> Filter ahead of time</p> <pre><code>cols = ['color','make','year'] df[df.color == 'black', cols].grouby(cols).size() </code></pre> <p><strong><em>Option 2</em></strong> Use <code>xs</code> for index cross sections</p> <pre><code>cols = ['color','make','year'] grp = df[cols]....
2
2016-09-12T19:37:28Z
[ "python", "pandas", "indexing", "group-by", "condition" ]
Running tests in single Python file with nose
39,457,196
<p>I'm using nose 1.3.7 with Anaconda 4.1.1 (Python 3.5.2). I want to run unit tests in a single file, e.g. <code>foo.py</code>. According to the <a href="http://nose.readthedocs.io/en/latest/usage.html" rel="nofollow">documentation</a> I should be able to simply run:</p> <pre><code>nosetests foo.py </code></pre> <p>...
0
2016-09-12T19:14:16Z
39,457,947
<p>I have a standalone Python 3.4 version and <code>nosetests foo.py</code> runs tests only in <code>foo.py</code> and <code>nosetests spam.py</code> runs test only in <code>spam.py</code>. </p> <p>A plain <code>nosetests</code> command without any option specified, runs tests in all files with names starting with th...
1
2016-09-12T20:02:28Z
[ "python", "unit-testing", "nose" ]
How would I use a while loop so that if they enter a number it would ask them the again?
39,457,203
<pre><code>fn = input("Hello, what is your first name?") firstname = (fn[0].upper()) ln = input("Hello, what is your last name?") lastname = (ln.lower()) </code></pre> <p>I want fn to be on a loop so that if they enter their a number instead of letters, it would repeat the question</p>
2
2016-09-12T19:14:38Z
39,457,239
<pre><code>if result.isalpha(): print "the string entered contains only letters !" </code></pre> <p>I guess ?</p> <pre><code>a="6" while not a.isalpha(): a = raw_input("Enter your name:") print "You entered:",a </code></pre> <p>if you just wanted to eliminate only words that contained numbers you could do</p>...
1
2016-09-12T19:16:56Z
[ "python", "python-3.x" ]
How would I use a while loop so that if they enter a number it would ask them the again?
39,457,203
<pre><code>fn = input("Hello, what is your first name?") firstname = (fn[0].upper()) ln = input("Hello, what is your last name?") lastname = (ln.lower()) </code></pre> <p>I want fn to be on a loop so that if they enter their a number instead of letters, it would repeat the question</p>
2
2016-09-12T19:14:38Z
39,457,270
<p>I guess you need something like this</p> <pre><code>final_fn = "" while True: fn = input("Hello, what is your first name?") if valid(fn): final_fn = fn break </code></pre> <p>Define you validation method before it. An example would be as Joran mentioned</p> <pre><code>def valid(fn): re...
3
2016-09-12T19:18:56Z
[ "python", "python-3.x" ]
Blob detection using OpenCV
39,457,209
<p>I am trying to do some white blob detection using OpenCV. But my script failed to detect the big white block which is my goal while some small blobs are detected. I am new to OpenCV, and am i doing something wrong when using simpleblobdetection in OpenCV? [Solved partially, please read below]</p> <p>And here is the...
0
2016-09-12T19:15:10Z
39,462,615
<p>You could try setting params.maxArea to something obnoxiously large (somewhere in the tens of thousands): the default may be something lower than the area of the rectangle you're trying to detect. Also, I don't know how true this is or not, but I've heard that detection by color is bugged with a logic error, so it m...
1
2016-09-13T05:16:41Z
[ "python", "opencv" ]
Blob detection using OpenCV
39,457,209
<p>I am trying to do some white blob detection using OpenCV. But my script failed to detect the big white block which is my goal while some small blobs are detected. I am new to OpenCV, and am i doing something wrong when using simpleblobdetection in OpenCV? [Solved partially, please read below]</p> <p>And here is the...
0
2016-09-12T19:15:10Z
39,474,485
<p>If you just want to detect the white rectangle you can try to set a higher threshold, e.g. 253, erase small object with an opening and take the biggest blob. I first smoothed your image, then thresholding it:</p> <p><a href="http://i.stack.imgur.com/UrrBT.png" rel="nofollow"><img src="http://i.stack.imgur.com/UrrBT...
1
2016-09-13T16:04:26Z
[ "python", "opencv" ]
Django - request.session not being saved
39,457,321
<p>I have a pretty simply utility function that gets an open web order if their is a session key called 'orderId', and will create one if there is no session key, and the parameter 'createIfNotFound' is equal to true in the function. Stepping through it with my debugger I can see that the piece of code that sets the se...
0
2016-09-12T19:22:26Z
39,457,680
<p>In some cases you need to explicitly tell the session that it has been modified.</p> <p>You can do this by adding <code>request.session.modified = True</code> to your view, after changing something in <code>session</code></p> <p>You can read more on this here - <a href="https://docs.djangoproject.com/en/1.10/topic...
2
2016-09-12T19:43:52Z
[ "python", "django", "session", "view" ]
Pandas: how to compute the rolling sum of a variable over the last few days but only at a given hour?
39,457,435
<p>I have a dataframe as follows</p> <pre><code>df = pd.DataFrame({ 'X' : np.random.randn(50000)}, index=pd.date_range('1/1/2000', periods=50000, freq='T')) df.head(10) Out[37]: X 2000-01-01 00:00:00 -0.699565 2000-01-01 00:01:00 -0.646129 2000-01-01 00:02:00 1.339314 2000-01-01 00:03:00...
4
2016-09-12T19:28:51Z
39,457,986
<p>Behold the power of <code>groupby</code>!</p> <pre><code>df = # as you defined above df['rolling_sum_by_time'] = df.groupby(df.index.time)['X'].apply(lambda x: x.shift(1).rolling(10).sum()) </code></pre> <p>It's a big pill to swallow there, but we are grouping by time (as in python datetime.time), then getting the...
2
2016-09-12T20:05:14Z
[ "python", "pandas" ]
Pandas: how to compute the rolling sum of a variable over the last few days but only at a given hour?
39,457,435
<p>I have a dataframe as follows</p> <pre><code>df = pd.DataFrame({ 'X' : np.random.randn(50000)}, index=pd.date_range('1/1/2000', periods=50000, freq='T')) df.head(10) Out[37]: X 2000-01-01 00:00:00 -0.699565 2000-01-01 00:01:00 -0.646129 2000-01-01 00:02:00 1.339314 2000-01-01 00:03:00...
4
2016-09-12T19:28:51Z
39,457,992
<p>IIUC, what you want is to perform a rolling sum, but only on the observations grouped by the exact same time of day. This can be done by</p> <pre><code>df.X.groupby([df.index.hour, df.index.minute]).apply(lambda g: g.rolling(window=5).sum()) </code></pre> <p>(Note that your question alternates between 5 and 10 per...
2
2016-09-12T20:05:36Z
[ "python", "pandas" ]
Not able to get the resources attached with route table
39,457,457
<p>I am using python for AWS infrastructure automation. I need to get the resources attached with the Route Table for which API given is </p> <pre><code>ec2 = boto3.resource('ec2') route_table_association = ec2.RouteTableAssociation('rtb-**********') response=route_table_association.get_available_subresources() </c...
0
2016-09-12T19:30:13Z
39,465,382
<p>The id required are <a href="http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.RouteTableAssociation.id" rel="nofollow">RouteTableAssociationId i.e. rtbassoc-xxxxxx </a>, <strong>NOT the route table id</strong>.</p> <p>RouteTableAssociationId is inside <a href="http://boto3.readthedocs.io/en/la...
0
2016-09-13T08:23:52Z
[ "python", "amazon-web-services", "amazon-ec2", "boto3", "botocore" ]
Not able to get the resources attached with route table
39,457,457
<p>I am using python for AWS infrastructure automation. I need to get the resources attached with the Route Table for which API given is </p> <pre><code>ec2 = boto3.resource('ec2') route_table_association = ec2.RouteTableAssociation('rtb-**********') response=route_table_association.get_available_subresources() </c...
0
2016-09-12T19:30:13Z
39,470,406
<p>Thanks this worked for me.</p> <pre><code>response = client.describe_route_tables( RouteTableIds=[ routetable, ], Filters=[ { 'Name': 'route-table-id', 'Values': [ routetable ] } ] ) </code></pre>
0
2016-09-13T12:42:10Z
[ "python", "amazon-web-services", "amazon-ec2", "boto3", "botocore" ]
Convolution without any padding-opencv Python
39,457,468
<p>Is there any function in Opencv-python that can convolve an image with a kernel without any padding ? Basically, I want an image in which convolution takes place only in the regions where the kernel and the portion of the image fully overlaps.</p>
1
2016-09-12T19:30:45Z
39,463,454
<p>OpenCV only supports convolving an image where the output returned is the same size as the input image. As such, you can still use OpenCV's filter functions, but simply ignore those pixels along the edges where the kernel didn't fully encapsulate itself inside the image. Assuming that your image kernel is odd, you...
2
2016-09-13T06:25:29Z
[ "python", "opencv", "numpy", "image-processing" ]
Trying to interpolate linearly in python
39,457,469
<p>I have 3 arrays: a, b, c all with length 15. </p> <pre><code>a=[950, 850, 750, 675, 600, 525, 460, 400, 350, 300, 250, 225, 200, 175, 150] b = [16, 12, 9, -35, -40, -40, -40, -45, -50, -55, -60, -65, -70, -75, -80] c=[32.0, 22.2, 12.399999999999999, 2.599999999999998, -7.200000000000003, -17.0, -26.8000000000000...
2
2016-09-12T19:30:46Z
39,458,926
<p>Here's simpler variation of a function from <a href="http://stackoverflow.com/questions/15112964/digitizing-an-analog-signal/15114952#15114952">another answer of mine</a>:</p> <pre><code>from __future__ import division import numpy as np def find_roots(t, y): """ Given the input signal `y` with samples a...
2
2016-09-12T21:17:08Z
[ "python", "scipy", "interpolation" ]
Trying to interpolate linearly in python
39,457,469
<p>I have 3 arrays: a, b, c all with length 15. </p> <pre><code>a=[950, 850, 750, 675, 600, 525, 460, 400, 350, 300, 250, 225, 200, 175, 150] b = [16, 12, 9, -35, -40, -40, -40, -45, -50, -55, -60, -65, -70, -75, -80] c=[32.0, 22.2, 12.399999999999999, 2.599999999999998, -7.200000000000003, -17.0, -26.8000000000000...
2
2016-09-12T19:30:46Z
39,459,095
<p>Another simple solution using:</p> <ul> <li>one linear-regressor for each vector (done with scikit-learn as scipy-docs were down for me; easy to switch to numpy/scipy-based linear-regression)</li> <li>general-purpose minimization using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.mini...
0
2016-09-12T21:30:47Z
[ "python", "scipy", "interpolation" ]
Trying to interpolate linearly in python
39,457,469
<p>I have 3 arrays: a, b, c all with length 15. </p> <pre><code>a=[950, 850, 750, 675, 600, 525, 460, 400, 350, 300, 250, 225, 200, 175, 150] b = [16, 12, 9, -35, -40, -40, -40, -45, -50, -55, -60, -65, -70, -75, -80] c=[32.0, 22.2, 12.399999999999999, 2.599999999999998, -7.200000000000003, -17.0, -26.8000000000000...
2
2016-09-12T19:30:46Z
39,459,127
<p>This is not necessarily a solution to your problem, since your data does not appear to be linear, but it might give you some ideas. If you assume that your lines a, b, and c are linear, then the following idea works:</p> <p>Perform a linear regression of lines a, b and c to get their respective slopes (m_a, m_b, m_...
1
2016-09-12T21:33:11Z
[ "python", "scipy", "interpolation" ]
Can I use a trigger to add combinations of foreign keys?
39,457,487
<p>I'm in the situation where I want to do multiples inserts on a table with a trigger after insert.</p> <p>Here the python code to understand the objective first:</p> <pre><code>d = dict() d["Table1"] = ["1", "2"] d["Table2"] = ["A","B"] from itertools import product d["Table12"] = [ (t1,t2,-1) for t1, t2 in produc...
0
2016-09-12T19:31:43Z
39,457,794
<p>Use a <code>SELECT</code> query in the <code>INSERT</code> query.</p> <pre><code>CREATE TRIGGER table1_inisert AFTER INSERT ON Table1 FOR EACH ROW BEGIN INSERT INTO Table12 (name1, name2, val) SELECT NEW.name1, name2, -1 FROM Table2 END </code></pre>
0
2016-09-12T19:52:45Z
[ "python", "mysql", "database-design", "foreign-keys", "database-trigger" ]
Field content not always visible in kivy Textinput
39,457,516
<p>I am encountering some strange/unexpected behaviour when displaying content in a Textinput field (Initially used for new record input - subsequently for show record data). Data is available in a dictionary and is assigned to Textinput fields. For short data the characters will be hidden sometimes: </p> <p><a href="...
0
2016-09-12T19:34:09Z
39,461,888
<p>You <code>hint_text</code> instead of <code>text</code> for your TextInputs. Something like</p> <pre><code> MyTextInput: id: social hint_text: some_social_name </code></pre>
0
2016-09-13T03:42:26Z
[ "python", "kivy", "textinput", "kivy-language" ]
How to print the \n character in Jinja2
39,457,587
<p>I have the following string in Python: <code>thestring = "123\n456"</code></p> <p>In my Jinja2 template, I use <code>{{thestring}}</code> and the output is:</p> <blockquote> <p>123<br> 456</p> </blockquote> <p>The only way I can get Jinja2 to print the exact representation <code>123\n456</code> (including the...
0
2016-09-12T19:38:17Z
39,458,104
<p>I'll answer my own, maybe it helps someone who has the same question.</p> <p>This works: <code>{{thestring.encode('string_escape')}}</code></p>
1
2016-09-12T20:13:37Z
[ "python", "flask", "jinja2" ]
Airflow: How to SSH and run BashOperator from a different server
39,457,592
<p>Is there a way to ssh to different server and run BashOperator using Airbnb's Airflow? I am trying to run a hive sql command with Airflow but I need to SSH to a different box in order to run the hive shell. My tasks should look like this:</p> <ol> <li>SSH to server1</li> <li>start Hive shell</li> <li>run Hive comma...
0
2016-09-12T19:38:28Z
39,494,330
<p>I think that I just figured it out:</p> <ol> <li><p>Create a SSH connection in UI under Admin > Connection. Note: the connection will be deleted if you reset the database</p></li> <li><p>In the Python file add the following</p> <pre><code>from airflow.contrib.operations.ssh_execute_operator import SSHExecuteOpera...
0
2016-09-14T15:29:01Z
[ "python", "ssh", "airflow" ]
improve linear search for KNN efficiency w/ NumPY
39,457,604
<p>I am trying to calculate the distance of each point in the testing set from each point in the training set:</p> <p>This is what my loop looks like right now:</p> <pre><code> for x in testingSet for y in trainingSet print numpy.linalg.norm(x-y) </code></pre> <p>Where testingSet and trainingSet are nump...
0
2016-09-12T19:39:12Z
39,457,704
<p>This is because you naively iterate over your data, and loops are slow in python. Instead, use sklearn <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html" rel="nofollow">pairwise distance functions</a>, or even better - use sklearn <a href="http://scikit-learn....
3
2016-09-12T19:45:16Z
[ "python", "numpy", "machine-learning" ]
What is the proper level of indent for hanging indent with type hinting in python?
39,457,607
<p>What is the proper syntax for a hanging indent for a method with multiple parameters and type hinting?</p> <p><strong>Align under first parameter</strong></p> <pre><code>def get_library_book(self, book_id: str, library_id: str )-&gt; Book: </code></pre...
4
2016-09-12T19:39:21Z
39,458,753
<p>Read the previous line of <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 8</a> more carefully, the part before "or using a hanging indent".</p> <blockquote> <p>Continuation lines should align wrapped elements either vertically using Python's implicit line joining inside parentheses, bracke...
2
2016-09-12T21:03:35Z
[ "python", "python-3.x", "pep8", "type-hinting" ]
What is the proper level of indent for hanging indent with type hinting in python?
39,457,607
<p>What is the proper syntax for a hanging indent for a method with multiple parameters and type hinting?</p> <p><strong>Align under first parameter</strong></p> <pre><code>def get_library_book(self, book_id: str, library_id: str )-&gt; Book: </code></pre...
4
2016-09-12T19:39:21Z
39,458,856
<p>Appart from Terrys answer, take an example from <a href="https://github.com/python/typeshed" rel="nofollow"><code>typeshed</code></a> which is the project on Python's GitHub for annotating the <code>stdlib</code> with stubs. </p> <p>For example, in <a href="https://github.com/python/typeshed/blob/master/stdlib/3/im...
2
2016-09-12T21:12:29Z
[ "python", "python-3.x", "pep8", "type-hinting" ]
What is the proper level of indent for hanging indent with type hinting in python?
39,457,607
<p>What is the proper syntax for a hanging indent for a method with multiple parameters and type hinting?</p> <p><strong>Align under first parameter</strong></p> <pre><code>def get_library_book(self, book_id: str, library_id: str )-&gt; Book: </code></pre...
4
2016-09-12T19:39:21Z
39,459,117
<p>PEP8 has many good ideas in it, but I wouldn't rely on it to decide this kind of question about whitespace. When I studied PEP8's recommendations on whitespace, I found them to be inconsistent and even contradictory.</p> <p>Instead, I would look at general principles that apply to nearly all programming languages, ...
2
2016-09-12T21:32:18Z
[ "python", "python-3.x", "pep8", "type-hinting" ]
Openshift python requests proxy permission denied
39,457,610
<p>I'm trying to use a proxy with the python 'requests' package on an Openshift server. I am getting a permission denied error. See below.</p> <p>Is Openshift blocking the connection or am I not configuring it correctly? Something else? Openshift doesn't want to let me connect to a proxy because the code works fine ...
0
2016-09-12T19:39:30Z
39,620,002
<p>Most probably OpenShift blocks uncommon outgoing ports for <a href="http://security.stackexchange.com/questions/24310/why-block-outgoing-network-traffic-with-a-firewall">security reasons</a>. your proxy is listening on 6060. You should try to ssh into your gear and try <code>telnet</code></p> <p>In my gear, post 60...
0
2016-09-21T14:55:54Z
[ "python", "proxy", "openshift", "python-requests" ]
is there a 2D dictionary in python?
39,457,653
<p>I was about to create a matrix like :</p> <pre><code> 33 12 23 42 11 32 43 22 33 − 1 1 1 0 0 1 1 12 1 − 1 1 0 0 1 1 23 1 1 − 1 1 1 0 0 42 1 1 1 − 1 1 0 0 11 0 0 1 1 − 1 1 1 32 0 0 1 1 1 − 1 1 43 1 1 ...
3
2016-09-12T19:42:14Z
39,458,160
<p>You're clearly asking for something outside of <code>numpy</code>. </p> <p>A <a href="https://docs.python.org/2/library/collections.html#defaultdict-objects" rel="nofollow"><code>defauldict</code></a> with the <em><code>default_factory</code></em> as <code>dict</code> gives a sense of the <em>2D dictionary</em> you...
3
2016-09-12T20:17:27Z
[ "python", "numpy" ]
is there a 2D dictionary in python?
39,457,653
<p>I was about to create a matrix like :</p> <pre><code> 33 12 23 42 11 32 43 22 33 − 1 1 1 0 0 1 1 12 1 − 1 1 0 0 1 1 23 1 1 − 1 1 1 0 0 42 1 1 1 − 1 1 0 0 11 0 0 1 1 − 1 1 1 32 0 0 1 1 1 − 1 1 43 1 1 ...
3
2016-09-12T19:42:14Z
39,458,273
<p>If I understand correctly you just want to label your row/columns. To stay within the numpy array framework, a simple solution would be to create a mapping between the labels and the array order. I am also going to assume that it is OK to convert the labels into strings as they can be anything (though integers would...
0
2016-09-12T20:24:33Z
[ "python", "numpy" ]
is there a 2D dictionary in python?
39,457,653
<p>I was about to create a matrix like :</p> <pre><code> 33 12 23 42 11 32 43 22 33 − 1 1 1 0 0 1 1 12 1 − 1 1 0 0 1 1 23 1 1 − 1 1 1 0 0 42 1 1 1 − 1 1 0 0 11 0 0 1 1 − 1 1 1 32 0 0 1 1 1 − 1 1 43 1 1 ...
3
2016-09-12T19:42:14Z
39,458,815
<p>Are you looking for a dictionary with pairs as keys?</p> <pre><code>d = {} d[33, 12] = 1 d[33, 23] = 1 # etc </code></pre> <p>Note that in python <code>d[a, b]</code> is just syntactic sugar for <code>d[(a, b)]</code></p>
1
2016-09-12T21:08:29Z
[ "python", "numpy" ]
is there a 2D dictionary in python?
39,457,653
<p>I was about to create a matrix like :</p> <pre><code> 33 12 23 42 11 32 43 22 33 − 1 1 1 0 0 1 1 12 1 − 1 1 0 0 1 1 23 1 1 − 1 1 1 0 0 42 1 1 1 − 1 1 0 0 11 0 0 1 1 − 1 1 1 32 0 0 1 1 1 − 1 1 43 1 1 ...
3
2016-09-12T19:42:14Z
39,458,901
<p>Another possibility is to use tuples as the dictionary keys</p> <pre><code>dict((33,12):1, (23,12):1, ...] </code></pre> <p><code>scipy.sparse</code> has a sparse matrix format that stores it's values in such a dictionary. With your values such a matrix would represent a 50x50 matrix with mostly 0 values, and jus...
1
2016-09-12T21:15:21Z
[ "python", "numpy" ]
Python extract italic content from html
39,457,658
<p>I am trying to extract 'Italic' Content from a pdf in python. I have converted the pdf to html so that I can use the italic tag to extract the text. Here is how the html looks like</p> <pre><code>&lt;br&gt;&lt;/span&gt;&lt;/div&gt;&lt;div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; lef...
2
2016-09-12T19:42:35Z
39,458,011
<p>Try this:</p> <pre><code>from bs4 import BeautifulSoup soup = BeautifulSoup(html) bTags = [] for i in soup.find_all('span', style=lambda x: x and 'Italic' in x): bTags.append(i.text) print bTags </code></pre> <p>Passing a function to the <code>style</code> argument will filter results by the result of that f...
2
2016-09-12T20:06:41Z
[ "python", "html", "italic" ]
Django No module named backendssocial.apps.django_app.context_processors
39,457,702
<p>I'm adding an authentication via facebook and when I run my localhost I'm getting this error in terminal:</p> <pre><code>xx-MacBook-Pro:bookstore xx$ python manage.py runserver /Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py:22: RemovedInDjango110Warning: SubfieldBase has been deprecated. U...
0
2016-09-12T19:45:10Z
39,457,758
<p>You are missing one comma in <code>TEMPLATES</code> variable:</p> <pre><code>'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'so...
1
2016-09-12T19:49:17Z
[ "python", "django", "facebook" ]
Python pandas: conditionally select a uniform sample from a dataframe
39,457,762
<p>Say I have a dataframe as such</p> <pre><code>category1 category2 other_col another_col .... a 1 a 2 a 2 a 3 a 3 a 1 b 10 b 10 b 10 b 11 b 11 b 11 </code></pre> <p>I want to obtain a sample from...
6
2016-09-12T19:49:44Z
39,460,259
<p>Trick is building up a balanced array. I provided a clumsy way of doing it. Then cycle through the groupby object sampling by referencing the balanced array.</p> <pre><code>def rep_sample(df, col, n, *args, **kwargs): nu = df[col].nunique() m = len(df) mpb = n // nu mku = n - mpb * nu fills = ...
1
2016-09-12T23:39:40Z
[ "python", "pandas", "dataframe", "uniform" ]
How to use regex to disallow non-digts but allow a dot in Python?
39,457,780
<p>I am new to regex and trying to remove all <strong>non-digts</strong> but keep the <strong>dot</strong> (<strong>.</strong>) of a string:</p> <pre><code>x = ['ABCD, EFGH ', ' 20.9&amp;dog; ', ' IJKLM /&gt;'] </code></pre> <p>So far I have tried the following:</p> <pre><code>&gt;&gt;&gt; x = re.sub("\D", "", x) 20...
0
2016-09-12T19:51:31Z
39,457,854
<p>Instead of using the class <code>\D</code> you can define your own class of characters using <code>[...]</code>, and invert that class using <code>[^...]</code>. Now just put all the digits <code>0-9</code> and the <code>.</code> into that class:</p> <pre><code>&gt;&gt;&gt; x = ['ABCD, EFGH ', ' 20.9&amp;dog; ', ' ...
2
2016-09-12T19:56:10Z
[ "python", "regex", "python-2.7" ]
How to use regex to disallow non-digts but allow a dot in Python?
39,457,780
<p>I am new to regex and trying to remove all <strong>non-digts</strong> but keep the <strong>dot</strong> (<strong>.</strong>) of a string:</p> <pre><code>x = ['ABCD, EFGH ', ' 20.9&amp;dog; ', ' IJKLM /&gt;'] </code></pre> <p>So far I have tried the following:</p> <pre><code>&gt;&gt;&gt; x = re.sub("\D", "", x) 20...
0
2016-09-12T19:51:31Z
39,457,859
<p>This is a simple requirement which can be made explicit:</p> <pre><code>for item in x: print re.sub(r'[^0-9.]', "", item) </code></pre>
1
2016-09-12T19:56:19Z
[ "python", "regex", "python-2.7" ]
How to use regex to disallow non-digts but allow a dot in Python?
39,457,780
<p>I am new to regex and trying to remove all <strong>non-digts</strong> but keep the <strong>dot</strong> (<strong>.</strong>) of a string:</p> <pre><code>x = ['ABCD, EFGH ', ' 20.9&amp;dog; ', ' IJKLM /&gt;'] </code></pre> <p>So far I have tried the following:</p> <pre><code>&gt;&gt;&gt; x = re.sub("\D", "", x) 20...
0
2016-09-12T19:51:31Z
39,457,866
<p>You want an inverted character class:</p> <pre><code>re.sub(r"[^\d.]", "", x) </code></pre> <p>Note that <code>[^0-9.]</code> and <code>[^\d.]</code> are not the same, because <code>\d</code> matches many more characters than just <code>0123456789</code>:</p> <pre><code>&gt;&gt;&gt; print(textwrap.fill( ... ""...
2
2016-09-12T19:56:48Z
[ "python", "regex", "python-2.7" ]
How to use regex to disallow non-digts but allow a dot in Python?
39,457,780
<p>I am new to regex and trying to remove all <strong>non-digts</strong> but keep the <strong>dot</strong> (<strong>.</strong>) of a string:</p> <pre><code>x = ['ABCD, EFGH ', ' 20.9&amp;dog; ', ' IJKLM /&gt;'] </code></pre> <p>So far I have tried the following:</p> <pre><code>&gt;&gt;&gt; x = re.sub("\D", "", x) 20...
0
2016-09-12T19:51:31Z
39,457,953
<p>All the answers have this issue of skipping DOT without making sure that DOT is actually part of a decimal number. Hence a string like <code>Mr.Bean</code> will remain <code>Mr.Bean</code> since DOT is is part of the negative character class (exclusion list).</p> <p>To fix tihs issue you can use this negative looka...
0
2016-09-12T20:03:06Z
[ "python", "regex", "python-2.7" ]
Python: Turn List of Tuples into Dictionary of Nested Dictionaries
39,457,792
<p>so I have a bit of an issue on my hands. I have a list of tuples (made up of a level number and message) which will eventually become an HTML list. My issues is that before this happens, I would like to turn the tuples values into a dictionary of nested dictionaries. So here is the example:</p> <pre><code># I have ...
2
2016-09-12T19:52:42Z
39,457,912
<p>Assuming you only have three levels, something like following would do:</p> <pre><code>tuple_list = [(1, 'line 1'), (2, 'line 2'), (3, 'line 3'), (1, 'line 4')] a_dict = {} for prio, key in tuple_list: if prio == 1: a_dict[key] = {} first_level = key if prio == 2: a_dict[first_leve...
0
2016-09-12T20:00:09Z
[ "python", "list", "python-3.x", "dictionary", "tuples" ]
Python: Turn List of Tuples into Dictionary of Nested Dictionaries
39,457,792
<p>so I have a bit of an issue on my hands. I have a list of tuples (made up of a level number and message) which will eventually become an HTML list. My issues is that before this happens, I would like to turn the tuples values into a dictionary of nested dictionaries. So here is the example:</p> <pre><code># I have ...
2
2016-09-12T19:52:42Z
39,458,557
<p>As I pointed out in a comment, you should STRONGLY consider changing your incoming data structure if you have any control at all over it. A sequential list of tuples is definitely not ideal for what you're doing here. However it is possible if you treat it like a tree. Let's build a (sane) data structure to parse th...
2
2016-09-12T20:47:27Z
[ "python", "list", "python-3.x", "dictionary", "tuples" ]
Alternative of threading.Timer?
39,457,850
<p>I have a producer-consumer pattern Queue, it consumes incoming events and schedule qualified events sending out in 5 seconds. I am using <code>threading.Timer()</code><a href="https://docs.python.org/2/library/sched.html" rel="nofollow">python document</a>to do it and everything was working fine.</p> <p>Recently, I...
0
2016-09-12T19:55:54Z
39,478,434
<p>Thanks for @dano 's comment about the 3rd party modules! Based on my work requirement, I didn't install them on the server. </p> <p>Instead of using <code>threading.Timer()</code>, I choose to use a Redis based Delay Queue, I found some helpful source online: <a href="http://www.saltycrane.com/blog/2011/11/unique-p...
0
2016-09-13T20:24:50Z
[ "python", "python-2.7", "timer", "python-multithreading" ]
Returning the words after the first hypen is found
39,457,881
<p>Suppose I have a list of items - <code>['test_item_A-engine-blade', 'test_item_A-engine-part-initial', 'test_prop_prep-default-set']</code></p> <p>and I am trying to grab the words after the first hypen is found such that the result should be as follows:</p> <ul> <li>test_item_A-engine-blade => engine_blade</li> ...
0
2016-09-12T19:58:21Z
39,457,934
<p>You can just use <a href="https://docs.python.org/3.5/library/stdtypes.html#str.split"><code>split</code></a> with a maximum number of one.</p> <pre><code>something.split('-', maxsplit=1) </code></pre>
5
2016-09-12T20:01:48Z
[ "python" ]
How can I import a different version of a python module?
39,457,963
<p>I need to run my python script under sklearn v0.17 and on the server they have sklearn v0.15 installed.</p> <p>So I downloaded the <code>scikit-learn-0.17</code> package into <code>/home/mydir/lib/python2.7/site-packages/</code> and installed the package.</p> <p>However when I goto other directories and tried to r...
0
2016-09-12T20:03:53Z
39,458,109
<p>Python Virtual Environments were made to fix this problem. Create a virtual environment by navigating to the directory of your project and enter the <code>pyvenv ./Env</code> command. Activate the environment on a linux system with <code>source ./Env/bin/activate</code>. Now you have a sandboxed python environment, ...
0
2016-09-12T20:13:58Z
[ "python", "python-2.7", "scikit-learn", "python-module" ]
How can I import a different version of a python module?
39,457,963
<p>I need to run my python script under sklearn v0.17 and on the server they have sklearn v0.15 installed.</p> <p>So I downloaded the <code>scikit-learn-0.17</code> package into <code>/home/mydir/lib/python2.7/site-packages/</code> and installed the package.</p> <p>However when I goto other directories and tried to r...
0
2016-09-12T20:03:53Z
39,458,120
<p>General advice here would be to use <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a>, it allows you to have isolated environments for all your python projects.</p> <p>So each of your project can use different scikit version. </p> <p>Tutorial: <a href="https://www.sitepoint.com/virtual-...
0
2016-09-12T20:14:22Z
[ "python", "python-2.7", "scikit-learn", "python-module" ]
How to Trigger Windows Task Schedule restart after fails with python script
39,458,024
<p>I have a python script that when I find an error I throw sys.exit(1). This results in the task scheduler showing a "(0x1)" comment under last run result. A successful run returns "The operation completed successfully. (0x0)". Unfortunately though this does not trigger the task to be run again even though under setti...
1
2016-09-12T20:07:49Z
39,460,520
<p>Given that the task scheduler's event history is enabled, you can add a trigger for each exit code for which the task should be restarted. Trigger "on an event" with a custom XML query. The trigger should probably be delayed by at least 30 seconds to throttle attempts to restart the task. </p> <p>Here's an example ...
1
2016-09-13T00:21:44Z
[ "python", "windows", "error-handling", "scheduled-tasks" ]
Comparing two different solutions to a quiz
39,458,061
<p>I've been going through a course on CS on Udemy, and got a quiz to solve.</p> <p>Here's what is says:</p> <blockquote> <p>Define a procedure, find_last, that takes as input two strings, a search string and a target string, and returns the last position in the search string where the target string appears, or...
1
2016-09-12T20:10:29Z
39,458,117
<p>No need to code anything, just use python built-in string "right find":</p> <pre><code>print('aaaa'.rfind('a')) </code></pre> <p>result: 3</p> <pre><code>print('bbbbb'.rfind('a')) </code></pre> <p>result: -1</p> <p>also works for "more-than-1-char" search strings of course</p> <pre><code>print('bbbxb'.rfind('b...
4
2016-09-12T20:14:20Z
[ "python", "algorithm" ]
Comparing two different solutions to a quiz
39,458,061
<p>I've been going through a course on CS on Udemy, and got a quiz to solve.</p> <p>Here's what is says:</p> <blockquote> <p>Define a procedure, find_last, that takes as input two strings, a search string and a target string, and returns the last position in the search string where the target string appears, or...
1
2016-09-12T20:10:29Z
39,459,740
<p>I think <strong>the main idea of the course is to learn algorithms</strong> and this exercise is good to start with (<em>regardless if the solution is not the most efficient way to resolve such problems in a current programming language</em>). So, their solution is better because they 'jump' during iteration, and y...
1
2016-09-12T22:33:13Z
[ "python", "algorithm" ]
Insert rows and add missing data
39,458,148
<p>I wonder if somebody could give a few pointers on how to proceed with the following. Being a newbie to Pandas, I feel at the moment my overall knowledge and skill level is not sufficient at the moment to be able to process the request I outline below. </p> <p>I have a pandas dataframe which has a list of some 2000...
5
2016-09-12T20:16:23Z
39,458,416
<p>I think you need first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a> and <a href="htt...
2
2016-09-12T20:35:42Z
[ "python", "pandas", "insert", null, "reindex" ]
Insert rows and add missing data
39,458,148
<p>I wonder if somebody could give a few pointers on how to proceed with the following. Being a newbie to Pandas, I feel at the moment my overall knowledge and skill level is not sufficient at the moment to be able to process the request I outline below. </p> <p>I have a pandas dataframe which has a list of some 2000...
5
2016-09-12T20:16:23Z
39,458,835
<p>try this:</p> <pre><code>In [220]: r = (df.reset_index() .....: .set_index(pd.to_datetime(df.Year.map(str) + '-' + df.Month.map(str).str.zfill(2) + '-01')) .....: .resample('MS') .....: ) In [221]: new = r.pad().drop(['Qty','Sales'],1).join(r.mean().replace(np.nan, 0)[['Qty','Sales']]) In [...
1
2016-09-12T21:10:55Z
[ "python", "pandas", "insert", null, "reindex" ]
How to serialize related models in Django Rest API?
39,458,189
<p>I have tried all the solutions. Still cannot resolve it. Here are the codes.</p> <p><strong><em>models.py</em></strong> </p> <pre><code>class Car(models.Model): car_name = models.CharField(max_length=250) car_description = models.CharField(max_length=250) def __str__(self): return self.car_na...
0
2016-09-12T20:19:39Z
39,458,674
<p>You need to define a related name on the ForeignKey to create the reverse reference.</p> <pre><code>class Owners(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, default=0, related_name='owners') </code></pre>
0
2016-09-12T20:56:58Z
[ "python", "django", "python-2.7", "rest", "django-rest-framework" ]
Using List/Tuple/etc. from typing vs directly referring type as list/tuple/etc
39,458,193
<p>What's the difference of using <code>List</code>, <code>Tuple</code>, etc. from <code>typing</code> module:</p> <pre><code>from typing import Tuple def f(points: Tuple): return map(do_stuff, points) </code></pre> <p>As opposed to referring to Python's types directly:</p> <pre><code>def f(points: tuple): ...
2
2016-09-12T20:19:59Z
39,458,225
<p><code>typing.Tuple</code> and <code>typing.List</code> are <a href="https://docs.python.org/3/library/typing.html#generics" rel="nofollow"><em>Generic types</em></a>; this means you can specify what type their <em>contents</em> must be:</p> <pre><code>def f(points: Tuple[float, float]): return map(do_stuff, poi...
8
2016-09-12T20:22:17Z
[ "python", "python-3.5", "typing", "type-hinting" ]
How to allow a tkinter window to be opened multiple times
39,458,318
<p>I am making a makeshift sign in system with python. Currently if you enter the correct password it brings up a new admin window. If you enter the wrong one it brings up a new window that says wrong password. If you exit out of one of those windows and then try to enter a password again it breaks. <code>tkinter.TclEr...
2
2016-09-12T20:28:16Z
39,458,522
<p>I don't know <code>tkinter</code> much but I could fix your code, I hope it's a proper fix.</p> <ol> <li>Create <code>Toplevel</code> windows not <code>Tk</code>. those are dialog windows, as opposed to <code>Tk</code> window which must be unique. Same look &amp; feel, same methods</li> <li>Create windows when need...
3
2016-09-12T20:44:30Z
[ "python", "tkinter" ]
Is there a way to append data to a hdfs file using Pydoop?
39,458,325
<p>I am trying to write contents of an object to a file in hdfs using python. For this, I have found a hdfs API implemented in python named Pydoop. Reading the API, I can easily use <code>dump()</code> method of pydoop to write contents to a file in hdfs path but have not seen any method like <code>append()</code> that...
0
2016-09-12T20:28:40Z
39,459,023
<p>Haven't used Pydoop, but this reads just like the Python API for appending to a regular file. </p> <pre><code>from pydoop import hdfs with hdfs.open('/path/to/file', 'a') as f: f.write('bla') </code></pre>
0
2016-09-12T21:24:52Z
[ "python", "hadoop", "hdfs" ]
How to call Python function from Node.JS
39,458,333
<p>I'm working on making a <a href="https://github.com/nfarina/homebridge" rel="nofollow">Homebridge</a> plugin for a project. <code>Homebridge</code> is a Node.JS server which I have running on a Raspberry Pi which emulates an Apple HomeKit Bridge.</p> <p>Using <a href="http://stackoverflow.com/questions/23450534/how...
0
2016-09-12T20:29:16Z
39,458,584
<p>You're getting that error because you're closing the input stream:</p> <pre><code>py.stdin.end(); </code></pre> <p>After a stream has been closed, you can no longer write to it like you are here: </p> <pre><code>py.stdin.write(JSON.stringify(data)); </code></pre> <p>If the Python program you're running accepts m...
1
2016-09-12T20:49:38Z
[ "javascript", "python", "node.js" ]
Is there a way to add close buttons to tabs in tkinter.ttk.Notebook?
39,458,337
<p>I want to add close buttons to each tab in <code>tkinter.ttk.Notebook</code>. I already tried adding image and react to click event but unfortunately <code>BitmapImage</code> does not have <code>bind()</code> method.</p> <p>How can I fix this code?</p> <pre><code>#!/usr/binenv python3 from tkinter import * from t...
0
2016-09-12T20:29:27Z
39,459,376
<p>One advantage of the themed (ttk) widgets is that you can create new widgets out of individual widget "elements". While not exactly simple (nor well documented), you can create a new "close tab" element add add that to the "tab" element. </p> <p>I will present one possible solution. I'll admit it's not particularly...
2
2016-09-12T21:55:14Z
[ "python", "tkinter" ]
Making a random coordinate generator
39,458,369
<p>This code was originally meant for user input, however I want it to randomly create a polygon rather than manually selecting points myself.<br> I'll probably make it a for loop, rather than a while loop so you don't need to mention that.</p> <pre><code>import pygame from pygame.locals import * from sys import exit ...
0
2016-09-12T20:32:19Z
39,458,508
<p>I think this </p> <pre><code>points = (str(randint(0,639)), str(randint(0,479))) </code></pre> <p>Should be written like so (the extra comma makes a tuple). You need to append to the <code>points</code> list rather than re-assign the variable. </p> <pre><code>points.append( (point1, point2,) ) </code></pre> <p>T...
0
2016-09-12T20:43:22Z
[ "python", "random", "coordinates" ]
Compare 2 Pandas dataframes, row by row, cell by cell
39,458,396
<p>I have 2 dataframes, <code>df1</code> and <code>df2</code>, and want to do the following, storing results in <code>df3</code>: </p> <pre><code>for each row in df1: for each row in df2: create a new row in df3 (called "df1-1, df2-1" or whatever) to store results for each cell(column) in df1: ...
2
2016-09-12T20:33:49Z
39,458,848
<p>So to continue the discussion in the comments, you can use vectorization, which is one of the selling points of a library like pandas or numpy. Ideally, you shouldn't ever be calling <code>iterrows()</code>. To be a little more explicit with my suggestion:</p> <pre><code># with df1 and df2 provided as above, an exa...
2
2016-09-12T21:12:13Z
[ "python", "pandas", "dataframe", "iterator", "iteration" ]
Matplotlib- How to make color fill bias towards max & min values?
39,458,426
<p><strong>The issue</strong></p> <p>I have a plot of correlation of two variables with most of the values close to either -1 or 1. I'm using a seismic colormap (red &amp; blue w/ white in the middle), but most of the plot is either dark blue (close to -1) or dark red (close to 1), showing little detail near min &amp;...
0
2016-09-12T20:36:43Z
39,458,843
<p>There is a keyword argument <strong>norm</strong> that you can use with <strong>pcolormesh</strong> in order to change the scale of the color mapping. Take a look at the <a href="http://matplotlib.org/devdocs/users/colormapnorms.html#symmetric-logarithmic" rel="nofollow">matplotlib documentation</a> for this. And th...
1
2016-09-12T21:12:06Z
[ "python", "matplotlib", "colors", "colormap" ]
store dictionary in pandas dataframe
39,458,806
<p>I want to store a a dictionary to an data frame</p> <pre><code>dictionary_example={1234:{'choice':0,'choice_set':{0:{'A':100,'B':200,'C':300},1:{'A':200,'B':300,'C':300},2:{'A':500,'B':300,'C':300}}}, 234:{'choice':1,'choice_set':0:{'A':100,'B':400},1:{'A':100,'B':300,'C':1000}}, 1876:{'choice':2,'choice_set'...
3
2016-09-12T21:07:26Z
39,459,076
<p>I think the following is pretty close, the core idea is simply to convert those dictionaries into json and relying on pandas.read_json to parse them. </p> <pre><code>dictionary_example={ "1234":{'choice':0,'choice_set':{0:{'A':100,'B':200,'C':300},1:{'A':200,'B':300,'C':300},2:{'A':500,'B':300,'C':300}}}, ...
3
2016-09-12T21:28:55Z
[ "python", "pandas", "dictionary" ]
error using Python Elasticserarch-py package
39,458,810
<p>So I am trying to create a connection to AWS ES. I have successfully connected to my S3 bucket in the same zone. However, when I try to connect to ES, I get this message every time.</p> <pre><code>Please install requests to use RequestsHttpConnection. </code></pre> <p>I have imported the correct module but nothi...
1
2016-09-12T21:08:05Z
39,473,127
<p>As per the documentation for <a href="http://elasticsearch-py.readthedocs.io/en/master/transports.html" rel="nofollow">elasticsearch-py</a>.</p> <blockquote> <p>Note that the RequestsHttpConnection requires requests to be installed.</p> </blockquote> <p>There is a need to explictly install the <a href="http://do...
1
2016-09-13T14:56:57Z
[ "python", "amazon-web-services", "elasticsearch", "amazon-elasticsearch" ]
Creating a Unittest
39,458,818
<p>Hey I'm pretty new to python and I'm trying to create a Unit test for some code and I'm running into a lot of trouble, to be honest I'm wondering if the code is even testable. </p> <pre><code>""" Core employee class """ class Employee(object): empCount = 0 def __init__(self, name, salary, debt, takehome): s...
-1
2016-09-12T21:08:47Z
39,458,977
<p>I think your class is testable. But the tests are trivial since you only have an ˋ__init__` method and a display method.</p> <p>The starting for unit testing is using <strong><a href="https://docs.python.org/2/library/unittest.html" rel="nofollow">unittest</a></strong> library.</p> <p>Write a single test function...
0
2016-09-12T21:20:43Z
[ "python", "python-2.7" ]
Django model reload_from_db() vs. explicitly recalling from db
39,458,820
<p>If I have an object retrieved from a model, for example:</p> <pre><code>obj = Foo.objects.first() </code></pre> <p>I know that if I want to reference this object later and make sure that it has the current values from the database, I can call:</p> <pre><code>obj.refresh_from_db() </code></pre> <p>My question is,...
1
2016-09-12T21:08:55Z
39,461,946
<p>Django sources are usually relatively easy to follow. If we look at the <a href="https://github.com/django/django/blob/master/django/db/models/base.py#L656" rel="nofollow">refresh_from_db() implementation</a>, at its core it is still using this same <code>Foo.objects.get(id=obj.id)</code> approach:</p> <pre><code>...
1
2016-09-13T03:50:38Z
[ "python", "django", "django-models" ]
How to select json data randomly
39,458,831
<p>I have following json file and I need a way to randomly select json data and prints its value. </p> <p><strong>json file :</strong></p> <pre><code>{ "base": [{"1": "add"},{"2": "act"}], "past": [{"add": "added"},{"act": "acted"}], "past-participle": [{"add": "added"},{"act": "acted"}], "s-es-ies": ...
3
2016-09-12T21:09:58Z
39,458,941
<p>Use <code>random.choice</code> supplying as choices the sequence contained for the selected <code>key</code>:</p> <pre><code>user_input = input('&gt; ') &gt; past list(choice(j[user_input]).values())[0] Out[177]: 'added' </code></pre> <p>Factor it in a function to make it more compact:</p> <pre><code>def random...
2
2016-09-12T21:18:26Z
[ "python", "json", "python-3.x" ]
Pandas: how to increment a column's cell value based on a list of ids
39,458,871
<p>I have a list of ids that correspond to the row of a data frame. From that list of ids, I want to increment a value of another column that intersects with that id's row.</p> <p>What I was thinking was something like this:</p> <pre><code>ids = [1,2,3,4] for id in ids: my_df.loc[my_df['id']] == id]['other_colum...
3
2016-09-12T21:13:37Z
39,458,910
<p>try this:</p> <pre><code>my_df.loc[my_df['id'].isin(ids), 'other_column'] += 1 </code></pre> <p>Demo:</p> <pre><code>In [233]: ids=[0,2] In [234]: df = pd.DataFrame(np.random.randint(0,3, (5, 3)), columns=list('abc')) In [235]: df Out[235]: a b c 0 2 2 1 1 1 0 2 2 2 2 0 3 0 2 1 4 0 1 2 In [...
3
2016-09-12T21:16:12Z
[ "python", "pandas", "dataframe" ]
Pandas: how to increment a column's cell value based on a list of ids
39,458,871
<p>I have a list of ids that correspond to the row of a data frame. From that list of ids, I want to increment a value of another column that intersects with that id's row.</p> <p>What I was thinking was something like this:</p> <pre><code>ids = [1,2,3,4] for id in ids: my_df.loc[my_df['id']] == id]['other_colum...
3
2016-09-12T21:13:37Z
39,458,914
<p>the ids are unique, correct? If so, you can directly place the <code>id</code> into the <code>df</code>:</p> <pre><code>ids = [1,2,3,4] for id in ids: df.loc[id,'column_name'] = id+1 </code></pre>
1
2016-09-12T21:16:31Z
[ "python", "pandas", "dataframe" ]
How to stop automatic resizing of frames
39,458,874
<p>I have three frames, but when a new label appears the frames automatically readjust to a new size. How do I stop the readjustment and have the size of each frame set and immutable.</p> <pre><code>#Import tkinter to make gui from tkinter import * from tkinter import ttk import codecs #Program that results when user...
0
2016-09-12T21:13:51Z
39,459,490
<p>The simplest solution in this specific case is to give the label with the text a fixed width. When you specify a fixed width for a label, tkinter will do it's best to honor that width (though a lot depends on how you place it on the screen with <code>pack</code>, <code>place</code> or <code>grid</code>).</p> <pre><...
0
2016-09-12T22:06:07Z
[ "python", "tkinter" ]
How to stop automatic resizing of frames
39,458,874
<p>I have three frames, but when a new label appears the frames automatically readjust to a new size. How do I stop the readjustment and have the size of each frame set and immutable.</p> <pre><code>#Import tkinter to make gui from tkinter import * from tkinter import ttk import codecs #Program that results when user...
0
2016-09-12T21:13:51Z
39,459,653
<p>Just add a <code>width</code> option to <code>ttk.Label(mainframe2, textvariable=result).grid(column=2, row=4, sticky=(W, E))</code>:<br/> So it will become like this:<br/> <code>ttk.Label(mainframe2, textvariable=result, width=20).grid(column=2, row=4, sticky=(W, E))</code></p>
0
2016-09-12T22:22:24Z
[ "python", "tkinter" ]
String instead of integer in finding "bob"
39,458,987
<p>My question code:</p> <pre><code>count = 0 for char in s: if char.startswith("bob"): count += 1 print ("Number of times bob occurs is: " + str(count)) </code></pre> <p>I have a good solution as followed:</p> <pre><code>count = 0 for i in range(len(s)): if s[i: i+3] == "bob" count +...
-1
2016-09-12T21:21:24Z
39,459,307
<p>Your first code doesn't work because</p> <pre><code>for char in s: </code></pre> <p>just sets <code>char</code> to individual characters in the string. So if <code>s = "bob is bob"</code>, <code>char</code> will be <code>"b"</code>, <code>"o"</code>, <code>"b"</code>, <code>"i"</code>, etc. None of those single-ch...
0
2016-09-12T21:49:43Z
[ "python" ]
String instead of integer in finding "bob"
39,458,987
<p>My question code:</p> <pre><code>count = 0 for char in s: if char.startswith("bob"): count += 1 print ("Number of times bob occurs is: " + str(count)) </code></pre> <p>I have a good solution as followed:</p> <pre><code>count = 0 for i in range(len(s)): if s[i: i+3] == "bob" count +...
-1
2016-09-12T21:21:24Z
39,459,320
<p>What is wrong with your first piece of code will become apparent with a print statement in the loop. The statement <code>for char in s</code> loops through each character in <code>s</code> and no character starts with the word <code>bob</code>.</p> <p>If you really want a <code>for something in something</code> typ...
0
2016-09-12T21:50:27Z
[ "python" ]
scikit ShuffleSplit raising pandas "IndexError: index N is out of bounds for axis 0 with size M"
39,459,006
<p>I'm trying to use a scikit's GridSearch to find the best alpha for a Lasso, and one of parameters I want it iterate is the cross validation split. So, I'm doing:</p> <pre><code># X_train := Pandas Dataframe with no index (auto numbered index) and 62064 rows # y_train := Pandas 1-column Dataframe with no index (auto...
0
2016-09-12T21:23:00Z
39,460,772
<p>You shouldn't be varying <code>cv</code> in the cross validation parameters grid, the idea is that you have a fixed cross-validation, and use this to grid search over other parameters, something like this:</p> <pre><code>m_model = grid_search.GridSearchCV(model, {'learning_rate':...
0
2016-09-13T01:01:07Z
[ "python", "pandas", "dataframe", "scikit-learn", "cross-validation" ]
Argparse: How to disallow some options in the presence of others - Python
39,459,015
<p>I have the following utility:</p> <pre><code>import argparse parser = argparse.ArgumentParser(description='Do some action.') parser.add_argument('--foo', '--fo', type=int, default=-1, help='do something foo') parser.add_argument('--bar', '--br', type=int, default=-1, help='do something bar') parser.add_argument('-...
2
2016-09-12T21:23:55Z
39,459,093
<p>You can create mutually-exclusive groups of options with <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow"><code>parser.add_mutually_exclusive_group</code></a>:</p> <pre><code>group = parser.add_mutually_exclusive_group() group.add_argument('--foo', '--fo', type=int, default=-1, help='do some...
1
2016-09-12T21:30:34Z
[ "python", "parsing", "command-line", "argparse" ]
TypeError: str object is not an iterator
39,459,121
<p>I have a file consisting of words, one word on each line. The file looks like this:</p> <pre><code>aaa bob fff err ddd fff err </code></pre> <p>I want to count the frequency of the pair of words which occur one after the other.</p> <p>For example,</p> <pre><code>aaa,bob: 1 bob,fff:1 fff,err:2 </code></pre> <p>a...
6
2016-09-12T21:32:36Z
39,459,149
<p>Your value <code>x</code> holds a string 'ddd/ccc/etc'. it has not next. <code>next()</code> belongs to the iterator and it used to get next element from the iterator. The correct way to call it is <code>it.next()</code></p> <pre><code>it=iter(content) for x in it: print x, it.next(); </code></pre> <p>But you ...
-1
2016-09-12T21:35:03Z
[ "python", "dictionary", "iterator", "generator" ]
TypeError: str object is not an iterator
39,459,121
<p>I have a file consisting of words, one word on each line. The file looks like this:</p> <pre><code>aaa bob fff err ddd fff err </code></pre> <p>I want to count the frequency of the pair of words which occur one after the other.</p> <p>For example,</p> <pre><code>aaa,bob: 1 bob,fff:1 fff,err:2 </code></pre> <p>a...
6
2016-09-12T21:32:36Z
39,459,152
<p><code>line</code>, like all <code>strs</code>, is an iter<strong>able</strong>, which means it has an <code>__iter__</code> method. But <code>next</code> works with iter<strong>ators</strong>, which have a <code>__next__</code> method (in Python 2 it's a <code>next</code> method). When the interpreter executes <code...
1
2016-09-12T21:35:24Z
[ "python", "dictionary", "iterator", "generator" ]
TypeError: str object is not an iterator
39,459,121
<p>I have a file consisting of words, one word on each line. The file looks like this:</p> <pre><code>aaa bob fff err ddd fff err </code></pre> <p>I want to count the frequency of the pair of words which occur one after the other.</p> <p>For example,</p> <pre><code>aaa,bob: 1 bob,fff:1 fff,err:2 </code></pre> <p>a...
6
2016-09-12T21:32:36Z
39,459,209
<p>As others mentioned, you can't use <code>next</code> on a line which is an string. You can use <code>itertools.tee</code> to create two independent iterator from your file object, then use <code>collections.Counter</code> and <code>zip</code> to create a counter object from the pairs of lines</p> <pre><code>from it...
0
2016-09-12T21:41:47Z
[ "python", "dictionary", "iterator", "generator" ]
TypeError: str object is not an iterator
39,459,121
<p>I have a file consisting of words, one word on each line. The file looks like this:</p> <pre><code>aaa bob fff err ddd fff err </code></pre> <p>I want to count the frequency of the pair of words which occur one after the other.</p> <p>For example,</p> <pre><code>aaa,bob: 1 bob,fff:1 fff,err:2 </code></pre> <p>a...
6
2016-09-12T21:32:36Z
39,459,338
<pre><code>from collections import Counter with open(file, 'r') as f: content = f.readlines() result = Counter((a, b) for a, b in zip(content[0:-1], content[1:])) </code></pre> <p>That will be a dictionary whose keys are the line pairs (in order) and whose values are the number of times that pair occurred.</p>
3
2016-09-12T21:52:02Z
[ "python", "dictionary", "iterator", "generator" ]
TypeError: str object is not an iterator
39,459,121
<p>I have a file consisting of words, one word on each line. The file looks like this:</p> <pre><code>aaa bob fff err ddd fff err </code></pre> <p>I want to count the frequency of the pair of words which occur one after the other.</p> <p>For example,</p> <pre><code>aaa,bob: 1 bob,fff:1 fff,err:2 </code></pre> <p>a...
6
2016-09-12T21:32:36Z
39,459,395
<p>As others said, <strong>line</strong> is a string and thus cannot be used with the <strong>next()</strong> method. Also you can't use a list as a key for the dictionary because they are hashable. You can use a tuple instead. A simple solution:</p> <pre><code>f=open(file,'r') content=f.readlines() f.close() dic={} ...
1
2016-09-12T21:57:12Z
[ "python", "dictionary", "iterator", "generator" ]
TypeError: str object is not an iterator
39,459,121
<p>I have a file consisting of words, one word on each line. The file looks like this:</p> <pre><code>aaa bob fff err ddd fff err </code></pre> <p>I want to count the frequency of the pair of words which occur one after the other.</p> <p>For example,</p> <pre><code>aaa,bob: 1 bob,fff:1 fff,err:2 </code></pre> <p>a...
6
2016-09-12T21:32:36Z
39,460,098
<p>You can use a 2 line <a href="https://docs.python.org/2.7/library/collections.html#collections.deque" rel="nofollow">deque</a> and a <a href="https://docs.python.org/2.7/library/collections.html#collections.Counter" rel="nofollow">Counter</a>:</p> <pre><code>from collections import Counter, deque lc=Counter() d=de...
1
2016-09-12T23:18:59Z
[ "python", "dictionary", "iterator", "generator" ]
TypeError: str object is not an iterator
39,459,121
<p>I have a file consisting of words, one word on each line. The file looks like this:</p> <pre><code>aaa bob fff err ddd fff err </code></pre> <p>I want to count the frequency of the pair of words which occur one after the other.</p> <p>For example,</p> <pre><code>aaa,bob: 1 bob,fff:1 fff,err:2 </code></pre> <p>a...
6
2016-09-12T21:32:36Z
39,460,918
<p>You just need to keep track of the previous line, a file object returns it own iterator so you don't need the <em>iter</em> or <em>readlines</em> at all, call <em>next</em> once at the very start to creating a variable <em>prev</em> then just keep updating <em>prev</em> in the loop:</p> <pre><code>from collection...
6
2016-09-13T01:23:22Z
[ "python", "dictionary", "iterator", "generator" ]
How does one configure a proxy upstream of browsermob on osx?
39,459,171
<p>I'm looking to configure an upstream proxy for browsermob, preferably programmatically from within a python or shell script.</p> <p>It doesn't look like the python bindings for browsermob include an upstream-proxy configuration command or method. Is there another method I can use?</p>
1
2016-09-12T21:37:13Z
39,482,388
<p>The python bindings do actually allow you to configure an upstream proxy. When creating a proxy using <code>create_proxy</code>, you can set the value of <code>httpProxy</code> to the IP address and port of the upstream proxy (see the <a href="https://github.com/AutomatedTester/browsermob-proxy-py/blob/master/browse...
1
2016-09-14T04:15:03Z
[ "python", "osx", "proxy", "browsermob" ]
Getting data from a site, which cant be found in main HTML file in Python
39,459,199
<p>I'am using python and making a request: <code>page = requests.get('http://www.finam.ru/profile/moex-akcii/aeroflot/news/?start-date=2016-01-01&amp;end-date=2016-12-31',auth=('user', 'pass'))</code></p> <p>I expect, that i will be able to find everything, that i can see, when i view the website. But as i dont know i...
2
2016-09-12T21:40:18Z
39,459,258
<p>Besides the source html, there is a JavaScript code running on the web site, which manipulate and change the DOM (the tree structure that you describe). When you request it via Python, the JavaScript code does not run so you can see only the initial html code. Doing such stuff called scraping , you can do it with to...
2
2016-09-12T21:45:34Z
[ "python", "html" ]
python pandas.Series.str.contains words with space
39,459,277
<p>I'm trying to find strings that contain either " internet ", " program ", " socket programming " in the pandas dataframe. </p> <pre><code>df.col_name.str.contains(" internet | program | socket programming ", case=False) </code></pre> <p>Is this right way to do so? or Do I need to escape space using \ and raw strin...
1
2016-09-12T21:47:20Z
39,459,419
<p>Here is a small demo:</p> <pre><code>In [250]: df Out[250]: txt 0 Internet 1 There is no Internet in this apartment 2 Program2 3 I am learning socket programming too In [251]: df.txt.str.contains(" internet | pr...
3
2016-09-12T21:58:42Z
[ "python", "regex", "pandas", "dataframe" ]
Setting up a result backend (rpc) with Celery in Django
39,459,290
<p>I am attempting to get a result backend working on my local machine for a project I'm working on but I am running into an issue.</p> <p>Currently I am trying to create a queue system in order for my lab to create cases. This is to prevent duplicate sequence numbers from being used. I am already using Celery for our...
0
2016-09-12T21:48:12Z
39,460,999
<p>If you want to keep your result, try this <a href="http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html#keeping-results" rel="nofollow">Keeping Results</a></p> <pre><code>app = Celery('proj', backend='amqp', broker='amqp://guest@localhost//') </code></pre> <h3>EDIT</h3> <blockquote...
1
2016-09-13T01:34:13Z
[ "python", "django", "celery" ]
When printing outputs an empty line appears before my outputs
39,459,312
<p>I have attempted to write a program which asks the user for a string and a number (On the same line) and then prints all possible combinations of the string up to the size of the number. The output format should be: All capitals, Each combination on each line, Length of combination(Shortest First) and in alphabetica...
1
2016-09-12T21:49:50Z
39,459,608
<p>Observe the line:</p> <pre><code>for L in range(0, k+1) # Notice that L is starting at 0. </code></pre> <p>Now, observe this line:</p> <pre><code>for pos in combinations(S, L) </code></pre> <p>So, we will have the following during our first iteration of the inner for loop:</p> <pre><code>for pos in combinations...
0
2016-09-12T22:17:37Z
[ "python", "combinations" ]
Have Pandas column containing lists, how to pivot unique list elements to columns?
39,459,321
<p>I wrote a web scraper to pull information from a table of products and build a dataframe. The data table has a Description column which contains a comma separated string of attributes describing the product. I want to create a column in the dataframe for every unique attribute and populate the row in that column wit...
6
2016-09-12T21:50:30Z
39,459,769
<p>How about something that places an 'X' in the feature column if the product has that feature.</p> <p>The below creates a list of unique features ('Steel', 'Red', etc.), then creates a column for each feature in the original df. Then we iterate through each row and for each product feature, we place an 'X' in the c...
0
2016-09-12T22:35:33Z
[ "python", "pandas", "numpy", "dataframe", "pivot" ]