Пример #1
0
 def __healthCheck(self, interval = 300, daemon = False):
     while True:
         utility.sleep(interval, True)
         for key in self.device_list:
             if key is 'SELF': next
             ## if self.device_list[key]['STATUS'] is 'UNREACHABLE': next # Skip the unreachable devices
             else:
                 try:
                     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                     s.settimeout(2)
                     s.sendto('PING!'.encode('utf-8'), (self.device_list[key]['IP'], self.device_list[key]['PORT'] + 1))
                     message = s.recvfrom(self.buffer_size)
                     s.settimeout(None)
                     if message[0].decode('utf-8') != 'PONG!':
                         utility.warn("Health check device at [" + self.device_list[key]['IP'] + ":" + str(self.device_list[key]['PORT']) + "] not responding correctly! Mark device [" + key+ "] UNKNOWN" , False)
                         self.device_list[key]['STATUS'] = 'UNKNOWN'
                     else:
                         self.device_list[key]['STATUS'] = 'REACHABLE'
                 except Exception as e:
                     if key in self.device_list and self.device_list[key]['STATUS'] == 'REACHABLE':
                         utility.warn("Health check device at [" + self.device_list[key]['IP'] + "] failed! Mark device [" + key + "] UNREACHABLE" , False)
                         self.device_list[key]['STATUS'] = 'UNREACHABLE'
                 finally:
                     s.close()
         if not daemon:
             utility.info("        Health Check Result:\n--------------------------------------------------------------------------------")
             for device in self.device_list:
                 print(self.device_list[device]['STATUS'] + '    ' + self.device_list[device]['HOST'] + ': [' + self.device_list[device]['IP'] + ']')
Пример #2
0
 def __callback(self, ip, port, message = '', daemon = False):
     try:
         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
         if not daemon: utility.info("Responding to [" + ip + ":" + str(port) + "]")
         s.sendto(str(message).encode('utf-8'), (ip, port))
     except Exception as e:
         utility.warn(str(e) + "\n>>> Continue ...")
Пример #3
0
def connectSSH(commands,
               host="10.155.208.121",
               username="******",
               password="******",
               daemon=False):
    result = True
    if not daemon: utility.info("...SSH Connect to " + host)
    sshClient = pexpect.spawn('ssh -o StrictHostKeyChecking=no ' + username +
                              '@' + host)
    sshClient.expect("Password: "******":.*")
    sshClient.sendline("qrb_command_mode")
    sshClient.expect("#")
    if not daemon:
        if "Entered Into QRB Command Mode" in sshClient.before.decode('utf-8'):
            utility.info("Entered Into QRB Command Mode")
    for command in commands:
        sshClient.sendline(command)
        sshClient.expect("#")
        if not daemon:
            if "S\r" in sshClient.before.decode('utf-8'):
                utility.info('Command [' + command +
                             '] execution successful on host [' + host + ']')
            else:
                utility.warn('Command [' + command +
                             '] execution FAIL on host [' + host + ']',
                             track=False)
                result = False
    sshClient.sendline("exit")
    utility.sleep(1, daemon=True)
    sshClient.sendline("exit")
    return result
Пример #4
0
    def forever(self, interval_seconds = 1, cb_interval_func = None, func_data = None):
        counter = 0

        interval = interval_seconds * 10

        while not self.is_stop():
            time.sleep(0.1)

            counter += 1

            if counter == interval:
                counter = 0

                if cb_interval_func:
                    try:
                        cb_interval_func(func_data)
                    except:
                        util.except_print("cb_interval_func")
                        pass
                pass

        # block wait child processes exit
        for pname in self.workers.keys():
            self.workers[pname].join()
            util.warn("{}: worker stopped.".format(pname))

        with self.glock:
            util.remove_file_nothrow(self.pidfile)
            util.remove_file_nothrow(self.stopfile)
        pass
Пример #5
0
 def getDevice(self, name = 'SELF', daemon = False):
     if name in self.device_list:
         if not daemon:
             utility.info("Getting device " + name + " from devices list\n----------------------------------------------")
             utility.pp(self.device_list[name])
         return self.device_list[name]
     else:
         utility.warn("Device [" + str(name) + "] NOT found, return SELF", False)
         return self.device_list['SELF']
