Example #1
0
def get_names(locations):
    """Returns a set of possible location names from the Mapquest results"""
    names = {"street": set(),
             "adminArea6": set(),
             "adminArea5": set(),
             "adminArea4": set(),
             "adminArea3": set(),
             "adminArea2": set(),
             "adminArea1": set(),
             "name": set()}
    
    for location in locations:
        for field in names:
            if field in location and location[field] != "":
                if field == "adminArea1":
                    names[field].add(countries.get(alpha_2=location[field]).name)
                elif field == "adminArea3":
                    names[field].add(subdivisions.get(code = "{0}-{1}".format(
                        countries.get(alpha_2 = location["adminArea1"]),
                        location[field]
                    )))
                else:
                    names[field].add(location[field])

    return names
Example #2
0
def is_valid_country_code(code):
    if code == NO_COUNTRY:
        return True
    try:
        countries.get(alpha2=code)
        return True
    except KeyError:
        return False
Example #3
0
def is_valid_country_code(code):
    if code == NO_COUNTRY:
        return True
    try:
        countries.get(alpha2=code)
        return True
    except KeyError:
        return False
Example #4
0
 def to_code(country, code_len=2):
     try:
         if code_len == 3:
             return countries.get(name=country).alpha_3
         else:
             return countries.get(name=country).alpha_2
     except KeyError:
         return 'country not found'
Example #5
0
 def to_name(code):
     try:
         if len(code) == 2:
             return countries.get(alpha_2=code).name
         elif len(code) == 3:
             return countries.get(alpha_3=code).name
         else:
             return 'invalid country code'
     except KeyError:
         return 'country code does not match a known country'
Example #6
0
def country_iso_to_name(country_iso_or_name):
    country_name = country_iso_or_name
    if country_iso_or_name:
        try:
            country_name = countries.get(alpha2=country_iso_or_name).name
        except KeyError:
            try:
                country_name = countries.get(name=country_iso_or_name).name
            except KeyError:
                pass
    return country_name
Example #7
0
    def get(cls,
            alpha3=None,
            alpha2=None,
            name=None,
            numeric=None,
            official_name=None):
        """Load a `Country` with the given parameter.

        Passed values will take precedence in this order: alpha3, alpha2,
        name, official_name, numeric. The first argument in that order to
        contain data will be used, and all others will not be used.

        Args:
            alpha3: The alpha3 code of the `Country` to load.
            alpha2: The alpha2 code of the `Country` to load.
            name: The name of the `Country` to load. Note: This needs to be
                as it is in the ISO 3166-1 standard, so "Taiwan" needs to be
                "Taiwan, Province of China" and "Palestine" needs to be
                "Palestine, State of", even though we alter them in the
                property `Country.name`.
            official_name: The official name of the `Country` to load.
            numeric: The numeric of the `Country` to load.

        Returns:
            The `Country` from the database with the given data.
        """
        if alpha3:
            pass
        elif alpha2:
            try:
                alpha3 = countries.get(alpha2=alpha2).alpha3
            except KeyError:
                return None
        elif name:
            try:
                alpha3 = countries.get(name=name).alpha3
            except KeyError:
                return None
        elif numeric:
            try:
                alpha3 = countries.get(numeric=numeric).alpha3
            except KeyError:
                return None
        elif official_name:
            try:
                alpha3 = countries.get(official_name=official_name).alpha3
            except KeyError:
                return None
        return cls.query.filter(cls.alpha3 == alpha3.upper()).one_or_none()
Example #8
0
def alpha_2(code: str):
    """
        Validates that the given `code` is a valid alpha-2 country code.
    Full list of valid codes at https://www.iso.org/obp/ui/#search/code.

    Parameters
    ----------
    code: str
        Code to validate.

    Examples
    -------
    >>> alpha_2("CZ")      # ✅️
    >>> alpha_2("XX")      # ❌️
    >>> alpha_2("ARG")     # ❌️
    >>> alpha_2(123)       # ❌️

    Raises
    -------
    nintendeals.exceptions.InvalidAlpha2Code
        The `code` wasn't a valid alpha-2 code.
    """
    country = countries.get(alpha_2=code)

    if not country:
        raise InvalidAlpha2Code(code)
