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 can I find out what Python distribution I am using from within Python?
39,295,364
<p>I'm using an application (QGIS) that can execute Python and can be extended with plugins written in Python. Depending on the platform, the installer of this application brings along its own Python distribution which it installs alongside the application to be used by the application. On other platforms, the installation doesn't bring Python along and the system Python interpreter is used.</p> <p>Can I find out from within Python (in the application's interactive Python console or from within a plugin) what Python is being used?</p>
2
2016-09-02T14:54:15Z
39,295,386
<p><code>version_info</code> from <code>sys</code> module gives you that answer:</p> <pre><code>import sys print sys.version_info sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0) </code></pre> <p>You can get every value of it by using ie.: </p> <pre><code>print sys.version_info.major </code></pre>
2
2016-09-02T14:55:49Z
[ "python" ]
How can I find out what Python distribution I am using from within Python?
39,295,364
<p>I'm using an application (QGIS) that can execute Python and can be extended with plugins written in Python. Depending on the platform, the installer of this application brings along its own Python distribution which it installs alongside the application to be used by the application. On other platforms, the installation doesn't bring Python along and the system Python interpreter is used.</p> <p>Can I find out from within Python (in the application's interactive Python console or from within a plugin) what Python is being used?</p>
2
2016-09-02T14:54:15Z
39,295,406
<pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.version '2.7.12 (default, Jun 29 2016, 14:05:02) \n[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)]' </code></pre>
0
2016-09-02T14:56:38Z
[ "python" ]
How can I find out what Python distribution I am using from within Python?
39,295,364
<p>I'm using an application (QGIS) that can execute Python and can be extended with plugins written in Python. Depending on the platform, the installer of this application brings along its own Python distribution which it installs alongside the application to be used by the application. On other platforms, the installation doesn't bring Python along and the system Python interpreter is used.</p> <p>Can I find out from within Python (in the application's interactive Python console or from within a plugin) what Python is being used?</p>
2
2016-09-02T14:54:15Z
39,295,476
<pre><code>&gt;&gt;&gt; import platform &gt;&gt;&gt; print(platform.python_version()) </code></pre>
0
2016-09-02T15:00:41Z
[ "python" ]
Something like ast.literal_eval to execute variable assignments
39,295,414
<p>I want to do something like:</p> <pre><code>import ast def foo(common_stuff, assignment_str): common_stuff() ast.literal_eval(assignment_str) # assignment to unknown or passed variable foo('a=1;b=2') </code></pre> <p>is this possible in Python?</p> <p>I am trying to write a general function to (enforce DRY) for this:</p> <pre><code> for f, i in zip(task_set, xrange(len(task_set))): cd = f.cleaned_data t_name = cd.get('t_name') start_date = cd.get('start_date') end_date = cd.get('end_date') project = Project.objects.get(pro_id=p.pro_id) task = Task(t_name=t_name, start_date=start_date, end_date=end_date, project=project) task.save() tasks_list.append(task) </code></pre> <p>So I started writing the following:</p> <pre><code>def save_form(model, formset, foreignkey_assignment, *args){ for f, i in zip(formset, xrange(len(formset))): cd = f.cleaned_data get_key_name = lambda x: cd.get(x) ast.literal_eval(foreignkey_assignment) m = model(**{k:get_key_name(k) for k in args}) m.save() } </code></pre>
0
2016-09-02T14:57:04Z
39,296,116
<p>Yes you can</p> <pre><code>exec('a=1;b=2') </code></pre> <p>but you shouldn't. <a href="http://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided">Why should exec() and eval() be avoided?</a></p>
0
2016-09-02T15:36:59Z
[ "python", "eval", "variable-assignment", "literals" ]
Something like ast.literal_eval to execute variable assignments
39,295,414
<p>I want to do something like:</p> <pre><code>import ast def foo(common_stuff, assignment_str): common_stuff() ast.literal_eval(assignment_str) # assignment to unknown or passed variable foo('a=1;b=2') </code></pre> <p>is this possible in Python?</p> <p>I am trying to write a general function to (enforce DRY) for this:</p> <pre><code> for f, i in zip(task_set, xrange(len(task_set))): cd = f.cleaned_data t_name = cd.get('t_name') start_date = cd.get('start_date') end_date = cd.get('end_date') project = Project.objects.get(pro_id=p.pro_id) task = Task(t_name=t_name, start_date=start_date, end_date=end_date, project=project) task.save() tasks_list.append(task) </code></pre> <p>So I started writing the following:</p> <pre><code>def save_form(model, formset, foreignkey_assignment, *args){ for f, i in zip(formset, xrange(len(formset))): cd = f.cleaned_data get_key_name = lambda x: cd.get(x) ast.literal_eval(foreignkey_assignment) m = model(**{k:get_key_name(k) for k in args}) m.save() } </code></pre>
0
2016-09-02T14:57:04Z
39,296,162
<p><code>ast.literal_eval()</code> 'executes' the AST parse tree of an evaluation, and limits this to a strict subset that only allows for standard Python literals. You could take the <a href="https://hg.python.org/cpython/file/v3.5.1/Lib/ast.py#l38" rel="nofollow">source code</a> and add assignment support (where I'd use a separate dictionary to handle names). </p> <p>You'd have to add <code>Assign</code> and <code>Name</code> node handling (Python 3 version):</p> <pre><code>def literal_eval(node_or_string, namespace): """ Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None. """ if isinstance(node_or_string, str): node_or_string = ast.parse(node_or_string, mode='exec') if isinstance(node_or_string, ast.Module): node_or_string = node_or_string.body def _convert(node, ns=None): if isinstance(node, (ast.Str, ast.Bytes)): return node.s elif isinstance(node, ast.Num): return node.n elif isinstance(node, ast.Tuple): return tuple(map(_convert, node.elts)) elif isinstance(node, ast.List): return list(map(_convert, node.elts)) elif isinstance(node, ast.Set): return set(map(_convert, node.elts)) elif isinstance(node, ast.Dict): return dict((_convert(k), _convert(v)) for k, v in zip(node.keys, node.values)) elif isinstance(node, ast.NameConstant): return node.value elif isinstance(node, ast.UnaryOp) and \ isinstance(node.op, (ast.UAdd, ast.USub)) and \ isinstance(node.operand, (ast.Num, ast.UnaryOp, ast.BinOp)): operand = _convert(node.operand) if isinstance(node.op, ast.UAdd): return + operand else: return - operand elif isinstance(node, ast.BinOp) and \ isinstance(node.op, (ast.Add, ast.Sub)) and \ isinstance(node.right, (ast.Num, ast.UnaryOp, ast.BinOp)) and \ isinstance(node.left, (ast.Num, ast.UnaryOp, ast.BinOp)): left = _convert(node.left) right = _convert(node.right) if isinstance(node.op, ast.Add): return left + right else: return left - right elif isinstance(node, ast.Assign) and \ len(node.targets) == 1 and \ isinstance(node.targets[0], ast.Name): assert isinstance(ns, dict) # will be None when not top-level ns[node.targets[0].id] = _convert(node.value) return raise ValueError('malformed node or string: ' + repr(node)) return _convert(node_or_string, namespace) </code></pre> <p>Or you could use the <a href="https://newville.github.io/asteval/" rel="nofollow"><code>asteval</code> project</a>, which does exactly that and a little more, supporting simple expressions and assignment, using AST tree interpretation. </p>
1
2016-09-02T15:39:08Z
[ "python", "eval", "variable-assignment", "literals" ]
The MSS-maximum likelihood method for Fluctuation Test
39,295,443
<p>I am trying to implement an algorithm in the following paper (method 5) <a href="http://dx.doi.org/10.1016%2FS0076-6879(05)09012-9" rel="nofollow">http://dx.doi.org/10.1016%2FS0076-6879(05)09012-9</a> in python2.7 to improve my programming skill. Implementations can be found at these locations: Apparently I cannot post so many links. If my reputation goes up, I will post the links here.</p> <p><a href="http://i.stack.imgur.com/RsSYZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/RsSYZ.png" alt="This is the function I am trying to implement"></a></p> <p>Essentially, the algorithm is used for biological research, and finds the mutation rate of cells under some condition. Here is my attempt, which has errors (NOTE: I updated this code to remove an error however I am still not getting the right answer):</p> <pre><code> import numpy as np import sympy as sp from scipy.optimize import minimize def leeCoulson(nparray): median=np.median(nparray) x=sp.Symbol('x') M_est=sp.solve(sp.Eq(-x*sp.log(x) - 1.24*x + median,0),x) return M_est def ctArray(nparray,max): list=[0] * int(max+1) for i in range(int(max)+1): list[i]=nparray.count(i) return list values='filename1.csv' data=np.genfromtxt(values,delimiter=',') mVal=int(max(data)) ctArray_=ctArray(np.ndarray.tolist(data),mVal) ef mssCalc(estM,max=mVal,count=ctArray_): def rec(pi,r): pr=(estM/r)+sum([(pi[i]/(r-i+1)) for i in range(0,r-1)]) return pr prod=1 pi=[0]*max pi[0]=np.exp(-1*estM) for r in range(1,max): pi[r]=rec(pi,r) prod=prod*(pi[r]**count[r]) return -1*prod finalM=minimize (mssCalc,leeCoulson(data),method='nelder-mead',options={'xtol':1e-3,'disp':True}) print finalM </code></pre> <p>This code gives the following errors:</p> <pre><code> mss-mle_calc.py:37: RuntimeWarning: overflow encountered in multiply prod=prod*(pi[r]**count[r]) /opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/optimize/optimize.py:462: RuntimeWarning: invalid value encountered in subtract numpy.max(numpy.abs(fsim[0] - fsim[1:])) &lt;= ftol): Warning: Maximum number of function evaluations has been exceeded. </code></pre> <p>Please help me make this code better if you have some time.</p>
1
2016-09-02T14:58:41Z
39,298,785
<p>Thanks for looking, there were a couple stupid mistakes in my code. Here is the working code (as far as I can tell):</p> <pre><code> import numpy as np import sympy as sp from scipy.optimize import minimize def leeCoulson(nparray): median=np.median(nparray) x=sp.Symbol('x') M_est=sp.solve(sp.Eq(-x*sp.log(x) - 1.24*x + median,0),x) return float(M_est[0]) def ctArray(nparray,max): list=[0] * int(max+1) for i in range(int(max)+1): list[i]=nparray.count(i) return list values='filename1.csv' data=np.genfromtxt(values,delimiter=',') mVal=int(max(data)) ctArray_=ctArray(np.ndarray.tolist(data),mVal) def mssCalc(estM,max=mVal,count=ctArray_): def rec(pi,r): pr=(estM/r)*sum([(pi[i]/(r-i+1)) for i in range(0,r)]) return pr prod=1 pi=[0]*(max+1) pi[0]=np.exp(-1.0*estM) for r in range(1,max+1): pi[r]=rec(pi,r) prod=prod*(pi[r]**count[r]) return -1*prod finalM=minimize (mssCalc,leeCoulson(data),method='nelder-mead',options={'xtol':1e-3,'disp':True}) print finalM </code></pre>
0
2016-09-02T18:34:23Z
[ "python", "algorithm" ]
Why does struct.pack return these values?
39,295,552
<p>I have an array of signed 16bit integers that I want to convert to a little endian byte string using struct.pack in python. But I don't understand, what values struct.pack returns. Here's an example:</p> <pre><code>&gt;&gt;&gt; bytestr = struct.pack('&lt;9h',*[45, 70, 33, 38, -6, 26, 34, 46, 57]) &gt;&gt;&gt; bytestr &gt;&gt;&gt;&gt; '-\x00F\x00!\x00&amp;\x00\xfa\xff\x1a\x00"\x00.\x009\x00' </code></pre> <p>Why are there all these special characters, like '!' or '&amp;'? Shouldn't it be only a 2 character string for each byte?</p>
0
2016-09-02T15:05:29Z
39,295,591
<p>When Python shows you a representation of a string, it'll always try to show you printable text where possible. <code>-</code>, <code>F</code>, <code>!</code>, <code>&amp;</code>, etc. are printable ASCII characters for the given bytes.</p> <p>The output is otherwise entirely correct.</p> <ul> <li><p><code>45</code>, as a little-endian byte string, is represented as 0x2D 0x00 hexademimal (45 00 in decimal), but the 0x2D byte value is also the <code>-</code> character in the ASCII character set.</p></li> <li><p><code>70</code> becomes 0x46 0x00, and 0x46 is the letter <code>F</code> in ASCII.</p></li> <li><p><code>33</code> becomes 0x21 0x00, and 0x21 is <code>!</code></p></li> </ul> <p>etc.</p> <p>If you wanted to verify the values, you could print the hexadecimal representation:</p> <pre><code>&gt;&gt;&gt; bytestr.encode('hex') '2d00460021002600faff1a0022002e003900' </code></pre> <p>or you could convert to a <a href="https://docs.python.org/2/library/functions.html#bytearray" rel="nofollow"><code>bytearray()</code> object</a>, then to a list, to get a list of integers in the range 0-255:</p> <pre><code>&gt;&gt;&gt; list(bytearray(bytestr)) [45, 0, 70, 0, 33, 0, 38, 0, 250, 255, 26, 0, 34, 0, 46, 0, 57, 0] </code></pre> <p>These are just different ways of showing you what exact values are present in that byte string.</p>
1
2016-09-02T15:07:46Z
[ "python", "struct", "pack" ]
Python Web Scraper print issue
39,295,642
<p>I have created a web scraper in python but when printing at the end I want to print ("Bakerloo: " + info_from_website) that I have downloaded as you can see in the code, but it always comes out just as info_from_website and ignores the "Bakerloo: " string. Can't find anyway of solving it.</p> <pre><code>import urllib import urllib.request from bs4 import BeautifulSoup import sys url = 'https://tfl.gov.uk/tube-dlr-overground/status/' page = urllib.request.urlopen(url) soup = BeautifulSoup(page,"html.parser") try: bakerlooInfo = (soup.find('li',{"class":"rainbow-list-item bakerloo "}).find_all('span')[2].text) except: bakerlooInfo = (soup.find('li',{"class":"rainbow-list-item bakerloo disrupted expandable "}).find_all('span')[2].text) bakerloo = bakerlooInfo.replace('\n','') print("Bakerloo : " + bakerloo) </code></pre>
1
2016-09-02T15:10:25Z
39,295,883
<p>I would use a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a> instead, getting the element with <code>disruption-summary</code> class:</p> <pre><code>import requests from bs4 import BeautifulSoup url = 'https://tfl.gov.uk/tube-dlr-overground/status/' page = requests.get(url) soup = BeautifulSoup(page.content, "html.parser") service = soup.select_one('li.bakerloo .disruption-summary').get_text(strip=True) print("Bakerloo: " + service) </code></pre> <p>Prints:</p> <pre><code>Bakerloo: Good service </code></pre> <p>(using <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a> here).</p> <hr> <p>Note that if you want to just list all stations with the disruption summaries, do:</p> <pre><code>import requests from bs4 import BeautifulSoup url = 'https://tfl.gov.uk/tube-dlr-overground/status/' page = requests.get(url) soup = BeautifulSoup(page.content, "html.parser") for station in soup.select("#rainbow-list-tube-dlr-overground-tflrail-tram ul li"): station_name = station.select_one(".service-name").get_text(strip=True) service_info = station.select_one(".disruption-summary").get_text(strip=True) print(station_name + ": " + service_info) </code></pre> <p>Prints:</p> <pre><code>Bakerloo: Good service Central: Good service Circle: Good service District: Good service Hammersmith &amp; City: Good service Jubilee: Good service Metropolitan: Good service Northern: Good service Piccadilly: Good service Victoria: Good service Waterloo &amp; City: Good service London Overground: Good service TfL Rail: Good service DLR: Good service Tram: Good service </code></pre>
2
2016-09-02T15:23:09Z
[ "python", "python-3.x", "web-scraping" ]
How to real-time check the django view operating process
39,295,659
<p>Here is the thing, When I submit a form from template to view ,since the process of this view will cost a lot time. I don's think our user enjoy to wait. So, I want to this: when user click the submit button,the browser will redirect to a new page or just show a sub-page in the same window that can print the real-time executing information.</p> <p>Before I post this question, I did a little research, looks like the celery can do this thing, am I right? If there is same problem already be asked in stackoverflow ,PLZ give me the link.</p> <p>Thank for your time!</p> <p>(English is not my mother language, so I don't know if we have any term to describe this function,if we do,PLZ give me a hint )</p>
0
2016-09-02T15:11:09Z
39,295,894
<p><a href="https://channels.readthedocs.io/en/latest/" rel="nofollow">django-channels</a> could be a good solution to send information as they execute on the server side in this way you can send information on the client side by opening a websocket. </p> <p>Channel can be used to post data to the client side without having to wait for the HttpResponse. </p> <p>Heroku has nice <a href="https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django" rel="nofollow">post</a> explaning channels.</p> <p>Hope this helps.</p>
0
2016-09-02T15:23:27Z
[ "python", "django", "celery" ]
How does "\x"+* work?
39,295,728
<p>I'm trying to make a filesharing program, so I open the files in readbinary, and read it, establish a connection, and I try to send byte for byte.</p> <p>How can I send <code>b"\x" + (encoded bytes of the int from dataread[i])</code>?</p> <p>I always gives me an error, also, if it won't work, how can I read exactly a byte? So that I don't get an int? (like <code>dataread[0]</code>, if the value is <code>"\x01"</code>, I get 1).</p> <p>My code:</p> <pre><code>for g in range(len(datar)): esc = str(datar[g]) if len(esc) == 1: esc = "0"+esc esc = "\x"+bytes(esc,"utf8") c.send(esc) c.recv(500) print(g,"Bytes von",len(datar),"gesendet") </code></pre>
-3
2016-09-02T15:15:05Z
39,295,757
<p>The <code>'\xhh'</code> notation only works in <em>string or byte literals</em>. If you have an integer, just pass this to a <code>bytes()</code> object in a list:</p> <pre><code>bytes(dataread) # if dataread is a list of integers </code></pre> <p>or</p> <pre><code>bytes([dataread]) # if dataread is a single integer </code></pre> <p><code>bytes</code> objects are sequences of integer values, each limited to the range 0-255.</p> <p>To send individual bytes from <code>datar</code>, that translates to:</p> <pre><code>for byte in datar: c.send(bytes([esc])) c.recv(500) print(g,"Bytes von",len(datar),"gesendet") </code></pre>
2
2016-09-02T15:16:29Z
[ "python", "sockets", "python-3.x", "byte" ]
groupby, sum and count to one table
39,295,910
<p>I have a dataframe below</p> <pre><code>df=pd.DataFrame({"A":np.random.randint(1,10,9),"B":np.random.randint(1,10,9),"C":list('abbcacded')}) A B C 0 9 6 a 1 2 2 b 2 1 9 b 3 8 2 c 4 7 6 a 5 3 5 c 6 1 3 d 7 9 9 e 8 3 4 d </code></pre> <p>I would like to get grouping result (with key="C" column) below,and the row c d and e is dropped intentionally.</p> <pre><code> number A_sum B_sum a 2 16 15 b 2 3 11 </code></pre> <p>this is 2row*3column dataframe. the grouping key is column C. And The column "number"represents the count of each letter(a and b). A_sum and B_sum represents grouping sum of letters in column C.</p> <p>I guess we should use method groupby but how can I get this data summary table ?</p>
1
2016-09-02T15:24:42Z
39,296,273
<p>One option is to count the size and sum the columns for each group separately and then join them by index:</p> <pre><code>df.groupby("C")['A'].agg({"number": 'size'}).join(df.groupby('C').sum()) number A B # C # a 2 11 8 # b 2 14 12 # c 2 8 5 # d 2 11 12 # e 1 7 2 </code></pre> <p>You can also do <code>df.groupby('C').agg(["sum", "size"])</code> which gives an extra duplicated size column, but if you are fine with that, it should also work.</p>
1
2016-09-02T15:44:59Z
[ "python", "pandas", "numpy" ]
groupby, sum and count to one table
39,295,910
<p>I have a dataframe below</p> <pre><code>df=pd.DataFrame({"A":np.random.randint(1,10,9),"B":np.random.randint(1,10,9),"C":list('abbcacded')}) A B C 0 9 6 a 1 2 2 b 2 1 9 b 3 8 2 c 4 7 6 a 5 3 5 c 6 1 3 d 7 9 9 e 8 3 4 d </code></pre> <p>I would like to get grouping result (with key="C" column) below,and the row c d and e is dropped intentionally.</p> <pre><code> number A_sum B_sum a 2 16 15 b 2 3 11 </code></pre> <p>this is 2row*3column dataframe. the grouping key is column C. And The column "number"represents the count of each letter(a and b). A_sum and B_sum represents grouping sum of letters in column C.</p> <p>I guess we should use method groupby but how can I get this data summary table ?</p>
1
2016-09-02T15:24:42Z
39,296,352
<p>You can do this using a single <code>groupby</code> with</p> <pre><code>res = df.groupby(df.C).agg({'A': 'sum', 'B': {'sum': 'sum', 'count': 'count'}}) res.columns = ['A_sum', 'B_sum', 'count'] </code></pre>
1
2016-09-02T15:49:03Z
[ "python", "pandas", "numpy" ]
Send already filled form with Python Requests
39,295,920
<p>just a quick question.</p> <p>Is there a way to submit a pre-filled form with the Python Requests library?</p> <p>For example, I'm on a page with a pre-filled form, there is a 'Submit' button that's gonna submit a post request with data which is already in form. Is there a way to 'simulate' clicking the 'Submit' button?</p> <p>I'd like to get the Form Data upon the submission (from header) instead of scrapping each field and getting it's value.</p> <p>Any help is appreciated. Thank you in advance.</p>
-1
2016-09-02T15:25:13Z
39,296,026
<p>Things like these can easily and transparently be solved with packages like <a href="https://github.com/hickford/MechanicalSoup" rel="nofollow"><code>MechanicalSoup</code></a> or <a href="https://github.com/jmcarp/robobrowser" rel="nofollow"><code>RoboBrowser</code></a>. Both are based on <code>requests</code> and <code>BeautifulSoup</code>, they can read the contents of a form and perform "submit" using the default/given or the custom/supplied values.</p> <p><a href="https://pypi.python.org/pypi/mechanize/" rel="nofollow"><code>mechanize</code></a> is an another, probably a more popular alternative for this task. </p>
0
2016-09-02T15:31:44Z
[ "python", "forms", "submit", "python-requests" ]
Python: Append tuple to a set with tuples
39,295,942
<p>Following is my code which is a set of tuples: </p> <pre><code>data = {('A',20160129,36.44),('A',20160201,37.37),('A',20160104,41.06)}; print(data); </code></pre> <p>Output: <code>set([('A', 20160129, 36.44), ('A', 20160104, 41.06), ('A', 20160201, 37.37)])</code></p> <p>How do I append another tuple <code>('A', 20160000, 22)</code> to <code>data</code>?</p> <p>Expected output: <code>set([('A', 20160129, 36.44), ('A', 20160104, 41.06), ('A', 20160201, 37.37), ('A', 20160000, 22)])</code></p> <p>Note: I found a lot of resources to append data to a set but unfortunately none of them have the input data in the above format. I tried <code>append</code>, <code>|</code> &amp; <code>set</code> functions as well. </p>
-1
2016-09-02T15:26:53Z
39,296,040
<p>the trick is to send it inside brackets so it doesn't get exploded</p> <pre><code>data.update([('A', 20160000, 22)]) </code></pre>
2
2016-09-02T15:32:22Z
[ "python", "set" ]
Concatenation of Strings and lists
39,295,972
<p>In the following python script, it converts the Celsius degree to Fahrenheit but I need to join two list with strings between and after them</p> <pre><code>Celsius = [39.2, 36.5, 37.3, 37.8] fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius) print '\n'.join(str(i) for i in Celsius)+" in Celsius is "+''.join(str(i) for i in fahrenheit )+" in farenheit" </code></pre> <p>The outcome is this(not what i wanted):</p> <pre><code>39.2 36.5 37.3 37.8 in Celsius is 102.5697.799.14100.04 in farenheit </code></pre> <p>How can I achieve this:</p> <pre><code>39.2 in Celsius is equivalent to 102.56 in fahrenheit 36.5 in Celsius is equivalent to 97.7 in fahrenheit 37.3 in Celsius is equivalent to 99.14 in fahrenheit 37.8 in Celsius is equivalent to 100.04 in fahrenheit </code></pre> <p><strong>EDIT SORRY MY BAD</strong> Well, the original code I had was</p> <pre><code>def fahrenheit(T): return ((float(9)/5)*T + 32) def display(c,f): print c, "in Celsius is equivalent to ",\ f, " in fahrenheit" Celsius = [39.2, 36.5, 37.3, 37.8] for c in Celsius: display(c,fahrenheit(c)) </code></pre> <p>But due to reasons I need it to be <strong>within 3 lines</strong></p>
2
2016-09-02T15:28:26Z
39,296,030
<p>It's probably easiest to do the formatting as you go:</p> <pre><code>Celsius = [39.2, 36.5, 37.3, 37.8] def fahrenheit(c): return (float(9)/5)*c + 32 template = '{} in Celsius is equivalent to {} in fahrenheit' print '\n'.join(template.format(c, fahrenheit(c)) for c in Celsius) </code></pre> <p><strong>EDIT</strong></p> <p>If you really want it under 3 lines, we can inline the <code>fahrenheit</code> function:</p> <pre><code>Celsius = [39.2, 36.5, 37.3, 37.8] template = '{} in Celsius is equivalent to {} in fahrenheit' print '\n'.join(template.format(c, (float(9)/5)*c + 32) for c in Celsius) </code></pre> <p>If you don't mind long lines, you could inline <code>template</code> as well and get it down to 2 lines...</p> <p>However, there really isn't any good reason to do this as far as I can tell. There is no penalty for writing python code that takes up more lines. Indeed, there is generally a penalty in the other direction that you pay every time you try to understand a really long complex line of code :-)</p>
8
2016-09-02T15:31:50Z
[ "python", "python-2.7" ]
Concatenation of Strings and lists
39,295,972
<p>In the following python script, it converts the Celsius degree to Fahrenheit but I need to join two list with strings between and after them</p> <pre><code>Celsius = [39.2, 36.5, 37.3, 37.8] fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius) print '\n'.join(str(i) for i in Celsius)+" in Celsius is "+''.join(str(i) for i in fahrenheit )+" in farenheit" </code></pre> <p>The outcome is this(not what i wanted):</p> <pre><code>39.2 36.5 37.3 37.8 in Celsius is 102.5697.799.14100.04 in farenheit </code></pre> <p>How can I achieve this:</p> <pre><code>39.2 in Celsius is equivalent to 102.56 in fahrenheit 36.5 in Celsius is equivalent to 97.7 in fahrenheit 37.3 in Celsius is equivalent to 99.14 in fahrenheit 37.8 in Celsius is equivalent to 100.04 in fahrenheit </code></pre> <p><strong>EDIT SORRY MY BAD</strong> Well, the original code I had was</p> <pre><code>def fahrenheit(T): return ((float(9)/5)*T + 32) def display(c,f): print c, "in Celsius is equivalent to ",\ f, " in fahrenheit" Celsius = [39.2, 36.5, 37.3, 37.8] for c in Celsius: display(c,fahrenheit(c)) </code></pre> <p>But due to reasons I need it to be <strong>within 3 lines</strong></p>
2
2016-09-02T15:28:26Z
39,296,134
<p>You could always try formatting using %f for float numbers and placing the output in a loop:</p> <pre><code>for i in range(len(Celsius)): print '%f in Celsius is equivalent to %f in fahrenheit' % (Celsius[i], fahrenheit[i]) </code></pre> <p>EDIT: As per the suggestion of @mgilson, using <code>zip</code> would be better to use instead of taking a count of just <code>Celsius</code>:</p> <pre><code>for c,f in zip(Celsius, fahrenheit): print '%f in Celsius is equivalent to %f in fahrenheit' % (c,f) </code></pre>
0
2016-09-02T15:37:48Z
[ "python", "python-2.7" ]
Concatenation of Strings and lists
39,295,972
<p>In the following python script, it converts the Celsius degree to Fahrenheit but I need to join two list with strings between and after them</p> <pre><code>Celsius = [39.2, 36.5, 37.3, 37.8] fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius) print '\n'.join(str(i) for i in Celsius)+" in Celsius is "+''.join(str(i) for i in fahrenheit )+" in farenheit" </code></pre> <p>The outcome is this(not what i wanted):</p> <pre><code>39.2 36.5 37.3 37.8 in Celsius is 102.5697.799.14100.04 in farenheit </code></pre> <p>How can I achieve this:</p> <pre><code>39.2 in Celsius is equivalent to 102.56 in fahrenheit 36.5 in Celsius is equivalent to 97.7 in fahrenheit 37.3 in Celsius is equivalent to 99.14 in fahrenheit 37.8 in Celsius is equivalent to 100.04 in fahrenheit </code></pre> <p><strong>EDIT SORRY MY BAD</strong> Well, the original code I had was</p> <pre><code>def fahrenheit(T): return ((float(9)/5)*T + 32) def display(c,f): print c, "in Celsius is equivalent to ",\ f, " in fahrenheit" Celsius = [39.2, 36.5, 37.3, 37.8] for c in Celsius: display(c,fahrenheit(c)) </code></pre> <p>But due to reasons I need it to be <strong>within 3 lines</strong></p>
2
2016-09-02T15:28:26Z
39,296,366
<p>In order to do it with <code>join</code>, you can include the extra parts of the string inside of the <code>join</code> statement.</p> <pre><code>celsius = [39.2, 36.5, 37.3, 37.8] fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius) print '\n'.join(str(i) + " in celsius is " + str(j) + "in farenheit" for i, j in zip(celsius, fahrenheit)) </code></pre>
2
2016-09-02T15:49:27Z
[ "python", "python-2.7" ]
Concatenation of Strings and lists
39,295,972
<p>In the following python script, it converts the Celsius degree to Fahrenheit but I need to join two list with strings between and after them</p> <pre><code>Celsius = [39.2, 36.5, 37.3, 37.8] fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius) print '\n'.join(str(i) for i in Celsius)+" in Celsius is "+''.join(str(i) for i in fahrenheit )+" in farenheit" </code></pre> <p>The outcome is this(not what i wanted):</p> <pre><code>39.2 36.5 37.3 37.8 in Celsius is 102.5697.799.14100.04 in farenheit </code></pre> <p>How can I achieve this:</p> <pre><code>39.2 in Celsius is equivalent to 102.56 in fahrenheit 36.5 in Celsius is equivalent to 97.7 in fahrenheit 37.3 in Celsius is equivalent to 99.14 in fahrenheit 37.8 in Celsius is equivalent to 100.04 in fahrenheit </code></pre> <p><strong>EDIT SORRY MY BAD</strong> Well, the original code I had was</p> <pre><code>def fahrenheit(T): return ((float(9)/5)*T + 32) def display(c,f): print c, "in Celsius is equivalent to ",\ f, " in fahrenheit" Celsius = [39.2, 36.5, 37.3, 37.8] for c in Celsius: display(c,fahrenheit(c)) </code></pre> <p>But due to reasons I need it to be <strong>within 3 lines</strong></p>
2
2016-09-02T15:28:26Z
39,296,523
<p>3 lines:</p> <pre><code>&gt;&gt;&gt; Celsius = [39.2, 36.5, 37.3, 37.8] &gt;&gt;&gt; msg = '%g in Celsius is equivalent to %g in Fahrenheit' &gt;&gt;&gt; print '\n'.join(msg % (c, (9. * c)/5. + 32.) for c in Celsius) </code></pre> <p>yields:</p> <blockquote> <p>39.2 in Celsius is equivalent to 102.56 in Fahrenheit<br> 36.5 in Celsius is equivalent to 97.7 in Fahrenheit<br> 37.3 in Celsius is equivalent to 99.14 in Fahrenheit<br> 37.8 in Celsius is equivalent to 100.04 in Fahrenheit </p> </blockquote>
2
2016-09-02T15:58:25Z
[ "python", "python-2.7" ]
"rect" class can't be the parameterof the method "screen.blit()"
39,295,996
<p>I want to draw a rectangle to be a simplified rocket, but my <code>pycharm</code> shows <code>argument 1 must be pygame.Surface, not pygame.Rect</code> just like in the picture.<a href="http://i.stack.imgur.com/gk1MH.png" rel="nofollow"><img src="http://i.stack.imgur.com/gk1MH.png" alt="enter image description here"></a></p> <p>the following is my code:</p> <pre><code>screen = pygame.display.set_mode([400, 600]) screen.fill([0, 0, 0]) ship = pygame.draw.rect(screen, [255, 22, 150], [200, 400, 50, 100], 0) moon = pygame.draw.rect(screen, [79, 200, 145], [0, 550, 400, 50], 0) screen.blit(moon, [0, 500, 400, 100]) </code></pre> <p>Then I changed my code to this:</p> <pre><code>screen = pygame.display.set_mode([400, 600]) screen.fill([0, 0, 0]) ship_mode = pygame.draw.rect(screen, [255, 22, 150], [200, 400, 50, 100], 0) ship = ship_mode.convert() moon_mode = pygame.draw.rect(screen, [79, 200, 145], [0, 550, 400, 50], 0) moon = moon_mode.convert() screen.blit(moon, [0, 500, 400, 100]) </code></pre> <p>This time it indicates <code>Traceback (most recent call last): File "E:/untitled/launching rocket.py", line 11, in &lt;module&gt; ship = ship_mode.convert() AttributeError: 'pygame.Rect' object has no attribute 'convert'</code> How could I finish what I am expecting?</p>
0
2016-09-02T15:29:45Z
39,296,121
<p>The function <code>pygame.draw.rect</code> draws directly on the Surface (the one you've given as argument) and returns a Rect object representing the area drawn. It doesn't return a Surface. </p> <p>You can remove the line <code>screen.blit(moon, [0, 500, 400, 100])</code> since the rectangle is already drawn to the <code>screen</code>. You don't need to assign the function to anything either, unless you need a reference to where the rects were drawn.</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode([400, 600]) screen.fill([0, 0, 0]) pygame.draw.rect(screen, [255, 22, 150], [200, 400, 50, 100], 0) pygame.draw.rect(screen, [79, 200, 145], [0, 550, 400, 50], 0) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: quit() pygame.display.update() </code></pre> <p>If you want to move images around I suggest you do something like this:</p> <pre><code>import pygame pygame.init() screen = pygame.display.set_mode([400, 600]) ship_image = pygame.Surface((50, 100)) # Create a rectangular Surface. ship_image.fill((255, 22, 150)) # Fill it with a color. ship_rect = pygame.Rect(200, 400, 50, 100) # Create a rect for where to blit the ship. moon_image = pygame.Surface((400, 50)) # Create a rectangular Surface. moon_image.fill((79, 200, 145)) # Fill it with a color. moon_rect = pygame.Rect(0, 550, 400, 50) # Create a rect for where to blit the ship. while True: for event in pygame.event.get(): if event.type == pygame.QUIT: quit() elif event.type == pygame.KEYDOWN: # If you press a key down. if event.key == pygame.K_RIGHT: # If the key is the right arrow key. ship_rect.move_ip(5, 0) # Move the rect to the right. elif event.key == pygame.K_LEFT: ship_rect.move_ip(-5, 0) elif event.key == pygame.K_UP: ship_rect.move_ip(0, -5) elif event.key == pygame.K_DOWN: ship_rect.move_ip(0, 5) # Cover up the screen with the background color. # This is to erase all images on the screen. # Try removing this line to see why we want to do so. screen.fill((0, 0, 0)) screen.blit(ship_image, ship_rect) # Blit the ship image at the position of the ship_rect. screen.blit(moon_image, moon_rect) # Blit the moon image at the position of the moon_rect. pygame.display.update() # Update the display so all changes are visable </code></pre>
1
2016-09-02T15:37:10Z
[ "python", "python-2.7", "pygame" ]
No Results from Multi-property Projection Query in Google Cloud Datastore
39,296,051
<p>I'm trying to query the database with: </p> <pre><code>fields = "property_1, property_2, ... property_n" query = "SELECT {0} FROM Table WHERE property_{n+1} = '{1}'".format(fields, property_{n+1}) all_objs = CacheDatastore.fetch(query, refresh=True) </code></pre> <p>The problem is that the returned list is empty, while if the query is like </p> <p><code>"SELECT * FROM Table WHERE property_{n+1} ='{1}'"</code>, I receive the full set. I've created the necessary indexes and have deployed them, so it is not from there. </p> <p>The log says that a Blob key is not found, but none of the properties is different from <code>string</code>, <code>float</code> or <code>int</code>...</p>
0
2016-09-02T15:32:57Z
39,797,780
<p>It turned to be a bug in the db library which is no longer in development, so I'm leaving here the link to the ticket and the comments on it.<br> GAE allows indexing of static members of the db.Model class hierarchy, but returns 0 results for projection queries where the static member is included among the projected properties. <a href="https://code.google.com/p/google-cloud-platform/issues/detail?id=119" rel="nofollow">https://code.google.com/p/google-cloud-platform/issues/detail?id=119</a></p>
0
2016-09-30T18:23:37Z
[ "python", "google-app-engine", "cloud", "google-cloud-datastore", "projection" ]
Python zipfile removes execute permissions from binaries
39,296,101
<p>Not sure why this is happening, but when I run unzip a file (e.g. apache-groovy-binary-2.4.7.zip) at the command line... </p> <ul> <li>directories are rwx-r-xr-x </li> <li>files are rwxr-xr-x or rw-r--r--</li> </ul> <p>But when I run zipfile.extractall from a Python 2.7 script on the same file... </p> <ul> <li>directories are rwx-r-x--- </li> <li>files are all rw-r---- - even the ones that should be executables as per above.</li> </ul> <p>My umask setting is 0027 - this partly explains what's going on, but why is the executable bit being removed from all files?</p> <p>What's the easiest fix to get Python adopting similar behaviour to the command-line version (apart from shelling out, of course!)?</p>
0
2016-09-02T15:36:24Z
39,296,577
<p>The reason for this can be found in the <code>_extract_member()</code> method in <code>zipfile.py</code>, it only calls <code>shutil.copyfileobj()</code> which will write the output file without any execute bits.</p> <p>The easiest way to solve this is by subclassing <code>ZipFile</code> and changing <code>extract()</code> (or patching in an extended version. By default it is:</p> <pre><code>def extract(self, member, path=None, pwd=None): """Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a ZipInfo object. You can specify a different directory using `path'. """ if not isinstance(member, ZipInfo): member = self.getinfo(member) if path is None: path = os.getcwd() return self._extract_member(member, path, pwd) </code></pre> <p>This last line should be changed to actually set the mode based on the original attributes. You can do it this way:</p> <pre><code>import os from zipfile import ZipFile, ZipInfo class MyZipFile(ZipFile): def extract(self, member, path=None, pwd=None): if not isinstance(member, ZipInfo): member = self.getinfo(member) if path is None: path = os.getcwd() ret_val = self._extract_member(member, path, pwd) attr = member.external_attr &gt;&gt; 16 os.chmod(ret_val, attr) return ret_val with MyZipFile('test.zip') as zfp: zfp.extractall() </code></pre> <p>(The above is based on Python 3.5 and assumes the zipfile is called <code>test.zip</code>)</p>
0
2016-09-02T16:01:51Z
[ "python", "python-2.7" ]
Cross-referencing in lists with slightly different coordinates
39,296,124
<p>I want to do something very similar to the question asked here:</p> <p><a href="http://stackoverflow.com/questions/28393071/comparing-two-lists-of-coordinates-in-python-and-using-coordinate-values-to-assi">Comparing two lists of coordinates in python and using coordinate values to assign values</a></p> <p>That is, I have two lists of coordinates (say, x and y), and I want to extract a quantity from list 2 if the (x,y) coordinates match the (x,y) coordinates in list 1.</p> <p>Now, the answers in the question linked above do nicely for this, as long as the coordinates match <strong>exactly</strong></p> <p>However, I want to account for possibly slight variations. So, suppose there is a small deviation dx or dy in either coordinates. And suppose I say, "for <code>dx&lt;R</code>, I consider these coordinates the same." How would I go about putting that into code - keeping in mind the solution already given in the link above (or another creative solution, of course).</p> <p>Note: for the quick and dirty solution (a double for-loop) this is relatively easy. It is more tricky with the O(n) solution given in the accepted answer, which is what I'm looking for.</p>
1
2016-09-02T15:37:21Z
39,301,684
<p>This is definitely a computational geometry algorithm. You can reformulate it as follows: given a set of points in a plane, find for all points <code>P</code> the set of all points at a distance <code>&lt;= R</code> (with respect to the <a href="https://en.wikipedia.org/wiki/Chebyshev_distance" rel="nofollow">Chebyshev distance</a>, provided that the conditions <code>dx &lt;= R</code> and <code>dy &lt;= R</code> must happen).</p> <p>The solution in quadratic time is easy: you just have to check if a point lie in a given square. Nevertheless, I don't think the method based on hash table (which runs in <em>average</em> linear time) can be adapted easily.</p> <p>A solution in <code>O(n log n)</code> is conceivable, however (though it may be dominated by the number of points in each square: I assume <code>R</code> is very small, so that there is only a constant amount of points in a given square in average).</p> <p>For this you can adapt a <a href="https://en.wikipedia.org/wiki/Sweep_line_algorithm" rel="nofollow">sweep-line algorithm</a>. First you can "discretize" coordinates by considering only <code>x</code> an <code>y</code> corresponding to a given point in the input (this is used to make requests on <em>coordinates</em> rather than on <em>points</em>, while keeping a complexity only based on the number of points in the input).</p> <p>After that, you can sort your points e.g. according to their <code>x</code> coordinate. In fact it would be better to add also the "events" at <code>x+r</code> and <code>x-r</code> (you can put an event on <code>x</code> too, in order to consider each point rather than sweeping in a distinct data structure) for each point, corresponding to the left and to the right corner of the square. Sweep through these events, adding points when a left corner is encountered in a binary search tree ordered by <code>y</code> coordinate (*) and removing them when you read a right corner event. </p> <p>Thus, at a given time, your tree contains exactly the points <code>(x, y)</code> with <code>|x-xcurrent| &lt;= R</code> with respect to the current event. When you get a point, you just have to find all points in the set <code>(x, y)</code> verifying <code>|y-ycurrent| &lt;= R</code> with respect to the current event.</p> <p>(*) In fact, it might be possible to use data structures such as <a href="https://en.wikipedia.org/wiki/Fenwick_tree" rel="nofollow">Fenwick trees</a> which are easier to code "from scratch" and resulting in lower constants than complex data structures such as binary search trees.</p>
0
2016-09-02T23:02:31Z
[ "python", "algorithm", "list" ]
Pyyhon regular expression works on OSx but not on Windows
39,296,214
<pre><code>expression = re.compile(ur'\?(.*)') </code></pre> <p>The expression is simple and this project was originally built on a mac. It runs fine on the mac, however it doesn't run on windows failing with </p> <pre><code>File "path/to/scrapy/spiders/spider.py", line 42 expression = re.compile(ur'\?(.*)') ^ </code></pre>
1
2016-09-02T15:41:40Z
39,296,380
<p>It is not about Mac vs Windows, I suspect, <em>it is about the Python version you are using to run this code on</em>.</p> <p>When I run this code on Python 2.7 - it runs fine, no problems. On Python 3.5 I get a <code>SyntaxError</code> (cause of the <code>u</code> prefix, of course):</p> <pre><code> File "/Users/user/SO/test.py", line 3 expression = re.compile(ur'\?(.*)') ^ SyntaxError: invalid syntax </code></pre> <p>Check that you are actually using Python 2 on both machines.</p>
0
2016-09-02T15:50:08Z
[ "python", "windows", "osx" ]
plotting vertical bars instead of points, plot_date
39,296,229
<p>I want to plot vertical bars instead of points. The actual data I have are irregularly spaced, so this will help visualize gaps more easily. When I try to plot it, the best I can do are points, which don't increase in size as you zoom in!</p> <pre><code>import matplotlib from matplotlib import pyplot as plt import datetime XX = [datetime.date.today()+datetime.timedelta(x) for x in range(10)] YY = range(10) plt.plot_date(XX,YY,'o') </code></pre> <p><a href="http://i.stack.imgur.com/lYheA.png" rel="nofollow"><img src="http://i.stack.imgur.com/lYheA.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/cGna8.png" rel="nofollow"><img src="http://i.stack.imgur.com/cGna8.png" alt="enter image description here"></a></p> <p>Any ideas on how I can make taller/bigger (but not wider!) points?</p>
1
2016-09-02T15:42:32Z
39,296,554
<p>You can use <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.vlines" rel="nofollow"><code>ax.vlines</code></a> to plot a collection of vertical lines. </p> <p>You can adjust <code>ymin</code> and <code>ymax</code> to suit your data.</p> <pre><code>import matplotlib from matplotlib import pyplot as plt import datetime XX = [datetime.date.today()+datetime.timedelta(x) for x in range(10)] plt.vlines(XX, ymin=0, ymax=1, linewidth=5) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/fLkq1.png" rel="nofollow"><img src="http://i.stack.imgur.com/fLkq1.png" alt="enter image description here"></a></p>
1
2016-09-02T16:00:28Z
[ "python", "date", "matplotlib" ]
plotting vertical bars instead of points, plot_date
39,296,229
<p>I want to plot vertical bars instead of points. The actual data I have are irregularly spaced, so this will help visualize gaps more easily. When I try to plot it, the best I can do are points, which don't increase in size as you zoom in!</p> <pre><code>import matplotlib from matplotlib import pyplot as plt import datetime XX = [datetime.date.today()+datetime.timedelta(x) for x in range(10)] YY = range(10) plt.plot_date(XX,YY,'o') </code></pre> <p><a href="http://i.stack.imgur.com/lYheA.png" rel="nofollow"><img src="http://i.stack.imgur.com/lYheA.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/cGna8.png" rel="nofollow"><img src="http://i.stack.imgur.com/cGna8.png" alt="enter image description here"></a></p> <p>Any ideas on how I can make taller/bigger (but not wider!) points?</p>
1
2016-09-02T15:42:32Z
39,296,638
<p>Did you mean bars like this? </p> <p><a href="http://i.stack.imgur.com/Cb83O.png" rel="nofollow"><img src="http://i.stack.imgur.com/Cb83O.png" alt="enter image description here"></a></p> <p>And here is the code:</p> <pre><code>import matplotlib from matplotlib import pyplot as plt import datetime XX = [datetime.date.today()+datetime.timedelta(x) for x in range(10)] YY = range(10) plt.plot_date(XX,YY,'|') plt.show() </code></pre> <p>You can change the shape of your plot by changing the third argument you pass in the plt.plot_date function. In your code you are passing an 'o' that is why you get a dot. Here i pass bar to plot bar.</p>
0
2016-09-02T16:05:14Z
[ "python", "date", "matplotlib" ]
alternative to strptime for comparing dates?
39,296,230
<p>Is there any way to compare two dates without calling strptime each time in python? I'm sure given my problem there's no other way, but want to make sure I've checked all options. </p> <p>I'm going through a very large log file, each line has a date which I need to compare to see if that date is within the range of two other dates. I'm having to convert each date for each line with strptime which is causing a large bottleneck;</p> <pre><code>Fri Sep 2 15:12:43 2016 output2.file 63518075 function calls (63517618 primitive calls) in 171.409 seconds Ordered by: cumulative time List reduced from 571 to 10 due to restriction &lt;10&gt; ncalls tottime percall cumtime percall filename:lineno(function) 1 0.003 0.003 171.410 171.410 script.py:3(&lt;module&gt;) 1 0.429 0.429 171.367 171.367 scipt.py:1074(main) 1 3.357 3.357 162.009 162.009 script.py:695(get_data) 1569898 14.088 0.000 141.175 0.000 script.py:648(check_line) 1569902 6.899 0.000 71.706 0.000 {built-in method strptime} 1569902 31.198 0.000 64.805 0.000 /usr/lib64/python2.7/_strptime.py:295(_strptime) 1569876 15.324 0.000 43.170 0.000 script.py:626(dict_add) 4709757 23.370 0.000 23.370 0.000 {method 'strftime' of 'datetime.date' objects} 1569904 1.655 0.000 18.799 0.000 /usr/lib64/python2.7/_strptime.py:27(_getlang) 1569899 2.103 0.000 17.452 0.000 script.py:592(reverse) </code></pre> <p>The dates are formatted like this;</p> <pre><code>current_date = 01/Aug/1995:23:59:53 </code></pre> <p>And I'm comparing them like this;</p> <pre><code>with open(logfile) as file: for line in file: current_date = strptime_method(line) if current_date =&gt; end_date: break </code></pre> <p>Is there any alternative when it comes to comparing dates? </p> <p>Edit: Thanks everyone, in particular user2539738. Here's the results based on his/her suggestion, <strong>big speed difference</strong>;</p> <pre><code>Fri Sep 2 16:14:59 2016 output3.file 24270567 function calls (24270110 primitive calls) in 105.466 seconds Ordered by: cumulative time List reduced from 571 to 10 due to restriction &lt;10&gt; ncalls tottime percall cumtime percall filename:lineno(function) 1 0.002 0.002 105.466 105.466 script.py:3(&lt;module&gt;) 1 0.487 0.487 105.433 105.433 script.py:1082(main) 1 3.159 3.159 95.861 95.861 script.py:702(get_data) 1569898 21.663 0.000 77.138 0.000 script.py:648(check_line) 1569876 14.979 0.000 43.408 0.000 script.py:626(dict_add) 4709757 23.865 0.000 23.865 0.000 {method 'strftime' of 'datetime.date' objects} 1569899 1.943 0.000 15.556 0.000 script.py:592(reverse) 1 0.000 0.000 9.078 9.078 script.py:1066(print_data) 1 0.021 0.021 9.044 9.044 script.py:1005(print_ip) 10 0.001 0.000 7.067 0.707 script.py:778(ip_api) </code></pre>
5
2016-09-02T15:42:37Z
39,296,349
<p>I'm assuming current_date is a string</p> <p>First, make a dictionary</p> <pre><code>moDict = {"Aug":8, "Jan":1} #etc </code></pre> <p>Then, find year/month/day etc</p> <pre><code>current_date = "01/Aug/1995:23:59:53" Yr = int(current_date[7:11]) Mo = moDict[(current_date[3:6])] Day = int(current_date[0:2]) m_date = datetime.datetime(Yr,Mo,Day) </code></pre> <p>And you can use that to make comparisons</p>
1
2016-09-02T15:48:50Z
[ "python", "regex", "loops", "strptime" ]
alternative to strptime for comparing dates?
39,296,230
<p>Is there any way to compare two dates without calling strptime each time in python? I'm sure given my problem there's no other way, but want to make sure I've checked all options. </p> <p>I'm going through a very large log file, each line has a date which I need to compare to see if that date is within the range of two other dates. I'm having to convert each date for each line with strptime which is causing a large bottleneck;</p> <pre><code>Fri Sep 2 15:12:43 2016 output2.file 63518075 function calls (63517618 primitive calls) in 171.409 seconds Ordered by: cumulative time List reduced from 571 to 10 due to restriction &lt;10&gt; ncalls tottime percall cumtime percall filename:lineno(function) 1 0.003 0.003 171.410 171.410 script.py:3(&lt;module&gt;) 1 0.429 0.429 171.367 171.367 scipt.py:1074(main) 1 3.357 3.357 162.009 162.009 script.py:695(get_data) 1569898 14.088 0.000 141.175 0.000 script.py:648(check_line) 1569902 6.899 0.000 71.706 0.000 {built-in method strptime} 1569902 31.198 0.000 64.805 0.000 /usr/lib64/python2.7/_strptime.py:295(_strptime) 1569876 15.324 0.000 43.170 0.000 script.py:626(dict_add) 4709757 23.370 0.000 23.370 0.000 {method 'strftime' of 'datetime.date' objects} 1569904 1.655 0.000 18.799 0.000 /usr/lib64/python2.7/_strptime.py:27(_getlang) 1569899 2.103 0.000 17.452 0.000 script.py:592(reverse) </code></pre> <p>The dates are formatted like this;</p> <pre><code>current_date = 01/Aug/1995:23:59:53 </code></pre> <p>And I'm comparing them like this;</p> <pre><code>with open(logfile) as file: for line in file: current_date = strptime_method(line) if current_date =&gt; end_date: break </code></pre> <p>Is there any alternative when it comes to comparing dates? </p> <p>Edit: Thanks everyone, in particular user2539738. Here's the results based on his/her suggestion, <strong>big speed difference</strong>;</p> <pre><code>Fri Sep 2 16:14:59 2016 output3.file 24270567 function calls (24270110 primitive calls) in 105.466 seconds Ordered by: cumulative time List reduced from 571 to 10 due to restriction &lt;10&gt; ncalls tottime percall cumtime percall filename:lineno(function) 1 0.002 0.002 105.466 105.466 script.py:3(&lt;module&gt;) 1 0.487 0.487 105.433 105.433 script.py:1082(main) 1 3.159 3.159 95.861 95.861 script.py:702(get_data) 1569898 21.663 0.000 77.138 0.000 script.py:648(check_line) 1569876 14.979 0.000 43.408 0.000 script.py:626(dict_add) 4709757 23.865 0.000 23.865 0.000 {method 'strftime' of 'datetime.date' objects} 1569899 1.943 0.000 15.556 0.000 script.py:592(reverse) 1 0.000 0.000 9.078 9.078 script.py:1066(print_data) 1 0.021 0.021 9.044 9.044 script.py:1005(print_ip) 10 0.001 0.000 7.067 0.707 script.py:778(ip_api) </code></pre>
5
2016-09-02T15:42:37Z
39,297,009
<p>Since your dates appear to be in a fixed length format, it's trivially easy to parse and you don't need <code>strptime</code> to do it. You can rearrange them into the <a href="https://en.wikipedia.org/wiki/ISO_8601" rel="nofollow">ISO 8601 date/time format</a> and compare them directly as strings!</p> <pre><code>mos = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'} def custom_to_8601(dt): return dt[7:11] + '-' + mos[dt[3:6]] + '-' + dt[0:2] + 'T' + dt[12:] &gt;&gt;&gt; custom_to_8601('01/Aug/1995:23:59:53') '1995-08-01T23:59:53' </code></pre> <p>It might be a touch faster to use <code>join</code> instead of string concatenation and leave out the punctuation:</p> <pre><code>def comparable_date(dt): return ''.join([dt[7:11], mos[dt[3:6]], dt[0:2], dt[12:]]) &gt;&gt;&gt; comparable_date('01/Aug/1995:23:59:53') '1995080123:59:53' </code></pre> <p>Running <code>cProfile</code> on 1000000 repetitions for me produces these timings:</p> <ul> <li><code>custom_to_8601</code>: 0.978 seconds</li> <li><code>comparable_date</code>: 0.937 seconds</li> <li>your original code with <code>strptime</code>: 15.492 seconds</li> <li>an earlier answer using the <code>datetime</code> constructor: 1.134 seconds</li> </ul>
1
2016-09-02T16:28:08Z
[ "python", "regex", "loops", "strptime" ]
FirefoxDriver - Connection is not secure
39,296,285
<p>When I attempt to run my automation tests against Firefox 47.0.1 I get a warning mentioning that the connection is insecure. I have written the below code to resolve the issue, which unfortunately it's not working. If anyone has a solution that would be great. </p> <pre><code>if browser == 'firefox': profile = webdriver.FirefoxProfile() profile.set_preference("webdriver_accept_untrusted_certs", True) self.driver = webdriver.Firefox(firefox_profile=profile) </code></pre>
0
2016-09-02T15:45:20Z
39,296,424
<p>This occures because of <code>profile.set_preference("webdriver_accept_untrusted_certs", True)</code></p> <p>Remove this and try instead: <code>profile.set_preference("webdriver_assume_untrusted_issuer", False)</code> <code>profile.update_preferences()</code></p>
0
2016-09-02T15:52:50Z
[ "python", "selenium-webdriver", "selenium-firefoxdriver" ]
Microbit python variables issue
39,296,356
<p>I'm trying to make a higher or lower game for my sisters microbit and am having problems with my variables <code>random_int</code> &amp; <code>r_number</code>:</p> <pre><code>from microbit import * import random random_int = random.randint(0, 9) r_number = 7 while True: display.scroll(r_number) if button_a.is_pressed(): display.scroll("HIGHER") r_number = random_int display.scroll(random_int) if r_number =&lt; random_int): display.scroll('correct') elif r_number &gt;= random_int): display.scroll('incorrect') r_number = random_int elif button_b.is_pressed(): display.scroll("LOWER") r_number = random_int display.scroll(random_int) if r_number =&gt; random_int): display.scroll('correct') elif r_number &lt;= random_int): display.scroll('incorrect') r_number = random_int </code></pre>
0
2016-09-02T15:49:07Z
39,499,339
<p>Not sure what this is supposed to do. Not withstanding you only initialise your main variables once, and that outside of your main loop, I see syntax errors like that in #12 i.e. "if r_number =&lt; random_int):" That widowed closing bracket looks a mite strange to me. The micro:bit's is not very forgiving, and it's compilers not very forthcoming.</p>
0
2016-09-14T20:42:07Z
[ "python", "bbc-microbit" ]
Weird dictionary construct - duplicate keys
39,296,387
<p>I needed to write a function that 'maps' -1 to just '-', 1 to '' (yes, nothing) and every other value to a string representation of itself. Instead of using <code>if</code> statements i though i would do it with a dictionary like so:</p> <pre><code>def adj(my_value): return {-1: '-', 1: '', my_value: str(my_value)}[my_value] </code></pre> <p>And then it hit me, this dictionary allows duplicate keys and behaves as follows:</p> <pre><code>for x in [-1, 1, 4]: print(adj(x)) # -&gt; -1 # -&gt; 1 # -&gt; 4 </code></pre> <p>I did run it multiple times to make sure the <code>print()</code> was not "random" since dicts are not ordered but i consistently get this output.</p> <hr> <p>Now this is definitely not the behavior i was going for and in no way can such a construct be trusted but does anyone know why such a thing is even allowed since duplicate keys aren't? How is the calculation performed?</p>
1
2016-09-02T15:50:21Z
39,296,438
<p>The dictionary you made doesn't have duplicate keys. The "duplicates" overwrote each other. It's just as if you had done this:</p> <pre><code>d = {} d[1] = '' d[1] = 1 print(d[1]) </code></pre> <p>To demonstrate:</p> <pre><code>&gt;&gt;&gt; def adj(my_value): ... d = {-1: '-', 1: '', my_value: str(my_value)} ... print(d) ... return d[my_value] ... &gt;&gt;&gt; for x in [-1, 1, 4]: ... print(adj(x)) ... {1: '', -1: '-1'} -1 {1: '1', -1: '-'} 1 {1: '', 4: '4', -1: '-'} 4 </code></pre> <p>BTW, you could write the function like this:</p> <pre><code>def adj(my_value) d = {-1: '-', 1: ''} return d.get(my_value, str(my_value)) </code></pre>
6
2016-09-02T15:53:43Z
[ "python", "python-3.x", "dictionary" ]
Weird dictionary construct - duplicate keys
39,296,387
<p>I needed to write a function that 'maps' -1 to just '-', 1 to '' (yes, nothing) and every other value to a string representation of itself. Instead of using <code>if</code> statements i though i would do it with a dictionary like so:</p> <pre><code>def adj(my_value): return {-1: '-', 1: '', my_value: str(my_value)}[my_value] </code></pre> <p>And then it hit me, this dictionary allows duplicate keys and behaves as follows:</p> <pre><code>for x in [-1, 1, 4]: print(adj(x)) # -&gt; -1 # -&gt; 1 # -&gt; 4 </code></pre> <p>I did run it multiple times to make sure the <code>print()</code> was not "random" since dicts are not ordered but i consistently get this output.</p> <hr> <p>Now this is definitely not the behavior i was going for and in no way can such a construct be trusted but does anyone know why such a thing is even allowed since duplicate keys aren't? How is the calculation performed?</p>
1
2016-09-02T15:50:21Z
39,296,491
<p>Quoting the <a href="https://docs.python.org/3/reference/expressions.html#dictionary-displays" rel="nofollow">Python docs</a>:</p> <blockquote> <p>If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum. <strong>This means that you can specify the same key multiple times in the key/datum list, and the final dictionary’s value for that key will be the last one given.</strong></p> </blockquote> <p>It's not undefined behavior, it's as if you created an empty dictionary and set each key, one by one. You can fix your code by just shuffling the order around:</p> <pre><code>def adj(my_value): return {my_value: str(my_value), -1: '-', 1: ''}[my_value] </code></pre> <p>Other people might find this approach hard to read, though, so you may want to use <code>dict.get</code>'s default value, as the other answers have shown.</p> <p>Your question was recently asked on the <a href="https://mail.python.org/pipermail/python-ideas/2016-May/040042.html" rel="nofollow">Python mailing list</a> (in an easier to read format <a href="https://code.activestate.com/lists/python-ideas/39826/" rel="nofollow">here</a>).</p>
4
2016-09-02T15:56:31Z
[ "python", "python-3.x", "dictionary" ]
Weird dictionary construct - duplicate keys
39,296,387
<p>I needed to write a function that 'maps' -1 to just '-', 1 to '' (yes, nothing) and every other value to a string representation of itself. Instead of using <code>if</code> statements i though i would do it with a dictionary like so:</p> <pre><code>def adj(my_value): return {-1: '-', 1: '', my_value: str(my_value)}[my_value] </code></pre> <p>And then it hit me, this dictionary allows duplicate keys and behaves as follows:</p> <pre><code>for x in [-1, 1, 4]: print(adj(x)) # -&gt; -1 # -&gt; 1 # -&gt; 4 </code></pre> <p>I did run it multiple times to make sure the <code>print()</code> was not "random" since dicts are not ordered but i consistently get this output.</p> <hr> <p>Now this is definitely not the behavior i was going for and in no way can such a construct be trusted but does anyone know why such a thing is even allowed since duplicate keys aren't? How is the calculation performed?</p>
1
2016-09-02T15:50:21Z
39,296,499
<p>By doing <code>{-1: '-', 1: '', my_value: str(my_value)}</code>, you overwrite the <code>-1</code> or <code>1</code> entries if <code>my_value</code> is <code>-1</code> or <code>1</code> respectively. Instead, you can use <a href="https://docs.python.org/3/library/stdtypes.html#dict.get" rel="nofollow"><code>dict.get</code> with a default value</a>:</p> <pre><code>def adj(my_value): return {-1: '-', 1: ''}.get(my_value, str(my_value)) </code></pre>
1
2016-09-02T15:57:03Z
[ "python", "python-3.x", "dictionary" ]
tastypie overid create_response() method
39,296,421
<p>I tring to override tastypie <code>create_response</code> because I have some verification to do before sending response to user. this is my code:</p> <pre><code>class MyNamespacedModelResource(NamespacedModelResource): def create_response(self , request , data): r = super(MyNamespacedModelResource , self).create_response(request , data , response_class=HttpResponse) # ... some treatements... return r </code></pre> <p>And I have user NamespaceModelResource who work fine before.</p> <p>When I tring to add new user ( with post method) , I have got this </p> <pre><code>error: create_response() got an unexpected keyword argument 'response_class' </code></pre>
0
2016-09-02T15:52:34Z
39,299,666
<p>You have defined the method <code>create response()</code> with two positional arguments. However, the super class definition looks like this: </p> <pre><code>def create_response(self, request, data, response_class=HttpResponse, **response_kwargs) </code></pre> <p>Why this is a problem is that your overridden method is called with keyword arguments that you haven't "accepted" in your definition. That's what the <code>**response_kwargs</code> stands there for. It means this function can have an infinite number of keyword args. Your definition can have 0. So if you change your definition to either <code>create_response(self, request, data, **kwargs)</code> or <code>create_response(self, request, data, response_class=HttpResponse, **response_kwargs)</code>, you'll be rid of this problem. But you'll have another one on your hands. In 99% of the cases, keyword arguments must be passed on to the super class method. So the ideal version in most cases is to just duplicate both the definition and <code>super()</code> method call, which in your case looks like this: </p> <pre><code>class MyNamespacedModelResource(NamespacedModelResource): def create_response(self, request, data, response_class=HttpResponse, **response_kwargs): r = super(MyNamespacedModelResource , self).create_response(request, data, response_class=response_class, **response_kwargs) return r </code></pre>
0
2016-09-02T19:41:26Z
[ "python", "django", "tastypie" ]
extract number from a text file into variable using list
39,296,518
<p>I've a .text file with text</p> <blockquote> <p>.numvar 5</p> </blockquote> <p>I want to extract this 5 into a separate variable and use. I've used list to extract value but, I cannot manipulate the variable.</p> <pre><code> if ".numvars" in line: splitter=re.compile(r'\d+') numvars=splitter.findall(line) numvars=map(int, numvars) </code></pre> <p>how to store the 5 in separate variable.</p>
0
2016-09-02T15:57:59Z
39,296,652
<p>How about:</p> <pre><code>import re with open("test.txt") as f: for line in f: if ".numvar" in line: splitter = re.compile(r'\d+') numvars = splitter.findall(line) my_numbers = [int(n) for n in numvars] my_number = my_numbers[0] print(my_number) </code></pre>
0
2016-09-02T16:05:42Z
[ "python", "list" ]
How do I just display the numbers from the list without the comma and brackets on Python?
39,296,539
<pre><code>#This will ask the user to enter a 7 digit number #then it would calculate the modulus 11 check digit #then would show the user the complete 8 digit number weight=[8,7,6,5,4,3,2] number= input("Please enter your 7 digit number: ") #If the user enters more than 7 characters it will prompt the user to try again while len(number) &gt; 7: number=input ("Error! Only 7 numbers allowed! Try again: ") #This puts the 7 digit number into a list account_number=number #This converts the string in the list into a integer account_number = [int(i) for i in account_number] #This separates the numbers into multple values every character list(account_number) #This multiplies the account number by the weight num1=weight[0]*account_number[0] num2=weight[1]*account_number[1] num3=weight[2]*account_number[2] num4=weight[3]*account_number[3] num5=weight[4]*account_number[4] num6=weight[5]*account_number[5] num7=weight[6]*account_number[6] #This adds up the all the answers above num8=num7+num6+num5+num4+num3+num2+num1 #The use of % divides the number and gives the remainder remainder=num8%11 #This generates the final check digit check_number=11-remainder #This adds the check number to the 7 digit number (account number) account_number.insert(7,"{0}".format(check_number)) #This gives the user the total 8 digit number print ("Your account number is {0}".format(account_number)) </code></pre> <p>At the end, the account number is displayed like <code>[1,2,3,4,5,6,7]</code>. How can I display it like <code>1234567</code>, without commas and square brackets?</p>
-2
2016-09-02T15:59:32Z
39,296,603
<pre><code>&gt;&gt;&gt; "".join(map(str,account_number)) </code></pre> <p>This first converts ints to str, then joins them together with no spaces</p> <p>example:</p> <pre><code>&gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; map(str,a) ['1', '2', '3'] &gt;&gt;&gt; "".join(map(str,a)) '123' &gt;&gt;&gt; </code></pre> <p>In your case, change to this: </p> <pre><code>account_number = "".join(map(str, account_number)) print ("Your account number is {0}".format(account_number)) </code></pre> <p>follow up to comment:</p> <pre><code>while len(number) != 7: number=input ("Error! Only 7 numbers allowed! Try again: ") </code></pre>
5
2016-09-02T16:03:10Z
[ "python", "algorithm" ]
selecting random json element
39,296,542
<p><strong>python 3.5</strong></p> <p>hi i have following json file and i want to select json data random...</p> <p><strong>json</strong></p> <pre><code>{"x":[ {"A":"B"}, {"A":"C"}, {"F":"H"} ]} </code></pre> <p>select data where item in data['x'] is A </p> <p>(result would be C or B)</p> <p><strong>code</strong></p> <pre><code>data = json.load(open('j.json')) x = "" for item in data["x"]: T = True if "A" in item else False if T is True: x = item["A"] #break else: pass if x == "": print("nothing found") else : print(x) </code></pre> <p>when i break it , it just prints B every time i run script i want it to select B or C random any ideas?!</p>
0
2016-09-02T15:59:39Z
39,298,227
<p>Perhaps this program will answer your (not-yet-asked) question:</p> <pre><code>import json import random data = json.load(open('j.json')) values = [v for d in data['x'] for k,v in d.items() if k == 'A'] try: x = random.choice(values) print(x) except IndexError: print("nothing found") </code></pre>
0
2016-09-02T17:53:19Z
[ "python", "json" ]
How do I set initial form values of CreateView view using POST only (and not GET)?
39,296,546
<p>Users click a button that takes them to a new form via a POST request, which contains a pk. This is used to pre-populate the new form with some extra data. No data has been saved to database at this point. I don't want to pass this pk along the URL so can't call view using GET.</p> <p>I've tried overriding the <code>get_initial()</code> method in CreateView but this only seems to be called after a GET request.</p> <p>I've also tried <code>def post()</code> which gives me easy access to the fields but means I have to write more code to handle form validation etc (which is handled automagically by the vanilla CreateView).</p> <p>So, what's the best way to handle rendering and saving of a form when both requests are made via POST?</p>
0
2016-09-02T15:59:56Z
39,299,515
<p>What I'd do:</p> <pre><code>def post(self, request, **kwargs): # Replace 'list_of_pets' with stuff that you'll definitely have in the first request if 'list_of_pets' in request.POST: # Provide initial data for form in get() return self.get(request, **kwargs) else: # Provides automatic form validation return super().post(request, **kwargs) </code></pre> <p>In the <code>get()</code> method you can set the initial data and whatnot. You could also use a completely separate method, but overriding <code>get()</code> gives you the benefit that if someone wanders to the URL without a POST request, they don't get a nasty 405 right away (of course there are other ways to get avoid that it, just sayin').</p>
0
2016-09-02T19:28:49Z
[ "python", "django", "django-views" ]
Python it is possible to spawn background process which runs even if main process exits?
39,296,559
<p>What I'm trying to achieve: I want that my main process spawn another independent python process. Like:</p> <pre><code>for i in range(2): p = proces() p.start() sys.exit(0) </code></pre> <p>And my spawned processes should run in the background doing some task :) Because at the moment, if I spawn a process using <code>multiprocessing</code> library and then close my main scripts these processes also exits.</p>
0
2016-09-02T16:00:40Z
39,296,658
<pre><code>import time import multiprocessing import sys def run_forever(): print "ENTERED SUBPROCESS" while True: print "HELLO from subprocess" time.sleep(2) print "GOODBYE SUBPROCESS" if __name__ == "__main__": print "STARTING IN MAIN" multiprocessing.Process(target=run_forever).start() time.sleep(1) print "LEAVING MAIN PROG" sys.exit() </code></pre> <p>results in the following output</p> <pre><code>STARTING IN MAIN ENTERED SUBPROCESS HELLO LEAVING MAIN PROG HELLO HELLO HELLO HELLO HELLO ... </code></pre> <p>of coarse you may have a new problem now (ie you dont actually want run_forever to run forever ... there is no way to exit this process now ...)</p>
0
2016-09-02T16:05:59Z
[ "python", "multithreading", "multiprocessing" ]
Receiving a ValueError: Unknown level when running GoogleScraper
39,296,645
<p>I recently decided to get to grips with some python and try to learn my way around the language but i've inevitably ran into a couple of problems that I was hoping someone could help me with.</p> <p>Basically, I'm running on an OSx machine, I uninstalled the python that came with the operating system and used HomeBrew to download python 3.5.2, all that went successfully. Next I installed GoogleScraper (<a href="https://github.com/NikolaiT/GoogleScraper" rel="nofollow">https://github.com/NikolaiT/GoogleScraper</a>) which went well after a couple tries, but now, when I try to run a test query through terminal:</p> <pre><code>GoogleScraper -m http --keyword "apple" -v2 </code></pre> <p>After the machines whizzes and buzzes for a few seconds, it pops out with an error:</p> <pre><code> GoogleScraper -m http --keyword "apple" -v2 Traceback (most recent call last): File "/usr/local/bin/GoogleScraper", line 11, in &lt;module&gt; sys.exit(main()) File "/usr/local/lib/python3.5/site-packages/GoogleScraper/core.py", line 173, in main setup_logger(level=config.get('log_level').upper()) File "/usr/local/lib/python3.5/site-packages/GoogleScraper/log.py", line 23, in setup_logger logger.setLevel(level) File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/__init__.py", line 1255, in setLevel self.level = _checkLevel(level) File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/__init__.py", line 187, in _checkLevel raise ValueError("Unknown level: %r" % level) ValueError: Unknown level: '2' </code></pre> <p>I've been trying to learn python online and am making some progress, but for the life of me can't figure out what any of that error means, hopefully one of you could at least point me in the direction of a solution.</p> <p>Many thanks!</p>
2
2016-09-02T16:05:33Z
39,297,246
<p>As per <a href="https://github.com/NikolaiT/GoogleScraper/blob/master/GoogleScraper/log.py" rel="nofollow">the source</a>, the logging level is a string that corresponds to a <a href="https://en.wikipedia.org/wiki/Syslog#Severity_level" rel="nofollow">syslog severity level</a>, not a number indicating level of verboseness. This appears to work:</p> <pre><code>GoogleScraper -m http --keyword "apple" -v INFO </code></pre>
1
2016-09-02T16:44:36Z
[ "python", "osx", "python-3.x" ]
if statement seemingly being ignored in for loop
39,296,720
<p>noobie having trouble with if statements within a for loop </p> <p>def abilityBuy():</p> <pre><code>totalPoints = 28 abilities = { "Str":0, "Con":0, "Dex":0, "Int":0, "Wis":0, "Cha":0 } for i,v in abilities.items(): print "You have %s points." % totalPoints text = "Enter stat for %s: " % i stat = raw_input(text) if stat == 18: totalPoints = totalPoints - 16 elif stat == 17: totalPoints = totalPoints - 13 elif stat == 16: totalPoints = totalPoints - 10 elif stat == 15: totalPoints = totalPoints - 8 elif stat == 14: totalPoints = totalPoints - 6 elif stat == 13: totalPoints = totalPoints - 5 elif stat == 12: totalPoints = totalPoints - 4 elif stat == 11: totalPoints = totalPoints - 3 elif stat == 10: totalPoints = totalPoints - 2 elif stat == 9: totalPoints = totalPoints - 1 elif stat == 8: totalPoints = totalPoints - 0 abilities[i] = stat print abilities </code></pre> <p>abilityBuy()</p> <p>when ran it suppose to deduce the number of points required for a stat number example: if stat is equal to 18 reduce totalPoints by 16 this will give the totalpoints the remainder of 12 points but when ran the if statement is seemingly ignored and jumps passed them, adds to the dictionary and loops around and says totalPoints still equal to 28</p> <p>i don't know if it is indentation that is causing the issue or something else, also i have other for loops with if statements inside and they work how they are suppose to, yet this one doesn't seem to do what i am asking to</p> <p>open to any suggestions</p> <p>thanks</p> <p>Lyncius </p>
0
2016-09-02T16:09:49Z
39,296,824
<p>First thing that comes to mind: <code>raw_input()</code> returns a string, but your if statements compare stat to integers so none of them will evaluate to true. A simple solution is to convert it: <code>int(stat)</code>, but you will want to add a check for when users input non-numbers or values beyond what you test (ie, if a user inputs 19 or 'a').</p>
0
2016-09-02T16:16:35Z
[ "python" ]
if statement seemingly being ignored in for loop
39,296,720
<p>noobie having trouble with if statements within a for loop </p> <p>def abilityBuy():</p> <pre><code>totalPoints = 28 abilities = { "Str":0, "Con":0, "Dex":0, "Int":0, "Wis":0, "Cha":0 } for i,v in abilities.items(): print "You have %s points." % totalPoints text = "Enter stat for %s: " % i stat = raw_input(text) if stat == 18: totalPoints = totalPoints - 16 elif stat == 17: totalPoints = totalPoints - 13 elif stat == 16: totalPoints = totalPoints - 10 elif stat == 15: totalPoints = totalPoints - 8 elif stat == 14: totalPoints = totalPoints - 6 elif stat == 13: totalPoints = totalPoints - 5 elif stat == 12: totalPoints = totalPoints - 4 elif stat == 11: totalPoints = totalPoints - 3 elif stat == 10: totalPoints = totalPoints - 2 elif stat == 9: totalPoints = totalPoints - 1 elif stat == 8: totalPoints = totalPoints - 0 abilities[i] = stat print abilities </code></pre> <p>abilityBuy()</p> <p>when ran it suppose to deduce the number of points required for a stat number example: if stat is equal to 18 reduce totalPoints by 16 this will give the totalpoints the remainder of 12 points but when ran the if statement is seemingly ignored and jumps passed them, adds to the dictionary and loops around and says totalPoints still equal to 28</p> <p>i don't know if it is indentation that is causing the issue or something else, also i have other for loops with if statements inside and they work how they are suppose to, yet this one doesn't seem to do what i am asking to</p> <p>open to any suggestions</p> <p>thanks</p> <p>Lyncius </p>
0
2016-09-02T16:09:49Z
39,296,828
<p>It's because your <code>stat = raw_input</code> is returning a str value. stat is a str, and in your if statements your trying to compare it to an integer. <code>str == int</code> never works out. Either cast stat to an int, or compare it to str like...</p> <pre><code>stat = int(stat) </code></pre> <p>or </p> <pre><code>if stat == "18": </code></pre> <p>both will work out </p>
1
2016-09-02T16:16:42Z
[ "python" ]
if statement seemingly being ignored in for loop
39,296,720
<p>noobie having trouble with if statements within a for loop </p> <p>def abilityBuy():</p> <pre><code>totalPoints = 28 abilities = { "Str":0, "Con":0, "Dex":0, "Int":0, "Wis":0, "Cha":0 } for i,v in abilities.items(): print "You have %s points." % totalPoints text = "Enter stat for %s: " % i stat = raw_input(text) if stat == 18: totalPoints = totalPoints - 16 elif stat == 17: totalPoints = totalPoints - 13 elif stat == 16: totalPoints = totalPoints - 10 elif stat == 15: totalPoints = totalPoints - 8 elif stat == 14: totalPoints = totalPoints - 6 elif stat == 13: totalPoints = totalPoints - 5 elif stat == 12: totalPoints = totalPoints - 4 elif stat == 11: totalPoints = totalPoints - 3 elif stat == 10: totalPoints = totalPoints - 2 elif stat == 9: totalPoints = totalPoints - 1 elif stat == 8: totalPoints = totalPoints - 0 abilities[i] = stat print abilities </code></pre> <p>abilityBuy()</p> <p>when ran it suppose to deduce the number of points required for a stat number example: if stat is equal to 18 reduce totalPoints by 16 this will give the totalpoints the remainder of 12 points but when ran the if statement is seemingly ignored and jumps passed them, adds to the dictionary and loops around and says totalPoints still equal to 28</p> <p>i don't know if it is indentation that is causing the issue or something else, also i have other for loops with if statements inside and they work how they are suppose to, yet this one doesn't seem to do what i am asking to</p> <p>open to any suggestions</p> <p>thanks</p> <p>Lyncius </p>
0
2016-09-02T16:09:49Z
39,296,832
<p>The problem is with <a href="https://docs.python.org/2/library/functions.html#raw_input" rel="nofollow"><code>raw_input</code></a>. It returns a string, and you're just comparing it to ints.</p> <pre><code>stat = int(raw_input(text)) </code></pre> <p>would solve that part.</p>
1
2016-09-02T16:16:56Z
[ "python" ]
if statement seemingly being ignored in for loop
39,296,720
<p>noobie having trouble with if statements within a for loop </p> <p>def abilityBuy():</p> <pre><code>totalPoints = 28 abilities = { "Str":0, "Con":0, "Dex":0, "Int":0, "Wis":0, "Cha":0 } for i,v in abilities.items(): print "You have %s points." % totalPoints text = "Enter stat for %s: " % i stat = raw_input(text) if stat == 18: totalPoints = totalPoints - 16 elif stat == 17: totalPoints = totalPoints - 13 elif stat == 16: totalPoints = totalPoints - 10 elif stat == 15: totalPoints = totalPoints - 8 elif stat == 14: totalPoints = totalPoints - 6 elif stat == 13: totalPoints = totalPoints - 5 elif stat == 12: totalPoints = totalPoints - 4 elif stat == 11: totalPoints = totalPoints - 3 elif stat == 10: totalPoints = totalPoints - 2 elif stat == 9: totalPoints = totalPoints - 1 elif stat == 8: totalPoints = totalPoints - 0 abilities[i] = stat print abilities </code></pre> <p>abilityBuy()</p> <p>when ran it suppose to deduce the number of points required for a stat number example: if stat is equal to 18 reduce totalPoints by 16 this will give the totalpoints the remainder of 12 points but when ran the if statement is seemingly ignored and jumps passed them, adds to the dictionary and loops around and says totalPoints still equal to 28</p> <p>i don't know if it is indentation that is causing the issue or something else, also i have other for loops with if statements inside and they work how they are suppose to, yet this one doesn't seem to do what i am asking to</p> <p>open to any suggestions</p> <p>thanks</p> <p>Lyncius </p>
0
2016-09-02T16:09:49Z
39,296,852
<p>changed:</p> <p>from stat = raw_input(text)</p> <p>to stat = int(raw_inpur(text))</p> <p>problem solved</p>
0
2016-09-02T16:18:09Z
[ "python" ]
Replace in string with alternation
39,296,886
<p>I want to replace <code>##</code> with <code>&lt;&lt;</code> and <code>&gt;&gt;</code> with alternation. For example <code>abc##123##qwe##asd##</code> to <code>abc&lt;&lt;123&gt;&gt;qwe&lt;&lt;asd&gt;&gt;</code>. Of course I can read symbols one by one, check them, do the replace to <code>&lt;&lt;</code> if it's even time or to <code>&gt;&gt;</code> if it's odd time. But there is power collection of standard functions in Python so I wonder if I can use them to reduce my code.</p>
0
2016-09-02T16:20:18Z
39,297,787
<p>you can use following statement to change only pair of <code>##</code> and leave non-matching <code>##</code> as it is</p> <pre><code>d = "abc##123##qwe##asd" re.sub(r'(##)(.*?)(?(1)##)', r'&lt;&lt;\2&gt;&gt;', d) # 'abc&lt;&lt;123&gt;&gt;qwe##asd' </code></pre> <p>or you can do this</p> <pre><code>re.sub(r'(##)(.*?)(?(1)##)', r'&lt;&lt;\2&gt;&gt;', d).replace("##","&lt;&lt;") # 'abc&lt;&lt;123&gt;&gt;qwe&lt;&lt;asd' </code></pre>
0
2016-09-02T17:22:57Z
[ "python", "string", "replace" ]
How to fight with "maximum recursion depth exceeded" using matplotlib.pyplot
39,296,892
<p>The following code adds point on canvas by left click, draws a polyline with the drawn points by right click and also draws a sliding point on the lines while a cursor is moving. The only problem is that the execution stops pretty soon after "sliding" because of the title reason. How can I overcome this problem and slide as much as wanted?</p> <pre><code>import matplotlib.pyplot as plt class DumbyRemove: def __init__(self): pass def remove(self): pass the_points = list() drawn_points = list() moving_point = DumbyRemove() def draw_polyline(): global the_points, drawn_points if len(the_points) &lt; 2: return start_point = the_points[0] for end_point in the_points[1:]: xs = (start_point[0], end_point[0]) ys = (start_point[1], end_point[1]) start_point = end_point line = plt.Line2D(xs, ys, marker='.', color=(0.7, 0.3, 0.3)) plt.gcf().gca().add_artist(line) drawn_points = drawn_points + the_points the_points = list() plt.show() def button_press_callback(event): global the_points if event.button == 1: the_points.append((event.xdata, event.ydata)) p = plt.Line2D((event.xdata, event.xdata), (event.ydata, event.ydata), marker='o', color='r') plt.gcf().gca().add_artist(p) plt.show() else: draw_polyline() def handle_motion(event): global moving_point if len(drawn_points) &lt; 2: return x = event.xdata start_point = drawn_points[0] for end_point in drawn_points[1:]: start_x, start_y = start_point end_x, end_y = end_point if end_x &lt; start_x: end_x, start_x = start_x, end_x end_y, start_y = start_y, end_y if start_x &lt;= x &lt;= end_x: d = end_x - start_x lam = (x - start_x) / d y = start_y * (1 - lam) + end_y * lam moving_point.remove() moving_point = plt.Line2D((x, x), (y, y), marker='o', color='r') plt.gcf().gca().add_artist(moving_point) break start_point = end_point plt.show() fig = plt.gcf() fig.add_subplot(111, aspect='equal') fig.canvas.mpl_connect('button_press_event', button_press_callback) fig.canvas.mpl_connect('motion_notify_event', handle_motion) plt.show() </code></pre> <p>Traceback:</p> <pre><code>Exception in Tkinter callback x = self.convert_xunits(self._x) File "C:\Python27\lib\site-packages\matplotlib\artist.py", line 186, in convert_xunits ax = getattr(self, 'axes', None) RuntimeError: maximum recursion depth exceeded while calling a Python object Exception in Tkinter callback Traceback (most recent call last): File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__ return self.func(*args) File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 605, in destroy Gcf.destroy(self._num) File "C:\Python27\lib\site-packages\matplotlib\_pylab_helpers.py", line 60, in destroy manager.canvas.mpl_disconnect(manager._cidgcf) File "C:\Python27\lib\site-packages\matplotlib\backend_bases.py", line 2366, in mpl_disconnect return self.callbacks.disconnect(cid) File "C:\Python27\lib\site-packages\matplotlib\cbook.py", line 552, in disconnect del functions[function] File "C:\Python27\lib\weakref.py", line 327, in __delitem__ del self.data[ref(key)] RuntimeError: maximum recursion depth exceeded </code></pre>
0
2016-09-02T16:20:54Z
39,299,342
<p>Okey, fellas, I got it. The problem was due to intensive use of <strong>plt.show()</strong> in the event handler. Replacing it with <strong>event.canvas.draw()</strong> does the job.</p>
0
2016-09-02T19:15:16Z
[ "python", "matplotlib" ]
Change the facecolor of boxplot in pandas
39,297,093
<p>I need to change the colors of the boxplot drawn using <code>pandas</code> utility function. I can change most properties using the <code>color</code> argument but can't figure out how to change the <code>facecolor</code> of the box. Someone knows how to do it?</p> <pre><code>import pandas as pd import numpy as np data = np.random.randn(100, 4) labels = list("ABCD") df = pd.DataFrame(data, columns=labels) props = dict(boxes="DarkGreen", whiskers="DarkOrange", medians="DarkBlue", caps="Gray") df.plot.box(color=props) </code></pre>
1
2016-09-02T16:32:52Z
39,297,393
<p>While I still recommend seaborn and raw matplotlib over the plotting interface in pandas, it turns out that you can pass <code>patch_artist=True</code> as a kwarg to <code>df.plot.box</code>, which will pass it as a kwarg to <code>df.plot</code>, which will pass is as a kwarg to <code>matplotlib.Axes.boxplot</code>.</p> <pre><code>import pandas as pd import numpy as np data = np.random.randn(100, 4) labels = list("ABCD") df = pd.DataFrame(data, columns=labels) props = dict(boxes="DarkGreen", whiskers="DarkOrange", medians="DarkBlue", caps="Gray") df.plot.box(color=props, patch_artist=True) </code></pre> <p><a href="http://i.stack.imgur.com/ZicnB.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZicnB.png" alt="enter image description here"></a></p>
1
2016-09-02T16:54:49Z
[ "python", "pandas", "matplotlib", "boxplot" ]
Change the facecolor of boxplot in pandas
39,297,093
<p>I need to change the colors of the boxplot drawn using <code>pandas</code> utility function. I can change most properties using the <code>color</code> argument but can't figure out how to change the <code>facecolor</code> of the box. Someone knows how to do it?</p> <pre><code>import pandas as pd import numpy as np data = np.random.randn(100, 4) labels = list("ABCD") df = pd.DataFrame(data, columns=labels) props = dict(boxes="DarkGreen", whiskers="DarkOrange", medians="DarkBlue", caps="Gray") df.plot.box(color=props) </code></pre>
1
2016-09-02T16:32:52Z
39,352,762
<p>As suggested, I ended up creating a function to plot this, using raw <code>matplotlib</code>. </p> <pre><code>def plot_boxplot(data, ax): bp = ax.boxplot(data.values, patch_artist=True) for box in bp['boxes']: box.set(color='DarkGreen') box.set(facecolor='DarkGreen') for whisker in bp['whiskers']: whisker.set(color="DarkOrange") for cap in bp['caps']: cap.set(color="Gray") for median in bp['medians']: median.set(color="white") ax.axhline(0, color="DarkBlue", linestyle=":") ax.set_xticklabels(data.columns) </code></pre>
0
2016-09-06T15:29:29Z
[ "python", "pandas", "matplotlib", "boxplot" ]
Is it possible to kill the parent thread from within a child thread in python?
39,297,166
<p>I am using Python 3.5.2 on windows. </p> <p>I would like to run a python script but guarantee that it will not take more than <strong>N</strong> seconds. If it <em>does</em> take more than <strong>N</strong> seconds, an exception should be raised, and the program should exit. Initially I had thought I could just launch a thread at the beginning that waits for <strong>N</strong> seconds before throwing an exception, but this only manages to throw an exception to the timer thread, not to the parent thread. For example:</p> <pre><code>import threading import time def may_take_a_long_time(name, wait_time): print("{} started...".format(name)) time.sleep(wait_time) print("{} finished!.".format(name)) def kill(): time.sleep(3) raise TimeoutError("No more time!") kill_thread = threading.Thread(target=kill) kill_thread.start() may_take_a_long_time("A", 2) may_take_a_long_time("B", 2) may_take_a_long_time("C", 2) may_take_a_long_time("D", 2) </code></pre> <p>This outputs:</p> <pre><code>A started... A finished!. B started... Exception in thread Thread-1: Traceback (most recent call last): File "C:\Program Files\Python35\lib\threading.py", line 914, in _bootstrap_inner self.run() File "C:\Program Files\Python35\lib\threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "timeout.py", line 11, in kill raise TimeoutError("No more time!") TimeoutError: No more time! B finished!. C started... C finished!. D started... D finished!. </code></pre> <p>Is this even remotely possible? I realize I could do something like this:</p> <pre><code>import threading import time def may_take_a_long_time(name, wait_time, thread): if not thread.is_alive(): return print("{} started...".format(name)) time.sleep(wait_time) print("{} finished!.".format(name)) def kill(): time.sleep(3) raise TimeoutError("No more time!") kill_thread = threading.Thread(target=kill) kill_thread.start() may_take_a_long_time("A", 2, kill_thread) may_take_a_long_time("B", 2, kill_thread) may_take_a_long_time("C", 2, kill_thread) may_take_a_long_time("D", 2, kill_thread) </code></pre> <p>But this method fails if, for example, <code>may_take_a_long_time("B", 60, kill_thread)</code> was called. </p> <p>So I guess my TL;DR question is, what's the best way to put a time limit on the main thread itself?</p>
1
2016-09-02T16:38:45Z
39,297,260
<p>If the parent thread is the root thread, you may want to try <code>os._exit(0)</code>.</p> <pre><code>import os import threading import time def may_take_a_long_time(name, wait_time): print("{} started...".format(name)) time.sleep(wait_time) print("{} finished!.".format(name)) def kill(): time.sleep(3) os._exit(0) kill_thread = threading.Thread(target=kill) kill_thread.start() may_take_a_long_time("A", 2) may_take_a_long_time("B", 2) may_take_a_long_time("C", 2) may_take_a_long_time("D", 2) </code></pre>
1
2016-09-02T16:45:59Z
[ "python", "multithreading", "time" ]
Is it possible to kill the parent thread from within a child thread in python?
39,297,166
<p>I am using Python 3.5.2 on windows. </p> <p>I would like to run a python script but guarantee that it will not take more than <strong>N</strong> seconds. If it <em>does</em> take more than <strong>N</strong> seconds, an exception should be raised, and the program should exit. Initially I had thought I could just launch a thread at the beginning that waits for <strong>N</strong> seconds before throwing an exception, but this only manages to throw an exception to the timer thread, not to the parent thread. For example:</p> <pre><code>import threading import time def may_take_a_long_time(name, wait_time): print("{} started...".format(name)) time.sleep(wait_time) print("{} finished!.".format(name)) def kill(): time.sleep(3) raise TimeoutError("No more time!") kill_thread = threading.Thread(target=kill) kill_thread.start() may_take_a_long_time("A", 2) may_take_a_long_time("B", 2) may_take_a_long_time("C", 2) may_take_a_long_time("D", 2) </code></pre> <p>This outputs:</p> <pre><code>A started... A finished!. B started... Exception in thread Thread-1: Traceback (most recent call last): File "C:\Program Files\Python35\lib\threading.py", line 914, in _bootstrap_inner self.run() File "C:\Program Files\Python35\lib\threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "timeout.py", line 11, in kill raise TimeoutError("No more time!") TimeoutError: No more time! B finished!. C started... C finished!. D started... D finished!. </code></pre> <p>Is this even remotely possible? I realize I could do something like this:</p> <pre><code>import threading import time def may_take_a_long_time(name, wait_time, thread): if not thread.is_alive(): return print("{} started...".format(name)) time.sleep(wait_time) print("{} finished!.".format(name)) def kill(): time.sleep(3) raise TimeoutError("No more time!") kill_thread = threading.Thread(target=kill) kill_thread.start() may_take_a_long_time("A", 2, kill_thread) may_take_a_long_time("B", 2, kill_thread) may_take_a_long_time("C", 2, kill_thread) may_take_a_long_time("D", 2, kill_thread) </code></pre> <p>But this method fails if, for example, <code>may_take_a_long_time("B", 60, kill_thread)</code> was called. </p> <p>So I guess my TL;DR question is, what's the best way to put a time limit on the main thread itself?</p>
1
2016-09-02T16:38:45Z
39,297,315
<p>You can use <a href="https://docs.python.org/2/library/thread.html" rel="nofollow"><code>_thread.interrupt_main</code></a> (this module is called <code>thread</code> in Python 2.7):</p> <pre><code>import time, threading, _thread def long_running(): while True: print('Hello') def stopper(sec): time.sleep(sec) print('Exiting...') _thread.interrupt_main() threading.Thread(target = stopper, args = (2, )).start() long_running() </code></pre>
2
2016-09-02T16:49:20Z
[ "python", "multithreading", "time" ]
Python Failed to Verify any CRLs for SSL/TLS connections
39,297,240
<p>In Python 3.4, a <code>verify_flags</code> that can be used to check if a certificate was revoked against CRL, by set it to <code>VERIFY_CRL_CHECK_LEAF</code> or <code>VERIFY_CRL_CHECK_CHAIN</code>.</p> <p>I wrote a simple program for testing. But on my systems, this script failed to verify ANY connections even if it's perfectly valid. </p> <pre><code>import ssl import socket def tlscheck(domain, port): addr = domain ctx = ssl.create_default_context() ctx.options &amp;= ssl.CERT_REQUIRED ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF ctx.check_hostname = True #ctx.load_default_certs() #ctx.set_default_verify_paths() #ctx.load_verify_locations(cafile="/etc/ssl/certs/ca-certificates.crt") sock = ctx.wrap_socket(socket.socket(), server_hostname=addr) sock.connect((addr, port)) import pprint print("TLS Ceritificate:") pprint.pprint(sock.getpeercert()) print("TLS Version:", sock.version()) print("TLS Cipher:", sock.cipher()[0]) exit() tlscheck("stackoverflow.com", 443) </code></pre> <p>My code always quits with <code>ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)</code>. </p> <p>First I suspected that the certificate database was not loaded properly. But after I tried <code>load_default_certs()</code>, <code>set_default_verify_paths()</code>, <code>load_verify_locations(cafile="/etc/ssl/certs/ca-certificates.crt")</code>, and none of them worked.</p> <p>Also, <code>ctx.options &amp;= ssl.CERT_REQUIRED</code> works as expected, it can tell if a certificate chain is trusted or not. But not for CRLs... It also indicates that my CAs are correct.</p> <p>I know "/etc/ssl/certs/ca-certificates.crt" contains valid CAs. What is the problem?</p>
0
2016-09-02T16:44:23Z
39,297,998
<p>To check against CRL you have to manually download the CRL and put them in the right place so that the underlying OpenSSL library will find it. There is no automatic downloading of CRL and specifying the place where to look for the CRL is not intuitive either. What you can do:</p> <ul> <li>get the CRL distribution points from the certificate. For stackoverflow.com one is <a href="http://crl3.digicert.com/sha2-ha-server-g5.crl" rel="nofollow">http://crl3.digicert.com/sha2-ha-server-g5.crl</a></li> <li>download the current CRL from there</li> <li>convert it from the DER format to PEM format, because this is what is expected in the next step: <br> <code>openssl crl -inform der -in sha2-ha-server-g5.crl &gt; sha2-ha-server-g5.crl.pem</code></li> <li>add the location to the verify_locations:<br> <code>ctx.load_verify_locations(cafile="./sha2-ha-server-g5.crl.pem")</code></li> </ul> <p>This way you can verify the certificate against the CRL. </p>
1
2016-09-02T17:36:49Z
[ "python", "ssl" ]
For Loop Not Respecting Continue Command
39,297,255
<p>The problem I'm having is that the <code>continue</code> command is skipping inconsistently. It skips the numerical output <code>ebitda</code> but puts the incorrect <code>ticker</code> next to it. Why is this? If I make the ticker just <code>phm</code> an input it should skip, it correctly prints an empty list <code>[]</code> but when an invalid ticker is placed next to a valid one, the confusion starts happening. </p> <pre><code>import requests ticker = ['aapl', 'phm', 'mmm'] ebitda = [] for i in ticker: r_EV=requests.get('https://query2.finance.yahoo.com/v10/finance/quoteSummary/'+i+'?formatted=true&amp;crumb=8ldhetOu7RJ&amp;lang=en-US&amp;region=US&amp;modules=defaultKeyStatistics%2CfinancialData%2CcalendarEvents&amp;corsDomain=finance.yahoo.com') r_ebit = requests.get('https://query1.finance.yahoo.com/v10/finance/quoteSummary/' + i + '?formatted=true&amp;crumb=B2JsfXH.lpf&amp;lang=en-US&amp;region=US&amp;modules=incomeStatementHistory%2CcashflowStatementHistory%2CbalanceSheetHistory%2CincomeStatementHistoryQuarterly%2CcashflowStatementHistoryQuarterly%2CbalanceSheetHistoryQuarterly%2Cearnings&amp;corsDomain=finance.yahoo.com%27') data = r_EV.json() data1 = r_ebit.json() if data1['quoteSummary']['result'][0]['balanceSheetHistoryQuarterly']['balanceSheetStatements'][0].get('totalCurrentAssets') == None: continue #skips certain ticker if no Total Current Assets available (like for PHM) ebitda_data = data['quoteSummary']['result'][0]['financialData'] ebitda_dict = ebitda_data['ebitda'] ebitda.append(ebitda_dict['raw']) #navigates to dictionairy where ebitda is stored ebitda_formatted = dict(zip(ticker, ebitda)) print(ebitda_formatted) # should print {'aapl': 73961996288, 'mmm': 8618000384} # NOT: {'aapl': 73961996288, 'phm': 8618000384} </code></pre>
-2
2016-09-02T16:45:11Z
39,297,366
<p>The <code>continue</code> works just fine. You produce this list:</p> <pre><code>[73961996288, 8618000384] </code></pre> <p>However, you then zip that list with <code>ticker</code>, which still has 3 elements in it, including <code>'phm'</code>. <code>zip()</code> stops when one of the iterables is empty, so you produce the following tuples:</p> <pre><code>&gt;&gt;&gt; ebitda [73961996288, 8618000384] &gt;&gt;&gt; ticker ['aapl', 'phm', 'mmm'] &gt;&gt;&gt; zip(ticker, ebitda) [('aapl', 73961996288), ('phm', 8618000384)] </code></pre> <p>If you are <em>selectively</em> adding <code>ebitda</code> values to a list, you'd also have to record what <code>ticker</code> values you processed:</p> <pre><code>used_ticker.append(i) </code></pre> <p>and use that new list.</p> <p>Or you could just <em>start</em> with an empty <code>ebitda_formatted</code> dictionary and add to that in the loop:</p> <pre><code>ebitda_formatted[i] = ebitda_dict['raw'] </code></pre>
2
2016-09-02T16:53:02Z
[ "python", "for-loop", "continue" ]
Is there a faster way to change the 0s in a linespace?
39,297,284
<p>I'm working with Jupyter Notebooks and I need to do some calculations using a <code>linspace</code> which go to <code>b</code> from <code>a</code>, the problem is that I get the Zero Division Error, so I was wondering if there was a faster way to change the 0s in a linespace, instead of going trough each element, check if it's a 0 and then change it with the smallest representable number?</p>
0
2016-09-02T16:47:26Z
39,297,412
<pre><code>a= numpy.linspace(...) zero_mask = a==0 </code></pre> <p>is that what you mean?</p>
2
2016-09-02T16:55:44Z
[ "python", "numpy" ]
Store Scraped WebPage with Python SqlAlchemy
39,297,328
<p>I do many look ups and scrapes of webpages and I would like to store the response to those lookups in a database to avoid having to request them again (to improve speed but also to not be a nuisance). I am using sqlalchemy and python, and I've created an ORM class like below:</p> <pre><code>class MyClass(Base): __tablename__ = "myclass" url = Column(String, primary_key=True) article = Column(String) </code></pre> <p>When creating a new article and adding it to my session, i.e.:</p> <pre><code>session.add(MyClass(url=url,article=requests.get(url).text) </code></pre> <p>I am able to add it to the database. However, when I query the url's in the database, I receive this message back,</p> <pre><code>OperationalError: (sqlite3.OperationalError) unrecognized token: ':' [SQL: u'SELECT http://[mywebsite]] </code></pre> <p>I understand that it is having trouble with the ':' in http:// but am wondering if that is the case, is there any way to use a full web url as the primary key? </p> <p>Furthermore, what would be the recommended data types, both in terms of storage efficiency and look up efficiency to use for storing a webpage and its corresponding content?</p>
0
2016-09-02T16:50:14Z
39,297,653
<p>I think, escape the url before store it will resolve the problem.</p> <p>eg:</p> <pre><code>article = requests.get(url).text url = url.replace(":", "COLON") session.add(MyClass(url=url,article=article) </code></pre> <p>In a similar way, you can restore it when you take data out</p>
-1
2016-09-02T17:12:12Z
[ "python", "web-scraping", "sqlalchemy" ]
Detecting merged cells in a word document table
39,297,368
<p><strong>A little background</strong></p> <p>I have a software specification which I need to parse requirements from in the form of tables. They are not always in the same format either. I inherited a python script that uses win32com to parse the word document, and then openpyxl to export the requirements to an excel file, which is then uploaded to HP ALM. </p> <p><strong>Question</strong> </p> <p>Using python (or some other language that can communicate with python), I am looking for a relatively simple and easy way to differentiate between merged cells, and empty cells (both of which occur in the microsoft word documents)(2010 .docx). </p> <p><strong>Explanation</strong></p> <p>So far, I have been searching for a solution to this for a couple weeks now, but I haven't found a satisfactory answer to the problem yet. </p> <p>There are questions <a href="http://stackoverflow.com/questions/28559703/how-to-detect-merged-cells-in-vba-word-2010">here</a> and <a href="http://stackoverflow.com/questions/4523806/how-do-i-detect-a-word-table-with-horizontally-merged-cells">here</a> that I've looked at on stackoverflow. The second question says there is a field which will tell you whether there are merged cells in a table, which is a starting point, but not sufficient since it's possible the table will be one super long table spanning many pages.</p> <p><strong>Attempts at a solution</strong></p> <p><strong>Attempt 1.)</strong> My first thought was that surely win32com supports detecting merged cells in a table. So I searched and searched for methods that would do this for me. The only thing I found that would work is checking whether a merged cell is blank, while the previous one isn't. But, then I can't tell if the cell is truly blank or merged.</p> <p><strong>Attempt 2.)</strong> My next thought was to add the feature to win32com using COM and the win32 API. But, I found COM is quite unwieldy, out-of-date now, and super undocumented and difficult to use. The same goes for the win32 API. Basically, I found this is more effort than it's worth to do.</p> <p><strong>Attempt 3.)</strong> Then I began looking for alternative libraries to win32com, such as docx for python. The issue here, is that I work on a non-administrator computer, which severely restricts my ability to download third party libraries. Thus, I have yet to try this option, because I went down this road when getting win32com and openpyxl.</p> <p><strong>Attempt 4.)</strong> My latest and possibly final attempt at figuring this out was to turn the word docx document into an XML file that I can parse easily. However, I don't know XML, nor do I know the standard format word uses for XML.</p> <p>And here I am now looking for the quickest, cleanest, way to do this without rewriting libraries, or starting my 1000 line script over from scratch. (which by the way has a display GUI layed over the top of it, that's why it's so long)</p>
0
2016-09-02T16:53:05Z
39,297,551
<p>According to <a href="https://msdn.microsoft.com/en-us/library/office/ff821310.aspx" rel="nofollow">the doc</a> merged cells in Word become one cell after being merged (<a href="https://msdn.microsoft.com/en-us/library/office/ff840729.aspx" rel="nofollow">unlike excel</a>). So the concept of merged cells do not really exists in Word. The only way to detect them will be to analyse all the tables with the algorithm you found in the posts linked in your question. Which consist on finding <em>missing</em> cells that do not exists because another cell is taking their place (which is the result of a merge).</p>
0
2016-09-02T17:05:56Z
[ "python", "vba", "ms-word", "win32com" ]
Finding square root without using math.sqrt()?
39,297,441
<p>I recently was working on finding the square root of a number in <code>python</code> without using <code>sqrt()</code>. I came across this code and am having difficulty in understanding the logic in this code:</p> <pre><code>def sqrt(x): last_guess= x/2.0 while True: guess= (last_guess + x/last_guess)/2 if abs(guess - last_guess) &lt; .000001: # example threshold return guess last_guess= guess </code></pre> <p>More specifically the logic behind calculating <code>guess</code> in above code. Can anyone help me understanding the logic?</p>
0
2016-09-02T16:57:45Z
39,297,698
<p>You can always use the power (<code>**</code>) operator with an inverse exponent:</p> <pre><code>a = 2 ** (1.0 / 2) a &gt; 1.41421... </code></pre>
1
2016-09-02T17:16:07Z
[ "python", "square-root" ]
How to properly run a Python script from PHP
39,297,480
<p>I have a PHP script that unzips an archive containing Python scripts into a directory, str_replaces some things inside the script, shell_exec's the script, and then unlinks the script.</p> <p>I have no problems unzipping the archive or chmodding the contents to 0755. I can execute the generated scripts through terminal and they perform as expected, but with PHP nothing happens!</p> <p>I have tried specifying absolute paths for Python in my shell_exec and in a shebang within the Python file to no avail. There appear to be no syntax errors or unmet dependencies. I've tried this with all affected directories at chmod 0777 to no avail either. The section of relevant code is as follows...</p> <pre class="lang-php prettyprint-override"><code>if (in_array($oldExtension,$allowed)) { list($Width, $Height) = getimagesize($CUD); $EXFreshScript = $InstLoc.'/Applications/document-scanner-master.zip'; $EXTempScript = $InstLoc.'/DATA/'.$UserID.'/TEMPSCRIPTS'; mkdir($EXTempScript); chmod($EXTempScript, 0777); $ExtractScripts = shell_exec('unzip '.$EXFreshScript.' -d '.$EXTempScript); chmod($EXTempScript.'/document-scanner', 0777); $TempScript = $EXTempScript.'/document-scanner/scan.py'; chmod($EXTempScript.'/document-scanner', 0777); $TempScriptGlob = glob($TempScript); foreach ($TempScriptGlob as $TSG) { chmod($TSG, 0777); } chmod($EXTempScript.'/document-scanner/pyimagesearch', 0777); $TempScript1 = $EXTempScript.'/document-scanner/pyimagesearch'; $TempScriptGlob = glob($TempScript1); foreach ($TempScriptGlob as $TSG) { chmod($TSG, 0777); } $OutputDoc = $InstLoc.'/DATA/'.$UserID.'/DOCSCANTEMP.jpg'; $Code = 'DOCSCANTEMP.jpg'; $newCode = $InstLoc.'/DATA/'.$UserID.'/DOCSCANTEMP.jpg'; $ScriptData = file_get_contents($TempScript); $SwapCode = str_replace($Code, $newCode, $ScriptData); $WriteCode = file_put_contents($TempScript, $SwapCode); $txt = ('OP-Act: Modified the code of '.$TempScript.' with '.$Width.', '.$Height.' on '.$Time.'.'); $LogFile = file_put_contents($SesLogDir.'/'.$Date.'.txt', $txt.PHP_EOL , FILE_APPEND); $txt = ('OP-Act: Executing! '.$TempScript.' on '.$Time.'.'); $LogFile = file_put_contents($SesLogDir.'/'.$Date.'.txt', $txt.PHP_EOL , FILE_APPEND); chmod($TempScript, 0777); shell_exec('python '.$TempScript.' -i '.$CTD); $txt = ('OP-Act: Execute complete! '.$TempScript.' was executed on '.$Time.'.'); $LogFile = file_put_contents($SesLogDir.'/'.$Date.'.txt', $txt.PHP_EOL , FILE_APPEND); } </code></pre> <p>If anyone has any ideas I'd greatly appreciate it. The script this came from is over 650 lines long and I've got my issue narrowed down to this. Thanks!</p>
0
2016-09-02T17:00:42Z
39,307,722
<p>I'll focus on this line:</p> <pre><code>shell_exec('python '.$TempScript.' -i '.$CTD); </code></pre> <ol> <li>Seems like <code>$CTD</code> is not defined.</li> <li>Don't use <code>-i</code> flag because it enforces python prompt.</li> <li>Try to use <code>exec()</code> instead for better debugging.</li> </ol> <p>If it won't help you, let me know what it outputs.</p> <pre><code>$return = NULL; $output = []; exec('python '.$TempScript, $output, $return); var_dump($return); var_dump($output); </code></pre>
0
2016-09-03T13:58:00Z
[ "php", "python", "permissions", "shell-exec" ]
Plot CDF + cumulative histogram using Seaborn Python
39,297,523
<p>Is there a way to plot the CDF + cumulative histogram of a Pandas Series in Python using Seaborn only? I have the following:</p> <pre><code>import numpy as np import pandas as pd import seaborn as sns s = pd.Series(np.random.normal(size=1000)) </code></pre> <p>I know I can plot the cumulative histogram with <code>s.hist(cumulative=True, normed=1)</code>, and I know I can then plot the CDF using <code>sns.kdeplot(s, cumulative=True)</code>, but I want something that can do both in Seaborn, just like when plotting a distribution with <code>sns.distplot(s)</code>, which gives both the kde fit and the histogram. Is there a way? I wonder why they didn't implement something like <code>sns.distplot(cumulative=True)</code>. Otherwise, how can I make the color themes to match? Where do I find the default colors used for <code>sns.distplot()</code>? </p>
0
2016-09-02T17:03:50Z
39,306,779
<pre><code>import numpy as np import seaborn as sns x = np.random.randn(200) sns.distplot(x, hist_kws=dict(cumulative=True), kde_kws=dict(cumulative=True)) </code></pre> <p><a href="http://i.stack.imgur.com/eBDry.png" rel="nofollow"><img src="http://i.stack.imgur.com/eBDry.png" alt="enter image description here"></a></p>
2
2016-09-03T12:17:17Z
[ "python", "pandas", "seaborn" ]
missing last bin in histogram plot from matplot python
39,297,630
<p>I'm trying to draw histrogram based of my value </p> <pre><code>x = ['3', '1', '4', '1', '5', '9', '2', '6', '5', '3', '5', '2', '3', '4', '5', '6', '4', '2', '0', '1', '9', '8', '8', '8', '8', '8', '9', '3', '8', '0', '9', '5', '2', '5', '7', '2', '0', '1', '0', '6', '5'] x_num = [int(i) for i in x] key = '0123456789' for i in key: print(i," count =&gt;",x.count(i)) plt.hist(x_num, bins=[0,1,2,3,4,5,6,7,8,9]) </code></pre> <p><a href="http://i.stack.imgur.com/wZK0l.png" rel="nofollow"><img src="http://i.stack.imgur.com/wZK0l.png" alt="enter image description here"></a></p> <p>The last 2 numbers "8, 9" bin should have distribution count of 6 , 4 But in histogram it combine 8 and 9 and get value of 10 instead of separate them. Total number of bin should be 10 => but it only giving me graph of 9..</p> <p>How could I separate them and break 8 and 9 ? </p>
0
2016-09-02T17:10:34Z
39,297,910
<pre><code>import matplotlib.pyplot as plt x = ['3', '1', '4', '1', '5', '9', '2', '6', '5', '3', '5', '2', '3', '4', '5', '6', '4', '2', '0', '1', '9', '8', '8', '8', '8', '8', '9', '3', '8', '0', '9', '5', '2', '5', '7', '2', '0', '1', '0', '6', '5'] x_num = [int(i) for i in x] key = '0123456789' for i in key: print(i, " count =&gt;", x.count(i)) plt.hist(x_num, bins=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10]) plt.show() </code></pre>
1
2016-09-02T17:30:30Z
[ "python", "matplotlib" ]
Python module runs but shows "Syntax error while detecting tuple" in aptana
39,297,634
<p>I am learning python and when I was running the below code</p> <pre><code>print("X",end='awesome') </code></pre> <p>The code runs but shows the following syntax error</p> <pre><code>"Syntax error while detecting tuple" </code></pre> <p>How I can resolve it?</p>
0
2016-09-02T17:11:11Z
39,297,887
<p>Aptana is set to use syntax checking for Python 2.x, where <code>print</code> is a statement. It is recognizing this statement as if you were trying to print a tuple, which is what that would be in Python 2.x, and correctly pointing out that you can't have an <code>=</code> sign inside the tuple. But the code is written for Python 3.x, where <code>print</code> is a function call and this syntax is valid.</p> <p>You need to set Aptana to use the Python 3 grammar. I found <a href="https://pythoncodesnippets.wordpress.com/2015/12/23/how-to-configure-aptana-studio-with-python3-interpreter/" rel="nofollow">this page</a> that shows you how to set up Aptana to use a Python 3.x interpreter (which you probably already have, since the script runs) and syntax.</p>
1
2016-09-02T17:29:00Z
[ "python", "aptana" ]
Kivy Screen class bug
39,297,676
<p>For some reason in kivy when you create a screen class and add a widget to it, specifically an image you get an image 10x bigger than the original for some reason compared to when you make a widget class and add that widget class as a child to the screen class. Here is my code for the kv file: </p> <pre><code>&lt;StartScreen&gt; # Start Screen name:'Start' orientation: 'vertical' FloatLayout: id: Start_Layout Image: id: Start_Background source: r'Images\Battle.jpg' keep_ratio: True allow_stretch: True size: root.size &lt;MainScreen&gt; name: 'Main' orientation: 'vertical' FloatLayout: Image: source: r'Images\Button.png' allow_stretch: True keep_ratio: False size: 100, 100 </code></pre> <p>and for the python gui file...</p> <pre><code>from kivy.uix.widget import Widget from kivy.uix.image import Image from kivy.uix.boxlayout import BoxLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.label import Label from kivy.animation import Animation from kivy.uix.screenmanager import ScreenManager, Screen from kivy.clock import Clock from kivy.graphics.context_instructions import Color from kivy.graphics.vertex_instructions import * from kivy.core.window import Window from kivy.app import App from kivy.lang import Builder import kivy kivy.require('1.9.1') VERSION = '1.9.1' class GenericButton(Widget): Builder.load_file('Button.kv') def __init__(self, **kwargs): super(GenericButton, self).__init__(**kwargs) self.Button = self.ids['Button'] self.size = Window.size def on_touch_down(self, touch): self.Button.source = r'Images\ButtonPressed.png' def on_touch_up(self, touch): self.Button.source = r'Images\Button.png' class wid(Widget): def __init__(self, **kwargs): super(wid, self).__init__(**kwargs) </code></pre> <p>self.Button = Image(source='Images\Animatio\glow.gif', allow_stretch=False, keep_ratio=True) (pretend its indented cus im new and it wouldn't let me add it to the code block) self.add_widget(self.Button)</p> <pre><code>class StartScreen(Screen): def __init__(self, **kwargs): super(StartScreen, self).__init__(**kwargs) #self.Layout = self.ids['Start_Layout'] #self.size = Window.size #self.Layout.add_widget(GenericButton()) #self.ids['Start_Button'] = self.Layout.children[0] print self.ids #print self.ids.Start_Button.size print self.size[0]/2, self.size[1]/2 class MainScreen(Screen): def __init__(self, **kwargs): super(MainScreen, self).__init__(**kwargs) self.size = Window.size def on_touch_down(self, touch): self.Button.source = r'Images\ButtonPressed.png' def on_touch_up(self, touch): self.Button.source = r'Images\Button.png' class ScreenManager(ScreenManager): def __init__(self, **kwargs): super(MCGMScreenManager, self).__init__(**kwargs) Builder.load_file('Gui.kv') self.add_widget(StartScreen()) self.add_widget(MainScreen()) </code></pre> <p>And the app runs in the main file which i dont see a need to post. But an important thing might be that the app root class is ScreenManager</p> <p>edit: i messed around a bit and i did this in python but i cleared the children of GenericButton and added the button that GenericButton used to own as a child of StartScreen and same result, a huge unresponsive image.</p>
0
2016-09-02T17:13:53Z
39,307,415
<pre><code>&lt;MainScreen&gt; name: 'Main' orientation: 'vertical' FloatLayout: Image: source: r'Images\Button.png' allow_stretch: True keep_ratio: False size: 100, 100 </code></pre> <p>I didn't check if it's causing your particular issue, but the Image here doesn't take size 100, 100 because its parent (FloatLayout) is a layout class that automatically sets the size and position of its children. In this case, Image will automatically be resized to fill the FloatLayout.</p> <p>To prevent this, add <code>size_hint: None, None</code> to the Image, to disable automatic resizing in both the horizontal and vertical directions. This generally applies whenever you add something to a Layout.</p>
1
2016-09-03T13:25:25Z
[ "python", "kivy", "kivy-language" ]
if two requirements in a multiple if statement are meet than the next time they are meet I want to check something else
39,297,689
<p>So this is the code I have right now.</p> <pre><code>count1_1 = 0 previous_1 = False for i in B: if B[i] % 10 == 1 and B[i + 2] % 10 == 3: if A[i] * A[i + 2] == 1: current_1 = i % 10 == 1 if current_1 and previous_1: count1_1 += 1 previous_1 = current_1 return count1_1 </code></pre> <p>Right now this code counts every time that all the specified criteria are meet following the first time they are meet. I was wondering if anyone knows of a way I could modify the code so that when the code runs it first find the first number that meets these requirements:</p> <pre><code>if B[i] % 10 == 1 and B[i + 2] % 10 == 3: if A[i] * A[i + 2] == 1: </code></pre> <p>and also has i % 10 = 1. Then instead of finding each time these requirements are meet, it will only add to a count if the next time these requirements are meet:</p> <pre><code>if B[i] % 10 == 1 and B[i + 2] % 10 == 3: if A[i] * A[i + 2] == 1: </code></pre> <p>at that point i % 10 also has to be equal to 1. If it is not then I want the code to stop. </p> <p>Essentially I want to add to a count only if all the requirement are meet in consecutive times that these requirements are meet:</p> <pre><code>if B[i] % 10 == 1 and B[i + 2] % 10 == 3: if A[i] * A[i + 2] == 1: </code></pre> <p>EDIT:</p> <p>In this code B is a range and this is A</p> <p>[0, 1, 1, 1, 4, 1, 6, 1, 8, 9, 10, 1, 12, 1, 14, 15, 16, 1, 18, 1, 20, 21, 22, 1, 24, 25, 26, 27, 28, 1, 30, 1, 32, 33, 34, 35, 36, 1, 38, 39, 40, 1, 42, 1, 44, 45, 46, 1, 48, 49, 50, 51, 52, 1, 54, 55, 56, 57, 58, 1, 60, 1, 62, 63, 64, 65, 66, 1, 68, 69, 70, 1, 72, 1, 74, 75, 76, 77, 78, 1, 80, 81, 82, 1, 84, 85, 86, 87, 88, 1, 90, 91, 92, 93, 94, 95, 96, 1, 98, 99, 100, 1, 102, 1, 104, 105, 106, 1, 108, 1, 110]</p> <p>When I run my code it should only add to count1_1 once because the only time all conditions are meet in consecutive times that the first two conditions are meet is at index ((71,73),(101,103)). When I run my code it returns count1_1 = 4 because the conditions are meet 4 times after the first time the condition is meet at index(1,3). I want to change my code so that the next time that (i and i + 2 = 1) if the remainder of their index in % 10 is not equal to 1 and 3 than it will look for the next time that all conditions are meet and if all conditions are meet then again after that, like at index ((71,73),(101,103)), than it will add to count1_1.</p> <p>Hope that clears up the question a bit.</p>
-2
2016-09-02T17:15:22Z
39,298,135
<p>I think that I get it</p> <pre><code>def my_count(A): count = 0 previous=False for i in range(1, len(A)-2, 10): current = A[i] * A[i + 2] == 1 if previous and current: count += 1 previous = current return count data=[ 0, 1, 1, 1, 4, 1, 6, 1, 8, 9, #0 10, 1, 12, 1, 14, 15, 16, 1, 18, 1, #1 20, 21, 22, 1, 24, 25, 26, 27, 28, 1, #2 30, 1, 32, 33, 34, 35, 36, 1, 38, 39, #3 40, 1, 42, 1, 44, 45, 46, 1, 48, 49, #4 50, 51, 52, 1, 54, 55, 56, 57, 58, 1, #5 60, 1, 62, 63, 64, 65, 66, 1, 68, 69, #6 70, 1, 72, 1, 74, 75, 76, 77, 78, 1, #7 80, 81, 82, 1, 84, 85, 86, 87, 88, 1, #8 90, 91, 92, 93, 94, 95, 96, 1, 98, 99, #9 100, 1, 102, 1, 104, 105, 106, 1, 108, 1, #10 110] print(my_count(data)) # output: 1 </code></pre> <p>first as B is a range over the length of A, or so I assume, and you want only the index that are <em>i mod 10 = 1</em>, then that can by simply using the 3 argument call of <a href="https://docs.python.org/3/library/functions.html#func-range" rel="nofollow"><code>range</code></a> as that condition is fulfilled every 10 number starting in 1, therefore there is no need to check that every time. (Also for a range starting in 0 its i-esimo element is also i so using any of those is the same). The rest part should be self explanatory.</p> <p>Now, by arranging that example data as show above, you can clearly see that the index were they are consecutive is in [(1,3), (11,13)] not in [(71,73), (101,103)] as you claim </p>
0
2016-09-02T17:46:41Z
[ "python" ]
Why does this very basic query on this Django model fail?
39,297,718
<p>I have the following Django class:</p> <pre><code>from caching.base import CachingManager, CachingMixin from mptt.models import MPTTModel def make_id(): ''' inspired by http://instagram-engineering.tumblr.com/post/10853187575/sharding-ids-at-instagram ''' START_TIME = 1876545318034 return (int(time.time()*1000) - START_TIME &lt;&lt; 23 ) | random.SystemRandom().getrandbits(23) class My_Class(CachingMixin, MPTTModel): id = models.BigIntegerField(default=make_id, primary_key=True) # Other Attributes Snipped here for brevity </code></pre> <p>But look what happens when I try to query this class:</p> <pre><code>&gt;&gt;&gt; My_Class.objects.get(pk=5000) Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "my_virtual_env/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "my_virtual_env/lib/python2.7/site-packages/django/db/models/query.py", line 334, in get self.model._meta.object_name DoesNotExist: My_Class matching query does not exist. </code></pre> <p>Why does it fail?? How can I fix this?</p>
0
2016-09-02T17:18:03Z
39,297,795
<p>It could be you have no My_Class with id = 5000</p> <pre><code>try: mc = My_Class.objects.get(pk=id) except My_Class.DoesNotExist: mc = None </code></pre>
2
2016-09-02T17:23:21Z
[ "python", "django", "django-queryset" ]
Python List assignment and memory allocation
39,297,776
<p>Why does index assignment of another list form a linked list and list slice(one element slice) assignment of another list makes the list part of the original list when both the slice and element with the index points the same element? What changes happen in the memory allocation?</p> <pre><code>l = [1,2,3,4,5,6] l[2:3] = [7,8] # gives [1,2,7,8,5,6] # whereas: l[2] = [7,8] # gives [1,2,[7,8],4,5,6] </code></pre> <p>and initialy <code>l[2]=3</code> and <code>l[2:3]=3</code></p>
0
2016-09-02T17:22:03Z
39,312,203
<p>Your assumption is incorrect, when you say <em>"initialy l[2]=3 and l[2:3]=3"</em>.</p> <p>This is how it is, in fact:</p> <pre><code>l = [1, 2, 3, 4, 5, 6] l[2] # 3 l[2:3] # [3] </code></pre> <p><code>l[2]</code> is the element at index 2. <code>l[2:3]</code> is the slice (a sublist) of length one starting at index 2.</p> <p>Therefore, assigning to <code>l[2]</code> change to element and assigning to <code>l[2:3]</code> replaces a slice with another slice, exactly as you noticed:</p> <pre><code>l = [1, 2, 3, 4, 5, 6] l[2:3] = [7,8] # l is now [1, 2, 7, 8, 4, 5, 6] l = [1, 2, 3, 4, 5, 6] l[2] = [7,8] # l is now [1, 2, [7, 8], 4, 5, 6] </code></pre>
1
2016-09-03T23:27:31Z
[ "python", "list" ]
How to store Dict type result in database?
39,297,785
<p>I am using using <strong>facebook.graphAPI</strong> in python for searching restaurants in some specific city. The result it gives back is in <strong>DICT</strong> type.<br> My Code:</p> <pre><code>import facebook import json # get access_token from https://developers.facebook.com/tools/access_token/ graph = facebook.GraphAPI(access_token='EAAHuWhpN91gBAEcZCammDhlB2w0Q4FO1TH1J09IfZBBtJE8ruu78KNjdOxu38AOp9GxB0gv5YlSetJ70WLscYmMkpY2SrQkGWRQcojaZBZCb52kkHKs1yE868DJ9MEjrCRIMfeVZBVRwNfuT27gUFhaVomOzpyd3lHxYelx82qQZDZD', version='2.7') profile = graph.get_object("me") print profile rests=graph.request('search', {'q': 'Restaurants in Lahore', 'type': 'place'}) print type(rests) for key in rests: print "key: %s , value: %s" % (key, rests[key]) #TO get posts of Restaurant with id 816463355086343 posts = graph.get_connections('816463355086343', 'posts') </code></pre> <p>the result is like the picture given below. which is clearly not readable. <a href="http://i.stack.imgur.com/Alxyz.png" rel="nofollow">enter image description here</a></p> <p>So make I tried to make it readable. And it looks like this </p> <pre><code>key: data , value: [ { u'category': u'Hotel', u'id': u'106037262807337', u'location': { u'city': u'Lahore', u'zip': u'', u'country': u'Pakistan', u'longitude': 74.3356207, u'state': u'', u'street': u'PC Hotel Lahore, Mall Road Pakistan', u'latitude': 31.5480206 }, u'category_list': [ { u'id': u'165679780146824', u'name': u'Food &amp;amp; Restaurant' }, { u'id': u'180699075298665', u'name': u'Hospitality Service' }, { u'id': u'164243073639257', u'name': u'Hotel' } ], u'name': u'Pearl Continental, Lahore' }, { u'category': u'Local business', u'id': u'125484227592406', u'location': { u'city': u'Lahore', u'zip': u'', u'country': u'Pakistan', u'longitude': 74.417206363636, u'state': u'', u'street': u'masjad chok', u'latitude': 31.612784545455 }, u'category_list': [ { u'id': u'150534008338515', u'name': u'Barbecue Restaurant' } ], u'name': u'Lahore Defence' }, .... </code></pre> <p>I want to store the result into the database. I don't know <strong>How</strong> to do it? Please help me out it would be appreciated alot.<br> So I need instructions as how to use a database driver to store the data and retrieve it. </p>
0
2016-09-02T17:22:48Z
39,297,920
<p>Start by having an accessible Database server. Either set one up locally or if you have the means, set one up remotely. The image you attached to the question looks like a windows terminal, so download the MySQL Community Server for windows <a href="http://dev.mysql.com/downloads/mysql/" rel="nofollow">here</a>. </p> <p>The set up should be fairly straight forward. Keep your login credentials (most commonly used are -> username:root, password:root) somewhere secure. You'll be asked if and which password you'd like.</p> <p>When the server is up and running, it'll be available on <code>127.0.0.1:3306</code> by default. Now if you have some experience in MySQL, you'll know how to set up a basic database with some tables for your data to go in. (I'm assuming you have.)</p> <p>Once it's up and running, install mysql for python by executing <code>pip install MySQL-python</code> (this works for Python 2.7 as far as I know, use <code>pip install mysqlclient</code> for python 3+). This will install a python library that you can use in your code. Simply add the import statement for whichever library you chose at the top of your code as such: <code>import &lt;library_name&gt;</code>.</p> <p>Now I can't give you exact code because I know know which python version you're on but whichever you choose, there'll be documentation out there how to use it.</p> <p>It'll be in the following steps: </p> <ol> <li>Add the database connection details to the mysqlclient a. address (localhost:3306, ...) b. username (root, ...) c. password (root, ...) d. database_name (your_database_name)</li> <li>Create a cursor object which allows you to traverse the database tables</li> <li>Add an SQL statement to the cursor (i.e. SELECT * FROM CUSTOMERS)</li> <li>Place the result from your cursor execution into a variable</li> <li>Happy days</li> </ol>
0
2016-09-02T17:31:09Z
[ "python", "json", "facebook-graph-api" ]
Shell.BrowseForFolder in Python, how to retrieve folder path
39,297,801
<p>I have the following code which displays the Windows folder selection window:</p> <pre><code>from comtypes.client import CreateObject shell = CreateObject("Shell.Application") folder = shell.BrowseForFolder(0, "Select a folder", 1) </code></pre> <p>The Microsoft doc doesn't say anything about how to retrieve (the selected) folder path, anyway, a solution exists on the net for VB (for example <a href="http://stackoverflow.com/questions/31904226/shell-application-browseforfolder-how-do-i-get-full-path-of-folder-object">here</a>):</p> <pre><code>path = folder.Self.Path </code></pre> <p>This solution do not translate to comtypes, and a <code>help(folder)</code> do not show any <code>Self</code> property, it seems that <code>BrowseForFolder</code> returns a <code>FOLDER</code> type, but <code>Self</code> is a property of <code>FOLDER2</code> type, any one know why?</p>
0
2016-09-02T17:23:48Z
39,298,285
<p>As said TessellatingHeckler above, it works with win32com:</p> <pre><code>import win32com.client shell = win32com.client.Dispatch("Shell.Application") folder = shell.BrowseForFolder(0, "Now browse...", 1) print(folder.Self.Path) </code></pre> <p>But if you really want to use comtypes, here is a workaround:</p> <pre><code>from comtypes.client import CreateObject shell = CreateObject("Shell.Application") folder = shell.BrowseForFolder(0, "Now browse...", 1) name = folder.Title for item in folder.ParentFolder.Items(): if item.Name == name: print(item.Path) </code></pre>
0
2016-09-02T17:57:50Z
[ "python", "activex", "comtypes" ]
How to skip an unknown number of empty lines before header on pandas.read_csv?
39,297,878
<p>I want to read a dataframe from a csv file where the header is not in the first line. For example:</p> <pre><code>In [1]: import pandas as pd In [2]: import io In [3]: temp=u"""#Comment 1 ...: #Comment 2 ...: ...: #The previous line is empty ...: Header1|Header2|Header3 ...: 1|2|3 ...: 4|5|6 ...: 7|8|9""" In [4]: df = pd.read_csv(io.StringIO(temp), sep="|", comment="#", ...: skiprows=4).dropna() In [5]: df Out[5]: Header1 Header2 Header3 0 1 2 3 1 4 5 6 2 7 8 9 [3 rows x 3 columns] </code></pre> <p>The problem with the above code is that I don't now how many lines will exist before the header, therefore, I cannot use <code>skiprows=4</code> as I did here.</p> <p>I aware I can iterate through the file, as in the question <a href="https://stackoverflow.com/questions/20230083/read-pandas-dataframe-from-csv-beginning-with-non-fix-header">Read pandas dataframe from csv beginning with non-fix header</a>.</p> <p>What I am looking for is a simpler solution, like making <code>pandas.read_csv</code> disregard any empty line and taking the first non-empty line as the header.</p>
1
2016-09-02T17:28:39Z
39,298,213
<p>You need to set <code>skip_blank_lines=True</code></p> <pre><code>df = pd.read_csv(io.StringIO(temp), sep="|", comment="#", skip_blank_lines=True).dropna() </code></pre>
3
2016-09-02T17:52:17Z
[ "python", "csv", "pandas", "file-io", "data-import" ]
confused by tornado.concurrent.Future exception
39,297,897
<p>I'm trying to implement a variant of <a href="http://stackoverflow.com/questions/37849128/tornado-one-handler-blocks-for-another">this question</a> using tornado Futures. The queues a problem, because I don't want to past data being accumulated. IOW, I want the one http request handler to block waiting for result of another that occurs AFTER the original has started.</p> <p>But I think I'm missing a step.</p> <p>My code looks like:</p> <pre><code>Events = dict() class EventHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self, unit): # create future to block on future = tornado.concurrent.Future() # store the future at a place the produce can find it Events[unit] = future # block waiting for the future's response result = yield future.result() # deregister the future Events.pop(unit, None) self.write(result) @tornado.gen.coroutine def post(self, unit): # fetch the corresponding future if there is one future = Events.get(unit, None) if future: # found one, set the result to pass body over future.set_result(self.request.body) else: print('noop') self.write(bytes()) </code></pre> <p>What happens is that I get errors that look like:</p> <pre><code> File "./foo.py", line 44, in get result = yield future.result() File "/usr/lib/python3/dist-packages/tornado/concurrent.py", line 216, in result self._check_done() File "/usr/lib/python3/dist-packages/tornado/concurrent.py", line 294, in _check_done raise Exception("DummyFuture does not support blocking for results") </code></pre> <p>Am I not using the Future correctly? Is there an additional step I need to do in configuring it? Am I supposed to make a subclass that implements that <code>_check_done</code> behavior? Is my assumption that a tornado <code>Future</code> was synonymous with other systems calla a <code>promise</code> incorrect? Is there some different way to do this than just using a future/promise?</p>
1
2016-09-02T17:29:31Z
39,298,214
<p>You need to use</p> <pre><code>result = yield future </code></pre> <p>Not</p> <pre><code>result = yield future.result() </code></pre> <p><code>yield future.result()</code> is actually equivalent to <code>yield &lt;whatever is returned by future.result()&gt;</code>. If the result isn't ready yet, that means that the <code>result()</code> API would have to block (meaning, block the tornado event loop) until the result is ready, and <code>tornado.concurrent.Future</code> doesn't support that. You can only wait for the result using the non-blocking <code>yield future</code> construct.</p>
2
2016-09-02T17:52:26Z
[ "python", "python-3.x", "promise", "tornado", "future" ]
CSV file unread columns
39,297,959
<p>l m trying to get data from CSV file and there are three column ("date",stations","pcp" ) including 41 years data set. l would like to get these data separately.</p> <p>example dataset:</p> <pre><code> date stations pcp 1.01.1979 6 1.071 2.01.1979 6 5.909 3.01.1979 6 9.134 1.01.1979 5 1.229 2.01.1979 5 0.014 3.01.1979 5 3.241 </code></pre> <p>when l run code , l got this output</p> <pre><code>date;stations;pcp None None 2.04.1979;6;0.0 None None 3.04.1979;6;0.0 None None 4.04.1979;6;0.35 None None 5.04.1979;5;0.003 None None </code></pre> <p>date field including all data but stations and pcp fields are "None" how can l solve it?</p> <p>here is my code</p> <pre><code>import csv import numpy as np with open('p2.csv') as csvfile: reader = csv.DictReader(csvfile,fieldnames=("date","stations","pcp"),delimiter=' ', quotechar='|') for row in reader: print(row["date"],row["stations"],row["pcp"]) </code></pre>
1
2016-09-02T17:33:53Z
39,298,206
<p>Your input file (<code>p2.csv</code>):</p> <pre><code>date stations pcp 1.01.1979 6 1.071 2.01.1979 6 5.909 3.01.1979 6 9.134 1.01.1979 5 1.229 2.01.1979 5 0.014 3.01.1979 5 3.241 </code></pre> <p>Your code:</p> <pre><code>import csv import numpy as np with open('p2.csv') as csvfile: reader = csv.DictReader(csvfile,fieldnames=("date","stations","pcp"),delimiter=' ', quotechar='|') for row in reader: print(row["date"],row["stations"],row["pcp"]) </code></pre> <p>Output:</p> <pre><code>date stations pcp 1.01.1979 6 1.071 2.01.1979 6 5.909 3.01.1979 6 9.134 1.01.1979 5 1.229 2.01.1979 5 0.014 3.01.1979 5 3.241 </code></pre> <p>There is a serious problem with your input file. The delimter is not a single space, it's having multiple spaces. </p>
1
2016-09-02T17:51:38Z
[ "python", "csv" ]
Generating 15 minute time interval array in python
39,298,054
<p>I am new to python. I am trying to generate time interval array. for example: <code> time_array = ["2016-09-02T17:30:00Z", "2016-09-02T17:45:00Z", "2016-09-02T18:00:00Z", "2016-09-02T18:15:00Z", "2016-09-02T18:30:00Z", "2016-09-02T18:45:00Z"] </code> 1. It should create the element like above in zulu time till 9 pm everyday. 2. Should generate the elements for next and day after next as well 3. Start time from 7:00 am - Ed time 9:00 pm, if current_time is > start_time then generate 15 min time interval array till 9 pm. and then generate for next day and day + 2. And Interval should be 7:00, 7:15 like that.. not in 7:12, 8:32</p>
2
2016-09-02T17:40:53Z
39,298,331
<p>Looking at the data file, you should use the built in python date-time objects. followed by <code>strftime</code> to format your dates. </p> <p>Broadly you can modify the code below to however many date-times you would like First create a starting date. </p> <pre><code>Today= datetime.datetime.today() </code></pre> <p>Replace 100 with whatever number of time intervals you want. </p> <pre><code>date_list = [Today + datetime.timedelta(minutes=15*x) for x in range(0, 100)] </code></pre> <p>Finally, format the list in the way that you would like, using code like that below. </p> <pre><code>datetext=[x.strftime('%Y-%m-%d T%H:%M Z') for x in date_list] </code></pre>
3
2016-09-02T18:00:25Z
[ "python", "arrays", "python-2.7" ]
Generating 15 minute time interval array in python
39,298,054
<p>I am new to python. I am trying to generate time interval array. for example: <code> time_array = ["2016-09-02T17:30:00Z", "2016-09-02T17:45:00Z", "2016-09-02T18:00:00Z", "2016-09-02T18:15:00Z", "2016-09-02T18:30:00Z", "2016-09-02T18:45:00Z"] </code> 1. It should create the element like above in zulu time till 9 pm everyday. 2. Should generate the elements for next and day after next as well 3. Start time from 7:00 am - Ed time 9:00 pm, if current_time is > start_time then generate 15 min time interval array till 9 pm. and then generate for next day and day + 2. And Interval should be 7:00, 7:15 like that.. not in 7:12, 8:32</p>
2
2016-09-02T17:40:53Z
39,298,362
<p>Here's a generic <code>datetime_range</code> for you to use.</p> <h3>Code</h3> <pre><code>from datetime import datetime, timedelta def datetime_range(start, end, delta): current = start while current &lt; end: yield current current += delta dts = [dt.strftime('%Y-%m-%d T%H:%M Z') for dt in datetime_range(datetime(2016, 9, 1, 7), datetime(2016, 9, 1, 9+12), timedelta(minutes=15))] print(dts) </code></pre> <h3>Output</h3> <blockquote> <p>['2016-09-01 T07:00 Z', '2016-09-01 T07:15 Z', '2016-09-01 T07:30 Z', '2016-09-01 T07:45 Z', '2016-09-01 T08:00 Z', '2016-09-01 T08:15 Z', '2016-09-01 T08:30 Z', '2016-09-01 T08:45 Z', '2016-09-01 T09:00 Z', '2016-09-01 T09:15 Z', '2016-09-01 T09:30 Z', '2016-09-01 T09:45 Z' ... ]</p> </blockquote>
1
2016-09-02T18:02:54Z
[ "python", "arrays", "python-2.7" ]
Generating 15 minute time interval array in python
39,298,054
<p>I am new to python. I am trying to generate time interval array. for example: <code> time_array = ["2016-09-02T17:30:00Z", "2016-09-02T17:45:00Z", "2016-09-02T18:00:00Z", "2016-09-02T18:15:00Z", "2016-09-02T18:30:00Z", "2016-09-02T18:45:00Z"] </code> 1. It should create the element like above in zulu time till 9 pm everyday. 2. Should generate the elements for next and day after next as well 3. Start time from 7:00 am - Ed time 9:00 pm, if current_time is > start_time then generate 15 min time interval array till 9 pm. and then generate for next day and day + 2. And Interval should be 7:00, 7:15 like that.. not in 7:12, 8:32</p>
2
2016-09-02T17:40:53Z
39,298,434
<p>I'll provide a solution that does <em>not</em> handle timezones, since the problem is generating dates and times and you can set the timezone afterwards however you want.</p> <p>You have a starting date and starting and ending time (for each day), plus an interval (in minutes) for these datetimes. The idea is to create a <code>timedelta</code> object that represent the time interval and repeatedly update the datetime until we reach the ending time, then we advance by one day and reset the time to the initial one and repeat.</p> <p>A simple implementation could be:</p> <pre><code>def make_dates(start_date, number_of_days, start_time, end_time, interval, timezone): if isinstance(start_date, datetime.datetime): start_date = start_date.date() start_date = datetime.datetime.combine(start_date, start_time) cur_date = start_date num_days_passed = 0 step = datetime.timedelta(seconds=interval*60) while True: new_date = cur_date + step if new_date.time() &gt; end_time: num_days_passed += 1 if num_days_passed &gt; number_of_days: break new_date = start_date + datetime.timedelta(days=num_days_passed) ret_date, cur_date = cur_date, new_date yield ret_date In [31]: generator = make_dates(datetime.datetime.now(), 3, datetime.time(hour=17), datetime.time(hour=19), 15, None) In [32]: next(generator) Out[32]: datetime.datetime(2016, 9, 2, 17, 0) In [33]: next(generator) Out[33]: datetime.datetime(2016, 9, 2, 17, 15) In [34]: list(generator) Out[34]: [datetime.datetime(2016, 9, 2, 17, 30), datetime.datetime(2016, 9, 2, 17, 45), datetime.datetime(2016, 9, 2, 18, 0), datetime.datetime(2016, 9, 2, 18, 15), datetime.datetime(2016, 9, 2, 18, 30), datetime.datetime(2016, 9, 2, 18, 45), datetime.datetime(2016, 9, 2, 19, 0), datetime.datetime(2016, 9, 3, 17, 0), datetime.datetime(2016, 9, 3, 17, 15), datetime.datetime(2016, 9, 3, 17, 30), datetime.datetime(2016, 9, 3, 17, 45), datetime.datetime(2016, 9, 3, 18, 0), datetime.datetime(2016, 9, 3, 18, 15), datetime.datetime(2016, 9, 3, 18, 30), datetime.datetime(2016, 9, 3, 18, 45), datetime.datetime(2016, 9, 3, 19, 0), datetime.datetime(2016, 9, 4, 17, 0), datetime.datetime(2016, 9, 4, 17, 15), datetime.datetime(2016, 9, 4, 17, 30), datetime.datetime(2016, 9, 4, 17, 45), datetime.datetime(2016, 9, 4, 18, 0), datetime.datetime(2016, 9, 4, 18, 15), datetime.datetime(2016, 9, 4, 18, 30), datetime.datetime(2016, 9, 4, 18, 45), datetime.datetime(2016, 9, 4, 19, 0), datetime.datetime(2016, 9, 5, 17, 0), datetime.datetime(2016, 9, 5, 17, 15), datetime.datetime(2016, 9, 5, 17, 30), datetime.datetime(2016, 9, 5, 17, 45), datetime.datetime(2016, 9, 5, 18, 0), datetime.datetime(2016, 9, 5, 18, 15), datetime.datetime(2016, 9, 5, 18, 30), datetime.datetime(2016, 9, 5, 18, 45)] </code></pre> <p>Once you have the datetimes you can use the <a href="https://docs.python.org/3.5/library/datetime.html#datetime.datetime.strftime" rel="nofollow"><code>strftime</code></a> method to convert them to strings.</p>
2
2016-09-02T18:07:11Z
[ "python", "arrays", "python-2.7" ]
Generating 15 minute time interval array in python
39,298,054
<p>I am new to python. I am trying to generate time interval array. for example: <code> time_array = ["2016-09-02T17:30:00Z", "2016-09-02T17:45:00Z", "2016-09-02T18:00:00Z", "2016-09-02T18:15:00Z", "2016-09-02T18:30:00Z", "2016-09-02T18:45:00Z"] </code> 1. It should create the element like above in zulu time till 9 pm everyday. 2. Should generate the elements for next and day after next as well 3. Start time from 7:00 am - Ed time 9:00 pm, if current_time is > start_time then generate 15 min time interval array till 9 pm. and then generate for next day and day + 2. And Interval should be 7:00, 7:15 like that.. not in 7:12, 8:32</p>
2
2016-09-02T17:40:53Z
39,298,697
<p>Here is an example using an arbitrary date time</p> <pre><code>from datetime import datetime start = datetime(1900,1,1,0,0,0) end = datetime(1900,1,2,0,0,0) </code></pre> <p>Now you need to get the timedelta (the difference between two dates or times.) between the <code>start</code> and <code>end</code></p> <pre><code>seconds = (end - start).total_seconds() </code></pre> <p>Define the 15 minutes interval</p> <pre><code>from datetime import timedelta step = timedelta(minutes=15) </code></pre> <p>Iterate over the range of seconds, with step of time delta of 15 minutes (900 seconds) and sum it to <code>start</code>.</p> <pre><code>array = [] for i in range(0, int(seconds), int(step.total_seconds())): array.append(start + timedelta(seconds=i)) print array [datetime.datetime(1900, 1, 1, 0, 0), datetime.datetime(1900, 1, 1, 0, 15), datetime.datetime(1900, 1, 1, 0, 30), datetime.datetime(1900, 1, 1, 0, 45), datetime.datetime(1900, 1, 1, 1, 0), ... </code></pre> <p>At the end you can format the datetime objects to str representation.</p> <pre><code>array = [i.strftime('%Y-%m-%d %H:%M%:%S') for i in array] print array ['1900-01-01 00:00:00', '1900-01-01 00:15:00', '1900-01-01 00:30:00', '1900-01-01 00:45:00', '1900-01-01 01:00:00', ... </code></pre> <p>You can format datetime object at first iteration. But it may hurt your eyes</p> <pre><code>array.append((start + timedelta(seconds=i)).strftime('%Y-%m-%d %H:%M%:%S')) </code></pre>
1
2016-09-02T18:26:39Z
[ "python", "arrays", "python-2.7" ]
Generating 15 minute time interval array in python
39,298,054
<p>I am new to python. I am trying to generate time interval array. for example: <code> time_array = ["2016-09-02T17:30:00Z", "2016-09-02T17:45:00Z", "2016-09-02T18:00:00Z", "2016-09-02T18:15:00Z", "2016-09-02T18:30:00Z", "2016-09-02T18:45:00Z"] </code> 1. It should create the element like above in zulu time till 9 pm everyday. 2. Should generate the elements for next and day after next as well 3. Start time from 7:00 am - Ed time 9:00 pm, if current_time is > start_time then generate 15 min time interval array till 9 pm. and then generate for next day and day + 2. And Interval should be 7:00, 7:15 like that.. not in 7:12, 8:32</p>
2
2016-09-02T17:40:53Z
39,303,050
<p>This is the final script I have written based on the answers posted on my question:</p> <pre><code>from datetime import datetime from datetime import timedelta import calendar current_utc = datetime.utcnow().strftime("%Y-%m-%d-%H-%M-%S") current_year = int(current_utc.split("-")[0]) current_month = int(current_utc.split("-")[1]) current_date = int(current_utc.split("-")[2]) current_hour = int(current_utc.split("-")[3]) current_min = int(current_utc.split("-")[4]) current_sec = int(current_utc.split("-")[5]) #### To make minutes round to quarter #### min_range_1 = range(1,16) min_range_2 = range(16,31) min_range_3 = range(31,46) min_range_4 = range(46,60) if current_min in min_range_1: current_min = 15 elif current_min in min_range_2: current_min = 30 elif current_min in min_range_3: current_min = 45 elif current_min in min_range_4: current_hour = current_hour + 1 current_min = 0 else: print("Please check current minute.") current_sec = 00 date_range_31 = range(1,32) date_range_30 = range(1,31) month_days_31 = [1,3,5,7,8,10,12] month_days_30 = [4,6,9,11] if current_month in month_days_31: if current_date == 31: next_day_month = current_month + 1 next_day_date = 1 else: next_day_month = current_month next_day_date = current_date elif current_month == 2: if calendar.isleap(current_year): if current_date == 29: next_day_month = current_month + 1 next_day_date = 1 else: next_day_month = current_month next_day_date = current_date else: if current_date == 28: next_day_month = current_month + 1 next_day_date = 1 else: next_day_month = current_month next_day_date = current_date elif current_month in month_days_30: if current_date == 30: next_day_month = current_month + 1 next_day_date = 1 else: next_day_month = current_month next_day_date = current_date else: print("Please check the current month and date to procedd further.") if current_hour &lt; 11: current_hour = 11 current_min = 15 next_day_date = current_date + 1 current_start = datetime(current_year,current_month,current_date,current_hour,current_min,current_sec) current_end = datetime(current_year,current_month,current_date,21,15,0) next_day_start = datetime(current_year,next_day_month,next_day_date,11,15,0) next_day_end = datetime(current_year,next_day_month,next_day_date,21,15,0) current_seconds = (current_end - current_start).total_seconds() next_day_seconds = (next_day_end - next_day_start).total_seconds() step = timedelta(minutes=15) current_day_array = [] next_day_array = [] for i in range(0, int(current_seconds), int(step.total_seconds())): current_day_array.append(current_start + timedelta(seconds=i)) for i in range(0, int(next_day_seconds), int(step.total_seconds())): current_day_array.append(next_day_start + timedelta(seconds=i)) current_day_array = [i.strftime('%Y-%m-%dT%H:%M%:%SZ') for i in current_day_array] print current_day_array </code></pre> <p>Which produces the following output:</p> <pre><code>['2016-09-03T11:15:00Z', '2016-09-03T11:30:00Z', '2016-09-03T11:45:00Z', '2016-09-03T12:00:00Z', '2016-09-03T12:15:00Z', '2016-09-03T12:30:00Z', '2016-09-03T12:45:00Z', '2016-09-03T13:00:00Z', '2016-09-03T13:15:00Z', '2016-09-03T13:30:00Z', '2016-09-03T13:45:00Z', '2016-09-03T14:00:00Z', '2016-09-03T14:15:00Z', '2016-09-03T14:30:00Z', '2016-09-03T14:45:00Z', '2016-09-03T15:00:00Z', '2016-09-03T15:15:00Z', '2016-09-03T15:30:00Z', '2016-09-03T15:45:00Z', '2016-09-03T16:00:00Z', '2016-09-03T16:15:00Z', '2016-09-03T16:30:00Z', '2016-09-03T16:45:00Z', '2016-09-03T17:00:00Z', '2016-09-03T17:15:00Z', '2016-09-03T17:30:00Z', '2016-09-03T17:45:00Z', '2016-09-03T18:00:00Z', '2016-09-03T18:15:00Z', '2016-09-03T18:30:00Z', '2016-09-03T18:45:00Z', '2016-09-03T19:00:00Z', '2016-09-03T19:15:00Z', '2016-09-03T19:30:00Z', '2016-09-03T19:45:00Z', '2016-09-03T20:00:00Z', '2016-09-03T20:15:00Z', '2016-09-03T20:30:00Z', '2016-09-03T20:45:00Z', '2016-09-03T21:00:00Z', '2016-09-04T11:15:00Z', '2016-09-04T11:30:00Z', '2016-09-04T11:45:00Z', '2016-09-04T12:00:00Z', '2016-09-04T12:15:00Z', '2016-09-04T12:30:00Z', '2016-09-04T12:45:00Z', '2016-09-04T13:00:00Z', '2016-09-04T13:15:00Z', '2016-09-04T13:30:00Z', '2016-09-04T13:45:00Z', '2016-09-04T14:00:00Z', '2016-09-04T14:15:00Z', '2016-09-04T14:30:00Z', '2016-09-04T14:45:00Z', '2016-09-04T15:00:00Z', '2016-09-04T15:15:00Z', '2016-09-04T15:30:00Z', '2016-09-04T15:45:00Z', '2016-09-04T16:00:00Z', '2016-09-04T16:15:00Z', '2016-09-04T16:30:00Z', '2016-09-04T16:45:00Z', '2016-09-04T17:00:00Z', '2016-09-04T17:15:00Z', '2016-09-04T17:30:00Z', '2016-09-04T17:45:00Z', '2016-09-04T18:00:00Z', '2016-09-04T18:15:00Z', '2016-09-04T18:30:00Z', '2016-09-04T18:45:00Z', '2016-09-04T19:00:00Z', '2016-09-04T19:15:00Z', '2016-09-04T19:30:00Z', '2016-09-04T19:45:00Z', '2016-09-04T20:00:00Z', '2016-09-04T20:15:00Z', '2016-09-04T20:30:00Z', '2016-09-04T20:45:00Z', '2016-09-04T21:00:00Z'] </code></pre>
0
2016-09-03T03:47:12Z
[ "python", "arrays", "python-2.7" ]
I'm trying to enhance the contrast of image using following code
39,298,057
<p>Here i'm trying to: - Apply Adaptive filtering to image . - Enhance the contrast of image . my code is as follow : </p> <pre><code>#!/usr/bin/python import cv2 import numpy as np import PIL from PIL import ImageFilter from matplotlib import pyplot as plt img = cv2.imread('Crop.jpg',0) cv2.imshow('original',img) img = cv2.medianBlur(img,5) th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\ cv2.THRESH_BINARY,11,2) cv2.imshow('image',th3) th3 = th3.filter(ImageFilter.SMOOTH) cv2.imshow('image',th3) cv2.waitKey(0) cv2.destroyAllWindows() </code></pre> <p>I am getting following Error :</p> <blockquote> <p>Traceback (most recent call last):</p> <p>File "./adaptive.py", line 22, in </p> <p>th3 = th3.filter(ImageFilter.SMOOTH)</p> <p>AttributeError: 'numpy.ndarray' object has no attribute 'filter</p> </blockquote>
0
2016-09-02T17:41:08Z
39,299,335
<p>You may confuse with <a href="http://docs.opencv.org/2.4/modules/imgproc/doc/filtering.html?highlight=.smooth#cv.Smooth" rel="nofollow">cv.Smooth</a></p>
0
2016-09-02T19:14:53Z
[ "python", "image", "numpy" ]
Linking a Kivy Button to Function
39,298,059
<p>There is something in kivy I do not understand, and am hoping that someone could shed light. I have done a lot of reading in this topic but it just doesn't seem to be connecting in my head.</p> <p>My issue comes from linking a function to a kivy button. Right now I am trying to learn how to do a simple function:</p> <pre><code>def Math(): print 1+1 </code></pre> <p>What I would like to do something more complex:</p> <pre><code>def Math(a,b): print a^2 + b^2 </code></pre> <p>Where <code>a</code> and <code>b</code> are input labels from kivy, and upon clicking a button the answer will be printed.</p> <p>This is what I have so far:</p> <pre><code>from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition from kivy.uix.widget import Widget from kivy.uix.floatlayout import FloatLayout #######``Logics``####### class Math(FloatLayout): def add(self): print 1+1 #######``Windows``####### class MainScreen(Screen): pass class AnotherScreen(Screen): pass class ScreenManagement(ScreenManager): pass presentation = Builder.load_file("GUI_Style.kv") class MainApp(App): def build(self): return presentation if __name__ == "__main__": MainApp().run() </code></pre> <p>This is my kivy language file:</p> <pre><code>import NoTransition kivy.uix.screenmanager.NoTransition ScreenManagement: transition: NoTransition() MainScreen: AnotherScreen: &lt;MainScreen&gt;: name: "main" FloatLayout: Button: on_release: app.root.current = "other" text: "Next Screen" font_size: 50 color: 0,1,0,1 font_size: 25 size_hint: 0.3,0.2 pos_hint: {"right":1, "top":1} &lt;AnotherScreen&gt;: name: "other" FloatLayout: Button: color: 0,1,0,1 font_size: 25 size_hint: 0.3,0.2 text: "add" pos_hint: {"x":0, "y":0} on_release: root.add Button: color: 0,1,0,1 font_size: 25 size_hint: 0.3,0.2 text: "Back Home" on_release: app.root.current = "main" pos_hint: {"right":1, "top":1} </code></pre>
2
2016-09-02T17:41:14Z
39,299,585
<pre><code>&lt;AnotherScreen&gt;: name: "other" FloatLayout: Button: ... on_release: root.add &lt;-- here *root* evaluates to the top widget in the rule. </code></pre> <p>Which is an AnotherScreen instance, but it doesn't have an <code>add</code> method.</p> <pre><code>class Math(FloatLayout): def add(self): print 1+1 </code></pre> <p>Here you have declared a Math class by inheriting from the <code>FloatLayout</code>, which is a uix component -a widget-. And you defined a method on this class <code>add</code>. Still you haven't used it. In the kv file you used <code>FloatLayout</code>.</p> <p>Now in order for you to access a function in kv, most of the time you'll acces it as a method of a uix component, by using either <code>root</code>/<code>self</code> or <code>app</code>, you can also import it e.g: </p> <pre><code>#: import get_color_from_hex kivy.utils.get_color_from_hex &lt;ColoredWidget&gt;: canvas: Color: rgba: get_color_from_hex("DCDCDC") Rectangle: size: self.size pos: self.pos </code></pre> <p>So you can't do it like this:</p> <pre><code>&lt;AnotherScreen&gt;: name: "other" Math: id: math_layout Button: ... on_release: math_layout.add() </code></pre> <p>or like this:</p> <pre><code>class AnotherScreen(Screen): def add(self): print(1+1) </code></pre> <p>If you still have problems conserning this topic, i'll be glad to provide more help .</p>
0
2016-09-02T19:34:37Z
[ "python", "kivy", "kivy-language" ]
Formatting json strings in Python
39,298,089
<p>I have a query that runs and creates a dataframe like below:</p> <pre><code>Group Hour G1 0 G1 4 G2 1 G3 5 </code></pre> <p>I then write the dataframe to a json file using</p> <pre><code>out = df1.to_json(orient='records')[1:-1].replace('},{', '} {') </code></pre> <p>Currently my output looks like</p> <pre><code>{"Group":"G1","Hour":0} {"Group":"G2","Hour":4} {"Group":"G2","Hour":1} </code></pre> <p>It is a continuous stream of lines. I am trying to make each json document to be in a separate line like below:</p> <pre><code>{"Group":"G1","Hour":0} {"Group":"G2","Hour":4} {"Group":"G2","Hour":1} </code></pre> <p>Not sure whether there is a way to achieve this in Python. Any help would be appreciated.</p>
-1
2016-09-02T17:43:37Z
39,298,130
<p>Just change the <code>.replace('},{', '} {')</code> part to <code>.replace('},{', '}\n{')</code>?</p>
0
2016-09-02T17:46:21Z
[ "python", "json", "pandas" ]
Django: Create new data sets automatically
39,298,091
<p>I have three models. <code>Question</code>, <code>Person</code> and <code>Response</code>. Every person can only have one answer or response to a question. Because of that, I use <code>unique_together</code>:</p> <pre><code>class Meta: unique_together = (("question", "person"),) </code></pre> <p>So, my goal is that I have to each question one answer from every person in my database.</p> <p>I'd like to have that I can choose "Agree"/"Disagree"/"Neutral" in the admin interface to each question and for every person. But I don't want to create all those question/person-pairs.</p> <p>I want that if I create a new question:</p> <ul> <li>for every person: create -> new <code>Response</code> object with the new question and that I am able to set "Agree"/"Disagree"/"Neutral" in the admin interace then for every question/person-pair</li> </ul> <p>And if I create a new person:</p> <ul> <li>for every question: create -> new <code>Response</code> object with the new person and I will add the responses from the person in the admin interface again.</li> </ul> <p>But how do I do this that all possible Question/Person pairs are created automatically if I add a new question or person?</p> <p>Here for your information my models. Thanks a lot for your help!</p> <pre><code>from django.db import models class Question(models.Model): these_title = models.CharField(max_length=40) these_text = models.TextField(max_length=200) class Person(models.Model): name = models.CharField(max_length=50) information = models.TextField(max_length=300) website = models.URLField(blank=True) class Response(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) possible_responses = ( (1, 'Agree'), (0, 'Neutral'), (2, 'Disagree'), ) response = models.IntegerField( choices=possible_responses, blank=True, null=True, ) class Meta: unique_together = (("question", "person"),) </code></pre>
0
2016-09-02T17:43:50Z
39,299,112
<p>Use a post save signal. Documentation here: <a href="https://docs.djangoproject.com/en/1.10/ref/signals/" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/signals/</a></p>
0
2016-09-02T18:59:00Z
[ "python", "django", "django-models", "django-admin" ]
Pandas dataframe - data type issue
39,298,108
<p>I am trying to create a <code>pd.DataFrame</code>, but I am having trouble getting the data type correct. I have two <code>numpy</code> arrays that are type <code>float</code>.</p> <p>They were created from a list of coordinates (x &amp; y) as seen here:</p> <pre><code># Take coordinates from list and convert to a numpy array x_vector = np.asarray(x_list, dtype=float) y_vector = np.asarray(y_list, dtype=float) </code></pre> <p>For reference here is a sample of what <code>x_vector</code> looks like:</p> <pre><code>[-2248925.48185815 -2248925.48185815 -2248080.13621823 -2262432.04991849 -2250570.32692157 -2237312.76315587 -2237312.76315587 -2245650.16260083 -2245650.16260083 -2249323.93572129 -2247050.83128422 -2253151.83634956] </code></pre> <p>I am pleased with the formatting here, the issue arises when I try to add <code>x_vector</code> and <code>y_vector</code> to the pandas data frame. </p> <p>My logic is that I have 201 records of lat/lons so my <code>index</code> equals that, then I add <code>columns</code> corresponding to my data, finally I set the <code>dtype</code> to match my coordinates (float).</p> <p>Here is my code:</p> <pre><code>df = pd.DataFrame(index=range(1, 202, 1), columns=['lat', 'lon', 'ws_daily_max'], dtype=float) df['lat'] = y_vector df['lon'] = x_vector </code></pre> <p>However when I print <code>df</code> to the console, I get these values where the decimal place shifted significantly. What went wrong, why did the lat/lon values change? I was expecting them to be the same as the float values above, i.e. (<code>-2248925.48185815</code>)?</p> <p><code>index lat lon ws_daily_max 1 1.895464e+06 -2.248925e+06 NaN 2 1.895464e+06 -2.248925e+06 NaN</code></p> <p>I am truly confused as to what happened. No error message printed, but this is <em>not</em> the result I was expecting. Any clarity as to why and how to fix this would be greatly appreciated.</p> <p>Help me, StackExchange. You're my only hope.</p>
-1
2016-09-02T17:45:05Z
39,298,302
<p>This is the scientific notation of the same number. 1.895464e+06 means 1.895464*10^6 = 1895465. So the decimal place did not shift, just the representation. If you want to change the looks of the numbers, look at <a href="http://pandas.pydata.org/pandas-docs/stable/options.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/options.html</a>. I hope this helps.</p>
3
2016-09-02T17:58:49Z
[ "python", "pandas", "numpy" ]
Boofuzz Doesn't Restart Process After Crash
39,298,133
<p>I'm learning how to fuzz using boofuzz. I have everything setup on a Windows 7 VM. The target is the Vulnserver application. Since I know the <code>TRUN</code>, <code>GMON</code>, and <code>KSTET</code> commands are vulnerable, I put these commands in a <code>s_group</code> list. I expect the <code>vulnserver.exe</code> process to crash on the <code>TRUN</code> command, restart, and then continue testing the other commands. Below is the boofuzz script I used.</p> <pre><code>#!/usr/bin/python from boofuzz import * from boofuzz import pedrpc host = "172.16.37.201" port = 9999 # Define request s_initialize("Vulnserver") s_group("verbs", values=["TRUN", "GMON", "KSTET"]) if s_block_start("test", group="verbs"): s_delim(" ") s_string("AAA") s_string("\r\n") s_block_end("test") # Define Session logger = FuzzLogger(fuzz_loggers=[FuzzLoggerText()]) session = sessions.Session(log_level=10, sleep_time=0.03, fuzz_data_logger=logger) connection = SocketConnection(host, port, proto="tcp") target = sessions.Target(connection) target.procmon = pedrpc.Client(host, 26002) target.procmon_options = { "proc_name":"vulnserver.exe", "stop_commands":['wmic process where (name="vulnserver.exe") delete'], "start_commands":['C:\\Temp\\vulnserver.exe 9999'], } session.add_target(target) session.connect(s_get("Vulnserver")) session.fuzz() </code></pre> <p>After starting <code>vulnserver.exe</code>, I run my boofuzz script and get the following error:</p> <pre><code>..... +0c: 41414141 (1094795585) -&gt; N/A +10: 41414141 (1094795585) -&gt; N/A +14: 41414141 (1094795585) -&gt; N/A disasm around: 0x41414141 Unable to disassemble SEH unwind: ffffffff -&gt; ntdll.dll:774d61a5 mov edi,edi [2016-09-02 13:24:06,178] Test Case: 53 [2016-09-02 13:24:06,178] Info: primitive name: None, type: String, default value: AAA [2016-09-02 13:24:06,178] Info: Test case 53 of 8352 for this node. 53 of 8352 overall. Traceback (most recent call last): File "auto.py", line 34, in &lt;module&gt; session.fuzz() File "C:\Python27\lib\site-packages\boofuzz\sessions.py", line 414, in fuzz self._fuzz_current_case(*fuzz_args) File "C:\Python27\lib\site-packages\boofuzz\sessions.py", line 846, in _fuzz_current_case target.open() File "C:\Python27\lib\site-packages\boofuzz\sessions.py", line 71, in open self._target_connection.open() File "C:\Python27\lib\site-packages\boofuzz\socket_connection.py", line 118, in open self._sock.connect((self.host, self.port)) File "C:\Python27\lib\socket.py", line 228, in meth return getattr(self._sock,name)(*args) socket.error: [Errno 10061] No connection could be made because the target machine actively refused it </code></pre> <p>The error indicates that boofuzz did not restart the <code>vulnserver.exe</code> process. Below is the output from <code>process_monitor.py</code> if that helps.</p> <pre><code>C:\Tools\boofuzz&gt;python process_monitor.py --crash_bin "crash.bin" --proc_name "vulnserver.exe" --port 26002 [01:23.48] Process Monitor PED-RPC server initialized: [01:23.48] crash file: C:\Tools\boofuzz\crash.bin [01:23.48] # records: 0 [01:23.48] proc name: None [01:23.48] log level: 1 [01:23.48] awaiting requests... [01:24.01] updating target process name to 'vulnserver.exe' [01:24.01] updating stop commands to: ['wmic process where (name="vulnserver.exe") delete'] [01:24.01] updating start commands to: ['C:\\Temp\\vulnserver.exe 9999'] [01:24.01] debugger thread-1472837041 looking for process name: vulnserver.exe [01:24.01] debugger thread-1472837041 found match on pid 1060 [01:24.06] debugger thread-1472837041 caught access violation: '[INVALID]:41414141 Unable to disassemble at 41414141 from thread 1904 caused access violation' [01:24.06] debugger thread-1472837041 exiting [01:24.06] debugger thread-1472837046 looking for process name: vulnserver.exe </code></pre> <p>Thanks!</p>
3
2016-09-02T17:46:33Z
39,311,029
<h2>TL;DR</h2> <p>The failure to restart is a result of a series of bugs. Run <code>pip install --upgrade boofuzz</code> to get <a href="https://pypi.python.org/pypi/boofuzz/0.0.5" rel="nofollow">v0.0.5</a> or later, or pull down the latest code from <a href="https://github.com/jtpereyda/boofuzz/" rel="nofollow">Github</a>.</p> <h2>process_monitor bug</h2> <p>The key issue is that failures detected by procmon were being logged as info, not failures, meaning that a restart was not triggered. <a href="https://github.com/jtpereyda/boofuzz/pull/83" rel="nofollow">Fix PR</a>.</p> <h2>boofuzz bug</h2> <p>This line:</p> <pre><code>socket.error: [Errno 10061] No connection could be made because the target machine actively refused it </code></pre> <p>hints that the application under test most likely crashed. Boofuzz should handle this instead of crashing. This issue has been <a href="https://github.com/jtpereyda/boofuzz/issues/78" rel="nofollow">reported</a> and <a href="https://github.com/jtpereyda/boofuzz/pull/82" rel="nofollow">fixed</a>.</p> <h2>Other process_monitor bug</h2> <p>Notice in your <code>process_monitor.py</code> output the line:</p> <pre><code>[01:23.48] proc name: None </code></pre> <p>Proc name is not getting set! The error is in <code>process_monitor.py</code> line 368:</p> <pre><code>if opt in ("-p", "--proc_Name"): #oops! </code></pre> <p>It should be <code>--proc_name</code> not <code>--proc_Name</code>!</p> <p>This issue has been <a href="https://github.com/jtpereyda/boofuzz/pull/80" rel="nofollow">fixed</a> in the latest code. But a workaround would be to use the shortname <code>-p</code> instead of <code>--proc_name</code>.</p>
0
2016-09-03T20:24:03Z
[ "python", "fuzzing" ]
Stop the thread from inside the target function?
39,298,143
<p>Is there a way that I can stop the thread after few seconds (INTERNALLY)</p> <pre><code>t1 = Thread(target=call_script1, args=()) t2 = Thread(target=call_script2, args=()) t3 = Thread(target=call_script3, args=()) t1.start() t2.start() t3.start() t1.join() t2.join() t3.join() </code></pre> <p>The Main program waits until thread returns. I would like to know if there is a way - when I spawn a thread - say t2, it targets a function - call_script2. Lets say that function takes like 5 seconds to run completely. I would like to know if I can return the thread say like after 3 seconds.</p> <p>The ability of the thread to return after 3 seconds should be inside the call_script2 function. I believe having stop_event.wait(3) in the main thread does not work.</p> <p>call_script2 function looks something like this.</p> <pre><code>def InterfaceThread2(): a = 1; d = 2 i = 1 while i ==1: #ser = serial.Serial(3, 115200) if ser.isOpen(): ser.write('\x5A\x03\x02\x00\x02\x07') a = ser.read(7) #### THIS COMMAND WAITS UNTIL IT RECEIVES DATA FROM MCU ## This usually happens in 100ms in theory. If it is taking like more than 100ms -for safety say I will wait for three seconds and if it did not respond back ## I want to stop the thread and popup an error message. # Tell the GUI about the Information wx.CallAfter(pub.sendMessage, "APP_EVENT2", arg1 = a, arg2 = d) print "hello" time.sleep(1) i = i+1 </code></pre>
0
2016-09-02T17:47:18Z
39,298,705
<p>The <a href="https://docs.python.org/3/library/threading.html#threading.Thread" rel="nofollow"><code>Thread.join</code></a> method has an optional <code>timeout</code> parameter.</p> <pre><code># block until thread ``t`` completes, or just wait 3 seconds t.join(3) </code></pre> <p>If you want the target function to handle this logic of timing out, I suggest writing a wrapper to spawn a new thread, make the call, then join with a 3-second timeout.</p> <pre><code>from threading import Thread import time def counter(limit): for i in range(limit): print(i) time.sleep(0.1) timeout = 3 def wrapper(*args, **kwargs): t = Thread(target=counter, args=args, kwargs=kwargs) t.daemon = True t.start() t.join(timeout) t = Thread(target=wrapper, args=(100,)) t.start() t.join() </code></pre> <p>Note that this doesn't actually kill the subthread until the main process dies. Killing a thread without knowing what it's doing inside could cause all sorts of mess.</p> <p>If you can change the code of the original functions, you can have them periodically poll to check if anyone wants them dead.</p> <p>Edit: Looks like I somewhat misunderstood the question. It was more about how to use PySerial to share 1 open <code>Serial</code> object across 3 workers, with a timeout on reads from the serial port.</p>
0
2016-09-02T18:27:23Z
[ "python", "multithreading" ]
Stop the thread from inside the target function?
39,298,143
<p>Is there a way that I can stop the thread after few seconds (INTERNALLY)</p> <pre><code>t1 = Thread(target=call_script1, args=()) t2 = Thread(target=call_script2, args=()) t3 = Thread(target=call_script3, args=()) t1.start() t2.start() t3.start() t1.join() t2.join() t3.join() </code></pre> <p>The Main program waits until thread returns. I would like to know if there is a way - when I spawn a thread - say t2, it targets a function - call_script2. Lets say that function takes like 5 seconds to run completely. I would like to know if I can return the thread say like after 3 seconds.</p> <p>The ability of the thread to return after 3 seconds should be inside the call_script2 function. I believe having stop_event.wait(3) in the main thread does not work.</p> <p>call_script2 function looks something like this.</p> <pre><code>def InterfaceThread2(): a = 1; d = 2 i = 1 while i ==1: #ser = serial.Serial(3, 115200) if ser.isOpen(): ser.write('\x5A\x03\x02\x00\x02\x07') a = ser.read(7) #### THIS COMMAND WAITS UNTIL IT RECEIVES DATA FROM MCU ## This usually happens in 100ms in theory. If it is taking like more than 100ms -for safety say I will wait for three seconds and if it did not respond back ## I want to stop the thread and popup an error message. # Tell the GUI about the Information wx.CallAfter(pub.sendMessage, "APP_EVENT2", arg1 = a, arg2 = d) print "hello" time.sleep(1) i = i+1 </code></pre>
0
2016-09-02T17:47:18Z
39,298,758
<p>I think you can get the behavior you want by using the <code>timeout</code> parameter available on the <code>serial.Serial()</code> constructor. Additionally, you'll need to protect your interactions with the <code>Serial</code> instance with a <code>threading.Lock()</code>, so that your threads don't step on each other as they read/write data:</p> <pre><code>ser = serial.Serial(..., timeout=3, ...) lock = Threading.Lock() def call_script1(): a = 1 d = 2 i = 1 while i == 1: # Lock is acquired here with lock: if ser.isOpen(): ser.write('\x5A\x03\x02\x00\x02\x07') a = ser.read(7) if len(a) != 7: # We didn't get all the bytes we wanted, a timeout # must have occurred. print("Only read {} bytes!".format(len(a))) # Maybe exit or throw an exception? # Lock is released here. # Tell the GUI about the Information wx.CallAfter(pub.sendMessage, "APP_EVENT2", arg1 = a, arg2 = d) print "hello" time.sleep(1) i = i+1 def call_script2(): while i == 1: with lock: if ser.isOpen(): # Do whatever def call_script3(): while i == 1: with lock: if ser.isOpen(): # Do whatever t1 = Thread(target=call_script1, args=()) t2 = Thread(target=call_script2, args=()) t3 = Thread(target=call_script3, args=()) t1.start() t2.start() t3.start() t1.join() t2.join() t3.join() </code></pre>
1
2016-09-02T18:32:04Z
[ "python", "multithreading" ]
Hello! I am trying to set a line of a text file to a variable
39,298,160
<p>I used an if statement to see if the variable assignment worked but I think I am formatting something wrong. I tried this with and without the \n. Any help would be greatly appreciated.</p> <pre><code>lines=[] #creates a list file = open("gmail.txt", "r") #opens the text file for line in file: lines.append(line) #adds each line to list file.close() x=lines[0] #sets first item in list equal to x print(x) if x=="Hey \n": #if statement attempt to check if variable assignment worked print("good!") else: print("bad") </code></pre> <p>When running the code I get the following output</p> <pre><code>Hey bad </code></pre> <p>Since the if else statement returned "bad" then I must not understand how the string is formatted when pulling from a line. Any help would be greatly appreciated. </p> <p>The text file contains</p> <pre><code>Hey yo </code></pre>
-1
2016-09-02T17:48:41Z
39,298,634
<p>I think you're asking about how to read from a file. Here's the Pythonic way:</p> <pre><code>with open('gmail.txt') as f: for line in f: print(line) </code></pre> <p>If you want to save all the lines of the file into a list of lines:</p> <pre><code>with open('gmail.txt') as f: lines = f.readlines() </code></pre> <p>A more generic way to create a list from something you were for-looping over is to use the <code>list</code> constructor. Here's an example.</p> <pre><code>with open('gmail.txt') as f: lines = list(f) </code></pre>
0
2016-09-02T18:22:11Z
[ "python", "text-files" ]
Selecting highest rows on matrix pandas python.
39,298,235
<p>I have the following data:</p> <p><a href="https://github.com/antonio1695/Python/blob/master/nearBPO/facturasb.csv" rel="nofollow">https://github.com/antonio1695/Python/blob/master/nearBPO/facturasb.csv</a></p> <p>It is a matrix like the following example:</p> <pre><code>UUID A B C D E F G H I 1.1 0 1 0 0 0 1 0 0 0 1.2 1 1 0 0 0 0 0 0 0 1.3 0 0 0 0 1 0 0 0 0 1.4 0 0 0 1 0 1 1 1 1 1.5 0 1 0 0 0 0 1 0 0 1.6 0 0 1 0 0 0 1 0 0 1.7 0 1 0 0 0 0 0 1 0 1.8 0 0 1 0 0 0 1 0 0 1.9 0 1 0 0 0 0 1 0 1 </code></pre> <p>I would like to make a new matrix with only the 50 highest columns (3 in the example) and it's respective UUID. With the highest columns i mean those columns that have more 1's in the matrix. </p> <p>If i'm not clear enough, don't hesitate asking. Thank you. </p>
1
2016-09-02T17:53:39Z
39,298,355
<p>IIUC</p> <pre><code>df[df.sum().nlargest(3).index] </code></pre> <p><a href="http://i.stack.imgur.com/V6YQi.png" rel="nofollow"><img src="http://i.stack.imgur.com/V6YQi.png" alt="enter image description here"></a></p> <hr> <p>To exclude rows with all zeros among the n largest</p> <pre><code>n = df.sum().nlargest(3).index df1 = df.loc[:, n] df1[df1.eq(1).any(1)] </code></pre> <p><a href="http://i.stack.imgur.com/KAYTU.png" rel="nofollow"><img src="http://i.stack.imgur.com/KAYTU.png" alt="enter image description here"></a></p> <hr> <h3>Setup</h3> <pre><code>from StringIO import StringIO import pandas as pd text = """UUID A B C D E F G H I 1.1 0 1 0 0 0 1 0 0 0 1.2 1 1 0 0 0 0 0 0 0 1.3 0 0 0 0 1 0 0 0 0 1.4 0 0 0 1 0 1 1 1 1 1.5 0 1 0 0 0 0 1 0 0 1.6 0 0 1 0 0 0 1 0 0 1.7 0 1 0 0 0 0 0 1 0 1.8 0 0 1 0 0 0 1 0 0 1.9 0 1 0 0 0 0 1 0 1""" df = pd.read_csv(StringIO(text), index_col=0, delim_whitespace=True) </code></pre> <hr> <h3>Bonus solution with numpy</h3> <p>Assuming same setup (this is probably quicker)</p> <pre><code>n = df.values.sum(0).argsort()[-3:][::-1] m = (a[:, n] == 1).any(1) df.iloc[m, n] </code></pre> <p><strong><em>Notice</em></strong> the columns are not the same as my other solution. That is because the multiple columns summed to the same value.</p> <p><a href="http://i.stack.imgur.com/tOeBz.png" rel="nofollow"><img src="http://i.stack.imgur.com/tOeBz.png" alt="enter image description here"></a></p> <hr> <h3>Timing</h3> <p><a href="http://i.stack.imgur.com/b5Hig.png" rel="nofollow"><img src="http://i.stack.imgur.com/b5Hig.png" alt="enter image description here"></a></p>
3
2016-09-02T18:02:08Z
[ "python", "pandas", "matrix" ]
Selecting highest rows on matrix pandas python.
39,298,235
<p>I have the following data:</p> <p><a href="https://github.com/antonio1695/Python/blob/master/nearBPO/facturasb.csv" rel="nofollow">https://github.com/antonio1695/Python/blob/master/nearBPO/facturasb.csv</a></p> <p>It is a matrix like the following example:</p> <pre><code>UUID A B C D E F G H I 1.1 0 1 0 0 0 1 0 0 0 1.2 1 1 0 0 0 0 0 0 0 1.3 0 0 0 0 1 0 0 0 0 1.4 0 0 0 1 0 1 1 1 1 1.5 0 1 0 0 0 0 1 0 0 1.6 0 0 1 0 0 0 1 0 0 1.7 0 1 0 0 0 0 0 1 0 1.8 0 0 1 0 0 0 1 0 0 1.9 0 1 0 0 0 0 1 0 1 </code></pre> <p>I would like to make a new matrix with only the 50 highest columns (3 in the example) and it's respective UUID. With the highest columns i mean those columns that have more 1's in the matrix. </p> <p>If i'm not clear enough, don't hesitate asking. Thank you. </p>
1
2016-09-02T17:53:39Z
39,298,562
<p>Let's break this task into two parts. First, find which columns have the most <code>1</code>'s. Second, select only those columns.</p> <p>Here's some data:</p> <pre><code>In [1]: import numpy as np In [2]: import pandas as pd In [3]: import string In [4]: data = np.random.randint(2, size=(10, 10)) In [5]: data Out[5]: array([[1, 1, 1, 1, 0, 1, 0, 0, 0, 0], [1, 1, 1, 1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0, 0, 1, 1, 0], [0, 0, 0, 1, 0, 0, 0, 0, 1, 0], [0, 1, 0, 1, 1, 1, 0, 0, 1, 1], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 0, 1, 1, 1, 1], [0, 0, 1, 1, 1, 0, 1, 1, 0, 1], [0, 0, 1, 1, 1, 0, 1, 0, 1, 1]]) In [6]: df = pd.DataFrame(data, columns=list(string.ascii_lowercase[:10])) In [7]: df.index.name = 'uuid' In [8]: df Out[8]: a b c d e f g h i j uuid 0 1 1 1 1 0 1 0 0 0 0 1 1 1 1 1 0 1 0 0 0 0 2 0 0 0 1 1 1 0 0 0 0 3 0 1 0 0 1 0 0 1 1 0 4 0 0 0 1 0 0 0 0 1 0 5 0 1 0 1 1 1 0 0 1 1 6 0 0 1 1 1 1 1 1 0 0 7 1 1 1 1 1 0 1 1 1 1 8 0 0 1 1 1 0 1 1 0 1 9 0 0 1 1 1 0 1 0 1 1 </code></pre> <p>Now let's find the columns with the most <code>1</code>'s.</p> <pre><code>In [9]: df.sum() Out[9]: a 3 b 5 c 6 d 9 e 7 f 5 g 4 h 4 i 5 j 4 dtype: int64 In [10]: df.sum().sort_values(ascending=False) Out[10]: d 9 e 7 c 6 i 5 f 5 b 5 j 4 h 4 g 4 a 3 dtype: int64 </code></pre> <p>Get the names of the first 3 of those.</p> <pre><code>In [11]: df.sum().sort_values(ascending=False).index[:3] Out[11]: Index(['d', 'e', 'c'], dtype='object') </code></pre> <p>Use those names to select columns from the original dataframe.</p> <pre><code>In [12]: selection = df.sum().sort_values(ascending=False).index[:3] In [13]: df[selection] Out[13]: d e c uuid 0 1 0 1 1 1 0 1 2 1 1 0 3 0 1 0 4 1 0 0 5 1 1 0 6 1 1 1 7 1 1 1 8 1 1 1 9 1 1 1 </code></pre>
0
2016-09-02T18:16:03Z
[ "python", "pandas", "matrix" ]
running a python script within Flask
39,298,249
<p>So I have this simple python script running on Flask that I'd like to pass variables to with an ajax jQuery request. I might be missing something obvious but I can't get it to work properly. </p> <pre><code>@app.route('/test', methods=['GET', 'POST']) def test(): my_int1 = request.args.get('a') my_int2 = request.args.get('b') my_list = [my_int1, my_int2] with open('my_csv.csv', 'wb') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(my_list) return '' #does one have to have an return even tho it is just a script? </code></pre> <p>So, above will work fine when just passing parameters to the URL field: <code>http://127.0.0.1:5000/test?a=10&amp;b=25</code> however, trying this in the chrome console will not yield any output at all: </p> <pre><code>$.ajax({ method: "POST", url: "127.0.0.1:5000/test", data: {a: 10, b: 25}, dataType: "script" }); </code></pre> <p>What am I missing and why does the above jquery ajax request not work? <code>$.ajax is not a function(…)</code></p>
0
2016-09-02T17:54:44Z
39,298,381
<p>Please refer to <a href="http://flask.pocoo.org/docs/0.11/api/#flask.Request" rel="nofollow">http://flask.pocoo.org/docs/0.11/api/#flask.Request</a></p> <pre><code>request.args : If you want the parameters in the URL request.form : If you want the information in the body (as sent by a html POST form) request.values : If you want both </code></pre> <p>Try this</p> <pre><code>@app.route('/test', methods=['GET', 'POST']) def test(): my_int1 = request.values.get('a') my_int2 = request.values.get('b') </code></pre>
1
2016-09-02T18:04:12Z
[ "jquery", "python", "ajax", "flask" ]
running a python script within Flask
39,298,249
<p>So I have this simple python script running on Flask that I'd like to pass variables to with an ajax jQuery request. I might be missing something obvious but I can't get it to work properly. </p> <pre><code>@app.route('/test', methods=['GET', 'POST']) def test(): my_int1 = request.args.get('a') my_int2 = request.args.get('b') my_list = [my_int1, my_int2] with open('my_csv.csv', 'wb') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(my_list) return '' #does one have to have an return even tho it is just a script? </code></pre> <p>So, above will work fine when just passing parameters to the URL field: <code>http://127.0.0.1:5000/test?a=10&amp;b=25</code> however, trying this in the chrome console will not yield any output at all: </p> <pre><code>$.ajax({ method: "POST", url: "127.0.0.1:5000/test", data: {a: 10, b: 25}, dataType: "script" }); </code></pre> <p>What am I missing and why does the above jquery ajax request not work? <code>$.ajax is not a function(…)</code></p>
0
2016-09-02T17:54:44Z
39,298,852
<p>It appears your jQuery reference on that HTML page is not being loaded or not correct, please add this in the <code>&lt;head&gt; here &lt;/head&gt;</code> section of your HTML page.</p> <pre><code>&lt;script src="https://code.jquery.com/jquery-3.1.0.js"&gt;&lt;/script&gt; </code></pre>
0
2016-09-02T18:40:04Z
[ "jquery", "python", "ajax", "flask" ]
running a python script within Flask
39,298,249
<p>So I have this simple python script running on Flask that I'd like to pass variables to with an ajax jQuery request. I might be missing something obvious but I can't get it to work properly. </p> <pre><code>@app.route('/test', methods=['GET', 'POST']) def test(): my_int1 = request.args.get('a') my_int2 = request.args.get('b') my_list = [my_int1, my_int2] with open('my_csv.csv', 'wb') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(my_list) return '' #does one have to have an return even tho it is just a script? </code></pre> <p>So, above will work fine when just passing parameters to the URL field: <code>http://127.0.0.1:5000/test?a=10&amp;b=25</code> however, trying this in the chrome console will not yield any output at all: </p> <pre><code>$.ajax({ method: "POST", url: "127.0.0.1:5000/test", data: {a: 10, b: 25}, dataType: "script" }); </code></pre> <p>What am I missing and why does the above jquery ajax request not work? <code>$.ajax is not a function(…)</code></p>
0
2016-09-02T17:54:44Z
39,300,543
<p>Please, try with the following code and let me know if that's what you are looking for:</p> <pre><code>from flask import Flask, request import csv app = Flask(__name__) @app.route('/test', methods=['GET', 'POST']) def test(): if request.is_xhr: a = request.json['a'] b = request.json['b'] else: a = request.args.get('a') b = request.args.get('b') my_list = [a, b] with open('my_csv.csv', 'wb') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(my_list) return ''' &lt;html&gt; &lt;head&gt; &lt;title&gt;This is just a testing template!&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; ''' if __name__ == "__main__": app.run(host='0.0.0.0', debug=True) </code></pre> <p>To test from your Chrome console, you need first to go to <strong><a href="http://127.0.0.1:5000/test" rel="nofollow">http://127.0.0.1:5000/test</a></strong> (after that, jQuery will be available in your browser) then you run the following code:</p> <pre><code>$.ajax({ url: "http://127.0.0.1:5000/test", method: "POST", headers: {'Content-Type':'application/json'}, data: JSON.stringify({a: 10, b: 25}), success: function(data){console.log('result: ' + data);} }); </code></pre> <p>If you have a Cross-origin issue, add also the below code to your <strong>app.py</strong> file:</p> <pre><code>@app.after_request def after_request(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') response.headers.add('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS') return response </code></pre>
1
2016-09-02T20:51:16Z
[ "jquery", "python", "ajax", "flask" ]
Python Pandas: Check if all columns in rows value is NaN
39,298,372
<p>Kindly accept my apologies if my question has already been answered. I tried to find a solution but all I can find is to dropna solution for all NaN's in a dataframe. My question is that I have a dataframe with 6 columns and 500 rows. I need to check if in any particular row all the values are NaN so that I can drop them from my dataset. Example below row 2, 6 &amp; 7 contains all Nan from col1 to col6:</p> <pre><code> Col1 Col2 Col3 Col4 Col5 Col6 12 25 02 78 88 90 Nan Nan Nan Nan Nan Nan Nan 35 03 11 65 53 Nan Nan Nan Nan 22 21 Nan 15 93 111 165 153 Nan Nan Nan Nan Nan Nan Nan Nan Nan Nan Nan Nan 141 121 Nan Nan Nan Nan </code></pre> <p>Please note that top row is just headings and from 2nd row on wards my data starts. Will be grateful if anyone can help me in right direction to solve this puzzle.</p> <p>And also my 2nd question is that after deleting all Nan in all columns if I want to delete the rows where 4 or 5 columns data is missing then what will be the best solution.</p> <p>and last question is, is it possible after deleting the rows with most Nan's then how can I create box plot on the remaining for example 450 rows?</p> <p>Any response will be highly appreciated.</p> <p>Regards,</p>
0
2016-09-02T18:03:31Z
39,298,489
<blockquote> <p>I need to check if in any particular row all the values are NaN so that I can drop them from my dataset. </p> </blockquote> <p>That's exactly what <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow"><code>pd.DataFrame.dropna(how='all')</code></a> does:</p> <pre><code>In [3]: df = pd.DataFrame({'a': [None, 1, None], 'b': [None, 1, 2]}) In [4]: df Out[4]: a b 0 NaN NaN 1 1.0 1.0 2 NaN 2.0 In [5]: df.dropna(how='all') Out[5]: a b 1 1.0 1.0 2 NaN 2.0 </code></pre> <p>Regarding your second question, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.boxplot.html" rel="nofollow"><code>pd.DataFrame.boxplot</code></a> will do that. You can specify the columns you want (if needed), with the <code>column</code> parameter. See <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#box-plots" rel="nofollow">the example in the docs</a> also.</p>
1
2016-09-02T18:11:22Z
[ "python", "pandas", null ]
something better than time.time()?
39,298,445
<p>My team and I are designing a project which requires the detection of rising edge of a square wave and then storing the time using time.time() in a variable.If a same square wave is given to 3 different pins of RPi,and event detection is applied on each pin,theoretically,they should occur at the same time,but they have a delay which causes a difference in phase too (we are calculating phase from time). We concluded that time.time() is a slow function. Can anyone please help me as to which function to use to get SOC more precise than time.time()? Or please provide me with the programming behind the function time.time(). I'll be really thankful. </p>
1
2016-09-02T18:08:00Z
39,298,941
<p><code>time.time</code> uses <code>gettimeofday</code> on platforms that support it. That means its resolution is in microseconds.</p> <p>You might try using <code>time.clock_gettime(time.CLOCK_REALTIME)</code> which provides nanosecond resolution (assuming the underlying hardware/OS provides that). The result still gets converted to floating point as with <code>time.time</code>.</p> <p>It's also possible to load up the <code>libc</code> shared object and invoke the native <code>clock_gettime</code> using the <code>ctypes</code> module. In that way, you could obtain access to the actual nanosecond count provided by the OS. (Using <code>ctypes</code> has a fairly steep learning curve though.)</p>
0
2016-09-02T18:46:51Z
[ "python", "time", "soc" ]
Whitenoise, Mezzanine, Django -ImportError: cannot import name ManifestStaticFilesStorage
39,298,540
<p>I am trying to deploy my mezzanine project on heroku. The last error gives me an ultimate stack- ImportError: cannot import name ManifestStaticFilesStorage. Here is my core project structure:</p> <pre><code>├── deploy │   ├── crontab │   ├── gunicorn.conf.py.template │   ├── local_settings.py.template │   ├── nginx.conf │   └── supervisor.conf ├── dev.db ├── fabfile.py ├── flat │   ├── admin.py │   ├── admin.pyc │   ├── __init__.py │   ├── __init__.pyc │   ├── models.py │   ├── models.pyc │   ├── tests.py │   ├── views.py │   └── views.pyc ├── __init__.py ├── __init__.pyc ├── manage.py ├── Procfile ├── README.md ├── requirements.txt ├── runtime.txt ├── settings.py ├── staticfiles -&gt; mezzanine_heroku/staticfiles ├── urls.py ├── urls.pyc └── wsgi.py </code></pre> <p>wsgi.py:</p> <pre><code>import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = get_wsgi_application() application = DjangoWhiteNoise(application) </code></pre> <p>Procfile:</p> <pre><code>web: gunicorn wsgi </code></pre> <p>Traceback from heroku-logs:</p> <pre><code>ImportError: cannot import name ManifestStaticFilesStorage 2016-09-02T18:02:36.124458+00:00 app[web.1]: Traceback (most recent call last): 2016-09-02T18:02:36.124494+00:00 app[web.1]: File "/app/.heroku/python/bin/gunicorn", line 11, in &lt;module&gt; 2016-09-02T18:02:36.124529+00:00 app[web.1]: sys.exit(run()) 2016-09-02T18:02:36.124558+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run 2016-09-02T18:02:36.124620+00:00 app[web.1]: WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() 2016-09-02T18:02:36.124646+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 192, in run 2016-09-02T18:02:36.124706+00:00 app[web.1]: super(Application, self).run() 2016-09-02T18:02:36.124709+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 72, in run 2016-09-02T18:02:36.124754+00:00 app[web.1]: Arbiter(self).run() 2016-09-02T18:02:36.124800+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 218, in run 2016-09-02T18:02:36.124858+00:00 app[web.1]: self.halt(reason=inst.reason, exit_status=inst.exit_status) 2016-09-02T18:02:36.124862+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 331, in halt 2016-09-02T18:02:36.124962+00:00 app[web.1]: self.stop() 2016-09-02T18:02:36.124966+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 381, in stop 2016-09-02T18:02:36.125047+00:00 app[web.1]: time.sleep(0.1) 2016-09-02T18:02:36.125057+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 231, in handle_chld 2016-09-02T18:02:36.125138+00:00 app[web.1]: self.reap_workers() 2016-09-02T18:02:36.125141+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 506, in reap_workers 2016-09-02T18:02:36.125241+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2016-09-02T18:02:36.125304+00:00 app[web.1]: gunicorn.errors.HaltServer: &lt;HaltServer 'Worker failed to boot.' 3&gt; 2016-09-02T18:02:36.182785+00:00 heroku[web.1]: State changed from starting to crashed 2016-09-02T18:02:36.175782+00:00 heroku[web.1]: Process exited with status 1 </code></pre> <p>Most confusing is the <code>ImportError: cannot import name ManifestStaticFilesStorage</code> error.</p>
0
2016-09-02T18:14:37Z
39,307,701
<p>ManifestStaticFilesStorage was introduced in Django 1.7. Are you using an older version of Django? If so, you should upgrade to a <a href="https://www.djangoproject.com/download/#supported-versions" rel="nofollow">supported version</a>.</p> <p>It's still possible to use <a href="http://whitenoise.evans.io/en/legacy-2.x/" rel="nofollow">WhiteNoise 2.0.6</a> with older versions of Django, but this is not supported by either me or the Django team.</p>
1
2016-09-03T13:55:08Z
[ "python", "django", "heroku", "gunicorn", "mezzanine" ]
Protecting a view without requiring login in Django?
39,298,659
<p>I'm trying to password protect my registration page in Django without requiring the user to login, but I can't seem to figure it out. My flow should be:</p> <ol> <li>User accesses mydomain.com/register/</li> <li>User enters password into <code>registration_access</code> form</li> <li>If unsuccessful, user re-enters password</li> <li>If successful, user is presented with <code>UserCreationForm</code></li> <li>If <code>UserCreationForm</code> is not filled out properly, user is presented with <code>UserCreationForm</code> again + errors</li> <li>If <code>UserCreationForm</code> is filled out properly, user is redirected to their profile page</li> </ol> <p>The issue I'm having right now is that I can't redirect a user to a view without a URL (the view containing UserCreationForm).</p> <p>Here's my code:</p> <p><code>views.py</code></p> <pre><code>def register(request): if request.method == 'POST': # Gather information from all forms submitted user_custom_info = user_information(request.POST) user_info = UserCreationForm(request.POST) profile_info = deejay_form(request.POST) # Check to make sure they entered data into each of the forms info_validated = user_info.is_valid() and user_custom_info.is_valid() and profile_info.is_valid() # If they did... if info_validated: # Clean the data... user_custom_info = user_custom_info.cleaned_data user_info = user_info.cleaned_data profile_info = profile_info.cleaned_data # Create a new user with those traits new_user = User.objects.create_user(user_info['username'], user_custom_info['email'], user_info['password1']) new_user.first_name = user_custom_info['first_name'] new_user.last_name = user_custom_info['last_name'] new_user.save() # Create a new deejay with those traits.. new_deejay = Deejay(user=new_user, dj=profile_info['dj'], role=profile_info['role'], bio=profile_info['bio'], phone=profile_info['phone']) new_deejay.save() # Log in the user.. if not request.user.is_authenticated(): this_user = authenticate(username=user_info['username'], password=user_info['password1']) login(request, this_user) # Need to add to group - http://stackoverflow.com/questions/6288661/adding-a-user-to-a-group-in-django # Redirect to dj page return redirect('dj_detail', dj_name=Deejay.objects.get(user=request.user).dj) else: return render(request, 'pages/backend/register.html', {'forms':[user_custom_info, user_info, profile_info]}) return render(request, 'pages/backend/register.html', {'forms':[user_information, UserCreationForm, deejay_form]}) # View for a password protected registration form def register_protect(request): if request.method == 'POST': pw_info = registration_access(request.POST) if pw_info.is_valid(): return redirect(register) else: return render(request, 'pages/backend/register.html', {'forms':[pw_info]}) return render(request, 'pages/backend/register.html', {'forms':[registration_access]}) </code></pre> <p><code>forms.py</code></p> <pre><code>class user_information(forms.ModelForm): first_name = forms.CharField(label='First Name', required=True) last_name = forms.CharField(label='Last Name', required=True) email = forms.EmailField(label='Email', required=True) class Meta: model = User fields = ('first_name', 'last_name', 'email') class deejay_form(forms.ModelForm): class Meta: model = Deejay fields = ('dj', 'role', 'bio', 'phone') class registration_access(forms.Form): secret_password = forms.CharField(label="Secret Password", widget=forms.PasswordInput()) def clean(self): access_password = "mypassword" given_password = self.cleaned_data.get('secret_password') if given_password != access_password: raise forms.ValidationError("Did you forget your training?") return self.cleaned_data </code></pre>
0
2016-09-02T18:23:48Z
39,298,924
<p>"Redirect" means, by definition, to redirect back to the server. Thus you need to redirect to a URL. You can redirect to the same URL, but then you'd need to write your view to be able to handle the different things you want to do.</p> <p>To me, it sounds like you'd be better served using Javascript and handle things as a single page app.</p>
0
2016-09-02T18:45:38Z
[ "python", "django" ]
Anaconda Python virtualdev can't find libpython3.5m.so.1.0 on Windows Subsystem for Linux (Ubuntu 14.04)
39,298,681
<p>I installed Python 3.5.2 using Anaconda 4.1.1 on the Windows Anniversary Edition Linux Subsystem (WSL), which is more or less embedded Ubuntu 14.04.5 LTS.</p> <p>I installed virtualenv using:</p> <pre><code>pip install virtualenv </code></pre> <p>Then I tried to create a virtual environment inside <code>~/temp</code>:</p> <pre><code>user@host:~$ virtualenv ~/temp/test Using base prefix '/home/user/anaconda3' New python executable in /home/user/temp/test/bin/python /home/user/temp/test/bin/python: error while loading shared libraries: libpython3.5m.so.1.0: cannot open shared object file: No such file or directory ERROR: The executable /home/user/temp/test/bin/python is not functioning ERROR: It thinks sys.prefix is '/home/user' (should be '/home/user/temp/test') ERROR: virtualenv is not compatible with this system or executable </code></pre> <p>It's easy to assume that this is just a WSL issue, but everything else was working so far, and I've seen similar errors reported on Ubuntu. Any idea what the problem is?</p>
1
2016-09-02T18:25:31Z
39,370,303
<p>I have not experienced the same issue or tried to replicate the WSL environment. But usually when something similar happens with other libraries it is just likely to be a poorly configured environment. You have to checkout your library path:</p> <pre><code>echo $LD_LIBRARY_PATH </code></pre> <p>And make sure the directory that holds <code>libpython</code> is there. If not:</p> <pre><code>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/the/py/lib/dir </code></pre> <p>Add this last line to your <code>.bash_profile</code> or <code>.bashrc</code> to make it permanent.</p>
1
2016-09-07T12:44:17Z
[ "python", "linux", "ubuntu", "virtualenv", "wsl" ]
Selenium Python: What are the errors in my code?
39,298,794
<p>i would like to know why this code opens mozilla twice, and why it doesn´t close it when finishes. Furthermore, i don´t understand 100% why login is a class with a function, and not a function directly.</p> <pre><code>&gt; import unittest from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class LoginDetails(object): def __init__ (self): self.driver = webdriver.Firefox() def logindetails(self, username, password): driver = self.driver driver.maximize_window() driver.get("https://miclaro.claro.com.ar/") driver.implicitly_wait(30) driver.find_element_by_id("_58_login_movil").send_keys(username) driver.find_element_by_id("_58_password_movil").send_keys(password) driver.find_element_by_id("btn-home-login").click() # Login Success class TestLogin(unittest.TestCase): def setUp(self): self.ld = LoginDetails() self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) def test_sr_Login(self): self.ld.logindetails("user", "pass") def tearDown(self): self.driver.close() if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main() </code></pre> <p>Thank you very much!</p>
0
2016-09-02T18:35:27Z
39,298,899
<p>This is because you <em>instantiate webdriver twice</em> - once inside the <code>TestCase</code> and once inside the <code>LoginDetails</code> class.</p> <h1>Why the other answer is not entirely correct</h1> <p>The WebDriver should not be controlled by the <code>LoginDetails</code> class in this case. <code>LoginDetails</code> class is very close to a <a href="http://selenium-python.readthedocs.io/page-objects.html" rel="nofollow">Page Object</a> notation representation and, hence, should be given the driver "from outside". Plus, opening browser in one class and closing it in the other is making the code close to <a href="https://en.wikipedia.org/wiki/Spaghetti_code" rel="nofollow">"Spaghetti"</a>.</p> <h1>Better solution</h1> <p>Control the <code>webdriver</code> from the <code>TestCase</code> class and "share" with the <code>LoginDetails</code>:</p> <pre><code>import unittest from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class LoginDetails(object): def __init__ (self, driver): self.driver = driver def logindetails(self, username, password): driver = self.driver driver.maximize_window() driver.get("https://miclaro.claro.com.ar/") driver.implicitly_wait(30) driver.find_element_by_id("_58_login_movil").send_keys(username) driver.find_element_by_id("_58_password_movil").send_keys(password) driver.find_element_by_id("btn-home-login").click() class TestLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.ld = LoginDetails(self.driver) def test_sr_Login(self): self.ld.logindetails("user", "pass") def tearDown(self): self.driver.close() </code></pre>
2
2016-09-02T18:44:12Z
[ "python", "selenium", "selenium-webdriver", "webdriver" ]
Selenium Python: What are the errors in my code?
39,298,794
<p>i would like to know why this code opens mozilla twice, and why it doesn´t close it when finishes. Furthermore, i don´t understand 100% why login is a class with a function, and not a function directly.</p> <pre><code>&gt; import unittest from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class LoginDetails(object): def __init__ (self): self.driver = webdriver.Firefox() def logindetails(self, username, password): driver = self.driver driver.maximize_window() driver.get("https://miclaro.claro.com.ar/") driver.implicitly_wait(30) driver.find_element_by_id("_58_login_movil").send_keys(username) driver.find_element_by_id("_58_password_movil").send_keys(password) driver.find_element_by_id("btn-home-login").click() # Login Success class TestLogin(unittest.TestCase): def setUp(self): self.ld = LoginDetails() self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) def test_sr_Login(self): self.ld.logindetails("user", "pass") def tearDown(self): self.driver.close() if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main() </code></pre> <p>Thank you very much!</p>
0
2016-09-02T18:35:27Z
39,298,908
<h1>Firefox opens twice</h1> <p>In your test <code>self.ld = LoginDetails()</code> runs the <code>__init__</code> function of <code>LoginDetails()</code> which in turn runs <code>webdriver.Firefox()</code> then you issue the same in the next line in the test case. That is why Firefox opens twice. </p> <h1>Firefox does not close</h1> <p>For the same reason as above Firefox is not closed. The <code>tearDown</code> of your test case only closes the instance of <code>webdriver.Firefox()</code> defined in the test case itself not the one opened via the <code>__init__</code> function of the class.</p> <h1>Why <code>LoginDetails</code> is a class</h1> <p><code>LoginDetails</code> is a class in this case to keep <code>webdriver.Firefox()</code> persistent throughout your code. If it would be a function you would open one Firefox session each time you run the function. Unless you specify <code>webdriver.Firefox()</code> outside the function and then pass it to the function.</p> <h1>Corrected Code</h1> <p>The following code uses the class functionality:</p> <pre><code>import unittest from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class LoginDetails(object): def __init__ (self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) def logindetails(self, username, password): self.driver.maximize_window() self.driver.get("https://miclaro.claro.com.ar/") self.driver.implicitly_wait(30) self.driver.find_element_by_id("_58_login_movil").send_keys(username) self.driver.find_element_by_id("_58_password_movil").send_keys(password) self.driver.find_element_by_id("btn-home-login").click() def __del__(self): ''' ADDED based on comment by alecxe ''' self.driver.close() class TestLogin(unittest.TestCase): def setUp(self): self.ld = LoginDetails() def test_sr_Login(self): self.ld.logindetails("user", "pass") def tearDown(self): # driver is closed by LoginDetails pass if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main() </code></pre>
2
2016-09-02T18:44:42Z
[ "python", "selenium", "selenium-webdriver", "webdriver" ]
Improving LBP/HAAR detection XML cascades
39,298,867
<p>I am trying to do a car detector from UAV images with Python 2.7 and OpenCV 2.4.13. The goal is to detect cars from an upper view in any direction, in urban environments. I am facing time execution and accuracy problems.</p> <p>Detector works fine when I use it with some cascades that I obtained from internet:</p> <ul> <li>Banana classifier (obviously it does not detect cars, but detect the objects that it recognises as bananas): ( coding-robin.de/2013/07/22/train-your-own-opencv-haar-classifier.html)</li> <li>Face detection cascades from OpenCV (same behaviour as banana classifier)</li> </ul> <p>For the detection itself, I´m using <code>detectMultiScale()</code> with <code>scaleFactor = 1.1-1.2</code> and <code>minNeighbors=3</code></p> <p>The detection is performed in a reasonable time (a few seconds) in a 4000x3000 px image.</p> <p>The problems arise when I try to use my own trained classifiers. The results are bad and it takes very long to perform the detection (more than half an hour)</p> <p>For training, I extracted both positives and negatives images from a big orthomosaic (that I downscaled a few times) that has a parking lot with lots of cars. I´ve extracted a total of 50 cars (25x55 pixels), which then I reflected horizontally, resulting in 100 positive images, and 2119 negative images (60x60 pixels) from the same orthomosaic. I call this set the "complete set" of images. From that set, I created a subset (4 positives and 35 negatives), which I call the "Dummy set":</p> <p><a href="http://i.stack.imgur.com/OzYrM.jpg" rel="nofollow">Positive image example 1</a></p> <p><a href="http://i.stack.imgur.com/pUBoo.jpg" rel="nofollow">Negative image example 1</a></p> <p>For training, I used <code>opencv_createsamples</code> and <code>opencv_traincascade</code>. I created 6000 samples from the 100 positive images, rotating the cars from 0 to 360 degrees:</p> <pre><code>perl bin/createsamples.pl positives.txt negatives.txt samples 6000 "opencv_createsamples -bgcolor 0 -bgthresh 0 -maxxangle 0.5 -maxyangle 0.5 -maxzangle 6.28 -maxidev 40 -w 60 -h 60" </code></pre> <p>So now, I have 6000 60x60 pixels sample images of cars in any direction over random backgrounds.</p> <p>Then I executed <code>mergevec.py</code> to create the <code>samples.vec</code> file, and run the training application <code>opencv_traincascade</code>:</p> <pre><code>python mergevec.py -v samples/ -o samples.vec opencv_traincascade -data classifier -vec samples.vec -bg negatives.txt -numStages 20 -minHitRate 0.999 -maxFalseAlarmRate 0.5 -numPos 3700 -numNeg 2119 -w 60 -h 60 -mode ALL -precalcValBufSize 3096 -precalcIdxBufSize 3096 </code></pre> <p>With this method, I have trained four classifiers, two using the complete set, and the other two using the dummy set, one LBP and one HAAR for each set. The results I get are the following:</p> <ol> <li>Dummy set, LBP: Training stopped in 1 Stage. Fast detection, no objects detected</li> <li>Dummy set, HAAR: Training stopped in 1 Stage. Detection takes forever (or at least more than half an hour). I interrupted the process because it is obviously not working.</li> <li>Complete set, LBP: Training stopped in 6 Stages. Very slow detection (1-2 minutes in a 500x400 pixels image, using scaleFactor = 2). Detect a very few amount of objects (2), none of them cars, when there are at least 10 cars in the image, and also the same image used for training.</li> <li>Complete set, HAAR: I stopped training in 4th stage to test it. Same behaviour as with the Dummy set.</li> </ol> <p>What I'm doing wrong? Since the banana and the face cascades works in a reasonable time and detects objects, the problem is obviously in my cascades, but I cannot figure it out why. </p> <p>I really appreciate your help. Thanks in advance, Federico</p>
3
2016-09-02T18:41:31Z
39,385,938
<p>I can't say exactly, but I have an idea why you can't train HAAR (LBP) cascades to detect arbitrary oriented cars. </p> <p>These cascades work fine when detected objects with approximately the same shape and color (lightness). A frontal oriented face is a good example of these objects. But it works much worse when face has another orientation and color (it's not joke, standard haar cascades from OpenCV have problem with detection of a man with dark skin). Although these problems are the result of training set, which contains only the faces of frontal oriented european people. But if we try to add to training set faces with all colors and spatial orientations we face with the same problems as you.</p> <p>During the training process the training algorithm at each stage try to find the set of features (HAAR or LBP) which separates negative and positive samples. If detected object has complicated and variable shape the number of required features is very large. The big number of required features leads to that cascade classifier works very slowly or at all can't train.</p> <p>So that HAAR (LBP) cascades can't be used for detection of objects with variable shape. But you can look towards Deep Convolution Neural Networks. They can solve these problems as I know.</p>
0
2016-09-08T08:20:16Z
[ "python", "image", "opencv", "object-detection", "cascade-classifier" ]
Play multiple sounds at the same time in python
39,298,928
<p>I have been looking into a way to play sounds from a list of samples, and I found some modules that can do this.</p> <p>I am using <strong>AudioLazy</strong> module to play the sound using the following script:</p> <pre><code>from audiolazy import AudioIO sound = Somelist with AudioIO(True) as player: player.play(sound, rate=44100) </code></pre> <p>The problem with this code is that it stop the whole application till the sound stop playing and I can't play multiple sound at the same time.</p> <p>My program is interactive so what I want is to be able to play multiple sound at the same time,So for instance I can run this script which will play a 5 second sound then at the second 2 I can play a 5 second sound again.</p> <p>And I don't want the whole program to stop till the sound finish playing.</p>
2
2016-09-02T18:45:53Z
39,298,977
<p>I suggest using <a href="https://people.csail.mit.edu/hubert/pyaudio/docs/" rel="nofollow">Pyaudio</a> to do this.</p> <pre><code>sound1 = wave.open("/path/to/sound1", 'rb') sound2 = wave.open("/path/to/sound2", 'rb') def callback(in_data, frame_count, time_info, status): data1 = sound1.readframes(frame_count) data2 = sound2.readframes(frame_count) decodeddata1 = numpy.fromstring(data1, numpy.int16) decodeddata2 = numpy.fromstring(data2, numpy.int16) newdata = (decodeddata1 * 0.5 + decodeddata2* 0.5).astype(numpy.int16) return (result.tostring(), pyaudio.paContinue) </code></pre>
1
2016-09-02T18:49:25Z
[ "python", "audio", "interactive" ]
Play multiple sounds at the same time in python
39,298,928
<p>I have been looking into a way to play sounds from a list of samples, and I found some modules that can do this.</p> <p>I am using <strong>AudioLazy</strong> module to play the sound using the following script:</p> <pre><code>from audiolazy import AudioIO sound = Somelist with AudioIO(True) as player: player.play(sound, rate=44100) </code></pre> <p>The problem with this code is that it stop the whole application till the sound stop playing and I can't play multiple sound at the same time.</p> <p>My program is interactive so what I want is to be able to play multiple sound at the same time,So for instance I can run this script which will play a 5 second sound then at the second 2 I can play a 5 second sound again.</p> <p>And I don't want the whole program to stop till the sound finish playing.</p>
2
2016-09-02T18:45:53Z
39,298,998
<p>Using multiple threads will solve your problem :</p> <pre><code>import threading from audiolazy import AudioIO sound = Somelist with AudioIO(True) as player: t = threading.Thread(target=player.play, args=(sound,), kwargs={'rate':44100}) t.start() </code></pre>
1
2016-09-02T18:50:26Z
[ "python", "audio", "interactive" ]
Play multiple sounds at the same time in python
39,298,928
<p>I have been looking into a way to play sounds from a list of samples, and I found some modules that can do this.</p> <p>I am using <strong>AudioLazy</strong> module to play the sound using the following script:</p> <pre><code>from audiolazy import AudioIO sound = Somelist with AudioIO(True) as player: player.play(sound, rate=44100) </code></pre> <p>The problem with this code is that it stop the whole application till the sound stop playing and I can't play multiple sound at the same time.</p> <p>My program is interactive so what I want is to be able to play multiple sound at the same time,So for instance I can run this script which will play a 5 second sound then at the second 2 I can play a 5 second sound again.</p> <p>And I don't want the whole program to stop till the sound finish playing.</p>
2
2016-09-02T18:45:53Z
39,644,525
<p>Here is a simpler solution using <a href="https://github.com/jiaaro/pydub/" rel="nofollow">pydub</a>. </p> <p>Using <code>overlay</code> function of <code>AudioSegment</code> module, you can very easily <code>superimpose</code> multiple audio on to each other. </p> <p>Here is a working code to combine three audio files. Using same concept you can combine multiple audio onto each other. </p> <p>More on <code>overlay</code> function <a href="https://github.com/jiaaro/pydub/blob/master/pydub/audio_segment.py" rel="nofollow">here</a></p> <p><code>pydub</code> supports multiple audio formats as well.</p> <pre><code>from pydub import AudioSegment from pydub.playback import play audio1 = AudioSegment.from_file("chunk1.wav") #your first audio file audio2 = AudioSegment.from_file("chunk2.wav") #your second audio file audio3 = AudioSegment.from_file("chunk3.wav") #your third audio file mixed = audio1.overlay(audio2) #combine , superimpose audio files mixed1 = mixed.overlay(audio3) #Further combine , superimpose audio files #If you need to save mixed file mixed1.export("mixed.wav", format='wav') #export mixed audio file play(mixed1) #play mixed audio file </code></pre> <hr> <p><strong>Here are updates as per our discussions.</strong><br> First we create 44KHz signal and save to <code>sound.wav</code><br> Next Read wave file and save signal to text file<br> Then create three variations of input signal to test overlay.<br> Original signal has <code>dtype int16</code><br> Then we create three audio segments then mix/overlay as above. <code>wav</code> signal data is stored in <code>test.txt</code></p> <p><strong>Working Modified Code</strong></p> <pre><code>import numpy as np from scipy.io.wavfile import read from pydub import AudioSegment from pydub.playback import play import wave, struct, math #Create 44KHz signal and save to 'sound.wav' sampleRate = 44100.0 # hertz duration = 1.0 # seconds frequency = 440.0 # hertz wavef = wave.open('sound.wav','w') wavef.setnchannels(1) # mono wavef.setsampwidth(2) wavef.setframerate(sampleRate) for i in range(int(duration * sampleRate)): value = int(32767.0*math.cos(frequency*math.pi*float(i)/float(sampleRate))) data = struct.pack('&lt;h', value) wavef.writeframesraw( data ) wavef.writeframes('') wavef.close() #Read wave file and save signal to text file rate, signal = read("sound.wav") np.savetxt('test.txt', signal, delimiter=',') # X is an array #load wav data from text file wavedata1 = np.loadtxt("test.txt", comments="#", delimiter=",", unpack=False, dtype=np.int16) #Create variation of signal wavedata2 = np.loadtxt("test.txt", comments="#", delimiter=",", unpack=False, dtype=np.int32) #Create variation of signal wavedata3 = np.loadtxt("test.txt", comments="#", delimiter=",", unpack=False, dtype=np.float16) #create first audio segment audio_segment1 = AudioSegment( wavedata1.tobytes(), frame_rate=rate, sample_width=2, channels=1 ) #create second audio segment audio_segment2 = AudioSegment( wavedata2.tobytes(), frame_rate=rate, sample_width=2, channels=1 ) #create third audio segment audio_segment3 = AudioSegment( wavedata3.tobytes(), frame_rate=rate, sample_width=2, channels=1 ) # Play audio (requires ffplay, or pyaudio): play(audio_segment1) play(audio_segment2) play(audio_segment3) #Mix three audio segments mixed1 = audio_segment1.overlay(audio_segment2) #combine , superimpose audio files mixed2 = mixed1.overlay(audio_segment3) #Further combine , superimpose audio files #If you need to save mixed file mixed2.export("mixed.wav", format='wav') #export mixed audio file play(mixed2) #play mixed audio file </code></pre>
1
2016-09-22T16:40:25Z
[ "python", "audio", "interactive" ]
python pandas dtypes detection from sql
39,298,989
<p>I am quite troubled by the behaviour of Pandas DataFrame about Dtype detection.</p> <p>I use 'read_sql_query' to retrieve data from a database to build a DataFrame, and then dump it into a csv file.</p> <p>I don't need any transformation. Just dump it into a csv file and change date fields in the form : <strong>'%d/%m/%Y'</strong></p> <p>However :</p> <pre><code>self.dataframe.to_csv(self.fic, index=False, header=False, sep='|', mode='a', encoding='utf-8', line_terminator='\n', date_format='%d/%m/%Y ) </code></pre> <p>Would miss to transforme/format some date fields...</p> <p>I tried to do it another way :</p> <pre><code>l = list(self.dataframe.select_dtypes(include=['datetime64']).columns) for i in l: self.dataframe[i] = self.dataframe[i].dt.strftime('%d/%m/%Y') </code></pre> <p>I was about to be satisfied, but some more tests showed a weird behaviour :</p> <p><strong>if my sql request only selects two nuplets :</strong></p> <pre><code>requete = 'select * from DOMMAGE_INTERET where doi_id in (176433, 181564)' </code></pre> <p>Everything works, whatever formating in the csv or in the DataFrame.</p> <p>It detects date fields properly :</p> <pre><code>df.dtypes doi_id int64 aff_id int64 pdo_id int64 doi_date_decision datetime64[ns] doi_date_mod datetime64[ns] doi_montant float64 doi_reste_a_payer object doi_appliquer_taux int64 doi_date_update datetime64[ns] afg_id int64 dtype: object </code></pre> <p><strong>But when using a different selection :</strong></p> <pre><code>requete = 'select * from DOMMAGE_INTERET where rownum &lt; 100' </code></pre> <p>It miss again. And actually, fields types are detected differently :</p> <pre><code>doi_id int64 aff_id int64 pdo_id int64 doi_date_decision object doi_date_mod datetime64[ns] doi_montant float64 doi_reste_a_payer object doi_appliquer_taux int64 doi_date_update datetime64[ns] afg_id int64 dtype: object </code></pre> <p>As you can see : <strong>'doi_date_decision' type does change depending of the request selection</strong> but, of course, this is the same set of data !!!</p> <p>Isn't it weird?</p> <p>Do you have a explanation for this behaviour?</p>
0
2016-09-02T18:50:06Z
39,301,020
<p>It is difficult to dig into your issue without some data samples. However, you probably face either of the two cases:</p> <ul> <li>Some of the rows you select in your second case contain <code>NULL</code> values, which stops pandas interpret automatically your column as a datetime</li> <li>You have a different MDY convention in your database and some dates lower than 13rd of the month are parsed as dates while others aren't and are kept as strings until you convert manually in DMY</li> </ul>
1
2016-09-02T21:36:48Z
[ "python", "sql", "csv", "pandas", "dataframe" ]
python pandas dtypes detection from sql
39,298,989
<p>I am quite troubled by the behaviour of Pandas DataFrame about Dtype detection.</p> <p>I use 'read_sql_query' to retrieve data from a database to build a DataFrame, and then dump it into a csv file.</p> <p>I don't need any transformation. Just dump it into a csv file and change date fields in the form : <strong>'%d/%m/%Y'</strong></p> <p>However :</p> <pre><code>self.dataframe.to_csv(self.fic, index=False, header=False, sep='|', mode='a', encoding='utf-8', line_terminator='\n', date_format='%d/%m/%Y ) </code></pre> <p>Would miss to transforme/format some date fields...</p> <p>I tried to do it another way :</p> <pre><code>l = list(self.dataframe.select_dtypes(include=['datetime64']).columns) for i in l: self.dataframe[i] = self.dataframe[i].dt.strftime('%d/%m/%Y') </code></pre> <p>I was about to be satisfied, but some more tests showed a weird behaviour :</p> <p><strong>if my sql request only selects two nuplets :</strong></p> <pre><code>requete = 'select * from DOMMAGE_INTERET where doi_id in (176433, 181564)' </code></pre> <p>Everything works, whatever formating in the csv or in the DataFrame.</p> <p>It detects date fields properly :</p> <pre><code>df.dtypes doi_id int64 aff_id int64 pdo_id int64 doi_date_decision datetime64[ns] doi_date_mod datetime64[ns] doi_montant float64 doi_reste_a_payer object doi_appliquer_taux int64 doi_date_update datetime64[ns] afg_id int64 dtype: object </code></pre> <p><strong>But when using a different selection :</strong></p> <pre><code>requete = 'select * from DOMMAGE_INTERET where rownum &lt; 100' </code></pre> <p>It miss again. And actually, fields types are detected differently :</p> <pre><code>doi_id int64 aff_id int64 pdo_id int64 doi_date_decision object doi_date_mod datetime64[ns] doi_montant float64 doi_reste_a_payer object doi_appliquer_taux int64 doi_date_update datetime64[ns] afg_id int64 dtype: object </code></pre> <p>As you can see : <strong>'doi_date_decision' type does change depending of the request selection</strong> but, of course, this is the same set of data !!!</p> <p>Isn't it weird?</p> <p>Do you have a explanation for this behaviour?</p>
0
2016-09-02T18:50:06Z
39,313,375
<p>Your <code>to-csv</code> operation does not convert all specified date fields because as you mention, not all datetime columns are read in as datetime format but show as string (<em>object</em> dtype) in current dataframe. This is the unfortunate side effect of reading from external sources as the imported system --this includes Python, SAS, Stata, R, Excel, etc.-- attempts to define columns usually by first few rows unless otherwise explicitly defined.</p> <p>Fortunately, pandas's <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_query.html#pandas.read_sql_query" rel="nofollow"><code>read_sql_query()</code></a> maintains a parameter for <code>parse_dates</code>. So consider defining the dates during the read in operation as this argument takes a list or dictionary:</p> <pre><code>df = read_sql_query('select * from DOMMAGE_INTERET where rownum &lt; 100', engine, parse_dates = ['doi_date_decision', 'doi_date_mod', 'doi_date_update']) </code></pre> <p>Alternatively, convert with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>pd.to_datetime()</code></a> just after reading in and before <code>to_csv</code>:</p> <pre><code>df['doi_date_decision'] = pd.to_datetime(df['doi_date_decision']) </code></pre> <p>And most RDMS maintains datetime in <code>YYYY-MM-DD HH:MM:SS</code> format, aligning to pandas format.</p>
2
2016-09-04T03:49:37Z
[ "python", "sql", "csv", "pandas", "dataframe" ]