Пример #6
0
 def __execute_command(self, command, message, daemon = False):
     ## Removed timeout
     try:
         result = subprocess.check_output(command, shell = True).decode('utf-8')
         if not daemon: print (result)
         self.__callback(message[1][0], message[1][1], result, daemon)
     except Exception as e:
         utility.warn(str(e) + "\n>>> Continue", True)
         self.__callback(message[1][0], message[1][1], str(e), daemon)
Пример #7
0
 def healthCheck(self):
     result = self.getMXAResult()
     utility.pp(result)
     if float(result['EVM']) > 100.0:
         if not self.MY_DAEMON:
             utility.warn("EVM value " + result['EVM'] +
                          " is greater than 100.0!",
                          track=False)
         return False
     else:
         return True
Пример #8
0
 def __broadcast(self, delay = 1, daemon = False):
     try:
         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
         s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
         if not daemon: utility.info("Starting broadcasting at: [" + self.this_device['BROADCAST_IP'] + ":" + str(self.this_device['PORT']) + "]")
         while True:
             self.__loadConfig(self.this_device['PORT'])
             s.sendto(str(self.this_device).encode('utf-8'), (self.this_device['BROADCAST_IP'], int(self.this_device['PORT'])))
             utility.sleep(delay, True)
     except Exception as e:
         utility.warn(str(e) + "\n>>> Continue ...")
     finally:
         s.close()
Пример #9
0
 def loadSQLite(self, jfw_id, table_name=None, db_path=None):
     try:
         if table_name:
             config = sql.getSQLite(
                 'SELECT * FROM ' + str(table_name) + ' WHERE id=' +
                 str(jfw_id), db_path)[0]
         else:
             config = sql.getSQLite(
                 'SELECT * FROM ' + self.MY_JFW_TABLE_NAME + ' WHERE id=' +
                 str(jfw_id), db_path)[0]
     except Exception as e:
         utility.warn("JFW loadSQLite failed: " + str(e), track=False)
         config = {"error": str(e)}
     return self.__loadConfig(json=config)
Пример #10
0
 def execute(self, device, command, timeout = 20, daemon = False):
     try:
         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
         s.settimeout(timeout)
         if not daemon: utility.info("Sending command: [" + str(command) + "] to " + device['IP'] + ":" + str(device['PORT'] + 1))
         s.sendto(str(command).encode('utf-8') ,(device['IP'], device['PORT'] + 1))
         response = s.recvfrom(self.buffer_size)
         s.settimeout(None)
         if response: utility.info("Response from [" + response[1][0] + ":" + str(response[1][1]) + "]\n" + response[0].decode('utf-8'))
     except Exception as e:
         utility.warn(str(e) + "\n>>> Continue ...")
     finally:
         s.close()
         return response[0].decode('utf-8')
Пример #11
0
 def __get_host(self, port = 8888):
     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     try:
         s.connect(('10.255.255.255', 1))
         IP = s.getsockname()[0]
         if 'IP' in self.this_device and IP != self.this_device['IP']:
             utility.warn('*** IP Change Detected! ***\n    Old IP: ' + self.this_device['IP'] + '\n    New IP: ' + IP, False)
     except Exception as e:
         utility.warn(str(e) + "\n    Setting IP to 127.0.0.1", False)
         IP = '127.0.0.1'
     finally:
         self.this_device['HOST'] = socket.gethostname()
         self.this_device['IP'] = IP
         self.this_device['PORT'] = port
         self.this_device['BROADCAST_IP'] = utility.regexParser(IP, '(.*)\.[0-9]{1,3}', True) + '.255'
         self.this_device['STATUS'] = 'REACHABLE'
         self.device_list['SELF'] = self.this_device
         s.close()
Пример #12
0
    def notify_stop(self, exitCode = 0):
        try:
            self.lock()

            if not util.file_exists(self.stopfile):
                os.mknod(self.stopfile)
            else:
                util.warn("stopfile already exists: " + self.stopfile)
        except:
            util.except_print("notify_stop")
        finally:
            try:
                self.unlock()
            except:
                util.except_print("unlock")
                pass

        if not exitCode is None:
            sys.exit(exitCode)
        pass