Example #9
0
def test_bic_properties():
    bic = BIC("GENODEM1GLS")
    assert bic.length == 11
    assert bic.bank_code == "GENO"
    assert bic.country_code == "DE"
    assert bic.location_code == "M1"
    assert bic.branch_code == "GLS"
    assert bic.domestic_bank_codes == ["43060967", "43060988"]
    assert bic.bank_names == [
        "GLS Gemeinschaftsbank",
        "GLS Gemeinschaftsbank (GAA)",
    ]
    assert bic.bank_short_names == [
        "GLS Bank in Bochum (GAA)",
        "GLS Gemeinschaftsbk Bochum",
    ]
    assert bic.country == countries.get(alpha_2="DE")
    with pytest.warns(DeprecationWarning):
        assert bic.bank_name == "GLS Gemeinschaftsbank"
    with pytest.warns(DeprecationWarning):
        assert bic.bank_short_name == "GLS Bank in Bochum (GAA)"
    with pytest.warns(DeprecationWarning):
        assert bic.country_bank_code == "43060967"
    assert bic.exists
    assert bic.type == "passive"
Example #10
0
def iplookup(ipaddr):
    try:
        info = ipwhois.IPWhois(ipaddr).lookup_whois()
    except Exception as e:
        return {
            'country': 'Unknown',
            'isp': 'Unknown',
            'asn_cidr': 'Private-Use Networks',
            'asn_description': 'Private-Use Networks'
        }

# city = info['nets'][0]['city']?info['nets'][0]['city']:""
    city = (info['nets'][0]['city'] if (info['nets'][0]['city']) else "")
    country = countries.get(alpha_2=info['nets'][0]['country'])
    if city:
        countryname = country.name + '/' + city
    else:
        countryname = country.name
    if info['nets'][0]['description']:
        temp = info['nets'][0]['description'].splitlines()
        ipinfo = {
            'country': countryname,
            'isp': temp[0],
            'asn_cidr': info['asn_cidr'],
            'asn_description': info['asn_description']
        }
    else:
        ipinfo = {
            'country': countryname,
            'isp': 'Not Found',
            'asn_cidr': info['asn_cidr'],
            'asn_description': info['asn_description']
        }
    return ipinfo
Example #11
0
def participants(event):
    m = Meeting.get(id=event, post_type=MeetingPostType.MEETING.value)
    if not m:
        return redirect(url_for('.blog'))

    subs = Subscription.select(lambda x: x.meeting == m).order_by(
        Subscription.id.desc())
    users = {
        x.id: x
        for x in left_join(
            x for x in User for s in x.subscriptions if s.meeting == m)
    }

    data = [
        dict(type=x.type.fancy,
             status=ProfileStatus(users[x.user.id].status).fancy,
             country=countries.get(alpha_3=users[x.user.id].country).name,
             user=users[x.user.id].full_name,
             useid=x.user.id) for x in subs
    ]
    return render_template('participants.html',
                           data=data,
                           title=m.title,
                           subtitle='Participants',
                           crumb=dict(url=url_for('.blog_post', post=event),
                                      title='Participants',
                                      parent='Event main page'))
Example #12
0
    def test_subdivision_derived_fields(self) -> None:
        address = Address(
            line1="31, place du Théatre",
            postal_code="59000",
            city_name="Lille",
            subdivision_code="FR-59",
        )

        assert address.subdivision == subdivisions.get(code="FR-59")
        assert address.subdivision_code == "FR-59"
        assert address.subdivision_name == "Nord"
        assert address.subdivision_type_name == "Metropolitan department"
        assert address.subdivision_type_id == "metropolitan_department"

        assert address.metropolitan_department == subdivisions.get(
            code="FR-59")
        assert address.metropolitan_department_area_code == "FR-59"
        assert address.metropolitan_department_name == "Nord"
        assert address.metropolitan_department_type_name == "Metropolitan department"

        assert address.metropolitan_region == subdivisions.get(code="FR-HDF")
        assert address.metropolitan_region_area_code == "FR-HDF"
        assert address.metropolitan_region_name == "Hauts-de-France"
        assert address.metropolitan_region_type_name == "Metropolitan region"

        assert address.country == countries.get(alpha_2="FR")
        assert address.country_code == "FR"
        assert address.country_name == "France"
Example #13
0
    def dump_common(j):
        if show_path:
            click.echo(" |    |   Path: %s" % j.path)

        person = [j for j in (j.given_name, j.surname) if j]
        if person:
            click.echo(" |    |   Associated person: %s" % " ".join(person) + (" <%s>" % j.email_address if j.email_address else ""))
        elif j.email_address:
            click.echo(" |    |   Associated e-mail: " + j.email_address)

        bits = [j for j in (
            countries.get(alpha2=j.country_code.upper()).name if
            j.country_code else "",
            j.state_or_county,
            j.city,
            j.organization,
            j.organizational_unit) if j]
        if bits:
            click.echo(" |    |   Organization: %s" % ", ".join(bits))

        if show_key_type:
            click.echo(" |    |   Key type: %s-bit %s" % (j.key_length, j.key_type))

        if show_extensions:
            for key, value, data in j.extensions:
                click.echo((" |    |   Extension " + key + ":").ljust(50) + " " + value)
        elif j.key_usage:
            click.echo(" |    |   Key usage: " + j.key_usage)
        click.echo(" |    |")
