sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _delay_for_ratelimits(cls, start): """If request was shorter than max request time, delay""" stop = datetime.now() duration_microseconds = (stop - start).microseconds if duration_microseconds < cls.REQUEST_TIME_MICROSECONDS: time.sleep((cls.REQUEST_TIME_MICROSECONDS - dur...
If request was shorter than max request time, delay
entailment
def load_data(filename, format_file='cloudupdrs'): """ This is a general load data method where the format of data to load can be passed as a parameter, :param str filename: The path to load data from :param str format_file: format of the file. Default is CloudUPDRS ('cloudu...
This is a general load data method where the format of data to load can be passed as a parameter, :param str filename: The path to load data from :param str format_file: format of the file. Default is CloudUPDRS ('cloudupdrs'). Set to 'mpower' for mpower data. :return DataFrame dat...
entailment
def run(self): """ Run the configured method and write the HTTP response status and text to the output stream. """ region = AWSServiceRegion(access_key=self.key, secret_key=self.secret, uri=self.endpoint) query = self.query_factory(action...
Run the configured method and write the HTTP response status and text to the output stream.
entailment
def resample_signal(self, data_frame): """ Convenience method for frequency conversion and resampling of data frame. Object must have a DatetimeIndex. After re-sampling, this methods interpolate the time magnitude sum acceleration values and the x,y,z values of the data fra...
Convenience method for frequency conversion and resampling of data frame. Object must have a DatetimeIndex. After re-sampling, this methods interpolate the time magnitude sum acceleration values and the x,y,z values of the data frame acceleration :param data_frame: the data frame ...
entailment
def filter_data_frame(self, data_frame, centre=False, keep_cols=['anno']): """ This method filters a data frame signal as suggested in [1]. First step is to high pass filter the data frame using a butter Butterworth digital and analog filter (https://docs.scipy.org/doc/scipy...
This method filters a data frame signal as suggested in [1]. First step is to high pass filter the data frame using a butter Butterworth digital and analog filter (https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.butter.html). Then the method filter the data...
entailment
def get_canonical_host(self): """ Return the canonical host as for the Host HTTP header specification. """ host = self.host.lower() if self.port is not None: host = "%s:%s" % (host, self.port) return host
Return the canonical host as for the Host HTTP header specification.
entailment
def set_canonical_host(self, canonical_host): """ Set host and port from a canonical host string as for the Host HTTP header specification. """ parts = canonical_host.lower().split(":") self.host = parts[0] if len(parts) > 1 and parts[1]: self.port = i...
Set host and port from a canonical host string as for the Host HTTP header specification.
entailment
def get_uri(self): """Get a URL representation of the service.""" uri = "%s://%s%s" % (self.scheme, self.get_canonical_host(), self.path) return uri
Get a URL representation of the service.
entailment
def get_client(self, cls, purge_cache=False, *args, **kwds): """ This is a general method for getting a client: if present, it is pulled from the cache; if not, a new one is instantiated and then put into the cache. This method should not be called directly, but rather by other c...
This is a general method for getting a client: if present, it is pulled from the cache; if not, a new one is instantiated and then put into the cache. This method should not be called directly, but rather by other client-specific methods (e.g., get_ec2_client).
entailment
def optimized(fn): """Decorator that will call the optimized c++ version of a pycast function if available rather than theo original pycast function :param function fn: original pycast function :return: return the wrapped function :rtype: function """ def _optimized(self, *args, **kwa...
Decorator that will call the optimized c++ version of a pycast function if available rather than theo original pycast function :param function fn: original pycast function :return: return the wrapped function :rtype: function
entailment
def optimize(self, timeSeries, forecastingMethods=None, startingPercentage=0.0, endPercentage=100.0): """Runs the optimization on the given TimeSeries. :param TimeSeries timeSeries: TimeSeries instance that requires an optimized forecast. :param list forecastingMethods: List of forecastin...
Runs the optimization on the given TimeSeries. :param TimeSeries timeSeries: TimeSeries instance that requires an optimized forecast. :param list forecastingMethods: List of forecastingMethods that will be used for optimization. :param float startingPercentage: Defines the start of the in...
entailment
def include_path(self, path): """ Should this path be included based on the include_paths or exclude_paths. Keeps track of paths seen to allow finding unused filters. :param path: str: remote path to be filtered :return: bool: True if we should include the path """ ...
Should this path be included based on the include_paths or exclude_paths. Keeps track of paths seen to allow finding unused filters. :param path: str: remote path to be filtered :return: bool: True if we should include the path
entailment
def get_unused_paths(self): """ Returns which include_paths or exclude_paths that were not used via include_path method. :return: [str] list of filtering paths that were not used. """ return [path for path in self.filter.paths if path not in self.seen_paths]
Returns which include_paths or exclude_paths that were not used via include_path method. :return: [str] list of filtering paths that were not used.
entailment
def is_child(child_path, parent_path): """ Is parent_path a parent(or grandparent) directory of child_path. :param child_path: str: remote file path :param parent_path: str: remote file path :return: bool: True when parent_path is child_path's parent """ parent_di...
Is parent_path a parent(or grandparent) directory of child_path. :param child_path: str: remote file path :param parent_path: str: remote file path :return: bool: True when parent_path is child_path's parent
entailment
def parent_child_paths(path, some_path): """ Is path a parent of some_path or some_path is a parent of path. :param path: str: remote file path :param some_path: str: remote file path :return: bool: True when they are parents """ return PathFilterUtil.is_child(pat...
Is path a parent of some_path or some_path is a parent of path. :param path: str: remote file path :param some_path: str: remote file path :return: bool: True when they are parents
entailment
def method(method_class): """Decorator to use to mark an API method. When invoking L{Registry.scan} the classes marked with this decorator will be added to the registry. @param method_class: The L{Method} class to register. """ def callback(scanner, name, method_class): if method_clas...
Decorator to use to mark an API method. When invoking L{Registry.scan} the classes marked with this decorator will be added to the registry. @param method_class: The L{Method} class to register.
entailment
def hexlify(script, minify=False): """ Takes the byte content of a Python script and returns a hex encoded version of it. Based on the hexlify script in the microbit-micropython repository. """ if not script: return '' # Convert line endings in case the file was created on Windows. ...
Takes the byte content of a Python script and returns a hex encoded version of it. Based on the hexlify script in the microbit-micropython repository.
entailment
def unhexlify(blob): """ Takes a hexlified script and turns it back into a string of Python code. """ lines = blob.split('\n')[1:] output = [] for line in lines: # Discard the address, length etc. and reverse the hexlification output.append(binascii.unhexlify(line[9:-2])) # C...
Takes a hexlified script and turns it back into a string of Python code.
entailment
def embed_hex(runtime_hex, python_hex=None): """ Given a string representing the MicroPython runtime hex, will embed a string representing a hex encoded Python script into it. Returns a string representation of the resulting combination. Will raise a ValueError if the runtime_hex is missing. ...
Given a string representing the MicroPython runtime hex, will embed a string representing a hex encoded Python script into it. Returns a string representation of the resulting combination. Will raise a ValueError if the runtime_hex is missing. If the python_hex is missing, it will return the unmodifi...
entailment
def extract_script(embedded_hex): """ Given a hex file containing the MicroPython runtime and an embedded Python script, will extract the original Python script. Returns a string containing the original embedded script. """ hex_lines = embedded_hex.split('\n') script_addr_high = hex((_SCRIP...
Given a hex file containing the MicroPython runtime and an embedded Python script, will extract the original Python script. Returns a string containing the original embedded script.
entailment
def find_microbit(): """ Returns a path on the filesystem that represents the plugged in BBC micro:bit that is to be flashed. If no micro:bit is found, it returns None. Works on Linux, OSX and Windows. Will raise a NotImplementedError exception if run on any other operating system. """ ...
Returns a path on the filesystem that represents the plugged in BBC micro:bit that is to be flashed. If no micro:bit is found, it returns None. Works on Linux, OSX and Windows. Will raise a NotImplementedError exception if run on any other operating system.
entailment
def save_hex(hex_file, path): """ Given a string representation of a hex file, this function copies it to the specified path thus causing the device mounted at that point to be flashed. If the hex_file is empty it will raise a ValueError. If the filename at the end of the path does not end in ...
Given a string representation of a hex file, this function copies it to the specified path thus causing the device mounted at that point to be flashed. If the hex_file is empty it will raise a ValueError. If the filename at the end of the path does not end in '.hex' it will raise a ValueError.
entailment
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...
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...
entailment
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...
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
entailment
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...
Watch a file for changes by polling its last modification time. Call the provided function with *args and **kwargs upon modification.
entailment
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...
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 ...
entailment
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,...
Measure the execution time of a function call and print the result.
entailment
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...
Mark functions as deprecated. It will result in a warning being emitted when the function is used.
entailment
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...
Convert an identifier for a currency into a currency object. Parameters ---------- currency_str : str Returns ------- currency : Currency
entailment
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...
Create a Currency object from a JSON dump.
entailment
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...
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
entailment
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...
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 ...
entailment
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...
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 >>>...
entailment
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 ...
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...
entailment
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 -------- >>> ...
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...
entailment
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...
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...
entailment
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' """ ...
Calculate the checksam of the German IBAN format. Examples -------- >>> iban = 'DE41500105170123456789' >>> _calculate_german_iban_checksum(iban) '41'
entailment
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...
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' ...
entailment
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...
List up to 1000 files in a bucket. Parameters ---------- bucket : str profile_name : str, optional AWS profile Returns ------- s3_paths : List[str]
entailment
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 -----...
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 ...
entailment
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...
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...
entailment
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 ""...
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
entailment
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...
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')
entailment
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...
Get meta-information of an image. Parameters ---------- filepath : str Returns ------- meta : dict
entailment
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 -...
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] >>...
entailment
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...
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...
entailment
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...
See documentation of mpu.datastructures.dict_merge.
entailment
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[...
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...
entailment
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...
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...
entailment
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...
Remove rows by which have the given indices. Parameters ---------- indices : list Returns ------- filtered_list : EList
entailment
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 ...
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
entailment
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...
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
entailment
def example_df(): """Create an example dataframe.""" country_names = ['Germany', 'France', 'Indonesia', 'Ireland', 'Spain', 'Vatican'] population = [82521653, 66991000, 255461700, 4761865, 46549045, None...
Create an example dataframe.
entailment
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))) ...
Print a description of a Pandas dataframe. Parameters ---------- df : Pandas.DataFrame dtype : dict Maps column names to types
entailment
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...
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 ...
entailment
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...
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...
entailment
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...
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
entailment
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, ...
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,...
entailment
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 >>>...
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([])
entailment
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 ""...
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
entailment
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 ...
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...
entailment
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 : ...
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...
entailment
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_...
Run project initialization. This will ask the user for input. Parameters ---------- args : argparse named arguments
entailment
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'} >>> _...
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'
entailment
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...
Search and replace contents of a filepath. Parameters ---------- filepath : str translate : dict
entailment
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...
Get parser for mpu.
entailment
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...
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...
entailment
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...
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
entailment
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;...
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...
entailment
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 = (...
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) ...
entailment
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...
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.
entailment
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...
Log exception by using the root logger. Use it as `sys.excepthook = exception_logging`. Parameters ---------- exctype : type value : NameError tb : traceback
entailment
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
Setter for latiutde.
entailment
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
Setter for longitude.
entailment
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), ...
Calculate the distance from this location to there. Parameters ---------- there : Location Returns ------- distance_in_m : float
entailment
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()
Command line interface of mpu.
entailment
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'...
Get parser for mpu.
entailment
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...
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...
entailment
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)...
See documentation of mpu.io.read.
entailment
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
See documentation of mpu.io.read.
entailment
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 ...
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...
entailment
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: ...
See documentation of mpu.io.write.
entailment
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' ...
See documentation of mpu.io.write.
entailment
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 ...
See documentation of mpu.io.write.
entailment
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
See documentation of mpu.io.write.
entailment
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...
Read the content of an URL. Parameters ---------- url : str Returns ------- content : str
entailment
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: ...
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.
entailment
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 ...
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
entailment
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...
Get the date that a file was created. Parameters ---------- filepath : str Returns ------- creation_datetime : datetime.datetime or None
entailment
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...
Get the datetime that a file was last modified. Parameters ---------- filepath : str Returns ------- modification_datetime : datetime.datetime
entailment
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...
Get the last time filepath was accessed. Parameters ---------- filepath : str Returns ------- access_datetime : datetime.datetime
entailment
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...
Get meta-information about a file. Parameters ---------- filepath : str Returns ------- meta : dict
entailment
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)
Create a GZIP file from a source file. Parameters ---------- source : str Filepath sink : str Filepath
entailment
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 )
Start the patch
entailment
def setup(cls, client_id, client_secret): """Configure client in session """ cls.client_id = client_id cls.client_secret = client_secret
Configure client in session
entailment
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...
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....
entailment
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
Get the default context of the user and save it
entailment
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...
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
entailment
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 ...
Return true if the auth is not expired, else false
entailment
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...
Update the record right away. :param data: dictionary of changes :param kwargs: possibly a list of keyword args to change
entailment