How to use the geonamescache.GeonamesCache function in geonamescache

To help you get started, we’ve selected a few geonamescache examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github yaph / geonamescache / tests / test_geonamescache.py View on Github external
def setUp(self):
        self.geonamescache = GeonamesCache()
github p2pu / learning-circles / cities / __init__.py View on Github external
def update_autocomplete_list():
    import geonamescache
    admin1 = read_admin1_codes()
    def admin1_name(code):
        return next((a[1] for a in admin1 if a[0] == code), None) or ''

    gc = geonamescache.GeonamesCache()
    cities = [
        ', '.join([
            city['name'],
            admin1_name(city['country code'] + '.' + city['admin1 code']),
            gc.get_countries()[city['country code']]['name']
        ])
        for city in read_cities()
    ]
    with codecs.open('cities/autocomplete_list.csv', 'w', 'utf-8') as f:
        f.write('\n'.join(cities))
github OCHA-DAP / hdx-python-api / src / hdx / utilities / location.py View on Github external
# -*- coding: utf-8 -*-
"""Location utilities"""
from typing import List, Callable, Tuple, Optional, TypeVar

import geonamescache

ExceptionUpperBound = TypeVar('T', bound='Exception')


class Location(object):
    """Methods to help with countries and continents
    """

    gc = geonamescache.GeonamesCache()
    continents = gc.get_continents()
    countries = gc.get_countries().values()

    @staticmethod
    def get_country_name_from_iso3(iso3):
        # type: (str) -> Optional[str]
        """Get country name from iso3 code

        Args:
            iso3 (str): Iso 3 code for which to get country name

        Returns:
            Optional[str]: country name
        """
        iso3lower = iso3.lower()
        for countrydetails in Location.countries:
github autonomio / astetik / astetik / plots / world.py View on Github external
data = outliers(data, value_col)

    if value_col_to_title == True:
        title = title + ' {}'.format(value_col)

    descripton.strip()

    if area_to_code == True:
        data[area_col] = data[area_col].apply(country_to_code)
        data.set_index(area_col, inplace=True)

    if data.index.name != area_col:
        data.set_index(area_col, inplace=True)

    # filter data based on geo codes
    gc = GeonamesCache()
    iso3_codes = list(gc.get_dataset_by_key(gc.get_countries(), 'iso3').keys())
    data = data.loc[iso3_codes]
    data = data[~data[value_col].isna()]
    data[value_col] = data[value_col].astype(int)

    # set plot stuff
    values = data[value_col].dropna()

    if log == True:
        values = np.log1p(values)
        data[value_col] = np.log(data[value_col])

    if bin_mode == 'linear':
        bins = np.linspace(values.min(), values.max(), num_colors)
    elif bin_mode == 'quantile':
        bins = np.nanpercentile(values, np.arange(0,
github yaph / d3-geomap / scripts / topo_countries.py View on Github external
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
from geonamescache import GeonamesCache

gc = GeonamesCache()
toposrc = 'data/states-provinces.json'

for iso2, country in gc.get_countries().items():
    iso3 = country['iso3']

    topojson = 'mapshaper -i {0} -filter \'"{1}" == adm0_a3\' -filter-fields fips,name -o format=topojson dist/topojson/countries/{1}.json'
    subprocess.call(topojson.format(toposrc, iso3), shell=True)
github yaph / ip-location-maps / continentmaps.py View on Github external
import geonamescache
import csv

import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

gc = geonamescache.GeonamesCache()
#FIXME use data from http://www.flickr.com/places/info/24865672
geocontinents = gc.get_continents()
geocountries = gc.get_countries()
continents = {}

with open('data/GeoLiteCity-Location.csv', 'rb') as csvin:
#with open('data/geotest.csv', 'rb') as csvin:
    reader = csv.reader(csvin)
    next(reader)  # copyright notice
    next(reader)  # headings

    for row in reader:
        iso = row[1]
        # records can have 01, AP, EU, A1, A2 as country
        if iso not in geocountries:
            continue
github yaph / geonamescache / scripts / countries2csv.py View on Github external
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
from geonamescache import GeonamesCache

gc = GeonamesCache()
countries = gc.get_countries()
df = pd.DataFrame.from_dict(countries, orient='index')
df.to_csv('geonamescache/countries.csv', index=False)
github yaph / geonamescache / geonamescache / mappers.py View on Github external
def country(from_key='name', to_key='iso'):
    """Creates and returns a mapper function to access country data.

    The mapper function that is returned must be called with one argument. In
    the default case you call it with a name and it returns a 3-letter
    ISO_3166-1 code, e. g. called with ``Spain`` it would return ``ESP``.

    :param from_key: (optional) the country attribute you give as input.
        Defaults to ``name``.
    :param to_key: (optional) the country attribute you want as output.
        Defaults to ``iso``.
    :return: mapper
    :rtype: function
    """

    gc = GeonamesCache()
    dataset = gc.get_dataset_by_key(gc.get_countries(), from_key)

    def mapper(input):
        # For country name inputs take the names mapping into account.
        if 'name' == from_key:
            input = mappings.country_names.get(input, input)
        # If there is a record return the demanded attribute.
        item = dataset.get(input)
        if item:
            return item[to_key]

    return mapper