Example #14
0
    def test_subdivision_derived_fields(self):
        address = Address(line1='31, place du Théatre',
                          postal_code='59000',
                          city_name='Lille',
                          subdivision_code='FR-59')

        self.assertEquals(address.subdivision, subdivisions.get(code='FR-59'))
        self.assertEquals(address.subdivision_code, 'FR-59')
        self.assertEquals(address.subdivision_name, 'Nord')
        self.assertEquals(address.subdivision_type_name,
                          'Metropolitan department')
        self.assertEquals(address.subdivision_type_id,
                          'metropolitan_department')

        self.assertEquals(address.metropolitan_department,
                          subdivisions.get(code='FR-59'))
        self.assertEquals(address.metropolitan_department_area_code, 'FR-59')
        self.assertEquals(address.metropolitan_department_name, 'Nord')
        self.assertEquals(address.metropolitan_department_type_name,
                          'Metropolitan department')

        self.assertEquals(address.metropolitan_region,
                          subdivisions.get(code='FR-HDF'))
        self.assertEquals(address.metropolitan_region_area_code, 'FR-HDF')
        self.assertEquals(address.metropolitan_region_name, 'Hauts-de-France')
        self.assertEquals(address.metropolitan_region_type_name,
                          'Metropolitan region')

        self.assertEquals(address.country, countries.get(alpha_2='FR'))
        self.assertEquals(address.country_code, 'FR')
        self.assertEquals(address.country_name, 'France')
Example #15
0
def territory_parents(territory_code, include_country=True):
    """ Return the whole hierarchy of territories, up to the country.

    Values returned by the generator are either subdivisions or country
    objects, starting from the provided territory and up its way to the top
    administrative territory (i.e. country).
    """
    tree = []

    # Retrieving subdivision from alias to get full paternity
    territory_code = COUNTRY_ALIAS_TO_SUBDIVISION.get(territory_code,
                                                      territory_code)
    # If the provided territory code is a country, return it right away.
    territory_code = normalize_territory_code(territory_code)
    if territory_code in supported_country_codes():
        if include_country:
            tree.append(countries.get(alpha_2=territory_code))
        return tree

    # Else, resolve the territory as if it's a subdivision code.
    subdivision_code = territory_code
    while subdivision_code:
        subdiv = subdivisions.get(code=subdivision_code)
        tree.append(subdiv)
        if not subdiv.parent_code:
            break
        subdivision_code = subdiv.parent_code

    # Return country
    if include_country:
        tree.append(subdivisions.get(code=subdivision_code).country)

    return tree
Example #16
0
def territory_parents(territory_code, include_country=True):
    """ Return the whole hierarchy of territories, up to the country.

    Values returned by the generator are either subdivisions or country
    objects, starting from the provided territory and up its way to the top
    administrative territory (i.e. country).
    """
    tree = []

    # If the provided territory code is a country, return it right away.
    territory_code = normalize_territory_code(territory_code)
    if territory_code in supported_country_codes():
        if include_country:
            tree.append(countries.get(alpha2=territory_code))
        return tree

    # Else, resolve the territory as if it's a subdivision code.
    subdivision_code = territory_code
    while subdivision_code:
        subdiv = subdivisions.get(code=subdivision_code)
        tree.append(subdiv)
        if not subdiv.parent_code:
            break
        subdivision_code = subdiv.parent_code

    # Return country
    if include_country:
        tree.append(subdivisions.get(code=subdivision_code).country)

    return tree
Example #17
0
    def dump_common(j):
        if show_path:
            click.echo(" |    |   Path: %s" % j.path)

        person = [j for j in (j.given_name, j.surname) if j]
        if person:
            click.echo(" |    |   Associated person: %s" % " ".join(person) +
                       (" <%s>" % j.email_address if j.email_address else ""))
        elif j.email_address:
            click.echo(" |    |   Associated e-mail: " + j.email_address)

        bits = [
            j for j in (countries.get(
                alpha2=j.country_code.upper()).name if j.country_code else "",
                        j.state_or_county, j.city, j.organization,
                        j.organizational_unit) if j
        ]
        if bits:
            click.echo(" |    |   Organization: %s" % ", ".join(bits))

        if show_key_type:
            click.echo(" |    |   Key type: %s-bit %s" %
                       (j.key_length, j.key_type))

        if show_extensions:
            for key, value, data in j.extensions:
                click.echo((" |    |   Extension " + key + ":").ljust(50) +
                           " " + value)
        elif j.key_usage:
            click.echo(" |    |   Key usage: " + j.key_usage)
        click.echo(" |    |")
