repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
number_type
def number_type(numobj): """Gets the type of a valid phone number. Arguments: numobj -- The PhoneNumber object that we want to know the type of. Returns the type of the phone number, as a PhoneNumberType value; returns PhoneNumberType.UNKNOWN if it is invalid. """ region_code = region_code_for_number(numobj) metadata = PhoneMetadata.metadata_for_region_or_calling_code(numobj.country_code, region_code) if metadata is None: return PhoneNumberType.UNKNOWN national_number = national_significant_number(numobj) return _number_type_helper(national_number, metadata)
python
def number_type(numobj): """Gets the type of a valid phone number. Arguments: numobj -- The PhoneNumber object that we want to know the type of. Returns the type of the phone number, as a PhoneNumberType value; returns PhoneNumberType.UNKNOWN if it is invalid. """ region_code = region_code_for_number(numobj) metadata = PhoneMetadata.metadata_for_region_or_calling_code(numobj.country_code, region_code) if metadata is None: return PhoneNumberType.UNKNOWN national_number = national_significant_number(numobj) return _number_type_helper(national_number, metadata)
[ "def", "number_type", "(", "numobj", ")", ":", "region_code", "=", "region_code_for_number", "(", "numobj", ")", "metadata", "=", "PhoneMetadata", ".", "metadata_for_region_or_calling_code", "(", "numobj", ".", "country_code", ",", "region_code", ")", "if", "metadat...
Gets the type of a valid phone number. Arguments: numobj -- The PhoneNumber object that we want to know the type of. Returns the type of the phone number, as a PhoneNumberType value; returns PhoneNumberType.UNKNOWN if it is invalid.
[ "Gets", "the", "type", "of", "a", "valid", "phone", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1898-L1912
train
215,700
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_number_type_helper
def _number_type_helper(national_number, metadata): """Return the type of the given number against the metadata""" if not _is_number_matching_desc(national_number, metadata.general_desc): return PhoneNumberType.UNKNOWN if _is_number_matching_desc(national_number, metadata.premium_rate): return PhoneNumberType.PREMIUM_RATE if _is_number_matching_desc(national_number, metadata.toll_free): return PhoneNumberType.TOLL_FREE if _is_number_matching_desc(national_number, metadata.shared_cost): return PhoneNumberType.SHARED_COST if _is_number_matching_desc(national_number, metadata.voip): return PhoneNumberType.VOIP if _is_number_matching_desc(national_number, metadata.personal_number): return PhoneNumberType.PERSONAL_NUMBER if _is_number_matching_desc(national_number, metadata.pager): return PhoneNumberType.PAGER if _is_number_matching_desc(national_number, metadata.uan): return PhoneNumberType.UAN if _is_number_matching_desc(national_number, metadata.voicemail): return PhoneNumberType.VOICEMAIL if _is_number_matching_desc(national_number, metadata.fixed_line): if metadata.same_mobile_and_fixed_line_pattern: return PhoneNumberType.FIXED_LINE_OR_MOBILE elif _is_number_matching_desc(national_number, metadata.mobile): return PhoneNumberType.FIXED_LINE_OR_MOBILE return PhoneNumberType.FIXED_LINE # Otherwise, test to see if the number is mobile. Only do this if certain # that the patterns for mobile and fixed line aren't the same. if (not metadata.same_mobile_and_fixed_line_pattern and _is_number_matching_desc(national_number, metadata.mobile)): return PhoneNumberType.MOBILE return PhoneNumberType.UNKNOWN
python
def _number_type_helper(national_number, metadata): """Return the type of the given number against the metadata""" if not _is_number_matching_desc(national_number, metadata.general_desc): return PhoneNumberType.UNKNOWN if _is_number_matching_desc(national_number, metadata.premium_rate): return PhoneNumberType.PREMIUM_RATE if _is_number_matching_desc(national_number, metadata.toll_free): return PhoneNumberType.TOLL_FREE if _is_number_matching_desc(national_number, metadata.shared_cost): return PhoneNumberType.SHARED_COST if _is_number_matching_desc(national_number, metadata.voip): return PhoneNumberType.VOIP if _is_number_matching_desc(national_number, metadata.personal_number): return PhoneNumberType.PERSONAL_NUMBER if _is_number_matching_desc(national_number, metadata.pager): return PhoneNumberType.PAGER if _is_number_matching_desc(national_number, metadata.uan): return PhoneNumberType.UAN if _is_number_matching_desc(national_number, metadata.voicemail): return PhoneNumberType.VOICEMAIL if _is_number_matching_desc(national_number, metadata.fixed_line): if metadata.same_mobile_and_fixed_line_pattern: return PhoneNumberType.FIXED_LINE_OR_MOBILE elif _is_number_matching_desc(national_number, metadata.mobile): return PhoneNumberType.FIXED_LINE_OR_MOBILE return PhoneNumberType.FIXED_LINE # Otherwise, test to see if the number is mobile. Only do this if certain # that the patterns for mobile and fixed line aren't the same. if (not metadata.same_mobile_and_fixed_line_pattern and _is_number_matching_desc(national_number, metadata.mobile)): return PhoneNumberType.MOBILE return PhoneNumberType.UNKNOWN
[ "def", "_number_type_helper", "(", "national_number", ",", "metadata", ")", ":", "if", "not", "_is_number_matching_desc", "(", "national_number", ",", "metadata", ".", "general_desc", ")", ":", "return", "PhoneNumberType", ".", "UNKNOWN", "if", "_is_number_matching_de...
Return the type of the given number against the metadata
[ "Return", "the", "type", "of", "the", "given", "number", "against", "the", "metadata" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1915-L1948
train
215,701
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_number_matching_desc
def _is_number_matching_desc(national_number, number_desc): """Determine if the number matches the given PhoneNumberDesc""" # Check if any possible number lengths are present; if so, we use them to avoid checking the # validation pattern if they don't match. If they are absent, this means they match the general # description, which we have already checked before checking a specific number type. if number_desc is None: return False actual_length = len(national_number) possible_lengths = number_desc.possible_length if len(possible_lengths) > 0 and actual_length not in possible_lengths: return False return _match_national_number(national_number, number_desc, False)
python
def _is_number_matching_desc(national_number, number_desc): """Determine if the number matches the given PhoneNumberDesc""" # Check if any possible number lengths are present; if so, we use them to avoid checking the # validation pattern if they don't match. If they are absent, this means they match the general # description, which we have already checked before checking a specific number type. if number_desc is None: return False actual_length = len(national_number) possible_lengths = number_desc.possible_length if len(possible_lengths) > 0 and actual_length not in possible_lengths: return False return _match_national_number(national_number, number_desc, False)
[ "def", "_is_number_matching_desc", "(", "national_number", ",", "number_desc", ")", ":", "# Check if any possible number lengths are present; if so, we use them to avoid checking the", "# validation pattern if they don't match. If they are absent, this means they match the general", "# descripti...
Determine if the number matches the given PhoneNumberDesc
[ "Determine", "if", "the", "number", "matches", "the", "given", "PhoneNumberDesc" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1951-L1962
train
215,702
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_valid_number_for_region
def is_valid_number_for_region(numobj, region_code): """Tests whether a phone number is valid for a certain region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits with false. After this, the specific number pattern rules for the region are examined. This is useful for determining for example whether a particular number is valid for Canada, rather than just a valid NANPA number. Warning: In most cases, you want to use is_valid_number instead. For example, this method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for the region "GB" (United Kingdom), since it has its own region code, "IM", which may be undesirable. Arguments: numobj -- The phone number object that we want to validate. region_code -- The region that we want to validate the phone number for. Returns a boolean that indicates whether the number is of a valid pattern. """ country_code = numobj.country_code if region_code is None: return False metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code.upper()) if (metadata is None or (region_code != REGION_CODE_FOR_NON_GEO_ENTITY and country_code != country_code_for_valid_region(region_code))): # Either the region code was invalid, or the country calling code for # this number does not match that of the region code. return False nsn = national_significant_number(numobj) return (_number_type_helper(nsn, metadata) != PhoneNumberType.UNKNOWN)
python
def is_valid_number_for_region(numobj, region_code): """Tests whether a phone number is valid for a certain region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits with false. After this, the specific number pattern rules for the region are examined. This is useful for determining for example whether a particular number is valid for Canada, rather than just a valid NANPA number. Warning: In most cases, you want to use is_valid_number instead. For example, this method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for the region "GB" (United Kingdom), since it has its own region code, "IM", which may be undesirable. Arguments: numobj -- The phone number object that we want to validate. region_code -- The region that we want to validate the phone number for. Returns a boolean that indicates whether the number is of a valid pattern. """ country_code = numobj.country_code if region_code is None: return False metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code.upper()) if (metadata is None or (region_code != REGION_CODE_FOR_NON_GEO_ENTITY and country_code != country_code_for_valid_region(region_code))): # Either the region code was invalid, or the country calling code for # this number does not match that of the region code. return False nsn = national_significant_number(numobj) return (_number_type_helper(nsn, metadata) != PhoneNumberType.UNKNOWN)
[ "def", "is_valid_number_for_region", "(", "numobj", ",", "region_code", ")", ":", "country_code", "=", "numobj", ".", "country_code", "if", "region_code", "is", "None", ":", "return", "False", "metadata", "=", "PhoneMetadata", ".", "metadata_for_region_or_calling_code...
Tests whether a phone number is valid for a certain region. Note this doesn't verify the number is actually in use, which is impossible to tell by just looking at a number itself. If the country calling code is not the same as the country calling code for the region, this immediately exits with false. After this, the specific number pattern rules for the region are examined. This is useful for determining for example whether a particular number is valid for Canada, rather than just a valid NANPA number. Warning: In most cases, you want to use is_valid_number instead. For example, this method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for the region "GB" (United Kingdom), since it has its own region code, "IM", which may be undesirable. Arguments: numobj -- The phone number object that we want to validate. region_code -- The region that we want to validate the phone number for. Returns a boolean that indicates whether the number is of a valid pattern.
[ "Tests", "whether", "a", "phone", "number", "is", "valid", "for", "a", "certain", "region", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L1986-L2019
train
215,703
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
region_code_for_number
def region_code_for_number(numobj): """Returns the region where a phone number is from. This could be used for geocoding at the region level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid numbers). Arguments: numobj -- The phone number object whose origin we want to know Returns the region where the phone number is from, or None if no region matches this calling code. """ country_code = numobj.country_code regions = COUNTRY_CODE_TO_REGION_CODE.get(country_code, None) if regions is None: return None if len(regions) == 1: return regions[0] else: return _region_code_for_number_from_list(numobj, regions)
python
def region_code_for_number(numobj): """Returns the region where a phone number is from. This could be used for geocoding at the region level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid numbers). Arguments: numobj -- The phone number object whose origin we want to know Returns the region where the phone number is from, or None if no region matches this calling code. """ country_code = numobj.country_code regions = COUNTRY_CODE_TO_REGION_CODE.get(country_code, None) if regions is None: return None if len(regions) == 1: return regions[0] else: return _region_code_for_number_from_list(numobj, regions)
[ "def", "region_code_for_number", "(", "numobj", ")", ":", "country_code", "=", "numobj", ".", "country_code", "regions", "=", "COUNTRY_CODE_TO_REGION_CODE", ".", "get", "(", "country_code", ",", "None", ")", "if", "regions", "is", "None", ":", "return", "None", ...
Returns the region where a phone number is from. This could be used for geocoding at the region level. Only guarantees correct results for valid, full numbers (not short-codes, or invalid numbers). Arguments: numobj -- The phone number object whose origin we want to know Returns the region where the phone number is from, or None if no region matches this calling code.
[ "Returns", "the", "region", "where", "a", "phone", "number", "is", "from", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2022-L2044
train
215,704
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_region_code_for_number_from_list
def _region_code_for_number_from_list(numobj, regions): """Find the region in a list that matches a number""" national_number = national_significant_number(numobj) for region_code in regions: # If leading_digits is present, use this. Otherwise, do full # validation. # Metadata cannot be None because the region codes come from # the country calling code map. metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) if metadata is None: continue if metadata.leading_digits is not None: leading_digit_re = re.compile(metadata.leading_digits) match = leading_digit_re.match(national_number) if match: return region_code elif _number_type_helper(national_number, metadata) != PhoneNumberType.UNKNOWN: return region_code return None
python
def _region_code_for_number_from_list(numobj, regions): """Find the region in a list that matches a number""" national_number = national_significant_number(numobj) for region_code in regions: # If leading_digits is present, use this. Otherwise, do full # validation. # Metadata cannot be None because the region codes come from # the country calling code map. metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) if metadata is None: continue if metadata.leading_digits is not None: leading_digit_re = re.compile(metadata.leading_digits) match = leading_digit_re.match(national_number) if match: return region_code elif _number_type_helper(national_number, metadata) != PhoneNumberType.UNKNOWN: return region_code return None
[ "def", "_region_code_for_number_from_list", "(", "numobj", ",", "regions", ")", ":", "national_number", "=", "national_significant_number", "(", "numobj", ")", "for", "region_code", "in", "regions", ":", "# If leading_digits is present, use this. Otherwise, do full", "# valid...
Find the region in a list that matches a number
[ "Find", "the", "region", "in", "a", "list", "that", "matches", "a", "number" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2047-L2065
train
215,705
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
country_code_for_valid_region
def country_code_for_valid_region(region_code): """Returns the country calling code for a specific region. For example, this would be 1 for the United States, and 64 for New Zealand. Assumes the region is already valid. Arguments: region_code -- The region that we want to get the country calling code for. Returns the country calling code for the region denoted by region_code. """ metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) if metadata is None: raise Exception("Invalid region code %s" % region_code) return metadata.country_code
python
def country_code_for_valid_region(region_code): """Returns the country calling code for a specific region. For example, this would be 1 for the United States, and 64 for New Zealand. Assumes the region is already valid. Arguments: region_code -- The region that we want to get the country calling code for. Returns the country calling code for the region denoted by region_code. """ metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) if metadata is None: raise Exception("Invalid region code %s" % region_code) return metadata.country_code
[ "def", "country_code_for_valid_region", "(", "region_code", ")", ":", "metadata", "=", "PhoneMetadata", ".", "metadata_for_region", "(", "region_code", ".", "upper", "(", ")", ",", "None", ")", "if", "metadata", "is", "None", ":", "raise", "Exception", "(", "\...
Returns the country calling code for a specific region. For example, this would be 1 for the United States, and 64 for New Zealand. Assumes the region is already valid. Arguments: region_code -- The region that we want to get the country calling code for. Returns the country calling code for the region denoted by region_code.
[ "Returns", "the", "country", "calling", "code", "for", "a", "specific", "region", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2116-L2130
train
215,706
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
ndd_prefix_for_region
def ndd_prefix_for_region(region_code, strip_non_digits): """Returns the national dialling prefix for a specific region. For example, this would be 1 for the United States, and 0 for New Zealand. Set strip_non_digits to True to strip symbols like "~" (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is present, we return None. Warning: Do not use this method for do-your-own formatting - for some regions, the national dialling prefix is used only for certain types of numbers. Use the library's formatting functions to prefix the national prefix when required. Arguments: region_code -- The region that we want to get the dialling prefix for. strip_non_digits -- whether to strip non-digits from the national dialling prefix. Returns the dialling prefix for the region denoted by region_code. """ if region_code is None: return None metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) if metadata is None: return None national_prefix = metadata.national_prefix if national_prefix is None or len(national_prefix) == 0: return None if strip_non_digits: # Note: if any other non-numeric symbols are ever used in national # prefixes, these would have to be removed here as well. national_prefix = re.sub(U_TILDE, U_EMPTY_STRING, national_prefix) return national_prefix
python
def ndd_prefix_for_region(region_code, strip_non_digits): """Returns the national dialling prefix for a specific region. For example, this would be 1 for the United States, and 0 for New Zealand. Set strip_non_digits to True to strip symbols like "~" (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is present, we return None. Warning: Do not use this method for do-your-own formatting - for some regions, the national dialling prefix is used only for certain types of numbers. Use the library's formatting functions to prefix the national prefix when required. Arguments: region_code -- The region that we want to get the dialling prefix for. strip_non_digits -- whether to strip non-digits from the national dialling prefix. Returns the dialling prefix for the region denoted by region_code. """ if region_code is None: return None metadata = PhoneMetadata.metadata_for_region(region_code.upper(), None) if metadata is None: return None national_prefix = metadata.national_prefix if national_prefix is None or len(national_prefix) == 0: return None if strip_non_digits: # Note: if any other non-numeric symbols are ever used in national # prefixes, these would have to be removed here as well. national_prefix = re.sub(U_TILDE, U_EMPTY_STRING, national_prefix) return national_prefix
[ "def", "ndd_prefix_for_region", "(", "region_code", ",", "strip_non_digits", ")", ":", "if", "region_code", "is", "None", ":", "return", "None", "metadata", "=", "PhoneMetadata", ".", "metadata_for_region", "(", "region_code", ".", "upper", "(", ")", ",", "None"...
Returns the national dialling prefix for a specific region. For example, this would be 1 for the United States, and 0 for New Zealand. Set strip_non_digits to True to strip symbols like "~" (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is present, we return None. Warning: Do not use this method for do-your-own formatting - for some regions, the national dialling prefix is used only for certain types of numbers. Use the library's formatting functions to prefix the national prefix when required. Arguments: region_code -- The region that we want to get the dialling prefix for. strip_non_digits -- whether to strip non-digits from the national dialling prefix. Returns the dialling prefix for the region denoted by region_code.
[ "Returns", "the", "national", "dialling", "prefix", "for", "a", "specific", "region", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2133-L2165
train
215,707
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_possible_number
def is_possible_number(numobj): """Convenience wrapper around is_possible_number_with_reason. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it. Arguments: numobj -- the number object that needs to be checked Returns True if the number is possible """ result = is_possible_number_with_reason(numobj) return (result == ValidationResult.IS_POSSIBLE or result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY)
python
def is_possible_number(numobj): """Convenience wrapper around is_possible_number_with_reason. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it. Arguments: numobj -- the number object that needs to be checked Returns True if the number is possible """ result = is_possible_number_with_reason(numobj) return (result == ValidationResult.IS_POSSIBLE or result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY)
[ "def", "is_possible_number", "(", "numobj", ")", ":", "result", "=", "is_possible_number_with_reason", "(", "numobj", ")", "return", "(", "result", "==", "ValidationResult", ".", "IS_POSSIBLE", "or", "result", "==", "ValidationResult", ".", "IS_POSSIBLE_LOCAL_ONLY", ...
Convenience wrapper around is_possible_number_with_reason. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it. Arguments: numobj -- the number object that needs to be checked Returns True if the number is possible
[ "Convenience", "wrapper", "around", "is_possible_number_with_reason", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2197-L2216
train
215,708
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_possible_number_for_type
def is_possible_number_for_type(numobj, numtype): """Convenience wrapper around is_possible_number_for_type_with_reason. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it. Arguments: numobj -- the number object that needs to be checked numtype -- the type we are interested in Returns True if the number is possible """ result = is_possible_number_for_type_with_reason(numobj, numtype) return (result == ValidationResult.IS_POSSIBLE or result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY)
python
def is_possible_number_for_type(numobj, numtype): """Convenience wrapper around is_possible_number_for_type_with_reason. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it. Arguments: numobj -- the number object that needs to be checked numtype -- the type we are interested in Returns True if the number is possible """ result = is_possible_number_for_type_with_reason(numobj, numtype) return (result == ValidationResult.IS_POSSIBLE or result == ValidationResult.IS_POSSIBLE_LOCAL_ONLY)
[ "def", "is_possible_number_for_type", "(", "numobj", ",", "numtype", ")", ":", "result", "=", "is_possible_number_for_type_with_reason", "(", "numobj", ",", "numtype", ")", "return", "(", "result", "==", "ValidationResult", ".", "IS_POSSIBLE", "or", "result", "==", ...
Convenience wrapper around is_possible_number_for_type_with_reason. Instead of returning the reason for failure, this method returns true if the number is either a possible fully-qualified number (containing the area code and country code), or if the number could be a possible local number (with a country code, but missing an area code). Local numbers are considered possible if they could be possibly dialled in this format: if the area code is needed for a call to connect, the number is not considered possible without it. Arguments: numobj -- the number object that needs to be checked numtype -- the type we are interested in Returns True if the number is possible
[ "Convenience", "wrapper", "around", "is_possible_number_for_type_with_reason", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2219-L2239
train
215,709
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_possible_number_for_type_with_reason
def is_possible_number_for_type_with_reason(numobj, numtype): """Check whether a phone number is a possible number of a particular type. For types that don't exist in a particular region, this will return a result that isn't so useful; it is recommended that you use supported_types_for_region or supported_types_for_non_geo_entity respectively before calling this method to determine whether you should call it for this number at all. This provides a more lenient check than is_valid_number in the following sense: - It only checks the length of phone numbers. In particular, it doesn't check starting digits of the number. - For some numbers (particularly fixed-line), many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial only the subscriber number when dialing in the same area. This function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is passed in. On the other hand, because is_valid_number validates using information on both starting digits (for fixed line numbers, that would most likely be area codes) and length (obviously includes the length of area codes for fixed line numbers), it will return false for the subscriber-number-only version. Arguments: numobj -- The number object that needs to be checked numtype -- The type we are interested in Returns a value from ValidationResult which indicates whether the number is possible """ national_number = national_significant_number(numobj) country_code = numobj.country_code # Note: For regions that share a country calling code, like NANPA numbers, # we just use the rules from the default region (US in this case) since the # region_code_for_number will not work if the number is possible but not # valid. There is in fact one country calling code (290) where the possible # number pattern differs between various regions (Saint Helena and Tristan # da CuΓ±ha), but this is handled by putting all possible lengths for any # country with this country calling code in the metadata for the default # region in this case. if not _has_valid_country_calling_code(country_code): return ValidationResult.INVALID_COUNTRY_CODE region_code = region_code_for_country_code(country_code) # Metadata cannot be None because the country calling code is valid. metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) return _test_number_length(national_number, metadata, numtype)
python
def is_possible_number_for_type_with_reason(numobj, numtype): """Check whether a phone number is a possible number of a particular type. For types that don't exist in a particular region, this will return a result that isn't so useful; it is recommended that you use supported_types_for_region or supported_types_for_non_geo_entity respectively before calling this method to determine whether you should call it for this number at all. This provides a more lenient check than is_valid_number in the following sense: - It only checks the length of phone numbers. In particular, it doesn't check starting digits of the number. - For some numbers (particularly fixed-line), many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial only the subscriber number when dialing in the same area. This function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is passed in. On the other hand, because is_valid_number validates using information on both starting digits (for fixed line numbers, that would most likely be area codes) and length (obviously includes the length of area codes for fixed line numbers), it will return false for the subscriber-number-only version. Arguments: numobj -- The number object that needs to be checked numtype -- The type we are interested in Returns a value from ValidationResult which indicates whether the number is possible """ national_number = national_significant_number(numobj) country_code = numobj.country_code # Note: For regions that share a country calling code, like NANPA numbers, # we just use the rules from the default region (US in this case) since the # region_code_for_number will not work if the number is possible but not # valid. There is in fact one country calling code (290) where the possible # number pattern differs between various regions (Saint Helena and Tristan # da CuΓ±ha), but this is handled by putting all possible lengths for any # country with this country calling code in the metadata for the default # region in this case. if not _has_valid_country_calling_code(country_code): return ValidationResult.INVALID_COUNTRY_CODE region_code = region_code_for_country_code(country_code) # Metadata cannot be None because the country calling code is valid. metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, region_code) return _test_number_length(national_number, metadata, numtype)
[ "def", "is_possible_number_for_type_with_reason", "(", "numobj", ",", "numtype", ")", ":", "national_number", "=", "national_significant_number", "(", "numobj", ")", "country_code", "=", "numobj", ".", "country_code", "# Note: For regions that share a country calling code, like...
Check whether a phone number is a possible number of a particular type. For types that don't exist in a particular region, this will return a result that isn't so useful; it is recommended that you use supported_types_for_region or supported_types_for_non_geo_entity respectively before calling this method to determine whether you should call it for this number at all. This provides a more lenient check than is_valid_number in the following sense: - It only checks the length of phone numbers. In particular, it doesn't check starting digits of the number. - For some numbers (particularly fixed-line), many regions have the concept of area code, which together with subscriber number constitute the national significant number. It is sometimes okay to dial only the subscriber number when dialing in the same area. This function will return IS_POSSIBLE_LOCAL_ONLY if the subscriber-number-only version is passed in. On the other hand, because is_valid_number validates using information on both starting digits (for fixed line numbers, that would most likely be area codes) and length (obviously includes the length of area codes for fixed line numbers), it will return false for the subscriber-number-only version. Arguments: numobj -- The number object that needs to be checked numtype -- The type we are interested in Returns a value from ValidationResult which indicates whether the number is possible
[ "Check", "whether", "a", "phone", "number", "is", "a", "possible", "number", "of", "a", "particular", "type", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2318-L2365
train
215,710
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
truncate_too_long_number
def truncate_too_long_number(numobj): """Truncate a number object that is too long. Attempts to extract a valid number from a phone number that is too long to be valid, and resets the PhoneNumber object passed in to that valid version. If no valid number could be extracted, the PhoneNumber object passed in will not be modified. Arguments: numobj -- A PhoneNumber object which contains a number that is too long to be valid. Returns True if a valid phone number can be successfully extracted. """ if is_valid_number(numobj): return True numobj_copy = PhoneNumber() numobj_copy.merge_from(numobj) national_number = numobj.national_number while not is_valid_number(numobj_copy): # Strip a digit off the RHS national_number = national_number // 10 numobj_copy.national_number = national_number validation_result = is_possible_number_with_reason(numobj_copy) if (validation_result == ValidationResult.TOO_SHORT or national_number == 0): return False # To reach here, numobj_copy is a valid number. Modify the original object numobj.national_number = national_number return True
python
def truncate_too_long_number(numobj): """Truncate a number object that is too long. Attempts to extract a valid number from a phone number that is too long to be valid, and resets the PhoneNumber object passed in to that valid version. If no valid number could be extracted, the PhoneNumber object passed in will not be modified. Arguments: numobj -- A PhoneNumber object which contains a number that is too long to be valid. Returns True if a valid phone number can be successfully extracted. """ if is_valid_number(numobj): return True numobj_copy = PhoneNumber() numobj_copy.merge_from(numobj) national_number = numobj.national_number while not is_valid_number(numobj_copy): # Strip a digit off the RHS national_number = national_number // 10 numobj_copy.national_number = national_number validation_result = is_possible_number_with_reason(numobj_copy) if (validation_result == ValidationResult.TOO_SHORT or national_number == 0): return False # To reach here, numobj_copy is a valid number. Modify the original object numobj.national_number = national_number return True
[ "def", "truncate_too_long_number", "(", "numobj", ")", ":", "if", "is_valid_number", "(", "numobj", ")", ":", "return", "True", "numobj_copy", "=", "PhoneNumber", "(", ")", "numobj_copy", ".", "merge_from", "(", "numobj", ")", "national_number", "=", "numobj", ...
Truncate a number object that is too long. Attempts to extract a valid number from a phone number that is too long to be valid, and resets the PhoneNumber object passed in to that valid version. If no valid number could be extracted, the PhoneNumber object passed in will not be modified. Arguments: numobj -- A PhoneNumber object which contains a number that is too long to be valid. Returns True if a valid phone number can be successfully extracted.
[ "Truncate", "a", "number", "object", "that", "is", "too", "long", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2399-L2429
train
215,711
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_extract_country_code
def _extract_country_code(number): """Extracts country calling code from number. Returns a 2-tuple of (country_calling_code, rest_of_number). It assumes that the leading plus sign or IDD has already been removed. Returns (0, number) if number doesn't start with a valid country calling code. """ if len(number) == 0 or number[0] == U_ZERO: # Country codes do not begin with a '0'. return (0, number) for ii in range(1, min(len(number), _MAX_LENGTH_COUNTRY_CODE) + 1): try: country_code = int(number[:ii]) if country_code in COUNTRY_CODE_TO_REGION_CODE: return (country_code, number[ii:]) except Exception: pass return (0, number)
python
def _extract_country_code(number): """Extracts country calling code from number. Returns a 2-tuple of (country_calling_code, rest_of_number). It assumes that the leading plus sign or IDD has already been removed. Returns (0, number) if number doesn't start with a valid country calling code. """ if len(number) == 0 or number[0] == U_ZERO: # Country codes do not begin with a '0'. return (0, number) for ii in range(1, min(len(number), _MAX_LENGTH_COUNTRY_CODE) + 1): try: country_code = int(number[:ii]) if country_code in COUNTRY_CODE_TO_REGION_CODE: return (country_code, number[ii:]) except Exception: pass return (0, number)
[ "def", "_extract_country_code", "(", "number", ")", ":", "if", "len", "(", "number", ")", "==", "0", "or", "number", "[", "0", "]", "==", "U_ZERO", ":", "# Country codes do not begin with a '0'.", "return", "(", "0", ",", "number", ")", "for", "ii", "in", ...
Extracts country calling code from number. Returns a 2-tuple of (country_calling_code, rest_of_number). It assumes that the leading plus sign or IDD has already been removed. Returns (0, number) if number doesn't start with a valid country calling code.
[ "Extracts", "country", "calling", "code", "from", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2432-L2450
train
215,712
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_maybe_extract_country_code
def _maybe_extract_country_code(number, metadata, keep_raw_input, numobj): """Tries to extract a country calling code from a number. This method will return zero if no country calling code is considered to be present. Country calling codes are extracted in the following ways: - by stripping the international dialing prefix of the region the person is dialing from, if this is present in the number, and looking at the next digits - by stripping the '+' sign if present and then looking at the next digits - by comparing the start of the number and the country calling code of the default region. If the number is not considered possible for the numbering plan of the default region initially, but starts with the country calling code of this region, validation will be reattempted after stripping this country calling code. If this number is considered a possible number, then the first digits will be considered the country calling code and removed as such. It will raise a NumberParseException if the number starts with a '+' but the country calling code supplied after this does not match that of any known region. Arguments: number -- non-normalized telephone number that we wish to extract a country calling code from; may begin with '+' metadata -- metadata about the region this number may be from, or None keep_raw_input -- True if the country_code_source and preferred_carrier_code fields of numobj should be populated. numobj -- The PhoneNumber object where the country_code and country_code_source need to be populated. Note the country_code is always populated, whereas country_code_source is only populated when keep_raw_input is True. Returns a 2-tuple containing: - the country calling code extracted or 0 if none could be extracted - a string holding the national significant number, in the case that a country calling code was extracted. If no country calling code was extracted, this will be empty. """ if len(number) == 0: return (0, U_EMPTY_STRING) full_number = number # Set the default prefix to be something that will never match. possible_country_idd_prefix = unicod("NonMatch") if metadata is not None and metadata.international_prefix is not None: possible_country_idd_prefix = metadata.international_prefix country_code_source, full_number = _maybe_strip_i18n_prefix_and_normalize(full_number, possible_country_idd_prefix) if keep_raw_input: numobj.country_code_source = country_code_source if country_code_source != CountryCodeSource.FROM_DEFAULT_COUNTRY: if len(full_number) <= _MIN_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_SHORT_AFTER_IDD, "Phone number had an IDD, but after this was not " + "long enough to be a viable phone number.") potential_country_code, rest_of_number = _extract_country_code(full_number) if potential_country_code != 0: numobj.country_code = potential_country_code return (potential_country_code, rest_of_number) # If this fails, they must be using a strange country calling code # that we don't recognize, or that doesn't exist. raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Country calling code supplied was not recognised.") elif metadata is not None: # Check to see if the number starts with the country calling code for # the default region. If so, we remove the country calling code, and # do some checks on the validity of the number before and after. default_country_code = metadata.country_code default_country_code_str = str(metadata.country_code) normalized_number = full_number if normalized_number.startswith(default_country_code_str): potential_national_number = full_number[len(default_country_code_str):] general_desc = metadata.general_desc _, potential_national_number, _ = _maybe_strip_national_prefix_carrier_code(potential_national_number, metadata) # If the number was not valid before but is valid now, or if it # was too long before, we consider the number with the country # calling code stripped to be a better result and keep that # instead. if ((not _match_national_number(full_number, general_desc, False) and _match_national_number(potential_national_number, general_desc, False)) or (_test_number_length(full_number, metadata) == ValidationResult.TOO_LONG)): if keep_raw_input: numobj.country_code_source = CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN numobj.country_code = default_country_code return (default_country_code, potential_national_number) # No country calling code present. numobj.country_code = 0 return (0, U_EMPTY_STRING)
python
def _maybe_extract_country_code(number, metadata, keep_raw_input, numobj): """Tries to extract a country calling code from a number. This method will return zero if no country calling code is considered to be present. Country calling codes are extracted in the following ways: - by stripping the international dialing prefix of the region the person is dialing from, if this is present in the number, and looking at the next digits - by stripping the '+' sign if present and then looking at the next digits - by comparing the start of the number and the country calling code of the default region. If the number is not considered possible for the numbering plan of the default region initially, but starts with the country calling code of this region, validation will be reattempted after stripping this country calling code. If this number is considered a possible number, then the first digits will be considered the country calling code and removed as such. It will raise a NumberParseException if the number starts with a '+' but the country calling code supplied after this does not match that of any known region. Arguments: number -- non-normalized telephone number that we wish to extract a country calling code from; may begin with '+' metadata -- metadata about the region this number may be from, or None keep_raw_input -- True if the country_code_source and preferred_carrier_code fields of numobj should be populated. numobj -- The PhoneNumber object where the country_code and country_code_source need to be populated. Note the country_code is always populated, whereas country_code_source is only populated when keep_raw_input is True. Returns a 2-tuple containing: - the country calling code extracted or 0 if none could be extracted - a string holding the national significant number, in the case that a country calling code was extracted. If no country calling code was extracted, this will be empty. """ if len(number) == 0: return (0, U_EMPTY_STRING) full_number = number # Set the default prefix to be something that will never match. possible_country_idd_prefix = unicod("NonMatch") if metadata is not None and metadata.international_prefix is not None: possible_country_idd_prefix = metadata.international_prefix country_code_source, full_number = _maybe_strip_i18n_prefix_and_normalize(full_number, possible_country_idd_prefix) if keep_raw_input: numobj.country_code_source = country_code_source if country_code_source != CountryCodeSource.FROM_DEFAULT_COUNTRY: if len(full_number) <= _MIN_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_SHORT_AFTER_IDD, "Phone number had an IDD, but after this was not " + "long enough to be a viable phone number.") potential_country_code, rest_of_number = _extract_country_code(full_number) if potential_country_code != 0: numobj.country_code = potential_country_code return (potential_country_code, rest_of_number) # If this fails, they must be using a strange country calling code # that we don't recognize, or that doesn't exist. raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Country calling code supplied was not recognised.") elif metadata is not None: # Check to see if the number starts with the country calling code for # the default region. If so, we remove the country calling code, and # do some checks on the validity of the number before and after. default_country_code = metadata.country_code default_country_code_str = str(metadata.country_code) normalized_number = full_number if normalized_number.startswith(default_country_code_str): potential_national_number = full_number[len(default_country_code_str):] general_desc = metadata.general_desc _, potential_national_number, _ = _maybe_strip_national_prefix_carrier_code(potential_national_number, metadata) # If the number was not valid before but is valid now, or if it # was too long before, we consider the number with the country # calling code stripped to be a better result and keep that # instead. if ((not _match_national_number(full_number, general_desc, False) and _match_national_number(potential_national_number, general_desc, False)) or (_test_number_length(full_number, metadata) == ValidationResult.TOO_LONG)): if keep_raw_input: numobj.country_code_source = CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN numobj.country_code = default_country_code return (default_country_code, potential_national_number) # No country calling code present. numobj.country_code = 0 return (0, U_EMPTY_STRING)
[ "def", "_maybe_extract_country_code", "(", "number", ",", "metadata", ",", "keep_raw_input", ",", "numobj", ")", ":", "if", "len", "(", "number", ")", "==", "0", ":", "return", "(", "0", ",", "U_EMPTY_STRING", ")", "full_number", "=", "number", "# Set the de...
Tries to extract a country calling code from a number. This method will return zero if no country calling code is considered to be present. Country calling codes are extracted in the following ways: - by stripping the international dialing prefix of the region the person is dialing from, if this is present in the number, and looking at the next digits - by stripping the '+' sign if present and then looking at the next digits - by comparing the start of the number and the country calling code of the default region. If the number is not considered possible for the numbering plan of the default region initially, but starts with the country calling code of this region, validation will be reattempted after stripping this country calling code. If this number is considered a possible number, then the first digits will be considered the country calling code and removed as such. It will raise a NumberParseException if the number starts with a '+' but the country calling code supplied after this does not match that of any known region. Arguments: number -- non-normalized telephone number that we wish to extract a country calling code from; may begin with '+' metadata -- metadata about the region this number may be from, or None keep_raw_input -- True if the country_code_source and preferred_carrier_code fields of numobj should be populated. numobj -- The PhoneNumber object where the country_code and country_code_source need to be populated. Note the country_code is always populated, whereas country_code_source is only populated when keep_raw_input is True. Returns a 2-tuple containing: - the country calling code extracted or 0 if none could be extracted - a string holding the national significant number, in the case that a country calling code was extracted. If no country calling code was extracted, this will be empty.
[ "Tries", "to", "extract", "a", "country", "calling", "code", "from", "a", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2453-L2549
train
215,713
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_parse_prefix_as_idd
def _parse_prefix_as_idd(idd_pattern, number): """Strips the IDD from the start of the number if present. Helper function used by _maybe_strip_i18n_prefix_and_normalize(). Returns a 2-tuple: - Boolean indicating if IDD was stripped - Number with IDD stripped """ match = idd_pattern.match(number) if match: match_end = match.end() # Only strip this if the first digit after the match is not a 0, since # country calling codes cannot begin with 0. digit_match = _CAPTURING_DIGIT_PATTERN.search(number[match_end:]) if digit_match: normalized_group = normalize_digits_only(digit_match.group(1)) if normalized_group == U_ZERO: return (False, number) return (True, number[match_end:]) return (False, number)
python
def _parse_prefix_as_idd(idd_pattern, number): """Strips the IDD from the start of the number if present. Helper function used by _maybe_strip_i18n_prefix_and_normalize(). Returns a 2-tuple: - Boolean indicating if IDD was stripped - Number with IDD stripped """ match = idd_pattern.match(number) if match: match_end = match.end() # Only strip this if the first digit after the match is not a 0, since # country calling codes cannot begin with 0. digit_match = _CAPTURING_DIGIT_PATTERN.search(number[match_end:]) if digit_match: normalized_group = normalize_digits_only(digit_match.group(1)) if normalized_group == U_ZERO: return (False, number) return (True, number[match_end:]) return (False, number)
[ "def", "_parse_prefix_as_idd", "(", "idd_pattern", ",", "number", ")", ":", "match", "=", "idd_pattern", ".", "match", "(", "number", ")", "if", "match", ":", "match_end", "=", "match", ".", "end", "(", ")", "# Only strip this if the first digit after the match is...
Strips the IDD from the start of the number if present. Helper function used by _maybe_strip_i18n_prefix_and_normalize(). Returns a 2-tuple: - Boolean indicating if IDD was stripped - Number with IDD stripped
[ "Strips", "the", "IDD", "from", "the", "start", "of", "the", "number", "if", "present", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2552-L2572
train
215,714
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_maybe_strip_extension
def _maybe_strip_extension(number): """Strip extension from the end of a number string. Strips any extension (as in, the part of the number dialled after the call is connected, usually indicated with extn, ext, x or similar) from the end of the number, and returns it. Arguments: number -- the non-normalized telephone number that we wish to strip the extension from. Returns a 2-tuple of: - the phone extension (or "" or not present) - the number before the extension. """ match = _EXTN_PATTERN.search(number) # If we find a potential extension, and the number preceding this is a # viable number, we assume it is an extension. if match and _is_viable_phone_number(number[:match.start()]): # The numbers are captured into groups in the regular expression. for group in match.groups(): # We go through the capturing groups until we find one that # captured some digits. If none did, then we will return the empty # string. if group is not None: return (group, number[:match.start()]) return ("", number)
python
def _maybe_strip_extension(number): """Strip extension from the end of a number string. Strips any extension (as in, the part of the number dialled after the call is connected, usually indicated with extn, ext, x or similar) from the end of the number, and returns it. Arguments: number -- the non-normalized telephone number that we wish to strip the extension from. Returns a 2-tuple of: - the phone extension (or "" or not present) - the number before the extension. """ match = _EXTN_PATTERN.search(number) # If we find a potential extension, and the number preceding this is a # viable number, we assume it is an extension. if match and _is_viable_phone_number(number[:match.start()]): # The numbers are captured into groups in the regular expression. for group in match.groups(): # We go through the capturing groups until we find one that # captured some digits. If none did, then we will return the empty # string. if group is not None: return (group, number[:match.start()]) return ("", number)
[ "def", "_maybe_strip_extension", "(", "number", ")", ":", "match", "=", "_EXTN_PATTERN", ".", "search", "(", "number", ")", "# If we find a potential extension, and the number preceding this is a", "# viable number, we assume it is an extension.", "if", "match", "and", "_is_via...
Strip extension from the end of a number string. Strips any extension (as in, the part of the number dialled after the call is connected, usually indicated with extn, ext, x or similar) from the end of the number, and returns it. Arguments: number -- the non-normalized telephone number that we wish to strip the extension from. Returns a 2-tuple of: - the phone extension (or "" or not present) - the number before the extension.
[ "Strip", "extension", "from", "the", "end", "of", "a", "number", "string", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2676-L2701
train
215,715
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_check_region_for_parsing
def _check_region_for_parsing(number, default_region): """Checks to see that the region code used is valid, or if it is not valid, that the number to parse starts with a + symbol so that we can attempt to infer the region from the number. Returns False if it cannot use the region provided and the region cannot be inferred. """ if not _is_valid_region_code(default_region): # If the number is None or empty, we can't infer the region. if number is None or len(number) == 0: return False match = _PLUS_CHARS_PATTERN.match(number) if match is None: return False return True
python
def _check_region_for_parsing(number, default_region): """Checks to see that the region code used is valid, or if it is not valid, that the number to parse starts with a + symbol so that we can attempt to infer the region from the number. Returns False if it cannot use the region provided and the region cannot be inferred. """ if not _is_valid_region_code(default_region): # If the number is None or empty, we can't infer the region. if number is None or len(number) == 0: return False match = _PLUS_CHARS_PATTERN.match(number) if match is None: return False return True
[ "def", "_check_region_for_parsing", "(", "number", ",", "default_region", ")", ":", "if", "not", "_is_valid_region_code", "(", "default_region", ")", ":", "# If the number is None or empty, we can't infer the region.", "if", "number", "is", "None", "or", "len", "(", "nu...
Checks to see that the region code used is valid, or if it is not valid, that the number to parse starts with a + symbol so that we can attempt to infer the region from the number. Returns False if it cannot use the region provided and the region cannot be inferred.
[ "Checks", "to", "see", "that", "the", "region", "code", "used", "is", "valid", "or", "if", "it", "is", "not", "valid", "that", "the", "number", "to", "parse", "starts", "with", "a", "+", "symbol", "so", "that", "we", "can", "attempt", "to", "infer", ...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2704-L2717
train
215,716
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_set_italian_leading_zeros_for_phone_number
def _set_italian_leading_zeros_for_phone_number(national_number, numobj): """A helper function to set the values related to leading zeros in a PhoneNumber.""" if len(national_number) > 1 and national_number[0] == U_ZERO: numobj.italian_leading_zero = True number_of_leading_zeros = 1 # Note that if the number is all "0"s, the last "0" is not counted as # a leading zero. while (number_of_leading_zeros < len(national_number) - 1 and national_number[number_of_leading_zeros] == U_ZERO): number_of_leading_zeros += 1 if number_of_leading_zeros != 1: numobj.number_of_leading_zeros = number_of_leading_zeros
python
def _set_italian_leading_zeros_for_phone_number(national_number, numobj): """A helper function to set the values related to leading zeros in a PhoneNumber.""" if len(national_number) > 1 and national_number[0] == U_ZERO: numobj.italian_leading_zero = True number_of_leading_zeros = 1 # Note that if the number is all "0"s, the last "0" is not counted as # a leading zero. while (number_of_leading_zeros < len(national_number) - 1 and national_number[number_of_leading_zeros] == U_ZERO): number_of_leading_zeros += 1 if number_of_leading_zeros != 1: numobj.number_of_leading_zeros = number_of_leading_zeros
[ "def", "_set_italian_leading_zeros_for_phone_number", "(", "national_number", ",", "numobj", ")", ":", "if", "len", "(", "national_number", ")", ">", "1", "and", "national_number", "[", "0", "]", "==", "U_ZERO", ":", "numobj", ".", "italian_leading_zero", "=", "...
A helper function to set the values related to leading zeros in a PhoneNumber.
[ "A", "helper", "function", "to", "set", "the", "values", "related", "to", "leading", "zeros", "in", "a", "PhoneNumber", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2720-L2732
train
215,717
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
parse
def parse(number, region=None, keep_raw_input=False, numobj=None, _check_region=True): """Parse a string and return a corresponding PhoneNumber object. The method is quite lenient and looks for a number in the input text (raw input) and does not check whether the string is definitely only a phone number. To do this, it ignores punctuation and white-space, as well as any text before the number (e.g. a leading "Tel: ") and trims the non-number bits. It will accept a number in any format (E164, national, international etc), assuming it can be interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters into digits if it thinks this is a vanity number of the type "1800 MICROSOFT". This method will throw a NumberParseException if the number is not considered to be a possible number. Note that validation of whether the number is actually a valid number for a particular region is not performed. This can be done separately with is_valid_number. Note this method canonicalizes the phone number such that different representations can be easily compared, no matter what form it was originally entered in (e.g. national, international). If you want to record context about the number being parsed, such as the raw input that was entered, how the country code was derived etc. then ensure keep_raw_input is set. Note if any new field is added to this method that should always be filled in, even when keep_raw_input is False, it should also be handled in the _copy_core_fields_only() function. Arguments: number -- The number that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension. It can also be provided in RFC3966 format. region -- The region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. If the number is guaranteed to start with a '+' followed by the country calling code, then None or UNKNOWN_REGION can be supplied. keep_raw_input -- Whether to populate the raw_input field of the PhoneNumber object with number (as well as the country_code_source field). numobj -- An optional existing PhoneNumber object to receive the parsing results _check_region -- Whether to check the supplied region parameter; should always be True for external callers. Returns a PhoneNumber object filled with the parse number. Raises: NumberParseException if the string is not considered to be a viable phone number (e.g. too few or too many digits) or if no default region was supplied and the number is not in international format (does not start with +). """ if numobj is None: numobj = PhoneNumber() if number is None: raise NumberParseException(NumberParseException.NOT_A_NUMBER, "The phone number supplied was None.") elif len(number) > _MAX_INPUT_STRING_LENGTH: raise NumberParseException(NumberParseException.TOO_LONG, "The string supplied was too long to parse.") national_number = _build_national_number_for_parsing(number) if not _is_viable_phone_number(national_number): raise NumberParseException(NumberParseException.NOT_A_NUMBER, "The string supplied did not seem to be a phone number.") # Check the region supplied is valid, or that the extracted number starts # with some sort of + sign so the number's region can be determined. if _check_region and not _check_region_for_parsing(national_number, region): raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Missing or invalid default region.") if keep_raw_input: numobj.raw_input = number # Attempt to parse extension first, since it doesn't require # region-specific data and we want to have the non-normalised number here. extension, national_number = _maybe_strip_extension(national_number) if len(extension) > 0: numobj.extension = extension if region is None: metadata = None else: metadata = PhoneMetadata.metadata_for_region(region.upper(), None) country_code = 0 try: country_code, normalized_national_number = _maybe_extract_country_code(national_number, metadata, keep_raw_input, numobj) except NumberParseException: _, e, _ = sys.exc_info() matchobj = _PLUS_CHARS_PATTERN.match(national_number) if (e.error_type == NumberParseException.INVALID_COUNTRY_CODE and matchobj is not None): # Strip the plus-char, and try again. country_code, normalized_national_number = _maybe_extract_country_code(national_number[matchobj.end():], metadata, keep_raw_input, numobj) if country_code == 0: raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Could not interpret numbers after plus-sign.") else: raise if country_code != 0: number_region = region_code_for_country_code(country_code) if number_region != region: # Metadata cannot be null because the country calling code is valid. metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, number_region) else: # If no extracted country calling code, use the region supplied # instead. The national number is just the normalized version of the # number we were given to parse. normalized_national_number += _normalize(national_number) if region is not None: country_code = metadata.country_code numobj.country_code = country_code elif keep_raw_input: numobj.country_code_source = CountryCodeSource.UNSPECIFIED if len(normalized_national_number) < _MIN_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_SHORT_NSN, "The string supplied is too short to be a phone number.") if metadata is not None: potential_national_number = normalized_national_number carrier_code, potential_national_number, _ = _maybe_strip_national_prefix_carrier_code(potential_national_number, metadata) # We require that the NSN remaining after stripping the national # prefix and carrier code be long enough to be a possible length for # the region. Otherwise, we don't do the stripping, since the original # number could be a valid short number. validation_result = _test_number_length(potential_national_number, metadata) if validation_result not in (ValidationResult.TOO_SHORT, ValidationResult.IS_POSSIBLE_LOCAL_ONLY, ValidationResult.INVALID_LENGTH): normalized_national_number = potential_national_number if keep_raw_input and carrier_code is not None and len(carrier_code) > 0: numobj.preferred_domestic_carrier_code = carrier_code len_national_number = len(normalized_national_number) if len_national_number < _MIN_LENGTH_FOR_NSN: # pragma no cover # Check of _is_viable_phone_number() at the top of this function makes # this effectively unhittable. raise NumberParseException(NumberParseException.TOO_SHORT_NSN, "The string supplied is too short to be a phone number.") if len_national_number > _MAX_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_LONG, "The string supplied is too long to be a phone number.") _set_italian_leading_zeros_for_phone_number(normalized_national_number, numobj) numobj.national_number = to_long(normalized_national_number) return numobj
python
def parse(number, region=None, keep_raw_input=False, numobj=None, _check_region=True): """Parse a string and return a corresponding PhoneNumber object. The method is quite lenient and looks for a number in the input text (raw input) and does not check whether the string is definitely only a phone number. To do this, it ignores punctuation and white-space, as well as any text before the number (e.g. a leading "Tel: ") and trims the non-number bits. It will accept a number in any format (E164, national, international etc), assuming it can be interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters into digits if it thinks this is a vanity number of the type "1800 MICROSOFT". This method will throw a NumberParseException if the number is not considered to be a possible number. Note that validation of whether the number is actually a valid number for a particular region is not performed. This can be done separately with is_valid_number. Note this method canonicalizes the phone number such that different representations can be easily compared, no matter what form it was originally entered in (e.g. national, international). If you want to record context about the number being parsed, such as the raw input that was entered, how the country code was derived etc. then ensure keep_raw_input is set. Note if any new field is added to this method that should always be filled in, even when keep_raw_input is False, it should also be handled in the _copy_core_fields_only() function. Arguments: number -- The number that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension. It can also be provided in RFC3966 format. region -- The region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. If the number is guaranteed to start with a '+' followed by the country calling code, then None or UNKNOWN_REGION can be supplied. keep_raw_input -- Whether to populate the raw_input field of the PhoneNumber object with number (as well as the country_code_source field). numobj -- An optional existing PhoneNumber object to receive the parsing results _check_region -- Whether to check the supplied region parameter; should always be True for external callers. Returns a PhoneNumber object filled with the parse number. Raises: NumberParseException if the string is not considered to be a viable phone number (e.g. too few or too many digits) or if no default region was supplied and the number is not in international format (does not start with +). """ if numobj is None: numobj = PhoneNumber() if number is None: raise NumberParseException(NumberParseException.NOT_A_NUMBER, "The phone number supplied was None.") elif len(number) > _MAX_INPUT_STRING_LENGTH: raise NumberParseException(NumberParseException.TOO_LONG, "The string supplied was too long to parse.") national_number = _build_national_number_for_parsing(number) if not _is_viable_phone_number(national_number): raise NumberParseException(NumberParseException.NOT_A_NUMBER, "The string supplied did not seem to be a phone number.") # Check the region supplied is valid, or that the extracted number starts # with some sort of + sign so the number's region can be determined. if _check_region and not _check_region_for_parsing(national_number, region): raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Missing or invalid default region.") if keep_raw_input: numobj.raw_input = number # Attempt to parse extension first, since it doesn't require # region-specific data and we want to have the non-normalised number here. extension, national_number = _maybe_strip_extension(national_number) if len(extension) > 0: numobj.extension = extension if region is None: metadata = None else: metadata = PhoneMetadata.metadata_for_region(region.upper(), None) country_code = 0 try: country_code, normalized_national_number = _maybe_extract_country_code(national_number, metadata, keep_raw_input, numobj) except NumberParseException: _, e, _ = sys.exc_info() matchobj = _PLUS_CHARS_PATTERN.match(national_number) if (e.error_type == NumberParseException.INVALID_COUNTRY_CODE and matchobj is not None): # Strip the plus-char, and try again. country_code, normalized_national_number = _maybe_extract_country_code(national_number[matchobj.end():], metadata, keep_raw_input, numobj) if country_code == 0: raise NumberParseException(NumberParseException.INVALID_COUNTRY_CODE, "Could not interpret numbers after plus-sign.") else: raise if country_code != 0: number_region = region_code_for_country_code(country_code) if number_region != region: # Metadata cannot be null because the country calling code is valid. metadata = PhoneMetadata.metadata_for_region_or_calling_code(country_code, number_region) else: # If no extracted country calling code, use the region supplied # instead. The national number is just the normalized version of the # number we were given to parse. normalized_national_number += _normalize(national_number) if region is not None: country_code = metadata.country_code numobj.country_code = country_code elif keep_raw_input: numobj.country_code_source = CountryCodeSource.UNSPECIFIED if len(normalized_national_number) < _MIN_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_SHORT_NSN, "The string supplied is too short to be a phone number.") if metadata is not None: potential_national_number = normalized_national_number carrier_code, potential_national_number, _ = _maybe_strip_national_prefix_carrier_code(potential_national_number, metadata) # We require that the NSN remaining after stripping the national # prefix and carrier code be long enough to be a possible length for # the region. Otherwise, we don't do the stripping, since the original # number could be a valid short number. validation_result = _test_number_length(potential_national_number, metadata) if validation_result not in (ValidationResult.TOO_SHORT, ValidationResult.IS_POSSIBLE_LOCAL_ONLY, ValidationResult.INVALID_LENGTH): normalized_national_number = potential_national_number if keep_raw_input and carrier_code is not None and len(carrier_code) > 0: numobj.preferred_domestic_carrier_code = carrier_code len_national_number = len(normalized_national_number) if len_national_number < _MIN_LENGTH_FOR_NSN: # pragma no cover # Check of _is_viable_phone_number() at the top of this function makes # this effectively unhittable. raise NumberParseException(NumberParseException.TOO_SHORT_NSN, "The string supplied is too short to be a phone number.") if len_national_number > _MAX_LENGTH_FOR_NSN: raise NumberParseException(NumberParseException.TOO_LONG, "The string supplied is too long to be a phone number.") _set_italian_leading_zeros_for_phone_number(normalized_national_number, numobj) numobj.national_number = to_long(normalized_national_number) return numobj
[ "def", "parse", "(", "number", ",", "region", "=", "None", ",", "keep_raw_input", "=", "False", ",", "numobj", "=", "None", ",", "_check_region", "=", "True", ")", ":", "if", "numobj", "is", "None", ":", "numobj", "=", "PhoneNumber", "(", ")", "if", ...
Parse a string and return a corresponding PhoneNumber object. The method is quite lenient and looks for a number in the input text (raw input) and does not check whether the string is definitely only a phone number. To do this, it ignores punctuation and white-space, as well as any text before the number (e.g. a leading "Tel: ") and trims the non-number bits. It will accept a number in any format (E164, national, international etc), assuming it can be interpreted with the defaultRegion supplied. It also attempts to convert any alpha characters into digits if it thinks this is a vanity number of the type "1800 MICROSOFT". This method will throw a NumberParseException if the number is not considered to be a possible number. Note that validation of whether the number is actually a valid number for a particular region is not performed. This can be done separately with is_valid_number. Note this method canonicalizes the phone number such that different representations can be easily compared, no matter what form it was originally entered in (e.g. national, international). If you want to record context about the number being parsed, such as the raw input that was entered, how the country code was derived etc. then ensure keep_raw_input is set. Note if any new field is added to this method that should always be filled in, even when keep_raw_input is False, it should also be handled in the _copy_core_fields_only() function. Arguments: number -- The number that we are attempting to parse. This can contain formatting such as +, ( and -, as well as a phone number extension. It can also be provided in RFC3966 format. region -- The region that we are expecting the number to be from. This is only used if the number being parsed is not written in international format. The country_code for the number in this case would be stored as that of the default region supplied. If the number is guaranteed to start with a '+' followed by the country calling code, then None or UNKNOWN_REGION can be supplied. keep_raw_input -- Whether to populate the raw_input field of the PhoneNumber object with number (as well as the country_code_source field). numobj -- An optional existing PhoneNumber object to receive the parsing results _check_region -- Whether to check the supplied region parameter; should always be True for external callers. Returns a PhoneNumber object filled with the parse number. Raises: NumberParseException if the string is not considered to be a viable phone number (e.g. too few or too many digits) or if no default region was supplied and the number is not in international format (does not start with +).
[ "Parse", "a", "string", "and", "return", "a", "corresponding", "PhoneNumber", "object", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2735-L2893
train
215,718
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_build_national_number_for_parsing
def _build_national_number_for_parsing(number): """Converts number to a form that we can parse and return it if it is written in RFC3966; otherwise extract a possible number out of it and return it.""" index_of_phone_context = number.find(_RFC3966_PHONE_CONTEXT) if index_of_phone_context >= 0: phone_context_start = index_of_phone_context + len(_RFC3966_PHONE_CONTEXT) # If the phone context contains a phone number prefix, we need to # capture it, whereas domains will be ignored. if (phone_context_start < (len(number) - 1) and number[phone_context_start] == _PLUS_SIGN): # Additional parameters might follow the phone context. If so, we # will remove them here because the parameters after phone context # are not important for parsing the phone number. phone_context_end = number.find(U_SEMICOLON, phone_context_start) if phone_context_end > 0: national_number = number[phone_context_start:phone_context_end] else: national_number = number[phone_context_start:] else: national_number = U_EMPTY_STRING # Now append everything between the "tel:" prefix and the # phone-context. This should include the national number, an optional # extension or isdn-subaddress component. Note we also handle the case # when "tel:" is missing, as we have seen in some of the phone number # inputs. In that case we append everything from the beginning. index_of_rfc3996_prefix = number.find(_RFC3966_PREFIX) index_of_national_number = ((index_of_rfc3996_prefix + len(_RFC3966_PREFIX)) if (index_of_rfc3996_prefix >= 0) else 0) national_number += number[index_of_national_number:index_of_phone_context] else: # Extract a possible number from the string passed in (this strips leading characters that # could not be the start of a phone number.) national_number = _extract_possible_number(number) # Delete the isdn-subaddress and everything after it if it is # present. Note extension won't appear at the same time with # isdn-subaddress according to paragraph 5.3 of the RFC3966 spec, index_of_isdn = national_number.find(_RFC3966_ISDN_SUBADDRESS) if index_of_isdn > 0: national_number = national_number[:index_of_isdn] # If both phone context and isdn-subaddress are absent but other # parameters are present, the parameters are left in national_number. This # is because we are concerned about deleting content from a potential # number string when there is no strong evidence that the number is # actually written in RFC3966. return national_number
python
def _build_national_number_for_parsing(number): """Converts number to a form that we can parse and return it if it is written in RFC3966; otherwise extract a possible number out of it and return it.""" index_of_phone_context = number.find(_RFC3966_PHONE_CONTEXT) if index_of_phone_context >= 0: phone_context_start = index_of_phone_context + len(_RFC3966_PHONE_CONTEXT) # If the phone context contains a phone number prefix, we need to # capture it, whereas domains will be ignored. if (phone_context_start < (len(number) - 1) and number[phone_context_start] == _PLUS_SIGN): # Additional parameters might follow the phone context. If so, we # will remove them here because the parameters after phone context # are not important for parsing the phone number. phone_context_end = number.find(U_SEMICOLON, phone_context_start) if phone_context_end > 0: national_number = number[phone_context_start:phone_context_end] else: national_number = number[phone_context_start:] else: national_number = U_EMPTY_STRING # Now append everything between the "tel:" prefix and the # phone-context. This should include the national number, an optional # extension or isdn-subaddress component. Note we also handle the case # when "tel:" is missing, as we have seen in some of the phone number # inputs. In that case we append everything from the beginning. index_of_rfc3996_prefix = number.find(_RFC3966_PREFIX) index_of_national_number = ((index_of_rfc3996_prefix + len(_RFC3966_PREFIX)) if (index_of_rfc3996_prefix >= 0) else 0) national_number += number[index_of_national_number:index_of_phone_context] else: # Extract a possible number from the string passed in (this strips leading characters that # could not be the start of a phone number.) national_number = _extract_possible_number(number) # Delete the isdn-subaddress and everything after it if it is # present. Note extension won't appear at the same time with # isdn-subaddress according to paragraph 5.3 of the RFC3966 spec, index_of_isdn = national_number.find(_RFC3966_ISDN_SUBADDRESS) if index_of_isdn > 0: national_number = national_number[:index_of_isdn] # If both phone context and isdn-subaddress are absent but other # parameters are present, the parameters are left in national_number. This # is because we are concerned about deleting content from a potential # number string when there is no strong evidence that the number is # actually written in RFC3966. return national_number
[ "def", "_build_national_number_for_parsing", "(", "number", ")", ":", "index_of_phone_context", "=", "number", ".", "find", "(", "_RFC3966_PHONE_CONTEXT", ")", "if", "index_of_phone_context", ">=", "0", ":", "phone_context_start", "=", "index_of_phone_context", "+", "le...
Converts number to a form that we can parse and return it if it is written in RFC3966; otherwise extract a possible number out of it and return it.
[ "Converts", "number", "to", "a", "form", "that", "we", "can", "parse", "and", "return", "it", "if", "it", "is", "written", "in", "RFC3966", ";", "otherwise", "extract", "a", "possible", "number", "out", "of", "it", "and", "return", "it", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2896-L2941
train
215,719
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_copy_core_fields_only
def _copy_core_fields_only(inobj): """Returns a new phone number containing only the fields needed to uniquely identify a phone number, rather than any fields that capture the context in which the phone number was created. """ numobj = PhoneNumber() numobj.country_code = inobj.country_code numobj.national_number = inobj.national_number if inobj.extension is not None and len(inobj.extension) > 0: numobj.extension = inobj.extension if inobj.italian_leading_zero: numobj.italian_leading_zero = True # This field is only relevant if there are leading zeros at all. numobj.number_of_leading_zeros = inobj.number_of_leading_zeros if numobj.number_of_leading_zeros is None: # No number set is implicitly a count of 1; make it explicit. numobj.number_of_leading_zeros = 1 return numobj
python
def _copy_core_fields_only(inobj): """Returns a new phone number containing only the fields needed to uniquely identify a phone number, rather than any fields that capture the context in which the phone number was created. """ numobj = PhoneNumber() numobj.country_code = inobj.country_code numobj.national_number = inobj.national_number if inobj.extension is not None and len(inobj.extension) > 0: numobj.extension = inobj.extension if inobj.italian_leading_zero: numobj.italian_leading_zero = True # This field is only relevant if there are leading zeros at all. numobj.number_of_leading_zeros = inobj.number_of_leading_zeros if numobj.number_of_leading_zeros is None: # No number set is implicitly a count of 1; make it explicit. numobj.number_of_leading_zeros = 1 return numobj
[ "def", "_copy_core_fields_only", "(", "inobj", ")", ":", "numobj", "=", "PhoneNumber", "(", ")", "numobj", ".", "country_code", "=", "inobj", ".", "country_code", "numobj", ".", "national_number", "=", "inobj", ".", "national_number", "if", "inobj", ".", "exte...
Returns a new phone number containing only the fields needed to uniquely identify a phone number, rather than any fields that capture the context in which the phone number was created.
[ "Returns", "a", "new", "phone", "number", "containing", "only", "the", "fields", "needed", "to", "uniquely", "identify", "a", "phone", "number", "rather", "than", "any", "fields", "that", "capture", "the", "context", "in", "which", "the", "phone", "number", ...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2944-L2961
train
215,720
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_number_match_OO
def _is_number_match_OO(numobj1_in, numobj2_in): """Takes two phone number objects and compares them for equality.""" # We only care about the fields that uniquely define a number, so we copy these across explicitly. numobj1 = _copy_core_fields_only(numobj1_in) numobj2 = _copy_core_fields_only(numobj2_in) # Early exit if both had extensions and these are different. if (numobj1.extension is not None and numobj2.extension is not None and numobj1.extension != numobj2.extension): return MatchType.NO_MATCH country_code1 = numobj1.country_code country_code2 = numobj2.country_code # Both had country_code specified. if country_code1 != 0 and country_code2 != 0: if numobj1 == numobj2: return MatchType.EXACT_MATCH elif (country_code1 == country_code2 and _is_national_number_suffix_of_other(numobj1, numobj2)): # A SHORT_NSN_MATCH occurs if there is a difference because of the # presence or absence of an 'Italian leading zero', the presence # or absence of an extension, or one NSN being a shorter variant # of the other. return MatchType.SHORT_NSN_MATCH # This is not a match. return MatchType.NO_MATCH # Checks cases where one or both country_code fields were not # specified. To make equality checks easier, we first set the country_code # fields to be equal. numobj1.country_code = country_code2 # If all else was the same, then this is an NSN_MATCH. if numobj1 == numobj2: return MatchType.NSN_MATCH if _is_national_number_suffix_of_other(numobj1, numobj2): return MatchType.SHORT_NSN_MATCH return MatchType.NO_MATCH
python
def _is_number_match_OO(numobj1_in, numobj2_in): """Takes two phone number objects and compares them for equality.""" # We only care about the fields that uniquely define a number, so we copy these across explicitly. numobj1 = _copy_core_fields_only(numobj1_in) numobj2 = _copy_core_fields_only(numobj2_in) # Early exit if both had extensions and these are different. if (numobj1.extension is not None and numobj2.extension is not None and numobj1.extension != numobj2.extension): return MatchType.NO_MATCH country_code1 = numobj1.country_code country_code2 = numobj2.country_code # Both had country_code specified. if country_code1 != 0 and country_code2 != 0: if numobj1 == numobj2: return MatchType.EXACT_MATCH elif (country_code1 == country_code2 and _is_national_number_suffix_of_other(numobj1, numobj2)): # A SHORT_NSN_MATCH occurs if there is a difference because of the # presence or absence of an 'Italian leading zero', the presence # or absence of an extension, or one NSN being a shorter variant # of the other. return MatchType.SHORT_NSN_MATCH # This is not a match. return MatchType.NO_MATCH # Checks cases where one or both country_code fields were not # specified. To make equality checks easier, we first set the country_code # fields to be equal. numobj1.country_code = country_code2 # If all else was the same, then this is an NSN_MATCH. if numobj1 == numobj2: return MatchType.NSN_MATCH if _is_national_number_suffix_of_other(numobj1, numobj2): return MatchType.SHORT_NSN_MATCH return MatchType.NO_MATCH
[ "def", "_is_number_match_OO", "(", "numobj1_in", ",", "numobj2_in", ")", ":", "# We only care about the fields that uniquely define a number, so we copy these across explicitly.", "numobj1", "=", "_copy_core_fields_only", "(", "numobj1_in", ")", "numobj2", "=", "_copy_core_fields_o...
Takes two phone number objects and compares them for equality.
[ "Takes", "two", "phone", "number", "objects", "and", "compares", "them", "for", "equality", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L2964-L3001
train
215,721
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_national_number_suffix_of_other
def _is_national_number_suffix_of_other(numobj1, numobj2): """Returns true when one national number is the suffix of the other or both are the same. """ nn1 = str(numobj1.national_number) nn2 = str(numobj2.national_number) # Note that endswith returns True if the numbers are equal. return nn1.endswith(nn2) or nn2.endswith(nn1)
python
def _is_national_number_suffix_of_other(numobj1, numobj2): """Returns true when one national number is the suffix of the other or both are the same. """ nn1 = str(numobj1.national_number) nn2 = str(numobj2.national_number) # Note that endswith returns True if the numbers are equal. return nn1.endswith(nn2) or nn2.endswith(nn1)
[ "def", "_is_national_number_suffix_of_other", "(", "numobj1", ",", "numobj2", ")", ":", "nn1", "=", "str", "(", "numobj1", ".", "national_number", ")", "nn2", "=", "str", "(", "numobj2", ".", "national_number", ")", "# Note that endswith returns True if the numbers ar...
Returns true when one national number is the suffix of the other or both are the same.
[ "Returns", "true", "when", "one", "national", "number", "is", "the", "suffix", "of", "the", "other", "or", "both", "are", "the", "same", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3004-L3011
train
215,722
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_number_match_SS
def _is_number_match_SS(number1, number2): """Takes two phone numbers as strings and compares them for equality. This is a convenience wrapper for _is_number_match_OO/_is_number_match_OS. No default region is known. """ try: numobj1 = parse(number1, UNKNOWN_REGION) return _is_number_match_OS(numobj1, number2) except NumberParseException: _, exc, _ = sys.exc_info() if exc.error_type == NumberParseException.INVALID_COUNTRY_CODE: try: numobj2 = parse(number2, UNKNOWN_REGION) return _is_number_match_OS(numobj2, number1) except NumberParseException: _, exc2, _ = sys.exc_info() if exc2.error_type == NumberParseException.INVALID_COUNTRY_CODE: try: numobj1 = parse(number1, None, keep_raw_input=False, _check_region=False, numobj=None) numobj2 = parse(number2, None, keep_raw_input=False, _check_region=False, numobj=None) return _is_number_match_OO(numobj1, numobj2) except NumberParseException: return MatchType.NOT_A_NUMBER # One or more of the phone numbers we are trying to match is not a viable # phone number. return MatchType.NOT_A_NUMBER
python
def _is_number_match_SS(number1, number2): """Takes two phone numbers as strings and compares them for equality. This is a convenience wrapper for _is_number_match_OO/_is_number_match_OS. No default region is known. """ try: numobj1 = parse(number1, UNKNOWN_REGION) return _is_number_match_OS(numobj1, number2) except NumberParseException: _, exc, _ = sys.exc_info() if exc.error_type == NumberParseException.INVALID_COUNTRY_CODE: try: numobj2 = parse(number2, UNKNOWN_REGION) return _is_number_match_OS(numobj2, number1) except NumberParseException: _, exc2, _ = sys.exc_info() if exc2.error_type == NumberParseException.INVALID_COUNTRY_CODE: try: numobj1 = parse(number1, None, keep_raw_input=False, _check_region=False, numobj=None) numobj2 = parse(number2, None, keep_raw_input=False, _check_region=False, numobj=None) return _is_number_match_OO(numobj1, numobj2) except NumberParseException: return MatchType.NOT_A_NUMBER # One or more of the phone numbers we are trying to match is not a viable # phone number. return MatchType.NOT_A_NUMBER
[ "def", "_is_number_match_SS", "(", "number1", ",", "number2", ")", ":", "try", ":", "numobj1", "=", "parse", "(", "number1", ",", "UNKNOWN_REGION", ")", "return", "_is_number_match_OS", "(", "numobj1", ",", "number2", ")", "except", "NumberParseException", ":", ...
Takes two phone numbers as strings and compares them for equality. This is a convenience wrapper for _is_number_match_OO/_is_number_match_OS. No default region is known.
[ "Takes", "two", "phone", "numbers", "as", "strings", "and", "compares", "them", "for", "equality", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3014-L3043
train
215,723
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
_is_number_match_OS
def _is_number_match_OS(numobj1, number2): """Wrapper variant of _is_number_match_OO that copes with one PhoneNumber object and one string.""" # First see if the second number has an implicit country calling code, by # attempting to parse it. try: numobj2 = parse(number2, UNKNOWN_REGION) return _is_number_match_OO(numobj1, numobj2) except NumberParseException: _, exc, _ = sys.exc_info() if exc.error_type == NumberParseException.INVALID_COUNTRY_CODE: # The second number has no country calling code. EXACT_MATCH is no # longer possible. We parse it as if the region was the same as # that for the first number, and if EXACT_MATCH is returned, we # replace this with NSN_MATCH. region1 = region_code_for_country_code(numobj1.country_code) try: if region1 != UNKNOWN_REGION: numobj2 = parse(number2, region1) match = _is_number_match_OO(numobj1, numobj2) if match == MatchType.EXACT_MATCH: return MatchType.NSN_MATCH else: return match else: # If the first number didn't have a valid country calling # code, then we parse the second number without one as # well. numobj2 = parse(number2, None, keep_raw_input=False, _check_region=False, numobj=None) return _is_number_match_OO(numobj1, numobj2) except NumberParseException: return MatchType.NOT_A_NUMBER # One or more of the phone numbers we are trying to match is not a viable # phone number. return MatchType.NOT_A_NUMBER
python
def _is_number_match_OS(numobj1, number2): """Wrapper variant of _is_number_match_OO that copes with one PhoneNumber object and one string.""" # First see if the second number has an implicit country calling code, by # attempting to parse it. try: numobj2 = parse(number2, UNKNOWN_REGION) return _is_number_match_OO(numobj1, numobj2) except NumberParseException: _, exc, _ = sys.exc_info() if exc.error_type == NumberParseException.INVALID_COUNTRY_CODE: # The second number has no country calling code. EXACT_MATCH is no # longer possible. We parse it as if the region was the same as # that for the first number, and if EXACT_MATCH is returned, we # replace this with NSN_MATCH. region1 = region_code_for_country_code(numobj1.country_code) try: if region1 != UNKNOWN_REGION: numobj2 = parse(number2, region1) match = _is_number_match_OO(numobj1, numobj2) if match == MatchType.EXACT_MATCH: return MatchType.NSN_MATCH else: return match else: # If the first number didn't have a valid country calling # code, then we parse the second number without one as # well. numobj2 = parse(number2, None, keep_raw_input=False, _check_region=False, numobj=None) return _is_number_match_OO(numobj1, numobj2) except NumberParseException: return MatchType.NOT_A_NUMBER # One or more of the phone numbers we are trying to match is not a viable # phone number. return MatchType.NOT_A_NUMBER
[ "def", "_is_number_match_OS", "(", "numobj1", ",", "number2", ")", ":", "# First see if the second number has an implicit country calling code, by", "# attempting to parse it.", "try", ":", "numobj2", "=", "parse", "(", "number2", ",", "UNKNOWN_REGION", ")", "return", "_is_...
Wrapper variant of _is_number_match_OO that copes with one PhoneNumber object and one string.
[ "Wrapper", "variant", "of", "_is_number_match_OO", "that", "copes", "with", "one", "PhoneNumber", "object", "and", "one", "string", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3046-L3081
train
215,724
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_number_match
def is_number_match(num1, num2): """Takes two phone numbers and compares them for equality. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. Arguments num1 -- First number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. num2 -- Second number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. Returns: - EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers and any extension present are the same. - NSN_MATCH if either or both has no region specified, and the NSNs and extensions are the same. - SHORT_NSN_MATCH if either or both has no region specified, or the region specified is the same, and one NSN could be a shorter version of the other number. This includes the case where one has an extension specified, and the other does not. - NO_MATCH otherwise. """ if isinstance(num1, PhoneNumber) and isinstance(num2, PhoneNumber): return _is_number_match_OO(num1, num2) elif isinstance(num1, PhoneNumber): return _is_number_match_OS(num1, num2) elif isinstance(num2, PhoneNumber): return _is_number_match_OS(num2, num1) else: return _is_number_match_SS(num1, num2)
python
def is_number_match(num1, num2): """Takes two phone numbers and compares them for equality. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. Arguments num1 -- First number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. num2 -- Second number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. Returns: - EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers and any extension present are the same. - NSN_MATCH if either or both has no region specified, and the NSNs and extensions are the same. - SHORT_NSN_MATCH if either or both has no region specified, or the region specified is the same, and one NSN could be a shorter version of the other number. This includes the case where one has an extension specified, and the other does not. - NO_MATCH otherwise. """ if isinstance(num1, PhoneNumber) and isinstance(num2, PhoneNumber): return _is_number_match_OO(num1, num2) elif isinstance(num1, PhoneNumber): return _is_number_match_OS(num1, num2) elif isinstance(num2, PhoneNumber): return _is_number_match_OS(num2, num1) else: return _is_number_match_SS(num1, num2)
[ "def", "is_number_match", "(", "num1", ",", "num2", ")", ":", "if", "isinstance", "(", "num1", ",", "PhoneNumber", ")", "and", "isinstance", "(", "num2", ",", "PhoneNumber", ")", ":", "return", "_is_number_match_OO", "(", "num1", ",", "num2", ")", "elif", ...
Takes two phone numbers and compares them for equality. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. Arguments num1 -- First number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. num2 -- Second number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. Returns: - EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers and any extension present are the same. - NSN_MATCH if either or both has no region specified, and the NSNs and extensions are the same. - SHORT_NSN_MATCH if either or both has no region specified, or the region specified is the same, and one NSN could be a shorter version of the other number. This includes the case where one has an extension specified, and the other does not. - NO_MATCH otherwise.
[ "Takes", "two", "phone", "numbers", "and", "compares", "them", "for", "equality", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3084-L3114
train
215,725
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
can_be_internationally_dialled
def can_be_internationally_dialled(numobj): """Returns True if the number can only be dialled from outside the region, or unknown. If the number can only be dialled from within the region as well, returns False. Does not check the number is a valid number. Note that, at the moment, this method does not handle short numbers (which are currently all presumed to not be diallable from outside their country). Arguments: numobj -- the phone number objectfor which we want to know whether it is diallable from outside the region. """ metadata = PhoneMetadata.metadata_for_region(region_code_for_number(numobj), None) if metadata is None: # Note numbers belonging to non-geographical entities (e.g. +800 # numbers) are always internationally diallable, and will be caught # here. return True nsn = national_significant_number(numobj) return not _is_number_matching_desc(nsn, metadata.no_international_dialling)
python
def can_be_internationally_dialled(numobj): """Returns True if the number can only be dialled from outside the region, or unknown. If the number can only be dialled from within the region as well, returns False. Does not check the number is a valid number. Note that, at the moment, this method does not handle short numbers (which are currently all presumed to not be diallable from outside their country). Arguments: numobj -- the phone number objectfor which we want to know whether it is diallable from outside the region. """ metadata = PhoneMetadata.metadata_for_region(region_code_for_number(numobj), None) if metadata is None: # Note numbers belonging to non-geographical entities (e.g. +800 # numbers) are always internationally diallable, and will be caught # here. return True nsn = national_significant_number(numobj) return not _is_number_matching_desc(nsn, metadata.no_international_dialling)
[ "def", "can_be_internationally_dialled", "(", "numobj", ")", ":", "metadata", "=", "PhoneMetadata", ".", "metadata_for_region", "(", "region_code_for_number", "(", "numobj", ")", ",", "None", ")", "if", "metadata", "is", "None", ":", "# Note numbers belonging to non-g...
Returns True if the number can only be dialled from outside the region, or unknown. If the number can only be dialled from within the region as well, returns False. Does not check the number is a valid number. Note that, at the moment, this method does not handle short numbers (which are currently all presumed to not be diallable from outside their country). Arguments: numobj -- the phone number objectfor which we want to know whether it is diallable from outside the region.
[ "Returns", "True", "if", "the", "number", "can", "only", "be", "dialled", "from", "outside", "the", "region", "or", "unknown", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3117-L3137
train
215,726
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
is_mobile_number_portable_region
def is_mobile_number_portable_region(region_code): """Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability. Arguments: region_code -- the region for which we want to know whether it supports mobile number portability or not. """ metadata = PhoneMetadata.metadata_for_region(region_code, None) if metadata is None: return False return metadata.mobile_number_portable_region
python
def is_mobile_number_portable_region(region_code): """Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability. Arguments: region_code -- the region for which we want to know whether it supports mobile number portability or not. """ metadata = PhoneMetadata.metadata_for_region(region_code, None) if metadata is None: return False return metadata.mobile_number_portable_region
[ "def", "is_mobile_number_portable_region", "(", "region_code", ")", ":", "metadata", "=", "PhoneMetadata", ".", "metadata_for_region", "(", "region_code", ",", "None", ")", "if", "metadata", "is", "None", ":", "return", "False", "return", "metadata", ".", "mobile_...
Returns true if the supplied region supports mobile number portability. Returns false for invalid, unknown or regions that don't support mobile number portability. Arguments: region_code -- the region for which we want to know whether it supports mobile number portability or not.
[ "Returns", "true", "if", "the", "supplied", "region", "supports", "mobile", "number", "portability", ".", "Returns", "false", "for", "invalid", "unknown", "or", "regions", "that", "don", "t", "support", "mobile", "number", "portability", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3140-L3152
train
215,727
daviddrysdale/python-phonenumbers
python/phonenumbers/timezone.py
time_zones_for_geographical_number
def time_zones_for_geographical_number(numobj): """Returns a list of time zones to which a phone number belongs. This method assumes the validity of the number passed in has already been checked, and that the number is geo-localizable. We consider fixed-line and mobile numbers possible candidates for geo-localization. Arguments: numobj -- a valid phone number for which we want to get the time zones to which it belongs Returns a list of the corresponding time zones or a single element list with the default unknown time zone if no other time zone was found or if the number was invalid""" e164_num = format_number(numobj, PhoneNumberFormat.E164) if not e164_num.startswith(U_PLUS): # pragma no cover # Can only hit this arm if there's an internal error in the rest of # the library raise Exception("Expect E164 number to start with +") for prefix_len in range(TIMEZONE_LONGEST_PREFIX, 0, -1): prefix = e164_num[1:(1 + prefix_len)] if prefix in TIMEZONE_DATA: return TIMEZONE_DATA[prefix] return _UNKNOWN_TIME_ZONE_LIST
python
def time_zones_for_geographical_number(numobj): """Returns a list of time zones to which a phone number belongs. This method assumes the validity of the number passed in has already been checked, and that the number is geo-localizable. We consider fixed-line and mobile numbers possible candidates for geo-localization. Arguments: numobj -- a valid phone number for which we want to get the time zones to which it belongs Returns a list of the corresponding time zones or a single element list with the default unknown time zone if no other time zone was found or if the number was invalid""" e164_num = format_number(numobj, PhoneNumberFormat.E164) if not e164_num.startswith(U_PLUS): # pragma no cover # Can only hit this arm if there's an internal error in the rest of # the library raise Exception("Expect E164 number to start with +") for prefix_len in range(TIMEZONE_LONGEST_PREFIX, 0, -1): prefix = e164_num[1:(1 + prefix_len)] if prefix in TIMEZONE_DATA: return TIMEZONE_DATA[prefix] return _UNKNOWN_TIME_ZONE_LIST
[ "def", "time_zones_for_geographical_number", "(", "numobj", ")", ":", "e164_num", "=", "format_number", "(", "numobj", ",", "PhoneNumberFormat", ".", "E164", ")", "if", "not", "e164_num", ".", "startswith", "(", "U_PLUS", ")", ":", "# pragma no cover", "# Can only...
Returns a list of time zones to which a phone number belongs. This method assumes the validity of the number passed in has already been checked, and that the number is geo-localizable. We consider fixed-line and mobile numbers possible candidates for geo-localization. Arguments: numobj -- a valid phone number for which we want to get the time zones to which it belongs Returns a list of the corresponding time zones or a single element list with the default unknown time zone if no other time zone was found or if the number was invalid
[ "Returns", "a", "list", "of", "time", "zones", "to", "which", "a", "phone", "number", "belongs", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/timezone.py#L64-L86
train
215,728
daviddrysdale/python-phonenumbers
python/phonenumbers/unicode_util.py
is_letter
def is_letter(uni_char): """Determine whether the given Unicode character is a Unicode letter""" category = Category.get(uni_char) return (category == Category.UPPERCASE_LETTER or category == Category.LOWERCASE_LETTER or category == Category.TITLECASE_LETTER or category == Category.MODIFIER_LETTER or category == Category.OTHER_LETTER)
python
def is_letter(uni_char): """Determine whether the given Unicode character is a Unicode letter""" category = Category.get(uni_char) return (category == Category.UPPERCASE_LETTER or category == Category.LOWERCASE_LETTER or category == Category.TITLECASE_LETTER or category == Category.MODIFIER_LETTER or category == Category.OTHER_LETTER)
[ "def", "is_letter", "(", "uni_char", ")", ":", "category", "=", "Category", ".", "get", "(", "uni_char", ")", "return", "(", "category", "==", "Category", ".", "UPPERCASE_LETTER", "or", "category", "==", "Category", ".", "LOWERCASE_LETTER", "or", "category", ...
Determine whether the given Unicode character is a Unicode letter
[ "Determine", "whether", "the", "given", "Unicode", "character", "is", "a", "Unicode", "letter" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/unicode_util.py#L128-L135
train
215,729
daviddrysdale/python-phonenumbers
python/phonenumbers/unicode_util.py
digit
def digit(uni_char, default_value=None): """Returns the digit value assigned to the Unicode character uni_char as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.""" uni_char = unicod(uni_char) # Force to Unicode. if default_value is not None: return unicodedata.digit(uni_char, default_value) else: return unicodedata.digit(uni_char)
python
def digit(uni_char, default_value=None): """Returns the digit value assigned to the Unicode character uni_char as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.""" uni_char = unicod(uni_char) # Force to Unicode. if default_value is not None: return unicodedata.digit(uni_char, default_value) else: return unicodedata.digit(uni_char)
[ "def", "digit", "(", "uni_char", ",", "default_value", "=", "None", ")", ":", "uni_char", "=", "unicod", "(", "uni_char", ")", "# Force to Unicode.", "if", "default_value", "is", "not", "None", ":", "return", "unicodedata", ".", "digit", "(", "uni_char", ","...
Returns the digit value assigned to the Unicode character uni_char as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.
[ "Returns", "the", "digit", "value", "assigned", "to", "the", "Unicode", "character", "uni_char", "as", "integer", ".", "If", "no", "such", "value", "is", "defined", "default", "is", "returned", "or", "if", "not", "given", "ValueError", "is", "raised", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/unicode_util.py#L397-L405
train
215,730
daviddrysdale/python-phonenumbers
python/phonenumbers/unicode_util.py
Block.get
def get(cls, uni_char): """Return the Unicode block of the given Unicode character""" uni_char = unicod(uni_char) # Force to Unicode code_point = ord(uni_char) if Block._RANGE_KEYS is None: Block._RANGE_KEYS = sorted(Block._RANGES.keys()) idx = bisect.bisect_left(Block._RANGE_KEYS, code_point) if (idx > 0 and code_point >= Block._RANGES[Block._RANGE_KEYS[idx - 1]].start and code_point <= Block._RANGES[Block._RANGE_KEYS[idx - 1]].end): return Block._RANGES[Block._RANGE_KEYS[idx - 1]] elif (idx < len(Block._RANGES) and code_point >= Block._RANGES[Block._RANGE_KEYS[idx]].start and code_point <= Block._RANGES[Block._RANGE_KEYS[idx]].end): return Block._RANGES[Block._RANGE_KEYS[idx]] else: return Block.UNKNOWN
python
def get(cls, uni_char): """Return the Unicode block of the given Unicode character""" uni_char = unicod(uni_char) # Force to Unicode code_point = ord(uni_char) if Block._RANGE_KEYS is None: Block._RANGE_KEYS = sorted(Block._RANGES.keys()) idx = bisect.bisect_left(Block._RANGE_KEYS, code_point) if (idx > 0 and code_point >= Block._RANGES[Block._RANGE_KEYS[idx - 1]].start and code_point <= Block._RANGES[Block._RANGE_KEYS[idx - 1]].end): return Block._RANGES[Block._RANGE_KEYS[idx - 1]] elif (idx < len(Block._RANGES) and code_point >= Block._RANGES[Block._RANGE_KEYS[idx]].start and code_point <= Block._RANGES[Block._RANGE_KEYS[idx]].end): return Block._RANGES[Block._RANGE_KEYS[idx]] else: return Block.UNKNOWN
[ "def", "get", "(", "cls", ",", "uni_char", ")", ":", "uni_char", "=", "unicod", "(", "uni_char", ")", "# Force to Unicode", "code_point", "=", "ord", "(", "uni_char", ")", "if", "Block", ".", "_RANGE_KEYS", "is", "None", ":", "Block", ".", "_RANGE_KEYS", ...
Return the Unicode block of the given Unicode character
[ "Return", "the", "Unicode", "block", "of", "the", "given", "Unicode", "character" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/unicode_util.py#L378-L394
train
215,731
daviddrysdale/python-phonenumbers
python/phonenumbers/carrier.py
_is_mobile
def _is_mobile(ntype): """Checks if the supplied number type supports carrier lookup""" return (ntype == PhoneNumberType.MOBILE or ntype == PhoneNumberType.FIXED_LINE_OR_MOBILE or ntype == PhoneNumberType.PAGER)
python
def _is_mobile(ntype): """Checks if the supplied number type supports carrier lookup""" return (ntype == PhoneNumberType.MOBILE or ntype == PhoneNumberType.FIXED_LINE_OR_MOBILE or ntype == PhoneNumberType.PAGER)
[ "def", "_is_mobile", "(", "ntype", ")", ":", "return", "(", "ntype", "==", "PhoneNumberType", ".", "MOBILE", "or", "ntype", "==", "PhoneNumberType", ".", "FIXED_LINE_OR_MOBILE", "or", "ntype", "==", "PhoneNumberType", ".", "PAGER", ")" ]
Checks if the supplied number type supports carrier lookup
[ "Checks", "if", "the", "supplied", "number", "type", "supports", "carrier", "lookup" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/carrier.py#L136-L140
train
215,732
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumber.py
PhoneNumber.clear
def clear(self): """Erase the contents of the object""" self.country_code = None self.national_number = None self.extension = None self.italian_leading_zero = None self.number_of_leading_zeros = None self.raw_input = None self.country_code_source = CountryCodeSource.UNSPECIFIED self.preferred_domestic_carrier_code = None
python
def clear(self): """Erase the contents of the object""" self.country_code = None self.national_number = None self.extension = None self.italian_leading_zero = None self.number_of_leading_zeros = None self.raw_input = None self.country_code_source = CountryCodeSource.UNSPECIFIED self.preferred_domestic_carrier_code = None
[ "def", "clear", "(", "self", ")", ":", "self", ".", "country_code", "=", "None", "self", ".", "national_number", "=", "None", "self", ".", "extension", "=", "None", "self", ".", "italian_leading_zero", "=", "None", "self", ".", "number_of_leading_zeros", "="...
Erase the contents of the object
[ "Erase", "the", "contents", "of", "the", "object" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumber.py#L168-L177
train
215,733
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumber.py
PhoneNumber.merge_from
def merge_from(self, other): """Merge information from another PhoneNumber object into this one.""" if other.country_code is not None: self.country_code = other.country_code if other.national_number is not None: self.national_number = other.national_number if other.extension is not None: self.extension = other.extension if other.italian_leading_zero is not None: self.italian_leading_zero = other.italian_leading_zero if other.number_of_leading_zeros is not None: self.number_of_leading_zeros = other.number_of_leading_zeros if other.raw_input is not None: self.raw_input = other.raw_input if other.country_code_source is not CountryCodeSource.UNSPECIFIED: self.country_code_source = other.country_code_source if other.preferred_domestic_carrier_code is not None: self.preferred_domestic_carrier_code = other.preferred_domestic_carrier_code
python
def merge_from(self, other): """Merge information from another PhoneNumber object into this one.""" if other.country_code is not None: self.country_code = other.country_code if other.national_number is not None: self.national_number = other.national_number if other.extension is not None: self.extension = other.extension if other.italian_leading_zero is not None: self.italian_leading_zero = other.italian_leading_zero if other.number_of_leading_zeros is not None: self.number_of_leading_zeros = other.number_of_leading_zeros if other.raw_input is not None: self.raw_input = other.raw_input if other.country_code_source is not CountryCodeSource.UNSPECIFIED: self.country_code_source = other.country_code_source if other.preferred_domestic_carrier_code is not None: self.preferred_domestic_carrier_code = other.preferred_domestic_carrier_code
[ "def", "merge_from", "(", "self", ",", "other", ")", ":", "if", "other", ".", "country_code", "is", "not", "None", ":", "self", ".", "country_code", "=", "other", ".", "country_code", "if", "other", ".", "national_number", "is", "not", "None", ":", "self...
Merge information from another PhoneNumber object into this one.
[ "Merge", "information", "from", "another", "PhoneNumber", "object", "into", "this", "one", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumber.py#L179-L196
train
215,734
daviddrysdale/python-phonenumbers
python/phonenumbers/util.py
mutating_method
def mutating_method(func): """Decorator for methods that are allowed to modify immutable objects""" def wrapper(self, *__args, **__kwargs): old_mutable = self._mutable self._mutable = True try: # Call the wrapped function return func(self, *__args, **__kwargs) finally: self._mutable = old_mutable return wrapper
python
def mutating_method(func): """Decorator for methods that are allowed to modify immutable objects""" def wrapper(self, *__args, **__kwargs): old_mutable = self._mutable self._mutable = True try: # Call the wrapped function return func(self, *__args, **__kwargs) finally: self._mutable = old_mutable return wrapper
[ "def", "mutating_method", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "*", "__args", ",", "*", "*", "__kwargs", ")", ":", "old_mutable", "=", "self", ".", "_mutable", "self", ".", "_mutable", "=", "True", "try", ":", "# Call the wrapped fu...
Decorator for methods that are allowed to modify immutable objects
[ "Decorator", "for", "methods", "that", "are", "allowed", "to", "modify", "immutable", "objects" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/util.py#L169-L179
train
215,735
daviddrysdale/python-phonenumbers
python/phonenumbers/re_util.py
fullmatch
def fullmatch(pattern, string, flags=0): """Try to apply the pattern at the start of the string, returning a match object if the whole string matches, or None if no match was found.""" # Build a version of the pattern with a non-capturing group around it. # This is needed to get m.end() to correctly report the size of the # matched expression (as per the final doctest above). grouped_pattern = re.compile("^(?:%s)$" % pattern.pattern, pattern.flags) m = grouped_pattern.match(string) if m and m.end() < len(string): # Incomplete match (which should never happen because of the $ at the # end of the regexp), treat as failure. m = None # pragma no cover return m
python
def fullmatch(pattern, string, flags=0): """Try to apply the pattern at the start of the string, returning a match object if the whole string matches, or None if no match was found.""" # Build a version of the pattern with a non-capturing group around it. # This is needed to get m.end() to correctly report the size of the # matched expression (as per the final doctest above). grouped_pattern = re.compile("^(?:%s)$" % pattern.pattern, pattern.flags) m = grouped_pattern.match(string) if m and m.end() < len(string): # Incomplete match (which should never happen because of the $ at the # end of the regexp), treat as failure. m = None # pragma no cover return m
[ "def", "fullmatch", "(", "pattern", ",", "string", ",", "flags", "=", "0", ")", ":", "# Build a version of the pattern with a non-capturing group around it.", "# This is needed to get m.end() to correctly report the size of the", "# matched expression (as per the final doctest above).", ...
Try to apply the pattern at the start of the string, returning a match object if the whole string matches, or None if no match was found.
[ "Try", "to", "apply", "the", "pattern", "at", "the", "start", "of", "the", "string", "returning", "a", "match", "object", "if", "the", "whole", "string", "matches", "or", "None", "if", "no", "match", "was", "found", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/re_util.py#L27-L39
train
215,736
daviddrysdale/python-phonenumbers
tools/python/buildprefixdata.py
load_locale_prefixdata_file
def load_locale_prefixdata_file(prefixdata, filename, locale=None, overall_prefix=None, separator=None): """Load per-prefix data from the given file, for the given locale and prefix. We assume that this file: - is encoded in UTF-8 - may have comment lines (starting with #) and blank lines - has data lines of the form '<prefix>|<stringdata>' - contains only data for prefixes that are extensions of the filename. If overall_prefix is specified, lines are checked to ensure their prefix falls within this value. If locale is specified, prefixdata[prefix][locale] is filled in; otherwise, just prefixdata[prefix]. If separator is specified, the string data will be split on this separator, and the output values in the dict will be tuples of strings rather than strings. """ with open(filename, "rb") as infile: lineno = 0 for line in infile: uline = line.decode('utf-8') lineno += 1 dm = DATA_LINE_RE.match(uline) if dm: prefix = dm.group('prefix') stringdata = dm.group('stringdata') if stringdata != stringdata.rstrip(): print ("%s:%d: Warning: stripping trailing whitespace" % (filename, lineno)) stringdata = stringdata.rstrip() if overall_prefix is not None and not prefix.startswith(overall_prefix): raise Exception("%s:%d: Prefix %s is not within %s" % (filename, lineno, prefix, overall_prefix)) if separator is not None: stringdata = tuple(stringdata.split(separator)) if prefix not in prefixdata: prefixdata[prefix] = {} if locale is not None: prefixdata[prefix][locale] = stringdata else: prefixdata[prefix] = stringdata elif BLANK_LINE_RE.match(uline): pass elif COMMENT_LINE_RE.match(uline): pass else: raise Exception("%s:%d: Unexpected line format: %s" % (filename, lineno, line))
python
def load_locale_prefixdata_file(prefixdata, filename, locale=None, overall_prefix=None, separator=None): """Load per-prefix data from the given file, for the given locale and prefix. We assume that this file: - is encoded in UTF-8 - may have comment lines (starting with #) and blank lines - has data lines of the form '<prefix>|<stringdata>' - contains only data for prefixes that are extensions of the filename. If overall_prefix is specified, lines are checked to ensure their prefix falls within this value. If locale is specified, prefixdata[prefix][locale] is filled in; otherwise, just prefixdata[prefix]. If separator is specified, the string data will be split on this separator, and the output values in the dict will be tuples of strings rather than strings. """ with open(filename, "rb") as infile: lineno = 0 for line in infile: uline = line.decode('utf-8') lineno += 1 dm = DATA_LINE_RE.match(uline) if dm: prefix = dm.group('prefix') stringdata = dm.group('stringdata') if stringdata != stringdata.rstrip(): print ("%s:%d: Warning: stripping trailing whitespace" % (filename, lineno)) stringdata = stringdata.rstrip() if overall_prefix is not None and not prefix.startswith(overall_prefix): raise Exception("%s:%d: Prefix %s is not within %s" % (filename, lineno, prefix, overall_prefix)) if separator is not None: stringdata = tuple(stringdata.split(separator)) if prefix not in prefixdata: prefixdata[prefix] = {} if locale is not None: prefixdata[prefix][locale] = stringdata else: prefixdata[prefix] = stringdata elif BLANK_LINE_RE.match(uline): pass elif COMMENT_LINE_RE.match(uline): pass else: raise Exception("%s:%d: Unexpected line format: %s" % (filename, lineno, line))
[ "def", "load_locale_prefixdata_file", "(", "prefixdata", ",", "filename", ",", "locale", "=", "None", ",", "overall_prefix", "=", "None", ",", "separator", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "infile", ":", "li...
Load per-prefix data from the given file, for the given locale and prefix. We assume that this file: - is encoded in UTF-8 - may have comment lines (starting with #) and blank lines - has data lines of the form '<prefix>|<stringdata>' - contains only data for prefixes that are extensions of the filename. If overall_prefix is specified, lines are checked to ensure their prefix falls within this value. If locale is specified, prefixdata[prefix][locale] is filled in; otherwise, just prefixdata[prefix]. If separator is specified, the string data will be split on this separator, and the output values in the dict will be tuples of strings rather than strings.
[ "Load", "per", "-", "prefix", "data", "from", "the", "given", "file", "for", "the", "given", "locale", "and", "prefix", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildprefixdata.py#L83-L128
train
215,737
daviddrysdale/python-phonenumbers
tools/python/buildprefixdata.py
load_locale_prefixdata
def load_locale_prefixdata(indir, separator=None): """Load per-prefix data from the given top-level directory. Prefix data is assumed to be held in files <indir>/<locale>/<prefix>.txt. The same prefix may occur in multiple files, giving the prefix's description in different locales. """ prefixdata = {} # prefix => dict mapping locale to description for locale in os.listdir(indir): if not os.path.isdir(os.path.join(indir, locale)): continue for filename in glob.glob(os.path.join(indir, locale, "*%s" % PREFIXDATA_SUFFIX)): overall_prefix, ext = os.path.splitext(os.path.basename(filename)) load_locale_prefixdata_file(prefixdata, filename, locale, overall_prefix, separator) return prefixdata
python
def load_locale_prefixdata(indir, separator=None): """Load per-prefix data from the given top-level directory. Prefix data is assumed to be held in files <indir>/<locale>/<prefix>.txt. The same prefix may occur in multiple files, giving the prefix's description in different locales. """ prefixdata = {} # prefix => dict mapping locale to description for locale in os.listdir(indir): if not os.path.isdir(os.path.join(indir, locale)): continue for filename in glob.glob(os.path.join(indir, locale, "*%s" % PREFIXDATA_SUFFIX)): overall_prefix, ext = os.path.splitext(os.path.basename(filename)) load_locale_prefixdata_file(prefixdata, filename, locale, overall_prefix, separator) return prefixdata
[ "def", "load_locale_prefixdata", "(", "indir", ",", "separator", "=", "None", ")", ":", "prefixdata", "=", "{", "}", "# prefix => dict mapping locale to description", "for", "locale", "in", "os", ".", "listdir", "(", "indir", ")", ":", "if", "not", "os", ".", ...
Load per-prefix data from the given top-level directory. Prefix data is assumed to be held in files <indir>/<locale>/<prefix>.txt. The same prefix may occur in multiple files, giving the prefix's description in different locales.
[ "Load", "per", "-", "prefix", "data", "from", "the", "given", "top", "-", "level", "directory", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildprefixdata.py#L131-L145
train
215,738
daviddrysdale/python-phonenumbers
tools/python/buildprefixdata.py
output_prefixdata_code
def output_prefixdata_code(prefixdata, outfilename, module_prefix, varprefix, per_locale, chunks): """Output the per-prefix data in Python form to the given file """ sorted_keys = sorted(prefixdata.keys()) total_keys = len(sorted_keys) if chunks == -1: chunk_size = PREFIXDATA_CHUNK_SIZE total_chunks = int(math.ceil(total_keys / float(chunk_size))) else: chunk_size = int(math.ceil(total_keys / float(chunks))) total_chunks = chunks outdirname = os.path.dirname(outfilename) longest_prefix = 0 for chunk_num in range(total_chunks): chunk_index = chunk_size * chunk_num chunk_keys = sorted_keys[chunk_index:chunk_index + chunk_size] chunk_data = {} for key in chunk_keys: chunk_data[key] = prefixdata[key] chunk_file = os.path.join(outdirname, 'data%d.py' % chunk_num) chunk_longest = output_prefixdata_chunk( chunk_data, chunk_file, module_prefix, per_locale) if chunk_longest > longest_prefix: longest_prefix = chunk_longest with open(outfilename, "w") as outfile: if per_locale: prnt(PREFIXDATA_LOCALE_FILE_PROLOG % {'module': module_prefix}, file=outfile) else: prnt(PREFIXDATA_FILE_PROLOG % {'module': module_prefix}, file=outfile) prnt(COPYRIGHT_NOTICE, file=outfile) prnt("%s_DATA = {}" % varprefix, file=outfile) for chunk_num in range(total_chunks): prnt("from .data%d import data" % chunk_num, file=outfile) prnt("%s_DATA.update(data)" % varprefix, file=outfile) prnt("del data", file=outfile) prnt("%s_LONGEST_PREFIX = %d" % (varprefix, longest_prefix), file=outfile)
python
def output_prefixdata_code(prefixdata, outfilename, module_prefix, varprefix, per_locale, chunks): """Output the per-prefix data in Python form to the given file """ sorted_keys = sorted(prefixdata.keys()) total_keys = len(sorted_keys) if chunks == -1: chunk_size = PREFIXDATA_CHUNK_SIZE total_chunks = int(math.ceil(total_keys / float(chunk_size))) else: chunk_size = int(math.ceil(total_keys / float(chunks))) total_chunks = chunks outdirname = os.path.dirname(outfilename) longest_prefix = 0 for chunk_num in range(total_chunks): chunk_index = chunk_size * chunk_num chunk_keys = sorted_keys[chunk_index:chunk_index + chunk_size] chunk_data = {} for key in chunk_keys: chunk_data[key] = prefixdata[key] chunk_file = os.path.join(outdirname, 'data%d.py' % chunk_num) chunk_longest = output_prefixdata_chunk( chunk_data, chunk_file, module_prefix, per_locale) if chunk_longest > longest_prefix: longest_prefix = chunk_longest with open(outfilename, "w") as outfile: if per_locale: prnt(PREFIXDATA_LOCALE_FILE_PROLOG % {'module': module_prefix}, file=outfile) else: prnt(PREFIXDATA_FILE_PROLOG % {'module': module_prefix}, file=outfile) prnt(COPYRIGHT_NOTICE, file=outfile) prnt("%s_DATA = {}" % varprefix, file=outfile) for chunk_num in range(total_chunks): prnt("from .data%d import data" % chunk_num, file=outfile) prnt("%s_DATA.update(data)" % varprefix, file=outfile) prnt("del data", file=outfile) prnt("%s_LONGEST_PREFIX = %d" % (varprefix, longest_prefix), file=outfile)
[ "def", "output_prefixdata_code", "(", "prefixdata", ",", "outfilename", ",", "module_prefix", ",", "varprefix", ",", "per_locale", ",", "chunks", ")", ":", "sorted_keys", "=", "sorted", "(", "prefixdata", ".", "keys", "(", ")", ")", "total_keys", "=", "len", ...
Output the per-prefix data in Python form to the given file
[ "Output", "the", "per", "-", "prefix", "data", "in", "Python", "form", "to", "the", "given", "file" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildprefixdata.py#L164-L200
train
215,739
daviddrysdale/python-phonenumbers
tools/python/buildprefixdata.py
_standalone
def _standalone(argv): """Parse the given input directory and emit generated code.""" varprefix = "GEOCODE" per_locale = True separator = None chunks = -1 try: opts, args = getopt.getopt(argv, "hv:fs:c:", ("help", "var=", "flat", "sep=", "chunks=")) except getopt.GetoptError: prnt(__doc__, file=sys.stderr) sys.exit(1) for opt, arg in opts: if opt in ("-h", "--help"): prnt(__doc__, file=sys.stderr) sys.exit(1) elif opt in ("-v", "--var"): varprefix = arg elif opt in ("-f", "--flat"): per_locale = False elif opt in ("-s", "--sep"): separator = arg elif opt in ("-c", "--chunks"): chunks = int(arg) else: prnt("Unknown option %s" % opt, file=sys.stderr) prnt(__doc__, file=sys.stderr) sys.exit(1) if len(args) != 3: prnt(__doc__, file=sys.stderr) sys.exit(1) if per_locale: prefixdata = load_locale_prefixdata(args[0], separator=separator) else: prefixdata = {} load_locale_prefixdata_file(prefixdata, args[0], separator=separator) output_prefixdata_code(prefixdata, args[1], args[2], varprefix, per_locale, chunks)
python
def _standalone(argv): """Parse the given input directory and emit generated code.""" varprefix = "GEOCODE" per_locale = True separator = None chunks = -1 try: opts, args = getopt.getopt(argv, "hv:fs:c:", ("help", "var=", "flat", "sep=", "chunks=")) except getopt.GetoptError: prnt(__doc__, file=sys.stderr) sys.exit(1) for opt, arg in opts: if opt in ("-h", "--help"): prnt(__doc__, file=sys.stderr) sys.exit(1) elif opt in ("-v", "--var"): varprefix = arg elif opt in ("-f", "--flat"): per_locale = False elif opt in ("-s", "--sep"): separator = arg elif opt in ("-c", "--chunks"): chunks = int(arg) else: prnt("Unknown option %s" % opt, file=sys.stderr) prnt(__doc__, file=sys.stderr) sys.exit(1) if len(args) != 3: prnt(__doc__, file=sys.stderr) sys.exit(1) if per_locale: prefixdata = load_locale_prefixdata(args[0], separator=separator) else: prefixdata = {} load_locale_prefixdata_file(prefixdata, args[0], separator=separator) output_prefixdata_code(prefixdata, args[1], args[2], varprefix, per_locale, chunks)
[ "def", "_standalone", "(", "argv", ")", ":", "varprefix", "=", "\"GEOCODE\"", "per_locale", "=", "True", "separator", "=", "None", "chunks", "=", "-", "1", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "argv", ",", "\"hv:fs:c:\"", ...
Parse the given input directory and emit generated code.
[ "Parse", "the", "given", "input", "directory", "and", "emit", "generated", "code", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/tools/python/buildprefixdata.py#L223-L258
train
215,740
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
_limit
def _limit(lower, upper): """Returns a regular expression quantifier with an upper and lower limit.""" if ((lower < 0) or (upper <= 0) or (upper < lower)): raise Exception("Illegal argument to _limit") return unicod("{%d,%d}") % (lower, upper)
python
def _limit(lower, upper): """Returns a regular expression quantifier with an upper and lower limit.""" if ((lower < 0) or (upper <= 0) or (upper < lower)): raise Exception("Illegal argument to _limit") return unicod("{%d,%d}") % (lower, upper)
[ "def", "_limit", "(", "lower", ",", "upper", ")", ":", "if", "(", "(", "lower", "<", "0", ")", "or", "(", "upper", "<=", "0", ")", "or", "(", "upper", "<", "lower", ")", ")", ":", "raise", "Exception", "(", "\"Illegal argument to _limit\"", ")", "r...
Returns a regular expression quantifier with an upper and lower limit.
[ "Returns", "a", "regular", "expression", "quantifier", "with", "an", "upper", "and", "lower", "limit", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L57-L61
train
215,741
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
_verify
def _verify(leniency, numobj, candidate, matcher): """Returns True if number is a verified number according to the leniency.""" if leniency == Leniency.POSSIBLE: return is_possible_number(numobj) elif leniency == Leniency.VALID: if (not is_valid_number(numobj) or not _contains_only_valid_x_chars(numobj, candidate)): return False return _is_national_prefix_present_if_required(numobj) elif leniency == Leniency.STRICT_GROUPING: return _verify_strict_grouping(numobj, candidate, matcher) elif leniency == Leniency.EXACT_GROUPING: return _verify_exact_grouping(numobj, candidate, matcher) else: raise Exception("Error: unsupported Leniency value %s" % leniency)
python
def _verify(leniency, numobj, candidate, matcher): """Returns True if number is a verified number according to the leniency.""" if leniency == Leniency.POSSIBLE: return is_possible_number(numobj) elif leniency == Leniency.VALID: if (not is_valid_number(numobj) or not _contains_only_valid_x_chars(numobj, candidate)): return False return _is_national_prefix_present_if_required(numobj) elif leniency == Leniency.STRICT_GROUPING: return _verify_strict_grouping(numobj, candidate, matcher) elif leniency == Leniency.EXACT_GROUPING: return _verify_exact_grouping(numobj, candidate, matcher) else: raise Exception("Error: unsupported Leniency value %s" % leniency)
[ "def", "_verify", "(", "leniency", ",", "numobj", ",", "candidate", ",", "matcher", ")", ":", "if", "leniency", "==", "Leniency", ".", "POSSIBLE", ":", "return", "is_possible_number", "(", "numobj", ")", "elif", "leniency", "==", "Leniency", ".", "VALID", ...
Returns True if number is a verified number according to the leniency.
[ "Returns", "True", "if", "number", "is", "a", "verified", "number", "according", "to", "the", "leniency", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L209-L224
train
215,742
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
_get_national_number_groups_without_pattern
def _get_national_number_groups_without_pattern(numobj): """Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that would be formatted together following standard formatting rules.""" # This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of # digits. rfc3966_format = format_number(numobj, PhoneNumberFormat.RFC3966) # We remove the extension part from the formatted string before splitting # it into different groups. end_index = rfc3966_format.find(U_SEMICOLON) if end_index < 0: end_index = len(rfc3966_format) # The country-code will have a '-' following it. start_index = rfc3966_format.find(U_DASH) + 1 return rfc3966_format[start_index:end_index].split(U_DASH)
python
def _get_national_number_groups_without_pattern(numobj): """Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that would be formatted together following standard formatting rules.""" # This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of # digits. rfc3966_format = format_number(numobj, PhoneNumberFormat.RFC3966) # We remove the extension part from the formatted string before splitting # it into different groups. end_index = rfc3966_format.find(U_SEMICOLON) if end_index < 0: end_index = len(rfc3966_format) # The country-code will have a '-' following it. start_index = rfc3966_format.find(U_DASH) + 1 return rfc3966_format[start_index:end_index].split(U_DASH)
[ "def", "_get_national_number_groups_without_pattern", "(", "numobj", ")", ":", "# This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of", "# digits.", "rfc3966_format", "=", "format_number", "(", "numobj", ",", "PhoneNumberFormat", ".", "RFC3966", "...
Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that would be formatted together following standard formatting rules.
[ "Helper", "method", "to", "get", "the", "national", "-", "number", "part", "of", "a", "number", "formatted", "without", "any", "national", "prefix", "and", "return", "it", "as", "a", "set", "of", "digit", "blocks", "that", "would", "be", "formatted", "toge...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L337-L352
train
215,743
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
_get_national_number_groups
def _get_national_number_groups(numobj, formatting_pattern): """Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that should be formatted together according to the formatting pattern passed in.""" # If a format is provided, we format the NSN only, and split that according to the separator. nsn = national_significant_number(numobj) return _format_nsn_using_pattern(nsn, formatting_pattern, PhoneNumberFormat.RFC3966).split(U_DASH)
python
def _get_national_number_groups(numobj, formatting_pattern): """Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that should be formatted together according to the formatting pattern passed in.""" # If a format is provided, we format the NSN only, and split that according to the separator. nsn = national_significant_number(numobj) return _format_nsn_using_pattern(nsn, formatting_pattern, PhoneNumberFormat.RFC3966).split(U_DASH)
[ "def", "_get_national_number_groups", "(", "numobj", ",", "formatting_pattern", ")", ":", "# If a format is provided, we format the NSN only, and split that according to the separator.", "nsn", "=", "national_significant_number", "(", "numobj", ")", "return", "_format_nsn_using_patte...
Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that should be formatted together according to the formatting pattern passed in.
[ "Helper", "method", "to", "get", "the", "national", "-", "number", "part", "of", "a", "number", "formatted", "without", "any", "national", "prefix", "and", "return", "it", "as", "a", "set", "of", "digit", "blocks", "that", "should", "be", "formatted", "tog...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L355-L362
train
215,744
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
PhoneNumberMatcher._find
def _find(self, index): """Attempts to find the next subsequence in the searched sequence on or after index that represents a phone number. Returns the next match, None if none was found. Arguments: index -- The search index to start searching at. Returns the phone number match found, None if none can be found. """ match = _PATTERN.search(self.text, index) while self._max_tries > 0 and match is not None: start = match.start() candidate = self.text[start:match.end()] # Check for extra numbers at the end. # TODO: This is the place to start when trying to support # extraction of multiple phone number from split notations (+41 79 # 123 45 67 / 68). candidate = self._trim_after_first_match(_SECOND_NUMBER_START_PATTERN, candidate) match = self._extract_match(candidate, start) if match is not None: return match # Move along index = start + len(candidate) self._max_tries -= 1 match = _PATTERN.search(self.text, index) return None
python
def _find(self, index): """Attempts to find the next subsequence in the searched sequence on or after index that represents a phone number. Returns the next match, None if none was found. Arguments: index -- The search index to start searching at. Returns the phone number match found, None if none can be found. """ match = _PATTERN.search(self.text, index) while self._max_tries > 0 and match is not None: start = match.start() candidate = self.text[start:match.end()] # Check for extra numbers at the end. # TODO: This is the place to start when trying to support # extraction of multiple phone number from split notations (+41 79 # 123 45 67 / 68). candidate = self._trim_after_first_match(_SECOND_NUMBER_START_PATTERN, candidate) match = self._extract_match(candidate, start) if match is not None: return match # Move along index = start + len(candidate) self._max_tries -= 1 match = _PATTERN.search(self.text, index) return None
[ "def", "_find", "(", "self", ",", "index", ")", ":", "match", "=", "_PATTERN", ".", "search", "(", "self", ".", "text", ",", "index", ")", "while", "self", ".", "_max_tries", ">", "0", "and", "match", "is", "not", "None", ":", "start", "=", "match"...
Attempts to find the next subsequence in the searched sequence on or after index that represents a phone number. Returns the next match, None if none was found. Arguments: index -- The search index to start searching at. Returns the phone number match found, None if none can be found.
[ "Attempts", "to", "find", "the", "next", "subsequence", "in", "the", "searched", "sequence", "on", "or", "after", "index", "that", "represents", "a", "phone", "number", ".", "Returns", "the", "next", "match", "None", "if", "none", "was", "found", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L497-L524
train
215,745
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
PhoneNumberMatcher._trim_after_first_match
def _trim_after_first_match(self, pattern, candidate): """Trims away any characters after the first match of pattern in candidate, returning the trimmed version.""" trailing_chars_match = pattern.search(candidate) if trailing_chars_match: candidate = candidate[:trailing_chars_match.start()] return candidate
python
def _trim_after_first_match(self, pattern, candidate): """Trims away any characters after the first match of pattern in candidate, returning the trimmed version.""" trailing_chars_match = pattern.search(candidate) if trailing_chars_match: candidate = candidate[:trailing_chars_match.start()] return candidate
[ "def", "_trim_after_first_match", "(", "self", ",", "pattern", ",", "candidate", ")", ":", "trailing_chars_match", "=", "pattern", ".", "search", "(", "candidate", ")", "if", "trailing_chars_match", ":", "candidate", "=", "candidate", "[", ":", "trailing_chars_mat...
Trims away any characters after the first match of pattern in candidate, returning the trimmed version.
[ "Trims", "away", "any", "characters", "after", "the", "first", "match", "of", "pattern", "in", "candidate", "returning", "the", "trimmed", "version", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L526-L532
train
215,746
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
PhoneNumberMatcher._is_latin_letter
def _is_latin_letter(cls, letter): """Helper method to determine if a character is a Latin-script letter or not. For our purposes, combining marks should also return True since we assume they have been added to a preceding Latin character.""" # Combining marks are a subset of non-spacing-mark if (not is_letter(letter) and Category.get(letter) != Category.NON_SPACING_MARK): return False block = Block.get(letter) return (block == Block.BASIC_LATIN or block == Block.LATIN_1_SUPPLEMENT or block == Block.LATIN_EXTENDED_A or block == Block.LATIN_EXTENDED_ADDITIONAL or block == Block.LATIN_EXTENDED_B or block == Block.COMBINING_DIACRITICAL_MARKS)
python
def _is_latin_letter(cls, letter): """Helper method to determine if a character is a Latin-script letter or not. For our purposes, combining marks should also return True since we assume they have been added to a preceding Latin character.""" # Combining marks are a subset of non-spacing-mark if (not is_letter(letter) and Category.get(letter) != Category.NON_SPACING_MARK): return False block = Block.get(letter) return (block == Block.BASIC_LATIN or block == Block.LATIN_1_SUPPLEMENT or block == Block.LATIN_EXTENDED_A or block == Block.LATIN_EXTENDED_ADDITIONAL or block == Block.LATIN_EXTENDED_B or block == Block.COMBINING_DIACRITICAL_MARKS)
[ "def", "_is_latin_letter", "(", "cls", ",", "letter", ")", ":", "# Combining marks are a subset of non-spacing-mark", "if", "(", "not", "is_letter", "(", "letter", ")", "and", "Category", ".", "get", "(", "letter", ")", "!=", "Category", ".", "NON_SPACING_MARK", ...
Helper method to determine if a character is a Latin-script letter or not. For our purposes, combining marks should also return True since we assume they have been added to a preceding Latin character.
[ "Helper", "method", "to", "determine", "if", "a", "character", "is", "a", "Latin", "-", "script", "letter", "or", "not", ".", "For", "our", "purposes", "combining", "marks", "should", "also", "return", "True", "since", "we", "assume", "they", "have", "been...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L535-L549
train
215,747
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
PhoneNumberMatcher._extract_match
def _extract_match(self, candidate, offset): """Attempts to extract a match from a candidate string. Arguments: candidate -- The candidate text that might contain a phone number. offset -- The offset of candidate within self.text Returns the match found, None if none can be found """ # Skip a match that is more likely a publication page reference or a # date. if (_SLASH_SEPARATED_DATES.search(candidate)): return None # Skip potential time-stamps. if _TIME_STAMPS.search(candidate): following_text = self.text[offset + len(candidate):] if _TIME_STAMPS_SUFFIX.match(following_text): return None # Try to come up with a valid match given the entire candidate. match = self._parse_and_verify(candidate, offset) if match is not None: return match # If that failed, try to find an "inner match" -- there might be a # phone number within this candidate. return self._extract_inner_match(candidate, offset)
python
def _extract_match(self, candidate, offset): """Attempts to extract a match from a candidate string. Arguments: candidate -- The candidate text that might contain a phone number. offset -- The offset of candidate within self.text Returns the match found, None if none can be found """ # Skip a match that is more likely a publication page reference or a # date. if (_SLASH_SEPARATED_DATES.search(candidate)): return None # Skip potential time-stamps. if _TIME_STAMPS.search(candidate): following_text = self.text[offset + len(candidate):] if _TIME_STAMPS_SUFFIX.match(following_text): return None # Try to come up with a valid match given the entire candidate. match = self._parse_and_verify(candidate, offset) if match is not None: return match # If that failed, try to find an "inner match" -- there might be a # phone number within this candidate. return self._extract_inner_match(candidate, offset)
[ "def", "_extract_match", "(", "self", ",", "candidate", ",", "offset", ")", ":", "# Skip a match that is more likely a publication page reference or a", "# date.", "if", "(", "_SLASH_SEPARATED_DATES", ".", "search", "(", "candidate", ")", ")", ":", "return", "None", "...
Attempts to extract a match from a candidate string. Arguments: candidate -- The candidate text that might contain a phone number. offset -- The offset of candidate within self.text Returns the match found, None if none can be found
[ "Attempts", "to", "extract", "a", "match", "from", "a", "candidate", "string", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L556-L582
train
215,748
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
PhoneNumberMatcher._extract_inner_match
def _extract_inner_match(self, candidate, offset): """Attempts to extract a match from candidate if the whole candidate does not qualify as a match. Arguments: candidate -- The candidate text that might contain a phone number offset -- The current offset of candidate within text Returns the match found, None if none can be found """ for possible_inner_match in _INNER_MATCHES: group_match = possible_inner_match.search(candidate) is_first_match = True while group_match and self._max_tries > 0: if is_first_match: # We should handle any group before this one too. group = self._trim_after_first_match(_UNWANTED_END_CHAR_PATTERN, candidate[:group_match.start()]) match = self._parse_and_verify(group, offset) if match is not None: return match self._max_tries -= 1 is_first_match = False group = self._trim_after_first_match(_UNWANTED_END_CHAR_PATTERN, group_match.group(1)) match = self._parse_and_verify(group, offset + group_match.start(1)) if match is not None: return match self._max_tries -= 1 group_match = possible_inner_match.search(candidate, group_match.start() + 1) return None
python
def _extract_inner_match(self, candidate, offset): """Attempts to extract a match from candidate if the whole candidate does not qualify as a match. Arguments: candidate -- The candidate text that might contain a phone number offset -- The current offset of candidate within text Returns the match found, None if none can be found """ for possible_inner_match in _INNER_MATCHES: group_match = possible_inner_match.search(candidate) is_first_match = True while group_match and self._max_tries > 0: if is_first_match: # We should handle any group before this one too. group = self._trim_after_first_match(_UNWANTED_END_CHAR_PATTERN, candidate[:group_match.start()]) match = self._parse_and_verify(group, offset) if match is not None: return match self._max_tries -= 1 is_first_match = False group = self._trim_after_first_match(_UNWANTED_END_CHAR_PATTERN, group_match.group(1)) match = self._parse_and_verify(group, offset + group_match.start(1)) if match is not None: return match self._max_tries -= 1 group_match = possible_inner_match.search(candidate, group_match.start() + 1) return None
[ "def", "_extract_inner_match", "(", "self", ",", "candidate", ",", "offset", ")", ":", "for", "possible_inner_match", "in", "_INNER_MATCHES", ":", "group_match", "=", "possible_inner_match", ".", "search", "(", "candidate", ")", "is_first_match", "=", "True", "whi...
Attempts to extract a match from candidate if the whole candidate does not qualify as a match. Arguments: candidate -- The candidate text that might contain a phone number offset -- The current offset of candidate within text Returns the match found, None if none can be found
[ "Attempts", "to", "extract", "a", "match", "from", "candidate", "if", "the", "whole", "candidate", "does", "not", "qualify", "as", "a", "match", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L584-L613
train
215,749
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
PhoneNumberMatcher._parse_and_verify
def _parse_and_verify(self, candidate, offset): """Parses a phone number from the candidate using phonenumberutil.parse and verifies it matches the requested leniency. If parsing and verification succeed, a corresponding PhoneNumberMatch is returned, otherwise this method returns None. Arguments: candidate -- The candidate match. offset -- The offset of candidate within self.text. Returns the parsed and validated phone number match, or None. """ try: # Check the candidate doesn't contain any formatting which would # indicate that it really isn't a phone number. if (not fullmatch(_MATCHING_BRACKETS, candidate) or _PUB_PAGES.search(candidate)): return None # If leniency is set to VALID or stricter, we also want to skip # numbers that are surrounded by Latin alphabetic characters, to # skip cases like abc8005001234 or 8005001234def. if self.leniency >= Leniency.VALID: # If the candidate is not at the start of the text, and does # not start with phone-number punctuation, check the previous # character if (offset > 0 and not _LEAD_PATTERN.match(candidate)): previous_char = self.text[offset - 1] # We return None if it is a latin letter or an invalid # punctuation symbol if (self._is_invalid_punctuation_symbol(previous_char) or self._is_latin_letter(previous_char)): return None last_char_index = offset + len(candidate) if last_char_index < len(self.text): next_char = self.text[last_char_index] if (self._is_invalid_punctuation_symbol(next_char) or self._is_latin_letter(next_char)): return None numobj = parse(candidate, self.preferred_region, keep_raw_input=True) if _verify(self.leniency, numobj, candidate, self): # We used parse(keep_raw_input=True) to create this number, # but for now we don't return the extra values parsed. # TODO: stop clearing all values here and switch all users # over to using raw_input rather than the raw_string of # PhoneNumberMatch. numobj.country_code_source = CountryCodeSource.UNSPECIFIED numobj.raw_input = None numobj.preferred_domestic_carrier_code = None return PhoneNumberMatch(offset, candidate, numobj) except NumberParseException: # ignore and continue pass return None
python
def _parse_and_verify(self, candidate, offset): """Parses a phone number from the candidate using phonenumberutil.parse and verifies it matches the requested leniency. If parsing and verification succeed, a corresponding PhoneNumberMatch is returned, otherwise this method returns None. Arguments: candidate -- The candidate match. offset -- The offset of candidate within self.text. Returns the parsed and validated phone number match, or None. """ try: # Check the candidate doesn't contain any formatting which would # indicate that it really isn't a phone number. if (not fullmatch(_MATCHING_BRACKETS, candidate) or _PUB_PAGES.search(candidate)): return None # If leniency is set to VALID or stricter, we also want to skip # numbers that are surrounded by Latin alphabetic characters, to # skip cases like abc8005001234 or 8005001234def. if self.leniency >= Leniency.VALID: # If the candidate is not at the start of the text, and does # not start with phone-number punctuation, check the previous # character if (offset > 0 and not _LEAD_PATTERN.match(candidate)): previous_char = self.text[offset - 1] # We return None if it is a latin letter or an invalid # punctuation symbol if (self._is_invalid_punctuation_symbol(previous_char) or self._is_latin_letter(previous_char)): return None last_char_index = offset + len(candidate) if last_char_index < len(self.text): next_char = self.text[last_char_index] if (self._is_invalid_punctuation_symbol(next_char) or self._is_latin_letter(next_char)): return None numobj = parse(candidate, self.preferred_region, keep_raw_input=True) if _verify(self.leniency, numobj, candidate, self): # We used parse(keep_raw_input=True) to create this number, # but for now we don't return the extra values parsed. # TODO: stop clearing all values here and switch all users # over to using raw_input rather than the raw_string of # PhoneNumberMatch. numobj.country_code_source = CountryCodeSource.UNSPECIFIED numobj.raw_input = None numobj.preferred_domestic_carrier_code = None return PhoneNumberMatch(offset, candidate, numobj) except NumberParseException: # ignore and continue pass return None
[ "def", "_parse_and_verify", "(", "self", ",", "candidate", ",", "offset", ")", ":", "try", ":", "# Check the candidate doesn't contain any formatting which would", "# indicate that it really isn't a phone number.", "if", "(", "not", "fullmatch", "(", "_MATCHING_BRACKETS", ","...
Parses a phone number from the candidate using phonenumberutil.parse and verifies it matches the requested leniency. If parsing and verification succeed, a corresponding PhoneNumberMatch is returned, otherwise this method returns None. Arguments: candidate -- The candidate match. offset -- The offset of candidate within self.text. Returns the parsed and validated phone number match, or None.
[ "Parses", "a", "phone", "number", "from", "the", "candidate", "using", "phonenumberutil", ".", "parse", "and", "verifies", "it", "matches", "the", "requested", "leniency", ".", "If", "parsing", "and", "verification", "succeed", "a", "corresponding", "PhoneNumberMa...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L615-L667
train
215,750
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
PhoneNumberMatcher.has_next
def has_next(self): """Indicates whether there is another match available""" if self._state == PhoneNumberMatcher._NOT_READY: self._last_match = self._find(self._search_index) if self._last_match is None: self._state = PhoneNumberMatcher._DONE else: self._search_index = self._last_match.end self._state = PhoneNumberMatcher._READY return (self._state == PhoneNumberMatcher._READY)
python
def has_next(self): """Indicates whether there is another match available""" if self._state == PhoneNumberMatcher._NOT_READY: self._last_match = self._find(self._search_index) if self._last_match is None: self._state = PhoneNumberMatcher._DONE else: self._search_index = self._last_match.end self._state = PhoneNumberMatcher._READY return (self._state == PhoneNumberMatcher._READY)
[ "def", "has_next", "(", "self", ")", ":", "if", "self", ".", "_state", "==", "PhoneNumberMatcher", ".", "_NOT_READY", ":", "self", ".", "_last_match", "=", "self", ".", "_find", "(", "self", ".", "_search_index", ")", "if", "self", ".", "_last_match", "i...
Indicates whether there is another match available
[ "Indicates", "whether", "there", "is", "another", "match", "available" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L690-L699
train
215,751
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumbermatcher.py
PhoneNumberMatcher.next
def next(self): """Return the next match; raises Exception if no next match available""" # Check the state and find the next match as a side-effect if necessary. if not self.has_next(): raise StopIteration("No next match") # Don't retain that memory any longer than necessary. result = self._last_match self._last_match = None self._state = PhoneNumberMatcher._NOT_READY return result
python
def next(self): """Return the next match; raises Exception if no next match available""" # Check the state and find the next match as a side-effect if necessary. if not self.has_next(): raise StopIteration("No next match") # Don't retain that memory any longer than necessary. result = self._last_match self._last_match = None self._state = PhoneNumberMatcher._NOT_READY return result
[ "def", "next", "(", "self", ")", ":", "# Check the state and find the next match as a side-effect if necessary.", "if", "not", "self", ".", "has_next", "(", ")", ":", "raise", "StopIteration", "(", "\"No next match\"", ")", "# Don't retain that memory any longer than necessar...
Return the next match; raises Exception if no next match available
[ "Return", "the", "next", "match", ";", "raises", "Exception", "if", "no", "next", "match", "available" ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumbermatcher.py#L701-L710
train
215,752
daviddrysdale/python-phonenumbers
python/phonenumbers/shortnumberinfo.py
is_possible_short_number_for_region
def is_possible_short_number_for_region(short_numobj, region_dialing_from): """Check whether a short number is a possible number when dialled from a region. This provides a more lenient check than is_valid_short_number_for_region. Arguments: short_numobj -- the short number to check as a PhoneNumber object. region_dialing_from -- the region from which the number is dialed Return whether the number is a possible short number. """ if not _region_dialing_from_matches_number(short_numobj, region_dialing_from): return False metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from) if metadata is None: # pragma no cover return False short_numlen = len(national_significant_number(short_numobj)) return (short_numlen in metadata.general_desc.possible_length)
python
def is_possible_short_number_for_region(short_numobj, region_dialing_from): """Check whether a short number is a possible number when dialled from a region. This provides a more lenient check than is_valid_short_number_for_region. Arguments: short_numobj -- the short number to check as a PhoneNumber object. region_dialing_from -- the region from which the number is dialed Return whether the number is a possible short number. """ if not _region_dialing_from_matches_number(short_numobj, region_dialing_from): return False metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from) if metadata is None: # pragma no cover return False short_numlen = len(national_significant_number(short_numobj)) return (short_numlen in metadata.general_desc.possible_length)
[ "def", "is_possible_short_number_for_region", "(", "short_numobj", ",", "region_dialing_from", ")", ":", "if", "not", "_region_dialing_from_matches_number", "(", "short_numobj", ",", "region_dialing_from", ")", ":", "return", "False", "metadata", "=", "PhoneMetadata", "."...
Check whether a short number is a possible number when dialled from a region. This provides a more lenient check than is_valid_short_number_for_region. Arguments: short_numobj -- the short number to check as a PhoneNumber object. region_dialing_from -- the region from which the number is dialed Return whether the number is a possible short number.
[ "Check", "whether", "a", "short", "number", "is", "a", "possible", "number", "when", "dialled", "from", "a", "region", ".", "This", "provides", "a", "more", "lenient", "check", "than", "is_valid_short_number_for_region", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L66-L83
train
215,753
daviddrysdale/python-phonenumbers
python/phonenumbers/shortnumberinfo.py
is_possible_short_number
def is_possible_short_number(numobj): """Check whether a short number is a possible number. If a country calling code is shared by multiple regions, this returns True if it's possible in any of them. This provides a more lenient check than is_valid_short_number. Arguments: numobj -- the short number to check Return whether the number is a possible short number. """ region_codes = region_codes_for_country_code(numobj.country_code) short_number_len = len(national_significant_number(numobj)) for region in region_codes: metadata = PhoneMetadata.short_metadata_for_region(region) if metadata is None: continue if short_number_len in metadata.general_desc.possible_length: return True return False
python
def is_possible_short_number(numobj): """Check whether a short number is a possible number. If a country calling code is shared by multiple regions, this returns True if it's possible in any of them. This provides a more lenient check than is_valid_short_number. Arguments: numobj -- the short number to check Return whether the number is a possible short number. """ region_codes = region_codes_for_country_code(numobj.country_code) short_number_len = len(national_significant_number(numobj)) for region in region_codes: metadata = PhoneMetadata.short_metadata_for_region(region) if metadata is None: continue if short_number_len in metadata.general_desc.possible_length: return True return False
[ "def", "is_possible_short_number", "(", "numobj", ")", ":", "region_codes", "=", "region_codes_for_country_code", "(", "numobj", ".", "country_code", ")", "short_number_len", "=", "len", "(", "national_significant_number", "(", "numobj", ")", ")", "for", "region", "...
Check whether a short number is a possible number. If a country calling code is shared by multiple regions, this returns True if it's possible in any of them. This provides a more lenient check than is_valid_short_number. Arguments: numobj -- the short number to check Return whether the number is a possible short number.
[ "Check", "whether", "a", "short", "number", "is", "a", "possible", "number", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L86-L107
train
215,754
daviddrysdale/python-phonenumbers
python/phonenumbers/shortnumberinfo.py
is_valid_short_number_for_region
def is_valid_short_number_for_region(short_numobj, region_dialing_from): """Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. Arguments: short_numobj -- the short number to check as a PhoneNumber object. region_dialing_from -- the region from which the number is dialed Return whether the short number matches a valid pattern """ if not _region_dialing_from_matches_number(short_numobj, region_dialing_from): return False metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from) if metadata is None: # pragma no cover return False short_number = national_significant_number(short_numobj) general_desc = metadata.general_desc if not _matches_possible_number_and_national_number(short_number, general_desc): return False short_number_desc = metadata.short_code if short_number_desc.national_number_pattern is None: # pragma no cover return False return _matches_possible_number_and_national_number(short_number, short_number_desc)
python
def is_valid_short_number_for_region(short_numobj, region_dialing_from): """Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. Arguments: short_numobj -- the short number to check as a PhoneNumber object. region_dialing_from -- the region from which the number is dialed Return whether the short number matches a valid pattern """ if not _region_dialing_from_matches_number(short_numobj, region_dialing_from): return False metadata = PhoneMetadata.short_metadata_for_region(region_dialing_from) if metadata is None: # pragma no cover return False short_number = national_significant_number(short_numobj) general_desc = metadata.general_desc if not _matches_possible_number_and_national_number(short_number, general_desc): return False short_number_desc = metadata.short_code if short_number_desc.national_number_pattern is None: # pragma no cover return False return _matches_possible_number_and_national_number(short_number, short_number_desc)
[ "def", "is_valid_short_number_for_region", "(", "short_numobj", ",", "region_dialing_from", ")", ":", "if", "not", "_region_dialing_from_matches_number", "(", "short_numobj", ",", "region_dialing_from", ")", ":", "return", "False", "metadata", "=", "PhoneMetadata", ".", ...
Tests whether a short number matches a valid pattern in a region. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. Arguments: short_numobj -- the short number to check as a PhoneNumber object. region_dialing_from -- the region from which the number is dialed Return whether the short number matches a valid pattern
[ "Tests", "whether", "a", "short", "number", "matches", "a", "valid", "pattern", "in", "a", "region", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L110-L134
train
215,755
daviddrysdale/python-phonenumbers
python/phonenumbers/shortnumberinfo.py
is_valid_short_number
def is_valid_short_number(numobj): """Tests whether a short number matches a valid pattern. If a country calling code is shared by multiple regions, this returns True if it's valid in any of them. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. See is_valid_short_number_for_region for details. Arguments: numobj - the short number for which we want to test the validity Return whether the short number matches a valid pattern """ region_codes = region_codes_for_country_code(numobj.country_code) region_code = _region_code_for_short_number_from_region_list(numobj, region_codes) if len(region_codes) > 1 and region_code is not None: # If a matching region had been found for the phone number from among two or more regions, # then we have already implicitly verified its validity for that region. return True return is_valid_short_number_for_region(numobj, region_code)
python
def is_valid_short_number(numobj): """Tests whether a short number matches a valid pattern. If a country calling code is shared by multiple regions, this returns True if it's valid in any of them. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. See is_valid_short_number_for_region for details. Arguments: numobj - the short number for which we want to test the validity Return whether the short number matches a valid pattern """ region_codes = region_codes_for_country_code(numobj.country_code) region_code = _region_code_for_short_number_from_region_list(numobj, region_codes) if len(region_codes) > 1 and region_code is not None: # If a matching region had been found for the phone number from among two or more regions, # then we have already implicitly verified its validity for that region. return True return is_valid_short_number_for_region(numobj, region_code)
[ "def", "is_valid_short_number", "(", "numobj", ")", ":", "region_codes", "=", "region_codes_for_country_code", "(", "numobj", ".", "country_code", ")", "region_code", "=", "_region_code_for_short_number_from_region_list", "(", "numobj", ",", "region_codes", ")", "if", "...
Tests whether a short number matches a valid pattern. If a country calling code is shared by multiple regions, this returns True if it's valid in any of them. Note that this doesn't verify the number is actually in use, which is impossible to tell by just looking at the number itself. See is_valid_short_number_for_region for details. Arguments: numobj - the short number for which we want to test the validity Return whether the short number matches a valid pattern
[ "Tests", "whether", "a", "short", "number", "matches", "a", "valid", "pattern", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L137-L156
train
215,756
daviddrysdale/python-phonenumbers
python/phonenumbers/shortnumberinfo.py
_region_code_for_short_number_from_region_list
def _region_code_for_short_number_from_region_list(numobj, region_codes): """Helper method to get the region code for a given phone number, from a list of possible region codes. If the list contains more than one region, the first region for which the number is valid is returned. """ if len(region_codes) == 0: return None elif len(region_codes) == 1: return region_codes[0] national_number = national_significant_number(numobj) for region_code in region_codes: metadata = PhoneMetadata.short_metadata_for_region(region_code) if metadata is not None and _matches_possible_number_and_national_number(national_number, metadata.short_code): # The number is valid for this region. return region_code return None
python
def _region_code_for_short_number_from_region_list(numobj, region_codes): """Helper method to get the region code for a given phone number, from a list of possible region codes. If the list contains more than one region, the first region for which the number is valid is returned. """ if len(region_codes) == 0: return None elif len(region_codes) == 1: return region_codes[0] national_number = national_significant_number(numobj) for region_code in region_codes: metadata = PhoneMetadata.short_metadata_for_region(region_code) if metadata is not None and _matches_possible_number_and_national_number(national_number, metadata.short_code): # The number is valid for this region. return region_code return None
[ "def", "_region_code_for_short_number_from_region_list", "(", "numobj", ",", "region_codes", ")", ":", "if", "len", "(", "region_codes", ")", "==", "0", ":", "return", "None", "elif", "len", "(", "region_codes", ")", "==", "1", ":", "return", "region_codes", "...
Helper method to get the region code for a given phone number, from a list of possible region codes. If the list contains more than one region, the first region for which the number is valid is returned.
[ "Helper", "method", "to", "get", "the", "region", "code", "for", "a", "given", "phone", "number", "from", "a", "list", "of", "possible", "region", "codes", ".", "If", "the", "list", "contains", "more", "than", "one", "region", "the", "first", "region", "...
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L259-L274
train
215,757
daviddrysdale/python-phonenumbers
python/phonenumbers/shortnumberinfo.py
_example_short_number
def _example_short_number(region_code): """Gets a valid short number for the specified region. Arguments: region_code -- the region for which an example short number is needed. Returns a valid short number for the specified region. Returns an empty string when the metadata does not contain such information. """ metadata = PhoneMetadata.short_metadata_for_region(region_code) if metadata is None: return U_EMPTY_STRING desc = metadata.short_code if desc.example_number is not None: return desc.example_number return U_EMPTY_STRING
python
def _example_short_number(region_code): """Gets a valid short number for the specified region. Arguments: region_code -- the region for which an example short number is needed. Returns a valid short number for the specified region. Returns an empty string when the metadata does not contain such information. """ metadata = PhoneMetadata.short_metadata_for_region(region_code) if metadata is None: return U_EMPTY_STRING desc = metadata.short_code if desc.example_number is not None: return desc.example_number return U_EMPTY_STRING
[ "def", "_example_short_number", "(", "region_code", ")", ":", "metadata", "=", "PhoneMetadata", ".", "short_metadata_for_region", "(", "region_code", ")", "if", "metadata", "is", "None", ":", "return", "U_EMPTY_STRING", "desc", "=", "metadata", ".", "short_code", ...
Gets a valid short number for the specified region. Arguments: region_code -- the region for which an example short number is needed. Returns a valid short number for the specified region. Returns an empty string when the metadata does not contain such information.
[ "Gets", "a", "valid", "short", "number", "for", "the", "specified", "region", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L277-L292
train
215,758
daviddrysdale/python-phonenumbers
python/phonenumbers/shortnumberinfo.py
_example_short_number_for_cost
def _example_short_number_for_cost(region_code, cost): """Gets a valid short number for the specified cost category. Arguments: region_code -- the region for which an example short number is needed. cost -- the cost category of number that is needed. Returns a valid short number for the specified region and cost category. Returns an empty string when the metadata does not contain such information, or the cost is UNKNOWN_COST. """ metadata = PhoneMetadata.short_metadata_for_region(region_code) if metadata is None: return U_EMPTY_STRING desc = None if cost == ShortNumberCost.TOLL_FREE: desc = metadata.toll_free elif cost == ShortNumberCost.STANDARD_RATE: desc = metadata.standard_rate elif cost == ShortNumberCost.PREMIUM_RATE: desc = metadata.premium_rate else: # ShortNumberCost.UNKNOWN_COST numbers are computed by the process of # elimination from the other cost categoried. pass if desc is not None and desc.example_number is not None: return desc.example_number return U_EMPTY_STRING
python
def _example_short_number_for_cost(region_code, cost): """Gets a valid short number for the specified cost category. Arguments: region_code -- the region for which an example short number is needed. cost -- the cost category of number that is needed. Returns a valid short number for the specified region and cost category. Returns an empty string when the metadata does not contain such information, or the cost is UNKNOWN_COST. """ metadata = PhoneMetadata.short_metadata_for_region(region_code) if metadata is None: return U_EMPTY_STRING desc = None if cost == ShortNumberCost.TOLL_FREE: desc = metadata.toll_free elif cost == ShortNumberCost.STANDARD_RATE: desc = metadata.standard_rate elif cost == ShortNumberCost.PREMIUM_RATE: desc = metadata.premium_rate else: # ShortNumberCost.UNKNOWN_COST numbers are computed by the process of # elimination from the other cost categoried. pass if desc is not None and desc.example_number is not None: return desc.example_number return U_EMPTY_STRING
[ "def", "_example_short_number_for_cost", "(", "region_code", ",", "cost", ")", ":", "metadata", "=", "PhoneMetadata", ".", "short_metadata_for_region", "(", "region_code", ")", "if", "metadata", "is", "None", ":", "return", "U_EMPTY_STRING", "desc", "=", "None", "...
Gets a valid short number for the specified cost category. Arguments: region_code -- the region for which an example short number is needed. cost -- the cost category of number that is needed. Returns a valid short number for the specified region and cost category. Returns an empty string when the metadata does not contain such information, or the cost is UNKNOWN_COST.
[ "Gets", "a", "valid", "short", "number", "for", "the", "specified", "cost", "category", "." ]
9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/shortnumberinfo.py#L295-L322
train
215,759
Shopify/shopify_python_api
shopify/base.py
ShopifyResourceMeta.connection
def connection(cls): """HTTP connection for the current thread""" local = cls._threadlocal if not getattr(local, 'connection', None): # Make sure these variables are no longer affected by other threads. local.user = cls.user local.password = cls.password local.site = cls.site local.timeout = cls.timeout local.headers = cls.headers local.format = cls.format local.version = cls.version local.url = cls.url if cls.site is None: raise ValueError("No shopify session is active") local.connection = ShopifyConnection( cls.site, cls.user, cls.password, cls.timeout, cls.format) return local.connection
python
def connection(cls): """HTTP connection for the current thread""" local = cls._threadlocal if not getattr(local, 'connection', None): # Make sure these variables are no longer affected by other threads. local.user = cls.user local.password = cls.password local.site = cls.site local.timeout = cls.timeout local.headers = cls.headers local.format = cls.format local.version = cls.version local.url = cls.url if cls.site is None: raise ValueError("No shopify session is active") local.connection = ShopifyConnection( cls.site, cls.user, cls.password, cls.timeout, cls.format) return local.connection
[ "def", "connection", "(", "cls", ")", ":", "local", "=", "cls", ".", "_threadlocal", "if", "not", "getattr", "(", "local", ",", "'connection'", ",", "None", ")", ":", "# Make sure these variables are no longer affected by other threads.", "local", ".", "user", "="...
HTTP connection for the current thread
[ "HTTP", "connection", "for", "the", "current", "thread" ]
88d3ba332fb2cd331f87517a16f2c2d4296cee90
https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/base.py#L33-L50
train
215,760
Shopify/shopify_python_api
shopify/base.py
ShopifyResourceMeta.get_prefix_source
def get_prefix_source(cls): """Return the prefix source, by default derived from site.""" try: return cls.override_prefix() except AttributeError: if hasattr(cls, '_prefix_source'): return cls.site + cls._prefix_source else: return cls.site
python
def get_prefix_source(cls): """Return the prefix source, by default derived from site.""" try: return cls.override_prefix() except AttributeError: if hasattr(cls, '_prefix_source'): return cls.site + cls._prefix_source else: return cls.site
[ "def", "get_prefix_source", "(", "cls", ")", ":", "try", ":", "return", "cls", ".", "override_prefix", "(", ")", "except", "AttributeError", ":", "if", "hasattr", "(", "cls", ",", "'_prefix_source'", ")", ":", "return", "cls", ".", "site", "+", "cls", "....
Return the prefix source, by default derived from site.
[ "Return", "the", "prefix", "source", "by", "default", "derived", "from", "site", "." ]
88d3ba332fb2cd331f87517a16f2c2d4296cee90
https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/base.py#L119-L127
train
215,761
Shopify/shopify_python_api
shopify/session.py
Session.__encoded_params_for_signature
def __encoded_params_for_signature(cls, params): """ Sort and combine query parameters into a single string, excluding those that should be removed and joining with '&' """ def encoded_pairs(params): for k, v in six.iteritems(params): if k == 'hmac': continue if k.endswith('[]'): #foo[]=1&foo[]=2 has to be transformed as foo=["1", "2"] note the whitespace after comma k = k.rstrip('[]') v = json.dumps(list(map(str, v))) # escape delimiters to avoid tampering k = str(k).replace("%", "%25").replace("=", "%3D") v = str(v).replace("%", "%25") yield '{0}={1}'.format(k, v).replace("&", "%26") return "&".join(sorted(encoded_pairs(params)))
python
def __encoded_params_for_signature(cls, params): """ Sort and combine query parameters into a single string, excluding those that should be removed and joining with '&' """ def encoded_pairs(params): for k, v in six.iteritems(params): if k == 'hmac': continue if k.endswith('[]'): #foo[]=1&foo[]=2 has to be transformed as foo=["1", "2"] note the whitespace after comma k = k.rstrip('[]') v = json.dumps(list(map(str, v))) # escape delimiters to avoid tampering k = str(k).replace("%", "%25").replace("=", "%3D") v = str(v).replace("%", "%25") yield '{0}={1}'.format(k, v).replace("&", "%26") return "&".join(sorted(encoded_pairs(params)))
[ "def", "__encoded_params_for_signature", "(", "cls", ",", "params", ")", ":", "def", "encoded_pairs", "(", "params", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "params", ")", ":", "if", "k", "==", "'hmac'", ":", "continue", "if...
Sort and combine query parameters into a single string, excluding those that should be removed and joining with '&'
[ "Sort", "and", "combine", "query", "parameters", "into", "a", "single", "string", "excluding", "those", "that", "should", "be", "removed", "and", "joining", "with", "&" ]
88d3ba332fb2cd331f87517a16f2c2d4296cee90
https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/session.py#L141-L160
train
215,762
Shopify/shopify_python_api
shopify/resources/refund.py
Refund.calculate
def calculate(cls, order_id, shipping=None, refund_line_items=None): """ Calculates refund transactions based on line items and shipping. When you want to create a refund, you should first use the calculate endpoint to generate accurate refund transactions. Args: order_id: Order ID for which the Refund has to created. shipping: Specify how much shipping to refund. refund_line_items: A list of line item IDs and quantities to refund. Returns: Unsaved refund record """ data = {} if shipping: data['shipping'] = shipping data['refund_line_items'] = refund_line_items or [] body = {'refund': data} resource = cls.post( "calculate", order_id=order_id, body=json.dumps(body).encode() ) return cls( cls.format.decode(resource.body), prefix_options={'order_id': order_id} )
python
def calculate(cls, order_id, shipping=None, refund_line_items=None): """ Calculates refund transactions based on line items and shipping. When you want to create a refund, you should first use the calculate endpoint to generate accurate refund transactions. Args: order_id: Order ID for which the Refund has to created. shipping: Specify how much shipping to refund. refund_line_items: A list of line item IDs and quantities to refund. Returns: Unsaved refund record """ data = {} if shipping: data['shipping'] = shipping data['refund_line_items'] = refund_line_items or [] body = {'refund': data} resource = cls.post( "calculate", order_id=order_id, body=json.dumps(body).encode() ) return cls( cls.format.decode(resource.body), prefix_options={'order_id': order_id} )
[ "def", "calculate", "(", "cls", ",", "order_id", ",", "shipping", "=", "None", ",", "refund_line_items", "=", "None", ")", ":", "data", "=", "{", "}", "if", "shipping", ":", "data", "[", "'shipping'", "]", "=", "shipping", "data", "[", "'refund_line_item...
Calculates refund transactions based on line items and shipping. When you want to create a refund, you should first use the calculate endpoint to generate accurate refund transactions. Args: order_id: Order ID for which the Refund has to created. shipping: Specify how much shipping to refund. refund_line_items: A list of line item IDs and quantities to refund. Returns: Unsaved refund record
[ "Calculates", "refund", "transactions", "based", "on", "line", "items", "and", "shipping", ".", "When", "you", "want", "to", "create", "a", "refund", "you", "should", "first", "use", "the", "calculate", "endpoint", "to", "generate", "accurate", "refund", "tran...
88d3ba332fb2cd331f87517a16f2c2d4296cee90
https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/resources/refund.py#L10-L34
train
215,763
Shopify/shopify_python_api
scripts/shopify_api.py
TasksMeta.help
def help(cls, task=None): """Describe available tasks or one specific task""" if task is None: usage_list = [] for task in iter(cls._tasks): task_func = getattr(cls, task) usage_string = " %s %s" % (cls._prog, task_func.usage) desc = task_func.__doc__.splitlines()[0] usage_list.append((usage_string, desc)) max_len = functools.reduce(lambda m, item: max(m, len(item[0])), usage_list, 0) print("Tasks:") cols = int(os.environ.get("COLUMNS", 80)) for line, desc in usage_list: task_func = getattr(cls, task) if desc: line = "%s%s # %s" % (line, " " * (max_len - len(line)), desc) if len(line) > cols: line = line[:cols - 3] + "..." print(line) else: task_func = getattr(cls, task) print("Usage:") print(" %s %s" % (cls._prog, task_func.usage)) print("") print(task_func.__doc__)
python
def help(cls, task=None): """Describe available tasks or one specific task""" if task is None: usage_list = [] for task in iter(cls._tasks): task_func = getattr(cls, task) usage_string = " %s %s" % (cls._prog, task_func.usage) desc = task_func.__doc__.splitlines()[0] usage_list.append((usage_string, desc)) max_len = functools.reduce(lambda m, item: max(m, len(item[0])), usage_list, 0) print("Tasks:") cols = int(os.environ.get("COLUMNS", 80)) for line, desc in usage_list: task_func = getattr(cls, task) if desc: line = "%s%s # %s" % (line, " " * (max_len - len(line)), desc) if len(line) > cols: line = line[:cols - 3] + "..." print(line) else: task_func = getattr(cls, task) print("Usage:") print(" %s %s" % (cls._prog, task_func.usage)) print("") print(task_func.__doc__)
[ "def", "help", "(", "cls", ",", "task", "=", "None", ")", ":", "if", "task", "is", "None", ":", "usage_list", "=", "[", "]", "for", "task", "in", "iter", "(", "cls", ".", "_tasks", ")", ":", "task_func", "=", "getattr", "(", "cls", ",", "task", ...
Describe available tasks or one specific task
[ "Describe", "available", "tasks", "or", "one", "specific", "task" ]
88d3ba332fb2cd331f87517a16f2c2d4296cee90
https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/scripts/shopify_api.py#L62-L86
train
215,764
Shopify/shopify_python_api
shopify/resources/gift_card.py
GiftCard.add_adjustment
def add_adjustment(self, adjustment): """ Create a new Gift Card Adjustment """ resource = self.post("adjustments", adjustment.encode()) return GiftCardAdjustment(GiftCard.format.decode(resource.body))
python
def add_adjustment(self, adjustment): """ Create a new Gift Card Adjustment """ resource = self.post("adjustments", adjustment.encode()) return GiftCardAdjustment(GiftCard.format.decode(resource.body))
[ "def", "add_adjustment", "(", "self", ",", "adjustment", ")", ":", "resource", "=", "self", ".", "post", "(", "\"adjustments\"", ",", "adjustment", ".", "encode", "(", ")", ")", "return", "GiftCardAdjustment", "(", "GiftCard", ".", "format", ".", "decode", ...
Create a new Gift Card Adjustment
[ "Create", "a", "new", "Gift", "Card", "Adjustment" ]
88d3ba332fb2cd331f87517a16f2c2d4296cee90
https://github.com/Shopify/shopify_python_api/blob/88d3ba332fb2cd331f87517a16f2c2d4296cee90/shopify/resources/gift_card.py#L26-L31
train
215,765
aiven/pghoard
pghoard/rohmu/object_storage/local.py
atomic_create_file
def atomic_create_file(file_path): """Open a temporary file for writing, rename to final name when done""" fd, tmp_file_path = tempfile.mkstemp( prefix=os.path.basename(file_path), dir=os.path.dirname(file_path), suffix=".metadata_tmp" ) try: with os.fdopen(fd, "w") as out_file: yield out_file os.rename(tmp_file_path, file_path) except Exception: # pytest: disable=broad-except with contextlib.suppress(Exception): os.unlink(tmp_file_path) raise
python
def atomic_create_file(file_path): """Open a temporary file for writing, rename to final name when done""" fd, tmp_file_path = tempfile.mkstemp( prefix=os.path.basename(file_path), dir=os.path.dirname(file_path), suffix=".metadata_tmp" ) try: with os.fdopen(fd, "w") as out_file: yield out_file os.rename(tmp_file_path, file_path) except Exception: # pytest: disable=broad-except with contextlib.suppress(Exception): os.unlink(tmp_file_path) raise
[ "def", "atomic_create_file", "(", "file_path", ")", ":", "fd", ",", "tmp_file_path", "=", "tempfile", ".", "mkstemp", "(", "prefix", "=", "os", ".", "path", ".", "basename", "(", "file_path", ")", ",", "dir", "=", "os", ".", "path", ".", "dirname", "("...
Open a temporary file for writing, rename to final name when done
[ "Open", "a", "temporary", "file", "for", "writing", "rename", "to", "final", "name", "when", "done" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/local.py#L217-L230
train
215,766
aiven/pghoard
pghoard/rohmu/object_storage/azure.py
AzureTransfer._stream_blob
def _stream_blob(self, key, fileobj, progress_callback): """Streams contents of given key to given fileobj. Data is read sequentially in chunks without any seeks. This requires duplicating some functionality of the Azure SDK, which only allows reading entire blob into memory at once or returning data from random offsets""" file_size = None start_range = 0 chunk_size = self.conn.MAX_CHUNK_GET_SIZE end_range = chunk_size - 1 while True: try: # pylint: disable=protected-access blob = self.conn._get_blob(self.container_name, key, start_range=start_range, end_range=end_range) if file_size is None: file_size = self._parse_length_from_content_range(blob.properties.content_range) fileobj.write(blob.content) start_range += blob.properties.content_length if start_range == file_size: break if blob.properties.content_length == 0: raise StorageError( "Empty response received for {}, range {}-{}".format(key, start_range, end_range) ) end_range += blob.properties.content_length if end_range >= file_size: end_range = file_size - 1 if progress_callback: progress_callback(start_range, file_size) except azure.common.AzureHttpError as ex: # pylint: disable=no-member if ex.status_code == 416: # Empty file return raise
python
def _stream_blob(self, key, fileobj, progress_callback): """Streams contents of given key to given fileobj. Data is read sequentially in chunks without any seeks. This requires duplicating some functionality of the Azure SDK, which only allows reading entire blob into memory at once or returning data from random offsets""" file_size = None start_range = 0 chunk_size = self.conn.MAX_CHUNK_GET_SIZE end_range = chunk_size - 1 while True: try: # pylint: disable=protected-access blob = self.conn._get_blob(self.container_name, key, start_range=start_range, end_range=end_range) if file_size is None: file_size = self._parse_length_from_content_range(blob.properties.content_range) fileobj.write(blob.content) start_range += blob.properties.content_length if start_range == file_size: break if blob.properties.content_length == 0: raise StorageError( "Empty response received for {}, range {}-{}".format(key, start_range, end_range) ) end_range += blob.properties.content_length if end_range >= file_size: end_range = file_size - 1 if progress_callback: progress_callback(start_range, file_size) except azure.common.AzureHttpError as ex: # pylint: disable=no-member if ex.status_code == 416: # Empty file return raise
[ "def", "_stream_blob", "(", "self", ",", "key", ",", "fileobj", ",", "progress_callback", ")", ":", "file_size", "=", "None", "start_range", "=", "0", "chunk_size", "=", "self", ".", "conn", ".", "MAX_CHUNK_GET_SIZE", "end_range", "=", "chunk_size", "-", "1"...
Streams contents of given key to given fileobj. Data is read sequentially in chunks without any seeks. This requires duplicating some functionality of the Azure SDK, which only allows reading entire blob into memory at once or returning data from random offsets
[ "Streams", "contents", "of", "given", "key", "to", "given", "fileobj", ".", "Data", "is", "read", "sequentially", "in", "chunks", "without", "any", "seeks", ".", "This", "requires", "duplicating", "some", "functionality", "of", "the", "Azure", "SDK", "which", ...
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/azure.py#L161-L191
train
215,767
aiven/pghoard
pghoard/rohmu/object_storage/base.py
BaseTransfer.format_key_for_backend
def format_key_for_backend(self, key, remove_slash_prefix=False, trailing_slash=False): """Add a possible prefix to the key before sending it to the backend""" path = self.prefix + key if trailing_slash: if not path or path[-1] != "/": path += "/" else: path = path.rstrip("/") if remove_slash_prefix: # Azure defines slashes in the beginning as "dirs" for listing purposes path = path.lstrip("/") return path
python
def format_key_for_backend(self, key, remove_slash_prefix=False, trailing_slash=False): """Add a possible prefix to the key before sending it to the backend""" path = self.prefix + key if trailing_slash: if not path or path[-1] != "/": path += "/" else: path = path.rstrip("/") if remove_slash_prefix: # Azure defines slashes in the beginning as "dirs" for listing purposes path = path.lstrip("/") return path
[ "def", "format_key_for_backend", "(", "self", ",", "key", ",", "remove_slash_prefix", "=", "False", ",", "trailing_slash", "=", "False", ")", ":", "path", "=", "self", ".", "prefix", "+", "key", "if", "trailing_slash", ":", "if", "not", "path", "or", "path...
Add a possible prefix to the key before sending it to the backend
[ "Add", "a", "possible", "prefix", "to", "the", "key", "before", "sending", "it", "to", "the", "backend" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/base.py#L34-L44
train
215,768
aiven/pghoard
pghoard/rohmu/object_storage/base.py
BaseTransfer.format_key_from_backend
def format_key_from_backend(self, key): """Strip the configured prefix from a key retrieved from the backend before passing it on to other pghoard code and presenting it to the user.""" if not self.prefix: return key if not key.startswith(self.prefix): raise StorageError("Key {!r} does not start with expected prefix {!r}".format(key, self.prefix)) return key[len(self.prefix):]
python
def format_key_from_backend(self, key): """Strip the configured prefix from a key retrieved from the backend before passing it on to other pghoard code and presenting it to the user.""" if not self.prefix: return key if not key.startswith(self.prefix): raise StorageError("Key {!r} does not start with expected prefix {!r}".format(key, self.prefix)) return key[len(self.prefix):]
[ "def", "format_key_from_backend", "(", "self", ",", "key", ")", ":", "if", "not", "self", ".", "prefix", ":", "return", "key", "if", "not", "key", ".", "startswith", "(", "self", ".", "prefix", ")", ":", "raise", "StorageError", "(", "\"Key {!r} does not s...
Strip the configured prefix from a key retrieved from the backend before passing it on to other pghoard code and presenting it to the user.
[ "Strip", "the", "configured", "prefix", "from", "a", "key", "retrieved", "from", "the", "backend", "before", "passing", "it", "on", "to", "other", "pghoard", "code", "and", "presenting", "it", "to", "the", "user", "." ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/base.py#L46-L54
train
215,769
aiven/pghoard
pghoard/rohmu/object_storage/base.py
BaseTransfer.delete_tree
def delete_tree(self, key): """Delete all keys under given root key. Basic implementation works by just listing all available keys and deleting them individually but storage providers can implement more efficient logic.""" self.log.debug("Deleting tree: %r", key) names = [item["name"] for item in self.list_path(key, with_metadata=False, deep=True)] for name in names: self.delete_key(name)
python
def delete_tree(self, key): """Delete all keys under given root key. Basic implementation works by just listing all available keys and deleting them individually but storage providers can implement more efficient logic.""" self.log.debug("Deleting tree: %r", key) names = [item["name"] for item in self.list_path(key, with_metadata=False, deep=True)] for name in names: self.delete_key(name)
[ "def", "delete_tree", "(", "self", ",", "key", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Deleting tree: %r\"", ",", "key", ")", "names", "=", "[", "item", "[", "\"name\"", "]", "for", "item", "in", "self", ".", "list_path", "(", "key", ",",...
Delete all keys under given root key. Basic implementation works by just listing all available keys and deleting them individually but storage providers can implement more efficient logic.
[ "Delete", "all", "keys", "under", "given", "root", "key", ".", "Basic", "implementation", "works", "by", "just", "listing", "all", "available", "keys", "and", "deleting", "them", "individually", "but", "storage", "providers", "can", "implement", "more", "efficie...
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/base.py#L59-L65
train
215,770
aiven/pghoard
pghoard/rohmu/object_storage/base.py
BaseTransfer.sanitize_metadata
def sanitize_metadata(self, metadata, replace_hyphen_with="-"): """Convert non-string metadata values to strings and drop null values""" return {str(k).replace("-", replace_hyphen_with): str(v) for k, v in (metadata or {}).items() if v is not None}
python
def sanitize_metadata(self, metadata, replace_hyphen_with="-"): """Convert non-string metadata values to strings and drop null values""" return {str(k).replace("-", replace_hyphen_with): str(v) for k, v in (metadata or {}).items() if v is not None}
[ "def", "sanitize_metadata", "(", "self", ",", "metadata", ",", "replace_hyphen_with", "=", "\"-\"", ")", ":", "return", "{", "str", "(", "k", ")", ".", "replace", "(", "\"-\"", ",", "replace_hyphen_with", ")", ":", "str", "(", "v", ")", "for", "k", ","...
Convert non-string metadata values to strings and drop null values
[ "Convert", "non", "-", "string", "metadata", "values", "to", "strings", "and", "drop", "null", "values" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/base.py#L112-L115
train
215,771
aiven/pghoard
pghoard/rohmu/dates.py
parse_timestamp
def parse_timestamp(ts, *, with_tz=True, assume_local=False): """Parse a given timestamp and return a datetime object with or without tzinfo. If `with_tz` is False and we can't parse a timezone from the timestamp the datetime object is returned as-is and we assume the timezone is whatever was requested. If `with_tz` is False and we can parse a timezone, the timestamp is converted to either local or UTC time based on `assume_local` after which tzinfo is stripped and the timestamp is returned. When `with_tz` is True and there's a timezone in the timestamp we return it as-is. If `with_tz` is True but we can't parse a timezone we add either local or UTC timezone to the datetime based on `assume_local`. """ parse_result = dateutil.parser.parse(ts) # pylint thinks dateutil.parser.parse always returns a tuple even though we didn't request it. # So this check is pointless but convinces pylint that we really have a datetime object now. dt = parse_result[0] if isinstance(parse_result, tuple) else parse_result # pylint: disable=unsubscriptable-object if with_tz is False: if not dt.tzinfo: return dt tz = dateutil.tz.tzlocal() if assume_local else datetime.timezone.utc return dt.astimezone(tz).replace(tzinfo=None) if dt.tzinfo: return dt tz = dateutil.tz.tzlocal() if assume_local else datetime.timezone.utc return dt.replace(tzinfo=tz)
python
def parse_timestamp(ts, *, with_tz=True, assume_local=False): """Parse a given timestamp and return a datetime object with or without tzinfo. If `with_tz` is False and we can't parse a timezone from the timestamp the datetime object is returned as-is and we assume the timezone is whatever was requested. If `with_tz` is False and we can parse a timezone, the timestamp is converted to either local or UTC time based on `assume_local` after which tzinfo is stripped and the timestamp is returned. When `with_tz` is True and there's a timezone in the timestamp we return it as-is. If `with_tz` is True but we can't parse a timezone we add either local or UTC timezone to the datetime based on `assume_local`. """ parse_result = dateutil.parser.parse(ts) # pylint thinks dateutil.parser.parse always returns a tuple even though we didn't request it. # So this check is pointless but convinces pylint that we really have a datetime object now. dt = parse_result[0] if isinstance(parse_result, tuple) else parse_result # pylint: disable=unsubscriptable-object if with_tz is False: if not dt.tzinfo: return dt tz = dateutil.tz.tzlocal() if assume_local else datetime.timezone.utc return dt.astimezone(tz).replace(tzinfo=None) if dt.tzinfo: return dt tz = dateutil.tz.tzlocal() if assume_local else datetime.timezone.utc return dt.replace(tzinfo=tz)
[ "def", "parse_timestamp", "(", "ts", ",", "*", ",", "with_tz", "=", "True", ",", "assume_local", "=", "False", ")", ":", "parse_result", "=", "dateutil", ".", "parser", ".", "parse", "(", "ts", ")", "# pylint thinks dateutil.parser.parse always returns a tuple eve...
Parse a given timestamp and return a datetime object with or without tzinfo. If `with_tz` is False and we can't parse a timezone from the timestamp the datetime object is returned as-is and we assume the timezone is whatever was requested. If `with_tz` is False and we can parse a timezone, the timestamp is converted to either local or UTC time based on `assume_local` after which tzinfo is stripped and the timestamp is returned. When `with_tz` is True and there's a timezone in the timestamp we return it as-is. If `with_tz` is True but we can't parse a timezone we add either local or UTC timezone to the datetime based on `assume_local`.
[ "Parse", "a", "given", "timestamp", "and", "return", "a", "datetime", "object", "with", "or", "without", "tzinfo", "." ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/dates.py#L12-L40
train
215,772
aiven/pghoard
pghoard/common.py
create_pgpass_file
def create_pgpass_file(connection_string_or_info): """Look up password from the given object which can be a dict or a string and write a possible password in a pgpass file; returns a connection_string without a password in it""" info = pgutil.get_connection_info(connection_string_or_info) if "password" not in info: return pgutil.create_connection_string(info) linekey = "{host}:{port}:{dbname}:{user}:".format( host=info.get("host", "localhost"), port=info.get("port", 5432), user=info.get("user", ""), dbname=info.get("dbname", "*")) pwline = "{linekey}{password}".format(linekey=linekey, password=info.pop("password")) pgpass_path = os.path.join(os.environ.get("HOME"), ".pgpass") if os.path.exists(pgpass_path): with open(pgpass_path, "r") as fp: pgpass_lines = fp.read().splitlines() else: pgpass_lines = [] if pwline in pgpass_lines: LOG.debug("Not adding authentication data to: %s since it's already there", pgpass_path) else: # filter out any existing lines with our linekey and add the new line pgpass_lines = [line for line in pgpass_lines if not line.startswith(linekey)] + [pwline] content = "\n".join(pgpass_lines) + "\n" with open(pgpass_path, "w") as fp: os.fchmod(fp.fileno(), 0o600) fp.write(content) LOG.debug("Wrote %r to %r", pwline, pgpass_path) return pgutil.create_connection_string(info)
python
def create_pgpass_file(connection_string_or_info): """Look up password from the given object which can be a dict or a string and write a possible password in a pgpass file; returns a connection_string without a password in it""" info = pgutil.get_connection_info(connection_string_or_info) if "password" not in info: return pgutil.create_connection_string(info) linekey = "{host}:{port}:{dbname}:{user}:".format( host=info.get("host", "localhost"), port=info.get("port", 5432), user=info.get("user", ""), dbname=info.get("dbname", "*")) pwline = "{linekey}{password}".format(linekey=linekey, password=info.pop("password")) pgpass_path = os.path.join(os.environ.get("HOME"), ".pgpass") if os.path.exists(pgpass_path): with open(pgpass_path, "r") as fp: pgpass_lines = fp.read().splitlines() else: pgpass_lines = [] if pwline in pgpass_lines: LOG.debug("Not adding authentication data to: %s since it's already there", pgpass_path) else: # filter out any existing lines with our linekey and add the new line pgpass_lines = [line for line in pgpass_lines if not line.startswith(linekey)] + [pwline] content = "\n".join(pgpass_lines) + "\n" with open(pgpass_path, "w") as fp: os.fchmod(fp.fileno(), 0o600) fp.write(content) LOG.debug("Wrote %r to %r", pwline, pgpass_path) return pgutil.create_connection_string(info)
[ "def", "create_pgpass_file", "(", "connection_string_or_info", ")", ":", "info", "=", "pgutil", ".", "get_connection_info", "(", "connection_string_or_info", ")", "if", "\"password\"", "not", "in", "info", ":", "return", "pgutil", ".", "create_connection_string", "(",...
Look up password from the given object which can be a dict or a string and write a possible password in a pgpass file; returns a connection_string without a password in it
[ "Look", "up", "password", "from", "the", "given", "object", "which", "can", "be", "a", "dict", "or", "a", "string", "and", "write", "a", "possible", "password", "in", "a", "pgpass", "file", ";", "returns", "a", "connection_string", "without", "a", "passwor...
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/common.py#L26-L55
train
215,773
aiven/pghoard
pghoard/common.py
replication_connection_string_and_slot_using_pgpass
def replication_connection_string_and_slot_using_pgpass(target_node_info): """Like `connection_string_and_slot_using_pgpass` but returns a connection string for a replication connection.""" connection_info, slot = connection_info_and_slot(target_node_info) connection_info["dbname"] = "replication" connection_info["replication"] = "true" connection_string = create_pgpass_file(connection_info) return connection_string, slot
python
def replication_connection_string_and_slot_using_pgpass(target_node_info): """Like `connection_string_and_slot_using_pgpass` but returns a connection string for a replication connection.""" connection_info, slot = connection_info_and_slot(target_node_info) connection_info["dbname"] = "replication" connection_info["replication"] = "true" connection_string = create_pgpass_file(connection_info) return connection_string, slot
[ "def", "replication_connection_string_and_slot_using_pgpass", "(", "target_node_info", ")", ":", "connection_info", ",", "slot", "=", "connection_info_and_slot", "(", "target_node_info", ")", "connection_info", "[", "\"dbname\"", "]", "=", "\"replication\"", "connection_info"...
Like `connection_string_and_slot_using_pgpass` but returns a connection string for a replication connection.
[ "Like", "connection_string_and_slot_using_pgpass", "but", "returns", "a", "connection", "string", "for", "a", "replication", "connection", "." ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/common.py#L85-L92
train
215,774
aiven/pghoard
pghoard/transfer.py
TransferAgent.transmit_metrics
def transmit_metrics(self): """ Keep metrics updated about how long time ago each filetype was successfully uploaded. Transmits max once per ten seconds, regardless of how many threads are running. """ global _last_stats_transmit_time # pylint: disable=global-statement with _STATS_LOCK: # pylint: disable=not-context-manager if time.monotonic() - _last_stats_transmit_time < 10.0: return for site in self.state: for filetype, prop in self.state[site]["upload"].items(): if prop["last_success"]: self.metrics.gauge( "pghoard.last_upload_age", time.monotonic() - prop["last_success"], tags={ "site": site, "type": filetype, } ) _last_stats_transmit_time = time.monotonic()
python
def transmit_metrics(self): """ Keep metrics updated about how long time ago each filetype was successfully uploaded. Transmits max once per ten seconds, regardless of how many threads are running. """ global _last_stats_transmit_time # pylint: disable=global-statement with _STATS_LOCK: # pylint: disable=not-context-manager if time.monotonic() - _last_stats_transmit_time < 10.0: return for site in self.state: for filetype, prop in self.state[site]["upload"].items(): if prop["last_success"]: self.metrics.gauge( "pghoard.last_upload_age", time.monotonic() - prop["last_success"], tags={ "site": site, "type": filetype, } ) _last_stats_transmit_time = time.monotonic()
[ "def", "transmit_metrics", "(", "self", ")", ":", "global", "_last_stats_transmit_time", "# pylint: disable=global-statement", "with", "_STATS_LOCK", ":", "# pylint: disable=not-context-manager", "if", "time", ".", "monotonic", "(", ")", "-", "_last_stats_transmit_time", "<...
Keep metrics updated about how long time ago each filetype was successfully uploaded. Transmits max once per ten seconds, regardless of how many threads are running.
[ "Keep", "metrics", "updated", "about", "how", "long", "time", "ago", "each", "filetype", "was", "successfully", "uploaded", ".", "Transmits", "max", "once", "per", "ten", "seconds", "regardless", "of", "how", "many", "threads", "are", "running", "." ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/transfer.py#L80-L101
train
215,775
aiven/pghoard
pghoard/rohmu/encryptor.py
EncryptorFile.write
def write(self, data): """Encrypt and write the given bytes""" self._check_not_closed() if not data: return 0 enc_data = self.encryptor.update(data) self.next_fp.write(enc_data) self.offset += len(data) return len(data)
python
def write(self, data): """Encrypt and write the given bytes""" self._check_not_closed() if not data: return 0 enc_data = self.encryptor.update(data) self.next_fp.write(enc_data) self.offset += len(data) return len(data)
[ "def", "write", "(", "self", ",", "data", ")", ":", "self", ".", "_check_not_closed", "(", ")", "if", "not", "data", ":", "return", "0", "enc_data", "=", "self", ".", "encryptor", ".", "update", "(", "data", ")", "self", ".", "next_fp", ".", "write",...
Encrypt and write the given bytes
[ "Encrypt", "and", "write", "the", "given", "bytes" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/encryptor.py#L101-L109
train
215,776
aiven/pghoard
pghoard/rohmu/encryptor.py
DecryptorFile.read
def read(self, size=-1): """Read up to size decrypted bytes""" self._check_not_closed() if self.state == "EOF" or size == 0: return b"" elif size < 0: return self._read_all() else: return self._read_block(size)
python
def read(self, size=-1): """Read up to size decrypted bytes""" self._check_not_closed() if self.state == "EOF" or size == 0: return b"" elif size < 0: return self._read_all() else: return self._read_block(size)
[ "def", "read", "(", "self", ",", "size", "=", "-", "1", ")", ":", "self", ".", "_check_not_closed", "(", ")", "if", "self", ".", "state", "==", "\"EOF\"", "or", "size", "==", "0", ":", "return", "b\"\"", "elif", "size", "<", "0", ":", "return", "...
Read up to size decrypted bytes
[ "Read", "up", "to", "size", "decrypted", "bytes" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/encryptor.py#L314-L322
train
215,777
aiven/pghoard
pghoard/gnutaremu.py
SedStatementParser.tokenize_string
def tokenize_string(cls, string, separator): """Split string with given separator unless the separator is escaped with backslash""" results = [] token = "" found_escape = False for c in string: if found_escape: if c == separator: token += separator else: token += "\\" + c found_escape = False continue if c == "\\": found_escape = True elif c == separator: results.append(token) token = "" else: token += c results.append(token) return results
python
def tokenize_string(cls, string, separator): """Split string with given separator unless the separator is escaped with backslash""" results = [] token = "" found_escape = False for c in string: if found_escape: if c == separator: token += separator else: token += "\\" + c found_escape = False continue if c == "\\": found_escape = True elif c == separator: results.append(token) token = "" else: token += c results.append(token) return results
[ "def", "tokenize_string", "(", "cls", ",", "string", ",", "separator", ")", ":", "results", "=", "[", "]", "token", "=", "\"\"", "found_escape", "=", "False", "for", "c", "in", "string", ":", "if", "found_escape", ":", "if", "c", "==", "separator", ":"...
Split string with given separator unless the separator is escaped with backslash
[ "Split", "string", "with", "given", "separator", "unless", "the", "separator", "is", "escaped", "with", "backslash" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/gnutaremu.py#L148-L170
train
215,778
aiven/pghoard
pghoard/rohmu/object_storage/google.py
GoogleTransfer._unpaginate
def _unpaginate(self, domain, initial_op, *, on_properties): """Iterate thru the request pages until all items have been processed""" request = initial_op(domain) while request is not None: result = self._retry_on_reset(request, request.execute) for on_property in on_properties: items = result.get(on_property) if items is not None: yield on_property, items request = domain.list_next(request, result)
python
def _unpaginate(self, domain, initial_op, *, on_properties): """Iterate thru the request pages until all items have been processed""" request = initial_op(domain) while request is not None: result = self._retry_on_reset(request, request.execute) for on_property in on_properties: items = result.get(on_property) if items is not None: yield on_property, items request = domain.list_next(request, result)
[ "def", "_unpaginate", "(", "self", ",", "domain", ",", "initial_op", ",", "*", ",", "on_properties", ")", ":", "request", "=", "initial_op", "(", "domain", ")", "while", "request", "is", "not", "None", ":", "result", "=", "self", ".", "_retry_on_reset", ...
Iterate thru the request pages until all items have been processed
[ "Iterate", "thru", "the", "request", "pages", "until", "all", "items", "have", "been", "processed" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/google.py#L194-L203
train
215,779
aiven/pghoard
pghoard/rohmu/object_storage/google.py
GoogleTransfer.get_or_create_bucket
def get_or_create_bucket(self, bucket_name): """Look up the bucket if it already exists and try to create the bucket in case it doesn't. Note that we can't just always try to unconditionally create the bucket as Google imposes a strict rate limit on bucket creation operations, even if it doesn't result in a new bucket. Quietly handle the case where the bucket already exists to avoid race conditions. Note that we'll get a 400 Bad Request response for invalid bucket names ("Invalid bucket name") as well as for invalid project ("Invalid argument"), try to handle both gracefully.""" start_time = time.time() gs_buckets = self.gs.buckets() # pylint: disable=no-member try: request = gs_buckets.get(bucket=bucket_name) self._retry_on_reset(request, request.execute) self.log.debug("Bucket: %r already exists, took: %.3fs", bucket_name, time.time() - start_time) except HttpError as ex: if ex.resp["status"] == "404": pass # we need to create it elif ex.resp["status"] == "403": raise InvalidConfigurationError("Bucket {0!r} exists but isn't accessible".format(bucket_name)) else: raise else: return bucket_name try: req = gs_buckets.insert(project=self.project_id, body={"name": bucket_name}) self._retry_on_reset(req, req.execute) self.log.debug("Created bucket: %r successfully, took: %.3fs", bucket_name, time.time() - start_time) except HttpError as ex: error = json.loads(ex.content.decode("utf-8"))["error"] if error["message"].startswith("You already own this bucket"): self.log.debug("Bucket: %r already exists, took: %.3fs", bucket_name, time.time() - start_time) elif error["message"] == "Invalid argument.": raise InvalidConfigurationError("Invalid project id {0!r}".format(self.project_id)) elif error["message"].startswith("Invalid bucket name"): raise InvalidConfigurationError("Invalid bucket name {0!r}".format(bucket_name)) else: raise return bucket_name
python
def get_or_create_bucket(self, bucket_name): """Look up the bucket if it already exists and try to create the bucket in case it doesn't. Note that we can't just always try to unconditionally create the bucket as Google imposes a strict rate limit on bucket creation operations, even if it doesn't result in a new bucket. Quietly handle the case where the bucket already exists to avoid race conditions. Note that we'll get a 400 Bad Request response for invalid bucket names ("Invalid bucket name") as well as for invalid project ("Invalid argument"), try to handle both gracefully.""" start_time = time.time() gs_buckets = self.gs.buckets() # pylint: disable=no-member try: request = gs_buckets.get(bucket=bucket_name) self._retry_on_reset(request, request.execute) self.log.debug("Bucket: %r already exists, took: %.3fs", bucket_name, time.time() - start_time) except HttpError as ex: if ex.resp["status"] == "404": pass # we need to create it elif ex.resp["status"] == "403": raise InvalidConfigurationError("Bucket {0!r} exists but isn't accessible".format(bucket_name)) else: raise else: return bucket_name try: req = gs_buckets.insert(project=self.project_id, body={"name": bucket_name}) self._retry_on_reset(req, req.execute) self.log.debug("Created bucket: %r successfully, took: %.3fs", bucket_name, time.time() - start_time) except HttpError as ex: error = json.loads(ex.content.decode("utf-8"))["error"] if error["message"].startswith("You already own this bucket"): self.log.debug("Bucket: %r already exists, took: %.3fs", bucket_name, time.time() - start_time) elif error["message"] == "Invalid argument.": raise InvalidConfigurationError("Invalid project id {0!r}".format(self.project_id)) elif error["message"].startswith("Invalid bucket name"): raise InvalidConfigurationError("Invalid bucket name {0!r}".format(bucket_name)) else: raise return bucket_name
[ "def", "get_or_create_bucket", "(", "self", ",", "bucket_name", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "gs_buckets", "=", "self", ".", "gs", ".", "buckets", "(", ")", "# pylint: disable=no-member", "try", ":", "request", "=", "gs_buckets...
Look up the bucket if it already exists and try to create the bucket in case it doesn't. Note that we can't just always try to unconditionally create the bucket as Google imposes a strict rate limit on bucket creation operations, even if it doesn't result in a new bucket. Quietly handle the case where the bucket already exists to avoid race conditions. Note that we'll get a 400 Bad Request response for invalid bucket names ("Invalid bucket name") as well as for invalid project ("Invalid argument"), try to handle both gracefully.
[ "Look", "up", "the", "bucket", "if", "it", "already", "exists", "and", "try", "to", "create", "the", "bucket", "in", "case", "it", "doesn", "t", ".", "Note", "that", "we", "can", "t", "just", "always", "try", "to", "unconditionally", "create", "the", "...
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/rohmu/object_storage/google.py#L348-L390
train
215,780
aiven/pghoard
pghoard/walreceiver.py
WALReceiver.fetch_timeline_history_files
def fetch_timeline_history_files(self, max_timeline): """Copy all timeline history files found on the server without checking if we have them or not. The history files are very small so reuploading them should not matter.""" while max_timeline > 1: self.c.execute("TIMELINE_HISTORY {}".format(max_timeline)) timeline_history = self.c.fetchone() history_filename = timeline_history[0] history_data = timeline_history[1].tobytes() self.log.debug("Received timeline history: %s for timeline %r", history_filename, max_timeline) compression_event = { "type": "CLOSE_WRITE", "compress_to_memory": True, "delete_file_after_compression": False, "input_data": BytesIO(history_data), "full_path": history_filename, "site": self.site, } self.compression_queue.put(compression_event) max_timeline -= 1
python
def fetch_timeline_history_files(self, max_timeline): """Copy all timeline history files found on the server without checking if we have them or not. The history files are very small so reuploading them should not matter.""" while max_timeline > 1: self.c.execute("TIMELINE_HISTORY {}".format(max_timeline)) timeline_history = self.c.fetchone() history_filename = timeline_history[0] history_data = timeline_history[1].tobytes() self.log.debug("Received timeline history: %s for timeline %r", history_filename, max_timeline) compression_event = { "type": "CLOSE_WRITE", "compress_to_memory": True, "delete_file_after_compression": False, "input_data": BytesIO(history_data), "full_path": history_filename, "site": self.site, } self.compression_queue.put(compression_event) max_timeline -= 1
[ "def", "fetch_timeline_history_files", "(", "self", ",", "max_timeline", ")", ":", "while", "max_timeline", ">", "1", ":", "self", ".", "c", ".", "execute", "(", "\"TIMELINE_HISTORY {}\"", ".", "format", "(", "max_timeline", ")", ")", "timeline_history", "=", ...
Copy all timeline history files found on the server without checking if we have them or not. The history files are very small so reuploading them should not matter.
[ "Copy", "all", "timeline", "history", "files", "found", "on", "the", "server", "without", "checking", "if", "we", "have", "them", "or", "not", ".", "The", "history", "files", "are", "very", "small", "so", "reuploading", "them", "should", "not", "matter", "...
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/walreceiver.py#L60-L81
train
215,781
aiven/pghoard
pghoard/pghoard.py
PGHoard.check_backup_count_and_state
def check_backup_count_and_state(self, site): """Look up basebackups from the object store, prune any extra backups and return the datetime of the latest backup.""" basebackups = self.get_remote_basebackups_info(site) self.log.debug("Found %r basebackups", basebackups) if basebackups: last_backup_time = basebackups[-1]["metadata"]["start-time"] else: last_backup_time = None allowed_basebackup_count = self.config["backup_sites"][site]["basebackup_count"] if allowed_basebackup_count is None: allowed_basebackup_count = len(basebackups) while len(basebackups) > allowed_basebackup_count: self.log.warning("Too many basebackups: %d > %d, %r, starting to get rid of %r", len(basebackups), allowed_basebackup_count, basebackups, basebackups[0]["name"]) basebackup_to_be_deleted = basebackups.pop(0) pg_version = basebackup_to_be_deleted["metadata"].get("pg-version") last_wal_segment_still_needed = 0 if basebackups: last_wal_segment_still_needed = basebackups[0]["metadata"]["start-wal-segment"] if last_wal_segment_still_needed: self.delete_remote_wal_before(last_wal_segment_still_needed, site, pg_version) self.delete_remote_basebackup(site, basebackup_to_be_deleted["name"], basebackup_to_be_deleted["metadata"]) self.state["backup_sites"][site]["basebackups"] = basebackups return last_backup_time
python
def check_backup_count_and_state(self, site): """Look up basebackups from the object store, prune any extra backups and return the datetime of the latest backup.""" basebackups = self.get_remote_basebackups_info(site) self.log.debug("Found %r basebackups", basebackups) if basebackups: last_backup_time = basebackups[-1]["metadata"]["start-time"] else: last_backup_time = None allowed_basebackup_count = self.config["backup_sites"][site]["basebackup_count"] if allowed_basebackup_count is None: allowed_basebackup_count = len(basebackups) while len(basebackups) > allowed_basebackup_count: self.log.warning("Too many basebackups: %d > %d, %r, starting to get rid of %r", len(basebackups), allowed_basebackup_count, basebackups, basebackups[0]["name"]) basebackup_to_be_deleted = basebackups.pop(0) pg_version = basebackup_to_be_deleted["metadata"].get("pg-version") last_wal_segment_still_needed = 0 if basebackups: last_wal_segment_still_needed = basebackups[0]["metadata"]["start-wal-segment"] if last_wal_segment_still_needed: self.delete_remote_wal_before(last_wal_segment_still_needed, site, pg_version) self.delete_remote_basebackup(site, basebackup_to_be_deleted["name"], basebackup_to_be_deleted["metadata"]) self.state["backup_sites"][site]["basebackups"] = basebackups return last_backup_time
[ "def", "check_backup_count_and_state", "(", "self", ",", "site", ")", ":", "basebackups", "=", "self", ".", "get_remote_basebackups_info", "(", "site", ")", "self", ".", "log", ".", "debug", "(", "\"Found %r basebackups\"", ",", "basebackups", ")", "if", "baseba...
Look up basebackups from the object store, prune any extra backups and return the datetime of the latest backup.
[ "Look", "up", "basebackups", "from", "the", "object", "store", "prune", "any", "extra", "backups", "and", "return", "the", "datetime", "of", "the", "latest", "backup", "." ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/pghoard.py#L311-L340
train
215,782
aiven/pghoard
pghoard/pghoard.py
PGHoard.startup_walk_for_missed_files
def startup_walk_for_missed_files(self): """Check xlog and xlog_incoming directories for files that receivexlog has received but not yet compressed as well as the files we have compressed but not yet uploaded and process them.""" for site in self.config["backup_sites"]: compressed_xlog_path, _ = self.create_backup_site_paths(site) uncompressed_xlog_path = compressed_xlog_path + "_incoming" # Process uncompressed files (ie WAL pg_receivexlog received) for filename in os.listdir(uncompressed_xlog_path): full_path = os.path.join(uncompressed_xlog_path, filename) if not wal.WAL_RE.match(filename) and not wal.TIMELINE_RE.match(filename): self.log.warning("Found invalid file %r from incoming xlog directory", full_path) continue compression_event = { "delete_file_after_compression": True, "full_path": full_path, "site": site, "src_path": "{}.partial", "type": "MOVE", } self.log.debug("Found: %r when starting up, adding to compression queue", compression_event) self.compression_queue.put(compression_event) # Process compressed files (ie things we've processed but not yet uploaded) for filename in os.listdir(compressed_xlog_path): if filename.endswith(".metadata"): continue # silently ignore .metadata files, they're expected and processed below full_path = os.path.join(compressed_xlog_path, filename) metadata_path = full_path + ".metadata" is_xlog = wal.WAL_RE.match(filename) is_timeline = wal.TIMELINE_RE.match(filename) if not ((is_xlog or is_timeline) and os.path.exists(metadata_path)): self.log.warning("Found invalid file %r from compressed xlog directory", full_path) continue with open(metadata_path, "r") as fp: metadata = json.load(fp) transfer_event = { "file_size": os.path.getsize(full_path), "filetype": "xlog" if is_xlog else "timeline", "local_path": full_path, "metadata": metadata, "site": site, "type": "UPLOAD", } self.log.debug("Found: %r when starting up, adding to transfer queue", transfer_event) self.transfer_queue.put(transfer_event)
python
def startup_walk_for_missed_files(self): """Check xlog and xlog_incoming directories for files that receivexlog has received but not yet compressed as well as the files we have compressed but not yet uploaded and process them.""" for site in self.config["backup_sites"]: compressed_xlog_path, _ = self.create_backup_site_paths(site) uncompressed_xlog_path = compressed_xlog_path + "_incoming" # Process uncompressed files (ie WAL pg_receivexlog received) for filename in os.listdir(uncompressed_xlog_path): full_path = os.path.join(uncompressed_xlog_path, filename) if not wal.WAL_RE.match(filename) and not wal.TIMELINE_RE.match(filename): self.log.warning("Found invalid file %r from incoming xlog directory", full_path) continue compression_event = { "delete_file_after_compression": True, "full_path": full_path, "site": site, "src_path": "{}.partial", "type": "MOVE", } self.log.debug("Found: %r when starting up, adding to compression queue", compression_event) self.compression_queue.put(compression_event) # Process compressed files (ie things we've processed but not yet uploaded) for filename in os.listdir(compressed_xlog_path): if filename.endswith(".metadata"): continue # silently ignore .metadata files, they're expected and processed below full_path = os.path.join(compressed_xlog_path, filename) metadata_path = full_path + ".metadata" is_xlog = wal.WAL_RE.match(filename) is_timeline = wal.TIMELINE_RE.match(filename) if not ((is_xlog or is_timeline) and os.path.exists(metadata_path)): self.log.warning("Found invalid file %r from compressed xlog directory", full_path) continue with open(metadata_path, "r") as fp: metadata = json.load(fp) transfer_event = { "file_size": os.path.getsize(full_path), "filetype": "xlog" if is_xlog else "timeline", "local_path": full_path, "metadata": metadata, "site": site, "type": "UPLOAD", } self.log.debug("Found: %r when starting up, adding to transfer queue", transfer_event) self.transfer_queue.put(transfer_event)
[ "def", "startup_walk_for_missed_files", "(", "self", ")", ":", "for", "site", "in", "self", ".", "config", "[", "\"backup_sites\"", "]", ":", "compressed_xlog_path", ",", "_", "=", "self", ".", "create_backup_site_paths", "(", "site", ")", "uncompressed_xlog_path"...
Check xlog and xlog_incoming directories for files that receivexlog has received but not yet compressed as well as the files we have compressed but not yet uploaded and process them.
[ "Check", "xlog", "and", "xlog_incoming", "directories", "for", "files", "that", "receivexlog", "has", "received", "but", "not", "yet", "compressed", "as", "well", "as", "the", "files", "we", "have", "compressed", "but", "not", "yet", "uploaded", "and", "proces...
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/pghoard.py#L346-L392
train
215,783
aiven/pghoard
pghoard/pghoard.py
PGHoard.write_backup_state_to_json_file
def write_backup_state_to_json_file(self): """Periodically write a JSON state file to disk""" start_time = time.time() state_file_path = self.config["json_state_file_path"] self.state["walreceivers"] = { key: {"latest_activity": value.latest_activity, "running": value.running, "last_flushed_lsn": value.last_flushed_lsn} for key, value in self.walreceivers.items() } self.state["pg_receivexlogs"] = { key: {"latest_activity": value.latest_activity, "running": value.running} for key, value in self.receivexlogs.items() } self.state["pg_basebackups"] = { key: {"latest_activity": value.latest_activity, "running": value.running} for key, value in self.basebackups.items() } self.state["compressors"] = [compressor.state for compressor in self.compressors] self.state["transfer_agents"] = [ta.state for ta in self.transfer_agents] self.state["queues"] = { "compression_queue": self.compression_queue.qsize(), "transfer_queue": self.transfer_queue.qsize(), } self.log.debug("Writing JSON state file to %r", state_file_path) write_json_file(state_file_path, self.state) self.log.debug("Wrote JSON state file to disk, took %.4fs", time.time() - start_time)
python
def write_backup_state_to_json_file(self): """Periodically write a JSON state file to disk""" start_time = time.time() state_file_path = self.config["json_state_file_path"] self.state["walreceivers"] = { key: {"latest_activity": value.latest_activity, "running": value.running, "last_flushed_lsn": value.last_flushed_lsn} for key, value in self.walreceivers.items() } self.state["pg_receivexlogs"] = { key: {"latest_activity": value.latest_activity, "running": value.running} for key, value in self.receivexlogs.items() } self.state["pg_basebackups"] = { key: {"latest_activity": value.latest_activity, "running": value.running} for key, value in self.basebackups.items() } self.state["compressors"] = [compressor.state for compressor in self.compressors] self.state["transfer_agents"] = [ta.state for ta in self.transfer_agents] self.state["queues"] = { "compression_queue": self.compression_queue.qsize(), "transfer_queue": self.transfer_queue.qsize(), } self.log.debug("Writing JSON state file to %r", state_file_path) write_json_file(state_file_path, self.state) self.log.debug("Wrote JSON state file to disk, took %.4fs", time.time() - start_time)
[ "def", "write_backup_state_to_json_file", "(", "self", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "state_file_path", "=", "self", ".", "config", "[", "\"json_state_file_path\"", "]", "self", ".", "state", "[", "\"walreceivers\"", "]", "=", "{"...
Periodically write a JSON state file to disk
[ "Periodically", "write", "a", "JSON", "state", "file", "to", "disk" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/pghoard.py#L493-L518
train
215,784
aiven/pghoard
pghoard/pgutil.py
get_connection_info
def get_connection_info(info): """turn a connection info object into a dict or return it if it was a dict already. supports both the traditional libpq format and the new url format""" if isinstance(info, dict): return info.copy() elif info.startswith("postgres://") or info.startswith("postgresql://"): return parse_connection_string_url(info) else: return parse_connection_string_libpq(info)
python
def get_connection_info(info): """turn a connection info object into a dict or return it if it was a dict already. supports both the traditional libpq format and the new url format""" if isinstance(info, dict): return info.copy() elif info.startswith("postgres://") or info.startswith("postgresql://"): return parse_connection_string_url(info) else: return parse_connection_string_libpq(info)
[ "def", "get_connection_info", "(", "info", ")", ":", "if", "isinstance", "(", "info", ",", "dict", ")", ":", "return", "info", ".", "copy", "(", ")", "elif", "info", ".", "startswith", "(", "\"postgres://\"", ")", "or", "info", ".", "startswith", "(", ...
turn a connection info object into a dict or return it if it was a dict already. supports both the traditional libpq format and the new url format
[ "turn", "a", "connection", "info", "object", "into", "a", "dict", "or", "return", "it", "if", "it", "was", "a", "dict", "already", ".", "supports", "both", "the", "traditional", "libpq", "format", "and", "the", "new", "url", "format" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/pgutil.py#L34-L43
train
215,785
aiven/pghoard
pghoard/restore.py
Restore.list_basebackups_http
def list_basebackups_http(self, arg): """List available basebackups from a HTTP source""" self.storage = HTTPRestore(arg.host, arg.port, arg.site) self.storage.show_basebackup_list(verbose=arg.verbose)
python
def list_basebackups_http(self, arg): """List available basebackups from a HTTP source""" self.storage = HTTPRestore(arg.host, arg.port, arg.site) self.storage.show_basebackup_list(verbose=arg.verbose)
[ "def", "list_basebackups_http", "(", "self", ",", "arg", ")", ":", "self", ".", "storage", "=", "HTTPRestore", "(", "arg", ".", "host", ",", "arg", ".", "port", ",", "arg", ".", "site", ")", "self", ".", "storage", ".", "show_basebackup_list", "(", "ve...
List available basebackups from a HTTP source
[ "List", "available", "basebackups", "from", "a", "HTTP", "source" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/restore.py#L184-L187
train
215,786
aiven/pghoard
pghoard/restore.py
Restore.list_basebackups
def list_basebackups(self, arg): """List basebackups from an object store""" self.config = config.read_json_config_file(arg.config, check_commands=False, check_pgdata=False) site = config.get_site_from_config(self.config, arg.site) self.storage = self._get_object_storage(site, pgdata=None) self.storage.show_basebackup_list(verbose=arg.verbose)
python
def list_basebackups(self, arg): """List basebackups from an object store""" self.config = config.read_json_config_file(arg.config, check_commands=False, check_pgdata=False) site = config.get_site_from_config(self.config, arg.site) self.storage = self._get_object_storage(site, pgdata=None) self.storage.show_basebackup_list(verbose=arg.verbose)
[ "def", "list_basebackups", "(", "self", ",", "arg", ")", ":", "self", ".", "config", "=", "config", ".", "read_json_config_file", "(", "arg", ".", "config", ",", "check_commands", "=", "False", ",", "check_pgdata", "=", "False", ")", "site", "=", "config",...
List basebackups from an object store
[ "List", "basebackups", "from", "an", "object", "store" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/restore.py#L194-L199
train
215,787
aiven/pghoard
pghoard/restore.py
Restore.get_basebackup
def get_basebackup(self, arg): """Download a basebackup from an object store""" if not arg.tablespace_dir: tablespace_mapping = {} else: try: tablespace_mapping = dict(v.split("=", 1) for v in arg.tablespace_dir) except ValueError: raise RestoreError("Invalid tablespace mapping {!r}".format(arg.tablespace_dir)) self.config = config.read_json_config_file(arg.config, check_commands=False, check_pgdata=False) site = config.get_site_from_config(self.config, arg.site) try: self.storage = self._get_object_storage(site, arg.target_dir) self._get_basebackup( pgdata=arg.target_dir, basebackup=arg.basebackup, site=site, debug=arg.debug, status_output_file=arg.status_output_file, primary_conninfo=arg.primary_conninfo, recovery_end_command=arg.recovery_end_command, recovery_target_action=arg.recovery_target_action, recovery_target_name=arg.recovery_target_name, recovery_target_time=arg.recovery_target_time, recovery_target_xid=arg.recovery_target_xid, restore_to_master=arg.restore_to_master, overwrite=arg.overwrite, tablespace_mapping=tablespace_mapping, tablespace_base_dir=arg.tablespace_base_dir, ) except RestoreError: # pylint: disable=try-except-raise # Pass RestoreErrors thru raise except Exception as ex: if self.log_tracebacks: self.log.exception("Unexpected _get_basebackup failure") raise RestoreError("{}: {}".format(ex.__class__.__name__, ex))
python
def get_basebackup(self, arg): """Download a basebackup from an object store""" if not arg.tablespace_dir: tablespace_mapping = {} else: try: tablespace_mapping = dict(v.split("=", 1) for v in arg.tablespace_dir) except ValueError: raise RestoreError("Invalid tablespace mapping {!r}".format(arg.tablespace_dir)) self.config = config.read_json_config_file(arg.config, check_commands=False, check_pgdata=False) site = config.get_site_from_config(self.config, arg.site) try: self.storage = self._get_object_storage(site, arg.target_dir) self._get_basebackup( pgdata=arg.target_dir, basebackup=arg.basebackup, site=site, debug=arg.debug, status_output_file=arg.status_output_file, primary_conninfo=arg.primary_conninfo, recovery_end_command=arg.recovery_end_command, recovery_target_action=arg.recovery_target_action, recovery_target_name=arg.recovery_target_name, recovery_target_time=arg.recovery_target_time, recovery_target_xid=arg.recovery_target_xid, restore_to_master=arg.restore_to_master, overwrite=arg.overwrite, tablespace_mapping=tablespace_mapping, tablespace_base_dir=arg.tablespace_base_dir, ) except RestoreError: # pylint: disable=try-except-raise # Pass RestoreErrors thru raise except Exception as ex: if self.log_tracebacks: self.log.exception("Unexpected _get_basebackup failure") raise RestoreError("{}: {}".format(ex.__class__.__name__, ex))
[ "def", "get_basebackup", "(", "self", ",", "arg", ")", ":", "if", "not", "arg", ".", "tablespace_dir", ":", "tablespace_mapping", "=", "{", "}", "else", ":", "try", ":", "tablespace_mapping", "=", "dict", "(", "v", ".", "split", "(", "\"=\"", ",", "1",...
Download a basebackup from an object store
[ "Download", "a", "basebackup", "from", "an", "object", "store" ]
2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a
https://github.com/aiven/pghoard/blob/2994165d4ef3ff7a5669a2527346bcbfb5b3bd8a/pghoard/restore.py#L201-L238
train
215,788
scikit-hep/uproot
uproot/rootio.py
TKey.get
def get(self, dismiss=True): """Extract the object this key points to. Objects are not read or decompressed until this function is explicitly called. """ try: return _classof(self._context, self._fClassName).read(self._source, self._cursor.copied(), self._context, self) finally: if dismiss: self._source.dismiss()
python
def get(self, dismiss=True): """Extract the object this key points to. Objects are not read or decompressed until this function is explicitly called. """ try: return _classof(self._context, self._fClassName).read(self._source, self._cursor.copied(), self._context, self) finally: if dismiss: self._source.dismiss()
[ "def", "get", "(", "self", ",", "dismiss", "=", "True", ")", ":", "try", ":", "return", "_classof", "(", "self", ".", "_context", ",", "self", ".", "_fClassName", ")", ".", "read", "(", "self", ".", "_source", ",", "self", ".", "_cursor", ".", "cop...
Extract the object this key points to. Objects are not read or decompressed until this function is explicitly called.
[ "Extract", "the", "object", "this", "key", "points", "to", "." ]
fc406827e36ed87cfb1062806e118f53fd3a3b0a
https://github.com/scikit-hep/uproot/blob/fc406827e36ed87cfb1062806e118f53fd3a3b0a/uproot/rootio.py#L883-L893
train
215,789
zarr-developers/zarr
zarr/hierarchy.py
open_group
def open_group(store=None, mode='a', cache_attrs=True, synchronizer=None, path=None, chunk_store=None): """Open a group using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means read/write (must exist); 'a' means read/write (create if doesn't exist); 'w' means create (overwrite if exists); 'w-' means create (fail if exists). cache_attrs : bool, optional If True (default), user attributes will be cached for attribute read operations. If False, user attributes are reloaded from the store prior to all attribute read operations. synchronizer : object, optional Array synchronizer. path : string, optional Group path within store. chunk_store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. Returns ------- g : zarr.hierarchy.Group Examples -------- >>> import zarr >>> root = zarr.open_group('data/example.zarr', mode='w') >>> foo = root.create_group('foo') >>> bar = root.create_group('bar') >>> root <zarr.hierarchy.Group '/'> >>> root2 = zarr.open_group('data/example.zarr', mode='a') >>> root2 <zarr.hierarchy.Group '/'> >>> root == root2 True """ # handle polymorphic store arg store = _normalize_store_arg(store) if chunk_store is not None: chunk_store = _normalize_store_arg(chunk_store) path = normalize_storage_path(path) # ensure store is initialized if mode in ['r', 'r+']: if contains_array(store, path=path): err_contains_array(path) elif not contains_group(store, path=path): err_group_not_found(path) elif mode == 'w': init_group(store, overwrite=True, path=path, chunk_store=chunk_store) elif mode == 'a': if contains_array(store, path=path): err_contains_array(path) if not contains_group(store, path=path): init_group(store, path=path, chunk_store=chunk_store) elif mode in ['w-', 'x']: if contains_array(store, path=path): err_contains_array(path) elif contains_group(store, path=path): err_contains_group(path) else: init_group(store, path=path, chunk_store=chunk_store) # determine read only status read_only = mode == 'r' return Group(store, read_only=read_only, cache_attrs=cache_attrs, synchronizer=synchronizer, path=path, chunk_store=chunk_store)
python
def open_group(store=None, mode='a', cache_attrs=True, synchronizer=None, path=None, chunk_store=None): """Open a group using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means read/write (must exist); 'a' means read/write (create if doesn't exist); 'w' means create (overwrite if exists); 'w-' means create (fail if exists). cache_attrs : bool, optional If True (default), user attributes will be cached for attribute read operations. If False, user attributes are reloaded from the store prior to all attribute read operations. synchronizer : object, optional Array synchronizer. path : string, optional Group path within store. chunk_store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. Returns ------- g : zarr.hierarchy.Group Examples -------- >>> import zarr >>> root = zarr.open_group('data/example.zarr', mode='w') >>> foo = root.create_group('foo') >>> bar = root.create_group('bar') >>> root <zarr.hierarchy.Group '/'> >>> root2 = zarr.open_group('data/example.zarr', mode='a') >>> root2 <zarr.hierarchy.Group '/'> >>> root == root2 True """ # handle polymorphic store arg store = _normalize_store_arg(store) if chunk_store is not None: chunk_store = _normalize_store_arg(chunk_store) path = normalize_storage_path(path) # ensure store is initialized if mode in ['r', 'r+']: if contains_array(store, path=path): err_contains_array(path) elif not contains_group(store, path=path): err_group_not_found(path) elif mode == 'w': init_group(store, overwrite=True, path=path, chunk_store=chunk_store) elif mode == 'a': if contains_array(store, path=path): err_contains_array(path) if not contains_group(store, path=path): init_group(store, path=path, chunk_store=chunk_store) elif mode in ['w-', 'x']: if contains_array(store, path=path): err_contains_array(path) elif contains_group(store, path=path): err_contains_group(path) else: init_group(store, path=path, chunk_store=chunk_store) # determine read only status read_only = mode == 'r' return Group(store, read_only=read_only, cache_attrs=cache_attrs, synchronizer=synchronizer, path=path, chunk_store=chunk_store)
[ "def", "open_group", "(", "store", "=", "None", ",", "mode", "=", "'a'", ",", "cache_attrs", "=", "True", ",", "synchronizer", "=", "None", ",", "path", "=", "None", ",", "chunk_store", "=", "None", ")", ":", "# handle polymorphic store arg", "store", "=",...
Open a group using file-mode-like semantics. Parameters ---------- store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. mode : {'r', 'r+', 'a', 'w', 'w-'}, optional Persistence mode: 'r' means read only (must exist); 'r+' means read/write (must exist); 'a' means read/write (create if doesn't exist); 'w' means create (overwrite if exists); 'w-' means create (fail if exists). cache_attrs : bool, optional If True (default), user attributes will be cached for attribute read operations. If False, user attributes are reloaded from the store prior to all attribute read operations. synchronizer : object, optional Array synchronizer. path : string, optional Group path within store. chunk_store : MutableMapping or string, optional Store or path to directory in file system or name of zip file. Returns ------- g : zarr.hierarchy.Group Examples -------- >>> import zarr >>> root = zarr.open_group('data/example.zarr', mode='w') >>> foo = root.create_group('foo') >>> bar = root.create_group('bar') >>> root <zarr.hierarchy.Group '/'> >>> root2 = zarr.open_group('data/example.zarr', mode='a') >>> root2 <zarr.hierarchy.Group '/'> >>> root == root2 True
[ "Open", "a", "group", "using", "file", "-", "mode", "-", "like", "semantics", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L1060-L1139
train
215,790
zarr-developers/zarr
zarr/hierarchy.py
Group.name
def name(self): """Group name following h5py convention.""" if self._path: # follow h5py convention: add leading slash name = self._path if name[0] != '/': name = '/' + name return name return '/'
python
def name(self): """Group name following h5py convention.""" if self._path: # follow h5py convention: add leading slash name = self._path if name[0] != '/': name = '/' + name return name return '/'
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "_path", ":", "# follow h5py convention: add leading slash", "name", "=", "self", ".", "_path", "if", "name", "[", "0", "]", "!=", "'/'", ":", "name", "=", "'/'", "+", "name", "return", "name", "...
Group name following h5py convention.
[ "Group", "name", "following", "h5py", "convention", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L136-L144
train
215,791
zarr-developers/zarr
zarr/hierarchy.py
Group.group_keys
def group_keys(self): """Return an iterator over member names for groups only. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) >>> sorted(g1.group_keys()) ['bar', 'foo'] """ for key in sorted(listdir(self._store, self._path)): path = self._key_prefix + key if contains_group(self._store, path): yield key
python
def group_keys(self): """Return an iterator over member names for groups only. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) >>> sorted(g1.group_keys()) ['bar', 'foo'] """ for key in sorted(listdir(self._store, self._path)): path = self._key_prefix + key if contains_group(self._store, path): yield key
[ "def", "group_keys", "(", "self", ")", ":", "for", "key", "in", "sorted", "(", "listdir", "(", "self", ".", "_store", ",", "self", ".", "_path", ")", ")", ":", "path", "=", "self", ".", "_key_prefix", "+", "key", "if", "contains_group", "(", "self", ...
Return an iterator over member names for groups only. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) >>> sorted(g1.group_keys()) ['bar', 'foo']
[ "Return", "an", "iterator", "over", "member", "names", "for", "groups", "only", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L368-L386
train
215,792
zarr-developers/zarr
zarr/hierarchy.py
Group.array_keys
def array_keys(self): """Return an iterator over member names for arrays only. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) >>> sorted(g1.array_keys()) ['baz', 'quux'] """ for key in sorted(listdir(self._store, self._path)): path = self._key_prefix + key if contains_array(self._store, path): yield key
python
def array_keys(self): """Return an iterator over member names for arrays only. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) >>> sorted(g1.array_keys()) ['baz', 'quux'] """ for key in sorted(listdir(self._store, self._path)): path = self._key_prefix + key if contains_array(self._store, path): yield key
[ "def", "array_keys", "(", "self", ")", ":", "for", "key", "in", "sorted", "(", "listdir", "(", "self", ".", "_store", ",", "self", ".", "_path", ")", ")", ":", "path", "=", "self", ".", "_key_prefix", "+", "key", "if", "contains_array", "(", "self", ...
Return an iterator over member names for arrays only. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> d1 = g1.create_dataset('baz', shape=100, chunks=10) >>> d2 = g1.create_dataset('quux', shape=200, chunks=20) >>> sorted(g1.array_keys()) ['baz', 'quux']
[ "Return", "an", "iterator", "over", "member", "names", "for", "arrays", "only", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L413-L431
train
215,793
zarr-developers/zarr
zarr/hierarchy.py
Group.visitvalues
def visitvalues(self, func): """Run ``func`` on each object. Note: If ``func`` returns ``None`` (or doesn't return), iteration continues. However, if ``func`` returns anything else, it ceases and returns that value. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g3.create_group('baz') >>> g5 = g3.create_group('quux') >>> def print_visitor(obj): ... print(obj) >>> g1.visitvalues(print_visitor) <zarr.hierarchy.Group '/bar'> <zarr.hierarchy.Group '/bar/baz'> <zarr.hierarchy.Group '/bar/quux'> <zarr.hierarchy.Group '/foo'> >>> g3.visitvalues(print_visitor) <zarr.hierarchy.Group '/bar/baz'> <zarr.hierarchy.Group '/bar/quux'> """ def _visit(obj): yield obj keys = sorted(getattr(obj, "keys", lambda: [])()) for k in keys: for v in _visit(obj[k]): yield v for each_obj in islice(_visit(self), 1, None): value = func(each_obj) if value is not None: return value
python
def visitvalues(self, func): """Run ``func`` on each object. Note: If ``func`` returns ``None`` (or doesn't return), iteration continues. However, if ``func`` returns anything else, it ceases and returns that value. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g3.create_group('baz') >>> g5 = g3.create_group('quux') >>> def print_visitor(obj): ... print(obj) >>> g1.visitvalues(print_visitor) <zarr.hierarchy.Group '/bar'> <zarr.hierarchy.Group '/bar/baz'> <zarr.hierarchy.Group '/bar/quux'> <zarr.hierarchy.Group '/foo'> >>> g3.visitvalues(print_visitor) <zarr.hierarchy.Group '/bar/baz'> <zarr.hierarchy.Group '/bar/quux'> """ def _visit(obj): yield obj keys = sorted(getattr(obj, "keys", lambda: [])()) for k in keys: for v in _visit(obj[k]): yield v for each_obj in islice(_visit(self), 1, None): value = func(each_obj) if value is not None: return value
[ "def", "visitvalues", "(", "self", ",", "func", ")", ":", "def", "_visit", "(", "obj", ")", ":", "yield", "obj", "keys", "=", "sorted", "(", "getattr", "(", "obj", ",", "\"keys\"", ",", "lambda", ":", "[", "]", ")", "(", ")", ")", "for", "k", "...
Run ``func`` on each object. Note: If ``func`` returns ``None`` (or doesn't return), iteration continues. However, if ``func`` returns anything else, it ceases and returns that value. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g3.create_group('baz') >>> g5 = g3.create_group('quux') >>> def print_visitor(obj): ... print(obj) >>> g1.visitvalues(print_visitor) <zarr.hierarchy.Group '/bar'> <zarr.hierarchy.Group '/bar/baz'> <zarr.hierarchy.Group '/bar/quux'> <zarr.hierarchy.Group '/foo'> >>> g3.visitvalues(print_visitor) <zarr.hierarchy.Group '/bar/baz'> <zarr.hierarchy.Group '/bar/quux'>
[ "Run", "func", "on", "each", "object", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L458-L496
train
215,794
zarr-developers/zarr
zarr/hierarchy.py
Group.visit
def visit(self, func): """Run ``func`` on each object's path. Note: If ``func`` returns ``None`` (or doesn't return), iteration continues. However, if ``func`` returns anything else, it ceases and returns that value. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g3.create_group('baz') >>> g5 = g3.create_group('quux') >>> def print_visitor(name): ... print(name) >>> g1.visit(print_visitor) bar bar/baz bar/quux foo >>> g3.visit(print_visitor) baz quux """ base_len = len(self.name) return self.visitvalues(lambda o: func(o.name[base_len:].lstrip("/")))
python
def visit(self, func): """Run ``func`` on each object's path. Note: If ``func`` returns ``None`` (or doesn't return), iteration continues. However, if ``func`` returns anything else, it ceases and returns that value. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g3.create_group('baz') >>> g5 = g3.create_group('quux') >>> def print_visitor(name): ... print(name) >>> g1.visit(print_visitor) bar bar/baz bar/quux foo >>> g3.visit(print_visitor) baz quux """ base_len = len(self.name) return self.visitvalues(lambda o: func(o.name[base_len:].lstrip("/")))
[ "def", "visit", "(", "self", ",", "func", ")", ":", "base_len", "=", "len", "(", "self", ".", "name", ")", "return", "self", ".", "visitvalues", "(", "lambda", "o", ":", "func", "(", "o", ".", "name", "[", "base_len", ":", "]", ".", "lstrip", "("...
Run ``func`` on each object's path. Note: If ``func`` returns ``None`` (or doesn't return), iteration continues. However, if ``func`` returns anything else, it ceases and returns that value. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g3.create_group('baz') >>> g5 = g3.create_group('quux') >>> def print_visitor(name): ... print(name) >>> g1.visit(print_visitor) bar bar/baz bar/quux foo >>> g3.visit(print_visitor) baz quux
[ "Run", "func", "on", "each", "object", "s", "path", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L498-L527
train
215,795
zarr-developers/zarr
zarr/hierarchy.py
Group.tree
def tree(self, expand=False, level=None): """Provide a ``print``-able display of the hierarchy. Parameters ---------- expand : bool, optional Only relevant for HTML representation. If True, tree will be fully expanded. level : int, optional Maximum depth to descend into hierarchy. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g3.create_group('baz') >>> g5 = g3.create_group('quux') >>> d1 = g5.create_dataset('baz', shape=100, chunks=10) >>> g1.tree() / β”œβ”€β”€ bar β”‚ β”œβ”€β”€ baz β”‚ └── quux β”‚ └── baz (100,) float64 └── foo >>> g1.tree(level=2) / β”œβ”€β”€ bar β”‚ β”œβ”€β”€ baz β”‚ └── quux └── foo >>> g3.tree() bar β”œβ”€β”€ baz └── quux └── baz (100,) float64 Notes ----- Please note that this is an experimental feature. The behaviour of this function is still evolving and the default output and/or parameters may change in future versions. """ return TreeViewer(self, expand=expand, level=level)
python
def tree(self, expand=False, level=None): """Provide a ``print``-able display of the hierarchy. Parameters ---------- expand : bool, optional Only relevant for HTML representation. If True, tree will be fully expanded. level : int, optional Maximum depth to descend into hierarchy. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g3.create_group('baz') >>> g5 = g3.create_group('quux') >>> d1 = g5.create_dataset('baz', shape=100, chunks=10) >>> g1.tree() / β”œβ”€β”€ bar β”‚ β”œβ”€β”€ baz β”‚ └── quux β”‚ └── baz (100,) float64 └── foo >>> g1.tree(level=2) / β”œβ”€β”€ bar β”‚ β”œβ”€β”€ baz β”‚ └── quux └── foo >>> g3.tree() bar β”œβ”€β”€ baz └── quux └── baz (100,) float64 Notes ----- Please note that this is an experimental feature. The behaviour of this function is still evolving and the default output and/or parameters may change in future versions. """ return TreeViewer(self, expand=expand, level=level)
[ "def", "tree", "(", "self", ",", "expand", "=", "False", ",", "level", "=", "None", ")", ":", "return", "TreeViewer", "(", "self", ",", "expand", "=", "expand", ",", "level", "=", "level", ")" ]
Provide a ``print``-able display of the hierarchy. Parameters ---------- expand : bool, optional Only relevant for HTML representation. If True, tree will be fully expanded. level : int, optional Maximum depth to descend into hierarchy. Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g3.create_group('baz') >>> g5 = g3.create_group('quux') >>> d1 = g5.create_dataset('baz', shape=100, chunks=10) >>> g1.tree() / β”œβ”€β”€ bar β”‚ β”œβ”€β”€ baz β”‚ └── quux β”‚ └── baz (100,) float64 └── foo >>> g1.tree(level=2) / β”œβ”€β”€ bar β”‚ β”œβ”€β”€ baz β”‚ └── quux └── foo >>> g3.tree() bar β”œβ”€β”€ baz └── quux └── baz (100,) float64 Notes ----- Please note that this is an experimental feature. The behaviour of this function is still evolving and the default output and/or parameters may change in future versions.
[ "Provide", "a", "print", "-", "able", "display", "of", "the", "hierarchy", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L566-L612
train
215,796
zarr-developers/zarr
zarr/hierarchy.py
Group.create_group
def create_group(self, name, overwrite=False): """Create a sub-group. Parameters ---------- name : string Group name. overwrite : bool, optional If True, overwrite any existing array with the given name. Returns ------- g : zarr.hierarchy.Group Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g1.create_group('baz/quux') """ return self._write_op(self._create_group_nosync, name, overwrite=overwrite)
python
def create_group(self, name, overwrite=False): """Create a sub-group. Parameters ---------- name : string Group name. overwrite : bool, optional If True, overwrite any existing array with the given name. Returns ------- g : zarr.hierarchy.Group Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g1.create_group('baz/quux') """ return self._write_op(self._create_group_nosync, name, overwrite=overwrite)
[ "def", "create_group", "(", "self", ",", "name", ",", "overwrite", "=", "False", ")", ":", "return", "self", ".", "_write_op", "(", "self", ".", "_create_group_nosync", ",", "name", ",", "overwrite", "=", "overwrite", ")" ]
Create a sub-group. Parameters ---------- name : string Group name. overwrite : bool, optional If True, overwrite any existing array with the given name. Returns ------- g : zarr.hierarchy.Group Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.create_group('foo') >>> g3 = g1.create_group('bar') >>> g4 = g1.create_group('baz/quux')
[ "Create", "a", "sub", "-", "group", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L630-L654
train
215,797
zarr-developers/zarr
zarr/hierarchy.py
Group.create_groups
def create_groups(self, *names, **kwargs): """Convenience method to create multiple groups in a single call.""" return tuple(self.create_group(name, **kwargs) for name in names)
python
def create_groups(self, *names, **kwargs): """Convenience method to create multiple groups in a single call.""" return tuple(self.create_group(name, **kwargs) for name in names)
[ "def", "create_groups", "(", "self", ",", "*", "names", ",", "*", "*", "kwargs", ")", ":", "return", "tuple", "(", "self", ".", "create_group", "(", "name", ",", "*", "*", "kwargs", ")", "for", "name", "in", "names", ")" ]
Convenience method to create multiple groups in a single call.
[ "Convenience", "method", "to", "create", "multiple", "groups", "in", "a", "single", "call", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L667-L669
train
215,798
zarr-developers/zarr
zarr/hierarchy.py
Group.require_group
def require_group(self, name, overwrite=False): """Obtain a sub-group, creating one if it doesn't exist. Parameters ---------- name : string Group name. overwrite : bool, optional Overwrite any existing array with given `name` if present. Returns ------- g : zarr.hierarchy.Group Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.require_group('foo') >>> g3 = g1.require_group('foo') >>> g2 == g3 True """ return self._write_op(self._require_group_nosync, name, overwrite=overwrite)
python
def require_group(self, name, overwrite=False): """Obtain a sub-group, creating one if it doesn't exist. Parameters ---------- name : string Group name. overwrite : bool, optional Overwrite any existing array with given `name` if present. Returns ------- g : zarr.hierarchy.Group Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.require_group('foo') >>> g3 = g1.require_group('foo') >>> g2 == g3 True """ return self._write_op(self._require_group_nosync, name, overwrite=overwrite)
[ "def", "require_group", "(", "self", ",", "name", ",", "overwrite", "=", "False", ")", ":", "return", "self", ".", "_write_op", "(", "self", ".", "_require_group_nosync", ",", "name", ",", "overwrite", "=", "overwrite", ")" ]
Obtain a sub-group, creating one if it doesn't exist. Parameters ---------- name : string Group name. overwrite : bool, optional Overwrite any existing array with given `name` if present. Returns ------- g : zarr.hierarchy.Group Examples -------- >>> import zarr >>> g1 = zarr.group() >>> g2 = g1.require_group('foo') >>> g3 = g1.require_group('foo') >>> g2 == g3 True
[ "Obtain", "a", "sub", "-", "group", "creating", "one", "if", "it", "doesn", "t", "exist", "." ]
fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5
https://github.com/zarr-developers/zarr/blob/fb8e6d5ea6bc26e451e5cf0eaaee36977556d5b5/zarr/hierarchy.py#L671-L697
train
215,799