content
stringlengths
42
6.51k
def max_abs(lst): """ return largest abs value element of a list """ return max(abs(num) for num in lst)
def linspace(start, stop, n): """ Programa que entrega un arreglo de numeros equitativamnte espaciado de n elementos empe_ zando en start y hasta stop. _Doctest >>> linspace(-5,5,3) [-5.0, 0.0, 5.0] """ step = (stop-start)/(n-1) return [start+step*(i) for i in range(n)]
def cleanup_user(user): """Given a dictionary of a user, return a new dictionary for output as JSON.""" return {"id" : str(user["_id"])}
def isbad(qlink): """ filter out bad links. """ if None == qlink or '' == qlink: return True if (qlink.startswith('http://') and ( qlink.endswith('.html') or qlink.endswith('.htm') or qlink.endswith('.php') or qlink.endswith('.pl') or qlink.endswith('/'))): return False else: return True
def AsList(arg): """return the given argument unchanged if already a list or tuple, otherwise return a single element list""" return arg if isinstance(arg, (tuple, list)) else [arg]
def planet(size): """Construct a planet of some size.""" assert size > 0 "*** YOUR CODE HERE ***" return ['planet', size]
def list_dict(l): """ return a dictionary with all items of l being the keys of the dictionary """ d = {} for i in l: d[i]=None return d
def lerp2d(a: tuple, b: tuple, r: float) -> tuple: """Returns a point interpolated from a to b, at r.""" return ( a[0] + (b[0] - a[0]) * r, a[1] + (b[1] - a[1]) * r )
def _make_option(options): """Help make regex options from string Example: >>> _make_option('# // --') '(#|//|--)' """ return '(' + '|'.join(options.split()) + ')'
def negbin(old): """ Given a binary number as an string, it returns all bits negated """ return ''.join(('0','1')[x=='0'] for x in old)
def find_largest_digit_helper(n, max_int): """ This function find the biggest int by using the backtracking method. ----------------------------------- :param n: (int) number. :param max_int: (int) help update the biggest digit in integers. :return: ans: (int) the biggest integers. """ # When int is smaller than zero. if n < 0: n //= -1 # Base Case if n < 10: if n % 10 > max_int: max_int = n % 10 return max_int # Recursion else: current = n % 10 if current > max_int: max_int = current ans = find_largest_digit_helper(n // 10, max_int) return ans # ans = find_largest_digit_helper(n // 10, max_int) # return ans # else: # ans = find_largest_digit_helper(n // 10, max_int) # return ans
def mark_no_copy_rules(grammar): """ Takes a 'simple' grammar where each rule is not marked as being a copy rule or not, and returns the same grammar but with an extra field that marks that this rule is not a copy rule (False) """ return [ (lhs,[ (r,False) for r in rhs ]) for (lhs,rhs) in grammar ]
def get_sma(data_points) -> float: """ Returns simple moving average """ return sum(data_points) / len(data_points)
def roq_transform(pressure, loading): """Rouquerol transform function.""" return loading * (1 - pressure)
def vertical_op(c, latex=False, op='and', spacing=1): """Return TLA conjunction with one conjunct per line.""" assert op in {'and', 'or'}, op if not c: r = 'TRUE' if op == 'and' else 'FALSE' return r # singleton ? if len(c) == 1: return c[0] if latex: pref = 4 * ' ' nl = r' \\' + '\n' else: pref = '/\\ ' if op == 'and' else '\/ ' nl = '\n' * spacing r = list() for s in c: t = s.split('\n') t[0] = '{p}{first}'.format(p=pref, first=t[0]) sep = '\n{indent}'.format(indent=len(pref) * ' ') e = sep.join(t) r.append(e) r = nl.join(r) env = 'conj' if op == 'and' else 'disj' if latex: r = ('\\begin{' + env + '}\n' + r + '\n\\end{' + env + '}') return r
def get_uploader_image(base_images_project): """Returns the uploader base image in |base_images_project|.""" return f'gcr.io/{base_images_project}/uploader'
def disjunct2Lists(l1, l2): """OR 2 posting lists --> return a list""" p1 = p2 = 0 resultDocs = [] while p1 < len(l1) and p2 < len(l2): if l1[p1] == l2[p2]: resultDocs.append(l1[p1]) p1 = p1 + 1 p2 = p2 + 1 elif (l1[p1]) < (l2[p2]): resultDocs.append(l1[p1]) p1 = p1 + 1 else: resultDocs.append(l2[p2]) p2 = p2 + 1 if p1 < len(l1): resultDocs.extend(l1[p1:]) elif p2 < len(l2): resultDocs.extend(l2[p2:]) return resultDocs
def encode(string_): """Change String to Integers""" return (lambda f, s: f(list( ord(c) for c in str(string_) ) , \ s))(lambda f, s: sum(f[i] * 256 ** i for i in \ range(len(f))), str(string_))
def u_init(x, xmin, xmax): """ initial condition """ middle = 0.5*(xmin+xmax) width = 0.1*(xmax-xmin) x_centered = xmin + x % (xmax-xmin) middle = 0.5*(xmin+xmax) return 0.25 \ + .125/width**10 * (x_centered-middle-width)**5 \ * (middle-x_centered-width)**5 \ * (abs(x_centered-middle) <= width)
def linear_search(L, e): """ Function of linear searching a list to look for specific element Complexity: O(n) :param L: List-object :param e: Element to look for :return: Boolean value if element has been found """ found = False for i in range(len(L)): if e == L[i]: found = True return found
def timer(start, end): """ Give duration time between 2 times in hh:mm:ss. Parameters ---------- start: float the starting time. end: float the ending time. """ hours, rem = divmod(end-start, 3600) minutes, seconds = divmod(rem, 60) return("{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds))
def confidence_to_level(confidence: int) -> str: """Maps the confidence of a finding to a SARIF level.""" if confidence < 70: return "warning" else: return "error"
def _make_percentage_energy(network, sun): """ Calculates the percentage of the energy consumed by the electrical network and by solar system. """ sun_percentage = sun/network network_percentage = 1 - sun_percentage if sun_percentage >= 1: return 1, 0 else: return sun_percentage, network_percentage
def ek(cell): """ Returns the WT reversal potential (in mV) for the given integer index ``cell``. """ reversal_potentials = { 1: -91.6, 2: -92.8, 3: -95.1, 4: -92.3, 5: -106.1 } return reversal_potentials[cell]
def pixel_tag(path): """ Build the HTML surrounding a given image path that will be injected as a tracking pixel. :param path: URL path to the tracking pixel. :type request: string :returns: HTML markup for image tag. :rtype: string """ return ('<img style="height:0;width:0;position:absolute;" ' 'src="%s" alt="" />' % path)
def combinations(n: int, k: int) -> int: """Compute :math:`\binom{n}{k}`, the number of combinations of *n* things taken *k* at a time. :param n: integer size of population :param k: groups within the population :returns: :math:`\binom{n}{k}` """ # An important consideration here is that someone hasn't confused # the two argument values. # :: assert k <= n # Here's the embedded factorial function. It's recursive. The Python # stack limit is a limitation on the size of numbers we can use. # :: def fact(a: int) -> int: if a == 0: return 1 return a*fact(a-1) # Here's the final calculation. Note that we're using integer division. # Otherwise, we'd get an unexpected conversion to float. # :: return fact(n)//(fact(k)*fact(n-k))
def _parse_args(arg): """Split all the string arg into a list of args.""" return arg.split()
def numero_digitos(n): """ processo iterativo """ res=1 while not n<10: res+= 1 n= n//10 return res
def clean_int(v): """Remove commas from a float""" if v is None or not str(v).strip(): return None return int(str(v).replace(',', '').replace(' ',''))
def serialize_anonymous_subscriber_forms(cleaned_data): """ Return the shape directory-api-client expects for saving international buyers. @param {dict} cleaned_data - All the fields in `AnonymousSubscribeForm` @returns dict """ return { 'name': cleaned_data['full_name'], 'email': cleaned_data['email_address'], 'sector': cleaned_data['sector'], 'company_name': cleaned_data['company_name'], 'country': cleaned_data['country'], }
def parse_local_mounts(xs): """ process block device info returned by device-scanner to produce a legacy version of local mounts """ return [(d["source"], d["target"], d["fstype"]) for d in xs]
def _list_to_regex_component(l, max_ambiguity = 3): """ list of str to regex Parameters ---------- l : list list of strings max_ambiguity : int default is 3, more than max results in '.' rather than a set [] Example ------- >>> _list_to_regex_component(['A']) 'A' >>> _list_to_regex_component(['A','T','C']) '[ATC]' >>> _list_to_regex_component(['A','T','C','G']) '.' >>> _list_to_regex_component(['A','-','C']) '[AC]?' """ if len(l) < 1: s = '.?' elif len(l) < 2: s = l[0] elif len(l) <= max_ambiguity: s = f"[{''.join(l)}]" else: s = '.' if s == '-': s = s.replace('-', '.?') elif s.find('-') != -1: s = s.replace('-', '') s = f"{s}?" return s
def extract_core_orgs(orgs, project_rcn): """Seperate a project-organisation (which) is likely to be a department, with a non-unique address. Args: orgs (list): List of organiations to process (NB: this will be modified) project_rcn (str): The record number of this project Returns: core_orgs (list): The unique 'parent' organisations. """ core_orgs = [] for org in orgs: ctry = org.pop('country') core_orgs.append({'name': org.pop('name'), 'id': org['organization_id'], 'country_code': ctry['isoCode'], 'country_name': ctry['name']}) return core_orgs
def f1_score(recall, precision): """ This function is used to calculate the f1_score :param recall: This is the value of recall :param precision: This is the value of precision :return: the f1_score """ return (2 * recall * precision) / float(recall + precision)
def by_tag(tag, tiddlers): """ Return those tiddlers that have tag tag. """ return [tiddler for tiddler in tiddlers if tag in tiddler.tags]
def sanitise_config(config): """Return a sanitised configuration of a switch device. :param config: a configuration dict to sanitise. :returns: a copy of the configuration, with sensitive fields removed. """ sanitised_fields = {"password"} return { key: "******" if key in sanitised_fields else value for key, value in config.items() }
def counting_sort(array, maxval): """in-place counting sort""" n = len(array) m = maxval + 1 count = [0] * m # init with zeros for a in array: count[a] += 1 # count occurences i = 0 for a in range(m): # emit for c in range(count[a]): # - emit 'count[a]' copies of 'a' array[i] = a i += 1 return array
def parse_replicon_field(accession_string): """Return a list of accessions""" accessions = list() replicons = accession_string.split('; ') for replicon in replicons: replicon_accession = replicon.split('/')[-1] replicon_accession = replicon_accession.split(':')[-1] accessions.append(replicon_accession) return accessions
def format_job_instance(job): """ Format the job instance correctly """ ret = { "Function": job.get("fun", "unknown-function"), "Arguments": list(job.get("arg", [])), # unlikely but safeguard from invalid returns "Target": job.get("tgt", "unknown-target"), "Target-type": job.get("tgt_type", "list"), "User": job.get("user", "root"), } if "metadata" in job: ret["Metadata"] = job.get("metadata", {}) else: if "kwargs" in job: if "metadata" in job["kwargs"]: ret["Metadata"] = job["kwargs"].get("metadata", {}) return ret
def bound(x, bounds): """ restrict x to a range of bounds = [min, max]""" return min(max(x, bounds[0]), bounds[1])
def is_complex(num): """Judge whether the number is a complex.""" try: complex(num) except Exception: return False return True
def get_highest_bench_points(bench_points): """ Returns a tuple of the team with the highest scoring bench :param bench_points: List [(team_name, std_points)] :return: Tuple (team_name, std_points) of the team with most std_points """ max_tup = ("team_name", 0) for tup in bench_points: if tup[1] > max_tup[1]: max_tup = tup return max_tup
def _optionxform(optionname): """Used by the configfile parsers.""" return optionname.lower().replace('-', '_')
def is_archive(filepath): """Determines if a filepath indicates that it's an archive.""" exts = [ ".tar.bz2", ".tar.gz", ] for ext in exts: if filepath.endswith(ext): return True return False
def qualified_name_tuple(cls): """ Get the module name and the thing-name for a class. e.g. ('instakit.processors.halftone', 'FloydSteinberg') """ mod_name = getattr(cls, '__module__') cls_name = getattr(cls, '__qualname__', getattr(cls, '__name__')) return mod_name, cls_name
def category_hamming_dist(x, y): """Counts number of mismatches as distance between two lists""" dist = 0 for i in range(0, len(x)): if x[i] != y[i]: dist += 1 return dist
def get_stats(tp, tn, fp, fn): """ Computes performace measures using the correctness measures returned by check_preds() Parameters: ----------------- tp: number of true positive predictions returned by check_preds() fp: number of false positive predictions returned by check_preds() tn: number of true negative predictions returned by check_preds() fn: number of false negative predictions returned by check_preds() Returns: ----------------- acc: (tp + tn) / (tp + tn + fp + fn) recall: tp / (tp + fn) precision: tp / (tp + fp) fscore: F1 Score, 2 * precision * recall / (precision + recall) """ acc = (tp + tn) / (tp + tn + fp + fn) recall = 0.0 precision = 0.0 fscore = 0.0 if tp == 0.0: if fp == 0.0 and fn == 0.0: recall, precision, fscore = 1.0, 1.0, 1.0 else: recall, precision, fscore = 0.0, 0.0, 0.0 else: recall = tp / (tp + fn) precision = tp / (tp + fp) fscore = 2 * precision * recall / (precision + recall) return (acc, recall, precision, fscore)
def humanize_bytes(bytesize, precision=2): """ Humanize byte size figures https://gist.github.com/moird/3684595 """ abbrevs = ( (1 << 50, 'PB'), (1 << 40, 'TB'), (1 << 30, 'GB'), (1 << 20, 'MB'), (1 << 10, 'kB'), (1, 'bytes') ) if bytesize == 1: return '1 byte' factor, suffix = 1, "bytes" for factor, suffix in abbrevs: if bytesize >= factor: break if factor == 1: precision = 0 return '%.*f %s' % (precision, bytesize / float(factor), suffix)
def get_name(node_name): """ Omit any parenting information from the provided node name. :param str node_name: :return: Name :rtype: str """ return node_name.rsplit("|", 1)[-1]
def list_cycles(grammar, max_count, parent, length, counts, prev_pair=""): """Restricted to max_count""" counts[prev_pair] += 1 result = ( [parent] if length == 1 else [ parent + x for node in grammar[parent] for x in list_cycles( grammar, max_count, node, length - 1, counts, parent + node ) if counts[parent + node] < max_count ] ) counts[prev_pair] -= 1 return result
def arithmetic_series_recur(n): """Arithmetic series by recursion. Time complexity: O(n). Space complexity: O(n) """ # Base case. if n <= 1: return n return n + arithmetic_series_recur(n - 1)
def odd_or_even(number): """Determine if a number is odd or even.""" if number % 2 == 0: # se o resto da divicao for zero return 'Even' # Par else: return 'Odd'
def convert(elts): """Convert a list of tuples into a dictionary Arguments: elts {list} -- List of tuples Returns: dict -- List of tuples converted into a dictionary """ if not elts: return {} result = {k: v for (k, v, *_) in elts} return result
def _match_file_path(path, level, v): """Helper function to match part.""" if v == "*" or v is True: try: path[level] return True except IndexError: return False else: return path[level] == v
def NZ(PassedValue,ValueIfNone=""): """ This function replaces the first argument with the second if the first argument is None. By default the second argument is an empty string. """ if PassedValue: return PassedValue else: return ValueIfNone
def has_prefix(words, sub_s): """ :param sub_s: :return: """ for word in words: if word.startswith(sub_s): return True
def PNT2TidalOcto_Pv14(XA,beta0PNT=0): """ TaylorT2 0PN Octopolar Tidal Coefficient, v^14 Phasing Term. XA = mass fraction of object beta0PNT = 0PN Octopole Tidal Flux coefficient """ return (5)/(9)*(520+beta0PNT)-(2600*XA)/(9)
def is_number(number): """ Check whether this is a number (int, long, float, hex) . Aruguments: number: {string}, input string for number check. """ try: float(number) # for int, long, float except ValueError: try: int(number, 16) # for possible hex except ValueError: return False return True
def get_player_id(first_name, last_name, team): """ Returns a custom player ID of first initial + last name + team i.e. for Tom Brady in New England that is T.Brady-NE """ if (team == None): team = 'None' return first_name[0] + "." + last_name + "-" + team
def _make_divisible(v, divisor, min_value=None): """ Taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param divisor: :param min_value: :return: """ if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v < 0.9 * v: new_v += divisor return new_v
def divideEdge(slon,slat,shgt,elon,elat,ehgt,cnt): """ Make interleaving point for dividing a long edge """ dlon = (elon-slon)/cnt; dlat = (elat-slat)/cnt; dhgt = (ehgt-shgt)/cnt; lonlats = [(slon+i*dlon,slat+i*dlat,shgt+i*dhgt) for i in range(1,cnt)] return lonlats
def sum_list(input_list: list) -> int: """ Sums the values of a list :param input_list: :return: the sum of the values """ result = 0 for i in input_list: result += i return result
def cancel_run_endpoint(host): """ Utility function to generate the get run endpoint given the host. """ return f'https://{host}/api/2.1/jobs/runs/cancel'
def live_accounts_agg(metric): """ Computes the fraction of editors that have "live" accounts """ total = 0 pos = 0 for r in metric.__iter__(): try: if r[1]: pos += 1 total += 1 except (IndexError, TypeError): continue if total: return [total, pos, float(pos) / total] else: return [total, pos, 0.0]
def is_linear(reg_type): """ Checks whether a regression type is linear. """ return reg_type == "linear"
def num_days_months(y): """ For a given year, provide the number of days of each month. """ ndays = [31,28,31,30,31,30,31,31,30,31,30,31] if y%4 == 0: ndays[1] = 29 return ndays
def parse_line(line_data): """ Return the (line number, left hand side, right hand side) of a stripped postfix config line. Lines are like: smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache """ num,line = line_data left, sep, right = line.partition("=") if not sep: return None return (num, left.strip(), right.strip())
def make_qs(pd): """ convert back from dict to qs """ query = [] for k,vl in pd.items(): for v in vl: pair = v and "%s=%s" % (k,v) or k query.append(pair) return "&".join(query)
def process(data, template_name_key, split_char=";", **kwargs): """ Function to split templates. e.g. if ``template_name_key`` value contains several templates, this processor will split them using ``split_char`` and produce data item for each template coping data accordingly. :param data: list of dictionaries to process :param template_name_key: string, name of the template key :param split_char: str, character to use to split template names """ ret = [] # iterate over data and split templates while data: item = data.pop(0) # run sanity check if not isinstance(item.get(template_name_key, None), str): continue # do templates split if any if split_char in item[template_name_key]: templates = [i.strip() for i in item.pop(template_name_key).split(split_char)] for t_name in templates: item_copy = item.copy() item_copy[template_name_key] = t_name ret.append(item_copy) else: ret.append(item) del data return ret
def dispatch(func, *args, **kwargs): """ Dynamic abstracted task for pre-registration of celery tasks. Arguments: func (callable): Function to deserialize and call. *args (list, tuple): Arguments to pass to function. **kwargs (dict): Keyword arguments to pass to function. """ return func(*args, **kwargs)
def lin(variable): """ Turn variable into the linear domain. Args: variable (float): array of elements to be transformed. Returns: float:array of elements transformed """ lin = 10**(variable/10) return lin
def get_subverts(voxel, g, step): """return list (len=8) of point coordinates (x,y,z) that are vertices of the voxel (i,j,k)""" (i, j, k) = voxel dx, dy, dz = g["dx"], g["dy"], g["dz"] DX, DY, DZ = step v1_0, v1_1, v1_2 = g["xlo"] + i * dx, g["ylo"] + j * dy, g["zlo"] + k * dz vertices = [ (v1_0, v1_1, v1_2), (v1_0 + DX, v1_1, v1_2), (v1_0 + DX, v1_1 + DY, v1_2), (v1_0, v1_1 + DY, v1_2), (v1_0, v1_1, v1_2 + DZ), (v1_0 + DX, v1_1, v1_2 + DZ), (v1_0 + DX, v1_1 + DY, v1_2 + DZ), (v1_0, v1_1 + DY, v1_2 + DZ), ] return vertices
def binomial_coeff_recursive(n, k): #This is the author's original version """Uses recursion to compute the binomial coefficient "n choose k" n: number of trials k: number of successes returns: int """ if k == 0: return 1 if n == 0: return 0 res = binomial_coeff_recursive(n-1, k) + binomial_coeff_recursive(n-1, k-1) return res
def notes_to_intervals(notes: list) -> list: """Convert a list of MIDI pitches to a list of intervals. >>> notes_to_intervals([60, 62, 64, 60]) [2, 2, -4] Parameters ---------- notes : list The notes, as MIDI pitches Returns ------- list The intervals """ pairs = zip(notes[:-1], notes[1:]) get_interval = lambda pair: pair[1] - pair[0] intervals = list(map(get_interval, pairs)) return intervals
def _UnorderableListDifference(expected, actual): """Same behavior as _SortedListDifference but for lists of unorderable items (like dicts). As it does a linear search per item (remove) it has O(n*n) performance.""" missing = [] while expected: item = expected.pop() try: actual.remove(item) except ValueError: missing.append(item) # anything left in actual is unexpected return missing, actual
def toLower(str): """ This method just turns the first char of a word to lowercase. """ return str[:1].lower() + str[1:] if str else ''
def _ordinal(n: int) -> str: """Return suffix for ordinal. https://codegolf.stackexchange.com/a/74047 Parameters ---------- n : int Must be >= 2 Returns ------- str Ordinal form `n`. Ex 1 -> '1st', 2 -> '2nd', 3 -> '3rd'. """ i: int = n % 5 * (n % 100 ^ 15 > 4 > n % 10) return str(n) + "tsnrhtdd"[i::4]
def distance(a, b): """ Squared distance between points a & b """ return (a[0]-b[0])**2 + (a[1]-b[1])**2
def make_valid_sql(table_name, geometry_column_name): """ """ sql = "UPDATE %s SET %s=ST_MakeValid(%s)" sql = sql % (table_name, geometry_column_name, geometry_column_name) return sql
def make_html(url, time): """ Return browser readable html that loads url in an iframe and refreshes after time seconds """ html = f""" <!doctype html> <html> <head> <title>Kiosk</title> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <meta http-equiv="refresh" content={time}> </head> <body style="margin:0px;padding:0px;overflow:hidden"> <iframe src= {url} frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe> </body> </html> """ return html
def _validate_sample_size(str_i): """Helper for --sample argument option in argparse""" i = float(str_i) assert 0 <= i <= 1, "given sample size must be a number between [0, 1]" return i
def _nodes_to_road_section(origin: str, destination: str) -> str: """Create a road section 'A->B' from two nodes 'A' and 'B'.""" return f"{origin}->{destination}"
def is_self_contained_example(block): """Basic sanity check if markdown block contains a class and a main method.""" return "public static void main" in block and "public class" in block
def HashKey(flavor): """Generate the name of the key for this flavor's hash. Arguments: flavor: kind of tool. Returns: The string key for the hash. """ return 'NACL_TOOL_%s_HASH' % flavor.upper()
def serialize_utf8(value, partition_key): """A serializer accepting bytes or str arguments and returning utf-8 encoded bytes Can be used as `pykafka.producer.Producer(serializer=serialize_utf8)` """ if value is not None and type(value) != bytes: # allow UnicodeError to be raised here if the encoding fails value = value.encode('utf-8') if partition_key is not None and type(partition_key) != bytes: partition_key = partition_key.encode('utf-8') return value, partition_key
def get_arg(type_arg): """get the argument from type:arg format | str --> str""" return type_arg.partition(':')[2]
def combine_coverage(d1, d2): """ Given two coverage dictionaries, combine the recorded coverage and return a new dictionary. """ keys = set(d1.keys()) keys.update(set(d2.keys())) new_d = {} for k in keys: v = d1.get(k, set()) v2 = d2.get(k, set()) s = set(v) s.update(v2) new_d[k] = s return new_d
def expected_time_in_markov_state_ignoring_class_2_arrivals( state, lambda_1, mu, num_of_servers, system_capacity ): """ The expected time of the Markov chain model at the state given. Note here that for a state (u,v) where v = system capacity (C) no class 1 arrival can occur and thus the rate at which the model leaves that state changes. """ if state[1] == system_capacity: return 1 / (min(state[1], num_of_servers) * mu) return 1 / (min(state[1], num_of_servers) * mu + lambda_1)
def clean_output(text): """ Remove whitespace and newline characters from input text.""" # text = text.replace(' ', '') return text.replace('\n', '')
def r_upper(l: list) -> list: """Recursively calls str.upper on each string in l.""" result = [] if not l: return [] result.append(l[0].upper()) return result + r_upper(l[1:])
def cvtCsvIntStr(csvstr): """ Convert Comma-Separated-Value integer string into list of integers. Parameters: cvsstr - comma-separated-value string of integers format: "d,d,d,d,..." Return Value: Returns list of converted integer values on success. Returns empty list on error. """ sValList = csvstr.split(',') dlist = [] for sVal in sValList: try: dlist += [int(sVal)] except (SyntaxError, NameError, TypeError, ValueError): return [] return dlist
def euclid(a, b): """ Finds x and y such that ax + by = gcd(a,b) Returns the tuple (gcd(a,b), x, y) """ last_b1, b1 = 1, 0 last_b2, b2 = 0, 1 last_b3, b3 = a, b while b3 != 0: q = last_b3 // b3 last_b1, b1 = b1, last_b1 - q * b1 last_b2, b2 = b2, last_b2 - q * b2 last_b3, b3 = b3, last_b3 - q * b3 return last_b3, last_b1, last_b2
def transpose(matrix): """Takes a 2D matrix (as nested list) and returns the transposed version. """ return [list(val) for val in zip(*matrix)]
def make_id(string): """Translate : A simple Title -> a_simple_title""" return string.replace(' ', '-').lower()
def first(iterable, condition=lambda x: True, default=None): """ Returns the first item in the `iterable` that satisfies the `condition`. If the condition is not given, returns the first item of the iterable. If there is no first element, the default is returned (None if default is not provided). """ try: return next(x for x in iterable if condition(x)) except StopIteration: return default
def build_parameters(options, path): """ Build the URI parameters needed to query the DNSDB API :param options: Dictionary :param path: String :return: String """ time_filters = { "time_first_before": options["time_first_before"], "time_first_after": options["time_first_after"], "time_last_before": options["time_last_before"], "time_last_after": options["time_last_after"], } server_limit = "?limit={}".format(options["remote_limit"]) uri_parts = [options["server"], path, server_limit] for key, value in time_filters.items(): if value: uri_parts.append("&{}={}".format(key, value)) uri = "".join(uri_parts) return uri
def format_block(content, language=''): """Formats text into a code block.""" return f'```{language}\n{content}\n```'
def replace_partial_url(starting_url, replace_from, replace_to): """ Simple helper at this point. Maybe useful if we want to try supporting regex in the future. """ new_url = starting_url.replace(replace_from, replace_to) if not new_url.startswith('/'): new_url = '/' + new_url return new_url
def create_sequence_regex(peptide_sequence): """ creates a regular expression from a possibly ambiguous AA sequence :param peptide_sequence: peptide sequence of any length (string) :return: peptide sequence in re form (string) """ # ensure that sequence is a string peptide_sequence = str(peptide_sequence) # if no ambiguous characters are present, return the original seq. if ("B" not in peptide_sequence and "J" not in peptide_sequence and "Z" not in peptide_sequence and "X" not in peptide_sequence): return peptide_sequence # if any ambiguous characters are present, replace them with OR statements else: peptide_sequence = peptide_sequence.replace("B", "[B|D|N]") peptide_sequence = peptide_sequence.replace("J", "[J|I|L]") peptide_sequence = peptide_sequence.replace("Z", "[Z|E|Q]") peptide_sequence = peptide_sequence.replace("X", "[A-Z]") return peptide_sequence
def get_max_y(file_name): """Get max y value to allow comparison of results (same scale).""" # These values were determined by hand. We could be fancy and read # all data files first to determine max y, but too much work for low # return at this point. if 'mlp' in file_name: return 0.5 else: # Assume it's the CNN test return 3.5