title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python Top Level JSON Index
39,797,618
<p>I have the following JSON file from an API I am calling:</p> <pre><code>{ "14500": [ { "5": { "versionName": "VersionOne", "expand": "executionSummaries", "name": "Regression", "projectId": 15006, "startDate": "", "executionSummaries": { "executionSummary": [] } }, "7": { "versionName": "VersionOne", "expand": "executionSummaries", "versionId": 14500, "projectId": 15006, "startDate": "19/Sep/16", "executionSummaries": { "executionSummary": [] } }, "-1": { "versionName": "VersionOne", "expand": "executionSummaries", "name": "Ad hoc", "modifiedBy": "", "projectId": 15006, "startDate": "", "executionSummaries": { "executionSummary": [] } }, "recordsCount": 3 } ], "14501": [ { "-1": { "versionName": "Version 2", "expand": "executionSummaries", "projectId": 15006, "startDate": "", "executionSummaries": { "executionSummary": [] } }, "recordsCount": 1 } ], } </code></pre> <p>I need to iterate through the top level, and the next level (ex. "14500", and "5", "7", etc..) to find keys and values. So for instance I need to search through the entire JSON file to find the name that matches "Regression" and locate that set of datas values for "ProjectID" and possibly other strings. I had previously done this by using data["level1"][0]["level2"] etc., but in this case the numbers will never be the same so I don't know how to call them. I wrote the following after looking through some posts on here, but it only works for one level, not the next level down in JSON.</p> <pre><code>request = requests.get(getCyclesURL, headers=headers) requestData = json.loads(request.text) requestDataKeys = requestData.keys for k in requestDataKeys(): dictionaryIDs = requestData[k] for m in requestDataKeys: newDictionaryIDs = requestData[k][m] for dict in newDictionaryIDs: if dict['versionName'] == versionName: versionID = dict['versionID'] print '%s: %s'%(versionName, versionID) </code></pre>
0
2016-09-30T18:13:47Z
39,797,828
<pre><code>def find_in_dicts(d, key, value): #This finds all dictionaries that has the given key and value for k, v in d.items(): if k == key: if v == value: yield d else: if isinstance(v, dict): for i in find_in_dicts(v, key, value): yield i elif isinstance(v, list) and isinstance(v[0], dict): for item in v: for i in find_in_dicts(item, key, value): yield i </code></pre> <p>This should work recursivly no matter how deep your data structure gets. I'm not able to test it at the moment, but I hope it at elast gives you some idea.</p>
0
2016-09-30T18:26:04Z
[ "python", "json" ]
Python Top Level JSON Index
39,797,618
<p>I have the following JSON file from an API I am calling:</p> <pre><code>{ "14500": [ { "5": { "versionName": "VersionOne", "expand": "executionSummaries", "name": "Regression", "projectId": 15006, "startDate": "", "executionSummaries": { "executionSummary": [] } }, "7": { "versionName": "VersionOne", "expand": "executionSummaries", "versionId": 14500, "projectId": 15006, "startDate": "19/Sep/16", "executionSummaries": { "executionSummary": [] } }, "-1": { "versionName": "VersionOne", "expand": "executionSummaries", "name": "Ad hoc", "modifiedBy": "", "projectId": 15006, "startDate": "", "executionSummaries": { "executionSummary": [] } }, "recordsCount": 3 } ], "14501": [ { "-1": { "versionName": "Version 2", "expand": "executionSummaries", "projectId": 15006, "startDate": "", "executionSummaries": { "executionSummary": [] } }, "recordsCount": 1 } ], } </code></pre> <p>I need to iterate through the top level, and the next level (ex. "14500", and "5", "7", etc..) to find keys and values. So for instance I need to search through the entire JSON file to find the name that matches "Regression" and locate that set of datas values for "ProjectID" and possibly other strings. I had previously done this by using data["level1"][0]["level2"] etc., but in this case the numbers will never be the same so I don't know how to call them. I wrote the following after looking through some posts on here, but it only works for one level, not the next level down in JSON.</p> <pre><code>request = requests.get(getCyclesURL, headers=headers) requestData = json.loads(request.text) requestDataKeys = requestData.keys for k in requestDataKeys(): dictionaryIDs = requestData[k] for m in requestDataKeys: newDictionaryIDs = requestData[k][m] for dict in newDictionaryIDs: if dict['versionName'] == versionName: versionID = dict['versionID'] print '%s: %s'%(versionName, versionID) </code></pre>
0
2016-09-30T18:13:47Z
39,797,925
<p>Here is a partial script tailored to your exact input. If it finds <code>name: regression</code> at the appropriate level, it prints a few of the related values.</p> <pre><code>for k, list_of_dicts in requestData.items(): for d in list_of_dicts: for k, v in d.items(): if isinstance(v, dict) and v.get('name') == "Regression": print '%s: %s %s'%(v.get('projectId'), v.get('versionName'), v.get('versionId')) </code></pre>
0
2016-09-30T18:31:33Z
[ "python", "json" ]
Python Top Level JSON Index
39,797,618
<p>I have the following JSON file from an API I am calling:</p> <pre><code>{ "14500": [ { "5": { "versionName": "VersionOne", "expand": "executionSummaries", "name": "Regression", "projectId": 15006, "startDate": "", "executionSummaries": { "executionSummary": [] } }, "7": { "versionName": "VersionOne", "expand": "executionSummaries", "versionId": 14500, "projectId": 15006, "startDate": "19/Sep/16", "executionSummaries": { "executionSummary": [] } }, "-1": { "versionName": "VersionOne", "expand": "executionSummaries", "name": "Ad hoc", "modifiedBy": "", "projectId": 15006, "startDate": "", "executionSummaries": { "executionSummary": [] } }, "recordsCount": 3 } ], "14501": [ { "-1": { "versionName": "Version 2", "expand": "executionSummaries", "projectId": 15006, "startDate": "", "executionSummaries": { "executionSummary": [] } }, "recordsCount": 1 } ], } </code></pre> <p>I need to iterate through the top level, and the next level (ex. "14500", and "5", "7", etc..) to find keys and values. So for instance I need to search through the entire JSON file to find the name that matches "Regression" and locate that set of datas values for "ProjectID" and possibly other strings. I had previously done this by using data["level1"][0]["level2"] etc., but in this case the numbers will never be the same so I don't know how to call them. I wrote the following after looking through some posts on here, but it only works for one level, not the next level down in JSON.</p> <pre><code>request = requests.get(getCyclesURL, headers=headers) requestData = json.loads(request.text) requestDataKeys = requestData.keys for k in requestDataKeys(): dictionaryIDs = requestData[k] for m in requestDataKeys: newDictionaryIDs = requestData[k][m] for dict in newDictionaryIDs: if dict['versionName'] == versionName: versionID = dict['versionID'] print '%s: %s'%(versionName, versionID) </code></pre>
0
2016-09-30T18:13:47Z
39,798,282
<p>Check out amazing <a href="http://boltons.readthedocs.io/en/latest/" rel="nofollow"><code>boltons</code></a> library! It has a <a href="http://sedimental.org/remap.html" rel="nofollow"><code>remap</code></a> function that may be an overkill in your case, but is a good thing to know about. Here's an elegant way to extract all dicts with <code>'name': 'Regression'</code> from your nested data structure:</p> <pre><code>from boltons.iterutils import remap # Copy your actual data here data = {'14500': [{'5': {'name': 'Regression'}, '7': {'name': 'Ad hoc'}}]} regressions = [] def visit(path, key, value): if isinstance(value, dict) and value.get('name') == 'Regression': # You can do whatever you want here! # If you're here then `value` is a dict # and its `name` field equals to 'Regression'. regressions.append(value) return key, value remap(data, visit=visit, reraise_visit=False) assert regressions == [{'name': 'Regression'}] </code></pre> <p>If you only need dicts on a certain level, you can also check length of <code>path</code> in the <code>visit</code> function.</p>
0
2016-09-30T18:53:49Z
[ "python", "json" ]
Trouble setting up linprog in Python
39,797,663
<p>I am using the following code but I have not been able to set up the problem to run.</p> <pre><code>import numpy as np from scipy.optimize import linprog c = np.asarray([-0.098782540360068297, -0.072316526358138802, 0.004, 0.004, 0.004, 0.004]) A_ub = np.asarray([[1.0, 0, 0, 0, 0, 0], [-1.0, 0, 0, 0, 0, 0], [0, -1.0, 0, 0, 0, 0], [0, 1.0, 0, 0, 0, 0], [1.0, 1.0, 0, 0, 0, 0]]) b_ub = np.asarray([3.0, 3.0, 3.0, 3.0, 20.0]) A_eq = np.asarray([[1.0, 0, -1, 1, -1, 1], [0, -1.0, -1, 1, -1, 1]]) b_eq = np.asarray([0,0]) res = linprog(c, A_ub, b_ub, A_eq, b_eq) lb = np.zeros([6,1]) #lower bound for x array ub = np.ones([6,1])*2 #upper bound for x array res2 = linprog(c, A_ub, b_ub, bounds=(lb, ub)) </code></pre> <p>I get error as:</p> <pre><code>ValueError: Invalid input for linprog with method = 'simplex'. Length of bounds is inconsistent with the length of c </code></pre>
0
2016-09-30T18:16:47Z
39,803,389
<p>The bounds parameter wants a list of pairs. Use something like:</p> <pre><code>lb = np.zeros(6) #lower bound for x array ub = np.ones(6)*2 #upper bound for x array res2 = linprog(c, A_ub, b_ub, bounds=list(zip(lb, ub))) </code></pre>
1
2016-10-01T05:37:00Z
[ "python", "optimization", "scipy" ]
Pip is installed, but command not found
39,797,671
<p>Pip has been on my machine for years, but recently I could not get it to work. To fix this I ran:</p> <pre><code>$ sudo python get-pip.py The directory '/Users/tomeldridge/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/tomeldridge/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting pip Downloading pip-8.1.2-py2.py3-none-any.whl (1.2MB) 100% |████████████████████████████████| 1.2MB 759kB/s Collecting wheel Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB) 100% |████████████████████████████████| 71kB 4.3MB/s Installing collected packages: pip, wheel Found existing installation: pip 7.1.2 Uninstalling pip-7.1.2: Successfully uninstalled pip-7.1.2 Successfully installed pip-8.1.2 wheel-0.29.0 </code></pre> <p>But pip still doesn't work:</p> <pre><code>$ pip --version -bash: pip: command not found </code></pre> <p>I think I might have caused this issue messing with <code>$PATH</code>.</p> <p>When I run `sudo bash -c 'echo $PATH' I get:</p> <pre><code>/usr/sbin:/usr/bin:/sbin:/bin:usr/local/bin </code></pre> <p>Is this correct?</p>
0
2016-09-30T18:17:12Z
39,798,218
<p>Your problem is <code>usr/local/bin</code> in your path, it has to be <code>/usr/local/bin</code>.</p> <p>That should do it.</p> <p>You should be able to change that in the file <code>~/.bash_profile</code>.</p>
1
2016-09-30T18:49:42Z
[ "python", "pip" ]
Matplotlib3D color based points on their Z axis value
39,797,672
<p>I am currently scattering points in a 3D graph. My X,Y and Z are lists (len(Z)=R). However, I would like to give them a color based on their Z value. For example if Z>1 the color would be red, Z>2 blue Z>3 pink and so on. My current code is:</p> <pre><code>from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(X,Y,Z,for k in range (R): if Z&gt;1: color=['red']) plt.show() </code></pre>
0
2016-09-30T18:17:13Z
39,799,461
<p>If you see the gallery, you will find the answer. You need to pass an array to <code>c=colors</code>. See these: <a href="http://matplotlib.org/examples/mplot3d/scatter3d_demo.html" rel="nofollow">1</a>, <a href="http://matplotlib.org/examples/pie_and_polar_charts/polar_scatter_demo.html" rel="nofollow">2</a>.</p> <pre><code>import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt def randrange(n, vmin, vmax): return (vmax - vmin)*np.random.rand(n) + vmin fig = plt.figure(figsize=(8,5)) ax = fig.add_subplot(111, projection='3d') n = 100 xs = randrange(n, 23, 32) ys = randrange(n, 0, 100) zs = randrange(n, 0, 50) scat = ax.scatter(xs, ys, zs, c=zs, marker="o", cmap="viridis") plt.colorbar(scat) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/Vf9zp.png" rel="nofollow"><img src="http://i.stack.imgur.com/Vf9zp.png" alt="enter image description here"></a></p>
0
2016-09-30T20:18:09Z
[ "python", "matplotlib" ]
How to run a python script with arguments via the click of a button in javascript
39,797,807
<p>So I've written a program in JavaScript that outputs a JSON. What I want to do is, with the click of a button, I want to pass in that JSON as an argument to a python script.</p> <p>I am not entirely sure how to proceed with this:</p> <pre><code>$.ajax({ url: "/path/to/your/scriptPython", success: function(response) { // here you do whatever you want with the response variable } }); </code></pre> <p>Any feedback or help is appreciated.</p>
2
2016-09-30T18:25:12Z
39,798,133
<p>This depends on one important consideration: where is your Python code?</p> <p>If you want the Python to run on the user's machine, that gets complicated due to security measures: websites generally aren't allowed to execute arbitrary code on viewers' machines. (Imagine if that Python code wiped their hard drive, for instance.) In this case it might be best to have users download the JSON as a file, and then open that with your Python program.</p> <p>If you want the Python to run on your server, you can make a POST request to the script's endpoint, and pass the JSON in the POST data. The details of this will depend on your choice of Python web framework (I'm fond of Flask), but the Javascript would be pretty much the same:</p> <pre><code>$.ajax({ type: 'POST', data: my_json_variable, url: 'http://example.com/python_endpoint', success: function(response){ /* deal with the script's output */ } }); </code></pre>
0
2016-09-30T18:44:02Z
[ "javascript", "python", "ajax" ]
SettingWithCopyWarning on Column Creation
39,797,819
<p>I'm trying to create a moving average column for my data called 'mv_avg'. I'm getting a SettingWithCopyWarning that I have been unable to fix. I could suppress the warning, but I cannot figure out where in my code I am creating a copy, and I want to utilize best practices. I've created a generalizable example below to illustrate the problem.</p> <pre><code>data = {'category' : ['a', 'a', 'a', 'b', 'b', 'b'], 'value' : [1,2,3,4,5,6]} df = pd.DataFrame(data) df_a = df.loc[df['category'] == 'a'] df_a['mv_avg'] = df_a['value'].rolling(window=2).mean() </code></pre> <p>This returns: </p> <pre><code>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead </code></pre> <p>I've also tried the more verbose version:</p> <pre><code>df_a.loc[: , 'mv_avg'] = df_a.loc[:,'value'].rolling(window=2).mean() </code></pre> <p>but I get the same error. What is the best way to accomplish this without the warning?</p>
2
2016-09-30T18:25:38Z
39,798,005
<p>you can create a copy using .copy()</p> <pre><code>import pandas as pd data = {'category' : ['a', 'a', 'a', 'b', 'b', 'b'], 'value' : [1,2,3,4,5,6]} df = pd.DataFrame(data) df_a = df.loc[df['category'] == 'a'].copy() df_a['mv_avg'] = df_a['value'].rolling(window=2).mean() </code></pre> <p>or you can use an indexer such has :</p> <pre><code>import pandas as pd data = {'category' : ['a', 'a', 'a', 'b', 'b', 'b'], 'value' : [1,2,3,4,5,6]} df = pd.DataFrame(data) indexer = df[df['category'] == 'a'].index df_a = df.loc[indexer, :] df_a['mv_avg'] = df_a['value'].rolling(window=2).mean() </code></pre>
3
2016-09-30T18:35:32Z
[ "python", "pandas" ]
SettingWithCopyWarning on Column Creation
39,797,819
<p>I'm trying to create a moving average column for my data called 'mv_avg'. I'm getting a SettingWithCopyWarning that I have been unable to fix. I could suppress the warning, but I cannot figure out where in my code I am creating a copy, and I want to utilize best practices. I've created a generalizable example below to illustrate the problem.</p> <pre><code>data = {'category' : ['a', 'a', 'a', 'b', 'b', 'b'], 'value' : [1,2,3,4,5,6]} df = pd.DataFrame(data) df_a = df.loc[df['category'] == 'a'] df_a['mv_avg'] = df_a['value'].rolling(window=2).mean() </code></pre> <p>This returns: </p> <pre><code>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead </code></pre> <p>I've also tried the more verbose version:</p> <pre><code>df_a.loc[: , 'mv_avg'] = df_a.loc[:,'value'].rolling(window=2).mean() </code></pre> <p>but I get the same error. What is the best way to accomplish this without the warning?</p>
2
2016-09-30T18:25:38Z
39,798,051
<p>Here are three options</p> <ol> <li><p>Ignore/filter the warning; in this case it is spurious as you are deliberately assigning to a filtered DataFrame.</p></li> <li><p>If you are done with <code>df</code>, you could <code>del</code> it, which will prevent the warning, because <code>df_a</code>will no longer hold a reference to <code>df</code>.</p></li> <li><p>Take a copy as in the other answer</p></li> </ol>
2
2016-09-30T18:39:06Z
[ "python", "pandas" ]
Wedge Patch Position Not Updating
39,797,843
<p>I am attempting to shift the position of a <code>matplotlib.patches.Wedge</code> by modifying its <code>center</code> property, but it does not seem to have any effect.</p> <p>For example:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.patches as patches fig = plt.figure() ax = fig.add_subplot(111) tmp = patches.Wedge([2, 2], 3, 0, 180) ax.add_artist(tmp) tmp.center = [4, 4] # Try to move! ax.set_xlim([0, 10]) ax.set_ylim([0, 10]) print(tmp.center) plt.show() </code></pre> <p>Produces the following:</p> <p><a href="http://i.stack.imgur.com/at9Fg.png" rel="nofollow"><img src="http://i.stack.imgur.com/at9Fg.png" alt="sad"></a></p> <p>Which is clearly incorrect.</p> <p>A similar approach functions fine for <code>matplotlib.patches.Ellipse</code>:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.patches as patches fig = plt.figure() ax = fig.add_subplot(111) tmp = patches.Ellipse([2, 2], 2, 2) ax.add_artist(tmp) tmp.center = [4, 4] # Try to move! ax.set_xlim([0, 10]) ax.set_ylim([0, 10]) print(tmp.center) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/xzLCK.png" rel="nofollow"><img src="http://i.stack.imgur.com/xzLCK.png" alt="ellip"></a></p> <p>And <code>matplotlib.patches.Rectangle</code> (with the change from <code>center</code> to <code>xy</code>)</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.patches as patches fig = plt.figure() ax = fig.add_subplot(111) tmp = patches.Rectangle([2, 2], 3, 2) ax.add_artist(tmp) tmp.xy = [4, 4] # Try to move! ax.set_xlim([0, 10]) ax.set_ylim([0, 10]) print(tmp.xy) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/5RYHz.png" rel="nofollow"><img src="http://i.stack.imgur.com/5RYHz.png" alt="rect"></a></p> <p>I thought it might be <code>Wedge</code> utilizing <code>xy</code> rather than <code>center</code>, but the <code>Wedge</code> object does not have an <code>xy</code> attribute. What am I missing here?</p>
2
2016-09-30T18:26:50Z
39,798,332
<p>You probably have to <code>update</code> the properties of your <code>Wedge</code>:</p> <pre><code>tmp.update({'center': [4,4]}) </code></pre> <p>As you see, the method accepts a dict that specifies the properties to update.</p> <p><a href="http://i.stack.imgur.com/cppA9.png" rel="nofollow"><img src="http://i.stack.imgur.com/cppA9.png" alt="result"></a></p>
1
2016-09-30T18:56:09Z
[ "python", "python-3.x", "matplotlib" ]
Working with time series in Pandas/Python
39,798,002
<p>I have the following data:</p> <pre><code> AdjClose Chg RM Target date 2014-01-16 41.733862 0.002045 0 NaN 2014-01-17 41.695141 -0.000928 1 NaN 2014-01-21 42.144309 0.010773 1 NaN 2014-01-22 41.803561 -0.008085 1 NaN 2014-01-23 41.640931 -0.003890 0 3.0 2014-01-24 41.586721 -0.001302 0 3.0 2014-01-27 41.323416 -0.006331 0 2.0 2014-01-28 41.710630 0.009370 1 2.0 2014-01-29 41.780328 0.001671 0 1.0 2014-01-30 42.701896 0.022057 0 1.0 </code></pre> <p>I'm sure there is an easy way to do this, but I have yet to figure it out. For each day, I need to see how many times over the previous n days, has there been an up/down or down/up movement.</p> <p>My ugly solution was to do the following for a 5day Target:</p> <pre><code>dd['RM']=0 dd['RM'][((dd['Chg']&gt;0) &amp; (dd['Chg'].shift(1)&lt;0))| ((dd['Chg']&lt;0) &amp; (dd['Chg'].shift(1)&gt;0))] = 1 dd['Target']=pd.rolling_sum(dd['RM'],window=5) </code></pre> <p>and then just do a rolling_sum over the previous n days.</p> <p>I would love some help with a more elegant solution. Thank you.</p>
2
2016-09-30T18:35:22Z
39,798,914
<p>I would do a <code>rolling_sum()</code> exactly as you have done, though I think the up/down and down/up are easily measured as <em>when the sign changes</em>:</p> <pre><code>dd['RM'] = np.int64(np.sign(dd['Chg']) != np.sign(dd['Chg'].shift(1))) dd['RM'].values[0] = 0 </code></pre>
2
2016-09-30T19:36:10Z
[ "python", "pandas" ]
How do I insert a space after and before a dash that is not already surrounded by spaces?
39,798,023
<p>Let's say I have these strings:</p> <pre><code>string1= "Queen -Bohemian Rhapsody" string2= "Queen-Bohemian Rhapsody" string3= "Queen- Bohemian Rhapsody" </code></pre> <p>I want all of them to become to be like this:</p> <pre><code> string1= "Queen - Bohemian Rhapsody" string2= "Queen - Bohemian Rhapsody" string3= "Queen - Bohemian Rhapsody" </code></pre> <p>How can I do this in Python?</p> <p>Thanks!</p>
2
2016-09-30T18:37:23Z
39,798,065
<p>You can regexp:</p> <pre><code>import re pat = re.compile(r"\s?-\s?") # \s? matches 0 or 1 occurenece of white space # re.sub replaces the pattern in string string1 = re.sub(pat, " - ", string1) string2 = re.sub(pat, " - ", string2) string3 = re.sub(pat, " - ", string3) </code></pre>
6
2016-09-30T18:39:51Z
[ "python", "regex", "string" ]
Printing columns in a DB2 database
39,798,026
<p>I want to print all the columns of a table in a database in db2. This is the current code I have now for doing that.</p> <pre><code>#!/usr/bin/python import ibm_db from ibm_db import tables, fetch_assoc, exec_immediate conn = ibm_db.connect("DATABASE=DB;HOSTNAME=9.6.24.89;PORT=50000;PROTOCOL=TCPIP;UID=R1990;PWD=secret;", "", "") def results(command): ret = [] result = fetch_assoc(command) while result: # This builds a list in memory. Theoretically, if there's a lot of rows, # we could run out of memory. In practice, I've never had that happen. # If it's ever a problem, you could use # yield result # Then this function would become a generator. You lose the ability to access # results by index or slice them or whatever, but you retain # the ability to iterate on them. ret.append(result) result = fetch_assoc(command) return ret # Ditch this line if you choose to use a generator. t = results(tables(conn)) sql = "SELECT * FROM SYSIBM.SYSTABLES WHERE type = 'T' AND name= 'Tables' " # Using our list of tables t from before... stmt = ibm_db.exec_immediate(conn, sql) tuple = ibm_db.fetch_both(stmt) count = 0 while tuple != False: print tuple tuple = ibm_db.fetch_tuple(stmt) </code></pre> <p>The results mostly look like this.</p> <blockquote> <p>\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x0f\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\xbf\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00</p> </blockquote> <p>Can someone please help me out with this? Fairly new to this.</p>
0
2016-09-30T18:37:36Z
39,803,514
<p>I think you have a problem of encodage format (Unicode possible)</p> <p>->And if you try this query, have you the same result?:</p> <pre><code> SELECT cast(TABLE_NAME as varchar(255) ccsid 1147) TABLE_NAME FROM SYSIBM.SYSTABLES WHERE type = 'T' AND name= 'Tables' </code></pre> <p>->May be can you try this too:</p> <pre><code> ibm_db.exec_immediate(conn, sql).decode('cp-1251') </code></pre>
0
2016-10-01T05:58:16Z
[ "python", "database", "python-2.7", "db2" ]
Can't connect to compose.io mongoDB on bluemix
39,798,088
<p>I'm trying connect to mongoDB but it seems that I can't reach the host.</p> <p>This problem occurs in mongoshell and pymongo. On shell I use</p> <pre><code>mongo --ssl --sslAllowInvalidCertificates host:port/db -u user -p pass --sslCAFile ca.pem </code></pre> <p>and I get the error message bellow.</p> <pre><code>MongoDB shell version: 3.2.9 connecting to: host:port/db 2016-09-30T13:41:57.268-0300 W NETWORK [thread1] Failed to connect to host_ip:port after 5000 milliseconds, giving up. 2016-09-30T13:41:57.323-0300 E QUERY [thread1] Error: couldn't connect to server host:port, connection attempt failed : connect@src/mongo/shell/mongo.js:231:14 @(connect):1:6 exception: connect failed </code></pre> <p>On pymongo, I connect with the code bellow </p> <pre><code>Config = configparser.ConfigParser() Config.read('configurations.cfg') mongo_conf = Config['mongoDB_test'] connect = "mongodb://%s:%s@%s:%s/%s?ssl=true" \ %(mongo_conf['user'],mongo_conf['pass'],mongo_conf['host'],mongo_conf['port'],mongo_conf['database']) client = MongoClient(connect,ssl_ca_certs=mongo_conf['cert']) db = client[mongo_conf['database']] </code></pre> <p>and when I run, I get this</p> <pre><code>Traceback (most recent call last): File "test.py", line 24, in &lt;module&gt; db.test.insert_one(data) File "/home/jmpf13/repos/laura/dev_env/lib/python3.5/site-packages/pymongo/collection.py", line 627, in insert_one with self._socket_for_writes() as sock_info: File "/usr/lib/python3.5/contextlib.py", line 59, in __enter__ return next(self.gen) File "/home/jmpf13/repos/laura/dev_env/lib/python3.5/site-packages/pymongo/mongo_client.py", line 762, in _get_socket server = self._get_topology().select_server(selector) File "/home/jmpf13/repos/laura/dev_env/lib/python3.5/site-packages/pymongo/topology.py", line 210, in select_server address)) File "/home/jmpf13/repos/laura/dev_env/lib/python3.5/site-packages/pymongo/topology.py", line 186, in select_servers self._error_message(selector)) pymongo.errors.ServerSelectionTimeoutError: host:port: timed out </code></pre>
0
2016-09-30T18:41:23Z
39,798,536
<p>I've just connected to a mongoDB instance I've deployed to bluemix using mongo shell with similar syntax to what you've used, and it works fine.</p> <p>There might be a problem with your deployment. In the bluemix ui, when you open your mongo service, does the "Status" indicator appear green?</p> <p>The other thing I would do is try to verify that host is reachable on that port. For instance, using something like tcping: <code>tcping &lt;host&gt; &lt;port&gt;</code></p> <p>Or, if in a pinch, telnet to the port: <code>telnet &lt;host&gt; &lt;port&gt;</code> For the latter you'll get something like:</p> <p><code>Trying &lt;ip&gt;... Connected to &lt;host&gt;. Escape character is '^]'.</code></p> <p>If any of these fail, I'd make sure nothing on your end is blocking the traffic and then reach out to support in case your deployment did not provision correctly or otherwise has issues.</p>
2
2016-09-30T19:10:18Z
[ "python", "mongodb", "ibm-bluemix", "pymongo", "compose" ]
Matching pairs game in Python tkinter
39,798,141
<p>I am trying to create a matching card game in Python 3 tkinter. The player is presented with a 4x4 grid of buttons, each button with an image. There are eight pairs of images. The player clicks on a button, and the button shows the image; the player clicks on another button to show its image. If the two buttons show the same image, the images stay until the game ends; else, when I click another button, both these images cease to be displayed. </p> <p>I can create the grid, however, I'm having trouble getting the actual game to work. Below is the code I've created so far.</p> <pre><code>#Import all necessary modules. from tkinter import * from tkinter import ttk import random #Imnporting shuffle allows us to shuffle a list. from random import shuffle import time #Create canvas and assign it to variable root. root = Tk() #Making photo accessible def stimage(file): return PhotoImage(width=100,height=100,file=file) clicks=[] clickCount=0 faceUp=[] score=0 back = PhotoImage(width=100, height=100, file="blank space.gif") images = [stimage("homer.gif"), stimage("ducky.gif"), stimage("hulk.gif"), stimage("torus.gif"), stimage("ronaldo-moth.gif"), stimage("beyonce.gif"), stimage("monkey.gif"), stimage("kim.gif")] #Function returns a button, equipped with a command that changes its background colour. It takes the argument image. def button(n): #Create a button with parent root, and a red colour for image. This will be the back of each card. button = Button(root,height=100,width=100, image=back) #Command for button. Flips over when clicked. def flip(): global clickCount global faceUp clickCount+=1 #Make the card display an image. button.config(image=images[n]) #If image of button is displayed, append to list faceUp if button.cget("image")!=back: #Append the button object and image index n to list faceUp faceUp.append([button,n]) if clickCount==2: clickCount=0 if faceUp[0][1]==faceUp[1][1]: print("Hello") else: button.config(image=back) faceUp=[] button.config(command=flip) return button #Create a list of coordinates that the buttons will occupy. coord = [[a,b] for a in range(1,5) for b in range(1,5)] #Randomise coordinates so buttons appear in random places. random.shuffle(coord) buttons=[] for i in range(8): buttons.append(button(i)) buttons[2*i].grid(row=coord[i][0], column=coord[i][1]) buttons.append(button(i)) buttons[2*i+1].grid(row=coord[i+8][0], column=coord[i+8][1]) </code></pre> <p>It doesn't work because if you click a non-matching pair, the button just fails to show its image. </p> <p>Could anyone help?</p>
-1
2016-09-30T18:44:24Z
39,798,189
<p>you need to create an ifelse statement that checks for the legality of the move, if it is legal, continue with script, if else give the user a message but loop it back to the user guess. </p>
0
2016-09-30T18:47:18Z
[ "python", "python-3.x", "tkinter" ]
Pretty Printing (2D Arrays, Box)
39,798,149
<p>I have written the following code:</p> <pre><code>for row in range(len(listOfLists)): print('+' + '-+'*len(listOfLists)) print('|', end='') for col in range(len(listOfLists[row])): print(listOfLists[row][col], end='|') print(' ') #To change lines print('+' + '-+'*len(listOfLists)) </code></pre> <p>Input: </p> <blockquote> <pre><code>[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']] </code></pre> </blockquote> <p>Output:</p> <blockquote> <pre><code>+-+-+-+-+ |a|b|c| +-+-+-+-+ |d|e|f| +-+-+-+-+ |g|h|i| +-+-+-+-+ |j|k|l| +-+-+-+-+ </code></pre> </blockquote> <p>Desired Output:</p> <blockquote> <pre><code>+-+-+-+ |a|b|c| +-+-+-+ |d|e|f| +-+-+-+ |g|h|i| +-+-+-+ |j|k|l| +-+-+-+ </code></pre> </blockquote> <p>Which prints a '+-+' around the elements of the 2D array. However, my code only works for a square array (n^2).</p> <p>How can I generalise it so that it works for any variation of array (as long as all lists are equal length)</p> <p>Thank you</p>
2
2016-09-30T18:44:49Z
39,798,299
<p>Your problem was that <code>len(listOfLists)</code> was used for the size of the printed table in both directions. <code>len(listOfLists)</code> defaults to number of rows, by doing <code>len(listOfLists[1])</code> you get the number of columns.</p> <pre><code> listOfLists = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']] for row in range(len(listOfLists)): print('+' + '-+'*len(listOfLists[0])) print('|', end='') for col in range(len(listOfLists[row])): print(listOfLists[row][col], end='|') print(' ') #To change lines print('+' + '-+'*(len(listOfLists[0]))) </code></pre> <p>output: </p> <pre><code>+-+-+-+ |a|b|c| +-+-+-+ |d|e|f| +-+-+-+ |g|h|i| +-+-+-+ |j|k|l| +-+-+-+ </code></pre> <p>Happy coding!</p>
2
2016-09-30T18:54:27Z
[ "python", "arrays", "multidimensional-array" ]
Pretty Printing (2D Arrays, Box)
39,798,149
<p>I have written the following code:</p> <pre><code>for row in range(len(listOfLists)): print('+' + '-+'*len(listOfLists)) print('|', end='') for col in range(len(listOfLists[row])): print(listOfLists[row][col], end='|') print(' ') #To change lines print('+' + '-+'*len(listOfLists)) </code></pre> <p>Input: </p> <blockquote> <pre><code>[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']] </code></pre> </blockquote> <p>Output:</p> <blockquote> <pre><code>+-+-+-+-+ |a|b|c| +-+-+-+-+ |d|e|f| +-+-+-+-+ |g|h|i| +-+-+-+-+ |j|k|l| +-+-+-+-+ </code></pre> </blockquote> <p>Desired Output:</p> <blockquote> <pre><code>+-+-+-+ |a|b|c| +-+-+-+ |d|e|f| +-+-+-+ |g|h|i| +-+-+-+ |j|k|l| +-+-+-+ </code></pre> </blockquote> <p>Which prints a '+-+' around the elements of the 2D array. However, my code only works for a square array (n^2).</p> <p>How can I generalise it so that it works for any variation of array (as long as all lists are equal length)</p> <p>Thank you</p>
2
2016-09-30T18:44:49Z
39,798,301
<pre><code>def awesome_print(listOfLists): for row in range(len(listOfLists)): print('+' + '-+'*len(listOfLists[row])) print('|', end='') for col in range(len(listOfLists[row])): print(listOfLists[row][col], end='|') print(' ') #To change lines print('+' + '-+'*len(listOfLists[row])) awesome_print([[1,2,3], [1,2,3], [2,3,0], [2,3,4]]) </code></pre> <p>Output</p> <pre><code>+-+-+-+ |1|2|3| +-+-+-+ |1|2|3| +-+-+-+ |2|3|0| +-+-+-+ |2|3|4| +-+-+-+ </code></pre> <p>In case you need to print data with non fixed size of subarrays</p> <pre><code>def awesome_print2(listOfLists): for row in range(len(listOfLists)): print('+' + '-+'*len(listOfLists[row])) print('|', end='') for col in range(len(listOfLists[row])): print(listOfLists[row][col], end='|') print() print('+' + '-+'*len(listOfLists[row])) awesome_print2([[1,2,3,5], [1,2,3], [2,3,0,6,3], [2,3,4]]) </code></pre> <p>Output: </p> <pre><code>+-+-+-+-+ |1|2|3|5| +-+-+-+-+ +-+-+-+ |1|2|3| +-+-+-+ +-+-+-+-+-+ |2|3|0|6|3| +-+-+-+-+-+ +-+-+-+ |2|3|4| +-+-+-+ </code></pre>
1
2016-09-30T18:54:39Z
[ "python", "arrays", "multidimensional-array" ]
Pretty Printing (2D Arrays, Box)
39,798,149
<p>I have written the following code:</p> <pre><code>for row in range(len(listOfLists)): print('+' + '-+'*len(listOfLists)) print('|', end='') for col in range(len(listOfLists[row])): print(listOfLists[row][col], end='|') print(' ') #To change lines print('+' + '-+'*len(listOfLists)) </code></pre> <p>Input: </p> <blockquote> <pre><code>[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l']] </code></pre> </blockquote> <p>Output:</p> <blockquote> <pre><code>+-+-+-+-+ |a|b|c| +-+-+-+-+ |d|e|f| +-+-+-+-+ |g|h|i| +-+-+-+-+ |j|k|l| +-+-+-+-+ </code></pre> </blockquote> <p>Desired Output:</p> <blockquote> <pre><code>+-+-+-+ |a|b|c| +-+-+-+ |d|e|f| +-+-+-+ |g|h|i| +-+-+-+ |j|k|l| +-+-+-+ </code></pre> </blockquote> <p>Which prints a '+-+' around the elements of the 2D array. However, my code only works for a square array (n^2).</p> <p>How can I generalise it so that it works for any variation of array (as long as all lists are equal length)</p> <p>Thank you</p>
2
2016-09-30T18:44:49Z
39,798,347
<p>You are printing this separator based on number of rows, not number of columns. Using additional test cases helps with debugging immediately.</p> <pre><code>def printListOfLists(listOfLists): for row in range(len(listOfLists)): print('+' + '-+' * len(listOfLists[0])) print('|', end='') for col in range(len(listOfLists[row])): print(listOfLists[row][col], end='|') print(' ') # To change lines print('+' + '-+' * len(listOfLists[0])) printListOfLists([ ['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['j', 'k', 'l'] ]) printListOfLists([['a', 'b', 'c']]) printListOfLists([['a'], ['b'], ['c']]) </code></pre> <p>All produced results are now expected:</p> <pre><code>+-+-+-+ |a|b|c| +-+-+-+ |d|e|f| +-+-+-+ |g|h|i| +-+-+-+ |j|k|l| +-+-+-+ +-+-+-+ |a|b|c| +-+-+-+ +-+ |a| +-+ |b| +-+ |c| +-+ </code></pre>
2
2016-09-30T18:57:22Z
[ "python", "arrays", "multidimensional-array" ]
LINE RESTful Messaging API - Error with wrong IP address
39,798,152
<p>I am using LINE Messaging API trying to push a message via bot. I've followed the configuration/setup detailed in <a href="https://business.line.me/en/" rel="nofollow">https://business.line.me/en/</a> and encountered this error - Access to this API denied due to the following reason: Your ip address [23.3.104.4] is not allowed to access this API. Please add your IP to the IP whitelist in the developer center."</p> <p>But I already added my ip to the Server Whitelist in the developer center. The IP indicated in the error is not even my ip.</p> <p>Below is snippet of python code:</p> <pre><code>def line_http(uri, req_body, accessToken, m='post'): req_headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + accessToken } if m=='post': result = urlfetch.post(url=uri, payload=req_body, headers=req_headers) else: result = urlfetch.get(url=uri, payload=req_body, headers=req_headers) return result resp = line_http('https://api.line.me/v1/profile', {},'xxxxxxxxxxx', 'get') r = json.loads(resp.body) pprint(r) mid = r['mid'] req_body={'to':mid, 'messages':[{'type': 'text', 'text': "SPBotReport finished."}]} jsonStr = json.dumps(req_body) resp = line_http('https://api.line.me/v2/bot/message/push', jsonStr, 'xxxxxxxxxxx') if resp.status == 200: print("SPBotReport LINE text finished successfully.") sys.exit() else: print("Status:%s, Reason:%s" % (resp.status, resp.reason)) if resp.headers["content-type"].find("json") &gt; 0: r = json.loads(resp.body) print("message: %s" % r["message"]) </code></pre>
0
2016-09-30T18:44:59Z
39,864,043
<p>I think that might be a bug and caused of "Server IP Whitelist" in your bot settings. Try to remove the ip address you assigned.</p>
0
2016-10-05T01:20:54Z
[ "python", "line" ]
Reading 24-Bit WAV with wavio Python 3.5
39,798,259
<p>I am using <a href="https://github.com/WarrenWeckesser/wavio/blob/master/wavio.py" rel="nofollow">wavio</a> by WarrenWeckesser as I need to read 24-bit wav files in python. The wav files I have are produced by some instrumentation and I am trying to get the raw values without any normalisation or scaling.</p> <p>In the wavio module the code that does the work is this:</p> <pre><code> if sampwidth == 3: a = _np.empty((num_samples, nchannels, 4), dtype=_np.uint8) raw_bytes = _np.fromstring(data, dtype=_np.uint8) a[:, :, :sampwidth] = raw_bytes.reshape(-1, nchannels, sampwidth) a[:, :, sampwidth:] = (a[:, :, sampwidth - 1:sampwidth] &gt;&gt; 7) * 255 result = a.view('&lt;i4').reshape(a.shape[:-1] </code></pre> <p>Can someone explain what it is actually doing (I am a relatively new to numpy and array slicing). I understand most of it but I don't understand what is going on here:</p> <pre><code> a[:, :, sampwidth:] = (a[:, :, sampwidth - 1:sampwidth] &gt;&gt; 7) * 255 </code></pre> <p>In my case it does the transform from 24 to 32 bit but I can't work out whether it is scaling the data, or simply padding it out without changing any raw values.</p>
0
2016-09-30T18:52:49Z
39,799,109
<p>The shape of <code>a</code> is <code>(num_samples, nchannels, 4)</code> and <code>sampwidth == 3</code>, so that line is the same as</p> <pre><code>a[:, :, 3:] = (a[:, :, 2:3] &gt;&gt; 7) * 255 </code></pre> <p>which is the same as</p> <pre><code>a[:, :, 3] = (a[:, :, 2] &gt;&gt; 7) * 255 </code></pre> <p>we could devectorize the outer two loops:</p> <pre><code>for i in range(num_samples): for j in range(nchannels): a[i, j, 3] = (a[i, j, 2] &gt;&gt; 7) * 255 </code></pre> <p>The dtype of <code>a</code> is <code>_np.uint8</code>, so <code>a[...] &gt;&gt; 7</code> can only give out 0 when the value is &lt;128, or 1 when it is ≥128, so the above becomes:</p> <pre><code>for i in range(num_samples): for j in range(nchannels): v = a[i, j, 2] a[i, j, 3] = 255 if v &gt;= 128 else 0 </code></pre> <p>If the data are 24-bit little-endian integers, this is equivalent to doing a <a href="https://en.wikipedia.org/wiki/Sign_extension" rel="nofollow">sign-extension</a> into 32-bit.</p>
1
2016-09-30T19:50:06Z
[ "python", "numpy", "wav" ]
Python NIM game: how do i add new game (y) or (n)
39,798,278
<p>I have a question: How do i put New Game in code or PlayAgain (y) or (n) This is for my school project. I have been trying to find myself a solution but it will only repeat question "play again" or error. </p> <pre><code> import random player1 = input("Enter your real name: ") player2 = "Computer" state = random.randint(12,15) print("The number of sticks is " , state) while(True): print(player1) while(True): move = int(input("Enter your move: ")) if move in (1,2,3) and move &lt;= state: break print("Illegal move") state = state - move print("The number of sticks is now " , state) if state == 0: print(player1 , "wins") break print(player2) move = random.randint(1,3) if state in (1,2,3): move = state print("My move is " , move) state = state - move print("The number of sticks is now " , state) if state == 0: print("Computer wins") break </code></pre>
0
2016-09-30T18:53:44Z
39,799,347
<p>Your loop condition is always <code>True</code>. This is what needs adjusting. Instead you only want to loop while the user wants to continue</p> <pre><code>choice = 'y' # so that we run at least once while choice == 'y': ... choice = input("Play again? (y/n):") </code></pre> <p>You will have to make sure to reset the state each time you begin a new game.</p> <p>Since you have multiple points at which your game can end, you'll need to either refactor your code, or replace the <code>break</code>s. For example</p> <pre><code>if state == 0: print(player1 , "wins") choice = input("Play again? (y/n):") continue </code></pre> <p>Or what may be easier is to put the game into an inner loop</p> <pre><code>choice = 'y' while choice == 'y': while True: ... if state == 0: print(player1, "wins") break ... choice = input("Play again? (y/n):") </code></pre> <p>At that point I'd start factoring things into functions if I were you</p>
0
2016-09-30T20:07:59Z
[ "python", "python-3.x" ]
Override django model save function that extends AbstractBaseUser
39,798,306
<p>Im using restframework for user signup i need generate random password before save, i override save method in model but this never run and throw message password field is required. ¿How i can override this? Thanks.</p> <pre><code># ViewSet. class AgentViewSet(viewsets.ModelViewSet): queryset = Agents.objects.all() serializer_class = AgentSerializer permission_classes = (permissions.AllowAny,) http_method_names = ['post'] # Model. class Agents(AbstractBaseUser): oldkey = models.CharField(max_length=32, blank=True, null=True) is_main_user = models.IntegerField(blank=True, null=True) name = models.CharField(max_length=45, blank=True, null=True) lastname = models.CharField(max_length=45, blank=True, null=True) email1 = models.CharField( max_length=100, blank=True, null=True, unique=True ) email2 = models.CharField(max_length=100, blank=True, null=True) city = models.CharField(max_length=200, blank=True, null=True) country = models.ForeignKey( 'bdetail.Countries', models.DO_NOTHING, db_column='country', blank=True, null=True ) username = models.CharField(max_length=30, blank=True, null=True) image = models.CharField(max_length=80, blank=True, null=True) num_access = models.IntegerField(blank=True, null=True) phone1 = models.CharField(max_length=20, blank=True, null=True) phone2 = models.CharField(max_length=20, blank=True, null=True) phone3 = models.CharField(max_length=20, blank=True, null=True) whatsapp = models.CharField(max_length=20, blank=True, null=True) permissions = models.CharField( max_length=10, blank=True, null=True, default='limited') fb_profile_id = models.CharField(max_length=30, blank=True, null=True) fb_access_token = models.TextField(blank=True, null=True) clients = models.ForeignKey( 'Clients', models.DO_NOTHING, blank=True, null=True ) last_login_time = models.IntegerField(blank=True, null=True) about = models.TextField('Acerca de mi', blank=True) USERNAME_FIELD = 'email1' REQUIRED_FIELDS = ['name'] objects = MyUserManager() class Meta: db_table = 'agents' def get_full_name(self): return self.name, ' ', self.lastname def get_short_name(self): return self.name def has_perm(self, perm, obj=None): return True def save(self, *args, **kwargs): raise Exception('ingres') def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True def __unicode__(self): return unicode(self.name) or u'' @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return False </code></pre>
0
2016-09-30T18:54:51Z
39,798,451
<p>Try overriding the <code>create_user</code> method in your <code>MyUserManager</code>. Something like:</p> <pre><code>def create_user(self, **kwargs): kwargs['password'] = # Generate random password return super().create_user(**kwargs) </code></pre>
0
2016-09-30T19:03:20Z
[ "python", "django", "python-2.7", "login", "django-rest-framework" ]
Override django model save function that extends AbstractBaseUser
39,798,306
<p>Im using restframework for user signup i need generate random password before save, i override save method in model but this never run and throw message password field is required. ¿How i can override this? Thanks.</p> <pre><code># ViewSet. class AgentViewSet(viewsets.ModelViewSet): queryset = Agents.objects.all() serializer_class = AgentSerializer permission_classes = (permissions.AllowAny,) http_method_names = ['post'] # Model. class Agents(AbstractBaseUser): oldkey = models.CharField(max_length=32, blank=True, null=True) is_main_user = models.IntegerField(blank=True, null=True) name = models.CharField(max_length=45, blank=True, null=True) lastname = models.CharField(max_length=45, blank=True, null=True) email1 = models.CharField( max_length=100, blank=True, null=True, unique=True ) email2 = models.CharField(max_length=100, blank=True, null=True) city = models.CharField(max_length=200, blank=True, null=True) country = models.ForeignKey( 'bdetail.Countries', models.DO_NOTHING, db_column='country', blank=True, null=True ) username = models.CharField(max_length=30, blank=True, null=True) image = models.CharField(max_length=80, blank=True, null=True) num_access = models.IntegerField(blank=True, null=True) phone1 = models.CharField(max_length=20, blank=True, null=True) phone2 = models.CharField(max_length=20, blank=True, null=True) phone3 = models.CharField(max_length=20, blank=True, null=True) whatsapp = models.CharField(max_length=20, blank=True, null=True) permissions = models.CharField( max_length=10, blank=True, null=True, default='limited') fb_profile_id = models.CharField(max_length=30, blank=True, null=True) fb_access_token = models.TextField(blank=True, null=True) clients = models.ForeignKey( 'Clients', models.DO_NOTHING, blank=True, null=True ) last_login_time = models.IntegerField(blank=True, null=True) about = models.TextField('Acerca de mi', blank=True) USERNAME_FIELD = 'email1' REQUIRED_FIELDS = ['name'] objects = MyUserManager() class Meta: db_table = 'agents' def get_full_name(self): return self.name, ' ', self.lastname def get_short_name(self): return self.name def has_perm(self, perm, obj=None): return True def save(self, *args, **kwargs): raise Exception('ingres') def has_module_perms(self, app_label): "Does the user have permissions to view the app `app_label`?" # Simplest possible answer: Yes, always return True def __unicode__(self): return unicode(self.name) or u'' @property def is_staff(self): "Is the user a member of staff?" # Simplest possible answer: All admins are staff return False </code></pre>
0
2016-09-30T18:54:51Z
39,799,199
<p>Add or update in your code</p> <p>AgentSerializer(serializers.py)</p> <pre><code>class AgentSerializer(serializers.ModelSerializer): class Meta: model = Agents def create(self, validated_data): return Agents.objects.create(**validated_data) </code></pre> <p>In views.py</p> <pre><code>class AgentViewSet(viewsets.ModelViewSet): queryset = Agents.objects.all() serializer_class = AgentSerializer permission_classes = (permissions.AllowAny,) http_method_names = ['post'] def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): Agents.objects.create_user(**serializer.validated_data) return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return JSONResponse(serializer.errors, status=400) </code></pre> <p>In models.py:</p> <pre><code>class MyUserManager(BaseUserManager): def _create_user(self, email, password, is_staff, **extra_fields): password= # Generate random password email = self.normalize_email(email) user = self.model(email=email, is_staff=is_staff, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): return self._create_user(email, password, False **extra_fields) </code></pre>
1
2016-09-30T19:57:14Z
[ "python", "django", "python-2.7", "login", "django-rest-framework" ]
GeoPoint equivalent for a Cartesian coordinate system
39,798,328
<p>I have fields <code>x</code> and <code>y</code> on some search documents that correspond to Cartesian coordinates, and I'd like to perform a radial search like:</p> <pre><code>query = '(x * x) + (y * y) &lt; 100' </code></pre> <p>which would equate to "find all the things less than 10m away from (0,0)"</p> <p>Trying to use that <em>particular</em> expression fails with <code>QueryError: Failed to parse query</code>, so it seems I need to take another approach.</p> <p><strong>Is there a built-in way to do this?</strong></p> <p>I've seen the GeoPoint fields and <code>distance</code> query function that nearly do what I need, the problem being that my <code>x,y</code>s aren't longitude and latitude. I've thought about trying to abuse this - map all coordinates to a much smaller domain, in which the lat/long system closely approximates the Cartesian domain. This seems a little hacky though, so I'm looking for something better.</p>
2
2016-09-30T18:56:01Z
39,849,952
<p><strong>No, there isn't.</strong></p> <p>The search API doesn't support arbitrarily computed expressions on fields (like <code>x * x</code> in your example). What it does support is enumerated <a href="https://cloud.google.com/appengine/docs/python/search/query_strings" rel="nofollow">here</a>. Your mapping from Cartesian coordinates to lat/long fields sounds like it would be the most plausible approach.</p> <p>(Full disclosure: I'm on the team.)</p>
1
2016-10-04T10:29:08Z
[ "python", "google-app-engine", "google-cloud-platform" ]
Executing related os commands in python
39,798,453
<p>I'm trying to create a simple script in python which is essentially a shell terminal. It will repeatedly ask for input commands and will attempt to execute the given os commands. What I cannot figure out, is how to make Python 'remember' the commands that were executed.</p> <p>Example of what I mean:</p> <ol> <li>User inputs <code>ls</code> </li> <li>Python prints contents of current directory</li> <li>Next user inputs <code>cd exampledir</code></li> <li>Python executes the command</li> <li>User inputs <code>ls</code></li> <li>Python prints contents of <code>exampledir</code></li> </ol> <p>Since the command sequence is <code>ls</code> > <code>cd exampledir</code> > <code>ls</code> I expect the program to return the contents of the exampledir, but instead the output of the two <code>ls</code> commands is the same.</p> <p>Is there a way to make Python somehow 'remember' the commands that were executed and execute next command based on the previous ones?</p> <p>I know you can use something like <code>cd exampledir &amp;&amp; ls</code> but this is not what I'm looking for. The commands must be executed separately like in a shell terminal.</p> <p>Code so far:</p> <pre><code>import subprocess while True: cmd = input("Command to Execute: ") p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = p.communicate()[0] print(out) </code></pre>
0
2016-09-30T19:03:46Z
39,798,507
<p>you cant <code>cd</code> out with the <code>subprocess</code> module, the function will run but the path wont change for the python script that is running,<br> what you can do instead is something like:</p> <pre><code>import os if # condition where cd command used: os.chdir("path/to/new/dir") </code></pre> <p>this will change the path for the python script that you're running and then you can <code>ls</code> to get a different output.</p>
1
2016-09-30T19:08:02Z
[ "python", "linux", "shell", "command", "subprocess" ]
Executing related os commands in python
39,798,453
<p>I'm trying to create a simple script in python which is essentially a shell terminal. It will repeatedly ask for input commands and will attempt to execute the given os commands. What I cannot figure out, is how to make Python 'remember' the commands that were executed.</p> <p>Example of what I mean:</p> <ol> <li>User inputs <code>ls</code> </li> <li>Python prints contents of current directory</li> <li>Next user inputs <code>cd exampledir</code></li> <li>Python executes the command</li> <li>User inputs <code>ls</code></li> <li>Python prints contents of <code>exampledir</code></li> </ol> <p>Since the command sequence is <code>ls</code> > <code>cd exampledir</code> > <code>ls</code> I expect the program to return the contents of the exampledir, but instead the output of the two <code>ls</code> commands is the same.</p> <p>Is there a way to make Python somehow 'remember' the commands that were executed and execute next command based on the previous ones?</p> <p>I know you can use something like <code>cd exampledir &amp;&amp; ls</code> but this is not what I'm looking for. The commands must be executed separately like in a shell terminal.</p> <p>Code so far:</p> <pre><code>import subprocess while True: cmd = input("Command to Execute: ") p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = p.communicate()[0] print(out) </code></pre>
0
2016-09-30T19:03:46Z
39,798,917
<p>The thing that you have to understand is: you want to write a <strong>full</strong> interpreter of shell commands. That means: any command that alters the <strong>state</strong> of your <strong>shell</strong> ... needs to well, change some internal state. </p> <p>Meaning: your python "interpreter" starts within a certain directory. So when you tell the interpreter to <strong>change</strong> the directory, it can't just send that request to some shell that goes away one second later.</p> <p>In other words: you can't have it both ways. Either you pass down <strong>all</strong> commands into a sub process; leading to the problem that makes up your question. Or your "interpreter" does "all the work" itself. </p> <p>And just for the record: as you might have guessed - writing a "shell" is a complex task. What makes you think that you should re-invent that wheel?</p>
0
2016-09-30T19:36:22Z
[ "python", "linux", "shell", "command", "subprocess" ]
Data Validation Using Functions
39,798,473
<p>How do I create a function that validates the following?</p> <pre><code>def get_order(): order=int(input("Select an item number: ")) return order </code></pre> <p>I tried this:</p> <pre><code>def validate_order(order_choice): order_choice=get_order() return order_choice while order_choice &lt; 1 or order_choice &gt; 8: order_choice=int(input("Invalid value. Re-enter item number: ")) return order_choice </code></pre> <p>I am confused on how to use parameters correctly. </p> <p>Thanks!</p>
2
2016-09-30T19:05:13Z
39,798,954
<p>I'm going to assume you want to validate that the order number is indeed an integer.</p> <p>To do this we will use the <code>isinstance()</code> function. Which accepts a variable and a type and returns <code>True</code> or <code>False</code> depending on whether or not it matches the second argument.</p> <p>In your case it will look like this:</p> <pre><code>order = input("Select an item number: ") while isinstance(order, int) or order not in xrange(1,9): order = get_order("Invalid value. Re-enter item number: ") </code></pre>
0
2016-09-30T19:39:05Z
[ "python", "function", "validation" ]
Data Validation Using Functions
39,798,473
<p>How do I create a function that validates the following?</p> <pre><code>def get_order(): order=int(input("Select an item number: ")) return order </code></pre> <p>I tried this:</p> <pre><code>def validate_order(order_choice): order_choice=get_order() return order_choice while order_choice &lt; 1 or order_choice &gt; 8: order_choice=int(input("Invalid value. Re-enter item number: ")) return order_choice </code></pre> <p>I am confused on how to use parameters correctly. </p> <p>Thanks!</p>
2
2016-09-30T19:05:13Z
39,799,176
<pre><code>def get_order(): order=int(input("Select an item number: ")) return order </code></pre> <p>The validation:</p> <pre><code>def validate_order(order_choice): order_choice=get_order() while order_choice &lt; 1 or order_choice &gt; 8: order_choice=int(input("Invalid value. Re-enter item number: ")) return order_choice </code></pre>
0
2016-09-30T19:55:14Z
[ "python", "function", "validation" ]
Set string in 'A' python script from 'B' python script
39,798,530
<p>I have two scripts: </p> <p>A.py (is TK window)</p> <pre><code>def function(): string = StringVar() string.set("Hello I'm A.py") </code></pre> <p>From B.py I wish change string that appear in Tk window.</p> <pre><code>def changestring(): string.set("Hello I'm B.py") </code></pre> <p>Obviously don't work! How I can change string from another python script? </p>
-1
2016-09-30T19:09:45Z
39,799,903
<p>Variables have scopes. You cannot access variables which are in the scope of one function from another function.</p> <p>There has to be some common point in the code which "knows" about A and about B. That code should pass the variables from one to the other.</p> <p>Based on this comment:</p> <blockquote> <p>A.py is the graphic and B is the core with a infinite loop that listen the USB interrupt</p> </blockquote> <p>I would say that you need two objects implementing the two functionalities, let's call them "graphic" and "usb". One of them has to "know" about the other. Either "graphic" should observe "usb", or "usb" should update "graphic".</p> <p>For example:</p> <pre><code># possibly in A.py: class Graphic(object): def __init__(self): self.string = StringVar() def function(self): self.string.set("Hello I'm A.py") # possibly in B.py: class USB(object): def __init__(self, graphic): self.graphic = graphic def changestring(self): self.graphic.string.set("Hello I'm B.py") # somewhere: from A import Graphic from B import USB def main(): graphic = Graphic() usb = USB(graphic) #... usb.changestring() </code></pre>
2
2016-09-30T20:51:19Z
[ "python", "function", "variables", "tk" ]
Python dict key with max value
39,798,560
<p>I have a dictionary with IP addresses and their free memory space. I'm trying to save an IP to one variable and the next highest one to another variable. </p> <pre><code>masterdict: {'192.168.100.102': '1620', '192.168.100.103': '470', '192.168.100.101': '1615'} print masterdict rmip = max(masterdict, key=masterdict.get) print "&lt;br&gt;rmip&lt;br&gt;" print rmip del masterdict [rmip] print "&lt;br&gt;masterdict after deletion&lt;br&gt;&lt;br&gt;" print masterdict nnip = max(masterdict, key=masterdict.get) print "&lt;br&gt;nnip&lt;br&gt;" print nnip </code></pre> <p>But the output i get is:</p> <blockquote> <p>masterdict {'192.168.100.102': '1620', '192.168.100.103': '470', '192.168.100.101': '1615'}</p> <p>rmip 192.168.100.103</p> <p>masterdict after deletion {'192.168.100.102': '1620', '192.168.100.101': '1615'}</p> <p>nnip 192.168.100.102 </p> </blockquote> <p>Why is it printing <code>192.168.100.103</code> as <code>rmip</code>? Shouldn't it be the one with the highest value? i.e. <code>192.168.100.102</code> and then <code>101</code> as <code>nnip</code>?</p>
0
2016-09-30T19:12:21Z
39,798,598
<p>The values in your dictionary are strings so <code>max</code> is comparing them as strings. If you want to compare them as integers, then you need to use the key function to convert the strings to integers...:</p> <pre><code>rmip = max(masterdict, key=lambda key: int(masterdict[key]) </code></pre> <p>Or change the values to <code>int</code> and then use your current max statement:</p> <pre><code>masterdict = {k: int(v) for k, v in masterdict.items()} rmip = max(masterdict, key=masterdict.get) </code></pre>
4
2016-09-30T19:15:20Z
[ "python", "dictionary" ]
Take union of two columns, Python + Pandas
39,798,594
<p>I have a df arranged like follows:</p> <pre><code> x y z 0 a jj Nan 1 b ii mm 2 c kk nn 3 d ii NaN 4 e Nan oo 5 f jj mm 6 g Nan nn </code></pre> <p>The desired output is:</p> <pre><code> x y z w 0 a jj Nan a 1 b ii mm a 2 c kk nn c 3 d ii NaN a 4 e Nan oo e 5 f jj mm a 6 g Nan nn c </code></pre> <p>The logic is </p> <ol> <li><p>to take union of column y &amp; z : <em><code>ii == jj</code> since in index 1 and 5, they both have <code>mm</code> in column z</em></p></li> <li><p>group this union : <em>index 0,1,3,5 are a group, index 2,6 are another group</em></p></li> <li><p>within the group, randomly take one cell in column x and assign it to column w for the whole group</p></li> </ol> <p>I have no clue at all about this problem. Can somebody help me?</p> <p><strong>EDITNOTE:</strong></p> <p>I was first post a perfectly sorted column y and column z like follows:</p> <pre><code> x y z w 0 a ii NaN a 1 b ii mm a 2 c jj mm a 3 d jj Nan a 4 e kk nn e 5 f Nan nn e 6 g Nan oo g </code></pre> <p>For this case, piRSquared's solution works perfect. </p> <p><strong>EDITNOTE2:</strong> </p> <p>Nickil Maveli's solution works perfect for my problem. However, I noted that there's a situation that the solution can not handle, that is :</p> <pre><code> x y z 0 a ii mm 1 b ii nn 2 c jj nn 3 d jj oo 4 e kk oo </code></pre> <p>By Nickil Maveli's solution, the result would be like follows:</p> <pre><code> 0 1 2 w 0 a ii mm a 1 b ii mm a 2 c jj nn c 3 d jj nn c 4 e kk oo e </code></pre> <p>However, the desired output should be w = ['a', 'a', 'a', 'a', 'a']. </p>
4
2016-09-30T19:14:56Z
39,799,676
<p>This one is tricky!</p> <p>I first evaluate which elements share the same <code>'y'</code> values as it's neighbor.<br> Then I check who has the same <code>'z'</code> as their neighbor.<br> A new group is when neither of these things are true.</p> <pre><code>y_chk = df.y.eq(df.y.shift()) z_chk = df.z.eq(df.z.shift()) grps = (~y_chk &amp; ~z_chk).cumsum() df['w'] = df.groupby(grps).x.transform(pd.Series.head, n=1) df </code></pre> <p><a href="http://i.stack.imgur.com/8hAuu.png" rel="nofollow"><img src="http://i.stack.imgur.com/8hAuu.png" alt="enter image description here"></a></p>
3
2016-09-30T20:33:57Z
[ "python", "pandas" ]
Take union of two columns, Python + Pandas
39,798,594
<p>I have a df arranged like follows:</p> <pre><code> x y z 0 a jj Nan 1 b ii mm 2 c kk nn 3 d ii NaN 4 e Nan oo 5 f jj mm 6 g Nan nn </code></pre> <p>The desired output is:</p> <pre><code> x y z w 0 a jj Nan a 1 b ii mm a 2 c kk nn c 3 d ii NaN a 4 e Nan oo e 5 f jj mm a 6 g Nan nn c </code></pre> <p>The logic is </p> <ol> <li><p>to take union of column y &amp; z : <em><code>ii == jj</code> since in index 1 and 5, they both have <code>mm</code> in column z</em></p></li> <li><p>group this union : <em>index 0,1,3,5 are a group, index 2,6 are another group</em></p></li> <li><p>within the group, randomly take one cell in column x and assign it to column w for the whole group</p></li> </ol> <p>I have no clue at all about this problem. Can somebody help me?</p> <p><strong>EDITNOTE:</strong></p> <p>I was first post a perfectly sorted column y and column z like follows:</p> <pre><code> x y z w 0 a ii NaN a 1 b ii mm a 2 c jj mm a 3 d jj Nan a 4 e kk nn e 5 f Nan nn e 6 g Nan oo g </code></pre> <p>For this case, piRSquared's solution works perfect. </p> <p><strong>EDITNOTE2:</strong> </p> <p>Nickil Maveli's solution works perfect for my problem. However, I noted that there's a situation that the solution can not handle, that is :</p> <pre><code> x y z 0 a ii mm 1 b ii nn 2 c jj nn 3 d jj oo 4 e kk oo </code></pre> <p>By Nickil Maveli's solution, the result would be like follows:</p> <pre><code> 0 1 2 w 0 a ii mm a 1 b ii mm a 2 c jj nn c 3 d jj nn c 4 e kk oo e </code></pre> <p>However, the desired output should be w = ['a', 'a', 'a', 'a', 'a']. </p>
4
2016-09-30T19:14:56Z
39,804,570
<p>Make all null strings as <code>NaN</code> values by replacing them. Next, group them according to 'y' and fill all the missing values with the value corresponding to it's first valid index present in 'z'. </p> <p>Then, perform groupby operation on 'z', by applying sum which aggregates all the values present in 'x' together. Slice it accordingly to fill all the values in that group with that particular value(Here, slice=0).</p> <p>Convert it to a dictionary to create the mapping and finally assign it back to a new column, 'w' as shown:</p> <pre><code>df_new = df.replace('Nan', np.NaN) df_new['z'] = df_new.groupby('y')['z'].transform(lambda x: x.loc[x.first_valid_index()]) df['w'] = df_new['z'].map(df_new.groupby('z')['x'].apply(lambda x: x.sum()[0]).to_dict()) df </code></pre> <p><a href="http://i.stack.imgur.com/V6RLm.png" rel="nofollow"><img src="http://i.stack.imgur.com/V6RLm.png" alt="Image"></a></p>
1
2016-10-01T08:34:30Z
[ "python", "pandas" ]
Take union of two columns, Python + Pandas
39,798,594
<p>I have a df arranged like follows:</p> <pre><code> x y z 0 a jj Nan 1 b ii mm 2 c kk nn 3 d ii NaN 4 e Nan oo 5 f jj mm 6 g Nan nn </code></pre> <p>The desired output is:</p> <pre><code> x y z w 0 a jj Nan a 1 b ii mm a 2 c kk nn c 3 d ii NaN a 4 e Nan oo e 5 f jj mm a 6 g Nan nn c </code></pre> <p>The logic is </p> <ol> <li><p>to take union of column y &amp; z : <em><code>ii == jj</code> since in index 1 and 5, they both have <code>mm</code> in column z</em></p></li> <li><p>group this union : <em>index 0,1,3,5 are a group, index 2,6 are another group</em></p></li> <li><p>within the group, randomly take one cell in column x and assign it to column w for the whole group</p></li> </ol> <p>I have no clue at all about this problem. Can somebody help me?</p> <p><strong>EDITNOTE:</strong></p> <p>I was first post a perfectly sorted column y and column z like follows:</p> <pre><code> x y z w 0 a ii NaN a 1 b ii mm a 2 c jj mm a 3 d jj Nan a 4 e kk nn e 5 f Nan nn e 6 g Nan oo g </code></pre> <p>For this case, piRSquared's solution works perfect. </p> <p><strong>EDITNOTE2:</strong> </p> <p>Nickil Maveli's solution works perfect for my problem. However, I noted that there's a situation that the solution can not handle, that is :</p> <pre><code> x y z 0 a ii mm 1 b ii nn 2 c jj nn 3 d jj oo 4 e kk oo </code></pre> <p>By Nickil Maveli's solution, the result would be like follows:</p> <pre><code> 0 1 2 w 0 a ii mm a 1 b ii mm a 2 c jj nn c 3 d jj nn c 4 e kk oo e </code></pre> <p>However, the desired output should be w = ['a', 'a', 'a', 'a', 'a']. </p>
4
2016-09-30T19:14:56Z
39,809,512
<p>In the general case this is a set consolidation/connected components problem. While if we assume certain things about your data we can solve a reduced case, it's just a bit of bookkeeping to do the whole thing.</p> <p>scipy has a connected components function we can use if we do some preparation:</p> <pre><code>import scipy.sparse def via_cc(df_in): df = df_in.copy() # work with ranked version dfr = df[["y","z"]].rank(method='dense') # give nans their own temporary rank dfr = dfr.fillna(dfr.max().fillna(0) + dfr.isnull().cumsum(axis=0)) # don't let y and z get mixed up; have separate nodes per column dfr["z"] += dfr["y"].max() # build the adjacency matrix size = int(dfr.max().max()) + 1 m = scipy.sparse.coo_matrix(([1]*len(dfr), (dfr.y, dfr.z)), (size, size)) # do the work to find the groups _, cc = scipy.sparse.csgraph.connected_components(m) # get the group codes group = pd.Series(cc[dfr["y"].astype(int).values], index=dfr.index) # fill in w from x appropriately df["w"] = df["x"].groupby(group).transform(min) return df </code></pre> <p>which gives me</p> <pre><code>In [230]: via_cc(df0) Out[230]: x y z w 0 a jj NaN a 1 b ii mm a 2 c kk nn c 3 d ii NaN a 4 e NaN oo e 5 f jj mm a 6 g NaN nn c In [231]: via_cc(df1) Out[231]: x y z w 0 a ii mm a 1 b ii nn a 2 c jj nn a 3 d jj oo a 4 e kk oo a </code></pre> <p>If you have a set consolidation recipe around, like the one <a href="https://rosettacode.org/wiki/Set_consolidation#Python:_Iterative" rel="nofollow">here</a>, you can simplify some of the above at the cost of an external function.</p> <p>(Aside: note that in my df0, the "Nan"s are really NaNs. If you have a <em>string</em> "Nan" (note how it's different from NaN), then the code will think it's just another string and will assume that you want all "Nan"s to be in the same group.)</p>
2
2016-10-01T17:26:12Z
[ "python", "pandas" ]
UTF-8 characters usage in python3.4 script is throwing SyntaxError. How to use it?
39,798,615
<p>I am trying execute following lines of code in python3.4:</p> <pre><code>user ="ŠŒŽ‡†ƒ€‰" print(user) </code></pre> <p>But the above user initialization line is resulting in following error:</p> <pre><code>SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0x8a in position 0: invalid start byte </code></pre> <p>I want to use the same user in authentication later. How to use UTF-8 characters in python3.4 script ?</p>
0
2016-09-30T19:16:22Z
39,799,151
<p>Your file is not actually saved in UTF-8. Assuming that the syntax error is occurring on the first non-ASCII character (<code>Å </code>), the file is most likely encoded in <a href="https://en.wikipedia.org/wiki/Windows-1252" rel="nofollow">Windows 1252</a>, which encodes that character as 0x8A. If you wish to continue using this encoding, add this line to the top of your Python file:</p> <pre><code># -*- coding: windows-1252 -*- </code></pre>
4
2016-09-30T19:53:17Z
[ "python", "python-3.x", "utf-8" ]
BeautifulSoup - Misspelled Class
39,798,712
<p>I am attempting to scrape location data from <a href="https://www.wellstar.org/locations/pages/default.aspx" rel="nofollow">https://www.wellstar.org/locations/pages/default.aspx</a> and while I was inspecting the source, I noticed that the class for the hospital's address is sometimes spelled with an extra 'd' - 'adddress' vs 'address'. Is there a way to account for this difference in the following code? I have attempted to incorporate an <code>if</code> statement to test the length of the <code>address</code> object but I only get the addresses associated with the 'adddress' class. I feel that I am close yet out of ideas.</p> <pre><code>import urllib import urllib.request from bs4 import BeautifulSoup import re def make_soup(url): thepage = urllib.request.urlopen(url) soupdata = BeautifulSoup(thepage,"html.parser") return soupdata soup = make_soup("https://www.wellstar.org/locations/pages/default.aspx") for table in soup.findAll("table",class_="s4-wpTopTable"): for type in table.findAll("h3"): type = type.get_text() for name in table.findAll("div",class_="PurpleBackgroundHeading"): name = name.get_text() address="" for address in table.findAll("div",class_="WS_Location_Adddress"): address = address.get_text(separator=" ") if len(address)==0: for address in table.findAll("div",class_="WS_Location_Address"): address = address.get_text(separator = " ") print(type, name, address) </code></pre>
2
2016-09-30T19:23:58Z
39,798,775
<p><code>BeautifulSoup</code> is great at adapting, you can use a regular expression:</p> <pre><code>for address in table.find_all("div", class_=re.compile(r"WS_Location_Ad{2,}ress")): </code></pre> <p>where <code>d{2,}</code> would match <code>d</code> 2 or more times.</p> <hr> <p>Or, you can just specify a <em>list</em> of classes:</p> <pre><code>for address in table.find_all("div", class_=["WS_Location_Address", "WS_Location_Adddress"]): </code></pre>
2
2016-09-30T19:27:42Z
[ "python", "web-scraping", "beautifulsoup" ]
flask-sockets and ZeroMQ
39,798,788
<p>I'm playing around with getting <code>zeromq</code> pub/sub messages sent up to a browser with a websocket. The following "works", in that messages do get sent up through a websocket. However, trying to reload the page just hangs, as I'm guessing the <code>while True</code> loop is blocking. I thought that the <code>gevent.sleep()</code> call would allow a context switch, but apparently not. Any idea how to get all these parts working together? </p> <pre><code>import zmq import json import gevent from flask_sockets import Sockets from flask import Flask, render_template import logging from gevent import monkey monkey.patch_all() app = Flask(__name__) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) sockets = Sockets(app) context = zmq.Context() ZMQ_LISTENING_PORT = 6557 @app.route('/') def index(): return render_template('index.html') @sockets.route('/zeromq') def send_data(ws): logger.info('Got a websocket connection, sending up data from zmq') socket = context.socket(zmq.SUB) socket.connect('tcp://localhost:{PORT}'.format(PORT=ZMQ_LISTENING_PORT)) socket.setsockopt(zmq.SUBSCRIBE, "") gevent.sleep() while True: data = socket.recv_json() logger.info(data) ws.send(json.dumps(data)) gevent.sleep() if __name__ == '__main__': from gevent import pywsgi from geventwebsocket.handler import WebSocketHandler server = pywsgi.WSGIServer(('', 25000), app, handler_class=WebSocketHandler) server.serve_forever() </code></pre>
0
2016-09-30T19:28:22Z
39,798,888
<p>Nevermind, just realized need to do </p> <pre><code>import zmq.green as zmq </code></pre> <p>in order to use with gevent compatibility. <a href="https://pyzmq.readthedocs.io/en/latest/api/zmq.green.html" rel="nofollow">Here's a link to pyZeormq docs.</a></p>
0
2016-09-30T19:34:34Z
[ "python", "zeromq", "flask-sockets" ]
Django - filter model
39,798,840
<p>I have a model with a field that is a list. For example:</p> <pre><code>mymodel.sessions = [session1, session2] </code></pre> <p>I need a query to get all <code>mymodels</code> that <code>session1</code> is exist their sessions.</p> <p>The model`s field looks like that</p> <pre><code>sessions = models.ForeignKey("Session", related_name="abstracts", null=True, blank=True) </code></pre> <p>Thank you !</p>
2
2016-09-30T19:31:24Z
39,799,018
<p>You can use reverse lookups that go back along the foreign key to query for values in the related model.</p> <pre><code>MyModel.objects.filter(sessions__id=1) </code></pre> <p>That will filter all <code>MyModel</code>s that have a foreign key to a session with an <code>id</code> of 1.</p> <p>For more information see <a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/db/queries/#lookups-that-span-relationships</a></p>
0
2016-09-30T19:43:28Z
[ "python", "django", "django-models" ]
Django - filter model
39,798,840
<p>I have a model with a field that is a list. For example:</p> <pre><code>mymodel.sessions = [session1, session2] </code></pre> <p>I need a query to get all <code>mymodels</code> that <code>session1</code> is exist their sessions.</p> <p>The model`s field looks like that</p> <pre><code>sessions = models.ForeignKey("Session", related_name="abstracts", null=True, blank=True) </code></pre> <p>Thank you !</p>
2
2016-09-30T19:31:24Z
39,799,086
<p>From the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.filter" rel="nofollow">Django docs for <code>filter</code></a>:</p> <blockquote> <p><code>filter(**kwargs)</code></p> <p>Returns a new QuerySet containing objects that match the given lookup parameters.</p> </blockquote> <p>You can filter on a ForeignKey relationship using the id, if you have it:</p> <blockquote> <p>The field specified in a lookup has to be the name of a model field. There’s one exception though, in case of a ForeignKey you can specify the field name suffixed with _id. In this case, the value parameter is expected to contain the raw value of the foreign model’s primary key.</p> </blockquote> <p>In your instance, this would like the following:</p> <pre><code>mymodel.objects.filter(sessions_id=4) </code></pre> <p>If you want to filter on any other field in the Sessions model, simply use a double underscore with the field. Some examples:</p> <pre><code>mymodel.objects.filter(sessions__name='session1') mymodel.objects.filter(sessions__name__contains='1') </code></pre>
0
2016-09-30T19:48:30Z
[ "python", "django", "django-models" ]
Breaking out of while True loop
39,798,918
<p>I have a python script which will parse xml file for serial numbers and will write them to a text file. The problem with the below code is, It is going on infinite loop. If I am adding a break statement some where after logging to a file, It is writing only one serial number. How do I increase the counter, so that the program will exit after writing all the serial numbers.</p> <pre><code>try: while True: data, addr = s.recvfrom(65507) mylist=data.split('\r') url = re.findall('http?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', data) print url[0] response = urllib2.urlopen(url[0]) the_page = response.read() tree = ET.XML(the_page) with open("temp.xml", "w") as f: f.write(ET.tostring(tree)) document = parse('temp.xml') actors = document.getElementsByTagName("ns0:serialNumber") for act in actors: for node in act.childNodes: if node.nodeType == node.TEXT_NODE: r = "{}".format(node.data) print r logToFile(str(r)) time.sleep(10) s.sendto(msg, ('239.255.255.250', 1900) ) except socket.timeout: pass </code></pre>
1
2016-09-30T19:36:25Z
39,799,085
<p>I would normally create a flag so that the while would be</p> <pre><code>while working == True: </code></pre> <p>Then reset the flag at the appropriate time.</p> <p>This allows you to use the <code>else</code> statement to close the text file and output the final results after the while loop is complete. <a href="http://stackoverflow.com/questions/3295938/else-clause-on-python-while-statement">Else clause on Python while statement</a>.</p> <p>Note that it is always better to explicitly close open files when finished rather than relying on garbage collection. You should also close the file and output a timeout message in the except logic.</p> <p>For debugging, you can output a statement at each write to the text file.</p>
1
2016-09-30T19:48:28Z
[ "python", "xml", "while-loop", "break" ]
Breaking out of while True loop
39,798,918
<p>I have a python script which will parse xml file for serial numbers and will write them to a text file. The problem with the below code is, It is going on infinite loop. If I am adding a break statement some where after logging to a file, It is writing only one serial number. How do I increase the counter, so that the program will exit after writing all the serial numbers.</p> <pre><code>try: while True: data, addr = s.recvfrom(65507) mylist=data.split('\r') url = re.findall('http?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', data) print url[0] response = urllib2.urlopen(url[0]) the_page = response.read() tree = ET.XML(the_page) with open("temp.xml", "w") as f: f.write(ET.tostring(tree)) document = parse('temp.xml') actors = document.getElementsByTagName("ns0:serialNumber") for act in actors: for node in act.childNodes: if node.nodeType == node.TEXT_NODE: r = "{}".format(node.data) print r logToFile(str(r)) time.sleep(10) s.sendto(msg, ('239.255.255.250', 1900) ) except socket.timeout: pass </code></pre>
1
2016-09-30T19:36:25Z
39,799,426
<p>If your s.recvfrom(65507) is working correctly it should be an easy fix. Write this code just below your <code>data, addr = s.recvfrom(65507)</code></p> <pre><code>if not data: break </code></pre>
0
2016-09-30T20:15:22Z
[ "python", "xml", "while-loop", "break" ]
Breaking out of while True loop
39,798,918
<p>I have a python script which will parse xml file for serial numbers and will write them to a text file. The problem with the below code is, It is going on infinite loop. If I am adding a break statement some where after logging to a file, It is writing only one serial number. How do I increase the counter, so that the program will exit after writing all the serial numbers.</p> <pre><code>try: while True: data, addr = s.recvfrom(65507) mylist=data.split('\r') url = re.findall('http?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', data) print url[0] response = urllib2.urlopen(url[0]) the_page = response.read() tree = ET.XML(the_page) with open("temp.xml", "w") as f: f.write(ET.tostring(tree)) document = parse('temp.xml') actors = document.getElementsByTagName("ns0:serialNumber") for act in actors: for node in act.childNodes: if node.nodeType == node.TEXT_NODE: r = "{}".format(node.data) print r logToFile(str(r)) time.sleep(10) s.sendto(msg, ('239.255.255.250', 1900) ) except socket.timeout: pass </code></pre>
1
2016-09-30T19:36:25Z
39,800,539
<p>You open a <code>UDP</code> socket and you use <code>recvfrom</code> to get data from the socket.<br> You set a high <code>timeout</code> which makes this function a <code>blocking function</code>. It means when you start listening on the socket, if no data have been sent from the sender your program will be blocked on that line until either the sender sends something or the <code>timeout</code> reaches. In case of <code>timeout</code> and no data the function will raise an <code>Exception</code>. </p> <p>I see two options:</p> <ul> <li><p>Send something from the sender that indicates the end of stream (the serial numbers in your case).</p></li> <li><p>Set a small <code>timeout</code> then catch the <code>Exception</code> and use it to break the loop. </p></li> </ul> <p>Also, take a look at this question: <a href="http://stackoverflow.com/questions/31166594/socket-python-recvfrom">socket python : recvfrom</a></p> <p>Hope it helps.</p>
0
2016-09-30T21:48:16Z
[ "python", "xml", "while-loop", "break" ]
Cumulative Sum List
39,798,962
<p>I'm trying to create a cumulative list, but my output clearly isn't cumulative. Does anyone know what I'm doing wrong? Thanks</p> <pre><code>import numpy as np import math import random l=[] for i in range (50): def nextTime(rateParameter): return -math.log(1.0 - random.random()) / rateParameter a = np.round(nextTime(1/15),0) l.append(a) np.cumsum(l) print(l) </code></pre>
0
2016-09-30T19:39:33Z
39,799,016
<p>The cumulative sum is not taken <em>in place</em>, you have to assign the return value:</p> <pre><code>cum_l = np.cumsum(l) print(cum_l) </code></pre> <p>You don't need to place that function in the <code>for</code> loop. Putting it outside will avoid defining a new function at every iteration and your code will still produce the expected result.</p>
1
2016-09-30T19:43:27Z
[ "python", "numpy", "cumsum" ]
Cumulative Sum List
39,798,962
<p>I'm trying to create a cumulative list, but my output clearly isn't cumulative. Does anyone know what I'm doing wrong? Thanks</p> <pre><code>import numpy as np import math import random l=[] for i in range (50): def nextTime(rateParameter): return -math.log(1.0 - random.random()) / rateParameter a = np.round(nextTime(1/15),0) l.append(a) np.cumsum(l) print(l) </code></pre>
0
2016-09-30T19:39:33Z
39,799,192
<p>If you are using <code>numpy</code> then <code>numpy</code> is the way to go, however, if all you need to do is provide a cumulative sum then Python3 comes with <code>itertools.accumulate</code>:</p> <pre><code>def nextTime(rateParameter): while True: yield -math.log(1.0 - random.random()) / rateParameter &gt;&gt;&gt; list(it.accumulate(map(round, it.islice(nextTime(1/15), 50)))) [2, 9, 14, 26, 27, ...] </code></pre>
0
2016-09-30T19:56:42Z
[ "python", "numpy", "cumsum" ]
Creating bytesIO object
39,799,009
<p>I am working on a <a href="https://en.wikipedia.org/wiki/Scrapy" rel="nofollow">Scrapy</a> spider, trying to extract the text from multiple PDF files in a directory, using <a href="https://pypi.python.org/pypi/slate" rel="nofollow">slate</a>. I have no interest in saving the actual PDF to disk, and so I've been advised to look into the io.bytesIO subclass at <a href="https://docs.python.org/2/library/io.html#buffered-streams" rel="nofollow">https://docs.python.org/2/library/io.html#buffered-streams</a>.</p> <p>However I'm not sure how to pass the PDF body to the bytesIO class and then pass the virtual PDF slate to get the text. So far I have:</p> <pre><code>class Ove_Spider(BaseSpider): name = "ove" allowed_domains = ['myurl.com'] start_urls = ['myurl/hgh/'] def parse(self, response): for a in response.xpath('//a[@href]/@href'): link = a.extract() if link.endswith('.pdf'): link = urlparse.urljoin(base_url, link) yield Request(link, callback=self.save_pdf) def save_pdf(self, response): in_memory_pdf = BytesIO() in_memory_pdf.read(response.body) # Trying to read in PDF which is in response body </code></pre> <p>I'm getting:</p> <pre><code>in_memory_pdf.read(response.body) TypeError: integer argument expected, got 'str' </code></pre> <p>How can I get this working?</p>
0
2016-09-30T19:43:08Z
39,799,090
<p>When you do <code>in_memory_pdf.read(response.body)</code> you are supposed to pass the number of bytes to read. You want to initialize the buffer, not read into it.</p> <p>In python 2, just initialize <code>BytesIO</code> as:</p> <pre><code> in_memory_pdf = BytesIO(response.body) </code></pre> <p>In Python 3, you cannot use <code>BytesIO</code> with a string because it expects bytes. The error message shows that <code>response.body</code> is of type <code>str</code>: we have to encode it.</p> <pre><code> in_memory_pdf = BytesIO(bytes(response.body,'ascii')) </code></pre> <p>But as a pdf can be binary data, I suppose that <code>response.body</code> would be <code>bytes</code>, not <code>str</code>. In that case, the simple <code>in_memory_pdf = BytesIO(response.body)</code> works.</p>
1
2016-09-30T19:48:49Z
[ "python", "pdf" ]
Run python commands in parallel in Linux shell scripting
39,799,057
<p>I have a script which gets input from the user through command line arguments. It processes the arguments and starts running python commands. For Example:</p> <pre><code>./run.sh p1 p2 p3 p4 python abc.py p1 p4 python xyz.py p2 p3 </code></pre> <p>where <code>p1</code>, <code>p2</code>, <code>p3</code> and <code>p4</code> can be of any type. </p> <p>I need to run both of these python commands in parallel and in two different terminals. How can I do it so that I don't need to wait for 1 command to finish in order to start the next command?</p> <p>I tried GNU parallel but it doesn't seem to work. </p>
1
2016-09-30T19:46:19Z
39,799,144
<p>Try running each process in the background by adding <code>&amp;</code> to the end of the command.</p> <pre><code>python abc.py p1 p4 &amp; python xyz.py p2 p3 &amp; </code></pre> <p><a href="http://www.hacktux.com/bash/ampersand" rel="nofollow">Some Info</a></p>
1
2016-09-30T19:52:49Z
[ "python", "linux", "shell" ]
Run python commands in parallel in Linux shell scripting
39,799,057
<p>I have a script which gets input from the user through command line arguments. It processes the arguments and starts running python commands. For Example:</p> <pre><code>./run.sh p1 p2 p3 p4 python abc.py p1 p4 python xyz.py p2 p3 </code></pre> <p>where <code>p1</code>, <code>p2</code>, <code>p3</code> and <code>p4</code> can be of any type. </p> <p>I need to run both of these python commands in parallel and in two different terminals. How can I do it so that I don't need to wait for 1 command to finish in order to start the next command?</p> <p>I tried GNU parallel but it doesn't seem to work. </p>
1
2016-09-30T19:46:19Z
39,804,333
<p>Your task is not where GNU Parallel excels, but it can be done:</p> <pre><code>parallel ::: "python abc.py p1 p4" "python xyz.py p2 p3" </code></pre>
0
2016-10-01T08:02:32Z
[ "python", "linux", "shell" ]
Form data is storing in database when using jQuery
39,799,074
<p>i was trying to use jquery to load form when value of drop down change .it loading the form but after submitting data is not storing in database . it just refreshes the page.</p> <blockquote> <p>forms.py</p> </blockquote> <pre><code>class accountForm(forms.ModelForm): choice = ( ('payment type','payment type'), ('paypal', 'paypal'), ('payeer', 'payeer'), ('payza', 'payza'), ('bitcoin', 'bitcoin'), ) payment_type = forms.ChoiceField(choices = choice, widget = forms.Select(attrs = {'class':'forms-control'})) email = forms.EmailField(widget = forms.EmailInput(attrs={'class':'form-control'})) bitcoin = forms.CharField(widget = forms.TextInput(attrs = {'class':'form-control'})) amount = forms.IntegerField(widget = forms.NumberInput(attrs = {'class':'form-control'})) class Meta: model = payments fields = [ "payment_type", "email", "bitcoin", "amount", ] </code></pre> <blockquote> <p>views.py</p> </blockquote> <pre><code>def payment(request, username): form = accountForm(request.POST or None) if form.is_valid(): print(form) form.save(commit = False) form.save() return HttpResponseRedirect('/accounts/profile/') context = {'form':form} return render(request, 'payment.html', context) </code></pre> <blockquote> <p>payment.html</p> </blockquote> <pre><code>&lt;div class="panel-body"&gt; &lt;div class="tab-content"&gt; &lt;div class="tab-pane active" id="home"&gt; &lt;div class="panel-body" id="panel"&gt; &lt;div class="form-group"&gt; &lt;h4 class="text-primary"&gt;Select Withdrawal Type&lt;/h4&gt; {{ form.payment_type }} &lt;/div&gt; &lt;/div&gt; &lt;div class="panel-body"&gt; &lt;form method="POST" id="form" enctype='multipart/form-data'&gt; {% csrf_token %} &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <blockquote> <p>jquery</p> </blockquote> <pre><code>&lt;script type="text/javascript"&gt; $('select').on('change', function (e) { var Selected = $("option:selected", this); var valueSelected = this.value; console.log(valueSelected); if (valueSelected == 'paypal') { $("#panel").change(function (e) { $("#panel").empty(); // $('#form').append('{% csrf_token %}'); $('#form').append('&lt;label&gt;email&lt;/label&gt;'); $('#form').append('{{ form.email }}'); $('#form').append('{{ form.amount }}'); $('#form').append('&lt;button class="btn btn-primary btn-default"&gt;submit&lt;/button&gt;'); }) } }); &lt;/script&gt; </code></pre>
0
2016-09-30T19:47:49Z
39,799,213
<p>Where is the implementation for your forms.save()? Describe how save() is implemented in forms model. It could be somewhere there or If you are using any service like Amazon AWS and botto as interface, the issue could be in these two places also.</p> <p>Obviously you have only printed the form and you are using HttpResponseRedirect which is why your form is printed and your profile page is reloaded.</p>
0
2016-09-30T19:58:07Z
[ "jquery", "python", "django", "django-forms", "django-views" ]
Python regex find all substrings between two character pairs
39,799,096
<p>I have tried previous answers here on SO. I was able to find only one subset of several. </p> <p>here is the code and sample that I am working on.</p> <pre><code>s = "{| mySting0 |} The {| mySting1 |} The {| mySting2 |} The {| mySting3 |} make it work " result = re.findall('{\|(.*)|}', s) </code></pre> <p>the output is,</p> <pre><code>[' mySting0 |} The {| mySting1 |} The {| mySting2 |} The {| mySting3 |} make it work '] </code></pre> <p>What am I doing wrong?</p>
0
2016-09-30T19:49:22Z
39,799,123
<p>You can use this regex:</p> <pre><code>&gt;&gt;&gt; s = "{| mySting0 |} The {| mySting1 |} The {| mySting2 |} The {| mySting3 |} make it work " &gt;&gt;&gt; re.findall(r'{\|(.*?)\|}', s) [' mySting0 ', ' mySting1 ', ' mySting2 ', ' mySting3 '] </code></pre> <p><strong>Changes are:</strong></p> <ol> <li>Use lazy quantifier <code>.*?</code> instead of greedy <code>.*</code></li> <li>Excape 2nd <code>|</code> as well in your regex</li> </ol>
3
2016-09-30T19:50:58Z
[ "python", "regex" ]
Python simple email validity check
39,799,159
<p>In Python, if i wanted to write something that returns a boolean True as long as the @ symbol appears after the . symbol, how would I write this? </p> <p>I have tried writing something like:</p> <pre><code>if myString[x] == "@" &gt; myString[x] == ".": return True </code></pre> <p>but, I assume that this won't work because they're both essentially the same index. Looking for some explanation as well, just learning a lot of basics still. Thanks!</p>
-1
2016-09-30T19:53:47Z
39,799,193
<pre><code>if str.index('@') &gt; str.index('.'): return True; </code></pre>
1
2016-09-30T19:56:48Z
[ "python" ]
Python simple email validity check
39,799,159
<p>In Python, if i wanted to write something that returns a boolean True as long as the @ symbol appears after the . symbol, how would I write this? </p> <p>I have tried writing something like:</p> <pre><code>if myString[x] == "@" &gt; myString[x] == ".": return True </code></pre> <p>but, I assume that this won't work because they're both essentially the same index. Looking for some explanation as well, just learning a lot of basics still. Thanks!</p>
-1
2016-09-30T19:53:47Z
39,799,203
<p>You could use a simple regular expression:</p> <pre><code>import re rx = re.compile(r'\S+@\S+') string = """This text contains an email@address.com somewhere""" if rx.search(string): print("Somewhere in there is an email address") </code></pre> <p>See <a href="http://ideone.com/7FpfgH" rel="nofollow"><strong>a demo on ideone.com</strong></a>.</p>
1
2016-09-30T19:57:31Z
[ "python" ]
Python simple email validity check
39,799,159
<p>In Python, if i wanted to write something that returns a boolean True as long as the @ symbol appears after the . symbol, how would I write this? </p> <p>I have tried writing something like:</p> <pre><code>if myString[x] == "@" &gt; myString[x] == ".": return True </code></pre> <p>but, I assume that this won't work because they're both essentially the same index. Looking for some explanation as well, just learning a lot of basics still. Thanks!</p>
-1
2016-09-30T19:53:47Z
39,799,341
<p><code>return str.find('@') &gt; str.find('.') and str.find('.') &gt; -1</code></p> <p>This will check that <code>@</code> is after <code>.</code>, and that both symbols are present in the string. This is however a <strong>very</strong> bad way to check for email validity.</p>
1
2016-09-30T20:07:19Z
[ "python" ]
concatenate next to string if string found
39,799,240
<p>I'm trying to search through my strings then concatenate the string.</p> <pre><code>string = ' &lt;html&gt;&lt;body&gt;&lt;svg style="background: #40484b;" version="1.1" viewbox="0 0 400 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;defs&gt; &lt;!-- if you use the same shape multiple times, you put the reference here and reference it with &lt;use&gt; --&gt; &lt;rect height="100" id="path-1" width="100" x="25" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-3" width="100" x="150" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-5" width="100" x="275" y="25"&gt;&lt;/rect&gt; &lt;!-- gradient --&gt; &lt;lineargradient id="gradient" x1="50%" x2="50%" y1="0%" y2="100%"&gt; &lt;stop offset="0%" stop-color="#FF8D77"&gt;&lt;/stop&gt; &lt;stop offset="50%" stop-color="#FFBDB1"&gt;&lt;/stop&gt; &lt;stop offset="100%" stop-color="#F4E3F6"&gt;&lt;/stop&gt; &lt;/lineargradient&gt; &lt;!-- clip-path --&gt; &lt;clippath id="clip"&gt; &lt;circle cx="325" cy="75" r="50"&gt;&lt;/circle&gt; &lt;/clippath&gt; &lt;!-- filter --&gt; &lt;/defs&gt;&gt; &lt;g fill-rule="evenodd"&gt; &lt;use fill="#FF8D77" fill-opacity="0.5" filter="url(#glow)" xlink:href="#path-1"&gt;&lt;/use&gt; &lt;use fill="url(#gradient)" xlink:href="#path-3"&gt;&lt;/use&gt; &lt;use clip-path="url(#clip)" fill="#FF8D77" xlink:href="#path-5"&gt;&lt;/use&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/body&gt;&lt;/html&gt;' </code></pre> <p>That's how my string looks like. So far this is what I have</p> <pre><code> string_list = string if "&lt;defs&gt;" in string: ###I'm trying to concatenate strings after &lt;defs&gt; like &lt;defs&gt; string string </code></pre> <p>Also, I'd like to keep appending strings instead of replacing. Like If I have a user type in something; it keeps adding strings after defs instead of replacing what I already have.</p> <p>The output I'm expecting would be something like this, I added "concatenated string1" and "concatenated string2". I'm trying to add strings next to "defs" from my string list overall.</p> <p>Also what I meant by keep adding strings instead of replace is for instance. I have a - first user type in string "concatenate1" - Second user type in string "concatenate2" I want to add both concatenate 1 + contatenate 2 next to my defs tag.</p> <pre><code>&lt;html&gt;&lt;body&gt;&lt;svg style="background: #40484b;" version="1.1" viewbox="0 0 400 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;defs&gt; &lt;concatenated string1&gt; &lt;concatenated string2&gt; &lt;!-- if you use the same shape multiple times, you put the reference here and reference it with &lt;use&gt; --&gt; &lt;rect height="100" id="path-1" width="100" x="25" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-3" width="100" x="150" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-5" width="100" x="275" y="25"&gt;&lt;/rect&gt; &lt;!-- gradient --&gt; &lt;lineargradient id="gradient" x1="50%" x2="50%" y1="0%" y2="100%"&gt; &lt;stop offset="0%" stop-color="#FF8D77"&gt;&lt;/stop&gt; &lt;stop offset="50%" stop-color="#FFBDB1"&gt;&lt;/stop&gt; &lt;stop offset="100%" stop-color="#F4E3F6"&gt;&lt;/stop&gt; &lt;/lineargradient&gt; &lt;!-- clip-path --&gt; &lt;clippath id="clip"&gt; &lt;circle cx="325" cy="75" r="50"&gt;&lt;/circle&gt; &lt;/clippath&gt; &lt;!-- filter --&gt; &lt;/defs&gt;&gt; &lt;g fill-rule="evenodd"&gt; &lt;use fill="#FF8D77" fill-opacity="0.5" filter="url(#glow)" xlink:href="#path-1"&gt;&lt;/use&gt; &lt;use fill="url(#gradient)" xlink:href="#path-3"&gt;&lt;/use&gt; &lt;use clip-path="url(#clip)" fill="#FF8D77" xlink:href="#path-5"&gt;&lt;/use&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
0
2016-09-30T20:00:20Z
39,799,305
<p>You can concatenate strings with the <code>+</code> symbol.</p> <pre><code>&gt;&gt;&gt; 'foo' + 'bar' 'foobar' </code></pre>
0
2016-09-30T20:04:24Z
[ "python", "string", "parsing", "concatenation" ]
concatenate next to string if string found
39,799,240
<p>I'm trying to search through my strings then concatenate the string.</p> <pre><code>string = ' &lt;html&gt;&lt;body&gt;&lt;svg style="background: #40484b;" version="1.1" viewbox="0 0 400 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;defs&gt; &lt;!-- if you use the same shape multiple times, you put the reference here and reference it with &lt;use&gt; --&gt; &lt;rect height="100" id="path-1" width="100" x="25" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-3" width="100" x="150" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-5" width="100" x="275" y="25"&gt;&lt;/rect&gt; &lt;!-- gradient --&gt; &lt;lineargradient id="gradient" x1="50%" x2="50%" y1="0%" y2="100%"&gt; &lt;stop offset="0%" stop-color="#FF8D77"&gt;&lt;/stop&gt; &lt;stop offset="50%" stop-color="#FFBDB1"&gt;&lt;/stop&gt; &lt;stop offset="100%" stop-color="#F4E3F6"&gt;&lt;/stop&gt; &lt;/lineargradient&gt; &lt;!-- clip-path --&gt; &lt;clippath id="clip"&gt; &lt;circle cx="325" cy="75" r="50"&gt;&lt;/circle&gt; &lt;/clippath&gt; &lt;!-- filter --&gt; &lt;/defs&gt;&gt; &lt;g fill-rule="evenodd"&gt; &lt;use fill="#FF8D77" fill-opacity="0.5" filter="url(#glow)" xlink:href="#path-1"&gt;&lt;/use&gt; &lt;use fill="url(#gradient)" xlink:href="#path-3"&gt;&lt;/use&gt; &lt;use clip-path="url(#clip)" fill="#FF8D77" xlink:href="#path-5"&gt;&lt;/use&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/body&gt;&lt;/html&gt;' </code></pre> <p>That's how my string looks like. So far this is what I have</p> <pre><code> string_list = string if "&lt;defs&gt;" in string: ###I'm trying to concatenate strings after &lt;defs&gt; like &lt;defs&gt; string string </code></pre> <p>Also, I'd like to keep appending strings instead of replacing. Like If I have a user type in something; it keeps adding strings after defs instead of replacing what I already have.</p> <p>The output I'm expecting would be something like this, I added "concatenated string1" and "concatenated string2". I'm trying to add strings next to "defs" from my string list overall.</p> <p>Also what I meant by keep adding strings instead of replace is for instance. I have a - first user type in string "concatenate1" - Second user type in string "concatenate2" I want to add both concatenate 1 + contatenate 2 next to my defs tag.</p> <pre><code>&lt;html&gt;&lt;body&gt;&lt;svg style="background: #40484b;" version="1.1" viewbox="0 0 400 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;defs&gt; &lt;concatenated string1&gt; &lt;concatenated string2&gt; &lt;!-- if you use the same shape multiple times, you put the reference here and reference it with &lt;use&gt; --&gt; &lt;rect height="100" id="path-1" width="100" x="25" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-3" width="100" x="150" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-5" width="100" x="275" y="25"&gt;&lt;/rect&gt; &lt;!-- gradient --&gt; &lt;lineargradient id="gradient" x1="50%" x2="50%" y1="0%" y2="100%"&gt; &lt;stop offset="0%" stop-color="#FF8D77"&gt;&lt;/stop&gt; &lt;stop offset="50%" stop-color="#FFBDB1"&gt;&lt;/stop&gt; &lt;stop offset="100%" stop-color="#F4E3F6"&gt;&lt;/stop&gt; &lt;/lineargradient&gt; &lt;!-- clip-path --&gt; &lt;clippath id="clip"&gt; &lt;circle cx="325" cy="75" r="50"&gt;&lt;/circle&gt; &lt;/clippath&gt; &lt;!-- filter --&gt; &lt;/defs&gt;&gt; &lt;g fill-rule="evenodd"&gt; &lt;use fill="#FF8D77" fill-opacity="0.5" filter="url(#glow)" xlink:href="#path-1"&gt;&lt;/use&gt; &lt;use fill="url(#gradient)" xlink:href="#path-3"&gt;&lt;/use&gt; &lt;use clip-path="url(#clip)" fill="#FF8D77" xlink:href="#path-5"&gt;&lt;/use&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
0
2016-09-30T20:00:20Z
39,799,403
<p>To insert additional string in your string variable <code>html</code>, you can do something like this:</p> <pre><code>import re html = '&lt;html&gt; ... &lt;defs&gt;&lt;-- inserts will go here --&gt; ... &lt;/html&gt;' insert = 'this line gets inserted' html = re.sub(r'(.*?&lt;defs&gt;)(.*)', r'\g&lt;1&gt;' + insert + r'\g&lt;2&gt;', html) # html is now '&lt;html&gt; ... &lt;defs&gt;this line gets inserted&lt;-- inserts will go here --&gt; ... &lt;/html&gt;' </code></pre> <p>If you make this into a function, you can keep injecting more lines repeatedly.</p> <pre><code>import re def add_definitions(html, definitions): html = re.sub(r'(.*?&lt;defs&gt;)(.*)', r'\g&lt;1&gt;' + ''.join(definitions) + r'\g&lt;2&gt;', html) return html # then you can use it like this... html = '&lt;html&gt; ... &lt;defs&gt;&lt;-- inserts will go here --&gt; ... &lt;/html&gt;' html = add_definitions(html, [ 'add this line 1.', 'add this line 2.' ]) # html should now be '&lt;html&gt; ... &lt;defs&gt;add this line 1.add this line2.&lt;-- inserts will go here --&gt; ... &lt;/html&gt;' </code></pre>
0
2016-09-30T20:12:53Z
[ "python", "string", "parsing", "concatenation" ]
concatenate next to string if string found
39,799,240
<p>I'm trying to search through my strings then concatenate the string.</p> <pre><code>string = ' &lt;html&gt;&lt;body&gt;&lt;svg style="background: #40484b;" version="1.1" viewbox="0 0 400 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;defs&gt; &lt;!-- if you use the same shape multiple times, you put the reference here and reference it with &lt;use&gt; --&gt; &lt;rect height="100" id="path-1" width="100" x="25" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-3" width="100" x="150" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-5" width="100" x="275" y="25"&gt;&lt;/rect&gt; &lt;!-- gradient --&gt; &lt;lineargradient id="gradient" x1="50%" x2="50%" y1="0%" y2="100%"&gt; &lt;stop offset="0%" stop-color="#FF8D77"&gt;&lt;/stop&gt; &lt;stop offset="50%" stop-color="#FFBDB1"&gt;&lt;/stop&gt; &lt;stop offset="100%" stop-color="#F4E3F6"&gt;&lt;/stop&gt; &lt;/lineargradient&gt; &lt;!-- clip-path --&gt; &lt;clippath id="clip"&gt; &lt;circle cx="325" cy="75" r="50"&gt;&lt;/circle&gt; &lt;/clippath&gt; &lt;!-- filter --&gt; &lt;/defs&gt;&gt; &lt;g fill-rule="evenodd"&gt; &lt;use fill="#FF8D77" fill-opacity="0.5" filter="url(#glow)" xlink:href="#path-1"&gt;&lt;/use&gt; &lt;use fill="url(#gradient)" xlink:href="#path-3"&gt;&lt;/use&gt; &lt;use clip-path="url(#clip)" fill="#FF8D77" xlink:href="#path-5"&gt;&lt;/use&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/body&gt;&lt;/html&gt;' </code></pre> <p>That's how my string looks like. So far this is what I have</p> <pre><code> string_list = string if "&lt;defs&gt;" in string: ###I'm trying to concatenate strings after &lt;defs&gt; like &lt;defs&gt; string string </code></pre> <p>Also, I'd like to keep appending strings instead of replacing. Like If I have a user type in something; it keeps adding strings after defs instead of replacing what I already have.</p> <p>The output I'm expecting would be something like this, I added "concatenated string1" and "concatenated string2". I'm trying to add strings next to "defs" from my string list overall.</p> <p>Also what I meant by keep adding strings instead of replace is for instance. I have a - first user type in string "concatenate1" - Second user type in string "concatenate2" I want to add both concatenate 1 + contatenate 2 next to my defs tag.</p> <pre><code>&lt;html&gt;&lt;body&gt;&lt;svg style="background: #40484b;" version="1.1" viewbox="0 0 400 150" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"&gt; &lt;defs&gt; &lt;concatenated string1&gt; &lt;concatenated string2&gt; &lt;!-- if you use the same shape multiple times, you put the reference here and reference it with &lt;use&gt; --&gt; &lt;rect height="100" id="path-1" width="100" x="25" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-3" width="100" x="150" y="25"&gt;&lt;/rect&gt; &lt;rect height="100" id="path-5" width="100" x="275" y="25"&gt;&lt;/rect&gt; &lt;!-- gradient --&gt; &lt;lineargradient id="gradient" x1="50%" x2="50%" y1="0%" y2="100%"&gt; &lt;stop offset="0%" stop-color="#FF8D77"&gt;&lt;/stop&gt; &lt;stop offset="50%" stop-color="#FFBDB1"&gt;&lt;/stop&gt; &lt;stop offset="100%" stop-color="#F4E3F6"&gt;&lt;/stop&gt; &lt;/lineargradient&gt; &lt;!-- clip-path --&gt; &lt;clippath id="clip"&gt; &lt;circle cx="325" cy="75" r="50"&gt;&lt;/circle&gt; &lt;/clippath&gt; &lt;!-- filter --&gt; &lt;/defs&gt;&gt; &lt;g fill-rule="evenodd"&gt; &lt;use fill="#FF8D77" fill-opacity="0.5" filter="url(#glow)" xlink:href="#path-1"&gt;&lt;/use&gt; &lt;use fill="url(#gradient)" xlink:href="#path-3"&gt;&lt;/use&gt; &lt;use clip-path="url(#clip)" fill="#FF8D77" xlink:href="#path-5"&gt;&lt;/use&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/body&gt;&lt;/html&gt; </code></pre>
0
2016-09-30T20:00:20Z
39,799,511
<p>For a string with multiple lines you should use triple single quotes or triple double quotes. And instead of "if" statement you better use a "for" loop.</p>
1
2016-09-30T20:20:57Z
[ "python", "string", "parsing", "concatenation" ]
Jinja2 Specify Route REST Type
39,799,290
<p>My question is can I specify the type of REST route in Jinja2, for example if I have the route:</p> <pre><code>RedirectRoute('/&lt;id&gt;/somthing/&lt;key&gt;', myFile.Handler, name='name', strict_slash=True), </code></pre> <hr> <pre><code>class Handler(JSONHandler): def get(): ... def delete(): ... def post(): ... </code></pre> <hr> <pre><code>&lt;a href="{{ uri_for('name', id=id, key=key) }}" target="_blank"&gt;Delete&lt;/a&gt; </code></pre> <p>Is it possible to specify the <code>delete()</code> handler form the Jinja2 template?</p>
0
2016-09-30T20:03:21Z
39,800,067
<p>If I understand what you're asking, you have an endpoint which respond to the methods GET, POST, and DELETE and you want to know if you can make the HTML resulting from Jinja send a DELETE request your endpoint.</p> <p>The short answer is no. DELETE must always be performed by JavaScript and AJAX. The only methods you can specify in an HTML are GET (via a link) and POST (via a form).</p>
1
2016-09-30T21:03:45Z
[ "python", "html", "jinja2" ]
Deprecation warning on 13 dimentional array
39,799,325
<p>I have my sample data arranged in a matrix of dimension 216,13 where 216 are number of samples and 13 are features. I am fitting that in K-NN algorithm and when I predict this with 1,13 matrix I keep in getting a warning</p> <blockquote> <p><em>DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.</em></p> </blockquote> <p>I get valid and desirable response and this is working for me as expected but I would like to know how to get rid of this warning? </p> <p>Here is the data</p> <pre><code>X = [ [0.0, 0.0, 0.75, 0.0, 0.25, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0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0.0, 0.0, 0.0], [1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [0.5, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.75, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.25, 0.0, 0.25, 0.0, 0.75, 0.0, 0.0, 0.5], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0]] test = [0.0, 0.0, 0.0, 0.0, 0.0, -0.4, 0.6000000000000001, 0.0, 0.0, 0.6000000000000001, 0.0, 0.0, 0.0] clf = NearestNeighbors(n_neighbors=5,metric=cust_distance_current) clf.fit(X) Z= clf.kneighbors(test) x,y = Z[0],Z[1] print('distance : %s' % x) print('labels : %s' % y) </code></pre>
0
2016-09-30T20:06:07Z
39,800,533
<p>Ans1: use <code>x[0]</code> and <code>y[0]</code> instead of x,y.</p> <p>Your question asks to know why. You are not looking for any answer as your solution already works. Thus here is the explanation:</p> <p>You are using a 1D array not a 13D array. You have posted question in totally confusing manner too.</p> <p>You pasted the out put of X. And pasted code where you print x, y which take value from Z. Not X.</p> <p>What you are doing in <code>x,y = Z[0],Z[1]</code> is:</p> <p>x = passing values of Z[0] to one list</p> <p>y = passing values of Z[1] to second list</p> <p>Z is a 1D array. With 2 items. Z = [[ 1item_1, 1item_2,...], [ 2item_1, 2item_2,...]]</p> <p>Ans2: What the error message clearly mentions to you is that you are passing values of 1D array Z to x, y which are list. And it will not be supported for higher versions (of what it mentions as 0.17 and 0.19). Though it is supporting for your version.</p> <p>Hope you understood.</p>
0
2016-09-30T21:48:06Z
[ "python", "scikit-learn" ]
Deprecation warning on 13 dimentional array
39,799,325
<p>I have my sample data arranged in a matrix of dimension 216,13 where 216 are number of samples and 13 are features. I am fitting that in K-NN algorithm and when I predict this with 1,13 matrix I keep in getting a warning</p> <blockquote> <p><em>DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.</em></p> </blockquote> <p>I get valid and desirable response and this is working for me as expected but I would like to know how to get rid of this warning? </p> <p>Here is the data</p> <pre><code>X = [ [0.0, 0.0, 0.75, 0.0, 0.25, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.75], [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 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0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.75, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.25, 0.0, 0.25, 0.0, 0.75, 0.0, 0.0, 0.5], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0]] test = [0.0, 0.0, 0.0, 0.0, 0.0, -0.4, 0.6000000000000001, 0.0, 0.0, 0.6000000000000001, 0.0, 0.0, 0.0] clf = NearestNeighbors(n_neighbors=5,metric=cust_distance_current) clf.fit(X) Z= clf.kneighbors(test) x,y = Z[0],Z[1] print('distance : %s' % x) print('labels : %s' % y) </code></pre>
0
2016-09-30T20:06:07Z
39,800,681
<p>The problem is that you are passing a 1d array to <code>clf.kneighbors(test)</code>. Actually, you are using a list, which will implicitly get converted to a numpy array. Anyway, the following should solve the issue, as per the warning:</p> <pre><code>In [14]: arr = np.array(test) In [15]: arr.shape Out[15]: (13,) In [16]: arr = arr.reshape(1,-1) In [17]: arr.shape Out[17]: (1, 13) In [18]: clf.kneighbors(arr) Out[18]: (array([[ 0.585235 , 0.69282032, 0.71063352, 0.73654599, 0.82462113]]), array([[126, 128, 181, 182, 20]])) In [19]: </code></pre>
0
2016-09-30T22:01:39Z
[ "python", "scikit-learn" ]
Accessing bytesIO object after creation
39,799,427
<p>I am working on a scrapy spider, trying to extract text multiple pdfs in a directory, using slate (<a href="https://pypi.python.org/pypi/slate" rel="nofollow">https://pypi.python.org/pypi/slate</a>). I have no interest in saving the actual PDF to disk , and so I've been advised to look into the io.bytesIO subclass at <a href="https://docs.python.org/2/library/io.html#buffered-streams" rel="nofollow">https://docs.python.org/2/library/io.html#buffered-streams</a>. Based on <a href="http://stackoverflow.com/questions/39799009/creating-and-accessing-bytesio-object/39799090#39799090">Creating bytesIO object</a> , I have initialized the bytesIO class with the pdf body, but now I need to pass the data to the slate module. So far I have:</p> <pre><code>def save_pdf(self, response): in_memory_pdf = BytesIO(response.body) with open(in_memory_pdf, 'rb') as f: doc = slate.PDF(f) print(doc[0]) </code></pre> <p>I'm getting: </p> <pre><code>in_memory_pdf.read(response.body) TypeError: integer argument expected, got 'str' </code></pre> <p>How can I get this working?</p> <p>edit:</p> <pre><code>with open(in_memory_pdf, 'rb') as f: TypeError: coercing to Unicode: need string or buffer, _io.BytesIO found </code></pre> <p>edit 2:</p> <pre><code>def save_pdf(self, response): in_memory_pdf = BytesIO(bytes(response.body)) in_memory_pdf.seek(0) doc = slate.PDF(in_memory_pdf) print(doc) </code></pre>
0
2016-09-30T20:15:26Z
39,799,545
<p>You already know the answer. It is clearly mentioned in the Python TypeError message and clear from the documentation:</p> <pre><code>class io.BytesIO([initial_bytes]) </code></pre> <p>BytesIO accepts bytes. And you are passing it contents. i.e: response.body which is a string.</p>
1
2016-09-30T20:24:04Z
[ "python", "pdf" ]
Padding zeros into list at specific positions
39,799,455
<p>Given two lists of different length, but with mostly similar (or overlapping) values such as:</p> <pre><code>ls_1 = [7, 26, 26, 55, 69, 71, 73, 80, 121, 124, 126, 127, 131, 133, 144, 153, 153, 159, 160, 210, 219, 221, 235, 235, 241, 243, 289, 299, 300, 309, 327, 327, 328, 391, 419, 421, 423, 433] ls_2 = [7, 28, 28, 60, 69, 81, 121, 124, 125, 127, 131, 133, 144, 153, 153, 159, 160, 210, 219, 221, 235, 235, 241, 243, 327, 327, 330, 391, 419, 421, 423, 433] </code></pre> <p>Is there a an easy way to pad in the 'missing' values in list 2 with zeros so that the lists match in length?</p> <p>EDIT: I'm trying to find a way of making the lists have the same exact length by placing zeros where they are <em>most likely</em> to be found. Likelihood here is intended as as the measured distance between item[i] in list 1 and item[i] in list 2. </p> <p><em>Note1</em>: I understand that the problem is no well defined. A useful answer would for instance point me at a method to compare items in lists and finding a likely threshold.</p> <p><em>Note2</em>: Lists are always sorted, performance is not a big issue.</p> <p>Example: insert two zero between the values 69 and 81, and some more other zeros between 330 and 391.</p> <p>My approach so far has been calculating the difference between values and when the <code>difference &gt; some_treshold</code>, I'd do a <code>ls_2.insert</code>. </p> <p>However this seems not to be the most foolproof method, since it requirers an arbitrary threshold. </p> <pre><code>for i in range(len(ls_2)): distance = ls_2[i] - ls_1[i] if distance &gt; 3: ls_2.insert(i, 0) print(len(ls_2), len(ls_1)) #double-checking, lengths are the same. </code></pre> <p>I'm asking this question specifically because it leads to another question, that is how to compare different sized lists of integers. What I have in mind is that by doing the padding here described would enable me to implement more straightforwardly algorithms such as cos distance and euclidean distance. The very end goal is to pad a large number of lists and rank them by similarity to reference list of integers.</p> <p>Let me know if all this makes sense or if there are more straightforward ways of going about it. (And if it'd be more appropriate to post two separate questions). </p>
0
2016-09-30T20:17:32Z
39,799,527
<pre><code>ls_2.insert(ls_2.index(81), 0) </code></pre> <p>will insert a zero before the value <code>81</code>, just repeat and you have your two zeros. Cache the result of <code>ls_2.index(81)</code> in a variable to speed things up little.</p>
0
2016-09-30T20:22:25Z
[ "python", "sorting", "padding" ]
Padding zeros into list at specific positions
39,799,455
<p>Given two lists of different length, but with mostly similar (or overlapping) values such as:</p> <pre><code>ls_1 = [7, 26, 26, 55, 69, 71, 73, 80, 121, 124, 126, 127, 131, 133, 144, 153, 153, 159, 160, 210, 219, 221, 235, 235, 241, 243, 289, 299, 300, 309, 327, 327, 328, 391, 419, 421, 423, 433] ls_2 = [7, 28, 28, 60, 69, 81, 121, 124, 125, 127, 131, 133, 144, 153, 153, 159, 160, 210, 219, 221, 235, 235, 241, 243, 327, 327, 330, 391, 419, 421, 423, 433] </code></pre> <p>Is there a an easy way to pad in the 'missing' values in list 2 with zeros so that the lists match in length?</p> <p>EDIT: I'm trying to find a way of making the lists have the same exact length by placing zeros where they are <em>most likely</em> to be found. Likelihood here is intended as as the measured distance between item[i] in list 1 and item[i] in list 2. </p> <p><em>Note1</em>: I understand that the problem is no well defined. A useful answer would for instance point me at a method to compare items in lists and finding a likely threshold.</p> <p><em>Note2</em>: Lists are always sorted, performance is not a big issue.</p> <p>Example: insert two zero between the values 69 and 81, and some more other zeros between 330 and 391.</p> <p>My approach so far has been calculating the difference between values and when the <code>difference &gt; some_treshold</code>, I'd do a <code>ls_2.insert</code>. </p> <p>However this seems not to be the most foolproof method, since it requirers an arbitrary threshold. </p> <pre><code>for i in range(len(ls_2)): distance = ls_2[i] - ls_1[i] if distance &gt; 3: ls_2.insert(i, 0) print(len(ls_2), len(ls_1)) #double-checking, lengths are the same. </code></pre> <p>I'm asking this question specifically because it leads to another question, that is how to compare different sized lists of integers. What I have in mind is that by doing the padding here described would enable me to implement more straightforwardly algorithms such as cos distance and euclidean distance. The very end goal is to pad a large number of lists and rank them by similarity to reference list of integers.</p> <p>Let me know if all this makes sense or if there are more straightforward ways of going about it. (And if it'd be more appropriate to post two separate questions). </p>
0
2016-09-30T20:17:32Z
39,800,099
<p>Go about it by adding 0s at the end of your <code>ls_2</code>. Not in between as you have pointed out. This reduces a lot of complexity.</p> <p>Something like:</p> <pre><code>ls_1_length = len(ls_1) ls_2_length = len(ls_2) length_diff = ls_1_length - ls_2_length for index in length_diff: ls_2.append(0) </code></pre> <p>For the second part of your question. If you want to compare two lists of variable size why do you want to make these two lists the same size?</p> <p>Hope this helps.</p>
0
2016-09-30T21:05:59Z
[ "python", "sorting", "padding" ]
Defining Multivariate Gaussian Function for Quadrature with Scipy
39,799,523
<p>I'm having some trouble defining a multivariate gaussian pdf for quadrature using scipy. I write a function that takes a mean vector and covariance matrix as input and returns a gaussian function.</p> <pre><code>def make_mvn_pdf(mu, sigma): def f(x): return sp.stats.multivariate_normal.pdf(x, mu, sigma) return f </code></pre> <p>When I use make_mvn_pdf to define a Gaussian and try to index into the Gaussian I get an error that does not make sense. I begin by defining a mean vector and covariance matrix and passing them into make_mvn_pdf:</p> <pre><code># define covariance matrix Sigma = np.asarray([[1, .15], [.15, 1]]) # define propagator B = np.diag([2, 2]) # define data Obs = np.array([[-0.06895746],[ 0.18778 ]]) # define a Gaussian PDF: g_int_func = make_mvn_pdf(mean = np.dot(B,Obs[t,:]), cov = Sigma) </code></pre> <p>I try to pass in observations to the density in order to get back probabilities:</p> <pre><code>testarray=np.random.random((2,2)) g_int_func(testarray) </code></pre> <p>This returns the following error which I do not understand.</p> <pre><code>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-50-083a1915f674&gt; in &lt;module&gt;() 1 g_int_func = make_mvn_pdf(np.dot(B,Obs[t,:]),Gamma) ----&gt; 2 g_int_func(testarray) /Users/...in f(x) 17 def make_mvn_pdf(mu, sigma): 18 def f(x): ---&gt; 19 return sp.stats.multivariate_normal.pdf(x, mu, sigma) 20 return f 21 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/stats/_multivariate.pyc in pdf(self, x, mean, cov, allow_singular) 427 428 """ --&gt; 429 dim, mean, cov = _process_parameters(None, mean, cov) 430 x = _process_quantiles(x, dim) 431 psd = _PSD(cov, allow_singular=allow_singular) /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/stats/_multivariate.pyc in _process_parameters(dim, mean, cov) 54 55 if mean.ndim != 1 or mean.shape[0] != dim: ---&gt; 56 raise ValueError("Array 'mean' must be a vector of length %d." % dim) 57 if cov.ndim == 0: 58 cov = cov * np.eye(dim) ValueError: Array 'mean' must be a vector of length 2. </code></pre> <p>The ValueError states that the array 'mean' must be a vector of length 2 but this is the case. In fact, the dimension of the mean and covariance matrix and data passed in are all of length 2.</p>
0
2016-09-30T20:22:17Z
39,800,551
<p>The value that you give as the mean is <code>np.dot(B, Obs)</code> (taking into account the change you suggested in a comment), where <code>B</code> has shape (2, 2) and <code>Obs</code> has shape (2, 1). The result of that <code>dot</code> call has shape (2, 1). The problem is that is a <em>two</em>-dimensional array, and <code>multivariate_normal.pdf</code> expects <code>mu</code> to be a <em>one</em>-dimensional array, i.e. an array with shape (2,). (The error message uses the word "vector", which is a poor choice, because for many people, an array with shape (n, 1) <em>is</em> a (column) vector. It would be less ambiguous if the error message said "Array 'mean' must be a one-dimensional array of length 2.")</p> <p>There are at least two easy ways to fix the problem:</p> <ul> <li>You could ensure that <code>Obs</code> has shape (2,) instead of (2, 1), e.g. <code>Obs = np.array([-0.06895746, 0.18778])</code>. The <code>np.dot(B, Obs)</code> has shape (2,).</li> <li>"Flatten" the <code>mean</code> argument by using the <code>ravel</code> method: <code>mean=np.dot(B,Obs).ravel()</code>.</li> </ul>
1
2016-09-30T21:49:28Z
[ "python", "scipy", "statistics", "gaussian", "numerical-integration" ]
Cython code runs 125x slower when compiled against python 2 vs python 3
39,799,524
<p>I have a big block of Cython code that is parsing <a href="http://ibis.org/interconnect_wip/touchstone_spec2_draft3.pdf" rel="nofollow">Touchstone files</a> that I want to work with Python 2 and Python 3. I'm using very C-style parsing techniques for what I thought would be maximum efficiency, including manually malloc-ing and free-ing <code>char*</code> instead of using <code>bytes</code> so that I can avoid the GIL. When compiled using</p> <pre><code>python 3.5.2 0 anaconda cython 0.24.1 py35_0 anaconda </code></pre> <p>I see speeds that I'm happy with, a moderate boost on small files (~20% faster) and a huge boost on large files (~2.5<strong>x</strong> faster). When compiled against</p> <pre><code>python 2.7.12 0 anaconda cython 0.24.1 py27_0 anaconda </code></pre> <p>It runs about 125x slower (~17ms in Python 3 vs ~2.2s in Python 2). It's the exact same code compiled in different environments using a pretty simple <code>setuputils</code> script. I'm not currently using NumPy from Cython for any of the parsing or data storage.</p> <pre><code>import cython cimport cython from cython cimport array import array from libc.stdlib cimport strtod, malloc, free from libc.string cimport memcpy ctypedef long long int64_t # Really VS2008? Couldn't include this by default? # Bunch of definitions and utility functions omitted @cython.boundscheck(False) cpdef Touchstone parse_touchstone(bytes file_contents, int num_ports): cdef: char c char* buffer = &lt;char*&gt; file_contents int64_t length_of_buffer = len(file_contents) int64_t i = 0 # These are some cpdef enums FreqUnits freq_units Domain domain Format fmt double z0 bint option_line_found = 0 array.array data = array.array('d') array.array row = array.array('d', [0 for _ in range(row_size)]) while i &lt; length_of_buffer: c = buffer[i] # cdef char c if is_whitespace(c): i += 1 continue if is_comment_char(c): # Returns the last index of the comment i = parse_comment(buffer, length_of_buffer) continue if not option_line_found and is_option_leader_char(c): # Returns the last index of the option line # assigns values of all references passed in i = parse_option_line( buffer, length_of_buffer, i, &amp;domain, &amp;fmt, &amp;z0, &amp;freq_units) if i &lt; 0: # Lots of boring code along the lines of # if i == some_int: # raise Exception("message") # I did this so that only my top-level parse has to interact # with the interpreter, all the lower level functions have nogil option_line_found = 1 if option_line_found: if is_digit(c): # Parse a float row[row_idx] = strtod(buffer + i, &amp;end_of_value) # Jump the cursor to the end of that float i = end_of_value - p - 1 row_idx += 1 if row_idx == row_size: # append this row onto the main data array data.extend(row) row_idx = 0 i += 1 return Touchstone(num_ports, domain, fmt, z0, freq_units, data) </code></pre> <p>I've ruled out a few things, such as type casts. I also tested where the code simply loops over the entire file doing nothing. Either Cython optimized that away or it's just really fast because it causes <code>parse_touchstone</code> to not even show up in a <code>cProfile/pstats</code> report. I determined that it's not just the comment, whitespace, and option line parsing (not shown is the significantly more complicated keyword-value parsing) after I threw in a print statement in the last <code>if row_idx == row_size</code> block to print out a status and discovered that it's taking about 0.5-1 second (guesstimate) to parse a row with 512 floating point numbers on it. That really should not take so long, especially when using <code>strtod</code> to do the parsing. I also checked parsing just 2 rows' worth of values then jumping out of the while loop and it told me that parsing the comments, whitespace, and option line took up about 800ms (1/3 of the overall time), and that was for 6 lines of text totaling less than 150 bytes.</p> <p>Am I just missing something here? Is there a small trick that would cause Cython code to run 3 orders of magnitude slower in Python 2 than Python 3?</p> <p>(Note: I haven't shown the full code here because I'm not sure if I'm allowed to for legal reasons and because it's about 450 lines total)</p>
2
2016-09-30T20:22:17Z
39,838,264
<p>The problem is with <code>strtod</code>, which is not <a href="http://www.ryanjuckett.com/programming/optimizing-atof-and-strtod/" rel="nofollow">optimized in VS2008</a>. Apparently it internally calculates the length of the input string each time its called, and if you call it with a long string this will slow down your code considerably. To circumvent this you have to write a wrapper around <code>strtod</code> to use only small buffers at a time (see the above link for one example of how to do this) or write your own <code>strtod</code> function.</p>
1
2016-10-03T18:38:18Z
[ "python", "python-2.7", "cython" ]
specifying string types in cython code
39,799,571
<p>I'm doing some experimentation with cython and I came across some unexpected behavior: </p> <pre><code>In [1]: %load_ext cython In [2]: %%cython ...: cdef class foo(object): ...: cdef public char* val ...: def __init__(self, char* val): ...: self.val = val ...: In [3]: f = foo('aaa') In [4]: f.val Out[4]: '\x01' </code></pre> <p>What's going on with <code>f.val</code>? repeated inspection produces seemingly random output, so it looks like <code>f.val</code> is pointing to invalid memory.</p> <p>The answer to <a href="http://stackoverflow.com/questions/30879708/string-in-cython-functions">this question</a> suggests that you should use <code>str</code> instead. Indeed, this version works fine:</p> <pre><code>In [21]: %%cython ...: cdef class foo(object): ...: cdef public str val ...: def __init__(self, str val): ...: self.val = val </code></pre> <p>So, what is going on in the first version? It seems like the <code>char*</code> is getting freed at some point after class construction but I'm not really clear on why.</p>
2
2016-09-30T20:25:50Z
39,800,829
<p>When you convert a Python bytestring to a <code>char *</code> in Cython, Cython gives you a pointer to the contents of the string object. This raw pointer does not affect the string's Python refcount (it'd be infeasible to track which pointers refer to which strings).</p> <p>When the string's refcount hits zero and the string is reclaimed, your pointer becomes invalid.</p> <p>You shouldn't convert Python bytestrings to <code>char *</code>s unless you actually need a <code>char *</code>. If you do, make sure to also keep a normal Python reference to the string for as long as you need the <code>char *</code>, to extend the string's lifetime.</p>
2
2016-09-30T22:15:21Z
[ "python", "cython" ]
SqlAlchemy issues with foreign keys
39,799,616
<p>I am getting the error </p> <blockquote> <p>Could not parse rfc1738 URL from string 'MACHINE_IE'</p> </blockquote> <p>When I attempt to import the following</p> <pre><code>class MACHINE(declarative_base()): __tablename__ = 'MACHINE' MACHINE_UID = Column(Integer, primary_key=True) MACHINE_IP = Column(String) MACHINE_NAME = Column(String) MACHINE_INFO = Column(String) class IE(declarative_base()): __tablename__ = 'IE' IE_UID = Column(Integer, primary_key=True) IE_VERSION = Column(String) IE_MAJOR = Column(String) class MACHINE_IE(declarative_base().metadata): __tablename__ = 'MACHINE_IE' IE_UID = Column(Integer, ForeignKey("IE.IE_UID"), primary_key=True) MACHINE_UID = Column(Integer, ForeignKey("MACHINE.MACHINE_UID")) EFFECTIVE_DATE = Column(DateTime) </code></pre> <p>If I remove</p> <blockquote> <p>metadata</p> </blockquote> <p>then I can import the module and perform a query on the "MACHINE" and "IE" tables and display the data from the rows. However when I query "MACHINE_IE" and then try to display some data from the query I get the following</p> <blockquote> <p>sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'MACHINE_IE.IE_UID' could not find table 'IE' with which to generate a foreign key to target column 'IE_UID'</p> </blockquote> <p>I am guessing I need "metadata" in there but the error seems to be complaining about the db connection string when I use it. However I am able to connect to the db w/o issue if "metadata" is removed.</p> <p>Here is the connection data</p> <pre><code>connect_string = "oracle+cx_oracle://{0}:{1}@{2}:{3}/{4}".format(user, pw, server, port, sid) </code></pre> <p>Any assistance is appreciated.</p>
0
2016-09-30T20:29:17Z
39,799,806
<p>You are using multiple instances of <code>Base</code>. You should be doing:</p> <pre><code>Base = declarative_base() class MACHINE(Base): ... class IE(Base): ... ... </code></pre>
1
2016-09-30T20:44:23Z
[ "python", "sqlalchemy" ]
Merging two dataframes only at specific times
39,799,712
<p>I have two excel files that I'm trying to merge into one using <code>pandas</code>. The first file is a list of times and dates with a subscriber count for that given time and day. The second file has weather information on an hourly basis. I import both files and the data resembles:</p> <pre><code>df1= Date Count 2010-01-02 09:00:00 15 2010-01-02 10:00:00 8 2010-01-02 11:00:00 9 2010-01-02 12:00:00 11 2010-01-02 13:00:00 8 2010-01-02 14:00:00 10 2010-01-02 15:00:00 8 2010-01-02 16:00:00 6 ... df2 = Date Temp Rel_Hum Pressure Weather 2010-01-00 09:00:00 -5 93 100.36 Snow,Fog 2010-01-01 10:00:00 -5 93 100.36 Snow,Fog 2010-01-02 11:00:00 -6.5 91 100 Snow,Fog 2010-01-03 12:00:00 -7 87 89 Snow,Fog 2010-01-04 13:00:00 -7 87 89 Snow,Fog 2010-01-05 14:00:00 -6.7 88 89 Snow,Fog 2010-01-06 15:00:00 -6.5 89 89 Snow,Fog 2010-01-07 16:00:00 -6 88 90 Snow,Fog 2010-01-08 17:00:00 -6 89 89 Snow,Fog ... </code></pre> <p>I only need to weather info for the times that are specified in <code>df1</code>, but <code>df2</code> contains weather info for a 24 hour period for everyday of that month. </p> <p>Since <code>df1</code> only contains 2 columns, I've modified <code>df1</code> to have a <code>Temp</code> <code>Rel_Hum</code> <code>Pressure</code> and <code>Weather</code> column so that it resembles: </p> <pre><code>Date Count Temp Rel_Hum Pressure Weather 2010-01-02 09:00:00 15 0 0 0 0 2010-01-02 10:00:00 8 0 0 0 0 2010-01-02 11:00:00 9 0 0 0 0 2010-01-02 12:00:00 11 0 0 0 0 2010-01-02 13:00:00 8 0 0 0 0 2010-01-02 14:00:00 10 0 0 0 0 2010-01-02 15:00:00 8 0 0 0 0 2010-01-02 16:00:00 6 0 0 0 0 ... </code></pre> <p>I've managed to test the code that I've written for a one month period and the problem that I'm encountering is that it is taking a great deal of time to complete the task. I wanted to know if there was a faster way of going about this</p> <pre><code>import pandas as pd import numpy as np from datetime import datetime location = '/home/lukasz/Documents/BUS/HOURLY_DATA.xlsx' location2 = '/home/lukasz/Documents/BUS/Weather Data/2010-01.xlsx' df1 = pd.read_excel(location) df2 = pd.read_excel(location2) df.Temp = df.Temp.astype(float) df.Rel_Hum = df.Rel_Hum.astype(float) df.Pressure = df.Pressure.astype(float) df.Weather = df.Weather.astype(str) n = len(df2) - len(df) for i in range(len(df)): print(df['Date'][i]) for j in range(i, i+n): date_object = datetime.strptime(df2['Date/Time'][j], '%Y-%m-%d %H:%M') # The date column in df2 is a str if df['Date'][i] == date_object: df.set_value(i, 'Temp', df2['Temp'][j]) df.set_value(i, 'Dew_Point_Temp', df2['Dew_Point_Temp'][j]) df.set_value(i, 'Rel_Hum', df2['Rel_Hum'][j]) df.set_value(i, 'Pressure', df2['Pressure'][j]) df.set_value(i, 'Weather', df2['Weather'][j]) # print(df[:5]) df.to_excel(location, index=False) </code></pre>
2
2016-09-30T20:36:41Z
39,799,843
<p>Use a combination of <code>reindex</code> to get <code>df2</code> aligned with <code>df1</code>. Make sure to include parameter <code>method='ffill'</code> to forward fill weather information.</p> <p>Then use <code>join</code></p> <pre><code>df1.join(df2.set_index('Date').reindex(df1.Date, method='ffill'), on='Date') </code></pre> <p><a href="http://i.stack.imgur.com/v9AYW.png" rel="nofollow"><img src="http://i.stack.imgur.com/v9AYW.png" alt="enter image description here"></a></p>
2
2016-09-30T20:47:11Z
[ "python", "pandas" ]
Using arithmetic equations in Python
39,799,747
<p>is there a way to round the value down to the lowest integer for this?</p> <pre><code>x = 5.5 z = 1 x -= z </code></pre> <p>x is just 4.5 in this case</p> <p>but I want something like this</p> <pre><code>x = int(x - z) </code></pre> <p>which produces x as 4 but i would like to use the '-='</p> <p>is there a way?</p>
-2
2016-09-30T20:40:01Z
39,799,795
<p>No unfortunately there isn't a way to do exactly what you described. Your best option would be to do <code>x=int(x-z)</code> or if you want to round up in the case that <code>x=4.5</code> and preserve the <code>float</code> type, <code>x=round(x-z)</code>. </p>
2
2016-09-30T20:43:14Z
[ "python" ]
Using arithmetic equations in Python
39,799,747
<p>is there a way to round the value down to the lowest integer for this?</p> <pre><code>x = 5.5 z = 1 x -= z </code></pre> <p>x is just 4.5 in this case</p> <p>but I want something like this</p> <pre><code>x = int(x - z) </code></pre> <p>which produces x as 4 but i would like to use the '-='</p> <p>is there a way?</p>
-2
2016-09-30T20:40:01Z
39,799,845
<pre><code>x = 5.5 a = 1 x -= a x = int(x) </code></pre> <p>Try this. It will work</p>
0
2016-09-30T20:47:18Z
[ "python" ]
Using arithmetic equations in Python
39,799,747
<p>is there a way to round the value down to the lowest integer for this?</p> <pre><code>x = 5.5 z = 1 x -= z </code></pre> <p>x is just 4.5 in this case</p> <p>but I want something like this</p> <pre><code>x = int(x - z) </code></pre> <p>which produces x as 4 but i would like to use the '-='</p> <p>is there a way?</p>
-2
2016-09-30T20:40:01Z
39,799,911
<p>You can also use a dedicated solution:</p> <pre><code>import math math.floor(x-z) </code></pre> <p>It will always give you lower integer value (in fact it will be a float type but with an integer value).</p> <p>Note that for <code>round(0.7) == 1.0</code>!!</p>
0
2016-09-30T20:52:08Z
[ "python" ]
How to remove frequency from signal
39,799,821
<p>I want to remove one frequency (one peak) from signal and plot my function without it. After fft I found frequency and amplitude and I am not sure what I need to do now. For example I want to remove my highest peak (marked with red dot on plot).</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # create data N = 4097 T = 100.0 t = np.linspace(-T/2,T/2,N) f = np.sin(50.0 * 2.0*np.pi*t) + 0.5*np.sin(80.0 * 2.0*np.pi*t) #plot function plt.plot(t,f,'r') plt.show() # perform FT and multiply by dt dt = t[1]-t[0] ft = np.fft.fft(f) * dt freq = np.fft.fftfreq(N, dt) freq = freq[:N/2+1] amplitude = np.abs(ft[:N/2+1]) # plot results plt.plot(freq, amplitude,'o-') plt.legend(('numpy fft * dt'), loc='upper right') plt.xlabel('f') plt.ylabel('amplitude') #plt.xlim([0, 1.4]) plt.plot(freq[np.argmax(amplitude)], max(amplitude), 'ro') print "Amplitude: " + str(max(amplitude)) + " Frequency: " + str(freq[np.argmax(amplitude)]) plt.show() </code></pre>
3
2016-09-30T20:45:59Z
39,801,000
<p>You can design a bandstop filter:</p> <pre><code>wc = freq[np.argmax(amplitude)] / (0.5 / dt) wp = [wc * 0.9, wc / 0.9] ws = [wc * 0.95, wc / 0.95] b, a = signal.iirdesign(wp, ws, 1, 40) f = signal.filtfilt(b, a, f) </code></pre>
5
2016-09-30T22:32:49Z
[ "python", "numpy", "math", "fft" ]
How to remove frequency from signal
39,799,821
<p>I want to remove one frequency (one peak) from signal and plot my function without it. After fft I found frequency and amplitude and I am not sure what I need to do now. For example I want to remove my highest peak (marked with red dot on plot).</p> <pre><code>import numpy as np import matplotlib.pyplot as plt # create data N = 4097 T = 100.0 t = np.linspace(-T/2,T/2,N) f = np.sin(50.0 * 2.0*np.pi*t) + 0.5*np.sin(80.0 * 2.0*np.pi*t) #plot function plt.plot(t,f,'r') plt.show() # perform FT and multiply by dt dt = t[1]-t[0] ft = np.fft.fft(f) * dt freq = np.fft.fftfreq(N, dt) freq = freq[:N/2+1] amplitude = np.abs(ft[:N/2+1]) # plot results plt.plot(freq, amplitude,'o-') plt.legend(('numpy fft * dt'), loc='upper right') plt.xlabel('f') plt.ylabel('amplitude') #plt.xlim([0, 1.4]) plt.plot(freq[np.argmax(amplitude)], max(amplitude), 'ro') print "Amplitude: " + str(max(amplitude)) + " Frequency: " + str(freq[np.argmax(amplitude)]) plt.show() </code></pre>
3
2016-09-30T20:45:59Z
39,801,665
<p>I wanted something like this. I know that there is better solution but my hacked works. :) Second peak is removed.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from scipy.fftpack import rfft, irfft, fftfreq, fft import scipy.fftpack # Number of samplepoints N = 500 # sample spacing T = 0.1 x = np.linspace(0.0, N*T, N) y = 5*np.sin(x) + np.cos(2*np.pi*x) yf = scipy.fftpack.fft(y) xf = np.linspace(0.0, 1.0/(2.0*T), N/2) #fft end f_signal = rfft(y) W = fftfreq(y.size, d=x[1]-x[0]) cut_f_signal = f_signal.copy() cut_f_signal[(W&gt;0.6)] = 0 cut_signal = irfft(cut_f_signal) # plot results f, axarr = plt.subplots(1, 3) axarr[0].plot(x, y) axarr[0].plot(x,5*np.sin(x),'g') axarr[1].plot(xf, 2.0/N * np.abs(yf[:N//2])) axarr[1].legend(('numpy fft * dt'), loc='upper right') axarr[1].set_xlabel("f") axarr[1].set_ylabel("amplitude") axarr[2].plot(x,cut_signal) axarr[2].plot(x,5*np.sin(x),'g') plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/zIbct.png" rel="nofollow"><img src="http://i.stack.imgur.com/zIbct.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/s46SR.png" rel="nofollow"><img src="http://i.stack.imgur.com/s46SR.png" alt="enter image description here"></a></p>
1
2016-10-01T00:06:53Z
[ "python", "numpy", "math", "fft" ]
converting an object to float in pandas along with replacing a $ sign
39,799,859
<p>I am fairly new to Pandas and I am working on project where I have a column that looks like the following:</p> <pre><code>AverageTotalPayments $7064.38 $7455.75 $6921.90 ETC </code></pre> <p>I am trying to get the cost factor out of it where the cost could be anything above 7000. First, this column is an object. Thus, I know that I probably cannot do a comparison with it to a number. My code, that I have looks like the following:</p> <pre><code>import pandas as pd health_data = pd.read_csv("inpatientCharges.csv") state = input("What is your state: ") issue = input("What is your issue: ") #This line of code will create a new dataframe based on the two letter state code state_data = health_data[(health_data.ProviderState == state)] #With the new data set I search it for the injury the person has. issue_data=state_data[state_data.DRGDefinition.str.contains(issue.upper())] #I then make it replace the $ sign with a '' so I have a number. I also believe at this point my code may be starting to break down. issue_data = issue_data['AverageTotalPayments'].str.replace('$', '') #Since the previous line took out the $ I convert it from an object to a float issue_data = issue_data[['AverageTotalPayments']].astype(float) #I attempt to print out the values. cost = issue_data[(issue_data.AverageTotalPayments &gt;= 10000)] print(cost) </code></pre> <p>When I run this code I simply get nan back. Not exactly what I want. Any help with what is wrong would be great! Thank you in advance.</p>
2
2016-09-30T20:48:18Z
39,799,920
<p>Consider the <code>pd.Series</code> <code>s</code></p> <pre><code>s 0 $7064.38 1 $7455.75 2 $6921.90 Name: AverageTotalPayments, dtype: object </code></pre> <p>This gets the float values</p> <pre><code>pd.to_numeric(s.str.replace('$', ''), 'ignore') 0 7064.38 1 7455.75 2 6921.90 Name: AverageTotalPayments, dtype: float64 </code></pre> <p>Filter <code>s</code></p> <pre><code>s[pd.to_numeric(s.str.replace('$', ''), 'ignore') &gt; 7000] 0 $7064.38 1 $7455.75 Name: AverageTotalPayments, dtype: object </code></pre>
2
2016-09-30T20:52:34Z
[ "python", "pandas", "data-science" ]
converting an object to float in pandas along with replacing a $ sign
39,799,859
<p>I am fairly new to Pandas and I am working on project where I have a column that looks like the following:</p> <pre><code>AverageTotalPayments $7064.38 $7455.75 $6921.90 ETC </code></pre> <p>I am trying to get the cost factor out of it where the cost could be anything above 7000. First, this column is an object. Thus, I know that I probably cannot do a comparison with it to a number. My code, that I have looks like the following:</p> <pre><code>import pandas as pd health_data = pd.read_csv("inpatientCharges.csv") state = input("What is your state: ") issue = input("What is your issue: ") #This line of code will create a new dataframe based on the two letter state code state_data = health_data[(health_data.ProviderState == state)] #With the new data set I search it for the injury the person has. issue_data=state_data[state_data.DRGDefinition.str.contains(issue.upper())] #I then make it replace the $ sign with a '' so I have a number. I also believe at this point my code may be starting to break down. issue_data = issue_data['AverageTotalPayments'].str.replace('$', '') #Since the previous line took out the $ I convert it from an object to a float issue_data = issue_data[['AverageTotalPayments']].astype(float) #I attempt to print out the values. cost = issue_data[(issue_data.AverageTotalPayments &gt;= 10000)] print(cost) </code></pre> <p>When I run this code I simply get nan back. Not exactly what I want. Any help with what is wrong would be great! Thank you in advance.</p>
2
2016-09-30T20:48:18Z
39,799,927
<p>Try this:</p> <pre><code>In [83]: df Out[83]: AverageTotalPayments 0 $7064.38 1 $7455.75 2 $6921.90 3 aaa In [84]: df.AverageTotalPayments.str.extract(r'.*?(\d+\.*\d*)', expand=False).astype(float) &gt; 7000 Out[84]: 0 True 1 True 2 False 3 False Name: AverageTotalPayments, dtype: bool In [85]: df[df.AverageTotalPayments.str.extract(r'.*?(\d+\.*\d*)', expand=False).astype(float) &gt; 7000] Out[85]: AverageTotalPayments 0 $7064.38 1 $7455.75 </code></pre>
2
2016-09-30T20:53:00Z
[ "python", "pandas", "data-science" ]
How can I use x, y coordinate matrices to choose where a character appears in a string with python?
39,799,890
<p>I am attempting to make a simple maze game to test a NNS with genetic algorithms. the maze for each test would use a matrix to hold the x, y points of things like barriers, the start, the end, and the player's current position. The main thing that I need help with is placing the right character in the right location in a string so when the strings of row 1-25 are read (probably with a for loop) it will read out a layout of the map. As an example, the barrier points 1,1 3,4 and 1,5 would look like this if an "o" is a space: first string<code>|XoooX|</code>, second string<code>|ooooo|</code>, third string<code>|ooooo|</code>, fourth string<code>|ooXoo|</code>. Any ideas? Thanks in advance!</p>
-1
2016-09-30T20:50:36Z
39,800,059
<p>You're probably looking for something along the lines of this:</p> <pre><code>width = 6 height = 6 coords = [(1,1),(3,4),(1,5)] print('\n'.join(['|' + ''.join(['x' if (x,y) in coords else 'o' for x in range(width)]) + '|' for y in range(height)])) </code></pre> <p>Using list comprehension, we can easily construct each row one at a time:</p> <pre><code>''.join(['x' if (x,y) in coords else 'o' for x in range(width)]) </code></pre> <p>Basically, print an <code>x</code> if the coordinate contains something, otherwise use <code>o</code>.</p> <p>Add the side bars in...</p> <pre><code>'|' + ''.join([...]) + '|' </code></pre> <p><code>''.join()</code> is a <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow">very useful function</a> for this.</p> <p>Then all we have to do is repeat this for each row, making sure to insert a line break between each row.</p> <pre><code>'\n'.join([...]) </code></pre>
0
2016-09-30T21:03:26Z
[ "python", "arrays", "string", "matrix", "coordinate" ]
Install Paramiko on my Mac OS X 10.11
39,799,891
<p>I tried to install paramiko on my Mac OS X 10.11</p> <p>sudo pip install paramiko</p> <p>Password:*******</p> <p>then I got </p> <pre><code>The directory '/Users/bheng/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/bheng/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting paramiko Downloading paramiko-2.0.2-py2.py3-none-any.whl (171kB) 100% |████████████████████████████████| 174kB 6.7MB/s Requirement already satisfied (use --upgrade to upgrade): pyasn1&gt;=0.1.7 in /Library/Python/2.7/site-packages (from paramiko) Collecting cryptography&gt;=1.1 (from paramiko) Downloading cryptography-1.5.2-cp27-cp27m-macosx_10_10_intel.whl (2.4MB) 100% |████████████████████████████████| 2.4MB 568kB/s Requirement already satisfied (use --upgrade to upgrade): cffi&gt;=1.4.1 in /Library/Python/2.7/site-packages (from cryptography&gt;=1.1-&gt;paramiko) Collecting setuptools&gt;=11.3 (from cryptography&gt;=1.1-&gt;paramiko) Downloading setuptools-28.0.0-py2.py3-none-any.whl (467kB) 100% |████████████████████████████████| 471kB 2.7MB/s Requirement already satisfied (use --upgrade to upgrade): six&gt;=1.4.1 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from cryptography&gt;=1.1-&gt;paramiko) Collecting idna&gt;=2.0 (from cryptography&gt;=1.1-&gt;paramiko) Downloading idna-2.1-py2.py3-none-any.whl (54kB) 100% |████████████████████████████████| 61kB 10.4MB/s Collecting ipaddress (from cryptography&gt;=1.1-&gt;paramiko) Downloading ipaddress-1.0.17-py2-none-any.whl Collecting enum34 (from cryptography&gt;=1.1-&gt;paramiko) Downloading enum34-1.1.6-py2-none-any.whl Requirement already satisfied (use --upgrade to upgrade): pycparser in /Library/Python/2.7/site-packages (from cffi&gt;=1.4.1-&gt;cryptography&gt;=1.1-&gt;paramiko) Installing collected packages: setuptools, idna, ipaddress, enum34, cryptography, paramiko Found existing installation: setuptools 1.1.6 Uninstalling setuptools-1.1.6: Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 736, in install requirement.uninstall(auto_confirm=True) File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 742, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 299, in move copytree(src, real_dst, symlinks=True) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 208, in copytree raise Error, errors Error: [('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.py', '/tmp/pip-EMyxYY-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.py', "[Errno 1] Operation not permitted: '/tmp/pip-EMyxYY-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.py'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.pyc', '/tmp/pip-EMyxYY-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.pyc', "[Errno 1] Operation not permitted: '/tmp/pip-EMyxYY-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/__init__.pyc'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.py', '/tmp/pip-EMyxYY-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.py', "[Errno 1] Operation not permitted: '/tmp/pip-EMyxYY-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.py'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.pyc', '/tmp/pip-EMyxYY-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.pyc', "[Errno 1] Operation not permitted: '/tmp/pip-EMyxYY-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/markers.pyc'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib', '/tmp/pip-EMyxYY-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib', "[Errno 1] Operation not permitted: '/tmp/pip-EMyxYY-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib'")] </code></pre> <p>What did I do wrong ? </p> <p>Any helps on this will be much appreciated ! </p>
1
2016-09-30T20:50:39Z
39,806,539
<p>Try <code>sudo chown $(whoami) /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/_markerlib/</code> Then do the same for any directories that Python doesn't have permissions for.</p> <p>Recent versions of OSX and macOS have a system called System Integrity Protection that means that some directories don't have user permissions. This is in order to prevent the possibility of malware controlling system-central directories, such as <code>/System</code> and <code>/tmp</code>.</p> <p><strong>EDIT</strong></p> <p><code>pip install --user paramiko</code> installs the library under the user directory, meaning you won't have problems with permissions. There are other ways to fix this issue with Python consistently, see the comments on this post for more.</p>
2
2016-10-01T12:21:11Z
[ "python", "osx", "paramiko" ]
How to serialize a single model instance AND include the primary key
39,799,893
<p>I have a single model instance <code>obj</code>. I want to serialize it, and for the primary key to be included in the serialized data.</p> <ul> <li><p><code>django.core.serializers.serializer</code> wants a queryset (throws an error that <code>ojb</code> isn't iterable).</p></li> <li><p>I simply cannot coerce <code>django.forms.model_to_dict</code> into including the primary key in the serialized object, even explicitly calling: <code>model_to_dict(obj, fields=['pk'])</code> or <code>model_to_dict(obj, fields=['id'])</code></p></li> </ul> <p>How do I do this?</p>
0
2016-09-30T20:50:49Z
39,803,866
<p><code>model_to_dict</code> will not dump fields that have <code>editable=False</code> (so, for example, the primary key). It is possible to manually construct the object serialization by:</p> <pre><code>{field.name: field.value_from_object(obj) for field in obj._meta.fields} </code></pre>
0
2016-10-01T06:57:08Z
[ "python", "django", "serialization" ]
Dynamic method binding with inheritance in Python
39,799,973
<p>I am new to python (~ a month), and I wish I had switched to it sooner (after years of perl). </p> <p><strong>Problem</strong>: I want objects to have different functionality to the same method call based on their type. The methods are assigned at runtime, based on the module loaded (which composes all objects).</p> <p><strong>Question</strong>: I wanted to know if there was a popular design pattern that I could use instead of the below, or if this already has a design pattern name (I sadly have no formal CS background, and knowing this will help my documentation)<strong>?</strong></p> <p>I have a class hierarchy (as of now, 26 of them with 3 base classes). Only the base classes have some trivial methods (eg: add_child), and each derived class only extends the base class with new data attributes (specific to the derived class), overriding methods when necessary (eg: __str__).</p> <p>I am dealing with tree(s) where nodes are of different classes. Yet, the nodes should the same certain method names (<code>stringify</code>, <code>print_tree</code>, <code>emit</code>, <code>eval</code>, <code>transform_X</code>, etc), thereby allowing easy/blind iterator operation. Each method may do something different, yet the methods have the same call name (like <em>polymorphism</em>).</p> <p>I primarily wanted to grant specific abilities (methods) to nodes, based on their type. Initially, I implemented this using the <a href="http://stackoverflow.com/questions/25891637/visitor-pattern-in-python?newreg=d5c745988c5844e8a248268074a9b7bb">Visitor Pattern</a>. But, then realized I didn't really have to, considering I was working in Python.</p> <p>In the below example, I have methods which are dynamically assigned to classes. Note, in below example the iteration/recursion method call name (<code>print_tree</code>) is different from the function name (<code>generic__print_tree</code>).</p> <pre class="lang-py prettyprint-override"><code>#astmethods.py def generic__print_tree(self, level=1): """ Desc: print nodes with indentation Target: Any tree node """ print("{}&gt; {}".format('-' * level, self)) for child in self.children: child.print_tree((level + 1)) def ASTNode__stringify(self): """ Desc: Return string representation of the tree under this node Target: AST/CFG nodes """ text = str(self) for child in self.children: text += ", { " + child.stringify() + " }" return text </code></pre> <p>Finally the <strong>main</strong> modules has this function, <em>extend_types()</em> which gets called during module init. The nodes are expected to do different things, within the context of this module, based on their type (not value). The methods assigned are inherited, unless overridden.</p> <pre class="lang-py prettyprint-override"><code># mainModule1.py def extend_types(): """ Upgrade the AST node classes with neat functions for use within this module's context """ # same simple functions across class hierarchies # I should just derive them both from a common base class to avoid this ASTNode.print_tree = generic__print_tree SimpleNode.print_tree = generic__print_tree # ASTNode and all derived class get this method ASTNode.stringify = ASTNode__stringify # All AST nodes get the base method, except for Ignore and Arraysel type nodes # traversal looks the same with child.tidy() ASTNode.tidy = ASTNode__tidy ASTIgnore.tidy = ASTIgnore__tidy ASTArraySel.tidy = ASTArraySel__tidy # All AST nodes get the base method, except for the Coverage and If type nodes ASTNode.transform_controlFlow = ASTNode__transform_controlFlow ASTCoverage.transform_controlFlow = ASTCoverage__transform_controlFlow ASTIf.transform_controlFlow = ASTIf__transform_controlFlow </code></pre> <p>edit: removed distracting info, made the example for a single module context</p>
0
2016-09-30T20:56:49Z
39,800,961
<h2>Problem Summary</h2> <p>Ignoring the irrelevant details, the problems here can be summed up as follows:</p> <p>There is one base class and many derived classes. There is a certain functionality which should apply to all of the derived classes, but depends on some external switch (in the question: choice of <em>"<strong>main</strong> module"</em>).</p> <p>The idea in the question is to monkeypatch the base class depending on the switch. </p> <h2>Solution</h2> <p>Instead of that, the functionality which depends on the external switch should be separated.</p> <p>In example:</p> <pre><code># There is a base class: class ASTNode(object): pass # There are many derived classes, e.g.: class ASTVar(ASTNode): pass # One implementation of function stringify or another # should be defined for all objects, depending on some external factor def stringify1(node): # something def stringify2(node): # something else # Depending on whatever, choose one of them: stringify = stringify1 </code></pre> <p>This is now used just a little bit differently than in the original code: intead of <code>node.stringify()</code>, there is now <code>stringify(node)</code>. But there is nothing wrong with that.</p> <p>BTW...</p> <p>Maybe it would be more pleasing to the eye to use a class:</p> <p>class NodeHandler1(object): def print_tree(node): # do something</p> <pre><code>def stringify(node): # do something ... </code></pre> <p>But that is not required at all.</p> <h2>The Moral</h2> <p>Do not monkeypatch. That is always bad design.</p>
0
2016-09-30T22:28:08Z
[ "python", "design-patterns", "visitor" ]
How is a page instance's slug defined in Mezzanine CMS?
39,800,065
<p>From the <a href="https://github.com/stephenmcd/mezzanine/blob/master/docs/content-architecture.rst" rel="nofollow">Mezzanine docs</a>:</p> <blockquote> <p>By default the template pages/page.html is used, but if a custom template exists it will be used instead. The check for a custom template will first check for a template with the same name as the Page instance’s slug, and if not then a template with a name derived from the subclass model’s name is checked for. So given the above example the templates pages/dr-seuss.html and pages/author.html would be checked for respectively.</p> </blockquote> <p>The question is where does Mezzanine CMS gets the slug for an instance of a page? Is it from the title attribute?</p>
2
2016-09-30T21:03:38Z
39,800,201
<p>The slug is automatically generated from the title attribute by default, but it can also be set manually from the "URL" option in the meta data section of the page admin.</p>
1
2016-09-30T21:14:15Z
[ "python", "django", "mezzanine" ]
Extending a C++ application with python
39,800,120
<p>I have a legacy (but still internally maintained) application written in C++ which handles some hardware, interacts with databases, receives commands via serial line or socket... in short it does a non-trivial amount of work.</p> <p>This application runs under Linux (ARM/Buildroot).</p> <p>Now the need is to revamp the control interface adding a RESTful API.</p> <p>I am exploring the possibility to do so via a Python extension.</p> <p>Note I am a C++/java programmer and I'm not really proficient in Python, but I know the basics.</p> <p>General idea would be:</p> <ul> <li>Start a Python interpreter as a thread in the C++ application.</li> <li>Use Flask/jinja2 (or just plain Bottle) to handle incoming RESTful requests.</li> <li>Expose a few (perhaps just one) C++ class to Python.</li> <li>Call from Python the appropriate C++ methods to perform the required actions.</li> </ul> <p>I studied the official documentation (mainly pertaining plain C) and several alternatives, including:</p> <ul> <li>Boost.Python (possibly too heavy for our limited hardware)</li> <li>pybind11 (seems concerned only in extending Python, not embedding it).</li> <li><a href="http://www.codeproject.com/Articles/11805/Embedding-Python-in-C-C-Part-I" rel="nofollow">http://www.codeproject.com/Articles/11805/Embedding-Python-in-C-C-Part-I</a> (deals only with embedding, without giving Python access to C++ classes).</li> </ul> <p>Question are:</p> <ul> <li>does this make any sense?</li> <li>what is the least intrusive way (if any) to achieve this?</li> <li>which lib/framework is advised to use?</li> <li>is there some tutorial project along these lines?</li> </ul> <p>I know the question is quite broad, but I hope to narrow it as soon as the first comments will point me in the right direction.</p>
0
2016-09-30T21:07:39Z
39,812,790
<p>Can you do it the other way around - embed your C++ code in Python program? This way it would be more prepared for moving existing functionality Python like you said.</p> <p>Python makes a lot of things easier (faster to develop, easier to maintain) - communication with databases, libraries (if hey have Python wrappers), process/thread management... Keep in C++ just the stuff that needs to be in C++, like dealing with hardware, C/C++-only libraries, CPU-heavy code.</p> <p>Have a look at <a href="http://cython.org/" rel="nofollow">Cython</a> for embedding C++ in Python. Cython is basically a compiler from Python-like language to a .c/.cpp file that "just" calls the Python C API, so it can be used from "normal" Python code, but can also call other C/C++ code.</p> <p><strong>Alternative:</strong> Implement an API in the C++ application and create a separate Python application that uses this API. By API I don't mean REST API, but something more low-level - RPC, ZeroMQ, plain sockets...</p>
0
2016-10-02T00:33:05Z
[ "python", "c++", "extending", "python-embedding" ]
How to test render_to_response in Pyramid Python
39,800,132
<p>I have a piece of code that calls Pyramid's render_to_response. I am not quite sure how to test that piece. In my test, the request object that is sent in is a DummyRequest by Pyramid. How can I capture <code>to_be_rendered</code>.</p> <pre><code>from pyramid.renderers import render_to_response def custom_adapter(response): data = { 'message': response.message } to_be_rendered = render_to_response(response.renderer, data) to_be_rendered.status_int = response.status_code return to_be_rendered </code></pre>
2
2016-09-30T21:08:25Z
39,812,289
<p>I believe <code>render_to_response</code> should return a <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/webob.html#response" rel="nofollow">response</a> object. You should be able to call <code>custom_adapter</code> directly in your unit test, providing a <code>DummyRequest</code> and make assertions on the <code>Response</code> object returned by your <code>custom_adapter</code></p> <pre><code>def test_custom_adapter(self): dummy = DummyRequest() # not sure of the object here response = custom_adapter(dummy) self.assertEqual(response.status, 200) </code></pre>
1
2016-10-01T23:05:41Z
[ "python", "unit-testing", "py.test" ]
Trying to use views in django like I use to used in python
39,800,209
<p>why it does not work ? It suppose to work, in python I can use this like this function, can any one explain me please ?</p> <p><strong>views:</strong></p> <pre><code>class MiVista(View): def get(self, request, var): self.var = 'Hello' # &lt;la logica de la vista&gt; return HttpResponse(self.var) one = MiVista() one.get(222222) </code></pre> <p><strong>urls:</strong></p> <pre><code>url(r'^indice/', MiVista.as_view()), </code></pre> <p>So the functions does not work like function in python using POO ?</p> <p>Thank you guys!</p>
0
2016-09-30T21:15:08Z
39,801,082
<p>So as @MadWombat mentioned, you are not passing enough arguments, so you need to pass <code>self</code>, which already passing by calling from instance objects, <code>request</code>(not passing), <code>var</code>(passing). And as you are not providing that you are passing <code>var=2222</code>, python thinks that <code>2222</code> is <code>request</code> argument.</p> <p>So basically you need to create <code>request</code> argument. You can do this with <a href="https://docs.djangoproject.com/en/1.10/topics/testing/advanced/#django.test.RequestFactory" rel="nofollow"><code>RequestFactory</code></a>. Like that</p> <pre><code>from django.test import RequestFactory from django.views.generic import View class MiVista(View): def get(self, request, var): self.var = var # &lt;la logica de la vista&gt; return HttpResponse(self.var) rf = RequestFactory() rf.get('indice/') one = MiVista.as_view()(rf, var='hello') </code></pre>
1
2016-09-30T22:41:44Z
[ "python", "django", "django-views" ]
Accumulate values of "neigborhood" from edgelist with numpy
39,800,223
<p>I have a undirected network where each node can be one of <strong>k</strong> types. For each node <em>i</em>, I need to calculate the number of neighbors that node <em>i</em> has of each type.</p> <p>Right now I am representing the edges with an edgelist where the columns are indexes of the nodes. The nodes are represented as a <strong>n x k</strong> matrix, where each column represents a node type. If a node is of type <em>k</em> then the <em>k</em>th column's value is 1, 0 otherwise.</p> <p>Here's my current code, which is correct, but too slow.</p> <pre><code># example nodes and edges, both typically much longer nodes = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]) edges = np.array([[0, 1], [1, 2]]) neighbors = np.zeros_like(nodes) for i, j in edges: neighbors[i] += nodes[j] neighbors[j] += nodes[i] </code></pre> <p>Is there some clever numpy that would allow me to avoid this for loop? If the best way to do this is with an adjacency matrix, that is also acceptable.</p>
4
2016-09-30T21:16:18Z
39,805,998
<p>If I understand your question correctly, the <a href="https://pypi.python.org/pypi/numpy-indexed" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) has a fast and elegant solution to this:</p> <pre><code># generate a random example graph n_edges = 50 n_nodes = 10 n_types = 3 edges = np.random.randint(0, n_nodes, size=(n_edges, 2)) node_types = np.random.randint(0, 2, size=(n_nodes, n_types)).astype(np.bool) # Note; this is for a directed graph s, e = edges.T # for undirected, add reversed edges s, e = np.concatenate([edges, edges[:,::-1]], axis=0).T import numpy_indexed as npi node_idx, neighbor_type_count = npi.group_by(s).sum(node_types[e]) </code></pre> <p>In general, operations on graphs, or algorithms involving jagged-arrays, can often be efficiently and elegantly expressed using grouping-operations.</p>
2
2016-10-01T11:22:43Z
[ "python", "numpy", "vectorization", "graph-algorithm", "numpy-broadcasting" ]
Accumulate values of "neigborhood" from edgelist with numpy
39,800,223
<p>I have a undirected network where each node can be one of <strong>k</strong> types. For each node <em>i</em>, I need to calculate the number of neighbors that node <em>i</em> has of each type.</p> <p>Right now I am representing the edges with an edgelist where the columns are indexes of the nodes. The nodes are represented as a <strong>n x k</strong> matrix, where each column represents a node type. If a node is of type <em>k</em> then the <em>k</em>th column's value is 1, 0 otherwise.</p> <p>Here's my current code, which is correct, but too slow.</p> <pre><code># example nodes and edges, both typically much longer nodes = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]]) edges = np.array([[0, 1], [1, 2]]) neighbors = np.zeros_like(nodes) for i, j in edges: neighbors[i] += nodes[j] neighbors[j] += nodes[i] </code></pre> <p>Is there some clever numpy that would allow me to avoid this for loop? If the best way to do this is with an adjacency matrix, that is also acceptable.</p>
4
2016-09-30T21:16:18Z
39,840,352
<p>You can simply use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.at.html" rel="nofollow"><code>np.add.at</code></a> -</p> <pre><code>out = np.zeros_like(nodes) np.add.at(out, edges[:,0],nodes[edges[:,1]]) np.add.at(out, edges[:,1],nodes[edges[:,0]]) </code></pre>
1
2016-10-03T21:00:37Z
[ "python", "numpy", "vectorization", "graph-algorithm", "numpy-broadcasting" ]
Can't access models from seperate: ImportError: no module named "HealthNet.ActivityLog"
39,800,229
<p>I've been working on a way to log the activity of a system for a school project in Python 3.4 and Django 1.9. I am currently trying to import a models.py file from my ActivityLog app into other applications in my HealthNet project to save the activity. The IDE I'm using (Pycharm), is telling me that my code is correct but I get the this error whenever I try to makemigrations/migrate/runserver:</p> <blockquote> <p>ImportError: No module named 'HealthNet.ActivityLog'</p> </blockquote> <p>Here is my file setup:</p> <pre><code>HealthNet ActivityLog Migrations __init__.py admin.py apps.py models.py tests.py views.py Appointments Migrations __init__.py admin.py apps.py models.py tests.py views.py HealthNet __init__.py settings.py urls.py wsgi.py </code></pre> <p>I'm trying to import models.py from ActivityLog into views.py from Appointments.</p> <p>Here's my code from models.py</p> <pre><code>from django.db import models class Log(models.Model): logTime = models.DateTimeField() logEvent = models.CharField(max_length=500) def __str__(self): return self.logEvent </code></pre> <p>This is the import statement from views.py in the Appointment package, which is the line that the error is tracing back to:</p> <pre><code>from HealthNet.ActivityLog.models import Log </code></pre> <p>And here is my list of installed apps in my settings.py file:</p> <pre><code>INSTALLED_APPS = [ 'Appointment.apps.AppointmentConfig', 'User.apps.UserConfig', 'ActivityLog.apps.ActivitylogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] </code></pre> <p>Thank you!</p>
0
2016-09-30T21:16:47Z
39,800,312
<pre><code>from ActivityLog.models import Log </code></pre> <p>'ActivityLog' and 'Appointments' are apps. So add 'ActivityLog' and 'Appointments' to INSTALLED_APPS in settings.py</p> <p>For eg: </p> <pre><code> INSTALLED_APPS = [ 'Appointment.apps.AppointmentConfig', 'User.apps.UserConfig', .......................... ......................... 'ActivityLog', 'Appointments', ] </code></pre> <p>Try this. It will work.</p>
1
2016-09-30T21:25:33Z
[ "python", "django" ]
Python: replace data frame values based on column name and conditional
39,800,232
<p>Let’s say we have a data frame with 6 columns. For a subset of 3 of those columns we want to change instances of 3 to 1. Can you suggest an elegant way to do so? Simply writing a line like:</p> <pre><code>df['A'][df.A == 3] = 1 </code></pre> <p>is inefficient in my real data as the dimensions are much larger (like changing 50 out of 200 variables). </p> <p>Perhaps we could work on this example:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,10,size=(100, 6)), columns=list('ABCDEF')) </code></pre> <p>Where we want to change values of 3 to 1 in columns A, B, and C. Thanks.</p>
2
2016-09-30T21:16:52Z
39,800,526
<p>You can loop through the subset of columns and use <code>loc</code> for assignment.</p> <pre><code>subset cols = ['A', 'B', 'C'] # For example. for col in subset_cols: df.loc[df[col] == 3, col] = 1 </code></pre>
0
2016-09-30T21:47:30Z
[ "python", "dataframe" ]
Python 2.7 calculating remainder with division and two inputs
39,800,282
<p>It's a question for my assignment in intro to programming and I'm not quite understanding how to do this without the use of Ifs because our prof just wants basic modulus and division. Im trying to get 3 outputs. balloons greater than children (which works), balloons equal to children which just outputs 0 and 0. and balloons less than children, which doesnt work.</p> <pre><code># number of balloons children = int(input("Enter number of balloons: ")) # number of children coming to the party balloons = int(input("Enter the number of children coming to the party: ")) # number of balloons each child will receive receive_balloons = int(balloons % children) # number of balloons leftover for decorations remaining = children % balloons print("{:s}""{:d}""{:s}""{:d}".format("Number of balloons for each child is ", receive_balloons, " and the amount leftover is ", remaining)) print(balloons, "", (remaining)) </code></pre>
0
2016-09-30T21:22:09Z
39,800,454
<p>You need to fix your variable assignment, you are assigning to the wrong variables and actually divide the numbers to get <code>receive_balloons</code> correctly:</p> <pre><code>balloons = int(input("Enter number of balloons: ")) children = int(input("Enter the number of children coming to the party: ")) receive_balloons = balloons // children remaining = balloons % children # Alternatively receive_balloons, remaining = divmod(balloons, children) print("Number of balloons for each child is {} and the amount leftover is {}".format(receive_balloons, remaining)) </code></pre> <p>Output (10/5):</p> <pre><code>Enter number of balloons: 10 Enter the number of children coming to the party: 5 Number of balloons for each child is 2 and the amount leftover is 0 </code></pre> <p>Output (10/8):</p> <pre><code>Enter number of balloons: 10 Enter the number of children coming to the party: 8 Number of balloons for each child is 1 and the amount leftover is 2 </code></pre> <p>Note: in Python2.7 you should use <code>raw_input</code>.</p>
1
2016-09-30T21:39:15Z
[ "python", "python-2.7", "modulus" ]
Python 2.7 calculating remainder with division and two inputs
39,800,282
<p>It's a question for my assignment in intro to programming and I'm not quite understanding how to do this without the use of Ifs because our prof just wants basic modulus and division. Im trying to get 3 outputs. balloons greater than children (which works), balloons equal to children which just outputs 0 and 0. and balloons less than children, which doesnt work.</p> <pre><code># number of balloons children = int(input("Enter number of balloons: ")) # number of children coming to the party balloons = int(input("Enter the number of children coming to the party: ")) # number of balloons each child will receive receive_balloons = int(balloons % children) # number of balloons leftover for decorations remaining = children % balloons print("{:s}""{:d}""{:s}""{:d}".format("Number of balloons for each child is ", receive_balloons, " and the amount leftover is ", remaining)) print(balloons, "", (remaining)) </code></pre>
0
2016-09-30T21:22:09Z
39,800,502
<p>You need to use the // operator for the number of balloons per child and % for remaining balloons</p> <pre><code># number of balloons balloons = int(input("Enter number of balloons: ")) # number of children coming to the party children = int(input("Enter the number of children coming to the party: ")) receive_balloons, remaining = (balloons // children, balloons % children) print("{:s}""{:d}""{:s}""{:d}".format("Number of balloons for each child is ", receive_balloons, " and the amount leftover is ", remaining)) print(balloons, "", (remaining)) </code></pre>
1
2016-09-30T21:44:18Z
[ "python", "python-2.7", "modulus" ]
python package import works locally, then blows up in cronjob
39,800,373
<p>running a cronjob I get the following error:</p> <pre><code>From cchilders@C02S21TWG8WMMBP.localdomain Fri Sep 30 15:58:00 2016 Return-Path: &lt;cchilders@C02S21TWG8WMMBP.localdomain&gt; X-Original-To: cchilders Delivered-To: cchilders@C02S21TWG8WMMBP.localdomain Received: by C02S21TWG8WMMBP.localdomain (Postfix, from userid 501) id D84CE1453D2; Fri, 30 Sep 2016 15:58:00 -0500 (CDT) From: cchilders@C02S21TWG8WMMBP.localdomain (Cron Daemon) To: cchilders@C02S21TWG8WMMBP.localdomain Subject: Cron &lt;cchilders@C02S21TWG8WMMBP&gt; /usr/local/bin/python ~/scripts/updates/update_files.py pull X-Cron-Env: &lt;SHELL=/bin/sh&gt; X-Cron-Env: &lt;PATH=/usr/bin:/bin&gt; X-Cron-Env: &lt;LOGNAME=cchilders&gt; X-Cron-Env: &lt;USER=cchilders&gt; X-Cron-Env: &lt;HOME=/Users/cchilders&gt; Message-Id: &lt;20160930205800.D84CE1453D2@C02S21TWG8WMMBP.localdomain&gt; Date: Fri, 30 Sep 2016 15:58:00 -0500 (CDT) Traceback (most recent call last): File "/Users/cchilders/scripts/updates/update_files.py", line 12, in &lt;module&gt; from ez_scrip_lib.updates import pull_system_file_from_scripts_project_and_update_it, push_system_file_to_scripts_project ImportError: No module named ez_scrip_lib.updates </code></pre> <p>But this library is definitely available:</p> <pre><code>In [1]: from ez_scrip_lib.updates import pull_system_file_from_scripts_project_and_update_it, push_system_file_to_scripts_project In [2]: </code></pre> <p>/scripts/updates/update_files.py:</p> <pre><code>#!/usr/bin/env python import sys from ez_scrip_lib.updates import pull_system_file_from_scripts_project_and_update_it, push_system_file_to_scripts_project files = [{'real_path': '.fake', 'repo_path': 'bash/fake-one'}, {'real_path': '.fake2', 'repo_path': 'bash/fake2'}, {'real_path': '.fake3', 'repo_path': 'bash/fake3'} ] callbacks = {'pull': pull_system_file_from_scripts_project_and_update_it, 'push': push_system_file_to_scripts_project} args = sys.argv purpose_arg = args[1] for f in files: callbacks[purpose_arg](**f) </code></pre> <p>Recently I changed the shebang to match, using <code>#!/usr/local/bin/python</code>, still doesn't work</p> <p>The way I find my package now is from my .bash_profile:</p> <pre><code>SCRIPTS="$HOME/scripts" export PYTHONPATH="${PYTHONPATH}:$SCRIPTS" </code></pre> <p>Scripts project:</p> <p>~/scripts/</p> <pre><code>__init__.py ~/scripts/__init__.py ~/scripts/ez_scrip_lib/__init__.py ~/scripts/ez_scrip_lib/updates.py ~/scripts/updates/update_files.py </code></pre> <p>My library <code>ez_scrip_lib</code> is also inside the scripts project, for convenience (I update all things in one editor at one time). It should probably be broken off, as it's very large, but not once have my scripts taken issue at finding things inside <code>ez_scrip_lib</code>. Only in this cronjob does it fail</p> <p>This script does work fine from command line ran like normal:</p> <pre><code>./scripts/updates/update_files.py pull </code></pre> <p>Removing the python interpreter from crontab since the script already has shebang (one SO suggestion) doesn't work either:</p> <pre><code>*/1 * * * * ~/scripts/updates/update_files.py pull </code></pre> <p>same error</p> <p>Cronjobs always seem to fail running python files for some reason, but at least on Mac I'm getting error logs automatically. How can I get this cronjob to find my package when it runs python script? Thank you</p>
0
2016-09-30T21:31:06Z
39,800,523
<p><code>Cron</code> doesn't know which directory is relative to your project, only what is relative to itself. It's likely looking for the modules in some place off in la-la land. A quick fix might be to specify the working directory of the script then try importing the modules:</p> <pre><code>os.chdir("/Users/cchilders/scripts/updates") </code></pre> <p>Or something along those lines should get things back in order...</p>
1
2016-09-30T21:47:08Z
[ "python", "bash", "osx", "unix", "crontab" ]
Accesing laptop camera with openCV
39,800,435
<p>I run the following code, according this page - <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html" rel="nofollow">http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html</a></p> <pre><code>cap = cv2.VideoCapture(0) print cap.read() print cap.open() cap.release() </code></pre> <p>the results I get are:</p> <p>(False, None)</p> <p>TypeError: Required argument 'device' (pos 1) not found</p> <p>I use jupyter notebook, python 2.7, openCV 2.4. </p> <p>How can I get the openCV to work with the cam?</p>
0
2016-09-30T21:37:29Z
39,802,980
<p>For OpenCV 2.4, use the following code:</p> <pre><code>import cv2 import cv cap = cv2.VideoCapture(0) while True: ret,img=cap.read() cv2.imshow('Video', img) if(cv2.waitKey(10) &amp; 0xFF == ord('b')): break </code></pre> <p>If you still can't get the camera input, replace VideoCapture(0) with VideoCapture(1). The issue could be because of a 3rd party camera driver installed on your machine.</p> <p>If that doesn't work either, try VideoCapture("path/to/saved_video"). If you have entered the filePath correctly, and your openCV configuration has no issues, you should get saved video frames. This would imply that you need to check the camera drivers </p>
0
2016-10-01T04:18:50Z
[ "python", "opencv" ]
Code that generates a random 10 digit filename and creates the file
39,800,513
<p>I tried using:</p> <pre><code>import random filenamemaker = random.randint(1,1000) </code></pre> <p>all help would be great thanks :)</p>
2
2016-09-30T21:45:22Z
39,800,572
<p>The simplest way would be with <a href="https://docs.python.org/3/library/string.html#string.digits" rel="nofollow"><code>string.digits</code></a> and <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow"><code>random.sample</code></a>. You could also use the <a href="https://docs.python.org/3/reference/compound_stmts.html#with" rel="nofollow"><code>with</code></a> statement with an empty <a href="https://docs.python.org/3/reference/simple_stmts.html#grammar-token-pass_stmt" rel="nofollow"><code>pass</code></a> in it if don't plan on using the file and automatically want it closed:</p> <pre><code>from string import digits from random import sample with open("".join(sample(digits, 10)), 'w'): pass </code></pre> <p>This is equivalent to:</p> <pre><code>filename = "".join(sample(digits, 10)) f = open(filename, 'w') f.close() </code></pre> <p>On consecutive calls, this generates filenames such as:</p> <pre><code>3672945108 6298517034 </code></pre>
3
2016-09-30T21:52:04Z
[ "python", "python-3.x", "random" ]
Code that generates a random 10 digit filename and creates the file
39,800,513
<p>I tried using:</p> <pre><code>import random filenamemaker = random.randint(1,1000) </code></pre> <p>all help would be great thanks :)</p>
2
2016-09-30T21:45:22Z
39,800,579
<pre><code>import random filename = "" for i in range(10): filename += str(random.randint(0,9)) f = open(filename + ".txt", "w") </code></pre>
0
2016-09-30T21:52:33Z
[ "python", "python-3.x", "random" ]
Code that generates a random 10 digit filename and creates the file
39,800,513
<p>I tried using:</p> <pre><code>import random filenamemaker = random.randint(1,1000) </code></pre> <p>all help would be great thanks :)</p>
2
2016-09-30T21:45:22Z
39,800,588
<p><code>randint</code> takes two arguments: a lower and upper (inclusive) bound for the generated number. Your code will generate a number between 1 and 1000 (inclusive), which could be anywhere from 1 to 4 digits.</p> <p>This will generate a number between 1 and 9999999999:</p> <pre><code>&gt;&gt;&gt; n = random.randint(1, 9999999999) </code></pre> <p>You will then want to pad it with zero's and make it a string, in case it is less than 10 digits:</p> <pre><code>&gt;&gt;&gt; filename = str(n).zfill(10) </code></pre> <p>You can then open this and write to it:</p> <pre><code>with open(filename + '.txt', 'w') as f: # do stuff pass </code></pre>
0
2016-09-30T21:53:28Z
[ "python", "python-3.x", "random" ]
Stacked Lines in Pandas
39,800,620
<p>I want to draw stacked lines in <code>pandas Dataframe</code>. So, currently I draw one line:</p> <pre><code>df.plot.line(x='xvals',y='yvals') </code></pre> <p>in which <code>xvals</code> column contains <code>x</code> values, and <code>yvals</code> contains <code>y</code> values. </p> <p>How can I add another line in the same graph?</p>
2
2016-09-30T21:56:42Z
39,800,902
<p>Keep the returned <code>Axes</code> object and pass to <code>ax</code> argument:</p> <pre><code>ax = df.plot.line(x='xvals',y='yvals') df.plot.line(x='xvals2',y='yvals2', ax=ax) </code></pre>
2
2016-09-30T22:22:32Z
[ "python", "pandas", "dataframe" ]
&pound; displaying in urllib2 and Beautiful Soup
39,800,624
<p>I'm trying to write a small web scraper in python, and I think I've run into an encoding issue. I'm trying to scrape <a href="http://www.resident-music.com/tickets" rel="nofollow">http://www.resident-music.com/tickets</a> (specifically the table on the page) - a row might look something like this -</p> <pre><code> &lt;tr&gt; &lt;td style="width:64.9%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;the great escape 2017&amp;nbsp; local early bird tickets, selling fast&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:13.1%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;18&lt;sup&gt;th&lt;/sup&gt;&amp;ndash; 20&lt;sup&gt;th&lt;/sup&gt; may&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:15.42%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;various&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:6.58%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;&amp;pound;55.00&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>I'm essentially trying to replace the <code>&amp;pound;55.00</code> with £55, and any other 'non-text' nasties.</p> <p>I've tried a few different encoding things you can go with beautifulsoup, and urllib2 - to no avail, I think I'm just doing it all wrong.</p> <p>Thanks</p>
2
2016-09-30T21:57:18Z
39,800,910
<p>I used <code>requests</code> for this but hopefully you can do that using <code>urllib2</code> also. So here is the code:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import requests from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(requests.get('your_url').text) chart = soup.findAll(name='tr') print str(chart).replace('&amp;pound;',unichr(163)) #replace '&amp;pound;' with '£' </code></pre> <p>Now you should take the expected output!</p> <p>Sample output:</p> <pre><code>... &lt;strong&gt;£71.50&lt;/strong&gt;&lt;/p&gt; ... </code></pre> <p>Anyway about the parsing you can do it with many ways, what was interesting here is: <code>print str(chart).replace('&amp;pound;',unichr(163))</code> which was quite challenging :)</p> <blockquote> <p>Update</p> </blockquote> <p>If you want to escape more than one (or even one) characters (like dashes,pounds etc...), it would be easier/more efficient for you to use a <code>parser</code> as in Padraic's answer. Sometimes as you will also read in the comments they handle and other encoding issues. </p>
1
2016-09-30T22:23:22Z
[ "python", "encoding", "beautifulsoup", "urllib2" ]
&pound; displaying in urllib2 and Beautiful Soup
39,800,624
<p>I'm trying to write a small web scraper in python, and I think I've run into an encoding issue. I'm trying to scrape <a href="http://www.resident-music.com/tickets" rel="nofollow">http://www.resident-music.com/tickets</a> (specifically the table on the page) - a row might look something like this -</p> <pre><code> &lt;tr&gt; &lt;td style="width:64.9%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;the great escape 2017&amp;nbsp; local early bird tickets, selling fast&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:13.1%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;18&lt;sup&gt;th&lt;/sup&gt;&amp;ndash; 20&lt;sup&gt;th&lt;/sup&gt; may&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:15.42%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;various&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:6.58%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;&amp;pound;55.00&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>I'm essentially trying to replace the <code>&amp;pound;55.00</code> with £55, and any other 'non-text' nasties.</p> <p>I've tried a few different encoding things you can go with beautifulsoup, and urllib2 - to no avail, I think I'm just doing it all wrong.</p> <p>Thanks</p>
2
2016-09-30T21:57:18Z
39,801,638
<p>You want to <em>unescape</em> the html which you can do using <em>html.unescape</em> in python3:</p> <pre><code>In [14]: from html import unescape In [15]: h = """&lt;tr&gt; ....: &lt;td style="width:64.9%;height:11px;"&gt; ....: &lt;p&gt;&lt;strong&gt;the great escape 2017&amp;nbsp; local early bird tickets, selling fast&lt;/strong&gt;&lt;/p&gt; ....: &lt;/td&gt; ....: &lt;td style="width:13.1%;height:11px;"&gt; ....: &lt;p&gt;&lt;strong&gt;18&lt;sup&gt;th&lt;/sup&gt;&amp;ndash; 20&lt;sup&gt;th&lt;/sup&gt; may&lt;/strong&gt;&lt;/p&gt; ....: &lt;/td&gt; ....: &lt;td style="width:15.42%;height:11px;"&gt; ....: &lt;p&gt;&lt;strong&gt;various&lt;/strong&gt;&lt;/p&gt; ....: &lt;/td&gt; ....: &lt;td style="width:6.58%;height:11px;"&gt; ....: &lt;p&gt;&lt;strong&gt;&amp;pound;55.00&lt;/strong&gt;&lt;/p&gt; ....: &lt;/td&gt; ....: &lt;/tr&gt;""" In [16]: In [16]: print(unescape(h)) &lt;tr&gt; &lt;td style="width:64.9%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;the great escape 2017  local early bird tickets, selling fast&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:13.1%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;18&lt;sup&gt;th&lt;/sup&gt;– 20&lt;sup&gt;th&lt;/sup&gt; may&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:15.42%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;various&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:6.58%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;£55.00&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>For python2 use:</p> <pre><code>In [6]: from html.parser import HTMLParser In [7]: unescape = HTMLParser().unescape In [8]: print(unescape(h)) &lt;tr&gt; &lt;td style="width:64.9%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;the great escape 2017  local early bird tickets, selling fast&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:13.1%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;18&lt;sup&gt;th&lt;/sup&gt;– 20&lt;sup&gt;th&lt;/sup&gt; may&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:15.42%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;various&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; &lt;td style="width:6.58%;height:11px;"&gt; &lt;p&gt;&lt;strong&gt;£55.00&lt;/strong&gt;&lt;/p&gt; &lt;/td&gt; </code></pre> <p>You can see both correctly unescape all entities not just the pound sign.</p>
2
2016-10-01T00:01:49Z
[ "python", "encoding", "beautifulsoup", "urllib2" ]
Exception Class Failed to Import
39,800,625
<p>I have two files. One is <code>program_utils.py</code> with the contents:</p> <pre><code>class SomeException(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) </code></pre> <p>another, say, <code>program.py</code>, with </p> <pre><code>import program_utils def SomeFunction(arg): if arg in set([ok_val1, ok_val2]): # do something else: raise SomeException('reason') </code></pre> <p>When I run <code>program.py</code> it complains: <code>NameError: name 'MyException' is not defined</code>. When I paste the contents of <code>program_utils.py</code> directly into <code>program.py</code>, it works fine. Why?</p>
0
2016-09-30T21:57:18Z
39,800,715
<p>Unlike <code>#include</code> in <code>C</code>/<code>C++</code>, in python the <code>import</code> statement is not equivalent to copy/pasting the file into your file.</p> <p>If you want that behavior, you can sort of get it by doing:</p> <pre><code>from program_utils import * </code></pre> <p>However, there are some caveats. e.g.: if you are importing a package, the <code>__all__</code> variable in the <code>__init__.py</code> controls which symbols get imported whtin doing <code>from foo import *</code>.</p> <p>In general, <code>from foo import *</code> is not a very good practice. You don't necessarily know what symbols you are importing. Additionally you may overwrite the value of some symbols if you do that with more than one module and they both define the same symbol(s).</p> <p>Arguably it is also somewhat more clear what is going on if you use the module name when using its symbols. i.e.:</p> <pre><code>foo.bar() </code></pre> <p>vs</p> <pre><code>from foo import * ... from spam import * bar() </code></pre> <p>In the second case it might not be obvious that <code>bar</code> came from the foo module.</p> <p>There is a (small) performance consideration. If you end up doing <code>foo.bar()</code> a lot, you are actually doing an unnecessary dictionary lookup because every time, the interpreter looks up <code>'bar'</code> in <code>foo.__dict__</code>. To fix that, you can do:</p> <pre><code>from foo import bar </code></pre>
2
2016-09-30T22:04:43Z
[ "python", "exception", "python-import" ]
Python: TypeError: 'int' object is not callable. Most likely a easy fix. cant seem to fiture out how to fix it
39,800,654
<p>here is the a section of the code.</p> <pre><code>import math length_centre=eval(input("Enter length from centre to corner of pentagon: ")) side_length= 2*length_centre*(math.sin(math.pi/5)) print(side_length) areaP =(5((side_length)**2))/(4*((math.tan)((math.pi)/5))) print(areaP) </code></pre> <p>error for the code:</p> <p>areaP =(5((4)**2))/(4*((math.tan)((math.pi)/5))) TypeError: 'int' object is not callable</p>
2
2016-09-30T21:59:16Z
39,800,701
<p>Programming languages don't have implicit multiplication like written math, so <code>5((side_length)**2)</code> is not legal, it's trying to call <code>5</code> as a function with argument <code>side_length ** 2</code>. I'm guessing you want <code>5 * side_length**2</code> (removing some extraneous parens that aren't needed since exponentiation binds more tightly than other math ops anyway).</p> <p>Cleaning it all up, you'd have:</p> <pre><code>import math # Use float to get the specific type you want, rather than executing whatever # code the user types. If this is Py2, change input to raw_input too, # because Py2's input is equivalent to wrapping raw_input in eval already length_centre=float(input("Enter length from centre to corner of pentagon: ")) # Strip a whole bunch of unnecessary parens side_length = 2 * length_centre * math.sin(math.pi / 5) print(side_length) # Strip a whole bunch of unnecessary parens (left in some technically unnecessary parens # because they group the complex operands for the division visually) areaP = (5 * side_length**2) / (4 * math.tan(math.pi / 5)) print(areaP) </code></pre>
3
2016-09-30T22:03:59Z
[ "python", "int" ]
comment python code in visual studio code
39,800,665
<p>My visual studio code comment python code with <code>'''</code> instead of using <code>#</code> when try to comment a block of code with the key combination <code>ctrl + shift + a</code>. I have ubuntu 16.04</p>
0
2016-09-30T21:59:51Z
39,801,177
<p>This has nothing specifically to to with Visual Studio, but a result of the python commenting styles. Generally, single line comments are done with the pound (or hash) symbol:</p> <pre><code># This is a comment </code></pre> <p>In contrast, three quotation marks (either ''' or """) can be used to easily produce multi-line comments.</p> <pre><code>''' This is also a comment. However, this comment crosses multiple lines ''' </code></pre> <p>or</p> <pre><code>""" This is yet another multiline comment For long comments the quotation marks are much easier than # comments. """ </code></pre> <p>Hope this helps.</p>
2
2016-09-30T22:53:36Z
[ "python", "vscode" ]
How to change date format and add a day to the date
39,800,751
<p>I have a date format that looks like this: 2016-08-30 and need to transform it to yyyy,mm,dd, as well as add a day. The purpose is to get a quandl format for days.</p> <pre><code>i = datetime.strptime(i,'%Y-%m-%d').strftime('%Y,%-m,%d') print i j = dt.datetime(i) + dt.timedelta(1) </code></pre> <p>This is the code I have. It tells me that I need to have an int in the dt.datetime function, but when I make it an int by doing dt.datetime(int(i)), I get this error.</p> <pre><code>ValueError: invalid literal for int() with base 10: '2016,8,30' </code></pre> <p>Thanks</p>
0
2016-09-30T22:08:39Z
39,800,775
<p>You can use <code>timedelta</code> to add a day and use <code>strftime</code> to format the date string.</p> <pre><code>import datetime dt = datetime.datetime.strptime('2016-01-23', '%Y-%m-%d') dt = dt + datetime.timedelta(days=1) print dt.strftime('%Y,%m,%d') </code></pre>
0
2016-09-30T22:10:43Z
[ "python", "datetime", "date-formatting", "timedelta" ]
Adding a sorted tuple to a dictionary as a key
39,800,762
<p>I am very new to Python and i am trying my best to learn Python. I have been trying to implement a community detection algorithm that i came across and i would really appreciate if i could get help from anyone here. </p> <p>I have a <strong>defaultdict(list)</strong>, my input, which looks like : </p> <pre><code>input = [('B', ['D']), ('D', ['E']), ('F', ['E']), ('G', ['D', 'F'])] </code></pre> <p>Here, <strong>'B', 'D', 'E'</strong> etc represent nodes in a tree. The <strong>key</strong> in the dictionary represents <strong>children</strong> nodes and the <strong>value</strong> represents <strong>parent</strong> nodes. So in the above input, 'B' is a child of 'D', 'D' is a child of 'E' etc.</p> <p>I am trying to create a dictionary with <strong>tuples</strong>(in sorted order) as <strong>keys</strong> and <strong>int</strong> as <strong>values</strong>. The expected output is: </p> <pre><code>output = [(('A', 'B'), 1.0), (('B', 'C'), 1.0), (('B', 'D'), 3.0), (('D', 'E'), 4.5), (('D', 'G'), 0.5), (('E', 'F'), 1.5), (('F', 'G'), 0.5)] </code></pre> <p>In the above output, the key is a tuple which represents an edge in the input. For ex : ('A' , 'B') represents an edge between A and B and the int value is something that i calculate.</p> <p>I would love to know know how this can be done.</p> <p>I have tried the following:</p> <p>1)</p> <pre><code>edges = [] for node,parents in input.items(): for p in sorted(parents): tup = (node,p) tup = sorted(tup) edges.append(tup) /*output of the above line: [['E', 'F'], ['D', 'E'], ['A', 'B'], ['B', 'C'], ['B', 'D'], ['D', 'G'], ['F', 'G']]*/ </code></pre> <p>And then i thought i will pull values from this list to a dict. Obviously, i got a dict with <strong>key</strong> of type <strong>List</strong> and further the items in list were not sorted.</p> <p>2) </p> <pre><code>edges = {} for node,parents in node2parents.items(): for p in sorted(parents): t = (node,p) t = sorted(t) edges[t] = 0 </code></pre> <p>On executing the above, i got a <strong>TypeError: unhashable type: 'list'</strong></p> <p>I have tried few other ways, but none proved to be successful. It would be great if someone could help me learn how i could do this.</p> <p>PS : I would have posted evidences of more "failed" efforts of mine, but i dint want to waste your time by making you go through all the stupid ways i have been trying to accomplish my goals. Also, i googled and tried if i could find an answer to my question. Though there were countless possible solutions, i still failed to implement the logic successfully. I am honestly trying to learn Python and it would be great if you could push me in the right direction.</p>
0
2016-09-30T22:09:28Z
39,800,796
<p><a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow"><code>sorted</code> returns a new sorted <code>list</code></a>, regardless of the input's type. If you want the result to be a sorted <code>tuple</code>, just wrap the <code>sorted</code> call in the <code>tuple</code> constructor:</p> <pre><code>t = tuple(sorted(t)) </code></pre> <p>For Python built-in types, only immutable types (e.g. <code>int</code>, <code>str</code>, or <code>tuple</code>s and <code>frozenset</code>s containing only other immutable types) are suitable for use as keys in <code>dict</code>s and values in <code>set</code>/<code>frozenset</code>s, which is why preserving the <code>tuple</code> type is important; <code>list</code> is mutable, and to avoid a sticky situation where a mutable object like a <code>list</code> is added to a <code>dict</code>, then changed (so suddenly the hash and equality comparisons for it don't correspond to where it was bucketed), rendering it unfindable and violating the <code>dict</code> assumptions, they prohibit using mutable built-in types completely.</p>
2
2016-09-30T22:12:42Z
[ "python", "dictionary", "tuples", "defaultdict" ]
Email logging with Python Django
39,800,772
<p>Django does support email log handlers.</p> <p>But this way, if some error is repeated often, we risk to be mail-bombed by ERROR emails.</p> <p>How to send us emails on errors but not too often?</p> <p>Any other solutions?</p>
1
2016-09-30T22:10:32Z
39,806,260
<p>Use a <code>BufferingSMTPHandler</code> as described in <a href="https://gist.github.com/1379446" rel="nofollow">this Gist</a>. You can adapt the described class to your needs.</p>
1
2016-10-01T11:47:33Z
[ "python", "django", "logging" ]