content
stringlengths
42
6.51k
def snake_to_camel(s: str, upper_first: bool = True) -> str: """Converts "snake_case" to "CamelCase".""" first, *others = s.split("_") return first.title() if upper_first else first.lower() + "".join(map(str.title, others))
def is_debug_mode(job): """ Check if a job in a debug mode, i.e. tail of stdout available or real-time logging is activated in Pilot :param job: dict :return: bool """ if ('specialhandling' in job and not job['specialhandling'] is None and 'debug' in job['specialhandling']) or ( 'com...
def delta_decode(integers): """Turns a list of integers into a new list of integers where the values in the first are treated as deltas to be applied to the previous value. :param list integers: the integers to decode. :rtype: ``list``""" array, last = [], 0 for i in integers: last += ...
def generate_next_number(previous, factor, multiple): """Generates next number in sequence""" while True: value = (previous * factor) % 2147483647 if value % multiple == 0: return value previous = value
def make_input_args_list(funccall): """ Given the way the functional was invoked as a function work out what the argument list is. This list will be used to initialize the input data to the actual subroutine call. The list of arguments is returned. """ data = funccall.split("(") data = data[1].s...
def get_parser_args(args=None): """ Transform args (``None``, ``str``, ``list``, ``dict``) to parser-compatible (list of strings) args. Parameters ---------- args : string, list, dict, default=None Arguments. If dict, '--' are added in front and there should not be positional arguments. ...
def is_valid_pdb(ext): """ Checks if is a valid PDB file """ formats = ['pdb'] return ext in formats
def move_up(node): """Function to move one position down in 8 puzzle if possible Parameters ---------- position : [list] [takes the node configuration from the possible moves as input] Returns ------- [list] [based on the position of 0, it returns the node by swapping the 0...
def dic_with_keys_and_values(hkeys, objvalues): """Factory function using keys and values to make dict.""" if len(hkeys) != len(objvalues): print("Keys' and values' length aren't same!") return None d = dict() for i, key in enumerate(hkeys): d[key] = objvalues[i] return d
def _unpad( s: str, ) -> str: """Unpads a string that was previously padded by _pad(). :param s: The string to unpad :type s: bytes :returns: The unpadded string :rtype: str """ last_character = s[len(s) - 1:] bytes_to_remove = ord(last_character) return s[:-byte...
def composeMap(fun1, fun2, l): """ Returns a new list r where each element in r is fun2(fun1(i)) for the corresponding element i in l :param fun1: function :param fun2: function :param l: list :return: list """ # Fill in new = [] for i in l: t = fun2(fun1(...
def cin2mm(arg): """ Convert 1/100 in to millimeters. Arguments: arg: Number or sequence of numbers. Returns: Converted number or sequence. """ if not type(arg) in [list, tuple]: return float(arg) * 0.254 return [float(j) * 0.254 for j in arg]
def to_list(list_str): """Convert a string to a list. """ # strip list of square brackets and remove all whitespace stripped_list_str = list_str.replace("\n", "")\ .replace(" ", "").replace("\t", "")\ .strip("][").rstrip(",") # check empty list if stripped_list_str == "": ...
def traffic_light(load): """Takes a floating point number load. The function should return the string: "green" for values of load below 0.7 "amber" for values of load equal to or greater than 0.7 but smaller than 0.9 "red" for values of load equal to 0.9 or greater than 0.9""" if load < 0.7: ...
def mapfmt(fmt: bytes, size: int) -> bytes: """ Changes the type of of a format string from 32-bit to 64-bit. WARNING: doesn't handle strings. Example ------- >>> mapfmt(b'2i 6f') b'2q 6d' """ if size == 4: return fmt return fmt.replace(b'i', b'q').replace(b'f', b'd')
def _pick_created_date(parameters_json: dict) -> str: """ Modified 9/28/21 to include additional logic based on collection. Otherwise return first occurrance of: date, or created, or dateSubmitted """ if 'Notre Dame Commencement Program: ' in parameters_json.get('title', ''): return parameters_json['ti...
def avr_name(MCU): """The name of the AVR. Example: __AVR_ATmega328P__ -> ATmega328P """ return MCU.strip('_').split('_')[-1]
def convert_status_flag(status_flag): """Convert a NMEA RMB/RMC status flag to bool. Args: status_flag (str): NMEA status flag, which should be "A" or "V" Returns: True if the status_flag is "A" for Active. """ if status_flag == "A": return True elif status_flag == "V":...
def FLOOR(number): """ Returns the largest integer less than or equal to the specified number. See https://docs.mongodb.com/manual/reference/operator/aggregation/floor/ for more details :param number: The number or field of number :return: Aggregation operator """ return {'$floor': numbe...
def _round_all(numbers): """Internal utility function to round all numbers in a list.""" return [round(n) for n in numbers]
def isTriangle(input): """Check if list of three sides is a triangle.""" if 2 * max(input) < sum(input): return True return False
def average_by_index(scores): """ :param scores: (list) Containing all the scores input by user :return : (float) The average of the elements in scores ---------------------------------------------- This function uses indices in for loop to calculate the average of scores """ total = 0 for i in range(len(score...
def float_or(val, or_val=None): """return val if val is integer Args: val (?): input value to test or_val (?): value to return if val is not an int Returns: ?: val as int otherwise returns or_val """ try: return(float(val)) except: return(or_val)
def _membership_to_list_of_communities(membership_vector, size): """Convert membership vector to list of lists of vertices in each community Parameters ---------- membership_vector : list of int community membership i.e. vertex/label `i` is in community `membership_vector[i]` size : int ...
def brown(text): """ Return this text formatted brown (maroon) """ return '\x0305%s\x03' % text
def get_number_fargs(func): """Return the number of function arguments""" return func.__code__.co_argcount
def _byd_quirk(dvcc, bms, charge_voltage, charge_current, feedback_allowed): """ Quirk for the BYD batteries. When the battery sends CCL=0, float it at 55V. """ if charge_current == 0: return (55, 40, feedback_allowed) return (charge_voltage, charge_current, feedback_allowed)
def func(paramento1, paramentro2='padrao'): """Doc String """ # <bloco de codigo> valor = 0 return valor
def layer_extend(var, default, layers): """Process job input to extend for the proper number of layers.""" # if it's a number if not isinstance(var, list): # change the default to that number default = var # make it a list var = [var] # extend for each layer while len(var) < layers: var...
def to_apple_arch(arch): """converts conan-style architecture into Apple-style arch""" return {'x86': 'i386', 'x86_64': 'x86_64', 'armv7': 'armv7', 'armv8': 'arm64', 'armv8_32': 'arm64_32', 'armv8.3': 'arm64e', 'armv7s': 'armv7s', ...
def is_float(in_value): """Checks if a value is a valid float. Parameters ---------- in_value A variable of any type that we want to check is a float. Returns ------- bool True/False depending on whether it was a float. Examples -------- >>> is_float(1.5) T...
def get_subtitle(raw): """ Extract subtitle if present. @param raw: json object of a Libris edition @type raw: dictionary """ title = raw["mainEntity"].get("hasTitle") return [x.get("subtitle") for x in title if x["@type"] == "Title"][0]
def IsNumber(Value): """Determine whether the specified value is a number by converting it into a float. Arguments: Value (str, int or float): Text Returns: bool : True, Value is a number; Otherwsie, False. """ Status = True if Value is None: return Statu...
def profile_start_step(value): """0 - 99""" return {'step':value}
def make_indent(code: list, quantity): """Makes indents in code""" return list(map(lambda x: ' ' * quantity + x, code))
def part_one(target): """Return the answer to part one of this day Expectation is that the answer is in the correct format""" '''presume each spiral is a box, the box has a length and a max digit value which would be the length ** 2 in the bottom right corner''' def box_len(index): ...
def _tuplik(e, indexes): """ """ if len(e) == 1: return e[0] else: R = [e[i] for i in indexes] if len(R) == 1: return R[0] return R
def interpret_number(s, context=None): """Convert a raw Number value to the integer it represents. This is a little more lenient than the SGF spec: it permits leading and trailing spaces, and spaces between the sign and the numerals. """ return int(s, 10)
def somefx(f, coll): """ Returns the first f(x) for x in coll where f(x) is logical true. If no such element is found, returns None. >>> import string >>> somefx(string.strip, ['', ' ', ' Hello ', ' ']) 'Hello' >>> somefx(string.strip, ['', ' ', ' ']) """ for elem in col...
def get_symlink_output(pull_number, job_name, build_number): """Return the location where the symlink should be created.""" # GCS layout is defined here: # https://github.com/kubernetes/test-infra/tree/master/gubernator#job-artifact-gcs-layout if not pull_number: # Symlinks are only created for pull request...
def check_channels_presence(task, channels, *args, **kwargs): """ Check that all the channels are correctly defined on the PNA. """ if kwargs.get('test_instr'): traceback = {} err_path = task.get_error_path() with task.test_driver() as instr: if instr is None: ...
def parse_specific_gate_opts(strategy, fit_opts): """Parse the options from ``fit_opts`` which are relevant for ``strategy``. """ gate_opts = { 'tol': fit_opts['tol'], 'steps': fit_opts['steps'], 'init_simple_guess': fit_opts['init_simple_guess'], 'condition_tensors': fit_opt...
def adjust_points(points, adjust_x, adjust_y): """Adjust points based by adjust_x and adjust_y.""" adjusted = [] for point_x, point_y in points: adjusted.append((point_x - adjust_x, point_y - adjust_y)) return adjusted
def in_nD_list(search_list, key): """ Find element in non-uniform nD list recursively >>> in_nD_list(["++--,.", ["++>-", [">++"]], [["+"], [["-"]]]], "]") False """ for element in search_list: if isinstance(element, str): if key in element: break else: ...
def grad_logp(p, alpha0, x): """ d log p / dz """ return (alpha0-1.+x)/p
def red(text): """Returns a string with ANSI codes for red color and reset color wrapping the provided text. """ return '\033[31m%s\033[39m' % text
def getFirst(decod): """Returns the firs decoded symbol or 0 if we haven't decoded anything""" if decod: return decod[0] return 0
def get_is_not_entity_from_full_name(name): """ iterates through the name and checks for a set of rules that identify that the name belongs to an entity (as opposed to an artist) Rules: - if the name is suffixed with a comma ',' (ex. "hats incredible, inc., braintree, ma") - if the name ...
def zipit(list_of_items): """Zips different hyperparameter settings.""" if len(list_of_items) == 1: return list_of_items[0] main_items = list_of_items[0] other_items = zipit(list_of_items[1:]) if len(main_items) != len(other_items): if len(main_items) == 1: main_items *= len(other_items) eli...
def remove_duplicates(data: list) -> list: """ Remove duplicated elements from list Args: data: incoming data with duplicates Returns: Cleaned data """ result: list = [] devices: dict = {} for element in data: if element["protocol"] == "ubnt": devices[e...
def check_branch(pr_branch, label, label_branch): """Detects necessary labels based on the branch :return: list of labels """ labels = [] if pr_branch == label_branch: print(f"Detected label from branch. Adding label {label}") labels.append(label) return labels
def extract_tag(tag_list, key): """ Summary: Search tag list for prescence of tag matching key parameter Returns: tag, TYPE: list """ if {x['Key']: x['Value'] for x in tag_list}.get(key): return list(filter(lambda x: x['Key'] == key, tag_list))[0] return []
def auto_typecast(value): """ Automatically convert a string into its desired data type. :param value: The value to be converted. Example:: >>> bpy.auto_typecast("True") True >>> bpy.auto_typecast("1.2345") 1.2345 """ str_to_bool = lambda x: { "True": True, "Fa...
def list_unique_values(dictionary): """ Return all the unique values from `dictionary`'s values lists except `None` and `dictionary`'s keys where these values appeared Args: dictionary: dictionary which values are lists or None Returns: dict where keys are unique values from `dicti...
def getSeconds(text): """ translates file time format into seconds :param text: input time format :return: seconds as string """ text = text.lower().strip('pts') seconds = 0 if not text == "" and 'h' in text: hours, text = text.split('h') seconds += int(hours) * 3600 ...
def groom_repdb (data): """ data is a list. """ groomed = [] ok_keys = \ [ "created_date", "data", "data_type", "derived", "derived_type", "source", "source_url", ] for d in data: gd = {} for k, v in d.items(): if k in ok_keys: gd[k]...
def remove_filename_in_path(path): """remove the file name from a path Args: path (str): complete path Returns: complete path without the file name """ splitter = "\\" if len(path.split("\\")) > 1 else "/" path_list = path.split(splitter)[:-1] return "".join(elt + splitter ...
def getallis(l,match): """ get all indices of match pattern in list """ return [i for i, x in enumerate(l) if x == match]
def cleanjoin(listlike, join_on=""): """ returns string of joined items in list, removing whitespace """ return join_on.join([text.strip() for text in listlike]).strip()
def column_is_foreign_key(column): """Returns whether a column object is marked as a foreign key.""" foreign_key = column['is foreign key'] if isinstance(foreign_key, str): foreign_key = foreign_key.lower() if foreign_key in {'y', 'n', 'yes', 'no', '-'}: foreign_key = foreign_key in {'y', 'yes'} ...
def event_team_object_factory(event_id, team_id): """Cook up a fake eventteam json object from given ids.""" eventteam = { 'event_id': event_id, 'team_id': team_id } return eventteam
def build_features(x, y, sentence, features_functions, i_shift=0): """applies predefined functions on one sample returns shifted (corrected) data,i,j i_shift is the row number, calling function is responsible setting it """ data, i, j = [], [], [] for ind, f in enumerate(features_functions): ...
def get_name(name): """ Generates a pretty(er) name from a database table name. """ return name[name.find("_") + 1:].replace("_", " ").capitalize()
def _prefix_confound_filter(prefix, all_compcor_name): """Get confound columns by prefix and acompcor mask.""" compcor_cols_filt = [] for nn in range(len(all_compcor_name)): nn_str = str(nn).zfill(2) compcor_col = f"{prefix}_comp_cor_{nn_str}" compcor_cols_filt.append(compcor_col) ...
def _DisposeCircularBitInfo(bitInfo, minRadius=1, maxFragment=True): """Dispose the bitinfo retrived from GetFoldedCircularFragment() or GetUnfoldedCircularFragment() *internal only* """ allFragments = list(bitInfo.keys()) station = {} # maxFragments = [] for idx, pairs in bitInfo.items(): ...
def intersect(s1, s2): """ Returns the intersection of two slices (which must have the same step). Parameters ---------- s1, s2 : slice The slices to intersect. Returns ------- slice """ assert (s1.step is None and s2.step is None) or s1.step == s2.step, \ "Only i...
def print_settings(silent, buffer_length=14, **kwargs): """ Function that dynamically prints out a list of key-value pairs as passed. Means that when this function can be """ # ............................................................ def strbuffer(local_string): """ ...
def get_change(current: float, previous: float) -> float: """Get the percent change.""" if current == previous: return 100.0 if previous != 0: return (abs(current - previous) / previous) * 100.0 else: return 0
def make_event(data_line): """ Given a line of data from a tab separated data file, return a dict containing the data for the event :param data_line: :return: dict """ return dict(zip(['tag', 'label', 'url', 'start', 'end'], data_line.strip('\n').split('\t')))
def select(item, truth): """This will only work when item is a pointer""" if truth: return item else: return None
def dict_to_string(data): """Takes a dictionary and converts it to a string to send over serial connection with Micro:Bit Args: data: Dict Returns: str: JSON string of the data. """ return (str(data).replace("'", '"') .replace(": False", ": false") ...
def concatixnames(ixname='ix', source_suffix='source', target_suffix='target'): """ Args: ixname (str): 'ix' source_suffix (str): 'left' target_suffix (str): 'right' Returns: str, str, list(): 'ix_source', 'ix_target', ['ix_source', 'ix_target'] """ ixnamesource = '...
def retry_ntime(ret, func, c, uri): """Retry function given times.""" for cnt in range(ret): if func: return True else: print("[%s/%d]: Retrying..." % (c[0], c[1]), "COUNT:%d" % (cnt + 1), end="\r") print("[%s/%d]:" % (c[0], c[1]), "<FAIL> %s" % uri)...
def __version_compare(v1, v2): """ Compare two Commander version versions and will return: 1 if version 1 is bigger 0 if equal -1 if version 2 is bigger """ # This will split both the versions by '.' arr1 = v1.split(".") arr2 = v2.split(".") n = len(arr1) m =...
def escape_desc(desc): """Escape `desc` suitable for a doc comment.""" if desc is not None: return desc.replace("[", "\\[").replace("]", "\\]") else: return ""
def __get_season_for_month(month): """ This method get the season for a specific month for a number of a month. @param month: A month in number @return the season in string format, and the season in string format. """ season = int(month)%12 // 3 + 1 season_str = "" if s...
def top_level(symbol): """A rule that matches top-level symbols.""" return (symbol and ('.' not in symbol)) or None
def without_score(contribution): """Returns a contribution without the score.""" return {x: contribution[x] for x in contribution if x != "score"}
def compute_union_of_regions( regions ): """Compute a non-overlapping set of regions covering the same position as the input regions. Input is a list of lists or tuples [ [a1,b1], ... ] Output is a similar list. All regions are assumed to be closed i.e. to contain their endpoints""" result = [] reg...
def set_rois_file(filepathstr): """ return None or path to file containing rois list""" if filepathstr == "None": roisfilepath = None # fullpath else: roisfilepath = filepathstr return roisfilepath
def is_file_like(obj): """ Indicates whether a specified value is a 'file-like' object. :param obj: the object/value. :return: >>> is_file_like(None) False >>> is_file_like(1) False >>> is_file_like('') False >>> is_file_like('abc') False >>> is_file_like([1, 2]...
def float_dot_zero(qt: float) -> bool: """ Returns true if a float ends in .0 (and so can be converted to an integer without losing data). All other situations return false Args: qt (float): the quantity to check Returns: bool: if the float ends in .0 """ if isinstance(qt, floa...
def clean_al(alg, code="ACDEFGHIKLMNPQRSTVWY", gap="-"): """ Replaces any character that is not a valid amino acid by a gap. **Arguments** amino acid sequence alignment **Key Arguments** :code: list of valid amino acid characters (case sensitive) :gap: gap character for replacement "...
def build_job_data(data): """ Args: data: any kind of object. Returns: list: list of jobs """ def build_entry(entry_data): entry = dict() entry['JobID'] = entry_data.get('job_id') entry['SampleID'] = entry_data.get('job_sample_id') entry['Submission...
def list_difference(list1, list2): """ Returns the difference of the two given lists. Parameters ---------- list1 : `None`, `list`, `set` The first list, what's inclusive elements should go into the return's zero-th element. list2 : `None`, `list`, `set` The second list, wha...
def convert_ID(mobile_number): """ Covert valid mobile to ID phone code""" number_str = ''.join(filter(str.isdigit, str(mobile_number))) if number_str[:2]=='08': number_str = '62'+number_str[1:] elif number_str[:1] == '8' : number_str = '62'+number_str[0:] return number_str
def clients_url(tenant_url): """Returns the clients API endpoint for a given tenant """ return '{0}/clients/v2'.format(tenant_url)
def checkOperatorPrecedence(a,b): """ 0 if a's precedence is more than b operator 1 otherwise """ check={} check['(']=1 check['*']=2 check['/']=2 check['-']=3 check['+']=3 if check[a] <= check[b]: return 1 else: return 0
def rComp(sequence): """Reverse complements a sequence, preserving case.""" d={'A':'T','T':'A','C':'G','G':'C','a':'t','t':'a','c':'g','g':'c','N':'N','n':'n'} cSeq='' for s in sequence: cSeq+=d[s] cSeq=cSeq[::-1] return cSeq
def is_grease(int_value): """ Returns if a value is GREASE. See https://tools.ietf.org/html/draft-ietf-tls-grease-01 """ hex_str = hex(int_value)[2:].lower() if len(hex_str) < 4: return False first_byte = hex_str[0:2] last_byte = hex_str[-2:] return ( first_byte[1...
def build_data(license): """Return the data to send in the POST request.""" return {"LicNumber": str(license), "SSNumber": None, "DOB": None, "firstname": None, "lastname": None, "B1": "Submit"}
def is_hide(x, y, mat): """ :param x: coordonata x :param y: coordonata y :param mat: matricea nodului curent :return: daca este ascunzatoare pentru soricel """ if 0 < x < len(mat) and 0 < y < len(mat): return mat[x][y] == "@"
def jinja_indent(_in_str, level): """ Indentation helper for the jinja2 templates """ _in_str = str(_in_str) return "\n".join( ["" if not line else level * " " + line for line in _in_str.split("\n")] )
def to_bool(s, default=False): """ Convert an arbitrary 0/1/T/F/Y/N string to a boolean True/False value.""" if isinstance(s, str) and s: if s[0].lower() in ['1', 't', 'y']: return True elif s[0].lower() in ['0', 'f', 'n']: return False elif isinstance(s, bool): ...
def assemble_haplotypes(snps): """Input phased SNPS data. Assemble haplotype strings for two chromosomes.""" h = {"A": {}, "B": {}} for snp in snps: if snp.gt == "1|0": h["A"][snp.pos] = snp.alt h["B"][snp.pos] = snp.ref elif snp.gt == "0|1": h["A"][snp.po...
def ground_truth_MaxAR(n, phi): """Determine the ground truth for the extremal index for data generated by an MAxAR model with inverse-weibull distributed errors PARAMETERS: n : number of rows phi : autoregressive coefficient """ gt = 1- phi return gt
def _renderatts(atts): """ Used by Parser and Node classes to render tag attributes. atts : list of (str, str | None) -- zero or more key-value pairs (note: string values must be HTML-encoded) Result : str """ return ''.join(((' ' + name) if value is None else ' {}="{}"'.format(name, value)) for name, value in...
def validate_dog_age(letter): """this function takes a letter as age and returns a tuple or range of ages""" if "b" or "y" or "a" or "s" in letter: return (1, 97) elif "b" or "y" in letter: return (1, 26) elif "a" or "s" in letter: return (25, 97) elif 'b' in letter: ...
def read_file(f): """ Read an entire file and return the contents """ with open(f) as f: return f.read()
def _strtime2int(t: str) -> int: """ >>> _strtime2int("11:15") 1115 """ return int("".join(t.split(":")))