title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python - Intensity map without interpolation
39,894,926
<p>I need to make an intensity plot.</p> <p>I have three lists of x,y,z values, imported from real data: <code>x_list, y_list, z_list</code>. Each of these lists contain 200 values. Therefore there is a corresponding value of z for each x,y couple.</p> <p>I have tried the following, after some search on the web and a...
0
2016-10-06T11:34:47Z
39,895,429
<p>From what I understand, you want to display xyz points in a 2D graph where z-value would be represented by a color. If that is correct the solution is as simple as stating <code>facecolors=z_list</code> in your scatter plot:</p> <pre><code>data = np.random.rand(200,3) x_list = data[:,0] y_list = data[:,1] z_list = ...
2
2016-10-06T12:00:50Z
[ "python", "matplotlib" ]
Generate html document with images and text within python script (without servers if possible)
39,894,970
<p>How can I generate HTML containing images and text, using a template and css, in python?</p> <p>There are few similar questions on stackoverflow (e.g.: <a href="http://stackoverflow.com/questions/6748559/generating-html-documents-in-python">Q1</a>, <a href="http://stackoverflow.com/questions/98135/how-do-i-use-djan...
0
2016-10-06T11:37:05Z
39,895,138
<p>I use code like this:</p> <pre><code>self.content = ''' &lt;html&gt; &lt;head&gt; ''' + base_pyhtml.getAdmin ('documentation') + ''' &lt;style&gt; ''' + base_pycss.getAll () + ''' ''' + documentation_pycss.getAll () + ''' &lt;/style&gt;...
0
2016-10-06T11:45:32Z
[ "python", "html", "css", "django" ]
Generate html document with images and text within python script (without servers if possible)
39,894,970
<p>How can I generate HTML containing images and text, using a template and css, in python?</p> <p>There are few similar questions on stackoverflow (e.g.: <a href="http://stackoverflow.com/questions/6748559/generating-html-documents-in-python">Q1</a>, <a href="http://stackoverflow.com/questions/98135/how-do-i-use-djan...
0
2016-10-06T11:37:05Z
39,895,310
<p>There are quite a few python template engines - for a start you may want to have a look here : <a href="https://wiki.python.org/moin/Templating" rel="nofollow">https://wiki.python.org/moin/Templating</a></p> <p>As far as I'm concerned I'd use jinja2 but YMMV.</p>
1
2016-10-06T11:54:00Z
[ "python", "html", "css", "django" ]
Generate html document with images and text within python script (without servers if possible)
39,894,970
<p>How can I generate HTML containing images and text, using a template and css, in python?</p> <p>There are few similar questions on stackoverflow (e.g.: <a href="http://stackoverflow.com/questions/6748559/generating-html-documents-in-python">Q1</a>, <a href="http://stackoverflow.com/questions/98135/how-do-i-use-djan...
0
2016-10-06T11:37:05Z
39,932,850
<p>Thanks for your answers, they helped me coming up with something that works for me.</p> <p>I am using <code>jinja2</code> to render and html file ('index.html') that I have made separately. </p> <pre><code>from jinja2 import Template, Environment, FileSystemLoader # Render html file env = Environment(loader=File...
-1
2016-10-08T13:19:29Z
[ "python", "html", "css", "django" ]
How to choose object from list and print its name
39,895,170
<p>I have class Something with few objects:</p> <pre><code>class Something(): def __init__(self, name, attr1, attr2): self.name= name self.attr1= attr1 self.attr2= attr2 def getName(self): return self.name Obj1=Something('Name1', 'bla bla1', 'bla bla2') Obj2=Something('Name2', 'bla bla3', 'bla ...
0
2016-10-06T11:46:43Z
39,895,279
<p>Thing is that you compare string to an object here:</p> <pre><code>if y == i: </code></pre> <p>so you should either look at <code>__eq__</code> method of your class, or compare input string with obj name like:</p> <pre><code>if y == i.getName() </code></pre>
0
2016-10-06T11:52:25Z
[ "python", "class", "object" ]
How to choose object from list and print its name
39,895,170
<p>I have class Something with few objects:</p> <pre><code>class Something(): def __init__(self, name, attr1, attr2): self.name= name self.attr1= attr1 self.attr2= attr2 def getName(self): return self.name Obj1=Something('Name1', 'bla bla1', 'bla bla2') Obj2=Something('Name2', 'bla bla3', 'bla ...
0
2016-10-06T11:46:43Z
39,895,296
<p>in your lines:</p> <pre><code>for i in objects: if y == i: </code></pre> <p>i is an object, and y in a string, so you can't compare them</p> <p>however, you can do </p> <pre><code>for i in objects: if y == i.getName(): </code></pre> <p>so you compare two strings together</p>
0
2016-10-06T11:53:24Z
[ "python", "class", "object" ]
getting list of indices of each value of list in a pythonic way
39,895,221
<p>I have a list <code>data</code> of values, and I want to return a dictionary mapping each value of <code>data</code> to a list of the indices where this value appears.</p> <p>This can be done using this code:</p> <pre><code>data = np.array(data) {val: list(np.where(data==val)[0]) for val in data} </code></pre> <p...
0
2016-10-06T11:49:43Z
39,895,339
<p>You can use a <a href="https://docs.python.org/3/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> of <code>lists</code> to achieve this in O(n):</p> <pre><code>from collections import defaultdict d = defaultdict(list) for idx, item in enumerate(data): d[item].append...
4
2016-10-06T11:55:35Z
[ "python", "numpy" ]
getting list of indices of each value of list in a pythonic way
39,895,221
<p>I have a list <code>data</code> of values, and I want to return a dictionary mapping each value of <code>data</code> to a list of the indices where this value appears.</p> <p>This can be done using this code:</p> <pre><code>data = np.array(data) {val: list(np.where(data==val)[0]) for val in data} </code></pre> <p...
0
2016-10-06T11:49:43Z
39,895,368
<p>Try this out :</p> <pre><code>data = np.array(data) dic = {} for i, val in enumerate(data): if val in dic.keys(): dic[val].append(i) else: dic[val]=[] dic[val].append(i) </code></pre>
1
2016-10-06T11:56:52Z
[ "python", "numpy" ]
Pandas dataframe creation from a list
39,895,315
<p>Im getting the following error <code>Shape of passed values is (1, 5), indices imply (5, 5)</code>. From what I can tell this suggests that the data set doesnt match the column count, and of course it obviously is correct. Initially I thought it could be due to using a list, but I get the same issue if passing in a ...
1
2016-10-06T11:54:10Z
39,895,386
<p>you have to pass a 2d dimensional array to <code>pd.DataFrame</code> for the data if you force the shape by passing <code>columns</code></p> <pre><code>data = [['data1', 'data2', 'data3', 'data4', 'data5']] df = pd.DataFrame(data, columns=['column1', 'column2', 'column3', 'column4', 'column5']) </code></pre>
1
2016-10-06T11:57:50Z
[ "python", "pandas" ]
Pandas dataframe creation from a list
39,895,315
<p>Im getting the following error <code>Shape of passed values is (1, 5), indices imply (5, 5)</code>. From what I can tell this suggests that the data set doesnt match the column count, and of course it obviously is correct. Initially I thought it could be due to using a list, but I get the same issue if passing in a ...
1
2016-10-06T11:54:10Z
39,895,572
<p>You've missed the list brackets around <code>data</code></p> <pre><code>df = pd.DataFrame(data = [data], columns=['column1', 'column2', 'column3', 'column4', 'column5'], index=None) </code></pre> <p>Things to note: <code>pd.DataFrame()</code> expects a list of <em>tuples</em>, this means: </p> <pre><code>data ...
0
2016-10-06T12:07:05Z
[ "python", "pandas" ]
2D Orthogonal projection of vector onto line with numpy yields wrong result
39,895,330
<p>I have 350 document scores that, when I plot them, have this shape:</p> <pre><code>docScores = [(0, 68.62998962), (1, 60.21374512), (2, 54.72480392), (3, 50.71389389), (4, 49.39723969), ..., (345, 28.3756237), (346, 28.37126923), (347, 28.36397934), (348, 28.35762787), (34...
3
2016-10-06T11:55:10Z
39,895,669
<p>First of all, is the point at ~(50, 37) <code>p</code> or <code>s+p</code>? If <code>p</code>, that might be your problem right there! If the Y component of your <code>p</code> variable is positive, you won't get the results you expect when you do the dot product.</p> <p>Assuming that point is <code>s+p</code>, i...
1
2016-10-06T12:12:43Z
[ "python", "numpy", "plot", "linear-algebra", "orthogonal" ]
2D Orthogonal projection of vector onto line with numpy yields wrong result
39,895,330
<p>I have 350 document scores that, when I plot them, have this shape:</p> <pre><code>docScores = [(0, 68.62998962), (1, 60.21374512), (2, 54.72480392), (3, 50.71389389), (4, 49.39723969), ..., (345, 28.3756237), (346, 28.37126923), (347, 28.36397934), (348, 28.35762787), (34...
3
2016-10-06T11:55:10Z
39,898,113
<p>If you are using the plot to visually determine if the solution looks correct, you must plot the data using the same scale on each axis, i.e. use <code>plt.axis('equal')</code>. If the axes do not have equal scales, the angles between lines are distorted in the plot.</p>
2
2016-10-06T14:02:54Z
[ "python", "numpy", "plot", "linear-algebra", "orthogonal" ]
How to run non-linear regression in python
39,895,369
<p>i am having the following information(dataframe) in python</p> <pre><code>product baskets scaling_factor 12345 475 95.5 12345 108 57.7 12345 2 1.4 12345 38 21.9 12345 320 88.8 </code></pre> <p>and I want to run the following <strong>non-linear regression</strong> and <strong>estima...
2
2016-10-06T11:56:56Z
39,895,677
<p>For problems like these I always use <a href="http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.optimize.minimize.html" rel="nofollow"><code>scipy.optimize.minimize</code></a> with my own least squares function. The optimization algorithms don't handle large differences between the various inputs wel...
3
2016-10-06T12:13:08Z
[ "python", "python-3.x", "pandas", "numpy", "sklearn-pandas" ]
How to run non-linear regression in python
39,895,369
<p>i am having the following information(dataframe) in python</p> <pre><code>product baskets scaling_factor 12345 475 95.5 12345 108 57.7 12345 2 1.4 12345 38 21.9 12345 320 88.8 </code></pre> <p>and I want to run the following <strong>non-linear regression</strong> and <strong>estima...
2
2016-10-06T11:56:56Z
39,896,700
<p>Agreeing with Chris Mueller, I'd also use <code>scipy</code> but <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow"><code>scipy.optimize.curve_fit</code></a>. The code looks like:</p> <pre><code>###the top two lines are required on my linux machine import mat...
2
2016-10-06T12:59:31Z
[ "python", "python-3.x", "pandas", "numpy", "sklearn-pandas" ]
Creating lambda function with conditions on one df to use in df.apply of another df
39,895,553
<p>Consider <code>df</code></p> <pre><code>Index A B C 0 20161001 0 24.5 1 20161001 3 26.5 2 20161001 6 21.5 3 20161001 9 29.5 4 20161001 12 20.5 5 20161002 0 30.5 6 20161002 3 22.5 7 20161002 6 25.5 ... </cod...
2
2016-10-06T12:06:26Z
39,895,896
<p>You could make use of Boolean Indexing and the <code>sum()</code> aggregate function</p> <pre><code># Create the first dataframe (df) df = pd.DataFrame([[20161001,0 ,24.5], [20161001,3 ,26.5], [20161001,6 ,21.5], [20161001,9 ,29.5], [201610...
2
2016-10-06T12:22:42Z
[ "python", "pandas", "lambda" ]
Jenkins Python API: get QueueItem by ID
39,895,586
<p>Invoking a job in Jenkins via <a href="https://pypi.python.org/pypi/jenkinsapi/0.2.31" rel="nofollow">jenkinsapi</a> returns a <code>jenkinsapi.queue.QueueItem</code> object that represents queued build.</p> <p>How can I get <code>QueueItem</code> object of an already queued build, given <code>queue_id</code>? I ha...
0
2016-10-06T12:08:06Z
39,895,920
<p>It seems you have to create <code>QueueItem</code> manually:</p> <pre><code>j = Jenkins(...) url = j.base_server_url() + "/queue/item/" + str(queue_id) + "/" queue_item = jenkinsapi.queue.QueueItem(url, j); </code></pre>
0
2016-10-06T12:23:50Z
[ "python", "jenkins", "jenkins-api" ]
How to access a object's attrbute by using string corresponding to name if object is attribute of some other object
39,895,789
<p>I have 3 classes as below:- </p> <pre><code>class C(object): def __init__(self, v): self.var = v class B(object): def __init__(self, c): self.c = c class A(object): def __init__(self, b): self.b = b I have created instances as c = C("required result") b = B(c) a = A(b) &gt;&...
0
2016-10-06T12:18:33Z
39,896,267
<p>Here is the more accurate way, I suppose. (using <code>try-except</code> construction):</p> <pre><code>... c = C("required result") b = B(c) a = A(b) def sample(obj, path): path_attrs = path.split('.') # splitting inner attributes path inner_attr = None for p in path_attrs: try: ...
1
2016-10-06T12:39:17Z
[ "python" ]
How to access a object's attrbute by using string corresponding to name if object is attribute of some other object
39,895,789
<p>I have 3 classes as below:- </p> <pre><code>class C(object): def __init__(self, v): self.var = v class B(object): def __init__(self, c): self.c = c class A(object): def __init__(self, b): self.b = b I have created instances as c = C("required result") b = B(c) a = A(b) &gt;&...
0
2016-10-06T12:18:33Z
39,896,333
<p>You can use <a href="https://docs.python.org/3/library/operator.html#operator.attrgetter" rel="nofollow">operator.attrgetter</a> which takes a dotted name notation, eg:</p> <pre><code>from operator import attrgetter attrgetter('b.c.var')(a) # 'required result' </code></pre> <p>Then if you don't like that syntax, u...
5
2016-10-06T12:42:47Z
[ "python" ]
How to open my favorite editor from PsychoPy Builder
39,895,908
<p>I'm using PsychoPy Builder. I'd like to write codes with vim. How should I open it from PsychoPy Builder? Sorry about my poor English.</p>
-2
2016-10-06T12:23:15Z
39,902,743
<p>The "builder" is a gui interface to the psychopy library. If you want to write code then you probably want to use psychopy as a library. To do that you will have to figure out where the library is stored on your system, and that might be easier if you don't use the stand-alone version, but get one of the library ver...
0
2016-10-06T17:59:28Z
[ "python", "psychopy" ]
How to check if videos overlap
39,896,059
<p>I am new to video analysis and python and is working on a project on video composition. I have three videos that overlap. for example below are the start and end time of the videos</p> <pre><code> video1 video2 video3 start 19-13-30 19-13-25 19-13-45 end 19-13-55 19-13-35 19-13-59 </code><...
-2
2016-10-06T12:29:47Z
39,901,194
<p>Suppose you have a list of starttime and endtime of the videos [[video1_starttime,video1_endtime],[video2_starttime,video2_endtime],[video3_starttime,video3_endtime]], you can first sort the list based on startimes and then iterate over it to check if it is overlapping.</p> <p>You can use the below code to check fo...
0
2016-10-06T16:27:00Z
[ "python", "timestamp", "video-processing" ]
Is it possible to get values from my local machine to my form inputs tag?
39,896,551
<p>I have this code:</p> <pre><code>&lt;div class="col-md-12"&gt; &lt;div class="form-panel"&gt; &lt;h4&gt;&lt;i class="fa fa-angle-right"&gt;&lt;/i&gt; Testing &lt;/h4&gt; &lt;hr /&gt; &lt;form method="post" name="ibisaserver"&gt; &lt;div...
0
2016-10-06T12:52:55Z
39,900,979
<p>There are two ways which you can use:</p> <ol> <li><p>Make the python file generate the output html file, which you can use. <a href="https://www.decalage.info/python/html" rel="nofollow">HTML.py</a> is a good option to start with it.</p></li> <li><p>You can use XmlHttpRequest to read local files using javascript a...
0
2016-10-06T16:15:42Z
[ "javascript", "python", "html", "linux", "debian" ]
execution failure of an self insertion_sort definition in python3
39,896,566
<p>I want to put the numbers from the smallest to the largest.</p> <p>NO.1 succeed</p> <pre><code>def insertion_sort(list): for index in range(1,len(list)): value = list[index] i = index-1 while i &gt;=0: if value &lt; list[i]: list[i+1]=list[i] ...
1
2016-10-06T12:53:36Z
39,896,829
<p>Implementation of insertion sort (without sentinel) should look like;</p> <pre><code>def insertion_sort(list_): for index in range(1,len(list_)): value = list_[index] i = index - 1 while i &gt;= 0 and list_[i] &gt; value : list_[i + 1] = list_[i] list_[i] = valu...
0
2016-10-06T13:05:27Z
[ "python" ]
Retruning multiple objects and using them as arguments
39,896,610
<p>I have a function which goes something like this:</p> <pre><code>def do_something(lis): do something return lis[0], lis[1] </code></pre> <p>and another function which needs to take those two return objects as arguments:</p> <pre><code>def other_function(arg1, arg2): pass </code></pre> <p>I have tried...
2
2016-10-06T12:55:33Z
39,896,654
<p>You need to unpack those arguments when calling <code>other_function</code>. </p> <pre><code>other_function(*do_something(lis)) </code></pre> <p>Based on the error message, it looks like your other function is defined (and should be defined as)</p> <pre><code>def other_function(arg1, arg2): pass </code></pre>...
3
2016-10-06T12:57:49Z
[ "python", "function", "functional-programming", "return", "arguments" ]
Retruning multiple objects and using them as arguments
39,896,610
<p>I have a function which goes something like this:</p> <pre><code>def do_something(lis): do something return lis[0], lis[1] </code></pre> <p>and another function which needs to take those two return objects as arguments:</p> <pre><code>def other_function(arg1, arg2): pass </code></pre> <p>I have tried...
2
2016-10-06T12:55:33Z
39,896,692
<p>You can do it like this:</p> <pre><code>other_function(*do_something(list)) </code></pre> <p>The <code>*</code> char will expand the <code>tuple</code> returned by <code>do_something</code>.</p> <p>Your <code>do_something</code> function is actually returning a <code>tuple</code> which contains several values but...
1
2016-10-06T12:59:13Z
[ "python", "function", "functional-programming", "return", "arguments" ]
Can I perform multiple assertions in pytest?
39,896,716
<p>I'm using pytest for my selenium tests and wanted to know if it's possible to have multiple assertions in a single test?</p> <p>I call a function that compares multiple values and I want the test to report on all the values that don't match up. The problem I'm having is that using "assert" or "pytest.fail" stops th...
0
2016-10-06T13:00:22Z
39,897,110
<p>As Jon Clements commented, you can fill a list of error messages and then assert the list is empty, displaying each message when the assertion is false.</p> <p>concretely, it could be something like that:</p> <pre><code>def test_something(self): errors = [] # replace assertions by conditions if not co...
0
2016-10-06T13:17:50Z
[ "python", "selenium", "py.test" ]
Can I perform multiple assertions in pytest?
39,896,716
<p>I'm using pytest for my selenium tests and wanted to know if it's possible to have multiple assertions in a single test?</p> <p>I call a function that compares multiple values and I want the test to report on all the values that don't match up. The problem I'm having is that using "assert" or "pytest.fail" stops th...
0
2016-10-06T13:00:22Z
39,899,876
<p>Here's an alternative approach called <a href="http://pythontesting.net/strategy/delayed-assert/" rel="nofollow">Delayed assert</a>, It pretty much similar to what @Tryph has provided, and gives better stack trace.</p>
0
2016-10-06T15:20:31Z
[ "python", "selenium", "py.test" ]
ra & dec conversion from hh:mm:ss to degrees
39,896,756
<p>I have a file that contains ra &amp; dec in hh:mm:ss format. Say the file name is "coord.txt" and it's content is :</p> <blockquote> <p>06 40 34.8 10 04 22 06 41 11.6 10 02 24 06 40 50.9 10 01 43</p> </blockquote> <p>06 40 34.8 is the ra and 10 04 22 is the dec How do I convert it to degrees with pyth...
0
2016-10-06T13:02:11Z
39,897,712
<pre><code>s = "06 40 34.8 10 04 22 06 41 11.6 10 02 24 06 40 50.9 10 01 43" # or s = f.readline() d = [float(i) for i in s.split()] # d = [6.0, 40.0, 34.8, 10.0, 4.0, 22.0, 6.0, 41.0, 11.6, 10.0, 2.0, 24.0, 6.0, 40.0, 50.9, 10.0, 1.0, 43.0] d2 = [d[i:i+3] for i in range(0, len(d), 3)] # d2 = [[6.0, 40.0, 34.8], [10...
0
2016-10-06T13:44:50Z
[ "python", "awk" ]
ra & dec conversion from hh:mm:ss to degrees
39,896,756
<p>I have a file that contains ra &amp; dec in hh:mm:ss format. Say the file name is "coord.txt" and it's content is :</p> <blockquote> <p>06 40 34.8 10 04 22 06 41 11.6 10 02 24 06 40 50.9 10 01 43</p> </blockquote> <p>06 40 34.8 is the ra and 10 04 22 is the dec How do I convert it to degrees with pyth...
0
2016-10-06T13:02:11Z
39,899,050
<p>implementing @M.Danilchenko's logic in <code>awk</code></p> <pre><code>$ awk '{for(i=1;i&lt;NF;i+=3) a[++c]=($i*15+($(i+1)+$(i+2)/60)/4); for(i=1;i&lt;c;i+=2) printf "(%.3f,%.3f) ", a[i],a[i+1]; print ""}' file (100.145,151.092) (100.298,150.600) (100.212,150.429) </code></pre> <p>where</p> <pre...
0
2016-10-06T14:44:37Z
[ "python", "awk" ]
Multiprocessing process does not join when putting complex dictionary in return queue
39,896,807
<p>Given a pretty standard read/write multithreaded process with a read Queue and a write Queue:</p> <p>8 times <code>worker done</code> is printed, but the join() statement is never passed. But if I replace <code>queue_out.put(r)</code> by `queue_out.put(1) it works. </p> <p>This is melting my brain, probably someth...
2
2016-10-06T13:04:34Z
39,899,602
<p>I <em>think</em> I have pieced this together from two sources as I always have the same problem. I think the important thing is that this is in Windows. </p> <p>Note from <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">the documentation</a></p> <blockquote> <p>Since Windows lacks ...
1
2016-10-06T15:08:26Z
[ "python", "multithreading", "dictionary", "queue", "multiprocessing" ]
alternative reading binary in python instead of C++
39,896,826
<p>I have a binary file and C++ code which can read that binary file like follow.</p> <pre><code>int NumberOfWord; FILE *f = fopen("../data/vec.bin", "rb"); fscanf(f, "%d", &amp;NumberOfWord); cout &lt;&lt; NumberOfWord&lt; &lt;endl; </code></pre> <p>This output is:</p> <pre><code>114042 </code></pre> <p>I want to ...
1
2016-10-06T13:05:20Z
39,896,994
<p>In C format strings, <code>%d</code> is short for decimal.</p> <p>In Python, <code>d</code> is short for double.</p> <p>If it's an integer, you should use <code>i</code> in <code>struct.unpack</code> call.</p> <pre><code>with open("../data/vec.bin","rb") as f: b = f.read() print struct.unpack("i",b)[0] </...
0
2016-10-06T13:12:35Z
[ "python", "c++" ]
alternative reading binary in python instead of C++
39,896,826
<p>I have a binary file and C++ code which can read that binary file like follow.</p> <pre><code>int NumberOfWord; FILE *f = fopen("../data/vec.bin", "rb"); fscanf(f, "%d", &amp;NumberOfWord); cout &lt;&lt; NumberOfWord&lt; &lt;endl; </code></pre> <p>This output is:</p> <pre><code>114042 </code></pre> <p>I want to ...
1
2016-10-06T13:05:20Z
39,898,513
<p>As you have been able to read the file correctly with this C++ (or rather C) line, <code>fscanf(f, "%d", &amp;NumberOfWord);</code>, I assume that your file contains a text representation of 114042. So it contains the bytes</p> <p><code>0x31 0x31 0x34 0x30 0x34 0x32 ...</code> or <code>'1', '1', '4', '0', '4', '2',...
1
2016-10-06T14:20:19Z
[ "python", "c++" ]
Calling python from matlab
39,896,899
<p>I am using matlab 2016b and was excited to see that there is some python support in Matlab (<a href="https://uk.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html" rel="nofollow">https://uk.mathworks.com/help/matlab/matlab_external/call-python-from-matlab.html</a>)</p> <p>I was wondering if ther...
2
2016-10-06T13:08:15Z
39,898,393
<p>Yes sure! I agree that the documentation could be slightly better in that part, but anyways. Note that Python support has been available since MATLAB R2014b. So, first you should check that Python is available and you have the correct version installed:</p> <pre><code>pyversion </code></pre> <p>Next, create a Pyth...
1
2016-10-06T14:14:31Z
[ "python", "matlab" ]
Simple MLP time series training yields unexpeced mean line results
39,896,985
<p>I'm trying to play around with simple time series predictions. Given number of inputs (1Min ticks) Net should attempt to predict next one. I've trained 3 nets with different settings to illustrate my problem:</p> <p><a href="http://i.stack.imgur.com/F2JAw.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/F2JAw...
7
2016-10-06T13:12:17Z
39,947,694
<p>First of all, I want to commend you for usage non linear rectifying. According to what Geoffrey Hinton inventor of Boltzmann machine believe, non linear rectifier is a best feet for activities of human brain. </p> <p>But for other parts you've chosen I propose you to change NN architecture. For predictions of stock...
2
2016-10-09T19:32:02Z
[ "python", "neural-network", "deep-learning", "theano", "lasagne" ]
Make a filter to one color
39,896,995
<p>I tried to make a function to detect some word from browser. My current solution is take the screenshot in location where the text can appear.</p> <pre><code> im = ImageGrab.grab(bbox=(1229, 11, 1233, 20)) im = im.convert('1') pixels = im.getdata() </code></pre> <p>But, it work with only small picture wh...
0
2016-10-06T13:12:36Z
39,900,753
<p>You can use filtering on each point of image using the code below:</p> <pre><code>output = pixels.point(lambda x: 1 if x==REQUIREDCOLOR else 0, '1') </code></pre>
0
2016-10-06T16:03:23Z
[ "python", "python-imaging-library" ]
Pass data from a template tag to a django view
39,897,013
<p>I'd like to pass a parameter with data, like category_id=2 from my template to the view. Here is how I think it should work (which obviously doesn't)...</p> <p>The view </p> <pre><code>def category_detail(request, category_id): return_list = Category.objects.filter(category_id=category_id) return render(r...
0
2016-10-06T13:13:27Z
39,897,399
<p>You can build a list of urls by doing something like:</p> <pre><code>{% for category in expense_list.all %} &lt;a href="{% url 'app_label:view_name' category_id=category.id %}"&gt;{{ category.name }}&lt;/a&gt; {% endfor %} </code></pre> <p>Where app_label is the label/name of the app and view_name in this case...
0
2016-10-06T13:30:00Z
[ "python", "django" ]
Python: If Condition then skip to return
39,897,333
<p>I wondered if there is a nice way to tell the python interpreter to <strong>skip to the next/last return statement of a function</strong>.</p> <p>Lets assume the following dummy code:</p> <pre class="lang-py prettyprint-override"><code>def foo(bar): do(stuff) if condition: do(stuff) if condition2: ...
4
2016-10-06T13:26:55Z
39,897,500
<p>I think I would create a list of functions (I assume that all the <code>do(stuff)</code> in your example are actually different functions). Then you can use a <code>for</code> loop:</p> <pre><code>list_of_funcs = [func1, func2, func3] for func in list_of_funcs: func(stuff) if not condition: break re...
5
2016-10-06T13:34:03Z
[ "python", "return", "indentation" ]
Python: If Condition then skip to return
39,897,333
<p>I wondered if there is a nice way to tell the python interpreter to <strong>skip to the next/last return statement of a function</strong>.</p> <p>Lets assume the following dummy code:</p> <pre class="lang-py prettyprint-override"><code>def foo(bar): do(stuff) if condition: do(stuff) if condition2: ...
4
2016-10-06T13:26:55Z
39,897,551
<p>Refactoring your code is a <em>much</em> better idea than what I am about to suggest, but this is an option.</p> <pre><code>class GotoEnd(Exception): pass def foo(bar): try: do(stuff) if not condition: raise GotoEnd do(stuff) if not condition2: raise GotoEnd do(stuff) if not conditi...
0
2016-10-06T13:36:36Z
[ "python", "return", "indentation" ]
Insert data row-wise instead of column-wise and 1 blank row after each record
39,897,370
<p>Here is my code:</p> <pre><code>wb = Workbook() dest_filename = 'book.xlsx' th_list = ["this", "that", "what", "is", "this"] ws1 = wb.active ws1.title = 'what' for row in range(1, 2): for col in range(1, len(th_list)): _ = ws1.cell(column=col, row=row, value="{0}".format(th_list[col].encode('utf-8'))...
-1
2016-10-06T13:28:36Z
39,897,834
<p>Why are you writing something so incredibly complicated?</p> <pre><code>for v in th_list: ws.append([v]) # pad as necessary, never encode ws.append() # blank row </code></pre>
0
2016-10-06T13:50:51Z
[ "python", "python-2.7", "openpyxl" ]
Insert data row-wise instead of column-wise and 1 blank row after each record
39,897,370
<p>Here is my code:</p> <pre><code>wb = Workbook() dest_filename = 'book.xlsx' th_list = ["this", "that", "what", "is", "this"] ws1 = wb.active ws1.title = 'what' for row in range(1, 2): for col in range(1, len(th_list)): _ = ws1.cell(column=col, row=row, value="{0}".format(th_list[col].encode('utf-8'))...
-1
2016-10-06T13:28:36Z
39,913,364
<p>I have found the solution to both of my queries myself. Here it is:</p> <pre><code>wb = Workbook() dest_filename = 'book.xlsx' th_list = ["this", "that", "what", "is", "this"] ws1 = wb.active ws1.title = 'what' for col in range(1, 2): for row in range(1, len(th_list)+1): _ = ws1.cell(column=col, row=...
0
2016-10-07T08:58:43Z
[ "python", "python-2.7", "openpyxl" ]
Python and Node.js on Heroku
39,897,505
<p>I have started to make a Node server which runs on Heroku. It was working fine until I tried to use the (unofficial) Duolingo API. I wrote the following Python script to connect to the API:</p> <pre><code>import duolingo import simplejson as json lingo = duolingo.Duolingo('harleyrowland') print json.dumps(lingo.g...
0
2016-10-06T13:34:22Z
39,947,385
<p>Try to remove the deprecated <a href="https://github.com/ddollar/heroku-buildpack-multi" rel="nofollow">heroku-buildpack-multi</a> and use the Heroku <a href="https://devcenter.heroku.com/articles/using-multiple-buildpacks-for-an-app" rel="nofollow"><code>buildpacks</code></a> command:</p> <pre><code>$ heroku build...
1
2016-10-09T19:01:49Z
[ "python", "node.js", "heroku" ]
Unable to set manual scaling on a google app engine service
39,897,559
<p>I am unable to set manual scaling on a google app engine service (Previously called module). Using python on app engine. </p> <p><strong><em>app.yaml:</em></strong></p> <pre><code>application: xxx-xxxx version: 2 runtime: python27 module: xxbackend instance_class: F4 api_version: 1 threadsafe: true handlers: - ur...
2
2016-10-06T13:36:53Z
39,899,666
<p>You have the same <code>module:</code> name is both yamls. <code>app.yaml</code> should not specify a module, so it uses the <code>default</code> module. So remove <code>module: xxbackend</code> from <code>app.yaml</code>. Otherwise, you are overriding the expected config.</p> <p>Then, when you deploy, use a com...
1
2016-10-06T15:11:28Z
[ "python", "python-2.7", "google-app-engine" ]
Convert a string with ns precision to datetime in a panda dataframe
39,897,698
<p>I'm having a hard time converting a string with ns precision in a datetime format in a panda dataframe.</p> <p>I have a data frame like the following :</p> <pre><code>print df Event Time 0 A 08:00:00.123456789 1 B 08:00:00.234567890 2 C 08:00:00.345678901 </code></pre> <p...
2
2016-10-06T13:44:09Z
39,899,576
<p>The following did the trick for me:</p> <pre><code>&gt;&gt;&gt; df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S.%f') &gt;&gt;&gt; df Event Time 0 A 1900-01-01 08:00:00.123456789 1 B 1900-01-01 08:00:00.234567890 2 C 1900-01-01 08:00:00.345678901 </code></pre> <p>As n...
0
2016-10-06T15:07:45Z
[ "python", "pandas" ]
PyBluez doesn'y find a nBlue device
39,897,711
<p>I am trying to connect though Python BlueZ using the Linux Bluetooth stach to a small round nBlue device which works on Bluetooth, but the python program only finds devices like my phone or other laptops. What could be a potential problem?</p>
0
2016-10-06T13:44:49Z
39,984,040
<p>Your python programming is scanning for normal Bluetooth devices. You have to make it scan for BLE devices to see your small round nBlue device.</p> <p>For example, on my Raspberry Pi 3 with BlueZ installed:</p> <pre><code>sudo hcitool scan </code></pre> <p>sees <em>only</em> 'normal' bluetooth devices like phone...
0
2016-10-11T18:20:25Z
[ "python", "bluetooth", "iot", "bluez", "pybluez" ]
Python-Create array from txt
39,897,913
<p>I'm trying to create an array of stock tickers in Python 2.7 from a txt file. The txt file simply has 1 ticker per line like:</p> <pre><code>SRCE ABTX AMBC ATAX </code></pre> <p>The code I'm using looks like:</p> <pre><code>FinTick= [] def parseRus(): try: readFile=open(r'filename.txt','r').r...
2
2016-10-06T13:54:37Z
39,898,102
<pre><code>&gt;&gt;&gt; tickers = [] &gt;&gt;&gt; with open("filename.txt", "r") as f: for ticker in f.readlines(): tickers.append(ticker.strip()) &gt;&gt;&gt; tickers ['SRCE', 'ABTX', 'AMBC', 'ATAX'] </code></pre> <p>Try using <code>readlines()</code> and <code>strip()</code> instead.</p> <p>Ed...
2
2016-10-06T14:02:31Z
[ "python", "arrays", "python-2.7" ]
Python-Create array from txt
39,897,913
<p>I'm trying to create an array of stock tickers in Python 2.7 from a txt file. The txt file simply has 1 ticker per line like:</p> <pre><code>SRCE ABTX AMBC ATAX </code></pre> <p>The code I'm using looks like:</p> <pre><code>FinTick= [] def parseRus(): try: readFile=open(r'filename.txt','r').r...
2
2016-10-06T13:54:37Z
39,900,261
<p>I finally figured a fix.</p> <p>I had to modify the text file from 1 column to 1 row then saved as a .csv and modified the code to:</p> <pre><code>FinTick= [] def parseRus(): try: readFile=open(r'filename.csv','r').read() splitFile=readFile.split(',') for eachLine in splitFile: ...
0
2016-10-06T15:39:26Z
[ "python", "arrays", "python-2.7" ]
I am having diffculty to understand this program
39,897,974
<p>i just came across this program and it seems to me very difficult to understand. which is calculating the Fibonacci boundary for a positive number, returns a 2-tuple. The first element is the Largest Fibonacci Number smaller than x and the second component is the Smallest Fibonacci Number larger than x. The return v...
-2
2016-10-06T13:57:30Z
39,898,202
<blockquote> <p>Why is it returning -1</p> </blockquote> <p>It validates the input. There is no sensible result if <code>x</code> is less than zero so in that case it returns -1 which will cause the calling code to throw an exception when it fails to unpack the result. This is poor code, it would be much more normal...
1
2016-10-06T14:06:18Z
[ "python", "python-2.7", "python-3.x" ]
I am having diffculty to understand this program
39,897,974
<p>i just came across this program and it seems to me very difficult to understand. which is calculating the Fibonacci boundary for a positive number, returns a 2-tuple. The first element is the Largest Fibonacci Number smaller than x and the second component is the Smallest Fibonacci Number larger than x. The return v...
-2
2016-10-06T13:57:30Z
39,898,281
<pre><code>if x &lt; 0: return -1 </code></pre> <p>This is checking if the number is a positive integer bigger than one. Since Fib needs to be a positive integer. </p> <pre><code> if x &lt;= 0: break </code></pre> <p>Uses the above to check if it should print anything out (if there is a valid output to print...
0
2016-10-06T14:09:09Z
[ "python", "python-2.7", "python-3.x" ]
I am having diffculty to understand this program
39,897,974
<p>i just came across this program and it seems to me very difficult to understand. which is calculating the Fibonacci boundary for a positive number, returns a 2-tuple. The first element is the Largest Fibonacci Number smaller than x and the second component is the Smallest Fibonacci Number larger than x. The return v...
-2
2016-10-06T13:57:30Z
39,901,687
<p>If you are wondering, the reason why it has two output parameters and one output is since two numbers are being generated inside the function itself.</p> <p>If I have said program:</p> <pre><code>def diameter(x): diameter = x * 2 return diameter, x diameter, radius = diameter(radius) </code></pre> <p>the...
0
2016-10-06T16:56:14Z
[ "python", "python-2.7", "python-3.x" ]
Python Scipy Optimize with Lower bounds (instead of A_ub)
39,897,984
<p>I spent about 4-5 hours last night searching Stack Overflow, going through scipy optimize documents etc and could not find an answer to my problem. My question is, how do I set a lower bounds for the optimization equation when the option only seems to be for upper bound? Please see my equation and code below.</p> <...
0
2016-10-06T13:58:01Z
39,898,430
<p><code>a'x &gt;= b</code> is the same as <code>-a'x &lt;= -b</code>. I.e. multiply the <code>&gt;=</code> inequality by -1.</p>
0
2016-10-06T14:15:53Z
[ "python", "optimization" ]
Traversing json array in python
39,898,068
<p>I'm using urllib.request.urlopen to get a JSON response that looks like this:</p> <pre><code>{ "batchcomplete": "", "query": { "pages": { "76972": { "pageid": 76972, "ns": 0, "title": "Title", "thumbnail": { "original": "https://linktofile....
0
2016-10-06T14:01:15Z
39,898,142
<p>Do this instead:</p> <pre><code>my_content = json_object['query']['pages']['76972']['thumbnail']['original'] </code></pre> <p>The reason is, you need to mention <code>index</code> as <code>[0]</code> only when you have list as the object. But in your case, every item is of <code>dict</code> type. You need to speci...
2
2016-10-06T14:03:58Z
[ "python", "json", "django", "urllib" ]
Traversing json array in python
39,898,068
<p>I'm using urllib.request.urlopen to get a JSON response that looks like this:</p> <pre><code>{ "batchcomplete": "", "query": { "pages": { "76972": { "pageid": 76972, "ns": 0, "title": "Title", "thumbnail": { "original": "https://linktofile....
0
2016-10-06T14:01:15Z
39,898,148
<p>Doing <code>[0]</code> is looking for that key - which doesn't exist. Assuming you don't always know what the key of the page is, Try this:</p> <pre><code>pages = json_object['query']['pages'] for key, value in pages.items(): # this is python3 original = value['thumbnail']['original'] </code></pre> <p>Otherw...
0
2016-10-06T14:04:11Z
[ "python", "json", "django", "urllib" ]
Traversing json array in python
39,898,068
<p>I'm using urllib.request.urlopen to get a JSON response that looks like this:</p> <pre><code>{ "batchcomplete": "", "query": { "pages": { "76972": { "pageid": 76972, "ns": 0, "title": "Title", "thumbnail": { "original": "https://linktofile....
0
2016-10-06T14:01:15Z
39,898,166
<p>You can iterate over keys:</p> <pre><code>for page_no in json_object['query']['pages']: page_data = json_object['query']['pages'][page_no] </code></pre>
0
2016-10-06T14:05:06Z
[ "python", "json", "django", "urllib" ]
How to Login, Logout and User Registration through in build Authentication method?
39,898,103
<p>view.py</p> <pre><code>from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib import messages # Create your views here. def signin(request): if request.method=='POST': username=request.POST['username'] password=r...
2
2016-10-06T14:02:32Z
39,917,110
<blockquote> <p>Use this code for signin in views.py file</p> </blockquote> <pre><code>def signin(request): if request.method=='POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(...
3
2016-10-07T12:16:59Z
[ "python", "django" ]
No module named statistics.distributions
39,898,133
<p>I was trying to use Sympy stats library when i encountered this problem:</p> <pre><code>&gt;&gt;&gt; from sympy.statistics.distributions import Sample Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ImportError: No module named statistics.distributions </code></pre> <p>The pro...
2
2016-10-06T14:03:30Z
39,923,316
<p><code>sympy.statistics</code> has been removed in favor of <code>sympy.stats</code>. Here is the documentation: <a href="http://docs.sympy.org/latest/modules/stats.html" rel="nofollow">http://docs.sympy.org/latest/modules/stats.html</a>. </p> <p>For producing the mean of a list of numbers, you can use <code>Discret...
3
2016-10-07T17:59:50Z
[ "python", "python-3.x", "statistics", "sympy" ]
simplify numpy array representation of image
39,898,151
<p>I have an image, read into <code>np.array</code> by PIL. In my case, it's a<code>(1000, 1500)</code> <code>np.array</code>.</p> <p>I'd like to simplify it for visualisation purposes. By simplification, I following transformation from this matrix</p> <pre><code>1 1 1 1 0 0 1 0 1 0 0 0 </code></pre> <p>to </p> <p...
0
2016-10-06T14:04:30Z
39,898,302
<p>Use a combination of <code>np.reshape()</code> and <code>np.sum(array)</code> with <code>axis</code> argument.:</p> <pre><code>import numpy as np a = np.array([[1, 1, 1, 1, 0, 0], [1, 0, 1, 0, 0, 0]]) a = np.reshape(a, (a.shape[0]/2, 2, a.shape[1]/2, 2)) a = np.sum(a, axis=(1, 3)) &gt;= 2 </code></pre> <p>The resh...
1
2016-10-06T14:09:54Z
[ "python", "arrays", "image", "numpy", "image-processing" ]
simplify numpy array representation of image
39,898,151
<p>I have an image, read into <code>np.array</code> by PIL. In my case, it's a<code>(1000, 1500)</code> <code>np.array</code>.</p> <p>I'd like to simplify it for visualisation purposes. By simplification, I following transformation from this matrix</p> <pre><code>1 1 1 1 0 0 1 0 1 0 0 0 </code></pre> <p>to </p> <p...
0
2016-10-06T14:04:30Z
39,898,414
<p>You could use <a href="http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.fromarray" rel="nofollow"><code>PIL.Image.fromarray</code></a> to take the image into PIL, then <a href="http://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize" rel="nofollow">resize</a> or convert ...
1
2016-10-06T14:15:19Z
[ "python", "arrays", "image", "numpy", "image-processing" ]
heroku django server error
39,898,182
<p>Trying to deploy django project on heroku: <a href="https://crmtestnewone.herokuapp.com/crm/" rel="nofollow">https://crmtestnewone.herokuapp.com/crm/</a></p> <p>Do all as this instruction said but getting error (Server Error (500)) <a href="https://github.com/DjangoGirls/tutorial-extensions/blob/master/heroku/READM...
0
2016-10-06T14:05:44Z
39,899,982
<p>change to debug=true, got error: Could not parse the remainder: '=' from '=' in<br> problem was in: {% if search_clients = 'no auth'%} it should be == It works fine localy throught.</p> <p>Newtt thanks for your help!</p>
0
2016-10-06T15:25:56Z
[ "python", "django", "heroku" ]
Turning table data into columns and counting by frequency
39,898,338
<p>I have a dataframe in the following form:</p> <p><a href="http://i.stack.imgur.com/Ej9td.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ej9td.png" alt="enter image description here"></a></p> <p>shape is 2326 x 1271</p> <p>Column names are just serialized from 0-1269 while rows are categories that could re...
0
2016-10-06T14:11:59Z
39,899,507
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> along with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>crosstab</code></a> to compute the frequency counts:</p> <p><stro...
1
2016-10-06T15:04:59Z
[ "python", "pandas", "reshape" ]
How to type python file in cmd?
39,898,375
<p>I have completed a py file as follow:</p> <pre><code>import re file = open('/Path/text1.txt') word = 'summer flowers' try : flag = 0 for line in file : lines = line.lower() x=re.findall('.*'+word+'\s.*',lines) if len(x)&gt;0: flag =1 print line els...
0
2016-10-06T14:13:35Z
39,898,548
<pre><code>import re import sys file = sys.argv[2] word = sys.argv[1] try : flag = 0 for line in file : lines = line.lower() x=re.findall('.*'+word+'\s.*',lines) if len(x)&gt;0: flag =1 printline else: flag = flag if flag == 0: ...
2
2016-10-06T14:22:10Z
[ "python", "python-2.7", "text-mining" ]
How to type python file in cmd?
39,898,375
<p>I have completed a py file as follow:</p> <pre><code>import re file = open('/Path/text1.txt') word = 'summer flowers' try : flag = 0 for line in file : lines = line.lower() x=re.findall('.*'+word+'\s.*',lines) if len(x)&gt;0: flag =1 print line els...
0
2016-10-06T14:13:35Z
39,898,553
<p>Using the <code>sys</code> module. Specifically, <a href="https://docs.python.org/2/library/sys.html#sys.argv" rel="nofollow"><code>sys.argv</code></a></p> <p>From the docs:</p> <blockquote> <p>sys.argv</p> <p>The list of command line arguments passed to a Python script. argv[0] is the script name (it is op...
0
2016-10-06T14:22:18Z
[ "python", "python-2.7", "text-mining" ]
I need to host node js through python
39,898,439
<pre><code>var util = require('util'); var exec = require('child_process').spawn; var run = exec('/usr/bin/python', ['-m', 'SimpleHTTPServer', '9002']); run.stdout.on('data', function(data){ console.log('stdout: ' + data.toString()); }); run.stderr.on('data', function (data) { console.log('stderr: ' ...
-2
2016-10-06T14:16:20Z
39,901,825
<p>Not entirely sure I see the problem. Your code works. </p> <p>1) Make sure you access <code>localhost:9002</code><br> 2) If you meant to run your bottle code, then use </p> <pre><code>var run = exec('/usr/bin/python', ['/path/to/bottle_server.py']); </code></pre> <p><a href="http://i.stack.imgur.com/EEGKK.png" re...
0
2016-10-06T17:03:14Z
[ "python", "node.js", "client-server" ]
Understanding numpy condition on array
39,898,467
<p>I don't understand some code from Kaggle's solution. </p> <p>Here is an example of the data: </p> <pre><code>PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked 1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S 2,1,1,"Cumings, Mrs. John Bradley (Florence Briggs Thayer)",fem...
0
2016-10-06T14:18:06Z
39,898,675
<p>Here's how it works:</p> <p><code>women_only_stats = data[0::,4] == "female"</code> will create a <strong>mask</strong> (array of <code>booleans</code>) for the indices of your dataframe.</p> <p>When passed to <code>data</code>, the mask will do a <strong>projection</strong> on the samples where <code>women_only_...
1
2016-10-06T14:28:03Z
[ "python", "arrays", "numpy" ]
TF-IDF score from TfIdfTransformer in sklearn on same word in two sentences with same frequency
39,898,477
<p>If I have two sentences containing the same word, and this word appears with the same counts (frequency) in both sentences, why is the Tf-Idf score I get different for them?</p> <p>Consider this list of texts:</p> <pre><code>data = [ 'Jumper in knit.', 'A sweater in knit, black sweater.', ] </code></pre> ...
1
2016-10-06T14:18:29Z
39,899,936
<p>Reason is, after some more digging, that in the default configuration of the <code>TfIdfTransformer</code>, the scores get normalised in L2 norm at the end, per row.</p> <p>In fact, the kwarg <code>norm</code> is documents in the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.t...
0
2016-10-06T15:23:47Z
[ "python", "scikit-learn", "tf-idf" ]
Spyder 3.0 won't let me run file
39,898,490
<p>Spyder 3.0, Windows 10 64-bit</p> <p>Hello everyone, I used to be able to write code and run the files in Spyder without a problem but now the button to run the code is greyed out and I can't run the file. Not even using F5 or clicking Run from the Run menu tab.</p> <p><a href="http://i.stack.imgur.com/BIPMN.png" ...
-1
2016-10-06T14:19:03Z
39,963,557
<p>I'm having the exact same problem. Once I save my code turns white (I have a "skin" which is why its different) And it wouldn't let me run the file. I noticed that the saved file was in a different format which is probably be the cause. But I just did a simple factory reset and it works for me now.</p>
0
2016-10-10T17:21:58Z
[ "python", "menu", "spyder" ]
Python: How to initialize a list with generator function
39,898,514
<p>Let's say i have 2 following functions:</p> <pre><code>def get_items(): items = [] for i in xrange(2, 10): items.append(i) return items def gen_items(): for i in xrange(2, 10): yield i </code></pre> <p>I know i can use both of them in a for loop like this</p> <pre><code>for item i...
3
2016-10-06T14:20:28Z
39,898,547
<p>The list builtin will accept any iterator: </p> <pre><code>l = list(gen_items()) </code></pre>
4
2016-10-06T14:22:05Z
[ "python", "generator" ]
Python: How to initialize a list with generator function
39,898,514
<p>Let's say i have 2 following functions:</p> <pre><code>def get_items(): items = [] for i in xrange(2, 10): items.append(i) return items def gen_items(): for i in xrange(2, 10): yield i </code></pre> <p>I know i can use both of them in a for loop like this</p> <pre><code>for item i...
3
2016-10-06T14:20:28Z
39,898,551
<p>You can just directly create it using <code>list</code> which will handle iterating for you</p> <pre><code>&gt;&gt;&gt; list(gen_items()) [2, 3, 4, 5, 6, 7, 8, 9] </code></pre>
3
2016-10-06T14:22:14Z
[ "python", "generator" ]
'Wrong number of dimensions' error in Theano - LSTM
39,898,576
<p>I am trying to recreate <a href="http://christianherta.de/lehre/dataScience/machineLearning/neuralNetworks/LSTM.php" rel="nofollow">this</a> LSTM example for my own data. </p> <pre><code>Traceback (most recent call last): File "lstm.py", line 124, in &lt;module&gt; train_rnn(train_data) File "lstm.py", line...
1
2016-10-06T14:23:17Z
39,949,934
<p>The function create_dataset is returning one numpy array. However, when you call i, o = train_data[index], you are trying to obtain two values. You can for example assigning the value to a temporal variable, and then split it as you need.</p> <p><strong>EDIT</strong> the variables <code>i</code> and <code>o</code> ...
0
2016-10-10T00:38:21Z
[ "python", "numpy", "deep-learning", "theano", "lstm" ]
Python: List youtube videos titles and url from an extracted HTML
39,898,644
<p>I'm making a simple script with Python 3.5, it asks a title (e.g. a song), it goes on youtube.com/results?search_query=my+title and extracts the html code.</p> <p>That's what I did, but now i'm facing a problem: I want my script to list the videos propositions title and register the corresponding link, so e.g it gi...
0
2016-10-06T14:26:20Z
39,899,009
<p>You can use the built in htmlparser library in python to extract the tags that contain the titles of the videos that you want. This library will be give you multiple ways to parse through tags as well as provide you with a clearer readable output.</p> <p><a href="https://docs.python.org/3/library/html.parser.html" ...
0
2016-10-06T14:43:00Z
[ "python", "html", "video", "youtube" ]
I have a dictionary stored as numpy array a typical key is in the format of
39,898,668
<p>I have a dictionary of data stored as a numpy array. A typical key in the dictionary is in the format of:</p> <pre><code>('Typical Key', {'a': 100 'b': 'NaN', 'c': 'NaN', 'e': 360300, 'f': 8308552, 'g': 'NaN', 'h': 3576206, 'i': True, 'j': 'NaN', 'k': 'NaN', 'l': 'NaN', 'm': 'blah.blah@blah.com', 'x': 'NaN'}) </cod...
2
2016-10-06T14:27:39Z
39,898,851
<pre><code>import sys Max = -sys.maxint best_key = None for k, v in data_dict: # k refers to each 'typical key' inner_dict = v for key, value in inner_dict.items(): if isinstance(value, int) and Max &lt; value: Max = value best_key = key print best_key </code></pre>
0
2016-10-06T14:36:03Z
[ "python", "pandas", "numpy", "dictionary", "regression" ]
I have a dictionary stored as numpy array a typical key is in the format of
39,898,668
<p>I have a dictionary of data stored as a numpy array. A typical key in the dictionary is in the format of:</p> <pre><code>('Typical Key', {'a': 100 'b': 'NaN', 'c': 'NaN', 'e': 360300, 'f': 8308552, 'g': 'NaN', 'h': 3576206, 'i': True, 'j': 'NaN', 'k': 'NaN', 'l': 'NaN', 'm': 'blah.blah@blah.com', 'x': 'NaN'}) </cod...
2
2016-10-06T14:27:39Z
39,900,559
<p>O.K sorted it by tweaking the code proplerly - possibly because i had not articulated what i wanted to do properly Had to tweak the code slightly but this did work - i need to work to understand why my other code was not returning the expected value </p> <pre><code>import sys Max = -sys.maxint best_key = None f...
1
2016-10-06T15:54:18Z
[ "python", "pandas", "numpy", "dictionary", "regression" ]
I have a dictionary stored as numpy array a typical key is in the format of
39,898,668
<p>I have a dictionary of data stored as a numpy array. A typical key in the dictionary is in the format of:</p> <pre><code>('Typical Key', {'a': 100 'b': 'NaN', 'c': 'NaN', 'e': 360300, 'f': 8308552, 'g': 'NaN', 'h': 3576206, 'i': True, 'j': 'NaN', 'k': 'NaN', 'l': 'NaN', 'm': 'blah.blah@blah.com', 'x': 'NaN'}) </cod...
2
2016-10-06T14:27:39Z
39,901,951
<p>With your sample dictionary:</p> <pre><code>In [684]: dd Out[684]: {'a': 100, 'b': 'NaN', 'c': 'NaN', 'e': 360300, 'f': 8308552, 'g': 'NaN', 'h': 3576206, 'i': True, 'j': 'NaN', 'k': 'NaN', 'l': 'NaN', 'm': 'blah.blah@blah.com', 'x': 'NaN'} </code></pre> <p>I can easily pull out a list of the values -...
0
2016-10-06T17:10:37Z
[ "python", "pandas", "numpy", "dictionary", "regression" ]
MLP in tensorflow for regression... not converging
39,898,696
<p>Hello it is my first time working with tensorflow, i try to adapt the example here <a href="https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/multilayer_perceptron.py" rel="nofollow">TensorFlow-Examples</a> to use this code for regression problems with boston database. Basica...
1
2016-10-06T14:28:59Z
39,900,746
<p>A couple of points. </p> <p>Your model is quite shallow being only two layers. Granted you'll need more data to train a larger model so I don't know how much data you have in the Boston data set.</p> <p>What are your labels? That would better inform whether squared error is better for your model.</p> <p>Also you...
0
2016-10-06T16:03:04Z
[ "python", "machine-learning", "tensorflow", "multi-layer" ]
Logger to not show INFO from external libaries
39,898,754
<p>I want logger to print INFO messages from all my code but not from 3rd party libraries. This is discussed in multiple places, but the suggested solution does not work for me. Here is my simulation of external library, <code>extlib.py</code>:</p> <pre><code>#!/usr/bin/env python3 from logging import info def f(): ...
0
2016-10-06T14:31:56Z
39,898,805
<p>The problem is that they aren't using the logger class in the external library. If they were then you could filter it out. I'm not certain you can stop them from logging information since they are using the <code>info</code> function call. Here is a workaround though.</p> <p><a href="http://stackoverflow.com/que...
2
2016-10-06T14:34:11Z
[ "python", "logging" ]
Django: how to add compare condition in annotate queryset
39,898,782
<p>I want to add compare operations in annotate queryset to calculate value for specific field. How can I do that? This is my annotate queryset</p> <pre><code>sale_item_list = OrderItem.objects.filter(order_id=order.id) \ .values('item__name') \ .annotate(price=F('price')) \ ...
1
2016-10-06T14:32:49Z
39,899,080
<p>Try using the lesser and greater than field lookups <code>__gt</code> and <code>__lt</code>:</p> <pre><code>When(quantity__lt=inventory, then=Sum(F('quantity') * F('price'))), When(quantity__gt=inventory, then=Sum(F('inventory') * F('price'))), </code></pre> <p>See <a href="https://docs.djangoproject.com/el/1.10/r...
1
2016-10-06T14:46:04Z
[ "python", "django", "python-3.x" ]
How to Print a Path in Python?
39,898,784
<p>I want to make a script open the CMD and then enter a path:</p> <pre><code>import pyautogui as pag pag.hotkey('win','r') pag.typewrite('cmd') pag.press('enter') pag.typewrite('C:\Users\XY\AppData\') </code></pre> <p>that doesn't work. So, I tried this:</p> <pre><code>import pyautogui as pag pag.hotkey('win',...
0
2016-10-06T14:33:02Z
39,899,011
<p>when a string is read in from <code>input()</code> or from text boxes in gui's (in general.. idk about pag) the extra slashes are automatically put in. They are not automatically put in for string literals in your code however and must be escaped (hence the double slash). Here is a short console session (python 2.7)...
0
2016-10-06T14:43:07Z
[ "python", "python-3.x", "printing", "pyautogui" ]
SFTP via Paramiko to ipv6 linux machine
39,898,819
<p>I am relatively new to python and am trying sftp for the first time via python script. I want my python script to get a file from a <strong>Dual Stack Machine (Both IPv4 and IPv6 present)</strong>. Below is the code snippet I am using for Paramiko:</p> <pre><code>host = ip #ip is a string that has the value of IP p...
0
2016-10-06T14:34:37Z
39,922,784
<p>Paramiko's <code>Transport</code> class supports passing in a socket object as well as a tuple. So maybe try specifically passing in an ipv6 socket?</p> <pre><code>import socket sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock.connect((hostname, port)) transport = paramiko.Transport(sock) </code></pr...
1
2016-10-07T17:21:31Z
[ "python", "linux", "python-2.7", "paramiko" ]
Python callback variable scope
39,898,876
<p>I have a function <code>fun()</code> that binds a callback <code>callback()</code> when a matplotlib figure is clicked. I want this callback to be able to access the variable space of <code>fun()</code> to make changes. How can I go about this?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def ...
0
2016-10-06T14:37:04Z
39,899,375
<p>I understand you would like to have some state, that can be changed during runtime. One option might be to use a callable object, that is not a function (I have not tested it):</p> <pre><code>class Callback(object): def __init__(self, data): self.data = data def __call__(self, event): # ...
1
2016-10-06T14:58:58Z
[ "python", "matplotlib", "scope" ]
Python sqlite3: INSERT into table WHERE NOT EXISTS, using ? substitution parameter
39,898,887
<p>I'm creating a table of descriptions from a list of not necessarily unique descriptions. I would like the table to contain only distinct descriptions, so while inserting descriptions into the table, I need to check to see if they already exist. My code(simplified) looks something like as follows:</p> <pre><code>cur...
0
2016-10-06T14:37:39Z
39,900,386
<p>To replace <code>VALUES</code> by <code>SELECT</code> should work</p> <pre><code>cursor.executemany(''' INSERT INTO descriptions(desc) SELECT (?) WHERE NOT EXISTS ( SELECT * FROM descriptions as d WHERE d.desc=?)''', zip(descripts, descripts)) </code></pre>
1
2016-10-06T15:45:36Z
[ "python", "python-2.7", "sqlite", "sqlite3" ]
Python Case Matching Input and Output
39,898,890
<p>I'm doing the pig latin question that I'm sure everyone here is familiar with it. The only thing I can't seem to get is matching the case of the input and output. For example, when the user enters Latin, my code produces <code>atinLay</code>. I want it to produce <code>Atinlay</code>.</p> <pre><code>import string ...
2
2016-10-06T14:37:46Z
39,898,991
<p>simply use the built in string functions.</p> <pre><code>s = "Hello".lower() s == "hello" s = "hello".upper() s == "HELLO" s = "elloHay".title() s == "Ellohay" </code></pre>
0
2016-10-06T14:42:08Z
[ "python", "string" ]
Python Case Matching Input and Output
39,898,890
<p>I'm doing the pig latin question that I'm sure everyone here is familiar with it. The only thing I can't seem to get is matching the case of the input and output. For example, when the user enters Latin, my code produces <code>atinLay</code>. I want it to produce <code>Atinlay</code>.</p> <pre><code>import string ...
2
2016-10-06T14:37:46Z
39,899,077
<p>What you need is <a href="http://docs.python/3/library/stdtypes.html#str.title" rel="nofollow"><code>str.title()</code></a>. Once you have done your piglatin conversion, you can use <code>title()</code> built-in function to produce the desired output, like so:</p> <pre><code>&gt;&gt;&gt; "atinLay".title() 'Atinlay'...
1
2016-10-06T14:45:55Z
[ "python", "string" ]
Global name 'camera' is not defined in python
39,898,927
<p>In this script :-</p> <pre><code>camera_port = 0 ramp_frames = 400 camera = cv2.VideoCapture(camera_port) def get_image(): global camera retval, im = camera.read() return im def Camera(): global camera for i in xrange(ramp_frames): temp = get_image() print("Taking image...") camera_capt...
6
2016-10-06T14:39:13Z
39,899,081
<p>You need to have defined <code>camera</code> outside the scope of your methods as well. What the <code>global</code> keyword does is tell Python that you will modify that variable which you defined externally. If you haven't, you get this error.</p> <p><strong>EDIT</strong></p> <p>I didn't notice that you had alr...
4
2016-10-06T14:46:14Z
[ "python", "python-2.7", "opencv" ]
Changing string to an existing variable name to create 1 function for multiple variables (Inside class, using root from Tkinter)
39,898,992
<pre><code>from tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.plot = Canvas(master, width=500, height=120) self.plot.pack() self.1 = self.plot.create_text(10,10, text = "0") self.2 = self.plot.create_text(30,10, te...
0
2016-10-06T14:42:26Z
39,899,135
<p>This is called <code>setattr()</code> in python:</p> <pre><code>&gt;&gt;&gt; a = App(...) &gt;&gt;&gt; setattr(a, "name", "foo") &gt;&gt;&gt; a.name "foo" </code></pre>
1
2016-10-06T14:47:59Z
[ "python", "string", "variables", "tkinter", "tkinter-canvas" ]
Changing string to an existing variable name to create 1 function for multiple variables (Inside class, using root from Tkinter)
39,898,992
<pre><code>from tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.plot = Canvas(master, width=500, height=120) self.plot.pack() self.1 = self.plot.create_text(10,10, text = "0") self.2 = self.plot.create_text(30,10, te...
0
2016-10-06T14:42:26Z
39,899,219
<p>Create a function within your class using <code>setattr()</code> as:</p> <pre><code>def update_property(self, name, value): self.setattr(name, value) </code></pre> <p>Here, <code>name</code> is the class's <code>peoperty</code> and <code>value</code> is the value you want to set for the previosu property </p>
0
2016-10-06T14:52:20Z
[ "python", "string", "variables", "tkinter", "tkinter-canvas" ]
Changing string to an existing variable name to create 1 function for multiple variables (Inside class, using root from Tkinter)
39,898,992
<pre><code>from tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.plot = Canvas(master, width=500, height=120) self.plot.pack() self.1 = self.plot.create_text(10,10, text = "0") self.2 = self.plot.create_text(30,10, te...
0
2016-10-06T14:42:26Z
39,902,027
<p>The proper solution isn't to translate strings to variable names. Instead, store the items in a list or dictionary.</p> <p>For example, this uses a dictionary:</p> <pre><code>class App: def __init__(self, master): ... self.items = {} self.items[1] = self.plot.create_text(10,10, text = "...
0
2016-10-06T17:15:17Z
[ "python", "string", "variables", "tkinter", "tkinter-canvas" ]
How to flatten a pandas dataframe with some columns as json?
39,899,005
<p>I have a dataframe <code>df</code> that loads data from a database. Most of the columns are json strings while some are even list of jsons. For example:</p> <pre><code>id name columnA columnB 1 John {"dist": "600", "time": "0:12.10"} [{"pos": "1st", "value": "500"},{...
3
2016-10-06T14:42:52Z
39,899,896
<p>create a custom function to flatten <code>columnB</code> then use <code>pd.concat</code></p> <pre><code>def flatten(js): return pd.DataFrame(js).set_index('pos').squeeze() pd.concat([df.drop(['columnA', 'columnB'], axis=1), df.columnA.apply(pd.Series), df.columnB.apply(flatten)], axis=1) ...
2
2016-10-06T15:21:36Z
[ "python", "json", "pandas", "flatten" ]
How to flatten a pandas dataframe with some columns as json?
39,899,005
<p>I have a dataframe <code>df</code> that loads data from a database. Most of the columns are json strings while some are even list of jsons. For example:</p> <pre><code>id name columnA columnB 1 John {"dist": "600", "time": "0:12.10"} [{"pos": "1st", "value": "500"},{...
3
2016-10-06T14:42:52Z
39,906,235
<p>Here's a solution using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.json.json_normalize.html" rel="nofollow"><code>json.normalize</code></a> again by using a custom function to get the data in the correct format understood by <code>json.normalize</code> function.</p> <pre><code>import a...
3
2016-10-06T21:57:45Z
[ "python", "json", "pandas", "flatten" ]
Communicate multiple times with a subprocess in Python
39,899,074
<p>This question is NOT a duplicate of </p> <p><a href="http://stackoverflow.com/questions/3065060/communicate-multiple-times-with-a-process-without-breaking-the-pipe">Communicate multiple times with a process without breaking the pipe?</a></p> <p>That question is solved because its use case allows inputs to be sent ...
0
2016-10-06T14:45:45Z
39,909,410
<p>Basicly <a href="http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python">Non-blocking read on a subprocess.PIPE in python</a></p> <p>Set the proc pipes (proc.stdout, proc.stdin, ...) to nonblocking mode via <code>fnctl</code> and then write/read them directly.</p> <p>You might w...
0
2016-10-07T04:30:15Z
[ "python" ]
Import CSV file into SQL Server using Python
39,899,088
<p>I am having trouble uploading a CSV file into a table in MS SQL Server, The CSV file has 25 columns and the header has the same name as table in SQL which also has 25 columns. When I run the script it throws an error </p> <pre><code>params arg (&lt;class 'list'&gt;) can be only a tuple or a dictionary </code></pre>...
1
2016-10-06T14:46:28Z
39,904,616
<p>You are using <code>csv.reader</code> incorrectly. The first argument to <code>.reader</code> is not the path to the CSV file, it is</p> <blockquote> <p>[an] object which supports the iterator protocol and returns a string each time its <code>__next__()</code> method is called — file objects and list objects ar...
0
2016-10-06T19:55:55Z
[ "python", "python-3.x", "pymssql" ]
How to send a repeat request in urllib2.urlopen in Python if the first call is just stuck?
39,899,092
<p>I am making a call to a URL in Python using urllib2.urlopen in a while(True) loop</p> <p>My URL keeps changing every time (as there is a change in a particular parameter of the URL every time).</p> <p>My code look as as follows:</p> <pre><code>def get_url(url): '''Get json page data using a specified API url'...
0
2016-10-06T14:46:31Z
39,899,347
<p>Depending on how many retries you want to attempt, use a try/catch inside a loop:</p> <pre><code>while True: try: response = urlopen(url, timeout=10) break except: # do something with the error pass # do something with response data = str(response.read().decode('utf-8')) ... ...
1
2016-10-06T14:57:48Z
[ "python", "http", "urllib2" ]
How to send a repeat request in urllib2.urlopen in Python if the first call is just stuck?
39,899,092
<p>I am making a call to a URL in Python using urllib2.urlopen in a while(True) loop</p> <p>My URL keeps changing every time (as there is a change in a particular parameter of the URL every time).</p> <p>My code look as as follows:</p> <pre><code>def get_url(url): '''Get json page data using a specified API url'...
0
2016-10-06T14:46:31Z
39,899,854
<p>With this method you can retry once. </p> <pre><code>def get_url(url, trial=1): try: '''Get json page data using a specified API url''' response = urlopen(url, timeout=10) data = str(response.read().decode('utf-8')) page = json.loads(data) return page except: ...
0
2016-10-06T15:19:41Z
[ "python", "http", "urllib2" ]
How can I store in a variable certain lines in python?
39,899,142
<p>I have this code: </p> <pre><code>with open("/etc/network/interfaces", "r") as file: content = file.read() print content </code></pre> <p>it's working and showing this:</p> <p><a href="http://i.stack.imgur.com/Zauen.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zauen.png" alt="enter image descrip...
-3
2016-10-06T14:48:27Z
39,899,355
<pre><code>with open("/etc/network/interfaces", "r") as file: for line in file: words=line.split(' ')#break the line into a list of words. print(words[0],words[1]) # </code></pre> <p>I have not tested it, but gives you an idea.</p>
0
2016-10-06T14:58:08Z
[ "python", "linux", "python-2.7", "python-3.x", "debian" ]
How can I store in a variable certain lines in python?
39,899,142
<p>I have this code: </p> <pre><code>with open("/etc/network/interfaces", "r") as file: content = file.read() print content </code></pre> <p>it's working and showing this:</p> <p><a href="http://i.stack.imgur.com/Zauen.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zauen.png" alt="enter image descrip...
-3
2016-10-06T14:48:27Z
39,899,482
<blockquote> <p>For example, I want to store the word (lo) in the second line in a variable and then print that variable.</p> </blockquote> <p>Use the re module in Python's builtin library:</p> <pre><code>import re with open("/etc/network/interfaces", "r") as file: content = file.readlines() target_word = re....
0
2016-10-06T15:03:50Z
[ "python", "linux", "python-2.7", "python-3.x", "debian" ]
overlapping tick labels on plot consisting of several axis - tight_layout not working
39,899,145
<p>In a plot constructed by the code </p> <pre><code>left, width = 0.1, 0.8 rect1 = [left, 0.7, width, 0.2] rect2 = [left, 0.3, width, 0.4] rect3 = [left, 0.1, width, 0.2] fig = plt.figure(facecolor='white') ax1 = fig.add_axes(rect1) ax2 = fig.add_axes(rect2,sharex=ax1) ax3 = fig.add_axes(rect3,sharex=ax1) </code></pr...
-1
2016-10-06T14:48:28Z
39,899,708
<p>By setting the y-labels manually, using </p> <pre><code> ax1.set_yticks([30, 70]) </code></pre> <p>the overlap can be prevented. </p> <p>This solution is not completely satisfying however, since it is hardcoded and not very generic. But it works for this specific problem.</p> <p>Another solution would be to move...
0
2016-10-06T15:13:06Z
[ "python", "matplotlib" ]
How Can I implement functions like mean.median and variance if I have a dictionary with 2 keys in Python?
39,899,162
<p>I have many files in a folder that like this one: <a href="http://i.stack.imgur.com/MitYd.png" rel="nofollow">enter image description here</a></p> <p>and I'm trying to implement a dictionary for data. I'm interested in create it with 2 keys (the first one is the http address and the second is the third field (plugi...
0
2016-10-06T14:49:08Z
39,900,206
<p>You can do what you want using a dictionary, but you should really consider using the <a href="http://pandas.pydata.org/" rel="nofollow">Pandas</a> library. This library is centered around tabular data structure called "DataFrame" that excels in column-wise and row-wise calculations such as the one that you seem to ...
1
2016-10-06T15:36:44Z
[ "python", "dictionary" ]
pandas fillna date from another column
39,899,396
<p>Get my test data:</p> <pre><code> import pandas as pd df = {'Id': {1762056: 2.0, 1762055: 1.0}, 'FillDate': {1762056: Timestamp('2015-08-01 00:00:00'), 1762055:Timestamp('2015-08-01 00:00:00')}, 'Date': {1762056: nan, 1762055: nan}, } df = pd.DataFrame(df) </code></pre> <p>Data looks like:</p> <pre><cod...
1
2016-10-06T14:59:49Z
39,899,458
<p>This worked:</p> <pre><code> df['Date'].fillna(pd.to_datetime(df['FillDate']).dt.date, inplace=True) </code></pre> <p>which gives</p> <pre><code> Id Date FillDate 1.0 2015-08-01 2015-08-01 2.0 2015-08-01 2015-08-01 </code></pre>
3
2016-10-06T15:02:44Z
[ "python", "date", "datetime", "pandas", "data-manipulation" ]
IndentationError: unindent does not match any outer indentation level - tokenize, line 8
39,899,428
<pre><code>import calendar def leapyr(year1, year2): count = 0 while year1 &lt;= year2: if calendar.isleap(year1) == True: count = count + 1 year1 = year1 + 1 print count leapyr(2008, 1015) </code></pre> <p>i have no bloody idea why this doesnt work. I tried "python -m tabnan...
-2
2016-10-06T15:01:13Z
39,903,158
<p>Python allows mixing tabs and spaces. Before interpreting the source, python interpreter replaces tabs with spaces in such way that each tab is aligned to 8 spaces (see <a href="https://docs.python.org/2/reference/lexical_analysis.html#indentation" rel="nofollow">the doc on indentation</a>).</p> <p>If your editor i...
0
2016-10-06T18:25:31Z
[ "python" ]
Match Making using GAE + ndb
39,899,451
<p>I have a game in which users contact a server to find a user of their level who wants to play a game. Here is the basic architecture of a game request.</p> <p><a href="http://i.stack.imgur.com/vMIHi.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/vMIHi.jpg" alt="enter image description here"></a></p> <p>I a...
3
2016-10-06T15:02:29Z
39,902,281
<p>Not sure about your first question, but you might be able to simulate it with a sleep statement in your transaction.</p> <p>For your second question, there is another architecture that you could use. If the waiting queue duration is relatively short (minutes instead of hours), you might want to use memcache. It w...
2
2016-10-06T17:31:31Z
[ "python", "google-app-engine", "google-cloud-datastore", "app-engine-ndb" ]
Match Making using GAE + ndb
39,899,451
<p>I have a game in which users contact a server to find a user of their level who wants to play a game. Here is the basic architecture of a game request.</p> <p><a href="http://i.stack.imgur.com/vMIHi.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/vMIHi.jpg" alt="enter image description here"></a></p> <p>I a...
3
2016-10-06T15:02:29Z
39,916,238
<p>1.- If you do the entity get and the post inside a transaction, then the same entity can not be matched for a game and therefore no error and it remains consistent.</p> <p>2.- The 1 write per second is sthe limit for transactions inside the same entity group. If you need more, you can shard the queue entity.</p> <...
1
2016-10-07T11:33:51Z
[ "python", "google-app-engine", "google-cloud-datastore", "app-engine-ndb" ]
pyaes and the relationship between byte and str in Python 3?
39,899,477
<p>I'm trying to use pyaes (<a href="https://github.com/ricmoo/pyaes/blob/master/README.md" rel="nofollow">https://github.com/ricmoo/pyaes/blob/master/README.md</a>) in Python 3 to encrypt and decrypt text using pyaes. When I encrypt text, I give pyaes a <code>str</code> value i.e.</p> <pre><code>plaintext = 'plain te...
2
2016-10-06T15:03:35Z
39,899,953
<p><code>decrypted_plaintext.decode()</code> will give you a <code>str</code>, which will most likely be what you want. A <code>bytes</code> object is a raw string of bytes in an unspecified encoding. To convert that to a <code>str</code>, you have to tell Python to decode it using <a href="https://docs.python.org/3/...
0
2016-10-06T15:24:34Z
[ "python", "encryption" ]
pyaes and the relationship between byte and str in Python 3?
39,899,477
<p>I'm trying to use pyaes (<a href="https://github.com/ricmoo/pyaes/blob/master/README.md" rel="nofollow">https://github.com/ricmoo/pyaes/blob/master/README.md</a>) in Python 3 to encrypt and decrypt text using pyaes. When I encrypt text, I give pyaes a <code>str</code> value i.e.</p> <pre><code>plaintext = 'plain te...
2
2016-10-06T15:03:35Z
39,900,016
<p>In Python 3 <code>str</code> type represents a string in unicode format. It is composed of relatively abstract codepoints, that is numbers coding characters. There are several ways to transform (encode) those codepoints to actual bytes which are known as "encodings". utf-8 and utf-16 are some encodings which allow t...
0
2016-10-06T15:27:49Z
[ "python", "encryption" ]