Example #18
0
 def validate_country(value):
     """
     Validate country alpha_2 code
     """
     if not countries.get(alpha_2=value):
         raise serializers.ValidationError("Invalid country code")
     return value
Example #19
0
def getpartsandholesfromcountry(filename):
  name = splitext(basename(filename))[0]
  fullname = name
  iso = re.search(r'[A-Z]{3}', name)
  if iso:
    fullname = countries.get(alpha_3=iso.group(0))
    fullname = (fullname.name or fullname.official_name).replace("'", "\\'") if fullname else filename
  return (fullname, getpartsandholesfromfile(filename))
Example #20
0
 def country_name(self, name):
     if not name:
         self.set_value()
         return
     country = countries.get(name=name)
     if not country:
         raise UnknownCountryNameError(name)
     self.set_value(countryCode=country.alpha_2, countryName=country.name)
Example #21
0
    def validate(self):
        """ Check fields consistency and requirements in one go.

        Properly check that fields are consistent between themselves, and only
        raise an exception at the end, for the whole address object. Our custom
        exception will provide a detailed status of bad fields.
        """
        # Keep a classification of bad fields along the validation process.
        required_fields = set()
        invalid_fields = set()
        inconsistent_fields = set()

        # Check that all required fields are set.
        for field_id in self.REQUIRED_FIELDS:
            if not getattr(self, field_id):
                required_fields.add(field_id)

        # Check all fields for invalidity, only if not previously flagged as
        # required.
        if 'country_code' not in required_fields:
            # Check that the country code exists.
            try:
                countries.get(alpha2=self.country_code)
            except KeyError:
                invalid_fields.add('country_code')
        if self.subdivision_code and 'subdivision_code' not in required_fields:
            # Check that the country code exists.
            try:
                subdivisions.get(code=self.subdivision_code)
            except KeyError:
                invalid_fields.add('subdivision_code')

        # Check country consistency against subdivision, only if none of the
        # two fields were previously flagged as required or invalid.
        if self.subdivision_code and not set(
                ['country_code', 'subdivision_code']).intersection(
                    required_fields.union(invalid_fields)) and \
                country_from_subdivision(
                    self.subdivision_code) != self.country_code:
            inconsistent_fields.add(
                tuple(sorted(('country_code', 'subdivision_code'))))

        # Raise our custom exception at last.
        if required_fields or invalid_fields or inconsistent_fields:
            raise InvalidAddress(
                required_fields, invalid_fields, inconsistent_fields)
    def validate(self):
        """ Check fields consistency and requirements in one go.

        Properly check that fields are consistent between themselves, and only
        raise an exception at the end, for the whole address object. Our custom
        exception will provide a detailed status of bad fields.
        """
        # Keep a classification of bad fields along the validation process.
        required_fields = set()
        invalid_fields = dict()
        inconsistent_fields = set()

        # Check that all required fields are set.
        for field_id in self.REQUIRED_FIELDS:
            if not getattr(self, field_id):
                required_fields.add(field_id)

        # Check all fields for invalidity, only if not previously flagged as
        # required.
        if 'country_code' not in required_fields:
            # Check that the country code exists.
            try:
                countries.get(alpha_2=self.country_code)
            except KeyError:
                invalid_fields['country_code'] = self.country_code
        if self.subdivision_code and 'subdivision_code' not in required_fields:
            # Check that the country code exists.
            try:
                subdivisions.get(code=self.subdivision_code)
            except KeyError:
                invalid_fields['subdivision_code'] = self.subdivision_code

        # Check country consistency against subdivision, only if none of the
        # two fields were previously flagged as required or invalid.
        if self.subdivision_code and not set(
                ['country_code', 'subdivision_code']).intersection(
                    required_fields.union(invalid_fields)) and \
                country_from_subdivision(
                    self.subdivision_code) != self.country_code:
            inconsistent_fields.add(
                tuple(sorted(('country_code', 'subdivision_code'))))

        # Raise our custom exception at last.
        if required_fields or invalid_fields or inconsistent_fields:
            raise InvalidAddress(required_fields, invalid_fields,
                                 inconsistent_fields)
Example #23
0
 def ui_convcountry(c):
     if c is not None:
         if len(c) == 2:
             return countries.get(alpha_2=c).name
         else:
             return c
     else:
         return "N/A"
Example #24
0
def get_city_full_name(city_name, country_name):
    try:
        country = countries.get(name=country_name).alpha_2
        city = city_name + ',' + country
        return city
    except AttributeError:
        print('ISO 3166 country code for ' + city_name +
              ' is not available in database')
        return city_name
