def find(self, table, item, threshold): #takes in item to compare against and a threshold integer node.clear() head = node.custom("""SELECT * FROM %s WHERE distance = 0 """ % (table)) node.clear() if distance.getDistance(item, head[0]['NAME']) <= threshold: self.matches.append(head[0]['NAME']) # print head results = node.custom("""SELECT * FROM %s WHERE parent = '%s' AND distance >= %d AND distance <= %d """ % ( table, head[0]['NAME'], distance.getDistance(item, head[0]['NAME']) - threshold, distance.getDistance(item, head[0]['NAME']) + threshold ) ) # print results for record in results: # print record self.__find(table, record['NAME'], item, threshold) return self.matches
def getNewXY(pos1, pos2): x1 = float(pos1[0]) y1 = float(pos1[1]) x2 = float(pos2[0]) y2 = float(pos2[1]) if x2 - x1 == 0: if y1 >= y2: return (x1, y1 - 0.1) else: return (x1, y1 + 0.1) else: m = (y2 - y1) / (x2 - x1) c = y1 - m * x1 A = (m * m + 1) B = 2 * (m * c - m * y1 - x1) C = y1 * y1 - radius * radius + x1 * x1 - 2 * c * y1 + c * c temp = math.sqrt(B * B - 4 * A * C) nx1 = (-B + temp) / (2 * A) nx2 = (-B - temp) / (2 * A) ny1 = m * nx1 + c ny2 = m * nx2 + c dist1 = distance.getDistance({'x': x2, 'y': y2}, {'x': nx1, 'y': ny1}) dist2 = distance.getDistance({'x': x2, 'y': y2}, {'x': nx2, 'y': ny2}) if dist1 <= dist2: return (nx1, ny1) else: return (nx2, ny2)
def __addNode(table, root, item): node.clear() head = node.read(table, {'parent': root, 'distance': distance.getDistance(root, item)}) # print root if head: return __addNode(table, head[0]['NAME'], item) else: return node.create(table, {'name': item, 'parent': root, 'distance': distance.getDistance(root, item)})
def GuoTuAreaPoint(LatObject, LonObject, GuoTu_JSON): personNum = 0 monneyNum = 0 multidStr = '[' for guotu in GuoTu_JSON: LatOther = guotu['t11'] LonOther = guotu['t10'] LatOther = float(LatOther) LonOther = float(LonOther) dis = getDistance(LatObject, LonObject, LatOther, LonOther) if (dis < distance): tempid = str(guotu['id']) if (idList.count(tempid) == 0): idList.append(tempid) personNum += float(guotu['t13']) monneyNum += float(guotu['t14']) multidStr += '{"id":"' + str(guotu['id']) \ + '","name":"' + str(guotu['t1']) \ + '","t2":"' + str(guotu['t2']) \ + '","type":"' + str(guotu['t3']) \ + '","type2":"' + str(guotu['t4']) \ + '","t5":"' + str(guotu['t5']) \ + '","t6":"' + str(guotu['t6']) \ + '","address":"' + str(guotu['t7']) \ + '","person":"' + str(guotu['t8']) \ + '","tel":"' + str(guotu['t9']) \ + '","Lon":"' + str(guotu['t10']) \ + '","Lat":"' + str(guotu['t11']) \ + '","pNum":"' + str(guotu['t13']) \ + '","mNum":"' + str(guotu['t14']) \ + '"},' multidStr = multidStr.rstrip(',') + ']' result = '"Guott_id":{0},"personNum":{1},"monneyNum":{2}'.format( multidStr, personNum, monneyNum) return result
def calc(): error = None # for error returns # if there's some sort of input from the website if request.method == 'POST': # check if any of the necessary variables are uninitialized if request.form['starting-point'] != None and request.form[ 'destination'] != None and request.form['mpg'] != '0': # get the distance from the starting point to destination info = distance.getDistance(request.form['starting-point'], request.form['destination']) # make sure a valid distance was given before running calculations if info[2] == -1: return render_template('app.html', error=error) base_url = 'https://www.google.com/maps/dir/' url = base_url + info[0] + '/' + info[1] # calculate the necessary variables emission = emission_calc.co2calcprint(request.form['mpg'], info[2]) yearTravels = emission_calc.numTravelsInYear(emission) trees = emission_calc.numTrees(emission) homes = emission_calc.numPerHomePerYear(emission) # store the calculated data in a tuple and return it to the end html file data = (emission, homes, trees, yearTravels, url) return render_template('test.html', data=data) # return error if there was an issue with any of the inputted values return render_template('app.html', error=error)
def findRide(self, rides, step, STEP_COUNT): rides.sort(key=lambda r: getDistance(self.position, r.start_position)) for r in rides: timetodo = r.isDoable(rides, self, step, STEP_COUNT) if timetodo != -1: return self.assign(r, timetodo) return None
def space_cluster(df1, R_max): d = [] # save distance data # Get the latitude and longitude that meets the conditions def JD(k): # Define longitude a = df1[df1.序号 == k].经度 return a.tolist()[0] def WD(k): # Defining latitude b = df1[df1.序号 == k].纬度 # print(b) return b.tolist()[0] m, n = df1.shape print('m', 'n', m, n) # Computing space aggregation area for i in range(m): d.append([]) for j in range(m): # print(JD(i+1),WD(i+1),JD(j+1),WD(j+1)) d[i].append( distance.getDistance(JD(i + 1), WD(i + 1), JD(j + 1), WD(j + 1)) ) # Calculate the distance between the current location and another locations # print('i',i,','"d[i]",d ) #print(d) for k in range(m): # print(d[i][k]) if (d[i][k] <= R_max): c = {} c["center_xbid"] = i + 1 c["r"] = d[i][k] xbid = [] # save the array subscript #print('d[i][k]',d[i][k]) for v in range(m): # print(d[i][v]) #xbid = list(set(xbid)) if (d[i][k] >= d[i][v]): if (i != k): xbid.append(v + 1) else: xbid.append(i + 1) else: continue #if i == 170: # print('xbid-171', xbid) xbid = list(set(xbid)) c["xbids"] = xbid circle.append(c) # save form [{ }{ }{ }] else: continue # print(circle) # print('d', d) return circle
def results(): if request.method == "POST": name = request.form["form_name"] address = request.form["form_address"] treatment = request.form["form_treatment"] place = request.form["form_place"] sessions = request.form["form_sessions"] cost = request.form["form_costs"] mileage = calculateMileage(getDistance(address, place)) expense = calculateExpense(sessions, cost, getDistance(address, place)) data = Data(name, address, treatment, place, sessions, cost, mileage, expense) db.session.add(data) db.session.commit() createCsv(Data.query.all()) return render_template("results.html", result=expense)
def searchUsers(bookName, userId): pass con = sql.connect("templates/database.db") cur = con.cursor() bookId = getBookid(bookName) userAddress = cur.execute("SELECT address FROM users WHERE user_id = ? ", (userId, )).fetchall()[0][0] userCoordinates = coordinates.getCoordinates(userAddress) userCoordinates = ','.join(str(x) for x in userCoordinates) cur.execute("SELECT user_id FROM userBookList WHERE book_id=? ", (bookId, )) userIdList = cur.fetchall() if userIdList == []: return 'Sorry! No one around you seems to have this book :(' coordinateList = [] nameList = [] emailList = [] addressList = [] phoneList = [] for id in userIdList: id = id[0] cur.execute( "SELECT name, email, address, phone FROM users WHERE user_id = ? ", (id, )) x = cur.fetchall()[0] nameList.append(x[0]) emailList.append(x[1]) addressList.append(x[2]) phoneList.append(x[3]) coordinate = coordinates.getCoordinates(x[2]) if coordinate[1] != 'error': coordinate = ','.join(str(x) for x in coordinate) coordinateList.append(coordinate) else: coordinateList.append('error') coordinateList = '|'.join(coordinateList) distanceList = distance.getDistance(userCoordinates, coordinateList) ret = [] i = 0 for item in distanceList: ret.append({ 'distance': item['dist'], 'tim': item['tim'], 'name': nameList[i], 'email': emailList[i], 'phone': phoneList[i], 'address': addressList[i] }) i += 1 ret = sorted(ret, key=lambda k: k['distance']) return ret
def __find(self, table, root, item, threshold): if distance.getDistance(root, item) <= threshold: self.matches.append(root) node.clear() results = node.custom("""SELECT * FROM %s WHERE parent = '%s' AND distance >= %d AND distance <= %d """ % ( table, root, distance.getDistance(item, root) - threshold, distance.getDistance(item, root) + threshold ) ) # print results for record in results: self.__find(table, record['NAME'], item, threshold)
def getNearestMarket(here, markets): print here poss = [] for market in markets: poss.append(market['Position']) dists = distance.getDistance(here, poss) for i in range(len(markets)): markets[i]['Distance'] = dists[i][0] markets[i]['DistanceValue'] = dists[i][1] markets.sort(key=lambda student: student['DistanceValue']) print markets return markets[0]
def __del__(self): self.cap.release() cv2.destroyAllWindows() #this line would be replaced with gps #endLocation = geocoder.ip['me'] position = self.startLocation.latlng source = str(position[0]) + "," + str(position[1]) destpos = distance.getGeocode(random.choice(self.addresses)).json() dest = str(destpos['results'][0]['geometry']['location']['lat']) + "," + str(destpos['results'][0]['geometry']['location']['lng']) response = distance.getDistance(source, dest) #print(json.dumps(response.json(), indent=4, sort_keys=True)) dist = response.json()['rows'][0]['elements'][0]['distance']['value'] print("Traveling to: %s\n%s" % (response.json()['destination_addresses'][0], response.json()['rows'][0]['elements'][0]['distance']['text'])) r = requests.post(self.URL + "/users/" + self.user + "/addDrive/", data={'distTraveled': dist, 'eyeRatio':format(self.runningResult/self.runningTotal, '.2f'), 'timeSpent':int(time.time() - self.begin)}) r = requests.post(self.URL + "/users/" + self.user + "/", data={'driving': False})
def GuoTuAreaPoint(LatObject, LonObject, distance): person = 0 monney = 0 result = 0 idStr = '' for guotu in guotu_json: LatOther = guotu['t11'] LonOther = guotu['t10'] LatOther = float(LatOther) LonOther = float(LonOther) dis = getDistance(LatObject, LonObject, LatOther, LonOther) if (dis < distance): person += float(guotu['t13']) monney += float(guotu['t14']) idStr += str(guotu['id']) + ',' idStr = idStr.rstrip(',') if (not person.__eq__(0) and not monney.__eq__(0)): result = '"Guott002_id":"{0}","person":{1},"monney":{2}'.format(idStr, person, monney) return result
def __cleanPlaces__(places, city, start): [parks, parks_max] = [0, 3] [rests, rests_max] = [0, 3] locs = [] new_places = [] for place in places: cont = True for loc in locs: if (d.getDistance(loc[0], loc[1], place.lat, place.lon) < 120): cont = False break if (cont): if (place.isPark() and parks < parks_max): new_places.append(place) locs.append([place.lat, place.lon]) parks += 1 elif (place.isRestaurant() and rests < rests_max): new_places.append(place) locs.append([place.lat, place.lon]) rests += 1 elif (not place.isPark() and not place.isRestaurant()): new_places.append(place) locs.append([place.lat, place.lon]) print("Acceptable Locations: " + str(len(new_places))) print() places = new_places[:min(20, len(new_places))] sortPlaces_rating(places) return places
def isBad(self): if (d.getDistance(self.city_coords[0], self.city_coords[1], self.lat, self.lon) > 72000): return True if (self.rating < 3 or self.reviews < 25): return True return len(list(set(bad) & set(self.types))) > 0
def back(): GPIO.output(pin1a, False) GPIO.output(pin1b, True) def stop(): GPIO.output(pin1a, True) GPIO.output(pin1b, True) from distance import getDistance import time currentD = 0 while True: dis = getDistance() print "******Distance = ", dis time.sleep(1) if dis > 20: front() elif dis > 10: back() elif dis > 0: stop() """ while True: cmd = raw_input("f: forward, b: back, s: stop, e: exit! \n") print(cmd) if cmd == 'f':
def FindBestPerson(self, req): persons = boys.find() if persons.count() == 0: return None best_dist = math.inf best_pos = 0 best_person = None for person in persons: total_dist_old = person['total_distance'] old_x = 0 old_y = 0 if len(person['handled_reqs']) != 0: old_x = person['handled_reqs'][-1]['x'] else: old_x = person['curr_x'] if len(person['handled_reqs']) != 0: old_y = person['handled_reqs'][-1]['y'] else: old_y = person['curr_y'] if len(person['handled_reqs']) > 0: distance_to_workshop = distance.getDistance( workshop, { 'x': person['handled_reqs'][-1]['x'], 'y': person['handled_reqs'][-1]['y'] }) else: distance_to_workshop = distance.getDistance( workshop, { 'x': person['curr_x'], 'y': person['curr_y'] }) pos = 0 old_x = 0 old_y = 0 min_distance = math.inf if len(person['unhandled_reqs']) == 0: #min_distance = 0 pass else: distance_to_workshop = 0 for i, r in enumerate(person['unhandled_reqs']): if min_distance >= (distance.getDistance( req, r) + distance.getDistance(req, { 'x': old_x, 'y': old_y })): min_distance = ( distance.getDistance(req, r) + distance.getDistance(req, { 'x': old_x, 'y': old_y })) pos = i old_x = r['x'] old_y = r['y'] if min_distance >= (distance.getDistance(req, { 'x': old_x, 'y': old_y })): min_distance = (distance.getDistance(req, { 'x': old_x, 'y': old_y })) if old_x == 0.0 and old_y == 0.0: pos = 0 else: pos = len(person['unhandled_reqs']) - 1 if (min_distance + total_dist_old + distance_to_workshop) < best_dist: best_dist = (min_distance + total_dist_old + distance_to_workshop) best_pos = pos best_person = person['id'] return { 'best_dist': best_dist, 'best_pos': best_pos, 'best_person': best_person }
def NewPerson(self, req): dist = distance.getDistance(req, workshop) return dist
def updateBoys(): result = boys.find() print(result.count()) new_x = 0 new_y = 0 for p in result: if p['curr_x'] == 0.0 and p['curr_y'] == 0.0: for un_req in p['unhandled_reqs']: p['handled_reqs'].append(un_req) ## changeeeeee boys.update_one({'id': p['id']}, { '$set': { 'handled_reqs': p['handled_reqs'], 'unhandled_reqs': [] } }) if len(p['handled_reqs']) > 0: new_x, new_y = getNewXY( (p['curr_x'], p['curr_y']), (p['handled_reqs'][0]['x'], p['handled_reqs'][0]['y'])) else: new_x, new_y = getNewXY((p['curr_x'], p['curr_y']), (workshop['x'], workshop['y'])) elif len(p['handled_reqs']) > 0 and p['curr_x'] == p['handled_reqs'][ 0]['x'] and p['curr_y'] == p['handled_reqs'][0]['y']: p['handled_reqs'].pop(0) boys.update_one({'id': p['id']}, {'$set': { 'handled_reqs': p['handled_reqs'] }}) if len(p['handled_reqs']) > 0: new_x, new_y = getNewXY( (p['curr_x'], p['curr_y']), (p['handled_reqs'][0]['x'], p['handled_reqs'][0]['y'])) else: new_x, new_y = getNewXY((p['curr_x'], p['curr_y']), (workshop['x'], workshop['y'])) else: if len(p['handled_reqs']) > 0: if distance.getDistance({ 'x': p['curr_x'], 'y': p['curr_y'] }, { 'x': p['handled_reqs'][0]['x'], 'y': p['handled_reqs'][0]['y'] }) <= radius: new_x = p['handled_reqs'][0]['x'] new_y = p['handled_reqs'][0]['y'] else: new_x, new_y = getNewXY( (p['curr_x'], p['curr_y']), (p['handled_reqs'][0]['x'], p['handled_reqs'][0]['y'])) else: if distance.getDistance({ 'x': p['curr_x'], 'y': p['curr_y'] }, { 'x': workshop['x'], 'y': workshop['y'] }) <= radius: new_x = workshop['x'] new_y = workshop['y'] else: new_x, new_y = getNewXY((p['curr_x'], p['curr_y']), (workshop['x'], workshop['y'])) ## changeeee boys.update_one({'id': p['id']}, {'$set': { 'curr_x': new_x, 'curr_y': new_y }})
searchedTuits = findInRadius(searchedFeature, tuits['tuits'], radioFind) #print len(searchedTuits) buildMap(searchedFeature, searchedTuits, radioFind) ##### SEGUNDA TAREA print 'Analysis...' analysis = {} analysis['analysis'] = [] maxDistance = float(raw_input('Dame una distancia m?xima : ')) for monum in allFeatures: lon, lat = monum['geometry']['coordinates'] mo = {} mo['idnotes'] = monum['properties']['idnotes'] mo['num_tweets'] = len([ tuit for tuit in tuits['tuits'] if getDistance(lon, lat, **tuit['coordenadas']) <= maxDistance ]) analysis['analysis'].append(mo) print analysis ## TERCERA TAREA wordHashtag = raw_input('Introduce un hashtag') tuitsWithHashtag = [ tuit for tuit in tuits['tuits'] if wordHashtag in tuit['hashtags'] ] lons = [tuit['coordenadas']['longitud'] for tuit in tuitsWithHashtag] lats = [tuit['coordenadas']['latitud'] for tuit in tuitsWithHashtag] lon = reduce(lambda a, b: a + b, lons) / len(lons) lat = reduce(lambda a, b: a + b, lats) / len(lats) mymap2 = pygmaps.maps(lat, lon, 16)
def findInRadius(monumento, tuits, radius): lon, lat = monumento['geometry']['coordinates'] return [ tuit for tuit in tuits if getDistance(lon, lat, **tuit['coordenadas']) <= radius ]