Exemple #1
0
	def get_house_results(self):

		zip_code = zipcode.isequal(self.zip)
		d = zip_code.to_dict()
		point = (d['lat'], d['lon'])
		zips = zipcode.isinradius(point, self.radius)
		zips = [new_zip for new_zip in zips if not new_zip.decommisioned != "FALSE"]
		zips = [new_zip.zip for new_zip in zips if new_zip.zip_type == "STANDARD"]

		ads_info = []
		for zip in zips:
			self.bro.driver.get("https://www.zillow.com/homes/for_sale/{0}_rb/house,condo,apartment_duplex,mobile,townhouse_type/?fromHomePage=true&shouldFireSellPageImplicitClaimGA=false&fromHomePageTab=buy".format(zip))

			try:
				next_button = self.bro.driver.find_element_by_xpath("//li[@class='zsg-pagination-next']")
			except:
				next_button = 'Something'

			while next_button:
				ads = self.bro.driver.find_elements_by_xpath("//div[@id='search-results']//article")

				for ad in ads:
					properties = self._get_ad_properties(ad)
					if properties:
						ads_info.extend([properties])

				try:
					next_button = self.bro.driver.find_element_by_xpath("//li[@class='zsg-pagination-next']")
					next_button.click()
				except:
					break
				time.sleep(2)  # Should get rid of this

		self.bro.driver.close()
		write_to_csv("Zillow", ads_info)
 def local_city_list_maker(starting_zip='98119', mile_radius=100):
     """returns a set of cities within radius of starting zip,
     formatted with state space city to use in weather_station_code_finder function"""
     zip_obj = zipcode.isequal(starting_zip)
     local_zips = zipcode.isinradius((zip_obj.lat, zip_obj.lon),
                                     mile_radius)
     return {' '.join([i.state, i.city]) for i in local_zips}
Exemple #3
0
def get_all_buy_li(zcode):

    if zipcode.isequal(str(zcode)) == None:
        return None
    req_url = 'https://www.zillow.com/homes/for_sale/' + str(zcode) + '_rb/'
    page = requests.get(req_url, headers=HEADER)
    tree = html.fromstring(page.content)

    list_li = tree.xpath(
        '/html/body/div[@class="main-wrapper " and @id="wrapper"]/div[@class="search-content-container" and @id="container"]/div[@class="active-view"]/div[@id="c-column"]/div[@id="inner-c-column"]/div[@id="list-container-column"]/div[@class="active-view"]/div[@id="list-results-container"]/div[@id="list-container"]/div[@id="inner-list-container"]/div[@id="list-core-content-container"]/div[@id="list-results"]/div[@id="search-results"]/ul[@class="photo-cards"]/li'
    )

    total_page = int(
        tree.xpath('//ol[@class="zsg-pagination"]/li')[-2].getchildren()
        [0].text)
    for page_num in range(2, total_page + 1):
        req_url = 'https://www.zillow.com/homes/for_sale/' + str(
            zcode) + '_rb/' + str(page_num) + '_p/'
        page = requests.get(req_url, headers=HEADER)
        tree = html.fromstring(page.content)
        list_li += tree.xpath(
            '/html/body/div[@class="main-wrapper " and @id="wrapper"]/div[@class="search-content-container" and @id="container"]/div[@class="active-view"]/div[@id="c-column"]/div[@id="inner-c-column"]/div[@id="list-container-column"]/div[@class="active-view"]/div[@id="list-results-container"]/div[@id="list-container"]/div[@id="inner-list-container"]/div[@id="list-core-content-container"]/div[@id="list-results"]/div[@id="search-results"]/ul[@class="photo-cards"]/li'
        )

    return list_li
def get_region_from_zip(zip_code, mapping=None):
	if not mapping:
		mapping = get_region_mapping()

	zip_code_object = zipcode.isequal(zip_code)

	return mapping[zip_code_object.state]
