content
stringlengths
42
6.51k
def fix_filename(path): """Fix filenames for use in LaTeX. Latex has problems if there are one or more points in the filename, thus 'abc.def.jpg' will be changed to '{abc.def}.jpg' :param filename: :type filename: str :return: :rtype: str """ path_parts = path.split('/') dir...
def bit_ceil(n: int) -> int: """Calculate the smallest power of 2 not smaller than n.""" if n: # see https://stackoverflow.com/a/14267825/17332200 exp = (n - 1).bit_length() res = 1 << exp return res else: return 1
def counts_to_csr_data(count_dict, column_dict): """Convert a dictionary of count data to necessary inputs for a csr matrix. Parameters ---------- count_dict: dict of object to int The count of (hashed) objects; often ngrams. column_dict: dict of object to int The indices of the co...
def T1_sequence(length, target): """ Generate a gate sequence to measure relaxation time in a two-qubit chip. Parameters ---------- length : int Number of Identity gates. target : int Which qubit is measured. Returns ------- list Relaxation sequence. ""...
def isiterable(obj): """ isiterable """ return hasattr(obj, '__iter__')
def camel(chars): """ Convert word to camel case """ words = chars.split('_') return "".join(w.lower() if i is 0 else w.title() for i, w in enumerate(words))
def bingo(board: list, called: set) -> bool: """ Determine if the board has bingo based on the set of called numbers. """ transpose = list(zip(*board)) return any(all(x in called for x in row) for row in board) or any( all(x in called for x in row) for row in transpose )
def is_yaml(_path) -> bool: """Return True if file ends with .yaml or .yml, otherwise False.""" if _path.endswith(".yaml") or _path.endswith(".yml"): return True else: return False #try: # with open(_path, "r+") as file: # yaml.load(file) #except yaml.YAMLError: ...
def shell_sort(array): """ Shell Sort algorithm :param array: the array to be sorted. :return: sorted array. >>> import random >>> array = random.sample(range(-50, 50), 100) >>> shell_sort(array) == sorted(array) True >>> import string >>> array = random.choices(string.ascii_lett...
def get_whitespace_cnt(line): """ Return a count of leading tabs/spaces as (tab_cnt, space_cnt). """ tab_cnt = 0 space_cnt = 0 testline = line while testline.startswith('\t'): tab_cnt += 1 testline = testline[1:] testline = line while testline.startswith(' '): space_c...
def smart_import(mpath): """Given a path smart_import will import the module and return the attr reffered to.""" try: rest = __import__(mpath) except ImportError: split = mpath.split('.') rest = smart_import('.'.join(split[:-1])) rest = getattr(rest, split[-1]) return res...
def buffer_to_offset(buffer): """ Convert a byte buffer into an integer offset according to ArcGIS packing scheme: (buffer[0] & 0xff) + (buffer[1] & 0xff) * 2 ** 8 + (buffer[2] & 0xff) * 2 ** 16 + (buffer[3] & 0xff) * 2 ** 24 ... Parameters ---------- buffer: list[bytes] ...
def _get_mechanisms(p_all, cell_type, section_names, mechanisms): """Get mechanism Parameters ---------- cell_type : str The cell type section_names : str The section_names mechanisms : dict of list The mechanism properties to extract Returns ------- mech_pr...
def HWBtoRGB(H, WH, BL): """ convert HWB to RGB color :param H: hue value (0;360) :param WH: white value (0;100) :param BL: black value (0;100) :return: RGB tuple (0;255) """ WH /= 100.0 BL /= 100.0 v = 1.0 - BL if H == -1.0: # if hue is undefined v = int(v * 255) ...
def bytes_to_int(d: bytes) -> int: """Convert the WAMP byte representation to an int. Args: d: Bytes to convert. Returns: Integer value. """ return int.from_bytes(d, "big", signed=False)
def not_in_pycompss(decorator_name): """ Retrieves the "not in PyCOMPSs scope" error message. :param decorator_name: Decorator name which requires the message. :return: String - Not in PyCOMPSs error message. """ return "The " + decorator_name + \ " decorator only works within PyCOMP...
def _find_last_regex_match(a_from_row, a_regex, a_text_list): """ Retreive the previous line number (before `a_from_row') of `a_text_list' that match at least one regular expression of `a_regex'. """ l_row = a_from_row - 1 while l_row >= 0 and not any((a_regex[la_key].match(a_tex...
def is_none(val): """Check for values equivalent to None This will return True if val is one of None, 'none', 'None' """ if not isinstance(val, (type(None), str)): return False return val in [None, 'none', 'None']
def add_spaces_between_special_characters(InputText): """ :param InputText: :return: """ regular = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM " b = set(list(InputText)) spec = [] for i in b: if i not in regular: spec.append(i) for i in spec: ...
def update_dict(old_dict, values): """ Update dictionary without change the original object """ new_dict = old_dict.copy() new_dict.update(values) return new_dict
def is_job_queued(api_job_status_response): """Checks whether a job has been queued or not. Args: api_job_status_response (dict): status response of the job. Returns: Pair[boolean, int]: a pair indicating if the job is queued and in which position. """ is_queued, positi...
def asciiToString(ascii_list): """ Ascii bit data change to String list """ bit_index = 2 charic = 0 string_list = list() for bit in ascii_list: charic += bit*pow(4, bit_index) bit_index -= 1 if bit_index < 0: bit_index = 2 charic += 64 string_list.append(chr(charic)) charic = 0 return stri...
def input_columns_names(picture_size): """ Generate the names of the input columns representing the pixels of the pictures, for a given picture size. """ input_columns = [] for color in 'rgb': input_columns.extend(['%s%i' % (color, i) for i in range(picture_...
def _escape_split(sep, argstr): """ Allows for escaping of the separator: e.g. task:arg='foo\, bar' It should be noted that the way bash et. al. do command line parsing, those single quotes are required. (copied from fabric/main.py) """ escaped_sep = r'\%s' % sep if escaped_sep not in...
def acroname(name): """ Returns a three letter acronym given a podcast title """ if not len(name): return name # return empty string right back word_list = name.split() # first, trim npr label from some podcasts if 'NPR' == word_list[0]: word_list = word_list[1:] if name.star...
def human_time(seconds): """Human-readable duration, e.g. 5m2s or 1h2m. Args: seconds (float): Number of seconds. Returns: unicode: Human-readable duration. """ s = seconds if s < 5: return '{:0.2f}s'.format(s) if s < 60: return '{:0.0f}s'.format(s) ...
def shift(array, default): """ Shift items off the front of the `array` until it is empty, then return `default`. """ try: return array.pop(0) except IndexError: return default
def bound(n): """Accepts a number and requires it to be greater than 2.""" if n < 2: raise ValueError('n must be greater than or equal to 2') return int(n)
def developer(id, name, email, url = None): """ Generates an id/string pair which can be consumed by maven_pom""" if not url: url = "http://github.com/{id}".format(id = id) return "{id}::{name}::{email}::{url}".format(id = id, name = name, email = email, url = url)
def fib_memo(n, memo = None): """Assumes n is an int >= 0, memo used only by recursive calls Returns Fibonacci of n""" if memo == None: memo = {} if n == 0 or n == 1: return 1 try: return memo[n] except KeyError: result = fib_memo(n-1, memo) + fib_memo(n-2, mem...
def rate_each_option(feature_list, option_list): """ rate each feature in each option Parameters ---------- feature_list: list list of features on which to rate each option option_list: list list of options which are being pitted against each other Retu...
def from_doi(doi_identifier): """ Make an ISBN out of the given DOI. .. note:: Taken from https://github.com/xlcnd/isbnlib/issues/30#issuecomment-167444777. .. note:: See https://github.com/xlcnd/isbnlib#note. The returned ISBN may not be issued yet (it is a valid on...
def albedoLandsat57(blue, green, red, nir, chan5, chan7): """ #Broadband albedo Landsat 5TM and 7ETM+, (maybe othetoo but not sure) :param blue: :param green: :param red: :param nir: :param chan5: :param chan7: :return: """ return(0.293 * blue + 0.274 * green + 0.233 * red + 0.1...
def CreateLookUpTable(numStrands, lengthStrands): """ Returns a look up table for the scaffold in string formatm initialized with empty initial values = ''. """ lookUpScaffold = [['' for x in range(lengthStrands)] for y in range(numStrands)] return lookUpScaffold
def getColor(k) : """Homemade legend, returns a nice color for 0 < k < 10 :param k : indice """ colors = ["#862B59","#A10000","#0A6308","#123677","#ff8100","#F28686","#6adf4f","#58ccdd","#3a3536","#00ab7c"] #colors = [(134,43,89,1),(161,0,0,1)] return colors[k]
def get_ext(f_name): """Get the file extension""" for i in range(len(f_name)-1,-1,-1): if f_name[i]=='.': return f_name[i:] return None
def asunicode(x): """ Args: s(bytes or unicode) Returns: bytes Raises: UnicodeDecodeError: bytes with extended-ASCII characters """ if isinstance(x, bytes): return x.decode("utf-8") return x
def sum_first_n(numbers, n): """ What comes in: -- An sequence of numbers. -- A nonnegative integer n that is less than or equal to the length of the given sequence. What goes out: Returns the sum of the first n numbers in the given sequence, where n is the sec...
def code_matrix_puzzle(n:int): """ CodeMatrix and bonus sequences for decipher :param n: choose one in the library :return: """ CodeMatrix=list() Bonus_squence=list() # each code Matrix pair with specific Bonus sequences # the codes now in hexadecimal form, 'BD' is changed '...
def _unpad_data(data: bytes) -> bytes: """ Removes padding from the data according to PKCS7 standard and returns data such that len(new_data) = len(data) - pad_len :param data: the data to unpad :return: the original data without padding """ return data[:-data[-1]]
def find_all(L, x): """Find indexes of all occurrences of *x* in list *L*, and return a list of them.""" out = [] prev = -1 while 1: try: prev = L.index(x,prev+1) out.append(prev) except: return out
def is_integer(n, tolerance=0.): """ Check if `n` is less than `tolerance` away from the nearest integer. """ return abs(n-round(n))<=tolerance
def mblg_to_mw_atkinson_boore_87(mag): """ Convert magnitude value from Mblg to Mw using Atkinson and Boore 1987 conversion equation. Implements equation as in line 1656 in hazgridXnga2.f """ return 2.715 - 0.277 * mag + 0.127 * mag * mag
def has_duplicates_new(l): """ Return True if any list element appears more then once. Return Flase if otherwise. """ d = {} for e in l: d[e] = d.get(e, 0) + 1 if d[e] > 1: return True return False
def pick_any(iterable): """Return any item from iterable, or raise StopIteration if empty.""" return next(iter(iterable))
def ecef_wkt_string(): """ Credit: https://epsg.io/4978 """ result = b"""\ GEOCCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["metre",1, AUTHORITY...
def process_data(data): """ Create a data structure to represent a variable @return a dict """ variable = {} time_step = set() time_averaging = set() notes = set() cmip6_cmor_tables_row_id = set() col_anomaly_type = 2 col_time_step = 3 col_long_name = 4 col_descript...
def process_settings(pelicanobj): """Sets user specified settings (see README for more details)""" # Default settings ovh_settings = {} ovh_settings['config'] = {} # Get the user specified settings try: settings = pelicanobj.settings['MD_OVH'] except: settings = None #...
def build_url(city: str, unit: str, key: str) -> str: """ Build API call url. Parameters: city (str): City name. unit (str): Units system (metric or imperial). key (str): API key. Returns: full_url (str): API call URL. """ api_url = 'http://api.openweathermap.org/data/2.5/weather?q=' if unit == 'm': unit...
def get_shortest_path(pred, orig, dest): """ Get the shortest path to dest given the predecessor list pred from single-source shortest path algorithm Parameters: pred - list of predecessor nodes from a sssp algorithm with orig as source source - source node dest - d...
def match_link(links, name): """ Diagnoses in app have substrings of how diagnosis named in desease list """ keys = links.keys() for k in keys: if k.lower() in name.lower(): return links[k] return ""
def unmask_buff(buff): """ unmask buff, using the firsts 4 bytes as the mask """ mask = buff[:4] return bytes(x ^ mask[i % 4] for i, x in enumerate(buff[4:]))
def _sign(a): """Returns 1 if a > 0, 0 if a == 0, and -1 if a < 0.""" if a == "infinity": return 1 if a == "-infinity": return -1 if int(a) > 0: return 1 if int(a) < 0: return -1 return 0
def uts_to_time(uts): """ Converts Unix Time Stamp to Days and Hours """ uts = int(uts) / 3600 days = 0 hours = 0 while uts - 24 >= 0: days += 1 uts -= 24 * 3600 hours += uts if days == 1: return "1 day ago" elif days > 1: return str(days) + " days ago" ...
def max_sub_seq(arr): """ Problem1 Maximal Uncontinuous Sequence arr = [1, 2, 3, 4] res = 6 (2 + 4) arr = [-1, 1] res = 1 arr = [-1, -1, -1, ...] res = 0 length = 10 ^ 6 dp[i] = max(dp[i - 1], dp[i - 2] + arr[i]) dp[i - 1] = max(dp[i - 2], dp[i - 3] + arr[i - 1]) ...
def get_project_dirname_from_input_path(path): """ Turn .../projects/uid/name or .../projects/uid/name/foo... to uid :param path: ../projects/uid/path :return: project ID """ pos = path.find('/projects/') if pos != -1: pos2 = path.find('/', pos + 10) if pos2 != -1: ...
def _variables_to_structure(variables): """Represents variables a nested dictionary with scope names as keys.""" structure = {} for name, value in variables.items(): fields = name.split("/") cur = structure for i, key in enumerate(fields): if key not in cur: if i + 1 == len(fields): ...
def _resource_duplicate_name_errors(resources): """Validate a `resources` list for duplicate naming. Returns: A list of validation error messages. Empty if all is ok. """ # Nested dict tracking count of resources per type per name. # E.g. { 'some.resource.Type': { 'some-resource-name': 2 } } ty...
def import_object(name): """Function that returns a class in a module given its dot import statement.""" name_module, name_class = name.rsplit('.', 1) module = __import__(name_module, fromlist=[name_class]) return getattr(module, name_class)
def accuracy(correct_count: float, total_count: float) -> float: """ compute accuracy """ if total_count == 0: return 0.0 return correct_count / total_count
def adjust(center, neighbors): """Calculates the mean coordinates of a list of (x, y) tuples Used to calculate the new position of a cluster center """ if len(neighbors) == 0: return center # Watch out for overflow... avg_x = sum([n[0] for n in neighbors]) / len(neighbors) avg_y = s...
def get_file_type(filepath): """Returns the extension of a given filepath or url.""" return filepath.split(".")[-1]
def all_success_returncode(returncode_list): """Check if all of the returncode indicates a success code.""" for returncode in returncode_list: if returncode != 0: return False return True
def check_year(y, s): """Returns True if y is an int, raises an error if y is not None""" if y is not None: if not isinstance(y, int): raise ValueError('arg `{}` must be an integer!'.format(s)) return True
def parse_headers(req_headers): """ Load headers from request to dictionary Args: req_headers (dict): the request's headers Returns: dict: dictionary hosting the request headers """ headers_lst = ["CONTENT-TYPE", "CONTENT-ENCODING", "RESPONSE-FORMAT", "CLEAN"...
def comp_magnetization_dict(self, is_north=True): """Compute the dictionary of the magnetization direction of the magnets (key=magnet_X, value=angle[rad]) Mangetization angle with Hole centered on Ox axis Parameters ---------- self : HoleM54 a HoleM54 object is_north: True True:...
def get_blacklist_scans(subject_id, blacklist_path, new_id=None): """ Finds all entries in <blacklist_path> that belong to the participant with ID <subject_id>. If <new_id> is given, it modifies the found lines to contain the new subject's ID. """ try: with open(blacklist_path, 'r') as b...
def _get_error_message(text): """Prints the error message from the SWISS-MODEL annotation upload page that is returned after a failed submission. As SWISS-MODEL returns an HTML page, this function uses an HTML parser to extract the error message. This is error-prone and might fail if the remote...
def _unwrap_function(func): """Unwrap decorated functions to allow fetching types from them.""" while hasattr(func, "__wrapped__"): func = func.__wrapped__ return func
def id_wo_prefix(block_id): """Shorten a block id by removing the main_inst. prefix if present. """ return block_id[len('main_inst.'):] if block_id.startswith('main_inst.') \ else block_id
def _residual_str(name): """Makes a residual symbol.""" return '\\mathcal{R}(%s)' % name
def is_formatted_text(value: object) -> bool: """ Check whether the input is valid formatted text (for use in assert statements). In case of a callable, it doesn't check the return type. """ if callable(value): return True if isinstance(value, (str, list)): return True if...
def collect_pod_timings(lines): """Finds first log message from each container for every pod. :param lines: Log lines :returns: Dictionary of (container, time) pairs """ timings = {} pod_container = {} start = None for l in lines: # Get pod pod = l.get("pod") co...
def decompose_chrstr(peak_str): """ Take peak name as input and return splitted strs. Args: peak_str (str): peak name. Returns: tuple: splitted peak name. Examples: >>> decompose_chrstr("chr1_111111_222222") "chr1", "111111", "222222" """ *chr_, start, end = ...
def pluralize(n: int, singular: str, plural: str) -> str: """ Use the plural or singular form based on some count. """ return singular if n == 1 else plural
def modified_lorentzian(t, baseline, slope, t0, Delta, Gamma): """ Pressure profile for a vortex Args: t (float array): time baseline (float): baseline against which vortex excursion occurs slope (float): slope against which excursion occurs t0 (float): central time ...
def is_number(s): """Determines whether a string can be converted into a number. :param s: The string to be checked :type s: str :return: If the string can be represented as an integer, True; else, False. :rtype: bool """ try: int(s) return True except ValueError: ...
def get_security_token(owner_info): """Get the security token value. :param owner_info: dictionary containing token value :return: string """ if 'token' in owner_info: return owner_info['token'] else: return ''
def format_dict(data): """Return a formatted string. :param data: a dict :rtype: a string formatted to {a:b, c:d} """ if not isinstance(data, dict): return str(data) return str({str(key): str(value) for key, value in data.items()})
def get_dimension_pv(cprop_mapping, value_mapping, type_key, value_key, entry): """ Get the mapped cprop and value for a dimension in a data entry. Args: cprop_mapping: map of dimension type code to corresponding schema dcid value_mapping: map of dimension type code to map of dimension value to ...
def pseudoCluster(rank): """This is a temporary function to rename processors based on rank.""" if rank < 2: return "node1" elif rank < 4: return "node2" elif rank < 6: return "node3" elif rank < 8: return "node4"
def get_value_key(generator, name): """ Return a key for the given generator and name pair. If name None, no key is generated. """ if name is not None: return f"{generator}+{name}" return None
def fuzzy_string_distance(s, t, costs=(1, 1, 1)): """ iterative_levenshtein(s, t) -> ldist ldist is the Levenshtein distance between the strings s and t. For all i and j, dist[i,j] will contain the Levenshtein distance between the first i characters of s and the first j characters of t """ r...
def format_properties(properties_list): """ create a dict of properties formatted for loading into Nuxeo """ properties = {} repeatables = ("ucldc_schema:collection", "ucldc_schema:campusunit", "ucldc_schema:subjecttopic", "ucldc_schema:contributor", "ucldc_schema:creator", "ucldc_schema:date", "ucldc_schem...
def get_model_top_scope_name(model_name, problem_name): """ Returns the top scope name of all models. Args: model_name: The model string. problem_name: The problem name. Returns: A str. """ if model_name is None: model_name = "SequenceToSequence" return problem_name or ...
def half_split_int(x): """Private function for multiplications""" x_digits = str(x) if len(x_digits) % 2 != 0: x_digits = '0' + x_digits half_index = len(x_digits) // 2 return int(x_digits[:half_index]), int(x_digits[half_index:])
def z_ratio(row): """ get significance value by zscore difference """ row.sort() top1 = row[-1] top2 = row[-2] return(top1-top2)
def decode_text(string): """ decode bytestring as utf-8 """ return string.decode('utf-8')
def get_usage_page_id(full_usage_id): """Extract 16 bits page id from full usage id (32 bits)""" return (full_usage_id >> 16) & 0xffff
def json_filename(symbol): """Appends .json to the string SYMBOL""" return "optionJSON/" + symbol + ".json"
def nucleotide(nucleotide_index): """ Convert nucleotide index to a character. """ nucleotides = ['?','A','C','G','T'] if 1 <= nucleotide_index and nucleotide_index <= 4: return nucleotides[nucleotide_index] return '?'
def _get_fields(errors): """Parses an API call error response and retrieves paths in the API call response and return it as a list of string messages. Args: errors (list): The list of errors returned from the unsuccessful API call Returns: A list of string paths e.g ["pers...
def cam_com(exp, wellu, wellv, fieldx, fieldy, dxcoord, dycoord): """Add a field to the cam list. Return a list with parts for the cam command. """ # pylint: disable=too-many-arguments wellx = str(wellu + 1) welly = str(wellv + 1) fieldx = str(fieldx + 1) fieldy = str(fieldy + 1) r...
def validate_hr_req(req): """ Validates that the information sent to the heart_rate() function is of the correct type for each attribute Args: req: POST request Returns: bool: True if all input data is in the correct format. False if input data is not in correct format ...
def PAPER(n): """ Returns control codes to set the paper colour (0-7). Use this in a ``PRINT`` or ``SET`` command. Example: ``PRINT("normal",PAPER(1),"blue",PAPER(2),"red")`` Args: - n - integer - the paper colour (0-7) """ return "".join((chr(17),chr(int(n))))
def broadcastable_to_str(b): """Return string representation of broadcastable.""" named_broadcastable = { (): "scalar", (False,): "vector", (False, True): "col", (True, False): "row", (False, False): "matrix", } if b in named_broadcastable: bcast = named_b...
def get_rootpath(rootpath, project): """Select the rootpath.""" if project in rootpath: return rootpath[project] if 'default' in rootpath: return rootpath['default'] raise KeyError('default rootpath must be specified in config-user file')
def __IsAscii(srcStr: str) -> bool: """ Check if a string only contains ASCII characters """ try: srcStr.encode('ascii') return True except UnicodeDecodeError: return False except UnicodeEncodeError: return False
def human_readable_number(number: float) -> str: """Print a large number in a readable format. Return a readable format for a number, e.g. 123 milions becomes 123M. Args: number: a float to be printed in human readable format. Returns: readable_number: a string containing the formatted number. """ ...
def is_str(object): """Check if the given object is a string""" return isinstance(object, str)