Пример #13
0
 def __discover(self, delay = 1, daemon = False):
     while True:
         try:
             s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
             s.bind(('', self.this_device['PORT']))
             while True:
                 message = utility.strToDict(s.recvfrom(self.buffer_size)[0].decode('utf-8'))
                 if message and message['HOST'] != self.this_device['HOST']:
                     if message['HOST'] not in self.device_list or (message['HOST'] in self.device_list and self.device_list[message['HOST']]['STATUS'] != 'REACHABLE'):
                         self.device_list[message['HOST']] = message
                         try:
                             hs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                             hs.settimeout(2)
                             hs.sendto('PING!'.encode('utf-8'), (message['IP'], message['PORT'] + 1))
                             return_message = hs.recvfrom(self.buffer_size)
                             hs.settimeout(None)
                             if return_message[0].decode('utf-8') != 'PONG!':
                                 utility.warn("Handshake with device at [" + message['IP'] + ":" + str(message['PORT']) + "] Failed! Mark device [" + message['HOST'] + "] UNKNOWN" , False)
                                 self.device_list[message['HOST']]['STATUS'] = 'UNKNOWN'
                             else:
                                 self.device_list[message['HOST']]['STATUS'] = 'REACHABLE'
                                 if not daemon: utility.info("Discovered device [" + message['HOST'] + "] at [" + message['IP'] + "]")
                         except Exception as e:
                             if not daemon: utility.warn("Handshake with device at [" + message['IP'] + ":" + str(message['PORT']) + "] Failed! Mark device [" + message['HOST'] + "] UNREACHABLE" , False)
                             self.device_list[message['HOST']]['STATUS'] = 'UNREACHABLE'
                         finally:
                             hs.close()
                         break
             utility.sleep(delay, True)
         except Exception as e:
             utility.warn(str(e) + "\n>>> Continue ...")
         finally:
             s.close()
Пример #14
0
 def __execution(self, daemon = False):
     try:
         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
         s.bind((self.this_device['IP'], self.this_device['PORT'] + 1))
         while True:
             message = s.recvfrom(self.buffer_size)
             command = message[0].decode('utf-8')
             ## TODO TODO TODO start building command here !!!!!!!!!!!!
             if command == 'PING!':
                 no_print = True     ## set no_print to False to print health check message
                 if not no_print: utility.info("Receive health check package from [" + str(message[1][0]) + ":" + str(message[1][1]) + "]")
                 self.__callback(message[1][0], message[1][1], 'PONG!', no_print)
             elif command:
                 if not daemon: utility.info("Receive command from [" + str(message[1][0]) + ":" + str(message[1][1]) + "]")
                 if not daemon: utility.info("Executing command: [" + command + "]\n----------------------- Result ------------------------")
                 execute_thread = threading.Thread(target = self.__execute_command, args = (command, message, daemon))
                 execute_thread.daemon = True
                 execute_thread.start()
     except Exception as e:
         utility.warn(str(e) + "\n>>> Continue ...")
     finally:
         s.close()
Пример #15
0
def get_strava_description_items():
    """
    Returns all items with strava.descriptions. The key will be a short cut without 'strava.description' prefix.
    :return: Dictionary with config items with shortcut keys, can be empty. For instance:
            [
                {
                    'condition_field': 'strava_name',
                    'condition_value': 'die runden stunde',
                    'text': 'ttt',
                },
                {
                    'condition_field': 'training_type',
                    'condition_value': 'Etappe',
                    'text': 'bbbb',
                }
            ]

    """
    ret = []
    # for item in read_config().items():

    for (key, value) in [i for i in read_config().items() if i[0].startswith(key_strava_description_prefix)]:
        # print(f"{key} --> {value}")
        parts = value.split("?")

        # Should never hit in production
        if len(parts) != 2:
            warn(f"Invalid config value '{value}' for key '{key}': Missing '?'")
            continue

        ret.append(
            dict(condition_field=key.replace(key_strava_description_prefix,""),
                 condition_value=parts[0],
                 text=parts[1],)
        )

    # print(ret)
    return ret