Exemple #5
0
def location():
    # Get geo location based on IP
    if config['use_geoloc'] == "0":
        zipcodes = config['zipcode']
        city = zipcode.isequal(zipcodes)
        logging.debug("USING CONFIGURED ZIP CODE: %s" % zipcodes)
        geojson = requests.get("https://api.weather.gov/points/%s,%s" %
                               (city.lat, city.lng))
        geojson = json.loads(geojson.text)
        geolocation = geojson["properties"]["forecast"]
        city = geojson["properties"]["relativeLocation"]["properties"]["city"]
        state = geojson["properties"]["relativeLocation"]["properties"][
            "state"]

        return geolocation

    else:
        logging.debug("ATTEMPTING TO GEO LOCATE BASED ON IP...")
        geo_loc = requests.get('https://ipinfo.io/json')
        geo_loc = json.loads(geo_loc.text)
        geo_loc = geo_loc["loc"]

        # Get weather.gov Forecast Office URL
        logging.debug(
            "WEATHER.GOV ENTRY URL: https://api.weather.gov/points/%s" %
            geo_loc)
        geojson = requests.get("https://api.weather.gov/points/%s" % geo_loc)
        geojson = json.loads(geojson.text)
        city = geojson["properties"]["relativeLocation"]["properties"]["city"]
        state = geojson["properties"]["relativeLocation"]["properties"][
            "state"]
        geolocation = geojson["properties"]["forecast"]
        logging.debug("WEATHER.GOV GRID POINTS URL: %s" % geolocation)

    return geolocation
def local_zipcodes(startingzip='98119', radius=10):
    """ Returns zipcodes within radius of startingzip """
    zip_obj = zipcode.isequal(startingzip)
    try:
        local_zips = zipcode.isinradius((zip_obj.lat, zip_obj.lon), radius)
        return [i.zip for i in local_zips]
    except AttributeError:
        return 'No surrounding data available for ' + startingzip
def gen_city_zip():
    zips = {}
    for i in range(99999):
        z = zip.isequal(format(i, '05d'))
        if z is not None:
            zips[z.city] = format(i, '05d')

    return (zips)
Exemple #8
0
def get_zipcode_info(in_zip):
    parsed_zip = in_zip[0:5]
    zip = zipcode.isequal(parsed_zip)
    data = {}
    print zip
    data["zip"] = zip.zip
    data["city"] = zip.city
    data["state"] = zip.state
    return data
Exemple #9
0
 def clean_postal_code(self):
     value = self.cleaned_data['postal_code']
     if len(value) < 5:
         raise ValidationError('Postal code must be 5 digits')
     if not ZIPCODE_REGEX.match(value):
         raise ValidationError('Postal code must be 5 digits')
     if not zipcode.isequal(str(value)):
         raise ValidationError('Invalid postal code')
     return self.cleaned_data['postal_code']
def get_zipcode_info(in_zip):
    parsed_zip = in_zip[0:5]
    zip = zipcode.isequal(parsed_zip)
    data = {}
    print zip
    data["zip"] = zip.zip
    data["city"] = zip.city
    data["state"] = zip.state
    return data
Exemple #11
0
def local_city_grabber(starting_zip='98119', mile_radius=100):
    """returns dict of zipcodes within radius of starting zip"""
    cities = {}
    zip_obj = zipcode.isequal(starting_zip)
    local_zips = zipcode.isinradius((zip_obj.lat, zip_obj.lon), mile_radius)
    for i in local_zips:
        state_city = i.state + ' ' + i.city
        if state_city not in cities:
            cities[state_city] = {'zip': i.zip}
    return cities
def local_city_list_maker(starting_zip='98119', mile_radius=100):
    """returns list of cities within radius of starting zip"""
    city_list = []
    zip_obj = zipcode.isequal(starting_zip)
    local_zips = zipcode.isinradius((zip_obj.lat, zip_obj.lon), mile_radius)
    for i in local_zips:
        state_city = i.state + ' ' + i.city
        if state_city not in city_list:
            city_list.append(state_city)
    return city_list
Exemple #13
0
def local_city_list_maker(starting_zip='98119', mile_radius=100):
    """returns list of cities within radius of starting zip"""
    city_list = []
    zip_obj = zipcode.isequal(starting_zip)
    local_zips = zipcode.isinradius((zip_obj.lat, zip_obj.lon), mile_radius)
    for i in local_zips:
        state_city = i.state + ' ' + i.city
        if state_city not in city_list:
            city_list.append(state_city)
    return city_list
Exemple #14
0
def zip_to_geocode(zip):
    try:
        geo_code = zipcode.isequal(str(zip))
        if geo_code is None:
            raise Exception
    except:
        geo_code = 'Invalid zip code or zip code format not recogized'
        return None
    else:
        return [geo_code.lat, geo_code.lon]
