Dataset Viewer
Auto-converted to Parquet Duplicate
id
int64
0
401
prompt
stringlengths
268
2.83M
0
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' Based on the information above, please complete the function in the current file: def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """
1
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_camel_case(input_string: Any) -> bool: """ Checks if a string is formatted as camel case. A string is considered camel case when: - it's composed only by letters ([a-zA-Z]) and optionally numbers ([0-9]) - it contains both lowercase and uppercase letters - it does not start with a number *Examples:* >>> is_camel_case('MyString') # returns true >>> is_camel_case('mystring') # returns false :param input_string: String to test. :type input_string: str :return: True for a camel case string, false otherwise. """ return is_full_string(input_string) and CAMEL_CASE_TEST_RE.match(input_string) is not None def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_snake_case(input_string: Any, separator: str = '_') -> bool: """ Checks if a string is formatted as "snake case". A string is considered snake case when: - it's composed only by lowercase/uppercase letters and digits - it contains at least one underscore (or provided separator) - it does not start with a number *Examples:* >>> is_snake_case('foo_bar_baz') # returns true >>> is_snake_case('foo') # returns false :param input_string: String to test. :type input_string: str :param separator: String to use as separator. :type separator: str :return: True for a snake case string, false otherwise. """ if is_full_string(input_string): re_map = { '_': SNAKE_CASE_TEST_RE, '-': SNAKE_CASE_TEST_DASH_RE } re_template = r'([a-z]+\d*{sign}[a-z\d{sign}]*|{sign}+[a-z\d]+[a-z\d{sign}]*)' r = re_map.get( separator, re.compile(re_template.format(sign=re.escape(separator)), re.IGNORECASE) ) return r.match(input_string) is not None return False def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' #FILE: python-string-utils/string_utils/_regex.py CAMEL_CASE_REPLACE_RE = re.compile(r'([a-z]|[A-Z]+)(?=[A-Z])') #CURRENT FILE: python-string-utils/string_utils/manipulation.py import base64 import random import unicodedata import zlib from typing import Union from uuid import uuid4 from ._regex import * from .errors import InvalidInputError from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string[::-1] def shuffle(input_string: str) -> str: """ Return a new string containing same chars of the given one but in a randomized order. *Example:* >>> shuffle('hello world') # possible output: 'l wodheorll' :param input_string: String to shuffle :type input_string: str :return: Shuffled string """ if not is_string(input_string): raise InvalidInputError(input_string) # turn the string into a list of chars chars = list(input_string) # shuffle the list random.shuffle(chars) # convert the shuffled list back to string return ''.join(chars) def compress(input_string: str, encoding: str = 'utf-8', compression_level: int = 9) -> str: """ Compress the given string by returning a shorter one that can be safely used in any context (like URL) and restored back to its original state using `decompress()`. **Bear in mind:** Besides the provided `compression_level`, the compression result (how much the string is actually compressed by resulting into a shorter string) depends on 2 factors: 1. The amount of data (string size): short strings might not provide a significant compression result\ or even be longer than the given input string (this is due to the fact that some bytes have to be embedded\ into the compressed string in order to be able to restore it later on)\ 2. The content type: random sequences of chars are very unlikely to be successfully compressed, while the best\ compression result is obtained when the string contains several recurring char sequences (like in the example). Behind the scenes this method makes use of the standard Python's zlib and base64 libraries. *Examples:* >>> n = 0 # <- ignore this, it's a fix for Pycharm (not fixable using ignore comments) >>> # "original" will be a string with 169 chars: >>> original = ' '.join(['word n{}'.format(n) for n in range(20)]) >>> # "compressed" will be a string of 88 chars >>> compressed = compress(original) :param input_string: String to compress (must be not empty or a ValueError will be raised). :type input_string: str :param encoding: String encoding (default to "utf-8"). :type encoding: str :param compression_level: A value between 0 (no compression) and 9 (best compression), default to 9. :type compression_level: int :return: Compressed string. """ return __StringCompressor.compress(input_string, encoding, compression_level) def asciify(input_string: str) -> str: """ Force string content to be ascii-only by translating all non-ascii chars into the closest possible representation (eg: ó -> o, Ë -> E, ç -> c...). **Bear in mind**: Some chars may be lost if impossible to translate. *Example:* >>> asciify('èéùúòóäåëýñÅÀÁÇÌÍÑÓË') # returns 'eeuuooaaeynAAACIINOE' :param input_string: String to convert :return: Ascii utf-8 string """ if not is_string(input_string): raise InvalidInputError(input_string) # "NFKD" is the algorithm which is able to successfully translate the most of non-ascii chars normalized = unicodedata.normalize('NFKD', input_string) # encode string forcing ascii and ignore any errors (unrepresentable chars will be stripped out) ascii_bytes = normalized.encode('ascii', 'ignore') # turns encoded bytes into an utf-8 string ascii_string = ascii_bytes.decode('utf-8') return ascii_string def snake_case_to_camel(input_string: str, upper_case_first: bool = True, separator: str = '_') -> str: """ Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) *Example:* >>> snake_case_to_camel('the_snake_is_green') # returns 'TheSnakeIsGreen' :param input_string: String to convert. :type input_string: str :param upper_case_first: True to turn the first letter into uppercase (default). :type upper_case_first: bool :param separator: Sign to use as separator (default to "_"). :type separator: str :return: Converted string """ if not is_string(input_string): raise InvalidInputError(input_string) if not is_snake_case(input_string, separator): return input_string tokens = [s.title() for s in input_string.split(separator) if is_full_string(s)] if not upper_case_first: tokens[0] = tokens[0].lower() out = ''.join(tokens) return out def prettify(input_string: str) -> str: """ Reformat a string by applying the following basic grammar and formatting rules: - String cannot start or end with spaces - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \\*, =) must have one, and only one space before and after themselves - One, and only one space should follow a dot, a comma, an exclamation or a question mark - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \ after quotes (foo" bar"baz -> foo "bar" baz) - Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \ after brackets ("foo(bar )baz" -> "foo (bar) baz") - Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%") - Saxon genitive is correct ("Dave' s dog" -> "Dave's dog") *Examples:* >>> prettify(' unprettified string ,, like this one,will be"prettified" .it\\' s awesome! ') >>> # -> 'Unprettified string, like this one, will be "prettified". It\'s awesome!' :param input_string: String to manipulate :return: Prettified string. """ formatted = __StringFormatter(input_string).format() return formatted def slugify(input_string: str, separator: str = '-') -> str: """ Converts a string into a "slug" using provided separator. The returned string has the following properties: - it has no spaces - all letters are in lower case - all punctuation signs and non alphanumeric chars are removed - words are divided using provided separator - all chars are encoded as ascii (by using `asciify()`) - is safe for URL *Examples:* >>> slugify('Top 10 Reasons To Love Dogs!!!') # returns: 'top-10-reasons-to-love-dogs' >>> slugify('Mönstér Mägnët') # returns 'monster-magnet' :param input_string: String to convert. :type input_string: str :param separator: Sign used to join string tokens (default to "-"). :type separator: str :return: Slug string """ if not is_string(input_string): raise InvalidInputError(input_string) # replace any character that is NOT letter or number with spaces out = NO_LETTERS_OR_NUMBERS_RE.sub(' ', input_string.lower()).strip() # replace spaces with join sign out = SPACES_RE.sub(separator, out) # normalize joins (remove duplicates) out = re.sub(re.escape(separator) + r'+', separator, out) return asciify(out) def booleanize(input_string: str) -> bool: """ Turns a string into a boolean based on its content (CASE INSENSITIVE). A positive boolean (True) is returned if the string value is one of the following: - "true" - "1" - "yes" - "y" Otherwise False is returned. *Examples:* >>> booleanize('true') # returns True >>> booleanize('YES') # returns True >>> booleanize('nope') # returns False :param input_string: String to convert :type input_string: str :return: True if the string contains a boolean-like positive value, false otherwise """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string.lower() in ('true', '1', 'yes', 'y') def decompress(input_string: str, encoding: str = 'utf-8') -> str: """ Restore a previously compressed string (obtained using `compress()`) back to its original state. :param input_string: String to restore. :type input_string: str :param encoding: Original string encoding. :type encoding: str :return: Decompressed string. """ return __StringCompressor.decompress(input_string, encoding) Based on the information above, please complete the function in the current file: def camel_case_to_snake(input_string, separator='_'): """ Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) *Example:* >>> camel_case_to_snake('ThisIsACamelStringTest') # returns 'this_is_a_camel_case_string_test' :param input_string: String to convert. :type input_string: str :param separator: Sign to use as separator. :type separator: str :return: Converted string. """
2
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' def is_snake_case(input_string: Any, separator: str = '_') -> bool: """ Checks if a string is formatted as "snake case". A string is considered snake case when: - it's composed only by lowercase/uppercase letters and digits - it contains at least one underscore (or provided separator) - it does not start with a number *Examples:* >>> is_snake_case('foo_bar_baz') # returns true >>> is_snake_case('foo') # returns false :param input_string: String to test. :type input_string: str :param separator: String to use as separator. :type separator: str :return: True for a snake case string, false otherwise. """ if is_full_string(input_string): re_map = { '_': SNAKE_CASE_TEST_RE, '-': SNAKE_CASE_TEST_DASH_RE } re_template = r'([a-z]+\d*{sign}[a-z\d{sign}]*|{sign}+[a-z\d]+[a-z\d{sign}]*)' r = re_map.get( separator, re.compile(re_template.format(sign=re.escape(separator)), re.IGNORECASE) ) return r.match(input_string) is not None return False def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_camel_case(input_string: Any) -> bool: """ Checks if a string is formatted as camel case. A string is considered camel case when: - it's composed only by letters ([a-zA-Z]) and optionally numbers ([0-9]) - it contains both lowercase and uppercase letters - it does not start with a number *Examples:* >>> is_camel_case('MyString') # returns true >>> is_camel_case('mystring') # returns false :param input_string: String to test. :type input_string: str :return: True for a camel case string, false otherwise. """ return is_full_string(input_string) and CAMEL_CASE_TEST_RE.match(input_string) is not None #CURRENT FILE: python-string-utils/string_utils/manipulation.py import base64 import random import unicodedata import zlib from typing import Union from uuid import uuid4 from ._regex import * from .errors import InvalidInputError from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string[::-1] def shuffle(input_string: str) -> str: """ Return a new string containing same chars of the given one but in a randomized order. *Example:* >>> shuffle('hello world') # possible output: 'l wodheorll' :param input_string: String to shuffle :type input_string: str :return: Shuffled string """ if not is_string(input_string): raise InvalidInputError(input_string) # turn the string into a list of chars chars = list(input_string) # shuffle the list random.shuffle(chars) # convert the shuffled list back to string return ''.join(chars) def compress(input_string: str, encoding: str = 'utf-8', compression_level: int = 9) -> str: """ Compress the given string by returning a shorter one that can be safely used in any context (like URL) and restored back to its original state using `decompress()`. **Bear in mind:** Besides the provided `compression_level`, the compression result (how much the string is actually compressed by resulting into a shorter string) depends on 2 factors: 1. The amount of data (string size): short strings might not provide a significant compression result\ or even be longer than the given input string (this is due to the fact that some bytes have to be embedded\ into the compressed string in order to be able to restore it later on)\ 2. The content type: random sequences of chars are very unlikely to be successfully compressed, while the best\ compression result is obtained when the string contains several recurring char sequences (like in the example). Behind the scenes this method makes use of the standard Python's zlib and base64 libraries. *Examples:* >>> n = 0 # <- ignore this, it's a fix for Pycharm (not fixable using ignore comments) >>> # "original" will be a string with 169 chars: >>> original = ' '.join(['word n{}'.format(n) for n in range(20)]) >>> # "compressed" will be a string of 88 chars >>> compressed = compress(original) :param input_string: String to compress (must be not empty or a ValueError will be raised). :type input_string: str :param encoding: String encoding (default to "utf-8"). :type encoding: str :param compression_level: A value between 0 (no compression) and 9 (best compression), default to 9. :type compression_level: int :return: Compressed string. """ return __StringCompressor.compress(input_string, encoding, compression_level) def asciify(input_string: str) -> str: """ Force string content to be ascii-only by translating all non-ascii chars into the closest possible representation (eg: ó -> o, Ë -> E, ç -> c...). **Bear in mind**: Some chars may be lost if impossible to translate. *Example:* >>> asciify('èéùúòóäåëýñÅÀÁÇÌÍÑÓË') # returns 'eeuuooaaeynAAACIINOE' :param input_string: String to convert :return: Ascii utf-8 string """ if not is_string(input_string): raise InvalidInputError(input_string) # "NFKD" is the algorithm which is able to successfully translate the most of non-ascii chars normalized = unicodedata.normalize('NFKD', input_string) # encode string forcing ascii and ignore any errors (unrepresentable chars will be stripped out) ascii_bytes = normalized.encode('ascii', 'ignore') # turns encoded bytes into an utf-8 string ascii_string = ascii_bytes.decode('utf-8') return ascii_string def prettify(input_string: str) -> str: """ Reformat a string by applying the following basic grammar and formatting rules: - String cannot start or end with spaces - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \\*, =) must have one, and only one space before and after themselves - One, and only one space should follow a dot, a comma, an exclamation or a question mark - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \ after quotes (foo" bar"baz -> foo "bar" baz) - Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \ after brackets ("foo(bar )baz" -> "foo (bar) baz") - Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%") - Saxon genitive is correct ("Dave' s dog" -> "Dave's dog") *Examples:* >>> prettify(' unprettified string ,, like this one,will be"prettified" .it\\' s awesome! ') >>> # -> 'Unprettified string, like this one, will be "prettified". It\'s awesome!' :param input_string: String to manipulate :return: Prettified string. """ formatted = __StringFormatter(input_string).format() return formatted def camel_case_to_snake(input_string, separator='_'): """ Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) *Example:* >>> camel_case_to_snake('ThisIsACamelStringTest') # returns 'this_is_a_camel_case_string_test' :param input_string: String to convert. :type input_string: str :param separator: Sign to use as separator. :type separator: str :return: Converted string. """ if not is_string(input_string): raise InvalidInputError(input_string) if not is_camel_case(input_string): return input_string return CAMEL_CASE_REPLACE_RE.sub(lambda m: m.group(1) + separator, input_string).lower() def slugify(input_string: str, separator: str = '-') -> str: """ Converts a string into a "slug" using provided separator. The returned string has the following properties: - it has no spaces - all letters are in lower case - all punctuation signs and non alphanumeric chars are removed - words are divided using provided separator - all chars are encoded as ascii (by using `asciify()`) - is safe for URL *Examples:* >>> slugify('Top 10 Reasons To Love Dogs!!!') # returns: 'top-10-reasons-to-love-dogs' >>> slugify('Mönstér Mägnët') # returns 'monster-magnet' :param input_string: String to convert. :type input_string: str :param separator: Sign used to join string tokens (default to "-"). :type separator: str :return: Slug string """ if not is_string(input_string): raise InvalidInputError(input_string) # replace any character that is NOT letter or number with spaces out = NO_LETTERS_OR_NUMBERS_RE.sub(' ', input_string.lower()).strip() # replace spaces with join sign out = SPACES_RE.sub(separator, out) # normalize joins (remove duplicates) out = re.sub(re.escape(separator) + r'+', separator, out) return asciify(out) def strip_margin(input_string: str) -> str: """ Removes tab indentation from multi line strings (inspired by analogous Scala function). *Example:* >>> strip_margin(''' >>> line 1 >>> line 2 >>> line 3 >>> ''') >>> # returns: >>> ''' >>> line 1 >>> line 2 >>> line 3 >>> ''' :param input_string: String to format :type input_string: str :return: A string without left margins """ if not is_string(input_string): raise InvalidInputError(input_string) line_separator = '\n' lines = [MARGIN_RE.sub('', line) for line in input_string.split(line_separator)] out = line_separator.join(lines) return out def booleanize(input_string: str) -> bool: """ Turns a string into a boolean based on its content (CASE INSENSITIVE). A positive boolean (True) is returned if the string value is one of the following: - "true" - "1" - "yes" - "y" Otherwise False is returned. *Examples:* >>> booleanize('true') # returns True >>> booleanize('YES') # returns True >>> booleanize('nope') # returns False :param input_string: String to convert :type input_string: str :return: True if the string contains a boolean-like positive value, false otherwise """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string.lower() in ('true', '1', 'yes', 'y') def decompress(input_string: str, encoding: str = 'utf-8') -> str: """ Restore a previously compressed string (obtained using `compress()`) back to its original state. :param input_string: String to restore. :type input_string: str :param encoding: Original string encoding. :type encoding: str :return: Decompressed string. """ return __StringCompressor.decompress(input_string, encoding) def strip_html(input_string: str, keep_tag_content: bool = False) -> str: """ Remove html code contained into the given string. *Examples:* >>> strip_html('test: <a href="foo/bar">click here</a>') # returns 'test: ' >>> strip_html('test: <a href="foo/bar">click here</a>', keep_tag_content=True) # returns 'test: click here' :param input_string: String to manipulate. :type input_string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. """ if not is_string(input_string): raise InvalidInputError(input_string) r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r.sub('', input_string) def roman_encode(input_number: Union[str, int]) -> str: """ Convert the given number/string into a roman number. The passed input must represents a positive integer in the range 1-3999 (inclusive). Why this limit? You may be wondering: 1. zero is forbidden since there is no related representation in roman numbers 2. the upper bound 3999 is due to the limitation in the ascii charset\ (the higher quantity sign displayable in ascii is "M" which is equal to 1000, therefore based on\ roman numbers rules we can use 3 times M to reach 3000 but we can't go any further in thousands without\ special "boxed chars"). *Examples:* >>> roman_encode(37) # returns 'XXXVIII' >>> roman_encode('2020') # returns 'MMXX' :param input_number: An integer or a string to be converted. :type input_number: Union[str, int] :return: Roman number string. """ return __RomanNumbers.encode(input_number) Based on the information above, please complete the function in the current file: def snake_case_to_camel(input_string: str, upper_case_first: bool = True, separator: str = '_') -> str: """ Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) *Example:* >>> snake_case_to_camel('the_snake_is_green') # returns 'TheSnakeIsGreen' :param input_string: String to convert. :type input_string: str :param upper_case_first: True to turn the first letter into uppercase (default). :type upper_case_first: bool :param separator: Sign to use as separator (default to "_"). :type separator: str :return: Converted string """
4
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_snake_case(input_string: Any, separator: str = '_') -> bool: """ Checks if a string is formatted as "snake case". A string is considered snake case when: - it's composed only by lowercase/uppercase letters and digits - it contains at least one underscore (or provided separator) - it does not start with a number *Examples:* >>> is_snake_case('foo_bar_baz') # returns true >>> is_snake_case('foo') # returns false :param input_string: String to test. :type input_string: str :param separator: String to use as separator. :type separator: str :return: True for a snake case string, false otherwise. """ if is_full_string(input_string): re_map = { '_': SNAKE_CASE_TEST_RE, '-': SNAKE_CASE_TEST_DASH_RE } re_template = r'([a-z]+\d*{sign}[a-z\d{sign}]*|{sign}+[a-z\d]+[a-z\d{sign}]*)' r = re_map.get( separator, re.compile(re_template.format(sign=re.escape(separator)), re.IGNORECASE) ) return r.match(input_string) is not None return False def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' #FILE: python-string-utils/string_utils/_regex.py HTML_RE = re.compile( r'((<([a-z]+:)?[a-z]+[^>]*/?>)(.*?(</([a-z]+:)?[a-z]+>))?|<!--.*-->|<!doctype.*>)', re.IGNORECASE | re.MULTILINE | re.DOTALL ) HTML_TAG_ONLY_RE = re.compile( r'(<([a-z]+:)?[a-z]+[^>]*/?>|</([a-z]+:)?[a-z]+>|<!--.*-->|<!doctype.*>)', re.IGNORECASE | re.MULTILINE | re.DOTALL ) #CURRENT FILE: python-string-utils/string_utils/manipulation.py import base64 import random import unicodedata import zlib from typing import Union from uuid import uuid4 from ._regex import * from .errors import InvalidInputError from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string[::-1] def shuffle(input_string: str) -> str: """ Return a new string containing same chars of the given one but in a randomized order. *Example:* >>> shuffle('hello world') # possible output: 'l wodheorll' :param input_string: String to shuffle :type input_string: str :return: Shuffled string """ if not is_string(input_string): raise InvalidInputError(input_string) # turn the string into a list of chars chars = list(input_string) # shuffle the list random.shuffle(chars) # convert the shuffled list back to string return ''.join(chars) def roman_decode(input_string: str) -> int: """ Decode a roman number string into an integer if the provided string is valid. *Example:* >>> roman_decode('VII') # returns 7 :param input_string: (Assumed) Roman number :type input_string: str :return: Integer value """ return __RomanNumbers.decode(input_string) def compress(input_string: str, encoding: str = 'utf-8', compression_level: int = 9) -> str: """ Compress the given string by returning a shorter one that can be safely used in any context (like URL) and restored back to its original state using `decompress()`. **Bear in mind:** Besides the provided `compression_level`, the compression result (how much the string is actually compressed by resulting into a shorter string) depends on 2 factors: 1. The amount of data (string size): short strings might not provide a significant compression result\ or even be longer than the given input string (this is due to the fact that some bytes have to be embedded\ into the compressed string in order to be able to restore it later on)\ 2. The content type: random sequences of chars are very unlikely to be successfully compressed, while the best\ compression result is obtained when the string contains several recurring char sequences (like in the example). Behind the scenes this method makes use of the standard Python's zlib and base64 libraries. *Examples:* >>> n = 0 # <- ignore this, it's a fix for Pycharm (not fixable using ignore comments) >>> # "original" will be a string with 169 chars: >>> original = ' '.join(['word n{}'.format(n) for n in range(20)]) >>> # "compressed" will be a string of 88 chars >>> compressed = compress(original) :param input_string: String to compress (must be not empty or a ValueError will be raised). :type input_string: str :param encoding: String encoding (default to "utf-8"). :type encoding: str :param compression_level: A value between 0 (no compression) and 9 (best compression), default to 9. :type compression_level: int :return: Compressed string. """ return __StringCompressor.compress(input_string, encoding, compression_level) def asciify(input_string: str) -> str: """ Force string content to be ascii-only by translating all non-ascii chars into the closest possible representation (eg: ó -> o, Ë -> E, ç -> c...). **Bear in mind**: Some chars may be lost if impossible to translate. *Example:* >>> asciify('èéùúòóäåëýñÅÀÁÇÌÍÑÓË') # returns 'eeuuooaaeynAAACIINOE' :param input_string: String to convert :return: Ascii utf-8 string """ if not is_string(input_string): raise InvalidInputError(input_string) # "NFKD" is the algorithm which is able to successfully translate the most of non-ascii chars normalized = unicodedata.normalize('NFKD', input_string) # encode string forcing ascii and ignore any errors (unrepresentable chars will be stripped out) ascii_bytes = normalized.encode('ascii', 'ignore') # turns encoded bytes into an utf-8 string ascii_string = ascii_bytes.decode('utf-8') return ascii_string def prettify(input_string: str) -> str: """ Reformat a string by applying the following basic grammar and formatting rules: - String cannot start or end with spaces - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \\*, =) must have one, and only one space before and after themselves - One, and only one space should follow a dot, a comma, an exclamation or a question mark - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \ after quotes (foo" bar"baz -> foo "bar" baz) - Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \ after brackets ("foo(bar )baz" -> "foo (bar) baz") - Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%") - Saxon genitive is correct ("Dave' s dog" -> "Dave's dog") *Examples:* >>> prettify(' unprettified string ,, like this one,will be"prettified" .it\\' s awesome! ') >>> # -> 'Unprettified string, like this one, will be "prettified". It\'s awesome!' :param input_string: String to manipulate :return: Prettified string. """ formatted = __StringFormatter(input_string).format() return formatted def slugify(input_string: str, separator: str = '-') -> str: """ Converts a string into a "slug" using provided separator. The returned string has the following properties: - it has no spaces - all letters are in lower case - all punctuation signs and non alphanumeric chars are removed - words are divided using provided separator - all chars are encoded as ascii (by using `asciify()`) - is safe for URL *Examples:* >>> slugify('Top 10 Reasons To Love Dogs!!!') # returns: 'top-10-reasons-to-love-dogs' >>> slugify('Mönstér Mägnët') # returns 'monster-magnet' :param input_string: String to convert. :type input_string: str :param separator: Sign used to join string tokens (default to "-"). :type separator: str :return: Slug string """ if not is_string(input_string): raise InvalidInputError(input_string) # replace any character that is NOT letter or number with spaces out = NO_LETTERS_OR_NUMBERS_RE.sub(' ', input_string.lower()).strip() # replace spaces with join sign out = SPACES_RE.sub(separator, out) # normalize joins (remove duplicates) out = re.sub(re.escape(separator) + r'+', separator, out) return asciify(out) def strip_margin(input_string: str) -> str: """ Removes tab indentation from multi line strings (inspired by analogous Scala function). *Example:* >>> strip_margin(''' >>> line 1 >>> line 2 >>> line 3 >>> ''') >>> # returns: >>> ''' >>> line 1 >>> line 2 >>> line 3 >>> ''' :param input_string: String to format :type input_string: str :return: A string without left margins """ if not is_string(input_string): raise InvalidInputError(input_string) line_separator = '\n' lines = [MARGIN_RE.sub('', line) for line in input_string.split(line_separator)] out = line_separator.join(lines) return out def booleanize(input_string: str) -> bool: """ Turns a string into a boolean based on its content (CASE INSENSITIVE). A positive boolean (True) is returned if the string value is one of the following: - "true" - "1" - "yes" - "y" Otherwise False is returned. *Examples:* >>> booleanize('true') # returns True >>> booleanize('YES') # returns True >>> booleanize('nope') # returns False :param input_string: String to convert :type input_string: str :return: True if the string contains a boolean-like positive value, false otherwise """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string.lower() in ('true', '1', 'yes', 'y') def decompress(input_string: str, encoding: str = 'utf-8') -> str: """ Restore a previously compressed string (obtained using `compress()`) back to its original state. :param input_string: String to restore. :type input_string: str :param encoding: Original string encoding. :type encoding: str :return: Decompressed string. """ return __StringCompressor.decompress(input_string, encoding) def roman_encode(input_number: Union[str, int]) -> str: """ Convert the given number/string into a roman number. The passed input must represents a positive integer in the range 1-3999 (inclusive). Why this limit? You may be wondering: 1. zero is forbidden since there is no related representation in roman numbers 2. the upper bound 3999 is due to the limitation in the ascii charset\ (the higher quantity sign displayable in ascii is "M" which is equal to 1000, therefore based on\ roman numbers rules we can use 3 times M to reach 3000 but we can't go any further in thousands without\ special "boxed chars"). *Examples:* >>> roman_encode(37) # returns 'XXXVIII' >>> roman_encode('2020') # returns 'MMXX' :param input_number: An integer or a string to be converted. :type input_number: Union[str, int] :return: Roman number string. """ return __RomanNumbers.encode(input_number) Based on the information above, please complete the function in the current file: def strip_html(input_string: str, keep_tag_content: bool = False) -> str: """ Remove html code contained into the given string. *Examples:* >>> strip_html('test: <a href="foo/bar">click here</a>') # returns 'test: ' >>> strip_html('test: <a href="foo/bar">click here</a>', keep_tag_content=True) # returns 'test: click here' :param input_string: String to manipulate. :type input_string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. """
5
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_snake_case(input_string: Any, separator: str = '_') -> bool: """ Checks if a string is formatted as "snake case". A string is considered snake case when: - it's composed only by lowercase/uppercase letters and digits - it contains at least one underscore (or provided separator) - it does not start with a number *Examples:* >>> is_snake_case('foo_bar_baz') # returns true >>> is_snake_case('foo') # returns false :param input_string: String to test. :type input_string: str :param separator: String to use as separator. :type separator: str :return: True for a snake case string, false otherwise. """ if is_full_string(input_string): re_map = { '_': SNAKE_CASE_TEST_RE, '-': SNAKE_CASE_TEST_DASH_RE } re_template = r'([a-z]+\d*{sign}[a-z\d{sign}]*|{sign}+[a-z\d]+[a-z\d{sign}]*)' r = re_map.get( separator, re.compile(re_template.format(sign=re.escape(separator)), re.IGNORECASE) ) return r.match(input_string) is not None return False def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_camel_case(input_string: Any) -> bool: """ Checks if a string is formatted as camel case. A string is considered camel case when: - it's composed only by letters ([a-zA-Z]) and optionally numbers ([0-9]) - it contains both lowercase and uppercase letters - it does not start with a number *Examples:* >>> is_camel_case('MyString') # returns true >>> is_camel_case('mystring') # returns false :param input_string: String to test. :type input_string: str :return: True for a camel case string, false otherwise. """ return is_full_string(input_string) and CAMEL_CASE_TEST_RE.match(input_string) is not None def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' #CURRENT FILE: python-string-utils/string_utils/manipulation.py import base64 import random import unicodedata import zlib from typing import Union from uuid import uuid4 from ._regex import * from .errors import InvalidInputError from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string class __StringFormatter: def __init__(self, input_string): if not is_string(input_string): raise InvalidInputError(input_string) self.input_string = input_string def __uppercase_first_char(self, regex_match): return regex_match.group(0).upper() def __remove_duplicates(self, regex_match): return regex_match.group(1)[0] def __uppercase_first_letter_after_sign(self, regex_match): match = regex_match.group(1) return match[:-1] + match[2].upper() def __ensure_right_space_only(self, regex_match): return regex_match.group(1).strip() + ' ' def __ensure_left_space_only(self, regex_match): return ' ' + regex_match.group(1).strip() def __ensure_spaces_around(self, regex_match): return ' ' + regex_match.group(1).strip() + ' ' def __remove_internal_spaces(self, regex_match): return regex_match.group(1).strip() def __fix_saxon_genitive(self, regex_match): return regex_match.group(1).replace(' ', '') + ' ' # generates a placeholder to inject temporary into the string, it will be replaced with the original # value at the end of the process @staticmethod def __placeholder_key(): return '$' + uuid4().hex + '$' def format(self) -> str: # map of temporary placeholders placeholders = {} out = self.input_string # looks for url or email and updates placeholders map with found values placeholders.update({self.__placeholder_key(): m[0] for m in URLS_RE.findall(out)}) placeholders.update({self.__placeholder_key(): m for m in EMAILS_RE.findall(out)}) # replace original value with the placeholder key for p in placeholders: out = out.replace(placeholders[p], p, 1) out = PRETTIFY_RE['UPPERCASE_FIRST_LETTER'].sub(self.__uppercase_first_char, out) out = PRETTIFY_RE['DUPLICATES'].sub(self.__remove_duplicates, out) out = PRETTIFY_RE['RIGHT_SPACE'].sub(self.__ensure_right_space_only, out) out = PRETTIFY_RE['LEFT_SPACE'].sub(self.__ensure_left_space_only, out) out = PRETTIFY_RE['SPACES_AROUND'].sub(self.__ensure_spaces_around, out) out = PRETTIFY_RE['SPACES_INSIDE'].sub(self.__remove_internal_spaces, out) out = PRETTIFY_RE['UPPERCASE_AFTER_SIGN'].sub(self.__uppercase_first_letter_after_sign, out) out = PRETTIFY_RE['SAXON_GENITIVE'].sub(self.__fix_saxon_genitive, out) out = out.strip() # restore placeholder keys with their associated original value for p in placeholders: out = out.replace(p, placeholders[p], 1) return out def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string[::-1] def roman_decode(input_string: str) -> int: """ Decode a roman number string into an integer if the provided string is valid. *Example:* >>> roman_decode('VII') # returns 7 :param input_string: (Assumed) Roman number :type input_string: str :return: Integer value """ return __RomanNumbers.decode(input_string) def compress(input_string: str, encoding: str = 'utf-8', compression_level: int = 9) -> str: """ Compress the given string by returning a shorter one that can be safely used in any context (like URL) and restored back to its original state using `decompress()`. **Bear in mind:** Besides the provided `compression_level`, the compression result (how much the string is actually compressed by resulting into a shorter string) depends on 2 factors: 1. The amount of data (string size): short strings might not provide a significant compression result\ or even be longer than the given input string (this is due to the fact that some bytes have to be embedded\ into the compressed string in order to be able to restore it later on)\ 2. The content type: random sequences of chars are very unlikely to be successfully compressed, while the best\ compression result is obtained when the string contains several recurring char sequences (like in the example). Behind the scenes this method makes use of the standard Python's zlib and base64 libraries. *Examples:* >>> n = 0 # <- ignore this, it's a fix for Pycharm (not fixable using ignore comments) >>> # "original" will be a string with 169 chars: >>> original = ' '.join(['word n{}'.format(n) for n in range(20)]) >>> # "compressed" will be a string of 88 chars >>> compressed = compress(original) :param input_string: String to compress (must be not empty or a ValueError will be raised). :type input_string: str :param encoding: String encoding (default to "utf-8"). :type encoding: str :param compression_level: A value between 0 (no compression) and 9 (best compression), default to 9. :type compression_level: int :return: Compressed string. """ return __StringCompressor.compress(input_string, encoding, compression_level) def strip_html(input_string: str, keep_tag_content: bool = False) -> str: """ Remove html code contained into the given string. *Examples:* >>> strip_html('test: <a href="foo/bar">click here</a>') # returns 'test: ' >>> strip_html('test: <a href="foo/bar">click here</a>', keep_tag_content=True) # returns 'test: click here' :param input_string: String to manipulate. :type input_string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. """ if not is_string(input_string): raise InvalidInputError(input_string) r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r.sub('', input_string) def asciify(input_string: str) -> str: """ Force string content to be ascii-only by translating all non-ascii chars into the closest possible representation (eg: ó -> o, Ë -> E, ç -> c...). **Bear in mind**: Some chars may be lost if impossible to translate. *Example:* >>> asciify('èéùúòóäåëýñÅÀÁÇÌÍÑÓË') # returns 'eeuuooaaeynAAACIINOE' :param input_string: String to convert :return: Ascii utf-8 string """ if not is_string(input_string): raise InvalidInputError(input_string) # "NFKD" is the algorithm which is able to successfully translate the most of non-ascii chars normalized = unicodedata.normalize('NFKD', input_string) # encode string forcing ascii and ignore any errors (unrepresentable chars will be stripped out) ascii_bytes = normalized.encode('ascii', 'ignore') # turns encoded bytes into an utf-8 string ascii_string = ascii_bytes.decode('utf-8') return ascii_string def snake_case_to_camel(input_string: str, upper_case_first: bool = True, separator: str = '_') -> str: """ Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) *Example:* >>> snake_case_to_camel('the_snake_is_green') # returns 'TheSnakeIsGreen' :param input_string: String to convert. :type input_string: str :param upper_case_first: True to turn the first letter into uppercase (default). :type upper_case_first: bool :param separator: Sign to use as separator (default to "_"). :type separator: str :return: Converted string """ if not is_string(input_string): raise InvalidInputError(input_string) if not is_snake_case(input_string, separator): return input_string tokens = [s.title() for s in input_string.split(separator) if is_full_string(s)] if not upper_case_first: tokens[0] = tokens[0].lower() out = ''.join(tokens) return out def camel_case_to_snake(input_string, separator='_'): """ Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) *Example:* >>> camel_case_to_snake('ThisIsACamelStringTest') # returns 'this_is_a_camel_case_string_test' :param input_string: String to convert. :type input_string: str :param separator: Sign to use as separator. :type separator: str :return: Converted string. """ if not is_string(input_string): raise InvalidInputError(input_string) if not is_camel_case(input_string): return input_string return CAMEL_CASE_REPLACE_RE.sub(lambda m: m.group(1) + separator, input_string).lower() def slugify(input_string: str, separator: str = '-') -> str: """ Converts a string into a "slug" using provided separator. The returned string has the following properties: - it has no spaces - all letters are in lower case - all punctuation signs and non alphanumeric chars are removed - words are divided using provided separator - all chars are encoded as ascii (by using `asciify()`) - is safe for URL *Examples:* >>> slugify('Top 10 Reasons To Love Dogs!!!') # returns: 'top-10-reasons-to-love-dogs' >>> slugify('Mönstér Mägnët') # returns 'monster-magnet' :param input_string: String to convert. :type input_string: str :param separator: Sign used to join string tokens (default to "-"). :type separator: str :return: Slug string """ if not is_string(input_string): raise InvalidInputError(input_string) # replace any character that is NOT letter or number with spaces out = NO_LETTERS_OR_NUMBERS_RE.sub(' ', input_string.lower()).strip() # replace spaces with join sign out = SPACES_RE.sub(separator, out) # normalize joins (remove duplicates) out = re.sub(re.escape(separator) + r'+', separator, out) return asciify(out) def strip_margin(input_string: str) -> str: """ Removes tab indentation from multi line strings (inspired by analogous Scala function). *Example:* >>> strip_margin(''' >>> line 1 >>> line 2 >>> line 3 >>> ''') >>> # returns: >>> ''' >>> line 1 >>> line 2 >>> line 3 >>> ''' :param input_string: String to format :type input_string: str :return: A string without left margins """ if not is_string(input_string): raise InvalidInputError(input_string) line_separator = '\n' lines = [MARGIN_RE.sub('', line) for line in input_string.split(line_separator)] out = line_separator.join(lines) return out def booleanize(input_string: str) -> bool: """ Turns a string into a boolean based on its content (CASE INSENSITIVE). A positive boolean (True) is returned if the string value is one of the following: - "true" - "1" - "yes" - "y" Otherwise False is returned. *Examples:* >>> booleanize('true') # returns True >>> booleanize('YES') # returns True >>> booleanize('nope') # returns False :param input_string: String to convert :type input_string: str :return: True if the string contains a boolean-like positive value, false otherwise """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string.lower() in ('true', '1', 'yes', 'y') Based on the information above, please complete the function in the current file: def prettify(input_string: str) -> str: """ Reformat a string by applying the following basic grammar and formatting rules: - String cannot start or end with spaces - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \\*, =) must have one, and only one space before and after themselves - One, and only one space should follow a dot, a comma, an exclamation or a question mark - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \ after quotes (foo" bar"baz -> foo "bar" baz) - Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \ after brackets ("foo(bar )baz" -> "foo (bar) baz") - Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%") - Saxon genitive is correct ("Dave' s dog" -> "Dave's dog") *Examples:* >>> prettify(' unprettified string ,, like this one,will be"prettified" .it\\' s awesome! ') >>> # -> 'Unprettified string, like this one, will be "prettified". It\'s awesome!' :param input_string: String to manipulate :return: Prettified string. """
6
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_camel_case(input_string: Any) -> bool: """ Checks if a string is formatted as camel case. A string is considered camel case when: - it's composed only by letters ([a-zA-Z]) and optionally numbers ([0-9]) - it contains both lowercase and uppercase letters - it does not start with a number *Examples:* >>> is_camel_case('MyString') # returns true >>> is_camel_case('mystring') # returns false :param input_string: String to test. :type input_string: str :return: True for a camel case string, false otherwise. """ return is_full_string(input_string) and CAMEL_CASE_TEST_RE.match(input_string) is not None def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' #CURRENT FILE: python-string-utils/string_utils/manipulation.py import base64 import random import unicodedata import zlib from typing import Union from uuid import uuid4 from ._regex import * from .errors import InvalidInputError from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string[::-1] def compress(input_string: str, encoding: str = 'utf-8', compression_level: int = 9) -> str: """ Compress the given string by returning a shorter one that can be safely used in any context (like URL) and restored back to its original state using `decompress()`. **Bear in mind:** Besides the provided `compression_level`, the compression result (how much the string is actually compressed by resulting into a shorter string) depends on 2 factors: 1. The amount of data (string size): short strings might not provide a significant compression result\ or even be longer than the given input string (this is due to the fact that some bytes have to be embedded\ into the compressed string in order to be able to restore it later on)\ 2. The content type: random sequences of chars are very unlikely to be successfully compressed, while the best\ compression result is obtained when the string contains several recurring char sequences (like in the example). Behind the scenes this method makes use of the standard Python's zlib and base64 libraries. *Examples:* >>> n = 0 # <- ignore this, it's a fix for Pycharm (not fixable using ignore comments) >>> # "original" will be a string with 169 chars: >>> original = ' '.join(['word n{}'.format(n) for n in range(20)]) >>> # "compressed" will be a string of 88 chars >>> compressed = compress(original) :param input_string: String to compress (must be not empty or a ValueError will be raised). :type input_string: str :param encoding: String encoding (default to "utf-8"). :type encoding: str :param compression_level: A value between 0 (no compression) and 9 (best compression), default to 9. :type compression_level: int :return: Compressed string. """ return __StringCompressor.compress(input_string, encoding, compression_level) def strip_html(input_string: str, keep_tag_content: bool = False) -> str: """ Remove html code contained into the given string. *Examples:* >>> strip_html('test: <a href="foo/bar">click here</a>') # returns 'test: ' >>> strip_html('test: <a href="foo/bar">click here</a>', keep_tag_content=True) # returns 'test: click here' :param input_string: String to manipulate. :type input_string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. """ if not is_string(input_string): raise InvalidInputError(input_string) r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r.sub('', input_string) def prettify(input_string: str) -> str: """ Reformat a string by applying the following basic grammar and formatting rules: - String cannot start or end with spaces - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \\*, =) must have one, and only one space before and after themselves - One, and only one space should follow a dot, a comma, an exclamation or a question mark - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \ after quotes (foo" bar"baz -> foo "bar" baz) - Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \ after brackets ("foo(bar )baz" -> "foo (bar) baz") - Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%") - Saxon genitive is correct ("Dave' s dog" -> "Dave's dog") *Examples:* >>> prettify(' unprettified string ,, like this one,will be"prettified" .it\\' s awesome! ') >>> # -> 'Unprettified string, like this one, will be "prettified". It\'s awesome!' :param input_string: String to manipulate :return: Prettified string. """ formatted = __StringFormatter(input_string).format() return formatted def booleanize(input_string: str) -> bool: """ Turns a string into a boolean based on its content (CASE INSENSITIVE). A positive boolean (True) is returned if the string value is one of the following: - "true" - "1" - "yes" - "y" Otherwise False is returned. *Examples:* >>> booleanize('true') # returns True >>> booleanize('YES') # returns True >>> booleanize('nope') # returns False :param input_string: String to convert :type input_string: str :return: True if the string contains a boolean-like positive value, false otherwise """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string.lower() in ('true', '1', 'yes', 'y') Based on the information above, please complete the function in the current file: def asciify(input_string: str) -> str: """ Force string content to be ascii-only by translating all non-ascii chars into the closest possible representation (eg: ó -> o, Ë -> E, ç -> c...). **Bear in mind**: Some chars may be lost if impossible to translate. *Example:* >>> asciify('èéùúòóäåëýñÅÀÁÇÌÍÑÓË') # returns 'eeuuooaaeynAAACIINOE' :param input_string: String to convert :return: Ascii utf-8 string """
7
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_snake_case(input_string: Any, separator: str = '_') -> bool: """ Checks if a string is formatted as "snake case". A string is considered snake case when: - it's composed only by lowercase/uppercase letters and digits - it contains at least one underscore (or provided separator) - it does not start with a number *Examples:* >>> is_snake_case('foo_bar_baz') # returns true >>> is_snake_case('foo') # returns false :param input_string: String to test. :type input_string: str :param separator: String to use as separator. :type separator: str :return: True for a snake case string, false otherwise. """ if is_full_string(input_string): re_map = { '_': SNAKE_CASE_TEST_RE, '-': SNAKE_CASE_TEST_DASH_RE } re_template = r'([a-z]+\d*{sign}[a-z\d{sign}]*|{sign}+[a-z\d]+[a-z\d{sign}]*)' r = re_map.get( separator, re.compile(re_template.format(sign=re.escape(separator)), re.IGNORECASE) ) return r.match(input_string) is not None return False def is_camel_case(input_string: Any) -> bool: """ Checks if a string is formatted as camel case. A string is considered camel case when: - it's composed only by letters ([a-zA-Z]) and optionally numbers ([0-9]) - it contains both lowercase and uppercase letters - it does not start with a number *Examples:* >>> is_camel_case('MyString') # returns true >>> is_camel_case('mystring') # returns false :param input_string: String to test. :type input_string: str :return: True for a camel case string, false otherwise. """ return is_full_string(input_string) and CAMEL_CASE_TEST_RE.match(input_string) is not None def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' #FILE: python-string-utils/string_utils/_regex.py NO_LETTERS_OR_NUMBERS_RE = re.compile(r'[^\w\d]+|_+', re.IGNORECASE | re.UNICODE) SPACES_RE = re.compile(r'\s') #CURRENT FILE: python-string-utils/string_utils/manipulation.py import base64 import random import unicodedata import zlib from typing import Union from uuid import uuid4 from ._regex import * from .errors import InvalidInputError from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string class __StringFormatter: def __init__(self, input_string): if not is_string(input_string): raise InvalidInputError(input_string) self.input_string = input_string def __uppercase_first_char(self, regex_match): return regex_match.group(0).upper() def __remove_duplicates(self, regex_match): return regex_match.group(1)[0] def __uppercase_first_letter_after_sign(self, regex_match): match = regex_match.group(1) return match[:-1] + match[2].upper() def __ensure_right_space_only(self, regex_match): return regex_match.group(1).strip() + ' ' def __ensure_left_space_only(self, regex_match): return ' ' + regex_match.group(1).strip() def __ensure_spaces_around(self, regex_match): return ' ' + regex_match.group(1).strip() + ' ' def __remove_internal_spaces(self, regex_match): return regex_match.group(1).strip() def __fix_saxon_genitive(self, regex_match): return regex_match.group(1).replace(' ', '') + ' ' # generates a placeholder to inject temporary into the string, it will be replaced with the original # value at the end of the process @staticmethod def __placeholder_key(): return '$' + uuid4().hex + '$' def format(self) -> str: # map of temporary placeholders placeholders = {} out = self.input_string # looks for url or email and updates placeholders map with found values placeholders.update({self.__placeholder_key(): m[0] for m in URLS_RE.findall(out)}) placeholders.update({self.__placeholder_key(): m for m in EMAILS_RE.findall(out)}) # replace original value with the placeholder key for p in placeholders: out = out.replace(placeholders[p], p, 1) out = PRETTIFY_RE['UPPERCASE_FIRST_LETTER'].sub(self.__uppercase_first_char, out) out = PRETTIFY_RE['DUPLICATES'].sub(self.__remove_duplicates, out) out = PRETTIFY_RE['RIGHT_SPACE'].sub(self.__ensure_right_space_only, out) out = PRETTIFY_RE['LEFT_SPACE'].sub(self.__ensure_left_space_only, out) out = PRETTIFY_RE['SPACES_AROUND'].sub(self.__ensure_spaces_around, out) out = PRETTIFY_RE['SPACES_INSIDE'].sub(self.__remove_internal_spaces, out) out = PRETTIFY_RE['UPPERCASE_AFTER_SIGN'].sub(self.__uppercase_first_letter_after_sign, out) out = PRETTIFY_RE['SAXON_GENITIVE'].sub(self.__fix_saxon_genitive, out) out = out.strip() # restore placeholder keys with their associated original value for p in placeholders: out = out.replace(p, placeholders[p], 1) return out def asciify(input_string: str) -> str: """ Force string content to be ascii-only by translating all non-ascii chars into the closest possible representation (eg: ó -> o, Ë -> E, ç -> c...). **Bear in mind**: Some chars may be lost if impossible to translate. *Example:* >>> asciify('èéùúòóäåëýñÅÀÁÇÌÍÑÓË') # returns 'eeuuooaaeynAAACIINOE' :param input_string: String to convert :return: Ascii utf-8 string """ if not is_string(input_string): raise InvalidInputError(input_string) # "NFKD" is the algorithm which is able to successfully translate the most of non-ascii chars normalized = unicodedata.normalize('NFKD', input_string) # encode string forcing ascii and ignore any errors (unrepresentable chars will be stripped out) ascii_bytes = normalized.encode('ascii', 'ignore') # turns encoded bytes into an utf-8 string ascii_string = ascii_bytes.decode('utf-8') return ascii_string def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string[::-1] def shuffle(input_string: str) -> str: """ Return a new string containing same chars of the given one but in a randomized order. *Example:* >>> shuffle('hello world') # possible output: 'l wodheorll' :param input_string: String to shuffle :type input_string: str :return: Shuffled string """ if not is_string(input_string): raise InvalidInputError(input_string) # turn the string into a list of chars chars = list(input_string) # shuffle the list random.shuffle(chars) # convert the shuffled list back to string return ''.join(chars) def compress(input_string: str, encoding: str = 'utf-8', compression_level: int = 9) -> str: """ Compress the given string by returning a shorter one that can be safely used in any context (like URL) and restored back to its original state using `decompress()`. **Bear in mind:** Besides the provided `compression_level`, the compression result (how much the string is actually compressed by resulting into a shorter string) depends on 2 factors: 1. The amount of data (string size): short strings might not provide a significant compression result\ or even be longer than the given input string (this is due to the fact that some bytes have to be embedded\ into the compressed string in order to be able to restore it later on)\ 2. The content type: random sequences of chars are very unlikely to be successfully compressed, while the best\ compression result is obtained when the string contains several recurring char sequences (like in the example). Behind the scenes this method makes use of the standard Python's zlib and base64 libraries. *Examples:* >>> n = 0 # <- ignore this, it's a fix for Pycharm (not fixable using ignore comments) >>> # "original" will be a string with 169 chars: >>> original = ' '.join(['word n{}'.format(n) for n in range(20)]) >>> # "compressed" will be a string of 88 chars >>> compressed = compress(original) :param input_string: String to compress (must be not empty or a ValueError will be raised). :type input_string: str :param encoding: String encoding (default to "utf-8"). :type encoding: str :param compression_level: A value between 0 (no compression) and 9 (best compression), default to 9. :type compression_level: int :return: Compressed string. """ return __StringCompressor.compress(input_string, encoding, compression_level) def strip_html(input_string: str, keep_tag_content: bool = False) -> str: """ Remove html code contained into the given string. *Examples:* >>> strip_html('test: <a href="foo/bar">click here</a>') # returns 'test: ' >>> strip_html('test: <a href="foo/bar">click here</a>', keep_tag_content=True) # returns 'test: click here' :param input_string: String to manipulate. :type input_string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. """ if not is_string(input_string): raise InvalidInputError(input_string) r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r.sub('', input_string) def snake_case_to_camel(input_string: str, upper_case_first: bool = True, separator: str = '_') -> str: """ Convert a snake case string into a camel case one. (The original string is returned if is not a valid snake case string) *Example:* >>> snake_case_to_camel('the_snake_is_green') # returns 'TheSnakeIsGreen' :param input_string: String to convert. :type input_string: str :param upper_case_first: True to turn the first letter into uppercase (default). :type upper_case_first: bool :param separator: Sign to use as separator (default to "_"). :type separator: str :return: Converted string """ if not is_string(input_string): raise InvalidInputError(input_string) if not is_snake_case(input_string, separator): return input_string tokens = [s.title() for s in input_string.split(separator) if is_full_string(s)] if not upper_case_first: tokens[0] = tokens[0].lower() out = ''.join(tokens) return out def prettify(input_string: str) -> str: """ Reformat a string by applying the following basic grammar and formatting rules: - String cannot start or end with spaces - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \\*, =) must have one, and only one space before and after themselves - One, and only one space should follow a dot, a comma, an exclamation or a question mark - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \ after quotes (foo" bar"baz -> foo "bar" baz) - Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \ after brackets ("foo(bar )baz" -> "foo (bar) baz") - Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%") - Saxon genitive is correct ("Dave' s dog" -> "Dave's dog") *Examples:* >>> prettify(' unprettified string ,, like this one,will be"prettified" .it\\' s awesome! ') >>> # -> 'Unprettified string, like this one, will be "prettified". It\'s awesome!' :param input_string: String to manipulate :return: Prettified string. """ formatted = __StringFormatter(input_string).format() return formatted def camel_case_to_snake(input_string, separator='_'): """ Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) *Example:* >>> camel_case_to_snake('ThisIsACamelStringTest') # returns 'this_is_a_camel_case_string_test' :param input_string: String to convert. :type input_string: str :param separator: Sign to use as separator. :type separator: str :return: Converted string. """ if not is_string(input_string): raise InvalidInputError(input_string) if not is_camel_case(input_string): return input_string return CAMEL_CASE_REPLACE_RE.sub(lambda m: m.group(1) + separator, input_string).lower() def strip_margin(input_string: str) -> str: """ Removes tab indentation from multi line strings (inspired by analogous Scala function). *Example:* >>> strip_margin(''' >>> line 1 >>> line 2 >>> line 3 >>> ''') >>> # returns: >>> ''' >>> line 1 >>> line 2 >>> line 3 >>> ''' :param input_string: String to format :type input_string: str :return: A string without left margins """ if not is_string(input_string): raise InvalidInputError(input_string) line_separator = '\n' lines = [MARGIN_RE.sub('', line) for line in input_string.split(line_separator)] out = line_separator.join(lines) return out def booleanize(input_string: str) -> bool: """ Turns a string into a boolean based on its content (CASE INSENSITIVE). A positive boolean (True) is returned if the string value is one of the following: - "true" - "1" - "yes" - "y" Otherwise False is returned. *Examples:* >>> booleanize('true') # returns True >>> booleanize('YES') # returns True >>> booleanize('nope') # returns False :param input_string: String to convert :type input_string: str :return: True if the string contains a boolean-like positive value, false otherwise """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string.lower() in ('true', '1', 'yes', 'y') def decompress(input_string: str, encoding: str = 'utf-8') -> str: """ Restore a previously compressed string (obtained using `compress()`) back to its original state. :param input_string: String to restore. :type input_string: str :param encoding: Original string encoding. :type encoding: str :return: Decompressed string. """ return __StringCompressor.decompress(input_string, encoding) def roman_encode(input_number: Union[str, int]) -> str: """ Convert the given number/string into a roman number. The passed input must represents a positive integer in the range 1-3999 (inclusive). Why this limit? You may be wondering: 1. zero is forbidden since there is no related representation in roman numbers 2. the upper bound 3999 is due to the limitation in the ascii charset\ (the higher quantity sign displayable in ascii is "M" which is equal to 1000, therefore based on\ roman numbers rules we can use 3 times M to reach 3000 but we can't go any further in thousands without\ special "boxed chars"). *Examples:* >>> roman_encode(37) # returns 'XXXVIII' >>> roman_encode('2020') # returns 'MMXX' :param input_number: An integer or a string to be converted. :type input_number: Union[str, int] :return: Roman number string. """ return __RomanNumbers.encode(input_number) Based on the information above, please complete the function in the current file: def slugify(input_string: str, separator: str = '-') -> str: """ Converts a string into a "slug" using provided separator. The returned string has the following properties: - it has no spaces - all letters are in lower case - all punctuation signs and non alphanumeric chars are removed - words are divided using provided separator - all chars are encoded as ascii (by using `asciify()`) - is safe for URL *Examples:* >>> slugify('Top 10 Reasons To Love Dogs!!!') # returns: 'top-10-reasons-to-love-dogs' >>> slugify('Mönstér Mägnët') # returns 'monster-magnet' :param input_string: String to convert. :type input_string: str :param separator: Sign used to join string tokens (default to "-"). :type separator: str :return: Slug string """
8
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' #CURRENT FILE: python-string-utils/string_utils/manipulation.py import base64 import random import unicodedata import zlib from typing import Union from uuid import uuid4 from ._regex import * from .errors import InvalidInputError from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string[::-1] Based on the information above, please complete the function in the current file: def booleanize(input_string: str) -> bool: """ Turns a string into a boolean based on its content (CASE INSENSITIVE). A positive boolean (True) is returned if the string value is one of the following: - "true" - "1" - "yes" - "y" Otherwise False is returned. *Examples:* >>> booleanize('true') # returns True >>> booleanize('YES') # returns True >>> booleanize('nope') # returns False :param input_string: String to convert :type input_string: str :return: True if the string contains a boolean-like positive value, false otherwise """
9
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' #FILE: python-string-utils/string_utils/_regex.py MARGIN_RE = re.compile(r'^[^\S\r\n]+') #CURRENT FILE: python-string-utils/string_utils/manipulation.py import base64 import random import unicodedata import zlib from typing import Union from uuid import uuid4 from ._regex import * from .errors import InvalidInputError from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string[::-1] def strip_html(input_string: str, keep_tag_content: bool = False) -> str: """ Remove html code contained into the given string. *Examples:* >>> strip_html('test: <a href="foo/bar">click here</a>') # returns 'test: ' >>> strip_html('test: <a href="foo/bar">click here</a>', keep_tag_content=True) # returns 'test: click here' :param input_string: String to manipulate. :type input_string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. """ if not is_string(input_string): raise InvalidInputError(input_string) r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r.sub('', input_string) def prettify(input_string: str) -> str: """ Reformat a string by applying the following basic grammar and formatting rules: - String cannot start or end with spaces - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \\*, =) must have one, and only one space before and after themselves - One, and only one space should follow a dot, a comma, an exclamation or a question mark - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \ after quotes (foo" bar"baz -> foo "bar" baz) - Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \ after brackets ("foo(bar )baz" -> "foo (bar) baz") - Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%") - Saxon genitive is correct ("Dave' s dog" -> "Dave's dog") *Examples:* >>> prettify(' unprettified string ,, like this one,will be"prettified" .it\\' s awesome! ') >>> # -> 'Unprettified string, like this one, will be "prettified". It\'s awesome!' :param input_string: String to manipulate :return: Prettified string. """ formatted = __StringFormatter(input_string).format() return formatted Based on the information above, please complete the function in the current file: def strip_margin(input_string: str) -> str: """ Removes tab indentation from multi line strings (inspired by analogous Scala function). *Example:* >>> strip_margin(''' >>> line 1 >>> line 2 >>> line 3 >>> ''') >>> # returns: >>> ''' >>> line 1 >>> line 2 >>> line 3 >>> ''' :param input_string: String to format :type input_string: str :return: A string without left margins """
10
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_snake_case(input_string: Any, separator: str = '_') -> bool: """ Checks if a string is formatted as "snake case". A string is considered snake case when: - it's composed only by lowercase/uppercase letters and digits - it contains at least one underscore (or provided separator) - it does not start with a number *Examples:* >>> is_snake_case('foo_bar_baz') # returns true >>> is_snake_case('foo') # returns false :param input_string: String to test. :type input_string: str :param separator: String to use as separator. :type separator: str :return: True for a snake case string, false otherwise. """ if is_full_string(input_string): re_map = { '_': SNAKE_CASE_TEST_RE, '-': SNAKE_CASE_TEST_DASH_RE } re_template = r'([a-z]+\d*{sign}[a-z\d{sign}]*|{sign}+[a-z\d]+[a-z\d{sign}]*)' r = re_map.get( separator, re.compile(re_template.format(sign=re.escape(separator)), re.IGNORECASE) ) return r.match(input_string) is not None return False def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' #CURRENT FILE: python-string-utils/string_utils/manipulation.py import base64 import random import unicodedata import zlib from typing import Union from uuid import uuid4 from ._regex import * from .errors import InvalidInputError from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string class __StringCompressor: @staticmethod def __require_valid_input_and_encoding(input_string: str, encoding: str): if not is_string(input_string): raise InvalidInputError(input_string) if len(input_string) == 0: raise ValueError('Input string cannot be empty') if not is_string(encoding): raise ValueError('Invalid encoding') @classmethod def compress(cls, input_string: str, encoding: str = 'utf-8', compression_level: int = 9) -> str: cls.__require_valid_input_and_encoding(input_string, encoding) if not isinstance(compression_level, int) or compression_level < 0 or compression_level > 9: raise ValueError('Invalid compression_level: it must be an "int" between 0 and 9') # turns input string into a sequence of bytes using provided encoding original_bytes = input_string.encode(encoding) # compress bytes using zlib library compressed_bytes = zlib.compress(original_bytes, compression_level) # encode compressed bytes using base64 # (this ensure that all characters will be available and that the output string can be used safely in any # context such URLs) encoded_bytes = base64.urlsafe_b64encode(compressed_bytes) # finally turns base64 bytes into a string output = encoded_bytes.decode(encoding) return output @classmethod def decompress(cls, input_string: str, encoding: str = 'utf-8') -> str: cls.__require_valid_input_and_encoding(input_string, encoding) # turns input string into a sequence of bytes # (the string is assumed to be a previously compressed string, therefore we have to decode it using base64) input_bytes = base64.urlsafe_b64decode(input_string) # decompress bytes using zlib decompressed_bytes = zlib.decompress(input_bytes) # decode the decompressed bytes to get the original string back original_string = decompressed_bytes.decode(encoding) return original_string def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string[::-1] def shuffle(input_string: str) -> str: """ Return a new string containing same chars of the given one but in a randomized order. *Example:* >>> shuffle('hello world') # possible output: 'l wodheorll' :param input_string: String to shuffle :type input_string: str :return: Shuffled string """ if not is_string(input_string): raise InvalidInputError(input_string) # turn the string into a list of chars chars = list(input_string) # shuffle the list random.shuffle(chars) # convert the shuffled list back to string return ''.join(chars) def roman_decode(input_string: str) -> int: """ Decode a roman number string into an integer if the provided string is valid. *Example:* >>> roman_decode('VII') # returns 7 :param input_string: (Assumed) Roman number :type input_string: str :return: Integer value """ return __RomanNumbers.decode(input_string) def compress(input_string: str, encoding: str = 'utf-8', compression_level: int = 9) -> str: """ Compress the given string by returning a shorter one that can be safely used in any context (like URL) and restored back to its original state using `decompress()`. **Bear in mind:** Besides the provided `compression_level`, the compression result (how much the string is actually compressed by resulting into a shorter string) depends on 2 factors: 1. The amount of data (string size): short strings might not provide a significant compression result\ or even be longer than the given input string (this is due to the fact that some bytes have to be embedded\ into the compressed string in order to be able to restore it later on)\ 2. The content type: random sequences of chars are very unlikely to be successfully compressed, while the best\ compression result is obtained when the string contains several recurring char sequences (like in the example). Behind the scenes this method makes use of the standard Python's zlib and base64 libraries. *Examples:* >>> n = 0 # <- ignore this, it's a fix for Pycharm (not fixable using ignore comments) >>> # "original" will be a string with 169 chars: >>> original = ' '.join(['word n{}'.format(n) for n in range(20)]) >>> # "compressed" will be a string of 88 chars >>> compressed = compress(original) :param input_string: String to compress (must be not empty or a ValueError will be raised). :type input_string: str :param encoding: String encoding (default to "utf-8"). :type encoding: str :param compression_level: A value between 0 (no compression) and 9 (best compression), default to 9. :type compression_level: int :return: Compressed string. """ return __StringCompressor.compress(input_string, encoding, compression_level) def strip_html(input_string: str, keep_tag_content: bool = False) -> str: """ Remove html code contained into the given string. *Examples:* >>> strip_html('test: <a href="foo/bar">click here</a>') # returns 'test: ' >>> strip_html('test: <a href="foo/bar">click here</a>', keep_tag_content=True) # returns 'test: click here' :param input_string: String to manipulate. :type input_string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. """ if not is_string(input_string): raise InvalidInputError(input_string) r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r.sub('', input_string) def asciify(input_string: str) -> str: """ Force string content to be ascii-only by translating all non-ascii chars into the closest possible representation (eg: ó -> o, Ë -> E, ç -> c...). **Bear in mind**: Some chars may be lost if impossible to translate. *Example:* >>> asciify('èéùúòóäåëýñÅÀÁÇÌÍÑÓË') # returns 'eeuuooaaeynAAACIINOE' :param input_string: String to convert :return: Ascii utf-8 string """ if not is_string(input_string): raise InvalidInputError(input_string) # "NFKD" is the algorithm which is able to successfully translate the most of non-ascii chars normalized = unicodedata.normalize('NFKD', input_string) # encode string forcing ascii and ignore any errors (unrepresentable chars will be stripped out) ascii_bytes = normalized.encode('ascii', 'ignore') # turns encoded bytes into an utf-8 string ascii_string = ascii_bytes.decode('utf-8') return ascii_string def prettify(input_string: str) -> str: """ Reformat a string by applying the following basic grammar and formatting rules: - String cannot start or end with spaces - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \\*, =) must have one, and only one space before and after themselves - One, and only one space should follow a dot, a comma, an exclamation or a question mark - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \ after quotes (foo" bar"baz -> foo "bar" baz) - Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \ after brackets ("foo(bar )baz" -> "foo (bar) baz") - Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%") - Saxon genitive is correct ("Dave' s dog" -> "Dave's dog") *Examples:* >>> prettify(' unprettified string ,, like this one,will be"prettified" .it\\' s awesome! ') >>> # -> 'Unprettified string, like this one, will be "prettified". It\'s awesome!' :param input_string: String to manipulate :return: Prettified string. """ formatted = __StringFormatter(input_string).format() return formatted def strip_margin(input_string: str) -> str: """ Removes tab indentation from multi line strings (inspired by analogous Scala function). *Example:* >>> strip_margin(''' >>> line 1 >>> line 2 >>> line 3 >>> ''') >>> # returns: >>> ''' >>> line 1 >>> line 2 >>> line 3 >>> ''' :param input_string: String to format :type input_string: str :return: A string without left margins """ if not is_string(input_string): raise InvalidInputError(input_string) line_separator = '\n' lines = [MARGIN_RE.sub('', line) for line in input_string.split(line_separator)] out = line_separator.join(lines) return out def booleanize(input_string: str) -> bool: """ Turns a string into a boolean based on its content (CASE INSENSITIVE). A positive boolean (True) is returned if the string value is one of the following: - "true" - "1" - "yes" - "y" Otherwise False is returned. *Examples:* >>> booleanize('true') # returns True >>> booleanize('YES') # returns True >>> booleanize('nope') # returns False :param input_string: String to convert :type input_string: str :return: True if the string contains a boolean-like positive value, false otherwise """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string.lower() in ('true', '1', 'yes', 'y') def roman_encode(input_number: Union[str, int]) -> str: """ Convert the given number/string into a roman number. The passed input must represents a positive integer in the range 1-3999 (inclusive). Why this limit? You may be wondering: 1. zero is forbidden since there is no related representation in roman numbers 2. the upper bound 3999 is due to the limitation in the ascii charset\ (the higher quantity sign displayable in ascii is "M" which is equal to 1000, therefore based on\ roman numbers rules we can use 3 times M to reach 3000 but we can't go any further in thousands without\ special "boxed chars"). *Examples:* >>> roman_encode(37) # returns 'XXXVIII' >>> roman_encode('2020') # returns 'MMXX' :param input_number: An integer or a string to be converted. :type input_number: Union[str, int] :return: Roman number string. """ return __RomanNumbers.encode(input_number) Based on the information above, please complete the function in the current file: def decompress(input_string: str, encoding: str = 'utf-8') -> str: """ Restore a previously compressed string (obtained using `compress()`) back to its original state. :param input_string: String to restore. :type input_string: str :param encoding: Original string encoding. :type encoding: str :return: Decompressed string. """
11
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_snake_case(input_string: Any, separator: str = '_') -> bool: """ Checks if a string is formatted as "snake case". A string is considered snake case when: - it's composed only by lowercase/uppercase letters and digits - it contains at least one underscore (or provided separator) - it does not start with a number *Examples:* >>> is_snake_case('foo_bar_baz') # returns true >>> is_snake_case('foo') # returns false :param input_string: String to test. :type input_string: str :param separator: String to use as separator. :type separator: str :return: True for a snake case string, false otherwise. """ if is_full_string(input_string): re_map = { '_': SNAKE_CASE_TEST_RE, '-': SNAKE_CASE_TEST_DASH_RE } re_template = r'([a-z]+\d*{sign}[a-z\d{sign}]*|{sign}+[a-z\d]+[a-z\d{sign}]*)' r = re_map.get( separator, re.compile(re_template.format(sign=re.escape(separator)), re.IGNORECASE) ) return r.match(input_string) is not None return False def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_camel_case(input_string: Any) -> bool: """ Checks if a string is formatted as camel case. A string is considered camel case when: - it's composed only by letters ([a-zA-Z]) and optionally numbers ([0-9]) - it contains both lowercase and uppercase letters - it does not start with a number *Examples:* >>> is_camel_case('MyString') # returns true >>> is_camel_case('mystring') # returns false :param input_string: String to test. :type input_string: str :return: True for a camel case string, false otherwise. """ return is_full_string(input_string) and CAMEL_CASE_TEST_RE.match(input_string) is not None def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' #CURRENT FILE: python-string-utils/string_utils/manipulation.py import base64 import random import unicodedata import zlib from typing import Union from uuid import uuid4 from ._regex import * from .errors import InvalidInputError from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string class __RomanNumbers: # internal rule mappings for encode() __mappings = [ # units {1: 'I', 5: 'V'}, # tens {1: 'X', 5: 'L'}, # hundreds {1: 'C', 5: 'D'}, # thousands {1: 'M'}, ] # swap key/value definitions for decode() __reversed_mappings = [{v: k for k, v in m.items()} for m in __mappings] @classmethod def __encode_digit(cls, index: int, value: int) -> str: # if digit is zero, there is no sign to display if value == 0: return '' # from 1 to 3 we have just to repeat the sign N times (eg: III, XXX...) if value <= 3: return cls.__mappings[index][1] * value # if 4 we have to add unit prefix if value == 4: return cls.__mappings[index][1] + cls.__mappings[index][5] # if is 5, is a straight map if value == 5: return cls.__mappings[index][5] # if 6, 7 or 8 we have to append unit suffixes if value <= 8: suffix = cls.__mappings[index][1] * (value - 5) return cls.__mappings[index][5] + suffix # if 9 we have to prepend current unit to next return cls.__mappings[index][1] + cls.__mappings[index + 1][1] @classmethod def encode(cls, input_number: Union[str, int]) -> str: # force input conversion to a string (we need it in order to iterate on each digit) input_string = str(input_number) if not is_integer(input_string): raise ValueError('Invalid input, only strings or integers are allowed') value = int(input_string) if value < 1 or value > 3999: raise ValueError('Input must be >= 1 and <= 3999') input_len = len(input_string) output = '' # decode digits from right to left (start from units to thousands) for index in range(input_len): # get actual digit value as int digit = int(input_string[input_len - index - 1]) # encode digit to roman string encoded_digit = cls.__encode_digit(index, digit) # prepend encoded value to the current output in order to have the final string sorted # from thousands to units output = encoded_digit + output return output @classmethod def __index_for_sign(cls, sign: str) -> int: for index, mapping in enumerate(cls.__reversed_mappings): if sign in mapping: return index raise ValueError('Invalid token found: "{}"'.format(sign)) @classmethod def decode(cls, input_string: str) -> int: if not is_full_string(input_string): raise ValueError('Input must be a non empty string') # reverse the provided string so that we can start parsing from units to thousands reversed_string = reverse(input_string.upper()) # track last used value last_value = None # computed number to return output = 0 # for each sign in the string we get its numeric value and add or subtract it to the computed output for sign in reversed_string: # are we dealing with units, tens, hundreds or thousands? index = cls.__index_for_sign(sign) # it's basically 1 or 5 (based on mapping rules definitions) key_value = cls.__reversed_mappings[index][sign] # Based on the level (tens, hundreds...) we have to add as many zeroes as the level into which we are # in order to have the actual sign value. # For instance, if we are at level 2 we are dealing with hundreds, therefore instead of 1 or 5, we will # obtain 100 or 500 by adding 2 zeroes sign_value = int(str(key_value) + '0' * index) # increase total value if we are moving on with level if last_value is None or sign_value >= last_value: output += sign_value # Decrease value if we are back to a previous level # For instance, if we are parsing "IX", we first encounter "X" which is ten then "I" which is unit, # So we have to do the following operation in order to get 9 (the final result): 10 - 1 else: output -= sign_value last_value = sign_value return output def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string[::-1] def shuffle(input_string: str) -> str: """ Return a new string containing same chars of the given one but in a randomized order. *Example:* >>> shuffle('hello world') # possible output: 'l wodheorll' :param input_string: String to shuffle :type input_string: str :return: Shuffled string """ if not is_string(input_string): raise InvalidInputError(input_string) # turn the string into a list of chars chars = list(input_string) # shuffle the list random.shuffle(chars) # convert the shuffled list back to string return ''.join(chars) def compress(input_string: str, encoding: str = 'utf-8', compression_level: int = 9) -> str: """ Compress the given string by returning a shorter one that can be safely used in any context (like URL) and restored back to its original state using `decompress()`. **Bear in mind:** Besides the provided `compression_level`, the compression result (how much the string is actually compressed by resulting into a shorter string) depends on 2 factors: 1. The amount of data (string size): short strings might not provide a significant compression result\ or even be longer than the given input string (this is due to the fact that some bytes have to be embedded\ into the compressed string in order to be able to restore it later on)\ 2. The content type: random sequences of chars are very unlikely to be successfully compressed, while the best\ compression result is obtained when the string contains several recurring char sequences (like in the example). Behind the scenes this method makes use of the standard Python's zlib and base64 libraries. *Examples:* >>> n = 0 # <- ignore this, it's a fix for Pycharm (not fixable using ignore comments) >>> # "original" will be a string with 169 chars: >>> original = ' '.join(['word n{}'.format(n) for n in range(20)]) >>> # "compressed" will be a string of 88 chars >>> compressed = compress(original) :param input_string: String to compress (must be not empty or a ValueError will be raised). :type input_string: str :param encoding: String encoding (default to "utf-8"). :type encoding: str :param compression_level: A value between 0 (no compression) and 9 (best compression), default to 9. :type compression_level: int :return: Compressed string. """ return __StringCompressor.compress(input_string, encoding, compression_level) def strip_html(input_string: str, keep_tag_content: bool = False) -> str: """ Remove html code contained into the given string. *Examples:* >>> strip_html('test: <a href="foo/bar">click here</a>') # returns 'test: ' >>> strip_html('test: <a href="foo/bar">click here</a>', keep_tag_content=True) # returns 'test: click here' :param input_string: String to manipulate. :type input_string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. """ if not is_string(input_string): raise InvalidInputError(input_string) r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r.sub('', input_string) def asciify(input_string: str) -> str: """ Force string content to be ascii-only by translating all non-ascii chars into the closest possible representation (eg: ó -> o, Ë -> E, ç -> c...). **Bear in mind**: Some chars may be lost if impossible to translate. *Example:* >>> asciify('èéùúòóäåëýñÅÀÁÇÌÍÑÓË') # returns 'eeuuooaaeynAAACIINOE' :param input_string: String to convert :return: Ascii utf-8 string """ if not is_string(input_string): raise InvalidInputError(input_string) # "NFKD" is the algorithm which is able to successfully translate the most of non-ascii chars normalized = unicodedata.normalize('NFKD', input_string) # encode string forcing ascii and ignore any errors (unrepresentable chars will be stripped out) ascii_bytes = normalized.encode('ascii', 'ignore') # turns encoded bytes into an utf-8 string ascii_string = ascii_bytes.decode('utf-8') return ascii_string def prettify(input_string: str) -> str: """ Reformat a string by applying the following basic grammar and formatting rules: - String cannot start or end with spaces - The first letter in the string and the ones after a dot, an exclamation or a question mark must be uppercase - String cannot have multiple sequential spaces, empty lines or punctuation (except for "?", "!" and ".") - Arithmetic operators (+, -, /, \\*, =) must have one, and only one space before and after themselves - One, and only one space should follow a dot, a comma, an exclamation or a question mark - Text inside double quotes cannot start or end with spaces, but one, and only one space must come first and \ after quotes (foo" bar"baz -> foo "bar" baz) - Text inside round brackets cannot start or end with spaces, but one, and only one space must come first and \ after brackets ("foo(bar )baz" -> "foo (bar) baz") - Percentage sign ("%") cannot be preceded by a space if there is a number before ("100 %" -> "100%") - Saxon genitive is correct ("Dave' s dog" -> "Dave's dog") *Examples:* >>> prettify(' unprettified string ,, like this one,will be"prettified" .it\\' s awesome! ') >>> # -> 'Unprettified string, like this one, will be "prettified". It\'s awesome!' :param input_string: String to manipulate :return: Prettified string. """ formatted = __StringFormatter(input_string).format() return formatted def camel_case_to_snake(input_string, separator='_'): """ Convert a camel case string into a snake case one. (The original string is returned if is not a valid camel case string) *Example:* >>> camel_case_to_snake('ThisIsACamelStringTest') # returns 'this_is_a_camel_case_string_test' :param input_string: String to convert. :type input_string: str :param separator: Sign to use as separator. :type separator: str :return: Converted string. """ if not is_string(input_string): raise InvalidInputError(input_string) if not is_camel_case(input_string): return input_string return CAMEL_CASE_REPLACE_RE.sub(lambda m: m.group(1) + separator, input_string).lower() def strip_margin(input_string: str) -> str: """ Removes tab indentation from multi line strings (inspired by analogous Scala function). *Example:* >>> strip_margin(''' >>> line 1 >>> line 2 >>> line 3 >>> ''') >>> # returns: >>> ''' >>> line 1 >>> line 2 >>> line 3 >>> ''' :param input_string: String to format :type input_string: str :return: A string without left margins """ if not is_string(input_string): raise InvalidInputError(input_string) line_separator = '\n' lines = [MARGIN_RE.sub('', line) for line in input_string.split(line_separator)] out = line_separator.join(lines) return out def booleanize(input_string: str) -> bool: """ Turns a string into a boolean based on its content (CASE INSENSITIVE). A positive boolean (True) is returned if the string value is one of the following: - "true" - "1" - "yes" - "y" Otherwise False is returned. *Examples:* >>> booleanize('true') # returns True >>> booleanize('YES') # returns True >>> booleanize('nope') # returns False :param input_string: String to convert :type input_string: str :return: True if the string contains a boolean-like positive value, false otherwise """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string.lower() in ('true', '1', 'yes', 'y') def decompress(input_string: str, encoding: str = 'utf-8') -> str: """ Restore a previously compressed string (obtained using `compress()`) back to its original state. :param input_string: String to restore. :type input_string: str :param encoding: Original string encoding. :type encoding: str :return: Decompressed string. """ return __StringCompressor.decompress(input_string, encoding) def roman_decode(input_string: str) -> int: """ Decode a roman number string into an integer if the provided string is valid. *Example:* >>> roman_decode('VII') # returns 7 :param input_string: (Assumed) Roman number :type input_string: str :return: Integer value """ return __RomanNumbers.decode(input_string) Based on the information above, please complete the function in the current file: def roman_encode(input_number: Union[str, int]) -> str: """ Convert the given number/string into a roman number. The passed input must represents a positive integer in the range 1-3999 (inclusive). Why this limit? You may be wondering: 1. zero is forbidden since there is no related representation in roman numbers 2. the upper bound 3999 is due to the limitation in the ascii charset\ (the higher quantity sign displayable in ascii is "M" which is equal to 1000, therefore based on\ roman numbers rules we can use 3 times M to reach 3000 but we can't go any further in thousands without\ special "boxed chars"). *Examples:* >>> roman_encode(37) # returns 'XXXVIII' >>> roman_encode('2020') # returns 'MMXX' :param input_number: An integer or a string to be converted. :type input_number: Union[str, int] :return: Roman number string. """
12
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/validation.py def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_snake_case(input_string: Any, separator: str = '_') -> bool: """ Checks if a string is formatted as "snake case". A string is considered snake case when: - it's composed only by lowercase/uppercase letters and digits - it contains at least one underscore (or provided separator) - it does not start with a number *Examples:* >>> is_snake_case('foo_bar_baz') # returns true >>> is_snake_case('foo') # returns false :param input_string: String to test. :type input_string: str :param separator: String to use as separator. :type separator: str :return: True for a snake case string, false otherwise. """ if is_full_string(input_string): re_map = { '_': SNAKE_CASE_TEST_RE, '-': SNAKE_CASE_TEST_DASH_RE } re_template = r'([a-z]+\d*{sign}[a-z\d{sign}]*|{sign}+[a-z\d]+[a-z\d{sign}]*)' r = re_map.get( separator, re.compile(re_template.format(sign=re.escape(separator)), re.IGNORECASE) ) return r.match(input_string) is not None return False def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' #CURRENT FILE: python-string-utils/string_utils/manipulation.py import base64 import random import unicodedata import zlib from typing import Union from uuid import uuid4 from ._regex import * from .errors import InvalidInputError from .validation import is_snake_case, is_full_string, is_camel_case, is_integer, is_string class __RomanNumbers: # internal rule mappings for encode() __mappings = [ # units {1: 'I', 5: 'V'}, # tens {1: 'X', 5: 'L'}, # hundreds {1: 'C', 5: 'D'}, # thousands {1: 'M'}, ] # swap key/value definitions for decode() __reversed_mappings = [{v: k for k, v in m.items()} for m in __mappings] @classmethod def __encode_digit(cls, index: int, value: int) -> str: # if digit is zero, there is no sign to display if value == 0: return '' # from 1 to 3 we have just to repeat the sign N times (eg: III, XXX...) if value <= 3: return cls.__mappings[index][1] * value # if 4 we have to add unit prefix if value == 4: return cls.__mappings[index][1] + cls.__mappings[index][5] # if is 5, is a straight map if value == 5: return cls.__mappings[index][5] # if 6, 7 or 8 we have to append unit suffixes if value <= 8: suffix = cls.__mappings[index][1] * (value - 5) return cls.__mappings[index][5] + suffix # if 9 we have to prepend current unit to next return cls.__mappings[index][1] + cls.__mappings[index + 1][1] @classmethod def encode(cls, input_number: Union[str, int]) -> str: # force input conversion to a string (we need it in order to iterate on each digit) input_string = str(input_number) if not is_integer(input_string): raise ValueError('Invalid input, only strings or integers are allowed') value = int(input_string) if value < 1 or value > 3999: raise ValueError('Input must be >= 1 and <= 3999') input_len = len(input_string) output = '' # decode digits from right to left (start from units to thousands) for index in range(input_len): # get actual digit value as int digit = int(input_string[input_len - index - 1]) # encode digit to roman string encoded_digit = cls.__encode_digit(index, digit) # prepend encoded value to the current output in order to have the final string sorted # from thousands to units output = encoded_digit + output return output @classmethod def __index_for_sign(cls, sign: str) -> int: for index, mapping in enumerate(cls.__reversed_mappings): if sign in mapping: return index raise ValueError('Invalid token found: "{}"'.format(sign)) @classmethod def decode(cls, input_string: str) -> int: if not is_full_string(input_string): raise ValueError('Input must be a non empty string') # reverse the provided string so that we can start parsing from units to thousands reversed_string = reverse(input_string.upper()) # track last used value last_value = None # computed number to return output = 0 # for each sign in the string we get its numeric value and add or subtract it to the computed output for sign in reversed_string: # are we dealing with units, tens, hundreds or thousands? index = cls.__index_for_sign(sign) # it's basically 1 or 5 (based on mapping rules definitions) key_value = cls.__reversed_mappings[index][sign] # Based on the level (tens, hundreds...) we have to add as many zeroes as the level into which we are # in order to have the actual sign value. # For instance, if we are at level 2 we are dealing with hundreds, therefore instead of 1 or 5, we will # obtain 100 or 500 by adding 2 zeroes sign_value = int(str(key_value) + '0' * index) # increase total value if we are moving on with level if last_value is None or sign_value >= last_value: output += sign_value # Decrease value if we are back to a previous level # For instance, if we are parsing "IX", we first encounter "X" which is ten then "I" which is unit, # So we have to do the following operation in order to get 9 (the final result): 10 - 1 else: output -= sign_value last_value = sign_value return output def reverse(input_string: str) -> str: """ Returns the string with its chars reversed. *Example:* >>> reverse('hello') # returns 'olleh' :param input_string: String to revert. :type input_string: str :return: Reversed string. """ if not is_string(input_string): raise InvalidInputError(input_string) return input_string[::-1] def decompress(input_string: str, encoding: str = 'utf-8') -> str: """ Restore a previously compressed string (obtained using `compress()`) back to its original state. :param input_string: String to restore. :type input_string: str :param encoding: Original string encoding. :type encoding: str :return: Decompressed string. """ return __StringCompressor.decompress(input_string, encoding) def roman_encode(input_number: Union[str, int]) -> str: """ Convert the given number/string into a roman number. The passed input must represents a positive integer in the range 1-3999 (inclusive). Why this limit? You may be wondering: 1. zero is forbidden since there is no related representation in roman numbers 2. the upper bound 3999 is due to the limitation in the ascii charset\ (the higher quantity sign displayable in ascii is "M" which is equal to 1000, therefore based on\ roman numbers rules we can use 3 times M to reach 3000 but we can't go any further in thousands without\ special "boxed chars"). *Examples:* >>> roman_encode(37) # returns 'XXXVIII' >>> roman_encode('2020') # returns 'MMXX' :param input_number: An integer or a string to be converted. :type input_number: Union[str, int] :return: Roman number string. """ return __RomanNumbers.encode(input_number) Based on the information above, please complete the function in the current file: def roman_decode(input_string: str) -> int: """ Decode a roman number string into an integer if the provided string is valid. *Example:* >>> roman_decode('VII') # returns 7 :param input_string: (Assumed) Roman number :type input_string: str :return: Integer value """
13
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #CURRENT FILE: python-string-utils/string_utils/validation.py import json import string from typing import Any, Optional, List from ._regex import * from .errors import InvalidInputError def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_json(input_string: Any) -> bool: """ Check if a string is a valid json. *Examples:* >>> is_json('{"name": "Peter"}') # returns true >>> is_json('[1, 2, 3]') # returns true >>> is_json('{nope}') # returns false :param input_string: String to check. :type input_string: str :return: True if json, false otherwise """ if is_full_string(input_string) and JSON_WRAPPER_RE.match(input_string) is not None: try: return isinstance(json.loads(input_string), (dict, list)) except (TypeError, ValueError, OverflowError): pass return False def is_isbn(input_string: str, normalize: bool = True) -> bool: """ Checks if the given string represents a valid ISBN (International Standard Book Number). By default hyphens in the string are ignored, so digits can be separated in different ways, by calling this function with `normalize=False` only digit-only strings will pass the validation. *Examples:* >>> is_isbn('9780312498580') # returns true >>> is_isbn('1506715214') # returns true :param input_string: String to check. :param normalize: True to ignore hyphens ("-") in the string (default), false otherwise. :return: True if valid ISBN (10 or 13), false otherwise. """ checker = __ISBNChecker(input_string, normalize) return checker.is_isbn_13() or checker.is_isbn_10() def is_number(input_string: str) -> bool: """ Checks if a string is a valid number. The number can be a signed (eg: +1, -2, -3.3) or unsigned (eg: 1, 2, 3.3) integer or double or use the "scientific notation" (eg: 1e5). *Examples:* >>> is_number('42') # returns true >>> is_number('19.99') # returns true >>> is_number('-9.12') # returns true >>> is_number('1e3') # returns true >>> is_number('1 2 3') # returns false :param input_string: String to check :type input_string: str :return: True if the string represents a number, false otherwise """ if not isinstance(input_string, str): raise InvalidInputError(input_string) return NUMBER_RE.match(input_string) is not None def is_pangram(input_string: Any) -> bool: """ Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). *Examples:* >>> is_pangram('The quick brown fox jumps over the lazy dog') # returns true >>> is_pangram('hello world') # returns false :param input_string: String to check. :type input_string: str :return: True if the string is a pangram, False otherwise. """ if not is_full_string(input_string): return False return set(SPACES_RE.sub('', input_string)).issuperset(set(string.ascii_lowercase)) def is_snake_case(input_string: Any, separator: str = '_') -> bool: """ Checks if a string is formatted as "snake case". A string is considered snake case when: - it's composed only by lowercase/uppercase letters and digits - it contains at least one underscore (or provided separator) - it does not start with a number *Examples:* >>> is_snake_case('foo_bar_baz') # returns true >>> is_snake_case('foo') # returns false :param input_string: String to test. :type input_string: str :param separator: String to use as separator. :type separator: str :return: True for a snake case string, false otherwise. """ if is_full_string(input_string): re_map = { '_': SNAKE_CASE_TEST_RE, '-': SNAKE_CASE_TEST_DASH_RE } re_template = r'([a-z]+\d*{sign}[a-z\d{sign}]*|{sign}+[a-z\d]+[a-z\d{sign}]*)' r = re_map.get( separator, re.compile(re_template.format(sign=re.escape(separator)), re.IGNORECASE) ) return r.match(input_string) is not None return False def is_url(input_string: Any, allowed_schemes: Optional[List[str]] = None) -> bool: """ Check if a string is a valid url. *Examples:* >>> is_url('http://www.mysite.com') # returns true >>> is_url('https://mysite.com') # returns true >>> is_url('.mysite.com') # returns false :param input_string: String to check. :type input_string: str :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid). :type allowed_schemes: Optional[List[str]] :return: True if url, false otherwise """ if not is_full_string(input_string): return False valid = URL_RE.match(input_string) is not None if allowed_schemes: return valid and any([input_string.startswith(s) for s in allowed_schemes]) return valid def is_slug(input_string: Any, separator: str = '-') -> bool: """ Checks if a given string is a slug (as created by `slugify()`). *Examples:* >>> is_slug('my-blog-post-title') # returns true >>> is_slug('My blog post title') # returns false :param input_string: String to check. :type input_string: str :param separator: Join sign used by the slug. :type separator: str :return: True if slug, false otherwise. """ if not is_full_string(input_string): return False rex = r'^([a-z\d]+' + re.escape(separator) + r'*?)*[a-z\d]$' return re.match(rex, input_string) is not None def is_camel_case(input_string: Any) -> bool: """ Checks if a string is formatted as camel case. A string is considered camel case when: - it's composed only by letters ([a-zA-Z]) and optionally numbers ([0-9]) - it contains both lowercase and uppercase letters - it does not start with a number *Examples:* >>> is_camel_case('MyString') # returns true >>> is_camel_case('mystring') # returns false :param input_string: String to test. :type input_string: str :return: True for a camel case string, false otherwise. """ return is_full_string(input_string) and CAMEL_CASE_TEST_RE.match(input_string) is not None def is_decimal(input_string: str) -> bool: """ Checks whether the given string represents a decimal or not. A decimal may be signed or unsigned or use a "scientific notation". >>> is_decimal('42.0') # returns true >>> is_decimal('42') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' in input_string def is_palindrome(input_string: Any, ignore_spaces: bool = False, ignore_case: bool = False) -> bool: """ Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome). *Examples:* >>> is_palindrome('LOL') # returns true >>> is_palindrome('Lol') # returns false >>> is_palindrome('Lol', ignore_case=True) # returns true >>> is_palindrome('ROTFL') # returns false :param input_string: String to check. :type input_string: str :param ignore_spaces: False if white spaces matter (default), true otherwise. :type ignore_spaces: bool :param ignore_case: False if char case matters (default), true otherwise. :type ignore_case: bool :return: True if the string is a palindrome (like "otto", or "i topi non avevano nipoti" if strict=False),\ False otherwise """ if not is_full_string(input_string): return False if ignore_spaces: input_string = SPACES_RE.sub('', input_string) string_len = len(input_string) # Traverse the string one char at step, and for each step compares the # "head_char" (the one on the left of the string) to the "tail_char" (the one on the right). # In this way we avoid to manipulate the whole string in advance if not necessary and provide a faster # algorithm which can scale very well for long strings. for index in range(string_len): head_char = input_string[index] tail_char = input_string[string_len - index - 1] if ignore_case: head_char = head_char.lower() tail_char = tail_char.lower() if head_char != tail_char: return False return True def is_isogram(input_string: Any) -> bool: """ Checks if the string is an isogram (https://en.wikipedia.org/wiki/Isogram). *Examples:* >>> is_isogram('dermatoglyphics') # returns true >>> is_isogram('hello') # returns false :param input_string: String to check. :type input_string: str :return: True if isogram, false otherwise. """ return is_full_string(input_string) and len(set(input_string)) == len(input_string) def is_ip(input_string: Any) -> bool: """ Checks if a string is a valid ip (either v4 or v6). *Examples:* >>> is_ip('255.200.100.75') # returns true >>> is_ip('2001:db8:85a3:0000:0000:8a2e:370:7334') # returns true >>> is_ip('1.2.3') # returns false :param input_string: String to check. :type input_string: str :return: True if an ip, false otherwise. """ return is_ip_v6(input_string) or is_ip_v4(input_string) def contains_html(input_string: str) -> bool: """ Checks if the given string contains HTML/XML tags. By design, this function matches ANY type of tag, so don't expect to use it as an HTML validator, its goal is to detect "malicious" or undesired tags in the text. *Examples:* >>> contains_html('my string is <strong>bold</strong>') # returns true >>> contains_html('my string is not bold') # returns false :param input_string: Text to check :type input_string: str :return: True if string contains html, false otherwise. """ if not is_string(input_string): raise InvalidInputError(input_string) return HTML_RE.search(input_string) is not None def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' Based on the information above, please complete the function in the current file: def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """
14
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #CURRENT FILE: python-string-utils/string_utils/validation.py import json import string from typing import Any, Optional, List from ._regex import * from .errors import InvalidInputError def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) Based on the information above, please complete the function in the current file: def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """
15
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/_regex.py NUMBER_RE = re.compile(r'^([+\-]?)((\d+)(\.\d+)?(e\d+)?|\.\d+)$') #CURRENT FILE: python-string-utils/string_utils/validation.py import json import string from typing import Any, Optional, List from ._regex import * from .errors import InvalidInputError class __ISBNChecker: def __init__(self, input_string: str, normalize: bool = True): if not is_string(input_string): raise InvalidInputError(input_string) self.input_string = input_string.replace('-', '') if normalize else input_string def is_isbn_13(self) -> bool: if len(self.input_string) == 13: product = 0 try: for index, digit in enumerate(self.input_string): weight = 1 if (index % 2 == 0) else 3 product += int(digit) * weight return product % 10 == 0 except ValueError: pass return False def is_isbn_10(self) -> bool: if len(self.input_string) == 10: product = 0 try: for index, digit in enumerate(self.input_string): product += int(digit) * (index + 1) return product % 11 == 0 except ValueError: pass return False def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_json(input_string: Any) -> bool: """ Check if a string is a valid json. *Examples:* >>> is_json('{"name": "Peter"}') # returns true >>> is_json('[1, 2, 3]') # returns true >>> is_json('{nope}') # returns false :param input_string: String to check. :type input_string: str :return: True if json, false otherwise """ if is_full_string(input_string) and JSON_WRAPPER_RE.match(input_string) is not None: try: return isinstance(json.loads(input_string), (dict, list)) except (TypeError, ValueError, OverflowError): pass return False def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_isbn(input_string: str, normalize: bool = True) -> bool: """ Checks if the given string represents a valid ISBN (International Standard Book Number). By default hyphens in the string are ignored, so digits can be separated in different ways, by calling this function with `normalize=False` only digit-only strings will pass the validation. *Examples:* >>> is_isbn('9780312498580') # returns true >>> is_isbn('1506715214') # returns true :param input_string: String to check. :param normalize: True to ignore hyphens ("-") in the string (default), false otherwise. :return: True if valid ISBN (10 or 13), false otherwise. """ checker = __ISBNChecker(input_string, normalize) return checker.is_isbn_13() or checker.is_isbn_10() def is_decimal(input_string: str) -> bool: """ Checks whether the given string represents a decimal or not. A decimal may be signed or unsigned or use a "scientific notation". >>> is_decimal('42.0') # returns true >>> is_decimal('42') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' in input_string def is_isbn_10(input_string: str, normalize: bool = True) -> bool: """ Checks if the given string represents a valid ISBN 10 (International Standard Book Number). By default hyphens in the string are ignored, so digits can be separated in different ways, by calling this function with `normalize=False` only digit-only strings will pass the validation. *Examples:* >>> is_isbn_10('1506715214') # returns true >>> is_isbn_10('150-6715214') # returns true >>> is_isbn_10('150-6715214', normalize=False) # returns false :param input_string: String to check. :param normalize: True to ignore hyphens ("-") in the string (default), false otherwise. :return: True if valid ISBN 10, false otherwise. """ checker = __ISBNChecker(input_string, normalize) return checker.is_isbn_10() def is_isbn_13(input_string: str, normalize: bool = True) -> bool: """ Checks if the given string represents a valid ISBN 13 (International Standard Book Number). By default hyphens in the string are ignored, so digits can be separated in different ways, by calling this function with `normalize=False` only digit-only strings will pass the validation. *Examples:* >>> is_isbn_13('9780312498580') # returns true >>> is_isbn_13('978-0312498580') # returns true >>> is_isbn_13('978-0312498580', normalize=False) # returns false :param input_string: String to check. :param normalize: True to ignore hyphens ("-") in the string (default), false otherwise. :return: True if valid ISBN 13, false otherwise. """ checker = __ISBNChecker(input_string, normalize) return checker.is_isbn_13() Based on the information above, please complete the function in the current file: def is_number(input_string: str) -> bool: """ Checks if a string is a valid number. The number can be a signed (eg: +1, -2, -3.3) or unsigned (eg: 1, 2, 3.3) integer or double or use the "scientific notation" (eg: 1e5). *Examples:* >>> is_number('42') # returns true >>> is_number('19.99') # returns true >>> is_number('-9.12') # returns true >>> is_number('1e3') # returns true >>> is_number('1 2 3') # returns false :param input_string: String to check :type input_string: str :return: True if the string represents a number, false otherwise """
16
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #CURRENT FILE: python-string-utils/string_utils/validation.py import json import string from typing import Any, Optional, List from ._regex import * from .errors import InvalidInputError def is_number(input_string: str) -> bool: """ Checks if a string is a valid number. The number can be a signed (eg: +1, -2, -3.3) or unsigned (eg: 1, 2, 3.3) integer or double or use the "scientific notation" (eg: 1e5). *Examples:* >>> is_number('42') # returns true >>> is_number('19.99') # returns true >>> is_number('-9.12') # returns true >>> is_number('1e3') # returns true >>> is_number('1 2 3') # returns false :param input_string: String to check :type input_string: str :return: True if the string represents a number, false otherwise """ if not isinstance(input_string, str): raise InvalidInputError(input_string) return NUMBER_RE.match(input_string) is not None def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) Based on the information above, please complete the function in the current file: def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """
17
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #CURRENT FILE: python-string-utils/string_utils/validation.py import json import string from typing import Any, Optional, List from ._regex import * from .errors import InvalidInputError def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) Based on the information above, please complete the function in the current file: def is_decimal(input_string: str) -> bool: """ Checks whether the given string represents a decimal or not. A decimal may be signed or unsigned or use a "scientific notation". >>> is_decimal('42.0') # returns true >>> is_decimal('42') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """
18
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/_regex.py URL_RE = re.compile(r'^{}$'.format(URLS_RAW_STRING), re.IGNORECASE) #CURRENT FILE: python-string-utils/string_utils/validation.py import json import string from typing import Any, Optional, List from ._regex import * from .errors import InvalidInputError def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_json(input_string: Any) -> bool: """ Check if a string is a valid json. *Examples:* >>> is_json('{"name": "Peter"}') # returns true >>> is_json('[1, 2, 3]') # returns true >>> is_json('{nope}') # returns false :param input_string: String to check. :type input_string: str :return: True if json, false otherwise """ if is_full_string(input_string) and JSON_WRAPPER_RE.match(input_string) is not None: try: return isinstance(json.loads(input_string), (dict, list)) except (TypeError, ValueError, OverflowError): pass return False def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_isbn(input_string: str, normalize: bool = True) -> bool: """ Checks if the given string represents a valid ISBN (International Standard Book Number). By default hyphens in the string are ignored, so digits can be separated in different ways, by calling this function with `normalize=False` only digit-only strings will pass the validation. *Examples:* >>> is_isbn('9780312498580') # returns true >>> is_isbn('1506715214') # returns true :param input_string: String to check. :param normalize: True to ignore hyphens ("-") in the string (default), false otherwise. :return: True if valid ISBN (10 or 13), false otherwise. """ checker = __ISBNChecker(input_string, normalize) return checker.is_isbn_13() or checker.is_isbn_10() def is_number(input_string: str) -> bool: """ Checks if a string is a valid number. The number can be a signed (eg: +1, -2, -3.3) or unsigned (eg: 1, 2, 3.3) integer or double or use the "scientific notation" (eg: 1e5). *Examples:* >>> is_number('42') # returns true >>> is_number('19.99') # returns true >>> is_number('-9.12') # returns true >>> is_number('1e3') # returns true >>> is_number('1 2 3') # returns false :param input_string: String to check :type input_string: str :return: True if the string represents a number, false otherwise """ if not isinstance(input_string, str): raise InvalidInputError(input_string) return NUMBER_RE.match(input_string) is not None def is_slug(input_string: Any, separator: str = '-') -> bool: """ Checks if a given string is a slug (as created by `slugify()`). *Examples:* >>> is_slug('my-blog-post-title') # returns true >>> is_slug('My blog post title') # returns false :param input_string: String to check. :type input_string: str :param separator: Join sign used by the slug. :type separator: str :return: True if slug, false otherwise. """ if not is_full_string(input_string): return False rex = r'^([a-z\d]+' + re.escape(separator) + r'*?)*[a-z\d]$' return re.match(rex, input_string) is not None def is_decimal(input_string: str) -> bool: """ Checks whether the given string represents a decimal or not. A decimal may be signed or unsigned or use a "scientific notation". >>> is_decimal('42.0') # returns true >>> is_decimal('42') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' in input_string def is_ip(input_string: Any) -> bool: """ Checks if a string is a valid ip (either v4 or v6). *Examples:* >>> is_ip('255.200.100.75') # returns true >>> is_ip('2001:db8:85a3:0000:0000:8a2e:370:7334') # returns true >>> is_ip('1.2.3') # returns false :param input_string: String to check. :type input_string: str :return: True if an ip, false otherwise. """ return is_ip_v6(input_string) or is_ip_v4(input_string) def contains_html(input_string: str) -> bool: """ Checks if the given string contains HTML/XML tags. By design, this function matches ANY type of tag, so don't expect to use it as an HTML validator, its goal is to detect "malicious" or undesired tags in the text. *Examples:* >>> contains_html('my string is <strong>bold</strong>') # returns true >>> contains_html('my string is not bold') # returns false :param input_string: Text to check :type input_string: str :return: True if string contains html, false otherwise. """ if not is_string(input_string): raise InvalidInputError(input_string) return HTML_RE.search(input_string) is not None Based on the information above, please complete the function in the current file: def is_url(input_string: Any, allowed_schemes: Optional[List[str]] = None) -> bool: """ Check if a string is a valid url. *Examples:* >>> is_url('http://www.mysite.com') # returns true >>> is_url('https://mysite.com') # returns true >>> is_url('.mysite.com') # returns false :param input_string: String to check. :type input_string: str :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid). :type allowed_schemes: Optional[List[str]] :return: True if url, false otherwise """
19
You are a Python programmer working with a repository. Here is all the context you may find useful to complete the function: #FILE: python-string-utils/string_utils/errors.py class InvalidInputError(TypeError): """ Custom error raised when received object is not a string as expected. """ def __init__(self, input_data: Any): """ :param input_data: Any received object """ type_name = type(input_data).__name__ msg = 'Expected "str", received "{}"'.format(type_name) super().__init__(msg) #FILE: python-string-utils/string_utils/_regex.py EMAIL_RE = re.compile(r'^{}$'.format(EMAILS_RAW_STRING)) #CURRENT FILE: python-string-utils/string_utils/validation.py import json import string from typing import Any, Optional, List from ._regex import * from .errors import InvalidInputError def is_email(input_string: Any) -> bool: """ Check if a string is a valid email. Reference: https://tools.ietf.org/html/rfc3696#section-3 *Examples:* >>> is_email('my.email@the-provider.com') # returns true >>> is_email('@gmail.com') # returns false :param input_string: String to check. :type input_string: str :return: True if email, false otherwise. """ # first simple "pre check": it must be a non empty string with max len 320 and cannot start with a dot if not is_full_string(input_string) or len(input_string) > 320 or input_string.startswith('.'): return False try: # we expect 2 tokens, one before "@" and one after, otherwise we have an exception and the email is not valid head, tail = input_string.split('@') # head's size must be <= 64, tail <= 255, head must not start with a dot or contain multiple consecutive dots if len(head) > 64 or len(tail) > 255 or head.endswith('.') or ('..' in head): return False # removes escaped spaces, so that later on the test regex will accept the string head = head.replace('\\ ', '') if head.startswith('"') and head.endswith('"'): head = head.replace(' ', '')[1:-1] return EMAIL_RE.match(head + '@' + tail) is not None except ValueError: # borderline case in which we have multiple "@" signs but the head part is correctly escaped if ESCAPED_AT_SIGN.search(input_string) is not None: # replace "@" with "a" in the head return is_email(ESCAPED_AT_SIGN.sub('a', input_string)) return False def is_full_string(input_string: Any) -> bool: """ Check if a string is not empty (it must contains at least one non space character). *Examples:* >>> is_full_string(None) # returns false >>> is_full_string('') # returns false >>> is_full_string(' ') # returns false >>> is_full_string('hello') # returns true :param input_string: String to check. :type input_string: str :return: True if not empty, false otherwise. """ return is_string(input_string) and input_string.strip() != '' def is_integer(input_string: str) -> bool: """ Checks whether the given string represents an integer or not. An integer may be signed or unsigned or use a "scientific notation". *Examples:* >>> is_integer('42') # returns true >>> is_integer('42.0') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' not in input_string def is_json(input_string: Any) -> bool: """ Check if a string is a valid json. *Examples:* >>> is_json('{"name": "Peter"}') # returns true >>> is_json('[1, 2, 3]') # returns true >>> is_json('{nope}') # returns false :param input_string: String to check. :type input_string: str :return: True if json, false otherwise """ if is_full_string(input_string) and JSON_WRAPPER_RE.match(input_string) is not None: try: return isinstance(json.loads(input_string), (dict, list)) except (TypeError, ValueError, OverflowError): pass return False def is_string(obj: Any) -> bool: """ Checks if an object is a string. *Example:* >>> is_string('foo') # returns true >>> is_string(b'foo') # returns false :param obj: Object to test. :return: True if string, false otherwise. """ return isinstance(obj, str) def is_isbn(input_string: str, normalize: bool = True) -> bool: """ Checks if the given string represents a valid ISBN (International Standard Book Number). By default hyphens in the string are ignored, so digits can be separated in different ways, by calling this function with `normalize=False` only digit-only strings will pass the validation. *Examples:* >>> is_isbn('9780312498580') # returns true >>> is_isbn('1506715214') # returns true :param input_string: String to check. :param normalize: True to ignore hyphens ("-") in the string (default), false otherwise. :return: True if valid ISBN (10 or 13), false otherwise. """ checker = __ISBNChecker(input_string, normalize) return checker.is_isbn_13() or checker.is_isbn_10() def is_number(input_string: str) -> bool: """ Checks if a string is a valid number. The number can be a signed (eg: +1, -2, -3.3) or unsigned (eg: 1, 2, 3.3) integer or double or use the "scientific notation" (eg: 1e5). *Examples:* >>> is_number('42') # returns true >>> is_number('19.99') # returns true >>> is_number('-9.12') # returns true >>> is_number('1e3') # returns true >>> is_number('1 2 3') # returns false :param input_string: String to check :type input_string: str :return: True if the string represents a number, false otherwise """ if not isinstance(input_string, str): raise InvalidInputError(input_string) return NUMBER_RE.match(input_string) is not None def is_pangram(input_string: Any) -> bool: """ Checks if the string is a pangram (https://en.wikipedia.org/wiki/Pangram). *Examples:* >>> is_pangram('The quick brown fox jumps over the lazy dog') # returns true >>> is_pangram('hello world') # returns false :param input_string: String to check. :type input_string: str :return: True if the string is a pangram, False otherwise. """ if not is_full_string(input_string): return False return set(SPACES_RE.sub('', input_string)).issuperset(set(string.ascii_lowercase)) def is_ip_v6(input_string: Any) -> bool: """ Checks if a string is a valid ip v6. *Examples:* >>> is_ip_v6('2001:db8:85a3:0000:0000:8a2e:370:7334') # returns true >>> is_ip_v6('2001:db8:85a3:0000:0000:8a2e:370:?') # returns false (invalid "?") :param input_string: String to check. :type input_string: str :return: True if a v6 ip, false otherwise. """ return is_full_string(input_string) and IP_V6_RE.match(input_string) is not None def is_snake_case(input_string: Any, separator: str = '_') -> bool: """ Checks if a string is formatted as "snake case". A string is considered snake case when: - it's composed only by lowercase/uppercase letters and digits - it contains at least one underscore (or provided separator) - it does not start with a number *Examples:* >>> is_snake_case('foo_bar_baz') # returns true >>> is_snake_case('foo') # returns false :param input_string: String to test. :type input_string: str :param separator: String to use as separator. :type separator: str :return: True for a snake case string, false otherwise. """ if is_full_string(input_string): re_map = { '_': SNAKE_CASE_TEST_RE, '-': SNAKE_CASE_TEST_DASH_RE } re_template = r'([a-z]+\d*{sign}[a-z\d{sign}]*|{sign}+[a-z\d]+[a-z\d{sign}]*)' r = re_map.get( separator, re.compile(re_template.format(sign=re.escape(separator)), re.IGNORECASE) ) return r.match(input_string) is not None return False def is_url(input_string: Any, allowed_schemes: Optional[List[str]] = None) -> bool: """ Check if a string is a valid url. *Examples:* >>> is_url('http://www.mysite.com') # returns true >>> is_url('https://mysite.com') # returns true >>> is_url('.mysite.com') # returns false :param input_string: String to check. :type input_string: str :param allowed_schemes: List of valid schemes ('http', 'https', 'ftp'...). Default to None (any scheme is valid). :type allowed_schemes: Optional[List[str]] :return: True if url, false otherwise """ if not is_full_string(input_string): return False valid = URL_RE.match(input_string) is not None if allowed_schemes: return valid and any([input_string.startswith(s) for s in allowed_schemes]) return valid def is_decimal(input_string: str) -> bool: """ Checks whether the given string represents a decimal or not. A decimal may be signed or unsigned or use a "scientific notation". >>> is_decimal('42.0') # returns true >>> is_decimal('42') # returns false :param input_string: String to check :type input_string: str :return: True if integer, false otherwise """ return is_number(input_string) and '.' in input_string def is_palindrome(input_string: Any, ignore_spaces: bool = False, ignore_case: bool = False) -> bool: """ Checks if the string is a palindrome (https://en.wikipedia.org/wiki/Palindrome). *Examples:* >>> is_palindrome('LOL') # returns true >>> is_palindrome('Lol') # returns false >>> is_palindrome('Lol', ignore_case=True) # returns true >>> is_palindrome('ROTFL') # returns false :param input_string: String to check. :type input_string: str :param ignore_spaces: False if white spaces matter (default), true otherwise. :type ignore_spaces: bool :param ignore_case: False if char case matters (default), true otherwise. :type ignore_case: bool :return: True if the string is a palindrome (like "otto", or "i topi non avevano nipoti" if strict=False),\ False otherwise """ if not is_full_string(input_string): return False if ignore_spaces: input_string = SPACES_RE.sub('', input_string) string_len = len(input_string) # Traverse the string one char at step, and for each step compares the # "head_char" (the one on the left of the string) to the "tail_char" (the one on the right). # In this way we avoid to manipulate the whole string in advance if not necessary and provide a faster # algorithm which can scale very well for long strings. for index in range(string_len): head_char = input_string[index] tail_char = input_string[string_len - index - 1] if ignore_case: head_char = head_char.lower() tail_char = tail_char.lower() if head_char != tail_char: return False return True def is_ip(input_string: Any) -> bool: """ Checks if a string is a valid ip (either v4 or v6). *Examples:* >>> is_ip('255.200.100.75') # returns true >>> is_ip('2001:db8:85a3:0000:0000:8a2e:370:7334') # returns true >>> is_ip('1.2.3') # returns false :param input_string: String to check. :type input_string: str :return: True if an ip, false otherwise. """ return is_ip_v6(input_string) or is_ip_v4(input_string) def is_ip_v4(input_string: Any) -> bool: """ Checks if a string is a valid ip v4. *Examples:* >>> is_ip_v4('255.200.100.75') # returns true >>> is_ip_v4('nope') # returns false (not an ip) >>> is_ip_v4('255.200.100.999') # returns false (999 is out of range) :param input_string: String to check. :type input_string: str :return: True if an ip v4, false otherwise. """ if not is_full_string(input_string) or SHALLOW_IP_V4_RE.match(input_string) is None: return False # checks that each entry in the ip is in the valid range (0 to 255) for token in input_string.split('.'): if not (0 <= int(token) <= 255): return False return True def contains_html(input_string: str) -> bool: """ Checks if the given string contains HTML/XML tags. By design, this function matches ANY type of tag, so don't expect to use it as an HTML validator, its goal is to detect "malicious" or undesired tags in the text. *Examples:* >>> contains_html('my string is <strong>bold</strong>') # returns true >>> contains_html('my string is not bold') # returns false :param input_string: Text to check :type input_string: str :return: True if string contains html, false otherwise. """ if not is_string(input_string): raise InvalidInputError(input_string) return HTML_RE.search(input_string) is not None def words_count(input_string: str) -> int: """ Returns the number of words contained into the given string. This method is smart, it does consider only sequence of one or more letter and/or numbers as "words", so a string like this: "! @ # % ... []" will return zero! Moreover it is aware of punctuation, so the count for a string like "one,two,three.stop" will be 4 not 1 (even if there are no spaces in the string). *Examples:* >>> words_count('hello world') # returns 2 >>> words_count('one,two,three.stop') # returns 4 :param input_string: String to check. :type input_string: str :return: Number of words. """ if not is_string(input_string): raise InvalidInputError(input_string) return len(WORDS_COUNT_RE.findall(input_string)) Based on the information above, please complete the function in the current file: def is_email(input_string: Any) -> bool: """ Check if a string is a valid email. Reference: https://tools.ietf.org/html/rfc3696#section-3 *Examples:* >>> is_email('my.email@the-provider.com') # returns true >>> is_email('@gmail.com') # returns false :param input_string: String to check. :type input_string: str :return: True if email, false otherwise. """
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
12