def geocode_intersection(street1, street2, borocode, precinct):
    """
    Make external call to NYC's geocoder to get intersection.  If Geoclient
    can't do it, falls back on Google, but still returns Geoclient's error
    message.
    """

    # Basic response object, borrowing Geoclient's terminology
    resp = {
        u'streetName1In': street1,
        u'streetName2In': street2,
        u'boroughCode1In': borocode,
        u'source_precinct': precinct
    }

    if NYC_GEOCODER:
        borough = ['manhattan', 'bronx', 'brooklyn', 'queens',
                   'staten island'][int(borocode) - 1]
        resp = NYC_GEOCODER.intersection(street1, street2, borough)

        if u'latitude' not in resp or u'longitude' not in resp:
            warn(u"Could not use NYC geocoder: {0}".format(resp[u'message']))
        else:
            if int(precinct) != int(resp.get('policePrecinct')):
                warn(u"Precinct mismatch: {0} vs. {1}".format(
                    precinct, resp.get(u'policePrecinct')))

        # Successful geocode via NYC
        if u'message' not in resp:
            return resp

    if GOOGLE_GEOCODER:
        try:
            boro_name = BORO_NUM_TO_NAME[str(borocode)]

            warn(u"Falling back to google to geocode {0} and {1}, {2}".format(
                street1, street2, boro_name))
            # kwarg `exactly_one=False` will return a list of possibilities,
            # but experience shows that these options are all bad.

            google_resp = GOOGLE_GEOCODER.geocode(u"{0} and {1}, {2}, NY".format(
                street1, street2, BORO_NUM_TO_NAME[str(borocode)]))

            # Double check zip code to make sure it's in the city
            try:
                confirmed_borough = False
                confirmed_zip = False
                found_zip = None

                for comp in google_resp.data[0][u'address_components']:
                    if comp[u'long_name'].lower() == boro_name.lower():
                        confirmed_borough = True
                    if u'postal_code' in comp[u'types']:
                        found_zip = comp[u'long_name']
                        zip_borough = ZIPS.get(found_zip)
                        confirmed_zip = zip_borough.lower() == boro_name.lower()

                resp.update({
                    u'googleLongitude': unicode(google_resp.longitude),
                    u'googleLatitude': unicode(google_resp.latitude)
                })

                if confirmed_zip and confirmed_borough:
                    resp.update({
                        u'longitude': unicode(google_resp.longitude),
                        u'latitude': unicode(google_resp.latitude)
                    })
                else:

                    resp[u'googleMessage'] = u"Could not confirm Google's geocoding: {0}".format(
                        {'confirmed_borough': confirmed_borough,
                         'confirmed_zip': confirmed_zip})
                    if found_zip:
                        resp[u'googleMessage'] += \
                                u", Google found zip {0}, but that is not in {1}".format(
                                    found_zip, boro_name)

                    warn(resp[u'googleMessage'])

            except Exception as e:
                resp[u'googleMessage'] = u"Error confirming Google's geocoding: {0}".format(e)
                warn(resp[u'googleMessage'])

            time.sleep(4)

        except GeocoderError as e:
            warn(u"Google geocoder error: {0}".format(e))

    return resp
from utility import ParserException, month2num, columnize, warn, ZIPS

try:
    import nyc_geoclient
    config = json.load(open(os.path.join(os.path.dirname(__file__), 'config.json'), 'r'))
    app_id = config['nyc_geoclient_id']
    app_key = config['nyc_geoclient_key']
    NYC_GEOCODER = nyc_geoclient.Geoclient(app_id, app_key)

    try:
        import pygeocoder
        from pygeolib import GeocoderError
        GOOGLE_GEOCODER = pygeocoder.Geocoder
    except Exception as e:
        warn(u"Can't use Google geocoder: {0}\n".format(e))

        GOOGLE_GEOCODER = None

except Exception as e:
    warn(u"Can't use NYC geocoder: {0}\n".format(e))
    NYC_GEOCODER = None

INTERSECTIONS_LONLAT_PATH = 'public/intersections.txt'