Exemple #15
0
def extract_state(string):
    #rint (string)
    if string != "":
        zip_ = zipcode.isequal(string)
        if zip_ is None:
            return None
        else:
            return (zip_.state)
    else:
        return None
    def parse_store(self, response):
        item = ChainItem()
	item['store_name'] = self.validate(response.xpath("//h1[@class='pos-detail-store-name']/text()"))
	item['store_number'] = ''
	item['phone_number'] = self.validate(response.xpath("//p[@class='pos-detail-phone-number']/text()"))[4:].strip()
	item['city'] = self.validate(response.xpath("//span[@class='pos-city']/text()"))
	item['country'] = response.meta["country"]
	item['state'] = ""
	item['zip_code'] = self.validate(response.xpath("//span[@class='pos-postal-code']/text()"))
        temp = item['zip_code'].split(" ")

        if item['country'] == "United States" and len(temp) > 1:
            if len(temp[0]) == 2:
                item['state'] = temp[0]
                item['zip_code'] = temp[1]
            else:
                item['state'] = temp[1]
                item['zip_code'] = temp[0]
        if item['country'] == "Canada" and len(temp) > 2:
            tp_zip, tp_state = [], ""
            for tp in temp:
                if len(tp) == 2:
                    tp_state = tp
                else:
                    tp_zip.append(tp)
            item['state'] = tp_state
            item['zip_code'] = " ".join(tp_zip)

        if item['zip_code'].strip() != "":
            try:
                if item['country'] == "Canada":
                    item["state"] = self.pcdb[str(item['zip_code'].split(" ")[0])].province
                else:
                    item["state"] = zipcode.isequal(str(item['zip_code'])).state
            except:
                pass

	item['latitude'] = ''
	item['longitude'] = ''

        address = self.validate(response.xpath("//address[@class='pos-detail-store-address']/text()"))
	item['address'] = address.replace("\n", "").strip()
        
        open_hrs = response.xpath("//ul[@class='opening-hours']//li")
        open_hrs_list = []
        if len(open_hrs) > 0:
            for hr in open_hrs:
                open_hrs_list.append(self.validate(hr.xpath(".//meta/@content")))

	item['store_hours'] = "; ".join(open_hrs_list)
	#item['store_type'] = info_json["@type"]
	item['other_fields'] = ''
	item['coming_soon'] = '0'

        yield item
Exemple #17
0
def city_state(zip_c):

    in_zip = zipcode.isequal(zip_c)
    zip_state = in_zip.state
    zip_city = in_zip.city
    zip_city = zip_city.replace(" ", "")

    file_name = "yelp_" + zip_city.lower() + "_" + zip_state.lower(
    ) + "_" + zip_c + ".csv"

    return file_name
Exemple #18
0
def homepage(request):
    ip_forwarded = request.META.get('HTTP_X_FORWARDED_FOR')
    if ip_forwarded:
        ip = ip_forwarded.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    #convert ip into zipcode
    #if user doesn't input zipcode/location, default will be the automatically
    #converted zipcode
    if request.GET.get('zipcode'):
        query = request.GET.get('q')
        zip_code = request.GET.get('zipcode')
        """ 
        search = ZipcodeSearchEngine()
        zip = search.by_zipcode(zip_code) 
        longitude = zip['Longitude']
        lat = zip['Latitude']
        """
        zip = zipcode.isequal(str(zip_code))
        longitude = 0.00
        lat = 0.00
        sqs = SearchQuerySet().dwithin('location', Point(longitude, lat), D(mi=30))
        f = PostingFilter(request.GET, queryset=sqs)

        context = {
 	'city': zip['City'],
	'filter': f,
   	'sqs': sqs,
        'zipcode':'00001',
   	'query': query,
        }

    else:
        #Temporary stand-in ip-address
        query = request.GET.get('q')
        ip = '24.6.173.143'
        g = GeoIP2()
        location_dict = g.city(ip) 
        city = location_dict['city']
        lat = location_dict['latitude']
        longitude = location_dict['longitude']
        zip_code = location_dict['postal_code']
        sqs = SearchQuerySet().dwithin('location', Point(longitude, lat), D(mi=30))
        f = PostingFilter(request.GET, queryset=sqs)
        context = {
 	'city': city,
	'filter': f,
   	'sqs': sqs,
        'zipcode': '10001',
  	'query': query,
        }
    return render(request, 'search/filter_template.html', context)
