content
stringlengths
42
6.51k
def any2unicode(text, encoding='utf8', errors='strict'): """Convert `text` (bytestring in given encoding or unicode) to unicode. Parameters ---------- text : str Input text. errors : str, optional Error handling behaviour if `text` is a bytestring. encoding : str, optional ...
def replace_files(d,file_list): """ Replace files for mzmine task Inputs: d: an xml derived dictionary of batch commands file_list: a list of full paths to mzML files Outputs: d: an xml derived dict with new files in it """ for i,step in enumerate(d['batch']['batchstep']): ...
def time2int(float_time): """ Convert time from float (seconds) to int (nanoseconds). """ int_time = int(float_time * 10000000) return int_time
def extract_data_from_item(current_item): """ Extract data from dynamodb item. :param current_item: DynamoDB item """ bastion = current_item.get('bastion', None) alias = current_item.get('alias', None) account_num = current_item.get('accountNum', None) admins = len(current_item.get('adgroup-...
def mean(num_list): """ Calculates the mean of a list of numbers Parameters --------- num_list : list List of numbers of calculate the average of Returns ------- the average """ a = 0 for i in num_list: a += i return a / len(num_list)
def has_variant_suport(ref_base, alt_base, pos, alt_dict): """ ref_base: reference base of the true varaint. alt_base: alternative base of the true variant pos: pos: candidate position for unification. alt_dict: dictionary (pos: pos info) which keep position level candidate reference base and altern...
def make_input_parameters(name,value,minimum,maximum): """ Outputs a parameter dictionary to be used in the fit_model function. This dictionary has the following form: {parameter_name1:{'value':X, 'min':Y, 'max':Z}, parameter_name2:{'value':A, 'min':B, 'max':C}, ... } ...
def partion( key ): """ split the key have the format of donkey Arguments --------- key: string Examples -------- >>>partion( 'a__b__c' ) [ 'a', 'b', 'c' ] """ return key.split( '__' )
def roi(total_revenue, total_marketing_costs, total_other_costs): """Return the Return on Investment (ROI). Args: total_revenue (float): Total revenue generated. total_marketing_costs (float): Total marketing costs total_other_costs (float): Total other costs Returns: Retur...
def AutoUpdateUpgradeRepairMessage(value, flag_name): """Messaging for when auto-upgrades or node auto-repairs. Args: value: bool, value that the flag takes. flag_name: str, the name of the flag. Must be either autoupgrade or autorepair Returns: the formatted message string. """ action =...
def get_category_ids(form_data: dict) -> list: """Extract all category ids from the form data dictionary""" category_ids = [] for key in form_data: if key.startswith('category-'): category_ids.append(form_data[key]) return category_ids
def get_print_length(s: str) -> int: """ Returns number of lines a string object would have if split into a list """ return len(s.splitlines())
def findstr_in_file(file_path, line_str): """ Return True if the line is in the file; False otherwise. (Trailing whitespace is ignored.) """ try: with open(file_path, 'r') as fh: for line in fh.readlines(): if line_str == line.rstrip(): return ...
def check_ports(port_dictionary): """ This will run through the ports that are supposedly open and see if 22 is listed. If so, it will return the device type if it can be determined or False if not open Args: port_dictionary (dict) : dictionary of either one port or multiple ports of format {<p...
def close_tables(egg_string, target_level=0): """ The egg string is hierarchically ordered. This function appends curly brackets to close open tables. It takes the indentation of the last closed bracket as reference for the current level/depth of the hierarchy. :param egg_string: :type egg_string: str ...
def toList(s): """If s is not a list, return [s].""" if type(s).__name__ == "list": return s else: return [s]
def get_false_positive(false_p): """ Returns True, False for false positive as per DefectDojo standards. :param false_p: :return: """ if false_p: return True else: return False
def check_digit_from_upca(value): """calculate check digit, they are the same for both UPCA and UPCE""" check_digit=0 odd_pos=True for char in str(value)[::-1]: if odd_pos: check_digit+=int(char)*3 else: check_digit+=int(char) odd_pos=not odd_pos #alternat...
def dfdb(B, E): """ B is the base E is the exponent f = B^E partial df/dB = E * B**(E-1) """ out = E * (B**(E-1)) return out
def weak_pareto_dominates(vec1, vec2): """ Returns whether vec1 weakly dominates vec2 """ for i in range(len(vec1)): if vec1[i] < vec2[i]: return False return True
def _merge_args(args_base, args_adding): """add two dicts, return merged version""" return dict(list(args_base.items()) + list(args_adding.items()))
def find_cycle(start, graph): """Finds a path from `start` to itself in a directed graph. Note that if the graph has other cycles (that don't have `start` as a hop), they are ignored. Args: start: str name of the node to start. graph: {str => iterable of str} is adjacency map that defines the graph. ...
def params_1(kernels, time_1, time_system, time_format, sclk_id): """Input parameters from WGC API example 1.""" return { 'kernels': kernels, 'times': time_1, 'time_system': time_system, 'time_format': time_format, 'sclk_id': sclk_id, }
def _callable_str(callable_object): """ Get a name of the callable object. :param callable_object: object to be called :return: name of the callable object """ return callable_object.__name__ if hasattr(callable_object, '__name__') else str(callable_object)
def toggle_filters(count): """ hides/opens the filter block """ # Toggle between show and hide return count % 2 == 1 if count is not None else False
def is_ascii(s): """Check if s contains of ASCII-characters only.""" return all(ord(c) < 128 for c in s)
def _TrackSelector(kwargs): """Returns TrackSelector module name. Arguments: - `kwargs`: Not used in this function. """ return ("Alignment.CommonAlignmentProducer.AlignmentTrackSelector_cfi", "AlignmentTrackSelector")
def asymmetry (A,B,C): """ Ray's asymmetry parameter for molecular rotation. For a prolate symmetric top (B = C), kappa = -1. For an oblate symmetric top (B = A), kappa = +1. See Townes and Schawlow, Ch. 4. """ return (2.*B - A - C)/(A - C)
def is_html_input(dictionary): """ We check that it came html form or JSON request. :param object dictionary: Object with dictionary interface. :return: Check result. :rtype: bool """ return hasattr(dictionary, 'getlist')
def get_distance(p1, p2): """Distance entre les points p1 et p2, dans le plan horizontal, sans prendre en compte le y qui est la verticale. """ if p1 and p2: if None not in p1 and None not in p2: d = ((p1[0] - p2[0])**2 + (p1[2] - p2[2])**2)**0.5 return int(d) return...
def bias(tree, context): """A constant feature function, always returning 1""" return {'': 1}
def get_data_id(data_str): """ If data_str is of the format <ID>:<NAME>, or <URI>/<PATH>:<NAME> return ID or URI """ if ':' in data_str: name_or_id, _ = data_str.split(':') return name_or_id else: return data_str
def _compression_value_conversion(value): """ PNG compression values are within range [0, 9]. This value must be mapped to a [0-100] interval. """ try: if int(value) < 0 or int(value) > 100: raise RuntimeError("Quality argument must be of between 0 and 100.") return 0 if ...
def _interpret_output_mode(arg, default="interactive"): """ >>> _interpret_output_mode('Repr_If_Not_None') 'repr-if-not-none' """ if arg is None: arg = default rarg = str(arg).strip().lower().replace("-", "").replace("_", "") if rarg in ["none", "no", "n", "silent"]: retu...
def eosToLFN( path ): """Converts a EOS PFN to an LFN. Just strip out /eos/cms from path. If this string is not found, return path. ??? Shouldn't we raise an exception instead?""" return path.replace('root://eoscms.cern.ch/', '').replace('/eos/cms','')
def RemoveDaysFromShowtime( showtimeString ): """ Given a showtime string of the form "M 20:00, 23:00" or "Sat/Sun 20:00", this function removes *all* the days, returning just the time(s). """ s = showtimeString.strip() pp = s.split() dayString = pp[0] return s.lstrip(dayString).strip()
def magic_to_dict(kwargs, separator="_") -> dict: """decomposes recursively a dictionary with keys with underscores into a nested dictionary example : {'magnet_color':'blue'} -> {'magnet': {'color':'blue'}} see: https://plotly.com/python/creating-and-updating-figures/#magic-underscore-notation Paramete...
def circle_line_intersection(circle_center, circle_radius, pt1, pt2, full_line=True, tangent_tol=1e-9): """ Find the points at which a circle intersects a line-segment. This can happen at 0, 1, or 2 points. :param circle_center: The (x, y) location of the circle center :param circle_radius: The radius of ...
def is_pure(obj, prop): """ Checking and setting type to PURE Args: obj: None prop: None Return: Boolean """ return True if (not prop and not obj) else False
def reverse(v): """ Reverses any iterable value """ return v[::-1]
def split_by_list(s, intlist): """ Split iterable by a list of indices :param s: iterable :param intlist: list of indices :return: list of splitted parts """ res = [] points = [0] + intlist + [len(s)] for i in range(len(points)-1): res.append(s[points[i]:points[i+1]]) ...
def _render_groupings(fields): """Render the group by part of a query. Parameters ---------- fields : list A list of fields to group by. Returns ------- str A string that represents the "group by" part of a query. """ if not fields: return "" return "GRO...
def is_nested_list(input): """Checks if a list is nested, i.e., contains at least one other list.""" # Check if there is any list in the list if isinstance(input, list): return any(isinstance(elem, list) for elem in input) else: return False
def get_padding_2d(in_shape, k_shape, mode): """ H_out = (H_in + pads - K) // s + 1 if "VALID": pads = 0 if "SAME": pads = (h_out - 1) * s + k - H_in s = 1 --> h_out === h_in so, pads = (h_in - 1) * 1 + k - H_in so, pads = (w - 1) + k - w """ def get_padding_1d(w, k): if mode...
def MakeGray(rgbTuple, factor, maskColour): """ Make a pixel grayed-out. If the pixel matches the `maskColour`, it won't be changed. :param `rgbTuple`: a tuple representing a pixel colour; :param `factor`: a graying-out factor; :param `maskColour`: a colour mask. """ if rgbTuple != mas...
def addExperiment(inData, experiment): """ Convert from MIP granularity data to experiment granularity data; - add `experiment` to title, - add `experiment` to subject as DRS, - remove identifier. Returns deepcopy()_ed data, given `inData` is preserved. """ from copy import deepcopy ...
def lowercase(word_list): """ Simple wrapper to convert all words in the wordlist to lowercase. """ return [x.lower() for x in word_list]
def set_focus_emulation_enabled(enabled: bool) -> dict: """Enables or disables simulating a focused and active page. Parameters ---------- enabled: bool Whether to enable to disable focus emulation. **Experimental** """ return { "method": "Emulation.setFocusEmulationEna...
def arg_maxes(arr, indices=None): """ Get indices of all maximal values in array :param arr: the array :param indices: optional permutation on indices :return: array with indices of maxima """ if len(arr) == 0: return [] maxes = [] maximum = max(arr) for idx, el in enume...
def _SplitOptions(options): """Split string of hardware options into a list.""" if options: return options.split() else: return []
def flatten(children, sidx, lidx): """ Helper function used in Visitor to flatten and filter lists of lists """ ret = [children[sidx]] rest = children[lidx] if not isinstance(rest, list): rest = [rest] ret.extend(filter(bool, rest)) return ret
def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ position = set() for i in range(len(board)): for j in range(len(board)): if board[i][j] == None: position.add((i,j)) return position
def factorial(num: int): """ Calculates the factorial of a number. :param num: Number """ tot = 1 for n in range(1, num + 1): tot *= n return tot
def serialize_recent_data(analysis, type_str): """Convert output of images to json""" output = [] for e in range(0, len(analysis)): temp_output = { 'attributes': { 'instrument': analysis[e].get('spacecraft', None), 'source': analysis[e].get('source', None)...
def intersect(bboxA, bboxB): """Return a new bounding box that contains the intersection of 'self' and 'other', or None if there is no intersection """ new_top = max(bboxA[1], bboxB[1]) new_left = max(bboxA[0], bboxB[0]) new_right = min(bboxA[0]+bboxA[2], bboxB[0]+bboxB[2]) new_bottom = min(bboxA[1]+bboxA...
def cie_uv_10_deg_offsets(wavelength): """ Setup labels for CIE 2 deg for `uv` diagrams. I'm sure there is a more automated way to do this. We could calculate slope and calculate a line with inverse slope and maybe detect direction and calculate needed distance for new point, but this was easy ...
def _db_prepare_truncate(tableschema, tablename): """Prepare a truncate statement for a table in the database. @FIXME: as this is prone to injection check whether the tablename mentioned in args really exists. """ sql = """truncate table %(sch)s.%(tab)s cascade""" params = dict(sch=tableschema,...
def path_stroke_fix(path): """help to correct the path names of a given path""" path = path.replace('\\', '/') return path if path[-1] == '/' else f"{path}/"
def sort(source_list, ignore_case=False, reverse=False): """ :param list source_list: The list to sort :param bool ignore_case: Optional. Specify true to ignore case (Default False) :param bool reverse: Optional. Specify True to sort the list in descending order (Default False) :return: The sorted ...
def hailstone(n): """Print the hailstone sequence starting at n and return its length. >>> a = hailstone(10) 10 5 16 8 4 2 1 >>> a 7 """ "*** YOUR CODE HERE ***" step = 1 print(n) while n != 1: if n % 2 == 0: n = n // 2 els...
def make_iterable(idx): """ Simple function to ensure that an argument is iterable""" try: iter(idx) except TypeError: if idx is None: return [] else: idx = [idx] return idx
def unit(name): """Unit symbol of a counter, motor or EPICS record name: string, name of EPICS process variable or name of Python variable """ from os.path import splitext unit = "" if unit == "": try: unit = eval(name).unit except: pass if unit == "": try: unit = eva...
def to_dict_flat(rec_arr): """ convert array of records to dictionary rec[0] -> rec[1] """ return {item[0]: item[1] for item in rec_arr}
def _value_to_boolean(value): """Converts true-ish and false-ish values to boolean.""" try: value = value.upper() if value in ["TRUE", "T"]: return True elif value in ["FALSE", "F"]: return False except AttributeError: pass try: value = in...
def get_sorted(dictionary): """ Sort the dictionary """ return sorted(dictionary, key=lambda x: dictionary[x], reverse=True)
def _ref(ref: str): """ ``` {'ref': ref} ``` """ return {'ref': ref}
def fix(f, start): """Compute a fixed point of `f`, the hard way, starting from `start`.""" prev, current = start, f(start) while current != prev: prev, current = current, f(current) return current
def clamp(x: float, minval: float, maxval: float) -> float: """ Clamp value """ if x >= maxval: return maxval elif x <= minval: return minval return x
def str_match_fuzzy(xstring, list_string): """ if any of list_strinf elt matches partially xstring """ for xi in list_string: if xstring.find(xi) > -1: return True return False
def _cut_string(string: str, from_line: int, to_line: int, from_col: int, to_col: int): """Cut a string and return the resulting substring. Example: Given a *string*, "xxxxxxxxxxx xxxxxAXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXBxxxx xxxx" , to cut a substring from...
def cubed(v): """ Returns cubed value """ return v*v*v
def operating_system(os): """ Property: PatchBaseline.OperatingSystem """ valid_os = [ "WINDOWS", "AMAZON_LINUX", "AMAZON_LINUX_2", "UBUNTU", "REDHAT_ENTERPRISE_LINUX", "SUSE", "CENTOS", "DEBIAN", "ORACLE_LINUX", ] if os no...
def tolist(a): """Convert a given input to the dictionary format. Parameters ---------- a : list or other Returns ------- list Examples -------- >>> tolist(2) [2] >>> tolist([1, 2]) [1, 2] >>> tolist([]) [] """ if type(a) is list: return a ...
def find_brackets(smiles): """ Find indexes of the first matching brackets ( "(" and ")" ). It doesn't check if all brackets are valid, i.e. complete. Parameters ---------- smiles Returns ------- list Index of first and second matching bracket. """ indexes = [] n_b...
def correct_time_of_shot(shot, goal_times): """ Corrects time of shot (a goal was scored on) by comparing its original time with a list of actual times of goals scored in the game and finding the goal incident with the minimum time difference. Optionally correcting the time of the shot when a non-ze...
def count_bad_base(seq): """ Return the number of bases that are not A/T/C/G, excluding 'N's """ #count = 0 #for s in seq: # if s not in ['A','T','C','G','N']: # pdb.set_trace() # print(s) return sum(s.upper() not in ['A','T','C','G','N'] for s in seq)
def pick_arg_type(arg): """Arg is a bit string whose name length determines what type we should use for passing it""" return 'xed_uint32_t' #if arg == None or len(arg) <= 32: # utype = "xed_uint32_t" #else: # utype = "xed_uint64_t" #return utype
def remap_output(joboutput): """ @rtype : boolean """ jobfileoutput = joboutput if joboutput.startswith("ftp://"): jobfileoutput = joboutput.split('/')[-1] if joboutput.startswith("s3://"): jobfileoutput = joboutput.split('/')[-1] return jobfileoutput
def jumping_on_clouds(array): """https://www.hackerrank.com/challenges/jumping-on-the-clouds""" jumps = 0 i = 0 n = len(array) while i < n - 1: jumps += 1 if i < n - 2 and array[i + 2] == 0: i = i + 2 else: i += 1 return jumps
def bits_to_intervals(bits): """ Converts bit numbers to bit intervals. :returns: list of tuples: [(bitoffset_0, bitsize_0), ...] """ if not bits: return [] bit_numbers = sorted(bits) result = [] bitoffset = prev_bit = bit_numbers[0] bitsize = 1 for bit in bit_numbers[1:]: ...
def box(t, t_start, t_stop): """Return a box-shape (Theta-function) that is zero before `t_start` and after `t_stop` and one elsewehere. Parameters: t (scalar, numpy.ndarray): Time point or time grid t_start (scalar): First value of `t` for which the box has value 1 t_stop (scalar)...
def _sum(a, i, j): """Return the sum of the elements from a[i] to a[j].""" if i > j: # T(n) = 0 return 0 if i == j: # T(n) = 1 return a[i] mid = (i+j)//2 return _sum(a, i, mid) + _sum(a, mid+1, j)
def parser(data): """ Parse fish information. Inputs: data, a tuple of strings. Returns: a list of ints. """ school = list(map(int, data[0].split(","))) counter = [0 for x in range(9)] for x in range(max(school) + 1): counter[x] += school.count(x) return counter
def list_rindex(lst, el): """Index of the last occurrence of an item in a list. Return None is item not found.""" for i in reversed(range(len(lst))): if lst[i] == el: return i return None
def build_entity(start, end, value, entity_type, **kwargs): """Builds a standard entity dictionary. Adds additional keyword parameters.""" entity = { "start": start, "end": end, "value": value, "entity": entity_type } entity.update(kwargs) return entity
def flat_dict(od, separator='_', key=''): """ Function to flatten nested dictionary. Each level is collapsed and joined with the specified seperator. :param od: dictionary or dictionary-like object :type od: dict :param seperator: character(s) joining successive levels :type seperator: str...
def non_content_line(line): """ Returns True iff <line> represents a non-content line of an Extended CSV file, i.e. a blank line or a comment. :param line: List of comma-separated components in an input line. :returns: `bool` of whether the line contains no data. """ if len(line) == 0: ...
def play_monty_hall(switch=False): """Return ``True`` if the contestant wins one round of Monty Hall. Arguments --------- switch : bool If `True`, then switch doors, otherwise stick with the original door. """ ### To Do: Use np.random to simulate a game win = True # Stub return...
def combinations(l): """Pure-Python implementation of itertools.combinations(l, 2).""" result = [] for x in range(len(l) - 1): ls = l[x+1:] for y in ls: result.append((l[x],y)) return result
def compare(v1, v2): """ Order smallest to largest. """ if v1 < v2: return -1 elif v1 > v2: return 1 return 0
def check_variable_type(variable_type): """return True if GitLab variable_type is valid""" if variable_type in {'env_var', 'file'}: return True return False
def flatten_dict(data: dict, level_separator: str = ".") -> dict: """Flattens a nested dictionary, separating nested keys by separator. Args: data: data to flatten level_separator: separator to use when combining keys from nested dictionary. """ flattened = {} for key, value in data...
def ExpandedName(node): """Get the expanded name of any object""" if hasattr(node, 'nodeType') and node.nodeType in [Node.ELEMENT_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.ATTRIBUTE_NODE, NAMESPACE_NODE]: return ExpandedNameWrapper.ExpandedNameWrapper(node) return None
def get_station(nmeaStr): """Return the station without doing anything else. Try to be fast""" fields = nmeaStr.split(',') station = None for i in range(len(fields)-1,5,-1): if len(fields[i])==0: continue # maybe it should throw a parse exception instead? if fields[i][0] in ...
def close(f1, f2, epsilon=0.0001): """Checks if f1~f2 with epsilon accuracy.""" return abs(f1-f2) <= epsilon
def score(flags): """The weights are completely arbitrary""" weight = { 'onstore-dual-use': 0.8, 'dual-use': 0.8, 'onstore-spyware': 1.0, 'offstore-spyware': 1.0, 'offstore-app': 0.8, 'regex-spy': 0.3, 'odds-ratio': 0.2, 'system-app': -0.1 } ...
def delete_keys_seq(d, keys): """:yaql:deleteAll Returns dict with keys removed. Keys are provided as an iterable collection. :signature: dict.deleteAll(keys) :receiverArg dict: input dictionary :argType dict: mapping :arg keys: keys to be removed from dictionary :argType keys: iterabl...
def _parse_name(name): """Parse name in complex dict definition. In complex definition required params can be marked with `*`. :param name: :return: name and required flag :rtype: tuple """ required = False if name[-1] == '*': name = name[0:-1] required = True ret...
def is_generic(klass: type): """Determine whether klass is a generic class.""" return hasattr(klass, "__origin__")
def _determine_overlap_3prime( fragment1_start, fragment1_stop, fragment2_start, fragment2_stop ): """ Observe whether the start-site of fragment2 overlaps the 3' end of fragment1. Parameters: ----------- fragment1_start fragment1_stop fragment2_start fragment2_stop Returns...