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
sequencelengths
1
5
Web scrapping table with hidden part using python
40,119,941
<p>I´m trying to get the information from this table:</p> <pre><code>&lt;table class="table4 table4-1 table4-1-1"&gt;&lt;thead&gt;&lt;tr&gt;&lt;th class="estilo1"&gt;No&lt;/th&gt;&lt;th class="estilo2"&gt;Si&lt;/th&gt;&lt;!-- &lt;th&gt;&lt;div class="contenedor-vinculos6"&gt;&lt;a title="Ver más " class="vinculo-interrogacion" href="#"&gt;Más información&lt;/a&gt;&lt;/div&gt;&lt;/th&gt;--&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="estilo1"&gt;&lt;span class="estilo3"&gt;100%&lt;span class="numero-voto"&gt;(15)&lt;/span&gt;&lt;/span&gt;&lt;div class="grafica1 grafica1-desacuerdo"&gt;&lt;div class="item-grafica" style="width: 100%;"/&gt;&lt;/div&gt;&lt;/div&gt;&lt;/td&gt;&lt;td class="estilo2"&gt;&lt;span class="estilo3"&gt;0%&lt;span class="numero-voto"&gt;(0)&lt;/span&gt;&lt;/span&gt;&lt;div class="grafica1 grafica1-deacuerdo"&gt;&lt;div class="item-grafica" style="width: 0%;"/&gt;&lt;/div&gt;&lt;/div&gt;&lt;/td&gt;&lt;td&gt;&lt;span class="display-none"&gt;Más información&lt;/span&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt; </code></pre> <p>I´m doing the following in python3:</p> <pre><code>req = Request('http://www.congresovisible.org/votaciones/10918/',headers=headers) web_page = urlopen(req) soup = BeautifulSoup(web_page.read(), 'html.parser') table= soup.find_all('table', attrs={'class':'table4 table4-1 table4-1-1'}) </code></pre> <p>This works but only shows part of the table, it excludes everything after: </p> <pre><code>&lt;td class="estilo2"&gt;&lt;span class="estilo3...) </code></pre> <p>This is the output </p> <pre><code>[&lt;table class="table4 table4-1 table4-1-1"&gt;&lt;thead&gt;&lt;tr&gt;&lt;th class="estilo1"&gt;No&lt;/th&gt;&lt;th class="estilo2"&gt;Si&lt;/th&gt;&lt;!-- &lt;th&gt;&lt;div class="contenedor-vinculos6"&gt;&lt;a title="Ver más " class="vinculo-interrogacion" href="#"&gt;Más información&lt;/a&gt;&lt;/div&gt;&lt;/th&gt;--&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;&lt;tr&gt;&lt;td class="estilo1"&gt;&lt;span class="estilo3"&gt;100%&lt;span class="numero-voto"&gt;(15)&lt;/span&gt;&lt;/span&gt;&lt;div class="grafica1 grafica1-desacuerdo"&gt;&lt;div class="item-grafica" style="width: 100%;"&gt;&lt;/div&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;] </code></pre> <p>How could I extract the whole table? </p>
1
2016-10-18T23:59:07Z
40,119,988
<p>It is actually quite easy to solve. <code>html.parser</code> does not parse this kind of non-well-formed HTML well. Use a <em>more lenient</em> <code>html5lib</code> instead. This works for me:</p> <pre><code>import requests from bs4 import BeautifulSoup response = requests.get('http://www.congresovisible.org/votaciones/10918/') soup = BeautifulSoup(response.content, 'html5lib') table = soup.find_all('table', attrs={'class':'table4 table4-1 table4-1-1'}) print(table) </code></pre> <p>Note that this requires <code>html5lib</code> package to be installed:</p> <pre><code>pip install --upgrade html5lib </code></pre> <hr> <p>By the way, <code>lxml</code> parser works as well:</p> <pre><code>soup = BeautifulSoup(response.content, 'lxml') </code></pre>
1
2016-10-19T00:04:23Z
[ "python", "web-scraping", "beautifulsoup", "html-table" ]
UnicodeEncodeError: 'ascii' codec can't encode characters in position 26-27: ordinal not in range(128)
40,120,027
<p>I'm running a job that runs a python script collecting Facebook events data from Facebook Graph API and printing out information about the events using Heroku Scheduler. Since it is an automated job that runs daily at a specific time in the cloud, the printing to screen will be logged into Heroku logs when that job starts running in the cloud by Heroku Scheduler.</p> <p>The weird thing is, I have no problem when I run the python script manually by executing a heroku run command, but when it is run by the Heroku Scheduler automatically in the cloud and logging the printing, there is an encoding error.</p> <p>The relevant python script with the error is as follows:</p> <pre><code>def importFromPages(): sources = sources_collection.find( projection= { 'id' : 1, 'source' : 1, 'name' : 1, '_id' : 0 } ) headers = { 'Content-Type' : 'application/json' } params = { 'fields' : 'id, name, cover, start_time, end_time, place', 'access_token' : FB_ACCESS_TOKEN } for source in sources: print(source['name']) data = requests.get( 'https://graph.facebook.com/v2.7/{}/events'.format(source['id']), params=params, headers=headers ) if data.status_code == 200: data = json.loads(data.text) data = data['data'] if len(data) == 0: continue for event in data: now = arrow.now().timestamp end = arrow.get(event.get('end_time', None)).timestamp if end != None: if end &lt;= now: continue print(event['id']) event['host'] = source events_collection.update( { 'id' : event['id'] }, { '$set' : event }, upsert=True ) else: print('data.status_code != 200') </code></pre> <p>The heroku logs that showed the encoding error when the job is scheduled to run is here:</p> <pre><code>2016-10-18T12:31:34.270891+00:00 app[scheduler.1368]: UNSW Bitfwd 2016-10-18T12:31:34.411757+00:00 app[scheduler.1368]: IGA UNSW 2016-10-18T12:31:34.531127+00:00 app[scheduler.1368]: UNSW Barbell Club 2016-10-18T12:31:34.721310+00:00 app[scheduler.1368]: 660525034113560 2016-10-18T12:31:34.724900+00:00 app[scheduler.1368]: Circusoc - The UNSW Circus Society 2016-10-18T12:31:34.947553+00:00 app[scheduler.1368]: UNSW Medical Music Society 2016-10-18T12:31:35.140233+00:00 app[scheduler.1368]: 1166082866820866 2016-10-18T12:31:35.145683+00:00 app[scheduler.1368]: MODsoc Ministry of Dance UNSW 2016-10-18T12:31:35.370460+00:00 app[scheduler.1368]: Arc at UNSW Art &amp; Design 2016-10-18T12:31:35.616661+00:00 app[scheduler.1368]: 1145482732204348 2016-10-18T12:31:35.622455+00:00 app[scheduler.1368]: Accounting Society Of UNSW (AccSoc) 2016-10-18T12:31:35.815662+00:00 app[scheduler.1368]: 1375370362476567 2016-10-18T12:31:35.817958+00:00 app[scheduler.1368]: 1679765869019301 2016-10-18T12:31:35.821599+00:00 app[scheduler.1368]: Traceback (most recent call last): 2016-10-18T12:31:35.821601+00:00 app[scheduler.1368]: File "data.py", line 127, in &lt;module&gt; 2016-10-18T12:31:35.821652+00:00 app[scheduler.1368]: main() 2016-10-18T12:31:35.821655+00:00 app[scheduler.1368]: File "data.py", line 124, in main 2016-10-18T12:31:35.821709+00:00 app[scheduler.1368]: importFromPages() 2016-10-18T12:31:35.821711+00:00 app[scheduler.1368]: File "data.py", line 92, in importFromPages 2016-10-18T12:31:35.821715+00:00 app[scheduler.1368]: print(source['name']) 2016-10-18T12:31:35.821745+00:00 app[scheduler.1368]: UnicodeEncodeError: 'ascii' codec can't encode characters in position 26-27: ordinal not in range(128) 2016-10-18T12:31:36.333406+00:00 heroku[scheduler.1368]: Process exited with status 1 2016-10-18T12:31:36.337350+00:00 heroku[scheduler.1368]: State changed from up to complete </code></pre> <p>When I run the job manually using heroku run as follows, there is no encoding print error and the job is able to complete without any errors:</p> <pre><code>heroku run python data.py Running python data.py on ⬢ eventobotdatacollector... up, run.4056 (Free) </code></pre> <p>Does anyone have an idea what is the problem here and why the different environments caused the error?</p>
0
2016-10-19T00:10:07Z
40,120,162
<p>I don't know about the influences of the different environments. But I was able to solve a similar problem by explicity unicode-encoding the data I wanted to print out (or write to a file, for that matter). Try</p> <pre><code>print(source['name'].encode('utf-8')) </code></pre> <p>or have a look here, for a more complete and knowledgeable explanation of unicode issues in Python: <a href="http://stackoverflow.com/questions/2392732/sqlite-python-unicode-and-non-utf-data">SQLite, python, unicode, and non-utf data</a></p> <p>Hope this helps. Regards,</p>
2
2016-10-19T00:28:58Z
[ "python", "facebook", "heroku", "encoding" ]
Command function for button "resets"
40,120,031
<p>So in my tkinter python program I am calling on a command when a button is clicked. When that happens it runs a function but in the function I have it set a label to something on the first time the button is clicked and after that it should only update the said label. Basically after the attempt it changes the attempt to 1 ensuring the if statement will see that and not allow it to pass. However it keeps resetting and I don't know how to stop it. When you click the button no matter first or third the button resets and proof of that occurs because the h gets printed. It's as if the function restarts but it shouldn't since it's a loop for the GUI.</p> <pre><code>def fight(): #Sees which one is stronger if user is stronger he gets win if no he gets loss also displays enemy stats and removes used characters after round is finished try: attempt=0 namel = "" namer="" left = lbox.curselection()[0] right = rbox.curselection()[0] totalleft = 0 totalright = 0 if left == 0: namel = "Rash" totalleft = Rash.total elif left==1: namel = "Untss" totalleft = Untss.total elif left==2: namel = "Illora" totalleft = 60+35+80 if right == 0: namer = "Zys" totalright = Zys.total elif right==1: namer = "Eentha" totalright = Eentha.total elif right==2: namer = "Dant" totalright = Dant.total lbox.delete(lbox.curselection()[0]) rbox.delete(rbox.curselection()[0]) print(namel) print(namer) if attempt == 0: wins.set("Wins") loss.set("Loss") print("h") attempt=1 if (totalleft&gt;totalright): wins.set(wins.get()+"\n"+namel) loss.set(loss.get()+"\n"+namer) else: wins.set(wins.get()+"\n"+namer) loss.set(loss.get()+"\n"+namel) except IndexError: pass </code></pre> <p>Also for those of you who saw my previous question I still need help with that I just also want to fix this bug too. </p>
0
2016-10-19T00:11:06Z
40,120,192
<p>At beginning of function <code>fight</code> you set <code>attempt = 0</code> so you reset it. </p> <p>Besides <code>attempt</code> is local variable. It is created when you execute function <code>fight</code> and it is deleted when you leave function <code>fight</code>. You have to use global variable (or global <code>IntVar</code>)</p> <pre><code>attempt = 0 def fight(): global attempt </code></pre> <p>BTW: of you use only values <code>0</code>/<code>1</code> in <code>attempt</code> then you can use <code>True</code>/<code>False</code>. </p> <pre><code>attempt = False def fight(): global attempt ... if not attempt: attempt = True </code></pre>
1
2016-10-19T00:33:13Z
[ "python", "tkinter" ]
Python How can i read text file like dictionary
40,120,085
<p>I hava a text file like this :</p> <pre><code>"imei": "123456789", "sim_no": "+90 xxx xxx xx xx", "device_type": "standart", "hw_version": "1.01", "sw_version": "1.02" </code></pre> <p>and i want read this file like dictionary. I mean, when i write imei it should give me 123456789. I'm creating free dictionary and i'm reading this file but its reading like string.</p> <pre><code>file=open("test.txt","r") buffer={} print(type(buffer)) buffer=file.read() print(type(buffer)) &lt;class 'dict'&gt; &lt;class 'str'&gt; </code></pre> <p>EDIT : Problem is solved.</p> <pre><code>import json with open("test.txt") as f: mydict = json.loads('{{ {} }}'.format(f.read())) </code></pre>
0
2016-10-19T00:19:20Z
40,120,113
<p>I think you can check this <a href="http://stackoverflow.com/questions/4803999/python-file-to-dictionary">post</a>, and you can change the splitting word to ":" .</p> <p>Hopefully it helps!</p>
-1
2016-10-19T00:24:15Z
[ "python", "python-3.x" ]
Python How can i read text file like dictionary
40,120,085
<p>I hava a text file like this :</p> <pre><code>"imei": "123456789", "sim_no": "+90 xxx xxx xx xx", "device_type": "standart", "hw_version": "1.01", "sw_version": "1.02" </code></pre> <p>and i want read this file like dictionary. I mean, when i write imei it should give me 123456789. I'm creating free dictionary and i'm reading this file but its reading like string.</p> <pre><code>file=open("test.txt","r") buffer={} print(type(buffer)) buffer=file.read() print(type(buffer)) &lt;class 'dict'&gt; &lt;class 'str'&gt; </code></pre> <p>EDIT : Problem is solved.</p> <pre><code>import json with open("test.txt") as f: mydict = json.loads('{{ {} }}'.format(f.read())) </code></pre>
0
2016-10-19T00:19:20Z
40,121,329
<p>I tried to come up with a more elegant solution that doesn't use regular expressions, but everything I came up with is far more verbose, so try this:</p> <pre><code>import re d = {} with open('test.txt') as f: for line in f: k, v = re.findall(r'"(.+?)"', line) d[k] = v print(d) </code></pre> <p><code>re.findall(r'\"(.+?)\"', line)</code> will return all the matches where text is within quotes on each line, and assign the first match to <code>k</code> and the second to <code>v</code>. These are then used as keys and values in a dictionary <code>d</code>. Assuming that the format of your text file is constant, this should give you the result you are looking for.</p> <p>Note that the order of the dictionary will likely be different than your text file, but that shouldn't matter since it is a dictionary.</p>
1
2016-10-19T02:56:03Z
[ "python", "python-3.x" ]
Python How can i read text file like dictionary
40,120,085
<p>I hava a text file like this :</p> <pre><code>"imei": "123456789", "sim_no": "+90 xxx xxx xx xx", "device_type": "standart", "hw_version": "1.01", "sw_version": "1.02" </code></pre> <p>and i want read this file like dictionary. I mean, when i write imei it should give me 123456789. I'm creating free dictionary and i'm reading this file but its reading like string.</p> <pre><code>file=open("test.txt","r") buffer={} print(type(buffer)) buffer=file.read() print(type(buffer)) &lt;class 'dict'&gt; &lt;class 'str'&gt; </code></pre> <p>EDIT : Problem is solved.</p> <pre><code>import json with open("test.txt") as f: mydict = json.loads('{{ {} }}'.format(f.read())) </code></pre>
0
2016-10-19T00:19:20Z
40,121,626
<p>Use the <code>json</code> module; you've already got legal JSON aside from missing the outer curly braces:</p> <pre><code>import json with open("test.txt") as f: mydict = json.loads('{{ {} }}'.format(f.read())) </code></pre>
2
2016-10-19T03:29:17Z
[ "python", "python-3.x" ]
Remove the square brackets? (Newbie)
40,120,103
<p>I am new to Python and I have somehow ended up with two lists of lists, each of which contains a single integer (float in y below), as follows:</p> <pre><code>&gt;x array([[11], [101], [1001], [10001], [100001]], dtype=object) &gt;y array([[0.0], [0.0009751319885253906], [0.03459000587463379], [3.7970290184020996], [498.934268951416]], dtype=object) </code></pre> <p>All I wish to do is to plot x vs y, but this clearly won't work, probably for a number of reasons, but at least because each 'value' is in square brackets (i.e. a list in itself). How could I have prevented these values (e.g. 11, 101, 1001, 10001) from becoming lists?</p> <p>Being from a Fortran background, I am struggling greatly with Python's lists, tuples, arrays, numpy arrays, etc. All I wish to do is to read from a text file whose contents are (say):</p> <p>11 0.0</p> <p>101 0.0009751319885253906</p> <p>1001 0.03459000587463379</p> <p>10001 3.7970290184020996</p> <p>100001 498.934268951416</p> <p>and to read the first 'column' as x and the second 'column' as y, with the aim of plotting this data.</p> <p>Can anyone please recommend an online course which clarifies the use of lists, tuples, arrays, etc for this kind of thing?</p> <p>Many thanks in advance.</p> <p>EDIT: In response to people's comments and suggestions, I am including my code used, the input file content and the interactive window output at the end of the run.</p> <p>Many thanks to everyone who has responded to me; I have found all comments and suggestions to be very helpful. I shall act on all of these responses and try to figure things out for myself, but I would appreciate it if anyone could take a look at my code, 'input file' contents and interactive window 'output' to see if they can help me further. Again, I really appreciate the time and effort people have put in to communicate with me about this.</p> <p>Here is the code:</p> <pre><code>import re import numpy as np import time import pandas as pd def dict2mat(res1, res2): # # input 2 dictionaries and return the content of the first as x # and the content of the second as y # s = pd.Series(res1) x = s.values s = pd.Series(res2) y = s.values return x, y f = open('results.txt', 'r') nnp = {} tgen = {} tconn = {} tcalc = {} tfill = {} iline = 0 for i in range(1000): line = f.readline() if "Example" in line: # # first line of text having numerical values of interest contains # the string 'Example' # iline = iline+1 # # extract number of nodes (integer) # nnp[iline] = [int(s) for s in re.findall(r"\d+", line)] line = f.readline() # # extract time taken to generate data set (float) # tgen[iline] = [float(s) for s in re.findall(r"\d+[\.]\d+", line)] line = f.readline() # # extract time taken to generate connectivity data (float) # tconn[iline] = [float(s) for s in re.findall(r"\d+[\.]\d+", line)] line = f.readline() # # extract time taken to calculate error (float) for corners # tcalc[iline] = [float(s) for s in re.findall(r"\d+[\.]\d+", line)] line = f.readline() # # extract time taken to fill in stress results at midsides (float) # tfill[iline] = [float(s) for s in re.findall(r"\d+[\.]\d+", line)] # # use function dict2mat to replace the contents of 'number of nodes' # and each of the 'times' in turn by vectors x and y # xgen, ygen = dict2mat(nnp, tgen) xconn, yconn = dict2mat(nnp, tconn) xcalc, ycalc = dict2mat(nnp, tcalc) xfill, yfill = dict2mat(nnp, tfill) # get x and y vectors x = np.array(xgen) y = np.array(ygen) print('x: ') print(x) print('y: ') print(y) </code></pre> <p>Here is the content of the file which the code reads from:</p> <pre><code>Random seed used to form data = 9001 Example has 11 generated global surface nodes Time taken to generate the data: --- 0.002001047134399414 seconds --- Time taken to find connectivity: --- 0.0 seconds --- Time taken to calculate Stress Error for corner nodes only: --- 0.0004999637603759766 seconds --- Time taken to fill-in midside node Stress Errors: --- 0.0 seconds --- Random seed used to form data = 9001 Example has 101 generated global surface nodes Time taken to generate the data: --- 0.01451420783996582 seconds --- Time taken to find connectivity: --- 0.0 seconds --- Time taken to calculate Stress Error for corner nodes only: --- 0.004984855651855469 seconds --- Time taken to fill-in midside node Stress Errors: --- 0.0009751319885253906 seconds --- Random seed used to form data = 9001 Example has 1001 generated global surface nodes Time taken to generate the data: --- 0.10301804542541504 seconds --- Time taken to find connectivity: --- 0.0 seconds --- Time taken to calculate Stress Error for corner nodes only: --- 0.04008197784423828 seconds --- Time taken to fill-in midside node Stress Errors: --- 0.03459000587463379 seconds --- Random seed used to form data = 9001 Example has 10001 generated global surface nodes Time taken to generate the data: --- 1.0397570133209229 seconds --- Time taken to find connectivity: --- 0.0 seconds --- Time taken to calculate Stress Error for corner nodes only: --- 0.41377687454223633 seconds --- Time taken to fill-in midside node Stress Errors: --- 3.7970290184020996 seconds --- Random seed used to form data = 9001 Example has 100001 generated global surface nodes Time taken to generate the data: --- 10.153867959976196 seconds --- Time taken to find connectivity: --- 0.0 seconds --- Time taken to calculate Stress Error for corner nodes only: --- 3.938124895095825 seconds --- Time taken to fill-in midside node Stress Errors: --- 498.934268951416 seconds --- </code></pre> <p>Finally, this is what appears in the interactive window after execution:</p> <pre><code>x: &gt;&gt;&gt; print(x) [[11] [101] [1001] [10001] [100001]] &gt;&gt;&gt; print('y: ') y: &gt;&gt;&gt; print(y) [[0.002001047134399414] [0.01451420783996582] [0.10301804542541504] [1.0397570133209229] [10.153867959976196]] &gt;&gt;&gt; </code></pre> <p>I hope this all helps and I thank anyone in advance for any help they are able to provide.</p> <p>Simon.</p>
0
2016-10-19T00:22:26Z
40,120,271
<p>If you want a single list, you can use this:</p> <pre><code>x = [[11], [101], [1001], [10001], [100001]] newList = [item for list2 in x for item in list2] </code></pre> <p>Assume <code>list2</code> are the lists inside <code>x</code>.</p> <p>So:</p> <pre><code>newList = [11, 101, 1001, 10001, 100001] </code></pre> <p>However, if the main insterest is to avoid sublists, perhaps you'll need to share the code you used in order to see complete input.</p>
0
2016-10-19T00:43:06Z
[ "python", "arrays", "plot", "data-fitting" ]
Remove the square brackets? (Newbie)
40,120,103
<p>I am new to Python and I have somehow ended up with two lists of lists, each of which contains a single integer (float in y below), as follows:</p> <pre><code>&gt;x array([[11], [101], [1001], [10001], [100001]], dtype=object) &gt;y array([[0.0], [0.0009751319885253906], [0.03459000587463379], [3.7970290184020996], [498.934268951416]], dtype=object) </code></pre> <p>All I wish to do is to plot x vs y, but this clearly won't work, probably for a number of reasons, but at least because each 'value' is in square brackets (i.e. a list in itself). How could I have prevented these values (e.g. 11, 101, 1001, 10001) from becoming lists?</p> <p>Being from a Fortran background, I am struggling greatly with Python's lists, tuples, arrays, numpy arrays, etc. All I wish to do is to read from a text file whose contents are (say):</p> <p>11 0.0</p> <p>101 0.0009751319885253906</p> <p>1001 0.03459000587463379</p> <p>10001 3.7970290184020996</p> <p>100001 498.934268951416</p> <p>and to read the first 'column' as x and the second 'column' as y, with the aim of plotting this data.</p> <p>Can anyone please recommend an online course which clarifies the use of lists, tuples, arrays, etc for this kind of thing?</p> <p>Many thanks in advance.</p> <p>EDIT: In response to people's comments and suggestions, I am including my code used, the input file content and the interactive window output at the end of the run.</p> <p>Many thanks to everyone who has responded to me; I have found all comments and suggestions to be very helpful. I shall act on all of these responses and try to figure things out for myself, but I would appreciate it if anyone could take a look at my code, 'input file' contents and interactive window 'output' to see if they can help me further. Again, I really appreciate the time and effort people have put in to communicate with me about this.</p> <p>Here is the code:</p> <pre><code>import re import numpy as np import time import pandas as pd def dict2mat(res1, res2): # # input 2 dictionaries and return the content of the first as x # and the content of the second as y # s = pd.Series(res1) x = s.values s = pd.Series(res2) y = s.values return x, y f = open('results.txt', 'r') nnp = {} tgen = {} tconn = {} tcalc = {} tfill = {} iline = 0 for i in range(1000): line = f.readline() if "Example" in line: # # first line of text having numerical values of interest contains # the string 'Example' # iline = iline+1 # # extract number of nodes (integer) # nnp[iline] = [int(s) for s in re.findall(r"\d+", line)] line = f.readline() # # extract time taken to generate data set (float) # tgen[iline] = [float(s) for s in re.findall(r"\d+[\.]\d+", line)] line = f.readline() # # extract time taken to generate connectivity data (float) # tconn[iline] = [float(s) for s in re.findall(r"\d+[\.]\d+", line)] line = f.readline() # # extract time taken to calculate error (float) for corners # tcalc[iline] = [float(s) for s in re.findall(r"\d+[\.]\d+", line)] line = f.readline() # # extract time taken to fill in stress results at midsides (float) # tfill[iline] = [float(s) for s in re.findall(r"\d+[\.]\d+", line)] # # use function dict2mat to replace the contents of 'number of nodes' # and each of the 'times' in turn by vectors x and y # xgen, ygen = dict2mat(nnp, tgen) xconn, yconn = dict2mat(nnp, tconn) xcalc, ycalc = dict2mat(nnp, tcalc) xfill, yfill = dict2mat(nnp, tfill) # get x and y vectors x = np.array(xgen) y = np.array(ygen) print('x: ') print(x) print('y: ') print(y) </code></pre> <p>Here is the content of the file which the code reads from:</p> <pre><code>Random seed used to form data = 9001 Example has 11 generated global surface nodes Time taken to generate the data: --- 0.002001047134399414 seconds --- Time taken to find connectivity: --- 0.0 seconds --- Time taken to calculate Stress Error for corner nodes only: --- 0.0004999637603759766 seconds --- Time taken to fill-in midside node Stress Errors: --- 0.0 seconds --- Random seed used to form data = 9001 Example has 101 generated global surface nodes Time taken to generate the data: --- 0.01451420783996582 seconds --- Time taken to find connectivity: --- 0.0 seconds --- Time taken to calculate Stress Error for corner nodes only: --- 0.004984855651855469 seconds --- Time taken to fill-in midside node Stress Errors: --- 0.0009751319885253906 seconds --- Random seed used to form data = 9001 Example has 1001 generated global surface nodes Time taken to generate the data: --- 0.10301804542541504 seconds --- Time taken to find connectivity: --- 0.0 seconds --- Time taken to calculate Stress Error for corner nodes only: --- 0.04008197784423828 seconds --- Time taken to fill-in midside node Stress Errors: --- 0.03459000587463379 seconds --- Random seed used to form data = 9001 Example has 10001 generated global surface nodes Time taken to generate the data: --- 1.0397570133209229 seconds --- Time taken to find connectivity: --- 0.0 seconds --- Time taken to calculate Stress Error for corner nodes only: --- 0.41377687454223633 seconds --- Time taken to fill-in midside node Stress Errors: --- 3.7970290184020996 seconds --- Random seed used to form data = 9001 Example has 100001 generated global surface nodes Time taken to generate the data: --- 10.153867959976196 seconds --- Time taken to find connectivity: --- 0.0 seconds --- Time taken to calculate Stress Error for corner nodes only: --- 3.938124895095825 seconds --- Time taken to fill-in midside node Stress Errors: --- 498.934268951416 seconds --- </code></pre> <p>Finally, this is what appears in the interactive window after execution:</p> <pre><code>x: &gt;&gt;&gt; print(x) [[11] [101] [1001] [10001] [100001]] &gt;&gt;&gt; print('y: ') y: &gt;&gt;&gt; print(y) [[0.002001047134399414] [0.01451420783996582] [0.10301804542541504] [1.0397570133209229] [10.153867959976196]] &gt;&gt;&gt; </code></pre> <p>I hope this all helps and I thank anyone in advance for any help they are able to provide.</p> <p>Simon.</p>
0
2016-10-19T00:22:26Z
40,120,405
<p>Without getting into the code behind reading from a file, you'll first want to setup your program with a list of tuples.</p> <pre><code>#Example empty list points = [] #x,y = (1, 2) assigns 1 to x and 2 to y x,y = (1, 2) #this appends the tuple (x, y) into the points list points.append((x, y)) </code></pre> <p>If you have a file that you want to pull the coordinates in from try some code like this:</p> <pre><code>#Example empty list points = [] filename = "myfile.txt" file_with_points = open(filename, "r") for line in file_with_points.readlines(): #assume the points are separated by a space splitline = line.split(" ") x, y = splitline[0], splitline[1] points.append((x, y)) file_with_points.close() print points </code></pre> <p>Hopefully this solution helped you work with lists. If you need more info on really basic python check out <a href="https://www.codecademy.com/learn/python" rel="nofollow">https://www.codecademy.com/learn/python</a></p>
1
2016-10-19T00:59:20Z
[ "python", "arrays", "plot", "data-fitting" ]
How to skip to a line via character seeking in Python
40,120,122
<p>If I have a text file that has a bunch of random text before I get to the stuff I actually want, how do I move the file pointer there? </p> <p>Say for example my text file looks like this:</p> <pre><code>#foeijfoijeoijoijfoiej ijfoiejoi jfeoijfoifj i jfoei joi jo ijf eoij oie jojf #feoijfoiejf ioj oij oi jo ij i joi jo ij oij #### oijroijf 3## # o #foeijfoiej i jo i iojf 3 ## #io joi joij oi j## io joi joi j3# 3i ojoi joij # The stuff I care about </code></pre> <p>(The hashtags are a part of the actual text file)</p> <p>How do I move the file pointer to the line of stuff I care about, and then how would I get python to tell me the number of the line, and start the reading of the file there?</p> <p>I've tried doing a loop to find the line that the last hashtag is in, and then reading from there, but I still need to get rid of the hashtag, and need the line number.</p>
0
2016-10-19T00:25:13Z
40,120,531
<p>Try using the <a href="https://docs.python.org/3/library/io.html#io.IOBase.readlines" rel="nofollow">readlines</a> function. This will return a list containing each line. You can use a <code>for</code> loop to parse through each line, searching for what you need, then obtain the number of the line via its index in the list. For instance:</p> <pre><code>with open('some_file_path.txt') as f: contents = f.readlines() object = '#the line I am looking for' for line in contents: if object in line: line_num = contents.index(object) </code></pre> <p>To get rid of the pound sign, just use the <a href="https://docs.python.org/3/library/stdtypes.html?highlight=replace#str.replace" rel="nofollow">replace</a> function. Eg. <code>new_line = line.replace('#','')</code></p>
0
2016-10-19T01:16:36Z
[ "python", "loops", "text" ]
How to skip to a line via character seeking in Python
40,120,122
<p>If I have a text file that has a bunch of random text before I get to the stuff I actually want, how do I move the file pointer there? </p> <p>Say for example my text file looks like this:</p> <pre><code>#foeijfoijeoijoijfoiej ijfoiejoi jfeoijfoifj i jfoei joi jo ijf eoij oie jojf #feoijfoiejf ioj oij oi jo ij i joi jo ij oij #### oijroijf 3## # o #foeijfoiej i jo i iojf 3 ## #io joi joij oi j## io joi joi j3# 3i ojoi joij # The stuff I care about </code></pre> <p>(The hashtags are a part of the actual text file)</p> <p>How do I move the file pointer to the line of stuff I care about, and then how would I get python to tell me the number of the line, and start the reading of the file there?</p> <p>I've tried doing a loop to find the line that the last hashtag is in, and then reading from there, but I still need to get rid of the hashtag, and need the line number.</p>
0
2016-10-19T00:25:13Z
40,120,773
<p>You can't seek to it directly without knowing the size of the junk data or scanning through the junk data. But it's not too hard to wrap the file in <a href="https://docs.python.org/3/library/itertools.html#itertools.dropwhile" rel="nofollow"><code>itertools.dropwhile</code></a> to discard lines until you see the "good" data, after which it iterates through all remaining lines:</p> <pre><code>import itertools # Or def a regular function that returns True until you see the line # delimiting the beginning of the "good" data not_good = '# The stuff I care about\n'.__ne__ with open(filename) as f: for line in itertools.dropwhile(not_good, f): ... You'll iterate the lines at and after the good line ... </code></pre> <p>If you actually need the file descriptor positioned appropriately, not just the lines, this variant should work:</p> <pre><code>import io with open(filename) as f: # Get first good line good_start = next(itertools.dropwhile(not_good, f)) # Seek back to undo the read of the first good line: f.seek(-len(good_start), io.SEEK_CUR) # f is now positioned at the beginning of the line that begins the good data </code></pre> <p>You can tweak this to get the actual line number if you really need it (rather than just needing the offset). It's a little less readable though, so explicit iteration via <code>enumerate</code> may make more sense if you need to do it (left as exercise). The way to make Python work for you is:</p> <pre><code>from future_builtins import map # Py2 only from operator import itemgetter with open(filename) as f: linectr = itertools.count() # Get first good line # Pair each line with a 0-up number to advance the count generator, but # strip it immediately so not_good only processes lines, not line nums good_start = next(itertools.dropwhile(not_good, map(itemgetter(0), zip(f, linectr)))) good_lineno = next(linectr) # Keeps the 1-up line number by advancing once # Seek back to undo the read of the first good line: f.seek(-len(good_start), io.SEEK_CUR) # f is now positioned at the beginning of the line that begins the good data </code></pre>
0
2016-10-19T01:50:47Z
[ "python", "loops", "text" ]
Python Eve - How to filter by datetime value
40,120,147
<p>How can I return items filtered by date or date interval? I was trying something like this based on the filtering example from eve's <a href="http://python-eve.org/features.html#filtering" rel="nofollow">documentation</a>:</p> <pre><code>/records/?where={"date": {"$gte": "2016-10-17"}} </code></pre> <p>I was thinking this python syntax could work too by checking this comment in eve's request parsing <a href="https://github.com/nicolaiarocci/eve/blob/develop/eve/io/mongo/parser.py#L21-L23" rel="nofollow">code</a>:</p> <pre><code>/records/?where=date==datetime('2016-10-16') </code></pre> <p>But the result is 500 internal error, maybe the syntax is wrong. I'm having a hard time getting it right. </p> <p>Thanks.</p>
1
2016-10-19T00:27:24Z
40,124,222
<p>Try this:</p> <pre><code>/records?where={"date": {"$gt": "Mon, 17 Oct 2016 03:00:00 GMT"}} </code></pre> <p>It uses the <code>DATE_FORMAT</code> setting which defaults to RFC1123.</p>
1
2016-10-19T06:54:36Z
[ "python", "mongodb", "eve" ]
Find function in Python 3.x
40,120,151
<p>When we have the following: </p> <pre><code>tweet2 = 'Want cheap snacks? Visit @cssu office in BA2283' </code></pre> <p><code>print(tweet2[tweet2.find('cheap')])</code> results in the output <code>'c'</code> and I cant wrap my head around how it does this. I tried the visualizer and it didn't show anything. Could anyone please explain?</p>
0
2016-10-19T00:27:37Z
40,120,197
<p><code>tweet2.find('cheap')</code> returns the index at which the beginning of "cheap" is found, and when that index is used in <code>tweet2[index]</code>, it returns the character at that index, which is "c"</p>
2
2016-10-19T00:34:14Z
[ "python", "python-3.x" ]
Find function in Python 3.x
40,120,151
<p>When we have the following: </p> <pre><code>tweet2 = 'Want cheap snacks? Visit @cssu office in BA2283' </code></pre> <p><code>print(tweet2[tweet2.find('cheap')])</code> results in the output <code>'c'</code> and I cant wrap my head around how it does this. I tried the visualizer and it didn't show anything. Could anyone please explain?</p>
0
2016-10-19T00:27:37Z
40,120,201
<p>You should consider reading python documentation on string methods and lists </p> <pre><code># define string variable tweet2 tweet2 = 'Want cheap snacks? Visit @cssu office in BA2283' # find position of substring 'cheap', which is 5 (strings has 0-based indices in python n = tweet2.find('cheap') # print 5th element of string, which is 'c' print(tweet2[n]) </code></pre>
0
2016-10-19T00:34:31Z
[ "python", "python-3.x" ]
Find function in Python 3.x
40,120,151
<p>When we have the following: </p> <pre><code>tweet2 = 'Want cheap snacks? Visit @cssu office in BA2283' </code></pre> <p><code>print(tweet2[tweet2.find('cheap')])</code> results in the output <code>'c'</code> and I cant wrap my head around how it does this. I tried the visualizer and it didn't show anything. Could anyone please explain?</p>
0
2016-10-19T00:27:37Z
40,120,204
<p><code>find</code> returns an index, not a slice.</p> <p>If you want the full string you can get it like so:</p> <pre><code>to_find = 'cheap' ind = tweet2.find(to_find) print(tweet2[ind:ind+len(to_find)]) </code></pre>
0
2016-10-19T00:35:09Z
[ "python", "python-3.x" ]
Find function in Python 3.x
40,120,151
<p>When we have the following: </p> <pre><code>tweet2 = 'Want cheap snacks? Visit @cssu office in BA2283' </code></pre> <p><code>print(tweet2[tweet2.find('cheap')])</code> results in the output <code>'c'</code> and I cant wrap my head around how it does this. I tried the visualizer and it didn't show anything. Could anyone please explain?</p>
0
2016-10-19T00:27:37Z
40,120,217
<p>It's because the find(str, string) method determines if str occurs in string, or in a substring of string and returns the position of first occurrence. So when you call <code>tweet2.find('cheap')</code> it will return the <strong>position</strong> that is the first occurs of cheap.</p>
0
2016-10-19T00:36:33Z
[ "python", "python-3.x" ]
Python runs the commented-out code
40,120,210
<p>I have a problem that sometimes <code>docker-py</code> returns an error:</p> <pre><code>Permission denied. </code></pre> <p>I'm trying to fix it. I commented out the piece of code, and received the following picture.</p> <pre><code>File "/opt/dst/src/utils/runner.py", line 48, in run_code \#if len(cli.containers(filters={'status': ['running', 'created']})) &gt;= settings.DOCKER_CONTAINER_COUNT: </code></pre> <pre class="lang-html prettyprint-override"><code>Traceback (most recent call last): File "/opt/dst/env/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/opt/dst/env/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/opt/dst/src/core/tasks.py", line 12, in run return 'Solution not found' File "/opt/dst/src/utils/runner.py", line 48, in run_code #if len(cli.containers(filters={'status': ['running', 'created']})) &gt;= settings.DOCKER_CONTAINER_COUNT: File "/opt/dst/env/lib/python2.7/site-packages/docker/api/container.py", line 85, in containers res = self._result(self._get(u, params=params), True) File "/opt/dst/env/lib/python2.7/site-packages/docker/utils/decorators.py", line 47, in inner return f(self, *args, **kwargs) File "/opt/dst/env/lib/python2.7/site-packages/docker/client.py", line 132, in _get return self.get(url, **self._set_request_timeout(kwargs)) File "/opt/dst/env/lib/python2.7/site-packages/requests/sessions.py", line 487, in get return self.request('GET', url, **kwargs) File "/opt/dst/env/lib/python2.7/site-packages/requests/sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "/opt/dst/env/lib/python2.7/site-packages/requests/sessions.py", line 585, in send r = adapter.send(request, **kwargs) File "/opt/dst/env/lib/python2.7/site-packages/requests/adapters.py", line 453, in send raise ConnectionError(err, request=request) ConnectionError: ('Connection aborted.', error(13, 'Permission denied')) </code></pre> <p>The runner.pyc file is updated. What could be the problem? Thank you for your help and sorry for my bad english</p> <p>UPDATE:</p> <pre><code>cli = Client('unix://var/run/docker.sock', version='1.19') kill_client = Client('unix://var/run/docker.sock', version='1.19', timeout=0.5) config = cli.create_host_config(**get_host_config(file_path)) #if len(cli.containers(filters={'status': ['running', 'created']})) &gt;= settings.DOCKER_CONTAINER_COUNT: # return 'must retry', None run_string = 'timeout {} python /tmp/script.py'.format(settings.DOCKER_EXECUTE_TIME) container = cli.create_container('python:2', run_string, user=uid, host_config=config) </code></pre>
-2
2016-10-19T00:36:05Z
40,142,703
<p>Due to an error in the script, worked two instance celery and this error occurred during the operation instance, who has worked with the old code.</p>
0
2016-10-19T22:44:31Z
[ "python", "django", "docker", "celery" ]
Efficient way to select most recent index with finite value in column from Pandas DataFrame?
40,120,299
<p>I'm trying to find the most recent index with a value that is not 'NaN' relative to the current index. So, say I have a DataFrame with 'NaN' values like this:</p> <pre><code> A B C 0 2.1 5.3 4.7 1 5.1 4.6 NaN 2 5.0 NaN NaN 3 7.4 NaN NaN 4 3.5 NaN NaN 5 5.2 1.0 NaN 6 5.0 6.9 5.4 7 7.4 NaN NaN 8 3.5 NaN 5.8 </code></pre> <p>If I am currently at index 4, I have the values:</p> <pre><code> A B C 4 3.5 NaN NaN </code></pre> <p>I want to know the last known value of 'B' relative to index 4, which is at index <code>1</code>:</p> <pre><code> A B C 1 5.1 -&gt; 4.6 NaN </code></pre> <p>I know I can get a list of all indexes with NaN values using something like:</p> <pre><code>indexes = df.index[df['B'].apply(np.isnan)] </code></pre> <p>But this seems inefficient in a large database. Is there a way to <code>tail</code> just the last one relative to the current index?</p>
4
2016-10-19T00:46:19Z
40,120,457
<p>You may try something like this, convert the <code>index</code> to a series that have the same <code>NaN</code> values as column <code>B</code> and then use <code>ffill()</code> which carries the last non missing index forward for all subsequent <code>NaN</code>s:</p> <pre><code>import pandas as pd import numpy as np df['Last_index_notnull'] = df.index.to_series().where(df.B.notnull(), np.nan).ffill() df['Last_value_notnull'] = df.B.ffill() df </code></pre> <p><a href="https://i.stack.imgur.com/b7p1B.png"><img src="https://i.stack.imgur.com/b7p1B.png" alt="enter image description here"></a></p> <p>Now at index <code>4</code>, you know the last non missing value is <code>4.6</code> and index is <code>1</code>.</p>
5
2016-10-19T01:06:28Z
[ "python", "pandas", "numpy", "dataframe" ]
Efficient way to select most recent index with finite value in column from Pandas DataFrame?
40,120,299
<p>I'm trying to find the most recent index with a value that is not 'NaN' relative to the current index. So, say I have a DataFrame with 'NaN' values like this:</p> <pre><code> A B C 0 2.1 5.3 4.7 1 5.1 4.6 NaN 2 5.0 NaN NaN 3 7.4 NaN NaN 4 3.5 NaN NaN 5 5.2 1.0 NaN 6 5.0 6.9 5.4 7 7.4 NaN NaN 8 3.5 NaN 5.8 </code></pre> <p>If I am currently at index 4, I have the values:</p> <pre><code> A B C 4 3.5 NaN NaN </code></pre> <p>I want to know the last known value of 'B' relative to index 4, which is at index <code>1</code>:</p> <pre><code> A B C 1 5.1 -&gt; 4.6 NaN </code></pre> <p>I know I can get a list of all indexes with NaN values using something like:</p> <pre><code>indexes = df.index[df['B'].apply(np.isnan)] </code></pre> <p>But this seems inefficient in a large database. Is there a way to <code>tail</code> just the last one relative to the current index?</p>
4
2016-10-19T00:46:19Z
40,121,467
<p>some useful methods to know</p> <p><strong><em><code>last_valid_index</code></em></strong><br> <strong><em><code>first_valid_index</code></em></strong><br> for columns <code>B</code> as of index <code>4</code></p> <pre><code>df.B.ix[:4].last_valid_index() 1 </code></pre> <p>you can use this for all columns in this way</p> <pre><code>pd.concat([df.ix[:i].apply(pd.Series.last_valid_index) for i in df.index], axis=1).T </code></pre> <p><a href="https://i.stack.imgur.com/CNBgf.png" rel="nofollow"><img src="https://i.stack.imgur.com/CNBgf.png" alt="enter image description here"></a></p>
4
2016-10-19T03:09:42Z
[ "python", "pandas", "numpy", "dataframe" ]
Python Argparse: how to make an argument required if and only if one flag is given?
40,120,379
<p>I am wondering how can I make one argument required when one flag is given, and optional when that flag is not given?</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument('-c', '--convert', action = 'store_true') parser.add_argument('-l', '--lookup', action = 'store_true') parser.add_argument('name', type = str) args = parser.parse_args() if args.name: print(args.name) if args.convert: print ("convert now!") </code></pre> <p>For example, in the codes above, I want <code>name</code> to be required, only when <code>-c</code> is given. When I run the program only with <code>-l</code>, then there is an error:</p> <pre><code>$ python3 test.py -l usage: test.py [-h] [-c] [-l] name test.py: error: the following arguments are required: name </code></pre> <p>I have tried to use argument group to divide the arguments into two groups 1. <code>-c</code> and <code>name</code>; 2. <code>-l</code>, but it didn't really work.</p> <p>Any suggestions are appreciated!</p>
0
2016-10-19T00:55:49Z
40,120,570
<p>This isn't something <code>argparse</code> can enforce on its own. What you can do is define <code>name</code> to be optional, then check after parsing if your constraint is met.</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument('-c', '--convert', action='store_true') parser.add_argument('-l', '--lookup', action='store_true') parser.add_argument('name', nargs='?') args = parser.parse_args() # If args.name must be a non-empty string when given, # you can use 'not args.name' in place of 'args.name is None' if args.convert and args.name is None: parser.error("&lt;name&gt; required with --convert") if args.name: print(args.name) if args.convert: print ("convert now!") </code></pre>
2
2016-10-19T01:22:53Z
[ "python", "python-3.x", "arguments", "argparse" ]
Python Argparse: how to make an argument required if and only if one flag is given?
40,120,379
<p>I am wondering how can I make one argument required when one flag is given, and optional when that flag is not given?</p> <pre><code>import argparse parser = argparse.ArgumentParser() parser.add_argument('-c', '--convert', action = 'store_true') parser.add_argument('-l', '--lookup', action = 'store_true') parser.add_argument('name', type = str) args = parser.parse_args() if args.name: print(args.name) if args.convert: print ("convert now!") </code></pre> <p>For example, in the codes above, I want <code>name</code> to be required, only when <code>-c</code> is given. When I run the program only with <code>-l</code>, then there is an error:</p> <pre><code>$ python3 test.py -l usage: test.py [-h] [-c] [-l] name test.py: error: the following arguments are required: name </code></pre> <p>I have tried to use argument group to divide the arguments into two groups 1. <code>-c</code> and <code>name</code>; 2. <code>-l</code>, but it didn't really work.</p> <p>Any suggestions are appreciated!</p>
0
2016-10-19T00:55:49Z
40,120,611
<p>There isn't anything in <code>argparse</code> to do this directly; but it can be approximated in various ways</p> <pre><code>parser.add_argument('-c', '--convert', action = 'store_true') parser.add_argument('-l', '--lookup', action = 'store_true') parser.add_argument('name', nargs='?', default='good default') </code></pre> <p>It's not required in either case, but in the case of <code>-c</code> you could either use the <code>good default</code>, or you can complain after parsing.</p> <pre><code>parser.add_argument('-c', '--convert') parser.add_argument('-l', '--lookup', nargs='?', default='adefault', const='aconst') </code></pre> <p>In this case, <code>-c</code> expects an argument, your required <code>name</code>. An argument is optional for <code>-l</code>. If no <code>-l</code>, the value is the <code>default</code>; if <code>-l</code> without the argument, the value is the <code>const</code>. You could even put <code>-c</code> and <code>-l</code> in a mutually exclusive group.</p> <p>There isn't a mechanism for requiring several arguments to go together (i.e. no 'mutually-required-group`). However subparsers work along that line. Do I need to illustrate how subparsers could be use here?</p> <p>Custom Actions classes can be used to force some sort of interaction between arguments, but usually it's easier to implement that sort of thing after parsing. Remember <code>argparse</code> allows you give arguments in any order. Thus the <code>name</code> positional could occur before <code>-c</code>, or after, or between <code>-l</code> and <code>-c</code> etc.</p>
1
2016-10-19T01:28:48Z
[ "python", "python-3.x", "arguments", "argparse" ]
error in code involving while loop and removing items from string
40,120,390
<p>I have a code that downloads tweets and I am trying to sort through it labeling it as positive or negative each time i label a tweet I want to remove it from the string so I won't be asked to label it again here is my code so far</p> <pre><code>while True: if len(tweet_list) == 0: break else: tweet1= (np.random.choice(tweet_list)) print tweet1 judge = input("1 pos, 2 neg 3 skip: ") if judge == 1: tweet_pos.append(tweet1) tweet_list.remove(tweet1) if judge == 2: tweet_neg.append(tweet1) tweet_list.remove(tweet1) </code></pre> <p>after I label the second tweet I am given this error</p> <pre><code>ValueError: list.remove(x): x not in list </code></pre>
0
2016-10-19T00:57:09Z
40,120,511
<p>You could do something like:</p> <pre><code>newList = [] for myLetter in myList: if myLetter is not 'x': newList.append(myLetter) newString = ''.join(newList) </code></pre>
0
2016-10-19T01:13:54Z
[ "python", "string", "while-loop", "tweepy" ]
error in code involving while loop and removing items from string
40,120,390
<p>I have a code that downloads tweets and I am trying to sort through it labeling it as positive or negative each time i label a tweet I want to remove it from the string so I won't be asked to label it again here is my code so far</p> <pre><code>while True: if len(tweet_list) == 0: break else: tweet1= (np.random.choice(tweet_list)) print tweet1 judge = input("1 pos, 2 neg 3 skip: ") if judge == 1: tweet_pos.append(tweet1) tweet_list.remove(tweet1) if judge == 2: tweet_neg.append(tweet1) tweet_list.remove(tweet1) </code></pre> <p>after I label the second tweet I am given this error</p> <pre><code>ValueError: list.remove(x): x not in list </code></pre>
0
2016-10-19T00:57:09Z
40,120,881
<p>Make an empty list outside out of your while loop like this:</p> <pre><code>tweet_pos = [] tweet_neg = [] alreadySeen = [] </code></pre> <p>Revise your first <code>if</code> statement in your code like so:</p> <pre><code>if len(alreadySeen) == 20: break </code></pre> <p>Make sure when you're displaying the tweets, you want to use <code>tweet1.text</code>. Sometimes it doesn't encode the message properly, or at all, so you can use <code>tweet1.text.encode('utf-8')</code>. Then each time you make a judgment, add that tweet to the <code>alreadySeen</code> list. Henceforth, check it to see if it is already in that list, and if it is, keep getting a random tweet until it hasn't already been seen.</p> <pre><code>if tweet1 not in alreadySeen: print tweet1.text.encode('utf-8') judge = input("1 pos, 2 neg, 3 skip: ") if judge == 1: tweet_pos.append(tweet1) elif judge == 2: tweet_neg.append(tweet1) alreadySeen.append(tweet1) </code></pre> <p>Finally, for confirmation, you can output the results by iterating through each tweet in <code>tweet_pos</code> and <code>tweet_neg</code> and print each tweet out just as you did earlier.</p> <pre><code>print "My positive tweets: " for pos in tweet_pos: print pos.text.encode('utf-8') print "My negative tweets: " for neg in tweet_neg: print neg.text.encode('utf-8') </code></pre> <p>Hope this helped.</p>
0
2016-10-19T02:03:46Z
[ "python", "string", "while-loop", "tweepy" ]
What am I missing on this spyder Loan Calculator?
40,120,674
<p>I´m learning Python at one of my college classes and I was asked to create a "Loan Calculator".... I might have an idea but I´m not sure how to fix an error that I´m getting <code>TypeError: 'float' object is not subscriptable</code></p> <p>This is the announcement The user has to enter the cost of the loan, interest rate and the number of years of the loan. Calculate the monthly payments with the following formula:</p> <pre><code>M = L[i(1+i)^n]/[(1+i)^(n)-1] Data: M = monthly payment L = loan amount i = interest rate (remember that 5%, i = 0.05) n = number of payments </code></pre> <p>And this is my code:</p> <pre><code># Loan Calculator # Equation: M = L[i(1+i)^n]/[(1+i)(n)-1] print("Loan Calculator") L = float(input("Loan amount: ")) i = float(input("Interest rate: ")) # Remember: 5% ---&gt; i=0.05 n = float(input("Number of payments: ")) M = (L[i*(1+i)**n]/[(1+i)**(n)-1]) # M = Monthly payment print("Monthly payment: " + M) </code></pre> <p>PS: I first thought I was missing convert "M" into a string, but after I changed to</p> <pre><code>print("Monthly payment: " + str(M)) </code></pre> <p>I'm still getting the same error... Please help!</p>
0
2016-10-19T01:36:29Z
40,120,769
<p>Needed a few changes: </p> <pre><code># Loan Calculator # Equation: M = L[i(1+i)^n]/[(1+i)(n)-1] print("Loan Calculator") L = float(input("Loan amount: ")) i = float(input("Interest rate: ")) # Remember: 5% ---&gt; i=0.05 n = float(input("Number of payments: ")) M = L*(i*(1+i)**n)/((1+i)**(n)-1) # M = Monthly payment print("Monthly payment: " , M) </code></pre> <p>Using some arbitrary values:</p> <pre><code>Loan Calculator Loan amount: 1000 Interest rate: 9 Number of payments: 100 ('Monthly payment: ', 9000.0) </code></pre>
0
2016-10-19T01:50:23Z
[ "python" ]
How to Create One Category from 2 Datasets in Python
40,120,679
<p>I have two data sets that both have data in it like follows:</p> <p>Data set 1:</p> <pre><code>Country Year Cause Gender Deaths 2090 2011 A000 1 70340 2090 2010 A001 2 53449 2090 2009 A002 1 1731 2090 2008 A003 2 1270 2090 2007 A004 1 148 2310 2011 A000 2 172 2310 2010 A001 1 24 2310 2009 A002 2 20 2310 2008 A003 1 27 2660 2013 A004 2 21 2660 2012 A005 1 88 2660 2011 A006 2 82 </code></pre> <p>Data set 2:</p> <pre><code>Country Year Cause Gender Deaths 2090 1999 B529 1 557 2090 1995 A001 2 234 2090 1996 B535 1 29 2090 1997 A002 2 33 2090 1998 B546 1 3224 2090 1999 B556 2 850 2310 1995 B555 1 319 2310 1996 A003 2 143 2310 1997 B563 1 251 2310 1998 B573 2 117 2660 1997 B561 1 244 2660 1998 A002 2 115 2660 1999 A001 1 10 2660 2000 B569 2 2 </code></pre> <p>I need to create categories on the Cause column codes which are for causes of death. But I need to make this category from using these combined causes from both data sets separately e.g.</p> <p>Road Traffic Accidents Category: From Data set 1: A001, A003</p> <p>Road Traffic Accidents Category: From Data set 2: B569, B555</p> <p>and the causes from both of these must be included in the Road Traffic Accidents Category.</p> <p>They must be included in each category for each data set (not combined) like: Road Traffic Accidents: A001, A003, B569, B555</p> <p>This is because say for example A001. In Data set 1 A001 is for Car Accidents, but in Data set 2 A001 means Heart Attack and I don't want Heart Attack in the Road Traffic Accidents category. But when the category is made from both data sets (i.e. Road Traffic Accidents: A001, A003, B569, B555) then A001 from both data sets is included in the Road Traffic Accidents category. </p> <p>The purpose of this question is to see how different categories differ over the years in terms of deaths - I am not allowed to combine both data sets manually not on Python. I am also not allowed to use any of the common packages such as Pandas, Numpy, etc.</p> <p>Thank you for help in advanced </p>
0
2016-10-19T01:37:06Z
40,121,212
<p>So my understanding of your problem is (correct me if I'm wrong), you have two datasets which both have a "Cause" column/variable. But the encoding of this "Cause" column in two datasets are different. </p> <p>In Dataset1, perhaps the encoding says:</p> <pre><code>Road Traffic Accidents Category: A001, A003 Heart Attack Category: C001, C002 #made up encoding </code></pre> <p>In Dataset2, perhaps the encoding says:</p> <pre><code>Road Traffic Accidents Category: B569, B555 Heart Attack Category: A001 Hurricane Cause of Death Category: E941 # made up encoding </code></pre> <p>What you want is to create a consistent category to cause encoding mapping which works for two datasets. </p> <p>I personally think python dictionary is the right data structure for this task. I assume you can load the category-cause mapping for both datasets. </p> <pre><code>data1_cat_cause = {'Road Traffic Accidents': ['A001', 'A003'], 'Heart Attack': ['C001', 'C002']} data2_cat_cause = {'Road Traffic Accidents': ['B569', 'B555'], 'Heart Attack': ['A001'], 'Hurricane Cause of Death': ['E941']} category_combined = set(data1_cat_cause.keys()) | set(data2_cat_cause.keys()) cat_cause_combined = {} for category in category_combined: cat_cause_combined[category] = {'Dataset1':data1_cat_cause.get(category),'Dataset2':data2_cat_cause.get(category)} </code></pre> <p>This would yield following information stored in the "cat_cause_combined" variable:</p> <pre><code> Dataset1 encoding Dataset2 encoding Road Traffic Accidents : ['A001', 'A003'] ['B569', 'B555'] Heart Attack : ['C001', 'C002'] ['A001'] Hurricane Cause of Death: None ['E941'] </code></pre> <p>I hope I understand your problem correctly and I hope this solution solves your problem. </p>
0
2016-10-19T02:43:20Z
[ "python", "dataset", "category", "jupyter-notebook" ]
Print user input in "cascade" of characters?
40,120,698
<p>I am trying to create code that gathers a user's first and last name (input order is last, first) and prints it first, last in a cascading way:</p> <pre><code> J o h n S m i t h </code></pre> <p>I'm really close, but I don't like the way my code works. I think there's an easier way, and I'm also running into issues where I get IndexError: string index out of range if I put in a name that is longer than how many print statements I put in. Any ideas?</p> <p>here's my code: </p> <pre><code>last = raw_input('enter your last name:') first= raw_input('enter your first name:') print(first[0]) print('\t' + first[1]) print('\t'*2 + first[2]) print('\t'*3+first[3]) print('\t'*4+first[4]) print('\t'*5+first[5]) print('\t'*6+first[6]) print(last[0]) print('\t' + last[1]) print('\t'*2 + last[2]) print('\t'*3+last[3]) print('\t'*4+last[4]) print('\t'*5+last[5]) </code></pre>
1
2016-10-19T01:39:25Z
40,120,777
<p>You can write a generic function, like the one shown below and reuse for your strings.</p> <pre><code>def cascade_name(name): for i, c in enumerate(name): print '\t'*(i+1), c </code></pre> <p>output:</p> <pre><code>&gt;&gt;&gt; cascade_name("foo") f o o </code></pre> <p>In your case you would do:</p> <pre><code>last = raw_input('enter your last name:') first= raw_input('enter your first name:') cascade_name(last) cascade_name(first) </code></pre>
1
2016-10-19T01:51:05Z
[ "python", "string", "printing" ]
How to write unittest for variable assignment in python?
40,120,770
<p>This is in <code>Python 2.7</code>. I have a class called <code>class A</code>, and there are some attributes that I want to throw an exception when being set by the user:</p> <pre><code>myA = A() myA.myattribute = 9 # this should throw an error </code></pre> <p>I want to write a <code>unittest</code> that ensures that this throws an error. </p> <p>After creating a test class and inheriting <code>unittest.TestCase</code>, I tried to write a test like this:</p> <pre><code>myA = A() self.assertRaises(AttributeError, eval('myA.myattribute = 9')) </code></pre> <p>But, this throws a <code>syntax error</code>. However, if I try <code>eval('myA.myattribute = 9')</code>, it throws the attribute error, as it should.</p> <p>How do I write a unittest to test this correctly? </p> <p>Thanks.</p>
3
2016-10-19T01:50:34Z
40,120,790
<p><code>self.assertRaises</code> takes a callable (and optionally one or more arguments for that callable) as its argument; you are providing the value that results from calling the callable with its arguments. The correct test would be <strike><code>self.assertRaises(AttributeError, eval, 'myA.myattribute = 9')</code></strike></p> <pre><code># Thanks to @mgilson for something that actually works while # resembling the original attempt. self.assertRaises(AttributeError, eval, 'myA.myattribute = 9', locals()) </code></pre> <p>However, you should use <code>assertRaises</code> as a context manager, which allows you to write the much more natural</p> <pre><code>with self.assertRaises(AttributeError): myA.myattribute = 9 </code></pre>
1
2016-10-19T01:53:29Z
[ "python", "python-2.7", "unit-testing", "python-unittest" ]
How to write unittest for variable assignment in python?
40,120,770
<p>This is in <code>Python 2.7</code>. I have a class called <code>class A</code>, and there are some attributes that I want to throw an exception when being set by the user:</p> <pre><code>myA = A() myA.myattribute = 9 # this should throw an error </code></pre> <p>I want to write a <code>unittest</code> that ensures that this throws an error. </p> <p>After creating a test class and inheriting <code>unittest.TestCase</code>, I tried to write a test like this:</p> <pre><code>myA = A() self.assertRaises(AttributeError, eval('myA.myattribute = 9')) </code></pre> <p>But, this throws a <code>syntax error</code>. However, if I try <code>eval('myA.myattribute = 9')</code>, it throws the attribute error, as it should.</p> <p>How do I write a unittest to test this correctly? </p> <p>Thanks.</p>
3
2016-10-19T01:50:34Z
40,120,791
<p>You can also use <code>assertRaises</code> as a context manager:</p> <pre><code>with self.assertRaises(AttributeError): myA.myattribute = 9 </code></pre> <p>The <a href="https://docs.python.org/3/library/unittest.html#basic-example" rel="nofollow">documentation shows more examples for this if you are interested</a>. The documentation for <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises" rel="nofollow">assertRaises</a> has a lot more detail on this subject as well.</p> <p>From that documentation:</p> <blockquote> <p>If only the exception and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function:</p> <pre><code>with self.assertRaises(SomeException): do_something() </code></pre> </blockquote> <p>which is exactly what you are trying to do.</p>
4
2016-10-19T01:53:41Z
[ "python", "python-2.7", "unit-testing", "python-unittest" ]
how to hide axes in matplotlib.pyplot
40,120,818
<p>I put the image in a <code>numpy</code> array, and draw it with the following code. How can I tell the program not to draw the axes, like <code>(0, 100, 200...)</code> </p> <pre><code>import matplotlib.pyplot as plt plt.figure() plt.imshow(output_ndarray) plt.savefig(output_png) </code></pre> <p><a href="https://i.stack.imgur.com/lIzWu.png" rel="nofollow"><img src="https://i.stack.imgur.com/lIzWu.png" alt="aflw picture"></a></p>
1
2016-10-19T01:56:44Z
40,121,071
<pre><code>plt.xticks([]) plt.yticks([]) </code></pre> <p><a href="http://matplotlib.org/api/pyplot_api.html" rel="nofollow">http://matplotlib.org/api/pyplot_api.html</a></p>
2
2016-10-19T02:26:38Z
[ "python", "numpy", "matplotlib" ]
how to hide axes in matplotlib.pyplot
40,120,818
<p>I put the image in a <code>numpy</code> array, and draw it with the following code. How can I tell the program not to draw the axes, like <code>(0, 100, 200...)</code> </p> <pre><code>import matplotlib.pyplot as plt plt.figure() plt.imshow(output_ndarray) plt.savefig(output_png) </code></pre> <p><a href="https://i.stack.imgur.com/lIzWu.png" rel="nofollow"><img src="https://i.stack.imgur.com/lIzWu.png" alt="aflw picture"></a></p>
1
2016-10-19T01:56:44Z
40,121,409
<p><a href="https://i.stack.imgur.com/M9NXQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/M9NXQ.png" alt="enter image description here"></a>You can also use...</p> <pre><code>plt.axis('off') </code></pre> <p><a href="https://i.stack.imgur.com/STpTP.png" rel="nofollow"><img src="https://i.stack.imgur.com/STpTP.png" alt="enter image description here"></a></p>
2
2016-10-19T03:03:28Z
[ "python", "numpy", "matplotlib" ]
Error importing storage module.whitenoise.django
40,121,126
<p>I'm trying to deploy a basic Django app to Heroku, but am getting an error when I try to deploy.</p> <p>It looks like the error is with <em>whitenoise</em>. I have <em>six</em> installed as part of my requirements so it should handle urllib.parse.</p> <p>Here is the error:</p> <pre><code>remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/storage.py", line 290, in get_storage_class remote: raise ImproperlyConfigured('Error importing storage module %s: "%s"' % (module, e)) remote: django.core.exceptions.ImproperlyConfigured: Error importing storage module whitenoise.django: "No module named urllib.parse" remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. </code></pre> <p>Here is the full stack:</p> <pre><code>remote: remote: -----&gt; Python app detected remote: -----&gt; Uninstalling stale dependencies remote: Uninstalling DateTime-4.1.1: remote: Successfully uninstalled DateTime-4.1.1 remote: Uninstalling simplejson-3.8.2: remote: Successfully uninstalled simplejson-3.8.2 remote: -----&gt; Noticed cffi. Bootstrapping libffi. remote: $ pip install -r requirements.txt remote: Collecting altgraph==0.10.2 (from -r requirements.txt (line 1)) remote: Downloading altgraph-0.10.2.tar.gz (481kB) remote: Collecting bdist-mpkg==0.5.0 (from -r requirements.txt (line 2)) remote: Downloading bdist_mpkg-0.5.0.tar.gz remote: Collecting bpython==0.12 (from -r requirements.txt (line 3)) remote: Downloading bpython-0.12.tar.gz (130kB) remote: Collecting csvkit==0.7.3 (from -r requirements.txt (line 4)) remote: Downloading csvkit-0.7.3.tar.gz remote: Collecting Cython==0.19.2 (from -r requirements.txt (line 5)) remote: Downloading Cython-0.19.2-cp27-cp27m-manylinux1_x86_64.whl (4.0MB) remote: Collecting dbf==0.94.3 (from -r requirements.txt (line 6)) remote: Downloading dbf-0.94.003.tar.gz (79kB) remote: Collecting dj-database-url==0.4.1 (from -r requirements.txt (line 7)) remote: Downloading dj-database-url-0.4.1.tar.gz remote: Collecting Django==1.5.4 (from -r requirements.txt (line 8)) remote: Downloading Django-1.5.4.tar.gz (8.1MB) remote: Collecting future==0.11.2 (from -r requirements.txt (line 9)) remote: Downloading future-0.11.2.tar.gz (321kB) remote: Collecting futures==3.0.5 (from -r requirements.txt (line 10)) remote: Downloading futures-3.0.5-py2-none-any.whl remote: Collecting greenlet==0.4.1 (from -r requirements.txt (line 11)) remote: Downloading greenlet-0.4.1.zip (75kB) remote: Collecting grequests==0.2.0 (from -r requirements.txt (line 12)) remote: Downloading grequests-0.2.0.tar.gz remote: Collecting gunicorn==19.6.0 (from -r requirements.txt (line 13)) remote: Downloading gunicorn-19.6.0-py2.py3-none-any.whl (114kB) remote: Collecting humanize==0.5 (from -r requirements.txt (line 14)) remote: Downloading humanize-0.5.tar.gz remote: Collecting iso8601==0.1.8 (from -r requirements.txt (line 15)) remote: Downloading iso8601-0.1.8.tar.gz remote: Collecting livestreamer==1.12.2 (from -r requirements.txt (line 16)) remote: Downloading livestreamer-1.12.2.tar.gz (430kB) remote: Collecting macholib==1.5.1 (from -r requirements.txt (line 17)) remote: Downloading macholib-1.5.1.tar.gz (454kB) remote: Collecting modulegraph==0.10.4 (from -r requirements.txt (line 18)) remote: Downloading modulegraph-0.10.4.tar.gz (532kB) remote: Collecting MySQL-python==1.2.4 (from -r requirements.txt (line 19)) remote: Downloading MySQL-python-1.2.4.zip (113kB) remote: Collecting openpyxl==2.0.3 (from -r requirements.txt (line 20)) remote: Downloading openpyxl-2.0.3.tar.gz (113kB) remote: Collecting py2app==0.7.3 (from -r requirements.txt (line 21)) remote: Downloading py2app-0.7.3.tar.gz (1.2MB) remote: Collecting pycrypto==2.6.1 (from -r requirements.txt (line 22)) remote: Downloading pycrypto-2.6.1.tar.gz (446kB) remote: Collecting pycurl==7.19.0.2 (from -r requirements.txt (line 23)) remote: Downloading pycurl-7.19.0.2.tar.gz (89kB) remote: Collecting Pygments==1.6 (from -r requirements.txt (line 24)) remote: Downloading Pygments-1.6.tar.gz (1.4MB) remote: Collecting pyOpenSSL==0.13.1 (from -r requirements.txt (line 25)) remote: Downloading pyOpenSSL-0.13.1.tar.gz (254kB) remote: Collecting pyparsing==2.0.1 (from -r requirements.txt (line 26)) remote: Downloading pyparsing-2.0.1.tar.gz (1.1MB) remote: Collecting python-dateutil==1.5 (from -r requirements.txt (line 27)) remote: Downloading python-dateutil-1.5.tar.gz (233kB) remote: Collecting pytz==2013.7 (from -r requirements.txt (line 28)) remote: Downloading pytz-2013.7.tar.bz2 (177kB) remote: Collecting requests==2.0.1 (from -r requirements.txt (line 29)) remote: Downloading requests-2.0.1-py2.py3-none-any.whl (439kB) remote: Collecting singledispatch==3.4.0.3 (from -r requirements.txt (line 30)) remote: Downloading singledispatch-3.4.0.3-py2.py3-none-any.whl remote: Collecting six==1.4.1 (from -r requirements.txt (line 31)) remote: Downloading six-1.4.1.tar.gz remote: Collecting SQLAlchemy==0.9.4 (from -r requirements.txt (line 32)) remote: Downloading SQLAlchemy-0.9.4.tar.gz (4.5MB) remote: Collecting virtualenv==15.0.3 (from -r requirements.txt (line 33)) remote: Downloading virtualenv-15.0.3-py2.py3-none-any.whl (3.5MB) remote: Collecting whitenoise==3.2.2 (from -r requirements.txt (line 34)) remote: Downloading whitenoise-3.2.2-py2.py3-none-any.whl remote: Collecting xattr==0.6.4 (from -r requirements.txt (line 35)) remote: Downloading xattr-0.6.4.tar.gz remote: Collecting xlrd==0.9.3 (from -r requirements.txt (line 36)) remote: Downloading xlrd-0.9.3.tar.gz (178kB) remote: Collecting zope.interface==4.1.1 (from -r requirements.txt (line 37)) remote: Downloading zope.interface-4.1.1.tar.gz (864kB) remote: Collecting gevent (from grequests==0.2.0-&gt;-r requirements.txt (line 12)) remote: Downloading gevent-1.1.2-cp27-cp27m-manylinux1_x86_64.whl (1.3MB) remote: Collecting jdcal (from openpyxl==2.0.3-&gt;-r requirements.txt (line 20)) remote: Downloading jdcal-1.3.tar.gz remote: Installing collected packages: altgraph, bdist-mpkg, Pygments, bpython, xlrd, python-dateutil, SQLAlchemy, jdcal, openpyxl, dbf, csvkit, Cython, dj-database-url, Django, future, futures, greenlet, gevent, requests, grequests, gunicorn, humanize, iso8601, six, singledispatch, livestreamer, macholib, modulegraph, MySQL-python, py2app, pycrypto, pycurl, pyOpenSSL, pyparsing, pytz, virtualenv, whitenoise, xattr, zope.interface remote: Running setup.py install for altgraph: started remote: Running setup.py install for altgraph: finished with status 'done' remote: Running setup.py install for bdist-mpkg: started remote: Running setup.py install for bdist-mpkg: finished with status 'done' remote: Running setup.py install for Pygments: started remote: Running setup.py install for Pygments: finished with status 'done' remote: Running setup.py install for bpython: started remote: Running setup.py install for bpython: finished with status 'done' remote: Running setup.py install for xlrd: started remote: Running setup.py install for xlrd: finished with status 'done' remote: Running setup.py install for python-dateutil: started remote: Running setup.py install for python-dateutil: finished with status 'done' remote: Running setup.py install for SQLAlchemy: started remote: Running setup.py install for SQLAlchemy: finished with status 'done' remote: Running setup.py install for jdcal: started remote: Running setup.py install for jdcal: finished with status 'done' remote: Running setup.py install for openpyxl: started remote: Running setup.py install for openpyxl: finished with status 'done' remote: Running setup.py install for dbf: started remote: Running setup.py install for dbf: finished with status 'done' remote: Running setup.py install for csvkit: started remote: Running setup.py install for csvkit: finished with status 'done' remote: Running setup.py install for dj-database-url: started remote: Running setup.py install for dj-database-url: finished with status 'done' remote: Running setup.py install for Django: started remote: Running setup.py install for Django: finished with status 'done' remote: Running setup.py install for future: started remote: Running setup.py install for future: finished with status 'done' remote: Running setup.py install for greenlet: started remote: Running setup.py install for greenlet: finished with status 'done' remote: Found existing installation: requests 2.11.1 remote: Uninstalling requests-2.11.1: remote: Successfully uninstalled requests-2.11.1 remote: Running setup.py install for grequests: started remote: Running setup.py install for grequests: finished with status 'done' remote: Running setup.py install for humanize: started remote: Running setup.py install for humanize: finished with status 'done' remote: Running setup.py install for iso8601: started remote: Running setup.py install for iso8601: finished with status 'done' remote: Running setup.py install for six: started remote: Running setup.py install for six: finished with status 'done' remote: Running setup.py install for livestreamer: started remote: Running setup.py install for livestreamer: finished with status 'done' remote: Running setup.py install for macholib: started remote: Running setup.py install for macholib: finished with status 'done' remote: Running setup.py install for modulegraph: started remote: Running setup.py install for modulegraph: finished with status 'done' remote: Running setup.py install for MySQL-python: started remote: Running setup.py install for MySQL-python: finished with status 'done' remote: Running setup.py install for py2app: started remote: Running setup.py install for py2app: finished with status 'done' remote: Running setup.py install for pycrypto: started remote: Running setup.py install for pycrypto: finished with status 'done' remote: Running setup.py install for pycurl: started remote: Running setup.py install for pycurl: finished with status 'done' remote: Running setup.py install for pyOpenSSL: started remote: Running setup.py install for pyOpenSSL: finished with status 'done' remote: Running setup.py install for pyparsing: started remote: Running setup.py install for pyparsing: finished with status 'done' remote: Found existing installation: pytz 2016.7 remote: Uninstalling pytz-2016.7: remote: Successfully uninstalled pytz-2016.7 remote: Running setup.py install for pytz: started remote: Running setup.py install for pytz: finished with status 'done' remote: Running setup.py install for xattr: started remote: Running setup.py install for xattr: finished with status 'done' remote: Found existing installation: zope.interface 4.3.2 remote: Uninstalling zope.interface-4.3.2: remote: Successfully uninstalled zope.interface-4.3.2 remote: Running setup.py install for zope.interface: started remote: Running setup.py install for zope.interface: finished with status 'done' remote: Successfully installed Cython-0.19.2 Django-1.5.4 MySQL-python-1.2.4 Pygments-1.6 SQLAlchemy-0.9.4 altgraph-0.10.2 bdist-mpkg-0.5.0 bpython-0.12 csvkit-0.7.3 dbf-0.94.3 dj-database-url-0.4.1 future-0.11.2 futures-3.0.5 gevent-1.1.2 greenlet-0.4.1 grequests-0.2.0 gunicorn-19.6.0 humanize-0.5 iso8601-0.1.8 jdcal-1.3 livestreamer-1.12.2 macholib-1.5.1 modulegraph-0.10.4 openpyxl-2.0.3 py2app-0.7.3 pyOpenSSL-0.13.1 pycrypto-2.6.1 pycurl-7.19.0.2 pyparsing-2.0.1 python-dateutil-1.5 pytz-2013.7 requests-2.0.1 singledispatch-3.4.0.3 six-1.4.1 virtualenv-15.0.3 whitenoise-3.2.2 xattr-0.6.4 xlrd-0.9.3 zope.interface-4.1.1 remote: remote: $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 10, in &lt;module&gt; remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command remote: klass = load_command_class(app_name, subcommand) remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 78, in load_command_class remote: return module.Command() remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 58, in __init__ remote: self.storage.path('') remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/functional.py", line 204, in inner remote: self._setup() remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/storage.py", line 307, in _setup remote: self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/files/storage.py", line 290, in get_storage_class remote: raise ImproperlyConfigured('Error importing storage module %s: "%s"' % (module, e)) remote: django.core.exceptions.ImproperlyConfigured: Error importing storage module whitenoise.django: "No module named urllib.parse" remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. </code></pre>
0
2016-10-19T02:33:06Z
40,127,263
<p>You're using an unsupported version of Django. Django 1.5 has been out of mainstream support for three years, and out of extended support for two. See here: <a href="https://www.djangoproject.com/download/#supported-versions" rel="nofollow">https://www.djangoproject.com/download/#supported-versions</a></p> <p>The latest version of WhiteNoise is tested with Django 1.8 and up.</p>
0
2016-10-19T09:23:24Z
[ "python", "django", "heroku" ]
python can not get my all examples right
40,121,169
<p>For my own understanding, I write 2 functions and use my examples to test. Similarly, both 2 functions have 1 example right and one wrong. 1. def count_from_word_list(tweet, L): """(str, list of str) -> int </p> <p>The first parameter represents a tweet. The second parameter is a list of words. Count how many times any of the words from the list occur in the tweet, and return the total number.</p> <pre><code>&gt;&gt;&gt; count_from_word_list('I like him and I like her', ["like","her"]) 3 &gt;&gt;&gt; count_from_word_list('I like him and he likes me', ["like","her"]) 1 """ count = 0 for i in L: if i in tweet: count = count + 1 return count </code></pre> <p>2. def contains_hashtag(tweet, h): """(str, str) -> bool </p> <pre><code>The first parameter represents a tweet, and second parameter represents a hashtag. Return True if and only if the tweet contains the hashtag. &gt;&gt;&gt; contains_hashtag('I like #csc120', '#csc120') True &gt;&gt;&gt; contains_hashtag('I like #csc120', '#csc') False """ if h in tweet: return True else: return False </code></pre>
-3
2016-10-19T02:39:08Z
40,121,648
<h2>First function</h2> <p>I assume from your example that the body of your first function looks like</p> <pre><code>def count_from_word_list(tweet, L): count = 0 for i in L: if i in tweet: count = count + 1 return count </code></pre> <p>Lets think about what is happening in logical steps:</p> <ol> <li>You use <code>i</code> to iterate over the list of words to search for.</li> <li>You then test if <code>i</code> is in <code>tweet</code> using the <code>in</code> keyword.</li> </ol> <p>And this is where your error lies. The <code>in</code> keyword in python is used to test if something contains something else. Once python sees that the left hand operand to <code>in</code> is in the right hand operand, it stops, and does not count all the occurrences of the appearance.</p> <p>If you want to count the number of times a given list of words appear in string do this instead:</p> <pre><code>def count_occurens_of_words(tweet, word_list): # create a variable to hold the count in. # It will be incremented each time we find # a word in the tweet that contains or matches a # word from the word_list count = 0 # for each word in the word_list for search_word in word_list: # for each word in the tweet for word in tweet.split(' '): # if a word in the tweet contains or matches a word from the word_list if search_word == word: # increment count count += 1 # return count return count </code></pre> <p><strong>Output:</strong></p> <pre><code>&gt;&gt;&gt; count_occurens_of_words('I like him and he likes me', ["like","her"]) 2 &gt;&gt;&gt; count_occurens_of_words('I like him and he likes her', ["like","her"]) 3 &gt;&gt;&gt; </code></pre> <h2>Second function</h2> <p>Assuming that your second function is something such as this:</p> <pre><code>def contains_hashtag(tweet, h): if h in tweet: return True else: return False </code></pre> <p>What you need to do is check if any word in the tweet is the hashtag your looking for. When you use <code>in</code> even if the hashtag is a substring of another hashtag it will return true. eg.</p> <pre><code>def contains_hashtag(tweet, h): for word in tweet.split(' '): if word == h: return True </code></pre>
0
2016-10-19T03:31:33Z
[ "python" ]
Using python request library to dynamically get HTTP Error String
40,121,187
<p>I've been asked to swap over from urllib2 to the requests library because the library is simpler to use and doesn't cause exceptions.</p> <p>I can get the HTTP error code with response.status_code but I don't see a way to get the error message for that code. Normally, I wouldn't care, but I'm testing an API and the string is just as important.</p> <p>Does anybody know of a simple way to get that string? I'm expecting 2 pieces something like:</p> <p>'400':'Bad Request'</p> <p>This is NOT a DUPLICATE</p> <p>Some of the codes being returned have unique strings being sent by the application that I am testing. These strings cannot be looked up using this method: requests.status_codes._codes[error][0] Since the string is dynamically coming from the back end server. I was able to get this information using urllib using this method: </p> <p><code>import urllib2 ... opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx)) except urllib2.HTTPError as err: try: error_message = err.read() ...</code></p> <p>The question now is... is there a method of getting the dynamic http error string? Thanks so much for being patient. The previous issue was closed so quickly I never got a chance to look at the answer, test it and re-ask by cleaning up the description.</p>
0
2016-10-19T02:40:25Z
40,121,270
<pre><code>response = requests.get(url) error_message = response.reason </code></pre>
1
2016-10-19T02:49:43Z
[ "python", "httprequest", "urllib2" ]
Using python request library to dynamically get HTTP Error String
40,121,187
<p>I've been asked to swap over from urllib2 to the requests library because the library is simpler to use and doesn't cause exceptions.</p> <p>I can get the HTTP error code with response.status_code but I don't see a way to get the error message for that code. Normally, I wouldn't care, but I'm testing an API and the string is just as important.</p> <p>Does anybody know of a simple way to get that string? I'm expecting 2 pieces something like:</p> <p>'400':'Bad Request'</p> <p>This is NOT a DUPLICATE</p> <p>Some of the codes being returned have unique strings being sent by the application that I am testing. These strings cannot be looked up using this method: requests.status_codes._codes[error][0] Since the string is dynamically coming from the back end server. I was able to get this information using urllib using this method: </p> <p><code>import urllib2 ... opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx)) except urllib2.HTTPError as err: try: error_message = err.read() ...</code></p> <p>The question now is... is there a method of getting the dynamic http error string? Thanks so much for being patient. The previous issue was closed so quickly I never got a chance to look at the answer, test it and re-ask by cleaning up the description.</p>
0
2016-10-19T02:40:25Z
40,121,278
<p>In <a href="https://docs.python.org/3.4/library/http.client.html#httpresponse-objects" rel="nofollow">HTTPResponse there's a <code>reason</code> attribute</a> that returns the reason phrase from the response's status line. In <a href="http://docs.python-requests.org/en/master/api/#requests.Response" rel="nofollow">the requests library the <code>requests.Response class</code></a> has an equivalent <code>reason</code> attribute that returns the same thing. Both should return the information from the response, not a fixed string based on the code.</p>
0
2016-10-19T02:50:57Z
[ "python", "httprequest", "urllib2" ]
using a Python script w 2nd Order Runge Kutta method to solve the equation of a pendulum, how do I add a calculation of the KE, PE, and TE?
40,121,203
<p>I am unable to figure out how to program my script to plot KE, PE, and TE. I have included multiple ########### in the parts of my code where I feel the problem lies. </p> <pre><code>def pendulum_runge_kutta(theta0,omega0,g,tfinal,dt): # initialize arrays t = np.arange(0.,tfinal+dt,dt) # time array t npoints = len(t) theta = np.zeros(npoints) # position array theta omega = np.zeros(npoints) # position array omega Ke = np.zeros(npoints) Pe = np.zeros(npoints) L=4 g = 9.81 t2=np.linspace(0,tfinal,1000) theta0=0.01 omega0=0 # exact solution for thetaExact = theta0*np.cos((g/L)**(1/2)*t2) # SECOND ORDER RUNGE_KUTTA SOLUTION theta[0] = theta0 omega[0] = omega0 #Ke[0] = ####################################### #Pe[0] =###################################### m=1.0 for i in range(npoints-1): # compute midpoint position (not used!) and velocity thetamid = theta[i] + omega[i]*dt omegamid = omega[i] - (g/L)*np.sin(theta[i])*dt/2 # use midpoint velocity to advance position theta[i+1] = theta[i] + omegamid*dt omega[i+1] = omega[i] -(g/L)*np.sin(thetamid)*dt/2 ###########calculate Ke, Pe, Te############ Ke[i+1] = 0.5*m*(omega[i+1]*L)**2 Pe[i+1] = m*g*L*np.sin(theta[i+1]) Te = Ke+Pe #plot result of Ke, Pe, Te pl.figure(1) pl.plot(t,Ke,'c-',label='kinetic energy') pl.plot(t,Pe,'m-',label='potential energy') pl.plot(t,Te,'g-',label='total energy') pl.title('Ke, Pe, and Te') pl.legend(loc='lower right') pl.show() #now plot the results pl.figure(2) pl.plot(t,theta,'ro',label='2oRK') pl.plot(t2,thetaExact,'r',label='Exact') pl.grid('on') pl.legend() pl.xlabel('Time (s)') pl.ylabel('Theta') pl.title('Theta vs Time') pl.show() #call function pendulum_runge_kutta(0.01, 0, 9.8, 12, .1) </code></pre>
0
2016-10-19T02:42:09Z
40,137,946
<p>You are missing a factor 1/2 in both theta updates. The formulas for the midpoint method apply uniformly to all components of the first order system.</p> <p>The potential energy should contain the integral of <code>sin(x)</code>, <code>C-cos(x)</code>. For instance, </p> <pre><code>Pe[i+1] = m*g*L*(1-np.cos(theta[i+1])) </code></pre> <p>The formulas for the energies at time point <code>i+1</code> also apply at time point <code>0</code>.</p> <p>And finally, the indicated exact solution is for the small angle approximation, there is no finitely expressible exact solution for the general physical pendulum. For the given amplitude of <code>theta0=0.01</code>, the small angle approximation should be good enough, but be aware of this for larger swings.</p>
0
2016-10-19T17:30:35Z
[ "python", "physics", "runge-kutta" ]
Initiate new processes instead of reusing prior in Python
40,121,205
<p>I am using multiprocessing in Python with:</p> <pre><code>import multiprocessing as mp all_arguments = range(0,20) pool = mp.Pool(processes=7) all_items = [pool.apply_async(main_multiprocessing_function, args=(argument_value,)) for argument_value in all_arguments] for item in all_items: item.get() </code></pre> <p>In the above, as far as i am aware, after a worker processor finishes, it moves on to the next value. Is there any way instead to force a 'new' worker processor to be initialed from scratch each time, rather than to re-use the old one?</p> <p>[Specifically, <code>main_multiprocessing_function</code> calls multiple other functions that each using caching to speed up the processing within each task. All those caches are however redundant for the next item to be processed, and thus am interested in a way of resetting everything back to being fresh]. </p>
0
2016-10-19T02:42:46Z
40,121,643
<p>From the <a href="https://docs.python.org/3.6/library/multiprocessing.html#multiprocessing.pool.Pool" rel="nofollow">docs</a>:</p> <blockquote> <p>maxtasksperchild is the number of tasks a worker process can complete before it will exit and be replaced with a fresh worker process, to enable unused resources to be freed. The default maxtasksperchild is None, which means worker processes will live as long as the pool.</p> </blockquote> <p>Just create the pool as </p> <pre><code>pool = mp.Pool(processes=7, maxtasksperchild=1) </code></pre>
2
2016-10-19T03:30:46Z
[ "python", "python-multiprocessing" ]
Python string to dictionary with json (not working)
40,121,231
<p>I have a text file like this :</p> <p>"imei": "123456789", "sim_no": "+90 xxx xxx xx xx", "device_type": "standart", "hw_version": "1.01", "sw_version": "1.02"</p> <p>and i want to convert to dictionary this file. Because i want to take values. </p> <pre><code>import json from time import sleep def buffer(data): dicto=json.loads(data) print(type(dicto)) file=open("config.txt", "r").read() jsondata=json.dumps(file) buffer(jsondata) result : &lt;class 'str'&gt; </code></pre> <p>When i working in shell like this :</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; h = '{"foo":"bar", "foo2":"bar2"}' &gt;&gt;&gt; type(h) &lt;class 'str'&gt; &gt;&gt;&gt; d=json.loads(h) &gt;&gt;&gt; d {'foo2': 'bar2', 'foo': 'bar'} &gt;&gt;&gt; type(d) &lt;class 'dict'&gt; &gt;&gt;&gt; </code></pre> <p>its working but i can't understand why my code not working. When i convert this file to dictionary i want to hold in a buffer. How can i hold this data inside array? Please excuse me i am new in Python.</p>
0
2016-10-19T02:45:08Z
40,121,388
<pre><code>import json from time import sleep def buffer(data): s = json.loads(data) dicto = {} tmp_list = s.split(',') for e in tmp_list: tmp = e.split(':') dicto[tmp[0]] = tmp[1] print(type(dicto)) file=open("config.txt", "r").read() jsondata=json.dumps(file) buffer(jsondata) </code></pre>
-1
2016-10-19T03:01:22Z
[ "python", "json", "python-3.x" ]
Python string to dictionary with json (not working)
40,121,231
<p>I have a text file like this :</p> <p>"imei": "123456789", "sim_no": "+90 xxx xxx xx xx", "device_type": "standart", "hw_version": "1.01", "sw_version": "1.02"</p> <p>and i want to convert to dictionary this file. Because i want to take values. </p> <pre><code>import json from time import sleep def buffer(data): dicto=json.loads(data) print(type(dicto)) file=open("config.txt", "r").read() jsondata=json.dumps(file) buffer(jsondata) result : &lt;class 'str'&gt; </code></pre> <p>When i working in shell like this :</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; h = '{"foo":"bar", "foo2":"bar2"}' &gt;&gt;&gt; type(h) &lt;class 'str'&gt; &gt;&gt;&gt; d=json.loads(h) &gt;&gt;&gt; d {'foo2': 'bar2', 'foo': 'bar'} &gt;&gt;&gt; type(d) &lt;class 'dict'&gt; &gt;&gt;&gt; </code></pre> <p>its working but i can't understand why my code not working. When i convert this file to dictionary i want to hold in a buffer. How can i hold this data inside array? Please excuse me i am new in Python.</p>
0
2016-10-19T02:45:08Z
40,121,587
<p>Seems like you could just add the outer curly braces JSON requires:</p> <pre><code>with open('config.txt', 'r+') as f: newdata = '{{ {} }}'.format(f.read()) f.seek(0) f.write(newdata) </code></pre> <p>Otherwise, the file is already JSON, so no actual use of the <code>json</code> module is required (unless you want to check if it's already legal before modifying, or verify legality after).</p>
2
2016-10-19T03:25:29Z
[ "python", "json", "python-3.x" ]
Python string to dictionary with json (not working)
40,121,231
<p>I have a text file like this :</p> <p>"imei": "123456789", "sim_no": "+90 xxx xxx xx xx", "device_type": "standart", "hw_version": "1.01", "sw_version": "1.02"</p> <p>and i want to convert to dictionary this file. Because i want to take values. </p> <pre><code>import json from time import sleep def buffer(data): dicto=json.loads(data) print(type(dicto)) file=open("config.txt", "r").read() jsondata=json.dumps(file) buffer(jsondata) result : &lt;class 'str'&gt; </code></pre> <p>When i working in shell like this :</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; h = '{"foo":"bar", "foo2":"bar2"}' &gt;&gt;&gt; type(h) &lt;class 'str'&gt; &gt;&gt;&gt; d=json.loads(h) &gt;&gt;&gt; d {'foo2': 'bar2', 'foo': 'bar'} &gt;&gt;&gt; type(d) &lt;class 'dict'&gt; &gt;&gt;&gt; </code></pre> <p>its working but i can't understand why my code not working. When i convert this file to dictionary i want to hold in a buffer. How can i hold this data inside array? Please excuse me i am new in Python.</p>
0
2016-10-19T02:45:08Z
40,122,103
<p>I have to solve this question :</p> <p>We have a text file like this :</p> <pre><code>"imei": "123456789", "sim_no": "+90 xxx xxx xx xx", "device_type": "standart", "hw_version": "1.01", "sw_version": "1.02" </code></pre> <p>And we should read this JSON data, then we should read this data each 1 min and put to buffer(idk how can i put, is buffer array or dict?) then we should delete the oldest file each 5 min. Exceptions are important. Format sould be like "imei", "hw_version", "sw_version", "device_type". We sould solve buffer overflowing.</p> <p>I write this code :</p> <pre><code>import json from time import sleep def buffer(data): pass #imei = data.get("imei") # I want to read like this # this function should put the variables to array counter=0 while True: with open("config.txt") as f: mydict = json.loads('{{ {} }}'.format(f.read())) buffer(mydict) sleep(60) counter+=1 if counter%5==0 # delete the oldest data </code></pre>
0
2016-10-19T04:24:17Z
[ "python", "json", "python-3.x" ]
Python : Web Scraping Specific Keywords
40,121,232
<p>My Question shouldn't be too hard to answer, The problem im having is im not sure how to scrape a website for specific keywords.. I'm quite new to Python.. So i know i need to add in some more details , Firstly what i dont want to do is use Beautiful Soup or any of those libs, im using lxml and requests, What i do want to do is ask the user for an input for a website and once its provided , Send a request to the provided URL, once the request is made i want it to grab all the html which i believe ive done using html.fromstring(site.content) so all thats been done the problem im having is i want it to find any link or text with the ending '.swf' and print it below that.. Anyone know any way of doing this?</p> <pre><code>def ScrapeSwf(): flashSite = raw_input('Please Provide Web URL : ') print 'Sending Requests...' flashReq = requests.get(flashSite) print 'Scraping...' flashTree = html.fromstring(flashReq.content) print ' Now i want to search the html for the swf link in the html' print ' And Display them using print probablly with a while condition' </code></pre> <p>Something like that .. Any help is highly appreciated</p>
0
2016-10-19T02:45:14Z
40,121,436
<p>You're using <code>lxhtml</code> to build the HTML into an object model, so you probably want to use <code>flashTree.xpath</code> to search the DOM using XML Path Language. Find the path you want in the source DOM and then write an xpath that extracts it, your web browser's developer tools and <a href="http://www.w3schools.com/xsl/xpath_intro.asp" rel="nofollow">w3schools</a> can help you.</p> <p>I personally wouldn't bother, I'd just extract the text I needed using a regular expression (<code>re.find(pattern, flashReq.content)</code>) because it's quicker. If I didn't know regex, wasn't comfortable with them, or I wanted raw speed then I'd use a crude string extraction like so:</p> <pre><code>start = flashReq.content.find(text_before_it) + len(text_before_it) end = flashReq.content.find(text_after_it, start) text_you_want = flashReq.content[start:end] </code></pre>
1
2016-10-19T03:06:45Z
[ "python", "web", "web-crawler", "screen-scraping", "scrape" ]
Python : Web Scraping Specific Keywords
40,121,232
<p>My Question shouldn't be too hard to answer, The problem im having is im not sure how to scrape a website for specific keywords.. I'm quite new to Python.. So i know i need to add in some more details , Firstly what i dont want to do is use Beautiful Soup or any of those libs, im using lxml and requests, What i do want to do is ask the user for an input for a website and once its provided , Send a request to the provided URL, once the request is made i want it to grab all the html which i believe ive done using html.fromstring(site.content) so all thats been done the problem im having is i want it to find any link or text with the ending '.swf' and print it below that.. Anyone know any way of doing this?</p> <pre><code>def ScrapeSwf(): flashSite = raw_input('Please Provide Web URL : ') print 'Sending Requests...' flashReq = requests.get(flashSite) print 'Scraping...' flashTree = html.fromstring(flashReq.content) print ' Now i want to search the html for the swf link in the html' print ' And Display them using print probablly with a while condition' </code></pre> <p>Something like that .. Any help is highly appreciated</p>
0
2016-10-19T02:45:14Z
40,121,984
<p>Here goes my attempt:</p> <pre><code>import requests [1] response = requests.get(flashSite) [2] myPage = response.content [3] for line in myPage.splitlines(): [4] if '.swf' in line: [5] start = line.find('http') [6] end = line.find('.swf') + 4 [7] print line[start:end] [8] </code></pre> <p>Explanation: <p><strong>1</strong>: Import the request module. I couldn't really figure out a way to get what I needed out of lxml, so I just stuck with this. <p><strong>2</strong>: Send a HTTP GET method to whatever site that has the Flash file <p><strong>3</strong>: Save its contents to a variable <p> Yes, I realize you could condense lines 2 and 3, I just did it this way because I felt it makes a bit more sense to me. <p><strong>4</strong>: Now iterating through each line in the code, going line by line. <p><strong>5</strong>: Check to see if '.swf' is in that line <p> Lines 6 through 8 demonstrate the string slicing method that <a href="http://stackoverflow.com/users/146642/gaz-davidson">@GazDavidson</a> mentioned in his answer. The reason I add 4 in line <strong>7</strong> is because '.swf' is 4 characters long. <p> You should be able to (roughly) get the result that provides a link to the SWF file.</p>
0
2016-10-19T04:12:30Z
[ "python", "web", "web-crawler", "screen-scraping", "scrape" ]
str.replace function raise erorr that an integer is required
40,121,350
<p>I wanna ask the problem I encountered. At first, Let me show you my whole code</p> <pre><code>df1 = pd.read_excel(r'E:\내논문자료\골목상권 데이터\이태원로 54길 내용뺀거.xlsx' , sheetname='first_day_datas') df1.registerdate= df1.registerdate.astype(str) # 칼럼 속성 바꾸기 df2 = pd.to_datetime(df1['registerdate'].str[0:10]) df3 = df2['registerdate'].str.replace('-', '').str.strip() </code></pre> <p>I just wanna change the string in registerdate column. when I put print(df2.head(3)). It shows like below</p> <pre><code>0 2016-10-11 1 2016-10-15 2 2016-10-15 </code></pre> <p>so I wanna replace '-' with ''. I type the code and 'TypeError: an integer is required' popped out. How can I solve this problem??</p>
4
2016-10-19T02:58:12Z
40,121,556
<pre><code>df2 = pd.to_datetime(df1['registerdate'].str[0:10]) # \____________/ # returns a series </code></pre> <hr> <pre><code>df2['registerdate'].str.replace('-', '').str.strip() #\_______________/ # is only something # if 'registration # is in the index # this is probably the source of your error </code></pre> <hr> <p>At this point <code>df2</code> is a <code>pd.Series</code> of <code>Timestamps</code>. the format <code>yyyy-mm-dd</code> is just the way that <code>Timestamp</code> is being displayed. To display it as <code>yyyymmdd</code>, do this</p> <pre><code>df2.dt.strftime('%Y%m%d') 0 20160331 1 20160401 2 20160402 3 20160403 4 20160404 Name: registerdate, dtype: object </code></pre>
2
2016-10-19T03:21:49Z
[ "python", "pandas" ]
str.replace function raise erorr that an integer is required
40,121,350
<p>I wanna ask the problem I encountered. At first, Let me show you my whole code</p> <pre><code>df1 = pd.read_excel(r'E:\내논문자료\골목상권 데이터\이태원로 54길 내용뺀거.xlsx' , sheetname='first_day_datas') df1.registerdate= df1.registerdate.astype(str) # 칼럼 속성 바꾸기 df2 = pd.to_datetime(df1['registerdate'].str[0:10]) df3 = df2['registerdate'].str.replace('-', '').str.strip() </code></pre> <p>I just wanna change the string in registerdate column. when I put print(df2.head(3)). It shows like below</p> <pre><code>0 2016-10-11 1 2016-10-15 2 2016-10-15 </code></pre> <p>so I wanna replace '-' with ''. I type the code and 'TypeError: an integer is required' popped out. How can I solve this problem??</p>
4
2016-10-19T02:58:12Z
40,121,723
<p>It seems df2 has no column 'registerdate', It is a timestamp list. I think <code>df2.map(lambda x: x.strftime('%Y%m%d')</code> can convert timestamp to the format you need.</p>
0
2016-10-19T03:42:02Z
[ "python", "pandas" ]
Control chromium kiosk mode url from python
40,121,382
<p><a href="http://stackoverflow.com/questions/30123632/using-python-to-start-a-browser-chromium-and-change-the-url">Using Python to start a browser (Chromium) and change the url</a></p> <p>The linked question is asking exactly what I want but I don't know how to implement the answer that is just to uses Selenium. </p> <p>I just need to load chromium in kiosk mode and load a local html page I have does this with <code>os.system('chromium-browser --kiosk file://.....')</code> but this loads a new window/tab every time so it's not efficient or fast</p>
0
2016-10-19T03:00:48Z
40,122,083
<p>You can add options to selenium's chromedriver, similar to how you would using <code>os.system</code></p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--kiosk") driver = webdriver.Chrome(chrome_options=chrome_options) driver.get("http://example.com") </code></pre> <p>To refresh or reload the page repeatedly, you could do <code>driver.get(url)</code> or <code>driver.refresh()</code> in a <code>while True</code> loop.</p>
0
2016-10-19T04:21:52Z
[ "python", "raspberry-pi" ]
Receive ImportError: cannot import name 'DictVectorizer'
40,121,483
<p>I have installed scikit-learn to a python environment through Anaconda. This is on Ubuntu 14.04. The line in my code it is complaining about is</p> <pre><code>from sklearn.feature_extraction.text import DictVectorizer </code></pre> <p>The error is </p> <pre><code>Import Error: cannot import name 'DictVectorizer' </code></pre> <p>I have tried uninstalling and reinstalling both using Conda and then with Pip. The install succeeds with no error no matter how I install it.</p> <p>If I start a python command line and type the import, no errors are given.</p> <p>Would anyone have any suggestions for how to be able to import the DictVectorizer in my code?</p>
0
2016-10-19T03:10:59Z
40,121,775
<p>I'm unfamiliar with that library. However, looking at the source on github it appears you have the import path wrong.</p> <p><code>from sklearn.feature_extraction import DictVectorizer</code> should work</p>
1
2016-10-19T03:49:59Z
[ "python", "scikit-learn" ]
Clustered Stacked Bar in Python Pandas
40,121,562
<p>I have created a single stacked bar chart but I want to have them clustered. Exactly something like the picture. </p> <p>Wondering if it's possible. </p> <p><a href="https://i.stack.imgur.com/SoxmW.png" rel="nofollow">link to picture</a></p>
-4
2016-10-19T03:22:29Z
40,121,800
<pre><code>df = pd.DataFrame(dict(Subsidy=[3, 3, 3], Bonus=[1, 1, 1], Expense=[2, 2, 2]), list('ABC')) df </code></pre> <p><a href="https://i.stack.imgur.com/OrFdi.png" rel="nofollow"><img src="https://i.stack.imgur.com/OrFdi.png" alt="enter image description here"></a></p> <pre><code>ax = df[['Subsidy', 'Bonus']].plot.bar(stacked=True, position=1, width=.2, ylim=[0, 8], color=['orange', 'red']) df[['Expense']].plot.bar(ax=ax, position=0, width=.2, color=['green']) </code></pre> <p><a href="https://i.stack.imgur.com/TR51i.png" rel="nofollow"><img src="https://i.stack.imgur.com/TR51i.png" alt="enter image description here"></a></p>
3
2016-10-19T03:51:49Z
[ "python", "pandas", "matplotlib" ]
Efficient matrix multiplication in Matlab
40,121,582
<p>I have two matrices, <code>A</code> (N by K) and <code>B</code> (N by M) and I would like to concentrate <code>A</code> and <code>B</code> into a tensor <code>C</code> (N by K by M) where <code>C(n,k,m) = A(n,k) * B(n,m)</code>. I know how to do it in python like </p> <pre><code>C = B[:,numpy.newaxis,:] * A[:,:,numpy.newaxis] </code></pre> <p>Can anyone please tell me the matlab code that does the same thing efficiently?</p>
2
2016-10-19T03:24:54Z
40,123,257
<p>Take advantage of the implicit expansion feature of <a href="https://www.mathworks.com/help/matlab/ref/bsxfun.html" rel="nofollow"><code>bsxfun</code></a>. Use <a href="https://www.mathworks.com/help/matlab/ref/permute.html" rel="nofollow"><code>permute</code></a> to have your <code>B</code> as an Nx1xM matrix:</p> <pre><code>C = bsxfun(@times, A, permute(B, [1, 3, 2])); </code></pre> <p>And from MATLAB <strong>R2016b</strong> onward, you can get the same result in this way:</p> <pre><code>C = A * permute(B, [1, 3, 2]); </code></pre>
2
2016-10-19T05:53:28Z
[ "python", "matlab", "numpy", "matrix", "matrix-multiplication" ]
How to run/interact with a Golang executable in Python?
40,121,657
<p>I have a command-line Golang executable on Windows named <code>cnki-downloader.exe</code> (open-sourced here: <a href="https://github.com/amyhaber/cnki-downloader" rel="nofollow">https://github.com/amyhaber/cnki-downloader</a>). I want to run this executable in Python, and interact with it (get its output, then input something, then get output, and so on)</p> <p>It's a command-line program, so I thought it's the same as a normal Windows command-line program built by MSVC. My code is like this:</p> <pre><code># coding=gbk from subprocess import Popen, PIPE p = Popen(["cnki-downloader.exe"], stdin=PIPE, stdout=PIPE) #p = Popen(["WlanHelper.exe"], stdin=PIPE, stdout=PIPE ) p.stdin.write( 'XXXXXX\n' ) result1 = p.stdout.read() # &lt;---- we never return here print result1 p.stdin.write( '1\n' ) result2 = p.stdout.read() print result2 </code></pre> <p>My Python code halts at the <code>Popen</code> call with <code>cnki-downloader.exe</code> parameter. Then I tried a C command-line program built by MSVC (named <code>WlanHelper.exe</code>), it runs well. My script can get the output from the exe.</p> <p>So I suspect that the command-line mechanism of the Golang executable is different from a native C/C++ program, and it's difficult for other languages (like Python) to call and interact with it.</p> <p>So I want to know <strong>how to interact with a Golang executable on Windows in other languages like Python?</strong>. If this is impossible, I can also consider modifying the Golang program's source code (because it's open source). But I hope I won't go that step. Thanks!</p> <hr> <p><strong>NOTE:</strong></p> <p>If possible, I want to call this Golang executable directly, instead of modifying it into a library and let Python import it. If I have to modify the Golang into a library, why not just remove the interactive manner and make everything into command-line parameters? There's no need to bother writing a Golang library. So please let's assume the Golang program is closed-sourced. I don't think there's no way for Python to call a command-line Golang program. If this is the case, then I think Golang <strong>REALLY</strong> needs to be improved in the interoperability with other languages.</p>
-2
2016-10-19T03:32:15Z
40,123,207
<p>Looking at the <a href="https://docs.python.org/2/library/subprocess.html#popen-objects" rel="nofollow">documentation</a> for the subprocess module you are using, it seems they have a warning about deadlocks using <code>stdout.read()</code> and friends:</p> <blockquote> <p>Warning This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.</p> </blockquote> <p>So, maybe try using <a href="https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow">communicate</a> instead?</p>
1
2016-10-19T05:50:43Z
[ "python", "windows", "go", "command-line" ]
H2O merging of scores with original data set
40,121,673
<p>I'm using H2O to generate predictions on a large data set with user ID as one of the columns. However, once I score the data set the predictions data set does not contain the ID... The only thing that keeps things working is the order of the scores matches the order of the input data set, which is pretty sloppy IMO.</p> <p>Is there a way to instruct H2O to either retain the ID column in the predictions data set or alternatively to add it post-scoring but still in H2O?</p> <p>I'm less excited about bringing the scores to python or R along with the data set with the IDs and using cbind and the likes but please chime in if this is the only option.</p>
1
2016-10-19T03:35:24Z
40,125,551
<p>Yes, you simply need to cbind the information from the frames that you want as your final output. Here is a full example: I'm doing a regression to predict a patient's height based on their age and risk category. (!)</p> <pre><code>import h2o h2o.init() patients = { 'age':[29, 33, 65], 'height':[188, 157, 175.1], 'name':["Tom", "Dick", "Harry"], 'risk':['A', 'B', 'B'] } train = h2o.H2OFrame.from_python( patients, destination_frame="patients" ) m = h2o.estimators.H2ODeepLearningEstimator() m.train(["age","risk"], "height", train) p = m.predict(train) train["name"].cbind(p["predict"]) </code></pre> <p>As I don't have any test data, for the sake of an example I predict on the training data. The final step is to take the columns from <code>train</code> and combine with the columns from <code>p</code>. (With a categorization, you'll get additional columns, which you may or may not want to include.)</p> <p><strong>NOTE:</strong> The cbind operation takes place in your H2O cluster, not on the client. So it works perfectly well if this is 100 million rows of data spread across multiple machines.</p> <p>P.S. Do <code>m.train(["age","height"], "risk", train)</code> to do a categorization instead.</p>
0
2016-10-19T08:05:12Z
[ "python", "h2o" ]
how to convert date-time to epoch in python?
40,121,686
<p>I want this particular date-time to be converted to epoch but it is giving me format error. what format should i use to do the following so that it can be json rendered. "2016-10-14 14:34:14+00:00". I am using python 2.7 and django 1.10</p> <pre><code>stra = "instance[0].Timing" formata = "%Y-%m-%d %H:%M:%S+00:00" timing = calendar.timegm(time.strptime(stra, formata)) return HttpResponse(json.dumps( {'result': 'True' 'timing': timing, })) </code></pre>
0
2016-10-19T03:37:07Z
40,121,732
<p>Option 1, you can use <code>isoformat()</code>:</p> <pre><code>from datetime import datetime print(datetime.utcnow().isoformat()) # '2016-10-19T03:39:40.485521' </code></pre> <p>Option 2, <code>strftime()</code>, do not confuse it with <code>strptime</code>:</p> <pre><code>print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S+00:00')) # '2016-10-19 03:42:58+00:00' </code></pre>
0
2016-10-19T03:43:24Z
[ "python", "json", "django", "datetime", "epoch" ]
how to convert date-time to epoch in python?
40,121,686
<p>I want this particular date-time to be converted to epoch but it is giving me format error. what format should i use to do the following so that it can be json rendered. "2016-10-14 14:34:14+00:00". I am using python 2.7 and django 1.10</p> <pre><code>stra = "instance[0].Timing" formata = "%Y-%m-%d %H:%M:%S+00:00" timing = calendar.timegm(time.strptime(stra, formata)) return HttpResponse(json.dumps( {'result': 'True' 'timing': timing, })) </code></pre>
0
2016-10-19T03:37:07Z
40,123,074
<p>Actually in django datetime object are converted in epoch as following way.</p> <p><strong>Emample 1</strong></p> <pre><code>import datetime current_date = datetime.datetime.now() epoch = int(current_date.strftime("%s")) * 1000 </code></pre> <p><strong>Example 2</strong></p> <pre><code>import datetime date_object = datetime.datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p') epoch = int(date_object.strftime("%s")) * 1000 </code></pre>
0
2016-10-19T05:43:08Z
[ "python", "json", "django", "datetime", "epoch" ]
how to convert date-time to epoch in python?
40,121,686
<p>I want this particular date-time to be converted to epoch but it is giving me format error. what format should i use to do the following so that it can be json rendered. "2016-10-14 14:34:14+00:00". I am using python 2.7 and django 1.10</p> <pre><code>stra = "instance[0].Timing" formata = "%Y-%m-%d %H:%M:%S+00:00" timing = calendar.timegm(time.strptime(stra, formata)) return HttpResponse(json.dumps( {'result': 'True' 'timing': timing, })) </code></pre>
0
2016-10-19T03:37:07Z
40,123,710
<p>This is a literal string, it's not pulling data out of whatever instance you have:</p> <pre><code>stra = "instance[0].Timing" </code></pre> <p>Perhaps you meant the following instead?</p> <pre><code>stra = instance[0].Timing </code></pre>
0
2016-10-19T06:24:19Z
[ "python", "json", "django", "datetime", "epoch" ]
Keep identical values in default dict
40,121,804
<p>I have the following two lists:</p> <pre><code>prefix = ['AGG', 'CAG', 'CAG', 'GAG', 'GGA', 'GGG', 'GGG'] suffix = ['GGG', 'AGG', 'AGG', 'AGG', 'GAG', 'GGA', 'GGG'] </code></pre> <p>I am trying to use defaultdict to get this result:</p> <pre><code>AGG -&gt; GGG CAG -&gt; AGG,AGG GAG -&gt; AGG GGA -&gt; GAG GGG -&gt; GGA,GGG </code></pre> <p>(Yes this is a Rosalind problem for those of you who know. I REALLY want to learn how to use dictionaries effectively though, so I am NOT looking for homework answers. Just dictionary help.) </p> <p>This is my code: </p> <pre><code>from collections import defaultdict nodes = defaultdict(set) for pre, suf in zip(prefix, suffix): nodes[pre].add(suf) for k,v in nodes.items(): print(k,v) </code></pre> <p>This is my result: </p> <pre><code>CAG {'AGG'} GAG {'AGG'} GGG {'GGG', 'GGA'} AGG {'GGG'} GGA {'GAG'} </code></pre> <p>So I have two issues:</p> <p>1) I need AGG, the value for CAG, to be preserved as two identical instances.</p> <p>2) I cannot figure out how to print from my dictionary nicely, without brackets and quotes and to add in the arrow. </p> <p>Thank you in advance! </p>
1
2016-10-19T03:52:11Z
40,121,825
<p>Use a <code>defaultdict</code> of <code>list</code>, instead of <code>set</code>. Sets removes duplicates. </p> <p>Your code is already fine, you'll just have to change the </p> <pre><code>nodes[pre].add(suf) </code></pre> <p>to</p> <pre><code>nodes[pre].append(suf) </code></pre> <p>For the printing, it will be like</p> <pre><code>print('{} -&gt; {}'.format(k, ','.join(v))) </code></pre>
2
2016-10-19T03:54:43Z
[ "python", "defaultdict" ]
Lambda that searches list and increments
40,121,807
<p>Using a Python <code>lambda</code> can you check whether an element exists in another list (of maps) and also increment a variable? I'm attempting to optimise/refactor my code using a lambda but I've gone and confused myself.</p> <p>Below is my existing code that I want to convert to a lambda. Is it possible to do this using one lambda or will I need to use 2 lambdas? Any advice how can I convert it to a lambda/s?</p> <pre><code>current_orders = auth.get_orders() # returns [{'id': 'foo', 'price': 1.99, ...}, ...] deleted_orders = auth.cancel_orders() # returns id's of all cancelled orders [{'id': 'foo'}, {'id': 'bar'}, ...] # Attempting to convert to lambda n_deleted = 0 for del_order in deleted_orders: for order in current_orders: if del_order['id'] == order['id']: n_deleted += 1 # lambda n_deleted = filter(lambda order, n: n += order['id'] in current_orders, deleted_orders) # end if n_deleted != len(orders): logger.error("Failed to cancel all limit orders") </code></pre> <p><em>Note:</em> I know I can say <code>if len(deleted_orders) &lt; len(current_orders): logger.error("Failed to delete ALL orders")</code> but I want to expand my lambda eventually to say <code>...: logger.error("Failed to delete ORDER with ID: %s")</code></p>
0
2016-10-19T03:52:23Z
40,121,831
<p>It is possible to hack around it but <code>lambda</code>s should not mutate, they should return a new result. Also you should not overcomplicate <code>lambda</code>s, they are meant for short quick functions such a <code>key</code> for a <code>sort</code> method</p>
1
2016-10-19T03:55:24Z
[ "python", "lambda" ]
Lambda that searches list and increments
40,121,807
<p>Using a Python <code>lambda</code> can you check whether an element exists in another list (of maps) and also increment a variable? I'm attempting to optimise/refactor my code using a lambda but I've gone and confused myself.</p> <p>Below is my existing code that I want to convert to a lambda. Is it possible to do this using one lambda or will I need to use 2 lambdas? Any advice how can I convert it to a lambda/s?</p> <pre><code>current_orders = auth.get_orders() # returns [{'id': 'foo', 'price': 1.99, ...}, ...] deleted_orders = auth.cancel_orders() # returns id's of all cancelled orders [{'id': 'foo'}, {'id': 'bar'}, ...] # Attempting to convert to lambda n_deleted = 0 for del_order in deleted_orders: for order in current_orders: if del_order['id'] == order['id']: n_deleted += 1 # lambda n_deleted = filter(lambda order, n: n += order['id'] in current_orders, deleted_orders) # end if n_deleted != len(orders): logger.error("Failed to cancel all limit orders") </code></pre> <p><em>Note:</em> I know I can say <code>if len(deleted_orders) &lt; len(current_orders): logger.error("Failed to delete ALL orders")</code> but I want to expand my lambda eventually to say <code>...: logger.error("Failed to delete ORDER with ID: %s")</code></p>
0
2016-10-19T03:52:23Z
40,121,895
<p>You can't use <code>+=</code> (or assignment of any kind) in a <code>lambda</code> at all, and using <code>filter</code> for side-effects is a terrible idea (this pattern looks kind of like how <code>reduce</code> is used, but it's hard to tell what you're trying to do).</p> <p>It looks like you're trying to count how many <code>order['id']</code> values appear in <code>current_orders</code>. You shouldn't use a <code>lambda</code> for this at all. To improve efficiency, get the <code>id</code>s from out as a <code>set</code> and use <code>set</code> operations to check if all the <code>id</code>s were found in both <code>list</code>:</p> <pre><code>from future_builtins import map # Only on Py2, to get generator based map from operator import itemgetter ... rest of your code ... getid = itemgetter('id') # Creating the `set`s requires a single linear pass, and comparison is # roughly linear as well; your original code had quadratic performance. if set(map(getid, current_orders)) != set(map(getid, deleted_orders)): logger.error("Failed to cancel all limit orders") </code></pre> <p>If you want to know <em>which</em> orders weren't canceled, a slight tweak, replacing the <code>if</code> check and <code>logger</code> output with:</p> <pre><code>for oid in set(map(getid, current_orders)).difference(map(getid, deleted_orders)): logger.error("Failed to cancel order ID %s", oid) </code></pre> <p>If you want the error logs ordered by <code>oid</code>, wrap the <code>set.difference</code> call in <code>sorted</code>, if you want it in the same order returned in <code>current_orders</code>, change to:</p> <pre><code>from itertools import filterfalse # On Py2, it's ifilterfalse # Could inline deletedids creation in filterfalse if you prefer; frozenset optional deletedids = frozenset(map(getid, deleted_orders)) for oid in filterfalse(deletedids.__contains__, map(getid, current_orders)): logger.error("Failed cancel order ID %s", oid) </code></pre>
3
2016-10-19T04:01:42Z
[ "python", "lambda" ]
Lambda that searches list and increments
40,121,807
<p>Using a Python <code>lambda</code> can you check whether an element exists in another list (of maps) and also increment a variable? I'm attempting to optimise/refactor my code using a lambda but I've gone and confused myself.</p> <p>Below is my existing code that I want to convert to a lambda. Is it possible to do this using one lambda or will I need to use 2 lambdas? Any advice how can I convert it to a lambda/s?</p> <pre><code>current_orders = auth.get_orders() # returns [{'id': 'foo', 'price': 1.99, ...}, ...] deleted_orders = auth.cancel_orders() # returns id's of all cancelled orders [{'id': 'foo'}, {'id': 'bar'}, ...] # Attempting to convert to lambda n_deleted = 0 for del_order in deleted_orders: for order in current_orders: if del_order['id'] == order['id']: n_deleted += 1 # lambda n_deleted = filter(lambda order, n: n += order['id'] in current_orders, deleted_orders) # end if n_deleted != len(orders): logger.error("Failed to cancel all limit orders") </code></pre> <p><em>Note:</em> I know I can say <code>if len(deleted_orders) &lt; len(current_orders): logger.error("Failed to delete ALL orders")</code> but I want to expand my lambda eventually to say <code>...: logger.error("Failed to delete ORDER with ID: %s")</code></p>
0
2016-10-19T03:52:23Z
40,121,956
<p>Probably you should be using a list comprehension. eg</p> <pre><code>current_order_ids = {order['id'] for order in current_orders} not_del = [order for order in deleted_orders if order['id'] not in current_order_ids] for order in not_del: logger.error("Failed to delete ORDER with ID: %s", order['id']) </code></pre>
1
2016-10-19T04:08:20Z
[ "python", "lambda" ]
Extracting year from string in python
40,121,822
<p>How can I parse the foll. in python to extract the year:</p> <pre><code>'years since 1250-01-01 0:0:0' </code></pre> <p>The answer should be 1250</p>
-1
2016-10-19T03:54:28Z
40,121,869
<p>There are all sorts of ways to do it, here are several options:</p> <ul> <li><p><a href="https://pypi.python.org/pypi/python-dateutil" rel="nofollow"><code>dateutil</code> parser</a> in a "fuzzy" mode:</p> <pre><code>In [1]: s = 'years since 1250-01-01 0:0:0' In [2]: from dateutil.parser import parse In [3]: parse(s, fuzzy=True).year # resulting year would be an integer Out[3]: 1250 </code></pre></li> <li><p>regular expressions with a <em>capturing group</em>:</p> <pre><code>In [2]: import re In [3]: re.search(r"years since (\d{4})", s).group(1) Out[3]: '1250' </code></pre></li> <li><p>splitting by "since" and then by a dash:</p> <pre><code>In [2]: s.split("since", 1)[1].split("-", 1)[0].strip() Out[2]: '1250' </code></pre></li> <li><p>or may be even splitting by the first dash and slicing the first substring:</p> <pre><code>In [2]: s.split("-", 1)[0][-4:] Out[2]: '1250' </code></pre></li> </ul> <p>The last two involve more "moving parts" and might not be applicable depending on possible variations of the input string.</p>
6
2016-10-19T03:59:30Z
[ "python", "regex" ]
Extracting year from string in python
40,121,822
<p>How can I parse the foll. in python to extract the year:</p> <pre><code>'years since 1250-01-01 0:0:0' </code></pre> <p>The answer should be 1250</p>
-1
2016-10-19T03:54:28Z
40,121,870
<p>You can use a regex with a capture group around the four digits, while also making sure you have a particular pattern around it. I would probably look for something that:</p> <ul> <li><p>4 digits and a capture <code>(\d{4})</code></p></li> <li><p>hyphen <code>-</code></p></li> <li><p>two digits <code>\d{2}</code></p></li> <li><p>hyphen <code>-</code></p></li> <li><p>two digits <code>\d{2}</code></p></li> </ul> <p>Giving: <code>(\d{4})-\d{2}-\d{2}</code></p> <p>Demo:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; d = re.findall('(\d{4})-\d{2}-\d{2}', 'years since 1250-01-01 0:0:0') &gt;&gt;&gt; d ['1250'] &gt;&gt;&gt; d[0] '1250' </code></pre> <p>if you need it as an int, just cast it as such:</p> <pre><code>&gt;&gt;&gt; int(d[0]) 1250 </code></pre>
4
2016-10-19T03:59:46Z
[ "python", "regex" ]
Extracting year from string in python
40,121,822
<p>How can I parse the foll. in python to extract the year:</p> <pre><code>'years since 1250-01-01 0:0:0' </code></pre> <p>The answer should be 1250</p>
-1
2016-10-19T03:54:28Z
40,121,874
<p>The following regex should make the four digit year available as the first capture group:</p> <pre><code>^.*\(d{4})-\d{2}-\d{2}.*$ </code></pre>
3
2016-10-19T04:00:07Z
[ "python", "regex" ]
Compare list of dictionary in Robot Framework
40,121,844
<p>I have two list of list of dictionary and i want to compare the vale of first list dictionary to second list of dictionary</p> <p>For example:</p> <pre><code>Dictionary A contains [{Name:C}, {Name:A}, {Name:B}] Dictionary B contains [{Name:A}, {Name:B}, {Name:C}] </code></pre> <p>How to take A's 1st Dictionary {Name:C} and check if it exists in Dictionary B. </p>
0
2016-10-19T03:57:28Z
40,121,904
<p>You want to see if some list of dictionaries contains at least one dictionary that maps <code>'name': 'C'</code> ?</p> <pre><code>any(d['name'] == 'C' for d in list_of_dict if 'name' in dict) </code></pre>
0
2016-10-19T04:02:41Z
[ "python", "list", "dictionary", "robotframework" ]
Compare list of dictionary in Robot Framework
40,121,844
<p>I have two list of list of dictionary and i want to compare the vale of first list dictionary to second list of dictionary</p> <p>For example:</p> <pre><code>Dictionary A contains [{Name:C}, {Name:A}, {Name:B}] Dictionary B contains [{Name:A}, {Name:B}, {Name:C}] </code></pre> <p>How to take A's 1st Dictionary {Name:C} and check if it exists in Dictionary B. </p>
0
2016-10-19T03:57:28Z
40,142,587
<p>If I understand your question correctly, you should be able to do this using the built in Collections library. This code took the values in one dictionary and checked to see if the value exists in the other. </p> <pre><code>*** Settings *** Library Collections *** Variables *** &amp;{DICTONARY_ONE} = name1=a name2=b name3=c name4=d &amp;{DICTONARY_TWO} = name1=c name2=a name3=d name4=b *** Test Cases *** Dictonary Test @{dictonary2_list} = Get Dictionary Values ${DICTONARY_TWO} :For ${item} in @{dictonary2_list} \ Dictionary Should Contain Value ${DICTONARY_ONE} ${item} </code></pre> <p>If this is not quite what you are after, there should be something in collections that will let you do what you need. Here is a link to the documentation.<br> <a href="http://robotframework.org/robotframework/latest/libraries/Collections.html" rel="nofollow">http://robotframework.org/robotframework/latest/libraries/Collections.html</a></p> <p>I hope that helps.</p>
0
2016-10-19T22:32:06Z
[ "python", "list", "dictionary", "robotframework" ]
how can I test for ordered subset
40,121,871
<p><strong><em>firstly</em></strong><br> I need to be able to test that <code>'abc'</code> is an ordered subset of <code>'axbyc'</code> and <code>'egd'</code> is not an ordered subset of <code>'edg'</code>. Another way to say it is that it is an ordered subset if I can remove specific characters of of one string and have it be equal to another.</p> <p><strong><em>secondly</em></strong><br> I need to compare one <code>pd.Series</code> with another <code>pd.Series</code> to determine if the elements of one are ordered subsets of the corresponding element of the other.</p> <p>consider the <code>pd.Series</code> <code>s1</code> and <code>s2</code></p> <pre><code>s1 = pd.Series(['abc', 'egd']) s2 = pd.Series(['axbyc', 'edg']) </code></pre> <p>I need to compare them such that the results of the question<br> Are the elements of <code>s1</code> ordered subsets of <code>s2</code> equals</p> <pre><code>0 True 1 False dtype: bool </code></pre>
3
2016-10-19T03:59:56Z
40,121,920
<p>For the first part of the question:</p> <pre><code>def ordered_subset(s1, s2): s2 = iter(s2) try: for c in s1: while next(s2) != c: pass else: return True except StopIteration: return False </code></pre> <p>For the second part of the question:</p> <pre><code>pd.concat([s1, s2], axis=1).apply(lambda x: ordered_subset(*x), axis=1) 0 True 1 False dtype: bool </code></pre>
2
2016-10-19T04:04:18Z
[ "python", "pandas" ]
how can I test for ordered subset
40,121,871
<p><strong><em>firstly</em></strong><br> I need to be able to test that <code>'abc'</code> is an ordered subset of <code>'axbyc'</code> and <code>'egd'</code> is not an ordered subset of <code>'edg'</code>. Another way to say it is that it is an ordered subset if I can remove specific characters of of one string and have it be equal to another.</p> <p><strong><em>secondly</em></strong><br> I need to compare one <code>pd.Series</code> with another <code>pd.Series</code> to determine if the elements of one are ordered subsets of the corresponding element of the other.</p> <p>consider the <code>pd.Series</code> <code>s1</code> and <code>s2</code></p> <pre><code>s1 = pd.Series(['abc', 'egd']) s2 = pd.Series(['axbyc', 'edg']) </code></pre> <p>I need to compare them such that the results of the question<br> Are the elements of <code>s1</code> ordered subsets of <code>s2</code> equals</p> <pre><code>0 True 1 False dtype: bool </code></pre>
3
2016-10-19T03:59:56Z
40,122,385
<p>use <code>'.*'.join</code> to create a regex pattern to match against sequence.</p> <pre><code>import re import pandas as pd s1 = pd.Series(['abc', 'egd']) s2 = pd.Series(['axbyc', 'edg']) match = lambda x: bool(re.match(*x)) pd.concat([s1.str.join('.*'), s2], axis=1).T.apply(match) 0 True 1 False dtype: bool </code></pre> <hr> <p>Notice that</p> <pre><code>s1.str.join('.*') 0 a.*b.*c 1 e.*g.*d Name: x, dtype: object </code></pre>
2
2016-10-19T04:51:35Z
[ "python", "pandas" ]
How to find 5 consecutive increasing/decreasing key/value pairs in dict based on the value
40,121,905
<p>I am a DBA and trying to get some data as per management request. I am also new to python. I have input like below(Few hundreds of records) with out the headers Date and Value. I put this data into a dictionary (Date as key). Now I am trying to loop through the dictionary for trying to find any 5 consecutive rows with either ascending or descending values (NOT Keys). Also I am looking for exactly 5 consecutive values not >5.</p> <pre><code>Date value 2015-11-16 112.33 2015-11-17 116.12 2015-11-18 115.52 2015-11-19 117.51 2015-11-20 117.91 2015-11-23 118.07 2015-11-24 119.35 2015-11-25 117.23 2015-11-27 118.43 2015-11-30 117.41 2015-12-01 116.82 2015-12-02 116.13 2015-12-03 114.83 2015-12-04 117.25 </code></pre> <p>For the above input data I am expecting the following output:</p> <pre><code>(5 consecutive ascending values) 2015-11-18 115.52 2015-11-19 117.51 2015-11-20 117.91 2015-11-23 118.07 2015-11-24 119.35 </code></pre> <p>and</p> <pre><code>(5 consecutive descending values) 2015-11-27 118.43 2015-11-30 117.41 2015-12-01 116.82 2015-12-02 116.13 2015-12-03 114.83 </code></pre> <p>What is the best way to approach this problem?</p>
0
2016-10-19T04:02:48Z
40,125,096
<p>The following approach should work for Python 2. It is best to work with the data as a list ordered by date, so it first converts the dictionary into an ordered list based on the dates.</p> <p>It then creates a list comparing each adjacent entry, if it ascends it stores <code>1</code>, equal <code>0</code> and descending <code>-1</code>. It then uses the <code>groupby()</code> to group this list into similar values. If the length of each group is exactly 4, then you have a run of 5 entries:</p> <pre><code>import itertools def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = itertools.tee(iterable) next(b, None) return itertools.izip(a, b) data = { "2015-11-16" : "112.33", "2015-11-17" : "116.12", "2015-11-18" : "115.52", "2015-11-19" : "117.51", "2015-11-20" : "117.91", "2015-11-23" : "118.07", "2015-11-24" : "119.35", "2015-11-25" : "117.23", "2015-11-27" : "118.43", "2015-11-30" : "117.41", "2015-12-01" : "116.82", "2015-12-02" : "116.13", "2015-12-03" : "114.83", "2015-12-04" : "117.25"} # Convert dict back to an ordered list sorted_by_date = [[k, data[k]] for k in sorted(data.keys())] # Compare adjacent entries data_cmp = [[cmp(v2[1], v1[1]), v1, v2] for v1, v2 in pairwise(sorted_by_date)] for k, g in itertools.groupby(data_cmp, key=lambda x: x[0]): elements = list(g) if len(elements) == 4: if k == 1: print "Ascending", [v1 for c, v1, v2 in elements] + [v2] else: print "Descending", [v1 for c, v1, v2 in elements] + [v2] </code></pre> <p>This would give you the following output:</p> <pre class="lang-none prettyprint-override"><code>Ascending [['2015-11-18', '115.52'], ['2015-11-19', '117.51'], ['2015-11-20', '117.91'], ['2015-11-23', '118.07'], ['2015-11-24', '119.35']] Descending [['2015-11-27', '118.43'], ['2015-11-30', '117.41'], ['2015-12-01', '116.82'], ['2015-12-02', '116.13'], ['2015-12-03', '114.83']] </code></pre> <p>If you are using Python 3, <code>cmp()</code> will need to be coded. </p> <p><a href="https://docs.python.org/2/library/itertools.html?highlight=pairwise#recipes" rel="nofollow"><code>pairwise()</code></a> is a well know Python recipe for reading consecutive entry pairs out of a list.</p>
0
2016-10-19T07:41:58Z
[ "python", "date", "dictionary", "collections" ]
Wrong output when trying to print out mouse position
40,121,925
<p>I'm trying to make a function which continually prints out the mouse position constantly until stopped. import pyautogui</p> <pre><code>import pyautogui print('Press CTRL + "c" to stop') while True: try: x, y = pyautogui.position() positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) print(positionStr, end = ' ') print('\b' * len(positionStr), end = '', flush = True) except KeyboardInterrupt: print('\nDone') break </code></pre> <p>The expected output should look something like this:</p> <p><em>X: 265 Y:634</em> <em>only one line continually refreshed</em></p> <p>But this is what I'm getting instead:</p> <p>XXXXXXXXXXXXXXXXXXX: 665 Y: 587</p> <p>XXXXXXXXXXXXXXXXX: 665 Y: 587 </p> <p>XXXXXXXXXXXXXXXXXXXX: 665 Y: 587 </p> <p>XXXXXXXXXX: 718 Y: 598 </p> <p>XXXXXXXXXXXX: 1268 Y: 766 </p> <p><em>remove the \b characters</em> import pyautogui</p> <pre><code>print('Press CTRL + "c" to stop') while True: try: x, y = pyautogui.position() positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) print(positionStr) print('\b' * len(positionStr), end = '', flush = True) except KeyboardInterrupt: print('\nDone') break </code></pre> <p><em>X: 830 Y: 543</em></p> <p><em>X: 830 Y: 543</em></p> <p><em>X: 830 Y: 543</em></p> <p><em>X: 830 Y: 543</em></p> <p>Done</p>
1
2016-10-19T04:04:40Z
40,122,096
<p>You are not backspacing enough characters. You forgot to account for the extra space "end" character. Of course you should be able to leave out the <code>end</code> parameter entirely.</p>
1
2016-10-19T04:23:53Z
[ "python", "debugging", "pyautogui" ]
Wrong output when trying to print out mouse position
40,121,925
<p>I'm trying to make a function which continually prints out the mouse position constantly until stopped. import pyautogui</p> <pre><code>import pyautogui print('Press CTRL + "c" to stop') while True: try: x, y = pyautogui.position() positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) print(positionStr, end = ' ') print('\b' * len(positionStr), end = '', flush = True) except KeyboardInterrupt: print('\nDone') break </code></pre> <p>The expected output should look something like this:</p> <p><em>X: 265 Y:634</em> <em>only one line continually refreshed</em></p> <p>But this is what I'm getting instead:</p> <p>XXXXXXXXXXXXXXXXXXX: 665 Y: 587</p> <p>XXXXXXXXXXXXXXXXX: 665 Y: 587 </p> <p>XXXXXXXXXXXXXXXXXXXX: 665 Y: 587 </p> <p>XXXXXXXXXX: 718 Y: 598 </p> <p>XXXXXXXXXXXX: 1268 Y: 766 </p> <p><em>remove the \b characters</em> import pyautogui</p> <pre><code>print('Press CTRL + "c" to stop') while True: try: x, y = pyautogui.position() positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) print(positionStr) print('\b' * len(positionStr), end = '', flush = True) except KeyboardInterrupt: print('\nDone') break </code></pre> <p><em>X: 830 Y: 543</em></p> <p><em>X: 830 Y: 543</em></p> <p><em>X: 830 Y: 543</em></p> <p><em>X: 830 Y: 543</em></p> <p>Done</p>
1
2016-10-19T04:04:40Z
40,122,177
<p>You could print the line with a Carriage Return : </p> <p>i.e. : </p> <pre><code>print(positionStr + '\r'), </code></pre> <p>Like so, the next line will replace the existing one. And you'll always see one line updated with the new mouse position. </p> <p>The full script :</p> <pre><code>#!/usr/bin/env python import pyautogui print('Press CTRL + "c" to stop') while True: try: x, y = pyautogui.position() positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) print(positionStr + '\r'), except KeyboardInterrupt: print('\nDone') break </code></pre> <p>Hope it helps.</p> <p><strong>EDIT</strong> </p> <p>As said in below comments, this solution will works on Unix platform but was not tested on others. It should break since the different line ending conventions. Thanks to @Code-Apprentice who's pointed it out. </p> <p><strong>RE-EDIT</strong> </p> <p>Since the comments of OP and Code-Apprentice, I tried to fix the script like this and it works like expected : </p> <pre><code>import pyautogui print('Press CTRL + "c" to stop') while True: try: x, y = pyautogui.position() positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) print(positionStr, end=' ') print('\b' * (len(positionStr) + 1), end='') except KeyboardInterrupt: print('\nDone') break </code></pre>
3
2016-10-19T04:31:49Z
[ "python", "debugging", "pyautogui" ]
Python script to count pixel values fails on a less-than/greater-than comparison
40,121,953
<p>I wrote a short script to count the pixel values in an image:</p> <pre><code>import os import sys import cv2 import numpy as np imn = (sys.argv[1]) a = cv2.imread(imn, 0) b = cv2.imread(imn, 1) c = cv2.GaussianBlur(cv2.imread(imn, 0), (7,7), 2) def NC(img): y = img.reshape(1, -1) numA = (y &lt; 127.5).sum() numB = (y &gt; 127.5).sum() return ({'less': numA, 'greater': numB}) aa = NC(a) bb = NC(b) cc = NC(c) print "File: {}".format(imn.split('/')[-1]) print "Image: {} - Set: {}".format('A', aa) print "Image: {} - Set: {}".format('B', bb) print "Image: {} - Set: {}".format('C', cc) </code></pre> <p>And it works perfectly:</p> <pre><code>File: ObamaBidenSituationRoom.jpg Image: A - Set: {'greater': 480558, 'less': 611282} Image: B - Set: {'greater': 1441948, 'less': 1833572} Image: C - Set: {'greater': 471559, 'less': 620281} </code></pre> <p>But when I tried to expand it:</p> <pre><code>def NC(img): y = img.reshape(1, -1) numA = (00.99 &lt; y &lt; 85.00).sum() numB = (85.00 &lt; y &lt; 170.0).sum() numC = (170.0 &lt; y &lt; 256.0).sum() return ({'low': numA, 'middle': numB, 'high': numC}) </code></pre> <p>It gave me an error:</p> <pre><code>Traceback (most recent call last): File "Bins--02.py", line 25, in &lt;module&gt; aa = NC(a) File "Bins--02.py", line 17, in NC numA = (00.99 &lt; y &lt; 85.00).sum() ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() </code></pre> <p>I got this image a while ago, but that was with a matplotlib library that I ended up not using. Why is it coming up here? Am I bounding that greater-than/less-than signs wrong? I tried to fix it</p> <p><code>numA = (00.99 &lt; y).sum() and (y &lt; 85.00).sum()</code></p> <p>But that just gave me random super high values.</p> <p><strong><em>UPDATE - Oct20</em></strong></p> <p>So, I changed it:</p> <pre><code>def NC(img): x = img.reshape(1, -1) numA = x[np.where((00.99 &lt; x) &amp; (x &lt; 85.00))].sum() numB = x[np.where((85.00 &lt; x) &amp; (x &lt; 170.0))].sum() numC = x[np.where((170.0 &lt; x) &amp; (x &lt; 256.0))].sum() numD = x.shape return ({'total': numD, 'low': numA, 'middle': numB, 'high': numC}) </code></pre> <p>And now it works, but there's a problem: the pixel counts don't match up. </p> <pre><code>Image: lenna.png Image: A Set:{'high': 8367459, 'middle': 20278460, 'total': (1, 262144), 'low': 3455619} Image: B Set:{'high': 45250935, 'middle': 43098232, 'total': (1, 786432), 'low': 11609051} Image: C Set:{'high': 8216989, 'middle': 20633144, 'total': (1, 262144), 'low': 3531090} </code></pre> <p>The measurements are pixels, there can't be more than the total. Where am I getting 2 million from?</p> <p>For example, I ran it on a 100x100 image of a blue circle: </p> <pre><code>Image: lightblue.png Image: A Set:{'high': 0, 'middle': 1035999, 'total': (1, 10000), 'low': 0} Image: B Set:{'high': 1758789, 'middle': 1212681, 'total': (1, 30000), 'low': 417612} Image: C Set:{'high': 0, 'middle': 1014135, 'total': (1, 10000), 'low': 31801} </code></pre> <p>and it's completely wrong.</p> <p><strong><em>Edit Two</em></strong></p> <p>I just ran it on a test array:</p> <pre><code>i = np.array([[1, 1, 1, 1, 1, 1, 1, 1], [3, 3, 3, 3, 3, 3, 3, 3], [200, 200, 200, 200, 200, 200, 200, 200]]) def NC(img): x = img.reshape(1, -1) numA = x[np.where((00.99 &lt; x) &amp; (x &lt; 85.00))].sum() numB = x[np.where((85.00 &lt; x) &amp; (x &lt; 170.0))].sum() numC = x[np.where((170.0 &lt; x) &amp; (x &lt; 256.0))].sum() numD = (img.shape[0] * img.shape[1]) return ({'total': numD, 'low': numA, 'middle': numB, 'high': numC}) aa = NC(i) bb = NC(i) cc = NC(i) print "Image: {} Set:{}".format('A', aa) print "Image: {} Set:{}".format('B', bb) print "Image: {} Set:{}".format('C', cc) </code></pre> <p>And it's entirely broken:</p> <pre><code>Image: A Set:{'high': 1600, 'middle': 0, 'total': 24, 'low': 32} Image: B Set:{'high': 1600, 'middle': 0, 'total': 24, 'low': 32} Image: C Set:{'high': 1600, 'middle': 0, 'total': 24, 'low': 32} </code></pre> <p>Why is it doing this?</p>
0
2016-10-19T04:08:02Z
40,128,144
<p>There are a couple of issues with your approach.</p> <p>When you do</p> <pre><code>(y &lt; 85.00).sum() </code></pre> <p>You're actually summing over the truth condition. So you end up counting where the condition evaluates to <code>True</code>. You can easily see it with a quick example:</p> <pre><code>In [6]: x = np.arange(10) In [7]: x Out[7]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) In [8]: x &lt; 4 Out[8]: array([ True, True, True, True, False, False, False, False, False, False], dtype=bool) In [9]: (x &lt; 4).sum() Out[9]: 4 </code></pre> <p>Now if you want to get the indices where the condition is satisfied, you can use <code>np.where</code></p> <pre><code>In [10]: np.where(x &lt; 4) Out[10]: (array([0, 1, 2, 3]),) </code></pre> <p>And use them for your sum</p> <pre><code>In [11]: x[np.where(x &lt; 4)].sum() Out[11]: 6 </code></pre> <p>The other issue comes from using the compact notation for the range which is easily solved splitting it in two with <code>&amp;</code> or <code>np.logical_and()</code></p> <pre><code>In [12]: x[np.where((2 &lt; x) &amp; (x &lt; 6))].sum() Out[12]: 12 </code></pre>
1
2016-10-19T10:02:28Z
[ "python", "arrays", "numpy", "operators", "truthiness" ]
Python SQLite TypeError
40,121,980
<pre><code>from sqlite3 import * def insert_record(Who, Invented): connection = connect(database = "activity.db") internet = connection.cursor() list = "INSERT INTO Information VALUES((Alexander_Graham, Phone))" internet.execute(list) rows_inserted = internet.rowcount connection.commit() internet.close() connection.close() #GUI interface from Tkinter import * window = Tk() the_button3 = Button(window, text='Record', command = insert_record).grid(row=1, sticky=W, padx=100,pady=5) window.mainloop() </code></pre> <p>Alright, so what I'm trying to do is when I press the Record button, the values for Information (it have 2 fields called Who and Invented, respectively) in activity.db will add a record Alexander_Graham and Phone.</p> <p>*activity.db is already premade in the same folder as the code</p> <p>But instead I get this error: TypeError: insert_record() takes exactly 2 arguments (0 given)</p> <p>How do I fix it? </p>
-1
2016-10-19T04:12:01Z
40,122,363
<p>insert record is a function that takes two required arguments, which you didn't pass values in for.</p> <pre><code>command = insert_record </code></pre> <p>A good example of this in action is the following test sequence:</p> <pre><code>In [1]: def func(one,two): ...: return one+two ...: In [2]: func() ------------------------------------------------------------------------- -- TypeError Traceback (most recent call last) &lt;ipython-input-2-08a2da4138f6&gt; in &lt;module&gt;() ----&gt; 1 func() TypeError: func() takes exactly 2 arguments (0 given) In [3]: func(1,3) Out[3]: 4 </code></pre> <p>In this function, it fails in the same was as your tk app. You need to provide a function that has default values, or handle it a different way.</p>
0
2016-10-19T04:49:29Z
[ "python", "sqlite" ]
Python SQLite TypeError
40,121,980
<pre><code>from sqlite3 import * def insert_record(Who, Invented): connection = connect(database = "activity.db") internet = connection.cursor() list = "INSERT INTO Information VALUES((Alexander_Graham, Phone))" internet.execute(list) rows_inserted = internet.rowcount connection.commit() internet.close() connection.close() #GUI interface from Tkinter import * window = Tk() the_button3 = Button(window, text='Record', command = insert_record).grid(row=1, sticky=W, padx=100,pady=5) window.mainloop() </code></pre> <p>Alright, so what I'm trying to do is when I press the Record button, the values for Information (it have 2 fields called Who and Invented, respectively) in activity.db will add a record Alexander_Graham and Phone.</p> <p>*activity.db is already premade in the same folder as the code</p> <p>But instead I get this error: TypeError: insert_record() takes exactly 2 arguments (0 given)</p> <p>How do I fix it? </p>
-1
2016-10-19T04:12:01Z
40,122,395
<p>When you press button then tkinter runs function <code>insert_record()</code> always without any arguments. </p> <p>You have to define function without arguments too.</p> <pre><code>def insert_record(): </code></pre> <p>Or with with default values ie.</p> <pre><code>def insert_record(Who=None, Invented=None): </code></pre> <p>Or you have to assign function with arguments - you can do it using <code>lambda</code></p> <pre><code>command=lambda:inser_record("Thomas Edison", "Bulb") </code></pre>
0
2016-10-19T04:52:22Z
[ "python", "sqlite" ]
Python: find a series of Chinese characters within a string and apply a function
40,122,058
<p>I've got a series of text that is mostly English, but contains some phrases with Chinese characters. Here's two examples:</p> <pre><code>s1 = "You say: 你好. I say: 再見" s2 = "答案, my friend, 在風在吹" </code></pre> <p>I'm trying to find each block of Chinese, apply a function which will translate the text (I already have a way to do the translation), then replace the translated text in the string. So the output would be something like this:</p> <pre><code>o1 = "You say: hello. I say: goodbye" o2 = "The answer, my friend, is blowing in the wind" </code></pre> <p>I can find the Chinese characters easily by doing this:</p> <pre><code>utf_line = s1.decode('utf-8') re.findall(ur'[\u4e00-\u9fff]+',utf_line) </code></pre> <p>...But I end up with a list of all the Chinese characters and no way of determining where each phrase begins and ends.</p>
1
2016-10-19T04:19:08Z
40,122,136
<p>A possible solution is to capture everything, but in different capture groups, so you can differentiate later if they're in Chinese or not.</p> <pre><code>ret = re.findall(ur'([\u4e00-\u9fff]+)|([^\u4e00-\u9fff]+)', utf_line) result = [] for match in ret: if match[0]: result.append(translate(match[0])) else: result.append(match[1]) print(''.join(result)) </code></pre>
2
2016-10-19T04:27:59Z
[ "python", "regex" ]
Python: find a series of Chinese characters within a string and apply a function
40,122,058
<p>I've got a series of text that is mostly English, but contains some phrases with Chinese characters. Here's two examples:</p> <pre><code>s1 = "You say: 你好. I say: 再見" s2 = "答案, my friend, 在風在吹" </code></pre> <p>I'm trying to find each block of Chinese, apply a function which will translate the text (I already have a way to do the translation), then replace the translated text in the string. So the output would be something like this:</p> <pre><code>o1 = "You say: hello. I say: goodbye" o2 = "The answer, my friend, is blowing in the wind" </code></pre> <p>I can find the Chinese characters easily by doing this:</p> <pre><code>utf_line = s1.decode('utf-8') re.findall(ur'[\u4e00-\u9fff]+',utf_line) </code></pre> <p>...But I end up with a list of all the Chinese characters and no way of determining where each phrase begins and ends.</p>
1
2016-10-19T04:19:08Z
40,122,721
<p>Regular expression <code>Match</code> objects give you the start and end indexes of a match. So, instead of <code>findall</code>, do your own search and record the indexes as you go. Then, you can translate each extent and replace in the string based on the known indexes of the phrases.</p> <pre><code>import re _scan_chinese_re = re.compile(r'[\u4e00-\u9fff]+') s1 = "You say: 你好. I say: 再見" s2 = "答案, my friend, 在風在吹" def translator(chinese_text): """My no good translator""" return ' '.join('??' for _ in chinese_text) def scanner(text): """Scan text string, translate chinese and return copy""" print('----&gt; text:', text) # list of extents where chinese text is found chinese_inserts = [] # [start, end] # keep scanning text to end index = 0 while index &lt; len(text): m = _scan_chinese_re.search(text[index:]) if not m: break # get extent from match object and add to list start = index + m.start() end = index + m.end() print('chinese at index', start, text[start:end]) chinese_inserts.append([start, end]) index += end # copy string and replace backwards so we don't mess up indexes copy = list(text) while chinese_inserts: start, end = chinese_inserts.pop() copy[start:end] = translator(text[start:end]) text = ''.join(copy) print('final', text) return text scanner(s1) scanner(s2) </code></pre> <p>With my questionable translator, the result is</p> <pre><code>----&gt; text: You say: 你好. I say: 再見 chinese at index 9 你好 chinese at index 20 再見 final You say: ?? ??. I say: ?? ?? ----&gt; text: 答案, my friend, 在風在吹 chinese at index 0 答案 chinese at index 15 在風在吹 final ?? ??, my friend, ?? ?? ?? ?? </code></pre>
0
2016-10-19T05:17:26Z
[ "python", "regex" ]
Python: find a series of Chinese characters within a string and apply a function
40,122,058
<p>I've got a series of text that is mostly English, but contains some phrases with Chinese characters. Here's two examples:</p> <pre><code>s1 = "You say: 你好. I say: 再見" s2 = "答案, my friend, 在風在吹" </code></pre> <p>I'm trying to find each block of Chinese, apply a function which will translate the text (I already have a way to do the translation), then replace the translated text in the string. So the output would be something like this:</p> <pre><code>o1 = "You say: hello. I say: goodbye" o2 = "The answer, my friend, is blowing in the wind" </code></pre> <p>I can find the Chinese characters easily by doing this:</p> <pre><code>utf_line = s1.decode('utf-8') re.findall(ur'[\u4e00-\u9fff]+',utf_line) </code></pre> <p>...But I end up with a list of all the Chinese characters and no way of determining where each phrase begins and ends.</p>
1
2016-10-19T04:19:08Z
40,122,744
<p>You could always use a in-place replace of the matched regular expression by using <code>re.sub()</code> in python.</p> <p>Try this:</p> <pre><code>print(re.sub(r'([\u4e00-\u9fff]+)', translate('\g&lt;0&gt;'), utf_line)) </code></pre>
3
2016-10-19T05:19:05Z
[ "python", "regex" ]
Python: find a series of Chinese characters within a string and apply a function
40,122,058
<p>I've got a series of text that is mostly English, but contains some phrases with Chinese characters. Here's two examples:</p> <pre><code>s1 = "You say: 你好. I say: 再見" s2 = "答案, my friend, 在風在吹" </code></pre> <p>I'm trying to find each block of Chinese, apply a function which will translate the text (I already have a way to do the translation), then replace the translated text in the string. So the output would be something like this:</p> <pre><code>o1 = "You say: hello. I say: goodbye" o2 = "The answer, my friend, is blowing in the wind" </code></pre> <p>I can find the Chinese characters easily by doing this:</p> <pre><code>utf_line = s1.decode('utf-8') re.findall(ur'[\u4e00-\u9fff]+',utf_line) </code></pre> <p>...But I end up with a list of all the Chinese characters and no way of determining where each phrase begins and ends.</p>
1
2016-10-19T04:19:08Z
40,122,821
<p>You can't get the indexes using <a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow">re.findall()</a>. You could use <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow">re.finditer()</a> instead, and refer to <a href="https://docs.python.org/2/library/re.html#re.MatchObject.group" rel="nofollow">m.group()</a>, <a href="https://docs.python.org/2/library/re.html#re.MatchObject.start" rel="nofollow">m.start()</a> and <a href="https://docs.python.org/2/library/re.html#re.MatchObject.end" rel="nofollow">m.end()</a>.</p> <p>However, for your particular case, it seems more practical to call a function using <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow">re.sub()</a>.</p> <blockquote> <p>If <em>repl</em> is a function, it is called for every non-overlapping occurrence of <em>pattern</em>. The function takes a single match object argument, and returns the replacement string</p> </blockquote> <p><strong>Code:</strong></p> <pre class="lang-python prettyprint-override"><code>import re s = "You say: 你好. I say: 再見. 答案, my friend, 在風在吹" utf_line = s.decode('utf-8') dict = {"你好" : "hello", "再見" : "goodbye", "答案" : "The answer", "在風在吹" : "is blowing in the wind", } def translate(m): block = m.group().encode('utf-8') # Do your translation here # this is just an example if block in dict: return dict[ block ] else: return "{unknown}" utf_translated = re.sub(ur'[\u4e00-\u9fff]+', translate, utf_line, re.UNICODE) print utf_translated.encode('utf-8') </code></pre> <p><strong>Output:</strong></p> <pre class="lang-none prettyprint-override"><code>You say: hello. I say: goodbye. The answer, my friend, is blowing in the wind </code></pre> <ul> <li><a href="http://ideone.com/Dq1muC" rel="nofollow">Ideone demo</a></li> </ul>
2
2016-10-19T05:24:54Z
[ "python", "regex" ]
Why sparse matrix computing on python is too slow
40,122,077
<p>The format I have used is the csr sparse matrix, which is recommended to be the fastest sparse structure for add and dot opertor. I compared its performance with the add and dot operator of np.array. However, it seems very weird that the computing for sparse matrix is much slower than the case under dense format. Why is it? And is there any more efficient way to implement sparse computing?</p> <pre><code>import numpy as np import scipy.sparse as sp import random #%% generate dense vector vector_length = 10000 nonzero_term = 200 x = np.zeros((vector_length, )) y = np.zeros((vector_length, )) index = random.sample(range(vector_length), nonzero_term) x[index] = np.random.rand(nonzero_term) index = random.sample(range(vector_length), nonzero_term) y[index] = np.random.rand(nonzero_term) #%% transform to sparse vector x_sp = sp.csr_matrix(x) y_sp = sp.csr_matrix(y) #%% test # dense add %timeit [x + y] # sparse add %timeit [x_sp + y_sp] # dense dot %timeit [x.dot(y)] # sparse dot %timeit [x_sp.dot(y_sp.T)] </code></pre> <p>and the result shows</p> <pre><code>100000 loops, best of 3: 6.06 µs per loop 10000 loops, best of 3: 97.8 µs per loop 100000 loops, best of 3: 3.45 µs per loop 1000 loops, best of 3: 225 µs per loop </code></pre>
2
2016-10-19T04:21:41Z
40,122,715
<p>Both sets of operations use compiled code. But the data is stored quite differently.</p> <p><code>x.shape</code> is (10000,); <code>y</code> likewise. <code>x+y</code> just has to allocate an array of the same shape, and efficiently in <code>c</code> step through the 3 data buffers.</p> <p><code>x_sp</code> has 200 nonzero values, the values are in <code>x_sp.data</code> and their column indices in <code>x_sp.indices</code>. There is a third array, <code>x_sp.indptr</code> but with only 2 values. Similarly for <code>y_sp</code>. But to add them, it has to step through 4 arrays, and assign values to two arrays. Even when coded in <code>c</code> there's a lot more work. In my test case <code>x_sp+y_sp</code> has 397 nonzero values. </p> <p>With these 1d arrays (1 row matrices), the <code>dot</code> involves the same sort of stepping through values, only summing them all to one final value.</p> <p>If the density of the matrices is low enough sparse calculations can be faster. That's true, I think, of matrix multiplication more so than addition. </p> <p>In sum, the per element calculation is more complicated with sparse matrices. So even if there are few elements, the overall time tends to longer.</p>
1
2016-10-19T05:17:13Z
[ "python", "performance", "numpy", "scipy", "sparse-matrix" ]
Deleting lines in python
40,122,192
<p>I was just wondering how to delete lines in python.</p> <p>Firstly I have opened up the csv file (using the with statements and whatnot), however the first couple of lines are unneccessary. They go along the lines of this:</p> <p>**version 2.0 keyboard strokes</p> <p>version 1.5 mouse wheel</p> <p>... ..**</p> <p>[data starts here which i will manipulate]</p> <p>Any functions I could use to perheps prompt the user with the number of rows theyd like to delete for future spreadsheets?</p> <pre><code> from __future__ import print_funciton import fileinput import csv with open('filename.csv', delimiter=",") readcsv = csv.reader(csvfile, delimiter=",") skip_rows = int(input('How many rows to skip? ')) for i in range(skip_rows): _ = next(readcsv) for row in readcsv: print(row,end='') </code></pre> <p>Alternatively, I tried this, but it doesnt seem to get rid of the rows that have blank spaces (blank rows included in the number of rows I'd like to delete). Meanwhile, the code above appears to get rid of those blank spaces, but there is line termination.</p> <pre><code> next(filecsv) for i in range(10) </code></pre>
1
2016-10-19T04:32:51Z
40,122,254
<p>You can prompt the user with a simple while loop and listen into <a href="https://docs.python.org/3/library/sys.html#sys.stdin" rel="nofollow">standard input</a> or using the <a href="https://docs.python.org/3/library/functions.html#input" rel="nofollow">input()</a> function. </p> <p>As to your question on how to delete lines in a file, you can read in the file as a list of lines.</p> <pre><code>lines=[] with open('input.txt') as f: lines=f.readlines() </code></pre> <p>You can then write back into the file everything past the lines you want to skip by using <a href="https://docs.python.org/2/tutorial/introduction.html#lists" rel="nofollow">list slicing</a>.</p> <p>Also I am pretty sure similar questions have been asked before, try to Google or search Stack Overflow for your question or a subset of your question next time.</p> <p><strong>P.S.</strong> I also want to add that if you are reading a very large file, it would be better if you read a line at a time, and outputted to a separate file. For a large enough file, you might run out of RAM to hold the file in memory.</p>
0
2016-10-19T04:39:09Z
[ "python", "csv" ]
Deleting lines in python
40,122,192
<p>I was just wondering how to delete lines in python.</p> <p>Firstly I have opened up the csv file (using the with statements and whatnot), however the first couple of lines are unneccessary. They go along the lines of this:</p> <p>**version 2.0 keyboard strokes</p> <p>version 1.5 mouse wheel</p> <p>... ..**</p> <p>[data starts here which i will manipulate]</p> <p>Any functions I could use to perheps prompt the user with the number of rows theyd like to delete for future spreadsheets?</p> <pre><code> from __future__ import print_funciton import fileinput import csv with open('filename.csv', delimiter=",") readcsv = csv.reader(csvfile, delimiter=",") skip_rows = int(input('How many rows to skip? ')) for i in range(skip_rows): _ = next(readcsv) for row in readcsv: print(row,end='') </code></pre> <p>Alternatively, I tried this, but it doesnt seem to get rid of the rows that have blank spaces (blank rows included in the number of rows I'd like to delete). Meanwhile, the code above appears to get rid of those blank spaces, but there is line termination.</p> <pre><code> next(filecsv) for i in range(10) </code></pre>
1
2016-10-19T04:32:51Z
40,122,298
<p>There are quite a few ways to grab input from a command line tool (which is what I am inferring you wrote). Here are a couple:</p> <p><em>Option 1:</em> created in a file called out.py use sys.argv</p> <pre><code>import sys arg1 = sys.argv[1] print("passed in value: %s" % arg1) </code></pre> <p>Then run it by passing in an argument (note index 1, script is index 0)</p> <pre><code>python out.py cell1 passed in value: cell1 </code></pre> <p><em>Option 2:</em></p> <p>A potentially better way is to use a commandline tool framework like click: <a href="http://click.pocoo.org/5/" rel="nofollow">http://click.pocoo.org/5/</a>. This has almost everything you could ever want to do, and they handle much of the hard logic for you.</p>
0
2016-10-19T04:43:21Z
[ "python", "csv" ]
Deleting lines in python
40,122,192
<p>I was just wondering how to delete lines in python.</p> <p>Firstly I have opened up the csv file (using the with statements and whatnot), however the first couple of lines are unneccessary. They go along the lines of this:</p> <p>**version 2.0 keyboard strokes</p> <p>version 1.5 mouse wheel</p> <p>... ..**</p> <p>[data starts here which i will manipulate]</p> <p>Any functions I could use to perheps prompt the user with the number of rows theyd like to delete for future spreadsheets?</p> <pre><code> from __future__ import print_funciton import fileinput import csv with open('filename.csv', delimiter=",") readcsv = csv.reader(csvfile, delimiter=",") skip_rows = int(input('How many rows to skip? ')) for i in range(skip_rows): _ = next(readcsv) for row in readcsv: print(row,end='') </code></pre> <p>Alternatively, I tried this, but it doesnt seem to get rid of the rows that have blank spaces (blank rows included in the number of rows I'd like to delete). Meanwhile, the code above appears to get rid of those blank spaces, but there is line termination.</p> <pre><code> next(filecsv) for i in range(10) </code></pre>
1
2016-10-19T04:32:51Z
40,122,350
<p>Use <a href="https://docs.python.org/3/library/fileinput.html#fileinput.input" rel="nofollow"><code>fileinput.input()</code></a> with the inplace update file option:</p> <pre><code>from __future__ import print_function import fileinput skip_rows = int(input('How many rows to skip? ')) f = fileinput.input('input.csv', inplace=True) for i in range(skip_rows): f.readline() for row in f: print(row, end='') </code></pre> <p>This will skip the first <code>skip_rows</code> rows of the input file and overwrite it without you having to manage writing and moving a temporary file.</p> <p>(You can omit importing <code>print_function</code> if you are using Python 3)</p>
0
2016-10-19T04:48:30Z
[ "python", "csv" ]
Deleting lines in python
40,122,192
<p>I was just wondering how to delete lines in python.</p> <p>Firstly I have opened up the csv file (using the with statements and whatnot), however the first couple of lines are unneccessary. They go along the lines of this:</p> <p>**version 2.0 keyboard strokes</p> <p>version 1.5 mouse wheel</p> <p>... ..**</p> <p>[data starts here which i will manipulate]</p> <p>Any functions I could use to perheps prompt the user with the number of rows theyd like to delete for future spreadsheets?</p> <pre><code> from __future__ import print_funciton import fileinput import csv with open('filename.csv', delimiter=",") readcsv = csv.reader(csvfile, delimiter=",") skip_rows = int(input('How many rows to skip? ')) for i in range(skip_rows): _ = next(readcsv) for row in readcsv: print(row,end='') </code></pre> <p>Alternatively, I tried this, but it doesnt seem to get rid of the rows that have blank spaces (blank rows included in the number of rows I'd like to delete). Meanwhile, the code above appears to get rid of those blank spaces, but there is line termination.</p> <pre><code> next(filecsv) for i in range(10) </code></pre>
1
2016-10-19T04:32:51Z
40,122,525
<blockquote> <p>Firstly I have opened up the csv file [...]</p> </blockquote> <p>Did you consider to use <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> to process your data?<br> If so, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pandas.read_csv</a>, allows to skip lines using the <code>skiprows</code> parameter.</p>
0
2016-10-19T05:02:40Z
[ "python", "csv" ]
Deleting lines in python
40,122,192
<p>I was just wondering how to delete lines in python.</p> <p>Firstly I have opened up the csv file (using the with statements and whatnot), however the first couple of lines are unneccessary. They go along the lines of this:</p> <p>**version 2.0 keyboard strokes</p> <p>version 1.5 mouse wheel</p> <p>... ..**</p> <p>[data starts here which i will manipulate]</p> <p>Any functions I could use to perheps prompt the user with the number of rows theyd like to delete for future spreadsheets?</p> <pre><code> from __future__ import print_funciton import fileinput import csv with open('filename.csv', delimiter=",") readcsv = csv.reader(csvfile, delimiter=",") skip_rows = int(input('How many rows to skip? ')) for i in range(skip_rows): _ = next(readcsv) for row in readcsv: print(row,end='') </code></pre> <p>Alternatively, I tried this, but it doesnt seem to get rid of the rows that have blank spaces (blank rows included in the number of rows I'd like to delete). Meanwhile, the code above appears to get rid of those blank spaces, but there is line termination.</p> <pre><code> next(filecsv) for i in range(10) </code></pre>
1
2016-10-19T04:32:51Z
40,122,865
<p>You will typically use an iterator to read files. You could do something like this:</p> <pre><code>numToSkip = 3 with open('somefile.txt') as f: for i, line in enumerate(f): if i &lt; numToSkip : continue # Do 'whatnot' processing here </code></pre>
0
2016-10-19T05:27:38Z
[ "python", "csv" ]
Submitting large directories in perforce
40,122,226
<p>I would like to know unix command to submit large directories in perforce. we use p4 submit to submit files in the depot. But in the case of directories what is the command to put it in depot in a single shot.</p>
-1
2016-10-19T04:36:31Z
40,123,083
<p>It's still just:</p> <pre><code>p4 submit </code></pre> <p>to submit everything open in your default changelist.</p> <p>If you want to submit all the files under a specific directory, but leave all other files open, do:</p> <pre><code>p4 submit directory/... </code></pre>
1
2016-10-19T05:43:29Z
[ "python", "unix", "perforce" ]
Python : Check an inputs first characters
40,122,354
<p>Okay so i have a problem i looked it up but didnt know exactly what to look up and kept seeing problems that had nothing to do with mine.. So my problem here is im taking an input in python</p> <pre><code>flashSite = raw_input('[?] Please Provide a Web Url : ') </code></pre> <p>After it takes the input i want it to check if the http:// characters are included in the beginning of the input , if they are then dont add them in again , if they arent then add them in for the user , Help is greatly appreciated.. Also im new to Stackoverflow so i will have problems with little things like putting code in comments and such:(</p> <p>edit : So from other answers and comments i came out with this</p> <pre><code>def ScrapeFlashFiles(): flashSite = raw_input('Please Provide a web URL : ') if flashSite.lower().startswith(flashSite, beg=0, end=7('http://')): return flashSite elif flashSite.lower().startswith(flashSite, beg=0, end=4('www.')): flashSite = 'http://' + flashSite print ' Sending requests... ' flashReq = requests.get(flashSite) print ' Scraping content ' flashTree = html.fromstring(flashReq.content) print 'Searching for keyword \'.swf\' ' for line in flashReq.content.split('\n'): if '.swf' in line: print line print 'Flash Scrape Complete..' </code></pre> <p>Am i doing something wrong here?</p> <p>Note i am a beginner.. Im getting an error now talking about an int..</p> <p>Source to where i was reading about the startswith method <a href="https://www.tutorialspoint.com/python/string_startswith.htm" rel="nofollow">https://www.tutorialspoint.com/python/string_startswith.htm</a></p>
0
2016-10-19T04:48:52Z
40,122,477
<p>raw_input returns a string, as visible from the documentation: <a href="https://docs.python.org/2/library/functions.html#" rel="nofollow">https://docs.python.org/2/library/functions.html#</a></p> <p>Since you're working with a string Type, you can use any of the string methods <a href="https://docs.python.org/2/library/stdtypes.html#string-methods" rel="nofollow">https://docs.python.org/2/library/stdtypes.html#string-methods</a>.</p> <p>For example:</p> <pre><code>expected_beginning = 'http://' if not flashSite.startswith(expected_beginning): flashSite = expected_beginning + flashSite </code></pre> <p>You could do interesting things, like make sure it's always lowercase by doing:</p> <pre><code>if not flashSite.lower().startswith(expected_beginning): </code></pre> <p>etc.</p>
1
2016-10-19T04:59:33Z
[ "python", "input", "character" ]
How to separately plot the figures in one big single figure using matplotlib?
40,122,557
<p>I have just started learning <code>Python</code>, I am analyzing a data from <code>.csv</code> file and I want to separate figures, but I am getting all the plots in one graph and I am not able to separate the graphs. Please help!</p> <pre><code>n = 10 i=0 for i in range(0,n): inflammation = matplotlib.pyplot.plot(data[i,:40])#inflammation graph for patient 0 </code></pre> <p>This is the image i got ,but I want separate graphs:</p> <p><a href="https://i.stack.imgur.com/qiH0C.png" rel="nofollow"><img src="https://i.stack.imgur.com/qiH0C.png" alt="enter image description here"></a></p>
0
2016-10-19T05:05:02Z
40,122,904
<p>Just use a new <code>figure()</code></p> <pre><code>n = 10 i=0 for i in range(0,n): matplotlib.pyplot.figure() inflammation = matplotlib.pyplot.plot(data[i,:40]) #inflammation graph for patient 0 </code></pre> <p>Each figure uses a lot of memory. So use it sparingly. Learn about <code>clf()</code> and <code>cla()</code> and <code>savefig()</code> if you have too many figures ...</p>
1
2016-10-19T05:31:32Z
[ "python", "matplotlib" ]
How to separately plot the figures in one big single figure using matplotlib?
40,122,557
<p>I have just started learning <code>Python</code>, I am analyzing a data from <code>.csv</code> file and I want to separate figures, but I am getting all the plots in one graph and I am not able to separate the graphs. Please help!</p> <pre><code>n = 10 i=0 for i in range(0,n): inflammation = matplotlib.pyplot.plot(data[i,:40])#inflammation graph for patient 0 </code></pre> <p>This is the image i got ,but I want separate graphs:</p> <p><a href="https://i.stack.imgur.com/qiH0C.png" rel="nofollow"><img src="https://i.stack.imgur.com/qiH0C.png" alt="enter image description here"></a></p>
0
2016-10-19T05:05:02Z
40,124,306
<p>You could always take a look at using <a href="http://matplotlib.org/api/pyplot_api.html?highlight=subplot#matplotlib.pyplot.subplot" rel="nofollow"><code>subplot()</code></a>, which would work as follows:</p> <pre><code>import matplotlib.pyplot as plt for n in range(1, 11): plt.subplot(2, 5, n) plt.plot(range(12)) plt.show() </code></pre> <p>This would display the following in a single figure:</p> <p><a href="https://i.stack.imgur.com/8ELXu.png" rel="nofollow"><img src="https://i.stack.imgur.com/8ELXu.png" alt="Ten subplots"></a></p>
1
2016-10-19T06:59:49Z
[ "python", "matplotlib" ]
tcp python socket hold connection forever
40,122,639
<p>I have a client-server model where the client will constantly checking a log file and as soon as a new line comes in the log file it sends that line to the server. </p> <p>Somehow I managed to work this thing using the following code.</p> <p><strong>server.py</strong></p> <pre><code>import SocketServer class MyTCPSocketHandler(SocketServer.BaseRequestHandler): def handle(self): # self.request is the TCP socket connected to the client data = self.request.recv(1024).strip() print data # process the data.. if __name__ == "__main__": HOST, PORT = "localhost", 9999 server = SocketServer.TCPServer((HOST, PORT), MyTCPSocketHandler) server.serve_forever() </code></pre> <p><strong>client.py</strong></p> <pre><code>import time import socket def follow(thefile): thefile.seek(0, 2) while True: line = thefile.readline() if not line: time.sleep(0.1) continue yield line def connect_socket(): HOST, PORT = "localhost", 9999 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT)) return sock if __name__ == '__main__': logfile = open("my_log.log") loglines = follow(logfile) for line in loglines: sock = connect_socket() # send data sock.sendall(bytes(line)) </code></pre> <p>the problem is every time I need to call the <code>connect_socket()</code> method to send a new line.</p> <p>I'm quite new to this topic so somebody please let me know is there any workaround for this to work in a such a way that once the connection is established between client and server I need to send data continuously to the server without making a new connection again and again. </p> <p>If I'm connecting only one time and using the same socket object to send data it was throwing </p> <blockquote> <p>socket.error: [Errno 32] Broken pipe</p> </blockquote> <p>Some StackOverflow links which I have followed are given below,</p> <p><a href="http://stackoverflow.com/questions/28021928/tcp-server-client-errno-32-broken-pipe">1</a>, <a href="http://stackoverflow.com/questions/180095/how-to-handle-a-broken-pipe-sigpipe-in-python">2</a>, <a href="http://stackoverflow.com/questions/6237569/python-socket-send-can-only-send-once-then-socket-error-errno-32-broken-pi">3</a></p> <p>One thing I found is </p> <blockquote> <p>Broken Pipe occurs when one end of the connection tries sending data while the other end has already closed the connection.</p> </blockquote> <p>How can I keep the connection open on both ends? For this use case should I go for an asynchronous method and if so which framework will be the best match <code>tornado</code> or <code>twisted</code>?</p>
0
2016-10-19T05:11:36Z
40,125,999
<p>After a line is transmitted, you close the connection on the client, but don't close it on the server.</p> <p>From <a href="https://docs.python.org/3.4/library/socketserver.html#socketserver.RequestHandler.finish" rel="nofollow">the docs</a>:</p> <blockquote> <p>RequestHandler.finish()</p> <p>Called after the handle() method to perform any clean-up actions required. <strong>The default implementation does nothing</strong>.</p> </blockquote> <p>So you should implement <code>finish</code> as well and close the socket (<code>self.request</code>) there.</p> <hr> <p>Another option is not to close the connection on the client:</p> <pre><code>sock = connect_socket() for line in loglines: # send data sock.sendall(bytes(line)) sock.sendall(b'bye') # EOF sock.close() </code></pre> <p>However in this case you should modify the server code and make sure it can serve multiple clients and it understands when to close the socket. With all these difficulties it is nevertheless the preferable way of doing things. Ideally, a client has a single TCP connection per session for they're costly to establish.</p>
0
2016-10-19T08:28:08Z
[ "python", "sockets", "tcp" ]
Correct way of sending JSON Data with encoding in Python
40,122,684
<p>I am developing API's on Django, and I am facing a lot of issues in encoding the data in python at the back-end and decoding it at front-end on java. </p> <p>Any standard rules for sending correct JSON Data to client application efficiently? </p> <p>There are some Hindi Characters which are not received properly on front end, it gives error saying that "JSON unterminated object at character" So I guess the problem is on my side</p>
0
2016-10-19T05:15:23Z
40,122,847
<p><code>json.loads</code> and <code>json.dumps</code> are generally used to encode and decode JSON data in python. </p> <p><code>dumps</code> takes an object and produces a string and <code>load</code> would take a file-like object, read the data from that object, and use that string to create an object. </p> <p>The encoder understands Python’s native types by default (string, unicode, int, float, list, tuple, dict).</p> <pre><code>import json data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 } ] print 'DATA:', repr(data) data_string = json.dumps(data) print 'JSON:', data_string </code></pre> <p>Values are encoded in a manner very similar to Python’s repr() output.</p> <pre><code>$ python json_simple_types.py DATA: [{'a': 'A', 'c': 3.0, 'b': (2, 4)}] JSON: [{"a": "A", "c": 3.0, "b": [2, 4]}] </code></pre> <p>Encoding, then re-decoding may not give exactly the same type of object.</p> <pre><code>import json data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 } ] data_string = json.dumps(data) print 'ENCODED:', data_string decoded = json.loads(data_string) print 'DECODED:', decoded print 'ORIGINAL:', type(data[0]['b']) print 'DECODED :', type(decoded[0]['b']) </code></pre> <p>In particular, strings are converted to unicode and tuples become lists.</p> <pre><code>$ python json_simple_types_decode.py ENCODED: [{"a": "A", "c": 3.0, "b": [2, 4]}] DECODED: [{u'a': u'A', u'c': 3.0, u'b': [2, 4]}] ORIGINAL: &lt;type 'tuple'&gt; DECODED : &lt;type 'list'&gt; </code></pre>
3
2016-10-19T05:26:19Z
[ "python", "json", "django" ]
Syntax error Jython
40,122,712
<p>I am getting a syntax error in my code. Can anyone say what's wrong in the syntax? I am new to this language, don't have much of an idea.</p> <p>Error message</p> <blockquote> <p>WASX7017E: Exception received while running file "JDBCoracle.py"; exception information: com.ibm.bsf.BSFException: exception from Jython: Traceback (innermost last): (no code object) at line 0 File "", line 8 name ="Oracle JDBC Driver" ^ SyntaxError: invalid syntax</p> </blockquote> <p>My code :</p> <pre><code>import sys ## **JDBCProvider** ## def OracleJDBC(cellName,serverName,): name ="Oracle JDBC Driver" print " Name of JDBC Provider which will be created ---&gt; " + name print " ----------------------------------------------------------------------------------------- " # Gets the name of cell cell = AdminControl.getCell() print cell cellid = AdminConfig.getid('/Cell:'+ cell +'/') print cellid print " ----------------------------------------------------------------------------------------- " ## Creating New JDBC Provider ## print " Creating New JDBC Provider :"+ name n1 = ["name" , "Oracle JDBC Driver" ] desc = ["description" , "Oracle JDBC Driver"] impn = ["implementationClassName" , "oracle.jdbc.pool.OracleConnectionPoolDataSource"] classpath = ["classpath" , ${ORACLE_JDBC_DRIVER_PATH}/ojdbc6.jar ] attrs1 = [n1 , impn , desc , classpath] Serverid = AdminConfig.getid("/Cell:"+ cellName +"/ServerName:"+ serverName +"/") jdbc = AdminConfig.create('JDBCProvider' , Serverid , attrs1) print " New JDBC Provider created :"+ name AdminConfig.save() print " Saving Configuraion " print " ----------------------------------------------------------------------------------------- " #################################################################################################################### #################################################################################################################### #main program starts here OracleJDBC(cellName,serverName) </code></pre> <p>Can some one help me see what I'm doing wrong? I'm new to this language.</p>
-1
2016-10-19T05:17:11Z
40,123,839
<p>Your error is the comma in <code>def OracleJDBC(cellName,serverName,):</code>; eliminate it and things will work. </p> <pre><code>import sys ## **JDBCProvider** ## def OracleJDBC(cellName,serverName): name ="Oracle JDBC Driver" print " Name of JDBC Provider which will be created ---&gt; " + name print " ----------------------------------------------------------------------------------------- " # Gets the name of cell cell = AdminControl.getCell() print cell cellid = AdminConfig.getid('/Cell:'+ cell +'/') print cellid print " ----------------------------------------------------------------------------------------- " ## Creating New JDBC Provider ## print " Creating New JDBC Provider :"+ name n1 = ["name" , "Oracle JDBC Driver" ] desc = ["description" , "Oracle JDBC Driver"] impn = ["implementationClassName" , "oracle.jdbc.pool.OracleConnectionPoolDataSource"] classpath = ["classpath" , '/path/to/ojdbc6.jar' ] attrs1 = [n1 , impn , desc , classpath] n1 = ["name" , "Oracle JDBC Driver" ] desc = ["description" , "Oracle JDBC Driver"] impn = ["implementationClassName" , "oracle.jdbc.pool.OracleConnectionPoolDataSource"] classpath = ["classpath" , ${ORACLE_JDBC_DRIVER_PATH}/ojdbc6.jar ] attrs1 = [n1 , impn , desc , classpath] Serverid = AdminConfig.getid("/Cell:" + cellName + "/ServerName:" + serverName +"/") jdbc = AdminConfig.create('JDBCProvider', Serverid, attrs1) print " New JDBC Provider created :" + name AdminConfig.save() print " Saving Configuraion " print " ----------------------------------------------------------------------------------------- " #################################################################################################################### #################################################################################################################### #main program starts here if __name__ == '__main__': OracleJDBC(cellName,serverName) </code></pre>
1
2016-10-19T06:32:25Z
[ "python", "jython" ]
How to know which is more advatageous with assigning same value to different attributes in python
40,122,713
<p>Between the two in python which will be faster and advatageous</p> <pre><code>a = b = c = d = 1 </code></pre> <p>and</p> <pre><code>a = 1 b = 1 c = 1 d = 1 </code></pre>
3
2016-10-19T05:17:11Z
40,122,792
<p>Simply run a test:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; min(timeit.repeat('a = b = c = d = 1', number=10000000)) 0.4885740280151367 &gt;&gt;&gt; min(timeit.repeat('a = 1; b = 1; c = 1; d = 1', number=10000000)) 0.6283371448516846 </code></pre> <p>Also note:</p> <pre><code>&gt;&gt;&gt; min(timeit.repeat('a, b, c, d = 1, 1, 1, 1', number=10000000)) 0.4040501117706299 </code></pre>
5
2016-10-19T05:22:44Z
[ "python", "python-2.7" ]
python url not found - Accessing views.py from AJAX
40,122,717
<p>New to Python and Django and I'm trying to make a simple ajax call from a button click to pass certain data to my views.py, however, when I try to make a url as seen on my ajax code below, the <code>documentId.id</code> does not append unless I directly append in without the <code>"?id="</code>.</p> <pre><code> {%for document in documents%} {{document.filename}} &lt;input type="button" id="{{document.id}}" onclick="loadData(this)" name="load-data" value="Add"/&gt; {%endfor%} &lt;script type ="text/javascript"&gt; function loadData(documentId){ $.ajax({ url:"upload-data/load" + "?id=" + documentId.id, data: {'documentId': documentId}, type: 'GET', success: function(){ window.location.href = "http://127.0.0.1:8000/url/locations"; } }); } &lt;/script&gt; </code></pre> <p>This gives me then an error that says the url cannot be found. I have a line in my urls.py below:</p> <pre><code>url(r^"upload-data/load/([0-9]+)/$', views.loadFile, name="load-data"), </code></pre> <p>Other than this method, I am stumped as to how I am going to extract my data to my views.py.</p> <pre><code>def loadFile(request): documentId = request.GET.get('id') newLayer = Layer(get_object_or_404(Document, pk = documentId)) newLayer.save() layers = Layer.objects.all() return render(request, 'url/loaded.html', { 'layers': layers}) </code></pre> <p>The persisting error in the console would be:</p> <blockquote> <p><a href="http://127.0.0.1:8000/upload-data/load/" rel="nofollow">http://127.0.0.1:8000/upload-data/load/</a> [HTTP/1.0 404 Not Found]</p> </blockquote>
0
2016-10-19T05:17:15Z
40,122,793
<p>In JavaScript you need </p> <pre><code>"upload-data/load/" + documentId.id </code></pre> <p>Django doesn't use <code>?id=</code> in <code>url</code> definition <code>r^"upload-data/load/([0-9]+)/$'</code>. It expects ie. <code>upload-data/load/123</code> instead of <code>upload-data/load?id=123</code></p> <hr> <p><strong>EDIT:</strong> and you need <code>id</code> in <code>def loadFile(request, id)</code>. </p> <p>And then you don't have to use <code>request.GET.get('id')</code></p>
0
2016-10-19T05:22:48Z
[ "python", "ajax", "django", "url", "onclick" ]
python url not found - Accessing views.py from AJAX
40,122,717
<p>New to Python and Django and I'm trying to make a simple ajax call from a button click to pass certain data to my views.py, however, when I try to make a url as seen on my ajax code below, the <code>documentId.id</code> does not append unless I directly append in without the <code>"?id="</code>.</p> <pre><code> {%for document in documents%} {{document.filename}} &lt;input type="button" id="{{document.id}}" onclick="loadData(this)" name="load-data" value="Add"/&gt; {%endfor%} &lt;script type ="text/javascript"&gt; function loadData(documentId){ $.ajax({ url:"upload-data/load" + "?id=" + documentId.id, data: {'documentId': documentId}, type: 'GET', success: function(){ window.location.href = "http://127.0.0.1:8000/url/locations"; } }); } &lt;/script&gt; </code></pre> <p>This gives me then an error that says the url cannot be found. I have a line in my urls.py below:</p> <pre><code>url(r^"upload-data/load/([0-9]+)/$', views.loadFile, name="load-data"), </code></pre> <p>Other than this method, I am stumped as to how I am going to extract my data to my views.py.</p> <pre><code>def loadFile(request): documentId = request.GET.get('id') newLayer = Layer(get_object_or_404(Document, pk = documentId)) newLayer.save() layers = Layer.objects.all() return render(request, 'url/loaded.html', { 'layers': layers}) </code></pre> <p>The persisting error in the console would be:</p> <blockquote> <p><a href="http://127.0.0.1:8000/upload-data/load/" rel="nofollow">http://127.0.0.1:8000/upload-data/load/</a> [HTTP/1.0 404 Not Found]</p> </blockquote>
0
2016-10-19T05:17:15Z
40,123,186
<p>Use something like this:</p> <pre><code>def loadFile(request): documentId= request.GET.get('id', ''). newLayer = Layer(get_object_or_404(Document, pk = documentId)) newLayer.save() layers = Layer.objects.all() return render(request, 'url/loaded.html', { 'layers': layers}) </code></pre> <p>And update your url as :</p> <pre><code> url(r^"upload-data/load/', views.loadFile, name="load-data") </code></pre> <p>And the script would be like :</p> <pre><code>&lt;script type ="text/javascript"&gt; function loadData(documentId){ $.ajax({ url:"upload-data/load/?id="+ documentId.id, data: {'documentId': documentId}, type: 'GET', success: function(){ window.location.href = "http://127.0.0.1:8000/url/locations"; } }); } &lt;/script&gt; </code></pre> <p>Thanks.</p>
1
2016-10-19T05:49:20Z
[ "python", "ajax", "django", "url", "onclick" ]
python url not found - Accessing views.py from AJAX
40,122,717
<p>New to Python and Django and I'm trying to make a simple ajax call from a button click to pass certain data to my views.py, however, when I try to make a url as seen on my ajax code below, the <code>documentId.id</code> does not append unless I directly append in without the <code>"?id="</code>.</p> <pre><code> {%for document in documents%} {{document.filename}} &lt;input type="button" id="{{document.id}}" onclick="loadData(this)" name="load-data" value="Add"/&gt; {%endfor%} &lt;script type ="text/javascript"&gt; function loadData(documentId){ $.ajax({ url:"upload-data/load" + "?id=" + documentId.id, data: {'documentId': documentId}, type: 'GET', success: function(){ window.location.href = "http://127.0.0.1:8000/url/locations"; } }); } &lt;/script&gt; </code></pre> <p>This gives me then an error that says the url cannot be found. I have a line in my urls.py below:</p> <pre><code>url(r^"upload-data/load/([0-9]+)/$', views.loadFile, name="load-data"), </code></pre> <p>Other than this method, I am stumped as to how I am going to extract my data to my views.py.</p> <pre><code>def loadFile(request): documentId = request.GET.get('id') newLayer = Layer(get_object_or_404(Document, pk = documentId)) newLayer.save() layers = Layer.objects.all() return render(request, 'url/loaded.html', { 'layers': layers}) </code></pre> <p>The persisting error in the console would be:</p> <blockquote> <p><a href="http://127.0.0.1:8000/upload-data/load/" rel="nofollow">http://127.0.0.1:8000/upload-data/load/</a> [HTTP/1.0 404 Not Found]</p> </blockquote>
0
2016-10-19T05:17:15Z
40,123,858
<p>From the above answers and comments it seems like rather than passing id as a <code>url param</code> you want to pass the same as a <code>get param</code>. In that case make your urls like below.</p> <pre><code>url(r^"upload-data/load/', views.loadFile, name="load-data") </code></pre> <p>and in views, check for get params by <code>replacing id with documentId</code>. document id will be in your <code>dict named as data passed to view</code>. So look for <code>request.GET.get('data','')</code> and from data extract id as below</p> <pre><code>def loadFile(request): data = request.GET.get('data', None) if data: documentId = data['documentId'] newLayer = Layer(get_object_or_404(Document, pk = documentId)) newLayer.save() layers = Layer.objects.all() return render(request, 'url/loaded.html', { 'layers': layers}) else: return JsonResponse({'error': 'pass document id'}, status=400) </code></pre> <p>Since you are passing a get param from javascript named as <code>documentId</code> not id.</p> <p>HTH</p>
0
2016-10-19T06:33:45Z
[ "python", "ajax", "django", "url", "onclick" ]
File Upload dialog is not picked by selenium
40,122,813
<p><a href="https://i.stack.imgur.com/oBL4R.png" rel="nofollow"><img src="https://i.stack.imgur.com/oBL4R.png" alt="enter image description here"></a></p> <p>I am trying to write a selenium based test in python. Here, I am trying to select a file for the first text box(<code>PGP Private Key</code>)</p> <p>Please note - 1. The text box(<code>PGP Private Key</code>) is read only(I cannot enter any text by keyboard) 2. <code>self.driver.send_keys(file)</code> is not working.</p> <p>As I mentioned in note, since <code>send_keys()</code> not working, I am trying to get the handle of 'File Upload' dialog. But <code>self.driver.window_handles</code>returns only one handle. That is of main window.</p> <p>How to upload the file? Any one of these 2 solutions(send_key or window handle) is fine.</p> <p>Please note, I am using firefox 28 and selenium 2.41.0</p>
0
2016-10-19T05:24:36Z
40,125,704
<p>In common case this code should work:</p> <pre><code>driver.find_element_by_xpath("//input[@id='selectKeys']").send_keys(path_to_file) </code></pre>
0
2016-10-19T08:12:58Z
[ "python", "selenium", "firefox", "firebug", "inspector" ]
Alternate for range in python
40,122,852
<p>If I have to generate natural numbers, I can use 'range' as follows:</p> <pre><code>list(range(5)) </code></pre> <p>[0, 1, 2, 3, 4]</p> <p>Is there any way to achieve this without using range function or looping?</p>
-1
2016-10-19T05:26:44Z
40,123,004
<p>You could use recursion to print first n natural numbers</p> <pre><code>def printNos(n): if n &gt; 0: printNos(n-1) print n printNos(100) </code></pre>
4
2016-10-19T05:38:10Z
[ "python" ]
Alternate for range in python
40,122,852
<p>If I have to generate natural numbers, I can use 'range' as follows:</p> <pre><code>list(range(5)) </code></pre> <p>[0, 1, 2, 3, 4]</p> <p>Is there any way to achieve this without using range function or looping?</p>
-1
2016-10-19T05:26:44Z
40,123,057
<p>Looping will be required in some form or another to generate a list of numbers, whether you do it yourself, use library functions, or use recursive methods.</p> <p>If you're not opposed to looping in principle (but just don't want to implement it yourself), there are many practical and esoteric ways to do it (a number have been mentioned here already).</p> <p>A similar question was posted here: <a href="http://stackoverflow.com/questions/8429794/how-to-fill-a-list">How to fill a list</a>. Although it has interesting solutions, they're all still looping, or using <code>range</code> type functions.</p>
2
2016-10-19T05:41:49Z
[ "python" ]
Alternate for range in python
40,122,852
<p>If I have to generate natural numbers, I can use 'range' as follows:</p> <pre><code>list(range(5)) </code></pre> <p>[0, 1, 2, 3, 4]</p> <p>Is there any way to achieve this without using range function or looping?</p>
-1
2016-10-19T05:26:44Z
40,123,095
<p>Based on Nihal's solution, but returns a list instead:</p> <pre><code>def recursive_range(n): if n == 0: return [] return recursive_range(n-1) + [n-1] </code></pre>
2
2016-10-19T05:44:00Z
[ "python" ]
Alternate for range in python
40,122,852
<p>If I have to generate natural numbers, I can use 'range' as follows:</p> <pre><code>list(range(5)) </code></pre> <p>[0, 1, 2, 3, 4]</p> <p>Is there any way to achieve this without using range function or looping?</p>
-1
2016-10-19T05:26:44Z
40,123,211
<p>Well, yes, you can do this without using <code>range</code>, loop or recursion:</p> <pre><code>&gt;&gt;&gt; num = 10 &gt;&gt;&gt; from subprocess import call &gt;&gt;&gt; call(["seq", str(num)]) </code></pre> <p>You can even have a list (or a generator, of course):</p> <pre><code>&gt;&gt;&gt; num = 10 &gt;&gt;&gt; from subprocess import check_output &gt;&gt;&gt; ls = check_output(["seq", str(num)]) &gt;&gt;&gt; [int(num) for num in ls[:-1].split('\n')] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42] </code></pre> <p>But...what's the purpose?</p>
2
2016-10-19T05:50:53Z
[ "python" ]
How to connect 2 ultrasonic sensors concurrently using python multiprocessing process?
40,123,068
<p>I'm new to python but i'm working on a project in which i need to connect 3 or more Ultrasonic Sensors concurrently. I read all about threads and multiprocessing ran a couple of examples successfully. I know the code has to be run form the command prompt or the PI2 terminal. However, the multiprocessing code I wrote does not work and I cannot figure out why. Could someone please help me. </p> <pre><code> from multiprocessing import Process from gpiozero import DistanceSensor ultrasonic = DistanceSensor(echo=18, trigger=23) ultrasonic_B = DistanceSensor(echo=25, trigger=24) ultrasonic_C = DistanceSensor(echo=12, trigger=16) ultrasonic.max_distance = 1 ultrasonic_B.max_distance = 1 ultrasonic_C.max_distance = 1 def A(name): while True: ultrasonic.wait_for_in_range() print('Distance') if ultrasonic.wait_for_out_of_range(): print('Out of range') def B(name): while True: ultrasonic_B.wait_for_in_range() print('Distance_B') if ultrasonic_B.wait_for_out_in_range(): print('Out of range_B') def C(name): while True: ultrasonic_C.wait_for_in_range() print('Distance_B') if ultrasonic_C.wait_for_out_in_range(): print('Out of range_B') if __name__ == "__main__": p = Process(target=A) p1 = Process(target=B) p2 = Process(target=C) p.start() p1.start() p2.start() </code></pre> <p>I took your suggestions into consideration and was able to make the first loop work but the other 2 loops give me nothing. Here is the updated code </p> <pre><code>from multiprocessing import Process from gpiozero import DistanceSensor ultrasonic = DistanceSensor(echo=18, trigger=23) ultrasonic_B = DistanceSensor(echo=25, trigger=24) ultrasonic_C = DistanceSensor(echo=12, trigger=16) ultrasonic.max_distance = 1 ultrasonic_B.max_distance = 1 ultrasonic_C.max_distance = 1 def A(): while ultrasonic.wait_for_in_range(): print('Distance') if ultrasonic.wait_for_out_of_range(): print('Out of range') def B(): while ultrasonic_B.wait_for_in_range(): print('Distance_B') if ultrasonic_B.wait_for_out_in_range(): print('Out of range_B') def C(): while ultrasonic_C.wait_for_in_range(): print('Distance_B') if ultrasonic_C.wait_for_out_in_range(): print('Out of range_B') if __name__ == "__main__": p = Process(target=A) p1 = Process(target=B) p2 = Process(target=C) p.run() p1.run() p2.run() </code></pre> <p>Result comes form first loop Distance Out of range Distance Out of range</p> <p>OK this is what I have</p> <pre><code>from multiprocessing import Process from gpiozero import DistanceSensor ultrasonic = DistanceSensor(echo=18, trigger=23) ultrasonic_B = DistanceSensor(echo=25, trigger=24) ultrasonic_C = DistanceSensor(echo=12, trigger=16) ultrasonic.max_distance = 1 ultrasonic_B.max_distance = 1 ultrasonic_C.max_distance = 1 def A(): while ultrasonic.wait_for_in_range(): print('Distance') if ultrasonic.wait_for_out_of_range(): print('Out of range') def B(): while ultrasonic_B.wait_for_in_range(): print('Distance_B') if ultrasonic_B.wait_for_out_in_range(): print('Out of range_B') def C(): while ultrasonic_C.wait_for_in_range(): print('Distance_B') if ultrasonic_C.wait_for_out_in_range(): print('Out of range_B') if __name__ == "__main__": p = Process(target=A) p1 = Process(target=B) p2 = Process(target=C) p.start() p1.start() p2.start() </code></pre>
0
2016-10-19T05:42:48Z
40,128,355
<p>You do not say what you mean with "does not work", so I am taking a few guesses here.</p> <p>The obvious fail here would be:</p> <blockquote> <p>TypeError: A() takes exactly 1 argument (0 given)</p> </blockquote> <p>Since functions <code>A</code>, <code>B</code> and <code>C</code> all take an argument <code>name</code>, and you do not provide it in <code>Process(target=A)</code>. It works if you just remove the parameter from the functions, since you are not even using it.</p> <p>You can also provide the argument in the call like this:</p> <pre><code>p = Process(target=A, args=('ultra_a',)) </code></pre> <p>Other one could be indentation error, at least in your code paste you have one extra space at each line until def B.</p>
0
2016-10-19T10:11:15Z
[ "python" ]
Keras - input shape of large 2-dimensional Array
40,123,070
<p>I want to build an array which contains a very large number of elements number of sequences (batch size) * size of dictionary (unique words in file) 474683 * 22995</p> <p>each sequence will have some number X of bits turned on which represents a word in the dictionary</p> <p>the sentence is: "I am the best king" lets say the dictionary is:</p> <p>[I, am, king, the, best, animal, toast, ...]</p> <p>the sequence will look like:</p> <p>[1,1,1,1,1,0,0,...]</p> <p>I try to import this to keras and I get an error:</p> <p>Exception: Error when checking model input: expected lstm_input_9 to have 3 dimensions, but got array with shape (93371, 22995)</p> <p>From <a href="http://stackoverflow.com/questions/38105999/dimension-mismatch-in-lstm-keras">here</a> we can see that keras expects: (batch_size, sequence_length, input_dimension)</p> <p>What can I do about this?</p> <p>If I try to build an nunpy array which has a sequence length, say 20, I will get a memory error (its something like 26gb), should I just split the array and train on each one separately?</p>
0
2016-10-19T05:43:00Z
40,123,655
<p>Okay, I decided to split the array and train on each of the split instead of pushing everything to memory:</p> <pre><code>data_cut = 3 X = np.zeros((len(inputs)/data_cut, max_len, len(words)), dtype=np.bool) y = np.zeros((len(inputs)/data_cut, len(words)), dtype=np.bool) # set the appropriate indices to 1 in each one-hot vector ins = [] for cuts in range(0,data_cut):#number of cuts cutLocation = len(inputs)/data_cut*cuts#location of cut start = (cutLocation) end = (len(inputs)/data_cut) * (cuts + 1) ins.append(inputs[start:end])#first half for i, example in enumerate(ins[cuts]): for t, word in enumerate(example): X[i, t, word_labels[word]] = 1 y[i, word_labels[outputs[i]]] = 1 model.fit(X, y, batch_size=64, nb_epoch=epochs) </code></pre> <p>Of course you want to split then train over the number of splits.</p> <p>If anyone want to take a stab at making this more efficient please write below.</p>
0
2016-10-19T06:20:58Z
[ "python", "arrays", "keras" ]
python loop to find the largest integer from a list
40,123,112
<p>I wrote a script to pull down a list of aws tags and then read the last octect and tell me which one is the highest IP. For example. here is the list of tags that are returned:</p> <p>['vlslabmc, 172.16.0.13/24', 'vlslabmc,172.16.0.5/24', 'vlslabmc,172.16.0.3/24', 'vlslabmc,172.16.0.12/24', 'vlslabmc,172.16.0.16/24', 'vlslabmc,172.16.0.6/24', 'vlslabmc,172.16.0.1/24', 'vlslabmc,172.16.0.11/24', 'vlslabmc,172.16.0.15/24', 'vlslabmc,172.16.0.17/24', 'vlslabmc,172.16.0.4/24', 'vlslabmc,172.16.0.7/24', 'vlslabmc,172.16.0.10/24', 'vlslabmc,172.16.0.9/24', 'vlslabmc,172.16.0.8/24', 'vlslabmc,172.16.0.2/24', 'vlslabmc,172.16.0.14/24']</p> <p>Here's my code to workout the largest IP from the tagLis (note that the largest is 17, 172.16.0.17)</p> <pre><code> 21 def findLargestIP(): 22 for i in tagList: 23 #remove all the spacing in the tags 24 ec2Tags = i.strip() 25 #seperate any multiple tags 26 ec2SingleTag = ec2Tags.split(',') 27 #find the last octect of the ip address 28 fullIPTag = ec2SingleTag[1].split('.') 29 #remove the CIDR from ip to get the last octect 30 lastIPsTag = fullIPTag[3].split('/') 31 lastOctect = lastIPsTag[0] 32 ipList.append(lastOctect) 33 largestIP = int(ipList[0]) 34 for latestIP in ipList: 35 if int(latestIP) &gt; largestIP: 36 largestIP = latestIP 37 return largestIP </code></pre> <p>I'm not sure why.. but when I print the value of largestIP it always prints out 16. Ive gone through the code it should have worked <strong>(I'm avoiding using the max function as I'm just learning to code)</strong></p> <p>Any help as aways is greatly appreciated.</p> <p>Thanks</p> <h2><strong>Edit with the answer below, and a question</strong></h2> <p>Ok so thanks to a clue from cmarie I got it working the problem was mainly</p> <pre><code>33 largestIP = int(ipList[0]) </code></pre> <p>Here's the code running before with an added print statement on the list append:</p> <pre><code>'13'] ['13', '5'] ['13', '5', '3'] ['13', '5', '3', '12'] ['13', '5', '3', '12', '16'] 16 ['13', '5', '3', '12', '16', '6'] 16 ['13', '5', '3', '12', '16', '6', '1'] 16 ['13', '5', '3', '12', '16', '6', '1', '11'] 16 ... ... ['13', '5', '3', '12', '16', '6', '1', '11', '15', '17', '4', '7', '10', '9', '8', '2'] 16 ['13', '5', '3', '12', '16', '6', '1', '11', '15', '17', '4', '7', '10', '9', '8', '2', '14'] 16 </code></pre> <p>Basically what was happening is that during this loop :</p> <pre><code>33 largestIP = int(ipList[0]) 34 for latestIP in ipList: 35 if int(latestIP) &gt; largestIP: 36 largestIP = latestIP </code></pre> <p>The loop stops at the 1st largest integer. in this case that is 16. <strong>*I'm not sure why it does but it does</strong></p> <p>Here's the working code:</p> <pre><code>19 def findLargestIP(): 20 ipList =[] 21 for i in tagList: 22 #remove all the spacing in the tags 23 ec2Tags = i.strip() 24 #seperate any multiple tags 25 ec2SingleTag = ec2Tags.split(',') 26 #find the last octect of the ip address 27 fullIPTag = ec2SingleTag[1].split('.') 28 #remove the CIDR from ip to get the last octect 29 lastIPsTag = fullIPTag[3].split('/') 30 lastOctect = lastIPsTag[0] 31 ipList.append(int(lastOctect)) 32 print ipList 33 largestIP = 0 34 for latestIP in ipList: 35 if latestIP &gt; largestIP: 36 largestIP = latestIP 37 print latestIP 38 print largestIP 39 return largestIP </code></pre> <p>and the result:</p> <pre><code>[13, 5, 3, 12, 16] 13 16 [13, 5, 3, 12, 16, 6] 13 16 [13, 5, 3, 12, 16, 6, 1] 13 16 [13, 5, 3, 12, 16, 6, 1, 11] 13 16 [13, 5, 3, 12, 16, 6, 1, 11, 15] 13 16 [13, 5, 3, 12, 16, 6, 1, 11, 15, 17] 13 16 17 </code></pre> <p>Note it found 17.</p>
1
2016-10-19T05:44:57Z
40,123,380
<p>So I had to refactor your code a little bit. I assumed ipList was an empty list. Are you sure you tested to see if it actually ran? Specifically your if statement</p> <pre><code>if int(latestIP) &gt; largestIP: largestIP = latestIP </code></pre> <p>would return a</p> <pre><code>TypeError: unorderable types: int() &gt; str() </code></pre> <p>because you would be assigning a string to largestIP and then in the next iteration, you would compare a string with an int. Aside from that, your code seems functional. It returns 17 as the largest last octet for me which seems right.</p> <p>If your intention is to return the largest last octet of your list of ip addresses, you might want to approach this a little bit differently.</p> <p><strong>Option 1:</strong> Accumulate list of IP Addresses first</p> <p>Instead of nesting a for loop in your loop to iterate through all the tags, you can first just accumulate the tags and then go through and find the max. This way, you go through the tag list once, and then the ip list once, instead of going through your entire ip list each time you iterate through your tag list.</p> <p><strong>Option 2:</strong> Create a list of only the last octet</p> <p>Similar to option 1, you would iterate through your tagList and accumulate all the last octets of the ip addresses casted to ints into a list, instead of the entire ip address. In a loop afterwards, you can call max on the list with the octets (I'm guessing you want to avoid this).</p> <p><strong>Option 3:</strong> Have a running greatest value</p> <p>I think this is the best solution. As you're going through the tag list, you can keep a variable that will have the greatest last octet so far. This way you only need to loop through the tag list once, and still come out with the greatest last octet thus far.</p> <p>If you want to grab the entire IP address, options 1 and 3 would still work, but for option 2, you might want to look into <a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow">python dictionaries</a>.</p>
0
2016-10-19T06:01:46Z
[ "python", "list", "loops", "integer" ]
python loop to find the largest integer from a list
40,123,112
<p>I wrote a script to pull down a list of aws tags and then read the last octect and tell me which one is the highest IP. For example. here is the list of tags that are returned:</p> <p>['vlslabmc, 172.16.0.13/24', 'vlslabmc,172.16.0.5/24', 'vlslabmc,172.16.0.3/24', 'vlslabmc,172.16.0.12/24', 'vlslabmc,172.16.0.16/24', 'vlslabmc,172.16.0.6/24', 'vlslabmc,172.16.0.1/24', 'vlslabmc,172.16.0.11/24', 'vlslabmc,172.16.0.15/24', 'vlslabmc,172.16.0.17/24', 'vlslabmc,172.16.0.4/24', 'vlslabmc,172.16.0.7/24', 'vlslabmc,172.16.0.10/24', 'vlslabmc,172.16.0.9/24', 'vlslabmc,172.16.0.8/24', 'vlslabmc,172.16.0.2/24', 'vlslabmc,172.16.0.14/24']</p> <p>Here's my code to workout the largest IP from the tagLis (note that the largest is 17, 172.16.0.17)</p> <pre><code> 21 def findLargestIP(): 22 for i in tagList: 23 #remove all the spacing in the tags 24 ec2Tags = i.strip() 25 #seperate any multiple tags 26 ec2SingleTag = ec2Tags.split(',') 27 #find the last octect of the ip address 28 fullIPTag = ec2SingleTag[1].split('.') 29 #remove the CIDR from ip to get the last octect 30 lastIPsTag = fullIPTag[3].split('/') 31 lastOctect = lastIPsTag[0] 32 ipList.append(lastOctect) 33 largestIP = int(ipList[0]) 34 for latestIP in ipList: 35 if int(latestIP) &gt; largestIP: 36 largestIP = latestIP 37 return largestIP </code></pre> <p>I'm not sure why.. but when I print the value of largestIP it always prints out 16. Ive gone through the code it should have worked <strong>(I'm avoiding using the max function as I'm just learning to code)</strong></p> <p>Any help as aways is greatly appreciated.</p> <p>Thanks</p> <h2><strong>Edit with the answer below, and a question</strong></h2> <p>Ok so thanks to a clue from cmarie I got it working the problem was mainly</p> <pre><code>33 largestIP = int(ipList[0]) </code></pre> <p>Here's the code running before with an added print statement on the list append:</p> <pre><code>'13'] ['13', '5'] ['13', '5', '3'] ['13', '5', '3', '12'] ['13', '5', '3', '12', '16'] 16 ['13', '5', '3', '12', '16', '6'] 16 ['13', '5', '3', '12', '16', '6', '1'] 16 ['13', '5', '3', '12', '16', '6', '1', '11'] 16 ... ... ['13', '5', '3', '12', '16', '6', '1', '11', '15', '17', '4', '7', '10', '9', '8', '2'] 16 ['13', '5', '3', '12', '16', '6', '1', '11', '15', '17', '4', '7', '10', '9', '8', '2', '14'] 16 </code></pre> <p>Basically what was happening is that during this loop :</p> <pre><code>33 largestIP = int(ipList[0]) 34 for latestIP in ipList: 35 if int(latestIP) &gt; largestIP: 36 largestIP = latestIP </code></pre> <p>The loop stops at the 1st largest integer. in this case that is 16. <strong>*I'm not sure why it does but it does</strong></p> <p>Here's the working code:</p> <pre><code>19 def findLargestIP(): 20 ipList =[] 21 for i in tagList: 22 #remove all the spacing in the tags 23 ec2Tags = i.strip() 24 #seperate any multiple tags 25 ec2SingleTag = ec2Tags.split(',') 26 #find the last octect of the ip address 27 fullIPTag = ec2SingleTag[1].split('.') 28 #remove the CIDR from ip to get the last octect 29 lastIPsTag = fullIPTag[3].split('/') 30 lastOctect = lastIPsTag[0] 31 ipList.append(int(lastOctect)) 32 print ipList 33 largestIP = 0 34 for latestIP in ipList: 35 if latestIP &gt; largestIP: 36 largestIP = latestIP 37 print latestIP 38 print largestIP 39 return largestIP </code></pre> <p>and the result:</p> <pre><code>[13, 5, 3, 12, 16] 13 16 [13, 5, 3, 12, 16, 6] 13 16 [13, 5, 3, 12, 16, 6, 1] 13 16 [13, 5, 3, 12, 16, 6, 1, 11] 13 16 [13, 5, 3, 12, 16, 6, 1, 11, 15] 13 16 [13, 5, 3, 12, 16, 6, 1, 11, 15, 17] 13 16 17 </code></pre> <p>Note it found 17.</p>
1
2016-10-19T05:44:57Z
40,123,446
<p>Why are doing this so complex. Here is oneliner for this</p> <pre><code>ip_list = ['vlslabmc, 172.16.0.13/24', 'vlslabmc,172.16.0.5/24', 'vlslabmc,172.16.0.3/24', 'vlslabmc,172.16.0.12/24', 'vlslabmc,172.16.0.16/24', 'vlslabmc,172.16.0.6/24', 'vlslabmc,172.16.0.1/24', 'vlslabmc,172.16.0.11/24', 'vlslabmc,172.16.0.15/24', 'vlslabmc,172.16.0.17/24', 'vlslabmc,172.16.0.4/24', 'vlslabmc,172.16.0.7/24', 'vlslabmc,172.16.0.10/24', 'vlslabmc,172.16.0.9/24', 'vlslabmc,172.16.0.8/24', 'vlslabmc,172.16.0.2/24', 'vlslabmc,172.16.0.14/24'] largestIP = max(ip_list, key=lambda i: int(i.split('/')[0].split('.')[-1])) </code></pre>
1
2016-10-19T06:06:25Z
[ "python", "list", "loops", "integer" ]
python loop to find the largest integer from a list
40,123,112
<p>I wrote a script to pull down a list of aws tags and then read the last octect and tell me which one is the highest IP. For example. here is the list of tags that are returned:</p> <p>['vlslabmc, 172.16.0.13/24', 'vlslabmc,172.16.0.5/24', 'vlslabmc,172.16.0.3/24', 'vlslabmc,172.16.0.12/24', 'vlslabmc,172.16.0.16/24', 'vlslabmc,172.16.0.6/24', 'vlslabmc,172.16.0.1/24', 'vlslabmc,172.16.0.11/24', 'vlslabmc,172.16.0.15/24', 'vlslabmc,172.16.0.17/24', 'vlslabmc,172.16.0.4/24', 'vlslabmc,172.16.0.7/24', 'vlslabmc,172.16.0.10/24', 'vlslabmc,172.16.0.9/24', 'vlslabmc,172.16.0.8/24', 'vlslabmc,172.16.0.2/24', 'vlslabmc,172.16.0.14/24']</p> <p>Here's my code to workout the largest IP from the tagLis (note that the largest is 17, 172.16.0.17)</p> <pre><code> 21 def findLargestIP(): 22 for i in tagList: 23 #remove all the spacing in the tags 24 ec2Tags = i.strip() 25 #seperate any multiple tags 26 ec2SingleTag = ec2Tags.split(',') 27 #find the last octect of the ip address 28 fullIPTag = ec2SingleTag[1].split('.') 29 #remove the CIDR from ip to get the last octect 30 lastIPsTag = fullIPTag[3].split('/') 31 lastOctect = lastIPsTag[0] 32 ipList.append(lastOctect) 33 largestIP = int(ipList[0]) 34 for latestIP in ipList: 35 if int(latestIP) &gt; largestIP: 36 largestIP = latestIP 37 return largestIP </code></pre> <p>I'm not sure why.. but when I print the value of largestIP it always prints out 16. Ive gone through the code it should have worked <strong>(I'm avoiding using the max function as I'm just learning to code)</strong></p> <p>Any help as aways is greatly appreciated.</p> <p>Thanks</p> <h2><strong>Edit with the answer below, and a question</strong></h2> <p>Ok so thanks to a clue from cmarie I got it working the problem was mainly</p> <pre><code>33 largestIP = int(ipList[0]) </code></pre> <p>Here's the code running before with an added print statement on the list append:</p> <pre><code>'13'] ['13', '5'] ['13', '5', '3'] ['13', '5', '3', '12'] ['13', '5', '3', '12', '16'] 16 ['13', '5', '3', '12', '16', '6'] 16 ['13', '5', '3', '12', '16', '6', '1'] 16 ['13', '5', '3', '12', '16', '6', '1', '11'] 16 ... ... ['13', '5', '3', '12', '16', '6', '1', '11', '15', '17', '4', '7', '10', '9', '8', '2'] 16 ['13', '5', '3', '12', '16', '6', '1', '11', '15', '17', '4', '7', '10', '9', '8', '2', '14'] 16 </code></pre> <p>Basically what was happening is that during this loop :</p> <pre><code>33 largestIP = int(ipList[0]) 34 for latestIP in ipList: 35 if int(latestIP) &gt; largestIP: 36 largestIP = latestIP </code></pre> <p>The loop stops at the 1st largest integer. in this case that is 16. <strong>*I'm not sure why it does but it does</strong></p> <p>Here's the working code:</p> <pre><code>19 def findLargestIP(): 20 ipList =[] 21 for i in tagList: 22 #remove all the spacing in the tags 23 ec2Tags = i.strip() 24 #seperate any multiple tags 25 ec2SingleTag = ec2Tags.split(',') 26 #find the last octect of the ip address 27 fullIPTag = ec2SingleTag[1].split('.') 28 #remove the CIDR from ip to get the last octect 29 lastIPsTag = fullIPTag[3].split('/') 30 lastOctect = lastIPsTag[0] 31 ipList.append(int(lastOctect)) 32 print ipList 33 largestIP = 0 34 for latestIP in ipList: 35 if latestIP &gt; largestIP: 36 largestIP = latestIP 37 print latestIP 38 print largestIP 39 return largestIP </code></pre> <p>and the result:</p> <pre><code>[13, 5, 3, 12, 16] 13 16 [13, 5, 3, 12, 16, 6] 13 16 [13, 5, 3, 12, 16, 6, 1] 13 16 [13, 5, 3, 12, 16, 6, 1, 11] 13 16 [13, 5, 3, 12, 16, 6, 1, 11, 15] 13 16 [13, 5, 3, 12, 16, 6, 1, 11, 15, 17] 13 16 17 </code></pre> <p>Note it found 17.</p>
1
2016-10-19T05:44:57Z
40,123,538
<p>The code is quite convoluted (much more than needed) but the error is that <code>ipList</code> gets filled with strings and then its elements are compared with an integer.</p> <p>This in Python 2 was a silent source of problems (you got a nonsensical but stable <code>True</code>/<code>False</code> result when comparing different types instead of an error) and in Python 3 it became an error.</p> <p>a much simpler implementation would in my opinion be:</p> <pre><code>return max(int(x.split(",")[1].split("/")[0].split(".")[-1]) for x in taglist) </code></pre> <p>with the meaning:</p> <ul> <li><code>split(",")[1]</code> to take the part after the comma</li> <li><code>split("/")[0]</code> to take the part before the slash</li> <li><code>split(".")[-1]</code> to take the last part of IP address</li> <li><code>int(...)</code> to convert to integer</li> <li><code>max(... for x in taglist</code> to do this for all elements and keeping the max</li> </ul> <p>or using a regexp with</p> <pre><code>return max(int(re.match(".*?([0-9]+)/", x).group(1)) for x in taglist) </code></pre>
1
2016-10-19T06:13:22Z
[ "python", "list", "loops", "integer" ]
python loop to find the largest integer from a list
40,123,112
<p>I wrote a script to pull down a list of aws tags and then read the last octect and tell me which one is the highest IP. For example. here is the list of tags that are returned:</p> <p>['vlslabmc, 172.16.0.13/24', 'vlslabmc,172.16.0.5/24', 'vlslabmc,172.16.0.3/24', 'vlslabmc,172.16.0.12/24', 'vlslabmc,172.16.0.16/24', 'vlslabmc,172.16.0.6/24', 'vlslabmc,172.16.0.1/24', 'vlslabmc,172.16.0.11/24', 'vlslabmc,172.16.0.15/24', 'vlslabmc,172.16.0.17/24', 'vlslabmc,172.16.0.4/24', 'vlslabmc,172.16.0.7/24', 'vlslabmc,172.16.0.10/24', 'vlslabmc,172.16.0.9/24', 'vlslabmc,172.16.0.8/24', 'vlslabmc,172.16.0.2/24', 'vlslabmc,172.16.0.14/24']</p> <p>Here's my code to workout the largest IP from the tagLis (note that the largest is 17, 172.16.0.17)</p> <pre><code> 21 def findLargestIP(): 22 for i in tagList: 23 #remove all the spacing in the tags 24 ec2Tags = i.strip() 25 #seperate any multiple tags 26 ec2SingleTag = ec2Tags.split(',') 27 #find the last octect of the ip address 28 fullIPTag = ec2SingleTag[1].split('.') 29 #remove the CIDR from ip to get the last octect 30 lastIPsTag = fullIPTag[3].split('/') 31 lastOctect = lastIPsTag[0] 32 ipList.append(lastOctect) 33 largestIP = int(ipList[0]) 34 for latestIP in ipList: 35 if int(latestIP) &gt; largestIP: 36 largestIP = latestIP 37 return largestIP </code></pre> <p>I'm not sure why.. but when I print the value of largestIP it always prints out 16. Ive gone through the code it should have worked <strong>(I'm avoiding using the max function as I'm just learning to code)</strong></p> <p>Any help as aways is greatly appreciated.</p> <p>Thanks</p> <h2><strong>Edit with the answer below, and a question</strong></h2> <p>Ok so thanks to a clue from cmarie I got it working the problem was mainly</p> <pre><code>33 largestIP = int(ipList[0]) </code></pre> <p>Here's the code running before with an added print statement on the list append:</p> <pre><code>'13'] ['13', '5'] ['13', '5', '3'] ['13', '5', '3', '12'] ['13', '5', '3', '12', '16'] 16 ['13', '5', '3', '12', '16', '6'] 16 ['13', '5', '3', '12', '16', '6', '1'] 16 ['13', '5', '3', '12', '16', '6', '1', '11'] 16 ... ... ['13', '5', '3', '12', '16', '6', '1', '11', '15', '17', '4', '7', '10', '9', '8', '2'] 16 ['13', '5', '3', '12', '16', '6', '1', '11', '15', '17', '4', '7', '10', '9', '8', '2', '14'] 16 </code></pre> <p>Basically what was happening is that during this loop :</p> <pre><code>33 largestIP = int(ipList[0]) 34 for latestIP in ipList: 35 if int(latestIP) &gt; largestIP: 36 largestIP = latestIP </code></pre> <p>The loop stops at the 1st largest integer. in this case that is 16. <strong>*I'm not sure why it does but it does</strong></p> <p>Here's the working code:</p> <pre><code>19 def findLargestIP(): 20 ipList =[] 21 for i in tagList: 22 #remove all the spacing in the tags 23 ec2Tags = i.strip() 24 #seperate any multiple tags 25 ec2SingleTag = ec2Tags.split(',') 26 #find the last octect of the ip address 27 fullIPTag = ec2SingleTag[1].split('.') 28 #remove the CIDR from ip to get the last octect 29 lastIPsTag = fullIPTag[3].split('/') 30 lastOctect = lastIPsTag[0] 31 ipList.append(int(lastOctect)) 32 print ipList 33 largestIP = 0 34 for latestIP in ipList: 35 if latestIP &gt; largestIP: 36 largestIP = latestIP 37 print latestIP 38 print largestIP 39 return largestIP </code></pre> <p>and the result:</p> <pre><code>[13, 5, 3, 12, 16] 13 16 [13, 5, 3, 12, 16, 6] 13 16 [13, 5, 3, 12, 16, 6, 1] 13 16 [13, 5, 3, 12, 16, 6, 1, 11] 13 16 [13, 5, 3, 12, 16, 6, 1, 11, 15] 13 16 [13, 5, 3, 12, 16, 6, 1, 11, 15, 17] 13 16 17 </code></pre> <p>Note it found 17.</p>
1
2016-10-19T05:44:57Z
40,123,866
<p>Although other people have already provide you some alternative ways to find the answer, if you want to keep using your program, here is some way of fixing it:</p> <pre><code>def findLargestIP(): ipList = [] for i in tagList: #remove all the spacing in the tags ec2Tags = i.strip() #seperate any multiple tags ec2SingleTag = ec2Tags.split(',') #find the last octect of the ip address fullIPTag = ec2SingleTag[1].split('.') #remove the CIDR from ip to get the last octect lastIPsTag = fullIPTag[3].split('/') lastOctect = lastIPsTag[0] ipList.append(int(lastOctect)) largestIP = 0 for latestIP in ipList: if latestIP &gt; largestIP: largestIP = latestIP return largestIP </code></pre> <p>The differences from this and your program are that here I:</p> <ul> <li>set <code>ipList = []</code></li> <li>make ipList contain integers, rather than strings</li> <li>set <code>largestIP = 0</code>, instead of taking the first number of the ipList (since you shouldn't assume the list is sorted)</li> <li>remove the loop to find the largest number outside the first loop [on the <code>tagList</code>] - just for eliminating unnecessary iterations</li> </ul> <p>If I would do that task, however, I would try to use regular expressions. Here is a way to do it:</p> <pre><code>import re def alternativeFindLargestIP(): ipList = re.findall(r'(?&lt;=\.)\d+(?=/)', ' '.join(tagList)) ipList = [int(num) for num in ipList] return max(ipList) </code></pre>
2
2016-10-19T06:34:21Z
[ "python", "list", "loops", "integer" ]