def get_city_data_geopy(zipc):
    """Given a zip code, return latlon and city name"""
    geolocator = Nominatim()
    coord_data = geolocator.geocode(str(zipc))
    name_data = zipcode.isequal(str(zipc))
    if coord_data is not None and name_data is not None:
        lat = coord_data[1][0]
        lon = coord_data[1][1]
        name = '%s, %s' % (name_data.city, name_data.state)
        return lat, lon, name
    # Some data points are empty, return string of none in this case
    else:
        return 'None', 'None', 'None'
def subscribe(number, zip):
    conn = pymysql.connect(host='127.0.0.1', user=config.DB_USER, passwd=config.DB_PASSWORD, db='thunderbuddy')
    cur = conn.cursor()
    try:
        if len(str(int(number))) > 15:
            cur.close()
            conn.close()
            resp = flask.Response("Please input a valid number", status=400)
            resp.headers["Access-Control-Allow-Origin"] = "*"
            return resp 
    except:
        cur.close()
        conn.close()
        resp = flask.Response("Please input a valid number", status=400)
        resp.headers["Access-Control-Allow-Origin"] = "*"
        return resp 
    # allow users to change their location without duplicating in the bases
    cur.execute("DELETE FROM user WHERE number=" + number)
    conn.commit()

    zipcodeInfo = zipcode.isequal(zip)
    numberInfo = client.phone_numbers.get(number, include_carrier_info=True)
    carrier = numberInfo.carrier['name']
    # Convert carrier to portal
    portal = ""
    if carrier in carrierPortalLookup:
        portal = carrierPortalLookup[carrier]
    else:
        cur.close()
        conn.close()
        resp = flask.Response("We are sorry, but ThunderBuddy does not support your carrier", status=400)
        resp.headers["Access-Control-Allow-Origin"] = "*"
        return resp
    sql = "INSERT INTO user(number,city,state,carrier_portal) VALUES(%s,%s,%s,%s)"
    city = str(zipcodeInfo.city).replace(" ", "_")
    state = str(zipcodeInfo.state)
    v = (str(number), city, state, portal)
    print(str(datetime.now()) + " Adding user - " + carrier + " " + str(v))
    cur.execute(sql, v)
    conn.commit()

    resp = flask.Response("Subscribed " + str(number), status=200)
    resp.headers["Access-Control-Allow-Origin"] = "*"
    cur.close()
    conn.close()
    return resp
Exemple #21
0
    def build_form(self, form_kwargs=None):
        """
        Instantiates the form the class should use to process the search query.
        """
        data = None
        kwargs = {"load_all": self.load_all}
        if form_kwargs:
            kwargs.update(form_kwargs)

        if len(self.request.GET):
            data = self.request.GET
	# Radius is defaulted to 30 miles	
        #import pdb; pdb.set_trace()
        if self.request.GET.get('zipcode'):
            self.zipcode = self.request.GET.get('zipcode')
            """
            search = ZipcodeSearchEngine()
            zip = search.by_zipcode(zip_code) 
            longitude = zip['Longitude']
            lat = zip['Latitude']
            """
            zip = zipcode.isequal(str(self.zipcode))
            longitude = zip.lng
            lat = zip.lat
            self.city = zip.city
            self.state = zip.state
            self.searchqueryset = SearchQuerySet().dwithin('location', Point(longitude, lat), D(mi=30))
            #f = PostingFilter(self.request.GET, queryset=sqs)
        else:
            ip = '24.6.173.143'
            g = GeoIP2()
            location_dict = g.city(ip) 
            self.city = location_dict['city']
            self.state = location_dict['region']
            lat = location_dict['latitude']
            longitude = location_dict['longitude']
            self.zipcode = location_dict['postal_code']
            self.searchqueryset = SearchQuerySet().dwithin('location', Point(longitude, lat), D(mi=30))
            #f = PostingFilter(self.request.GET, queryset=sqs)
        if self.searchqueryset is not None:
            kwargs["searchqueryset"] = self.searchqueryset
        
        self.zipcode_form = Zipcode_Form(self.request.GET)
        
        return self.form_class(data, **kwargs)
