async def send_and_get_transaction(client, data, sender_pk): if not data.get('nonce'): data['nonce'] = await client.eth_getTransactionCount( get_address(sender_pk), 'pending') tx = MTransaction(**data) signed_tx = tx.sign(sender_pk) tx_id = await client.eth_sendRawTransaction(to_hex(signed_tx.raw)) print("Transaction hash: %s" % tx_id) assert tx_id == to_hex(signed_tx.hash), 'Hashes are not equal' tx_data = await client.eth_getTransactionByHash(tx_id) print("Transaction data:") pprint.pprint(tx_data) print("Waiting until mined..") tx_data = await get_tx_until_mined(client, tx_id) print("Transaction data mined:") pprint.pprint(tx_data) return tx_data
def __init__(self): self._private_key = os.urandom(32) # wallet import format # self._private_key_wif = utils.privatekey_to_wif(self._private_key) self._public_key = utils.privatekey_to_publickey(self._private_key) self._hash_public_key = utils.hash_public_key(self._public_key) self._address = utils.get_address(self._hash_public_key)
def manager_connect(): global worker_dict global manager try: manager = AccountManager(address=utils.get_address(), authkey=config.AUTHKEY) manager.connect() worker_dict = manager.worker_dict() except (FileNotFoundError, AttributeError): print('Unable to connect to manager for worker data.') worker_dict = {}
def process_message(self, message): try: txt = message.text.encode('utf-8') except: if hasattr(message, 'contact') and message.contact is not None: txt = message.contact.phone_number if hasattr(message, 'location') and message.location is not None: txt = get_address(message.location.latitude, message.location.longitude).encode('utf-8') if txt: self.send_message(txt) self.get_current_view().process_message(txt)
def get_data(): global bluetooth_address print(bluetooth_address) if bluetooth_address is None: while bluetooth_address is None: bluetooth_address = utils.get_address() return "We now find Server address!\n Wait for data!" else: res_list = utils.get_data(bluetooth_address) print(res_list) res_data = str(res_list[0][0]) + "\n" + str(res_list[1][0]) return res_data
def test_get_address(self): """Tests for `get_address` function.""" result = get_address(-1.81602098644987, 52.5487429714954) expected = { "place_id":"73626440", "licence":"Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright", "osm_type":"way", "osm_id":"90394420", "lat":"52.54877605", "lon":"-1.81627023283164", "display_name":"137, Pilkington Avenue, Castle Vale, Maney, Birmingham, West Midlands, England, B72 1LH, United Kingdom", "address":{ "house_number":"137", "road":"Pilkington Avenue", "suburb":"Castle Vale", "hamlet":"Maney", "city":"Birmingham", "state_district":"West Midlands", "state":"England", "postcode":"B72 1LH", "country":"United Kingdom", "country_code":"gb" } } self.assertEqual(result['place_id'], expected['place_id']) self.assertEqual(result['address']['house_number'], expected['address']['house_number']) self.assertEqual(result['licence'], expected['licence']) self.assertEqual(sorted(result.keys()), sorted(expected.keys())) result = get_address(-40, 40) expected = {'NoDataError': 'No data on this location'} self.assertEqual(result, expected) result = get_address(-40,40, service = 'kk') expected = {'URLError': 'Cannot connect to URL'} self.assertEqual(result, expected)
def get_context_data(self, **kwargs): context = super(NearbyOfficeView, self).get_context_data(**kwargs) lat = self.kwargs.get('lat', None) lon = self.kwargs.get('lon', None) limit = self.kwargs.get('limit', 25) if lat and lon: your_location = get_address(lat, lon) context['nearby_office_list'] = return_within_limit( lat, lon, limit) if context['nearby_office_list'] == []: context[ 'message_string'] = "There are no field offices within " + str( limit) + " miles of " + your_location + "." else: context['message_string'] = "Field offices within " + str( limit) + " miles of " + your_location + "." return context
def wiki(): if request.method == 'POST': address = get_address( request.form['inputlon'], request.form['inputlat'] ) if 'road' in address['address'].keys(): title = isolate_name(address['address']['road']) article = get_wiki_info(title) if isinstance(article, str): result = article else: result = parse_wiki_content(article) return render_template("wiki.html", result = result, address = address) elif 'pedestrian' in address['address'].keys(): title = isolate_name(address['address']['pedestrian']) article = get_wiki_info(title) if isinstance(article, str): result = article else: result = parse_wiki_content(article) return render_template("wiki.html", result = result, address = dict(address)) elif address['NoDataError']: return render_template("wiki.html", result = "<h2>:-(</h2>", address = dict(address)) elif address['UrlError']: return render_template("wiki.html", result = ("<h2>Parece que no " "podemos conectar a " "alguno de los servicios " "que usa la aplicación." "</h2>"), address = address) else: return render_template("wiki.html", result = ("<h2>No sabemos qué ha " "pasado. Lo sentimos en " "más profundo de nuestro " "frágil corazón</h2>"), address = address)
def dump_employees(filepath): with open(filepath, 'r') as input_csv: reader = csv.reader(input_csv) next(reader) for line in reader: Name = line[1] City = line[2] Cuisine_style = line[3] Ranking = line[4] Rating = line[5] Price_range = line[6] Number_of_reviews = line[7] Reviews = line[8] menu = line[9] menu_link = line[9] address = line[9] add_value(Name, City, Cuisine_style, Ranking, Rating, Price_range, Number_of_reviews, Reviews, menu, get_link(menu_link), get_address(address))
def __init__(self, name, context, request, return_type='wgs84', **kw): FormInput.__init__(self, name, **kw) self.context = context self.request = request self.return_type = return_type self.address = None # value # { # "latitude":12, # 纬度,浮点数,范围为90 ~ -90 # 'longitude':21, # 经度,浮点数,范围为180 ~ -180。 # 'speed':12, # 速度,以米/每秒计 # 'accuracy':1, # 位置精度 # } if self.value: if isinstance(self.value, basestring): self.value = json.loads(self.value) self.address = get_address(','.join(self.value['latitude'], self.value['longitude'])) self.upload_url = self.context.absolute_url(self.request) + "/@@get_location"
def connect_udp_tracker(info_hash, peer_id, length): announce = my_ordred_dict[b'announce'] host = announce.split(b'/')[2] name, port = host.split(b':') ip = socket.gethostbyname(name) request = utils.get_connect_request() response = get_response(ip, int(port), request) if response and len(response) >= 16: action, tr_id, con_id = struct.unpack('!IIQ', response) if tr_id != TRANSACTION_ID or action != 0: return request = utils.get_announce_request(con_id, info_hash, peer_id, length) response = get_response(ip, int(port), request) if response and len(response) >= 20: ip, port = utils.get_address(response) return (ip, port) else: return None
async def call_contract_method(client, ct, contract_address, method, args=None, *, sender_pk): if args is None: args = [] response = await client.eth_call(get_address(sender_pk), contract_address, data=to_hex( ct.encode_function_call(method, args))) try: result = ct.decode_function_result(method, response)[0] except IndexError: raise ValueError('Incorrect result for decoding') print("Method '%s' result: %s" % (method, result)) return result
def send_data(): global bluetooth_address if bluetooth_address is None: while bluetooth_address is None: bluetooth_address = utils.get_address() control = request.args.get('control') res = 0 if control == 'temp': command = request.args.get('command') actual_command = 0 if command == 'fahrenheit': actual_command = 1 res = utils.send_lcd(bluetooth_address, actual_command, '') if control == 'data': data = request.args.get('command') print(data) res = utils.send_lcd(bluetooth_address, 0, data) if control == 'led': data = request.args.get('command') list_data = data.split('|') res = utils.send_led(bluetooth_address, list_data) print(str(res)) return str(res)
def __init__(self): self._private_key = os.urandom(32) self._public_key = utils.privatekey_to_publickey(self._private_key) self._hash_public_key = utils.hash_public_key(self._public_key) self._address = utils.get_address(self._hash_public_key)
args = parse_args() logger = getLogger() if args.status_bar: configure_logger(filename='scan.log') logger.info('-' * 30) logger.info('Starting up!') else: configure_logger(filename=None) logger.setLevel(args.log_level) AccountManager.register('captcha_queue', callable=get_captchas) AccountManager.register('extra_queue', callable=get_extras) if config.MAP_WORKERS: AccountManager.register('worker_dict', callable=get_workers, proxytype=DictProxy) manager = AccountManager(address=get_address(), authkey=config.AUTHKEY) try: manager.start(mgr_init) except (OSError, EOFError) as e: address = get_address() if platform == 'win32' or not isinstance(address, str): raise OSError('Another instance is running with the same manager address. Stop that process or change your MANAGER_ADDRESS.') from e else: raise OSError('Another instance is running with the same socket. Stop that process or: rm {}'.format(address)) from e loop = asyncio.get_event_loop() loop.set_exception_handler(exception_handler) overseer = Overseer(status_bar=args.status_bar, manager=manager) overseer.start() overseer_thread = Thread(target=overseer.check, name='overseer', daemon=True)
page = open('temp{}.htm'.format(page_number), 'r', encoding='utf-8') #page = urllib.request.urlopen(req , proxy , timeout=5) #time.ctime(1) # page=urllib2.urlopen(url) soup = BeautifulSoup(page.read(), "html.parser") services = soup.find_all('li', {'class': 'cntanr'}) # Iterate through the 10 results in the page for service_html in services: # Parse HTML to fetch data name = ut.get_name(service_html) phone = ut.get_phone_number(service_html) #rating = get_rating(service_html) #count = get_rating_count(service_html) address = ut.get_address(service_html) #location = get_location(service_html) #data = [name, phone, address] # creating a csv writer object csvwriter.writerow([name, phone, address]) page.close() time.sleep(2) os.system("taskkill /im firefox.exe /f") os.remove("temp{}.htm".format(page_number)) page_number += 1 log_file.write('page{} process ended at: '.format(page_number) + time.ctime() + '\r\n') print('page{} process ended at: '.format(page_number) + time.ctime()) #page_number+=1 csvfile.close() os.chdir(path)
else: authkey = b'm3wtw0' if hasattr(config, 'HASH_KEY'): HASH_KEY = config.HASH_KEY else: HASH_KEY = None class AccountManager(BaseManager): pass AccountManager.register('captcha_queue') AccountManager.register('extra_queue') manager = AccountManager(address=get_address(), authkey=authkey) manager.connect() captcha_queue = manager.captcha_queue() extra_queue = manager.extra_queue() middle_lat = (config.MAP_START[0] + config.MAP_END[0]) / 2 middle_lon = (config.MAP_START[1] + config.MAP_END[1]) / 2 middle_alt = random_altitude() driver = webdriver.Chrome() driver.set_window_size(803, 807) while not captcha_queue.empty(): account = captcha_queue.get() username = account.get('username') location = account.get('location')
def all_places(user_id, location, distance): # get the current address street, city = utils.get_address(location) res = {'street': street, 'city': city, 'places': []} # get all user places user_places = user_traces_db.get_all_user_places(user_id, location, distance) for place in user_places: res['places'].append({ "name": place['name'], "venueid": place['venue_id'], "placeid": place['place_id'], "category": place['category'] if place['category'] else "", "city": place['city'], "score": place.get('sml', 1.0), "address": place['address'], "latitude": place['latitude'], "longitude": place['longitude'], "checkins": 0, "distance": place['distance'], "origin": "user", "emoji": place['emoji'], "icon": place['icon'] }) # filter the venue ids venue_ids = set(p['venueid'] for p in user_places if p['venueid'] != "") # get all foursquare places foursquare_places = foursquare.get_all_places_from_db(location, distance=250) for place in [ p for p in foursquare_places if p['venueid'] not in venue_ids ]: category = place['categories'][0] if len( place['categories']) > 0 else "" res['places'].append({ "name": place['name'], "venueid": place['venue_id'], "placeid": "", "category": category, "city": place['city'], "address": place['address'], "latitude": place['latitude'], "longitude": place['longitude'], "checkins": place['nb_checkins'], "distance": place['distance'], "origin": "foursquare" }) return res
def connectionLost(self, reason): if self == self.factory.master: self.factory.master = None else: self.factory.clients.remove(utils.get_address(self))
def generate_visits(S, user_id, day, pool): if not S: return visits = {} places = {} moves = {} pis = {} # Get the names of the other places prev_visit = None prev_place = None for stay in S: lat, lon, start, end, start_idx, end_idx, nb_steps, avg_speed, average_inter_distance, start_local, end_local = stay # populate the places place = { "longitude": lon, "latitude": lat, "ssid": '', "user_id": user_id, "user_entered": False, "osm_point_id": '', "osm_polygon_id": '' } location = {"lat": lat, "lon": lon} # check that there is at least two points nb_points = end_idx - start_idx if nb_points < 2: print("too little points") continue # check if the place is in the database user_places = user_traces_db.get_user_place(user_id, location, distance=250, limit=5) user_place = get_most_likely_place(user_id, start_local, end_local, user_places) if user_place: # there is a user place in the vicinity place_id = user_place['place_id'] place['place_id'] = place_id place['name'] = user_place['name'] place['category'] = user_place['category'] place['user_entered'] = user_place['user_entered'] place['longitude'] = user_place['longitude'] place['latitude'] = user_place['latitude'] place['city'] = user_place['city'] place['address'] = user_place['address'] place['type'] = 'place' place['color'] = user_place['color'] place['venue_id'] = user_place['venue_id'] place['emoji'] = user_place['emoji'] place['icon'] = user_place['icon'] place['category_id'] = user_place['category_id'] place['osm_point_id'] = '' place['osm_polygon_id'] = '' places[place_id] = place else: # place not in the database, getting the closest foursquare place fsq_places = foursquare.get_places(location, 200, 5) if fsq_places: result = fsq_places[0] # result is ordered by decreasing likelihood name = result['name'] address = result['location']['address'] city = result['location']['city'] place['name'] = name place['category'] = result['category'][0] place['longitude'] = result['location']['lon'] place['latitude'] = result['location']['lat'] place['city'] = city place['address'] = address place['venue_id'] = result['id'] place['type'] = 'place' place['color'] = utils.pick_place_color(place['name']) place['emoji'] = result['emoji'] place['icon'] = result['icon'] place['category_id'] = result['category_id'] else: # filter the place out if few number of steps and no places street_name, city = utils.get_address({"lat": lat, "lon": lon}) if not city or city == '': continue place['category'] = "User place" place['type'] = 'place' place['venue_id'] = '' place['city'] = city place['address'] = street_name place['longitude'] = lon place['latitude'] = lat place['name'] = "Place in %s" % city place['emoji'] = "🏠" place['icon'] = "home" place['color'] = utils.pick_place_color('home') # save the place in the database place_id = user_traces_db.save_user_place_to_db(place) place['place_id'] = place_id places[place_id] = place if prev_visit and prev_visit['place_id'] == place['place_id']: # aggregate with the previous visit visit = prev_visit visit['departure'] = end else: # create a new visit visit = { "place_id": place['place_id'], "arrival": start, "original_arrival": start, "departure": end, "confidence": 1.0, "latitude": lat, "longitude": lon, "day": day, "user_id": user_id, "arrival_utc_offset": start - start_local, "departure_utc_offset": end - end_local, "original_place_id": place['place_id'] } # save the previous visit to the database if prev_visit: # get_visits_at_place(prev_visit) visit_id = user_traces_db.save_user_visit_to_db(prev_visit) a_utc_offset = prev_visit['arrival_utc_offset'] d_utc_offset = prev_visit['arrival_utc_offset'] print("[%s -> %s] %s %s" % ( utils.hm(prev_visit['arrival'] - a_utc_offset), utils.hm(prev_visit['departure'] - d_utc_offset), prev_place['emoji'], prev_place['name'])) prev_visit['visit_id'] = visit_id visits[visit_id] = prev_visit # create a new move move = { "departure_date": prev_visit['departure'], "arrival_date": start, "activity": "Unknown", "activity_confidence": 1.0, "departure_place_id": prev_visit['place_id'], "arrival_place_id": visit['place_id'], "day": day, "user_id": user_id } # save the move to the database move_id = user_traces_db.save_user_move_to_db(move) moves[move_id] = move prev_visit = visit prev_place = place # add the last visit to the database # get_visits_at_place(prev_visit) if prev_visit: visit_id = user_traces_db.save_user_visit_to_db(prev_visit) a_utc_offset = prev_visit['arrival_utc_offset'] d_utc_offset = prev_visit['arrival_utc_offset'] print("[%s -> %s] %s %s" % ( utils.hm(prev_visit['arrival'] - a_utc_offset), utils.hm(prev_visit['departure'] - d_utc_offset), prev_place['emoji'], prev_place['name'])) prev_visit['visit_id'] = visit_id visits[visit_id] = prev_visit # detect home and work locations home_id, work_ids = determine_home_work_places(user_id) print("home id: %s, work id: %s" % (home_id, work_ids)) if home_id and home_id in places: print("\tHome: %s" % places[home_id]['name']) home_place = user_traces_db.load_user_place(user_id, home_id) if home_place['pt'] == 0: # default value - nothing user_traces_db.update_place_type(user_id, home_id, 1) # probably home if work_ids and len(work_ids) > 0: for work_id in work_ids: if work_id in places: print("\tWork: %s" % places[work_id]['name']) work_place = user_traces_db.load_user_place(user_id, work_id) if work_place['pt'] == 0: # default value - nothing user_traces_db.update_place_type(user_id, work_id, 3) # probably work # get the personal information for all the places visited place_ids = [p['place_id'] for p in places.values()] venue_ids = [places[p]['venue_id'] for p in place_ids] result = pool.map_async(personal_information.get_personal_information, venue_ids) result.wait() res_pi = result.get() for i in range(len(res_pi)): place_id = place_ids[i] for c, v in res_pi[i].items(): for pi in v: pi['user_id'] = user_id pi['place_id'] = place_id pi['category_id'] = c pi['source'] = list(pi['source']) pi_id = user_traces_db.save_user_personal_information_to_db(pi) pi['pi_id'] = pi_id pis[pi_id] = pi user_traces_db.create_or_update_aggregate_personal_information(user_id, pi, pi_id) print("Done processing {} personal information with {} places and {} visits".format(len(pis), len(venue_ids), len(visits)))
def connectionMade(self): if not self.factory.master: self.factory.master = self else: self.factory.clients[utils.get_address(self)] = self