repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
ntoll/uflash
uflash.py
flash
def flash(path_to_python=None, paths_to_microbits=None, path_to_runtime=None, python_script=None, minify=False): """ Given a path to or source of a Python file will attempt to create a hex file and then flash it onto the referenced BBC micro:bit. If the path_to_python & python_script are unsp...
python
def flash(path_to_python=None, paths_to_microbits=None, path_to_runtime=None, python_script=None, minify=False): """ Given a path to or source of a Python file will attempt to create a hex file and then flash it onto the referenced BBC micro:bit. If the path_to_python & python_script are unsp...
[ "def", "flash", "(", "path_to_python", "=", "None", ",", "paths_to_microbits", "=", "None", ",", "path_to_runtime", "=", "None", ",", "python_script", "=", "None", ",", "minify", "=", "False", ")", ":", "# Check for the correct version of Python.", "if", "not", ...
Given a path to or source of a Python file will attempt to create a hex file and then flash it onto the referenced BBC micro:bit. If the path_to_python & python_script are unspecified it will simply flash the unmodified MicroPython runtime onto the device. If used, the python_script argument should be...
[ "Given", "a", "path", "to", "or", "source", "of", "a", "Python", "file", "will", "attempt", "to", "create", "a", "hex", "file", "and", "then", "flash", "it", "onto", "the", "referenced", "BBC", "micro", ":", "bit", "." ]
train
https://github.com/ntoll/uflash/blob/867468d386da0aa20212b69a152ce8bfc0972366/uflash.py#L284-L341
ntoll/uflash
uflash.py
extract
def extract(path_to_hex, output_path=None): """ Given a path_to_hex file this function will attempt to extract the embedded script from it and save it either to output_path or stdout """ with open(path_to_hex, 'r') as hex_file: python_script = extract_script(hex_file.read()) if outpu...
python
def extract(path_to_hex, output_path=None): """ Given a path_to_hex file this function will attempt to extract the embedded script from it and save it either to output_path or stdout """ with open(path_to_hex, 'r') as hex_file: python_script = extract_script(hex_file.read()) if outpu...
[ "def", "extract", "(", "path_to_hex", ",", "output_path", "=", "None", ")", ":", "with", "open", "(", "path_to_hex", ",", "'r'", ")", "as", "hex_file", ":", "python_script", "=", "extract_script", "(", "hex_file", ".", "read", "(", ")", ")", "if", "outpu...
Given a path_to_hex file this function will attempt to extract the embedded script from it and save it either to output_path or stdout
[ "Given", "a", "path_to_hex", "file", "this", "function", "will", "attempt", "to", "extract", "the", "embedded", "script", "from", "it", "and", "save", "it", "either", "to", "output_path", "or", "stdout" ]
train
https://github.com/ntoll/uflash/blob/867468d386da0aa20212b69a152ce8bfc0972366/uflash.py#L344-L355
ntoll/uflash
uflash.py
watch_file
def watch_file(path, func, *args, **kwargs): """ Watch a file for changes by polling its last modification time. Call the provided function with *args and **kwargs upon modification. """ if not path: raise ValueError('Please specify a file to watch') print('Watching "{}" for changes'.for...
python
def watch_file(path, func, *args, **kwargs): """ Watch a file for changes by polling its last modification time. Call the provided function with *args and **kwargs upon modification. """ if not path: raise ValueError('Please specify a file to watch') print('Watching "{}" for changes'.for...
[ "def", "watch_file", "(", "path", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "path", ":", "raise", "ValueError", "(", "'Please specify a file to watch'", ")", "print", "(", "'Watching \"{}\" for changes'", ".", "format", "...
Watch a file for changes by polling its last modification time. Call the provided function with *args and **kwargs upon modification.
[ "Watch", "a", "file", "for", "changes", "by", "polling", "its", "last", "modification", "time", ".", "Call", "the", "provided", "function", "with", "*", "args", "and", "**", "kwargs", "upon", "modification", "." ]
train
https://github.com/ntoll/uflash/blob/867468d386da0aa20212b69a152ce8bfc0972366/uflash.py#L358-L376
ntoll/uflash
uflash.py
main
def main(argv=None): """ Entry point for the command line tool 'uflash'. Will print help text if the optional first argument is "help". Otherwise it will ensure the optional first argument ends in ".py" (the source Python script). An optional second argument is used to reference the path to th...
python
def main(argv=None): """ Entry point for the command line tool 'uflash'. Will print help text if the optional first argument is "help". Otherwise it will ensure the optional first argument ends in ".py" (the source Python script). An optional second argument is used to reference the path to th...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "not", "argv", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "_HELP_TEXT", ")", "parser", ".", "add_argume...
Entry point for the command line tool 'uflash'. Will print help text if the optional first argument is "help". Otherwise it will ensure the optional first argument ends in ".py" (the source Python script). An optional second argument is used to reference the path to the micro:bit device. Any more ...
[ "Entry", "point", "for", "the", "command", "line", "tool", "uflash", "." ]
train
https://github.com/ntoll/uflash/blob/867468d386da0aa20212b69a152ce8bfc0972366/uflash.py#L379-L452
MartinThoma/mpu
mpu/decorators.py
timing
def timing(func): """Measure the execution time of a function call and print the result.""" @functools.wraps(func) def wrap(*args, **kw): t0 = time() result = func(*args, **kw) t1 = time() print('func:%r args:[%r, %r] took: %2.4f sec' % (func.__name__, args, kw,...
python
def timing(func): """Measure the execution time of a function call and print the result.""" @functools.wraps(func) def wrap(*args, **kw): t0 = time() result = func(*args, **kw) t1 = time() print('func:%r args:[%r, %r] took: %2.4f sec' % (func.__name__, args, kw,...
[ "def", "timing", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrap", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "t0", "=", "time", "(", ")", "result", "=", "func", "(", "*", "args", ",", "*", "*", "...
Measure the execution time of a function call and print the result.
[ "Measure", "the", "execution", "time", "of", "a", "function", "call", "and", "print", "the", "result", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/decorators.py#L13-L23
MartinThoma/mpu
mpu/decorators.py
deprecated
def deprecated(func): """ Mark functions as deprecated. It will result in a warning being emitted when the function is used. """ @functools.wraps(func) def new_func(*args, **kwargs): if sys.version_info < (3, 0): warnings.warn_explicit( "Call to deprecated fu...
python
def deprecated(func): """ Mark functions as deprecated. It will result in a warning being emitted when the function is used. """ @functools.wraps(func) def new_func(*args, **kwargs): if sys.version_info < (3, 0): warnings.warn_explicit( "Call to deprecated fu...
[ "def", "deprecated", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "warnings",...
Mark functions as deprecated. It will result in a warning being emitted when the function is used.
[ "Mark", "functions", "as", "deprecated", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/decorators.py#L26-L49
MartinThoma/mpu
mpu/units/__init__.py
get_currency
def get_currency(currency_str): """ Convert an identifier for a currency into a currency object. Parameters ---------- currency_str : str Returns ------- currency : Currency """ path = 'units/currencies.csv' # always use slash in Python packages filepath = pkg_resources.re...
python
def get_currency(currency_str): """ Convert an identifier for a currency into a currency object. Parameters ---------- currency_str : str Returns ------- currency : Currency """ path = 'units/currencies.csv' # always use slash in Python packages filepath = pkg_resources.re...
[ "def", "get_currency", "(", "currency_str", ")", ":", "path", "=", "'units/currencies.csv'", "# always use slash in Python packages", "filepath", "=", "pkg_resources", ".", "resource_filename", "(", "'mpu'", ",", "path", ")", "with", "open", "(", "filepath", ",", "'...
Convert an identifier for a currency into a currency object. Parameters ---------- currency_str : str Returns ------- currency : Currency
[ "Convert", "an", "identifier", "for", "a", "currency", "into", "a", "currency", "object", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/units/__init__.py#L236-L278
MartinThoma/mpu
mpu/units/__init__.py
Currency.from_json
def from_json(cls, json): """Create a Currency object from a JSON dump.""" obj = cls(name=json['name'], code=json['code'], numeric_code=json['numeric_code'], symbol=json['symbol'], exponent=json['exponent'], entiti...
python
def from_json(cls, json): """Create a Currency object from a JSON dump.""" obj = cls(name=json['name'], code=json['code'], numeric_code=json['numeric_code'], symbol=json['symbol'], exponent=json['exponent'], entiti...
[ "def", "from_json", "(", "cls", ",", "json", ")", ":", "obj", "=", "cls", "(", "name", "=", "json", "[", "'name'", "]", ",", "code", "=", "json", "[", "'code'", "]", ",", "numeric_code", "=", "json", "[", "'numeric_code'", "]", ",", "symbol", "=", ...
Create a Currency object from a JSON dump.
[ "Create", "a", "Currency", "object", "from", "a", "JSON", "dump", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/units/__init__.py#L348-L358
MartinThoma/mpu
mpu/shell.py
print_table
def print_table(table): """ Print as a table. I recommend looking at [`tabulate`](https://pypi.org/project/tabulate/). Parameters ---------- table : list Examples -------- >>> print_table([[1, 2, 3], [41, 0, 1]]) 1 2 3 41 0 1 """ table = [[str(cell) for cell i...
python
def print_table(table): """ Print as a table. I recommend looking at [`tabulate`](https://pypi.org/project/tabulate/). Parameters ---------- table : list Examples -------- >>> print_table([[1, 2, 3], [41, 0, 1]]) 1 2 3 41 0 1 """ table = [[str(cell) for cell i...
[ "def", "print_table", "(", "table", ")", ":", "table", "=", "[", "[", "str", "(", "cell", ")", "for", "cell", "in", "row", "]", "for", "row", "in", "table", "]", "column_widths", "=", "[", "len", "(", "cell", ")", "for", "cell", "in", "table", "[...
Print as a table. I recommend looking at [`tabulate`](https://pypi.org/project/tabulate/). Parameters ---------- table : list Examples -------- >>> print_table([[1, 2, 3], [41, 0, 1]]) 1 2 3 41 0 1
[ "Print", "as", "a", "table", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/shell.py#L66-L93
MartinThoma/mpu
mpu/string.py
is_email
def is_email(potential_email_address): """ Check if potential_email_address is a valid e-mail address. Please note that this function has no false-negatives but many false-positives. So if it returns that the input is not a valid e-mail adress, it certainly isn't. If it returns True, it might still...
python
def is_email(potential_email_address): """ Check if potential_email_address is a valid e-mail address. Please note that this function has no false-negatives but many false-positives. So if it returns that the input is not a valid e-mail adress, it certainly isn't. If it returns True, it might still...
[ "def", "is_email", "(", "potential_email_address", ")", ":", "context", ",", "mail", "=", "parseaddr", "(", "potential_email_address", ")", "first_condition", "=", "len", "(", "context", ")", "==", "0", "and", "len", "(", "mail", ")", "!=", "0", "dot_after_a...
Check if potential_email_address is a valid e-mail address. Please note that this function has no false-negatives but many false-positives. So if it returns that the input is not a valid e-mail adress, it certainly isn't. If it returns True, it might still be invalid. For example, the domain could not ...
[ "Check", "if", "potential_email_address", "is", "a", "valid", "e", "-", "mail", "address", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/string.py#L19-L53
MartinThoma/mpu
mpu/string.py
str2bool
def str2bool(string_, default='raise'): """ Convert a string to a bool. Parameters ---------- string_ : str default : {'raise', False} Default behaviour if none of the "true" strings is detected. Returns ------- boolean : bool Examples -------- >>> str2bool('Tr...
python
def str2bool(string_, default='raise'): """ Convert a string to a bool. Parameters ---------- string_ : str default : {'raise', False} Default behaviour if none of the "true" strings is detected. Returns ------- boolean : bool Examples -------- >>> str2bool('Tr...
[ "def", "str2bool", "(", "string_", ",", "default", "=", "'raise'", ")", ":", "true", "=", "[", "'true'", ",", "'t'", ",", "'1'", ",", "'y'", ",", "'yes'", ",", "'enabled'", ",", "'enable'", ",", "'on'", "]", "false", "=", "[", "'false'", ",", "'f'"...
Convert a string to a bool. Parameters ---------- string_ : str default : {'raise', False} Default behaviour if none of the "true" strings is detected. Returns ------- boolean : bool Examples -------- >>> str2bool('True') True >>> str2bool('1') True >>>...
[ "Convert", "a", "string", "to", "a", "bool", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/string.py#L124-L155
MartinThoma/mpu
mpu/string.py
str2bool_or_none
def str2bool_or_none(string_, default='raise'): """ Convert a string to a bool or to None. Parameters ---------- string_ : str default : {'raise', False} Default behaviour if none of the "true" or "none" strings is detected. Returns ------- bool_or_none : bool or None ...
python
def str2bool_or_none(string_, default='raise'): """ Convert a string to a bool or to None. Parameters ---------- string_ : str default : {'raise', False} Default behaviour if none of the "true" or "none" strings is detected. Returns ------- bool_or_none : bool or None ...
[ "def", "str2bool_or_none", "(", "string_", ",", "default", "=", "'raise'", ")", ":", "if", "is_none", "(", "string_", ",", "default", "=", "False", ")", ":", "return", "None", "else", ":", "return", "str2bool", "(", "string_", ",", "default", ")" ]
Convert a string to a bool or to None. Parameters ---------- string_ : str default : {'raise', False} Default behaviour if none of the "true" or "none" strings is detected. Returns ------- bool_or_none : bool or None Examples -------- >>> str2bool_or_none('True') T...
[ "Convert", "a", "string", "to", "a", "bool", "or", "to", "None", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/string.py#L186-L213
MartinThoma/mpu
mpu/string.py
is_none
def is_none(string_, default='raise'): """ Check if a string is equivalent to None. Parameters ---------- string_ : str default : {'raise', False} Default behaviour if none of the "None" strings is detected. Returns ------- is_none : bool Examples -------- >>> ...
python
def is_none(string_, default='raise'): """ Check if a string is equivalent to None. Parameters ---------- string_ : str default : {'raise', False} Default behaviour if none of the "None" strings is detected. Returns ------- is_none : bool Examples -------- >>> ...
[ "def", "is_none", "(", "string_", ",", "default", "=", "'raise'", ")", ":", "none", "=", "[", "'none'", ",", "'undefined'", ",", "'unknown'", ",", "'null'", ",", "''", "]", "if", "string_", ".", "lower", "(", ")", "in", "none", ":", "return", "True",...
Check if a string is equivalent to None. Parameters ---------- string_ : str default : {'raise', False} Default behaviour if none of the "None" strings is detected. Returns ------- is_none : bool Examples -------- >>> is_none('2', default=False) False >>> is_no...
[ "Check", "if", "a", "string", "is", "equivalent", "to", "None", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/string.py#L266-L294
MartinThoma/mpu
mpu/string.py
is_iban
def is_iban(potential_iban): """ Check if a string is a valid IBAN number. IBAN is described in ISO 13616-1:2007 Part 1. Spaces are ignored. # CODE 0 = always zero b = BIC or National Bank code c = Account number i = holder's kennitala (national identification number) k = IBAN...
python
def is_iban(potential_iban): """ Check if a string is a valid IBAN number. IBAN is described in ISO 13616-1:2007 Part 1. Spaces are ignored. # CODE 0 = always zero b = BIC or National Bank code c = Account number i = holder's kennitala (national identification number) k = IBAN...
[ "def", "is_iban", "(", "potential_iban", ")", ":", "path", "=", "'data/iban.csv'", "# always use slash in Python packages", "filepath", "=", "pkg_resources", ".", "resource_filename", "(", "'mpu'", ",", "path", ")", "data", "=", "mpu", ".", "io", ".", "read", "(...
Check if a string is a valid IBAN number. IBAN is described in ISO 13616-1:2007 Part 1. Spaces are ignored. # CODE 0 = always zero b = BIC or National Bank code c = Account number i = holder's kennitala (national identification number) k = IBAN check digits n = Branch number t...
[ "Check", "if", "a", "string", "is", "a", "valid", "IBAN", "number", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/string.py#L297-L346
MartinThoma/mpu
mpu/string.py
_calculate_german_iban_checksum
def _calculate_german_iban_checksum(iban, iban_fields='DEkkbbbbbbbbcccccccccc'): """ Calculate the checksam of the German IBAN format. Examples -------- >>> iban = 'DE41500105170123456789' >>> _calculate_german_iban_checksum(iban) '41' """ ...
python
def _calculate_german_iban_checksum(iban, iban_fields='DEkkbbbbbbbbcccccccccc'): """ Calculate the checksam of the German IBAN format. Examples -------- >>> iban = 'DE41500105170123456789' >>> _calculate_german_iban_checksum(iban) '41' """ ...
[ "def", "_calculate_german_iban_checksum", "(", "iban", ",", "iban_fields", "=", "'DEkkbbbbbbbbcccccccccc'", ")", ":", "number", "=", "[", "value", "for", "field_type", ",", "value", "in", "zip", "(", "iban_fields", ",", "iban", ")", "if", "field_type", "in", "...
Calculate the checksam of the German IBAN format. Examples -------- >>> iban = 'DE41500105170123456789' >>> _calculate_german_iban_checksum(iban) '41'
[ "Calculate", "the", "checksam", "of", "the", "German", "IBAN", "format", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/string.py#L349-L373
MartinThoma/mpu
mpu/string.py
human_readable_bytes
def human_readable_bytes(nb_bytes, suffix='B'): """ Convert a byte number into a human readable format. Parameters ---------- nb_bytes : number suffix : str, optional (default: "B") Returns ------- size_str : str Examples -------- >>> human_readable_bytes(123) '123...
python
def human_readable_bytes(nb_bytes, suffix='B'): """ Convert a byte number into a human readable format. Parameters ---------- nb_bytes : number suffix : str, optional (default: "B") Returns ------- size_str : str Examples -------- >>> human_readable_bytes(123) '123...
[ "def", "human_readable_bytes", "(", "nb_bytes", ",", "suffix", "=", "'B'", ")", ":", "for", "unit", "in", "[", "''", ",", "'Ki'", ",", "'Mi'", ",", "'Gi'", ",", "'Ti'", ",", "'Pi'", ",", "'Ei'", ",", "'Zi'", "]", ":", "if", "abs", "(", "nb_bytes", ...
Convert a byte number into a human readable format. Parameters ---------- nb_bytes : number suffix : str, optional (default: "B") Returns ------- size_str : str Examples -------- >>> human_readable_bytes(123) '123.0 B' >>> human_readable_bytes(1025) '1.0 KiB' ...
[ "Convert", "a", "byte", "number", "into", "a", "human", "readable", "format", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/string.py#L376-L404
MartinThoma/mpu
mpu/aws.py
list_files
def list_files(bucket, profile_name=None): """ List up to 1000 files in a bucket. Parameters ---------- bucket : str profile_name : str, optional AWS profile Returns ------- s3_paths : List[str] """ session = boto3.Session(profile_name=profile_name) conn = sessi...
python
def list_files(bucket, profile_name=None): """ List up to 1000 files in a bucket. Parameters ---------- bucket : str profile_name : str, optional AWS profile Returns ------- s3_paths : List[str] """ session = boto3.Session(profile_name=profile_name) conn = sessi...
[ "def", "list_files", "(", "bucket", ",", "profile_name", "=", "None", ")", ":", "session", "=", "boto3", ".", "Session", "(", "profile_name", "=", "profile_name", ")", "conn", "=", "session", ".", "client", "(", "'s3'", ")", "keys", "=", "[", "]", "ret...
List up to 1000 files in a bucket. Parameters ---------- bucket : str profile_name : str, optional AWS profile Returns ------- s3_paths : List[str]
[ "List", "up", "to", "1000", "files", "in", "a", "bucket", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/aws.py#L15-L41
MartinThoma/mpu
mpu/aws.py
s3_read
def s3_read(source, profile_name=None): """ Read a file from an S3 source. Parameters ---------- source : str Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar' profile_name : str, optional AWS profile Returns ------- content : bytes Raises -----...
python
def s3_read(source, profile_name=None): """ Read a file from an S3 source. Parameters ---------- source : str Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar' profile_name : str, optional AWS profile Returns ------- content : bytes Raises -----...
[ "def", "s3_read", "(", "source", ",", "profile_name", "=", "None", ")", ":", "session", "=", "boto3", ".", "Session", "(", "profile_name", "=", "profile_name", ")", "s3", "=", "session", ".", "client", "(", "'s3'", ")", "bucket_name", ",", "key", "=", ...
Read a file from an S3 source. Parameters ---------- source : str Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar' profile_name : str, optional AWS profile Returns ------- content : bytes Raises ------ botocore.exceptions.NoCredentialsError ...
[ "Read", "a", "file", "from", "an", "S3", "source", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/aws.py#L44-L72
MartinThoma/mpu
mpu/aws.py
s3_download
def s3_download(source, destination, exists_strategy=ExistsStrategy.RAISE, profile_name=None): """ Copy a file from an S3 source to a local destination. Parameters ---------- source : str Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar' desti...
python
def s3_download(source, destination, exists_strategy=ExistsStrategy.RAISE, profile_name=None): """ Copy a file from an S3 source to a local destination. Parameters ---------- source : str Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar' desti...
[ "def", "s3_download", "(", "source", ",", "destination", ",", "exists_strategy", "=", "ExistsStrategy", ".", "RAISE", ",", "profile_name", "=", "None", ")", ":", "if", "not", "isinstance", "(", "exists_strategy", ",", "ExistsStrategy", ")", ":", "raise", "Valu...
Copy a file from an S3 source to a local destination. Parameters ---------- source : str Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar' destination : str exists_strategy : {'raise', 'replace', 'abort'} What is done when the destination already exists? * `Exist...
[ "Copy", "a", "file", "from", "an", "S3", "source", "to", "a", "local", "destination", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/aws.py#L83-L122
MartinThoma/mpu
mpu/aws.py
s3_upload
def s3_upload(source, destination, profile_name=None): """ Copy a file from a local source to an S3 destination. Parameters ---------- source : str destination : str Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar' profile_name : str, optional AWS profile ""...
python
def s3_upload(source, destination, profile_name=None): """ Copy a file from a local source to an S3 destination. Parameters ---------- source : str destination : str Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar' profile_name : str, optional AWS profile ""...
[ "def", "s3_upload", "(", "source", ",", "destination", ",", "profile_name", "=", "None", ")", ":", "session", "=", "boto3", ".", "Session", "(", "profile_name", "=", "profile_name", ")", "s3", "=", "session", ".", "resource", "(", "'s3'", ")", "bucket_name...
Copy a file from a local source to an S3 destination. Parameters ---------- source : str destination : str Path starting with s3://, e.g. 's3://bucket-name/key/foo.bar' profile_name : str, optional AWS profile
[ "Copy", "a", "file", "from", "a", "local", "source", "to", "an", "S3", "destination", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/aws.py#L125-L141
MartinThoma/mpu
mpu/aws.py
_s3_path_split
def _s3_path_split(s3_path): """ Split an S3 path into bucket and key. Parameters ---------- s3_path : str Returns ------- splitted : (str, str) (bucket, key) Examples -------- >>> _s3_path_split('s3://my-bucket/foo/bar.jpg') S3Path(bucket_name='my-bucket', key...
python
def _s3_path_split(s3_path): """ Split an S3 path into bucket and key. Parameters ---------- s3_path : str Returns ------- splitted : (str, str) (bucket, key) Examples -------- >>> _s3_path_split('s3://my-bucket/foo/bar.jpg') S3Path(bucket_name='my-bucket', key...
[ "def", "_s3_path_split", "(", "s3_path", ")", ":", "if", "not", "s3_path", ".", "startswith", "(", "'s3://'", ")", ":", "raise", "ValueError", "(", "'s3_path is expected to start with \\'s3://\\', '", "'but was {}'", ".", "format", "(", "s3_path", ")", ")", "bucke...
Split an S3 path into bucket and key. Parameters ---------- s3_path : str Returns ------- splitted : (str, str) (bucket, key) Examples -------- >>> _s3_path_split('s3://my-bucket/foo/bar.jpg') S3Path(bucket_name='my-bucket', key='foo/bar.jpg')
[ "Split", "an", "S3", "path", "into", "bucket", "and", "key", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/aws.py#L147-L170
MartinThoma/mpu
mpu/image.py
get_meta
def get_meta(filepath): """ Get meta-information of an image. Parameters ---------- filepath : str Returns ------- meta : dict """ meta = {} try: from PIL import Image with Image.open(filepath) as img: width, height = img.size meta['width...
python
def get_meta(filepath): """ Get meta-information of an image. Parameters ---------- filepath : str Returns ------- meta : dict """ meta = {} try: from PIL import Image with Image.open(filepath) as img: width, height = img.size meta['width...
[ "def", "get_meta", "(", "filepath", ")", ":", "meta", "=", "{", "}", "try", ":", "from", "PIL", "import", "Image", "with", "Image", ".", "open", "(", "filepath", ")", "as", "img", ":", "width", ",", "height", "=", "img", ".", "size", "meta", "[", ...
Get meta-information of an image. Parameters ---------- filepath : str Returns ------- meta : dict
[ "Get", "meta", "-", "information", "of", "an", "image", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/image.py#L10-L35
MartinThoma/mpu
mpu/datastructures.py
flatten
def flatten(iterable, string_flattening=False): """ Flatten an given iterable of iterables into one list. Parameters ---------- iterable : iterable string_flattening : bool If this is False, then strings are NOT flattened Returns ------- flat_list : List Examples -...
python
def flatten(iterable, string_flattening=False): """ Flatten an given iterable of iterables into one list. Parameters ---------- iterable : iterable string_flattening : bool If this is False, then strings are NOT flattened Returns ------- flat_list : List Examples -...
[ "def", "flatten", "(", "iterable", ",", "string_flattening", "=", "False", ")", ":", "flat_list", "=", "[", "]", "for", "item", "in", "iterable", ":", "is_iterable", "=", "(", "isinstance", "(", "item", ",", "collections", ".", "Iterable", ")", "and", "(...
Flatten an given iterable of iterables into one list. Parameters ---------- iterable : iterable string_flattening : bool If this is False, then strings are NOT flattened Returns ------- flat_list : List Examples -------- >>> flatten([1, [2, [3]]]) [1, 2, 3] >>...
[ "Flatten", "an", "given", "iterable", "of", "iterables", "into", "one", "list", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/datastructures.py#L57-L92
MartinThoma/mpu
mpu/datastructures.py
dict_merge
def dict_merge(dict_left, dict_right, merge_method='take_left_shallow'): """ Merge two dictionaries. This method does NOT modify dict_left or dict_right! Apply this method multiple times if the dictionary is nested. Parameters ---------- dict_left : dict dict_right: dict merge_met...
python
def dict_merge(dict_left, dict_right, merge_method='take_left_shallow'): """ Merge two dictionaries. This method does NOT modify dict_left or dict_right! Apply this method multiple times if the dictionary is nested. Parameters ---------- dict_left : dict dict_right: dict merge_met...
[ "def", "dict_merge", "(", "dict_left", ",", "dict_right", ",", "merge_method", "=", "'take_left_shallow'", ")", ":", "new_dict", "=", "{", "}", "if", "merge_method", "in", "[", "'take_right_shallow'", ",", "'take_right_deep'", "]", ":", "return", "_dict_merge_righ...
Merge two dictionaries. This method does NOT modify dict_left or dict_right! Apply this method multiple times if the dictionary is nested. Parameters ---------- dict_left : dict dict_right: dict merge_method : {'take_left_shallow', 'take_left_deep', \ 'take_right_shall...
[ "Merge", "two", "dictionaries", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/datastructures.py#L95-L170
MartinThoma/mpu
mpu/datastructures.py
_dict_merge_right
def _dict_merge_right(dict_left, dict_right, merge_method): """See documentation of mpu.datastructures.dict_merge.""" new_dict = deepcopy(dict_left) for key, value in dict_right.items(): if key not in new_dict: new_dict[key] = value else: recurse = (merge_method == 't...
python
def _dict_merge_right(dict_left, dict_right, merge_method): """See documentation of mpu.datastructures.dict_merge.""" new_dict = deepcopy(dict_left) for key, value in dict_right.items(): if key not in new_dict: new_dict[key] = value else: recurse = (merge_method == 't...
[ "def", "_dict_merge_right", "(", "dict_left", ",", "dict_right", ",", "merge_method", ")", ":", "new_dict", "=", "deepcopy", "(", "dict_left", ")", "for", "key", ",", "value", "in", "dict_right", ".", "items", "(", ")", ":", "if", "key", "not", "in", "ne...
See documentation of mpu.datastructures.dict_merge.
[ "See", "documentation", "of", "mpu", ".", "datastructures", ".", "dict_merge", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/datastructures.py#L173-L189
MartinThoma/mpu
mpu/datastructures.py
set_dict_value
def set_dict_value(dictionary, keys, value): """ Set a value in a (nested) dictionary by defining a list of keys. .. note:: Side-effects This function does not make a copy of dictionary, but directly edits it. Parameters ---------- dictionary : dict keys : List[...
python
def set_dict_value(dictionary, keys, value): """ Set a value in a (nested) dictionary by defining a list of keys. .. note:: Side-effects This function does not make a copy of dictionary, but directly edits it. Parameters ---------- dictionary : dict keys : List[...
[ "def", "set_dict_value", "(", "dictionary", ",", "keys", ",", "value", ")", ":", "orig", "=", "dictionary", "for", "key", "in", "keys", "[", ":", "-", "1", "]", ":", "dictionary", "=", "dictionary", ".", "setdefault", "(", "key", ",", "{", "}", ")", ...
Set a value in a (nested) dictionary by defining a list of keys. .. note:: Side-effects This function does not make a copy of dictionary, but directly edits it. Parameters ---------- dictionary : dict keys : List[Any] value : object Returns ------- dict...
[ "Set", "a", "value", "in", "a", "(", "nested", ")", "dictionary", "by", "defining", "a", "list", "of", "keys", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/datastructures.py#L192-L221
MartinThoma/mpu
mpu/datastructures.py
does_keychain_exist
def does_keychain_exist(dict_, list_): """ Check if a sequence of keys exist in a nested dictionary. Parameters ---------- dict_ : Dict[str/int/tuple, Any] list_ : List[str/int/tuple] Returns ------- keychain_exists : bool Examples -------- >>> d = {'a': {'b': {'c': 'd...
python
def does_keychain_exist(dict_, list_): """ Check if a sequence of keys exist in a nested dictionary. Parameters ---------- dict_ : Dict[str/int/tuple, Any] list_ : List[str/int/tuple] Returns ------- keychain_exists : bool Examples -------- >>> d = {'a': {'b': {'c': 'd...
[ "def", "does_keychain_exist", "(", "dict_", ",", "list_", ")", ":", "for", "key", "in", "list_", ":", "if", "key", "not", "in", "dict_", ":", "return", "False", "dict_", "=", "dict_", "[", "key", "]", "return", "True" ]
Check if a sequence of keys exist in a nested dictionary. Parameters ---------- dict_ : Dict[str/int/tuple, Any] list_ : List[str/int/tuple] Returns ------- keychain_exists : bool Examples -------- >>> d = {'a': {'b': {'c': 'd'}}} >>> l_exists = ['a', 'b'] >>> does_key...
[ "Check", "if", "a", "sequence", "of", "keys", "exist", "in", "a", "nested", "dictionary", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/datastructures.py#L224-L252
MartinThoma/mpu
mpu/datastructures.py
EList.remove_indices
def remove_indices(self, indices): """ Remove rows by which have the given indices. Parameters ---------- indices : list Returns ------- filtered_list : EList """ new_list = [] for index, element in enumerate(self): if...
python
def remove_indices(self, indices): """ Remove rows by which have the given indices. Parameters ---------- indices : list Returns ------- filtered_list : EList """ new_list = [] for index, element in enumerate(self): if...
[ "def", "remove_indices", "(", "self", ",", "indices", ")", ":", "new_list", "=", "[", "]", "for", "index", ",", "element", "in", "enumerate", "(", "self", ")", ":", "if", "index", "not", "in", "indices", ":", "new_list", ".", "append", "(", "element", ...
Remove rows by which have the given indices. Parameters ---------- indices : list Returns ------- filtered_list : EList
[ "Remove", "rows", "by", "which", "have", "the", "given", "indices", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/datastructures.py#L38-L54
MartinThoma/mpu
mpu/path.py
get_all_files
def get_all_files(root, followlinks=False): """ Get all files within the given root directory. Note that this list is not ordered. Parameters ---------- root : str Path to a directory followlinks : bool, optional (default: False) Returns ------- filepaths : list ...
python
def get_all_files(root, followlinks=False): """ Get all files within the given root directory. Note that this list is not ordered. Parameters ---------- root : str Path to a directory followlinks : bool, optional (default: False) Returns ------- filepaths : list ...
[ "def", "get_all_files", "(", "root", ",", "followlinks", "=", "False", ")", ":", "filepaths", "=", "[", "]", "for", "path", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "root", ",", "followlinks", "=", "followlinks", ")", ":", "for", "name",...
Get all files within the given root directory. Note that this list is not ordered. Parameters ---------- root : str Path to a directory followlinks : bool, optional (default: False) Returns ------- filepaths : list List of absolute paths to files
[ "Get", "all", "files", "within", "the", "given", "root", "directory", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/path.py#L11-L32
MartinThoma/mpu
mpu/path.py
get_from_package
def get_from_package(package_name, path): """ Get the absolute path to a file in a package. Parameters ---------- package_name : str e.g. 'mpu' path : str Path within a package Returns ------- filepath : str """ filepath = pkg_resources.resource_filename(pac...
python
def get_from_package(package_name, path): """ Get the absolute path to a file in a package. Parameters ---------- package_name : str e.g. 'mpu' path : str Path within a package Returns ------- filepath : str """ filepath = pkg_resources.resource_filename(pac...
[ "def", "get_from_package", "(", "package_name", ",", "path", ")", ":", "filepath", "=", "pkg_resources", ".", "resource_filename", "(", "package_name", ",", "path", ")", "return", "os", ".", "path", ".", "abspath", "(", "filepath", ")" ]
Get the absolute path to a file in a package. Parameters ---------- package_name : str e.g. 'mpu' path : str Path within a package Returns ------- filepath : str
[ "Get", "the", "absolute", "path", "to", "a", "file", "in", "a", "package", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/path.py#L35-L51
MartinThoma/mpu
mpu/pd.py
example_df
def example_df(): """Create an example dataframe.""" country_names = ['Germany', 'France', 'Indonesia', 'Ireland', 'Spain', 'Vatican'] population = [82521653, 66991000, 255461700, 4761865, 46549045, None...
python
def example_df(): """Create an example dataframe.""" country_names = ['Germany', 'France', 'Indonesia', 'Ireland', 'Spain', 'Vatican'] population = [82521653, 66991000, 255461700, 4761865, 46549045, None...
[ "def", "example_df", "(", ")", ":", "country_names", "=", "[", "'Germany'", ",", "'France'", ",", "'Indonesia'", ",", "'Ireland'", ",", "'Spain'", ",", "'Vatican'", "]", "population", "=", "[", "82521653", ",", "66991000", ",", "255461700", ",", "4761865", ...
Create an example dataframe.
[ "Create", "an", "example", "dataframe", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/pd.py#L24-L46
MartinThoma/mpu
mpu/pd.py
describe
def describe(df, dtype=None): """ Print a description of a Pandas dataframe. Parameters ---------- df : Pandas.DataFrame dtype : dict Maps column names to types """ if dtype is None: dtype = {} print('Number of datapoints: {datapoints}'.format(datapoints=len(df))) ...
python
def describe(df, dtype=None): """ Print a description of a Pandas dataframe. Parameters ---------- df : Pandas.DataFrame dtype : dict Maps column names to types """ if dtype is None: dtype = {} print('Number of datapoints: {datapoints}'.format(datapoints=len(df))) ...
[ "def", "describe", "(", "df", ",", "dtype", "=", "None", ")", ":", "if", "dtype", "is", "None", ":", "dtype", "=", "{", "}", "print", "(", "'Number of datapoints: {datapoints}'", ".", "format", "(", "datapoints", "=", "len", "(", "df", ")", ")", ")", ...
Print a description of a Pandas dataframe. Parameters ---------- df : Pandas.DataFrame dtype : dict Maps column names to types
[ "Print", "a", "description", "of", "a", "Pandas", "dataframe", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/pd.py#L49-L85
MartinThoma/mpu
mpu/ml.py
indices2one_hot
def indices2one_hot(indices, nb_classes): """ Convert an iterable of indices to one-hot encoded list. You might also be interested in sklearn.preprocessing.OneHotEncoder Parameters ---------- indices : iterable iterable of indices nb_classes : int Number of classes dtyp...
python
def indices2one_hot(indices, nb_classes): """ Convert an iterable of indices to one-hot encoded list. You might also be interested in sklearn.preprocessing.OneHotEncoder Parameters ---------- indices : iterable iterable of indices nb_classes : int Number of classes dtyp...
[ "def", "indices2one_hot", "(", "indices", ",", "nb_classes", ")", ":", "if", "nb_classes", "<", "1", ":", "raise", "ValueError", "(", "'nb_classes={}, but positive number expected'", ".", "format", "(", "nb_classes", ")", ")", "one_hot", "=", "[", "]", "for", ...
Convert an iterable of indices to one-hot encoded list. You might also be interested in sklearn.preprocessing.OneHotEncoder Parameters ---------- indices : iterable iterable of indices nb_classes : int Number of classes dtype : type Returns ------- one_hot : list ...
[ "Convert", "an", "iterable", "of", "indices", "to", "one", "-", "hot", "encoded", "list", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/ml.py#L11-L44
MartinThoma/mpu
mpu/ml.py
one_hot2indices
def one_hot2indices(one_hots): """ Convert an iterable of one-hot encoded targets to a list of indices. Parameters ---------- one_hot : list Returns ------- indices : list Examples -------- >>> one_hot2indices([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) [0, 1, 2] >>> one_h...
python
def one_hot2indices(one_hots): """ Convert an iterable of one-hot encoded targets to a list of indices. Parameters ---------- one_hot : list Returns ------- indices : list Examples -------- >>> one_hot2indices([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) [0, 1, 2] >>> one_h...
[ "def", "one_hot2indices", "(", "one_hots", ")", ":", "indices", "=", "[", "]", "for", "one_hot", "in", "one_hots", ":", "indices", ".", "append", "(", "argmax", "(", "one_hot", ")", ")", "return", "indices" ]
Convert an iterable of one-hot encoded targets to a list of indices. Parameters ---------- one_hot : list Returns ------- indices : list Examples -------- >>> one_hot2indices([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) [0, 1, 2] >>> one_hot2indices([[1, 0], [1, 0], [0, 1]]) [0...
[ "Convert", "an", "iterable", "of", "one", "-", "hot", "encoded", "targets", "to", "a", "list", "of", "indices", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/ml.py#L47-L70
MartinThoma/mpu
mpu/math.py
generate_primes
def generate_primes(): """ Generate an infinite sequence of prime numbers. The algorithm was originally written by David Eppstein, UC Irvine. See: http://code.activestate.com/recipes/117119/ Examples -------- >>> g = generate_primes() >>> next(g) 2 >>> next(g) 3 >>> nex...
python
def generate_primes(): """ Generate an infinite sequence of prime numbers. The algorithm was originally written by David Eppstein, UC Irvine. See: http://code.activestate.com/recipes/117119/ Examples -------- >>> g = generate_primes() >>> next(g) 2 >>> next(g) 3 >>> nex...
[ "def", "generate_primes", "(", ")", ":", "divisors", "=", "{", "}", "# map number to at least one divisor", "candidate", "=", "2", "# next potential prime", "while", "True", ":", "if", "candidate", "in", "divisors", ":", "# candidate is composite. divisors[candidate] is t...
Generate an infinite sequence of prime numbers. The algorithm was originally written by David Eppstein, UC Irvine. See: http://code.activestate.com/recipes/117119/ Examples -------- >>> g = generate_primes() >>> next(g) 2 >>> next(g) 3 >>> next(g) 5
[ "Generate", "an", "infinite", "sequence", "of", "prime", "numbers", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/math.py#L23-L61
MartinThoma/mpu
mpu/math.py
factorize
def factorize(number): """ Get the prime factors of an integer except for 1. Parameters ---------- number : int Returns ------- primes : iterable Examples -------- >>> factorize(-17) [-1, 17] >>> factorize(8) [2, 2, 2] >>> factorize(3**25) [3, 3, 3, 3, ...
python
def factorize(number): """ Get the prime factors of an integer except for 1. Parameters ---------- number : int Returns ------- primes : iterable Examples -------- >>> factorize(-17) [-1, 17] >>> factorize(8) [2, 2, 2] >>> factorize(3**25) [3, 3, 3, 3, ...
[ "def", "factorize", "(", "number", ")", ":", "if", "not", "isinstance", "(", "number", ",", "int", ")", ":", "raise", "ValueError", "(", "'integer expected, but type(number)={}'", ".", "format", "(", "type", "(", "number", ")", ")", ")", "if", "number", "<...
Get the prime factors of an integer except for 1. Parameters ---------- number : int Returns ------- primes : iterable Examples -------- >>> factorize(-17) [-1, 17] >>> factorize(8) [2, 2, 2] >>> factorize(3**25) [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,...
[ "Get", "the", "prime", "factors", "of", "an", "integer", "except", "for", "1", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/math.py#L64-L101
MartinThoma/mpu
mpu/math.py
argmax
def argmax(iterable): """ Find the first index of the biggest value in the iterable. Parameters ---------- iterable : iterable Returns ------- argmax : int Examples -------- >>> argmax([0, 0, 0]) 0 >>> argmax([1, 0, 0]) 0 >>> argmax([0, 1, 0]) 1 >>>...
python
def argmax(iterable): """ Find the first index of the biggest value in the iterable. Parameters ---------- iterable : iterable Returns ------- argmax : int Examples -------- >>> argmax([0, 0, 0]) 0 >>> argmax([1, 0, 0]) 0 >>> argmax([0, 1, 0]) 1 >>>...
[ "def", "argmax", "(", "iterable", ")", ":", "max_value", "=", "None", "max_index", "=", "None", "for", "index", ",", "value", "in", "enumerate", "(", "iterable", ")", ":", "if", "(", "max_value", "is", "None", ")", "or", "max_value", "<", "value", ":",...
Find the first index of the biggest value in the iterable. Parameters ---------- iterable : iterable Returns ------- argmax : int Examples -------- >>> argmax([0, 0, 0]) 0 >>> argmax([1, 0, 0]) 0 >>> argmax([0, 1, 0]) 1 >>> argmax([])
[ "Find", "the", "first", "index", "of", "the", "biggest", "value", "in", "the", "iterable", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/math.py#L152-L180
MartinThoma/mpu
mpu/math.py
round_down
def round_down(x, decimal_places): """ Round a float down to decimal_places. Parameters ---------- x : float decimal_places : int Returns ------- rounded_float : float Examples -------- >>> round_down(1.23456, 3) 1.234 >>> round_down(1.23456, 2) 1.23 ""...
python
def round_down(x, decimal_places): """ Round a float down to decimal_places. Parameters ---------- x : float decimal_places : int Returns ------- rounded_float : float Examples -------- >>> round_down(1.23456, 3) 1.234 >>> round_down(1.23456, 2) 1.23 ""...
[ "def", "round_down", "(", "x", ",", "decimal_places", ")", ":", "from", "math", "import", "floor", "d", "=", "int", "(", "'1'", "+", "(", "'0'", "*", "decimal_places", ")", ")", "return", "floor", "(", "x", "*", "d", ")", "/", "d" ]
Round a float down to decimal_places. Parameters ---------- x : float decimal_places : int Returns ------- rounded_float : float Examples -------- >>> round_down(1.23456, 3) 1.234 >>> round_down(1.23456, 2) 1.23
[ "Round", "a", "float", "down", "to", "decimal_places", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/math.py#L206-L228
MartinThoma/mpu
mpu/datetime.py
add_time
def add_time(datetime_obj, days=0, hours=0, minutes=0, seconds=0): """ Add time to a timezone-aware datetime object. This keeps the timezone correct, even if it changes due to daylight saving time (DST). Parameters ---------- datetime_obj : datetime.datetime days : int hours : int ...
python
def add_time(datetime_obj, days=0, hours=0, minutes=0, seconds=0): """ Add time to a timezone-aware datetime object. This keeps the timezone correct, even if it changes due to daylight saving time (DST). Parameters ---------- datetime_obj : datetime.datetime days : int hours : int ...
[ "def", "add_time", "(", "datetime_obj", ",", "days", "=", "0", ",", "hours", "=", "0", ",", "minutes", "=", "0", ",", "seconds", "=", "0", ")", ":", "seconds", "+=", "minutes", "*", "60", "seconds", "+=", "hours", "*", "60", "**", "2", "seconds", ...
Add time to a timezone-aware datetime object. This keeps the timezone correct, even if it changes due to daylight saving time (DST). Parameters ---------- datetime_obj : datetime.datetime days : int hours : int minutes : int seconds : int Returns ------- datetime : dat...
[ "Add", "time", "to", "a", "timezone", "-", "aware", "datetime", "object", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/datetime.py#L16-L40
MartinThoma/mpu
mpu/datetime.py
generate
def generate(minimum, maximum, local_random=random.Random()): """ Generate a random date. The generated dates are uniformly distributed. Parameters ---------- minimum : datetime object maximum : datetime object local_random : random.Random Returns ------- generated_date : ...
python
def generate(minimum, maximum, local_random=random.Random()): """ Generate a random date. The generated dates are uniformly distributed. Parameters ---------- minimum : datetime object maximum : datetime object local_random : random.Random Returns ------- generated_date : ...
[ "def", "generate", "(", "minimum", ",", "maximum", ",", "local_random", "=", "random", ".", "Random", "(", ")", ")", ":", "if", "not", "(", "minimum", "<", "maximum", ")", ":", "raise", "ValueError", "(", "'{} is not smaller than {}'", ".", "format", "(", ...
Generate a random date. The generated dates are uniformly distributed. Parameters ---------- minimum : datetime object maximum : datetime object local_random : random.Random Returns ------- generated_date : datetime object Examples -------- >>> import random; r = rand...
[ "Generate", "a", "random", "date", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/datetime.py#L43-L79
MartinThoma/mpu
mpu/package/cli.py
run_init
def run_init(args): """ Run project initialization. This will ask the user for input. Parameters ---------- args : argparse named arguments """ root = args.root if root is None: root = '.' root = os.path.abspath(root) project_data = _get_package_data() project_...
python
def run_init(args): """ Run project initialization. This will ask the user for input. Parameters ---------- args : argparse named arguments """ root = args.root if root is None: root = '.' root = os.path.abspath(root) project_data = _get_package_data() project_...
[ "def", "run_init", "(", "args", ")", ":", "root", "=", "args", ".", "root", "if", "root", "is", "None", ":", "root", "=", "'.'", "root", "=", "os", ".", "path", ".", "abspath", "(", "root", ")", "project_data", "=", "_get_package_data", "(", ")", "...
Run project initialization. This will ask the user for input. Parameters ---------- args : argparse named arguments
[ "Run", "project", "initialization", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/package/cli.py#L16-L75
MartinThoma/mpu
mpu/package/cli.py
_multiple_replace
def _multiple_replace(text, search_replace_dict): """ Replace multiple things at once in a text. Parameters ---------- text : str search_replace_dict : dict Returns ------- replaced_text : str Examples -------- >>> d = {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e'} >>> _...
python
def _multiple_replace(text, search_replace_dict): """ Replace multiple things at once in a text. Parameters ---------- text : str search_replace_dict : dict Returns ------- replaced_text : str Examples -------- >>> d = {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e'} >>> _...
[ "def", "_multiple_replace", "(", "text", ",", "search_replace_dict", ")", ":", "# Create a regular expression from all of the dictionary keys", "regex", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "map", "(", "re", ".", "escape", ",", "search_replace_...
Replace multiple things at once in a text. Parameters ---------- text : str search_replace_dict : dict Returns ------- replaced_text : str Examples -------- >>> d = {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'e'} >>> _multiple_replace('abcdefghijklm', d) 'bcdeefghijklm'
[ "Replace", "multiple", "things", "at", "once", "in", "a", "text", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/package/cli.py#L88-L111
MartinThoma/mpu
mpu/package/cli.py
_adjust_template
def _adjust_template(filepath, translate): """ Search and replace contents of a filepath. Parameters ---------- filepath : str translate : dict """ with open(filepath, 'r') as file: filedata = file.read() filedata = _multiple_replace(filedata, translate) with open(file...
python
def _adjust_template(filepath, translate): """ Search and replace contents of a filepath. Parameters ---------- filepath : str translate : dict """ with open(filepath, 'r') as file: filedata = file.read() filedata = _multiple_replace(filedata, translate) with open(file...
[ "def", "_adjust_template", "(", "filepath", ",", "translate", ")", ":", "with", "open", "(", "filepath", ",", "'r'", ")", "as", "file", ":", "filedata", "=", "file", ".", "read", "(", ")", "filedata", "=", "_multiple_replace", "(", "filedata", ",", "tran...
Search and replace contents of a filepath. Parameters ---------- filepath : str translate : dict
[ "Search", "and", "replace", "contents", "of", "a", "filepath", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/package/cli.py#L114-L129
MartinThoma/mpu
mpu/package/cli.py
get_parser
def get_parser(parser=None): """Get parser for mpu.""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter if parser is None: parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) subparsers = parser.add_subpars...
python
def get_parser(parser=None): """Get parser for mpu.""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter if parser is None: parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) subparsers = parser.add_subpars...
[ "def", "get_parser", "(", "parser", "=", "None", ")", ":", "from", "argparse", "import", "ArgumentParser", ",", "ArgumentDefaultsHelpFormatter", "if", "parser", "is", "None", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "__doc__", ",", "formatt...
Get parser for mpu.
[ "Get", "parser", "for", "mpu", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/package/cli.py#L132-L144
MartinThoma/mpu
mpu/__init__.py
parallel_for
def parallel_for(loop_function, parameters, nb_threads=100): """ Execute the loop body in parallel. .. note:: Race-Conditions Executing code in parallel can cause an error class called "race-condition". Parameters ---------- loop_function : Python function which takes a tup...
python
def parallel_for(loop_function, parameters, nb_threads=100): """ Execute the loop body in parallel. .. note:: Race-Conditions Executing code in parallel can cause an error class called "race-condition". Parameters ---------- loop_function : Python function which takes a tup...
[ "def", "parallel_for", "(", "loop_function", ",", "parameters", ",", "nb_threads", "=", "100", ")", ":", "import", "multiprocessing", ".", "pool", "from", "contextlib", "import", "closing", "with", "closing", "(", "multiprocessing", ".", "pool", ".", "ThreadPool...
Execute the loop body in parallel. .. note:: Race-Conditions Executing code in parallel can cause an error class called "race-condition". Parameters ---------- loop_function : Python function which takes a tuple as input parameters : List of tuples Each element here sho...
[ "Execute", "the", "loop", "body", "in", "parallel", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/__init__.py#L16-L37
MartinThoma/mpu
mpu/__init__.py
clip
def clip(number, lowest=None, highest=None): """ Clip a number to a given lowest / highest value. Parameters ---------- number : number lowest : number, optional highest : number, optional Returns ------- clipped_number : number Examples -------- >>> clip(42, lowes...
python
def clip(number, lowest=None, highest=None): """ Clip a number to a given lowest / highest value. Parameters ---------- number : number lowest : number, optional highest : number, optional Returns ------- clipped_number : number Examples -------- >>> clip(42, lowes...
[ "def", "clip", "(", "number", ",", "lowest", "=", "None", ",", "highest", "=", "None", ")", ":", "if", "lowest", "is", "not", "None", ":", "number", "=", "max", "(", "number", ",", "lowest", ")", "if", "highest", "is", "not", "None", ":", "number",...
Clip a number to a given lowest / highest value. Parameters ---------- number : number lowest : number, optional highest : number, optional Returns ------- clipped_number : number Examples -------- >>> clip(42, lowest=0, highest=10) 10
[ "Clip", "a", "number", "to", "a", "given", "lowest", "/", "highest", "value", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/__init__.py#L40-L63
MartinThoma/mpu
mpu/__init__.py
consistent_shuffle
def consistent_shuffle(*lists): """ Shuffle lists consistently. Parameters ---------- *lists Variable length number of lists Returns ------- shuffled_lists : tuple of lists All of the lists are shuffled consistently Examples -------- >>> import mpu, random;...
python
def consistent_shuffle(*lists): """ Shuffle lists consistently. Parameters ---------- *lists Variable length number of lists Returns ------- shuffled_lists : tuple of lists All of the lists are shuffled consistently Examples -------- >>> import mpu, random;...
[ "def", "consistent_shuffle", "(", "*", "lists", ")", ":", "perm", "=", "list", "(", "range", "(", "len", "(", "lists", "[", "0", "]", ")", ")", ")", "random", ".", "shuffle", "(", "perm", ")", "lists", "=", "tuple", "(", "[", "sublist", "[", "ind...
Shuffle lists consistently. Parameters ---------- *lists Variable length number of lists Returns ------- shuffled_lists : tuple of lists All of the lists are shuffled consistently Examples -------- >>> import mpu, random; random.seed(8) >>> mpu.consistent_shuff...
[ "Shuffle", "lists", "consistently", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/__init__.py#L66-L90
MartinThoma/mpu
mpu/__init__.py
haversine_distance
def haversine_distance(origin, destination): """ Calculate the Haversine distance. Parameters ---------- origin : tuple of float (lat, long) destination : tuple of float (lat, long) Returns ------- distance_in_km : float Examples -------- >>> munich = (...
python
def haversine_distance(origin, destination): """ Calculate the Haversine distance. Parameters ---------- origin : tuple of float (lat, long) destination : tuple of float (lat, long) Returns ------- distance_in_km : float Examples -------- >>> munich = (...
[ "def", "haversine_distance", "(", "origin", ",", "destination", ")", ":", "lat1", ",", "lon1", "=", "origin", "lat2", ",", "lon2", "=", "destination", "if", "not", "(", "-", "90.0", "<=", "lat1", "<=", "90", ")", ":", "raise", "ValueError", "(", "'lat1...
Calculate the Haversine distance. Parameters ---------- origin : tuple of float (lat, long) destination : tuple of float (lat, long) Returns ------- distance_in_km : float Examples -------- >>> munich = (48.1372, 11.5756) >>> berlin = (52.5186, 13.4083) ...
[ "Calculate", "the", "Haversine", "distance", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/__init__.py#L161-L210
MartinThoma/mpu
mpu/__init__.py
is_in_intervall
def is_in_intervall(value, min_value, max_value, name='variable'): """ Raise an exception if value is not in an interval. Parameters ---------- value : orderable min_value : orderable max_value : orderable name : str Name of the variable to print in exception. """ if not...
python
def is_in_intervall(value, min_value, max_value, name='variable'): """ Raise an exception if value is not in an interval. Parameters ---------- value : orderable min_value : orderable max_value : orderable name : str Name of the variable to print in exception. """ if not...
[ "def", "is_in_intervall", "(", "value", ",", "min_value", ",", "max_value", ",", "name", "=", "'variable'", ")", ":", "if", "not", "(", "min_value", "<=", "value", "<=", "max_value", ")", ":", "raise", "ValueError", "(", "'{}={} is not in [{}, {}]'", ".", "f...
Raise an exception if value is not in an interval. Parameters ---------- value : orderable min_value : orderable max_value : orderable name : str Name of the variable to print in exception.
[ "Raise", "an", "exception", "if", "value", "is", "not", "in", "an", "interval", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/__init__.py#L213-L227
MartinThoma/mpu
mpu/__init__.py
exception_logging
def exception_logging(exctype, value, tb): """ Log exception by using the root logger. Use it as `sys.excepthook = exception_logging`. Parameters ---------- exctype : type value : NameError tb : traceback """ write_val = {'exception_type': str(exctype), 'messag...
python
def exception_logging(exctype, value, tb): """ Log exception by using the root logger. Use it as `sys.excepthook = exception_logging`. Parameters ---------- exctype : type value : NameError tb : traceback """ write_val = {'exception_type': str(exctype), 'messag...
[ "def", "exception_logging", "(", "exctype", ",", "value", ",", "tb", ")", ":", "write_val", "=", "{", "'exception_type'", ":", "str", "(", "exctype", ")", ",", "'message'", ":", "str", "(", "traceback", ".", "format_tb", "(", "tb", ",", "10", ")", ")",...
Log exception by using the root logger. Use it as `sys.excepthook = exception_logging`. Parameters ---------- exctype : type value : NameError tb : traceback
[ "Log", "exception", "by", "using", "the", "root", "logger", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/__init__.py#L230-L244
MartinThoma/mpu
mpu/__init__.py
Location.latitude
def latitude(self, latitude): """Setter for latiutde.""" if not (-90 <= latitude <= 90): raise ValueError('latitude was {}, but has to be in [-90, 90]' .format(latitude)) self._latitude = latitude
python
def latitude(self, latitude): """Setter for latiutde.""" if not (-90 <= latitude <= 90): raise ValueError('latitude was {}, but has to be in [-90, 90]' .format(latitude)) self._latitude = latitude
[ "def", "latitude", "(", "self", ",", "latitude", ")", ":", "if", "not", "(", "-", "90", "<=", "latitude", "<=", "90", ")", ":", "raise", "ValueError", "(", "'latitude was {}, but has to be in [-90, 90]'", ".", "format", "(", "latitude", ")", ")", "self", "...
Setter for latiutde.
[ "Setter", "for", "latiutde", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/__init__.py#L120-L125
MartinThoma/mpu
mpu/__init__.py
Location.longitude
def longitude(self, longitude): """Setter for longitude.""" if not (-180 <= longitude <= 180): raise ValueError('longitude was {}, but has to be in [-180, 180]' .format(longitude)) self._longitude = longitude
python
def longitude(self, longitude): """Setter for longitude.""" if not (-180 <= longitude <= 180): raise ValueError('longitude was {}, but has to be in [-180, 180]' .format(longitude)) self._longitude = longitude
[ "def", "longitude", "(", "self", ",", "longitude", ")", ":", "if", "not", "(", "-", "180", "<=", "longitude", "<=", "180", ")", ":", "raise", "ValueError", "(", "'longitude was {}, but has to be in [-180, 180]'", ".", "format", "(", "longitude", ")", ")", "s...
Setter for longitude.
[ "Setter", "for", "longitude", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/__init__.py#L128-L133
MartinThoma/mpu
mpu/__init__.py
Location.distance
def distance(self, there): """ Calculate the distance from this location to there. Parameters ---------- there : Location Returns ------- distance_in_m : float """ return haversine_distance((self.latitude, self.longitude), ...
python
def distance(self, there): """ Calculate the distance from this location to there. Parameters ---------- there : Location Returns ------- distance_in_m : float """ return haversine_distance((self.latitude, self.longitude), ...
[ "def", "distance", "(", "self", ",", "there", ")", ":", "return", "haversine_distance", "(", "(", "self", ".", "latitude", ",", "self", ".", "longitude", ")", ",", "(", "there", ".", "latitude", ",", "there", ".", "longitude", ")", ")" ]
Calculate the distance from this location to there. Parameters ---------- there : Location Returns ------- distance_in_m : float
[ "Calculate", "the", "distance", "from", "this", "location", "to", "there", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/__init__.py#L140-L153
MartinThoma/mpu
mpu/_cli.py
main
def main(): """Command line interface of mpu.""" parser = get_parser() args = parser.parse_args() if hasattr(args, 'func') and args.func: args.func(args) else: parser.print_help()
python
def main(): """Command line interface of mpu.""" parser = get_parser() args = parser.parse_args() if hasattr(args, 'func') and args.func: args.func(args) else: parser.print_help()
[ "def", "main", "(", ")", ":", "parser", "=", "get_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "hasattr", "(", "args", ",", "'func'", ")", "and", "args", ".", "func", ":", "args", ".", "func", "(", "args", ")", "el...
Command line interface of mpu.
[ "Command", "line", "interface", "of", "mpu", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/_cli.py#L13-L20
MartinThoma/mpu
mpu/_cli.py
get_parser
def get_parser(): """Get parser for mpu.""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('--version', action='version'...
python
def get_parser(): """Get parser for mpu.""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument('--version', action='version'...
[ "def", "get_parser", "(", ")", ":", "from", "argparse", "import", "ArgumentParser", ",", "ArgumentDefaultsHelpFormatter", "parser", "=", "ArgumentParser", "(", "description", "=", "__doc__", ",", "formatter_class", "=", "ArgumentDefaultsHelpFormatter", ")", "parser", ...
Get parser for mpu.
[ "Get", "parser", "for", "mpu", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/_cli.py#L23-L34
MartinThoma/mpu
mpu/io.py
read
def read(filepath, **kwargs): """ Read a file. Supported formats: * CSV * JSON, JSONL * pickle Parameters ---------- filepath : str Path to the file that should be read. This methods action depends mainly on the file extension. kwargs : dict Any keyword...
python
def read(filepath, **kwargs): """ Read a file. Supported formats: * CSV * JSON, JSONL * pickle Parameters ---------- filepath : str Path to the file that should be read. This methods action depends mainly on the file extension. kwargs : dict Any keyword...
[ "def", "read", "(", "filepath", ",", "*", "*", "kwargs", ")", ":", "if", "filepath", ".", "lower", "(", ")", ".", "endswith", "(", "'.csv'", ")", ":", "return", "_read_csv", "(", "filepath", ",", "kwargs", ")", "elif", "filepath", ".", "lower", "(", ...
Read a file. Supported formats: * CSV * JSON, JSONL * pickle Parameters ---------- filepath : str Path to the file that should be read. This methods action depends mainly on the file extension. kwargs : dict Any keywords for the specific file format. For CSV, t...
[ "Read", "a", "file", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L29-L77
MartinThoma/mpu
mpu/io.py
_read_csv
def _read_csv(filepath, kwargs): """See documentation of mpu.io.read.""" if 'delimiter' not in kwargs: kwargs['delimiter'] = ',' if 'quotechar' not in kwargs: kwargs['quotechar'] = '"' if 'skiprows' not in kwargs: kwargs['skiprows'] = [] if isinstance(kwargs['skiprows'], int)...
python
def _read_csv(filepath, kwargs): """See documentation of mpu.io.read.""" if 'delimiter' not in kwargs: kwargs['delimiter'] = ',' if 'quotechar' not in kwargs: kwargs['quotechar'] = '"' if 'skiprows' not in kwargs: kwargs['skiprows'] = [] if isinstance(kwargs['skiprows'], int)...
[ "def", "_read_csv", "(", "filepath", ",", "kwargs", ")", ":", "if", "'delimiter'", "not", "in", "kwargs", ":", "kwargs", "[", "'delimiter'", "]", "=", "','", "if", "'quotechar'", "not", "in", "kwargs", ":", "kwargs", "[", "'quotechar'", "]", "=", "'\"'",...
See documentation of mpu.io.read.
[ "See", "documentation", "of", "mpu", ".", "io", ".", "read", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L80-L114
MartinThoma/mpu
mpu/io.py
_read_jsonl
def _read_jsonl(filepath, kwargs): """See documentation of mpu.io.read.""" with open(filepath) as data_file: data = [json.loads(line, **kwargs) for line in data_file if len(line) > 0] return data
python
def _read_jsonl(filepath, kwargs): """See documentation of mpu.io.read.""" with open(filepath) as data_file: data = [json.loads(line, **kwargs) for line in data_file if len(line) > 0] return data
[ "def", "_read_jsonl", "(", "filepath", ",", "kwargs", ")", ":", "with", "open", "(", "filepath", ")", "as", "data_file", ":", "data", "=", "[", "json", ".", "loads", "(", "line", ",", "*", "*", "kwargs", ")", "for", "line", "in", "data_file", "if", ...
See documentation of mpu.io.read.
[ "See", "documentation", "of", "mpu", ".", "io", ".", "read", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L117-L123
MartinThoma/mpu
mpu/io.py
write
def write(filepath, data, **kwargs): """ Write a file. Supported formats: * CSV * JSON, JSONL * pickle Parameters ---------- filepath : str Path to the file that should be read. This methods action depends mainly on the file extension. data : dict or list ...
python
def write(filepath, data, **kwargs): """ Write a file. Supported formats: * CSV * JSON, JSONL * pickle Parameters ---------- filepath : str Path to the file that should be read. This methods action depends mainly on the file extension. data : dict or list ...
[ "def", "write", "(", "filepath", ",", "data", ",", "*", "*", "kwargs", ")", ":", "if", "filepath", ".", "lower", "(", ")", ".", "endswith", "(", "'.csv'", ")", ":", "return", "_write_csv", "(", "filepath", ",", "data", ",", "kwargs", ")", "elif", "...
Write a file. Supported formats: * CSV * JSON, JSONL * pickle Parameters ---------- filepath : str Path to the file that should be read. This methods action depends mainly on the file extension. data : dict or list Content that should be written kwargs : di...
[ "Write", "a", "file", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L126-L171
MartinThoma/mpu
mpu/io.py
_write_csv
def _write_csv(filepath, data, kwargs): """See documentation of mpu.io.write.""" kwargs_open = {'newline': ''} mode = 'w' if sys.version_info < (3, 0): kwargs_open.pop('newline', None) mode = 'wb' with open(filepath, mode, **kwargs_open) as fp: if 'delimiter' not in kwargs: ...
python
def _write_csv(filepath, data, kwargs): """See documentation of mpu.io.write.""" kwargs_open = {'newline': ''} mode = 'w' if sys.version_info < (3, 0): kwargs_open.pop('newline', None) mode = 'wb' with open(filepath, mode, **kwargs_open) as fp: if 'delimiter' not in kwargs: ...
[ "def", "_write_csv", "(", "filepath", ",", "data", ",", "kwargs", ")", ":", "kwargs_open", "=", "{", "'newline'", ":", "''", "}", "mode", "=", "'w'", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "kwargs_open", ".", "pop", "(...
See documentation of mpu.io.write.
[ "See", "documentation", "of", "mpu", ".", "io", ".", "write", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L174-L189
MartinThoma/mpu
mpu/io.py
_write_json
def _write_json(filepath, data, kwargs): """See documentation of mpu.io.write.""" with io_stl.open(filepath, 'w', encoding='utf8') as outfile: if 'indent' not in kwargs: kwargs['indent'] = 4 if 'sort_keys' not in kwargs: kwargs['sort_keys'] = True if 'separators' ...
python
def _write_json(filepath, data, kwargs): """See documentation of mpu.io.write.""" with io_stl.open(filepath, 'w', encoding='utf8') as outfile: if 'indent' not in kwargs: kwargs['indent'] = 4 if 'sort_keys' not in kwargs: kwargs['sort_keys'] = True if 'separators' ...
[ "def", "_write_json", "(", "filepath", ",", "data", ",", "kwargs", ")", ":", "with", "io_stl", ".", "open", "(", "filepath", ",", "'w'", ",", "encoding", "=", "'utf8'", ")", "as", "outfile", ":", "if", "'indent'", "not", "in", "kwargs", ":", "kwargs", ...
See documentation of mpu.io.write.
[ "See", "documentation", "of", "mpu", ".", "io", ".", "write", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L192-L205
MartinThoma/mpu
mpu/io.py
_write_jsonl
def _write_jsonl(filepath, data, kwargs): """See documentation of mpu.io.write.""" with io_stl.open(filepath, 'w', encoding='utf8') as outfile: kwargs['indent'] = None # JSON has to be on one line! if 'sort_keys' not in kwargs: kwargs['sort_keys'] = True if 'separators' not ...
python
def _write_jsonl(filepath, data, kwargs): """See documentation of mpu.io.write.""" with io_stl.open(filepath, 'w', encoding='utf8') as outfile: kwargs['indent'] = None # JSON has to be on one line! if 'sort_keys' not in kwargs: kwargs['sort_keys'] = True if 'separators' not ...
[ "def", "_write_jsonl", "(", "filepath", ",", "data", ",", "kwargs", ")", ":", "with", "io_stl", ".", "open", "(", "filepath", ",", "'w'", ",", "encoding", "=", "'utf8'", ")", "as", "outfile", ":", "kwargs", "[", "'indent'", "]", "=", "None", "# JSON ha...
See documentation of mpu.io.write.
[ "See", "documentation", "of", "mpu", ".", "io", ".", "write", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L208-L222
MartinThoma/mpu
mpu/io.py
_write_pickle
def _write_pickle(filepath, data, kwargs): """See documentation of mpu.io.write.""" if 'protocol' not in kwargs: kwargs['protocol'] = pickle.HIGHEST_PROTOCOL with open(filepath, 'wb') as handle: pickle.dump(data, handle, **kwargs) return data
python
def _write_pickle(filepath, data, kwargs): """See documentation of mpu.io.write.""" if 'protocol' not in kwargs: kwargs['protocol'] = pickle.HIGHEST_PROTOCOL with open(filepath, 'wb') as handle: pickle.dump(data, handle, **kwargs) return data
[ "def", "_write_pickle", "(", "filepath", ",", "data", ",", "kwargs", ")", ":", "if", "'protocol'", "not", "in", "kwargs", ":", "kwargs", "[", "'protocol'", "]", "=", "pickle", ".", "HIGHEST_PROTOCOL", "with", "open", "(", "filepath", ",", "'wb'", ")", "a...
See documentation of mpu.io.write.
[ "See", "documentation", "of", "mpu", ".", "io", ".", "write", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L225-L231
MartinThoma/mpu
mpu/io.py
urlread
def urlread(url, encoding='utf8'): """ Read the content of an URL. Parameters ---------- url : str Returns ------- content : str """ try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen response = urlopen(url) conte...
python
def urlread(url, encoding='utf8'): """ Read the content of an URL. Parameters ---------- url : str Returns ------- content : str """ try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen response = urlopen(url) conte...
[ "def", "urlread", "(", "url", ",", "encoding", "=", "'utf8'", ")", ":", "try", ":", "from", "urllib", ".", "request", "import", "urlopen", "except", "ImportError", ":", "from", "urllib2", "import", "urlopen", "response", "=", "urlopen", "(", "url", ")", ...
Read the content of an URL. Parameters ---------- url : str Returns ------- content : str
[ "Read", "the", "content", "of", "an", "URL", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L234-L253
MartinThoma/mpu
mpu/io.py
download
def download(source, sink=None): """ Download a file. Parameters ---------- source : str Where the file comes from. Some URL. sink : str or None (default: same filename in current directory) Where the file gets stored. Some filepath in the local file system. """ try: ...
python
def download(source, sink=None): """ Download a file. Parameters ---------- source : str Where the file comes from. Some URL. sink : str or None (default: same filename in current directory) Where the file gets stored. Some filepath in the local file system. """ try: ...
[ "def", "download", "(", "source", ",", "sink", "=", "None", ")", ":", "try", ":", "from", "urllib", ".", "request", "import", "urlretrieve", "# Python 3", "except", "ImportError", ":", "from", "urllib", "import", "urlretrieve", "# Python 2", "if", "sink", "i...
Download a file. Parameters ---------- source : str Where the file comes from. Some URL. sink : str or None (default: same filename in current directory) Where the file gets stored. Some filepath in the local file system.
[ "Download", "a", "file", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L256-L274
MartinThoma/mpu
mpu/io.py
hash
def hash(filepath, method='sha1', buffer_size=65536): """ Calculate a hash of a local file. Parameters ---------- filepath : str method : {'sha1', 'md5'} buffer_size : int, optional (default: 65536 byte = 64 KiB) in byte Returns ------- hash : str """ if method ...
python
def hash(filepath, method='sha1', buffer_size=65536): """ Calculate a hash of a local file. Parameters ---------- filepath : str method : {'sha1', 'md5'} buffer_size : int, optional (default: 65536 byte = 64 KiB) in byte Returns ------- hash : str """ if method ...
[ "def", "hash", "(", "filepath", ",", "method", "=", "'sha1'", ",", "buffer_size", "=", "65536", ")", ":", "if", "method", "==", "'sha1'", ":", "hash_function", "=", "hashlib", ".", "sha1", "(", ")", "elif", "method", "==", "'md5'", ":", "hash_function", ...
Calculate a hash of a local file. Parameters ---------- filepath : str method : {'sha1', 'md5'} buffer_size : int, optional (default: 65536 byte = 64 KiB) in byte Returns ------- hash : str
[ "Calculate", "a", "hash", "of", "a", "local", "file", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L277-L306
MartinThoma/mpu
mpu/io.py
get_creation_datetime
def get_creation_datetime(filepath): """ Get the date that a file was created. Parameters ---------- filepath : str Returns ------- creation_datetime : datetime.datetime or None """ if platform.system() == 'Windows': return datetime.fromtimestamp(os.path.getctime(filepa...
python
def get_creation_datetime(filepath): """ Get the date that a file was created. Parameters ---------- filepath : str Returns ------- creation_datetime : datetime.datetime or None """ if platform.system() == 'Windows': return datetime.fromtimestamp(os.path.getctime(filepa...
[ "def", "get_creation_datetime", "(", "filepath", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "return", "datetime", ".", "fromtimestamp", "(", "os", ".", "path", ".", "getctime", "(", "filepath", ")", ")", "else", ":", "st...
Get the date that a file was created. Parameters ---------- filepath : str Returns ------- creation_datetime : datetime.datetime or None
[ "Get", "the", "date", "that", "a", "file", "was", "created", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L309-L330
MartinThoma/mpu
mpu/io.py
get_modification_datetime
def get_modification_datetime(filepath): """ Get the datetime that a file was last modified. Parameters ---------- filepath : str Returns ------- modification_datetime : datetime.datetime """ import tzlocal timezone = tzlocal.get_localzone() mtime = datetime.fromtimest...
python
def get_modification_datetime(filepath): """ Get the datetime that a file was last modified. Parameters ---------- filepath : str Returns ------- modification_datetime : datetime.datetime """ import tzlocal timezone = tzlocal.get_localzone() mtime = datetime.fromtimest...
[ "def", "get_modification_datetime", "(", "filepath", ")", ":", "import", "tzlocal", "timezone", "=", "tzlocal", ".", "get_localzone", "(", ")", "mtime", "=", "datetime", ".", "fromtimestamp", "(", "os", ".", "path", ".", "getmtime", "(", "filepath", ")", ")"...
Get the datetime that a file was last modified. Parameters ---------- filepath : str Returns ------- modification_datetime : datetime.datetime
[ "Get", "the", "datetime", "that", "a", "file", "was", "last", "modified", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L333-L349
MartinThoma/mpu
mpu/io.py
get_access_datetime
def get_access_datetime(filepath): """ Get the last time filepath was accessed. Parameters ---------- filepath : str Returns ------- access_datetime : datetime.datetime """ import tzlocal tz = tzlocal.get_localzone() mtime = datetime.fromtimestamp(os.path.getatime(filep...
python
def get_access_datetime(filepath): """ Get the last time filepath was accessed. Parameters ---------- filepath : str Returns ------- access_datetime : datetime.datetime """ import tzlocal tz = tzlocal.get_localzone() mtime = datetime.fromtimestamp(os.path.getatime(filep...
[ "def", "get_access_datetime", "(", "filepath", ")", ":", "import", "tzlocal", "tz", "=", "tzlocal", ".", "get_localzone", "(", ")", "mtime", "=", "datetime", ".", "fromtimestamp", "(", "os", ".", "path", ".", "getatime", "(", "filepath", ")", ")", "return"...
Get the last time filepath was accessed. Parameters ---------- filepath : str Returns ------- access_datetime : datetime.datetime
[ "Get", "the", "last", "time", "filepath", "was", "accessed", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L352-L367
MartinThoma/mpu
mpu/io.py
get_file_meta
def get_file_meta(filepath): """ Get meta-information about a file. Parameters ---------- filepath : str Returns ------- meta : dict """ meta = {} meta['filepath'] = os.path.abspath(filepath) meta['creation_datetime'] = get_creation_datetime(filepath) meta['last_acc...
python
def get_file_meta(filepath): """ Get meta-information about a file. Parameters ---------- filepath : str Returns ------- meta : dict """ meta = {} meta['filepath'] = os.path.abspath(filepath) meta['creation_datetime'] = get_creation_datetime(filepath) meta['last_acc...
[ "def", "get_file_meta", "(", "filepath", ")", ":", "meta", "=", "{", "}", "meta", "[", "'filepath'", "]", "=", "os", ".", "path", ".", "abspath", "(", "filepath", ")", "meta", "[", "'creation_datetime'", "]", "=", "get_creation_datetime", "(", "filepath", ...
Get meta-information about a file. Parameters ---------- filepath : str Returns ------- meta : dict
[ "Get", "meta", "-", "information", "about", "a", "file", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L370-L395
MartinThoma/mpu
mpu/io.py
gzip_file
def gzip_file(source, sink): """ Create a GZIP file from a source file. Parameters ---------- source : str Filepath sink : str Filepath """ import gzip with open(source, 'rb') as f_in, gzip.open(sink, 'wb') as f_out: f_out.writelines(f_in)
python
def gzip_file(source, sink): """ Create a GZIP file from a source file. Parameters ---------- source : str Filepath sink : str Filepath """ import gzip with open(source, 'rb') as f_in, gzip.open(sink, 'wb') as f_out: f_out.writelines(f_in)
[ "def", "gzip_file", "(", "source", ",", "sink", ")", ":", "import", "gzip", "with", "open", "(", "source", ",", "'rb'", ")", "as", "f_in", ",", "gzip", ".", "open", "(", "sink", ",", "'wb'", ")", "as", "f_out", ":", "f_out", ".", "writelines", "(",...
Create a GZIP file from a source file. Parameters ---------- source : str Filepath sink : str Filepath
[ "Create", "a", "GZIP", "file", "from", "a", "source", "file", "." ]
train
https://github.com/MartinThoma/mpu/blob/61bc36d0192ca90c0bcf9b8a5d7d0d8520e20ff6/mpu/io.py#L398-L411
fulfilio/fulfil-python-api
fulfil_client/contrib/mocking.py
MockFulfil.start
def start(self): """ Start the patch """ self._patcher = mock.patch(target=self.target) MockClient = self._patcher.start() instance = MockClient.return_value instance.model.side_effect = mock.Mock( side_effect=self.model )
python
def start(self): """ Start the patch """ self._patcher = mock.patch(target=self.target) MockClient = self._patcher.start() instance = MockClient.return_value instance.model.side_effect = mock.Mock( side_effect=self.model )
[ "def", "start", "(", "self", ")", ":", "self", ".", "_patcher", "=", "mock", ".", "patch", "(", "target", "=", "self", ".", "target", ")", "MockClient", "=", "self", ".", "_patcher", ".", "start", "(", ")", "instance", "=", "MockClient", ".", "return...
Start the patch
[ "Start", "the", "patch" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/contrib/mocking.py#L38-L47
fulfilio/fulfil-python-api
fulfil_client/oauth.py
Session.setup
def setup(cls, client_id, client_secret): """Configure client in session """ cls.client_id = client_id cls.client_secret = client_secret
python
def setup(cls, client_id, client_secret): """Configure client in session """ cls.client_id = client_id cls.client_secret = client_secret
[ "def", "setup", "(", "cls", ",", "client_id", ",", "client_secret", ")", ":", "cls", ".", "client_id", "=", "client_id", "cls", ".", "client_secret", "=", "client_secret" ]
Configure client in session
[ "Configure", "client", "in", "session" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/oauth.py#L18-L22
MrTango/RISparser
RISparser/parser.py
read
def read(filelines, mapping=None, wok=False): """Parse a ris lines and return a list of entries. Entries are codified as dictionaries whose keys are the different tags. For single line and singly occurring tags, the content is codified as a string. In the case of multiline or multiple key occurrenc...
python
def read(filelines, mapping=None, wok=False): """Parse a ris lines and return a list of entries. Entries are codified as dictionaries whose keys are the different tags. For single line and singly occurring tags, the content is codified as a string. In the case of multiline or multiple key occurrenc...
[ "def", "read", "(", "filelines", ",", "mapping", "=", "None", ",", "wok", "=", "False", ")", ":", "if", "wok", ":", "if", "not", "mapping", ":", "mapping", "=", "WOK_TAG_KEY_MAPPING", "return", "Wok", "(", "filelines", ",", "mapping", ")", ".", "parse"...
Parse a ris lines and return a list of entries. Entries are codified as dictionaries whose keys are the different tags. For single line and singly occurring tags, the content is codified as a string. In the case of multiline or multiple key occurrences, the content is returned as a list of strings....
[ "Parse", "a", "ris", "lines", "and", "return", "a", "list", "of", "entries", "." ]
train
https://github.com/MrTango/RISparser/blob/d133d74022d3edbbdec19ef72bd34c8902a0bad1/RISparser/parser.py#L180-L204
fulfilio/fulfil-python-api
fulfil_client/client.py
Client.refresh_context
def refresh_context(self): """ Get the default context of the user and save it """ User = self.model('res.user') self.context = User.get_preferences(True) return self.context
python
def refresh_context(self): """ Get the default context of the user and save it """ User = self.model('res.user') self.context = User.get_preferences(True) return self.context
[ "def", "refresh_context", "(", "self", ")", ":", "User", "=", "self", ".", "model", "(", "'res.user'", ")", "self", ".", "context", "=", "User", ".", "get_preferences", "(", "True", ")", "return", "self", ".", "context" ]
Get the default context of the user and save it
[ "Get", "the", "default", "context", "of", "the", "user", "and", "save", "it" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/client.py#L144-L151
fulfilio/fulfil-python-api
fulfil_client/client.py
Client.login
def login(self, login, password, set_auth=False): """ Attempts a login to the remote server and on success returns user id and session or None Warning: Do not depend on this. This will be deprecated with SSO. param set_auth: sets the authentication on the client...
python
def login(self, login, password, set_auth=False): """ Attempts a login to the remote server and on success returns user id and session or None Warning: Do not depend on this. This will be deprecated with SSO. param set_auth: sets the authentication on the client...
[ "def", "login", "(", "self", ",", "login", ",", "password", ",", "set_auth", "=", "False", ")", ":", "rv", "=", "self", ".", "session", ".", "post", "(", "self", ".", "host", ",", "dumps", "(", "{", "\"method\"", ":", "\"common.db.login\"", ",", "\"p...
Attempts a login to the remote server and on success returns user id and session or None Warning: Do not depend on this. This will be deprecated with SSO. param set_auth: sets the authentication on the client
[ "Attempts", "a", "login", "to", "the", "remote", "server", "and", "on", "success", "returns", "user", "id", "and", "session", "or", "None" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/client.py#L173-L196
fulfilio/fulfil-python-api
fulfil_client/client.py
Client.is_auth_alive
def is_auth_alive(self): "Return true if the auth is not expired, else false" model = self.model('ir.model') try: model.search([], None, 1, None) except ClientError as err: if err and err.message['code'] == 403: return False raise ...
python
def is_auth_alive(self): "Return true if the auth is not expired, else false" model = self.model('ir.model') try: model.search([], None, 1, None) except ClientError as err: if err and err.message['code'] == 403: return False raise ...
[ "def", "is_auth_alive", "(", "self", ")", ":", "model", "=", "self", ".", "model", "(", "'ir.model'", ")", "try", ":", "model", ".", "search", "(", "[", "]", ",", "None", ",", "1", ",", "None", ")", "except", "ClientError", "as", "err", ":", "if", ...
Return true if the auth is not expired, else false
[ "Return", "true", "if", "the", "auth", "is", "not", "expired", "else", "false" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/client.py#L198-L210
fulfilio/fulfil-python-api
fulfil_client/client.py
Record.update
def update(self, data=None, **kwargs): """ Update the record right away. :param data: dictionary of changes :param kwargs: possibly a list of keyword args to change """ if data is None: data = {} data.update(kwargs) return self.model.write([se...
python
def update(self, data=None, **kwargs): """ Update the record right away. :param data: dictionary of changes :param kwargs: possibly a list of keyword args to change """ if data is None: data = {} data.update(kwargs) return self.model.write([se...
[ "def", "update", "(", "self", ",", "data", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "data", "is", "None", ":", "data", "=", "{", "}", "data", ".", "update", "(", "kwargs", ")", "return", "self", ".", "model", ".", "write", "(", "["...
Update the record right away. :param data: dictionary of changes :param kwargs: possibly a list of keyword args to change
[ "Update", "the", "record", "right", "away", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/client.py#L333-L343
fulfilio/fulfil-python-api
fulfil_client/client.py
Model.search_read_all
def search_read_all(self, domain, order, fields, batch_size=500, context=None, offset=0, limit=None): """ An endless iterator that iterates over records. :param domain: A search domain :param order: The order clause for search read :param fields: The fiel...
python
def search_read_all(self, domain, order, fields, batch_size=500, context=None, offset=0, limit=None): """ An endless iterator that iterates over records. :param domain: A search domain :param order: The order clause for search read :param fields: The fiel...
[ "def", "search_read_all", "(", "self", ",", "domain", ",", "order", ",", "fields", ",", "batch_size", "=", "500", ",", "context", "=", "None", ",", "offset", "=", "0", ",", "limit", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context"...
An endless iterator that iterates over records. :param domain: A search domain :param order: The order clause for search read :param fields: The fields argument for search_read :param batch_size: The optimal batch size when sending paginated requests
[ "An", "endless", "iterator", "that", "iterates", "over", "records", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/client.py#L390-L418
fulfilio/fulfil-python-api
fulfil_client/client.py
Model.find
def find(self, filter=None, page=1, per_page=10, fields=None, context=None): """ Find records that match the filter. Pro Tip: The fields could have nested fields names if the field is a relationship type. For example if you were looking up an order and also want to get the shipp...
python
def find(self, filter=None, page=1, per_page=10, fields=None, context=None): """ Find records that match the filter. Pro Tip: The fields could have nested fields names if the field is a relationship type. For example if you were looking up an order and also want to get the shipp...
[ "def", "find", "(", "self", ",", "filter", "=", "None", ",", "page", "=", "1", ",", "per_page", "=", "10", ",", "fields", "=", "None", ",", "context", "=", "None", ")", ":", "if", "filter", "is", "None", ":", "filter", "=", "[", "]", "rv", "=",...
Find records that match the filter. Pro Tip: The fields could have nested fields names if the field is a relationship type. For example if you were looking up an order and also want to get the shipping address country then fields would be: `['shipment_address', 'shipment_address.co...
[ "Find", "records", "that", "match", "the", "filter", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/client.py#L421-L454
fulfilio/fulfil-python-api
fulfil_client/client.py
Model.attach
def attach(self, id, filename, url): """Add an attachmemt to record from url :param id: ID of record :param filename: File name of attachment :param url: Public url to download file from. """ Attachment = self.client.model('ir.attachment') return Attachment.add_a...
python
def attach(self, id, filename, url): """Add an attachmemt to record from url :param id: ID of record :param filename: File name of attachment :param url: Public url to download file from. """ Attachment = self.client.model('ir.attachment') return Attachment.add_a...
[ "def", "attach", "(", "self", ",", "id", ",", "filename", ",", "url", ")", ":", "Attachment", "=", "self", ".", "client", ".", "model", "(", "'ir.attachment'", ")", "return", "Attachment", ".", "add_attachment_from_url", "(", "filename", ",", "url", ",", ...
Add an attachmemt to record from url :param id: ID of record :param filename: File name of attachment :param url: Public url to download file from.
[ "Add", "an", "attachmemt", "to", "record", "from", "url" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/client.py#L456-L466
fulfilio/fulfil-python-api
fulfil_client/client.py
AsyncResult.refresh_if_needed
def refresh_if_needed(self): """ Refresh the status of the task from server if required. """ if self.state in (self.PENDING, self.STARTED): try: response, = self._fetch_result()['tasks'] except (KeyError, ValueError): raise Exceptio...
python
def refresh_if_needed(self): """ Refresh the status of the task from server if required. """ if self.state in (self.PENDING, self.STARTED): try: response, = self._fetch_result()['tasks'] except (KeyError, ValueError): raise Exceptio...
[ "def", "refresh_if_needed", "(", "self", ")", ":", "if", "self", ".", "state", "in", "(", "self", ".", "PENDING", ",", "self", ".", "STARTED", ")", ":", "try", ":", "response", ",", "=", "self", ".", "_fetch_result", "(", ")", "[", "'tasks'", "]", ...
Refresh the status of the task from server if required.
[ "Refresh", "the", "status", "of", "the", "task", "from", "server", "if", "required", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/client.py#L572-L590
fulfilio/fulfil-python-api
examples/create-sale-order.py
get_product_inventory
def get_product_inventory(product_id, warehouse_ids): """ Return the product inventory in each location. The returned response will look like:: { 12: { // Product ID 4: { // Location ID 'quantity_on_hand': 12.0, 'quantity_...
python
def get_product_inventory(product_id, warehouse_ids): """ Return the product inventory in each location. The returned response will look like:: { 12: { // Product ID 4: { // Location ID 'quantity_on_hand': 12.0, 'quantity_...
[ "def", "get_product_inventory", "(", "product_id", ",", "warehouse_ids", ")", ":", "Product", "=", "client", ".", "model", "(", "'product.product'", ")", "return", "Product", ".", "get_product_inventory", "(", "[", "product_id", "]", ",", "warehouse_ids", ")", "...
Return the product inventory in each location. The returned response will look like:: { 12: { // Product ID 4: { // Location ID 'quantity_on_hand': 12.0, 'quantity_available': 8.0 }, 5: { // Loca...
[ "Return", "the", "product", "inventory", "in", "each", "location", ".", "The", "returned", "response", "will", "look", "like", "::" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/examples/create-sale-order.py#L29-L64
fulfilio/fulfil-python-api
examples/create-sale-order.py
get_customer
def get_customer(code): """ Fetch a customer with the code. Returns None if the customer is not found. """ Party = client.model('party.party') results = Party.find([('code', '=', code)]) if results: return results[0]['id']
python
def get_customer(code): """ Fetch a customer with the code. Returns None if the customer is not found. """ Party = client.model('party.party') results = Party.find([('code', '=', code)]) if results: return results[0]['id']
[ "def", "get_customer", "(", "code", ")", ":", "Party", "=", "client", ".", "model", "(", "'party.party'", ")", "results", "=", "Party", ".", "find", "(", "[", "(", "'code'", ",", "'='", ",", "code", ")", "]", ")", "if", "results", ":", "return", "r...
Fetch a customer with the code. Returns None if the customer is not found.
[ "Fetch", "a", "customer", "with", "the", "code", ".", "Returns", "None", "if", "the", "customer", "is", "not", "found", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/examples/create-sale-order.py#L67-L75
fulfilio/fulfil-python-api
examples/create-sale-order.py
get_address
def get_address(customer_id, data): """ Easier to fetch the addresses of customer and then check one by one. You can get fancy by using some validation mechanism too """ Address = client.model('party.address') addresses = Address.find( [('party', '=', customer_id)], fields=[ ...
python
def get_address(customer_id, data): """ Easier to fetch the addresses of customer and then check one by one. You can get fancy by using some validation mechanism too """ Address = client.model('party.address') addresses = Address.find( [('party', '=', customer_id)], fields=[ ...
[ "def", "get_address", "(", "customer_id", ",", "data", ")", ":", "Address", "=", "client", ".", "model", "(", "'party.address'", ")", "addresses", "=", "Address", ".", "find", "(", "[", "(", "'party'", ",", "'='", ",", "customer_id", ")", "]", ",", "fi...
Easier to fetch the addresses of customer and then check one by one. You can get fancy by using some validation mechanism too
[ "Easier", "to", "fetch", "the", "addresses", "of", "customer", "and", "then", "check", "one", "by", "one", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/examples/create-sale-order.py#L78-L102
fulfilio/fulfil-python-api
examples/create-sale-order.py
create_address
def create_address(customer_id, data): """ Create an address and return the id """ Address = client.model('party.address') Country = client.model('country.country') Subdivision = client.model('country.subdivision') country, = Country.find([('code', '=', data['country'])]) state, = Subdi...
python
def create_address(customer_id, data): """ Create an address and return the id """ Address = client.model('party.address') Country = client.model('country.country') Subdivision = client.model('country.subdivision') country, = Country.find([('code', '=', data['country'])]) state, = Subdi...
[ "def", "create_address", "(", "customer_id", ",", "data", ")", ":", "Address", "=", "client", ".", "model", "(", "'party.address'", ")", "Country", "=", "client", ".", "model", "(", "'country.country'", ")", "Subdivision", "=", "client", ".", "model", "(", ...
Create an address and return the id
[ "Create", "an", "address", "and", "return", "the", "id" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/examples/create-sale-order.py#L105-L129
fulfilio/fulfil-python-api
examples/create-sale-order.py
create_customer
def create_customer(name, email, phone): """ Create a customer with the name. Then attach the email and phone as contact methods """ Party = client.model('party.party') ContactMechanism = client.model('party.contact_mechanism') party, = Party.create([{'name': name}]) # Bulk create the ...
python
def create_customer(name, email, phone): """ Create a customer with the name. Then attach the email and phone as contact methods """ Party = client.model('party.party') ContactMechanism = client.model('party.contact_mechanism') party, = Party.create([{'name': name}]) # Bulk create the ...
[ "def", "create_customer", "(", "name", ",", "email", ",", "phone", ")", ":", "Party", "=", "client", ".", "model", "(", "'party.party'", ")", "ContactMechanism", "=", "client", ".", "model", "(", "'party.contact_mechanism'", ")", "party", ",", "=", "Party", ...
Create a customer with the name. Then attach the email and phone as contact methods
[ "Create", "a", "customer", "with", "the", "name", ".", "Then", "attach", "the", "email", "and", "phone", "as", "contact", "methods" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/examples/create-sale-order.py#L132-L148
fulfilio/fulfil-python-api
examples/create-sale-order.py
create_order
def create_order(order): """ Create an order on fulfil from order_details. See the calling function below for an example of the order_details """ SaleOrder = client.model('sale.sale') SaleOrderLine = client.model('sale.line') # Check if customer exists, if not create one customer_id = g...
python
def create_order(order): """ Create an order on fulfil from order_details. See the calling function below for an example of the order_details """ SaleOrder = client.model('sale.sale') SaleOrderLine = client.model('sale.line') # Check if customer exists, if not create one customer_id = g...
[ "def", "create_order", "(", "order", ")", ":", "SaleOrder", "=", "client", ".", "model", "(", "'sale.sale'", ")", "SaleOrderLine", "=", "client", ".", "model", "(", "'sale.line'", ")", "# Check if customer exists, if not create one", "customer_id", "=", "get_custome...
Create an order on fulfil from order_details. See the calling function below for an example of the order_details
[ "Create", "an", "order", "on", "fulfil", "from", "order_details", ".", "See", "the", "calling", "function", "below", "for", "an", "example", "of", "the", "order_details" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/examples/create-sale-order.py#L162-L235
fulfilio/fulfil-python-api
fulfil_client/model.py
model_base
def model_base(fulfil_client, cache_backend=None, cache_expire=10 * 60): """ Return a Base Model class that binds to the fulfil client instance and the cache instance. This design is inspired by the declarative base pattern in SQL Alchemy. """ return type( 'BaseModel', (Model,),...
python
def model_base(fulfil_client, cache_backend=None, cache_expire=10 * 60): """ Return a Base Model class that binds to the fulfil client instance and the cache instance. This design is inspired by the declarative base pattern in SQL Alchemy. """ return type( 'BaseModel', (Model,),...
[ "def", "model_base", "(", "fulfil_client", ",", "cache_backend", "=", "None", ",", "cache_expire", "=", "10", "*", "60", ")", ":", "return", "type", "(", "'BaseModel'", ",", "(", "Model", ",", ")", ",", "{", "'fulfil_client'", ":", "fulfil_client", ",", ...
Return a Base Model class that binds to the fulfil client instance and the cache instance. This design is inspired by the declarative base pattern in SQL Alchemy.
[ "Return", "a", "Base", "Model", "class", "that", "binds", "to", "the", "fulfil", "client", "instance", "and", "the", "cache", "instance", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L746-L763
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.all
def all(self): """ Return the results represented by this Query as a list. .. versionchanged:: 0.10.0 Returns an iterator that lazily loads records instead of fetching thousands of records at once. """ return self.rpc_model.search_read_all( ...
python
def all(self): """ Return the results represented by this Query as a list. .. versionchanged:: 0.10.0 Returns an iterator that lazily loads records instead of fetching thousands of records at once. """ return self.rpc_model.search_read_all( ...
[ "def", "all", "(", "self", ")", ":", "return", "self", ".", "rpc_model", ".", "search_read_all", "(", "self", ".", "domain", ",", "self", ".", "_order_by", ",", "self", ".", "fields", ",", "context", "=", "self", ".", "context", ",", "offset", "=", "...
Return the results represented by this Query as a list. .. versionchanged:: 0.10.0 Returns an iterator that lazily loads records instead of fetching thousands of records at once.
[ "Return", "the", "results", "represented", "by", "this", "Query", "as", "a", "list", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L346-L363
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.count
def count(self): "Return a count of rows this Query would return." return self.rpc_model.search_count( self.domain, context=self.context )
python
def count(self): "Return a count of rows this Query would return." return self.rpc_model.search_count( self.domain, context=self.context )
[ "def", "count", "(", "self", ")", ":", "return", "self", ".", "rpc_model", ".", "search_count", "(", "self", ".", "domain", ",", "context", "=", "self", ".", "context", ")" ]
Return a count of rows this Query would return.
[ "Return", "a", "count", "of", "rows", "this", "Query", "would", "return", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L365-L369
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.exists
def exists(self): """ A convenience method that returns True if a record satisfying the query exists """ return self.rpc_model.search_count( self.domain, context=self.context ) > 0
python
def exists(self): """ A convenience method that returns True if a record satisfying the query exists """ return self.rpc_model.search_count( self.domain, context=self.context ) > 0
[ "def", "exists", "(", "self", ")", ":", "return", "self", ".", "rpc_model", ".", "search_count", "(", "self", ".", "domain", ",", "context", "=", "self", ".", "context", ")", ">", "0" ]
A convenience method that returns True if a record satisfying the query exists
[ "A", "convenience", "method", "that", "returns", "True", "if", "a", "record", "satisfying", "the", "query", "exists" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L371-L378
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.show_active_only
def show_active_only(self, state): """ Set active only to true or false on a copy of this query """ query = self._copy() query.active_only = state return query
python
def show_active_only(self, state): """ Set active only to true or false on a copy of this query """ query = self._copy() query.active_only = state return query
[ "def", "show_active_only", "(", "self", ",", "state", ")", ":", "query", "=", "self", ".", "_copy", "(", ")", "query", ".", "active_only", "=", "state", "return", "query" ]
Set active only to true or false on a copy of this query
[ "Set", "active", "only", "to", "true", "or", "false", "on", "a", "copy", "of", "this", "query" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L380-L386
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.filter_by
def filter_by(self, **kwargs): """ Apply the given filtering criterion to a copy of this Query, using keyword expressions. """ query = self._copy() for field, value in kwargs.items(): query.domain.append( (field, '=', value) ) ...
python
def filter_by(self, **kwargs): """ Apply the given filtering criterion to a copy of this Query, using keyword expressions. """ query = self._copy() for field, value in kwargs.items(): query.domain.append( (field, '=', value) ) ...
[ "def", "filter_by", "(", "self", ",", "*", "*", "kwargs", ")", ":", "query", "=", "self", ".", "_copy", "(", ")", "for", "field", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "query", ".", "domain", ".", "append", "(", "(", "field",...
Apply the given filtering criterion to a copy of this Query, using keyword expressions.
[ "Apply", "the", "given", "filtering", "criterion", "to", "a", "copy", "of", "this", "Query", "using", "keyword", "expressions", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L388-L398
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.filter_by_domain
def filter_by_domain(self, domain): """ Apply the given domain to a copy of this query """ query = self._copy() query.domain = domain return query
python
def filter_by_domain(self, domain): """ Apply the given domain to a copy of this query """ query = self._copy() query.domain = domain return query
[ "def", "filter_by_domain", "(", "self", ",", "domain", ")", ":", "query", "=", "self", ".", "_copy", "(", ")", "query", ".", "domain", "=", "domain", "return", "query" ]
Apply the given domain to a copy of this query
[ "Apply", "the", "given", "domain", "to", "a", "copy", "of", "this", "query" ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L400-L406
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.first
def first(self): """ Return the first result of this Query or None if the result doesn't contain any row. """ results = self.rpc_model.search_read( self.domain, None, 1, self._order_by, self.fields, context=self.context ) return results and...
python
def first(self): """ Return the first result of this Query or None if the result doesn't contain any row. """ results = self.rpc_model.search_read( self.domain, None, 1, self._order_by, self.fields, context=self.context ) return results and...
[ "def", "first", "(", "self", ")", ":", "results", "=", "self", ".", "rpc_model", ".", "search_read", "(", "self", ".", "domain", ",", "None", ",", "1", ",", "self", ".", "_order_by", ",", "self", ".", "fields", ",", "context", "=", "self", ".", "co...
Return the first result of this Query or None if the result doesn't contain any row.
[ "Return", "the", "first", "result", "of", "this", "Query", "or", "None", "if", "the", "result", "doesn", "t", "contain", "any", "row", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L409-L418
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.get
def get(self, id): """ Return an instance based on the given primary key identifier, or None if not found. This returns a record whether active or not. """ ctx = self.context.copy() ctx['active_test'] = False results = self.rpc_model.search_read( ...
python
def get(self, id): """ Return an instance based on the given primary key identifier, or None if not found. This returns a record whether active or not. """ ctx = self.context.copy() ctx['active_test'] = False results = self.rpc_model.search_read( ...
[ "def", "get", "(", "self", ",", "id", ")", ":", "ctx", "=", "self", ".", "context", ".", "copy", "(", ")", "ctx", "[", "'active_test'", "]", "=", "False", "results", "=", "self", ".", "rpc_model", ".", "search_read", "(", "[", "(", "'id'", ",", "...
Return an instance based on the given primary key identifier, or None if not found. This returns a record whether active or not.
[ "Return", "an", "instance", "based", "on", "the", "given", "primary", "key", "identifier", "or", "None", "if", "not", "found", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L421-L435
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.limit
def limit(self, limit): """ Apply a LIMIT to the query and return the newly resulting Query. """ query = self._copy() query._limit = limit return query
python
def limit(self, limit): """ Apply a LIMIT to the query and return the newly resulting Query. """ query = self._copy() query._limit = limit return query
[ "def", "limit", "(", "self", ",", "limit", ")", ":", "query", "=", "self", ".", "_copy", "(", ")", "query", ".", "_limit", "=", "limit", "return", "query" ]
Apply a LIMIT to the query and return the newly resulting Query.
[ "Apply", "a", "LIMIT", "to", "the", "query", "and", "return", "the", "newly", "resulting", "Query", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L437-L443
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.offset
def offset(self, offset): """ Apply an OFFSET to the query and return the newly resulting Query. """ query = self._copy() query._offset = offset return query
python
def offset(self, offset): """ Apply an OFFSET to the query and return the newly resulting Query. """ query = self._copy() query._offset = offset return query
[ "def", "offset", "(", "self", ",", "offset", ")", ":", "query", "=", "self", ".", "_copy", "(", ")", "query", ".", "_offset", "=", "offset", "return", "query" ]
Apply an OFFSET to the query and return the newly resulting Query.
[ "Apply", "an", "OFFSET", "to", "the", "query", "and", "return", "the", "newly", "resulting", "Query", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L445-L451
fulfilio/fulfil-python-api
fulfil_client/model.py
Query.one
def one(self): """ Return exactly one result or raise an exception. Raises fulfil_client.exc.NoResultFound if the query selects no rows. Raises fulfil_client.exc.MultipleResultsFound if multiple rows are found. """ results = self.rpc_model.search_read( ...
python
def one(self): """ Return exactly one result or raise an exception. Raises fulfil_client.exc.NoResultFound if the query selects no rows. Raises fulfil_client.exc.MultipleResultsFound if multiple rows are found. """ results = self.rpc_model.search_read( ...
[ "def", "one", "(", "self", ")", ":", "results", "=", "self", ".", "rpc_model", ".", "search_read", "(", "self", ".", "domain", ",", "2", ",", "None", ",", "self", ".", "_order_by", ",", "self", ".", "fields", ",", "context", "=", "self", ".", "cont...
Return exactly one result or raise an exception. Raises fulfil_client.exc.NoResultFound if the query selects no rows. Raises fulfil_client.exc.MultipleResultsFound if multiple rows are found.
[ "Return", "exactly", "one", "result", "or", "raise", "an", "exception", "." ]
train
https://github.com/fulfilio/fulfil-python-api/blob/180ac969c427b1292439a0371866aa5f169ffa6b/fulfil_client/model.py#L454-L470