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
sequence
Python 2.7 encoding from csv file
40,103,127
<p>I have a problem with Python 2.7 encoding I have a csv file with some french characters (mangé, parlé, prêtre ...), the code I'm using is the following:</p> <pre><code>import pandas as pd path_dataset = 'P:\\Version_python\\Dataset\\data_set - Copy.csv' dataset = pd.read_csv(path_dataset, sep=';') for lab, row in dataset.iterrows(): print(row['Summary']) </code></pre> <p>I tried to add <code>encoding</code> to <code>read_csv()</code>, it didn't work. I tried <code>unicode</code>, <code>decode</code>(UTF-8) ... Nothing worked.</p> <p>Then I tried to concatenate those extracted words with some text, and I got a utf-8 error, I don't know how to deal with that. Thanks</p>
1
2016-10-18T08:21:55Z
40,103,412
<p>Here is a list of standard python encodings</p> <p><a href="https://docs.python.org/2/library/codecs.html" rel="nofollow">Standard Python 2.7 encodings</a></p> <p><code>utf-8</code> does not work but you can try some other encodings on the link above.</p> <p>Just tested <code>latin_1</code> works. So the code should be:</p> <pre><code>dataset = pd.read_csv(path_dataset, sep=';', encoding='latin_1') </code></pre>
2
2016-10-18T08:37:34Z
[ "python", "python-2.7", "pandas" ]
Generator that yields subpatterns of an original pattern with zeros introduced
40,103,182
<p>I have the following problem in which I want to generate patterns with a 0 introduced. The problem is that this should be space efficient, and thus I would like to use a generator that creates and returns one of the patterns at a time (i.e. I do not want to create a list and return it.) I am at a loss here because I don't know what I am doing wrong in calling the generator, so any help would be appreciated!</p> <p>original pattern = [ 0. 1. 1. 2.] generator should generate and return these: [ 0. 0. 1. 2.], [0. 1. 0. 2.], [ 0. 1. 1. 0.]</p> <p>However I can just yield one of the patterns with a call to the generator (the additional 1.0 is not an issue just to not cause any confusion...) and not all of them in succession. </p> <p>yielded subpattern = (array([ 0., 1., 0., 2.]), 1.0)</p> <p>The following is my code:</p> <pre><code>import numpy as np def removeoneletter(subpattern): # generator = [] originalpattern = subpattern subpatterncopy = subpattern.copy() nonzero = np.nonzero(subpattern) listnonzero = nonzero[0].tolist() # only replace elements at nonzero positions with zero for i in listnonzero: subpatterncopy = subpattern.copy() position = i transaction = subpatterncopy[i] np.put(subpatterncopy, position, 0) print('subpattern generator') print(subpatterncopy) # generator.append((subpatterncopy, transaction)) yield((subpatterncopy, transaction)) if i == len(listnonzero): break </code></pre> <p>and the function gets called by another function like so:</p> <pre><code>def someotherfunction(): combinations = removeoneletter(subpatterncopy) for x in combinations: # x = next(combinations) print('yielded subpattern') print(x) </code></pre>
0
2016-10-18T08:25:05Z
40,105,619
<p>Not being an numpy expert, this part looks a bit weird to me:</p> <pre><code>for i in listnonzero: .... if i == len(listnonzero): break </code></pre> <p>Your for loop assigns elements of listnonzero to i, and then you test that against the length of the list. If the listnonzero had five elements [5,42,6,77,12] and the first element you pick from the list happens to be number 5, you would break the loop and exit after the first iteration. </p> <p>Your code would (probably) work in Javascript or similar where "for i in something" assigns an index to i instead of a list member. </p> <p>If this does not help, try removing yield and adding a print statement there to see if your listnonzero and i are what you expect them to be. </p> <p>Just a thought. </p> <p>Hannu</p>
0
2016-10-18T10:20:39Z
[ "python", "generator", "yield" ]
kNN - How to locate the nearest neighbors in the training matrix based on the calculated distances
40,103,226
<p>I am trying to implement k-nearest neighbor algorithm using python. I ended up with the following code. However, I am struggling with finding the index of the items that are the nearest neighbors. The following function will return the distance matrix. However I need to get the indices of these neighbors in the <code>features_train</code> (the input matrix to the algorithm). </p> <pre><code>def find_kNN(k, feature_matrix, query_house): alldistances = np.sort(compute_distances(feature_matrix, query_house)) dist2kNN = alldistances[0:k+1] for i in range(k,len(feature_matrix)): dist = alldistances[i] j = 0 #if there is closer neighbor if dist &lt; dist2kNN[k]: #insert this new neighbor for d in range(0, k): if dist &gt; dist2kNN[d]: j = d + 1 dist2kNN = np.insert(dist2kNN, j, dist) dist2kNN = dist2kNN[0: len(dist2kNN) - 1] return dist2kNN print find_kNN(4, features_train, features_test[2]) </code></pre> <p>Output is:</p> <pre><code>[ 0.0028605 0.00322584 0.00350216 0.00359315 0.00391858] </code></pre> <p>Can someone help me to identify these nearest items in the <code>features_train</code>?</p>
0
2016-10-18T08:27:45Z
40,103,836
<p>I will suggest to use the python library <code>sklearn</code> that has a <code>KNeighborsClassifier</code> from which, once fitted, you can retrieve the nearest neighbors you are looking for :</p> <p>Try this out:</p> <pre><code># Import from sklearn.neighbors import KNeighborsClassifier # Instanciate your classifier neigh = KNeighborsClassifier(n_neighbors=4) #k=4 or whatever you want # Fit your classifier neigh.fit(X, y) # Where X is your training set and y is the training_output # Get the neighbors neigh.kneighbors(X_test, return_distance=False) # Where X_test is the sample or array of samples from which you want to get the k-nearest neighbors </code></pre>
1
2016-10-18T08:58:54Z
[ "python", "numpy", "machine-learning", "knn" ]
IronPython add Unicode characters at the start of a file
40,103,241
<p>I use a script to update the version of each AssemblyVersion.cs file of a .NET project. It always worked perfectly, but since a format my PC, it adds unicode character at the start of each .cs file edited. Like this:</p> <pre><code>using System.Reflection; using System.Runtime.InteropServices; using System.Security; </code></pre> <p>I use this code to open a file:</p> <pre><code>with open(fname, "r") as f: out_fname = fname + ".tmp" out = codecs.open(out_fname, "w", encoding='utf-8') textInFile="" for line in f: textInFile += (re.sub(pat, s_after,line)) out.write(u'\uFEFF') out.write(textInFile) out.close() os.remove(fname) os.rename(out_fname, fname) </code></pre> <p>I've also tried, as wrote <a href="http://stackoverflow.com/questions/19591458/python-reading-from-a-file-and-saving-to-utf-8">here</a>, to use <code>io</code> instead of <code>codecs</code>, but nothing is changed.</p> <p>On other teammates' PCs it works with the same configuration (Win10 and IronPython 2.7).</p> <p>What can I try to solve this issue? Where can I looking for the problem?</p> <p>Thanks</p>
0
2016-10-18T08:28:33Z
40,105,368
<p>It seems that the files at your file system are using ISO-8859-1 encoding, while you are adding the UT8 BOM marker at the beginning of each file. </p> <p>After your code does it's job, you get a file with UTF-8 BOM + ISO-8859-1 meta at the beginning.</p> <p>I would check the encoding of your input files before modification with Notepad++ (or any other editor) just to see if the scenario I described is valid. If it is, you will need to read your input files with a different encoding in order to avoid the metadata:</p> <pre><code>with open(fname, "r", "ISO-8859-1") as f: ... </code></pre>
0
2016-10-18T10:08:35Z
[ "c#", "python", "unicode", "encoding", "ironpython" ]
Recursive dictionary walking in python
40,103,514
<p>I am new to python and trying to create a recursive dictionary walker that outputs a path to each item in the dictionary.</p> <p>Below is my code including some sample data. The goal is to import weather data from weather underground and publish into mqtt topics on a raspberry pi. (The mqtt code all runs fine and is independent of this, for this I just need to generate the paths)</p> <p>The issue that I am having is that when I reach the 'forecastday' element of the dict, my function is returning what looks like json data instead of recursing further into the path.</p> <p>I have tried a few methods of walking the dict, but when the examples started getting into 'generators' etc, things were starting to get above my head a little.</p> <p>(The test data does not contain any private information, it is the general weather report for my nearest town)</p> <p>Thanks</p> <pre><code>import json def print_path(root, data, path): for element in data.keys(): if not isinstance(data[element], dict): print root + path + element, data[element] else: print_path(root, data[element], element+"/") json_string = u'{"response":{"version":"0.1","termsofService":"http://www.wunderground.com/weather/api/d/terms.html","features":{"almanac":1,"astronomy":1,"conditions":1,"forecast":1}},"current_observation":{"image":{"url":"http://icons.wxug.com/graphics/wu2/logo_130x80.png","title":"Weather Underground","link":"http://www.wunderground.com"},"display_location":{"full":"Llanelli, United Kingdom","city":"Llanelli","state":"","state_name":"United Kingdom","country":"UK","country_iso3166":"GB","zip":"00000","magic":"11","wmo":"03605","latitude":"51.67610931","longitude":"-4.15666723","elevation":"17.00000000"},"observation_location":{"full":"Llanelli, CARMARTHENSHIRE","city":"Llanelli","state":"CARMARTHENSHIRE","country":"GB","country_iso3166":"GB","latitude":"51.679951","longitude":"-4.140789","elevation":"40 ft"},"estimated":{},"station_id":"ICARMART4","observation_time":"Last Updated on October 18, 8:07 AM BST","observation_time_rfc822":"Tue, 18 Oct 2016 08:07:38 +0100","observation_epoch":"1476774458","local_time_rfc822":"Tue, 18 Oct 2016 08:07:44 +0100","local_epoch":"1476774464","local_tz_short":"BST","local_tz_long":"Europe/London","local_tz_offset":"+0100","weather":"Mostly Cloudy","temperature_string":"49.0 F (9.4 C)","temp_f":49.0,"temp_c":9.4,"relative_humidity":"90%","wind_string":"From the West at 4.5 MPH Gusting to 6.9 MPH","wind_dir":"West","wind_degrees":272,"wind_mph":4.5,"wind_gust_mph":"6.9","wind_kph":7.2,"wind_gust_kph":"11.1","pressure_mb":"1019","pressure_in":"30.09","pressure_trend":"0","dewpoint_string":"46 F (8 C)","dewpoint_f":46,"dewpoint_c":8,"heat_index_string":"NA","heat_index_f":"NA","heat_index_c":"NA","windchill_string":"47 F (9 C)","windchill_f":"47","windchill_c":"9","feelslike_string":"47 F (9 C)","feelslike_f":"47","feelslike_c":"9","visibility_mi":"6.2","visibility_km":"10.0","solarradiation":"--","UV":"0","precip_1hr_string":"0.00 in ( 0 mm)","precip_1hr_in":"0.00","precip_1hr_metric":" 0","precip_today_string":"0.07 in (2 mm)","precip_today_in":"0.07","precip_today_metric":"2","soil_moisture":"255.0","icon":"mostlycloudy","icon_url":"http://icons.wxug.com/i/c/k/mostlycloudy.gif","forecast_url":"http://www.wunderground.com/global/stations/03605.html","history_url":"http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=ICARMART4","ob_url":"http://www.wunderground.com/cgi-bin/findweather/getForecast?query=51.679951,-4.140789","nowcast":""},"forecast":{"txt_forecast":{"date":"7:03 AM BST","forecastday":[{"period":0,"icon":"partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif","title":"Tuesday","fcttext":"Sun and clouds mixed. High around 55F. Winds WNW at 10 to 20 mph.","fcttext_metric":"Sun and clouds mixed. High 12C. Winds WNW at 15 to 30 km/h.","pop":"0"},{"period":1,"icon":"nt_partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/nt_partlycloudy.gif","title":"Tuesday Night","fcttext":"Partly cloudy skies. Low 43F. Winds WNW at 5 to 10 mph.","fcttext_metric":"Partly cloudy. Low 6C. Winds WNW at 10 to 15 km/h.","pop":"10"},{"period":2,"icon":"partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif","title":"Wednesday","fcttext":"Partly cloudy skies in the morning will give way to cloudy skies during the afternoon. High 56F. Winds NW at 10 to 15 mph.","fcttext_metric":"Partly to mostly cloudy. High 13C. Winds NW at 15 to 25 km/h.","pop":"10"},{"period":3,"icon":"nt_partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/nt_partlycloudy.gif","title":"Wednesday Night","fcttext":"A few clouds. Low 41F. Winds N at 5 to 10 mph.","fcttext_metric":"Partly cloudy. Low around 5C. Winds N at 10 to 15 km/h.","pop":"10"},{"period":4,"icon":"partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif","title":"Thursday","fcttext":"Intervals of clouds and sunshine. High 59F. Winds N at 5 to 10 mph.","fcttext_metric":"Partly cloudy skies. High around 15C. Winds N at 10 to 15 km/h.","pop":"10"},{"period":5,"icon":"nt_partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/nt_partlycloudy.gif","title":"Thursday Night","fcttext":"Partly cloudy. Low 41F. Winds NE at 5 to 10 mph.","fcttext_metric":"Partly cloudy. Low near 5C. Winds NE at 10 to 15 km/h.","pop":"10"},{"period":6,"icon":"partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif","title":"Friday","fcttext":"Intervals of clouds and sunshine. High 58F. Winds E at 5 to 10 mph.","fcttext_metric":"Sunshine and clouds mixed. High 14C. Winds E at 10 to 15 km/h.","pop":"10"},{"period":7,"icon":"nt_partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/nt_partlycloudy.gif","title":"Friday Night","fcttext":"Partly cloudy. Low 44F. Winds E at 5 to 10 mph.","fcttext_metric":"Partly cloudy. Low 6C. Winds E at 10 to 15 km/h.","pop":"10"}]},"simpleforecast":{"forecastday":[{"date":{"epoch":"1476813600","pretty":"7:00 PM BST on October 18, 2016","day":18,"month":10,"year":2016,"yday":291,"hour":19,"min":"00","sec":0,"isdst":"1","monthname":"October","monthname_short":"Oct","weekday_short":"Tue","weekday":"Tuesday","ampm":"PM","tz_short":"BST","tz_long":"Europe/London"},"period":1,"high":{"fahrenheit":"55","celsius":"13"},"low":{"fahrenheit":"43","celsius":"6"},"conditions":"Partly Cloudy","icon":"partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif","skyicon":"","pop":0,"qpf_allday":{"in":0.00,"mm":0},"qpf_day":{"in":0.00,"mm":0},"qpf_night":{"in":0.00,"mm":0},"snow_allday":{"in":0.0,"cm":0.0},"snow_day":{"in":0.0,"cm":0.0},"snow_night":{"in":0.0,"cm":0.0},"maxwind":{"mph":20,"kph":32,"dir":"WNW","degrees":293},"avewind":{"mph":16,"kph":26,"dir":"WNW","degrees":293},"avehumidity":71,"maxhumidity":0,"minhumidity":0},{"date":{"epoch":"1476900000","pretty":"7:00 PM BST on October 19, 2016","day":19,"month":10,"year":2016,"yday":292,"hour":19,"min":"00","sec":0,"isdst":"1","monthname":"October","monthname_short":"Oct","weekday_short":"Wed","weekday":"Wednesday","ampm":"PM","tz_short":"BST","tz_long":"Europe/London"},"period":2,"high":{"fahrenheit":"56","celsius":"13"},"low":{"fahrenheit":"41","celsius":"5"},"conditions":"Partly Cloudy","icon":"partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif","skyicon":"","pop":10,"qpf_allday":{"in":0.00,"mm":0},"qpf_day":{"in":0.00,"mm":0},"qpf_night":{"in":0.00,"mm":0},"snow_allday":{"in":0.0,"cm":0.0},"snow_day":{"in":0.0,"cm":0.0},"snow_night":{"in":0.0,"cm":0.0},"maxwind":{"mph":15,"kph":24,"dir":"NW","degrees":318},"avewind":{"mph":12,"kph":19,"dir":"NW","degrees":318},"avehumidity":79,"maxhumidity":0,"minhumidity":0},{"date":{"epoch":"1476986400","pretty":"7:00 PM BST on October 20, 2016","day":20,"month":10,"year":2016,"yday":293,"hour":19,"min":"00","sec":0,"isdst":"1","monthname":"October","monthname_short":"Oct","weekday_short":"Thu","weekday":"Thursday","ampm":"PM","tz_short":"BST","tz_long":"Europe/London"},"period":3,"high":{"fahrenheit":"59","celsius":"15"},"low":{"fahrenheit":"41","celsius":"5"},"conditions":"Partly Cloudy","icon":"partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif","skyicon":"","pop":10,"qpf_allday":{"in":0.00,"mm":0},"qpf_day":{"in":0.00,"mm":0},"qpf_night":{"in":0.00,"mm":0},"snow_allday":{"in":0.0,"cm":0.0},"snow_day":{"in":0.0,"cm":0.0},"snow_night":{"in":0.0,"cm":0.0},"maxwind":{"mph":10,"kph":16,"dir":"N","degrees":2},"avewind":{"mph":7,"kph":11,"dir":"N","degrees":2},"avehumidity":78,"maxhumidity":0,"minhumidity":0},{"date":{"epoch":"1477072800","pretty":"7:00 PM BST on October 21, 2016","day":21,"month":10,"year":2016,"yday":294,"hour":19,"min":"00","sec":0,"isdst":"1","monthname":"October","monthname_short":"Oct","weekday_short":"Fri","weekday":"Friday","ampm":"PM","tz_short":"BST","tz_long":"Europe/London"},"period":4,"high":{"fahrenheit":"58","celsius":"14"},"low":{"fahrenheit":"44","celsius":"7"},"conditions":"Partly Cloudy","icon":"partlycloudy","icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif","skyicon":"","pop":10,"qpf_allday":{"in":0.00,"mm":0},"qpf_day":{"in":0.00,"mm":0},"qpf_night":{"in":0.00,"mm":0},"snow_allday":{"in":0.0,"cm":0.0},"snow_day":{"in":0.0,"cm":0.0},"snow_night":{"in":0.0,"cm":0.0},"maxwind":{"mph":10,"kph":16,"dir":"E","degrees":91},"avewind":{"mph":7,"kph":11,"dir":"E","degrees":91},"avehumidity":79,"maxhumidity":0,"minhumidity":0}]}},"moon_phase":{"percentIlluminated":"93","ageOfMoon":"17","phaseofMoon":"Waning Gibbous","hemisphere":"North","current_time":{"hour":"8","minute":"07"},"sunrise":{"hour":"7","minute":"46"},"sunset":{"hour":"18","minute":"15"},"moonrise":{"hour":"20","minute":"10"},"moonset":{"hour":"10","minute":"24"}},"sun_phase":{"sunrise":{"hour":"7","minute":"46"},"sunset":{"hour":"18","minute":"15"}},"almanac":{"airport_code":"EGFF","temp_high":{"normal":{"F":"55","C":"12"},"record":{"F":"66","C":"18"},"recordyear":"1997"},"temp_low":{"normal":{"F":"46","C":"7"},"record":{"F":"33","C":"0"},"recordyear":"1998"}}}' weather_report = json.loads(json_string) print_path("dev/blah/weather/", weather_report, "") </code></pre> <p>EDIT>></p> <p>This is some of the output that I get from the script</p> <pre><code>... dev/blah/weather/sunrise/minute 46 dev/blah/weather/sunrise/hour 7 dev/blah/weather/sunset/minute 15 dev/blah/weather/sunset/hour 18 dev/blah/weather/sunrise/minute 46 dev/blah/weather/sunrise/hour 7 dev/blah/weather/txt_forecast/date 7:03 AM BST dev/blah/weather/txt_forecast/forecastday [{u'title': u'Tuesday', u'icon_url': u'http://icons.wxug.com/i/c/k/partlycloudy.gif', u'fcttext_metric': u'Sun and clouds mixed. High 12C. Winds WNW at 15 to 30 km/h.', u'period': 0, u'pop': u'0', u'fcttext': u'Sun and clouds mixed. High around 55F. Winds WNW at 10 to 20 mph.', u'icon': u'partlycloudy'}, {u'title': u'Tuesday Night', u'icon_url': u'http://icons.wxug.com/i/c/k/nt_partlycloudy.gif', u'fcttext_metric': u'Partly cloudy. Low 6C. Winds WNW at 10 to 15 km/h.', u'period': 1, u'pop': u'10', u'fcttext': u'Partly cloudy skies. Low 43F. Winds WNW at 5 to 10 mph.', u'icon': u'nt_partlycloudy'}, {u'title': u'Wednesday', u'icon_url': u'http://icons.wxug.com/i/c/k/partlycloudy.gif', u'fcttext_metric': u'Partly to mostly cloudy. High 13C. Winds NW at 15 to 25 km/h.', u'period': 2, u'pop': u'10', u'fcttext': u'Partly cloudy skies in the morning will give way to cloudy skies during the afternoon. </code></pre> <p>For the last entry here it should say</p> <pre><code>dev/blah/weather/txt_forecast/forecastday/0/title Tuesday dev/blah/weather/txt_forecast/forecastday/0/icon partlycloudy </code></pre> <p>but instead it shows</p> <pre><code>[{u'title': u'Tuesday', u'icon_url': u'http://icons.wxug.com/i/c/k/partlycloudy.gif', u'fcttext_metric': u'Sun and clouds mixed. High 12C. Winds WNW at 15 to 30 km/h.', u'perio... </code></pre>
0
2016-10-18T08:42:34Z
40,103,951
<p>Just mix-in a regular for-loop into that recursion to iterate over the lists. </p> <pre><code>def print_path(root, data, path): for element, val in data.items(): if isinstance(val, dict): print_path(root, val, element+"/") elif isinstance(val, list): list_path = path+element+"/" for i, item in enumerate(val): print_path(root, item, list_path+str(i)+"/") else: print root + path + element, val </code></pre> <p>Should see <code>dev/blah/weather/txt_forecast/forecastday/0/title Tuesday</code> in the output</p>
0
2016-10-18T09:04:13Z
[ "python", "json", "dictionary", "recursion", "python-2.x" ]
python post request not working with Minio server import
40,103,817
<p>I have a problem with POST request with Python/Django and Minio server, this is the code</p> <pre><code>from django.http import HttpResponse import json from minio import Minio minioClient = Minio('mypath:9000', access_key='mykey', secret_key='mysecret', secure=False) def getMessage(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) for obj in data['files']: ...do some stuff.... minioClient.fget_object(myvar, myvar2, '/tmp/processing') return HttpResponse(file) </code></pre> <p>The problem is that the request won't work if I don't remove the import at the beginning and I can't understand why. This is the error generated:</p> <pre><code>HTTPConnectionPool(host='myhost', port=8001): Max retries exceeded with url: /myurl/ (Caused NewConnectionError ('&lt;requests.packages.urllib3.connection.HTTPConnection object at 0x7fcbeab21160&gt;: Failed to establish a new connection: [Errno 111] Connection refused',)) </code></pre> <p>and this is the script that make the request is this one:</p> <pre><code>.... some code.... try: r = requests.post("http://myurl:8001/mypath/", data=my_data, timeout=1) except Exception as e: print(e) </code></pre> <p>I've already tried to increase the timeout but it's not working and of course, I've tested the Minio part in another script, the import it's generating this error only in this request script.</p> <p>Thanks for the help</p>
0
2016-10-18T08:58:08Z
40,105,405
<p>From docs for urllib3: </p> <blockquote> <p>request(method, url, fields=None, headers=None, **urlopen_kw)¶ Make a request using urlopen() with the appropriate encoding of fields based on the method used.</p> </blockquote> <p>Maybe you could try something like this:</p> <pre><code>r = http.request('POST', "http://myurl:8001/mypath/", headers={'Content-Type': 'application/json'}, body=encoded_data) </code></pre>
1
2016-10-18T10:10:45Z
[ "python", "django", "post", "request", "minio" ]
Why am I unable to correctly retrieve and use a QTableWidgetItem?
40,103,845
<p>I looked up the documentation for creating QTableWidgetItems, and it says that I need to use the <code>item()</code> method. "Returns the item for the given row and column if one has been set; otherwise returns 0." Here is how I used it:</p> <p><code>self.table.item(item.row(),1)</code></p> <p>There definitely is an item at these values. <code>item.row()</code> is the row associated with an item in the same row I am trying to return. everything about that item is working fine, and <code>.text()</code> returns the correct information. I got that item by using <code>self.table.itemChanged.connect(self.log_change)</code></p> <p>for some reason it is just this item that I am trying to return that doesn't work. when I go <code>print(self.table.item(item.row(),1).text())</code> it prints nothing, just an empty string. The value it should print is <code>int(0)</code></p> <p>surrounding with <code>int()</code> doesn't work.</p> <p>Is there some way I can select or return the item at that row and column, and have <code>.text()</code> give the <code>int(0)</code> that is in there as a result? Why would it just be printing an empty string when the QTableWidget shows the number 0?</p> <p>Edit:</p> <pre><code> self.cur.execute("""SELECT s.StudentID, s.FullName, m.PreviouslyMailed, m.nextMail, m.learnersDate, m.RestrictedDate, m.DefensiveDate FROM StudentProfile s LEFT JOIN Mailouts m ON s.studentID=m.studentID""") self.all_data = self.cur.fetchall() self.search_results() self.table.setRowCount(len(self.all_data)) self.tableFields = ["Check","REMOVE THIS","Full name","Previously mailed?","Next mail","learners date","Restricted date","Defensive driving date"] self.columnList = ["StudentID","FullName","PreviouslyMailed","NextMail","learnersDate","RestrictedDate","DefensiveDate"] self.table.setColumnCount(len(self.tableFields)) self.table.setHorizontalHeaderLabels(self.tableFields) self.checkbox_list = [] for i, item in enumerate(self.all_data): FullName = QtGui.QTableWidgetItem(str(item[1])) PreviouslyMailed = QtGui.QComboBox() PreviouslyMailed_combobox_list = ["No", "Yes"] PreviouslyMailed.addItems(PreviouslyMailed_combobox_list) LearnersDate = QtGui.QTableWidgetItem(str(item[4])) RestrictedDate = QtGui.QTableWidgetItem(str(item[5])) DefensiveDate = QtGui.QTableWidgetItem(str(item[6])) NextMail = QtGui.QTableWidgetItem(str(item[3])) StudentID = QtGui.QTableWidgetItem(item[0]) self.table.setItem(i, 1, StudentID) self.table.setItem(i, 2, FullName) self.table.setCellWidget(i, 3, PreviouslyMailed) self.table.setItem(i, 4, LearnersDate) self.table.setItem(i, 5, RestrictedDate) self.table.setItem(i, 6, DefensiveDate) self.table.setItem(i, 7, NextMail) chkBoxItem = QtGui.QTableWidgetItem() chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) chkBoxItem.setCheckState(QtCore.Qt.Unchecked) self.checkbox_list.append(chkBoxItem) self.table.setItem(i, 0, self.checkbox_list[i]) FullName.setFlags(FullName.flags() &amp; ~Qt.ItemIsEditable) NextMail.setFlags(NextMail.flags() &amp; ~Qt.ItemIsEditable) self.table.blockSignals(False) self.changed_items = [] self.table.itemChanged.connect(self.log_change) def log_change(self, item): self.table.blockSignals(False) self.changed_items.append((self.table.itemAt(item.row(),1),item)) def click_btn_edit(self): print("Updating") IDList = [] for item in self.changed_items: text, col, row = item[1].text(), item[1].column(), item[1].row() new_data = self.all_data IDvar = item[0].text() #IDvar prints as an empty string. IDList.append(IDvar) </code></pre> <p>second edit:</p> <pre><code>import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4 import * import sqlite3 from datetime import datetime import calendar import sip sip.setapi('QVariant', 2) class WindowContainer(): def __init__(self): self.windows = [] def _fromUtf8(t): return t class mainWindowTemplate(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.setObjectName(_fromUtf8("mainWindowTemplate")) self.resize(800, 600) self.centralwidget = QtGui.QWidget(self) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.gridLayout = QtGui.QGridLayout(self.centralwidget) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.table = QtGui.QTableWidget(self.centralwidget) self.table.setObjectName(_fromUtf8("table")) self.table.setColumnCount(0) self.table.setRowCount(0) self.gridLayout.addWidget(self.table, 0, 0, 1, 1) self.btn_edit = QtGui.QPushButton(self.centralwidget) self.btn_edit.setObjectName(_fromUtf8("btn_edit")) self.gridLayout.addWidget(self.btn_edit, 1, 0, 1, 1) self.setCentralWidget(self.centralwidget) self.btn_edit.clicked.connect(self.click_btn_edit) self.menubar = QtGui.QMenuBar(self) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21)) self.menubar.setObjectName(_fromUtf8("menubar")) self.setMenuBar(self.menubar) """self.statusbar = QtGui.QStatusBar(self) self.statusbar.setObjectName(_fromUtf8("statusbar")) self.setStatusBar(self.statusbar)""" self.setWindowTitle("MainWindow") self.btn_edit.setText("Edit") self.conn = sqlite3.connect("EDA_Database.db") self.cur = self.conn.cursor() QtCore.QMetaObject.connectSlotsByName(self) self.show() self.click_btn_mailingInfo() def retranslateUi(self): self.setWindowTitle(_translate("MainWindow", "MainWindow", None)) def click_btn_mailingInfo(self): self.table.blockSignals(True) self.screen_name = "mailingInfo" self.cur.execute("""SELECT s.StudentID, s.FullName, m.PreviouslyMailed, m.nextMail, m.learnersDate, m.RestrictedDate, m.DefensiveDate FROM StudentProfile s LEFT JOIN Mailouts m ON s.studentID=m.studentID""") self.all_data = self.cur.fetchall() self.table.setRowCount(len(self.all_data)) self.tableFields = ["Check","If you see this column, an error has occured.","Full name","Previously mailed?","Next mail","learners date","Restricted date","Defensive driving date"] self.columnList = ["StudentID","FullName","PreviouslyMailed","NextMail","learnersDate","RestrictedDate","DefensiveDate"] self.table.setColumnCount(len(self.tableFields)) self.table.setHorizontalHeaderLabels(self.tableFields) self.checkbox_list = [] for i, item in enumerate(self.all_data): FullName = QtGui.QTableWidgetItem(str(item[1])) PreviouslyMailed = QtGui.QComboBox() PreviouslyMailed_combobox_list = ["No", "Yes"] PreviouslyMailed.addItems(PreviouslyMailed_combobox_list) LearnersDate = QtGui.QTableWidgetItem(str(item[4])) RestrictedDate = QtGui.QTableWidgetItem(str(item[5])) DefensiveDate = QtGui.QTableWidgetItem(str(item[6])) NextMail = QtGui.QTableWidgetItem(str(item[3])) StudentID = QtGui.QTableWidgetItem(str(item[0])) self.table.setItem(i, 1, StudentID) self.table.setItem(i, 2, FullName) self.table.setCellWidget(i, 3, PreviouslyMailed) self.table.setItem(i, 4, LearnersDate) self.table.setItem(i, 5, RestrictedDate) self.table.setItem(i, 6, DefensiveDate) self.table.setItem(i, 7, NextMail) chkBoxItem = QtGui.QTableWidgetItem() chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) chkBoxItem.setCheckState(QtCore.Qt.Unchecked) self.checkbox_list.append(chkBoxItem) self.table.setItem(i, 0, self.checkbox_list[i]) FullName.setFlags(FullName.flags() &amp; ~Qt.ItemIsEditable) NextMail.setFlags(NextMail.flags() &amp; ~Qt.ItemIsEditable) self.table.setColumnHidden(1, True) self.table.blockSignals(False) self.changed_items = [] self.combobox_item_list = [] self.table.itemChanged.connect(self.log_change) #PreviouslyMailed.currentIndexChanged.connect(self.comboBox_change(None,None,row,1,self.table.cellWidget(row,1).currentText())) def log_change(self, item): self.table.blockSignals(False) self.changed_items.append((self.table.item(item.row(),1),item)) def click_btn_edit(self): IDList = [] for item in self.changed_items: text, col, row = item[1].text(), item[1].column(), item[1].row() new_data = self.all_data IDvar = item[0].text() #no longer works print(text) #now works print(IDvar) IDList.append(IDvar) if __name__ == "__main__": container = WindowContainer() app = QApplication(sys.argv) container.windows.append(mainWindowTemplate()) sys.exit(app.exec_()) </code></pre>
1
2016-10-18T08:59:30Z
40,120,594
<p>If you look at the qt docs for QTableWidgetItem, you will see that it can only be constructed from another item, from a string, from an icon and a string, or from an integer representing the type id of the item. You are giving the constructor the student ID directly, so it is using that last constructor, which creates an empty item. So, use this:</p> <pre><code>StudentID = QtGui.QTableWidgetItem(str(item[0])) </code></pre> <p>Once that is fixed, you still have the issue that you are connecting to the table itemChanged signal in click_btn_mailingInfo. Verify that this function is only called once (in particular disable line for us to connection s by name to see if it makes a difference). </p>
0
2016-10-19T01:26:16Z
[ "python", "pyqt" ]
Alternative for matshow()
40,103,855
<p>I have a <code>101x101</code> matrix that I want to visualize graphically. So far I used the function <code>matshow</code> from <code>matplotlib.pyplot</code> as below:</p> <pre><code>import numpy as np import random import matplotlib.pyplot as plt A = np.zeros((101,101)) # do stuff to randomly change some values of A plt.ion() plt.matshow(A,cmap='PuBuGn') plt.colorbar() plt.show() </code></pre> <p>The output looks like this: <a href="https://i.stack.imgur.com/IBCLa.png" rel="nofollow"><img src="https://i.stack.imgur.com/IBCLa.png" alt="enter image description here"></a></p> <p>You should view this as an interaction matrix between species, and as you can see there are only three species strongly interacting. That is why it looks appropriate to consider a visualization like the following graph I found in a <a href="http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1004688" rel="nofollow">paper</a>, but I do not know if and how this can be implemented in Python:</p> <p><a href="https://i.stack.imgur.com/X4xBy.png" rel="nofollow"><img src="https://i.stack.imgur.com/X4xBy.png" alt="enter image description here"></a></p>
2
2016-10-18T08:59:52Z
40,109,202
<p>This should do the trick:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def old_graph(A): plt.matshow(A,cmap='PuBuGn') plt.colorbar() plt.title(r"abs$\left(\left[\mathbf{A}_{ij} \right ] \right )$ ; SIS=%d"%(sis,), va='bottom') plt.show() def new_graph(A, sis_list=np.zeros(0,int), symmetric=True, fig=None, pos=111): #create and edit figure: if fig is None: fig = plt.figure() ax = fig.add_subplot(pos, projection='polar') ax.set_rgrids([1],[' ']) ax.set_rmax(1) ax.set_thetagrids([]) ax.set_title(r"abs$\left(\left[\mathbf{A}_{ij} \right ] \right )$ ; SIS=%d"%(sis,), va='bottom') colormap = plt.get_cmap('PuBuGn') # make each species an angle value: n_species = A.shape[0] angles = np.linspace(0, 2*np.pi, n_species+1) # the radius will always be r_max, and each line # will always unite two points: r = np.ones((2,)) # prepare list of lines to sort: unordered_pairs_and_values = [] for index_line in xrange(n_species): for index_column in xrange(index_line): if symmetric: value = A[index_line,index_column] else: # not symmetric value= abs(A[index_line,index_column]- A[index_column,index_line]) unordered_pairs_and_values.append([[angles[index_line],angles[index_column]], value]) # sort the lines (otherwise white lines would cover the 'important' ones): ordered_pairs_and_values = sorted(unordered_pairs_and_values, key=lambda pair: pair[1]) # get the maximum value for scaling: I_max = ordered_pairs_and_values[-1][1] # plot every line in order: for pair in ordered_pairs_and_values: ax.plot(pair[0], r, color=colormap(pair[1]/I_max), linewidth=2, alpha=0.8) # don't know how to add the colorbar: #fig.colorbar(orientation='horizontal') # mark the angles: ax.plot(angles, np.ones(angles.shape), 'ko') # mark the important angles (comment if you don't know which ones are these): ax.plot(angles[sis_list], np.ones(sis_list.shape), 'ro') fig.show() if __name__ == '__main__': n_species = 51 sis = 3 # strongly interacting species sis_factor = 4. A = np.zeros((n_species,n_species)) # do stuff to randomly change some values of A: for index_line in xrange(n_species): for index_column in xrange(index_line+1): A[index_line,index_column] = np.random.random() A[index_column,index_line] = A[index_line,index_column] sis_list = np.random.randint(0,n_species,sis) for species in sis_list: A[species,:] *= sis_factor A[:,species] *= sis_factor for species2 in sis_list: # correct crossings A[species,species2] /= sis_factor # stuff to randomly change some values of A done old_graph(A=A) new_graph(A=A, sis_list=sis_list, symmetric=True) </code></pre> <p>Old graph: <a href="https://i.stack.imgur.com/HqjqG.png" rel="nofollow"><img src="https://i.stack.imgur.com/HqjqG.png" alt="old_graph"></a></p> <p>New graph: <a href="https://i.stack.imgur.com/QYcSZ.png" rel="nofollow"><img src="https://i.stack.imgur.com/QYcSZ.png" alt="enter image description here"></a> I still don't know:</p> <ul> <li>how to enter the colorbar, since it requires a plot that was mapped using a colormap.</li> <li>how to remove the r-ticks without rescaling the graph (you can try uncomment <code>#ax.set_rticks([])</code>)</li> </ul> <p>And the plot looks better with less interacting species: <a href="https://i.stack.imgur.com/mm73A.png" rel="nofollow"><img src="https://i.stack.imgur.com/mm73A.png" alt="enter image description here"></a> </p>
3
2016-10-18T13:08:31Z
[ "python", "matrix", "matplotlib" ]
Python delete a value from dictionary and not the key
40,103,876
<p>Is it possible to delete a value from a dictionary and not the key? For instance, I have the following code in which the user selects the key corresponding to the element that he wants to delete it , but I want do delete only the value and not the key ( the value is a list): </p> <pre><code>if (selection == 2): elem = int(input("Please select the KEY that you want to be deleted: ")) if dictionar.has_key(elem): #dictionar.pop(elem) del dictionar[elem] else: print("the KEY is not present ") </code></pre>
-1
2016-10-18T09:01:04Z
40,103,910
<p>No, it is not possible. Dictionaries consist of key/value pairs. You cannot have a key without a value. The best you can do is set that key's value to <code>None</code> or some other sentinel value, or use a different data structure that better suits your needs.</p>
4
2016-10-18T09:02:26Z
[ "python" ]
Python delete a value from dictionary and not the key
40,103,876
<p>Is it possible to delete a value from a dictionary and not the key? For instance, I have the following code in which the user selects the key corresponding to the element that he wants to delete it , but I want do delete only the value and not the key ( the value is a list): </p> <pre><code>if (selection == 2): elem = int(input("Please select the KEY that you want to be deleted: ")) if dictionar.has_key(elem): #dictionar.pop(elem) del dictionar[elem] else: print("the KEY is not present ") </code></pre>
-1
2016-10-18T09:01:04Z
40,103,960
<pre><code>dictionar = {} elem = int(input("Please select the KEY that you want to be deleted: ")) if dictionar.has_key(elem) dictionar[elem] = "" else: print("The KEY is not present") </code></pre> <p>This code checks if elem is in dictionar then turns the value into a blank string.</p>
-1
2016-10-18T09:04:50Z
[ "python" ]
Python delete a value from dictionary and not the key
40,103,876
<p>Is it possible to delete a value from a dictionary and not the key? For instance, I have the following code in which the user selects the key corresponding to the element that he wants to delete it , but I want do delete only the value and not the key ( the value is a list): </p> <pre><code>if (selection == 2): elem = int(input("Please select the KEY that you want to be deleted: ")) if dictionar.has_key(elem): #dictionar.pop(elem) del dictionar[elem] else: print("the KEY is not present ") </code></pre>
-1
2016-10-18T09:01:04Z
40,104,263
<p>Dictionaries are data structures with <code>{key:value}</code> pairs.</p> <p>To work with values, you can do replace the value with some other value or <code>None</code> like below:</p> <pre><code>dic = {} e = int(input("KEY to be deleted/replaced: ")) if dic.has_key(e): r = int(input("New value to put in or just press ENTER for no new value")) if not r: r=None dic[e]=r else: print("Key Absent") </code></pre>
0
2016-10-18T09:18:57Z
[ "python" ]
SqlAlchemy+pymssql. Will raw parametrized queries use same execution plan?
40,103,917
<p>In my application I have parametrized queries like this:</p> <pre><code>res = db_connection.execute(text(""" SELECT * FROM Luna_gestiune WHERE id_filiala = :id_filiala AND anul=:anul AND luna = :luna """), id_filiala=6, anul=2010, luna=7).fetchone() </code></pre> <p>Will such query use same query execution plan if I run it in loop with different parameter values?</p>
1
2016-10-18T09:02:41Z
40,118,291
<p>I'm guessing that it's unlikely, because pymssql performs the parameter substitution <em>before</em> sending the query to the server, unlike some other mechanisms that send the query "template" and the parameters separately (e.g., pyodbc, as described in <a href="http://stackoverflow.com/a/40065211/2144390">this answer</a>).</p> <p>That is, for the query you describe in your question, pymssql will not send a query string like</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM Luna_gestiune WHERE id_filiala = @P1 AND anul = @P2 AND luna = @P3 </code></pre> <p>along with separate values for @P1 = 6, @P2 = 2010, etc.. Instead it will build the literal query first, and then send</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM Luna_gestiune WHERE id_filiala = 6 AND anul = 2010 AND luna = 7 </code></pre> <p>So for each parameteized query you send, the SQL command text will be different, and my understanding is that database engines will only re-use a cached execution plan if the current command text is <em>identical</em> to the cached version.</p> <p><strong>Edit:</strong> Subsequent testing confirms that pymssql apparently <em>does not</em> re-use cached execution plans. Details in <a href="http://stackoverflow.com/a/40156617/2144390">this answer</a>.</p>
0
2016-10-18T21:21:53Z
[ "python", "sqlalchemy", "pymssql" ]
Move console cursor up
40,103,919
<p>I tried to create a simple clock up the top-left corner of the screen, updating every second:</p> <pre><code>def clock(): threading.Timer(1.0, clock).start() print('\033[0;0H' + time.asctime(time.localtime())) </code></pre> <p>I've used threading and the colorama module, but it seems the escape code just move the cursor the number of pixels specified, and not to the position.</p> <hr> <p>How can I move the cursor to the position <code>(0, 0)</code>?</p>
0
2016-10-18T09:02:50Z
40,104,556
<p>The line and column start at 1 not 0.</p> <pre><code>print('\033[1;1H' + time.asctime(time.localtime())) </code></pre> <p>or shorter</p> <pre><code>print('\033[H' + time.asctime(time.localtime())) </code></pre> <p>You might also need to save and restore position using ESC-7 and ESC-8.</p> <p>See <a href="http://ascii-table.com/ansi-escape-sequences-vt-100.php" rel="nofollow">http://ascii-table.com/ansi-escape-sequences-vt-100.php</a> for a list of codes.</p> <p>Barry</p>
1
2016-10-18T09:31:47Z
[ "python", "shell", "printing", "console", "cursor" ]
Serializing a JSON object for a Django URL
40,104,130
<p>I have a JSON object that looks like this:</p> <pre><code>var obj = { "selection":[ { "author":"John Doe", "articles":[ "Article One", "Article Two" ] } ] } </code></pre> <p>I want to pass this object to Django to render a view that displays 'Article One' and 'Article Two' upon render. I first serialize the JSON object so that it can be appended to a URL; I use <code>$.param(obj)</code> for serialization. Now the JSON object looks something like this:</p> <pre><code>"selection%5B0%5D%5Bauthor%5D=John+Doe&amp;selection%5B0%5D%5Barticles%5D%5B%5D=Article+One&amp;selection%5B0%5D%5Barticles%5D%5B%5D=Article+Two" </code></pre> <p>Now I can append this to a path and use <code>window.open(url)</code> the view will handle everything else. On the Django end, I was surprised to see that the structure of the JSON object has changed to this:</p> <pre><code>"selection[0][author]=John+Doe&amp;selection[0][articles][]=Article+One&amp;selection[0][articles][]=Article+Two" </code></pre> <p>I want to be able to use the JSON object as a dict e.g.:</p> <pre><code>obj = request.GET.get('selection') obj = json.loads(obj) print(obj[0].author) ... </code></pre> <p>How should I handle this JSON structure on the Django side of things?</p>
0
2016-10-18T09:12:42Z
40,104,486
<p>You are not properly serializing the object to JSON, even if you say you do. The correct way would be to use <code>JSON.stringify()</code>, as @dunder states.</p> <p>Than you parse it back to an object with <code>JSON.parse(strignifiedJson)</code>.</p> <pre><code>var obj = { "selection":[ { "author":"John Doe", "articles":[ "Article One", "Article Two" ] } ] } // Stringify and encode var objAsParam = encodeURIComponent(JSON.stringify(obj)); // Send as a param, for example like http://example.com?obj=YourStringifiedObject... // Parse it back: var parsedObj = JSON.parse(decodeURIComponent(objAsParam)); </code></pre>
0
2016-10-18T09:29:00Z
[ "javascript", "python", "json", "django" ]
How can i run a command on the command prompt with a batch file and keep running it for 'n' seconds?
40,104,259
<p>How can i run a command on the command prompt with a batch file and keep running it for 'n' seconds ? and then close it automatically ? (All in Background i.e without opening the console)</p>
-1
2016-10-18T09:18:53Z
40,104,432
<p>Use the <code>subprocess</code> module. You may be interested in <code>subprocess.run</code> and its <code>timeout</code> argument if you are using a newer version of Python (i.e. 3.5.x). If not, take a look at <code>subprocess.Popen</code>.</p> <blockquote> <p>The timeout argument is passed to Popen.communicate(). If the timeout expires, the child process will be killed and waited for. The TimeoutExpired exception will be re-raised after the child process has terminated.</p> </blockquote> <hr> <p>Reference: <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="nofollow">https://docs.python.org/3/library/subprocess.html#subprocess.run</a></p>
0
2016-10-18T09:26:45Z
[ "python", "python-2.7", "python-3.x", "command-line", "subprocess" ]
How can i run a command on the command prompt with a batch file and keep running it for 'n' seconds?
40,104,259
<p>How can i run a command on the command prompt with a batch file and keep running it for 'n' seconds ? and then close it automatically ? (All in Background i.e without opening the console)</p>
-1
2016-10-18T09:18:53Z
40,104,485
<p>Create any python(.py) file and run it like</p> <p><code>c:\python27\python.exe &lt;path_of_the_file&gt;/filename.py</code></p> <p>To keep running it over say, 1000 times:</p> <p><code>for /l %x in (1, 1, 1000) do c:\python27\python.exe &lt;path_of_the_file&gt;/filename.py</code></p> <p>Note: Assuming your python is installed at c:\python27\</p>
2
2016-10-18T09:28:55Z
[ "python", "python-2.7", "python-3.x", "command-line", "subprocess" ]
Django admin foreign key values custom form
40,104,291
<p>So, I have a model Puzzle and a model Piece. Piece has as foreignKey to Puzzle. And on the admin, on puzzle form to add a new element, i have a stackedInLine for pieces. But i can only add more if I enter all the data from the piece. Is there a way to add new Pieces to the puzzle by choosing from a dropdown with the Piece values already stored on the DB ?? I google'd forever and found nothing....thanks. So what I have is:</p> <pre><code>class Puzzle(models.Model): name = models.CharField(max_length=200) class Piece(models.Model): name = models.CharField(max_length=200) puzzle = models.ForeignKey(Puzzle, null=True) </code></pre> <p>And on the django backend, when I am editing a puzzle I would like to choose from a dropdown of all the Piece models stored on the DB and "assign" them to the current puzzle i'm editing. Is this possible? I'm at the moment using: </p> <pre><code>class PieceInline(admin.StackedInline): model = Piece extra = 1 class PuzzleAdmin(admin.ModelAdmin): model = Piece inlines = (PieceInLine, ) </code></pre> <p>So I have a stackedinline of pieces on the puzzle form, but I can only create new ones...</p>
0
2016-10-18T09:20:07Z
40,104,657
<p>What if you create a new model, say:</p> <pre><code>from django.dispatch import receiver class PieceSelector(models.Model): piece = models.ForeignKey(Piece) def __unicode__(self): return piece.some_field @receiver(post_save, sender=Piece) def piece_post_save_signal_receiver(sender, **kwargs): if kwargs['created']: PieceSelector.objects.create(piece=kwargs['instance']) </code></pre> <p>Now, when you create a Piece model object, you should create PieceSelector object too. You can do it using post_save signal of the Piece model and it will provide all the pieces in a dropdown.</p> <p>When in the admin.py, use PieceSelector as a StackedInline for Puzzle model.</p>
1
2016-10-18T09:36:24Z
[ "python", "django" ]
Issiue with implementation of 2D Discrete Cosine Transform in Python
40,104,377
<p>I'm trying to rewrite Zhao Koch steganography method from matlab into python and I am stuck right at the start.</p> <p>The first two procedures as they are in matlab:</p> <p>Step 1:</p> <pre><code>A = imread(casepath); # Reading stegonography case image and aquiring it's RGB values. In my case it's a 400x400 PNG image, so it gives a 400x400x3 array. </code></pre> <p>Step 2:</p> <pre><code>D = dct2(A(:,:,3)); # Applying 2D DCT to blue values of the image </code></pre> <p>Python code analog:</p> <pre><code>from scipy import misc from numpy import empty,arange,exp,real,imag,pi from numpy.fft import rfft,irfft arr = misc.imread('casepath')# 400x480x3 array (Step 1) arr[20, 30, 2] # Getting blue pixel value def dct(y): #Basic DCT build from numpy N = len(y) y2 = empty(2*N,float) y2[:N] = y[:] y2[N:] = y[::-1] c = rfft(y2) phi = exp(-1j*pi*arange(N)/(2*N)) return real(phi*c[:N]) def dct2(y): #2D DCT bulid from numpy and using prvious DCT function M = y.shape[0] N = y.shape[1] a = empty([M,N],float) b = empty([M,N],float) for i in range(M): a[i,:] = dct(y[i,:]) for j in range(N): b[:,j] = dct(a[:,j]) return b D = dct2(arr) # step 2 anlogue </code></pre> <p>However, when I try to execute the code I get the following error:</p> <pre><code>Traceback (most recent call last): File "path to .py file", line 31, in &lt;module&gt; D = dct2(arr) File "path to .py file", line 25, in dct2 a[i,:] = dct(y[i,:]) File "path to .py file", line 10, in dct y2[:N] = y[:] ValueError: could not broadcast input array from shape (400,3) into shape (400) </code></pre> <p>Perhaps someone could kindly explain to me what am I doing wrong?</p> <p>Additional Info: OS: Windows 10 Pro 64 bit Python: 2.7.12 scipy:0.18.1 numpy:1.11.2 pillow: 3.4.1</p>
0
2016-10-18T09:24:28Z
40,109,427
<p>Your code works fine, but it is designed to only accept a 2D array, just like <a href="https://uk.mathworks.com/help/images/ref/dct2.html" rel="nofollow"><code>dct2()</code></a> in Matlab. Since your <code>arr</code> is a 3D array, you want to do</p> <pre><code>D = dct2(arr[...,2]) </code></pre> <p>As mentioned in my comment, instead or reinventing the wheel, use the (fast) built-in <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.fftpack.dct.html" rel="nofollow"><code>dct()</code></a> from the scipy package.</p> <p>The code from the link in my comment effectively provides you this:</p> <pre><code>import numpy as np from scipy.fftpack import dct, idct def dct2(block): return dct(dct(block.T, norm='ortho').T, norm='ortho') def idct2(block): return idct(idct(block.T, norm='ortho').T, norm='ortho') </code></pre> <p>But again, I must stress that <strong>you have to call this function for each colour plane individually</strong>. Scipy's <code>dct()</code> will happily accept any N-dimensional array and will apply the transform on the last axis. Since that's your colour planes and not your rows and columns of your pixels, you'll get the wrong result. Yes, there is a way to address this with the <code>axis</code> input parameter, but I won't unnecessarily overcomplicate this answer.</p> <hr> <p>Regarding the various DCT implementations involved here, your version and scipy's implementation give the same result if you omit the <code>norm='ortho'</code> parameter from the snippet above. But with that parameter included, scipy's transform will agree with Matlab's.</p>
1
2016-10-18T13:18:59Z
[ "python", "matlab", "dct" ]
how to access GET query string multidimensional arrays in bottle python
40,104,438
<p>I know how to get individual values from keys such as:</p> <pre><code>some_val = request.query.some_key </code></pre> <p>But how do you access values when you have a url like this.</p> <p>Sample url : <a href="http://blahblah.com/what?draw=1&amp;columns%5B0%5D%5Bdata%5D=source_url&amp;columns%5B0%5D%5Bname%5D=&amp;columns%5B0%5D%5Bsearchable%5D=true&amp;columns%5B0%5D%5Borderable%5D=true&amp;columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B1%5D%5Bdata%5D=total_size&amp;columns%5B1%5D%5Bname%5D=&amp;columns%5B1%5D%5Bsearchable%5D=true&amp;columns%5B1%5D%5Borderable%5D=true&amp;columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B2%5D%5Bdata%5D=total_time&amp;columns%5B2%5D%5Bname%5D=&amp;columns%5B2%5D%5Bsearchable%5D=true&amp;columns%5B2%5D%5Borderable%5D=true&amp;columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B3%5D%5Bdata%5D=tag_name&amp;columns%5B3%5D%5Bname%5D=&amp;columns%5B3%5D%5Bsearchable%5D=true&amp;columns%5B3%5D%5Borderable%5D=true&amp;columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&amp;order%5B0%5D%5Bcolumn%5D=0&amp;order%5B0%5D%5Bdir%5D=asc&amp;start=0&amp;length=10&amp;search%5Bvalue%5D=&amp;search%5Bregex%5D=false&amp;_=1476782117541" rel="nofollow">http://blahblah.com/what?draw=1&amp;columns%5B0%5D%5Bdata%5D=source_url&amp;columns%5B0%5D%5Bname%5D=&amp;columns%5B0%5D%5Bsearchable%5D=true&amp;columns%5B0%5D%5Borderable%5D=true&amp;columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B1%5D%5Bdata%5D=total_size&amp;columns%5B1%5D%5Bname%5D=&amp;columns%5B1%5D%5Bsearchable%5D=true&amp;columns%5B1%5D%5Borderable%5D=true&amp;columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B2%5D%5Bdata%5D=total_time&amp;columns%5B2%5D%5Bname%5D=&amp;columns%5B2%5D%5Bsearchable%5D=true&amp;columns%5B2%5D%5Borderable%5D=true&amp;columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&amp;columns%5B3%5D%5Bdata%5D=tag_name&amp;columns%5B3%5D%5Bname%5D=&amp;columns%5B3%5D%5Bsearchable%5D=true&amp;columns%5B3%5D%5Borderable%5D=true&amp;columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&amp;columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&amp;order%5B0%5D%5Bcolumn%5D=0&amp;order%5B0%5D%5Bdir%5D=asc&amp;start=0&amp;length=10&amp;search%5Bvalue%5D=&amp;search%5Bregex%5D=false&amp;_=1476782117541</a></p> <p>What the params look like decoded:</p> <pre><code>_ 1476782117541 columns[0][data] source_url columns[0][name] columns[0][orderable] true columns[0][search][regex] false columns[0][search][value] columns[0][searchable] true columns[1][data] total_size columns[1][name] columns[1][orderable] true columns[1][search][regex] false columns[1][search][value] columns[1][searchable] true columns[2][data] total_time columns[2][name] columns[2][orderable] true columns[2][search][regex] false columns[2][search][value] columns[2][searchable] true columns[3][data] tag_name columns[3][name] columns[3][orderable] true columns[3][search][regex] false columns[3][search][value] columns[3][searchable] true draw 1 length 10 order[0][column] 0 order[0][dir] asc search[regex] false search[value] start 0 </code></pre> <p>I have tried </p> <pre><code>request.query.getall('order') </code></pre> <p>or </p> <pre><code>request.query.decode() </code></pre> <p>I am trying to parse the params that are sent automatically by datatables so i can modify my query accordingly. </p>
0
2016-10-18T09:26:58Z
40,122,808
<p>Since this question pertains to using <a href="https://datatables.net/" rel="nofollow">https://datatables.net/</a> with a bottle python backend. What i ended up doing is formatting the args on the client side like so. Maybe you'll find it useful.</p> <pre><code>$('#performance-table').DataTable( { "ajax": { "url" : "http://someapi.com/dt_set", "type": 'GET', "beforeSend": function (request) { request.setRequestHeader("Authorization", "Bearer " + token); }, data: function ( args ) { margs = {} margs.page_nr = args.draw; margs.how_many = args.length; margs.sort_column = args.columns[args.order[0].column].data; margs.sort_direction = args.order[0].dir; //return args; return margs; } }, "processing": true, "serverSide": true, "columns": [ { "data": "source_url" }, { "data": "total_size" }, { "data": "total_time" }, { "data": "tag_name" } ] }); </code></pre>
0
2016-10-19T05:24:16Z
[ "python", "get", "query-string", "bottle" ]
Pandas - Calculating daily differences relative to earliest value
40,104,449
<p>This is probably pretty easy, but for some reason I am finding it quite difficult to complete. Any tips would be greatly appreciated. I have some time series data consisting of 5-minute intervals each day, ala:</p> <pre><code>Date Values 2012-12-05 09:30:00 5 2012-12-05 09:35:00 7 2012-12-05 09:40:00 3 2012-12-05 09:45:00 2 2012-12-05 09:50:00 15 2012-12-06 09:30:00 4 2012-12-06 09:35:00 3 2012-12-06 09:40:00 8 2012-12-06 09:45:00 1 </code></pre> <p>I would like to calculate the differences relative to the first value of the day (which in this case always will be the 9:30 value), ie. end up with this DataFrame:</p> <pre><code>Date Values 2012-12-05 09:30:00 0 2012-12-05 09:35:00 2 2012-12-05 09:40:00 -2 2012-12-05 09:45:00 -3 2012-12-05 09:50:00 10 2012-12-06 09:30:00 0 2012-12-06 09:35:00 -1 2012-12-06 09:40:00 4 2012-12-06 09:45:00 -3 </code></pre>
2
2016-10-18T09:27:38Z
40,104,518
<p>You can use broadcasting:</p> <pre><code>df.Values - df.Values.iloc[0] </code></pre>
1
2016-10-18T09:30:09Z
[ "python", "pandas", "resampling" ]
Pandas - Calculating daily differences relative to earliest value
40,104,449
<p>This is probably pretty easy, but for some reason I am finding it quite difficult to complete. Any tips would be greatly appreciated. I have some time series data consisting of 5-minute intervals each day, ala:</p> <pre><code>Date Values 2012-12-05 09:30:00 5 2012-12-05 09:35:00 7 2012-12-05 09:40:00 3 2012-12-05 09:45:00 2 2012-12-05 09:50:00 15 2012-12-06 09:30:00 4 2012-12-06 09:35:00 3 2012-12-06 09:40:00 8 2012-12-06 09:45:00 1 </code></pre> <p>I would like to calculate the differences relative to the first value of the day (which in this case always will be the 9:30 value), ie. end up with this DataFrame:</p> <pre><code>Date Values 2012-12-05 09:30:00 0 2012-12-05 09:35:00 2 2012-12-05 09:40:00 -2 2012-12-05 09:45:00 -3 2012-12-05 09:50:00 10 2012-12-06 09:30:00 0 2012-12-06 09:35:00 -1 2012-12-06 09:40:00 4 2012-12-06 09:45:00 -3 </code></pre>
2
2016-10-18T09:27:38Z
40,104,547
<p>You need substract by <code>Series</code> created <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow"><code>transform</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.date.html" rel="nofollow"><code>Series.dt.date</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.first.html" rel="nofollow"><code>first</code></a>:</p> <pre><code>print (df.Values.groupby(df.Date.dt.day).transform('first')) 0 5 1 5 2 5 3 5 4 5 5 4 6 4 7 4 8 4 Name: Values, dtype: int64 df.Values = df.Values - df.Values.groupby(df.Date.dt.day).transform('first') print (df) Date Values 0 2012-12-05 09:30:00 0 1 2012-12-05 09:35:00 2 2 2012-12-05 09:40:00 -2 3 2012-12-05 09:45:00 -3 4 2012-12-05 09:50:00 10 5 2012-12-06 09:30:00 0 6 2012-12-06 09:35:00 -1 7 2012-12-06 09:40:00 4 8 2012-12-06 09:45:00 -3 </code></pre>
1
2016-10-18T09:31:07Z
[ "python", "pandas", "resampling" ]
How to create a field with a list of foreign keys in SQLAlchemy?
40,104,502
<p>I am trying to store a list of models within the field of another model. Here is a trivial example below, where I have an existing model, <code>Actor</code>, and I want to create a new model, <code>Movie</code>, with the field <code>Movie.list_of_actors</code>:</p> <pre><code>import uuid from sqlalchemy import Boolean, Column, Integer, String, DateTime from sqlalchemy.schema import ForeignKey rom sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship Base = declarative_base() class Actor(Base): __tablename__ = 'actors' id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) name = Column(String) nickname = Column(String) academy_awards = Column(Integer) # This is my new model: class Movie(Base): __tablename__ = 'movies' id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) title = Column(String) # How do I make this a list of foreign keys??? list_of_actors = Column(UUID(as_uuid=True), ForeignKey('actors.id')) </code></pre> <p>I understand that this can be done with a many-to-many relationship, but is there a more simple solution? <strong>Note that I don't need to look up which <code>Movie</code>'s an <code>Actor</code> is in</strong> - I just want to create a new <code>Movie</code> model and access the list of my <code>Actor</code>'s. And ideally, I would prefer not to add any new fields to my <code>Actor</code> model.</p> <p>I've gone through the tutorials using the <a href="http://docs.sqlalchemy.org/en/latest/orm/relationship_api.html#sqlalchemy.orm.relationship" rel="nofollow">relationships API</a>, which outlines the various one-to-many/many-to-many combinations using <code>back_propagates</code> and <code>backref</code> here: <a href="http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html</a> But I can't seem to implement my list of foreign keys without creating a full-blown many-to-many implementation.</p> <p>But if a many-to-many implementation is the only way to proceed, is there a way to implement it without having to create an "association table"? The "association table" is described here: <a href="http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/basic_relationships.html#many-to-many</a> ? Either way, an example would be very helpful!</p> <hr> <p>Also, if it matters, I am using Postgres 9.5. I see from <a href="http://stackoverflow.com/questions/21932489/how-to-make-array-field-with-foreign-key-constraint-in-sqlalchemy">this post</a> there might be support for arrays in Postgres, so any thoughts on that could be helpful.</p>
0
2016-10-18T09:29:23Z
40,104,800
<p>If you want many actors to be associated to a movie, and many movies be associated to an actor, you want a many-to-many. This means you need an association table. Otherwise, you could chuck away normalisation and use a NoSQL database.</p> <p>An association table solution might resemble:</p> <pre><code>class Actor(Base): __tablename__ = 'actors' id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) name = Column(String) nickname = Column(String) academy_awards = Column(Integer) class Movie(Base): __tablename__ = 'movies' id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) title = Column(String) actors = relationship('ActorMovie', uselist=True, backref='movies') class ActorMovie(Base): __tablename__ = 'actor_movies' actor_id = Column(UUID(as_uuid=True), ForeignKey('actors.id')) movie_id = Column(UUID(as_uuid=True), ForeignKey('movies.id')) </code></pre> <p>If you don't want ActorMovie to be an object inheriting from Base, you could use <code>sqlachlemy.schema.Table</code>.</p>
1
2016-10-18T09:42:26Z
[ "python", "postgresql", "sqlalchemy", "foreign-keys", "foreign-key-relationship" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and deleting a bigger one, if elements are equal function delete both of them. ''</p> </blockquote> <p>For example:</p> <ul> <li>la = ['bear', 'tiger', 'wolf', 'whale', 'elephant'] </li> <li>lb = ['swan', 'cat', 'dog', 'duck', 'rabbit']</li> </ul> <p>So the functin should return: ['bear','elephant'] ['cat','dog','duck']</p> <p>I have wrote the next code but it doesn't modify lists but create new ones and add there elements. Some ideas how can i do that?</p> <pre><code>def confront(s1, s2): if s1 &lt; s2: # condition that tells which element to choose later return 0 elif s2 &lt; s1: return 1 else: return 2 def modi(la,lb): latemp = [] lbtemp = [] i = 0 while i &lt; len(la): q = confront(la[i], lb[i]) if q == 0: latemp.append(la[i]) elif q == 1: lbtemp.append(lb[i]) i +=1 la = latemp lb = lbtemp return la, lb </code></pre> <p>I have tried remove() but it have created a big mess</p>
0
2016-10-18T09:29:44Z
40,104,686
<p>You should use <code>del</code> to delete list item. Also you should iterate from end to the beginning because if you will go from the beginning and delete let say <code>1st</code> element the element that was on the <code>3rd</code> place will be now on the <code>2nd</code></p> <p>It should look like</p> <pre><code>#you need to handle what if len of lists is 0, if lens are not the same and so on... def compare_and_delete(list1, list2): i = len(list1) -1 while i &gt;= 0: if list1[i] &gt; list2[i]: del list1[i] elif list2[i] &gt; list1[i]: del list2[i] else: del list1[i] del list2[i] i-=1 return list1, list2 l1, l2 = compare_and_delete(['bear', 'tiger', 'wolf', 'whale', 'elephant'], ['swan', 'cat', 'dog', 'duck', 'rabbit']) </code></pre>
0
2016-10-18T09:37:43Z
[ "python", "list", "python-3.x" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and deleting a bigger one, if elements are equal function delete both of them. ''</p> </blockquote> <p>For example:</p> <ul> <li>la = ['bear', 'tiger', 'wolf', 'whale', 'elephant'] </li> <li>lb = ['swan', 'cat', 'dog', 'duck', 'rabbit']</li> </ul> <p>So the functin should return: ['bear','elephant'] ['cat','dog','duck']</p> <p>I have wrote the next code but it doesn't modify lists but create new ones and add there elements. Some ideas how can i do that?</p> <pre><code>def confront(s1, s2): if s1 &lt; s2: # condition that tells which element to choose later return 0 elif s2 &lt; s1: return 1 else: return 2 def modi(la,lb): latemp = [] lbtemp = [] i = 0 while i &lt; len(la): q = confront(la[i], lb[i]) if q == 0: latemp.append(la[i]) elif q == 1: lbtemp.append(lb[i]) i +=1 la = latemp lb = lbtemp return la, lb </code></pre> <p>I have tried remove() but it have created a big mess</p>
0
2016-10-18T09:29:44Z
40,104,774
<p>You can take advantage of the fact that assigning to a slice modifies the list:</p> <pre><code>la[:] = latemp lb[:] = lbtemp </code></pre>
-2
2016-10-18T09:41:33Z
[ "python", "list", "python-3.x" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and deleting a bigger one, if elements are equal function delete both of them. ''</p> </blockquote> <p>For example:</p> <ul> <li>la = ['bear', 'tiger', 'wolf', 'whale', 'elephant'] </li> <li>lb = ['swan', 'cat', 'dog', 'duck', 'rabbit']</li> </ul> <p>So the functin should return: ['bear','elephant'] ['cat','dog','duck']</p> <p>I have wrote the next code but it doesn't modify lists but create new ones and add there elements. Some ideas how can i do that?</p> <pre><code>def confront(s1, s2): if s1 &lt; s2: # condition that tells which element to choose later return 0 elif s2 &lt; s1: return 1 else: return 2 def modi(la,lb): latemp = [] lbtemp = [] i = 0 while i &lt; len(la): q = confront(la[i], lb[i]) if q == 0: latemp.append(la[i]) elif q == 1: lbtemp.append(lb[i]) i +=1 la = latemp lb = lbtemp return la, lb </code></pre> <p>I have tried remove() but it have created a big mess</p>
0
2016-10-18T09:29:44Z
40,104,814
<p>Generally, when you're mutating a list while iterating over it. It's good practice to iterate over a copy instead. Below is an example of what you would do to mutate one list.</p> <pre><code>list = [] list_copy = list[:] for i in list_copy: list.remove(i) return list </code></pre> <p>This allows you to maintain the correct index per iteration.</p> <p>Below is my attempt to explain what I meant and using a for loop to get your expected result. Hope it helps.</p> <pre><code>def confront(s1, s2): if s1 &lt; s2: # condition that tells which element to choose later return 0 elif s2 &lt; s1: return 1 else: return 2 def modi(la,lb): la_copy = la[:] lb_copy = lb[:] for i in range(len(la_copy)): q = confront(la_copy[i], lb_copy[i]) if q == 0: lb.remove(lb_copy[i]) elif q == 1: la.remove(la_copy[i]) return la, lb la = ['bear', 'tiger', 'wolf', 'whale', 'elephant'] lb = ['swan', 'cat', 'dog', 'duck', 'rabbit'] </code></pre> <p>Calling it via a print() will get the returned two lists.</p> <p>Note: this returns a tuple. IF you'd like seperate lists call it via the following.</p> <pre><code>list1, list2 = modi(la,lb) print(list1) print(list2) ['bear', 'elephant'] ['cat', 'dog', 'duck'] </code></pre>
0
2016-10-18T09:42:53Z
[ "python", "list", "python-3.x" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and deleting a bigger one, if elements are equal function delete both of them. ''</p> </blockquote> <p>For example:</p> <ul> <li>la = ['bear', 'tiger', 'wolf', 'whale', 'elephant'] </li> <li>lb = ['swan', 'cat', 'dog', 'duck', 'rabbit']</li> </ul> <p>So the functin should return: ['bear','elephant'] ['cat','dog','duck']</p> <p>I have wrote the next code but it doesn't modify lists but create new ones and add there elements. Some ideas how can i do that?</p> <pre><code>def confront(s1, s2): if s1 &lt; s2: # condition that tells which element to choose later return 0 elif s2 &lt; s1: return 1 else: return 2 def modi(la,lb): latemp = [] lbtemp = [] i = 0 while i &lt; len(la): q = confront(la[i], lb[i]) if q == 0: latemp.append(la[i]) elif q == 1: lbtemp.append(lb[i]) i +=1 la = latemp lb = lbtemp return la, lb </code></pre> <p>I have tried remove() but it have created a big mess</p>
0
2016-10-18T09:29:44Z
40,104,979
<p>This will solve your problem. I think it's easier than all other solutions.</p> <pre><code>def modi(la, lb): new_la = [] new_lb = [] for a, b in zip(la, lb): if a == b: continue if a &gt; b: new_lb.append(b) if a &lt; b: new_la.append(a) return new_la, new_lb </code></pre> <p>If You, however, want to change EXISTING lists, You could do this:</p> <pre><code>def modi(la, lb): del_la = [] del_lb = [] for i, (a, b) in enumerate(zip(la, lb)): if a == b: del_la.append(i) del_lb.append(i) if a &gt; b: del_la.append(i) if a &lt; b: del_lb.append(i) for x in del_la[-1::-1]: del la[x] for x in del_lb[-1::-1]: del lb[x] return la, lb </code></pre>
0
2016-10-18T09:50:48Z
[ "python", "list", "python-3.x" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and deleting a bigger one, if elements are equal function delete both of them. ''</p> </blockquote> <p>For example:</p> <ul> <li>la = ['bear', 'tiger', 'wolf', 'whale', 'elephant'] </li> <li>lb = ['swan', 'cat', 'dog', 'duck', 'rabbit']</li> </ul> <p>So the functin should return: ['bear','elephant'] ['cat','dog','duck']</p> <p>I have wrote the next code but it doesn't modify lists but create new ones and add there elements. Some ideas how can i do that?</p> <pre><code>def confront(s1, s2): if s1 &lt; s2: # condition that tells which element to choose later return 0 elif s2 &lt; s1: return 1 else: return 2 def modi(la,lb): latemp = [] lbtemp = [] i = 0 while i &lt; len(la): q = confront(la[i], lb[i]) if q == 0: latemp.append(la[i]) elif q == 1: lbtemp.append(lb[i]) i +=1 la = latemp lb = lbtemp return la, lb </code></pre> <p>I have tried remove() but it have created a big mess</p>
0
2016-10-18T09:29:44Z
40,105,516
<p>In your own code <code>la = latemp</code> and <code>lb = lbtemp</code> create <em>references</em> to the two new lists that are local to the function, they have no bearing on the lists that you pass in to the function. According to your specs, you should be mutating the lists passed in not reassigning or creating new lists.</p> <p>Since you are doing an elementwise comparison, you could use <em>zip</em> and remove from each list according to your specs:</p> <pre><code>def modi(la, lb): for i, j in zip(la, lb): # both the same if i == j: la.remove(i) lb.remove(i) # element from la is bigger elif i &gt; j: la.remove(i) # else element from lb must be bigger else: lb.remove(j) la = ['bear', 'tiger', 'wolf', 'whale', 'elephant'] lb = ['swan', 'cat', 'dog', 'duck', 'rabbit'] modi(la, lb) # will modify the lists passed in. print(la, lb) </code></pre>
0
2016-10-18T10:15:53Z
[ "python", "list", "python-3.x" ]
modify lists removing elements without making a mess
40,104,510
<p>I'm trying to resolve now a task that sounds like that:</p> <blockquote> <p>''write a function modi(la, lb) that takes in input 2 lists la and lb that have the same number of elements inside. The function should <strong>modify</strong> lists la and lb camparing elements with the same indexes in two lists and deleting a bigger one, if elements are equal function delete both of them. ''</p> </blockquote> <p>For example:</p> <ul> <li>la = ['bear', 'tiger', 'wolf', 'whale', 'elephant'] </li> <li>lb = ['swan', 'cat', 'dog', 'duck', 'rabbit']</li> </ul> <p>So the functin should return: ['bear','elephant'] ['cat','dog','duck']</p> <p>I have wrote the next code but it doesn't modify lists but create new ones and add there elements. Some ideas how can i do that?</p> <pre><code>def confront(s1, s2): if s1 &lt; s2: # condition that tells which element to choose later return 0 elif s2 &lt; s1: return 1 else: return 2 def modi(la,lb): latemp = [] lbtemp = [] i = 0 while i &lt; len(la): q = confront(la[i], lb[i]) if q == 0: latemp.append(la[i]) elif q == 1: lbtemp.append(lb[i]) i +=1 la = latemp lb = lbtemp return la, lb </code></pre> <p>I have tried remove() but it have created a big mess</p>
0
2016-10-18T09:29:44Z
40,105,794
<p>Essentially, you need to keep track of how many times you've deleted from each list, and offset your indexing by that amount. Here's a basic approach:</p> <pre><code>&gt;&gt;&gt; a ['bear', 'tiger', 'wolf', 'whale', 'elephant'] &gt;&gt;&gt; b ['swan', 'cat', 'dog', 'duck', 'rabbit'] &gt;&gt;&gt; i = j = 0 &gt;&gt;&gt; for k, (str1,str2) in enumerate(zip(a,b)): ... if len(str1) == len(str2): ... del a[k-i], b[k-j] ... i += 1 ... j += 1 ... elif len(str1) &gt; len(str2): ... del a[k-i] ... i += 1 ... else: ... del b[k-j] ... j += 1 ... &gt;&gt;&gt; a [] &gt;&gt;&gt; b ['cat', 'dog', 'duck', 'rabbit'] &gt;&gt;&gt; </code></pre>
0
2016-10-18T10:28:40Z
[ "python", "list", "python-3.x" ]
Why does my plot not disappear on exit in ipython mode?
40,104,587
<p>I'm showing some plots using <code>matplotlib</code> in the <code>ipython</code> prompt. When closing the plot window it does not disappear but gets "stuck" in the background and does not respond to user actions. You can try it out yourself with the following code: </p> <pre><code># test.py import matplotlib.pyplot as plt def f(): plt.plot([1, 2, 3], [4, 3, 5]) plt.show() </code></pre> <p>and in the prompt</p> <pre><code>pingul $ ipython Python 3.5.2 (default, Jun 27 2016, 03:10:38) Type "copyright", "credits" or "license" for more information. IPython 5.1.0 -- An enhanced Interactive Python. In [1]: import test In [2]: test.f() ### Trying to close it now doesn't work </code></pre> <p>Is this a bug, or can I fix it somehow?</p> <p>Running the same code with the normal python prompt works as expected.</p>
0
2016-10-18T09:33:11Z
40,106,566
<p>You should be a bit careful with using pyplot in ipython. Especially <code>plt.show()</code> is blocking the ipython terminal. You should use <code>fig.show()</code>, since it does not block ipython. If you really want to use pyplot, one work-around is to use <code>plt.gcf().show()</code>, which will get the current figure (gcf=get current figure) and only show that figure. However I would recommend creating the figure as <code>fig = plt.figure()</code> and then use <code>fig.show()</code>. </p> <p>Please note that if you run it with python, you need <code>plt.show()</code>! Otherwise the figure will show, and then close immediately! </p>
0
2016-10-18T11:06:28Z
[ "python", "matplotlib", "ipython" ]
Why does my plot not disappear on exit in ipython mode?
40,104,587
<p>I'm showing some plots using <code>matplotlib</code> in the <code>ipython</code> prompt. When closing the plot window it does not disappear but gets "stuck" in the background and does not respond to user actions. You can try it out yourself with the following code: </p> <pre><code># test.py import matplotlib.pyplot as plt def f(): plt.plot([1, 2, 3], [4, 3, 5]) plt.show() </code></pre> <p>and in the prompt</p> <pre><code>pingul $ ipython Python 3.5.2 (default, Jun 27 2016, 03:10:38) Type "copyright", "credits" or "license" for more information. IPython 5.1.0 -- An enhanced Interactive Python. In [1]: import test In [2]: test.f() ### Trying to close it now doesn't work </code></pre> <p>Is this a bug, or can I fix it somehow?</p> <p>Running the same code with the normal python prompt works as expected.</p>
0
2016-10-18T09:33:11Z
40,129,300
<p>Try running <code>%matplotlib</code> before plotting, so that IPython integrates with the GUI event loop showing the plots.</p> <p>This shouldn't be necessary once matplotlib 2.0 is released, because it has some code to detect when it's running inside IPython.</p>
0
2016-10-19T10:50:56Z
[ "python", "matplotlib", "ipython" ]
Remove HTML tags in script
40,104,592
<p>I've found this piece of code on the internet. It takes a sentence and makes every single word into link with this word. But it has weak side: if a sentence has HTML in it, this script doesn't remove it.</p> <p>For example: it replaces '<code>&lt;b&gt;asserted&lt;/b&gt;</code>' with '<code>http://www.merriam-webster.com/dictionary/&lt;b&gt;asserted&lt;/b&gt;</code>'</p> <p>Could you please tell me what to change in this code for it to change '<code>&lt;b&gt;asserted&lt;/b&gt;</code>' to '<code>http://www.merriam-webster.com/dictionary/asserted</code>'.</p> <pre><code>var content = document.getElementById("sentence").innerHTML; var punctuationless = content.replace(/[.,\/#!$%\؟^?&amp;\*;:{}=\-_`~()”“"]/g, ""); var mixedCase = punctuationless.replace(/\s{2,}/g); var finalString = mixedCase.toLowerCase(); var words = (finalString).split(" "); var punctuatedWords = (content).split(" "); var processed = ""; for (i = 0; i &lt; words.length; i++) { processed += "&lt;a href = \"http://www.merriam-webster.com/dictionary/" + words[i] + "\"&gt;"; processed += punctuatedWords[i]; processed += "&lt;/a&gt; "; } document.getElementById("sentence").innerHTML = processed; </code></pre>
-1
2016-10-18T09:33:28Z
40,104,675
<pre><code>function stripAllHtml(str) { if (!str || !str.length) return '' str = str.replace(/&lt;script.*?&gt;.*?&lt;\/script&gt;/igm, '') let tmp = document.createElement("DIV"); tmp.innerHTML = str; return tmp.textContent || tmp.innerText || ""; } stripAllHtml('&lt;a&gt;test&lt;/a&gt;') </code></pre> <p>This function will strip all the HTML and return only text.</p> <p>Hopefully, this will work for you</p>
0
2016-10-18T09:37:08Z
[ "javascript", "python", "regex", "replace" ]
Remove HTML tags in script
40,104,592
<p>I've found this piece of code on the internet. It takes a sentence and makes every single word into link with this word. But it has weak side: if a sentence has HTML in it, this script doesn't remove it.</p> <p>For example: it replaces '<code>&lt;b&gt;asserted&lt;/b&gt;</code>' with '<code>http://www.merriam-webster.com/dictionary/&lt;b&gt;asserted&lt;/b&gt;</code>'</p> <p>Could you please tell me what to change in this code for it to change '<code>&lt;b&gt;asserted&lt;/b&gt;</code>' to '<code>http://www.merriam-webster.com/dictionary/asserted</code>'.</p> <pre><code>var content = document.getElementById("sentence").innerHTML; var punctuationless = content.replace(/[.,\/#!$%\؟^?&amp;\*;:{}=\-_`~()”“"]/g, ""); var mixedCase = punctuationless.replace(/\s{2,}/g); var finalString = mixedCase.toLowerCase(); var words = (finalString).split(" "); var punctuatedWords = (content).split(" "); var processed = ""; for (i = 0; i &lt; words.length; i++) { processed += "&lt;a href = \"http://www.merriam-webster.com/dictionary/" + words[i] + "\"&gt;"; processed += punctuatedWords[i]; processed += "&lt;/a&gt; "; } document.getElementById("sentence").innerHTML = processed; </code></pre>
-1
2016-10-18T09:33:28Z
40,105,685
<p>This regex /&lt;{1}[^&lt;>]{1,}>{1}/g should replace any text in a string that is between two of these &lt;> and the brackets themselves with a white space. This</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> var str = "&lt;hi&gt;How are you&lt;hi&gt;&lt;table&gt;&lt;tr&gt;I&lt;tr&gt;&lt;table&gt;love cake&lt;g&gt;" str = str.replace(/&lt;{1}[^&lt;&gt;]{1,}&gt;{1}/g," ") document.writeln(str);</code></pre> </div> </div> </p> <p>will give back " How are you I love cake".</p> <p>If you paste this</p> <pre><code>var stripHTML = str.mixedCase(/&lt;{1}[^&lt;&gt;]{1,}&gt;{1}/g,"") </code></pre> <p>just below this</p> <pre><code>var mixedCase = punctuationless.replace(/\s{2,}/g); </code></pre> <p>and replace mixedCase with stripHTML in the line after, it will probably work</p>
1
2016-10-18T10:23:10Z
[ "javascript", "python", "regex", "replace" ]
Logging into a AWS instance using boto3 library of python
40,104,641
<p>I am attempting to write a python code that would few of my manual steps in logging into the AWS platform. </p> <p>In Ubuntu terminal , I used to write the command</p> <pre><code>ssh -A ec2-user@&lt;ip-address&gt; </code></pre> <p>and then again log into another instance using</p> <pre><code>ssh ec2-user@&lt;ip.address&gt; </code></pre> <p>Now I am looking at python code that would be able to automate this logging in process. I have written the following code till now.</p> <pre><code>import boto3 ec2 = boto3.resource('ec2') </code></pre>
-1
2016-10-18T09:35:29Z
40,104,858
<p>There are 2 ways mostly to configure the boto3 library.</p> <ol> <li><p>You need to configure it first on your system and use the same configuration everywhere. You can use <a href="http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html" rel="nofollow"><strong>AWS CLI</strong></a> for this by running <code>aws configure</code> on your terminal.</p></li> <li><p>Set the environment variables and call the boto3 configuration via <code>process.env.ENV_KEY</code> and then use it like : </p></li> </ol> <p><code> client = boto3.client( 'ec2', aws_access_key_id=process.env.ACCESS_KEY, aws_secret_access_key=process.env.SECRET_KEY, aws_session_token=process.env.SESSION_TOKEN, ) </code></p>
2
2016-10-18T09:45:01Z
[ "python", "amazon-web-services", "amazon-ec2", "boto3" ]
Logging into a AWS instance using boto3 library of python
40,104,641
<p>I am attempting to write a python code that would few of my manual steps in logging into the AWS platform. </p> <p>In Ubuntu terminal , I used to write the command</p> <pre><code>ssh -A ec2-user@&lt;ip-address&gt; </code></pre> <p>and then again log into another instance using</p> <pre><code>ssh ec2-user@&lt;ip.address&gt; </code></pre> <p>Now I am looking at python code that would be able to automate this logging in process. I have written the following code till now.</p> <pre><code>import boto3 ec2 = boto3.resource('ec2') </code></pre>
-1
2016-10-18T09:35:29Z
40,105,117
<p>If you want to perform actions on a running instance, boto3 is not what you're looking for. What you're asking about is more in the realm of what's called <em>configuration management</em>.</p> <p>While you could write something yourself using an SSH library like <a href="http://www.paramiko.org/" rel="nofollow">Paramiko</a>, you may want to look at a more purpose-built software package like <a href="http://www.fabfile.org/" rel="nofollow">Fabric</a>. It's built on-top of the aforementioned Paramiko, with added functionality tailored to running commands on remote servers. For a more full-featured, open source configuration management solution, I recommend looking into <a href="https://www.ansible.com/" rel="nofollow">Ansible</a>.</p> <p>AWS also has a native service for configuring EC2 instances called <a href="https://aws.amazon.com/ec2/run-command/" rel="nofollow">EC2 Run Command</a>.</p>
0
2016-10-18T09:57:06Z
[ "python", "amazon-web-services", "amazon-ec2", "boto3" ]
Vertical Bar chart using rotation='vertical' not working
40,104,730
<p>From the matplot lib example <a href="http://matplotlib.org/examples/lines_bars_and_markers/barh_demo.html" rel="nofollow">lines_bars_and_markers</a> using <code>rotation='vertical'</code> does not make it vertical. What am I doing wrong?</p> <pre><code>""" Simple demo of a horizontal bar chart. """ import matplotlib.pyplot as plt plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt # Example data people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') y_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(people)) error = np.random.rand(len(people)) plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4) plt.yticks(y_pos, people) plt.xlabel('Performance') plt.title('How fast do you want to go today?') plt.show() rotation='vertical' </code></pre>
0
2016-10-18T09:39:05Z
40,104,887
<p><code>barh</code> is for horizontal bar charts, change to <code>bar</code> and then swap around the data for the axes. You can't simply write <code>rotation='vertical'</code> because that isn't telling the <code>matplotlib</code> library anything, it's just creating a string that is never used. </p> <pre><code>import matplotlib.pyplot as plt plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt # Example data people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') x_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(people)) error = np.random.rand(len(people)) plt.bar(x_pos, performance, yerr=error, align='center', alpha=0.4) plt.xticks(x_pos, people) plt.ylabel('Performance') plt.title('How fast do you want to go today?') plt.show() </code></pre>
3
2016-10-18T09:46:01Z
[ "python", "numpy", "matplotlib" ]
scrapy starting a new project
40,104,737
<p>I have installed python 2.7.12 version on a Windows 7 system. I have also installed pywin32 and Visual C++. When I enter the command <code>pip --version</code> it does not generate any output, the cursor moves to the next line and blinks.</p> <p>But when I use the command <code>python -m pip --version</code> the version of pip is displayed. Also to install scrapy I had to use the command <code>python -m pip install scrapy</code>. Scrapy got installed successfully. </p> <p>I have set the path in the environment variables correctly - <code>C:\Python27;C:\Python27\Scripts;</code></p> <p>When I had to start my new project in scrapy I used the command <code>scrapy startproject project_name</code>. Again, the cursor moved to the next line and blinked. No result is generated not even any error message.</p> <p>When I tried again and again it created the folder in the directory with the respective files.</p> <p>When I developed a code and tried to run the spider by the command <code>scrapy crawl name</code> again the same problem appeared - No response.</p> <p>Now again I am not able to create a new project as the same issue is arising.</p> <p>If someone could please suggest the possible reasons for the error and the solution for this.</p> <p>It worked out when i used the command <code>python -m scrapy &lt;command&gt; &lt;arguments?</code> to follow the scrapy tutorial. however it was fine until i run the crawl command. when i use the <code>python -m scrapy.cmdline shell 'http://quotes.toscrape.com/page/1/'</code> command it shows error </p> <pre><code>C:\Users\MinorMiracles\Desktop\tutorial&gt;python -m scrapy.cmdline crawl quotes 2016-10-19 10:26:15 [scrapy] INFO: Scrapy 1.2.0 started (bot: tutorial) 2016-10-19 10:26:15 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'tu torial.spiders', 'SPIDER_MODULES': ['tutorial.spiders'], 'ROBOTSTXT_OBEY': True, 'BOT_NAME': 'tutorial'} 2016-10-19 10:26:16 [scrapy] INFO: Enabled extensions: ['scrapy.extensions.logstats.LogStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.corestats.CoreStats'] 2016-10-19 10:26:17 [scrapy] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware', 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2016-10-19 10:26:17 [scrapy] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2016-10-19 10:26:17 [scrapy] INFO: Enabled item pipelines: [] 2016-10-19 10:26:17 [scrapy] INFO: Spider opened 2016-10-19 10:26:17 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 i tems (at 0 items/min) 2016-10-19 10:26:17 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023 2016-10-19 10:26:18 [scrapy] DEBUG: Crawled (404) &lt;GET http://quotes.toscrape.co m/robots.txt&gt; (referer: None) 2016-10-19 10:26:18 [scrapy] DEBUG: Crawled (200) &lt;GET http://quotes.toscrape.co m/page/1/&gt; (referer: None) 2016-10-19 10:26:18 [quotes] DEBUG: Saved file quotes-1.html 2016-10-19 10:26:18 [scrapy] DEBUG: Crawled (200) &lt;GET http://quotes.toscrape.co m/page/2/&gt; (referer: None) 2016-10-19 10:26:19 [quotes] DEBUG: Saved file quotes-2.html 2016-10-19 10:26:19 [scrapy] INFO: Closing spider (finished) 2016-10-19 10:26:19 [scrapy] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 675, 'downloader/request_count': 3, 'downloader/request_method_count/GET': 3, 'downloader/response_bytes': 5974, 'downloader/response_count': 3, 'downloader/response_status_count/200': 2, 'downloader/response_status_count/404': 1, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2016, 10, 19, 4, 56, 19, 56000), 'log_count/DEBUG': 6, 'log_count/INFO': 7, 'response_received_count': 3, 'scheduler/dequeued': 2, 'scheduler/dequeued/memory': 2, 'scheduler/enqueued': 2, 'scheduler/enqueued/memory': 2, 'start_time': datetime.datetime(2016, 10, 19, 4, 56, 17, 649000)} 2016-10-19 10:26:19 [scrapy] INFO: Spider closed (finished) C:\Users\MinorMiracles\Desktop\tutorial&gt;python -m scrapy.cmdline shell 'http://q uotes.toscrape.com/page/1/' 2016-10-19 11:11:40 [scrapy] INFO: Scrapy 1.2.0 started (bot: tutorial) 2016-10-19 11:11:40 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'tu torial.spiders', 'ROBOTSTXT_OBEY': True, 'DUPEFILTER_CLASS': 'scrapy.dupefilters .BaseDupeFilter', 'SPIDER_MODULES': ['tutorial.spiders'], 'BOT_NAME': 'tutorial' , 'LOGSTATS_INTERVAL': 0} 2016-10-19 11:11:40 [scrapy] INFO: Enabled extensions: ['scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.corestats.CoreStats'] 2016-10-19 11:11:40 [scrapy] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.robotstxt.RobotsTxtMiddleware', 'scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2016-10-19 11:11:40 [scrapy] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2016-10-19 11:11:40 [scrapy] INFO: Enabled item pipelines: [] 2016-10-19 11:11:40 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023 2016-10-19 11:11:40 [scrapy] INFO: Spider opened 2016-10-19 11:11:42 [scrapy] DEBUG: Retrying &lt;GET http://'http:/robots.txt&gt; (fai led 1 times): DNS lookup failed: address "'http:" not found: [Errno 11004] getad drinfo failed. 2016-10-19 11:11:45 [scrapy] DEBUG: Retrying &lt;GET http://'http:/robots.txt&gt; (fai led 2 times): DNS lookup failed: address "'http:" not found: [Errno 11004] getad drinfo failed. 2016-10-19 11:11:47 [scrapy] DEBUG: Gave up retrying &lt;GET http://'http:/robots.t xt&gt; (failed 3 times): DNS lookup failed: address "'http:" not found: [Errno 1100 4] getaddrinfo failed. 2016-10-19 11:11:47 [scrapy] ERROR: Error downloading &lt;GET http://'http:/robots. txt&gt;: DNS lookup failed: address "'http:" not found: [Errno 11004] getaddrinfo f ailed. DNSLookupError: DNS lookup failed: address "'http:" not found: [Errno 11004] get addrinfo failed. 2016-10-19 11:11:49 [scrapy] DEBUG: Retrying &lt;GET http://'http://quotes.toscrape .com/page/1/'&gt; (failed 1 times): DNS lookup failed: address "'http:" not found: [Errno 11004] getaddrinfo failed. 2016-10-19 11:11:51 [scrapy] DEBUG: Retrying &lt;GET http://'http://quotes.toscrape .com/page/1/'&gt; (failed 2 times): DNS lookup failed: address "'http:" not found: [Errno 11004] getaddrinfo failed. 2016-10-19 11:11:54 [scrapy] DEBUG: Gave up retrying &lt;GET http://'http://quotes. toscrape.com/page/1/'&gt; (failed 3 times): DNS lookup failed: address "'http:" not found: [Errno 11004] getaddrinfo failed. Traceback (most recent call last): File "C:\Python27\lib\runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "C:\Python27\lib\runpy.py", line 72, in _run_code exec code in run_globals File "C:\Python27\lib\site-packages\scrapy\cmdline.py", line 161, in &lt;module&gt; execute() File "C:\Python27\lib\site-packages\scrapy\cmdline.py", line 142, in execute _run_print_help(parser, _run_command, cmd, args, opts) File "C:\Python27\lib\site-packages\scrapy\cmdline.py", line 88, in _run_print _help func(*a, **kw) File "C:\Python27\lib\site-packages\scrapy\cmdline.py", line 149, in _run_comm and cmd.run(args, opts) File "C:\Python27\lib\site-packages\scrapy\commands\shell.py", line 71, in run shell.start(url=url) File "C:\Python27\lib\site-packages\scrapy\shell.py", line 47, in start self.fetch(url, spider) File "C:\Python27\lib\site-packages\scrapy\shell.py", line 112, in fetch reactor, self._schedule, request, spider) File "C:\Python27\lib\site-packages\twisted\internet\threads.py", line 122, in blockingCallFromThread result.raiseException() File "&lt;string&gt;", line 2, in raiseException twisted.internet.error.DNSLookupError: DNS lookup failed: address "'http:" not f ound: [Errno 11004] getaddrinfo failed. </code></pre> <p>can anyone tell me what is wrong</p>
0
2016-10-18T09:39:18Z
40,122,499
<p>Using the alternative command <code>python -m scrapy.cmdline &lt;command&gt; &lt;arguments&gt;</code> (e.g. python -m scrapy.cmdline version -v) worked</p> <p>thanks Paul</p>
0
2016-10-19T05:00:41Z
[ "python", "python-2.7", "web-scraping", "scrapy", "scrapy-spider" ]
django required file field validation
40,104,831
<p>Working with django form in which i have two file uploads fields one for artist image and another for event poster, both of these fields are required. </p> <pre><code>class CreateEventStepFirstForm(forms.Form): event_title = forms.CharField(required = True, max_length=20, widget=forms.TextInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'data-empty-message':'This field is required' })) ticket_title = forms.CharField(required = True, max_length=225, widget=forms.TextInput(attrs={ 'class' : 'custome-input promote-input', 'autocomplete' : 'off', 'data-empty-message':'This field is required' })) artist_image = forms.FileField(required = True, widget=forms.FileInput(attrs={ 'class' : 'upload-img', 'data-empty-message':'Please upload artist image, this field is required' })) event_poster = forms.FileField(required = True, widget=forms.FileInput(attrs={ 'class' : 'upload-img', 'data-empty-message':'Please upload artist image, this field is required' })) </code></pre> <p>Problem is that all fields are validated properly except these two file fields, when i select images for both artist_image and event_poster it don't validate the fields and give "This field is required" error even i select both images.</p> <p><img src="https://i.stack.imgur.com/mh43W.png" /></p>
0
2016-10-18T09:43:44Z
40,105,110
<p>You need to add <code>request.FILES</code> as follows:</p> <pre><code>form = CreateEventStepFirstForm(request.POST, request.FILES) </code></pre>
1
2016-10-18T09:56:54Z
[ "python", "django" ]
How to get date after subtracting days in pandas
40,104,946
<p>I have a dataframe:</p> <pre><code>In [15]: df Out[15]: date day 0 2015-10-10 23 1 2015-12-19 9 2 2016-03-05 34 3 2016-09-17 23 4 2016-04-30 2 </code></pre> <p>I want to subtract the number of days from the date and create a new column.</p> <pre><code>In [16]: df.dtypes Out[16]: date datetime64[ns] day int64 </code></pre> <p>Desired output something like:</p> <pre><code>In [15]: df Out[15]: date day date1 0 2015-10-10 23 2015-09-17 1 2015-12-19 9 2015-12-10 2 2016-03-05 34 2016-01-29 3 2016-09-17 23 2016-08-25 4 2016-04-30 2 2016-04-28 </code></pre> <p>I tried but this does not work:</p> <pre><code>df['date1']=df['date']+pd.Timedelta(df['date'].dt.day-df['day']) </code></pre> <p>it throws error :</p> <blockquote> <p>TypeError: unsupported type for timedelta days component: Series</p> </blockquote>
1
2016-10-18T09:49:11Z
40,105,235
<pre><code>import dateutil.relativedelta def calculate diff(v): return v['date'] - dateutil.relativedelta.relativedelta(day=v['day']) df['date1']=df.apply(calculate_diff, axis=1) </code></pre> <p>given that v['date'] is datetime object</p>
1
2016-10-18T10:02:06Z
[ "python", "pandas" ]
How to get date after subtracting days in pandas
40,104,946
<p>I have a dataframe:</p> <pre><code>In [15]: df Out[15]: date day 0 2015-10-10 23 1 2015-12-19 9 2 2016-03-05 34 3 2016-09-17 23 4 2016-04-30 2 </code></pre> <p>I want to subtract the number of days from the date and create a new column.</p> <pre><code>In [16]: df.dtypes Out[16]: date datetime64[ns] day int64 </code></pre> <p>Desired output something like:</p> <pre><code>In [15]: df Out[15]: date day date1 0 2015-10-10 23 2015-09-17 1 2015-12-19 9 2015-12-10 2 2016-03-05 34 2016-01-29 3 2016-09-17 23 2016-08-25 4 2016-04-30 2 2016-04-28 </code></pre> <p>I tried but this does not work:</p> <pre><code>df['date1']=df['date']+pd.Timedelta(df['date'].dt.day-df['day']) </code></pre> <p>it throws error :</p> <blockquote> <p>TypeError: unsupported type for timedelta days component: Series</p> </blockquote>
1
2016-10-18T09:49:11Z
40,105,381
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>to_timedelta</code></a>:</p> <pre><code>df['date1'] = df['date'] - pd.to_timedelta(df['day'], unit='d') print (df) date day date1 0 2015-10-10 23 2015-09-17 1 2015-12-19 9 2015-12-10 2 2016-03-05 34 2016-01-31 3 2016-09-17 23 2016-08-25 4 2016-04-30 2 2016-04-28 </code></pre> <p>If need <code>Timedelta</code> use <code>apply</code>, but it is slowier:</p> <pre><code>df['date1'] = df['date'] - df.day.apply(lambda x: pd.Timedelta(x, unit='D')) print (df) date day date1 0 2015-10-10 23 2015-09-17 1 2015-12-19 9 2015-12-10 2 2016-03-05 34 2016-01-31 3 2016-09-17 23 2016-08-25 4 2016-04-30 2 2016-04-28 </code></pre> <p><strong>Timings</strong>:</p> <pre><code>#[5000 rows x 2 columns] df = pd.concat([df]*1000).reset_index(drop=True) In [252]: %timeit df['date'] - df.day.apply(lambda x: pd.Timedelta(x, unit='D')) 10 loops, best of 3: 45.3 ms per loop In [253]: %timeit df['date'] - pd.to_timedelta(df['day'], unit='d') 1000 loops, best of 3: 1.71 ms per loop </code></pre>
3
2016-10-18T10:09:10Z
[ "python", "pandas" ]
Reg ex remove non alpha characters keeping spaces
40,105,027
<p>I've written a simple function that strips a string of all non-alpha characters keeping spaces in place.</p> <p>Currently it relies on using two regular expressions. However, in in interest of brevity I'd like to reduce those two reg exs into one. Is this possible?</p> <pre><code>import re def junk_to_alpha(s): reg = r"[^A-Za-z]" p = re.compile(reg) s = re.sub(p, " ", s) p = re.compile(r"\s+") s = re.sub(p, " ", s) return s print junk_to_alpha("Spoons! 12? \/@# ,.1 12 Yeah? {[]}") # Spoons Yeah </code></pre>
1
2016-10-18T09:52:51Z
40,105,089
<p>You may enclose the <code>[^a-zA-Z]+</code> with <code>\s*</code>:</p> <pre><code>import re def junk_to_alpha(s): s = re.sub(r"\s*[^A-Za-z]+\s*", " ", s) return s print junk_to_alpha("Spoons! 12? \/@# ,.1 12 Yeah? {[]}") </code></pre> <p>See the <a href="https://ideone.com/N1pz8v" rel="nofollow">online Python demo</a></p> <p>The pattern details:</p> <ul> <li><code>\s*</code> - zero or more whitespaces</li> <li><code>[^A-Za-z]+</code> - 1 or more characters other than ASCII letters</li> <li><code>\s*</code> - see above.</li> </ul>
1
2016-10-18T09:55:39Z
[ "python", "regex", "string", "python-2.7" ]
how to delete youtube's watch later video in selenium?
40,105,029
<p>I want to delete youtube's watch later videos. but my codes don't work.</p> <pre><code>&lt;button class="yt-uix-button yt-uix-button-size-default yt-uix-button-default yt-uix-button-empty yt-uix-button-has-icon no-icon-markup pl-video-edit-remove yt-uix-tooltip" type="button" onclick=";return false;" title="Remove"&gt;&lt;/button&gt; </code></pre> <p>my code is this.</p> <pre><code>_sDriver.get('https://www.youtube.com/playlist?list=WL') _sDriver.find_element_by_class_name('pl-video-edit-remove').click() </code></pre> <p>exception is this.</p> <pre><code>&gt;&gt;&gt; _sDriver.find_element_by_class_name('pl-video-edit-remove') &lt;selenium.webdriver.remote.webelement.WebElement (session="283d423c-5ff7-478f-89 b9-002499413126", element="{e00dbb1e-e0ca-4f79-8652-23c955b464e7}")&gt; &gt;&gt;&gt; _sDriver.find_element_by_class_name('pl-video-edit-remove').click() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 72, in click self._execute(Command.CLICK_ELEMENT) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 461, in _execute return self._parent.execute(command, params) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l ine 236, in execute self.error_handler.check_response(response) File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py" , line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotVisibleException: Message: Element is not c urrently visible and so may not be interacted with Stacktrace: at fxdriver.preconditions.visible (file:///c:/users/admini~1/appdata/local/t emp/tmppqz9zq/extensions/[email protected]/components/command-processor.js :10092) at DelayedCommand.prototype.checkPreconditions_ (file:///c:/users/admini~1/a ppdata/local/temp/tmppqz9zq/extensions/[email protected]/components/comman d-processor.js:12644) at DelayedCommand.prototype.executeInternal_/h (file:///c:/users/admini~1/ap pdata/local/temp/tmppqz9zq/extensions/[email protected]/components/command -processor.js:12661) at DelayedCommand.prototype.executeInternal_ (file:///c:/users/admini~1/appd ata/local/temp/tmppqz9zq/extensions/[email protected]/components/command-p rocessor.js:12666) at DelayedCommand.prototype.execute/&lt; (file:///c:/users/admini~1/appdata/loc al/temp/tmppqz9zq/extensions/[email protected]/components/command-processo r.js:12608) </code></pre> <p>I don't know what can I do for this. I need your help. thank you.</p>
0
2016-10-18T09:52:52Z
40,105,849
<p>The element that you are trying to click is not visible normally. It is only visible when you hover the mouse on it. So either you fire a mouseover event before clicking and try if it works.</p> <p>The other solution is that you can try executing the JavaScript.</p> <pre><code> driver.execute_script("document.getElementsByClassName('pl-video-edit-remove')[0].click()") </code></pre> <p>The script is working at my end.</p> <p>you may want to add some wait before executing the script so that the page loads properly.</p>
0
2016-10-18T10:31:25Z
[ "python", "selenium", "youtube" ]
Creating a Datastore Entry results in encrypted properties when viewing with the browser
40,105,116
<p>I manage to create or modify a datastore entity fine with google.cloud.datastore in python, but when I log in into my Cloud Platform project in the browser and check the entry, it looks like all of its properties are encrypted (They look like <code>"Rm9vIEJhcg=="</code> and such - If I create it from the browser I can see the normally).</p> <p>I am authenticating with a service account identity's json file:</p> <pre><code>self.client = datastore.Client() self.client = self.client.from_service_account_json(cert_file.json) </code></pre> <p>The service account has "editor" permissions on the whole project. Changing it to "Owner", which is the one set for the gmail account I use to log in, doesn't fix the issues.</p> <p>I create the entity like this:</p> <pre><code>with self.datastore.client.transaction(): entity = Entity(Key("key", project="project")) entity["property"] = "data" self.datastore.client.put(entity) </code></pre> <p>Any way to make it so the entry I modify with the python library are readable from the browser site?</p>
0
2016-10-18T09:57:05Z
40,132,794
<p>The value is not really encrypted, rather encoded with Base64. The reason for this is the value is stored as a Blob (raw bytes), instead of Text/Character String. The Console displays Blob fields in Base64 format. The value, Rm9vIEJhcg==, when decoded with Base64, is Foo Bar. </p> <p>I don't have much knowledge in Python, but take a look at the Note from the official <a href="https://googlecloudplatform.github.io/google-cloud-python/stable/datastore-entities.html" rel="nofollow">documentation</a>: </p> <blockquote> <p>When saving an entity to the backend, values which are “text” (unicode in Python2, str in Python3) will be saved using the ‘text_value’ field, after being encoded to UTF-8. When retrieved from the back-end, such values will be decoded to “text” again. Values which are “bytes” (str in Python2, bytes in Python3), will be saved using the ‘blob_value’ field, without any decoding / encoding step.</p> </blockquote> <p>Depending on the version of Python you are using, adjust the data type for your data and the issue should be resolved. </p>
0
2016-10-19T13:27:29Z
[ "python", "google-cloud-datastore", "google-cloud-python", "gcloud-python" ]
Why if Python flask route has more arguments, it returns an errormistakes?
40,105,148
<pre><code>@app.route("/ufname/&lt;uname&gt;/friend/&lt;fname&gt;") def v_ufname(uname,fname): return "s%\'s friend - %s\'s profile" % (uname,fname) </code></pre> <p><img src="https://i.stack.imgur.com/dHjad.png" alt="enter image description here"></p> <p>and i try add more %%%s%%\'s, the page write "<strong>%mary%'s friend - %linda%'s profile</strong>":</p> <p><img src="https://i.stack.imgur.com/S9VnX.png" alt="enter image description here"></p> <p>why? and how to rosoluvtion the page write "%mary%" %linda% has "%"?</p> <p>thanks!</p>
-5
2016-10-18T09:58:05Z
40,105,525
<p>Use</p> <pre><code>return "%s\'s friend - %s\'s profile" % (uname,fname) </code></pre> <p>Check out <a href="https://pyformat.info/" rel="nofollow">https://pyformat.info/</a></p>
2
2016-10-18T10:16:17Z
[ "python", "flask" ]
Python: How to execute a JavaScript Function (with lxml)?
40,105,271
<p>I'd like to parse a website where I need to make a JavaScript call before parsing the code, because exeuting the JavaScript function unfolds more informations that I need to parse.</p> <p>This is the part where the JavaScript gets called:</p> <pre><code>&lt;a href="javascript:StartUpdate(DIV_TS_4828_5899,41611,5899,';DIV_TS_0_4820;DIV_TS_4820_4828;DIV_TS_4828_5899',0)"&gt; &lt;img src="bilder/check_on.png" width="15" height="15"&gt; &lt;/a&gt; </code></pre> <p>Is it possible to execute this JavaScript function via lxml? It would be the most comfortable for me, because I would also like to parse the website with lxml afterwards.</p> <p>I know Selenium could do this, but is there a possibility with lxml?</p>
-1
2016-10-18T10:04:00Z
40,107,589
<p>No, it is not possible to execute JavaScript language by using parser of eXtensible Markup Language, even with module for parsing HyperText Markup Language.</p> <p>You need to use JavaScript interpreter to execute JavaScript code.</p> <p>If you really don't like Selenium you may try to use <a href="https://code.google.com/archive/p/pyv8/" rel="nofollow">PyV8</a> or <a href="https://pypi.python.org/pypi/PyExecJS" rel="nofollow">PyExecJs</a>.</p>
0
2016-10-18T11:55:04Z
[ "javascript", "python", "lxml" ]
How to split an RDD into two RDDs and save the result as RDDs with PySpark?
40,105,328
<p>I'm looking for a way to split an RDD into two or more RDDs, and save the results obtained as two separated RDDs. Given for exemple :</p> <pre><code>rdd_test = sc.parallelize(range(50), 1) </code></pre> <p>My code :</p> <pre><code>def split_population_into_parts(rdd_test): N = 2 repartionned_rdd = rdd_test.repartition(N).distinct() rdds_for_testab_populations = repartionned_rdd.glom() return rdds_for_testab_populations rdds_for_testab_populations = split_population_into_parts(rdd_test) </code></pre> <p>Which gives :</p> <p><strong>[[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48], [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]]</strong></p> <p>Now I want to associate avery list here to a new RDD. RDD1 and RDD2 for exemple. What to do ? Thx !</p>
0
2016-10-18T10:07:08Z
40,109,361
<p>I got the solutions.</p> <pre><code>def get_testab_populations_tables(rdds_for_testab_populations): i = 0 while i &lt; len(rdds_for_testab_populations.collect()): for testab_table in rdds_for_testab_populations.toLocalIterator(): namespace = globals() namespace['tAB_%d' % i] = sc.parallelize(testab_table) i += 1 return; </code></pre> <p>Then you can do :</p> <pre><code>print tAB_0.collect() print tAB_1.collect() etc. </code></pre>
0
2016-10-18T13:15:45Z
[ "python", "list", "pyspark", "rdd", "pyspark-sql" ]
create list for for-loop
40,105,332
<p>I have a script that creates a number of console links (with an html body built around) to VMs for faster access, the console links are put together by a number of strings and variables. </p> <p>I want to create a list the contains all the links created. </p> <p><strong>Nevermind I already created a list of all links, lost the overview of my script ...</strong></p>
0
2016-10-18T10:07:12Z
40,105,521
<p>You may use <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_output" rel="nofollow"><code>subprocess.check_output()</code></a> which runs command with arguments and return its output as a byte string. For example:</p> <pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; my_var = subprocess.check_output(["echo", "Hello"]) &gt;&gt;&gt; my_var 'Hello\n' </code></pre> <p>In case, you are having a executable file, say <code>my_script.py</code> which receives <code>param1</code> and <code>param2</code> as argument. Your <code>check_output</code> call should be like:</p> <pre><code>my_output = subprocess.check_output(["./my_script.py", "param1", "param2"]) </code></pre> <p>As per the document:</p> <blockquote> <p><strong>Note:</strong> Do not use stderr=PIPE with this function as that can deadlock based on the child process error volume. Use Popen with the communicate() method when you need a stderr pipe.</p> </blockquote>
1
2016-10-18T10:16:00Z
[ "python" ]
create list for for-loop
40,105,332
<p>I have a script that creates a number of console links (with an html body built around) to VMs for faster access, the console links are put together by a number of strings and variables. </p> <p>I want to create a list the contains all the links created. </p> <p><strong>Nevermind I already created a list of all links, lost the overview of my script ...</strong></p>
0
2016-10-18T10:07:12Z
40,105,713
<p>Probably you would want to modify your script to store the links in a data-structure like a list:</p> <pre><code>links = list() ... # iteration happens here link = 'https://' + host + ':' + console_port + '...' print link links.append(link) # script done here; return or use links </code></pre> <p>In the end you can then return/use the list of all links you collected.</p>
2
2016-10-18T10:24:29Z
[ "python" ]
Execute HTTP request to an external server when any CouchDB Data changes
40,105,366
<p>I am fairly new in CouchDB but successfully performed create, update, delete data using Fauxton UI. I have some PouchDB clients which will directly sync with this CouchDB database using HTTP Protocol. This PouchDB client will be authenticated with another ASP.NET Identity server and send a Bearer Token with each of its call to the CouchDB server. </p> <p>I have a remote Windows server (exposed with ASP.NET Web API endpoints) which has implementation of Permission Management (using ASP.NET Identity) and also another server which has ElasticSearch database (for fastest searching) instance. </p> <p><strong>My problem is, I want to execute some functions (using JavaScript, Python or any other supported language) to check the permission with that ASP.NET remote server and if permitted, then proceed the call to the CouchDB. I also want to capture the <code>_changes</code> event of CouchDB and execute another HTTP call to my ElasticSearch instance to insert/update this change.</strong> </p> <p>I have seen, I can write Python/Ruby code to which can execute a HTTP call. But I failed to understand how to hook these functions with my CouchDB (instance/cluster) so that these functions could be called and executed. </p>
0
2016-10-18T10:08:27Z
40,107,036
<p>Two JS modules that could solve parts of your issues:</p> <ul> <li><a href="https://www.npmjs.com/package/follow" rel="nofollow">follow</a>, to execute a function everytime a change happen on the followed CouchDB database</li> <li><a href="https://github.com/ryanramage/couch2elastic4sync" rel="nofollow">couch2elastic4sync</a>, uses the follow module to keep a CouchDB database and a ElasticSearch index in sync</li> </ul>
0
2016-10-18T11:28:26Z
[ "python", "asp.net", "oauth", "couchdb", "httprequest" ]
Decoding Byte/Bits to Binary
40,105,393
<p>I am using a Prologix GPIB-USB adaptor in a LISTEN only mode to decipher communication between two equipments (Semiconductor related namely Tester and Prober).</p> <p>I am able to decode most of the information as stated in the Manual , But unable to convert one of the Data namely BIN Category.</p> <p>Sample Data :</p> <pre><code>018022 C@A@@@@@@@ Q O A A 019022 CA@A@@@@@@ </code></pre> <p>Tool Manual :</p> <p><a href="https://i.stack.imgur.com/0mVZt.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/0mVZt.jpg" alt="Manual on How to read Incoming Data"></a></p> <p>The data i am interetsed in are "C@A@@@@@@@" and "CA@A@@@@@@" The First byte namely "C" is the command which is passed in. The Second Byte which can be "@" or "A" actually tells if the Test is Pass/Fail.</p> <p>converting to binary :</p> <pre><code>@ ---&gt; 0100 0000 A ---&gt; 0100 0001 </code></pre> <p>The Result is decided by the lower 4 bits of the Byte which is 0000(Pass) and 0001 (Fail). I am able to decode it correctly until here .</p> <p>The next 8 Bytes represent the BIN category , which during test was set as 5 if the test fail and 1 if it is Pass , so BIN number in "C@A@@@@@@@" is 1 and BIN number corresponding to "CA@A@@@@@@" is set at 5.</p> <p>I am unable to decode the value of 5 and 1 from the data which is generated from GPIB adaptor. Can someone suggest if it can actually be decoded as 5 and 1. I have attached the Manual which explain on how to read incoming Data.</p> <p>Stuck with this for long time :-(</p>
0
2016-10-18T10:10:13Z
40,105,990
<p>You can use struct.unpack to decode byte values to numbers. You need to know the length (in this case 8 bytes) and whether the number is big or little endian (test if you don't know). And whether the number is signed or unsigned. </p> <p>If your string is "C@A@@@@@@@" and the binary data is in bytes 3-10, you could try</p> <pre><code>import struct foo="C@A@@@@@@@" print struct.unpack("&gt;Q", foo[3:11]) </code></pre> <p>This would decode a 8 bytes long unsigned big-endian number. See <a href="https://docs.python.org/2/library/struct.html" rel="nofollow">https://docs.python.org/2/library/struct.html</a> for instructions. </p> <p>Hope this helps. </p> <p>Hannu</p>
0
2016-10-18T10:38:35Z
[ "python", "byte", "decoding", "bits", "gpib" ]
Why is there a trailing none when reading text in python?
40,105,412
<p>I'm trying to write a text reader program that can differ a text into three parts: title, tag, and content.</p> <p>what happen is that it's giving me a 'None' value at each end of the content.</p> <p>here is the content reader code:</p> <pre><code>#counting lines in the text def bufcount(file): file.seek(0) lines = 0 buf_size = 1024 * 1024 read_f = file.read # loop optimization buf = read_f(buf_size) while buf: lines += buf.count('\n') buf = read_f(buf_size) return lines #for reading the content def searchForTheContent(file): count=bufcount(file) file.seek(0) i=3 #to read after the third line, which is the content lines=file.readlines() while i&lt;count: i=i+1 #print(i) if lines[i]=="\n": pass if lines[i]!="\n": print(lines[i]) </code></pre> <p>Calling the Function:</p> <pre><code>path= '.\\Texts\\*.txt' files = glob.glob(path) for name in files: file= open(name) print(searchForTheContent(file)) </code></pre> <p>Result:</p> <pre><code>safahsdfhajfha dfasdfsdfsadf sadfasdfasdfasdfasdf asdfasfdasd None </code></pre> <p>Where is that 'None' value come from? and any suggestion how to remove it?</p>
0
2016-10-18T10:11:06Z
40,105,595
<p>You are printing the return value for the function:</p> <pre><code>print(searchForTheContent(file)) </code></pre> <p><code>searchForTheContent()</code> has no explicit <code>return</code> statement, so <code>None</code> is returned, and you are printing that. You'd get the same result with an empty function:</p> <pre><code>&gt;&gt;&gt; def foo(): pass ... &gt;&gt;&gt; print(foo()) None </code></pre> <p>Remove that <code>print()</code> call:</p> <pre><code>for name in files: file= open(name) searchForTheContent(file) </code></pre> <p>Just to be explicit: <code>print()</code> doesn't 'return' anything to the caller; <code>print()</code> sends output to the <code>stdout</code> stream, which usually is connected to your terminal which is why you see the output there. That output is not also given as a return value.</p>
3
2016-10-18T10:19:26Z
[ "python" ]
python - 'the truth value of an array with more than one element is ambiguous' - what truth value?
40,105,414
<p>first post! I've looked through a lot of other posts on this problem but can't find anything that applies to my code.</p> <p>I'm trying to read an audio file and then find the max and min values of the array of samples, <code>x</code>.<br> <code>wavread()</code> is a function defined in another module that I've imported.<br> It returns <code>fs, x</code>.<br> <code>x</code> is a one-dimensional array (<code>x.shape = (150529,)</code>.)</p> <pre><code>def minMaxAudio(inputFile): (fs, x) = wavread(inputFile) max_val = numpy.amax(x) min_val = numpy.amin(x) return (min_val, max_val) </code></pre> <p>when I type these lines individually into ipython, I get the result I want. but when I call this function from an imported .py file I get the error:</p> <pre><code>ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() </code></pre> <p>It highlights the last line (return statement) as the location of the error.</p> <p>Every other post on this that I've looked at includes some sort of evaluation or comparison operator in the code. Mine doesn't have one... does it?!</p> <p>Thanks!</p>
0
2016-10-18T10:11:13Z
40,107,303
<p>Have you noticed that if your WAV file has more than one channel, say it is stereo, min_val and max_val will be arrays themselves?</p> <p>Such a code would trigger the error you encounter:</p> <pre><code>min, max = minMaxAudio('acdc.wav') # Assuming floats if max &gt; 1: print('saturation') </code></pre> <p>Whereas the following will work:</p> <pre><code>min, max = minMaxAudio('acdc.wav') # Assuming floats if np.any(max &gt; 1): print('saturation') </code></pre>
0
2016-10-18T11:41:53Z
[ "python", "arrays", "numpy" ]
Python Django Template cannot get name from model function
40,105,470
<p>While I understood that I can call a function definition from our models, I can't seem to extract the file name of my uploaded document. Below I tried the following template format but either results from my desired output:</p> <p><strong><em>.html Version 1</em></strong></p> <pre><code>&lt;form action="." method="GET"&gt; {% if documents %} &lt;ul&gt; {% for document in documents %} &lt;li&gt; {{ document.docfile.filename }} &lt;input type = "submit" name="load-data" value="Add to Layer"/&gt; &lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre> <p><em>Result: It just shows the button.</em></p> <p><strong><em>.html Version 2</em></strong></p> <pre><code>&lt;form action="." method="GET"&gt; {% if documents %} &lt;ul&gt; {% for document in documents %} &lt;li&gt; {{ document.filename }} &lt;input type = "submit" name="load-data" value="Add to Layer"/&gt; &lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre> <p><em>Result: It just shows the button.</em></p> <p><strong><em>.html Version 3</em></strong></p> <pre><code>&lt;form action="." method="GET"&gt; {% if documents %} &lt;ul&gt; {% for document in documents %} &lt;li&gt; {{ document.docfile.name }} &lt;input type = "submit" name="load-data" value="Add to Layer"/&gt; &lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre> <p><em>Result: Prints the complete pathname (eg: /documents/2016/10/08/filename.csv) together with the button</em></p> <p>Here's the rest of my code:</p> <p><strong><em>models.py</em></strong></p> <pre><code>class Document(models.Model): docfile = models.FileField(upload_to='document/%Y/%m/%d') def filename(self): return os.path.basename(self.file.name) </code></pre> <p><strong><em>views.py</em></strong></p> <pre><code>documents = Document.objects.all() return render(request, 'gridlock/upload-data.html', { 'documents' : documents, 'form': form }) </code></pre> <p>I hope someone can explain why everything I tried: <code>{{ document.docfile.filename }}</code> or <code>{{document.file.filename}}</code> or <code>{{document.filename}}</code> won't work either for me? Thanks!</p>
2
2016-10-18T10:14:06Z
40,105,590
<p>I think you got pretty close with <code>{{ document.filename }}</code>, except in your models you need to change </p> <pre><code>def filename(self): return os.path.basename(self.file.name) </code></pre> <p>into</p> <pre><code>def filename(self): # try printing the filename here to see if it works print (os.path.basename(self.docfile.name)) return os.path.basename(self.docfile.name) </code></pre> <p>in your models the field is called docfile, so you need to use self.docfile to get its value.</p> <p>source: <a href="http://stackoverflow.com/questions/2683621/django-filefield-return-filename-only-in-template">django filefield return filename only in template</a></p>
4
2016-10-18T10:18:56Z
[ "python", "django", "file", "filefield" ]
Custom python editor
40,105,483
<p>I am looking for such python editors which suggest inputs(mentioned in file/database) while using custom modules and functions during writing programs.</p> <p>Is there similar type of editor already exists that I can build something upon? Can I develop such editor? If yes, how?</p>
0
2016-10-18T10:14:38Z
40,105,820
<p>Try PyCharm, probably this software will cover all your needs</p>
1
2016-10-18T10:29:48Z
[ "python", "editor" ]
Custom python editor
40,105,483
<p>I am looking for such python editors which suggest inputs(mentioned in file/database) while using custom modules and functions during writing programs.</p> <p>Is there similar type of editor already exists that I can build something upon? Can I develop such editor? If yes, how?</p>
0
2016-10-18T10:14:38Z
40,105,839
<p>You can use vim editor by including this line in your ~/.vimrc file.</p> <pre><code>:h ins-completion </code></pre> <p>Now you can use the below keyboard shortcut for auto complete feature for your custom functions. </p> <p>Completion can be done for:</p> <ol> <li>Whole lines |i_CTRL-X_CTRL-L|</li> <li>keywords in the current file |i_CTRL-X_CTRL-N|</li> <li>keywords in 'dictionary' |i_CTRL-X_CTRL-K|</li> <li>keywords in 'thesaurus', thesaurus-style |i_CTRL-X_CTRL-T|</li> <li>keywords in the current and included files |i_CTRL-X_CTRL-I|</li> <li>tags |i_CTRL-X_CTRL-]|</li> <li>file names |i_CTRL-X_CTRL-F|</li> <li>definitions or macros |i_CTRL-X_CTRL-D|</li> <li>Vim command-line |i_CTRL-X_CTRL-V|</li> </ol> <p>if you want to learn the vim basics use this link :<a href="http://vim.wikia.com/wiki/Tutorial" rel="nofollow">Vim Basics</a></p>
0
2016-10-18T10:30:50Z
[ "python", "editor" ]
Custom python editor
40,105,483
<p>I am looking for such python editors which suggest inputs(mentioned in file/database) while using custom modules and functions during writing programs.</p> <p>Is there similar type of editor already exists that I can build something upon? Can I develop such editor? If yes, how?</p>
0
2016-10-18T10:14:38Z
40,106,098
<p>I would suggest, that you use the PyDev plugin for eclipse. PyDev has a lot of stuff, that increases the efficiency. You find it under: <a href="http://www.pydev.org/" rel="nofollow">http://www.pydev.org/</a></p> <p>Best Regards 1574ad6</p>
0
2016-10-18T10:44:19Z
[ "python", "editor" ]
python two dimensional recursion
40,105,513
<p>I have list pairs of keys and their possible values that are parsed from command line. eg:</p> <p><code>[('-a',['1','2','3']), ('-b',['1','2'])]</code></p> <p>my goal is to produce combinations as follows:</p> <pre><code>prefix -a=1 -b=1 suffix prefix -a=1 -b=2 suffix prefix -a=2 -b=1 suffix prefix -a=2 -b=2 suffix prefix -a=3 -b=1 suffix prefix -a=3 -b=2 suffix </code></pre> <p>problem is, the list can be of any length and so does the values in the sub lists.</p> <p>The possible solution would be using some kind of recursion, so far what I wrote doesn't give me what I want:</p> <pre><code>def runner(args, comd=""): for i in range(len(args)): op, vals = args[i] for val in vals: comd = op + "=" + val + " " + runner(args[1:], comd) if i == len(args) - 1: print ("prefix " + comd + " suffix") return comd </code></pre>
0
2016-10-18T10:15:48Z
40,105,729
<p>You want to do <a href="https://en.wikipedia.org/wiki/Cartesian_product" rel="nofollow">cartesian product</a> of two list. Use <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product()</code></a> for doing that. For example:</p> <pre><code>&gt;&gt;&gt; my_list = [('-a',['1','2','3']), ('-b',['1','2'])] &gt;&gt;&gt; from itertools import product &gt;&gt;&gt; list(product(my_list[0][1], my_list[1][1])) [('1', '1'), ('1', '2'), ('2', '1'), ('2', '2'), ('3', '1'), ('3', '2')] </code></pre> <p>It gives the <code>list</code> of all combinations of <code>tuple</code> from both list. </p> <hr> <p>Now, coming to your problem, below is the sample code:</p> <pre><code>my_list = [('-a',['1','2','3']), ('-b',['1','2'])] keys, value_list = zip(*my_list) for item in product(*value_list): val_list = ['{}={}'.format(key, val) for key, val in zip(keys, item)] print 'prefix {} suffix'.format(' '.join(val_list)) # Output: prefix -a=1 -b=1 suffix prefix -a=1 -b=2 suffix prefix -a=2 -b=1 suffix prefix -a=2 -b=2 suffix prefix -a=3 -b=1 suffix prefix -a=3 -b=2 suffix </code></pre> <p><strong>Explanation:</strong></p> <p><a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip([iterable, ...])</code></a> returns a <em>list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence</em>. For example, in above code:</p> <pre><code>&gt;&gt;&gt; keys, value_list = zip(*my_list) # zipping the unwrapped "my_list" &gt;&gt;&gt; keys # value of keys ('-a', '-b') &gt;&gt;&gt; value_list # value of values_list (['1', '2', '3'], ['1', '2']) </code></pre> <p>Then I am doing the <em>cartesian product</em> on <code>values_list</code> (as explained in the very beginning) and again doing <code>zip</code> on the <code>keys</code> and each <code>item</code> of the cartesian product.</p>
3
2016-10-18T10:25:10Z
[ "python", "recursion", "combinations" ]
I want to read back a line from a specific line/string in python
40,105,536
<p>this is the code that has me really confused:</p> <pre><code>if search in open('test.txt').read(): print("product is found") </code></pre> <p>i am trying to re-read a line fro my text file using the .read() function however i do not know how this would work from searching a single string. EG: if search is 12345 i want to find this in the text file and then output it on the shell. I have tried numerous different ways but cannot get it to work. This is for my work experience and would help me a lot.</p>
0
2016-10-18T10:16:36Z
40,105,663
<p>try:</p> <pre><code>s = input("enter") file = open("test.txt","r") for line in file: if s in open('test.txt').read(): print("product is found") </code></pre>
-2
2016-10-18T10:22:29Z
[ "python" ]
I want to read back a line from a specific line/string in python
40,105,536
<p>this is the code that has me really confused:</p> <pre><code>if search in open('test.txt').read(): print("product is found") </code></pre> <p>i am trying to re-read a line fro my text file using the .read() function however i do not know how this would work from searching a single string. EG: if search is 12345 i want to find this in the text file and then output it on the shell. I have tried numerous different ways but cannot get it to work. This is for my work experience and would help me a lot.</p>
0
2016-10-18T10:16:36Z
40,105,696
<p>If I understood you right, you want to get the line which matches the <code>search</code>. If so, you just need to read file line by line which can be done like this</p> <pre><code>for line in open('test.txt'): if search in line: print("Product is found on line", line.strip()) </code></pre>
1
2016-10-18T10:23:37Z
[ "python" ]
Cannot find dynamic library when running a Python script from Bazel
40,105,625
<p>I am trying to setup CUDA enabled Python &amp; TensorFlow environment on OSx 10.11.6</p> <p>Everything went quite smoothly. First I installed following:</p> <ul> <li>CUDA - 7.5</li> <li>cuDNN - 5.1</li> </ul> <p>I ensured that the LD_LIBRARY_PATH and CUDA_HOME are set properly by adding following into my ~/.bash_profile file:</p> <pre><code>export CUDA_HOME=/usr/local/cuda export DYLD_LIBRARY_PATH="$CUDA_HOME/lib:$DYLD_LIBRARY_PATH" export LD_LIBRARY_PATH="$CUDA_HOME/lib:$LD_LIBRARY_PATH" export PATH="$CUDA_HOME/bin:$PATH" </code></pre> <p>Then I used Brew to install following:</p> <ul> <li>python - 2.7.12_2</li> <li>bazel - 0.3.2</li> <li>protobuf - 3.1.0</li> </ul> <p>Then I used Pip to install CPU only TensorFlow from: <a href="https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.11.0rc0-py2-none-any.whl" rel="nofollow">https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-0.11.0rc0-py2-none-any.whl</a></p> <p>I checked out the Magenta project from: <a href="https://github.com/tensorflow/magenta" rel="nofollow">https://github.com/tensorflow/magenta</a> and run all the test using:</p> <pre><code>bazel test //magenta/... </code></pre> <p>And all of them have passed.</p> <p>So far so good. So I decided to give the GPU enabled version of TensorFlow a shot and installed it from: <a href="https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow-0.11.0rc0-py2-none-any.whl" rel="nofollow">https://storage.googleapis.com/tensorflow/mac/gpu/tensorflow-0.11.0rc0-py2-none-any.whl</a></p> <p>Now all the tests fail with the following error:</p> <pre><code>import tensorflow as tf File "/usr/local/lib/python2.7/site-packages/tensorflow/__init__.py", line 23, in &lt;module&gt; from tensorflow.python import * File "/usr/local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 49, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/usr/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in &lt;module&gt; _pywrap_tensorflow = swig_import_helper() File "/usr/local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description) ImportError: dlopen(/usr/local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so, 10): Library not loaded: @rpath/libcudart.7.5.dylib Referenced from: /usr/local/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so Reason: image not found </code></pre> <p>So obviously the script run from Bazel has trouble locating the libcudart.7.5.dylib library.</p> <p>I did try running GPU computations from Python without Bazel and everything seems to be fine.</p> <p>I also did create a test script and run it using Bazel and it seems that the directory containing libcudart.7.5.dylib library is reachable, however the LD_LIBRARY_PATH is not set.</p> <p>I searched the documentation and found --action_env and --test_env flags, but none of them actually seems to set the LD_LIBRARY_PATH for the execution.</p> <p>These are the options from loaded from .bazelrc files.</p> <pre><code>Inherited 'common' options: --isatty=1 --terminal_columns=80 Inherited 'build' options: --define=allow_oversize_protos=true --copt -funsigned-char -c opt --spawn_strategy=standalone 'run' options: --spawn_strategy=standalone </code></pre> <p>What is the correct way to let Bazel know about the runtime dependencies?</p>
0
2016-10-18T10:20:50Z
40,111,416
<p>Use </p> <pre><code>export LD_LIBRARY_PATH=/usr/local/cuda/lib64/ </code></pre> <p>before launching bazel. Double check in the directory above if there is such a file.</p> <pre><code>ls /usr/local/cuda/lib64/libcudart.7.5.dylib </code></pre> <p>Note that in Macosx the name is different:</p> <pre><code>export DYLD_LIBRARY_PATH=/usr/local/cuda/lib/ </code></pre> <p>See this answer for more information on <a href="http://superuser.com/questions/282450/where-do-i-set-dyld-library-path-on-mac-os-x-and-is-it-a-good-idea">SuperUser</a></p>
0
2016-10-18T14:47:49Z
[ "python", "osx", "tensorflow", "bazel" ]
How to get custom object from callfunc in cx_Oracle?
40,105,683
<p>I have an PL/SQL function <code>my_function</code> that returns custom defined object:</p> <pre><code>CREATE OR REPLACE TYPE "TP_ACTION" AS OBJECT (   stop_time timestamp,   user_name varchar2(64),   error_msg tp_message_l, CONSTRUCTOR FUNCTION TP_ACTION(    usrnm in varchar2 := null ) RETURN SELF AS RESULT,   MEMBER PROCEDURE doClose(pi_session_MD5 IN  VARCHAR2),   member procedure setRunStatus(status in varchar2), ) </code></pre> <p>Therefore in python I call that function:</p> <pre><code>var_type = cursor.var(cx_Oracle.OBJECT, typename='TP_ACTION') cursor.callfunc('my_function', var_type, params) </code></pre> <p>After that I get exception:</p> <pre><code> cx_Oracle.NotSupportedError: Variable_TypeByPythonType(): unhandled data type. </code></pre> <p>Is it even possible to get custom definded object by calling PL/SQL function? Or maybe there is another way to get it?</p>
0
2016-10-18T10:23:08Z
40,112,328
<p>The ability to bind Oracle objects is only available in the unreleased (development) version of cx_Oracle. This is needed for calling a function that returns an object. If you can make use of the development version your code will work; otherwise, please wait for the official release.</p>
0
2016-10-18T15:31:26Z
[ "python", "plsql", "cx-oracle" ]
FFT removal of periodic noise
40,105,777
<p>This a much discussed topic, but I happen to have an issue that has not been answered yet. My problem is not the method it self but rather it's applicability: My image's f(x,y) represent physical values that can be <strong>negative or positive</strong>. When I mask the peaks corresponding with, say the median, i get, after application of the inverse FFT, an image which is complex. </p> <p>This seams logical as image != ifft(fft(image)) if image != image, thus it can very well be complex result?</p> <p>I thus take the absolute value of my image array, and get a nicely cleaned image. But by taking the abs of the image <strong>i have lost the negative values!</strong></p> <p>My code is complex and uses multiple images to find the correct positions where to mask so I will break down to the essentials:</p> <pre><code>def everything(fft,fftImage,sizeOfField,shapeOfFFT): max_x = [] max_y = [] median = np.median(fft) threshold = 500 #correctLocalMax() holds several subfunctions that look for the propper max_x and max_y. This works fine and returns 2 lists max_x,max_Y that contain the coordiantes of the max's max_x,max_y = correctLocalMax(iStart = 0,iStop = 30, jStart =0 , jStop = shapeOfFFT[1],threshold=threshold, max_x = max_x, max_y = max_y) for i in range(len(max_x)): for k in range(sizeOfField): for l in range(sizeOfField): fftImage[max_x[i]+k][max_y[i]+l] = median return(fftImage) image, coverage, stdev = pickleOpener(dataDir,i) field = getROI(image,area,i0,j0) fftImage = np.fft.fft2(image) fftImage = np.fft.fftshift(fftImage) fft = np.fft.fft2(coverage) fft = np.fft.fftshift(fft) fftMod = everything(fft, fftImage, sizeOfField, shapeOfFFT) imageBack = np.fft.ifft2(fftMod) imageBack = np.abs(imageBack) field = getROI(imageBack,area,i0,j0) </code></pre> <p>The images I have and get after processing look like this: <a href="https://i.stack.imgur.com/0QJoy.png" rel="nofollow"><img src="https://i.stack.imgur.com/0QJoy.png" alt="enter image description here"></a> The stripe pattern are the ones I wish to remove</p> <p><a href="https://i.stack.imgur.com/7RJF8.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/7RJF8.jpg" alt="enter image description here"></a> These are the masks applied to the FFT</p> <p><a href="https://i.stack.imgur.com/0J2DG.png" rel="nofollow"><img src="https://i.stack.imgur.com/0J2DG.png" alt="enter image description here"></a> The stripe pattern is mostly removed, however now the image is purely positive!</p> <p><strong>You can find the proper solution to the problem in the comments!</strong></p>
1
2016-10-18T10:27:39Z
40,106,070
<p>You could try two different approaches: Either you scale your image between the original values first, and rescale later, somewhat like this:</p> <pre><code>max_val = max(max(A)) min_val = min(min(A)) % normalize to [0,1] image = norm(image) % do your stuff here % then rescale to original values image = min_val + (max_val - min_val).*image / (max_val - min_val) </code></pre> <p>An alternative would be to save which values where negative in first place. Although I'd recommend to check whether they got changed during your function call to avoid reinstating your noise</p>
1
2016-10-18T10:43:06Z
[ "python", "image-processing", "fft" ]
Python complete newbie, JSON formatting
40,105,864
<p>I have never used Python before but am trying to use it due to some restrictions in another (proprietary) language, to retrieve some values from a web service and return them in json format to a home automation processor. The relevant section of code below returns :</p> <pre><code>[u'Name:London', u'Mode:Auto', u'Name:Ling', u'Mode:Away'] ["Name:London", "Mode:Auto", "Name:Ling", "Mode:Away"] </code></pre> <p>…which isn't valid json. I am sure this is a really dumb question but I have searched here and haven't found an answer that helps me. Apologies if I missed something obvious but can anyone tell me what I need to do to ensure the json.dumps command outputs data in the correct format?</p> <pre><code>CresData = [] for i in range(0, j): r = requests.get('http://xxxxxx.com/WebAPI/emea/api/v1/location/installationInfo?userId=%s&amp;includeTemperatureControlSystems=True' % UserID, headers=headers) CresData.append("Name:" + r.json()[i]['locationInfo']['name']) r = requests.get('http://xxxxxx.com/WebAPI/emea/api/v1/location/%s/status?includeTemperatureControlSystems=True' % r.json()[i]['locationInfo']['locationId'], headers = headers) CresData.append('Mode:' + r.json()['gateways'][0]['temperatureControlSystems'][0]['systemModeStatus']['mode']) Cres_json = json.dumps(CresData) print CresData print Cres_json </code></pre>
-2
2016-10-18T10:32:13Z
40,106,351
<p>I wasn't able to test the code as the link you mentioned is not a live link but your solution should be something like this</p> <p>It looks like you are looking for JSON format with key value pair. you need to pass a dict object into json.dumps() which will return you string in required JSON format.</p> <pre><code>CresData = dict() key_str = "Location" idx = 0 for i in range(0, j): data = dict() r = requests.get('http://xxxxxx.com/WebAPI/emea/api/v1/location/installationInfo?userId=%s&amp;includeTemperatureControlSystems=True' % UserID, headers=headers) data["Name"] = r.json()[i]['locationInfo']['name'] r = requests.get('http://xxxxxx.com/WebAPI/emea/api/v1/location/%s/status?includeTemperatureControlSystems=True' % r.json()[i]['locationInfo']['locationId'], headers = headers) data["mode"] = r.json()['gateways'][0]['temperatureControlSystems'][0]['systemModeStatus']['mode'] CresData[key_str + str(idx)] = data idx +=1 Cres_json = json.dumps(CresData) print CresData print Cres_json </code></pre>
0
2016-10-18T10:56:23Z
[ "python", "json" ]
Finding solution to a crypt equation in python
40,105,929
<p>Consider the equation ABCBA = D * BE * BFFA.The task is to determine where A, B, C, D, E and F which are distinct digits. The equation with numerical values is 91819 = 7 * 13 * 1009, hence the program should print {'A':9, 'B':1, 'C':8 , 'D':7,'E':3, 'F':0}. Here is the code i did</p> <pre><code>result=[] for A in range (10): for B in range(10): for C in range(10): for D in range(10): for E in range(10): for F in range(10): if int(str(A)+str(B)+str(C)+str(B)+str(A)) == D * int(str(B)+str(E)) * int(str(B)+str(F)+str(F)+str(A)): result.append({'A':A,'B':B,'C':C,'D':D,'E':E,'F':F}) print((result[len(result)-1])) </code></pre> <p>Now that it works for the equation in the example.How sholud I modify my code so that it works for any equation,which is to be input by the user?</p>
-2
2016-10-18T10:35:51Z
40,107,147
<p>If you only need your last output and want to discard everything else you can just overwrite the same variable over and over again:</p> <pre><code>result = {} for B in range(10): for C in range(10): for D in range(10): for E in range(10): for F in range(10): if int(str(A)+str(B)+str(C)+str(B)+str(A)) == D * int(str(B)+str(E)) * int(str(B)+str(F)+str(F)+str(A)): result = {'A':A,'B':B,'C':C,'D':D,'E':E,'F':F} pprint(result) </code></pre> <p>If you want to keep all results but only print the last one use a list:</p> <pre><code>result = [] for B in range(10): for C in range(10): for D in range(10): for E in range(10): for F in range(10): if int(str(A)+str(B)+str(C)+str(B)+str(A)) == D * int(str(B)+str(E)) * int(str(B)+str(F)+str(F)+str(A)): result.append({'A':A,'B':B,'C':C,'D':D,'E':E,'F':F}) pprint(result[-1]) </code></pre>
0
2016-10-18T11:34:14Z
[ "python", "python-3.x", "cryptography", "combinations" ]
Finding solution to a crypt equation in python
40,105,929
<p>Consider the equation ABCBA = D * BE * BFFA.The task is to determine where A, B, C, D, E and F which are distinct digits. The equation with numerical values is 91819 = 7 * 13 * 1009, hence the program should print {'A':9, 'B':1, 'C':8 , 'D':7,'E':3, 'F':0}. Here is the code i did</p> <pre><code>result=[] for A in range (10): for B in range(10): for C in range(10): for D in range(10): for E in range(10): for F in range(10): if int(str(A)+str(B)+str(C)+str(B)+str(A)) == D * int(str(B)+str(E)) * int(str(B)+str(F)+str(F)+str(A)): result.append({'A':A,'B':B,'C':C,'D':D,'E':E,'F':F}) print((result[len(result)-1])) </code></pre> <p>Now that it works for the equation in the example.How sholud I modify my code so that it works for any equation,which is to be input by the user?</p>
-2
2016-10-18T10:35:51Z
40,107,441
<p>I don't think @Khris's answer is 100% correct, as you do need a loop for <code>A</code>, and your original question listed that first digit of any number could not be 0; hence <code>A</code>, <code>B</code>, and <code>D</code> cannot be 0, so <code>if A and D and B:</code> is added for this.</p> <p>which then results in (printing all results, you can pick from there):</p> <pre><code>from pprint import pprint results = [] for A in range(10): for B in range(10): for C in range(10): for D in range(10): for E in range(10): for F in range(10): if A and D and B: if int(str(A)+str(B)+str(C)+str(B)+str(A)) == D * int(str(B)+str(E)) * int(str(B)+str(F)+str(F)+str(A)): results.append({'A':A,'B':B,'C':C,'D':D,'E':E,'F':F}) for result in results: pprint(result) </code></pre> <p>You further state the following:</p> <blockquote> <p>The last of many outputs of pprint gives the correct result.Can somebody edit it to print only the last(correct) result?</p> </blockquote> <p>Which is incorrect based on the equation <code>ABCBA = D * BE * BFFA</code>: the following results would all be valid:</p> <pre><code>{'A': 1, 'B': 1, 'C': 0, 'D': 1, 'E': 1, 'F': 0} # 11011 = 1 * 11 * 1001 {'A': 2, 'B': 1, 'C': 3, 'D': 1, 'E': 6, 'F': 3} # 21312 = 1 * 16 * 1332 {'A': 2, 'B': 1, 'C': 9, 'D': 1, 'E': 1, 'F': 9} # 21912 = 1 * 11 * 1992 {'A': 5, 'B': 1, 'C': 3, 'D': 3, 'E': 1, 'F': 5} # 51315 = 3 * 11 * 1555 {'A': 9, 'B': 1, 'C': 8, 'D': 7, 'E': 3, 'F': 0} # 91819 = 7 * 13 * 1009 </code></pre>
0
2016-10-18T11:49:13Z
[ "python", "python-3.x", "cryptography", "combinations" ]
Scrapy Request url must be str or unicode, got NoneType:
40,105,949
<p>I try to create my first spider scrapper using scrapy I use Dmoz as test, I get an error message: TypeError: Request url must be str or unicode, got NoneType But in the Debug I can see the right url</p> <p>Code:</p> <pre><code>import scrapy import urlparse class DmozSpider(scrapy.Spider): name = "dmoz" allowed_domains = ["dmoz.org"] start_urls = ["http://www.dmoz.org/search?q=france&amp;all=no&amp;t=regional&amp;cat=all"] def parse(self, response): sites = response.css('#site-list-content &gt; div.site-item &gt; div.title-and-desc') for site in sites: yield { 'name': site.css('a &gt; div.site-title::text').extract_first().strip(), 'url': site.xpath('a/@href').extract_first().strip(), 'description': site.css('div.site-descr::text').extract_first().strip(), } nxt = response.css('#subcategories-div &gt; div.previous-next &gt; div.next-page') next_page = nxt.css('a::attr(href)').extract_first() if next_page is not None: next_page = response.urljoin(next_page) yield scrapy.Request(next_page, callback=self.parse) </code></pre> <p>Logs:</p> <pre><code>2016-10-18 11:17:03 [scrapy] DEBUG: Crawled (200) &lt;GET http://www.dmoz.org/search?q=france&amp;start=20&amp;type=next&amp;all=no&amp;t=regional&amp;cat=all&gt; (referer: http://www.dmoz.org/search?q=france&amp;all=no&amp;t=regional&amp;cat=all) 2016-10-18 11:17:03 [scrapy] ERROR: Spider error processing &lt;GET http://www.dmoz.org/search?q=france&amp;start=20&amp;type=next&amp;all=no&amp;t=regional&amp;cat=all&gt; (referer: http://www.dmoz.org/search?q=france&amp;all=no&amp;t=regional&amp;cat=all) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/defer.py", line 102, in iter_errback yield next(it) File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/offsite.py", line 29, in process_spider_output for x in result: File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/referer.py", line 22, in &lt;genexpr&gt; return (_set_referer(r) for r in result or ()) File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/urllength.py", line 37, in &lt;genexpr&gt; return (r for r in result or () if _filter(r)) File "/usr/local/lib/python2.7/dist-packages/scrapy/spidermiddlewares/depth.py", line 58, in &lt;genexpr&gt; return (r for r in result or () if _filter(r)) File "/ENV/bin/tutorial/dirbot/spiders/dmoz.py", line 25, in parse yield scrapy.Request(next_page, callback=self.parse) File "/usr/local/lib/python2.7/dist-packages/scrapy/http/request/__init__.py", line 25, in __init__ self._set_url(url) File "/usr/local/lib/python2.7/dist-packages/scrapy/http/request/__init__.py", line 51, in _set_url raise TypeError('Request url must be str or unicode, got %s:' % type(url).__name__) TypeError: Request url must be str or unicode, got NoneType: 2016-10-18 11:17:03 [scrapy] INFO: Closing spider (finished) 2016-10-18 11:17:03 [scrapy] INFO: Stored json feed (20 items) in: test.json 2016-10-18 11:17:03 [scrapy] INFO: Dumping Scrapy stats: </code></pre>
0
2016-10-18T10:36:37Z
40,106,256
<p>The error is in your code here:</p> <pre><code>if next_page is not None: next_page = response.urljoin(next_page) yield scrapy.Request(next_page, callback=self.parse) </code></pre> <p>As Padraic Cunningham mentions in his commit: you <code>yield</code> the <code>Request</code> regardless of <code>next_page</code> is <code>None</code> or filled with an URL.</p> <p>You can solve your problem by changing your code to this:</p> <pre><code>if next_page is not None: next_page = response.urljoin(next_page) yield scrapy.Request(next_page, callback=self.parse) </code></pre> <p>where you put your <code>yield</code> inside your <code>if</code> block.</p> <p>By the way you can change your <code>if</code> to the following:</p> <pre><code>if next_page: </code></pre> <p>because of Python's truth.</p> <p>And because your spider stops working try to debug your application through <strong>scrapy shell</strong> where you can see if your CSS queries return values or not. You can also add an <code>else</code> to the previous <code>if</code> block which logs / prints a statement to the console that no <code>next_page</code> was found so you know that something is wrong with the site or your CSS queries.</p>
1
2016-10-18T10:52:16Z
[ "python", "web-scraping", "scrapy", "scrapy-spider" ]
Have an index error I don't know how to correct
40,106,053
<p>I found this code elsewhere on the site, but for some reason I keep getting the same error message:</p> <pre><code>products[row[0]] = [row[1], row[2], row[3]] IndexError: list index out of range. </code></pre> <p>I am unsure how to correct this, any help is appreciated, thanks. </p> <p>This is the code:</p> <pre><code>MAX_FIELD_LEN = 8 def main(): products = {} product_location = {} location = 0 # This is the file directory being made. with open('stockfile.txt', 'r+') as f: # This is my file being opened. for line in f: # keep track of each products location in file to overwrite with New_Stock product_location[line.split(',')[0]] = location location += len(line) # Need to strip to eliminate end of line character line = line[:-1] # This gets rid of the character which shows and end of line '\n' row = line.split(',') # The row is split by the comma products[row[0]] = [row[1], row[2], row[3]] # The products are equal to row 1 and row 2 and row 3. The GTIN is going to take the values of the product and price so GTIN 12345678 is going to correspond to Fridge and 1. print(products) total = 0 while True: GTIN = input('Please input GTIN: ') # To terminate user input, they just need to press ENTER if GTIN == "": break if (GTIN not in products): print('Sorry your code was invalid, try again:') break row = products[GTIN] description, value, stock = row print('Stock data: ') print('GTIN \t\tDesc. \t\tStock \t\tValue') print(GTIN,'\t',description,'\t', stock, '\t', value) quantity = input('Please also input your quantity required: ') row[2] = str(int(stock) - int(quantity)) product_total = int(quantity) * int(value) for i in range(len(row)): row[i] = row[i].rjust(MAX_FIELD_LEN) New_Stock = GTIN.rjust(MAX_FIELD_LEN) + ',' + ','.join(row) + '\n' #print(New_Stock, len(New_Stock)) f.seek(product_location[GTIN]) f.write(New_Stock) print('You bought: {0} {1} \nCost: {2}'.format(GTIN, description, product_total)) total = total + product_total f.close() print('Total of the order is £%s' % total) main() </code></pre>
0
2016-10-18T10:42:12Z
40,112,696
<p>Please check your input file 'stockfile.txt', at least one line of your file don't have 3 or more ",". Or you have some blank lines between your data.</p>
0
2016-10-18T15:47:32Z
[ "python", "indexoutofboundsexception" ]
remove control character whitespaces from dataframe
40,106,074
<p>I have a dataframe df by which I am getting list of list by using this</p> <pre><code>data = [list(map(str,n.tolist())) for n in df.values] </code></pre> <p>after that I replace specific control character from data like this </p> <pre><code>data = [ [e.replace(u'\xa0', u'') for e in tempval ] for tempval in data ] </code></pre> <p>This works fine but I want this to be done in dataframe itself please suggest something.</p>
1
2016-10-18T10:43:15Z
40,106,421
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>DataFrame.replace</code></a>:</p> <pre><code>df = pd.DataFrame({'A':['\xa0','s','w'], 'B':['s','w','v'], 'C':['e','d','\xa0']}) print (df) A B C 0 s e 1 s w d 2 w v </code></pre> <p>Then for creating <code>list</code> of <code>lists</code> convert <code>DataFrame</code> to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.values.html" rel="nofollow"><code>values</code></a> and then <code>tolist</code>:</p> <pre><code>df.replace(u'\xa0',u'', regex=True, inplace=True) #if need cast all values to str add astype print (df.astype(str).values.tolist()) [['', 's', 'e'], ['s', 'w', 'd'], ['w', 'v', '']] </code></pre>
0
2016-10-18T10:59:39Z
[ "python", "list", "pandas", "replace", "dataframe" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,138
<p>Basic approach:</p> <pre><code>&gt;&gt;&gt; a = [[0,1],[2,3]] &gt;&gt;&gt; b = [[5,6],[7,8]] &gt;&gt;&gt; c = [] &gt;&gt;&gt; for pair in zip(a,b): ... c.extend(pair) ... &gt;&gt;&gt; c [[0, 1], [5, 6], [2, 3], [7, 8]] &gt;&gt;&gt; </code></pre> <p>This breaks if the lengths aren't equal. But you can deal with that case as an exercise.</p>
6
2016-10-18T10:46:38Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,170
<p>Consider:</p> <pre><code>merged = [] for a_element, b_element in zip(a, b): merged.append(a_element) merged.append(b_element) </code></pre> <p>Unless you have very stringent performance requirements, the simplest approach is the right approach.</p>
1
2016-10-18T10:48:09Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,178
<p>You could <code>zip</code> the two lists and then reduce them to a flat list:</p> <pre><code>import operator c = reduce(operator.concat, zip(a, b)) </code></pre>
2
2016-10-18T10:48:25Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,269
<p>Assuming len(a) == len(b) and you're adding them one by one in turn:</p> <pre><code>for i in range(len(a)): c.append(a[i]) c.append(b[i]) </code></pre> <p>However, I would recommend to use <code>c = deque()</code>. Since deques are much quicker if you are making a lot of appends.</p>
0
2016-10-18T10:52:46Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,413
<p>Assuming the two lists are the same length, the most compact way to do this uses <code>itertools.chain</code> and <code>zip</code>.</p> <pre><code>from itertools import chain a = [[0,1],[2,3],[10,11],[12,13]] b = [[5,6],[7,8],[15,16],[17,18]] c = [*chain(*zip(a, b))] print(c) </code></pre> <p><strong>output</strong></p> <pre><code>[[0, 1], [5, 6], [2, 3], [7, 8], [10, 11], [15, 16], [12, 13], [17, 18]] </code></pre> <hr> <p>As juanpa.arrivillaga mentions in the comments, that syntax will not work on older versions of Python. Instead, you can do</p> <pre><code>c = list(chain(*zip(a, b))) </code></pre> <p>Here's another option, which doesn't use imports or the <code>*</code> splat operator:</p> <pre><code>c = [u for t in zip(a, b) for u in t] </code></pre> <hr> <p>If you need to handle input lists of unequal length, take a look at the <code>roundrobin</code> function in <a href="https://docs.python.org/3/library/itertools.html#itertools-recipes" rel="nofollow">Itertools Recipes</a>. Eg,</p> <pre><code>c = list(roundrobin(a, b)) </code></pre>
2
2016-10-18T10:59:10Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,106,860
<p>Another very simple approach using <em>string slicing</em> (and <strong>most performance efficient</strong>) as:</p> <pre><code>&gt;&gt;&gt; a = [[0,1],[2,3]] &gt;&gt;&gt; b = [[5,6],[7,8]] &gt;&gt;&gt; c = a + b # create a list with size = len(a) + len(b) &gt;&gt;&gt; c[::2], c[1::2] = a, b # alternately insert the value &gt;&gt;&gt; c [[0, 1], [5, 6], [2, 3], [7, 8]] </code></pre> <p>Below is the comparison of results with <code>timeit</code> for the answers mentioned here (Python version: 2.7):</p> <ol> <li><p>Using <em>string slicing</em>: 0.586 usec per loop</p> <pre><code>moin@moin-pc:~$ python -m "timeit" -s "a = [[0,1],[2,3]]; b = [[5,6],[7,8]];" "c = a + b; c[::2], c[1::2] = a, b" 1000000 loops, best of 3: 0.586 usec per loop </code></pre></li> <li><p>Using <code>itertools.chain()</code>: 1.89 usec per loop </p> <pre><code>moin@moin-pc:~$ python -m "timeit" -s "from itertools import chain; a = [[0,1],[2,3]]; b = [[5,6],[7,8]];" "c = list(chain(*zip(a, b)))" 1000000 loops, best of 3: 1.89 usec per loop </code></pre></li> <li><p>Using <code>reduce()</code>: 0.829 usec per loop</p> <pre><code>moin@moin-pc:~$ python -m "timeit" -s "import operator; a = [[0,1],[2,3]]; b = [[5,6],[7,8]];" "c = reduce(operator.concat, zip(a, b))" 1000000 loops, best of 3: 0.829 usec per loop </code></pre></li> <li><p>Using <code>list.extend()</code>: 0.824 usec per loop</p> <pre><code> moin@moin-pc:~$ python -m "timeit" -s "a = [[0,1],[2,3]]; b = [[5,6],[7,8]]; c=[]" "for pair in zip(a,b): c.extend(pair)" 1000000 loops, best of 3: 0.824 usec per loop </code></pre></li> <li><p>Using <code>list.append()</code> twice: 1.04 usec per loop</p> <pre><code>moin@moin-pc:~$ python -m "timeit" -s "a = [[0,1],[2,3]]; b = [[5,6],[7,8]]; c=[]" "for a_element, b_element in zip(a, b): c.append(a_element); c.append(b_element)" 1000000 loops, best of 3: 1.04 usec per loop </code></pre></li> </ol>
2
2016-10-18T11:20:54Z
[ "python", "list", "append" ]
alternately appending elements from two lists
40,106,080
<p>I have three lists with elements :</p> <pre><code>a = [[0,1],[2,3],...] b = [[5,6],[7,8],...] c = [] </code></pre> <p>I want to append elements from <code>a</code> and <code>b</code> into <code>c</code> to get:</p> <pre><code>c = [ [0,1],[5,6],[2,3],[7,8],.... ] </code></pre>
1
2016-10-18T10:43:27Z
40,120,558
<p>Using <a href="https://pythonhosted.org/more-itertools/api.html" rel="nofollow"><code>more_itertools</code></a> which implements the <code>itertools</code> <a href="https://docs.python.org/2/library/itertools.html#recipes" rel="nofollow"><code>roundrobin</code> recipe</a></p> <pre><code>&gt;&gt;&gt; from more_itertools import roundrobin &gt;&gt;&gt; a = [[0,1],[2,3]] &gt;&gt;&gt; b = [[5,6],[7,8]] &gt;&gt;&gt; list(roundrobin(a, b)) [[0, 1], [5, 6], [2, 3], [7, 8]] </code></pre>
0
2016-10-19T01:21:42Z
[ "python", "list", "append" ]
How to bind the return key to a function on the frame/form itself
40,106,166
<p>I'm making an app which has a sort of splash screen made in tkinter, and I would like it to close and call and run another part of the app, however i cannot for the life of me figure out why my bind won't work.</p> <p>Do keep in mind I started python about 2 weeks ago so I'm still very much a learner, any help would be greatly appreciated! I am aware that similar questions have been answered on here, however none of the questions have the windows as part of a class, and I'm having a hard time implementing the solutions into my code as a result.</p> <p>The code:</p> <pre><code>from Tkinter import * from PIL import ImageTk from PIL import Image import time class intro(Frame): global master master = Tk() #master.attributes("-fullscreen", TRUE) global img img = ImageTk.PhotoImage(Image.open("dorina.jpeg")) def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.nameLabel = Label(master, image=img) self.nameLabel.grid() checker = False self.bind("&lt;Return&gt;", lambda e: self.destroy()) if __name__ == "__main__": guiFrame = intro() guiFrame.mainloop() </code></pre>
1
2016-10-18T10:47:53Z
40,109,836
<p>This time as an answer and I hope it helps.</p> <p>The following works for me:</p> <pre><code>import Tkinter as tk class simpleapp_tk(tk.Tk): def __init__(self, parent): ## class derives from Tkinter --&gt; call its constructor tk.Tk.__init__(self, parent) ## keep track of the parent self.parent = parent self.bind("&lt;Return&gt;", lambda x: self.destroy()) if __name__ == "__main__": app = simpleapp_tk(None) app.title('test') #app.wm_attributes('-topmost', 1) # always on top app.mainloop() </code></pre>
0
2016-10-18T13:37:13Z
[ "python", "user-interface", "tkinter", "binding", "key" ]
How can I make this loop stop at a certain variable occurs
40,106,179
<p>I need to write a script that generates random numbers between 1-257000 and stops when a certain number occurs telling me how many numbers it generated so far.</p> <p>i manged to get this far but can't seem to get it to stop or count</p> <pre><code>x=1 while x &lt; 257000: import itertools import random def random_gen(low, high): while True: yield random.randrange(1, 257000) gen = random_gen(1, 100) items = list(itertools.islice(gen, 10)) print items x = x+1 </code></pre> <p>Thank you so much for your help </p>
-1
2016-10-18T10:48:30Z
40,106,427
<p>Huh. A few flaws (or at least unclear spots) in your code.</p> <ol> <li><p>You run your loop max 257000 times. Even though the probability is low, there is a chance that you don't hit the number you seek in the loop.</p></li> <li><p>Move your <code>import</code> statements out of your loop, no need to have python check loaded modules each round.</p></li> <li><p>You use a generator for choices of a list (<code>randrange</code>) where you can simply use a <code>randint()</code> call.</p></li> <li><p>You define a closed function within your loop which creates a new function at a new memory address each round.</p></li> <li><p>You slice your results into lists of 10 elements each; is this for printing, or do you actually need your random integers grouped into such lists?</p></li> </ol> <p>A very simple and straightforward implementation of your described problem could be:</p> <pre><code>import random num = 0 # Our counter certain_number = 123456 # The number we seek while True: # Run until we break # Increment for each new step num += 1 # Generate a single number from the given range random_number = random.randint(1, 257000) if random_number == certain_number: # Break if we hit it break print('Hit after {} tries.'.format(num)) &gt;&gt;&gt; Hit after 382001 tries. </code></pre>
2
2016-10-18T10:59:44Z
[ "python", "python-2.7", "loops", "random" ]
How can I make this loop stop at a certain variable occurs
40,106,179
<p>I need to write a script that generates random numbers between 1-257000 and stops when a certain number occurs telling me how many numbers it generated so far.</p> <p>i manged to get this far but can't seem to get it to stop or count</p> <pre><code>x=1 while x &lt; 257000: import itertools import random def random_gen(low, high): while True: yield random.randrange(1, 257000) gen = random_gen(1, 100) items = list(itertools.islice(gen, 10)) print items x = x+1 </code></pre> <p>Thank you so much for your help </p>
-1
2016-10-18T10:48:30Z
40,106,475
<p>First, put your <code>import</code> statements and your function definitons <em>outside</em> your while-loop. That's being <strong>super</strong> redundant.</p> <pre><code>&gt;&gt;&gt; def random_gen(low,high): ... while True: ... yield random.randrange(low,high) ... &gt;&gt;&gt; lucky = 7 &gt;&gt;&gt; rg = random_gen() &gt;&gt;&gt; rg = random_gen(1,1000) &gt;&gt;&gt; next(itertools.dropwhile(lambda t: t[1] != lucky, enumerate(rg, 1))) (811, 7) &gt;&gt;&gt; </code></pre> <p>Here's another run, just for fun:</p> <pre><code>&gt;&gt;&gt; rg = random_gen(1,257000) &gt;&gt;&gt; n,L = next(itertools.dropwhile(lambda t: t[1] != lucky, enumerate(rg, 1))) &gt;&gt;&gt; n 22602 &gt;&gt;&gt; L 7 &gt;&gt;&gt; </code></pre>
0
2016-10-18T11:02:12Z
[ "python", "python-2.7", "loops", "random" ]
Python Import specific file or directory
40,106,345
<p>I want to import file 'a' into file 'b' how to do it ? I tried with os,sys etc but it doesnt work for me. I just want to go 2 folders up and go into file a. I hope that its understable.</p> <p>file a : C:\Web\Tests\Current\Automated tests\Common\extensions\file.py</p> <p>file b: C:\Web\Tests\Current\Automated tests\EAW\extensions\targetFile.py</p>
0
2016-10-18T10:56:18Z
40,106,771
<p>At top of file b, append file a path into sys.path</p> <p>For your case, added line below into file_b.py</p> <pre><code>sys.path.append(r'C:\Web\Tests\Current\Automated tests\Common\extensions') import file_a </code></pre>
0
2016-10-18T11:16:19Z
[ "python", "file", "import", "directory" ]
Python Import specific file or directory
40,106,345
<p>I want to import file 'a' into file 'b' how to do it ? I tried with os,sys etc but it doesnt work for me. I just want to go 2 folders up and go into file a. I hope that its understable.</p> <p>file a : C:\Web\Tests\Current\Automated tests\Common\extensions\file.py</p> <p>file b: C:\Web\Tests\Current\Automated tests\EAW\extensions\targetFile.py</p>
0
2016-10-18T10:56:18Z
40,130,997
<pre><code>import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..' , 'Common' , 'extensions')) import library </code></pre> <p>this resolved my problem thanks !</p>
0
2016-10-19T12:07:08Z
[ "python", "file", "import", "directory" ]
How do I declare a line in a text file as a variable?
40,106,389
<p>For example, I have opened a text file and found a product that the user wants to "buy". The products are listed on a notepad text file, with the product name then a new line then the cost of the product, for example</p> <pre><code>radiators 0.50 fridge 0.50 </code></pre> <p>This is what I have done so far:</p> <pre><code>product = input("What product would you like?") userfile = open ("products.txt","r") lines = userfile.readlines() for i in range(0, len(lines)): line = lines[i] if product in (line): found = True print("Found " + line) print("This product is " + lines[i+1]) print("This product costs " +lines[i+2]) </code></pre> <p>I need to declare <code>lines[i+2]</code> as a variable so I can multiply it like an integer. Is there a way that I can do this?</p>
0
2016-10-18T10:58:00Z
40,106,495
<p>Try this out :</p> <p>product = input("What product would you like?")</p> <pre><code>userfile = open ("products.txt","r") lines = userfile.readlines() for line in lines: line = line.rstrip('\n') if product in line: found = True print("Found " + line) print("This product is " + lines[i+1]) print("This product costs " + int(lines[i+2])) </code></pre>
0
2016-10-18T11:03:20Z
[ "python", "file", "lines", "readlines" ]
Python IndexError handling
40,106,437
<pre><code>def kindDetector(list): for i in range(0,len(list)): if type(list[i]) != type('a'): return 0 return 1 def findWords(list,i): if i == 0: return list[0] if list[i] &lt; findWords(list,i-1): return list.pop(i) else: return list.pop(i-1) def sortWords(list,i): result=[] while i &gt;= 0: result.append(findWords(list,i)) i -=1 print(result) list = input('Enter your words, with a space between.\t').split() i = len(list)-1 if kindDetector(list): sortWords(list,i) </code></pre> <p>But here i only can enter 2 words when i try it with 3 this happens:</p> <pre><code>Traceback (most recent call last): File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 26, in &lt;module&gt; sortWords(list,i) File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 18, in sortWords result.append(findWords(list,i)) File "C:/Users/honey/Desktop/python/selfMade/sortWords.py", line 10, in findWords if list[i] &lt; findWords(list,i-1): IndexError: list index out of range </code></pre>
1
2016-10-18T11:00:16Z
40,106,977
<p>You have mixed <em>BubbleSort</em> (i.e. comparing neighbors and trying to shift them one at a time until the list is sorted) with <em>SelectionSort</em> (i.e. find the <em>smallest</em> item from an unsorted list and append it to the front of a resulting list).</p> <p>And, there are a few more problems here:</p> <ul> <li><p>Python passes variables by reference, which means that your functions receive a handle for the original list instead of a copy. If you change the list (what your <code>pop()</code> calls do) while iterating, you will run into index errors.</p></li> <li><p>Your <code>findWords</code> function is flawed. You iterate from back to front and check whether the current element is lexicographically smaller than its predecessor (i.e. <em>left</em> neighbor). You probably want to change the <code>pop</code>-calls to <code>return</code> statements, don't you?</p></li> </ul> <p>I have quickly implemented a few basic sorting algorithms (no error handling, type comparator usage etc whatsoever):</p> <pre><code>def is_list_of_strings(lst): for i in range(0,len(lst)): if type(lst[i]) not in (str, unicode): return False return True def is_sorted(lst): if len(lst) &lt; 2: return True for i in range(len(lst) - 1): if not lst[i] &lt; lst[i + 1]: return False return True def selection_sort(lst): l = lst[:] # Copy! r = [] while len(l): r.append(l.pop(l.index(min(l)))) return r def insertion_sort(lst): l = lst[1:] # Copy! r = [lst[0]] for e in l: inserted = False for w in r: if e &lt; w: r.insert(r.index(w), e) inserted = True break if not inserted: r.append(e) return r def bubble_sort(lst): l = lst[:] # Copy! while not is_sorted(l): for i in range(len(l) - 1): if l[i] &gt; l[i + 1]: tmp = l[i] l[i] = l[i + 1] l[i + 1] = tmp return l if __name__ == '__main__': lst = ['aaa', 'aba', 'aab', 'baz', 'bar'] print('Valid list of strings?', is_list_of_strings(lst)) print(lst, is_sorted(lst)) bbl = bubble_sort(lst) ins = insertion_sort(lst) sel = selection_sort(lst) print(bbl, is_sorted(bbl)) print(ins, is_sorted(ins)) print(sel, is_sorted(sel)) </code></pre> <p>Have a look at them, try to understand them and have a read about these three techniques online. And then try to re-implement them using your own functions. Have fun coding :)</p>
3
2016-10-18T11:26:09Z
[ "python", "python-3.x" ]
Python escape sequence complex output
40,106,468
<p>When I am writing the following command in Python IDLE it will give you the output with quotes, I want to know why it is giving such output.</p> <pre><code>x='''''abc\'abcddd''''' print x </code></pre> <p>This is output of the written code.</p> <pre><code>''abc'abcddd </code></pre>
3
2016-10-18T11:01:36Z
40,106,599
<p>It is due to pythons triple quoted strings:</p> <pre><code>''' ''' </code></pre> <p>It interprets everything in between as a character. So in your string:</p> <pre><code>'''''abc\'abcddd''''' </code></pre> <p>The first three quotes 'open' the string. Than it encounters 2 quotes, which it interprets as characters. Next it encounters an escaped quote, which would be printed as a quote anyway, but it still uses the escaped quote. It then encounters the first 3 of the last 5 quotes, ending the triple quoted string. It then encounters 2 more quotes forming an empty string <code>''</code>. </p> <p>A space at the places python considers 1 'thing':</p> <pre><code>''' ''abc\'abcddd ''' '' </code></pre>
2
2016-10-18T11:08:16Z
[ "python", "string", "escaping", "sequence" ]
Theano shared variable constructor error
40,106,537
<p>weights is a list of Numpy ndarray </p> <pre><code>WEIGHTS = [] for weight in weights: WEIGHTS.append(Theano.shared(Numpy.array(weight), dtype = Theano.config.floatX)) </code></pre> <p>Error:</p> <pre><code> No suitable SharedVariable constructor could be found. Are you sure all kwargs are supported? We do not support the parameter dtype or type. value="[[-0.59437655 -0.66183091 -0.49330967 0.5341272 -0.71235842 -0.5309111 -0.41950136 0.76606105 0.63401357 -0.66799208 -0.13825129 -0.64355341 -0.08321964 0.78879952 0.38723046 -0.80254236] [-0.00340653 -0.68424882 0.73717993 -0.03259952 0.01908119 -0.27347914 -0.54578049 -0.64197806 -0.70909294 -0.8278319 -0.54029437 -0.41299341 0.50841491 -0.4404315 0.0034083 -0.81478237] [-0.20577933 -0.09402267 -0.51729256 0.13291719 -0.18898014 -0.54618225 -0.38046483 0.91222028 -0.32784083 0.54191663 0.59148461 -0.34773102 -0.71356567 0.75372991 0.57200978 -1.00560169] [ 0.97094749 -1.04304354 -0.15371007 0.73932224 -0.7284857 0.17841782 -0.05476279 -0.30589505 -0.67929633 0.8480269 0.22350553 -0.04623159 -0.84297018 0.25937871 -0.46716392 0.51133557] [ 0.00915791 -0.04072289 0.38978791 -0.12274089 -0.30497646 0.16863023 -0.16831554 0.10480249 -0.82082575 0.0604674 0.61837916 -0.71897132 -0.63089596 -0.29704382 0.66048502 0.05797768] [-0.00160207 0.19007147 0.1006495 0.39384944 -0.67329269 -0.37062895 0.78985188 0.72247071 0.72813554 -0.23919282 -0.54938919 -0.70114392 0.83733916 -0.15144549 -0.81298212 0.34608201] [-0.37888527 0.57368407 -0.23682759 -0.02748364 0.21932119 0.68937528 -0.57860715 -0.84222829 0.00630163 0.24761677 0.85834009 0.77399599 0.57457557 0.73063443 -0.3520059 -0.04101319] [ 0.58357881 0.49840153 -0.33299835 0.43245037 -0.49692561 0.08307794 -0.39417695 0.45403968 -0.2331192 -0.44734402 0.63857672 0.11523024 -0.00893871 0.25680397 -0.57907839 0.15743863] [ 0.31255415 0.58321199 -0.30659539 0.17275353 -0.78450044 -0.63778058 -0.36795226 -0.19436784 -0.44348407 0.77695667 -0.71754174 0.4312374 -0.48059778 -0.45765487 -0.44493203 0.00242202]]". parameters="{'dtype': 'float64'}" </code></pre>
0
2016-10-18T11:05:02Z
40,106,793
<p>The shared function don't support the dtype parameter. It is numpy that support it. Error Resolved!</p>
0
2016-10-18T11:17:27Z
[ "python", "numpy", "theano" ]
KeyError in JSON request Python - NYT API
40,106,794
<p>I am trying to extract the URL of specific articles from NYT API. This is my code:</p> <pre><code>import requests for i in range(0,100): page=str(i) r = requests.get("http://api.nytimes.com/svc/search/v2/articlesearch.json?begin_date=20100101&amp;q=terrorist+attack&amp;page="+page+"&amp;api-key=***") data = r.json() article = data['response']['docs'] for url in article: print(url["web_url"]) </code></pre> <p>After printing the first 20 URL it gives me this error</p> <pre><code>KeyError: 'response' </code></pre> <p>however by checking random pages the key 'response' is present in any of them. What can I do to print all the URLs from the next 88 pages?</p>
-1
2016-10-18T11:17:37Z
40,111,097
<p>You are assuming that there are at least 101 pages to make requests (0 to 100).</p> <p>If you make a request to page 100, do you still get the same JSON structure with a <code>response</code> key?</p> <p>What you should instead use is a while loop that breaks when you get a <code>KeyError</code>.</p>
0
2016-10-18T14:34:14Z
[ "python" ]
How to make nested xml structure flat with python
40,106,821
<p>I have XML with huge nested structure. Like this one </p> <pre><code>&lt;root&gt; &lt;node1&gt; &lt;subnode1&gt; &lt;name1&gt;text1&lt;/name1&gt; &lt;/subnode1&gt; &lt;/node1&gt; &lt;node2&gt; &lt;subnode2&gt; &lt;name2&gt;text2&lt;/name2&gt; &lt;/subnode2&gt; &lt;/node2&gt; &lt;/root&gt; </code></pre> <p>I want convert it to</p> <pre><code>&lt;root&gt; &lt;node1&gt; &lt;name1&gt;text1&lt;/name1&gt; &lt;/node1&gt; &lt;node2&gt; &lt;name2&gt;text2&lt;/name2&gt; &lt;/node2&gt; &lt;/root&gt; </code></pre> <p>I was tried with following steps</p> <pre><code>from xml.etree import ElementTree as et tr = etree.parse(path) root = tr.getroot() for node in root.getchildren(): for element in node.iter(): if (element.text is not None): node.extend(element) </code></pre> <p>I also tried with <code>node.append(element)</code> but it also does not work it adds element in end and i got infinity loop. Any helps be appreciated.</p>
0
2016-10-18T11:19:07Z
40,110,597
<p>A few points to mention here: </p> <p>Firstly, your test <code>element.text is not None</code> always returns <code>True</code> if you parse your XML file as given above using <code>xml.etree.Elementree</code> since at the end of each node, there is a new line character, hence, the text in each supposedly not-having-text node always have <code>\n</code> character. An alternative is to use <code>lxml.etree.parse</code> with a <code>lxml.etree.XMLParser</code> that ignore the blank text as below. </p> <p>Secondly, it's not good to append to a tree while reading through it. The same reason for why this code will give infinite loop:</p> <pre><code>&gt;&gt;&gt; a = [1,2,3,4] &gt;&gt;&gt; for k in a: a.append(5) </code></pre> <p>You could see @Alex Martelli answer for this question here: <a href="http://stackoverflow.com/questions/1637807/modifying-list-while-iterating">Modifying list while iterating</a> regarding the issue.</p> <p>Hence, you should make a <em>buffer</em> XML tree and build it accordingly rather than modifying your tree while traversing it.</p> <pre><code>from xml.etree import ElementTree as et import pdb; from lxml import etree p = etree.XMLParser(remove_blank_text=True) path = 'test.xml' tr = et.parse(path, parser = p) root = tr.getroot() buffer = et.Element(root.tag); for node in root.getchildren(): bnode = et.Element(node.tag) for element in node.iter(): #pdb.set_trace() if (element.text is not None): bnode.append(element) #node.extend(element) buffer.append(bnode) et.dump(buffer) </code></pre> <p>Sample run and results:</p> <pre><code>Chip chip@ 01:01:53@ ~: python stackoverflow.py &lt;root&gt;&lt;node1&gt;&lt;name1&gt;text1&lt;/name1&gt;&lt;/node1&gt;&lt;node2&gt;&lt;name2&gt;text2&lt;/name2&gt;&lt;/node2&gt;&lt;/root&gt; </code></pre> <p>NOTE: you can always try to print a pretty XML tree using <code>lxml</code> package in python following tutorials here: <a href="http://stackoverflow.com/questions/749796/pretty-printing-xml-in-python">Pretty printing XML in Python</a> since the tree I printed out is rather horrible to read by naked eyes.</p>
1
2016-10-18T14:12:54Z
[ "python", "xml" ]
'QuerySet' object doesn't support item deletion Error
40,106,858
<p>I am trying to delete an Item in the QuerySet by Index. I am able to display the items of the QuerySet using <code>print q_set[code_id - 1]</code> but can not delete it using <code>del q_set[code_id - 1]</code>. I want to permanently delete the item and not filter excluding that item.</p> <p>I am getting this error: </p> <pre><code>TypeError at /lessons/customcode/5/delete 'QuerySet' object doesn't support item deletion </code></pre> <p>views.py</p> <pre><code>... def customcode_view(request): global q_set try: u = User.objects.get(username=request.user) except: return render(request,"login_required.html",{}) q_set = customcode.objects.filter(user=u) if request.method == "POST": form = CustomcodeForm(request.POST) if form.is_valid(): cc = form.save(commit=False) cc.user = u cc.save() return HttpResponseRedirect('#BOTTOM') else: form = CustomcodeForm() return render(request, "customcode.html" , {'q_set':q_set,'form':form,}) def deletecode(request,code_id): code_id = int(code_id) del q_set[code_id - 1] #this is the problem return redirect('customcode_view') ... </code></pre> <p>models.py</p> <pre><code>... class customcode(models.Model): user = models.ForeignKey(User) name = models.CharField(blank=False,max_length=250) sourcecode = models.TextField(blank=False) def __unicode__(self): return self.name ... </code></pre>
0
2016-10-18T11:20:48Z
40,107,130
<p>To <em>permanently</em> get rid of the entry, you don't want to remove the item from the queryset (which is just a volatile view onto your data), but <a href="https://docs.djangoproject.com/en/1.10/ref/models/instances/#deleting-objects" rel="nofollow">delete the row</a> from the database:</p> <pre><code>q_set[code_id - 1].delete() </code></pre> <p>Hth dtk</p>
4
2016-10-18T11:33:28Z
[ "python", "django" ]
How to plot one column in different graphs?
40,106,923
<p>I have the following problem. I have this kind of a dataframe:</p> <pre><code>f = pd.DataFrame([['Meyer', 2], ['Mueller', 4], ['Radisch', math.nan], ['Meyer', 2],['Pavlenko', math.nan]]) </code></pre> <p>is there an elegant way to split the DataFrame up in several dataframes by the first collumn? So, I would like to get a dataframe where first column = 'Müller' and another one for first column = Radisch. </p> <p>Thanks in advance,</p> <p>Erik</p>
1
2016-10-18T11:23:53Z
40,107,149
<p>You can loop by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.unique.html" rel="nofollow"><code>unique</code></a> values of column <code>A</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p> <pre><code>df = pd.DataFrame([['Meyer', 2], ['Mueller', 4], ['Radisch', np.nan], ['Meyer', 2], ['Pavlenko', np.nan]]) df.columns = list("AB") print (df) A B 0 Meyer 2.0 1 Mueller 4.0 2 Radisch NaN 3 Meyer 2.0 4 Pavlenko NaN print (df.A.unique()) ['Meyer' 'Mueller' 'Radisch' 'Pavlenko'] for x in df.A.unique(): print(df[df.A == x]) A B 0 Meyer 2.0 3 Meyer 2.0 A B 1 Mueller 4.0 A B 2 Radisch NaN A B 4 Pavlenko NaN </code></pre> <p>Then use <code>dict</code> comprehension - get <code>dictionary</code> of <code>DataFrames</code>:</p> <pre><code>dfs = {x:df[df.A == x].reset_index(drop=True) for x in df.A.unique()} print (dfs) {'Meyer': A B 0 Meyer 2.0 1 Meyer 2.0, 'Radisch': A B 0 Radisch NaN, 'Mueller': A B 0 Mueller 4.0, 'Pavlenko': A B 0 Pavlenko NaN} print (dfs.keys()) dict_keys(['Meyer', 'Radisch', 'Mueller', 'Pavlenko']) print (dfs['Meyer']) A B 0 Meyer 2.0 1 Meyer 2.0 print (dfs['Pavlenko']) A B 0 Pavlenko NaN </code></pre>
0
2016-10-18T11:34:19Z
[ "python", "pandas", "dataframe" ]
Calculate the equation given a string
40,106,976
<p>Given a random equation (with plus and multiply), calculate the result. </p> <p>For example, given, "5 + 3 * 4 * 2 + 1", return 30.</p> <p>This was a question I was given on a programming interview (a year ago) and was told to do it in at least 0(n) time. </p> <p>I attempted to do it in python. </p>
-1
2016-10-18T11:26:09Z
40,107,056
<p>Built-in function <code>eval()</code> <strong><em>not recommended</em></strong> as a go-to, but is rather quite helpful in this particular case:</p> <pre><code>string = "5 + 3 * 4 * 2 + 1" print (eval(string)) # 30 </code></pre> <p>Though there are quite an amount of side-effects and risks using <code>eval()</code>. So don't use quite often.<br> one quite useful way would be to extract the operators and the operands seperately and then do the desired arithmetic.</p> <pre><code>operands = [int(x) for x in string if x.isdigit()] # not using re as this is faster # [5, 3, 4, 2, 1] operators = re.findall(r"[^\d\s]", string) # ['+', '*', '*', '+'] </code></pre> <p>Now you can apply the operators to the two corresponding operands in a function maybe. <em>Just make sure to keep proper <strong>arithmetic convention</strong></em> (<code>*</code> should come before <code>+</code>)</p>
2
2016-10-18T11:29:24Z
[ "python", "math", "equation" ]
Calculate the equation given a string
40,106,976
<p>Given a random equation (with plus and multiply), calculate the result. </p> <p>For example, given, "5 + 3 * 4 * 2 + 1", return 30.</p> <p>This was a question I was given on a programming interview (a year ago) and was told to do it in at least 0(n) time. </p> <p>I attempted to do it in python. </p>
-1
2016-10-18T11:26:09Z
40,107,125
<p>You can write your expression in the form</p> <p><code>expression = term + term + ... + term</code></p> <p>and a term as</p> <p><code>term = value * value * ... * value</code></p> <p>This is an informal way of specifying the <em>grammar</em> for your expression. You ought to recognise that the evaluation of an expression of this form <strong>does not</strong> require a recursive descent parser which simplifies things greatly.</p> <p>An O(N) solution technique is then to evaluate each <code>term</code> from left to right; calling a function on each step that evaluates a particular <code>term</code>.</p>
0
2016-10-18T11:32:55Z
[ "python", "math", "equation" ]
Calculate the equation given a string
40,106,976
<p>Given a random equation (with plus and multiply), calculate the result. </p> <p>For example, given, "5 + 3 * 4 * 2 + 1", return 30.</p> <p>This was a question I was given on a programming interview (a year ago) and was told to do it in at least 0(n) time. </p> <p>I attempted to do it in python. </p>
-1
2016-10-18T11:26:09Z
40,107,396
<p>Another solution would be to convert your (infix) math expression to postfix, which is easy to evaluate using a stack. If you're interested here's a nice site describing the conversion as well as the evaluation/calcuation of a postfix-expression:</p> <p><a href="http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html" rel="nofollow">http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html</a></p> <p>Computational Complexity for converting infix to postfix and evaluating the expression would be about O(3*n) which in fact is still O(n).</p>
0
2016-10-18T11:46:39Z
[ "python", "math", "equation" ]
Calculate the equation given a string
40,106,976
<p>Given a random equation (with plus and multiply), calculate the result. </p> <p>For example, given, "5 + 3 * 4 * 2 + 1", return 30.</p> <p>This was a question I was given on a programming interview (a year ago) and was told to do it in at least 0(n) time. </p> <p>I attempted to do it in python. </p>
-1
2016-10-18T11:26:09Z
40,109,390
<p>Assuming you didn't want to use eval, you can try and do this inline. </p> <p>A good problem solving technique for this kind of question is to write out what you would want to happen. </p> <p>If you are looking at this item by item, you will notice that when we have addition, you can safely add all the previous results together. With multiplication we always have to wait for the next item. </p> <pre><code>def strToCal(strings): first = 0; second = 0; list1 = [] list1 = strings.split() mult = False for i in list1: if i == "+": first += second second = 0 mult = False elif i == "*": mult = True else: if mult: second *= int(i) else: second = int(i) return (first + second) print strToCal("5 * 34 * 75 * 2 + 1") </code></pre>
2
2016-10-18T13:17:20Z
[ "python", "math", "equation" ]
Changing Basemap projection causes beach balls / data to disappear (obspy)
40,107,244
<p>There's a very similar problem to my problem <a href="http://stackoverflow.com/questions/28776931/changing-basemap-projection-causes-data-to-disappear">here</a>, but the solution recommended on this page does not work in my case. For projection 'cyl', beach balls are plotted. Changing this projection to 'robin' (robinson) creates the projection without the data (beach balls). The recommendation for the other similar problem was to use:</p> <pre><code>x,y = map(lat, lon) </code></pre> <p>in order to convert the coordinates to the applicable projection but this is also included in my code (see below):</p> <pre><code>m = Basemap(projection='cyl', lon_0=0, resolution='c') m.drawmapboundary(fill_color='cornflowerblue') m.drawcountries() m.fillcontinents(color='white',lake_color='cornflowerblue', zorder=0) m.drawcoastlines() m.drawparallels(np.arange(-90.,120.,30.)) m.drawmeridians(np.arange(0.,420.,60.)) lats = [38.3215, -55.285, -56.241, -60.274] lons = [142.36929, -31.877, -26.935, -46.401] x, y = m(lons, lats) focmecs = [[193, 9, 78], [301, 62, 84], [101, 69, -56], [190, 89, -140]] eq_mw = [9.0, 7.4, 7.2, 7.7] ax = plt.gca() for i in range(len(focmecs)): # Loop to set the tensor (beach ball) colors eq = eq_mw[i] if eq &lt; 6: beachball_color = 'y' elif 6 &lt;= eq &lt; 8: beachball_color = 'orange' elif 8 &lt;= eq: beachball_color = 'r' b = beach(focmecs[i], facecolor=beachball_color, xy=(x[i], y[i]), width=10, linewidth=1, alpha=0.85) b.set_zorder(10) ax.add_collection(b) </code></pre>
0
2016-10-18T11:38:56Z
40,127,045
<p>The problem lies it seems with the projection and the axis or data coordinates transformation. When the width was changed from 10 to 1000000, then this resolves the issue:</p> <pre><code>b = beach(focmecs[i], facecolor=beachball_color, xy=(x[i], y[i]), width=1000000, linewidth=1, alpha=0.85) </code></pre>
0
2016-10-19T09:14:10Z
[ "python", "matplotlib-basemap" ]
pip install paramiko failed with error code 1
40,107,369
<p>While trying to install paramiko on my fedora I get the following error:</p> <pre><code>[mmorasch@michimorasch ~]$ sudo pip install paramiko Collecting paramiko Using cached paramiko-2.0.2-py2.py3-none-any.whl Requirement already satisfied (use --upgrade to upgrade): pyasn1&gt;=0.1.7 in /usr/lib/python2.7/site-packages (from paramiko) Collecting cryptography&gt;=1.1 (from paramiko) Using cached cryptography-1.5.2.tar.gz Requirement already satisfied (use --upgrade to upgrade): idna&gt;=2.0 in /usr/lib/python2.7/site-packages (from cryptography&gt;=1.1-&gt;paramiko) Requirement already satisfied (use --upgrade to upgrade): six&gt;=1.4.1 in /usr/lib/python2.7/site-packages (from cryptography&gt;=1.1-&gt;paramiko) Requirement already satisfied (use --upgrade to upgrade): setuptools&gt;=11.3 in /usr/lib/python2.7/site-packages (from cryptography&gt;=1.1-&gt;paramiko) Requirement already satisfied (use --upgrade to upgrade): enum34 in /usr/lib/python2.7/site-packages (from cryptography&gt;=1.1-&gt;paramiko) Requirement already satisfied (use --upgrade to upgrade): ipaddress in /usr/lib/python2.7/site-packages (from cryptography&gt;=1.1-&gt;paramiko) Requirement already satisfied (use --upgrade to upgrade): cffi&gt;=1.4.1 in /usr/lib64/python2.7/site-packages (from cryptography&gt;=1.1-&gt;paramiko) Requirement already satisfied (use --upgrade to upgrade): pycparser in /usr/lib/python2.7/site-packages (from cffi&gt;=1.4.1-&gt;cryptography&gt;=1.1-&gt;paramiko) Installing collected packages: cryptography, paramiko Running setup.py install for cryptography ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-kS98VZ/cryptography/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-c7TndX-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/cryptography copying src/cryptography/utils.py -&gt; build/lib.linux-x86_64-2.7/cryptography copying src/cryptography/fernet.py -&gt; build/lib.linux-x86_64-2.7/cryptography copying src/cryptography/exceptions.py -&gt; build/lib.linux-x86_64-2.7/cryptography copying src/cryptography/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography copying src/cryptography/__about__.py -&gt; build/lib.linux-x86_64-2.7/cryptography creating build/lib.linux-x86_64-2.7/cryptography/x509 copying src/cryptography/x509/oid.py -&gt; build/lib.linux-x86_64-2.7/cryptography/x509 copying src/cryptography/x509/name.py -&gt; build/lib.linux-x86_64-2.7/cryptography/x509 copying src/cryptography/x509/general_name.py -&gt; build/lib.linux-x86_64-2.7/cryptography/x509 copying src/cryptography/x509/extensions.py -&gt; build/lib.linux-x86_64-2.7/cryptography/x509 copying src/cryptography/x509/base.py -&gt; build/lib.linux-x86_64-2.7/cryptography/x509 copying src/cryptography/x509/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/x509 creating build/lib.linux-x86_64-2.7/cryptography/hazmat copying src/cryptography/hazmat/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat creating build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/serialization.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/padding.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/keywrap.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/hmac.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/hashes.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/constant_time.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/cmac.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives copying src/cryptography/hazmat/primitives/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives creating build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings copying src/cryptography/hazmat/bindings/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings creating build/lib.linux-x86_64-2.7/cryptography/hazmat/backends copying src/cryptography/hazmat/backends/multibackend.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends copying src/cryptography/hazmat/backends/interfaces.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends copying src/cryptography/hazmat/backends/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends creating build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/twofactor copying src/cryptography/hazmat/primitives/twofactor/utils.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/twofactor copying src/cryptography/hazmat/primitives/twofactor/totp.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/twofactor copying src/cryptography/hazmat/primitives/twofactor/hotp.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/twofactor copying src/cryptography/hazmat/primitives/twofactor/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/twofactor creating build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/x963kdf.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/pbkdf2.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/kbkdf.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/hkdf.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/concatkdf.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf copying src/cryptography/hazmat/primitives/kdf/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf creating build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/interfaces copying src/cryptography/hazmat/primitives/interfaces/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/interfaces creating build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/ciphers copying src/cryptography/hazmat/primitives/ciphers/modes.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/ciphers copying src/cryptography/hazmat/primitives/ciphers/base.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/ciphers copying src/cryptography/hazmat/primitives/ciphers/algorithms.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/ciphers copying src/cryptography/hazmat/primitives/ciphers/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/ciphers creating build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/utils.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/rsa.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/padding.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/ec.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/dsa.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/dh.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric copying src/cryptography/hazmat/primitives/asymmetric/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric creating build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings/openssl copying src/cryptography/hazmat/bindings/openssl/binding.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings/openssl copying src/cryptography/hazmat/bindings/openssl/_conditional.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings/openssl copying src/cryptography/hazmat/bindings/openssl/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings/openssl creating build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings/commoncrypto copying src/cryptography/hazmat/bindings/commoncrypto/binding.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings/commoncrypto copying src/cryptography/hazmat/bindings/commoncrypto/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings/commoncrypto creating build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/x509.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/utils.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/rsa.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/hmac.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/hashes.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/encode_asn1.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/ec.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/dsa.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/decode_asn1.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/cmac.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/ciphers.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/backend.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl copying src/cryptography/hazmat/backends/openssl/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl creating build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/commoncrypto copying src/cryptography/hazmat/backends/commoncrypto/hmac.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/commoncrypto copying src/cryptography/hazmat/backends/commoncrypto/hashes.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/commoncrypto copying src/cryptography/hazmat/backends/commoncrypto/ciphers.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/commoncrypto copying src/cryptography/hazmat/backends/commoncrypto/backend.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/commoncrypto copying src/cryptography/hazmat/backends/commoncrypto/__init__.py -&gt; build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/commoncrypto running egg_info writing requirements to src/cryptography.egg-info/requires.txt writing src/cryptography.egg-info/PKG-INFO writing top-level names to src/cryptography.egg-info/top_level.txt writing dependency_links to src/cryptography.egg-info/dependency_links.txt writing entry points to src/cryptography.egg-info/entry_points.txt warning: manifest_maker: standard file '-c' not found reading manifest file 'src/cryptography.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' no previously-included directories found matching 'docs/_build' warning: no previously-included files matching '*' found under directory 'vectors' writing manifest file 'src/cryptography.egg-info/SOURCES.txt' running build_ext generating cffi module 'build/temp.linux-x86_64-2.7/_padding.c' creating build/temp.linux-x86_64-2.7 generating cffi module 'build/temp.linux-x86_64-2.7/_constant_time.c' generating cffi module 'build/temp.linux-x86_64-2.7/_openssl.c' building '_openssl' extension creating build/temp.linux-x86_64-2.7/build creating build/temp.linux-x86_64-2.7/build/temp.linux-x86_64-2.7 gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/python2.7 -c build/temp.linux-x86_64-2.7/_openssl.c -o build/temp.linux-x86_64-2.7/build/temp.linux-x86_64-2.7/_openssl.o gcc: Fehler: /usr/lib/rpm/redhat/redhat-hardened-cc1: Datei oder Verzeichnis nicht gefunden error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-kS98VZ/cryptography/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-c7TndX-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-kS98VZ/cryptography/ </code></pre> <p>I see that the error is while compiling the cryptography setup, but I can't really find a way to solve this. After going through the forum I installed python3-devel and updated gcc, but it did not really help.</p> <p>Thanks in advance!</p>
0
2016-10-18T11:45:23Z
40,107,429
<p>Try</p> <pre><code>sudo dnf install redhat-rpm-config sudo yum install python-devel sudo yum install libevent-devel </code></pre> <p>and finally:</p> <pre><code>easy_install gevent </code></pre>
1
2016-10-18T11:48:36Z
[ "python", "fedora", "paramiko" ]
How to convert this Python code to R?
40,107,428
<p>,I need help with translating a python code into an R code.</p> <p>I have a data frame df, that contains the column IndicatorOfDefault and I would like too generate a column named indvalues.</p> <p>Example:</p> <pre><code>row number IndicatorOfDefault indvalues 823602 P 0 823603 P 0 823604 N1,N13, 8 823605 N1, 1 823606 P 0 823607 N1,N2,N3,N9,N10, 13 823608 P 0 </code></pre> <p>The code that I want to convert is the following:</p> <pre><code>df['indicators'] = df['IndicatorOfDefault'].str.split(',') Nvalues = {'' : -1, 'P' : 0, 'N1' : 1, 'N2' : 2, 'N11' : 3, 'N12' : 4, 'N3' : 5, 'N4' : 6, 'N6' : 7, 'N10' : 8, 'N13' : 9, 'N5' : 10, 'N7' : 11, 'N8': 12, 'N9' : 13} df['indvalues'] = df['indicators'].apply(lambda x: max([Nvalues.get(y,y) for y in x ])) </code></pre> <p>I would like to execute the same code in R, but I don't know how to write it in R. </p> <p>Can anyone help me please?</p> <p>Thanks in advance</p> <p>Why is this question off topic? I don't understand what's wrong... I am new to this site, so I would appreciate if someone could explain why this specific problem doesn't belong here? I've read what's written in the help center, but i still don't know what's wrong.</p> <p>I've managed to solve my problem in a different way. I get the result that I want - the most important indicator (it didn't needed to be a number necessary).</p> <pre><code> df$ind &lt;- "P" for(i in c(1, 2, 11, 12, 3, 4, 6, 10, 13, 5, 7, 8, 9)){ df &lt;- transform(df, ind = ifelse(grepl(as.character(paste0("N",i,",")),IndicatorOfDefault),as.character(paste0("N",i)),ind)) } </code></pre> <p>Example:</p> <pre><code>row number IndicatorOfDefault ind 823602 P P 823603 P P 823604 N1,N13, N13 823605 N1, N1 823606 P P 823607 N1,N2,N3,N9,N10, N9 823608 P P </code></pre>
-2
2016-10-18T11:48:21Z
40,114,085
<p>Since R does not have the dictionary object, the best translation will be a named list. Do note: R does not allow zero-length names, so <em>N0</em> is used. From there you can use R's <code>vapply()</code> and <code>strsplit()</code> to string split the column and find its corresponding max value. Specifically, <code>vapply()</code> as opposed to the standard <code>lapply()</code> is used to specify the output type as a numeric vector for dataframe column. </p> <p>Below includes both scripts to show exact <em>result</em> columns renders with posted data. </p> <p><strong>Python</strong></p> <pre class="lang-py prettyprint-override"><code>from io import StringIO import pandas as pd data = '''row number;IndicatorOfDefault;indvalues 823602;P;0 823603;P;0 823604;N1,N13,;8 823605;N1,;1 823606;P;0 823607;N1,N2,N3,N9,N10;13 823608;P;0''' df = pd.read_table(StringIO(data), sep=";") df['indicators'] = df['IndicatorOfDefault'].str.split(',') Nvalues = {'' : -1, 'P' : 0, 'N1' : 1, 'N2' : 2, 'N11' : 3, 'N12' : 4, 'N3' : 5, 'N4' : 6, 'N6' : 7, 'N10' : 8, 'N13' : 9, 'N5' : 10, 'N7' : 11, 'N8': 12, 'N9' : 13} df['result'] = df['indicators'].apply(lambda x: max([Nvalues.get(y,y) for y in x ])) print(df) # row number IndicatorOfDefault indvalues indicators result # 0 823602 P 0 [P] 0 # 1 823603 P 0 [P] 0 # 2 823604 N1,N13, 8 [N1, N13, ] 9 # 3 823605 N1, 1 [N1, ] 1 # 4 823606 P 0 [P] 0 # 5 823607 N1,N2,N3,N9,N10 13 [N1, N2, N3, N9, N10] 13 # 6 823608 P 0 [P] 0 </code></pre> <p><strong>R</strong></p> <pre class="lang-r prettyprint-override"><code>data = 'row number;IndicatorOfDefault;indvalues 823602;P;0 823603;P;0 823604;N1,N13,;8 823605;N1,;1 823606;P;0 823607;N1,N2,N3,N9,N10;13 823608;P;0' df = read.table(text=data, sep=";", header=TRUE, stringsAsFactors = FALSE) Nvalues = list(N0=-1, P=0, N1=1, N2=2, N11=3, N12=4, N3=5, N4=6, N6=7, N10=8, N13=9, N5=10, N7=11, N8=12, N9=13) df$indicators &lt;- lapply(df$IndicatorOfDefault, function(i) { as.character(strsplit(i, ",")[[1]]) }) df$result &lt;- vapply(df$indicators, function(i) { max(as.numeric(Nvalues[i])) }, numeric(1)) df # row.number IndicatorOfDefault indvalues indicators result # 1 823602 P 0 P 0 # 2 823603 P 0 P 0 # 3 823604 N1,N13, 8 N1, N13 9 # 4 823605 N1, 1 N1 1 # 5 823606 P 0 P 0 # 6 823607 N1,N2,N3,N9,N10 13 N1, N2, N3, N9, N10 13 # 7 823608 P 0 P 0 </code></pre>
0
2016-10-18T17:02:02Z
[ "python", "dataframe" ]
Python tkinter change variable label state and statusbar
40,107,452
<p>I do have a little problem here. It's about the exchange of variables of a label in TKinter. My program won't refresh the value's.</p> <pre><code>class Application(Frame): def __init__(self,parent,**kw): Frame.__init__(self,parent,**kw) self.x = None self.directory = None self.autostate = None self.state = "closed" self.GUI2() def state(self): #change states self.stateVar="open" self.statusbar = "Status: Opening gate..." #update tkinter self.group.update_idletasks() self.w.update_idletasks() def GUI2(self): self.statusbar = "Status:..." # menu left self.menu_left = tk.Frame(root, width=150, bg="red", bd=1, relief=RIDGE) self.menu_left_upper = tk.Frame(self.menu_left, width=300, height=900, bg="#C0C0C0") self.menu_left_lower = tk.Frame(self.menu_left, width=300, bd=1, relief=GROOVE) self.label1 = tk.Label(self.menu_left_lower, relief=FLAT, bg="blue" ) self.button1 = Button(self.menu_left_lower, text="RUN") self.test = tk.Label(self.menu_left_upper, text="info", bg="#C0C0C0") self.menu_left_upper.pack(side="top", fill="both", expand=TRUE) self.menu_left_lower.pack(side="top", fill="both", expand=FALSE) # right area self.some_title_frame = tk.Frame(root, bg="#dfdfdf", bd=1, relief=RIDGE) self.some_title = tk.Label(self.some_title_frame, text="some title", bg="#dfdfdf") self.text_area = Listbox(root, width=50, height=10, background="#ffffff", relief=GROOVE) #Label and Button self.group = LabelFrame(self.menu_left_upper, text="info", height=70) self.group.pack(side="top", fill="both", expand=TRUE) Button(self.menu_left_lower, text='Press', command=self.state).pack(side="bottom") self.w = Label(self.group, text='State='+self.stateVar) #text printed! self.w.pack(expand=TRUE) # status bar self.status_frame = tk.Frame(root) self.status = tk.Label(self.status_frame, text=self.statusbar, bd=1, relief=SUNKEN) #statusbar printed here self.status.pack(fill="both", expand=True) self.menu_left.grid(row=0, column=0, rowspan=2, sticky="nsew") self.status_frame.grid(row=2, column=0, columnspan=2, sticky="ew") root.grid_rowconfigure(1, weight=1) root.grid_columnconfigure(1, weight=1) #Starts the main loop and causes the class to interact with the init function if __name__ == '__main__': root = Tk() root.title("simulation") app = Application(root) app.grid() root.mainloop() </code></pre> <p>Here you can see the whole code.</p> <p>It's importend to check <strong># tab1</strong> in there will be the button. This button refers to the <strong>def state(self):</strong> This one needs to change the label and the statusbar. wich are packed in <strong>self.w</strong> and <strong>self.status</strong> in the program I added a <strong>#text printed!</strong> after the line.</p>
0
2016-10-18T11:49:43Z
40,108,270
<p>Below is an example program that should help you figure out how to change the text of labels. They key thing is creating a StringVar and pointing the label towards this so that the label is updated when the StringVar is.</p> <pre><code>from Tkinter import * class Application(Frame): def __init__(self,parent,**kw): Frame.__init__(self,parent,**kw) # Create a String variable to store our status string self.stateVar = StringVar() self.stateVar.set("Initial Value") # Create a label to display the status self.label1 = Label(textvariable=self.stateVar) self.label1.grid() # Create a button which will change the status self.button = Button(text="Press me", command=self.change) self.button.grid() def change(self): """Called when the button is pressed""" self.stateVar.set('You pressed the button') if __name__ == '__main__': root = Tk() root.title("simulation") app = Application(root) app.grid() root.mainloop() </code></pre>
0
2016-10-18T12:28:08Z
[ "python", "class", "tkinter" ]
Python tkinter change variable label state and statusbar
40,107,452
<p>I do have a little problem here. It's about the exchange of variables of a label in TKinter. My program won't refresh the value's.</p> <pre><code>class Application(Frame): def __init__(self,parent,**kw): Frame.__init__(self,parent,**kw) self.x = None self.directory = None self.autostate = None self.state = "closed" self.GUI2() def state(self): #change states self.stateVar="open" self.statusbar = "Status: Opening gate..." #update tkinter self.group.update_idletasks() self.w.update_idletasks() def GUI2(self): self.statusbar = "Status:..." # menu left self.menu_left = tk.Frame(root, width=150, bg="red", bd=1, relief=RIDGE) self.menu_left_upper = tk.Frame(self.menu_left, width=300, height=900, bg="#C0C0C0") self.menu_left_lower = tk.Frame(self.menu_left, width=300, bd=1, relief=GROOVE) self.label1 = tk.Label(self.menu_left_lower, relief=FLAT, bg="blue" ) self.button1 = Button(self.menu_left_lower, text="RUN") self.test = tk.Label(self.menu_left_upper, text="info", bg="#C0C0C0") self.menu_left_upper.pack(side="top", fill="both", expand=TRUE) self.menu_left_lower.pack(side="top", fill="both", expand=FALSE) # right area self.some_title_frame = tk.Frame(root, bg="#dfdfdf", bd=1, relief=RIDGE) self.some_title = tk.Label(self.some_title_frame, text="some title", bg="#dfdfdf") self.text_area = Listbox(root, width=50, height=10, background="#ffffff", relief=GROOVE) #Label and Button self.group = LabelFrame(self.menu_left_upper, text="info", height=70) self.group.pack(side="top", fill="both", expand=TRUE) Button(self.menu_left_lower, text='Press', command=self.state).pack(side="bottom") self.w = Label(self.group, text='State='+self.stateVar) #text printed! self.w.pack(expand=TRUE) # status bar self.status_frame = tk.Frame(root) self.status = tk.Label(self.status_frame, text=self.statusbar, bd=1, relief=SUNKEN) #statusbar printed here self.status.pack(fill="both", expand=True) self.menu_left.grid(row=0, column=0, rowspan=2, sticky="nsew") self.status_frame.grid(row=2, column=0, columnspan=2, sticky="ew") root.grid_rowconfigure(1, weight=1) root.grid_columnconfigure(1, weight=1) #Starts the main loop and causes the class to interact with the init function if __name__ == '__main__': root = Tk() root.title("simulation") app = Application(root) app.grid() root.mainloop() </code></pre> <p>Here you can see the whole code.</p> <p>It's importend to check <strong># tab1</strong> in there will be the button. This button refers to the <strong>def state(self):</strong> This one needs to change the label and the statusbar. wich are packed in <strong>self.w</strong> and <strong>self.status</strong> in the program I added a <strong>#text printed!</strong> after the line.</p>
0
2016-10-18T11:49:43Z
40,108,341
<p>The error is in the <code>Label</code> arguments: a tekst arguments is <em>not</em> updated if the input-variable is updated. You should assign the <code>stateVar</code> to the <code>Label</code>'s <code>textvariable</code> keyword argument and use no <code>text</code> argument.</p>
0
2016-10-18T12:31:34Z
[ "python", "class", "tkinter" ]
Indexing and slicing dataframe by date and time in python
40,107,591
<p>I have time a series datasets. I can select data from march to may by this code: </p> <pre><code>df[(df.index.month &gt;=3) &amp; (df.index.month&lt;=5)] </code></pre> <p>But the problem is how to select the data from <code>march-15</code> to <code>may-15</code>? Any help will be highly appreciated.</p> <p>and my dataframe looks like:</p> <pre><code>2000-02-25 0.01 2000-02-26 0.03 2000-02-27 1.0 2000-02-28 1.52 2000-02-29 0.23 2000-03-01 0.45 2000-03-05 2.15 2000-03-06 1.75 ................. ................. </code></pre>
1
2016-10-18T11:55:08Z
40,108,250
<p>You can use helper <code>Series</code> <code>s</code> where all years are replaced to same - e.g. <code>2000</code>:</p> <pre><code>print (df) A 2001-02-25 0.01 2002-02-26 0.03 2003-02-27 1.00 2004-02-28 1.52 2005-03-29 0.23 2006-03-01 0.45 2007-03-05 2.15 2008-03-06 1.75 s = pd.Series(df.index.map(lambda x: pd.datetime(2000, x.month, x.day))) mask = (s.dt.date &gt; pd.datetime(2000,3,15).date()) &amp; (s.dt.date &lt; pd.datetime(2000,5,15).date()) mask.index = df.index print (mask) 2001-02-25 False 2002-02-26 False 2003-02-27 False 2004-02-28 False 2005-03-29 True 2006-03-01 False 2007-03-05 False 2008-03-06 False dtype: bool df = df[mask] print (df) A 2005-03-29 0.23 </code></pre>
2
2016-10-18T12:26:45Z
[ "python", "pandas", "numpy", "dataframe" ]
Open file to read from web form
40,107,604
<p>I am working on a project where I have to upload a file from file storage (via web form) to MongoDB. In order to achieve this, I need to open the file in "rb" mode, then encode the file and finally upload to MongoDb. I am stuck when opening the file "rb" mode.</p> <pre><code> if form.validate(): for inFile in request.files.getlist("file"): connection = pymongo.MongoClient() db = connection.test uploads = db.uploads with open(inFile, "rb") as fin: f = fin.read() encoded = Binary(f,0) try: uploads.insert({"binFile": encoded}) check = True except Exception as e: self.errorList.append("Document upload is unsuccessful"+e) check = False </code></pre> <p>The above code is throwing <code>TypeError: coercing to Unicode: need string or buffer, FileStorage found</code> in the <code>open</code> step, i.e. this line:</p> <pre><code>with open(inFile, "rb") as fin: </code></pre> <p>Is there a way I can change my code to make it work? </p> <p>Thanks in advance</p>
1
2016-10-18T11:55:46Z
40,107,680
<p>The <code>FileStorage</code> object is already file-like so you can use as a file. You don't need to use <code>open</code> on it, just call <code>inFile.read()</code>.</p> <p>If this doesn't work for you for some reason, you can save the file to disk first using <code>inFile.save()</code> and open it from there.</p> <hr> <p>Reference: <a href="http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage" rel="nofollow">http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage</a></p>
0
2016-10-18T11:59:17Z
[ "python", "flask" ]
(possibly grouped) Row Values to Columns
40,107,657
<p>Let's say, after some groupby operation I have a dataframe like this:</p> <pre><code>data = pd.DataFrame(columns=['Key', 'Subkey', 'Value']) data.loc[0] = ['foo1', 'bar1', 20] data.loc[1] = ['foo1', 'bar2', 10] data.loc[2] = ['foo1', 'bar3', 5] data.loc[3] = ['foo2', 'bar1', 50] data.loc[4] = ['foo2', 'bar2', 100] data.loc[5] = ['foo2', 'bar3', 50] </code></pre> <p>What I then have is a dataframe that looks like this:</p> <pre><code>|Key |Subkey | Value | +----+-------+-------+ |foo1|bar1 |20 | |foo1|bar2 |10 | |foo1|bar3 |5 | |foo2|bar1 |50 | |foo2|bar2 |100 | |foo2|bar3 |50 | </code></pre> <p>What I would like to have is a new dataframe where the subkey is a new column, containing the same value as in the grouped frame above, like:</p> <pre><code>|Key |bar1 |bar2 |bar3 | +----+-----+------+------+ |foo1| 20 | 10 | 5 | |foo2| 50 | 100 | 50 | </code></pre> <p>Is there a one-line solution to this, or do I need to transform the dataframe programmatically?</p>
1
2016-10-18T11:58:19Z
40,107,752
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a>:</p> <pre><code>print (data.pivot(index='Key', columns='Subkey', values='Value')) Subkey bar1 bar2 bar3 Key foo1 20.0 10.0 5.0 foo2 50.0 100.0 50.0 </code></pre> <p>Then you can cast <code>float</code> values to <code>int</code>, <code>reset_index</code> and remove column names <code>Subkey</code>:</p> <pre><code>print (data.pivot(index='Key', columns='Subkey', values='Value') .astype(int) .reset_index() .rename_axis(None, axis=1)) Key bar1 bar2 bar3 0 foo1 20 10 5 1 foo2 50 100 50 </code></pre>
2
2016-10-18T12:02:30Z
[ "python", "pandas" ]
finding a special path string in HTML text in python
40,107,690
<p>I'm trying to extract a path in an HTML file that I read. In this case the path that I'm looking for is a logo from google's main site.</p> <p>I'm pretty sure that the regular expression I defined is right, but I guess I'm missing something.</p> <p>The code is:</p> <pre><code>import re import urllib a=urllib.urlopen ('https://www.google.co.il/') Text = a.read(250) print Text print '\n\n' b= re.search (r'\"\/[a-z0-9 ]*',Text) print format(b.group(0)) </code></pre> <p>The actual text that I want to get is:</p> <p><strong>/images/branding/googleg/1x/googleg_standard_color_128dp.png</strong></p> <p>I'd really appreciate it if someone could point me in the right direction</p>
2
2016-10-18T11:59:35Z
40,107,854
<p>this can help you:</p> <pre><code>re.search(r'\"\/.+\"',Text).group(0) </code></pre> <p>result:</p> <pre><code>&gt;&gt;&gt; re.search(r'\"\/.+\"',Text).group(0) '"/images/branding/googleg/1x/googleg_standard_color_128dp.png"' </code></pre>
0
2016-10-18T12:07:53Z
[ "python", "regex", "expression" ]