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
How would I make a simple recursive function outputting the number of divisors a number has?
38,493,387
<p>In an online class, I received this problem.</p> <p>Write a function numDivisors( N ) that returns the number of integers from 1 to N (inclusive) that divide N evenly. For example, numDivisors(42) would return 8, since 1, 2, 3, 6, 7, 14, 21, and 42 are divisors of 42. (Python 2.7)</p> <p>Although I have solved it ...
0
2016-07-21T01:26:12Z
38,493,455
<p>how about</p> <pre><code>def find_divisors(N,i=1): if i &gt;= N**0.5+1: return set([]) if N%i == 0: return set([i,N//i]).union(find_divisors(N,i+1)) return find_divisors(N,i+1) </code></pre> <p>recursion is a pretty lousy solution to this problem ... do you really need to find all the divisors? or are ...
1
2016-07-21T01:33:04Z
[ "python", "recursion" ]
How would I make a simple recursive function outputting the number of divisors a number has?
38,493,387
<p>In an online class, I received this problem.</p> <p>Write a function numDivisors( N ) that returns the number of integers from 1 to N (inclusive) that divide N evenly. For example, numDivisors(42) would return 8, since 1, 2, 3, 6, 7, 14, 21, and 42 are divisors of 42. (Python 2.7)</p> <p>Although I have solved it ...
0
2016-07-21T01:26:12Z
38,493,635
<p>If we have to be recursive:</p> <pre><code>&gt;&gt;&gt; def ndiv(N, i=1): ... return 1 if N==i else ((N % i == 0) + ndiv(N, i+1)) ... </code></pre> <p>Let's test it. As per the question:</p> <blockquote> <p>For example, numDivisors(42) would return 8</p> </blockquote> <pre><code>&gt;&gt;&gt; ndiv(42) 8 </...
1
2016-07-21T01:57:43Z
[ "python", "recursion" ]
Append keys and values to one JSON object from multiple JSON files
38,493,405
<p>I'm currently working with three json files. </p> <p>master.json</p> <pre><code> { "master":[ { "sport": "soccer", "id": 1 }, { "sport": "football", "id": 2 } ] } </code></pre> <p>data1.json</p> <pre><code>{ "soccer": { "players": 11 }, "football": { "pla...
0
2016-07-21T01:28:15Z
38,493,667
<p>This will do it. Bare in mind, this is for your case.</p> <pre><code>var master = { "master":[ { "sport": "soccer", "id": 1 }, { "sport": "football", "id": 2 } ] } var data1 = { "soccer": { "players": 11 }, "football": { "players": 12 } } var data2 = { ...
1
2016-07-21T02:01:19Z
[ "javascript", "python", "json" ]
Append keys and values to one JSON object from multiple JSON files
38,493,405
<p>I'm currently working with three json files. </p> <p>master.json</p> <pre><code> { "master":[ { "sport": "soccer", "id": 1 }, { "sport": "football", "id": 2 } ] } </code></pre> <p>data1.json</p> <pre><code>{ "soccer": { "players": 11 }, "football": { "pla...
0
2016-07-21T01:28:15Z
38,493,755
<p>Just to demonstrate the relative finesse of Python, I'll throw in a solution:</p> <pre><code>import json from collections import OrderedDict with open('master.json') as m, open('data1.json') as d1, open('data2.json') as d2: master = json.load(m, object_pairs_hook=OrderedDict) data1 = json.load(d1, object_p...
1
2016-07-21T02:12:49Z
[ "javascript", "python", "json" ]
python one-liner to do arithmetic operation on one element with same index for all sublists
38,493,469
<p>For example: I need to create a <code>list2</code> as <code>[[2, 0], [3, 0], [4, 0]]</code> from existing list <code>[[1, 0], [2, 0], [3, 0]]</code>. The index of the element is the same among all the sublist (0). How to achieve using one-liner?</p> <p>I have tried:</p> <pre><code>list=[[1,0],[2,0],[3,0]] list2=[i...
2
2016-07-21T01:35:39Z
38,493,493
<p><code>list2 = [[i+1,j], for [i,j] in list]</code></p> <p>if your sublists have different lengths:</p> <p><code>list2 = [[x[0]+1]+x[1:] for x in list]</code></p>
4
2016-07-21T01:38:09Z
[ "python", "list" ]
python one-liner to do arithmetic operation on one element with same index for all sublists
38,493,469
<p>For example: I need to create a <code>list2</code> as <code>[[2, 0], [3, 0], [4, 0]]</code> from existing list <code>[[1, 0], [2, 0], [3, 0]]</code>. The index of the element is the same among all the sublist (0). How to achieve using one-liner?</p> <p>I have tried:</p> <pre><code>list=[[1,0],[2,0],[3,0]] list2=[i...
2
2016-07-21T01:35:39Z
38,493,503
<p><code>[[x[0]+1,x[1]] for x in list]</code> although you really should not name things list because of name conflicts</p>
2
2016-07-21T01:39:27Z
[ "python", "list" ]
Python script running twice
38,493,508
<p>Can somebody help me understand why is my code executed twice?</p> <pre><code>import multiprocessing from time import sleep import os, signal def neverEnding(): while True: print ' Looping ... ' sleep(3) p = multiprocessing.Process(target=neverEnding) p.start() sleep(10) print p.is_alive() ...
2
2016-07-21T01:40:13Z
38,493,911
<p>Which python version do you use? I am using 2.6.9 on linux, the same code as yours but get the different result:</p> <pre><code> *Looping ... Looping ... Looping ... Looping ... True 6634 True terminated? Now? False* </code></pre> <p>The problem of why after "p.terminate()" the process is still alive is due to ...
0
2016-07-21T02:30:38Z
[ "python", "multiprocessing" ]
Accessing MATLAB data in Python with a concatenated filename
38,493,542
<p>I'm translating some MATLAB code into Python and I need to access data structures. Using scipy, I need to concatenate a user input string into a filename:</p> <p><code>cb_data = scipy.io.loadmat('./cb_data/' + subj_id + '_cb_AAAD_V2.mat' , 'rb')</code></p> <p>where subj_id is a variable coming from user input. I h...
0
2016-07-21T01:45:36Z
38,493,569
<p>The second argument, <code>mdict</code>, of <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html" rel="nofollow"><code>loadmat</code></a> is not the file access mode. It is optional, but if it is given, it must be a dictionary. The loaded arrays are added to this dictionay, with the va...
0
2016-07-21T01:49:27Z
[ "python", "matlab", "scipy" ]
Using a variable in a regex in Python
38,493,544
<p>I am trying to capture the last name, first name and number from a string that has the following pattern:</p> <pre><code>str = "Doe, John; 620 Eisenberg, Andrew; 253" </code></pre> <p>The following line of code seems to capture the last name and first name but returns None when I include the part for the number:</...
0
2016-07-21T01:45:48Z
38,493,665
<p>Replacing <code>:</code> with <code>;</code>, as @Kasramvd suggested, works perfectly:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = "Doe, John; 620 Eisenberg, Andrew; 253" &gt;&gt;&gt; re.findall(r'(?P&lt;last&gt;[A-Z][A-Za-z]+), (?P&lt;first&gt;[A-Z][A-Za-z]+); (?P&lt;num&gt;\d+)', s, re.M|re.I) [('Doe',...
2
2016-07-21T02:01:08Z
[ "python", "regex" ]
Using a variable in a regex in Python
38,493,544
<p>I am trying to capture the last name, first name and number from a string that has the following pattern:</p> <pre><code>str = "Doe, John; 620 Eisenberg, Andrew; 253" </code></pre> <p>The following line of code seems to capture the last name and first name but returns None when I include the part for the number:</...
0
2016-07-21T01:45:48Z
38,493,690
<p>Try this below:</p> <pre><code>&gt;&gt;&gt; input = "Doe, John; 620 Eisenberg, Andrew; 253" &gt;&gt;&gt; import re &gt;&gt;&gt; tmpLst = re.split(r'[;,\s]\s*', input) &gt;&gt;&gt; print tmpLst ['Doe', 'John', '620', 'Eisenberg', 'Andrew', '253'] &gt;&gt;&gt; output = [] &gt;&gt;&gt; for i in range(0, len(tmpLst), 3...
0
2016-07-21T02:04:45Z
[ "python", "regex" ]
'SparkSession' object has no attribute 'sparkContext'
38,493,570
<p>I have Spark 2.0.0 and I am trying to run some Python examples from Spark source code.</p> <p>This is the <a href="https://github.com/apache/spark/blob/master/examples/src/main/python/pi.py" rel="nofollow">example</a>. And I was running like:</p> <pre><code>spark-submit pi.py 2 </code></pre> <p>But I kept getting...
0
2016-07-21T01:49:29Z
39,668,926
<p>As @stpk mentioned, you are probably running an older spark version. For example, Spark 1.5.1 doesn't have <code>pyspark.sql.SparkSession</code> (check out the <a href="https://spark.apache.org/docs/1.5.1/api/python/pyspark.sql.html" rel="nofollow">api document</a>, but later versions have <a href="https://spark.apa...
0
2016-09-23T20:20:23Z
[ "python", "apache-spark", "pyspark" ]
Python: WindowsError when creating folder with os.mkdir and using square brackets
38,493,598
<p>On Windows, when I tried to create the following folder:</p> <pre><code> os.mkdir('H:\\__ Photos\\____Photos to be sorted\\[ Photo sorting process ]\\_NEW\\__PROC_PHOTOS\\1. Original CRW') </code></pre> <p>I got the error:</p> <blockquote> <p>WindowsError: [Error 3] <strong>The system cannot find the path sp...
0
2016-07-21T01:53:07Z
38,493,622
<p>You can use <code>os.makedirs</code> instead of <code>os.mkdir</code>. From the documentation:</p> <blockquote> <p>Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.</p> </blockquote>
3
2016-07-21T01:56:19Z
[ "python", "windows", "folder", "mkdir" ]
Python Anaconda - no module named numpy
38,493,608
<p>I recently installed Anaconda on Arch Linux from the Arch repositories. By default, it was set to Python3, whereas I would like to use Python2.7. I followed the Anaconda documentation to create a new Python2 environment. Upon running my Python script which uses Numpy, I got the error <code>No module named NumPy</cod...
0
2016-07-21T01:54:08Z
38,503,517
<p>The <code>anaconda</code> package in the AUR is broken. If anyone encounters this, simply install <code>anaconda</code> from their website. The AUR attempts to do a system-wide install, which gets rather screwy with the path.</p>
0
2016-07-21T11:50:51Z
[ "python", "python-2.7", "numpy", "anaconda" ]
How to append stdout to file for pyinotify daemonize?
38,493,659
<p>I am trying to add watches using python pyinotify and daemonize the notifier.</p> <pre><code>notifier = pyinotify.Notifier(wm, handler) notifier.loop(daemonize=True, pid_file='/tmp/pyinotifier.pid', stdout='/tmp/out.log', stderr='/tmp/error.log') </code></pre> <p>However I could find, the log files a...
0
2016-07-21T02:00:28Z
38,494,257
<p>Looking at <a href="https://github.com/seb-m/pyinotify/blob/master/python2/pyinotify.py#L1295" rel="nofollow">the source</a>, it appears as though the logs are opened in <code>O_WRONLY</code> mode, which is why you see them being overwritten each time you invoke the loop:</p> <pre><code>def __daemonize(self, pid_fi...
0
2016-07-21T03:10:38Z
[ "python", "pyinotify" ]
ZeroMQ ROUTER-DEALER redirect to another ROUTER-DEALER issue
38,493,675
<p>I have a static DNS named <code>vops-server.com</code> that points to my Dell PowerEdge 2950. On this 2950 I run the <code>server.py</code> which initially binds to <code>tcp://0.0.0.0:7777</code>, and subsequently redirects any incoming clients to a socket bound to a port greater than <code>7777</code>, the first o...
0
2016-07-21T02:02:27Z
38,548,405
<p>Same code works fine on the Dell PowerEdge 2950 running Windows Server 2012 R2. ZMQ appears to have issues with Ubuntu. </p>
0
2016-07-24T03:17:05Z
[ "python", "sockets", "zeromq" ]
Comparing rows of two pandas dataframes?
38,493,795
<p>This is a continuation of my question. <a href="http://stackoverflow.com/questions/38267763/fastest-way-to-compare-rows-of-two-pandas-dataframes/38270174#38270174">Fastest way to compare rows of two pandas dataframes?</a></p> <p>I have two dataframes <code>A</code> and <code>B</code>: </p> <p><code>A</code> is 100...
4
2016-07-21T02:17:44Z
38,494,149
<p>I'll stick by my initial answer but maybe explain better.</p> <p>You are asking to compare 2 pandas dataframes. Because of that, I'm going to build dataframes. I may use numpy, but my inputs and outputs will be dataframes.</p> <h3>Setup</h3> <p>You said we have a a 1000 x 500 array of ones and zeros. Let's bui...
7
2016-07-21T02:59:47Z
[ "python", "pandas", "numpy", "dataframe" ]
Where is the value of objects like lists,ints, and strings stored?
38,493,846
<p>Alright so all lists have <code>__setitem__</code> and <code>__getitem__</code> and ints have <code>__add__</code> <code>__sub__</code> and such to operate on their value. But where is that value actually stored / how can I reference it? Say I want to make a class imitating an list. It might look something like this...
2
2016-07-21T02:22:16Z
38,493,939
<p>I realize this doesn't directly answer your question about "where is the value ... stored", and I'm not sure what you mean by "I can't just simply directly call <code>__setitem__(key,item)</code> because you can't input a key outside of the range of the items already present in the list," but if I understand you cor...
1
2016-07-21T02:34:24Z
[ "python" ]
How to visualize the cluster result as a graph with different node color based on its cluster?
38,493,875
<p>i have a geodesic distance of graph data in .csv format</p> <p><img src="http://i.stack.imgur.com/CVu4B.png" alt="data.csv"></p> <p>i want to reduce it into 2D using Multidimensional Scaling (MDS) and cluster it using Kmedoids</p> <p>This is my code:</p> <pre><code># coding: utf-8 import numpy as np import csv ...
-1
2016-07-21T02:25:16Z
38,498,902
<p>You don't need MDS to run kMedoids - just run it on the original distance matrix (kMedoids can also be made to work on a similarity matrix by switching min for max).</p> <p>Use MDS only for plotting.</p> <p>The usual approach for visualization is to use a loop over clusters, and plot each cluster in a different co...
0
2016-07-21T08:26:46Z
[ "python", "csv", "graph", "cluster-analysis", "networkx" ]
Python combine 2 lists of strings for CSV
38,493,886
<p>I have two lists that I want to combine for csv output:</p> <pre><code>alist = ['a', 'b', 'c'] blist = ['d', 'e', 'f'] </code></pre> <p>However, I want the output for the csv to format like this:</p> <pre><code>clist = ['a', 'b', 'c', 'd e f'] </code></pre> <p>such that the last entry extended of the list contai...
0
2016-07-21T02:26:37Z
38,493,926
<p>Is this what you are after?</p> <pre><code> clist = alist + [" ".join(blist)] </code></pre> <p>otherwise I think what you are after doesn't make sense, or you need to explain better what you want... Given python syntax, <code>'x' 'y' 'z'</code> <strong>is</strong> <code>'xyz'</code>.</p>
0
2016-07-21T02:32:37Z
[ "python", "csv" ]
How to remove the quote and bracket from list value
38,493,899
<p>I have a function to return a list of values, referenced by result:</p> <pre><code>def populate(*args): i=1 result = [] for arg in args: arg = str(cols[i].get_text()) i+=1 result.append(arg) return result </code></pre> <p>And I want to assign the values from result to differ...
1
2016-07-21T02:28:20Z
38,494,061
<p>If you just want to convert each item in the list to string, then you could make it more simpler:</p> <pre><code>In [12]: a, b, c= [str(item) for item in result] In [13]: a, b, c Out[13]: ('LINZ', 'WLG Cisco BYOL 2', '32') In [14]: a Out[14]: 'LINZ' In [15]: b Out[15]: 'WLG Cisco BYOL 2' In [16]: c Out[16]: '32...
1
2016-07-21T02:49:09Z
[ "python", "string", "list" ]
Pygame keeps crashing when I open it
38,493,997
<p>I've have this dodging aliens game and it's not working. I can get the front begin screen to open but then when I hit enter to start it crashes and freezes. I've tried running it from python.exe instead of just IDLE but in that case it just pops up then closes right down. A few errors popped up the first few times I...
-3
2016-07-21T02:42:18Z
38,499,725
<p>I still see several issues with your code and I think you're trying to do too much at once for the very beginning. Try to keep it as simple as possible. Try creating a display and draw some image:</p> <pre><code>import pygame pygame.init() display = pygame.display.set_mode((750, 750)) img = pygame.image.load("""C...
0
2016-07-21T09:06:05Z
[ "python", "crash", "pygame" ]
Python - safely close socket connection on terminal from keyboard input besides cntrl-c?
38,494,003
<p>The server I'm communicating to has stream session slots and sometimes the stream session couldn’t opened because all stream session slots are used. I suspect its because I'm building a program that talks to the server and feel when I cntrl-c to force stop the stream it doesn't close safely keeping the stream sess...
0
2016-07-21T02:42:58Z
38,494,150
<p>After re-reading your question I think I answered some other question. Sorry.</p> <p>I don't know whether you identified root of problem correctly, but you can put your code in <code>try...except...finally...</code> structure. You can omit <code>except</code> or <code>finally</code>, if you don't need one of them.<...
0
2016-07-21T02:59:47Z
[ "python", "sockets", "python-sockets" ]
Python - safely close socket connection on terminal from keyboard input besides cntrl-c?
38,494,003
<p>The server I'm communicating to has stream session slots and sometimes the stream session couldn’t opened because all stream session slots are used. I suspect its because I'm building a program that talks to the server and feel when I cntrl-c to force stop the stream it doesn't close safely keeping the stream sess...
0
2016-07-21T02:42:58Z
38,494,447
<p>If you want to close your socket when you press "Ctrl + C" and then wait for another connection, you can try the code below.</p> <pre><code>while True: try: received = sock.recv(1024) except KeyboardInterrupt: print "i want to close client socket" sock.close() break excep...
0
2016-07-21T03:34:24Z
[ "python", "sockets", "python-sockets" ]
ImportError : cannot import name unwrap
38,494,014
<p>I have been trying to run my codes : (neaweather.py)</p> <pre><code>import requests from bs4 import BeautifulSoup import urllib3 r = requests.get('http://www.nea.gov.sg/api/WebAPI/? dataset=2hr_nowcast&amp;keyref=&lt;keyrefno&gt;') soup = BeautifulSoup(r.content, "xml") soup.find('validTime').string </code></pr...
0
2016-07-21T02:44:03Z
38,494,296
<p>From a Python prompt:</p> <pre><code>&gt;&gt;&gt; import urllib &gt;&gt;&gt; print urllib.__file__ </code></pre> <p>Make sure the file is part of the Python distribution and not your own script.</p>
0
2016-07-21T03:15:53Z
[ "python", "python-import", "importerror" ]
sqlalchemy building 'sqlalchemy.cprocessors' extension error: [Error 2]
38,494,235
<p>I need install Python sqlalchemy for windows. But the system can not find the file sqlalchemy.cprocessors' extension</p> <p>Thanks!</p>
-1
2016-07-21T03:08:06Z
38,566,254
<p>Installing <a href="https://www.microsoft.com/en-us/download/details.aspx?id=44266" rel="nofollow">Microsoft Visual C++ Compiler for Python</a> helped me.</p>
-2
2016-07-25T11:13:24Z
[ "python", "sqlalchemy" ]
Converting Dataframe Object into Date Python
38,494,246
<p>A python dataframe 'dff' containing data imported from SAS is having a date field whose type is showing as below by python:</p> <pre><code>dff.effvdate.head() Out[47]: 0 b'09JUL2013' 1 b'17OCT2013' 2 b'03MAR2014' 3 b'08MAY2014' 4 b'10MAR2015' Name: effvdate, dtype: object </code></pre> <p>I am tryi...
0
2016-07-21T03:09:05Z
38,494,297
<p>The error <code>TypeError: strptime() argument 1 must be str, not bytes</code> gives you the information you need to know! <code>d</code> is in bytes, not a string. you should cast d to string. </p> <pre><code>dff['REPORT_MONTH'] =[dt.datetime.strptime(d.decode('UTF-8'),"%d%b%Y").date() for d in dff['effvdate']]...
0
2016-07-21T03:15:54Z
[ "python", "date", "object", "dataframe", "casting" ]
How to find all the messages in a python protobuff
38,494,286
<p>I have a python google-protobuff, now I wanna find all the messages in this protobuff file.</p>
-1
2016-07-21T03:14:50Z
38,494,355
<p>This is a bit crude, but:</p> <pre><code>&gt;&gt;&gt; import protobufmodule &gt;&gt;&gt; from google.protobuf.message import Message &gt;&gt;&gt; messageClasses = [v for v in vars(protobufmodule).values() if isinstance(v, type) and issubclass(v, Message)] </code></pre>
1
2016-07-21T03:23:26Z
[ "python", "google-protobuf" ]
Flatten/ravel/collapse 3-dimensional xr.DataArray (Xarray) into 2 dimensions along an axis?
38,494,300
<p>I have a dataset where I'm storing replicates for different classes/subtypes (not sure what to call it) and then attributes for each one. Essentially, there are 5 subtype/classes, 4 replicates for each subtype/class, and 100 attributes that are measured. </p> <p><strong>Is there a method like <code>np.ravel</code>...
3
2016-07-21T03:15:57Z
38,495,149
<p>Yes, this is exactly what the <code>.stack</code> is for:</p> <pre><code>In [33]: stacked = DA_data.stack(desired=['subtype', 'replicates']) In [34]: stacked Out[34]: &lt;xarray.DataArray (attributes: 100, desired: 20)&gt; array([[ 0.54020268, 0.14914837, 0.83398895, ..., 0.25986503, 0.62520466, 0.086...
2
2016-07-21T04:54:09Z
[ "python", "arrays", "pandas", "multidimensional-array", "python-xarray" ]
import from parent directory in script which lies in sub directory
38,494,342
<p>Here's my directory structure:</p> <pre><code>my_package | +--__init__.py | +--setup.py | +--module.py | +--sub_package | +--__init__.py | +--script.py </code></pre> <p>The script <code>script.py</code> needs to import a function from <code>module.py</code>, and I need to be able to run <code>script.py...
0
2016-07-21T03:21:44Z
38,494,433
<p>I believe you can just say</p> <pre><code>import module </code></pre> <p>from within <code>script.py</code> if you do the following:</p> <p>from your terminal in the mypackage directory run:</p> <pre><code>$ python setup.py install </code></pre> <p>This will allow you to make the import statement that you want....
0
2016-07-21T03:32:08Z
[ "python", "python-3.x", "python-import" ]
import from parent directory in script which lies in sub directory
38,494,342
<p>Here's my directory structure:</p> <pre><code>my_package | +--__init__.py | +--setup.py | +--module.py | +--sub_package | +--__init__.py | +--script.py </code></pre> <p>The script <code>script.py</code> needs to import a function from <code>module.py</code>, and I need to be able to run <code>script.py...
0
2016-07-21T03:21:44Z
38,494,985
<p>In fact, python interpreter will find module in sys.path.It means if you add your module's directory in this example "somepath/my_package" to sys.path, python will find it by "import module".</p> <p>So how to achieve this goal?</p> <p>If your directory absolute path never change, you can do this below:</p> <pre><...
0
2016-07-21T04:38:51Z
[ "python", "python-3.x", "python-import" ]
How to use the while loop to get the factorial of an integer without getting endless factorials back?
38,494,434
<p>I have to write a program that tells the user the factorial of any integer between 1 and 15 while using the while loop. I wrote the code below and the output gives me endless factorials/numbers.. Do you know what I did wrong? Thank you!</p> <p>Update: I realized that I should use "while" for what num isn't, so I no...
0
2016-07-21T03:32:20Z
38,494,498
<p>you have missed the braces at the end of <code>int()</code> funtion</p> <pre><code># take input from the user num = int(input("Please enter a number from 1 to 15: ")) factorial = 1 # check if the number is negative, positive or zero while num &lt; 0: num = int(input("Negative numbers don't have factorials! Plea...
0
2016-07-21T03:42:32Z
[ "python", "while-loop" ]
How to use the while loop to get the factorial of an integer without getting endless factorials back?
38,494,434
<p>I have to write a program that tells the user the factorial of any integer between 1 and 15 while using the while loop. I wrote the code below and the output gives me endless factorials/numbers.. Do you know what I did wrong? Thank you!</p> <p>Update: I realized that I should use "while" for what num isn't, so I no...
0
2016-07-21T03:32:20Z
38,494,502
<p>You missed a closing parenthesis:</p> <pre><code>while num &gt; 15: num = int(input("Please enter a number between 1 and 15! ")) ^ here </code></pre>
0
2016-07-21T03:42:50Z
[ "python", "while-loop" ]
How to use the while loop to get the factorial of an integer without getting endless factorials back?
38,494,434
<p>I have to write a program that tells the user the factorial of any integer between 1 and 15 while using the while loop. I wrote the code below and the output gives me endless factorials/numbers.. Do you know what I did wrong? Thank you!</p> <p>Update: I realized that I should use "while" for what num isn't, so I no...
0
2016-07-21T03:32:20Z
38,495,390
<p>I would do this:</p> <pre><code>from math import factorial as factorial while True: num = int(input("Please enter a number from 1 to 15: ")) if 1 &lt;= num &lt;= 15: fact = factorial(num) print 'the factorial of {n} is {f}'.format(n=num, f=fact) else: num = int(input("Please ent...
2
2016-07-21T05:17:04Z
[ "python", "while-loop" ]
How to scrape data generated with infinite scroll?
38,494,563
<p>How to scrape the list of product from <a href="https://www.amazon.cn/gp/pdp/profile/A34PAP6LGJIN6N/ref=cm_cr_arp_d_pdp?ie=UTF8" rel="nofollow">this page</a> with scrapy?</p> <p>I have tried the ajax request url the browser sends:</p> <pre><code>https://www.amazon.cn/gp/profile/A34PAP6LGJIN6N/more?next_batch_param...
0
2016-07-21T03:50:10Z
38,495,644
<p>You need to replicate the headers you see in the request.</p> <p>If you inspect the response headers you can see: <a href="http://i.stack.imgur.com/upI1P.png" rel="nofollow"><img src="http://i.stack.imgur.com/upI1P.png" alt="amazon.ca next page headers"></a></p> <p>from this you need to update your <code>scrapy.Re...
1
2016-07-21T05:36:21Z
[ "python", "scrapy" ]
CSS style my django table
38,494,603
<p><a href="http://i.stack.imgur.com/fDCxv.png" rel="nofollow">picture of my table</a></p> <p>i rendered my table with django table2 and above link how it looks like</p> <p>i style it with css like this</p> <pre><code>thead { background-color: #4CAF50; font-color: white; } </code></pre> <p>It looks like the...
0
2016-07-21T03:54:01Z
38,495,400
<p>They are hyperlinks (<code>a</code> tag) for which the browser has <strong>default</strong> colors. You can set the color of hyperlinks like that:</p> <p><strong>For unvisited links</strong></p> <pre><code>a:link { color: red; } </code></pre> <p><strong>Visited links</strong></p> <pre><code>a:visited { c...
0
2016-07-21T05:17:52Z
[ "python", "css", "django", "table" ]
Why is pip still not recognized even though it is on my path?
38,494,617
<p>I ran the <a href="https://bootstrap.pypa.io/get-pip.py" rel="nofollow">get-pip</a> python file, and it told me that </p> <blockquote> <p>Requirement already up-to-date: pip in c:\python27\lib\site-packages</p> </blockquote> <p>So, I added that to my path. However, whenever I try to run a <code>pip</code> comman...
1
2016-07-21T03:56:18Z
38,494,663
<p>This says that module <code>pip</code> installed:</p> <blockquote> <p>Requirement already up-to-date: pip in c:\python27\lib\site-packages</p> </blockquote> <p>This says that there is no command <code>pip</code> in <code>path</code> (<code>pip.exe</code> is in <code>C:\Python27\Scripts</code>):</p> <blockquote>...
2
2016-07-21T04:02:13Z
[ "python", "pip" ]
How to generate all possible combinations of two coins with three possibilities (up, down and In between)
38,494,634
<p>Given two coins, the number of outcomes will be <strong>2^2</strong> (two coins with only two possibilities(head(up) or tail(down)). Gives the following possible combinations: </p> <pre><code> 00 01 10 11 </code></pre> <p>Where, <code>0</code> means head(up) and <code>1</code> means tail(down). </p> <p>Here...
3
2016-07-21T03:58:39Z
38,494,673
<p>Python solution:</p> <pre><code>from itertools import product possible_values = '01B' number_of_coins = 2 for result in product(possible_values, repeat=number_of_coins): print(''.join(result)) # Output: # 00 # 01 # 0B # 10 # 11 # 1B # B0 # B1 # BB </code></pre>
2
2016-07-21T04:03:04Z
[ "c#", "python", "c++", "matlab", "cartesian-product" ]
How to generate all possible combinations of two coins with three possibilities (up, down and In between)
38,494,634
<p>Given two coins, the number of outcomes will be <strong>2^2</strong> (two coins with only two possibilities(head(up) or tail(down)). Gives the following possible combinations: </p> <pre><code> 00 01 10 11 </code></pre> <p>Where, <code>0</code> means head(up) and <code>1</code> means tail(down). </p> <p>Here...
3
2016-07-21T03:58:39Z
38,494,800
<pre><code>from itertools import product outcomes = ["".join(item) for item in list(product('01B', repeat=2))] for outcome in outcomes: print(outcome) #reusults: 00 01 0B 10 11 1B B0 B1 BB </code></pre>
1
2016-07-21T04:18:27Z
[ "c#", "python", "c++", "matlab", "cartesian-product" ]
How to generate all possible combinations of two coins with three possibilities (up, down and In between)
38,494,634
<p>Given two coins, the number of outcomes will be <strong>2^2</strong> (two coins with only two possibilities(head(up) or tail(down)). Gives the following possible combinations: </p> <pre><code> 00 01 10 11 </code></pre> <p>Where, <code>0</code> means head(up) and <code>1</code> means tail(down). </p> <p>Here...
3
2016-07-21T03:58:39Z
38,495,490
<p>Matlab Solution: <code>n</code> is the amount of possible solutions. In your case 3 different once. <code>k</code> is the amount of sets. In your case 2 coins. <code>p</code>should contain a matrix with the results.</p> <pre><code>n = 3; k = 2; nk = nchoosek(1:n,k); p=zeros(0,k); for i=1:size(nk,1), pi = perms(...
1
2016-07-21T05:25:03Z
[ "c#", "python", "c++", "matlab", "cartesian-product" ]
How to generate all possible combinations of two coins with three possibilities (up, down and In between)
38,494,634
<p>Given two coins, the number of outcomes will be <strong>2^2</strong> (two coins with only two possibilities(head(up) or tail(down)). Gives the following possible combinations: </p> <pre><code> 00 01 10 11 </code></pre> <p>Where, <code>0</code> means head(up) and <code>1</code> means tail(down). </p> <p>Here...
3
2016-07-21T03:58:39Z
38,497,701
<p>I found several solutions for MATLAB. (That's not completely mine code, I found some parts and adapt it). Post it because <a href="http://stackoverflow.com/questions/38494634/how-to-generate-all-possible-combinations-of-two-coins-with-three-possibilities/38495490#38495490">@C.Colden' answer</a> is not full. What yo...
1
2016-07-21T07:27:32Z
[ "c#", "python", "c++", "matlab", "cartesian-product" ]
How to generate all possible combinations of two coins with three possibilities (up, down and In between)
38,494,634
<p>Given two coins, the number of outcomes will be <strong>2^2</strong> (two coins with only two possibilities(head(up) or tail(down)). Gives the following possible combinations: </p> <pre><code> 00 01 10 11 </code></pre> <p>Where, <code>0</code> means head(up) and <code>1</code> means tail(down). </p> <p>Here...
3
2016-07-21T03:58:39Z
38,508,963
<p>Granted I am not familiar with the syntax of these other languages, the solutions to them look overly complicated.</p> <p>It's just a simple doubly-nested <code>for</code> loop:</p> <p><strong>C++</strong></p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { const char* ch = "01B"; ...
0
2016-07-21T15:58:21Z
[ "c#", "python", "c++", "matlab", "cartesian-product" ]
pyexcel - get column names and add entire rows together
38,494,652
<p>I have a couple of speadsheets:</p> <pre><code>Sheet 1 sheet2 sheet3 A B C D E F D F G 1 2 3 4 5 6 7 9 8 </code></pre> <p>I'm using pyexcel to join rows together from spreadsheets 1 and 2, and 1 and 3, so the combined row for 1 and 2 would be:</p> <pre><code>A B C D E F D F G, 1 2 3 4...
0
2016-07-21T04:00:35Z
38,495,764
<p>It is not clear:</p> <ol> <li>How you are reading the worksheet</li> <li><p>how you want to handle the join when both sheets has values. I assume you want to sum up.</p> <pre><code>import numpy as np import pyexcel as pe a = np.array(pe.get_array(file_name='Sheet1.xlsx')) b = np.array(pe.get_array(file_name='Shee...
1
2016-07-21T05:44:34Z
[ "python", "python-3.x", "pyexcel" ]
Loop through a page of voice samples, downloading each sample and putting the lines into a text file
38,494,704
<p><a href="http://theportalwiki.com/wiki/GLaDOS_voice_lines" rel="nofollow">Here</a> is the page I am trying to do this on. It is the voice lines of GLaDOS from Portal. Each line is inner "i" HTML text as well as between quotes as displayed on the page. They each have a direct download link beside them labeled "downlo...
0
2016-07-21T04:06:52Z
38,494,759
<p>Your Python code is very close to working. Minor fix (plus using a context manager for the file) below:</p> <pre><code>from bs4 import BeautifulSoup import urllib.request soup = BeautifulSoup(urllib.request.urlopen("http://theportalwiki.com/wiki/GLaDOS_voice_lines"), "html.parser") tags = soup.find_all('i') with op...
1
2016-07-21T04:12:48Z
[ "python", "html", "file", "lua", "speech-synthesis" ]
AWS Elastic Beanstalk mod_wsgi "compiled for" version different than "runtime" version
38,494,722
<p>I'm seeing the following error when I run my Pyramid application on AWS Elastic Beanstalk.</p> <pre><code>[Thu Jul 21 03:45:20.629134 2016] [:warn] [pid 5232] mod_wsgi: Compiled for Python/2.7.9. [Thu Jul 21 03:45:20.629139 2016] [:warn] [pid 5232] mod_wsgi: Runtime using Python/2.7.10. </code></pre> <p>Anyone kno...
1
2016-07-21T04:08:58Z
38,512,539
<p>If you compile <em>mod_wsgi</em>, you need to point the configure script to the appropriate Python binary. For example:</p> <pre><code>wget -q "https://github.com/GrahamDumpleton/mod_wsgi/archive/4.4.21.tar.gz" tar -xzf '4.4.21.tar.gz' cd ./mod_wsgi-4.4.21 ./configure --with-python=/usr/local/bin/python3.5 make mak...
0
2016-07-21T19:10:22Z
[ "python", "amazon-web-services", "elastic-beanstalk", "mod-wsgi" ]
Listing locations in Azure using Python Azure SDK error
38,494,727
<p>I am trying out the listing of different locations in Azure using Python Azure SDKs from Windows machine Below is the error :</p> <p><img src="http://i.stack.imgur.com/VRrGK.png" alt="enter image description here"></p> <p>Please see my code :</p> <pre><code>import os import sys import logging from azure import * ...
0
2016-07-21T04:09:12Z
38,535,024
<p>Your code is correct. Based on the stacktrace, it's seems your certificate is not valid. This might help you: <a href="http://azure-sdk-for-python.readthedocs.io/en/latest/servicemanagement.html#creating-and-uploading-new-certificate-with-openssl" rel="nofollow">http://azure-sdk-for-python.readthedocs.io/en/latest/s...
0
2016-07-22T20:49:51Z
[ "python", "python-2.7", "azure" ]
Listing locations in Azure using Python Azure SDK error
38,494,727
<p>I am trying out the listing of different locations in Azure using Python Azure SDKs from Windows machine Below is the error :</p> <p><img src="http://i.stack.imgur.com/VRrGK.png" alt="enter image description here"></p> <p>Please see my code :</p> <pre><code>import os import sys import logging from azure import * ...
0
2016-07-21T04:09:12Z
38,553,275
<p>According to your code &amp; the error information, I think the issue was caused by the value of the <code>certificate_path</code> variable which is not a valid file path. On Windows, the path <code>\</code> means the root path of disk driver like <code>C:\</code> or <code>D:\</code>, and the file name <code>.pem</c...
0
2016-07-24T14:43:59Z
[ "python", "python-2.7", "azure" ]
Listing locations in Azure using Python Azure SDK error
38,494,727
<p>I am trying out the listing of different locations in Azure using Python Azure SDKs from Windows machine Below is the error :</p> <p><img src="http://i.stack.imgur.com/VRrGK.png" alt="enter image description here"></p> <p>Please see my code :</p> <pre><code>import os import sys import logging from azure import * ...
0
2016-07-21T04:09:12Z
39,504,122
<ol> <li><p>Identify the relevant python SDK API for the following: </p> <ul> <li>Spin-off an instance using a designated image from the storage account</li> </ul></li> <li>Why are anticipated platform issues.</li> <li>Identify the API to detach the data disk from the failed instance and attach it to the newly created...
-1
2016-09-15T06:09:16Z
[ "python", "python-2.7", "azure" ]
Listing locations in Azure using Python Azure SDK error
38,494,727
<p>I am trying out the listing of different locations in Azure using Python Azure SDKs from Windows machine Below is the error :</p> <p><img src="http://i.stack.imgur.com/VRrGK.png" alt="enter image description here"></p> <p>Please see my code :</p> <pre><code>import os import sys import logging from azure import * ...
0
2016-07-21T04:09:12Z
40,135,396
<p>Use <code>sms.list_locations()</code> to list out the regions.</p> <p>Thanks, Gopal.</p>
0
2016-10-19T15:12:38Z
[ "python", "python-2.7", "azure" ]
Get sound input & Find similar sound with Python
38,494,736
<p>What I wanna do is just like 'Shazam' or 'SoundHound' with Python, only sound version, not music.</p> <p>For example, when I make sound(e.g door slam), find the most similar sound data in the sound list.</p> <p>I don't know you can understand that because my English is bad, but just imagine the sound version of 'S...
0
2016-07-21T04:10:17Z
38,497,404
<p>There are several libraries you can use, but none of them will classify a sample as a 'door shut' for example. BUT you can use those libraries for feature extraction and build/get a data set of sound, build a classifier, train it and use it for sound classification.</p> <p>The libraries:</p> <ol> <li><p><strong>Fr...
2
2016-07-21T07:13:52Z
[ "python", "audio" ]
Alternative to Goto, Label in python?
38,494,761
<p>I know I can't use Goto and I know Goto is not the answer. I've readed similar questions, but I just can't figure out a way to solve my problem (I'm a noob, btw). </p> <p>So, I'm writting a program, in which you have to guess a number. This is an extract of the part I have problems:</p> <pre><code>` x = random....
0
2016-07-21T04:12:59Z
38,494,859
<p>You can use infinite loop, and also explicit break if necessary.</p> <pre><code>x = random.randint(0,100) #I want to put a label here while(True): y = int(raw_input("Guess the number between 1 and 100: ")) if isinstance( y, int ): while y != x: if y &gt; x: y = int(raw_input("Wrong! Try a...
0
2016-07-21T04:24:35Z
[ "python" ]
Alternative to Goto, Label in python?
38,494,761
<p>I know I can't use Goto and I know Goto is not the answer. I've readed similar questions, but I just can't figure out a way to solve my problem (I'm a noob, btw). </p> <p>So, I'm writting a program, in which you have to guess a number. This is an extract of the part I have problems:</p> <pre><code>` x = random....
0
2016-07-21T04:12:59Z
38,494,862
<p>There are lots of ways to do this, but generally you'll want to use loops, and you may want to explore <code>break</code> and <code>continue</code>. Here's one possible solution:</p> <pre><code>import random x = random.randint(1, 100) prompt = "Guess the number between 1 and 100: " while True: try: y...
6
2016-07-21T04:24:46Z
[ "python" ]
Alternative to Goto, Label in python?
38,494,761
<p>I know I can't use Goto and I know Goto is not the answer. I've readed similar questions, but I just can't figure out a way to solve my problem (I'm a noob, btw). </p> <p>So, I'm writting a program, in which you have to guess a number. This is an extract of the part I have problems:</p> <pre><code>` x = random....
0
2016-07-21T04:12:59Z
38,494,958
<h2>Python does not support <code>goto</code> or anything equivalent.</h2> <p>You should think about how you can structure your program using the tools python does offer you. It seems like you need to use a loop to accomplish your desired logic. You should check out the <a href="https://docs.python.org/3/tutorial/cont...
1
2016-07-21T04:36:33Z
[ "python" ]
Flask UnicodeDecodeError
38,494,772
<p>Error:</p> <blockquote> <p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xf0 in position 24: ordinal not in range(128)</p> </blockquote> <p>So basically I have a Flask app where users fill a sign up form and it renders a new page.</p> <p>Here's the code:</p> <pre><code>render_template('signUpSuccess.htm...
-1
2016-07-21T04:14:22Z
38,494,864
<p>Try passing a <code>unicode</code> object, not a <code>str</code> into <code>render_template()</code>, like so:</p> <pre><code>render_template('signUpSuccess.html', password=u"You should know, right? 😛") </code></pre> <p>Sample program:</p> <pre><code># coding: utf-8 from flask import Flask, render_template ...
1
2016-07-21T04:25:17Z
[ "python", "encoding", "utf-8", "flask" ]
Flask UnicodeDecodeError
38,494,772
<p>Error:</p> <blockquote> <p>UnicodeDecodeError: 'ascii' codec can't decode byte 0xf0 in position 24: ordinal not in range(128)</p> </blockquote> <p>So basically I have a Flask app where users fill a sign up form and it renders a new page.</p> <p>Here's the code:</p> <pre><code>render_template('signUpSuccess.htm...
-1
2016-07-21T04:14:22Z
38,494,876
<p>You should decode that string. Try this:</p> <pre><code>the_password = "You should know, right? 😛" the_password = the_password.decode('utf-8') render_template('signUpSuccess.html', password=the_password) </code></pre>
0
2016-07-21T04:26:52Z
[ "python", "encoding", "utf-8", "flask" ]
How do I work with different graph databases using the Bolt neo4j python?
38,494,879
<p>My test using Python Neo4j Bolt was successful. During the test I had opened a graph database (lets call it "First.graphdb"). Then I opened another python file and wanted to call neo4j. This time I had another graph database opened (lets call it "Second.graphdb) and I couldnt get through. How do I know which graphda...
0
2016-07-21T04:27:42Z
38,501,634
<p>If you use two encrypted connections to the same host, you will get into trouble with the SSL certificate.</p> <p>If you do the following, you will get a <code>ProtocolError</code> stating that the server certificate for the second connection does not match the known certificate for the first:</p> <pre><code>from ...
0
2016-07-21T10:23:56Z
[ "python", "neo4j" ]
Counting the grouped elements of a Dataframe in Python
38,494,908
<p>I have a dataframe that I am trying to group by and sum. I was able to achieve this, but I'd also like to count the grouped by elements. </p> <pre><code>sessions_summed = df.groupby("screens_completed").sum() print sessions_summed </code></pre> <p>using this, I get this output:</p> <pre><code>screens_completed ...
1
2016-07-21T04:31:47Z
38,495,716
<h2>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>DataFrame.pivot_table</code></a> to count the number of times a certain value appears in a column.</h2> <p>You can take advantage of the <code>aggfunc</code> argument in the <code>pivot_table</c...
0
2016-07-21T05:41:27Z
[ "python" ]
How does one use numpy's Meshgrid function with a random interval rather than a equally spaced one?
38,494,934
<p>Conceptually this is sort of what I wanted to do. I wanted to select random points in a 2D plane and then plot a surface plot of how that would look like. Similarly, an alternative (sub-optimal idea) could be to grade a Meshgrid and select N random points and their corresponding heights and then plot them in a surfa...
0
2016-07-21T04:33:43Z
38,508,403
<p>The x and y ranges used for meshgrid should not be in random order. This is because to draw a surface, it's not enough just to have a bunch of points in XYZ space: we also need to know which are to be connected with which. This is determined from the adjacency of values in the arrays.</p> <p>Example: if x_range is ...
2
2016-07-21T15:31:33Z
[ "python", "numpy", "random", "plot" ]
Installing Tensorflow on Mac for PyPy
38,494,982
<p>I am able to install tensorflow for python using pip just fine but when I try and install tensorflow for pypy using:</p> <pre><code>pypy -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.9.0-py2-none-any.whl </code></pre> <p>I get error messages about how pypy doesn't play well wi...
0
2016-07-21T04:38:40Z
38,663,650
<p>youcan use directly pip</p> <p>example: Mac OS X, CPU only - py2</p> <pre><code>export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/mac/tensorflow-0.9.0-py2-none-any.whl sudo pip install --upgrade $TF_BINARY_URL </code></pre> <p>If you need validate pip installation:</p> <pre><code>sudo easy_install ...
0
2016-07-29T16:37:41Z
[ "python", "osx", "numpy", "tensorflow", "pypy" ]
Store tuple as field in model
38,495,141
<p>I have the following models:-</p> <pre><code>class A(...): id=... name=... class B(...): setOfA=models.ManyToManyField(A) </code></pre> <p>What I want is that the setOfA be a 2-d array of A and date. That is:-</p> <p>setOfA = [[A1,date1],[A2,date2]]</p> <p>How can I implement this?</p>
1
2016-07-21T04:52:43Z
38,496,327
<p>You want custom relation model.</p> <pre><code>class A(...): id=... name=... class B(...): setOfA=models.ManyToManyField(A, through='Relation') class Relation(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) important_date = models.DateField() </code></pre> <p>Then to get ...
1
2016-07-21T06:18:57Z
[ "python", "django", "postgresql", "django-models", "django-queryset" ]
pyqtgraph : I want to execute pyqtgraph in new process
38,495,166
<p>Dear pyqtgraph masters, </p> <p>I want to execute pyqtgraph in a newly created process.</p> <p>In my project there is a python module : trading.py. This module makes a new process using this code</p> <pre><code>p = Process(target = realDataProcess.realDataProcessStart, args=(self.TopStockList, self.requestCodeLis...
0
2016-07-21T04:55:30Z
38,980,727
<p>My experience with multiprocess and pyqtgraph is, that you can't create a new pyqtgraph window on new processes. Therefore, you can only use pyqtgrahp on your <strong>main process</strong>. I think there was the explanation somewhere on the net.</p> <p>If you want to create additional processes to do something, bes...
0
2016-08-16T17:08:52Z
[ "python", "pyqt", "pyqtgraph", "multiprocess" ]
Column name and corresponding data are not matching in python
38,495,355
<p>I have a CSV file n while working on it in python I am facing following problem:</p> <p>CSV file:</p> <pre><code> cand_id cand_name cand_age cand_sex A1 Adam 35 M A2 Max 31 M A3 Uma 32 F B1 Jack 29...
2
2016-07-21T05:13:35Z
38,496,338
<p>You need add parameter <code>index_col=False</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>:</p> <pre><code>import pandas as pd df = pd.read_csv('P00000001-AL.csv', index_col=False) </code></pre> <pre><code>print (df.head()...
1
2016-07-21T06:19:32Z
[ "python", "python-3.x", "csv", "pandas" ]
How to create parallel tasks in Python
38,495,357
<p>I am creating a battle game for telegram groups as my beginner's project, one player challenges the other, and then a battle happens in the chat. Now I want to implement a "timeout" function for it. I've managed to make it work using _thread:</p> <pre><code>import _thread class Battle: def __init__(self, chat_...
0
2016-07-21T05:13:45Z
38,495,692
<p>I've got you started. I'm not sure how you are going to chat or keep record of who's playing.</p> <p>My first thoughts were to run threads but the while loop is easier and waits, too. I assumed Py 3 because of the print function. Let me know if this is what you had in mind.</p> <pre><code># from threading import T...
0
2016-07-21T05:39:29Z
[ "python", "multithreading" ]
How to open adb shell and execute commands inside shell using python
38,495,426
<p>I am trying to execute adb shell commands in python using subprocess.Popen</p> <p>Example: Need to execute 'command' in adb shell. While executing manually, I open the command window and execute as below and it works.</p> <pre><code>&gt;adb shell #&lt;command&gt; </code></pre> <p>In Python I am using as below but...
0
2016-07-21T05:20:29Z
38,501,052
<p>Ankur Kabra, try the code below:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess command = 'adb devices' p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() print 'standard output: %s \n er...
-1
2016-07-21T10:00:41Z
[ "android", "python", "shell", "adb" ]
How to open adb shell and execute commands inside shell using python
38,495,426
<p>I am trying to execute adb shell commands in python using subprocess.Popen</p> <p>Example: Need to execute 'command' in adb shell. While executing manually, I open the command window and execute as below and it works.</p> <pre><code>&gt;adb shell #&lt;command&gt; </code></pre> <p>In Python I am using as below but...
0
2016-07-21T05:20:29Z
38,523,219
<p>use pexpect (<a href="https://pexpect.readthedocs.io/en/stable/" rel="nofollow">https://pexpect.readthedocs.io/en/stable/</a>)</p> <pre><code>adb="/Users/lishaokai/Library/Android/sdk/platform-tools/adb" import pexpect import sys, os child = pexpect.spawn(adb + " shell") child.logfile_send = sys.stdout while True:...
0
2016-07-22T09:43:27Z
[ "android", "python", "shell", "adb" ]
How to open adb shell and execute commands inside shell using python
38,495,426
<p>I am trying to execute adb shell commands in python using subprocess.Popen</p> <p>Example: Need to execute 'command' in adb shell. While executing manually, I open the command window and execute as below and it works.</p> <pre><code>&gt;adb shell #&lt;command&gt; </code></pre> <p>In Python I am using as below but...
0
2016-07-21T05:20:29Z
38,525,350
<p>Found a way to do it using communicate() method in subprocess module</p> <pre><code>procId = subprocess.Popen('adb shell', stdin = subprocess.PIPE) procId.communicate('command1\ncommand2\nexit\n') </code></pre>
0
2016-07-22T11:29:53Z
[ "android", "python", "shell", "adb" ]
's' prefix for list in Python 3
38,495,500
<p><strong>Already did some searches on SO and looked on the python 3 documentation for str.split() and list()</strong></p> <p>Why does python prefix a list object with <code>s</code> when it prints to my terminal from a <code>.py</code> script, but not when I'm in the python shell?</p> <p>For example, if I make a sh...
0
2016-07-21T05:25:39Z
38,495,930
<p><strong>Sorry to waste your time, everyone!</strong></p> <p>I realized that I was executing this script from a <code>unittest</code> class and that the <code>s</code> character is printed upon execution of the <code>setup()</code> method. No problems now, thank you.</p>
0
2016-07-21T05:55:58Z
[ "python", "python-3.x" ]
Unix timestamp is different in two computers
38,495,603
<p>I just tried to run the same python code on two computers. The code says:</p> <pre><code>import time print time.time() </code></pre> <p>I started the execution in both computers with a click with both of my fingers (I accept a difference of up to 80ms), and both codes executed immediately (I saw no delay in execut...
0
2016-07-21T05:33:55Z
38,495,642
<p>Intern clocks of your computers are probably simply set at different times.</p>
0
2016-07-21T05:36:08Z
[ "python", "unix" ]
Unix timestamp is different in two computers
38,495,603
<p>I just tried to run the same python code on two computers. The code says:</p> <pre><code>import time print time.time() </code></pre> <p>I started the execution in both computers with a click with both of my fingers (I accept a difference of up to 80ms), and both codes executed immediately (I saw no delay in execut...
0
2016-07-21T05:33:55Z
38,498,162
<p>You need to synchronize your clocks, if not there is no possible such accuracy. Clocks naturally drift for many reasons. You can simply synchronize the clocks if your computers are on the internet by using <code>ntp</code>. There is a lot of <code>ntp</code> servers around the world. This usually synchronizes your c...
0
2016-07-21T07:50:30Z
[ "python", "unix" ]
Django self-referential class for most similar car
38,495,633
<p>Let's say I have a class <code>Car</code> with a number of fields describing its features. I call and display these features in my html using <code>{{ object.price }}</code> etc.</p> <p>With a nearest neighbor algorithm I have calculated a list of most similar cars for each car and would like to be able to display ...
0
2016-07-21T05:35:42Z
38,496,040
<p>You probably want asymmetrycal M2M with custom relation model for ordering nearest cars. In your case:</p> <pre><code>class Car(models.Model): """A model of a bureau.""" car_model = models.CharField(max_length = 50) price = models.IntegerField(default=1) most_similar = models.ManyToManyField('self',...
2
2016-07-21T06:02:15Z
[ "python", "django", "python-3.x", "django-models", "django-templates" ]
Find strings from a list starting with strings in another list
38,495,868
<p>I have two list <code>listOne</code> &amp; <code>listTwo</code></p> <p><strong>e.g.</strong></p> <p><code>listOne</code> could contain 'about', 'day', 'school'</p> <p><code>listTwo</code> could contain 'a','c','da','z'</p> <p>I want to find out all the elements in <code>listOne</code> which start with characters...
1
2016-07-21T05:50:42Z
38,495,918
<p>The way that you're doing it is fine. It's easy to read/understand, etc.</p> <p>However, if you really want, you can probably condense it down using <code>itertools.product</code>:</p> <pre><code>from itertools import product result = [elem2 for elem1, elem2 in product(listTwo, listOne) if elem2.startswith(elem1)...
1
2016-07-21T05:54:56Z
[ "python", "string", "list" ]
Find strings from a list starting with strings in another list
38,495,868
<p>I have two list <code>listOne</code> &amp; <code>listTwo</code></p> <p><strong>e.g.</strong></p> <p><code>listOne</code> could contain 'about', 'day', 'school'</p> <p><code>listTwo</code> could contain 'a','c','da','z'</p> <p>I want to find out all the elements in <code>listOne</code> which start with characters...
1
2016-07-21T05:50:42Z
38,495,985
<p>You can pass a tuple to <code>str.startswith</code> method. </p> <p>From the <a href="https://docs.python.org/2/library/stdtypes.html#str.startswit" rel="nofollow">doc</a>:</p> <blockquote> <p><strong>str.startswith(prefix[, start[, end]]):</strong> Return True if string starts with the prefix, otherwise retur...
1
2016-07-21T05:59:08Z
[ "python", "string", "list" ]
Converting a PDF file to a Text file in Python
38,496,026
<p>I've been on it for several days + researching the internet on how to get specific information from a pdf file.</p> <p>Eventually I was able to fetch all information using Python from a text file(which I created by going to the <em>PDF file -----> File ------> Save as Text</em>).</p> <p>The question is how do I ge...
2
2016-07-21T06:01:42Z
38,498,670
<p>You could use pdftotext.exe that you can download from <a href="http://www.foolabs.com/xpdf/download.html" rel="nofollow">http://www.foolabs.com/xpdf/download.html</a> and then execute it on your pdf files via Python:</p> <pre><code>import os import glob import subprocess #remember to put your pdftotxt.exe to the ...
0
2016-07-21T08:15:52Z
[ "python", "python-2.7", "pdf", "text", "converter" ]
Subscribe to Carriots Stream
38,496,055
<p>I am trying to subscribe to carriots data stream using paho mqtt client. But i am not able to read any data from carriots. Here's the source code i am using to subscribe to carriots.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- # Client paho-mqtt CarriotsMqttServer # sub_carriot.py import paho.mq...
0
2016-07-21T06:02:56Z
38,499,715
<p>The <code>mqtt.simple</code> function blocks until <code>msg_count</code> messages have been received and then it returns those messages.</p> <p>So the code as you have it will just sit until it has received 10 messages then it is probably going to exit without any output as there is nothing to collect the messages...
0
2016-07-21T09:05:32Z
[ "python", "mqtt", "iot", "paho" ]
Nested for-loop error python
38,496,105
<p>I am completely new to programing. I am trying to nest what i think is a "for-loop" inside of what i think is a "for-loop". Every time i run the program i get an error: "There's an error in your program: unexpected unindent". I honestly have no clue how to fix it. Any help would be greatly appreciated. Here is the ...
-3
2016-07-21T06:06:16Z
38,496,310
<p>In your code, you have two try blocks and one except. The indentation of the except block does not align with either of the try blocks. Moreover, you have defined the same function within the given function! Your code is all over the place. Remove the inner function block and replace it with a call to the function i...
0
2016-07-21T06:17:49Z
[ "python", "for-loop" ]
character buffer object error in translate python
38,496,199
<pre><code> 1 import sys 2 import string 3 from collections import Counter 4 5 def count_words(input_file_path, *w_f): 6 tab = dict.fromkeys([ord(i) for i in string.punctuation], u' ') 7 words = [] 8 count = 0 9 frequency = Counter() 10 with open(input_file_path, "r") as fp: 11 ...
0
2016-07-21T06:11:59Z
38,497,578
<p>From the <a href="https://docs.python.org/2/library/string.html#string.translate" rel="nofollow">documentation on <code>str.translate</code></a>:</p> <blockquote> <p>translate the characters using table, which <strong>must be a 256-character string</strong></p> </blockquote> <p>You're however trying to use a dic...
0
2016-07-21T07:21:59Z
[ "python", "translate" ]
Can I dynamically change an individual handler's log level in Python?
38,496,263
<p>I have a logger set up with two handlers - one to console and one a rotated file. I set each individual handlers with their own log level. The idea is that important messages are available on the console, while the lower level stuff goes to the file in case I need to do further troubleshooting.</p> <p>My config fil...
0
2016-07-21T06:15:08Z
38,496,484
<p>You'd have to traverse to the specific handler:</p> <pre><code>console_handler = logging.getLogger().handlers[0] old_level = console_handler.level console_handler.setLevel(logging.DEBUG) </code></pre> <p>The index matches the order from the <code>handlers</code> in your logging configuration (any previous handlers...
1
2016-07-21T06:26:27Z
[ "python", "logging" ]
Fastest way to extract dictionary of sums in numpy in 1 I/O pass
38,496,418
<p>Let's say I have an array like:</p> <pre><code>arr = np.array([[1,20,5], [1,20,8], [3,10,4], [2,30,6], [3,10,5]]) </code></pre> <p>and I would like to form a dictionary of the sum of the third column for each row that matches each value in the first c...
7
2016-07-21T06:23:23Z
38,497,749
<p>numpy approach:</p> <pre><code>u = np.unique(arr[:, 0]) s = ((arr[:, [0]] == u) * arr[:, [2]]).sum(0) dict(np.stack([u, s]).T) {1: 13, 2: 6, 3: 9} </code></pre> <p>pandas approach:</p> <pre><code>import pandas as pd import numpy as np pd.DataFrame(arr, columns=list('ABC')).groupby('A').C.sum().to_dict() {1: 1...
4
2016-07-21T07:30:20Z
[ "python", "numpy", "pandas", "dictionary", "vectorization" ]
Fastest way to extract dictionary of sums in numpy in 1 I/O pass
38,496,418
<p>Let's say I have an array like:</p> <pre><code>arr = np.array([[1,20,5], [1,20,8], [3,10,4], [2,30,6], [3,10,5]]) </code></pre> <p>and I would like to form a dictionary of the sum of the third column for each row that matches each value in the first c...
7
2016-07-21T06:23:23Z
38,501,309
<p>Here's a NumPy based approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.reduceat.html" rel="nofollow"><code>np.add.reduceat</code></a> -</p> <pre><code>sidx = arr[:,0].argsort() idx = np.append(0,np.where(np.diff(arr[sidx,0])!=0)[0]+1) keys = arr[sidx[idx],0] vals = np.add.reduc...
3
2016-07-21T10:10:16Z
[ "python", "numpy", "pandas", "dictionary", "vectorization" ]
Fastest way to extract dictionary of sums in numpy in 1 I/O pass
38,496,418
<p>Let's say I have an array like:</p> <pre><code>arr = np.array([[1,20,5], [1,20,8], [3,10,4], [2,30,6], [3,10,5]]) </code></pre> <p>and I would like to form a dictionary of the sum of the third column for each row that matches each value in the first c...
7
2016-07-21T06:23:23Z
38,501,662
<p>This is a typical grouping problem, which the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package solves efficiently and elegantly (if I may say so myself; I am its author)</p> <pre><code>import numpy_indexed as npi npi.group_by(arr[:, 0]).sum(arr[:, 2]) </cod...
3
2016-07-21T10:24:51Z
[ "python", "numpy", "pandas", "dictionary", "vectorization" ]
Fastest way to extract dictionary of sums in numpy in 1 I/O pass
38,496,418
<p>Let's say I have an array like:</p> <pre><code>arr = np.array([[1,20,5], [1,20,8], [3,10,4], [2,30,6], [3,10,5]]) </code></pre> <p>and I would like to form a dictionary of the sum of the third column for each row that matches each value in the first c...
7
2016-07-21T06:23:23Z
38,501,913
<p>The proper way of doing this is with NumPy is using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a>. If your unique first column labels are already small contiguous integers you could simply do:</p> <pre><code>cum_sums = np.bincount(arr[...
3
2016-07-21T10:35:18Z
[ "python", "numpy", "pandas", "dictionary", "vectorization" ]
Writing less elif statement
38,496,466
<p>I need help with this.</p> <pre><code>a = ["cat","dog","fish","hamster"] user = raw_input("choose your fav pet ") if user == a[0]: print a[0] elif user == a[1]: print a[1] elif user == a[2]: print a[2] elif user == a[3]: print a[3] else: print "sorry, the aninimal you type does not e...
0
2016-07-21T06:25:35Z
38,496,554
<p>I'd go with:</p> <pre><code>if user in a: print user </code></pre> <p>That will check if <code>user</code> input is in the list of pets and if it is, it will print it.</p>
4
2016-07-21T06:30:37Z
[ "python", "python-2.7", "if-statement" ]
Writing less elif statement
38,496,466
<p>I need help with this.</p> <pre><code>a = ["cat","dog","fish","hamster"] user = raw_input("choose your fav pet ") if user == a[0]: print a[0] elif user == a[1]: print a[1] elif user == a[2]: print a[2] elif user == a[3]: print a[3] else: print "sorry, the aninimal you type does not e...
0
2016-07-21T06:25:35Z
38,496,561
<p>Use a <code>for</code> loop:</p> <pre><code>for animal in a: if user == animal: print animal break else: print "Sorry, the animal you typed does not exist" </code></pre> <p>I'd note however that this code is a bit silly. If all you're going to do when you find the animal matching the user's...
5
2016-07-21T06:31:05Z
[ "python", "python-2.7", "if-statement" ]
Writing less elif statement
38,496,466
<p>I need help with this.</p> <pre><code>a = ["cat","dog","fish","hamster"] user = raw_input("choose your fav pet ") if user == a[0]: print a[0] elif user == a[1]: print a[1] elif user == a[2]: print a[2] elif user == a[3]: print a[3] else: print "sorry, the aninimal you type does not e...
0
2016-07-21T06:25:35Z
38,496,587
<p>Use in operator: </p> <pre><code>if user in a: print user else : print "sorry, the aninimal you type does not exist" </code></pre>
0
2016-07-21T06:32:47Z
[ "python", "python-2.7", "if-statement" ]
Writing less elif statement
38,496,466
<p>I need help with this.</p> <pre><code>a = ["cat","dog","fish","hamster"] user = raw_input("choose your fav pet ") if user == a[0]: print a[0] elif user == a[1]: print a[1] elif user == a[2]: print a[2] elif user == a[3]: print a[3] else: print "sorry, the aninimal you type does not e...
0
2016-07-21T06:25:35Z
38,496,976
<pre><code> a = ["cat","dog","pig","cat"] animal = input("enter animal:") if animal in a: print (animal , "found") else: print ("animal you entered not found in the list") </code></pre> <p>The above code is apt for your requirement.</p>
0
2016-07-21T06:51:52Z
[ "python", "python-2.7", "if-statement" ]
Writing less elif statement
38,496,466
<p>I need help with this.</p> <pre><code>a = ["cat","dog","fish","hamster"] user = raw_input("choose your fav pet ") if user == a[0]: print a[0] elif user == a[1]: print a[1] elif user == a[2]: print a[2] elif user == a[3]: print a[3] else: print "sorry, the aninimal you type does not e...
0
2016-07-21T06:25:35Z
38,499,352
<p>I would like to add a new way which i am unable to guess how every body missed. We must check string with case insensitive criteria.</p> <pre><code>a = ["cat","dog","fish","hamster"] user = raw_input("choose your fav pet ") // adding for user case where user might have entered DOG, but that is valid match matching...
0
2016-07-21T08:47:31Z
[ "python", "python-2.7", "if-statement" ]
Python Timedelta Arithmetic With noleap Calendars
38,496,831
<p>I'm working with CMIP5 data that has time units of "days since 1-1-1850". To find the current day I'm working with in the file, I would normally just do a timedelta addition from 1-1-1850 and the time value (in days) for the datapoint that I'm working with. However, CMIP5 (or at least the file I'm using) uses a 'nol...
1
2016-07-21T06:45:21Z
38,503,519
<p><a href="http://unidata.github.io/netcdf4-python/#netCDF4.num2date" rel="nofollow">netCDF num2date</a> is the function you are looking for:</p> <pre><code>import netCDF4 ncfile = netCDF4.Dataset('./foo.nc', 'r') time = ncfile.variables['time'] # note that we do not cast to numpy array yet time_convert = netCDF4.nu...
2
2016-07-21T11:51:02Z
[ "python", "datetime", "time-series", "netcdf", "timedelta" ]
Performance of groupby when dealing with `category` type in pandas
38,496,930
<p>I would like to understand the subtlety behind the usage of <code>category</code> in pandas.</p> <p>I created a random three columns DataFrame through</p> <pre><code>import pandas as pd import numpy as np a = np.random.choice(['a', 'A'], size=100000) b = np.random.choice(range(10000), size=100000) df = pd.DataFr...
1
2016-07-21T06:50:07Z
38,497,089
<p>I think you can use rather <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofollow"><code>SeriesGroupBy.nunique</code></a>, it works with <code>category</code> only a little bit slowier:</p> <pre><code>print (df.groupby(by='B')['A1'].nunique()) pr...
2
2016-07-21T06:58:00Z
[ "python", "performance", "pandas", "category" ]
Check if item in a Python list is an int/number
38,496,967
<p>I have a Python script that reads in a .csv file and stores each of the values into a list of lists: list[x][y]. I don't have any issues with this. </p> <pre><code>list = [] i = 0 for row in reader: list.append([]) list[i].append(row[0]) ... i += 1 </code></pre> <p>I want to check one of thes...
0
2016-07-21T06:51:26Z
38,497,044
<p>You can check it with this - this is for all numbers (positive and negative integer, floats, Nan), for only <code>int</code> or certain subclass, better approaches might exist.</p> <pre><code>def is_number(a): # will be True also for 'NaN' try: number = float(a) return True except ValueE...
1
2016-07-21T06:55:31Z
[ "python", "int", "isinstance" ]
Check if item in a Python list is an int/number
38,496,967
<p>I have a Python script that reads in a .csv file and stores each of the values into a list of lists: list[x][y]. I don't have any issues with this. </p> <pre><code>list = [] i = 0 for row in reader: list.append([]) list[i].append(row[0]) ... i += 1 </code></pre> <p>I want to check one of thes...
0
2016-07-21T06:51:26Z
38,502,956
<p>The following approach will return for integers only:</p> <pre><code>string_list = ['20.0', '100', 'abc', '10.3445', 'adsfasdf.adsfasdf', '10,3445', '34,0'] def check(inp): try: inp = inp.replace(',', '.') num_float = float(inp) num_int = int(num_float) return num_int == num_flo...
0
2016-07-21T11:23:21Z
[ "python", "int", "isinstance" ]
how to check if a datetime data is in the index of a dataframe
38,497,140
<p>i have a dataframe <code>df_hq</code> showed as follow</p> <p><a href="http://i.stack.imgur.com/gU4KH.png" rel="nofollow"><img src="http://i.stack.imgur.com/gU4KH.png" alt="enter image description here"></a></p> <pre><code>df_hq.index.values Out[26]: array([('000001.SZ', Timestamp('2009-01-05 00:00:00')), ...
1
2016-07-21T07:01:07Z
38,497,237
<p>If this is an index with tuples, you can only search easily for specific tuples.</p> <pre><code>('000001.SZ', Timestamp('2009-01-05 00:00:00')) in df_hq.index </code></pre> <p>I'd change it to a MultiIndex though for better functionality.</p> <pre><code>df_hq.index = pd.MultiIndex.from_tuples(df_hq.index.values) ...
1
2016-07-21T07:05:41Z
[ "python", "pandas" ]
Python OpenCV - VideoCapture.release() won't work in Linux
38,497,384
<p>I'm using OpenCV 2.4.9 and Python 2.7.11.</p> <p>I've written a small program that shows the camera output, and when pressing 'q', closes the camera but doesn't exit the application (for further work...).</p> <p>The issue is that the webcam is not really released, the LED keeps on and when I try again to open it, ...
1
2016-07-21T07:13:11Z
38,498,216
<p>The way to free the camera (without exiting) is indeed release(). I've tested your code in a Linux Mint 18 (64bit) environment running both OpenCV 2.4.13 and also OpenCV 3.1 with Python 2.7.12. There were no issues. </p> <p>Here is a way for you to see what is going on in your code:</p> <pre><code>import cv2 impor...
2
2016-07-21T07:53:20Z
[ "python", "linux", "opencv", "video-capture" ]
Get correct brace grouping from string
38,497,452
<p>I have files with incorrect JSON that I want to start fixing by getting it into properly grouped chunks.</p> <p>The brace grouping <code>{{ {} {} } } {{}} {{{}}}</code> should already be correct</p> <p>How can I grab all the top-level braces, correctly grouped, as separate strings?</p>
0
2016-07-21T07:15:59Z
38,497,614
<p>Using the <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><code>regex</code> module</a>:</p> <pre><code>In [1]: import regex In [2]: braces = regex.compile(r"\{(?:[^{}]++|(?R))*\}") In [3]: braces.findall("{{ {} {} } } {{}} {{{}}}") Out[3]: ['{{ {} {} } }', '{{}}', '{{{}}}'] </code></pre>
1
2016-07-21T07:23:39Z
[ "python" ]
Get correct brace grouping from string
38,497,452
<p>I have files with incorrect JSON that I want to start fixing by getting it into properly grouped chunks.</p> <p>The brace grouping <code>{{ {} {} } } {{}} {{{}}}</code> should already be correct</p> <p>How can I grab all the top-level braces, correctly grouped, as separate strings?</p>
0
2016-07-21T07:15:59Z
38,497,689
<p>If you don't want to install any extra modules simple function will do:</p> <pre><code>def top_level(s): depth = 0 start = -1 for i, c in enumerate(s): if c == '{': if depth == 0: start = i depth += 1 elif c == '}' and depth: depth -= ...
2
2016-07-21T07:26:57Z
[ "python" ]
Get correct brace grouping from string
38,497,452
<p>I have files with incorrect JSON that I want to start fixing by getting it into properly grouped chunks.</p> <p>The brace grouping <code>{{ {} {} } } {{}} {{{}}}</code> should already be correct</p> <p>How can I grab all the top-level braces, correctly grouped, as separate strings?</p>
0
2016-07-21T07:15:59Z
38,498,038
<p><code>pyparsing</code> can be really helpful here. It will handle pathological cases where you have braces inside strings, etc. It might be a little tricky to do all of this work yourself, <em>but</em> fortunately, somebody (the author of the library) has already done the <a href="http://pyparsing.wikispaces.com/f...
1
2016-07-21T07:44:03Z
[ "python" ]
Python: How to override text area in form using CSS
38,497,666
<p>Hi I would like to ask on how to override the text area in form using CSS. This is my codes:</p> <p>forms.py</p> <pre><code>description = forms.CharField(widget=forms.Textarea(attrs={'class': 'comment-control'})) </code></pre> <p>CSS:</p> <pre><code>.comment-control { background-color: #fff; width: 830p...
1
2016-07-21T07:25:49Z
38,497,893
<p>you should do something like this:</p> <pre><code>description = forms.CharField(widget=forms.Textarea(attrs={'cols':'4', 'rows':'50'})) </code></pre>
1
2016-07-21T07:37:26Z
[ "python", "html", "css" ]
np.nanmax() over all except one axis - is this the best way?
38,497,845
<p>For a numpy array of dimension <code>n</code>, I'd like to apply np.nanmax() to <code>n-1</code> dimensions producing a 1 dimensional array of maxima, ignoring all values set to <code>np.nan</code>.</p> <pre><code>q = np.arange(5*4*3.).reshape(3,4,5) % (42+1) q[q%5==0] = np.nan </code></pre> <p>producing:<...
1
2016-07-21T07:35:49Z
38,498,357
<p>The <code>axis</code> argument of <code>nanmax</code> can be a tuple of axes over which the maximum is computed. In your case, you want that tuple to contain all the axes except <code>m</code>. Here's one way you could do that:</p> <pre><code>In [62]: x Out[62]: array([[[[ 4., 3., nan, nan], [ 0.,...
1
2016-07-21T08:01:02Z
[ "python", "numpy" ]
How to reshape an array
38,497,892
<p>I want to create 5*3 array like below without typing it explicitly. </p> <pre><code>[[1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9, 14], [5, 10, 15]] </code></pre> <p>I used write following codes.</p> <pre><code>np.arange(1, 16).T.reshape((5,3)) </code></pre> <p>but it shows</p> <pre><code>array([[ 1, 2, ...
2
2016-07-21T07:37:25Z
38,498,030
<p>That's what you are looking for:</p> <pre><code>np.arange(1, 16).reshape((3,5)).T </code></pre> <p>In fact, in order: </p> <ul> <li><code>np.arange(1,16)</code> will return evenly spaced values within the interval 1 to 6 (default step size is 1) [<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy....
5
2016-07-21T07:43:37Z
[ "python", "numpy" ]
How to reshape an array
38,497,892
<p>I want to create 5*3 array like below without typing it explicitly. </p> <pre><code>[[1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9, 14], [5, 10, 15]] </code></pre> <p>I used write following codes.</p> <pre><code>np.arange(1, 16).T.reshape((5,3)) </code></pre> <p>but it shows</p> <pre><code>array([[ 1, 2, ...
2
2016-07-21T07:37:25Z
38,526,677
<p>For completeness, it is worth noticing that there is no need to transpose the array as suggested in the currently accepted answer. You just need to invoke <a href="http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.reshape.html#numpy.reshape" rel="nofollow"><code>numpy.reshape</code></a> with the followin...
1
2016-07-22T12:39:12Z
[ "python", "numpy" ]
Parse json array with out object in python
38,497,905
<p>I have a below json array file with out object. How do I parse it in python. I would like to construct all dataNomTime into a array.</p> <pre><code>[{ "id": 8916, "objectPaths": ["/thmo/help"], "dataTime": 1464961203, "dataNomTime": 1464818400, "dataEndTime": 1464904800, "attribs": null }, {...
0
2016-07-21T07:37:50Z
38,497,968
<p>Since you have a list of dictionaries, <code>data</code> is a list and should be treating as a list.</p> <p>If you want to extract all the <code>dataNomTime</code> you should do:</p> <pre><code>nom_times_list = [] for obj in data: nom_times_list.append(obj['dataNomTime']) </code></pre> <p>Or as a list compreh...
3
2016-07-21T07:40:59Z
[ "python" ]
Capturing image from Webcam Using Python on Windows
38,497,924
<p>the code i am using now is :- </p> <pre><code>from VideoCapture import Device cam = Device() cam.saveSnapshot('image.jpg') </code></pre> <p>using py 2.7 and imported pygame and all and videocapture i am getting this error in pycharm :- </p> <pre><code>C:\Python27\python.exe F:/Xtraz/Orion/Key-Logger.py Traceback...
0
2016-07-21T07:38:48Z
38,498,821
<p>You might want to downgrade you version of PIL, it seems like VideoCapture hasn't been updated for a while and is still relying on outdated versions of PIL.</p> <p>PIL 2.x seems to have a working <code>fromstring</code> method: <a href="https://github.com/python-pillow/Pillow/blob/2.9.0/PIL/Image.py#L750" rel="nofo...
0
2016-07-21T08:22:31Z
[ "python", "image", "save", "webcam", "capture" ]