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
I am trying to get binary data from text and converting to numpy arrays
37,452,031
<p>I am trying to get binary data from text and convert to numpy arrays. I tried these codes:</p> <pre><code>import numpy as np import matplotlib.pylab as pl '''a=open ('rawdata.txt ','r',) print (a.read()) a.close()''' data=np.genfromtxt ('rawdata.txt', delimiter=',') print (data) time =data [1:,][:,0] print (time) v...
3
2016-05-26T05:07:52Z
37,470,395
<p>Thank you guys for your answers. I finally got found the way:</p> <pre><code>import numpy as np import pylab as pl I=[] V=[] with open("rawdata.txt") as file: rawdata=[line.split()for line in file if not line.isspace()] data=np.array(rawdata) t=data[1:,0] I_b=data[1:,1] # I_b current in binary V...
1
2016-05-26T20:28:40Z
[ "python", "numpy", "matplotlib" ]
How to correct asyncio yield from in data_received
37,452,039
<p>I would make async request to database in data_received function, but i don't know how do it. I wrote simple HTTPServer with asyncio.sleep(2), but it doesn't work.</p> <pre><code>import time import asyncio class HTTPServer: def connection_made(self, transport): self.transport = transport pass ...
0
2016-05-26T05:08:11Z
37,456,884
<p>The "Protocol" you're using is from (quoting the documentation):</p> <blockquote> <p>18.5.4. Transports and protocols (callback based API)</p> </blockquote> <p>As explicitly told by the documentation, it's a "callback based API", which calls normal methods, and you can't change that, so wrapping <code>data_recei...
2
2016-05-26T09:32:58Z
[ "python", "python-3.x", "python-3.5", "httpserver", "python-asyncio" ]
creating a dic from a list of tuples where key takes a list of all available values in python3
37,452,089
<p>this is my code:</p> <pre><code>mylist=[('joe',120),('john',160),('abraham',250),('soo',250)] dic={} for i in mylist: if i[1] in dic: dic[i[1]].append(i[0]) else: dic[i[1]]=i[0] print(dic) </code></pre> <p>I expect:</p> <pre><code>dic={'120':['joe'], '160':['john'], '250':['abraham','soo...
2
2016-05-26T05:12:44Z
37,452,120
<p>When <code>i[1]</code> is not in the dictionary, you need to create a list object. Instead you are assigning just the string to that key:</p> <pre><code>dic[i[1]]=i[0] </code></pre> <p>If you wrap that in a list display your code works:</p> <pre><code>dic[i[1]] = [i[0]] # a list with i[0] as the only element </c...
3
2016-05-26T05:15:06Z
[ "python" ]
wxPython plot y-axis at specified x-coordinate
37,452,098
<p>This can be done by using matplotlib but I prefer to use wxPython.plot directly to keep it as simple as possible.</p> <p>Specifically, I'm trying to create a plot with a bottom x-axis and right y-axis.</p> <p>How would I do this?</p> <p>My initial idea is to inherit from plot and re-code the y-axis drawing. But, ...
0
2016-05-26T05:13:26Z
37,464,243
<p>Using the matplotlib is easy in python and have much more useful resources than wx, you can use this code above:</p> <pre><code> from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas class FigurePanel(wx.Panel): def __init__(self, parent): ...
0
2016-05-26T14:48:28Z
[ "python", "plot", "wxpython" ]
Django - dynamic form creation from random db entries
37,452,128
<p>This is an oversimplified example of what am I trying to achieve. Let's say I have these two models:</p> <pre><code>class Question(models.Model): text = models.CharField(max_length=255) class Answer(models.Model): text = models.CharField(max_length=255) question = models.ForeignKey(Question) </code></p...
0
2016-05-26T05:16:17Z
37,452,360
<p><a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#django.db.models.query.QuerySet.order_by" rel="nofollow">Random ordering</a>: </p> <pre><code>questions = Question.objects.all().order_by('?')[:3] </code></pre> <p>To validate form, it hink, you need restore same queryset with something like:</p>...
1
2016-05-26T05:33:25Z
[ "python", "django", "forms", "django-forms", "django-validation" ]
Search and print a line in every file in directory using glob.glob
37,452,206
<p>I have a folder on my desktop with 200+ txt files. I want to print line number 1050.539 in every file. Here is what I have:</p> <pre><code>import glob f=glob.glob('/Users/me/Desktop/Final/matched/ipmatches/*.txt') for line in f: if '1050.539' in line: print line </code></pre>
1
2016-05-26T05:22:06Z
37,452,295
<p>Glob only returns a list of file paths, you still have to open the files and read them.</p> <pre><code>import glob filesList = glob.glob('/Users/me/Desktop/Final/matched/ipmatches/*.txt') for fileName in filesList: with open(fileName, "r") as f: for line in f: if '1050.539' in line: ...
3
2016-05-26T05:27:55Z
[ "python", "canopy" ]
SSL Handshake failures with client and server
37,452,243
<p>So I'm building a client on Python and a server on Java to communicate and transfer files and strings. I'm thinking that the first thing I would have to do (besides connect the Server and Client) is complete the SSL Handshake. The following is my Python client code and Java server code that I have implemented:</p> ...
1
2016-05-26T05:24:30Z
37,452,804
<blockquote> <p>javax.net.ssl.SSLHandshakeException: no cipher suits in common</p> </blockquote> <p>This means that the server supports only ciphers the client does not support, i.e. no overlap and thus no common cipher which can be used for authentication and encryption.</p> <p>Given the source code of your server...
0
2016-05-26T06:07:01Z
[ "java", "python", "ssl", "sslhandshakeexception" ]
SSL Handshake failures with client and server
37,452,243
<p>So I'm building a client on Python and a server on Java to communicate and transfer files and strings. I'm thinking that the first thing I would have to do (besides connect the Server and Client) is complete the SSL Handshake. The following is my Python client code and Java server code that I have implemented:</p> ...
1
2016-05-26T05:24:30Z
37,452,850
<p>SSLV3 has been deprecated due to security weaknesses. Your client is trying to use the SSLV3 protocol while the server doesn't even recognise it.</p> <p>You can either :</p> <ul> <li>Set up the server to allow SSLV3 (not what I would recommend)</li> <li>Configure your socket in your python client to explicitly not...
0
2016-05-26T06:09:40Z
[ "java", "python", "ssl", "sslhandshakeexception" ]
Python \matplotlib: 3D, animated, and scatter plot
37,452,387
<p>I am almost new to Python... I have searched online and found a 2D animating python/matplotlib and it is working very well. here is the code</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np def _update_plot(i, fig, scat): scat.set_offsets(([0, i],[50, i...
1
2016-05-26T05:35:55Z
37,452,626
<p>change this <code>scat = plt.scatter(x,y,z, c='r', marker='o')</code> to </p> <pre><code>scat = ax.scatter(x,y,z, c='r', marker='o') </code></pre> <p><a href="http://i.stack.imgur.com/2AwHS.png" rel="nofollow"><img src="http://i.stack.imgur.com/2AwHS.png" alt="enter image description here"></a></p>
1
2016-05-26T05:53:25Z
[ "python", "matplotlib" ]
Generate sphinx documentation from Python and C
37,452,460
<p>I have a Python package that includes C code compiled into <code>.so</code>. In my Python code, I have docstrings. In my C code, I also have docstrings. Will <code>sphinx</code> be also sensitive to the docstrings given in the C source code, so that I can generate documentation automatically?</p>
0
2016-05-26T05:41:27Z
37,452,844
<p>Yes, assuming you mean docstrings that are available to the python interpreter as part of a compiled module. For example:</p> <pre><code>static PyMethodDef methods[] = { ... {"convolve", Pconvolve, METH_VARARGS, "convolve(xi,yi,x,dx,y): compute convolution of width dx[k] at points x[k],\nret...
1
2016-05-26T06:09:21Z
[ "python", "c", "python-sphinx" ]
Sqlalchemy array_length function
37,452,462
<p>Does SQLALCHEMY has a function to be used in queries for array_length?</p> <p>ie: </p> <pre><code>ssn.query(models.MedicationLog.dose_date, func.array_length(models.MedicationLog. dose_taken_times).label('dose_taken_times')) </code></pre>
1
2016-05-26T05:41:32Z
37,454,391
<p>Fixed it with using max and array_length</p> <pre><code>data = ssn.query(models.MedicationLog.dose_date, func.sum(func.array_length( models.MedicationLog.dose_taken_times, ARRAY_DEPTH )).label('dose_taken_times')).order_by(models.Medicat...
1
2016-05-26T07:35:38Z
[ "python", "postgresql", "sqlalchemy", "flask-sqlalchemy" ]
How to convert CSV to nested JSON(upto level 3) in Python
37,452,480
<p>I'm having the following data in CSV format.</p> <pre><code>id,category,sub_category,sub_category_type,count 0,fruits,citrus,lemon,30 1,fruits,citrus,lemon,40 2,fruits,citrus,lemon,50 3,fruits,citrus,grapefruit,20 4,fruits,citrus,orange,40 5,fruits,citrus,orange,10 6,fruits,berries,blueberry,20 7,fruits,berries,str...
1
2016-05-26T05:42:48Z
37,452,481
<p>The following code is inspired from <a href="https://github.com/andrewheekin/csv2flare.json/blob/master/csv2flare.json.py" rel="nofollow">this</a> github link. This code will help us in converting CSV upto level 3 nested JSON</p> <pre><code>import pandas as pd import json df = pd.read_csv('data.csv') # choose co...
0
2016-05-26T05:42:48Z
[ "python", "json", "csv", "pandas" ]
Convert python list to HTML table
37,452,589
<p>I am a novice coder and am not able to figure out my mistake here... I have a text that looks like this:</p> <pre><code>AAA,48,48,0,0,0,0,0,0,0,0,0 BBB,30,24,6,0,6,0,0,0,0,0,0 </code></pre> <p>I want to write it to a HTML table. The code for that is this:</p> <pre><code>temp_lines=ftemp.readlines(); for line in t...
-1
2016-05-26T05:51:08Z
37,452,770
<p>Consider the <a href="https://docs.python.org/2/library/stdtypes.html" rel="nofollow">following</a>:</p> <pre><code>For example, ' 1 2 3 '.split() returns ['1', '2', '3'] </code></pre> <p>you are trying to do this str(['1', '2', '3'])</p> <p>what happens when you try and concatenate:</p> <pre><code>"some htm...
0
2016-05-26T06:04:51Z
[ "python", "html" ]
Split string based on certain words and remove certain special characters in Python
37,452,810
<p>I have a list of tuples with strings. I would like to split up the string into smaller strings based on certain delimiter and remove certain characters.</p> <pre><code>item_list = [('apple OR orange AND NOT pineapple'), ((sugar and salt) or (pepper and vinegar)),..] # this is how each of the strings inside the tup...
2
2016-05-26T06:07:15Z
37,453,028
<pre><code>str1 = 'apple OR orange AND NOT pineapple' str2 = '(sugar and salt) or (pepper and vinegar)' def spliter(line): dim = ['AND', 'and', 'OR', 'or', 'NOT', 'not'] remove = ['[', ']', '(', ')'] for word in remove: line = line.replace(word,"") for word in dim: word = " "+word+" "...
0
2016-05-26T06:21:35Z
[ "python", "regex", "split" ]
Split string based on certain words and remove certain special characters in Python
37,452,810
<p>I have a list of tuples with strings. I would like to split up the string into smaller strings based on certain delimiter and remove certain characters.</p> <pre><code>item_list = [('apple OR orange AND NOT pineapple'), ((sugar and salt) or (pepper and vinegar)),..] # this is how each of the strings inside the tup...
2
2016-05-26T06:07:15Z
37,453,039
<p>Rather than splitting on stop words, split on spaces and filter out the stop words. You can remove the punctuation from the individual words with replace.</p> <p>For example:</p> <pre><code>stoplist = set(('AND', 'OR', 'NOT')) cleaned = [s.replace('(','').replace(')','') for s in item.split() ...
0
2016-05-26T06:22:05Z
[ "python", "regex", "split" ]
Split string based on certain words and remove certain special characters in Python
37,452,810
<p>I have a list of tuples with strings. I would like to split up the string into smaller strings based on certain delimiter and remove certain characters.</p> <pre><code>item_list = [('apple OR orange AND NOT pineapple'), ((sugar and salt) or (pepper and vinegar)),..] # this is how each of the strings inside the tup...
2
2016-05-26T06:07:15Z
37,453,057
<p>You can use <a href="https://docs.python.org/2/library/stdtypes.html#str.translate" rel="nofollow"><code>translate</code></a> to remove the unwanted characters and then <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>split</code></a> to get the words. Once you have the words ...
0
2016-05-26T06:23:11Z
[ "python", "regex", "split" ]
Split string based on certain words and remove certain special characters in Python
37,452,810
<p>I have a list of tuples with strings. I would like to split up the string into smaller strings based on certain delimiter and remove certain characters.</p> <pre><code>item_list = [('apple OR orange AND NOT pineapple'), ((sugar and salt) or (pepper and vinegar)),..] # this is how each of the strings inside the tup...
2
2016-05-26T06:07:15Z
37,453,059
<p><em>Python Code</em></p> <p>You can use <code>re.split</code> with <code>strip</code> like (<em>assuming there can be spaces in middle of word</em>)</p> <pre><code>&gt;&gt;&gt; item_list = [('apple OR ora nge AND NOT pineapple'), ('(sugar and salt) or (pepper and vinegar)')] &gt;&gt;&gt; [[x.strip() for x in re.sp...
1
2016-05-26T06:23:11Z
[ "python", "regex", "split" ]
Split string based on certain words and remove certain special characters in Python
37,452,810
<p>I have a list of tuples with strings. I would like to split up the string into smaller strings based on certain delimiter and remove certain characters.</p> <pre><code>item_list = [('apple OR orange AND NOT pineapple'), ((sugar and salt) or (pepper and vinegar)),..] # this is how each of the strings inside the tup...
2
2016-05-26T06:07:15Z
37,453,681
<p>Here's another take using list comprehensions:</p> <pre><code>item_list = [('apple OR orange AND NOT pineapple'), ('(sugar and salt) or (pepper and vinegar)')] delimeters = ['OR','AND','NOT','and','or','not'] [[i.replace('(','').replace(')','') for i in x.split() if i not in delimeters] for x in item_list] </code><...
1
2016-05-26T06:58:33Z
[ "python", "regex", "split" ]
Returns a copy of the list with the first number of items reversed
37,452,990
<pre><code>list1 = ['e', 'd', 'u', 'd'] list2 = ['m', 'o', 'b', 'b', 'e', 'd'] def reverse(list, number): number = (my_list[0]) for i in my_list: my_list = str(my_list[number]) + str(i) return my_list </code></pre> <p>Output should be:</p> <pre><code>[d,u,d,e] [b,o,m,b,e,d] </code></pre>
0
2016-05-26T06:19:16Z
37,453,101
<pre><code>&gt;&gt;&gt; list1 = ['e', 'd', 'u', 'd'] &gt;&gt;&gt; list2 = ['m', 'o', 'b', 'b', 'e', 'd'] &gt;&gt;&gt; def reverse(L, num): ... return L[:num][::-1] + L[num:] ... &gt;&gt;&gt; reverse(list1, 4) ['d', 'u', 'd', 'e'] &gt;&gt;&gt; reverse(list2, 3) ['b', 'o', 'm', 'b', 'e', 'd'] </code></pre> <p>Using...
0
2016-05-26T06:25:41Z
[ "python", "python-3.x" ]
Returns a copy of the list with the first number of items reversed
37,452,990
<pre><code>list1 = ['e', 'd', 'u', 'd'] list2 = ['m', 'o', 'b', 'b', 'e', 'd'] def reverse(list, number): number = (my_list[0]) for i in my_list: my_list = str(my_list[number]) + str(i) return my_list </code></pre> <p>Output should be:</p> <pre><code>[d,u,d,e] [b,o,m,b,e,d] </code></pre>
0
2016-05-26T06:19:16Z
37,453,475
<p>you can try:</p> <pre><code>&gt;&gt;&gt; def reverse(l,num): return [l[n] for n in range(num-1,-1,-1)] + l[num:] &gt;&gt;&gt; list1 = ['e', 'd', 'u', 'd'] &gt;&gt;&gt; list2 = ['m', 'o', 'b', 'b', 'e', 'd'] &gt;&gt;&gt; reverse(list1,4) ['d', 'u', 'd', 'e'] &gt;&gt;&gt; reverse(list2,3) ['b', 'o', 'm', 'b', 'e...
0
2016-05-26T06:47:37Z
[ "python", "python-3.x" ]
Python format function
37,452,997
<p>I have a value formatter</p> <pre><code>def formatter(value): return '{:.8f}'.format(value) </code></pre> <p>but instead of always returning to 8 decimal places I want to return to max of 8 decimal places so.</p> <pre><code>input | desired_output 100 | 100 100.01...
0
2016-05-26T06:19:46Z
37,453,058
<p>You can do it like this:</p> <pre><code>'{:^&lt;stringwidth&gt;.8f}'.format(value).rstrip('0').rstrip('.') </code></pre> <p>where stringwidth is the width of your desired output wherein the value should be centered.</p>
0
2016-05-26T06:23:11Z
[ "python", "string", "format" ]
Python format function
37,452,997
<p>I have a value formatter</p> <pre><code>def formatter(value): return '{:.8f}'.format(value) </code></pre> <p>but instead of always returning to 8 decimal places I want to return to max of 8 decimal places so.</p> <pre><code>input | desired_output 100 | 100 100.01...
0
2016-05-26T06:19:46Z
37,457,456
<p>The first solution doesn't work if the <code>stringwidth</code> is greater than the number of characters that makes your numbers, because it adds spaces around the string and the <code>rstrip</code> doesn't have any effect.</p> <p>For it to work, first you should round it (and strip, if necessary), and then, as the...
0
2016-05-26T09:56:59Z
[ "python", "string", "format" ]
default argument in bound function
37,453,047
<p>I'm developing a python script which sends text data to a zebra labelprinter. There's one bound function called "zebra_line" and you have to fill in x, y, text and font variables.</p> <pre><code> zebra_line = "^FO{x},{y}^A0,N,{font}^FH^FD{text}^FS".format template = "^XA\n" template += "^CI28\n" tem...
0
2016-05-26T06:22:44Z
37,453,210
<p>Simply define your own wrapper function. </p> <p>(not sure if there'll be a conflict with the named parameters and the function parameters, but you get the idea) </p> <pre><code>def my_zebra_line(x, y, text): zebra_line(x=x,y=y, text=text, font=35) template += my_zebra_line(30,700, "Test") </code></pre> <p>T...
0
2016-05-26T06:32:26Z
[ "python" ]
default argument in bound function
37,453,047
<p>I'm developing a python script which sends text data to a zebra labelprinter. There's one bound function called "zebra_line" and you have to fill in x, y, text and font variables.</p> <pre><code> zebra_line = "^FO{x},{y}^A0,N,{font}^FH^FD{text}^FS".format template = "^XA\n" template += "^CI28\n" tem...
0
2016-05-26T06:22:44Z
37,453,241
<p>Yes it is, however, not with an existing function. You can write a wrapper function, or you could use <a href="https://docs.python.org/2/library/functools.html#functools.partial" rel="nofollow"><code>functools.partial()</code></a> and supply a default argument for <code>font</code>:</p> <pre><code>from functools im...
3
2016-05-26T06:34:32Z
[ "python" ]
default argument in bound function
37,453,047
<p>I'm developing a python script which sends text data to a zebra labelprinter. There's one bound function called "zebra_line" and you have to fill in x, y, text and font variables.</p> <pre><code> zebra_line = "^FO{x},{y}^A0,N,{font}^FH^FD{text}^FS".format template = "^XA\n" template += "^CI28\n" tem...
0
2016-05-26T06:22:44Z
37,453,270
<p>It is possible. Here is the code that would do this for you:</p> <pre><code>from functools import partial zebra_line = partial(zebra_line, font=35) </code></pre> <p>Now, you can call <code>zebra_line</code> like this:</p> <pre><code>zebra_line(x=30,y=700, text="Test") </code></pre>
1
2016-05-26T06:36:17Z
[ "python" ]
Why Do I get: TypeError: choice() takes 2 positional arguments but 4 were given?
37,453,071
<p>I have a problem with random.choice which I can't understand. I pass 3 arguments to the function which is allowed to have 4 (<a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.choice.html" rel="nofollow">http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.choice.html...
0
2016-05-26T06:24:11Z
37,453,929
<p>the random.choice() only takes one list or tuple as a parameter </p> <pre><code>&gt;&gt;&gt; print random.choice( [1,2,3,4,5] ) 2 </code></pre> <p><a href="https://docs.python.org/2/library/random.html" rel="nofollow">https://docs.python.org/2/library/random.html</a></p>
-1
2016-05-26T07:12:10Z
[ "python", "random", "choice" ]
Why Do I get: TypeError: choice() takes 2 positional arguments but 4 were given?
37,453,071
<p>I have a problem with random.choice which I can't understand. I pass 3 arguments to the function which is allowed to have 4 (<a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.choice.html" rel="nofollow">http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.choice.html...
0
2016-05-26T06:24:11Z
37,453,990
<p>As you clarified in the comments, you are using <code>import random</code> which imports Python's random library. </p> <p>You should use <code>from numpy import random</code>, which will import Numpy's <code>random.choice</code> which is the one that you expect.</p>
4
2016-05-26T07:15:58Z
[ "python", "random", "choice" ]
change column values in CSV using python
37,453,119
<p>Let say this in the input CSV file.</p> <p><a href="https://i.stack.imgur.com/lkxwq.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/lkxwq.jpg" alt="enter image description here"></a></p> <p>I would like to go over the <code>Babys</code> column and change it to increasing number by 1.</p> <p>what i did is ...
-2
2016-05-26T06:27:12Z
37,453,803
<p>You can use python <code>pandas</code> to increase the column number by <code>n</code>:</p> <pre><code>import pandas data_df = pandas.read_csv('input.csv') data_df = data_df['age'].apply(lambda x: x+n) print data_df </code></pre> <p>for adding <code>1</code> replace <code>n</code> by <code>1</code>.</p>
1
2016-05-26T07:05:23Z
[ "python", "csv", "row" ]
change column values in CSV using python
37,453,119
<p>Let say this in the input CSV file.</p> <p><a href="https://i.stack.imgur.com/lkxwq.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/lkxwq.jpg" alt="enter image description here"></a></p> <p>I would like to go over the <code>Babys</code> column and change it to increasing number by 1.</p> <p>what i did is ...
-2
2016-05-26T06:27:12Z
37,454,020
<pre><code> v = open(input.csv) r=csv.reader(v) numline = len(v.readlines()) print (numline) for row in r: if row["Baby"] == "Baby": for i in range (1, numline): print("test") </code></pre> <p>what i did is to count how many row there are in the file, and run a fo...
0
2016-05-26T07:17:30Z
[ "python", "csv", "row" ]
change column values in CSV using python
37,453,119
<p>Let say this in the input CSV file.</p> <p><a href="https://i.stack.imgur.com/lkxwq.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/lkxwq.jpg" alt="enter image description here"></a></p> <p>I would like to go over the <code>Babys</code> column and change it to increasing number by 1.</p> <p>what i did is ...
-2
2016-05-26T06:27:12Z
37,456,887
<p>It can be done very easily when using <a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="nofollow">pandas</a> module </p> <p>import pandas as pd</p> <pre><code># read/parse CSV into pandas data frame df = pd.read_csv('input.csv', delim_whitespace=True) </code></pre> <p>Output:</p> <pre><code>I...
0
2016-05-26T09:33:06Z
[ "python", "csv", "row" ]
firing a sequence of parallel tasks
37,453,224
<p>For this dask code:</p> <pre><code>def inc(x): return x + 1 for x in range(5): array[x] = delay(inc)(x) </code></pre> <p>I want to access all the elements in <code>array</code> by executing the delayed tasks. But I can't call <code>array.compute()</code> since <code>array</code> is not a function. If I do</p...
1
2016-05-26T06:33:10Z
37,454,854
<p>It's easy to tell if things are executing in parallel if you force them to take a long time. If you run this code:</p> <pre><code>from time import sleep, time from dask import delayed start = time() def inc(x): sleep(1) print('[inc(%s): %s]' % (x, time() - start)) return x + 1 array = [0] * 5 for x i...
0
2016-05-26T07:56:56Z
[ "python", "dask" ]
firing a sequence of parallel tasks
37,453,224
<p>For this dask code:</p> <pre><code>def inc(x): return x + 1 for x in range(5): array[x] = delay(inc)(x) </code></pre> <p>I want to access all the elements in <code>array</code> by executing the delayed tasks. But I can't call <code>array.compute()</code> since <code>array</code> is not a function. If I do</p...
1
2016-05-26T06:33:10Z
37,463,379
<p>You can use the <code>dask.compute</code> function to compute many delayed values at once</p> <pre><code>from dask import delayed, compute array = [delayed(inc)(i) for i in range(5)] result = compute(*array) </code></pre>
0
2016-05-26T14:12:25Z
[ "python", "dask" ]
I need to change the format of the current Dataframe. How should i do this?
37,453,247
<p>I have a dataframe as below:</p> <pre><code>In [14]: grouped_data Out[14]: monthyear Facility Date Yield 0 Dec 15 CCM1 2015-12-01 2550.000000 1 Feb 16 CCM1 2016-02-01 4250.000000 2 Jan 16 CCM2 2016-01-01 1540.000000 3 Jan 16 CCM3 2016-01-01 6800.000000 4 Nov 15 ...
1
2016-05-26T06:34:46Z
37,453,290
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p> <pre><code>print (df.pivot_table(index=['monthyear','Date'], columns='Facility', values='Yield', fill_value...
1
2016-05-26T06:37:55Z
[ "python", "python-2.7", "pandas" ]
Where does the difference in size come from?
37,453,275
<p>I created a trie of sorts to store all the words (not definitions) in the English dictionary. The point of it was so that I can get all the words that only contain letters within a given range. </p> <p>The text file containing all the words is about 2.7 mb, but after creating the tree and writing it to a file using...
2
2016-05-26T06:36:42Z
37,453,820
<p>Nodes of a trie are huge as they store a link for all possible next letters. As you can see in the code, every node holds a list of 26 links (children).</p> <p>More compact schemes are possible (<a href="https://en.wikipedia.org/wiki/Trie#Compressing_tries">https://en.wikipedia.org/wiki/Trie#Compressing_tries</a>),...
5
2016-05-26T07:06:05Z
[ "python", "algorithm", "data-structures" ]
Filter options for sniff function in scapy
37,453,283
<p>I'm working on a scapy based tool where at a point I need to sniff a packet based on protocol and the ip address of the destination</p> <p>I'd like to know about the ways in which filter option in sniff() function can be used. I tried using format in documentation but most of the times it results in problems like t...
0
2016-05-26T06:37:23Z
37,453,842
<p><code>sniff()</code> uses Berkeley Packet Filter (BPF) <a href="http://biot.com/capstats/bpf.html" rel="nofollow">syntax</a> (the same one than <code>tcpdump</code>), here are some examples:</p> <p>Packets from or to host:</p> <pre><code>host x.x.x.x </code></pre> <p>Only TCP SYN segments:</p> <pre><code>tcp[tcp...
1
2016-05-26T07:07:20Z
[ "python", "linux", "networking", "ethernet", "scapy" ]
SaltStack diff of minion state using Python
37,453,549
<p>I am writing custom wrapper for SaltStack in python, I couldn't figure from the Salt documentation any way that I can get the diff of state of a minion. </p> <p>What I mean is when we run the state from CLI, it shows the diff in different colors and I am trying to show only the difference, not the whole.</p> <p>CL...
0
2016-05-26T06:51:53Z
37,475,538
<p>Are you looking for the history of changes and want to store them in a database?</p> <p>The matching page is this: <a href="https://docs.saltstack.com/en/latest/topics/jobs/job_cache.html" rel="nofollow">https://docs.saltstack.com/en/latest/topics/jobs/job_cache.html</a></p> <blockquote> <p>The Salt Master maint...
2
2016-05-27T05:33:56Z
[ "python", "salt-stack" ]
SaltStack diff of minion state using Python
37,453,549
<p>I am writing custom wrapper for SaltStack in python, I couldn't figure from the Salt documentation any way that I can get the diff of state of a minion. </p> <p>What I mean is when we run the state from CLI, it shows the diff in different colors and I am trying to show only the difference, not the whole.</p> <p>CL...
0
2016-05-26T06:51:53Z
38,176,877
<p>Using the python client, you can just add "test=true" as a kwarg to your localclient.cmd().</p> <p><a href="https://docs.saltstack.com/en/2015.8/ref/clients/index.html#salt-s-client-interfaces" rel="nofollow">https://docs.saltstack.com/en/2015.8/ref/clients/index.html#salt-s-client-interfaces</a></p> <p>Does that ...
0
2016-07-04T04:15:57Z
[ "python", "salt-stack" ]
Converting python long input to pseudo code
37,453,660
<pre><code>example = example + str(i + 1) + ": " + input("Example: ") + "\n" </code></pre> <p>the code above is giving me trouble converting it to pseudo code. I have tried doing something like : take user input for the example, add the example number at the start. Store it in a string on separate lines.</p> <p>What ...
0
2016-05-26T06:57:45Z
37,453,867
<p>Assuming <code>example = ""</code> and you are looping over some <code>i</code> value, and rewriting like so </p> <pre><code>example += str(i + 1) + ": " + input("Example: ") + "\n" </code></pre> <p>You can say "append a new line starting with the next number in the sequence followed by user input" </p> <p>In ter...
1
2016-05-26T07:08:50Z
[ "python", "pseudocode" ]
Python Pyramid gzip renderer
37,453,665
<p>I have a web application written with pyramid frameworks. One of my views is taking three seconds to be downloaded at the client side.<br> I want it to be served as a gzip file, is it possible to it using a build-in feature of pyramid?</p>
1
2016-05-26T06:57:56Z
37,616,784
<p>The question here does not discuss <em>why</em> it is slow and <em>if</em> 3 seconds is acceptable. Compressing may add further delay. Instead, the author should show source code in the question and then people can suggest how to make it faster.</p> <p>Pyramid has, however, buildin feature called <code>encode_conte...
1
2016-06-03T14:17:35Z
[ "python", "web-applications", "gzip", "pyramid" ]
Django User Update Form and View
37,453,821
<p>I am very early on in my Django/Python development journey, most things I have been able to slowly figure out after a few hours/days of head scratching and trial/error. I now have the commonly asked question that I cannot get working correctly:</p> <p><strong>How Do I Create a User Profile Update View/Form?</strong...
0
2016-05-26T07:06:09Z
37,454,482
<p>There's nothing specific to users here. You have two problems: the first is because of your urls. Your profile view does not end in a slash, so the form's action of "." sends it to the parent, "/dashboard", and it does not go through the processing code at all.</p> <pre><code>url(r'/dashboard/profile/$'...) </code>...
2
2016-05-26T07:39:44Z
[ "python", "django", "django-forms", "django-views", "django-users" ]
Python Pyomo: parameter estimation in an ODE system
37,454,055
<p>I am new using Pyomo, so I apologize in advance if this is a basic question. Well, I am working with kinetic models and my aim is to estimate kinetic parameters. I started with a 'toy model' for understanding better Pyomo before trying my complicated one.</p> <p>So, my toy model is a simple ODE system of 3 equation...
0
2016-05-26T07:19:48Z
37,478,914
<p>After asking for help in Pyomo's google group, I was pointed out that I commited a silly mistake:</p> <p>In your objective function you forgot to index x3_meas. Your objective function should be:</p> <pre><code>def _obj(model): return sum((model.x1[i]-model.x1_meas[i])**2+(model.x2[i]-model.x2_meas[i])**2+(mod...
0
2016-05-27T08:45:27Z
[ "python", "optimization", "pyomo" ]
What's the reason for TypeError: unhashable type: 'TopicAndPartition' when KafkaUtils.createDirectStream?
37,454,186
<p>I want to consume kafka message from any arbitrary offset by <code>KafkaUtils.createDirectStream</code>.</p> <p><strong>My source code:</strong></p> <pre><code>import sys from pyspark import SparkContext from pyspark.streaming import StreamingContext from pyspark.streaming.kafka import KafkaUtils, TopicAndPartiti...
1
2016-05-26T07:25:50Z
37,455,892
<p><code>pyspark</code> has a bug for python3, the <code>TopicAndPartition</code> class is missing a <code>hash</code> method, so you should change python3 to python2, the error is disappeared. </p> <p>then should cast the offset from int to long:</p> <pre><code>{TopicAndPartition("test123", 0): long(100), TopicAndPa...
2
2016-05-26T08:47:43Z
[ "python", "apache-spark", "spark-streaming", "pykafka" ]
web2py database always locked when trying to update from code
37,454,274
<p>Trying to simply update existing row in database (running on web2py), but always getting database locked error..</p> <p>Error message:</p> <pre><code>&lt;class 'sqlite3.OperationalError'&gt; database is locked </code></pre> <p>My setup</p> <ul> <li><p>in models/db.py I create database and it works when using dat...
0
2016-05-26T07:30:04Z
37,506,972
<p>Try using <code>myRecord</code> instead of <code>Record</code>, since it may be a reserved word.<br> I know <code>User</code> has given people issues in web2py. I would just tend to stay away from very generic aliases.</p> <p>Otherwise, is there anything currently in the db? If it is empty you would receive and er...
0
2016-05-29T06:34:41Z
[ "python", "web2py" ]
web2py database always locked when trying to update from code
37,454,274
<p>Trying to simply update existing row in database (running on web2py), but always getting database locked error..</p> <p>Error message:</p> <pre><code>&lt;class 'sqlite3.OperationalError'&gt; database is locked </code></pre> <p>My setup</p> <ul> <li><p>in models/db.py I create database and it works when using dat...
0
2016-05-26T07:30:04Z
37,507,114
<p>My Suggestion is</p> <p>1.First of all save the code when u make some changes.</p> <p>2.Aftr saving u r new code try to reload web2py.exe then run web2py so that u wont get Databaselocked error.</p> <p>3.Dont ever create tables in Sqlite database before.</p> <p>4.once u start running web2py and starts server and...
0
2016-05-29T06:57:10Z
[ "python", "web2py" ]
web2py database always locked when trying to update from code
37,454,274
<p>Trying to simply update existing row in database (running on web2py), but always getting database locked error..</p> <p>Error message:</p> <pre><code>&lt;class 'sqlite3.OperationalError'&gt; database is locked </code></pre> <p>My setup</p> <ul> <li><p>in models/db.py I create database and it works when using dat...
0
2016-05-26T07:30:04Z
37,559,972
<p>Check Whether there is no other connection (to sqlite db) open on your machine, if web2py shell is open, close it. </p> <p>Check DAL is defined only once or not. Define DAL only in <code>models/db.py</code>, no need to define it again in controller. </p> <p>Every variable defined in models is visible in controller...
1
2016-06-01T05:17:21Z
[ "python", "web2py" ]
How can I read a python django project URL and display complete webpage in email with it's CSS and javascript working
37,454,396
<p>I have a django project setup, I'm trying to fetch one URL using python urllib module by making a request. It is fetching the complete HTML of that page, and I'm passing that HTML with smtp module to send email. </p> <p>Now that web page is displayed in email body, but all the CSS and javascript didn't work as expe...
0
2016-05-26T07:35:54Z
37,454,855
<p>Because of the limitations and variability of how email clients render HTML it won't be possible to display HTML from web pages directly in emails. If the web pages you're talking about have been designed to work with email clients then you could use a library like <a href="https://pypi.python.org/pypi/premailer" re...
2
2016-05-26T07:57:00Z
[ "python", "django", "urllib" ]
Creating normalized gaussian graphs arranged in triangular subplots using gridspec
37,454,504
<p>I'm trying to make a triangle plot that looks somewhat like:</p> <p>x<br> o x<br> o o x </p> <p>I have code for the gridspec:</p> <pre><code> gs1 = gridspec.GridSpec(3,3) </code></pre> <p>Where the 'o's are plots of ellipses and the 'x's are gaussian plots. I have code that gives me the normalized gaussians: <...
1
2016-05-26T07:40:41Z
37,461,778
<p>Right now you have a confusing way of setting up the plots of the Gaussians. Calling <code>plt.plot</code> draws the plot on the currently active axes, which is why they all show up on the same graph. You should try changing your code for plotting the diagonal elements to something like the following:</p> <pre><cod...
0
2016-05-26T13:07:16Z
[ "python", "matplotlib", "plot", "gaussian", "subplot" ]
Command python: different meanings in command line and batch script
37,454,590
<p>I have installed Anaconda with <code>Python3</code>. Then, I additionally created a virtual environment with <code>Python2</code>. There are no other Pythons on the computer. My problem:</p> <p>If I run the command</p> <pre><code>python C:\Path\To\myScript.py arg1 arg2 </code></pre> <p>in CMD, Python 3.4 is used ...
0
2016-05-26T07:44:50Z
37,454,688
<p>since you're using Anaconda, adding a line <code>source deactivate</code> before the python command would deactivate any virtualenv explicitly</p> <p>edit: it's probably just <code>deactivate</code> for windows cmd prompt</p>
0
2016-05-26T07:49:41Z
[ "python", "python-2.7", "python-3.x", "batch-file", "command-line" ]
Command python: different meanings in command line and batch script
37,454,590
<p>I have installed Anaconda with <code>Python3</code>. Then, I additionally created a virtual environment with <code>Python2</code>. There are no other Pythons on the computer. My problem:</p> <p>If I run the command</p> <pre><code>python C:\Path\To\myScript.py arg1 arg2 </code></pre> <p>in CMD, Python 3.4 is used ...
0
2016-05-26T07:44:50Z
37,454,780
<p>Try specifying the full path to the Python3 (ie. /path/to/Python3 ) executable in your batch script. It's probably defaulting to the system python.</p> <p>If you are using a virtualenv, and you probably should be, there is a separate python executable at venv/bin/python (or similar under Windows) - using this spec...
2
2016-05-26T07:53:41Z
[ "python", "python-2.7", "python-3.x", "batch-file", "command-line" ]
Command python: different meanings in command line and batch script
37,454,590
<p>I have installed Anaconda with <code>Python3</code>. Then, I additionally created a virtual environment with <code>Python2</code>. There are no other Pythons on the computer. My problem:</p> <p>If I run the command</p> <pre><code>python C:\Path\To\myScript.py arg1 arg2 </code></pre> <p>in CMD, Python 3.4 is used ...
0
2016-05-26T07:44:50Z
37,454,829
<p>You can either change the default version of python by changing the value of path variable this can be done by following this answer <a href="http://stackoverflow.com/questions/8358265/how-to-update-path-variable-permanently-from-cmd-windows">How to update PATH variable permanently from cmd? Windows</a></p> <p>Or y...
0
2016-05-26T07:55:46Z
[ "python", "python-2.7", "python-3.x", "batch-file", "command-line" ]
How to access variables from inherited class of parent in python?
37,454,722
<p>I have the following code , where I want to achieve the following: Please Understand I am a newbie in OOP 1) Initialize "class B" from main function</p> <p>2) Inherit "class A" from "class B" and depending upon some conditions of variables of "class A" call "class D" from within "class B"</p> <p>3) After call of...
1
2016-05-26T07:51:11Z
37,454,832
<p>You haven't understood what inheritance is. An instance of D <em>is</em> an instance of A and B, because it inherits from them. The only thing you need to do is make sure you call <code>super()</code> in each <code>__init__</code> method; for some reason you've replaced the one in D with the totally wrong <code>D.__...
0
2016-05-26T07:55:48Z
[ "python", "oop", "inheritance", "multiple-inheritance" ]
How to access variables from inherited class of parent in python?
37,454,722
<p>I have the following code , where I want to achieve the following: Please Understand I am a newbie in OOP 1) Initialize "class B" from main function</p> <p>2) Inherit "class A" from "class B" and depending upon some conditions of variables of "class A" call "class D" from within "class B"</p> <p>3) After call of...
1
2016-05-26T07:51:11Z
37,456,575
<p>if you want to print out the value of "self.A_var" from inside "class D" than execute : <code>d.fun1()</code> checkout this modified code:</p> <pre><code>class A(object): def __init__(self): super(A, self).__init__() self.A_var = 0 print('Running A.__init__') class B(A): def __init...
0
2016-05-26T09:19:01Z
[ "python", "oop", "inheritance", "multiple-inheritance" ]
choose scale of x values in matplotlib
37,454,723
<p>I am trying to create a histogram using matplotlib. my X values double, from 2 - 2048. When I graph this on a histogram, there are a bunch of values right next to each other at the start, then it spreads out as the values go up. Since I know I will not have values in between, How can I change the graph to it steps u...
3
2016-05-26T07:51:18Z
37,455,720
<p>If you do not need a log scale, you may use this code to make an equal step in x-ticks:</p> <pre><code>import matplotlib from numpy.random import randn import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter import random import numpy as np def to_percent(y, position): # Ignore the passed i...
0
2016-05-26T08:39:31Z
[ "python", "matplotlib" ]
choose scale of x values in matplotlib
37,454,723
<p>I am trying to create a histogram using matplotlib. my X values double, from 2 - 2048. When I graph this on a histogram, there are a bunch of values right next to each other at the start, then it spreads out as the values go up. Since I know I will not have values in between, How can I change the graph to it steps u...
3
2016-05-26T07:51:18Z
37,456,416
<p>You can just plot the log values, and the log of the formatters. It is <em>much</em> simpler ...</p> <pre><code>plt.hist(np.log(x), bins=50, normed=True) plt.xticks(np.log(z), z) </code></pre> <p>You can also use a base 2 log if you wish ...</p>
2
2016-05-26T09:11:31Z
[ "python", "matplotlib" ]
Django, treat OneToOne related field as my own field
37,454,726
<p>I'm essentially trying to come up with my own inheritance scheme because Django's inheritance doesn't fit my needs.</p> <p>I'd like parent table(class) hold common data fields.<br> sub classess would have its own additional data in a separate table.</p> <pre><code>class ProductBase(models.Model): common = mod...
0
2016-05-26T07:51:24Z
37,455,261
<p>It doesn't seem like you want anything different to Django's standard inheritance.</p> <pre><code>class ProductBase(models.Model): common1 = models.IntegerField() common2 = models.IntegerField() class FooProduct(ProductBase): fooextra = models.IntegerField() class BarProduct(ProductBase): barextra...
1
2016-05-26T08:17:55Z
[ "python", "django", "django-inheritance" ]
Django, treat OneToOne related field as my own field
37,454,726
<p>I'm essentially trying to come up with my own inheritance scheme because Django's inheritance doesn't fit my needs.</p> <p>I'd like parent table(class) hold common data fields.<br> sub classess would have its own additional data in a separate table.</p> <pre><code>class ProductBase(models.Model): common = mod...
0
2016-05-26T07:51:24Z
37,455,283
<p>If I understand well, you want inheritance and you want the fields that are specific to the child class to be on a separate table. As far as I know, you don't need a proxy class to achieve that, you could just implement multi-table inheritance as specified in the manual at <a href="https://docs.djangoproject.com/en/...
0
2016-05-26T08:18:58Z
[ "python", "django", "django-inheritance" ]
How to handle negative values of cosine similarities
37,454,785
<p>I computed tf-idf of my documents based of terms. Then, I applied LSA to reduce the dimensionality of the terms. 'similarity_dist' contains values which are negative (see table below). How can I compute cosine distance with the range 0-1?</p> <pre><code>tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2, tokeniz...
0
2016-05-26T07:53:51Z
37,455,447
<p>cosine_similarity is in the range of -1 to 1</p> <p>cosine distance is defined as:</p> <pre><code>cosine_distance = 1 - cosine_similarity </code></pre> <p>hence cosine_distance will be in the range of: 0 to 2</p> <p>See <a href="https://en.wikipedia.org/wiki/Cosine_similarity" rel="nofollow">https://en.wikipedi...
0
2016-05-26T08:27:14Z
[ "python", "scikit-learn", "svd", "cosine-similarity", "lsa" ]
why does it appear can't multiply sequence by non-int of type 'str' ? I think I already give the width and height an integer velue. Thanks
37,454,995
<pre><code># This is a calcualtor shape = raw_input('what shape do you want to calculate? rectangle, circle, triangle, square? ') if shape == 'rectangle': width = raw_input('Please tell me the width of rectangle: ') height = raw_input('Please tell me the height of rectangle: ') print 'the area of the rec...
-2
2016-05-26T08:04:31Z
37,455,172
<p><code>raw_input</code> returns a string. Use <code>width = int(raw_input(...))</code>, and the same thing for <code>height</code> to convert them to actual integers. Demo:</p> <pre><code>&gt;&gt;&gt; width = raw_input('Please tell me the width of rectangle: ') Please tell me the width of rectangle: 5 &gt;&gt;&gt; ...
2
2016-05-26T08:12:44Z
[ "python" ]
why does it appear can't multiply sequence by non-int of type 'str' ? I think I already give the width and height an integer velue. Thanks
37,454,995
<pre><code># This is a calcualtor shape = raw_input('what shape do you want to calculate? rectangle, circle, triangle, square? ') if shape == 'rectangle': width = raw_input('Please tell me the width of rectangle: ') height = raw_input('Please tell me the height of rectangle: ') print 'the area of the rec...
-2
2016-05-26T08:04:31Z
37,455,536
<p>You get <code>can't multiply sequence of non-int of type 'str'</code> because <code>width</code> &amp; <code>height</code> are str.</p> <p>In <strong>python 2.x</strong> use:</p> <pre><code>width = int(raw_input('Please tell me the width of rectangle: ')) </code></pre> <p>In <strong>python 3.x</strong> use:</p> ...
0
2016-05-26T08:31:29Z
[ "python" ]
Vim-jedi: change the location of the function signature window
37,455,227
<p>I installed vim-jedi for autocompletion and I'm pretty happy about it except that when I open a parenthesis after a function name, the function signature appears at the top of the cursor and it is pretty annoying since the code "jumps" a few line.</p> <p>Is it possible to change the location of this to be at the bo...
0
2016-05-26T08:15:52Z
37,632,344
<h2>Right from jedi <code>README</code></h2> <p>Jedi displays function call signatures in insert mode in real-time, highlighting the current argument. The call signatures can be displayed as a pop-up in the buffer (set to 1, the default), which has the advantage of being easier to refer to, or in Vim's command line al...
0
2016-06-04T16:07:21Z
[ "python", "vim", "autocomplete", "jedi" ]
Django Channels - Internal Custom Routing not working
37,455,301
<p>I'm building a chat application based on this example (<a href="https://github.com/andrewgodwin/channels-examples/blob/master/multichat/chat/routing.py" rel="nofollow">https://github.com/andrewgodwin/channels-examples/blob/master/multichat/chat/routing.py</a>). When the javascript runs (socket already open, <strong>...
1
2016-05-26T08:19:57Z
38,154,841
<p>The Javascript file should be sending the data with a <code>"text"</code> key.</p> <p>Source: <a href="https://channels.readthedocs.io/en/latest/asgi.html#send-close" rel="nofollow">https://channels.readthedocs.io/en/latest/asgi.html#send-close</a></p>
0
2016-07-01T23:02:08Z
[ "python", "django", "websocket", "channels", "django-channels" ]
Django Channels - Internal Custom Routing not working
37,455,301
<p>I'm building a chat application based on this example (<a href="https://github.com/andrewgodwin/channels-examples/blob/master/multichat/chat/routing.py" rel="nofollow">https://github.com/andrewgodwin/channels-examples/blob/master/multichat/chat/routing.py</a>). When the javascript runs (socket already open, <strong>...
1
2016-05-26T08:19:57Z
38,268,661
<p>I tried to change my routing.py to as given below. I included the custom routing as normal routes in the websocket_routing and it started working for me. Hope this helps.</p> <pre><code>websocket_routing = [ # Called when WebSockets connect route("websocket.connect", ws_connect), # Called when WebSocke...
0
2016-07-08T14:04:50Z
[ "python", "django", "websocket", "channels", "django-channels" ]
python OSError: [Errorno 2] No such file or directory
37,455,313
<p>When I execute the next python script in ubuntu 14.04 with python 2.7:</p> <pre><code>./marathon_lb.py --marathon http://172.16.8.231:8080 --group external </code></pre> <p>It throws the next error:</p> <pre><code>Traceback (most recent call last): File "./marathon_lb.py", line 1441, in &lt;module&gt; args....
-1
2016-05-26T08:20:38Z
37,455,482
<p>It's a little hard to tell without your actual source code but error #2 usually happens when it can't find a file or a directory component.</p> <p>Given that you have a call to <code>writeConfigAndValidate</code> in your stack trace, you should probably start by investigating what file is actually being written.</p...
0
2016-05-26T08:28:35Z
[ "python", "python-2.7", "subprocess" ]
python OSError: [Errorno 2] No such file or directory
37,455,313
<p>When I execute the next python script in ubuntu 14.04 with python 2.7:</p> <pre><code>./marathon_lb.py --marathon http://172.16.8.231:8080 --group external </code></pre> <p>It throws the next error:</p> <pre><code>Traceback (most recent call last): File "./marathon_lb.py", line 1441, in &lt;module&gt; args....
-1
2016-05-26T08:20:38Z
37,455,501
<p>In your python file marathon_lb.py line 906</p> <pre><code>returncode = subprocess.call(args=cmd) </code></pre> <p>use <code>subprocess.call(cmd, shell=True)</code></p>
0
2016-05-26T08:29:43Z
[ "python", "python-2.7", "subprocess" ]
Extract recursivly multiple line data between two String- Regex & Python & XML
37,455,369
<p>I have a huge XML file from which I need data for specific entries. File structure is:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE stuff&gt; &lt;?xml-stylesheet href="file:///usr/local/test.xsl" type="text/xsl"?&gt; &lt;!-- 127.0.0.1 --&gt; &lt;opentag&gt; &lt;tag1&gt;&lt;XXXX YYYY VVV...
-1
2016-05-26T08:23:30Z
37,455,823
<p>Presuming the format is the same for all the files and <code>&lt;!-- 127.10.10.1 --&gt;</code> is actually in the first file you can use <em>itertools.groupby</em> to group the sections:</p> <pre><code>from itertools import groupby with open("your_file") as f: grps = groupby(f, key=lambda x: x.strip().startswit...
0
2016-05-26T08:44:16Z
[ "python", "regex", "xml", "parsing" ]
Extract recursivly multiple line data between two String- Regex & Python & XML
37,455,369
<p>I have a huge XML file from which I need data for specific entries. File structure is:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE stuff&gt; &lt;?xml-stylesheet href="file:///usr/local/test.xsl" type="text/xsl"?&gt; &lt;!-- 127.0.0.1 --&gt; &lt;opentag&gt; &lt;tag1&gt;&lt;XXXX YYYY VVV...
-1
2016-05-26T08:23:30Z
37,455,866
<p>Do not use regex for this. Instead have a look at the <a href="https://docs.python.org/3/library/xml.etree.elementtree.html" rel="nofollow">ElementTree</a> module. With this, you can just iterate over all the opentags, and then write each one into a different file. This is more pythonic than using regex ('<em>don't ...
0
2016-05-26T08:46:14Z
[ "python", "regex", "xml", "parsing" ]
The necessity of feature scaling before fitting a classifier in scikit-learn
37,455,379
<p>I used to believe that <code>scikit-learn</code>'s <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html" rel="nofollow">Logistic Regression</a> classifier (as well as <a href="http://scikit-learn.org/stable/modules/svm.html" rel="nofollow">SVM</a>) automatically stan...
3
2016-05-26T08:23:52Z
37,456,005
<p>From the following note in: <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html</a></p> <p>I'd assume that you need to preprocess the data yourself (e.g. w...
0
2016-05-26T08:52:26Z
[ "python", "scikit-learn", "classification" ]
Advantage of using methodtype in Python
37,455,426
<p>What are the advantages of using methodtypes from types module. It is used to add methods to object. But we can do that easily without it:</p> <pre><code>def func(): print 1 class A: pass obj = A() obj.func = func </code></pre> <p>It works even if we delete func in main scope by <code>del func</code>.</p> ...
2
2016-05-26T08:26:14Z
37,455,574
<p>A common use of <code>types.MethodType</code> is checking whether some object is a method. For example:</p> <pre><code>&gt;&gt;&gt; import types &gt;&gt;&gt; class A(object): ... def method(self): ... pass ... &gt;&gt;&gt; isinstance(A().method, types.MethodType) True &gt;&gt;&gt; def nonmethod(): ... ...
1
2016-05-26T08:32:52Z
[ "python", "oop", "methods", "monkeypatching" ]
Advantage of using methodtype in Python
37,455,426
<p>What are the advantages of using methodtypes from types module. It is used to add methods to object. But we can do that easily without it:</p> <pre><code>def func(): print 1 class A: pass obj = A() obj.func = func </code></pre> <p>It works even if we delete func in main scope by <code>del func</code>.</p> ...
2
2016-05-26T08:26:14Z
37,455,782
<p>In fact the difference between adding methods dynamically at run time and your example is huge:</p> <ul> <li>in your case, you just attach a function to an object, you can call it of course but it is <em>unbound</em>, it has no relation with the object itself (ie. you cannot use <code>self</code> inside the functio...
0
2016-05-26T08:42:27Z
[ "python", "oop", "methods", "monkeypatching" ]
How to enter values to an .xlsx file and keep formatting of cells
37,455,466
<p>I have a results analysing spreadsheet where i need to enter my raw data into a 8x6 cell 'plate' which has formatted cells to produce the output based on a graph created. This .xlsx file is heavily formatted with formulas for the analysis, and it is a commercial spreadsheet so I cannot replicate these formulas. </p>...
1
2016-05-26T08:28:04Z
37,455,745
<p>First:</p> <p>Apparently xlwt, does not support xlsx. <a href="http://stackoverflow.com/questions/15738904/does-xlwt-support-xlsx-format">does xlwt support xlsx Format</a></p> <p>Other library to use with format:</p> <p><a href="https://pypi.python.org/pypi/XlsxWriter" rel="nofollow">https://pypi.python.org/pypi/...
1
2016-05-26T08:40:45Z
[ "python", "excel", "formatting", "xlwt", "xlutils" ]
DRF : How to include serialized object that is returned from model method in serializer as a field?
37,455,488
<p>DRF newbie here. </p> <p>I'm trying to build an API for a school project. My project tree includes several applications and one is Profiles and the other is Trips. </p> <p>profiles.models includes Driver and DriverSession Model. trips.models includes Trip Model.</p> <p>Below you can see the DriverSession Model I'...
0
2016-05-26T08:29:11Z
37,456,362
<p>You didn't include the actual error message or the settings files or the profiles serializers. But just from your description it's possible that you didn't include the 'profile' in your installed apps.</p>
0
2016-05-26T09:08:23Z
[ "python", "django", "serialization", "django-models", "django-rest-framework" ]
DRF : How to include serialized object that is returned from model method in serializer as a field?
37,455,488
<p>DRF newbie here. </p> <p>I'm trying to build an API for a school project. My project tree includes several applications and one is Profiles and the other is Trips. </p> <p>profiles.models includes Driver and DriverSession Model. trips.models includes Trip Model.</p> <p>Below you can see the DriverSession Model I'...
0
2016-05-26T08:29:11Z
37,459,447
<p>you want to add your custom field to your serilizer you have to do some code like this : </p> <pre><code>class FooSerializer(serializers.ModelSerializer): my_field = serializers.SerializerMethodField('is_named_bar') def is_named_bar(self, foo): return foo.name == "bar" class Meta: model = Foo ...
1
2016-05-26T11:22:21Z
[ "python", "django", "serialization", "django-models", "django-rest-framework" ]
Python line profiler results inconsistent
37,455,556
<p>Why is it that python code runs at drastically different speeds despite being the same code run twice?</p> <p><strong>Code</strong></p> <p>I was doing some profiling for a short Python code:</p> <pre><code>import urllib3 @profile def download(url, file_path): http = urllib3.PoolManager() r = http.request...
0
2016-05-26T08:32:16Z
37,455,793
<p>The major difference is in the following line of code:</p> <pre><code>r = http.request("GET", url) </code></pre> <p>In this line you are trying to access remote web server.</p> <p>The following reasons might result with different access time to the Web Server:</p> <p>1) Caching</p> <p>2) Network load</p> <p>3)...
0
2016-05-26T08:42:56Z
[ "python", "line-profiler" ]
module initialization error: /var/task/TDNN.dll: invalid ELF header
37,455,638
<p>After searching through various resources, mostly from stackoverflow. I am able to get my code working on following python versions on my laptop (with Windows 10 installed) 1. WinPython3.4 64 bit 2. WinPython3.4 32 bit 3. Python 2.7 32 bit and in its virtualenv 4. Python 2.7 64 bit and in its virtualenv</p> <p>The...
0
2016-05-26T08:36:27Z
37,456,195
<p>An default AWS machine runs Linux and will not support dlls, which are make for Windows. You have to emulate Windows with wine or find a native Linux solution. </p> <p>AFAIK Amazon also offers Windows machines which would be an option.</p> <p>In general you should have a development environment that matches your d...
0
2016-05-26T09:02:04Z
[ "python", "c++", "python-2.7", "dll" ]
Mystic version lacks many features from the git repository?
37,455,709
<p>I installed the current <code>pip</code> package of <code>mystic</code>, which has version </p> <pre><code>&gt;&gt;&gt; mystic.__version__ Out[9]: '0.2a1' </code></pre> <p>, the current stable version. However, many features from the examples are missing. Take for example <a href="https://github.com/uqfoundation/m...
0
2016-05-26T08:39:11Z
37,462,178
<p>I'm the author. The issue is that the latest stable release is old -- very old. It's several years stale. Don't use it. Ok, so that's embarrassing… but for whatever reason, I haven't released <code>mystic</code> in a couple years. Development has been very steady over the past few years, and there has been a l...
2
2016-05-26T13:24:49Z
[ "python", "pip", "anaconda", "mystic" ]
Create db file in memory from buffer
37,455,754
<p>Is there a way in python to create an sqlite database file in memory, from a string? I have tried using sqlite3 and tempfile, but did not foubd something that helps</p>
0
2016-05-26T08:41:15Z
37,455,888
<p>I found an example of creating an in memory sqlite database <a href="http://zetcode.com/db/sqlitepythontutorial/" rel="nofollow">here</a>:</p> <pre><code>import sqlite3 con = sqlite3.connect(':memory:') </code></pre> <p>Some information about different ways to use <code>:memory:</code> can be found <a href="https:...
0
2016-05-26T08:47:37Z
[ "python", "sqlite", "memory", "sqlite3" ]
Create db file in memory from buffer
37,455,754
<p>Is there a way in python to create an sqlite database file in memory, from a string? I have tried using sqlite3 and tempfile, but did not foubd something that helps</p>
0
2016-05-26T08:41:15Z
37,456,077
<p>first one needs to create table1 in the database</p> <pre><code>import sqlite3 con = sqlite3.connect("memory.db") cur = con.cursor() cur.execute("CREATE TABLE table1 (A TEXT, B REAL, C TEXT);") </code></pre> <p>Then insert your string to table1 in database assuming that line is the string and has three entries sep...
0
2016-05-26T08:56:29Z
[ "python", "sqlite", "memory", "sqlite3" ]
The default path of python urlretrieve downloading file via HTTP
37,455,933
<p>We know that we could use <code>urllib.urlretrieve</code> to download file via HTTP to local file system. For example:</p> <pre><code>import urllib urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3") </code></pre> <p>I wonder where is the default path if we download a file like <code>mp3.mp3</co...
0
2016-05-26T08:49:36Z
37,456,041
<p>Default path have to be a directory from which program is called.</p>
0
2016-05-26T08:54:16Z
[ "python", "path", "urllib" ]
How to execute a python file from php
37,456,002
<p>i want to execute a python script on my server which execute and return a list of data. How can i execute python script by php and return back the python list data in php code.</p> <p>for example. python_file.py</p> <pre><code>import os def list_data(): """ this function will return a content list of pat...
0
2016-05-26T08:52:22Z
37,456,134
<p>With <code>exec</code> command you can execute a shell command.</p> <p><a href="http://php.net/manual/en/function.exec.php" rel="nofollow">http://php.net/manual/en/function.exec.php</a></p> <p>So basically any script ( including python ) can be executed.</p> <p>But using <code>exec</code> is not encouraged in web...
0
2016-05-26T08:59:10Z
[ "php", "python", "server" ]
How to execute a python file from php
37,456,002
<p>i want to execute a python script on my server which execute and return a list of data. How can i execute python script by php and return back the python list data in php code.</p> <p>for example. python_file.py</p> <pre><code>import os def list_data(): """ this function will return a content list of pat...
0
2016-05-26T08:52:22Z
37,456,604
<p>use this:</p> <pre><code>&lt;?php $data_list = `python path/to/python_file.py`; ?&gt; </code></pre>
0
2016-05-26T09:19:58Z
[ "php", "python", "server" ]
Python: write an INI file for Ansible
37,456,004
<p>I would like to generate a simple .INI file using python with a precise structure, i.e.</p> <pre><code>[win_clones] cl1 ansible_host=172.17.0.200 cl3 ansible_host=172.17.0.202 </code></pre> <p>So far this is what I was able to produce:</p> <pre><code>[win_clones] ansible_host = 172.17.0.200 [win_clones] ansible_...
1
2016-05-26T08:52:25Z
37,456,301
<p>This is an "INI-<em>like</em>" file, not an INI file. You'll have to write it manually:</p> <pre><code>topush = { 'cl1': {'ansible_host': ['172.17.0.200']}, 'cl3': {'ansible_host': ['172.17.0.202']} } def gen_host(data, group): ''' Takes a dictionary. It creates a INI file''' with open('host_test...
2
2016-05-26T09:05:51Z
[ "python", "ansible" ]
Python: write an INI file for Ansible
37,456,004
<p>I would like to generate a simple .INI file using python with a precise structure, i.e.</p> <pre><code>[win_clones] cl1 ansible_host=172.17.0.200 cl3 ansible_host=172.17.0.202 </code></pre> <p>So far this is what I was able to produce:</p> <pre><code>[win_clones] ansible_host = 172.17.0.200 [win_clones] ansible_...
1
2016-05-26T08:52:25Z
37,456,387
<p>Need to slightly correct function gen_host:</p> <pre><code>def gen_host(data, group): ''' Takes a dictionary. It creates a INI file''' config = ConfigParser() config.add_section(group) for key, value in data.iteritems(): config.set(group,'{0:s} ansible_host'.format(key),''.join(value['ansibl...
1
2016-05-26T09:10:01Z
[ "python", "ansible" ]
Chart with Pandas
37,456,130
<p>Here's my code so far:</p> <pre><code>import os import re import sys import io import pandas as pd def load_file(filename): df =pd.read_csv('filename', sep='\t', header=None) df[0]=pd.to_datetime(df[0], unit='s') #print df[0] return df def main(): df = load_file() daily = df.set_index(df[0...
-2
2016-05-26T08:58:58Z
37,457,150
<p>if you want to parse/convert UNIX timestamp into Python/numpy/pandas datetime you can do it this way:</p> <pre><code>In [58]: pd.to_datetime('1437775199.837855', unit='s') Out[58]: Timestamp('2015-07-24 21:59:59.837855') </code></pre> <p>or for the whole DF:</p> <pre><code>df['time'] = pd.to_datetime(df['time'], ...
0
2016-05-26T09:44:49Z
[ "python", "pandas", "charts" ]
Sorting in sparse matrix (Python 2.*)
37,456,131
<p>I'm solving a task in coursera and get stuck with sorting in sparse matrix. The problem is: i make a support vector classification (<code>sklearn.svm.SVC</code>) </p> <pre><code> clf = SVC(C=1, kernel='linear', random_state=241) clf.fit(X, y) </code></pre> <p>and as a result got a matrix <code>clf.coef_</co...
0
2016-05-26T08:59:02Z
37,456,666
<p>Since by calling <code>argsort</code> you get the sorted indices instead of the sorted array, you can use the result of <code>argsort</code> directly as feature indices.</p> <p>So if you have an array <code>[1.5, 2.5, 0.5]</code>, the result of <code>argsort</code> is <code>[2, 0, 1]</code>, representing that eleme...
0
2016-05-26T09:23:00Z
[ "python", "scikit-learn", "sparse-matrix", "python-2.x" ]
Kivy Bubble arrow blur
37,456,163
<p>I created a <code>Bubble</code> widget around a custom widget to display some options, but the arrow of that <code>Bubble</code> turned out unexpectedly big and blurry. All those widgets are positioned in a <code>GridLayout</code> that is put inside of a <code>ScrollView</code>. What could cause this issue? </p> <...
0
2016-05-26T09:00:30Z
37,467,741
<p>Your line <code>msg_stack[-1].width = 160</code> cripples it. Or rather the loop after it, where you set Bubble's width from that variable.</p> <p>You set Bubble's <code>size</code> in kv, then in python you play its <code>width</code> again as you add <code>Message</code> as a widget to <code>GridLayout</code> and...
1
2016-05-26T17:43:53Z
[ "python", "python-3.x", "kivy" ]
Pandas python and excel file
37,456,171
<p>I'm trying to write on an excel the following:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;user&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;...
0
2016-05-26T09:00:55Z
37,457,094
<p>Hope it helps you you can append all the dataframes and then write it to excel:<br> <code>data=label.append(df_recommendation)</code><br> similarly for the next two dataframes.</p>
1
2016-05-26T09:42:38Z
[ "python", "excel", "pandas" ]
Pandas python and excel file
37,456,171
<p>I'm trying to write on an excel the following:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt;user&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;...
0
2016-05-26T09:00:55Z
37,459,971
<p>You can use openpyxl to modify existing excel files with pandas.</p> <p>look on this example: <a href="http://stackoverflow.com/a/20221655/590335">http://stackoverflow.com/a/20221655/590335</a></p>
1
2016-05-26T11:45:25Z
[ "python", "excel", "pandas" ]
What is good way to check a key of a dictionary in python?
37,456,208
<p>I have a loop that over some values. I have a dictionary that it's keys are in the values of the loop iteration.</p> <p>I can't change the outer loop.</p> <pre><code>for i in range(1, 1000000000000): if i in my_dict.keys(): func() other_func(i) </code></pre> <p>Each element in: <code>my_dict.keys()</...
0
2016-05-26T09:02:34Z
37,456,306
<p>I think you can do something like this:</p> <pre><code>for i in my_dict: if 0 &lt; i &lt; 1000000000000: func() </code></pre> <p><code>range(1, 1000000000000)</code> will generate a list of numbers from <code>1</code> to <code>999999999999</code> and you just need to check if your key is in that range. S...
9
2016-05-26T09:05:57Z
[ "python", "python-2.7" ]
What is good way to check a key of a dictionary in python?
37,456,208
<p>I have a loop that over some values. I have a dictionary that it's keys are in the values of the loop iteration.</p> <p>I can't change the outer loop.</p> <pre><code>for i in range(1, 1000000000000): if i in my_dict.keys(): func() other_func(i) </code></pre> <p>Each element in: <code>my_dict.keys()</...
0
2016-05-26T09:02:34Z
37,456,318
<p>Change your for loop. See below script.</p> <pre><code>for key in my_dict.keys(): if 0 &lt; int(key) &lt; 1000000000000: func() </code></pre> <p>Change for loop because in original implementation for loop would iterate at most 1000000000000 times. But now it will iterate maximum of length of my_dict.</...
0
2016-05-26T09:06:26Z
[ "python", "python-2.7" ]
What is good way to check a key of a dictionary in python?
37,456,208
<p>I have a loop that over some values. I have a dictionary that it's keys are in the values of the loop iteration.</p> <p>I can't change the outer loop.</p> <pre><code>for i in range(1, 1000000000000): if i in my_dict.keys(): func() other_func(i) </code></pre> <p>Each element in: <code>my_dict.keys()</...
0
2016-05-26T09:02:34Z
37,456,346
<p>Well, <code>try</code> and <code>except</code> is a good way to go.</p> <pre><code>for i in range(1, 100000000): try: my_dict[i] except KeyError: continue func() </code></pre> <p>If <code>i</code> is not in the <code>keys</code>, then it will throw <code>KeyError</code> and will go to t...
0
2016-05-26T09:07:41Z
[ "python", "python-2.7" ]
What is good way to check a key of a dictionary in python?
37,456,208
<p>I have a loop that over some values. I have a dictionary that it's keys are in the values of the loop iteration.</p> <p>I can't change the outer loop.</p> <pre><code>for i in range(1, 1000000000000): if i in my_dict.keys(): func() other_func(i) </code></pre> <p>Each element in: <code>my_dict.keys()</...
0
2016-05-26T09:02:34Z
37,459,268
<p>The most simplest way is ,</p> <p>if my_dict.has_key('key'):</p>
0
2016-05-26T11:14:25Z
[ "python", "python-2.7" ]
Pythonic ways to re-group / pivot database output
37,456,292
<p>This is a situation I often find myself in with Python and I'm sure my solution could be a little more elegant. The simplest analogy I can make is a table of comments in a photo app; every comment links to a specific album and a specific photo. Picture something like this:</p> <pre><code>|------------|----------|--...
0
2016-05-26T09:05:34Z
37,457,040
<p>You can use <code>itertools.groupby</code> if you want to get a little tricky and flex your pythonista skills:</p> <pre><code>from itertools import groupby temp = {k:list(g) for k,g in groupby(ca, lambda x: x['photo_id'])} # I shortened the name comments_atomic to ca here </code></pre> <p>This will give you the in...
1
2016-05-26T09:40:22Z
[ "python", "python-2.7" ]
Getting a list of months between two dates
37,456,421
<p>I need to implement the code which will help me to get the list of months between two dates.</p> <p>I already have the code which will give the month delta , That is the number of months.</p> <p>Actually, I need the way to achieve getting the list of months between two dates.</p> <p>Here it is code for getting mo...
1
2016-05-26T09:11:42Z
37,457,063
<p>Change your print statement to:<br> <code>print calendar.month_name[:monthdelta]</code></p>
-1
2016-05-26T09:41:18Z
[ "python", "datetime", "calendar" ]
Getting a list of months between two dates
37,456,421
<p>I need to implement the code which will help me to get the list of months between two dates.</p> <p>I already have the code which will give the month delta , That is the number of months.</p> <p>Actually, I need the way to achieve getting the list of months between two dates.</p> <p>Here it is code for getting mo...
1
2016-05-26T09:11:42Z
37,457,172
<pre><code>from datetime import datetime,timedelta import time d = date1 delta = timedelta(months=1) while d &lt;= date2: print d.strftime("%m") d += delta </code></pre>
0
2016-05-26T09:45:38Z
[ "python", "datetime", "calendar" ]
Getting a list of months between two dates
37,456,421
<p>I need to implement the code which will help me to get the list of months between two dates.</p> <p>I already have the code which will give the month delta , That is the number of months.</p> <p>Actually, I need the way to achieve getting the list of months between two dates.</p> <p>Here it is code for getting mo...
1
2016-05-26T09:11:42Z
37,457,468
<p>Because I don't know your desired output I can't format mine, but this returns an integer of the total number of months between two dates.</p> <pre><code>def calculate_monthdelta(date1, date2): print abs(date1.year - date2.year) * 12 + abs(date1.month - date2.month) </code></pre>
0
2016-05-26T09:57:44Z
[ "python", "datetime", "calendar" ]
Getting a list of months between two dates
37,456,421
<p>I need to implement the code which will help me to get the list of months between two dates.</p> <p>I already have the code which will give the month delta , That is the number of months.</p> <p>Actually, I need the way to achieve getting the list of months between two dates.</p> <p>Here it is code for getting mo...
1
2016-05-26T09:11:42Z
37,459,429
<p>try this</p> <pre><code>import datetime import time from dateutil.rrule import rrule, MONTHLY months = [dt.strftime("%m") for dt in rrule(MONTHLY, dtstart=date1, until=date2)] print months </code></pre>
2
2016-05-26T11:21:51Z
[ "python", "datetime", "calendar" ]
Applying custom function while grouping returns NaN
37,456,532
<p>Given a dict, <code>performances</code>, storing Series of kind:</p> <pre><code>2015-02-28 NaN 2015-03-02 100.000000 2015-03-03 98.997117 2015-03-04 98.909215 2015-03-05 99.909979 2015-03-06 100.161486 2015-03-09 100.502772 2015-03-10 101.685314 2015-03-11 102.518433 2015-03-12 ...
1
2016-05-26T09:16:29Z
37,458,225
<p>If each month has at least one non <code>NaN</code> value, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.first_valid_index.html" rel="nofollow"><code>first_valid_index</code></a>:</p> <pre><code>print (df.b.groupby(df.index.month).apply(lambda x: x[x.first_valid_index()])) </code>...
1
2016-05-26T10:29:58Z
[ "python", "python-3.x", "pandas", "aggregate", "series" ]
Pandas irow() automatically converts int to float
37,456,634
<pre><code>x = DataFrame([(1,2.0),(2,4.0)], columns=['a','b']) x.dtypes a int64 b float64 a = x.irow(0) a output: a 1.0 b 2.0 Name: 0, dtype: float64 </code></pre> <p>why does pandas convert automatically to float? how can I keep the int columns as int without use astype/cast for each field after using i...
0
2016-05-26T09:21:42Z
37,456,699
<p>It returns a <code>Series</code> for that row so the <code>dtype</code> is promoted to <code>float</code> due to the presence of the <code>float</code> in col <code>b</code></p> <pre><code>In [33]: type(x.irow(0)) Out[33]: pandas.core.series.Series </code></pre> <p>Also that method is deprecated you should be usi...
1
2016-05-26T09:24:10Z
[ "python", "pandas" ]
How can uwsgi re-establish connection to remote mysql database whenever mysql services are restarted
37,456,656
<p>I have a python web application, where in, the application connects to a remote database.</p> <p>Application: flask+uwsgi+nginx . </p> <p>Database :mysql (remote). The application exposes rest api for which data is served from remote database.</p> <p>Everyday after db restoration, mysql service is restarted in th...
1
2016-05-26T09:22:39Z
37,617,082
<p>It really depends on the way you connect to your database</p> <p>In case you're using the popular ORMs:</p> <ul> <li><p>SQLAlchemy ORM</p> <p>engine = create_engine('mysql+mysqldb://...', pool_recycle=3600)</p> <p>as stated in the documentation <a href="http://docs.sqlalchemy.org/en/latest/dialects/mysql.html?hi...
0
2016-06-03T14:31:52Z
[ "python", "mysql", "web-services", "flask", "uwsgi" ]
Pandas DataFrame iterating over rows and sum
37,456,705
<p>I have got this pandas DataFrame:</p> <pre><code> recipe_name ingredient_group weight% pudding milk 0.60 pudding 2 sugar 0.10 pudding 2 sugar 0.70 pudding 2 milk 0.30 pudding 3 egg 0...
0
2016-05-26T09:24:29Z
37,456,762
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow"><code>transform</code></a> <a href="http://pandas.py...
4
2016-05-26T09:27:25Z
[ "python", "pandas" ]