VEHICLES = set([u'Ambulance',
                u'Bicycle',
                u'Bus',
                u'Fire truck',
                u'Large com veh(6 or more tires)',
                u'Livery vehicle',
Пример #18
0
def getEVMResult(counter=10, daemon=False):
    if not daemon:
        utility.info("############# " + Fore.YELLOW +
                     "Reading MXA EVM Results" + Style.RESET_ALL +
                     " #############")
    evmList = []
    rspwList = []
    pciList = []
    evmAvg = 0.0
    rspwAvg = 0.0
    pci = -1
    for i in range(counter):
        utility.info("[Iteration " + str(i + 1) + "]")
        mxaRead = getMXAResult(daemon=True)
        evmRead = str(
            mxaRead['RSEVM']
        )  ## str(connectMXA('CALC:EVM:DATA4:TABL:STR? "RSEVM"', 5, True))
        ## utility.debug("Test evm: " + evmRead, False)
        evmRead = float(''.join(j for j in evmRead
                                if j.isdigit() or j == '.' or j == '-'))
        if not evmRead:
            utility.error('Failed to read remote MXA at [' + TCP_IP + ']',
                          False)
            break
        evmList.append(evmRead)
        evmAvg += evmRead
        if str(mxaRead['RSRP']) == '---': rspwRead = str(mxaRead['RSTP'])
        else:
            rspwRead = str(
                mxaRead['RSRP']
            )  ## str(connectMXA('CALC:EVM:DATA4:TABL:STR? "RSRP"', 5, True))
        ## utility.debug("Test rstp: " + rspwRead, False)
        rspwRead = float(''.join(j for j in rspwRead
                                 if j.isdigit() or j == '.' or j == '-'))
        if not rspwRead:
            utility.error('Failed to read remote MXA at [' + TCP_IP + ']',
                          False)
            break
        rspwList.append(rspwRead)
        rspwAvg += rspwRead
        pciRead = int(''.join(i for i in str(mxaRead['CellId'])
                              if i.isdigit()))
        pciList.append(pciRead)
        if pci == -1:
            pci = pciRead
        else:
            if pci != pciRead:
                pci = -2
                utility.warn(
                    'MXA not getting consistent PCI value, read [' +
                    str(pciRead) + ']', False)

        if not daemon:
            utility.info("PCI: " + str(pci))
            utility.info("RS EVM: " + str(evmRead) + " %rms")
            utility.info("RS Rx. Power(Avg): " + str(rspwRead) + " dBm")
    evmAvg /= counter
    rspwAvg /= counter
    return {
        'EVM_LIST': evmList,
        'RSPW_LIST': rspwList,
        'PCI_LIST': pciList,
        'EVM_AVG': evmAvg,
        'RSPW_AVG': rspwAvg,
        'PCI': pci
    }
    print("+ 2: the latest released <make> is a must!                                            +")
    print("+ 3: the latest release <tcl> is a must!                                              +")
    print("+ 4: the <Python3> is a must! and python (3.3.0) is a plus                            +")
    print("+ And you may provide sereval params (if you choose customize mode) which list as:    +")
    print("+ (1) version num: the version number which you want to download(2.6.9 as a default)  +")
    print("+ (2) port: the port which you wish the redis-server run at(6379 as a default)        +")
    print("+ Are you ready? here we go!                                                          +")
    print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
    print()

    while True:
        stepContinue =input("make sure you will uninstall the redis. Entner (y/n) to continue:  ")
        if stepContinue   == 'y':
            break
        elif stepContinue == 'n':
            warn("the uninstall has been stoped")
            exit(0)         #return 0:normal        1:error

    installMode =input("default install mode or customize install mode? Enter (d/c) to continue:  ")

    global INSTALL_VERSION_PORT
    if installMode == 'c':
        INSTALL_VERSION_PORT['VERSION_NUM'] =input("please enter the version number(format like X.X.X):")
        INSTALL_VERSION_PORT['PORT_NUM']     =input("please enter the port :")

    notice("the log file will write under /home .\nyou must give current user write permission:\n")
    CMD_CHMOD_HOMEDIR_W ="sudo chmod o+w /home"
    process =subprocess.Popen(CMD_CHMOD_HOMEDIR_W, shell=True, universal_newlines=True, stdout=subprocess.PIPE)
    process.wait()

    #pre-process paths
Пример #20
0
from utility import ParserException, month2num, columnize, warn, ZIPS

try:
    import nyc_geoclient
    config = json.load(
        open(os.path.join(os.path.dirname(__file__), 'config.json'), 'r'))
    app_id = config['nyc_geoclient_id']
    app_key = config['nyc_geoclient_key']
    NYC_GEOCODER = nyc_geoclient.Geoclient(app_id, app_key)

    try:
        import pygeocoder
        from pygeolib import GeocoderError
        GOOGLE_GEOCODER = pygeocoder.Geocoder
    except Exception as e:
        warn(u"Can't use Google geocoder: {0}\n".format(e))

        GOOGLE_GEOCODER = None

except Exception as e:
    warn(u"Can't use NYC geocoder: {0}\n".format(e))
    NYC_GEOCODER = None

INTERSECTIONS_LONLAT_PATH = 'public/intersections.txt'

VEHICLES = set([
    u'Ambulance', u'Bicycle', u'Bus', u'Fire truck',
    u'Large com veh(6 or more tires)', u'Livery vehicle', u'Motorcycle',
    u'Other', u'Passenger vehicle', u'Pedicab', u'Pick-up truck', u'Scooter',
    u'Small com veh(4\ntires)', u'Sport utility /\nstation wagon',
    u'Taxi vehicle', u'Unknown', u'Van'
Пример #21
0
def geocode_intersection(street1, street2, borocode, precinct):
    """
    Make external call to NYC's geocoder to get intersection.  If Geoclient
    can't do it, falls back on Google, but still returns Geoclient's error
    message.
    """

    # Basic response object, borrowing Geoclient's terminology
    resp = {
        u'streetName1In': street1,
        u'streetName2In': street2,
        u'boroughCode1In': borocode,
        u'source_precinct': precinct
    }

    if NYC_GEOCODER:
        borough = [
            'manhattan', 'bronx', 'brooklyn', 'queens', 'staten island'
        ][int(borocode) - 1]
        resp = NYC_GEOCODER.intersection(street1, street2, borough)

        if u'latitude' not in resp or u'longitude' not in resp:
            warn(u"Could not use NYC geocoder: {0}".format(resp[u'message']))
        else:
            if int(precinct) != int(resp.get('policePrecinct')):
                warn(u"Precinct mismatch: {0} vs. {1}".format(
                    precinct, resp.get(u'policePrecinct')))

        # Successful geocode via NYC
        if u'message' not in resp:
            return resp

    if GOOGLE_GEOCODER:
        try:
            boro_name = BORO_NUM_TO_NAME[str(borocode)]

            warn(u"Falling back to google to geocode {0} and {1}, {2}".format(
                street1, street2, boro_name))
            # kwarg `exactly_one=False` will return a list of possibilities,
            # but experience shows that these options are all bad.

            google_resp = GOOGLE_GEOCODER.geocode(
                u"{0} and {1}, {2}, NY".format(
                    street1, street2, BORO_NUM_TO_NAME[str(borocode)]))

            # Double check zip code to make sure it's in the city
            try:
                confirmed_borough = False
                confirmed_zip = False
                found_zip = None

                for comp in google_resp.data[0][u'address_components']:
                    if comp[u'long_name'].lower() == boro_name.lower():
                        confirmed_borough = True
                    if u'postal_code' in comp[u'types']:
                        found_zip = comp[u'long_name']
                        zip_borough = ZIPS.get(found_zip)
                        confirmed_zip = zip_borough.lower() == boro_name.lower(
                        )

                resp.update({
                    u'googleLongitude': unicode(google_resp.longitude),
                    u'googleLatitude': unicode(google_resp.latitude)
                })

                if confirmed_zip and confirmed_borough:
                    resp.update({
                        u'longitude': unicode(google_resp.longitude),
                        u'latitude': unicode(google_resp.latitude)
                    })
                else:

                    resp[
                        u'googleMessage'] = u"Could not confirm Google's geocoding: {0}".format(
                            {
                                'confirmed_borough': confirmed_borough,
                                'confirmed_zip': confirmed_zip
                            })
                    if found_zip:
                        resp[u'googleMessage'] += \
                                u", Google found zip {0}, but that is not in {1}".format(
                                    found_zip, boro_name)

                    warn(resp[u'googleMessage'])

            except Exception as e:
                resp[
                    u'googleMessage'] = u"Error confirming Google's geocoding: {0}".format(
                        e)
                warn(resp[u'googleMessage'])

            time.sleep(4)

        except GeocoderError as e:
            warn(u"Google geocoder error: {0}".format(e))

    return resp
def geocode_intersection(street1, street2, borocode, precinct):
    """
    Make external call to NYC's geocoder to get intersection.  If Geoclient
    can't do it, falls back on Google, but still returns Geoclient's error
    message.
    """

    # Basic response object, borrowing Geoclient's terminology
    resp = {
        u"streetName1In": street1,
        u"streetName2In": street2,
        u"boroughCode1In": borocode,
        u"source_precinct": precinct,
    }

    if NYC_GEOCODER:
        borough = ["manhattan", "bronx", "brooklyn", "queens", "staten island"][int(borocode) - 1]
        resp = NYC_GEOCODER.intersection(street1, street2, borough)

        if "compass direction" in resp.get(u"message", u"").lower():
            warn(u"Using arbitrary compass direction 'W' for double intersection")
            resp = NYC_GEOCODER.intersection(street1, street2, borough, compassDirection="w")

        if u"latitude" not in resp or u"longitude" not in resp:
            warn(u"Could not use NYC geocoder: {0}".format(resp[u"message"]))
        else:
            if int(precinct) != int(resp.get("policePrecinct")):
                warn(u"Precinct mismatch: {0} vs. {1}".format(precinct, resp.get(u"policePrecinct")))

        # Successful geocode via NYC
        if u"message" not in resp:
            return resp

    if GOOGLE_GEOCODER:
        try:
            boro_name = BORO_NUM_TO_NAME[str(borocode)]

            if boro_name.lower() == "manhattan":
                boro_name = "New York"  # Google does better with this

            warn(u"Falling back to google to geocode {0} and {1}, {2}".format(street1, street2, boro_name))
            # kwarg `exactly_one=False` will return a list of possibilities,
            # but experience shows that these options are all bad.

            google_resp = GOOGLE_GEOCODER.geocode(
                u"{0} and {1}, {2}, NY".format(street1, street2, BORO_NUM_TO_NAME[str(borocode)])
            )

            # Double check zip code to make sure it's in the city
            try:
                confirmed_borough = False
                confirmed_zip = False
                found_zip = None

                relevant_google_resp_data = None
                for google_resp_data in google_resp.data:
                    if "intersection" in google_resp_data["types"]:
                        relevant_google_resp_data = google_resp_data

                if relevant_google_resp_data:
                    for comp in google_resp.data[0][u"address_components"]:
                        if comp.get(u"long_name", "").lower() == boro_name.lower():
                            confirmed_borough = True
                        if u"postal_code" in comp.get(u"types", []):
                            found_zip = comp.get(u"long_name")
                            zip_borough = ZIPS.get(found_zip, "")
                            confirmed_zip = zip_borough.lower() == boro_name.lower()

                    resp.update(
                        {
                            u"googleLongitude": unicode(google_resp.longitude),
                            u"googleLatitude": unicode(google_resp.latitude),
                        }
                    )

                    if confirmed_zip and confirmed_borough:
                        resp.update(
                            {u"longitude": unicode(google_resp.longitude), u"latitude": unicode(google_resp.latitude)}
                        )
                    else:
                        resp[u"googleMessage"] = u"Could not confirm Google's geocoding: {0}".format(
                            {"confirmed_borough": confirmed_borough, "confirmed_zip": confirmed_zip}
                        )
                        if found_zip:
                            resp[u"googleMessage"] += u", Google found zip {0}, but that is not in {1}".format(
                                found_zip, boro_name
                            )

                        warn(resp[u"googleMessage"])
                else:
                    resp[u"googleMessage"] = u"No intersection data for Google's geocoding"
                    warn(resp[u"googleMessage"])

            except Exception as e:
                resp[u"googleMessage"] = u"Error confirming Google's geocoding: {0}".format(e)
                warn(resp[u"googleMessage"])

            time.sleep(4)

        except GeocoderError as e:
            resp[u"googleMessage"] = u"Google geocoder error: {0}".format(e)
            warn(resp[u"googleMessage"])

    return resp
    print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
    print("+                      redis-automatic uninstall script (python)                              +")
    print("+------------------------------------------------------------————-----------------------------+")
    print("+ you may support sereval params (if you choosed customize mode when you installed the redis):+")
    print("+ (1) version num: the version number which you downloaded(2.6.9 as a default)                +")
    print("+ (2) port: the port which the redis-server run at(6379 as a default)                         +")
    print("+ Are you ready? here we go!                                                                  +")
    print("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
    print()

    while True:
        stepContinue =input("make sure you will uninstall the redis. Entner (y/n) to continue:  ")
        if stepContinue   == 'y':
            break
        elif stepContinue == 'n':
            warn("the uninstall has been stoped")
            exit(0)         #return 0:normal        1:error
            

    global INSTALL_VERSION_PORT

    while True:             #do .. while
        installMode =input("default install mode or customize install mode when installed redis? Enter (d/c) to continue:  ")
        if installMode   == 'c':
            INSTALL_VERSION_PORT['VERSION_NUM'] =input("please enter the version number(format like X.X.X):")
            INSTALL_VERSION_PORT['PORT_NUM']    =input("please enter the port :")
            break
        elif installMode == 'd':
            break