Exemple #22
0
def recuperar_dados_cidade_pelo_cep(cep):
    """
    Usa um biblioteca de zipcode dos EUA pra equalizar os nomes de cidades
    da base de dados e obter longitude e latidude.
    """
    if cep is not None or cep != "":
        #Utiliza apenas os 5 primeiros digitos do CEP
        numero_cep = cep[0:5]
        try:
            zip = zipcode.isequal(numero_cep)
            if zip is not None:
                return zip.city, zip.lon, zip.lat
            else:
                return "", "", ""
        except ValueError:
            return "", "", ""
    else:
        return "", "", ""
Exemple #23
0
def txt_to_dict(file_name):
    f = open(file_name)
    L = f.readlines()
    column = L[0][3:-1]
    L = L[1:]
    data = {}

    #extract column names from txt
    names = column.split('\t')
    
    #find zipcode column's index
    for m in range(len(names)):
        if "zip" in names[m].lower():
            index = m

    #zipcode to state and txt to dictionary
    for variable_name in names:
        data[variable_name] = []
    for i in range(len(L)):
        variable = L[i][:-1].split('\t')
        try:
            myzip = zipcode.isequal(variable[m])
            code = int(variable[m][0:3])
            if (len(variable[m]) == 5) & (199 < code < 205):
                state = "DC"
                print(state)
            elif (len(variable[m]) == 5) & (204 < code < 220):
                state = "MD"
            elif (len(variable[m]) == 5) & (479 < code < 500):
                state = "MI"
            elif (len(variable[m]) == 5) & (variable[m][0:3] == "276"):
                state = "NC"
            else:
                state = myzip.state
            for j in range(len(variable)):
                if j == m:
                    data[names[j]].append(state)
                else:
                    data[names[j]].append(variable[j])
        except:
            continue

    data_pd = DataFrame(data, columns=names)
    return data_pd
def gettingdata():
    gender = request.form.get("gender")
    city = request.form.get("city")
    zip = request.form.get("zip")
    zip = zipcode.isequal(zip)
    lat = zip.lat
    lon = zip.lon
    height = request.form.get("height")
    smoke = request.form.get("smoke")
    age = request.form.get("age")
    state = request.form.get("states")
    weight = request.form.get("weight")
    income = request.form.get("income")
    coverage = request.form.get("coverage")
    married_status = request.form.get("married_status")
    try:
        opinsured = request.form.get("500k")
    except:
        opinsured = int(request.form.get("other"))
    pre_existing = []
    try:
        pre_existing.append(request.form.get("c1"))
    except:
        pass
    try:
        pre_existing.append(request.form.get("c2"))
    except:
        pass
    try:
        pre_existing.append(request.form.get("c3"))
    except:
        pass
    try:
        pre_existing.append(request.form.get("c4"))
    except:
        pass
    try:
        pre_existing.append(request.form.get("c5"))
    except:
        pass
    prices = regression_file.get_data(age, lon, *pre_existing)
    # model_training.get_data(city, age, lon, gender, state, lat, coverage, opinsured, income, married_status, height, weight, smoke, *pre_existing)
    return render_template("results.html", plan_prices = prices)
def get_city_state_by_zip(zip_code):
    """
    Lookup a US zip code for corresponding city and state

    Args:
        zip_code (string / int) : zip code for lookup

    Returns:
        city (string): corresponding city
        state (string): corresponding state
        None: If no match is found
    """

    zip_code_instance = zipcode.isequal(str(zip_code))

    city = zip_code_instance.city
    state = zip_code_instance.state

    if len(str(state)) == 0:
        return None

    return zip_code_instance.city, zip_code_instance.state
def get_lat_long_by_zip(zip_code):
    """
    Lookup a US zip code for corresponding latitude
    and longitude

    Args:
        zip_code (string / int): zip code for lookup

    Returns:
        latitude (string): corresponding latitude
        longitude (string) :corresponding longitude
        None: If no match is found
    """

    zip_code_instance = zipcode.isequal(str(zip_code))
    latitude = zip_code_instance.latitude
    longitude = zip_code_instance.longitude

    if len(str(latitude)) == 0:
        return None

    return latitude, longitude