Example #25
0
 def validate_alpha2(alpha_2):
     """
     Validate that alpha 2 code is valid
     :param alpha_2: alpha 2 code from ISO3166
     """
     if countries.get(alpha_2=alpha_2):
         return alpha_2
     else:
         raise serializers.ValidationError('Invalid country alpha_2')
Example #26
0
def get_trip_queryset(loc=None, id_list=None):
    city = loc.split(',')[0]
    state_country = loc.split(', ')[1]
    if len(state_country) > 2:
        state_country = countries.get(name=state_country).alpha_2

    criteria = Q(traveler_id__in=id_list) & (
               Q(city__icontains=city) & (
               Q(state__icontains=state_country) | Q(country__icontains=state_country)))
    return Trips.objects.filter(criteria)
Example #27
0
def test_iban_properties():
    iban = IBAN("DE42430609677000534100")
    assert iban.bank_code == "43060967"
    assert iban.branch_code == ""
    assert iban.account_code == "7000534100"
    assert iban.country_code == "DE"
    assert iban.bic == "GENODEM1GLS"
    assert iban.formatted == "DE42 4306 0967 7000 5341 00"
    assert iban.length == 22
    assert iban.country == countries.get(alpha_2="DE")
Example #28
0
def to_official_name(country_name):
    """Given a human name for a country, return its full official name"""
    try:
        country = countries.get(alpha_2=to_code(country_name))
        if hasattr(country, "official_name"):
            return country.official_name
        else:
            return country.name
    except LookupError:
        return None
Example #29
0
 def country(self, country: str) -> None:
     if country in custom_countries:
         self._country_index = country
     else:
         zfilled_country = country.zfill(3)
         # only allow to set indexes which are known
         try:
             self._country_index = countries.get(
                 numeric=zfilled_country).numeric
         except KeyError:
             pass
 def map_country_traffic(row):
     try:
         row_obj = dict()
         if row[0] != u'(not set)':
             country = countries.get(name=row[0])
             row_obj['code'] = country.alpha_2
         row_obj['name'] = row[0]
         row_obj['value'] = row[1]
         return row_obj
     except Exception, e:
         pass
Example #31
0
 def get(self, country_alpha2: str):
     """
     Returns a country record.
     :param country_alpha2: The unique two character identifier of the country record.
     :type country_alpha2: str
     :return:
     """
     try:
         return countries.get(alpha_2=country_alpha2)
     except KeyError:
         abort(404, 'Country not found')
Example #32
0
def user_edit_page():
    from app.models.userdata import UserDataDB

    userdata = UserDataDB.query.filter_by(username=current_user.username).first()
    form = UserDataForm(username=userdata.username,
                        stream=userdata.stream,
                        interview_location=userdata.interview_location,
                        from_full=userdata.from_short,
                        interview_date=userdata.interview_date,
                        invitation_to_apply_date=userdata.invitation_to_apply_date,
                        mpnp_file_date=userdata.mpnp_file_date,
                        mpnp_request_additional_docs_date=userdata.mpnp_request_additional_docs_date,
                        mpnp_nomination_date=userdata.mpnp_nomination_date,
                        cio_received_date=userdata.cio_received_date,
                        cio_processing_fee_date=userdata.cio_processing_fee_date,
                        cio_file_number=userdata.cio_file_number,
                        embassy=userdata.embassy,
                        ecas_recieved=userdata.ecas_recieved,
                        ecas_in_process=userdata.ecas_in_process,
                        ecas_additional_documents_request1=userdata.ecas_additional_documents_request1,
                        ecas_medical_forms=userdata.ecas_medical_forms,
                        ecas_medical_exam_passed=userdata.ecas_medical_exam_passed,
                        ecas_medical_results_received=userdata.ecas_medical_results_received,
                        ecas_additional_documents_request2=userdata.ecas_additional_documents_request2,
                        povl_date=userdata.povl_date)

    if request.method == 'POST':
        from app import db
        user_data = UserDataDB.query.filter_by(username=current_user.username)
        user_data.update(dict(
            from_full=countries.get(alpha2=form.from_full.data).name,
            from_short=form.from_full.data,
            stream=form.stream.data,
            interview_location=form.interview_location.data,
            interview_date=form.interview_date.data,
            invitation_to_apply_date=form.invitation_to_apply_date.data,
            mpnp_file_date=form.mpnp_file_date.data,
            mpnp_request_additional_docs_date=form.mpnp_request_additional_docs_date.data,
            mpnp_nomination_date=form.mpnp_nomination_date.data,
            cio_received_date=form.cio_received_date.data,
            cio_processing_fee_date=form.cio_processing_fee_date.data,
            cio_file_number=form.cio_file_number.data,
            embassy=form.embassy.data,
            ecas_recieved=form.ecas_recieved.data,
            ecas_in_process=form.ecas_in_process.data,
            ecas_additional_documents_request1=form.ecas_additional_documents_request1.data,
            ecas_medical_forms=form.ecas_medical_forms.data,
            ecas_medical_exam_passed=form.ecas_medical_exam_passed.data,
            ecas_medical_results_received=form.ecas_medical_results_received.data,
            ecas_additional_documents_request2=form.ecas_additional_documents_request2.data,
            povl_date=form.povl_date.data))
        db.session.commit()
        return redirect(url_for('user.show_user_page', _id=user_data.first().id))
    return render_template('user_page_edit.jinja2.html', userdata=userdata, form=form)
