content
stringlengths
42
6.51k
def clean_whitespace(contents: str) -> str: """ Return the given string with all line breaks and spaces removed. For some reason our mock service returns a SOAP response with lots of whitespace. """ lines = [line.strip(" \r\n") for line in contents.split('\n')] return ''.join(lines)
def _splitter(value, separator): """ Return a list of values from a `value` string using `separator` as list delimiters. Empty values are NOT returned. """ if not value: return [] return [v.strip() for v in value.split(separator) if v.strip()]
def ot2bio_ote(ote_tag_sequence): """ ot2bio function for ote tag sequence :param ote_tag_sequence: :return: """ new_ote_sequence = [] n_tag = len(ote_tag_sequence) prev_ote_tag = '$$$' for i in range(n_tag): cur_ote_tag = ote_tag_sequence[i] assert cur_ote_tag == 'O' or cur_ote_tag == 'T' if cur_ote_tag == 'O': new_ote_sequence.append(cur_ote_tag) else: # cur_ote_tag is T if prev_ote_tag == 'T': new_ote_sequence.append('I') else: # cur tag is at the beginning of the opinion target new_ote_sequence.append('B') prev_ote_tag = cur_ote_tag return new_ote_sequence
def get_graph_counts(community_counts, labels_to_count): """ Aggregate community counts across communities """ graph_counts = dict.fromkeys(labels_to_count, {}) # Aggregate counts across graph for community in community_counts: for label in community_counts[community]: for (label_val, label_val_count) in community_counts[community][label].items(): if label_val in graph_counts[label]: graph_counts[label][label_val] += label_val_count else: graph_counts[label][label_val] = label_val_count return graph_counts
def parent_accession(location): """ Get the parent accessino for the given location. """ return location["exons"][0]["INSDC_accession"]
def prep_late_warning(assignment_name): """ Create a late warning message. :param assignment_name: Name of the assignment. :type assignment_name: str :return: A late warning message. :rtype: str """ return "The deadline for " + assignment_name + " has passed."
def elementwise_squared_error(true_val, pred_val): """The absolute error between a single true and predicted value. Parameters ---------- true_val : float True value. pred_val : float Predicted value. Returns ------- residual : float Squared error, (true_val - pred_val)^2 """ return (true_val - pred_val)**2
def validate_ids(data, field='id', unique=True): """ By this method we just return uniq list Actually we use it for {issue_id:xxx order: xxx} We don't really know what to do if we got 2 different order for the same issue. Of course frontend should prevent it. But I decided not raise an Exception for this case. """ if not isinstance(data, list): return [data] id_list = [int(x[field]) for x in data if field in x] unique_id_list = set(id_list) if unique and len(id_list) != len(unique_id_list): return unique_id_list return id_list
def insignificant(path): """Return True if path is considered insignificant.""" # This part is simply an implementation detail for the code base that the # script was developed against. Ideally this would be moved out to a config # file. return path.endswith('Dll.H') or path.endswith('Forward.H') or \ path.endswith('templates.H')
def plot_bounds(observed_min, observed_max): """Compute the plot bounds for observed data Args: observed_min (number) -- Lowest number found in data observed_max (number) -- Highest number found in data Returns: (number, number) A minimum and maximum x value for the plot """ if observed_min >= 0.0 and observed_max <= 1.0: plot_min, plot_max = (0.0, 1.0) else: # 10% padding on the high end padding = 0.1 * (observed_max - float(observed_min)) plot_min = observed_min plot_max = observed_max + padding return plot_min, plot_max
def uniq(seq): """ Output uniq values of a list """ Set = set(seq) return list(Set)
def comxyz(x,y,z): """Centre of mass given x, y and z vectors (all same size). x,y give position which has value z.""" Mx=0 My=0 mass=0 for i in range(len(x)): Mx=Mx+x[i]*z[i] My=My+y[i]*z[i] mass=mass+z[i] com=(Mx/mass, My/mass) return com
def comp_nthoctave_axis(noct, freqmin, freqmax): """Computes the frequency vector between freqmin and freqmax for the 1/n octave Parameters ---------- noct: int kind of octave band (1/3, etc) freqmin: float minimum frequency freqmax: float maximum frequency Returns ------- Frequency vector """ if noct == 3: table = [ 10, 12.5, 16, 20, 25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630, 800, 1000, 1250, 1600, 2000, 2500, 3150, 4000, 5000, 6300, 8000, 10000, 12500, 16000, 20000, ] f_oct = [f for f in table if (f >= freqmin and f <= freqmax)] else: f0 = 1000 f_oct = [f0] i = 1 while f_oct[-1] <= freqmax: f_oct.append(f0 * 2.0 ** (i / noct)) i = i + 1 f_oct = f_oct[:-2] i = -1 while f_oct[0] > freqmin: f_oct.insert(0, f0 * 2.0 ** (i / noct)) i = i - 1 f_oct = f_oct[1:] return f_oct
def is_string(s): """True if s behaves like a string (duck typing test).""" try: s + " " return True except TypeError: return False
def ecgmathcalc(timelist, voltagelist): """Method that performs the basic math functions This method takes the input lists from the fileparser and then obtains the basic metrics. These include the max and min and duration. It also obtains the length of the time list which is used in later calculations. Max and min are both obtained using built in python functions and duration is calculated by subtracting the endpoints. :param timelist: List of time values :param voltagelist: List of voltage values :returns minvolt: Minimum voltage value recorded :returns maxvolt: Maximum voltage value recorded :returns duration: Duration of the ECG recording :returns timelen: Length of the time list """ duration = 0 timelen = len(timelist) # Determines Min and Max voltages in the file minvolt = min(voltagelist) maxvolt = max(voltagelist) # Determines duration of input signal duration = timelist[timelen-1] - timelist[0] return minvolt, maxvolt, duration, timelen
def page_contents(source, items_per_page, page_number): """Retrieves the contents of a media list page. Args: source: An unevaluated SQLAlchemy ORM query representing the source of all items in this list, in the order in which they should appear in the list. items_per_page: The number of items that should appear on each page in the list. The last page may have fewer items, but all other pages should be filled. page_number: The number of the page whose contents should be retrieved, or zero if there are no pages and thus no page contents. Returns: A list of objects from 'source' that together form the contents of the media list page numbered 'page_number', given that at most 'items_per_page' items appear on each page. Each item will be annotated with the forms of metadata that will appear on the list. """ if page_number < 0: raise ValueError('Page number was negative.') elif page_number == 0: items = [] else: lower_bound = (page_number - 1) * items_per_page upper_bound = page_number * items_per_page items = source.slice(lower_bound, upper_bound).all() assert 0 < len(items), 'Empty page produced.' # If we can, we want to sprinkle metadata on the items. if hasattr(items[0].__class__, 'annotate'): items[0].__class__.annotate(items) return items
def flip_labels(obj): """ Rename fields x to y and y to x Parameters ---------- obj : dict_like | types.SimpleNamespace Object with labels to rename """ def sub(a, b): """ Substitute all keys that start with a to b """ for label in list(obj.keys()): if label.startswith(a): new_label = b+label[1:] obj[new_label] = obj.pop(label) if hasattr(obj, 'keys'): # dict or dataframe sub('x', 'z') sub('y', 'x') sub('z', 'y') elif hasattr(obj, 'x') and hasattr(obj, 'y'): obj.x, obj.y = obj.y, obj.x return obj
def tree_view(dictionary, level=0, sep="| "): """ View a dictionary as a tree. """ return "".join( [ "{0}{1}\n{2}".format(sep * level, k, tree_view(v, level + 1, sep=sep) if isinstance(v, dict) else "") for k, v in dictionary.items() ] )
def string_join(list, join_character): """**string_join(string, join_character)** -> return a string with elements for the lsit joined by the join_character * list: (list of strings) list of string to joins * join_character: (string) character to user between strings <code> Example: string_join(['linux', 'windows'], ',') Returns: 'linux,windows' </code> """ return join_character.join(list)
def Dic_Test_Empty_Dic(indic): """ check if indic is a (nested) empty dictionary. """ if indic.keys()!=[]: for key,keydata in indic.items(): if isinstance(keydata,dict): if keydata=={}: pass else: return Dic_Test_Empty_Dic(keydata) else: return False return True else: return False
def rearrange_pads(pads): """ Interleave pad values to match NNabla format (S0,S1,E0,E1) => (S0,E0,S1,E1)""" half = len(pads)//2 starts = pads[:half] ends = pads[half:] return [j for i in zip(starts, ends) for j in i]
def gmean(a, axis=0, dtype=None): """ Compute the geometric mean along the specified axis. Returns the geometric average of the array elements. That is: n-th root of (x1 * x2 * ... * xn) Parameters ---------- a : array_like Input array or object that can be converted to an array. axis : int or None, optional Axis along which the geometric mean is computed. Default is 0. If None, compute over the whole array `a`. dtype : dtype, optional Type of the returned array and of the accumulator in which the elements are summed. If dtype is not specified, it defaults to the dtype of a, unless a has an integer dtype with a precision less than that of the default platform integer. In that case, the default platform integer is used. Returns ------- gmean : ndarray see dtype parameter above See Also -------- numpy.mean : Arithmetic average numpy.average : Weighted average hmean : Harmonic mean Notes ----- The geometric average is computed over a single dimension of the input array, axis=0 by default, or all values in the array if axis=None. float64 intermediate and return values are used for integer inputs. Use masked arrays to ignore any non-finite values in the input or that arise in the calculations such as Not a Number and infinity because masked arrays automatically mask any non-finite values. """ import numpy as np if not isinstance(a, np.ndarray): # if not an ndarray object attempt to convert it log_a = np.log(np.array(a, dtype=dtype)) elif dtype: # Must change the default dtype allowing array type if isinstance(a, np.ma.MaskedArray): log_a = np.log(np.ma.asarray(a, dtype=dtype)) else: log_a = np.log(np.asarray(a, dtype=dtype)) else: log_a = np.log(a) return np.exp(log_a.mean(axis=axis))
def qualify_cpp_name(cpp_namespace, cpp_type_name): # type: (str, str) -> str """Preprend a type name with a C++ namespace if cpp_namespace is not None.""" if cpp_namespace: return cpp_namespace + "::" + cpp_type_name return cpp_type_name
def delete(r,i): """ remove element in the list r that corresponds to i """ ii = r.index(i) z = [] for i in range(len(r)): if i == ii: continue else: z = z + [r[i]] return z
def feature_label_separator(features:list): """ :param features: Nested List containing three individual lists = feature vectors, labels and Subject ID :return: separated lists """ traindata = [] trainlabels = [] subjects = [] for feature_list in features: traindata.extend(feature_list[0]) trainlabels.extend(feature_list[1]) subjects.extend(feature_list[2]) return traindata, trainlabels, subjects
def update_dict(left, right): """Updates left dict with content from right dict :param left: Left dict. :param right: Right dict. :return: the updated left dictionary. """ if left is None: return right if right is None: return left left.update(right) return left
def get_csi(LWdown, T, e, e_ad=0.22, k=0.47, return_all=False): """ Clear Sky Index after Marty and Philipona, 2000 Parameters ---------- LWdown : ndarray longwave down as measured/ simulated [W/m**2] T : ndarray temperature at lowest level [K] e : ndarray water vapor pressure [Pa] e_ad : float altitude dependent clear-sky emittance of a completely dry atmosphere k : float location dependent coefficient return_all : bool if False returns CSI, else returns (CSI, app_em, clear_sky_app_em) Returns ------- CSI : ndarray clear sky index = Notes ----- According to Marty and Philipona CSI <= 1 : clear sky, no clouds CSI > 1 : cloudy sky, overcast """ # Stephan-Boltzmann constant sigma = 5.67 * 10**-8 # apparent emittance of actual sky app_em = LWdown / (sigma * T**4) # clear sky apparent emittance cs_app_em = e_ad + k * (e * T) ** (1./7) CSI = app_em / cs_app_em if return_all: return (CSI, app_em, cs_app_em) else: return CSI
def reactions_to_user_lists(reaction_list): """Convert list of reactions from GitHub API into list of usernames for upvote and downvote""" upvotes = [] downvotes = [] for r in reaction_list: if r["content"] not in ["+1", "-1"] or r["user"]["type"] != "User": continue username = r["user"]["login"] if r["content"] == "+1": upvotes.append(username) elif r["content"] == "-1": downvotes.append(username) upvotes.sort() downvotes.sort() return upvotes, downvotes
def _CountPositives(solution): """Counts number of test images with non-empty ground-truth in `solution`. Args: solution: Dict mapping test image ID to list of ground-truth IDs. Returns: count: Number of test images with non-empty ground-truth. """ count = 0 for v in solution.values(): if v: count += 1 return count
def average_rewards(arr_rewards): """ Average list of rewards """ avg_rewards = [] for i in range(len(arr_rewards[0])): avg_rewards.append(0) for _, rewards in enumerate(arr_rewards): avg_rewards[i] += rewards[i] avg_rewards[i] /= len(arr_rewards) return avg_rewards
def rotate(l, n): """Shift list elements to the left Args: l (list): list to rotate n (int): number to shift list to the left Returns (list): list shifted """ return l[n:] + l[:n]
def is_number(s): """ Checks wether the provided string is a number. Accepted: 1 | 1.0 | 1e-3 | 1,0 """ s = s.replace(',', '.') try: float(s) return True except ValueError: return False
def float_or_none(arg): """Returns None or float from a `float_or_none` input argument. """ if arg is None or str(arg).lower() == 'none': return None return float(arg)
def validWebsite(website): """ Checks With a Regex If The URL Entered Is Correct Or Not! (User can use IP Too :) """ # web = webNotEmpty(website) # if web is "valid": # if not (re.match(r"(^(http://|https://)?([a-z0-9][a-z0-9-]*\.)+[a-z0-9][a-z0-9-]*$)", website)): # exit(wrong_URL) # else: # exit(empty_Website) return(website)
def linked(sig_1, sig_2): """Is used to link two signatures. It returns true iff the two signatures are from the same signer. >>> public_keys = [keygen()[1] for i in range(3)] >>> (sec, pub) = keygen() >>> public_keys.append(pub) >>> m1 = "some message" >>> m2 = "message" >>> sig1 = ringsign(public_keys, sec, m1) >>> sig2 = ringsign(public_keys, sec, m2) >>> linked(sig1, sig2) True >>> public_keys = [keygen()[1] for i in range(3)] >>> (sec1, pub1) = keygen() >>> (sec2, pub2) = keygen() >>> public_keys.extend((pub1, pub2)) >>> m = "some message" >>> sig1 = ringsign(public_keys, sec1, m) >>> sig2 = ringsign(public_keys, sec2, m) >>> linked(sig1, sig2) False """ return sig_1[0] == sig_2[0]
def get_input_ipc_handles(arr): """ Used for kneighbors() to extract the IPC handles from the input Numba arrays. The device of the current worker and the start/stop indices of the original cudf are passed along as well. :param arr: :return: """ if arr is None: return None arrs, dev, idx = arr mat = [(X.get_ipc_handle(), inds.get_ipc_handle(), dists.get_ipc_handle()) for X, inds, dists in arrs] return mat, dev, idx
def flatten_list(list_of_lists: list) -> list: """This function flattens the input list Args: list_of_lists (list): input list of lists that we want to flatten Returns: flattened_list (list): flattened list """ flattened_list = [item for sublist in list_of_lists for item in sublist] return flattened_list
def calculate_iou(gt, pr, form='pascal_voc') -> float: # https://www.kaggle.com/sadmanaraf/wheat-detection-using-faster-rcnn-train """Calculates the Intersection over Union. Args: gt: (np.ndarray[Union[int, float]]) coordinates of the ground-truth box pr: (np.ndarray[Union[int, float]]) coordinates of the prdected box form: (str) gt/pred coordinates format - pascal_voc: [xmin, ymin, xmax, ymax] - coco: [xmin, ymin, w, h] Returns: (float) Intersection over union (0.0 <= iou <= 1.0) """ if form == 'coco': gt = gt.copy() pr = pr.copy() gt[2] = gt[0] + gt[2] gt[3] = gt[1] + gt[3] pr[2] = pr[0] + pr[2] pr[3] = pr[1] + pr[3] # Calculate overlap area dx = min(gt[2], pr[2]) - max(gt[0], pr[0]) + 1 if dx < 0: return 0.0 dy = min(gt[3], pr[3]) - max(gt[1], pr[1]) + 1 if dy < 0: return 0.0 overlap_area = dx * dy # Calculate union area union_area = ( (gt[2] - gt[0] + 1) * (gt[3] - gt[1] + 1) + (pr[2] - pr[0] + 1) * (pr[3] - pr[1] + 1) - overlap_area ) return overlap_area / union_area
def parity_list(list_val, init_value=0): """ Helper function computes parity on list of 1's and 0's """ curr_value = init_value for value in list_val: curr_value = curr_value ^ value return curr_value
def is_valid_hcl(hair_color): """Checks for valid Hair Color.""" if len(hair_color) == 7 and hair_color[0] == '#' and set(hair_color[1:]).issubset(set('0123456789abcdef')): return True else: return False
def _fmt_cmd_for_err(cmd): """ Join a git cmd, quoting individual segments first so that it's relatively easy to see if there were whitespace issues or not. """ return ' '.join(['"%s"' % seg for seg in cmd])
def make_efile_url(efile_page_url: str) -> str: """ Helper function to get file download link on a Portland EFile hosting web page Parameters ---------- efile_page_url: str URL to Portland efile hosting web page e.g. https://efiles.portlandoregon.gov/record/14803529 Returns ------- efile url: str URL to the file itself e.g. https://efiles.portlandoregon.gov/record/14803529/File/Document """ if not efile_page_url.endswith("/"): efile_page_url += "/" return f"{efile_page_url}File/Document"
def _combine_ws(parts, whitespace): """Combine whitespace in a list with the element following it. Args: parts: A list of strings. whitespace: A string containing what's considered whitespace. Return: The modified list. """ out = [] ws = '' for part in parts: if not part: continue elif part in whitespace: ws += part else: out.append(ws + part) ws = '' if ws: out.append(ws) return out
def compute_G(kinetic, N, kb, T, Q): """Computes the variable G """ G = (2*kinetic - 3*N*kb*T)/Q return G
def make_command(params): """Flatten parameter dict to list for command.""" command = [params.pop("path")] last = params.pop("last", None) for key, value in params.items(): if isinstance(value, list): command.extend([key, *value]) else: command.extend([key, value]) if isinstance(last, list): command.extend(last) elif isinstance(last, str): command.append(last) return command
def _convert_string(key): """Convert OEIS String to Integer.""" if isinstance(key, str): key = int(key.strip().upper().strip("A")) return key
def last_test_terminated(out, returncode): """Last executed test terminated if in unsuccessful execution the last \ '[ RUN ]' doesn't have corresponding '[ FAILED ]' afterwards. """ no_fail_info = '[ RUN ]' in next(line for line in reversed( out.splitlines()) if '[ FAILED ]' in line or '[ RUN ]' in line) return returncode != 0 and no_fail_info
def inverse_gardner(rho, alpha=310, beta=0.25, fps=False): """ Computes Gardner's density prediction from P-wave velocity. Args: rho (ndarray): Density in kg/m^3. alpha (float): The factor, 310 for m/s and 230 for fps. beta (float): The exponent, usually 0.25. fps (bool): Set to true for FPS and the equation will use the typical value for alpha. Overrides value for alpha, so if you want to use your own alpha, regardless of units, set this to False. Returns: ndarray: Vp estimate in m/s. """ alpha = 230 if fps else alpha exponent = 1 / beta factor = 1 / alpha**exponent return factor * rho**exponent
def day_to_str_int(d): """Converts a day to an int form, str type, with a leading zero""" if d < 10: ds = "0{}".format(d) else: ds = str(d) return ds
def kmph2ms(kmph: float) -> float: """ Convert kilometers per hour to meters per second. :param float kmph: kmph :return: speed in m/s :rtype: float """ if not isinstance(kmph, (float, int)): return 0 return kmph * 0.2777778
def find_choiceval(choice_str, choice_list): """ Take number as string and return val string from choice_list, empty string if oob. choice_list is a simple python list. """ choice_val = "" try: choice_idx = int(choice_str) if choice_idx <= len(choice_list): choice_idx -= 1 choice_val = choice_list[choice_idx] except ValueError: pass return choice_val
def out_file_name(in_dir, in_file, calc_type, direction): """Set file name for outfile.""" if in_dir == "": out_name = f"{in_dir}n_{direction}_{calc_type}_{in_file}" else: out_name = f"{in_dir}/n_{direction}_{calc_type}_{in_file}" return out_name
def generate_separations(num_parts, word, start=0): """Generate all possible separations of a word in num_parts.""" if num_parts == 1: return [[word[start:]]] if num_parts > len(word) - start: return [] possibilities = [] for n in range(1, len(word) - start): new_possibilities = [] for possibility in generate_separations(num_parts - 1, word, start + n): new_possibilities.append([word[start:start + n]] + possibility) possibilities.extend(new_possibilities) return possibilities
def calculateTileCountUpToTier(tierSizeInTiles): """ The function caclulate the tileCount up to the top tier :type tileSizeInTiles: Array.<float> :return: Array.<float> """ tileCountUpToTier = [0] for i in range(1, len(tierSizeInTiles)): value = tierSizeInTiles[i - 1][0] * tierSizeInTiles[i - 1][1] + tileCountUpToTier[i - 1] tileCountUpToTier.append(int(value)) return tileCountUpToTier
def hex_string_to_int(value: str) -> int: """returns an int from a hex string""" return int(value, 16)
def vc_reflect(theta, theta1): """Convert theta and theta1 to 0-360 format. Parameters ---------- theta : float Angle of the surface measured from right. theta1 : float Angle of the incident beam measured from right. Returns ------- float """ #Combert theta and theta1 to 0-360 format if theta < 0: theta = 360.0 + theta if theta > 180: theta = theta -180.0 if theta1 < 0: theta1 = 360.0 + theta1 return theta - (theta1 - theta)
def normalize_interface(name): """Return the normalized interface name """ if not name: return def _get_number(name): digits = '' for char in name: if char.isdigit() or char in '/.': digits += char return digits if name.lower().startswith('gi'): if_type = 'GigabitEthernet' elif name.lower().startswith('te'): if_type = 'TenGigabitEthernet' elif name.lower().startswith('fa'): if_type = 'FastEthernet' elif name.lower().startswith('fo'): if_type = 'FortyGigabitEthernet' elif name.lower().startswith('et'): if_type = 'Ethernet' elif name.lower().startswith('vl'): if_type = 'Vlan' elif name.lower().startswith('lo'): if_type = 'loopback' elif name.lower().startswith('po'): if_type = 'port-channel' elif name.lower().startswith('nv'): if_type = 'nve' else: if_type = None number_list = name.split(' ') if len(number_list) == 2: if_number = number_list[-1].strip() else: if_number = _get_number(name) if if_type: proper_interface = if_type + if_number else: proper_interface = name return proper_interface
def romanToInt( s): """ :type s: str :rtype: int """ rome_dict = {"I":1, "V":5,"X":10,"L":50, "C":100, "D":500, "M":1000 } sum = 0 #arr_i = [] for i in range(0, len(s)-1): print(s[i]) if (rome_dict[s[i]]>=rome_dict[s[i+1]]): sum += rome_dict[s[i]] #print("positive ", s[i],rome_dict[s[i]],s[i+1],rome_dict[s[i+1]], " sum ", sum) else : sum -= rome_dict[s[i]] #sum += rome_dict[s[i+1]] #print("negative ", s[i],rome_dict[s[i]],s[i+1], rome_dict[s[i+1]], " sum ", sum) #i = i+1 #print(s[i]) sum += rome_dict[s[-1]] ### adding the last return sum
def quick_sort(l): """ Quick Sort Implementation. Time O(nlogn) Run. O(logn) space complexity. """ less = [] equal = [] greater = [] if len(l) > 1: pivot = l[0] for x in l: if x < pivot: less.append(x) elif x == pivot: equal.append(x) elif x > pivot: greater.append(x) return quick_sort(less) + equal + quick_sort(greater) # + operator to join lists else: return l
def fact_recursive(n): """Return factorial of given number, generated recursively.""" if n == 1: return 1 else: return n * fact_recursive(n-1)
def shallow(left, right, key, default): """Updates fields from src at key, into key at dst. """ left_v = left.get(key, default) if key in right: right_v = right[key] if key in left: if isinstance(left_v, dict) and isinstance(right_v, dict): return dict(left_v, **right_v) return right_v return left_v
def median(array): """ Calculates the median in an array. Parameters ---------- array: list list of integers Returns ------- int median """ if len(array) % 2 == 1: return array[int(len(array) / 2)] elif len(array) % 2 == 0: return (array[int(len(array) / 2) - 1] + array[int(len(array) / 2)])/2
def string2int(val): """ needs test harness """ if val == '': return 0 else: try: return int(val) except TypeError: return 0
def recon_action_update_payload(passed_keywords: dict) -> dict: """Create a properly formatted payload for handling recon actions. { "frequency": "string", "id": "string", "recipients": [ "string" ], "status": "string" } """ returned_payload = {} if passed_keywords.get("frequency", None): returned_payload["frequency"] = passed_keywords.get("frequency", None) if passed_keywords.get("id", None): returned_payload["id"] = passed_keywords.get("id", None) if passed_keywords.get("recipients", None): returned_payload["recipients"] = passed_keywords.get("recipients", None) if passed_keywords.get("status", None): returned_payload["status"] = passed_keywords.get("status", None) return returned_payload
def _atoi(text): """Convert a string to an int.""" return int(text) if text.isdigit() else text
def check_dups(li): """checks duplicates in list of ID values ID values must be read in as a list __author__ = "Luc Anselin <luc.anselin@asu.edu> " Arguments --------- li : list of ID values Returns ------- a list with the duplicate IDs """ return list(set([x for x in li if li.count(x) > 1]))
def get_api_auth_headers(api_key): """ Return HTTP Authorization header using WDL API key WDL follows the Authorization: <type> <credentials> pattern that was introduced by the W3C in HTTP 1.0. That means the value of your Authorization header must be set to: "Bearer <API Key>". The API Key provided by api_key is a secret token that Well Data Labs issues to your company or authenticated user. If you are an existing Well Data Labs customer, you can obtain an API Key for your data from support@welldatalabs.com. API Keys allow access to customer data just like a username and password. They should be protected and should not be shared. Parameters ---------- api_key: str The WDL API key to use for request authentication Returns ------- headers: dict A dictionary containing the HTTP Authorization header information to be consumed by the request GET call """ headers = {'Authorization': f'Bearer {api_key}'} return headers
def get_output_fieldnames(fields): """ Get filenames as they will be written to disk. """ return [field.replace("/", "_") for field in fields]
def color(content, option="match"): """ Change color content to color of option: + match pattern + line-number match pattern + path match pattern """ if option == "match": # color same key return '\033[30;43m{}\033[0m'.format(content) if option == "line": # color line find key return '\033[1;33m{}\033[0m'.format(content) # color of this path file return '\033[1;32m{}\033[0m'.format(content)
def convert_deliverables_tags(delivery_json: dict, sample_config_dict: dict) -> dict: """Replaces values of file_prefix with sample_name in deliverables dict""" for file in delivery_json["files"]: file_tags = file["tag"].split(",") for sample in sample_config_dict["samples"]: file_prefix = sample_config_dict["samples"][sample]["file_prefix"] sample_name = sample_config_dict["samples"][sample]["sample_name"] if file_prefix == file["id"]: file["id"] = sample_name for tag_index, tag in enumerate(file_tags): if tag == file_prefix or tag == file_prefix.replace( "_", "-"): file_tags[tag_index] = sample_name file_tags.append(sample_name) file["tag"] = list(set(file_tags)) return delivery_json
def merge_cache(previous: dict, current: dict) -> dict: """Merge cache.""" current["open"] = previous["open"] current["high"] = max(previous["high"], current["high"]) current["low"] = min(previous["low"], current["low"]) for key in ( "volume", "buyVolume", "notional", "buyNotional", "ticks", "buyTicks", ): current[key] += previous[key] # Add return current
def gen_derived(data): """ Generate derived information Should be called last """ return { 'miscellaneous': { 'number-of-layers': int( data['layout-matrices']['_kb_layout']['length']/(6*14) ), # because 6*14 is the number of bytes/layer for '_kb_layout' # (which is a uint8_t matrix) }, }
def groupby(f, coll): """ Group a collection by a key function >>> names = ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank'] >>> groupby(len, names) {3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']} """ d = dict() for item in coll: key = f(item) if key not in d: d[key] = [] d[key].append(item) return d
def plural(length, label, suffix='s'): """Return a label with an optional plural suffix""" return '%d %s%s' % (length, label, suffix if length != 1 else '')
def get_sources(edges): """Given a list of edges, determines the set of sources included. """ return set(edge[4] for edge in edges)
def position_string_to_id(positions): """ position_string_to_id converts input position strings to their integer representations defined by: Position 1 = Primary farm (ADC) Position 2 = Secondary farm (Mid) Position 3 = Tertiary farm (Top) Position 4 = Farming support (Jungle) Position 5 = Primary support (Support) Note that because of variable standardization of the string representations for each position (i.e "jg"="jng"="jungle"), this function only looks at the first character of each string when assigning integer positions since this seems to be more or less standard. Args: positions (list(string)) Returns: list(int) """ d = {"a":1, "m":2, "t":3, "j":4, "s":5} # This is lazy and I know it out = [] for position in positions: char = position[0] # Look at first character for position information out.append(d[char]) return out
def _verify_model_impl_values(func_name, model_ret, impl_ret): """ Verify that the implementation's returns match the model's returns """ # For now, all returns should match return model_ret == impl_ret
def is_rate_limit_error_message(message): """Check if the supplied error message belongs to a rate limit error.""" return isinstance(message, list) \ and len(message) > 0 \ and 'code' in message[0] \ and message[0]['code'] == 88
def pid_to_pc(pid): """Return program counter variable for given `pid`. The process owner controls this variable. """ assert pid >= 0, pid return 'pc{pid}'.format(pid=pid)
def fast_auc(y_true, y_prob): """ fast roc_auc computation: https://www.kaggle.com/c/microsoft-malware-prediction/discussion/76013 """ import numpy as np y_true = np.asarray(y_true) y_true = y_true[np.argsort(y_prob)] nfalse = 0 auc = 0 n = len(y_true) for i in range(n): y_i = y_true[i] nfalse += (1 - y_i) auc += y_i * nfalse auc /= (nfalse * (n - nfalse)) return auc
def _greater_than(input, values): """Checks if the given input is > the first value in the list :param input: The input to check :type input: int/float :param values: The values to check :type values: :func:`list` :returns: True if the condition check passes, False otherwise :rtype: bool """ try: return input > values[0] except IndexError: return False
def format_results(results): """Formats the results for CLI output""" formatted = "" for result in results: formatted += result.name + "\n" for subquest in result.results: formatted += " " + subquest.title + "\n" formatted += " " + subquest.result + "\n" formatted += "\n" return formatted
def power_pump(flate_pump_feed, rho_F, g, head_pump, ECE_motor, ECE_trans): """ Calculates the power of pump. Parameters ---------- flate_pump_feed : float The flow rate pump for Feed [m**3 / h] rho_F : float The density of feed, [kg / m**3] head_pump : float The hydraulic head of pump, [m] ECE_motor : float The energy conversion efficiency of motor, [dismensionless] ECE_trans : float The energy conversion efficiency of transfer, [dismensionless] Returns ------- power_pump : float The power of pump, [kW] References ---------- &&&& """ return (flate_pump_feed * rho_F * g * head_pump / (ECE_motor * ECE_trans))
def second(iterable): """ Gets the second element from an iterable. If there are no items are not enough items, then None will be returned. :param iterable: Iterable :return: Second element from the iterable """ if iterable is None or len(iterable) < 1: return None return iterable[1]
def nrj(pos, vel): """ compute energy for given moon """ return sum([abs(e) for e in pos]) * sum([abs(e) for e in vel])
def _check_parameter(params, required): """ checking parameter type :rtype: None """ key = params.keys() for req_word in required: if req_word not in key: print(req_word, ': ') raise Exception('Not input required parameter.') return None
def _api_url(api_host: str) -> str: """Obtiene la URL de la API de clearpass, a partir del hostname""" return "https://{}/api".format(api_host)
def has_duplicates1(t): """Checks whether any element appears more than once in a sequence. Simple version using a for loop. t: sequence """ d = {} for x in t: if x in d: return True d[x] = True return False
def get_index_of_max(iterable): """ Return the first index of one of the maximum items in the iterable. """ max_i = -1 max_v = float('-inf') for i, iter in enumerate(iterable): temp = max_v max_v = max(iter,max_v) if max_v != temp: max_i = i return max_i
def splitblocks(lst, limit): """Split list lst in blocks of max. limit entries. Return list of blocks.""" res = [] start = 0 while start < len(lst): res.append(lst[start:start + limit]) start += limit return res
def get_all_not_used_templates(used_templates, all_templates): """ Chooce not used template among all templates Args: used_templates: list of templates already used in the dialog all_templates: list of all available templates Returns: string template """ available = list(set(all_templates).difference(set(used_templates))) if len(available) > 0: return available else: return all_templates
def get_margin(element, level): """ Calculates right margin of element based on its level. I.e., embedded divs gradually shift to the right. """ if level: style = ' style=\"margin-left:{}em;\"'.format(level * 1.5) else: style = '' return '<{}{}>'.format(element, style)
def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" temp = enumerate(zip(*strs)) print(list(temp)) for i, letter_group in temp: if len(set(letter_group)) > 1: return strs[0][:i] return min(strs)
def is_prime(x=70): """Find whether an integer is prime.""" for i in range(2, x): # "range" returns a sequence of integers if x % i == 0: print("%d is not a prime: %d is a divisor" % (x, i)) #Print formatted text "%d %s %f %e" % (20,"30",0.0003,0.00003) return False print ("%d is a prime!" % x) return True
def response_ga(attributes, speech_response): """ create a simple json response """ return { 'version': '1.0', 'sessionAttributes': attributes, 'response': speech_response }
def imag(x): """ the imaginary part of x """ if isinstance(x, complex): return x.imag else: return type(x)(0)
def ACTG3(sequ , A = False , T = False , C = False, G = False): """ Calculate A, T, G, and C content at the third position. Args: sequ (str): DNA sequence A (bool): default = False T (bool): default = False C (bool): default = False G (bool): default = False Returns: - A3 content if arg(A) is True - T3 content if arg(T) is True - C3 content if arg(C) is True - G3 content if arg(G) is True - None if all args are False """ from itertools import tee A3 = 0 T3 = 0 G3 = 0 C3 = 0 sequ = str(sequ) codon, codon_1 = tee(sequ[i: i + 3] for i in range(0, len(sequ), 3) if len(sequ[i: i + 3]) == 3) lenght_codon = sum(1 for _ in codon_1) for i in codon: if A and A == True: if i[2] == 'A': A3 += 1 elif T and T == True: if i[2] == 'T': T3 += 1 elif C and C == True: if i[2] == 'C': C3 += 1 elif G and G == True: if i[2] == 'G': G3 += 1 if A and A == True: A3 = (A3 / lenght_codon ) * 100 return A3 elif T and T == True: T3 = (T3 / lenght_codon ) * 100 return T3 elif G and G == True: G3 = (G3 / lenght_codon ) * 100 return G3 elif C and C == True: C3 = (C3 / lenght_codon ) * 100 return C3
def get_neighbors(x, y, board): """ part 2 "neighbors" complexity of running get_neighbors for every square can actually be shown to run in linear time (not O(n^2)) by considering the number of times each square (floor or nonfloor) is visited """ nb = [] for di in range(8): dj = (di+2) % 8 dx, dy = (di % 4 > 0) * (2 * (di//4) - 1), (dj % 4 > 0) * (2 * (dj//4) - 1) n = 0 while True: n += 1 nx, ny = x + n*dx, y + n*dy if nx < 0 or nx >= len(board) or ny < 0 or ny >= len(board[0]): break if board[nx][ny] != '.': nb.append((nx, ny)) break return nb
def flatten(list_a: list): """Problem 7: Flatten a Nested List Structure, Parameters ---------- list_a : list The input list Returns ------- flat : list The flattened input list Raises ------ TypeError If the given argument is not of `list` type """ if not isinstance(list_a, list): raise TypeError('The argument given is not of `list` type.') flat = [] for x in list_a: if isinstance(x, list): # If element x is a list then the initial list should be # extended by the elements of list x flat.extend(flatten(x)) else: # Otherwise a single element is appended flat.append(x) return flat
def _get_stack_id(proj: str): """ Matching the project ID to CPG stack/dataset """ if proj == 'csiro-als': # We don't have a project for ALS yet return 'nagim' return proj