content
stringlengths
42
6.51k
def _merge(a, b): """Merges two dictionaries and returns a new one.""" c = dict(a) c.update(b) return c
def _calculateRange(imageCount : int, downloadRange): """Calculates the download index ranges""" rangeMin = 0 rangeMax = imageCount # do checks per index # 0 = index start # 1 = index end if downloadRange[0] is not None: # check if range start < 1 if downloadRange[0] < 1: ...
def get_train_length_distribution(max_train_length, min_train_length=2): """Create a distribution over program lengths for training. The max_train_length is given probability 90%. Each smaller length is given half the remaining probability, up to the min_train_length. Args: max_train_length: The maximum...
def is_allowed(pair, index_a_max, index_b_max): """ A pair of cell indices is only allowed if it is still on the grid. """ allowed = False if pair[0] >= 0 and pair[0] < index_a_max: if pair[1] >= 0 and pair[1] < index_b_max: allowed = True return allowed
def get_linear_formula(start_i, end_i): """ Get Patsy formula string that has the first order terms for the variables that range from start_i to end_i (inclusive). >>> get_linear_formula(4, 9) 'x4 + x5 + x6 + x7 + x8 + x9' """ return ' + '.join('x' + str(i) for i in range(start_i, end_i...
def remove_import_statements(code): """Removes lines with import statements from the code. Args: code: The code to be stripped. Returns: The code without import statements. """ new_code = [] for line in code.splitlines(): if not line.lstrip().startswith('import ') and \...
def get_neighbor_pos(position): """Returns the list of neighbor position""" x, y = position[0], position[1] list_ = [(x+1, y), (x-1,y), (x,y+1), (x, y-1)] return list_
def correctToBillions(item): """Remove M/B from data when necessary""" if item.endswith('M'): return float(item[:-1]) / 1000 elif item.endswith('B'): return item[:-1] else: return item.replace('N/A','')
def getit(obj, typ, default=None): #------------------------------------------ """Universal procedure for geting data from list/objects. """ it = default if type(obj) == list: #if obj is a list, then searching in a list for item in obj: #print 'deb:getit item, type(item)', item, type(item) try: if ite...
def exctractPythonClasses(pythonCode): """ Exctracts the classes name from the python code Parameters: pythonCode - The python code text (list of lines) Returns: classesList - The list of the names of the python classes declared in the file """ classesList = list...
def approx_pi2(n: int = 10000000) -> float: """ https://en.wikipedia.org/wiki/Approximations_of_%CF%80 >>> approx_pi2(1000) 3.1406380562059946 >>> approx_pi2() 3.1415925580959025 """ from math import sqrt val = sum(1 / k**2 for k in range(1, n + 1)) return sqrt(6 * val)
def allstrings(alphabet, length): """Find the list of all strings of 'alphabet' of length 'length'""" if length == 0: return [] c = [[a] for a in alphabet[:]] if length == 1: return c c = [[x,y] for x in alphabet for y in alphabet] if length == 2: return c for ...
def _build_parameters( server_no_context_takeover, client_no_context_takeover, server_max_window_bits, client_max_window_bits, ): """ Build a list of ``(name, value)`` pairs for some compression parameters. """ params = [] if server_no_context_takeover: params.append(('serve...
def get_author_from_parties(parties): """ Return an author string built from a ``parties`` list of party mappings, or None. """ if not parties: return # get all entries with role author and join their names authors = [a['name'] for a in parties if a['role'] == 'author'] authors...
def is_private(baseurl, package): """Tells if a given package (with a namespace) is public or private This function checks if a fully qualified package in the format ``<namespace>/<name>`` is publicly accessible. It does this by trying to access ``info/refs?service=git-upload-pack`` from the package i...
def bin_to_hex(bin_str: str, width: int = 8) -> str: """Converts binary string to hex string Parameters ---------- bin_str : str binary string to convert width : int, optional width of hex output (used for zero padding), default=8 Returns ------- str hexadecima...
def parse_synth_query_results(synthesis_list): """parses the return from getSynthesisSourceList, returns list of study ids """ synth_study_list = [] for study in synthesis_list['study_list']: study_id = study['study_id'] tree_id = study['tree_id'] if 'taxonomy' not in stud...
def write_last_id(last_id): """ Writes the last-responded to mention ID in a text file to avoid double- tweeting. Parameters ---------- None Returns ------- None """ with open("last_id.txt", "w") as f: f.write(str(last_id)) return None
def search_tweets_for_keyword(tweets, keyword, positive): """ Parses tweet text for keywords and keeps track of sentiment score of tweets. The function is used to associate certain tweets with a currency so the currency accumulates a sentiment score which can be averaged to generate a sentiment scor...
def secs_to_day_frac(secs): """ accepts seconds and returns TOD as fraction """ if secs: return float(secs) / 86400 else: return 0
def transform_genres(genres): """ """ return list(map(lambda genre: genre["name"], genres))
def getConfig(config, key, default): """ Get a value from a configuration dictionary returning a default value if the key is not found. """ if key in config: return config[key] else: return default
def sort_multidimensional_list(multi_list, sort_by_idx): """Takes a multi-dimensional list and sorts it by the length of a sub-list item. The item who's length we sort by is determined by the idx parameter. If your input is: ``` sort_multidimensional_list( [ [[1,2,3], ['a', 'b']], ...
def _window(region, start_index, end_index): """ Returns the list of words starting from `start_index`, going to `end_index` taken from region. If `start_index` is a negative number, or if `end_index` is greater than the index of the last word in region, this function will pad its return value with ...
def keywithmaxval(d): """ a) create a list of the dict's keys and values; b) return the key with the max value""" v=list(d.values()) k=list(d.keys()) return k[v.index(max(v))]
def _lower(key): """Transforms a string to lowercase, leaves other types alone.""" keyfn = getattr(key, 'lower', None) return keyfn() if keyfn else key
def compute_f1(actual, predicted): """ Computes the F1 score of your predictions. Note that we use 0.5 as the cutoff here. """ num = len(actual) true_positives = 0 false_positives = 0 false_negatives = 0 true_negatives = 0 precision = 0 recall = 0 for i in range(num): ...
def N_power_feed(Q_volume_feed, rho_F_avrg, g, H_hydrohead_feed_real, nu_motor_efficiency, nu_supply_efficiency): """ Calculates the power of pump. Parameters ---------- H_losses_feed_real : float The hydraulic losses, [m] Q_volume_feed : float The volume flow rate of feed, [m**...
def get_last_year(data_id): """Returns last year in which ground truth data or forecast data is available Args: data_id: forecast identifier beginning with "nmme" or "cfsv2" or ground truth identifier accepted by get_ground_truth """ if data_id.startswith("cfsv2"): return 2017 ...
def sum_array(array): """Return sum of all items in array. Parameters ---------- array: list list or array-like object containing numerical values. Returns ------- int: int sum of all elements contained within the array. Examples ------- ...
def get_index(search, names): """ Find index matching search in names list of 'Key|Value' """ for name_index, name in enumerate(names): if search == name.split('|')[0]: return name_index return None
def listOflistsToString(listOfLists): """ Convert a list of lists to a string, each list top level list separated by a newline. Args: listOfLists: a list of lists, containing strings in the lowest level Returns: listOfLists as a string, each top level list separated...
def Umidi2Ubeats(tmidi, time_signature): """ Converts time in the MIDI's units (quarter note) to beat units. """ compass = time_signature.copy() compass += [[1E99, "None"]] # for last compass to be taken in consideration tbeat = 0 for i in range(len(compass)-1): c = compass[i][1] Y = int(c.split("/")[1]) #...
def get_code(language, test_case): """ Extract code in specified language from test case. Args: language: extract code in this language from case test_case: test case containing code to execute Returns: code in specified language extracted from test case """ if lang...
def least_divisor(num, floor=2): """ Find the least divisor of a number, above some floor. """ assert num >= floor trial = floor while num % trial != 0: trial += 1 return trial
def update_dictionary(dictionary: dict, key: str, value: str, by_concat: bool = True, handle_error: bool = True, keep_duplicates: bool = False): """ Updates dictionary. if key absent updates the values...
def _should_add(element, progression, max_size): """Should an element be added to a progression? Specifically, if the progression has 0 or 1 elements, then add it, as this starts the progression. Otherwise check if the gap between the element and the last in the progression is the same as the gap i...
def get_min_index(cuts): """ Search for index where the cut is minimal in cuts that are valid """ min_index = 0 for i in range(0, len(cuts), 2): if cuts[i] < cuts[min_index]: min_index = i return min_index
def pyfqn(obj) -> str: """ Get the fully-qualified name (FQN) of an object's type. :param obj: the object :return: the fully-qualified type name """ return f"{obj.__class__.__module__}.{obj.__class__.__name__}"
def __editable_dist__(dist='pypackage'): """Is distribution an editable install?""" import os import sys for path_item in sys.path: egg_link = os.path.join(path_item, dist + '.egg-link') if os.path.isfile(egg_link): return True return False
def det(a): """Determinant of matrix a.""" return a[0][0]*a[1][1]*a[2][2] + a[0][1]*a[1][2]*a[2][0] + a[0][2]*a[1][0]*a[2][1] - a[0][2]*a[1][1]*a[2][0] - a[0][1]*a[1][0]*a[2][2] - a[0][0]*a[1][2]*a[2][1]
def high_error_days(limit=1): """ Gets the list of days with error rates above the limit :param limit: The percent threshold for finding a day that has too many errors. Default 1. :return: The query string """ return """ SELECT Round((errors_per_day.error_count::numeri...
def calculate_discrete_classifier_point(instances, threshold): """ From a list of instances, calculate the coordinates for a discrete classifier that uses the given threshold. """ TP = 0 # True positives FP = 0 # False positives P = 0 # Total positives N = 0 # Total negatives fo...
def aoec_cervix_labels2aggregates(report_labels): """ Convert the pre-defined labels extracted from cervix reports to coarse- and fine-grained aggregated labels Params: report_labels (dict(list)): the dict containing for each cervix report the pre-defined labels Returns: two dicts containing for each cerv...
def cmp(x, y): """ Replacement for built-in function cmp that was removed in Python 3 Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. """ return (x > y) - (x < y)
def orderDict(d: dict): """Deep sort dictionary by keys Args: d (dict): unsorted dictionary Returns: [dict]: Sorted dictionary """ return {k: orderDict(v) if isinstance(v, dict) else v for k, v in sorted(d.items())}
def merge_sort(arr,n=None,pivot_index=None): """Returns sorted array""" n = len(arr) if n is None else n if n==1: return arr if n==2: a = arr[0] b = arr[1] srt = arr if a<b else arr[::-1] return srt pivot_index = int(n/2)-1 if pivot_index is None else pivot_i...
def get_uid_gid(uid, gid=None): """Try to change UID and GID to the provided values. UID and GID are given as names like 'nobody' not integer. Src: http://mail.mems-exchange.org/durusmail/quixote-users/4940/1/ """ import pwd import grp uid, default_grp = pwd.getpwnam(uid)[2:4] if gid is...
def nsf(num, n=1): """n-Significant Figures""" numstr = ("{0:.%ie}" % (n - 1)).format(num) return float(numstr)
def cast(val): """ Cast a value from a string to one of: [int, float, str, List[int], List[float], List[str]] Args: val (str): The value to cast. Returns: object: The casted value. """ val = str(val.strip()) if val.strip("[]") != val: return [cast(elem) for ele...
def _read_params_from_file(filepath): """Extract key=value pairs from a file. :param filepath: path to a file containing key=value pairs separated by whitespace or newlines. :returns: a dictionary representing the content of the file """ with open(filepath) as f: cmdlin...
def is_valid_param(param): """Given a parameter string, this method checks whether that parameter is a modifiable parameter in header.f90.""" return param == "NS" or param == "NRTOT" or param == "NX" or param == "NTIME" or param == "NELEM"
def activation_params(pre_audit_requested=True): """Returns parameters for Activation of object""" return {'method': 'activate', 'preauditRequested': str(pre_audit_requested).lower()}
def unpack_x_y_sample_weight(data): """Unpacks user-provided data tuple. This is a convenience utility to be used when overriding `Model.train_step`, `Model.test_step`, or `Model.predict_step`. This utility makes it easy to support data of the form `(x,)`, `(x, y)`, or `(x, y, sample_weight)`. Standalone ...
def _extra_if_info(node): """ Given an interface node, find more information about the interface based on the interface type. """ def _serial_bsd_client(node): """Get serial device path""" devname = node.get('IODialinDevice') if devname is not None: return {'devna...
def concatenate_hashes(list): """ Shorthand to concatenate a list of lists Args: [[]] Returntype: [] """ return dict(sum(map(lambda X: X.items(), filter(lambda elem: elem is not None, list)), []))
def _ensure_bytes(s, encoding): """ Ensure *s* is a bytes string. Encode using *encoding* if it isn't. """ if isinstance(s, bytes): return s return s.encode(encoding)
def join_array(array): """ Joins array feilds using `\n` """ if array: return "\n".join(array)
def reverse_string(input): """ Return reversed input string Examples: reverse_string("abc") returns "cba" Args: input(str): string to be reversed Returns: a string that us reversed of input """ if len(input) == 0: return "" else: first_ch...
def calc_vb(va, ca, dha, dh2a, h, oh, cb): """ should not use """ vb = (va * (2 * ca - dha - 2 * dh2a - h + oh)) / (cb + dha + 2 * dh2a + h - oh) return vb
def check_data_columns(column_list, data_row): """Take a list of columns that are being inserted into (from the data_json) and make sure there are parameters for the abstracted insert statement :param column_list: list of columns name :param data_row: dictionary for a specific ingest row :return: d...
def filter_data_custom(data, condition=lambda x: True): """ A custom filter for filtering a iterable data container which can be given a condition function as 'condition' """ ret = [] for x in data: if condition(x): ret.append(x) return ret
def production(*args): """Creates a production rule or list of rules from the input. Supports two kinds of input: A parsed string of form "S->ABC" where S is a single character, and ABC is a string of characters. S is the input symbol, ABC is the output symbols. Neither...
def cria_copia_peca(peca): """ cria_copia_peca: peca -> peca Recebe uma peca e devolve uma copia nova da peca """ return {'peca': peca['peca']}
def filter_clusters(clusters, reference, minsize, mincontigs, checkpresence=True): """Creates a shallow copy of clusters, but without any clusters with a total size smaller than minsize, or fewer contigs than mincontigs. If checkpresence is True, raise error if a contig is not present in reference, else ...
def polynomial5(x, p0, p1, p2, p3, p4): """ 5th order polynomial """ return p0 * x + p1 * x ** 2 + p2 * x ** 3 + p3 * x ** 4 + p4 * x ** 5
def isvector_or_scalar(a): """ one-dimensional arrays having shape [N], row and column matrices having shape [1 N] and [N 1] correspondingly, and their generalizations having shape [1 1 ... N ... 1 1 1]. Scalars have shape [1 1 ... 1]. Empty arrays dont count """ try: return ...
def binary_search(list, target): """ Returns the index position of the target if found, else returns None complexity: O(log n) """ first = 0 last = len(list) - 1 while(first <= last): midpoint = (first+last)//2 if list[midpoint] == target: return midpoint ...
def base_url(host, port): """ Provides base URL for HTTP Management API :param host: JBossAS hostname :param port: JBossAS HTTP Management Port """ url = "http://{host}:{port}/management".format(host=host, port=port) return url
def get_user_printable_name(user, errstring="???"): """ Gets name of user in printable form. :param user: user object :param errstring: string to return if name could not be resolved :return: user.nick if exists, user.name otherwise (if exists), errstring if nick and name are missing """ i...
def column_trans(schema_property): """Generate SQL transformed columns syntax""" property_type = schema_property['type'] col_trans = '' if 'object' in property_type or 'array' in property_type: col_trans = 'parse_json' elif schema_property.get('format') == 'binary': col_trans = 'to_b...
def _cmp(x, y): """ Replacement for built-in function cmp that was removed in Python 3 Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y. """ return (x > y) - (x < y)
def chars_to_ranges(s): """ Return a list of character codes consisting of pairs [code1a, code1b, code2a, code2b,...] which cover all the characters in |s|. """ char_list = list(s) char_list.sort() i = 0 n = len(char_list) result = [] while i < n: code1 = ...
def _get_choices_and_answer(cqa): """Returns choices and the answer from a cqa example.""" choices = [] answer_key = cqa["answerKey"] answer = None for choice in cqa["question"]["choices"]: choices.append(choice["text"]) if answer_key == choice["label"]: answer = choice["...
def root_to_pathsnames(gamelist): """ Extract path and name lists from a gameList root object. Parameters ---------- gameList : ElementTree.Element An ElementTree object with a gameList root and game-elements. Expects an ET object read from a gamelist.xml file. Returns ------- ...
def find_span( knots, degree, x ): """ Determine the knot span index at location x, given the B-Splines' knot sequence and polynomial degree. See Algorithm A2.1 in [1]. For a degree p, the knot span index i identifies the indices [i-p:i] of all p+1 non-zero basis functions at a given locati...
def findInList(mylist,element): """ check if an element is in the list """ pos=-1 try: pos=mylist.index(element) except ValueError: pos=-1 return pos!=-1
def make_pattern(paths, _main=True): """ Returns a pattern string from a list of path strings. For example:: >>> make_pattern(['Dev1/ao1', 'Dev1/ao2','Dev1/ao3', 'Dev1/ao4']) 'Dev1/ao1:4' """ patterns = {} flag = False for path in paths: if path.startswith('/'): ...
def format_uri(entity_name: str) -> str: """ Format url from entity name. """ return entity_name.replace('_', '/')
def frame_index_to_pts(frame: int, start_pt: int, diff_per_frame: int) -> int: """ given a frame number and a starting pt offset, compute the expected pt for the frame. Frame is assumed to be an index (0-based) """ return start_pt + frame * diff_per_frame
def seat_number(seat): """Return the consecutive seat number (8 seats per row).""" rows, columns = list(range(128)), list(range(8)) for character in seat: if character == 'F': rows = rows[:len(rows) // 2] elif character == 'B': rows = rows[len(rows) // 2:] eli...
def clean_keys(items): """Renames the keys in items list to confirm to db fields""" m = { 'no.' : 'number', 'date from' : 'date_from', 'date to' : 'date_to', 'from' : 'from_station', 'to' : 'to_station', 'dep days' : 'days', '#' : 'stop_number',...
def deep_list(x): """fully copies trees of tuples to a tree of lists. deep_list( (1,2,(3,4)) ) returns [1,2,[3,4]]""" if type(x)!=type( () ): return x return map(deep_list,x)
def set_bn(n): """ function that sets size of the window in BM,OBM,SV estimates; please, make changes only here to change them simulteneously """ #return np.round(2*np.power(n,0.33)).astype(int) return 20
def get_field_style_cond(field): """ i..e, 'field#?object.partner_id and #{font=bold} or #{}?' """ if field and '#?' in field and '?' in field: i = field.index('#?') j = field.index('?', i+2) cond = field[i + 2:j] try: if cond or cond == '': return (fi...
def header_indices(header, columns): """Find the indices in the header of the given columns. Args: header: List of all column names in the csv file. columns: List of columns to select/drop. Return: List of indices. """ ret = [] for i, v in enumerate(header): n = len(r...
def isclose(a, b, tol=1e-8): """Is b close to a?""" return abs(a - b) <= tol
def get_next_oid(oid): """Get the next OID parent's node""" # increment pre last node, e.g.: "1.3.6.1.1" -> "1.3.6.2.1" oid_vals = oid.rsplit('.', 2) if len(oid_vals) < 2: oid_vals[-1] = str(int(oid_vals[-1]) + 1) else: oid_vals[-2] = str(int(oid_vals[-2]) + 1) oid_vals[-1] =...
def _try_convert(value): """Return a non-string if possible""" if value == 'None': return None if value == 'True': return True if value == 'False': return False valueneg = value[1:] if value[0] == '-' else value if valueneg == '0': return 0 if valueneg == '': ...
def count_boxes(boxes): """Count the number of boxes (predictions). Arguments: boxes {list} -- List of boxes Returns: integer -- Number of boxes """ count = 0 for i in boxes: count +=1 return count
def round_value(value): """ Round the given value to 1 decimal place. If the value is 0 or None, then simply return 0. """ if value: return round(float(value), 1) else: return 0
def asset_id(asset_description): """return a test asset id""" return f"users/bornToBeAlive/sepal_ui_test/{asset_description}"
def skip_semicolon(toks, start_idx): """ Args: Returns: """ idx = start_idx while idx < len(toks) and toks[idx] == ";": idx += 1 return idx
def Chebyshev_nodes(a, b, N): """Return N+1 Chebyshev nodes (for interpolation) on [a, b].""" from math import cos, pi half = 0.5 nodes = [0.5*(a+b) + 0.5*(b-a)*cos(float(2*i+1)/(2*(N+1))*pi) for i in range(N+1)] return nodes
def squarify(x, y, w, h): """Crop to square (centre of window)""" if w > h: x += int((w - h) / 2) w = h elif h > w: y += int((h - w) / 2) h = w return x, y, w, h
def odd_numbers_list(n): """ Returns the list of n first odd numbers """ return [2 * k - 1 for k in range(1, n + 1)]
def get_p_value(test_results): """ :param test_results: dict :return: float """ test_name = test_results['Test Name'] alt_hypothesis = test_results['Alt. Hypothesis'] p_value = test_results['p-value'] test_statistic = test_results['Test Statistic'] if 't-test' in test_name: ...
def _pad_data(data: bytes, n: int = 16) -> bytes: """ Adds padding to the data according to the PKCS7 standard. Note that at least one byte of padding is guaranteed to be added. :param data: the data to pad :param n: the length to pad the data to, defaults to 16 :return: the padded data """ ...
def handle_answer_question(payload: dict): """ send answer to the host Parameters ========== `payload` contains keys `display_name`, `room_code`, `player_session_id`, and `question_id` Returns ========= (success: bool, message: str, answer_payload: dict) """ display_nam...
def build_dataset_attributes_json_object(output_files, container_name, num_files, num_multi_page, percentage_multi_page): """ :param output_files: The files to output :param container_name: The storage container name :param num_files: The number of files process...