Example #33
0
def country_code_update(df):
    """
    change the country names to ISO alpha_2 country code

    # all cruise ship cases have been removed
    # West Bank and Gaza region is considered as part of Palestine (PS)
    # Taiwan is considered separately from China here, for it has potentially different data collection procedure.
    # XK represents Kosovo (XK, XKX, while Kosovo is not listed as an ISO standard country.
    #   The unofficial 2 and 3-digit codes are used by the European Commission and others,
    #   until Kosovo is assigned an ISO code.
    """
    from pycountry import countries as ct
    new_df = country_grouping(df)
    # country names in the data set that are not fit ISO standard
    completion = pd.DataFrame(np.array([['Bolivia', 'BO'], ['Brunei', 'BN'],
                                        ['Congo (Brazzaville)', 'CG'],
                                        ['Congo (Kinshasa)', 'CD'],
                                        ['Cote d\'Ivoire', 'CI'],
                                        ['Holy See', 'VA'], ['Iran', 'IR'],
                                        ['Korea, South', 'KR'],
                                        ['Moldova', 'MD'], ['Russia', 'RU'],
                                        ['Taiwan*', 'TW'], ['Tanzania', 'TZ'],
                                        ['US', 'US'], ['Venezuela', 'VE'],
                                        ['Vietnam', 'VN'], ['Syria', 'SY'],
                                        ['Laos', 'LA'],
                                        ['West Bank and Gaza', 'PS'],
                                        ['Kosovo', 'XK'], ['Burma', 'MM']]),
                              columns=['c_name', 'c_code'])
    country_code_list = []
    for country_name in new_df['Country/Region']:
        try:
            if country_name in completion['c_name'].tolist():
                # print('exception covered: ', country_name)
                country_code = completion['c_code'].loc[completion['c_name'] ==
                                                        country_name].item()
            # identifies the cruise ships in the data set considered as a 'country'
            elif country_name == 'Diamond Princess' or country_name == 'MS Zaandam':
                country_code = 'Cruise Ship'
            else:
                country_code = ct.get(name=country_name).alpha_2
        except KeyError:
            print('no result: ', country_name)
            country_code = 'None'
            pass
        country_code_list.append(country_code)
    # print(country_code_list)
    new_df.insert(0, "country_code", country_code_list, True)
    new_df = new_df.drop(columns='Country/Region')
    unknown_index = new_df[new_df['country_code'] == 'Cruise Ship'].index
    new_df.drop(
        unknown_index, inplace=True
    )  # drop when country_code = 'None', most likely are Cruise ships
    # new_df.set_index(new_df['country_code'])
    return new_df
Example #34
0
    def validate_fhir_address(self):
        if self.values.type:
            url = ADDRESS_TYPE_URL + "?code=" + self.values.type
            validate_valuesets(self.values.type, url, "address type")

        if self.values.use:
            url = ADDRESS_USE_URL + "?code=" + self.values.use
            validate_valuesets(self.values.use, url, "address use")

        if self.values.country:
            country_code = self.values.country

            # Check that the code is a recommended ISO 3166 3letter code
            try:
                countries.get(alpha3=country_code)
            except Exception:
                msg = ("This country code is not recommended. "
                       "Please use an ISO 3166 3letter country code")
                warnings.warn(msg, UserWarning)

        return self.values
Example #35
0
 def __init__(self, alpha_2):
     """
     Init a Country object with an alpha2 code
     :params country_name: ISO-3166 alpha_2 code
     """
     country = countries.get(alpha_2=alpha_2)
     if not country:
         raise CountryNotFoundError("Invalid country alpha2 code")
     self.alpha_2 = country.alpha_2
     self.alpha_3 = country.alpha_3
     self.name = country.name
     self.numeric = country.numeric