Exemple #27
0
  def parse_store(self, response):
    item = ChainItem()
    item['store_name'] = self.validate(response.xpath("//h1[@class='pos-detail-store-name']/text()"))
    item['store_number'] = ''
    item['phone_number'] = self.validate(response.xpath("//p[@class='pos-detail-phone-number']/text()"))[4:].strip()
    item['city'] = self.validate(response.xpath("//span[@class='pos-city']/text()"))
    item['country'] = response.meta["country"]
    item['state'] = ""
    item['zip_code'] = self.validate(response.xpath("//span[@class='pos-postal-code']/text()"))
      temp = item['zip_code'].split(" ")

      if item['country'] == "United States" and len(temp) > 1:
        if len(temp[0]) == 2:
          item['state'] = temp[0]
          item['zip_code'] = temp[1]
        else:
          item['state'] = temp[1]
          item['zip_code'] = temp[0]
      if item['country'] == "Canada" and len(temp) > 2:
        tp_zip, tp_state = [], ""
        for tp in temp:
          if len(tp) == 2:
            tp_state = tp
          else:
            tp_zip.append(tp)
        item['state'] = tp_state
        item['zip_code'] = " ".join(tp_zip)

      if item['zip_code'].strip() != "":
        try:
          if item['country'] == "Canada":
            item["state"] = self.pcdb[str(item['zip_code'].split(" ")[0])].province
          else:
            item["state"] = zipcode.isequal(str(item['zip_code'])).state
        except:
          pass
Exemple #28
0
from lxml import html
import re
import zipcode

# search = ZipcodeSearchEngine()


url = 'https://www.neighborhoodscout.com/{}/{}/crime'

state = ''
city = ''

address = '123 Main St, 94720 USA'
postal_code = re.search('(\\d{5})', address).group(0)

myzip = zipcode.isequal(postal_code)
state = myzip.state  
try:
	city = myzip.city.replace(" ", "-")
except Exception as e:
	print(e)

# zipcode = search.by_zipcode(postal_code)
# state = zipcode.State
# city = zipcode.City#.replace(" ", "-")


url = url.format(state, city)


f = open(cleanCSVFile,'wt')
try:
    writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
    writer.writerow( ('Boat Year', 'Boat Model','Boat Make', 'Seller Name', 'Postal Code', 'Boat Price', 'Boat Class','Boat Category','Boat Length','Propolsion Type','Hull Material','Fuel Type','City','State','lat','lon') )
finally:
    f.close()

with open('cleanData2.csv','rb') as csvfile:
    reader = csv.DictReader(csvfile)
    count2 = 0
    for row in reader:
    	f = open(cleanCSVFile, 'a')
        if row['Postal Code'] != '0':
            try:
                if len(row['Postal Code']) > 5:
                    temp = row['Postal Code']
                    temp = temp[:5]
                    myzip = zipcode.isequal(temp)
                else:
                    myzip = zipcode.isequal(row['Postal Code'])
                if myzip != None:
                    try:
                        writer = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
                        writer.writerow((row['Boat Year'],row['Boat Model'],row['Boat Make'],row['Seller Name'],row['Postal Code'],row['Boat Price'],row['Boat Class'],row['Boat Category'],row['Boat Length'],row['Propolsion Type'],row['Hull Material'],row['Fuel Type'],myzip.city,myzip.state,myzip.lat,myzip.lon))
                        count2 = count2 + 1
                    finally:
                        f.close()
            except:
                print row['Postal Code']
    print count2
Exemple #30
0
    tonum = '+1' + num
    twilio_sid = "AC3fc819a1fe2f836b25e54e0ef47ba23d"
    twilio_token = "52a06091ff97cdc10f3af0f6790c9daf"
    client = TwilioRestClient(twilio_sid, twilio_token)
    mess1 = "Next viewable event: " + mess
    message = client.messages.create(to=tonum,
                                     from_="+18045523194",
                                     body=mess1)


#---------------------------------------------------------------------
zip, sat = get_args()

init_LED()

myzip = zipcode.isequal(zip)
geolocator = Nominatim()
location = geolocator.geocode(myzip.city)

print("Satellite Information:")
tleInfo = st.tle_latest(norad_cat_id=[25544], ordinal=1, format='tle')

tle = ''.join(tleInfo)
tle0, tle1 = tle.splitlines()

print(st.tle_latest(norad_cat_id=[25544], ordinal=1, format='tle'))
print("Zip Information:")
print((location.latitude, location.longitude))
#print(location.address)