Example #36
0
 def get(cls, country):
     try:
         if PYCOUNTRY:
             c = countries.lookup(country)
             return Country(c.alpha_2, c.alpha_3, c.numeric, c.name,
                            getattr(c, "official_name", c.name))
         else:
             c = countries.get(country)
             return Country(c.alpha2, c.alpha3, c.numeric, c.name,
                            c.apolitical_name)
     except (LookupError, KeyError):
         raise LookupError("Invalid country code: {0}".format(country))
Example #37
0
    def check_invalid_fields(self, required_fields):
        """Check all fields for invalidity, only if not previously flagged as
        required.

        :param required_fields:
        :return:
        """
        invalid_fields = dict()
        if 'country_code' not in required_fields:
            # Check that the country code exists.
            try:
                countries.get(alpha_2=self.country_code)
            except KeyError:
                invalid_fields['country_code'] = self.country_code

        if self.subdivision_code and 'subdivision_code' not in required_fields:
            # Check that the country code exists.
            try:
                subdivisions.get(code=self.subdivision_code)
            except KeyError:
                invalid_fields['subdivision_code'] = self.subdivision_code
        return invalid_fields
Example #38
0
 def phone_info(self):
     """ Get phone number information.
     """
     try:
         number = parse(self.phone)
         region = pnu.region_code_for_country_code(number.country_code)
         return {
             'number': number,
             'valid': pnu.is_valid_number(number),
             'country': countries.get(alpha2=region),
         }
     except pnu.NumberParseException:
         return {}
Example #39
0
    def __init__(self, country_code, *args, **kwargs):
        super(ParserWithProxy, self).__init__(*args, **kwargs)

        self.country = countries.get(alpha2=country_code)
        self.proxies = []
        self.used_proxies = set()

        self.grab = None
        self.grab_use_count = None

        self.reinit_grab()

        self.setup_queue(getattr(config, 'QUEUE_BACKEND', 'memory'))
        if getattr(config, 'CACHE_ENABLED', False):
            self.setup_cache('mongo', getattr(config, 'CACHE_DATABASE', 'cache'))
Example #40
0
    def test_subdivision_derived_fields(self):
        address = Address(
            line1='31, place du Théatre',
            postal_code='59000',
            city_name='Lille',
            subdivision_code='FR-59')

        self.assertEquals(
            address.subdivision, subdivisions.get(code='FR-59'))
        self.assertEquals(
            address.subdivision_code, 'FR-59')
        self.assertEquals(
            address.subdivision_name, 'Nord')
        self.assertEquals(
            address.subdivision_type_name, 'Metropolitan department')
        self.assertEquals(
            address.subdivision_type_id, 'metropolitan_department')

        self.assertEquals(
            address.metropolitan_department, subdivisions.get(code='FR-59'))
        self.assertEquals(
            address.metropolitan_department_code, 'FR-59')
        self.assertEquals(
            address.metropolitan_department_name, 'Nord')
        self.assertEquals(
            address.metropolitan_department_type_name,
            'Metropolitan department')

        self.assertEquals(
            address.metropolitan_region, subdivisions.get(code='FR-O'))
        self.assertEquals(
            address.metropolitan_region_code, 'FR-O')
        self.assertEquals(
            address.metropolitan_region_name, 'Nord - Pas-de-Calais')
        self.assertEquals(
            address.metropolitan_region_type_name,
            'Metropolitan region')

        self.assertEquals(
            address.country, countries.get(alpha2='FR'))
        self.assertEquals(
            address.country_code, 'FR')
        self.assertEquals(
            address.country_name, 'France')
Example #41
0
def convert_bucket(facet, bucket):
    key = bucket.get('key_as_string', bucket.get('key'))
    data = {
        'count': bucket.get('doc_count'),
        'id': key,
        'label': key,
    }

    if facet == 'languages':
        try:
            locale = Locale(key.strip().lower())
            data['label'] = locale.get_display_name('en_US')
        except:
            pass
    elif facet == 'countries' and key is not None:
        try:
            country = countries.get(alpha2=key.strip().upper())
            data['label'] = country.name
        except:
            pass
    return data
Example #42
0
def signup_page():
    form = SignUpForm()
    if request.method == 'GET':
        return render_template('signup.jinja2.html', form=form)
    if request.method == 'POST' and form.validate() and validate_new_user(form.login.data, form.password.data,
                                                                                   form.confirm.data):
        user_data = UserDataDB.query.filter_by(username=form.login.data)
        if len(user_data.all()) == 0:
            if sessions.new_user(form.login.data, form.email.data, form.password.data):
                user_data = UserDataDB(username=form.login.data, from_full=countries.get(alpha2=form.country.data).name,
                                       from_short=form.country.data)
                db.session.add(user_data)
                db.session.commit()
                user = User.query.filter_by(username=form.login.data).first()
                login_user(user)
                return redirect(url_for('user.show_user_page', _id=user.id))
        else:
            sessions.new_user(form.login.data, form.email.data, form.password.data, _id=user_data.first().id)
            user = User.query.filter_by(username=form.login.data).first()
            login_user(user)
            return redirect(url_for('user.show_user_page', _id=user.id))
    else:
        return render_template('signup.jinja2.html', form=form)
Example #43
0
table = doc.tables[1]
for i, row in enumerate(table.rows[1:]):
    # print(i)
    # if i < 0:
    #    continue
    countryname = row.cells[0].paragraphs[0].text
    if countryname in transform:
        countryname = transform[countryname]
    network = row.cells[1].paragraphs[0].text
    mccmnc = row.cells[2].paragraphs[0].text
    if mccmnc:
        mcc, mnc = mccmnc.split(' ')
        try:
            mcc = int(mcc)
            mnc = int(mnc)
            country = countries.get(name=countryname)
            print('{} ({}): {} - {}'.format(countryname, country.alpha2,
                                            mccmnc, network))
            networkdict[mcc][mnc] = (country.alpha2, network)
        except ValueError:
            pass


operators = {k: dict(v) for k, v in networkdict.items()}

countries = defaultdict(list)
for mcc, mncs in operators.items():
    for mnc, c in mncs.items():
        countries[c[0]].append((mcc, mnc))
countries = {k: v for k, v in countries.items()}
Example #44
0
 def country(self):
     """ Return country object. """
     if self.country_code:
         return countries.get(alpha_2=self.country_code)
     return None
Example #45
0
def create_countries_dict():
    country_dict = [('', '')]
    for country_ in COUNTRIES:
        country_dict.append((country_, countries.get(alpha2=country_).name))
    return country_dict
Example #46
0
def lookup_country(code):
    if code == 'XK':
        return 'Kosovo'
    return countries.get(alpha2=code).name
Example #47
0
def create_countries_dict():
    country_dict = []
    for _country in COUNTRIES:
        country_dict.append((_country, countries.get(alpha2=_country).name))
    return country_dict
Example #48
0
 def _country(self):
     """pycountry.db.Country: A cached object with country data."""
     if not self._cached:
         self._cached = countries.get(alpha3=self.alpha3)
     return self._cached
Example #49
0
def test_verify_iso3166():
    for c in filter(exempt, flatten(mapping)):
        country = countries.get(alpha2=c)
        assert country
        assert country.alpha2 == c
Example #50
0
def parse_args(currency_options, names):
	c, n = currency_options
	b_curr, d_curr =  names

	# checks for currency names instead of ISO 4217 codes
	if c:
		# large import, only do so if necessary
		from pycountry import currencies
		# which args are NOT ISO 4217 Codes
		cond1 = not len(b_curr) == 3
		cond2 = not len(d_curr) == 3
		
		# both
		if cond1 and cond2:
			ISO_code = str(currencies.get(name=b_curr).letter)
			b_curr = ISO_code
			ISO_code = str(currencies.get(name=d_curr).letter)
			d_curr = ISO_code
		
		# just base currency
		elif cond1:
			ISO_code = str(currencies.get(name=b_curr).letter)
			b_curr = ISO_code
		
		# just desired currency
		elif cond2:
			ISO_code = str(currencies.get(name=d_curr).letter)
			d_curr = ISO_code


	if n:
		# large import, so only do so if necessary
		from pycountry import countries, currencies
		# which args are NOT ISO 4217 Codes
		cond1 = not len(b_curr) == 3
		cond2 = not len(d_curr) == 3

		# both
		if cond1 and cond2:
			country = countries.get(name=b_curr)
			numeric = str(country.numeric)
			
			if numeric in eurozone_numeric:
				b_curr = 'EUR'
			else:
				ISO_code = str(currencies.get(numeric=numeric).letter)
				b_curr = ISO_code
			
			country = countries.get(name=d_curr)
			numeric = str(country.numeric)
			if numeric in eurozone_numeric:
				d_curr = 'EUR'
			else:
				ISO_code = str(currencies.get(numeric=numeric).letter)
				d_curr = ISO_code

		# just base currency	
		elif cond1:
			country = countries.get(name=b_curr)
			numeric = str(country.numeric)
			if numeric in eurozone_numeric:
				b_curr = 'EUR'
			else:
				ISO_code = str(currencies.get(numeric=numeric).letter)
				b_curr = ISO_code

		# just target currency
		elif cond2:
			country = countries.get(name=d_curr)
			numeric = str(country.numeric)
			if numeric in eurozone_numeric:
				d_curr = 'EUR'
			else:
				ISO_code = str(currencies.get(numeric=numeric).letter)
				d_curr = ISO_code

	return b_curr, d_curr