#print (tle0)
	if VERBOSE:

		selectUserInfo = userInfo.lookup(userID)
		print 
		print "Age : ", selectUserInfo[0][1]
		print "Sex : ", selectUserInfo[0][2]
		print "Profession : ", selectUserInfo[0][3]
		try:
			ZipCode = int(selectUserInfo[0][4])
		except ValueError:
			#Handle the exception
			print 'Illegal ZipCode, setting to NYC **'
			ZipCode = 10001 #NYC

		print "ZipCode : ", ZipCode
		userZip = zipcode.isequal(str(ZipCode))
		print "Location : ", userZip.to_dict()['location_text']	

		print
		print "Rated Products : "
		for index in range(numProducts):  
			if index < len(moviesForUser):
				print ratedTitles[index][0][1]
				# print moviesForUser[index][1], ratedTitles[index][0][1]

		print
		print "Recommended Products : "
		for index in range(len(topRecs)):
			print recommendedTitles[index][0][1]
			# print topRecs[index][1], recommendedTitles[index][0][1]
import csv
import zipcode

with open('2017_zip_codes.txt', 'r') as zip_code_file:
    with open('2017_long_lat.csv', 'w+') as csv_file:
        csvwriter = csv.writer(csv_file)
        csvwriter.writerow(['long', 'lat'])
        for line in zip_code_file:
            line = line.strip()
            zip_ = zipcode.isequal(line.strip().split('-')[0])
            if (zip_ is not None):
                csvwriter.writerow([zip_.lon, zip_.lat])
Exemple #33
0
def get_lat_lon_from_zipcode(zipcode):
    zip = zipcode.isequal(zipcode)
    lat = zip.lat
    lon = zip.lon
    return (lat, lon)
Exemple #34
0
        dob = str(datetime(year, month, day)).split(" ")[0]
        height = random.randint(120, 160)
        ethnicity = random.randint(1, 8)
        religion = random.randint(1, 8)
        drink = random.choice(drink_smoke)
        smoke = random.choice(drink_smoke)
        relation_status = random.choice(current_relationship)
        want_kids = random.choice(want_kids_options)

        address = p['address'].split("\n")[0]
        #city = fake.city()

        # instead of using entire US, for demostration just use CA zipcodes 90001-96162, oregon - 97001 -97920,
        while True:
            zipc = fake.zipcode()
            myzip = zipcode.isequal(str(zipc))
            if myzip and myzip.state == 'CA':
                break

        # zipc = random.choice(range(90001, 96163))
        city = myzip.city
        state = myzip.state
        phone = fake.phone_number()

        emp = p['company']
        occ = p['job']
        edu = random.choice(level) + " in " + random.choice(fields)

        print >> f, str(uid) + "|" + email + "|" + password + "|" + fname + "|" + lname \
                             + "|" + dob + "|" + str(height) + "|" + gender + "|" + str(ethnicity) + "|" + str(religion) \
                             + "|" + drink + "|" + smoke + "|" + relation_status + "|" + want_kids \
 def local_city_list_maker(starting_zip='98119', mile_radius=100):
     """returns a set of cities within radius of starting zip,
     formatted with state space city to use in weather_station_code_finder function"""
     zip_obj = zipcode.isequal(starting_zip)
     local_zips = zipcode.isinradius((zip_obj.lat, zip_obj.lon), mile_radius)
     return {' '.join([i.state, i.city]) for i in local_zips}
Exemple #36
0
import zipcode
import re

my_zip = zipcode.isequal('98119')
local_zips = zipcode.isinradius((my_zip.lat, my_zip.lon), 100)



zip_dict = {}

## good code!!!
for i in local_zips:
    state_city = i.state + ' ' + i.city
    if state_city not in zip_dict:
        zip_dict[state_city] = [i.zip]
    zip_dict[state_city].append(i.zip)
## good code!!!




print(zip_dict)

code_db = open('weather_codes.txt', 'r').read()

for i in zip_dict:
    #m = re.search('{}.+'.format(i), code_db)
    m = re.search(i + '.*[PKXQ]\w{3}\s\s', code_db)
    #cm = re.search('^[PKXQ]{4}', m.group)
    # m = re.findall(i +'\s^[PKXQ]{4}', code_db)
    try:
def define_state(store):
    return zipcode.isequal(store['zip_code']).state
print("Tell the API what we want to export")
myExport = elq.CreateDef(entity='contacts', defType='exports', fields=myFields, filters=myFilter, defName="My zipcode export")
print("Start syncing the data for export")
mySync = elq.CreateSync(defObject=myExport)
status = elq.CheckSyncStatus(syncObject=mySync)
print(status)

print("Get the data...")

data = elq.GetSyncedData(defObject=myExport)
print("Data has " + str(len(data)) + " records") ## tells you how many records were exported; should match the number from our segment
print("First row: ")
print(data[0]) ## show us the first row of data

print("Clean up the zipcode values")
for row in data:
  if (row['Zip or Postal Code']!=''): ## Only process if the zipcode field is not blank
    zip_old = row['Zip or Postal Code'] # get the value from the field
    zip_clean = re.split('[^0-9]', zip_old)[0] # if there are any spaces, dashes or breaks, get only the first string of numbers i.e.; '12345-123' becomes '12345', and '87890 NEW ADDRESS' becomes '87890'
    zip_clean = zip_clean[:5] # trim down to only the first five digits
    zip_clean = zip_clean.zfill(5) # if the string is shorter than 5 digits, add 0's to the left side
    if (zipcode.isequal(zip_clean)): # check if zipcode is valid
      row['Zip or Postal Code'] = zip_clean # put the value back on the contact record
    else:
      row['Zip or Postal Code'] = '' # If not valid, set to blank

print("Import the updated data back into Eloqua...")
importDef = elq.CreateDef(entity='contacts', defType='imports', fields=myFields, defName='My zipcode import', identifierFieldName="Email Address")
postInData = elq.PostSyncData(data=data, defObject=importDef)
print("All done!")
def local_zipcodes(startingzip='98119', radius=100):
    """ Returns zipcodes within radius of startingzip"""
    zip_obj = zipcode.isequal(startingzip)
    local_zips = zipcode.isinradius((zip_obj.lat, zip_obj.lon), radius)
    return {i.zip for i in local_zips}
Exemple #40
0
import sys
import math
import ephem
from spacetrack import SpaceTrackClient
st = SpaceTrackClient('*****@*****.**', 'johnnyboy1234567')
import zipcode
from geopy.geocoders import Nominatim
#from orbit import satellite

myzip = zipcode.isequal('24061')
geolocator = Nominatim()
location = geolocator.geocode(myzip.city)

print ("Satellite Information:")
tleInfo = st.tle_latest(norad_cat_id=[25544], ordinal=1, format='tle')

tle = ''.join(tleInfo)
tle0, tle1 = tle.splitlines()


print(st.tle_latest(norad_cat_id=[25544], ordinal=1, format='tle'))
print ("Zip Information:")
print((location.latitude, location.longitude))
print(location.address)

print (tle0)
print ("---------------------------------")
print (tle1)
print ("---------------------------------")

iss = ephem.readtle("ISS (ZARYA)", tle0, tle1)
def local_city_grabber(starting_zip='98119', mile_radius=100):
    """returns set of cities within radius of starting zip"""
    zip_obj = zipcode.isequal(starting_zip)
    local_zips = zipcode.isinradius((zip_obj.lat, zip_obj.lon), mile_radius)
    return {'{} {}'.format(i.state, i.city) for i in local_zips}
Exemple #42
0
# check weather from zipcode
import requests
import sys
import zipcode

# regiter your api key at:
# https://www.wunderground.com/weather/api/
key = '16-digit wunderground api key'

zc = zipcode.isequal(sys.argv[1])
url = 'http://api.wunderground.com/api/{}/geolookup/conditions/q/{}/{}.json'.format(key, zc.state, sys.argv[1])
r = requests.get(url)

json_string = r.json()
location = json_string['current_observation']['display_location']['full']
temperature = json_string['current_observation']['temperature_string']
feelslike = json_string['current_observation']['feelslike_string']
print('Location: {}'.format(location), sys.argv[1])
print('Temperature: {} \nFeels like:{} '.format(temperature, feelslike))

# python weather.py <zip_code>

# sample output:
# Location: Dallas, TX 75248
# Temperature: 76.4 F (24.7 C)
# Feels like:76.4 F (26 C)