content
stringlengths
42
6.51k
def extract_times_from_individuals(individuals, warm_up_time, class_type): """ Extract waiting times and service times for all individuals and proceed to extract blocking times for just class 2 individuals. The function uses individual's records and determines the type of class that each individual is, based on the number of nodes visited. """ waiting_times = [] serving_times = [] blocking_times = [] first_node_to_visit = 2 - class_type total_node_visits = class_type + 1 for ind in individuals: if ( ind.data_records[0].node == first_node_to_visit and len(ind.data_records) == total_node_visits and ind.data_records[total_node_visits - 1].arrival_date > warm_up_time ): waiting_times.append(ind.data_records[total_node_visits - 1].waiting_time) serving_times.append(ind.data_records[total_node_visits - 1].service_time) if ( first_node_to_visit == ind.data_records[0].node == 1 and ind.data_records[0].arrival_date > warm_up_time ): blocking_times.append(ind.data_records[0].time_blocked) return waiting_times, serving_times, blocking_times
def reverse(sentence): """ split original sentence into a list, then append elements of the old list to the new list starting from last to first. then join the list back toghether. """ original = sentence.split() reverse = [] count = len(original) - 1 while count >= 0: reverse.append(original[count]) count = count - 1 result = " ".join(reverse) return result
def set_compilation_options(opts, compilation_options=None): """Set the IPU compilation options for the session. .. code-block:: python # Create a device with debug execution profile flag set to "compute_sets" opts = create_ipu_config() opts = set_compilation_options(opts, compilation_options={"debug.instrument": "true", "debug.allowOutOfMemory": "true"}) ipu.utils.configure_ipu_system(opts) with tf.Session() as s: ... Args: opts: An IpuOptions session control protobuf. compilation_options: A dictionary of Poplar compilation option flags to be sent to the executor. Returns: The IpuOptions configuration protobuf, with engine compilation options set. """ if compilation_options: if not isinstance(compilation_options, dict): raise Exception("`compilation_options` must be a dictionary") for (option_name, value) in compilation_options.items(): compilation_option = opts.compilation_options.add() compilation_option.option = option_name compilation_option.value = value return opts
def remove_leading_zeros(string: str) -> str: """Removes leading zeros from the given string, if applicable. Parameters ---------- string: str The string to remove leading zeros from. This string must represent an integer value (i.e. it cannot contain a decimal point or any other non-digit character). Returns ------- str The string without leading zeros """ return str(int(string))
def delta_g(g, g0, qg, qg0): """Gera o delta g""" if g0 < g: return (g0 - g) - qg else: return (g0 - g) + qg0
def mat_inter(box1, box2): """ whether two bbox is overlapped """ # box=(xA,yA,xB,yB) x01, y01, x02, y02 = box1 x11, y11, x12, y12 = box2 lx = abs((x01 + x02) / 2 - (x11 + x12) / 2) ly = abs((y01 + y02) / 2 - (y11 + y12) / 2) sax = abs(x01 - x02) sbx = abs(x11 - x12) say = abs(y01 - y02) sby = abs(y11 - y12) if lx <= (sax + sbx) / 2 and ly <= (say + sby) / 2: return True else: return False
def create_options(f107=1, time_independent=1, symmetrical_annual=1, symmetrical_semiannual=1, asymmetrical_annual=1, asymmetrical_semiannual=1, diurnal=1, semidiurnal=1, geomagnetic_activity=1, all_ut_effects=1, longitudinal=1, mixed_ut_long=1, mixed_ap_ut_long=1, terdiurnal=1): """Creates the options list based on keyword argument choices. Defaults to all 1's for the input options. Parameters ---------- f107 : float Account for F10.7 variations time_independent : float Account for time variations symmetrical_annual : float Account for symmetrical annual variations symmetrical_semiannual : float Account for symmetrical semiannual variations asymmetrical_annual : float Account for asymmetrical annual variations asymmetrical_semiannual : float Account for asymmetrical semiannual variations diurnal : float Account for diurnal variations semidiurnal : float Account for semidiurnal variations geomagnetic_activity : float Account for geomagnetic activity (1 = Daily Ap mode, -1 = Storm-time Ap mode) all_ut_effects : float Account for all UT/longitudinal effects longitudinal : float Account for longitudinal effects mixed_ut_long : float Account for UT and mixed UT/longitudinal effects mixed_ap_ut_long : float Account for mixed Ap, UT, and longitudinal effects terdiurnal : float Account for terdiurnal variations Returns ------- list 25 options as a list ready for msis2 input """ options = [f107, time_independent, symmetrical_annual, symmetrical_semiannual, asymmetrical_annual, asymmetrical_semiannual, diurnal, semidiurnal, geomagnetic_activity, all_ut_effects, longitudinal, mixed_ut_long, mixed_ap_ut_long, terdiurnal] + [1]*11 return options
def hamming2(s1, s2): """Calculate the Hamming distance between two bit strings""" assert len(s1) == len(s2) return sum(c1 != c2 for c1, c2 in zip(s1, s2))
def percent_btn(value): """Convert the current value to a percentage in decimal form.""" try: x = float(value) return x / 100 except ValueError: return "ERROR"
def ERR_BANNEDFROMCHAN(sender, receipient, message): """ Error Code 474 """ return "ERROR from <" + sender + ">: " + message
def ternary_point_kwargs( alpha=1.0, zorder=4, s: float = 25, marker="X", ): """ Plot point to a ternary figure. """ return dict( alpha=alpha, zorder=zorder, s=s, marker=marker, )
def get_lines_len(word_sizes): """return the length of all the lines that are 0 weperated""" line_lens=[] current_line_len=0 for dim in word_sizes: if dim==0: line_lens.append(current_line_len) current_line_len=0 else: current_line_len+=dim[0] return line_lens
def broadcast(i, n): """Broadcasts i to a vector of length n.""" try: i = list(i) except: i = [i] reps, leftovers = divmod(n, len(i)) return (i * reps) + i[:leftovers]
def wilkinson_algorithm(values, binwidth): """Wilkinson's algorithm to distribute dots into horizontal stacks.""" ndots = len(values) count = 0 stack_locs, stack_counts = [], [] while count < ndots: stack_first_dot = values[count] num_dots_stack = 0 while values[count] < (binwidth + stack_first_dot): num_dots_stack += 1 count += 1 if count == ndots: break stack_locs.append((stack_first_dot + values[count - 1]) / 2) stack_counts.append(num_dots_stack) return stack_locs, stack_counts
def constructTableQuery(ch, index): """helper function for characterInTableName""" payload = "' OR EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='test' AND TABLE_NAME LIKE '" tableStr = "" if(index == "no index"): tableStr += "%" + ch + "%" elif(index >= 0): tableStr += index * "_" + ch + "%" else: index *= -1 index -= 1 tableStr += "%" + ch + "_" * index payload += tableStr + "') AND ''='" #do I even need the AND ''=' part? it evaluates to '' = '' which is true so true/false AND true? Seems redundant return payload
def get_colors(scores, top_emotion): """Map colors to emotion `scores`""" red = green = blue = 0 # For warm and cold emotions, return solid color if top_emotion == 'anger': color = (255, 0, 0) # red return color elif top_emotion == 'fear': color = (255, 255, 0) # yellow return color elif top_emotion in ['sadness', 'contempt']: color = (0, 0, 255) # blue return color for e in scores.keys(): if e in ['anger', 'fear', 'happiness']: red += scores[e] if e in ['disgust', 'surprise', 'contempt', 'happiness']: green += scores[e] if e in ['neutral', 'sadness']: blue += scores[e] color = [int(c * 255) for c in [red, green, blue]] print("Red: {}, Green: {}, Blue: {}".format(*color)) return color
def parseargs(string:str): """Split a given string into individual arguments, seperated into key:arg for <key>=(' or ")<arg>(same char as start)""" arg = {} # ([%-%w]+)=([\"'])(.-)%2 # '([\w]+)=([\"\'])(.*)' # '([-\w]+)=([\"\']*)' ## pattern = re.compile('([\w]+)=([\"\'])(.*)') ## print(pattern) ## for match in re.findall(pattern, string): ## print(match) parts = string.split(' ') bkey = '' buffer = '' end = '"' for part in parts: if '=' in part: key, vp = part.split('=') if vp[0] in ('"', "'"): end = vp[0] if vp.endswith(end): arg[key] = vp[1:-1] else: bkey = key buffer += vp elif part.endswith(end): buffer += ' '+part arg[bkey] = buffer[1:-1] bkey, buffer = '', '' else: buffer += ' '+part return arg
def compute_in_degrees(digraph): """ take in param graph, output in degree dictionary """ graph = {} for node in digraph: graph[node] = 0 for node in digraph: for itr in digraph[node]: graph[itr] += 1 return graph
def normalize(path): """Replace spaces with underscores, everything to lowercase, remove double slashes :returns: normalized string """ return path.replace(" ", "_").lower().replace("//", "/")
def link_format(name, url): """make markdown link format string """ return "["+name+"]"+"("+url+")"
def _map_parameters_to_vars(px): """Return map `{a: x, b: x, ...}`.""" d = {d['a']: k for k, d in px.items()} d.update((d['b'], k) for k, d in px.items()) return d
def get_value(data, value): """Retrieve weather value.""" try: if value == "@mps": return round(float(data[value]) * 3.6, 1) return round(float(data[value]), 1) except (ValueError, IndexError, KeyError): return None
def quadratic_mag_model(data, a, b, c, d, e, f): """ Return the value of a three-dimenstional function linear in temperature and metallicity (with cross-term) and quadratic in the third term (nominally magnitude). Parameters ---------- data : array-like with dimensions (3, n) The idenpendent variable. Each column represents a collection of three values to be passed to the thee dimensions of the function. a : float or int The value of the constant coefficient. b, c, d : float or int The values of the coefficients for the linear terms of the function. e : float or int The value of the coefficient for the cross-term between temperature and metallicity. f : float or int The coefficient for the quadratic term of the third term (nominally absolute magnitude). Returns ------- float The value of the function for the given data and coefficients. """ return a + b * data[0] + c * data[1] + d * data[2] +\ e * data[1] / data[0] + f * data[2] ** 2
def raise_mask(dqarr, bitmask): """ Function that raises (sets) all the bits in 'dqarr' contained in the bitmask. :Parameters: dqarr: numpy array or integer numpy array which represents a dq plane (or part of it). The function also works when dqarr is a scalar integer. bitmask: integer A bit mask specifying all the bits to be logically "raised" in dqarr. For example, * bitmask=1 = 2**0 will raise bit 0. * bitmask=5 = 2**0 + 2**2 will raise bits 0 and 2. :Returns: newdqarr: numpy array or integer Returns array 'dqarr' with the specified bits raised in all elements (pixels). """ assert isinstance(bitmask, int) # The bits are raised with a binary OR operation. return dqarr | bitmask
def numestate_incolour(colour:str) -> int: """Return the number of fields in given colour.""" if colour in {'brown','blue'}: return 2 return 3
def word_count(text): """ This function counts amount of each given symbol in the text """ count = {} for c in set(text): count[c] = text.count(c) return count
def _unique_deps(new_deps_list): """Unique dependency list, for duplicate items only keep the later ones.""" result = [] deps = set() for dep in reversed(new_deps_list): if dep not in deps: result.append(dep) deps.add(dep) return list(reversed(result))
def moving_average_filter(val, filtered_val_prev, zeta): """ Basic moving average filter zeta = 1 -> ignore prev. vals zeta = 0 -> ignore current val """ filtered_val = (1-zeta)*filtered_val_prev + zeta*val return filtered_val
def sbfiz(value, lsb, width, size): """Signed Bitfield Insert in Zero""" if value & (1 << (width - 1)): # Extend sign sign_ext = (1 << (8 * size)) - (1 << (lsb + width)) return ((value & ((1 << width) - 1)) << lsb) | sign_ext else: return (value & ((1 << width) - 1)) << lsb
def step(x0: float, x1: float, p: float): """ Interplates step=wise between two values such that when p<0.5 the interpolated value is x0 and otherwise it's x1 """ return x0 if p < 0.5 else x1
def chunk_string(input_str, length): """ Splits a string in to smaller chunks. NOTE: http://stackoverflow.com/questions/18854620/ :param input_str: The input string to chunk. :type input_str: str :param length: The length of each chunk. :type length: int :return: A list of the input string as smaller chunks. :rtype: list """ return list((input_str[0 + i:length + i] for i in range(0, len(input_str), length)))
def section_is_higher(smoke_map, center, adjacent): """ True if the adjacent section is higher than the center (the point we're evaluating)""" if adjacent is None: return True else: return smoke_map[adjacent[0]][adjacent[1]] > center
def format_results(results, separator): """ :param results: :param separator: :return: """ if results.get('matched_bibcode', None): match = separator.join([str(results.get(field, '')) for field in ['source_bibcode', 'matched_bibcode', 'confidence', 'score', 'comment']]) if results.get('inspection', None): # found low confidence match or multiple matches for_inspection = [results.get('source_bibcode'), results.get('confidence'), results['inspection'].get('bibcodes'), results['inspection'].get('scores'), results['inspection'].get('comment')] return match, for_inspection # single match return match, None # when error, return status_code return '%s status_code=%s'%(results.get('comment', ''), results.get('status_code', '')), None
def get_netconnect_config(d_cfg): """Convert app configuration to netconnect configuration """ nc_cfg = {} if d_cfg['connection_type'] == 'wifi_client': wcfg = d_cfg['wifi'] cfg = {} cfg['wifi_client'] = {} cfg['name'] = 'wlan0' cfg['ipv4'] = wcfg['ipv4'] cfg['wifi_client']['ssid'] = wcfg['ssid'] cfg['wifi_client']['key'] = wcfg['key'] nc_cfg['lte'] = None nc_cfg['wifi_client'] = cfg elif d_cfg['connection_type'] == 'lte': cfg = {} cfg['name'] = 'ppp' cfg['metric'] = 300 cfg['lte'] = d_cfg['lte'] nc_cfg['lte'] = cfg nc_cfg['wifi_client'] = None else: nc_cfg['wifi_client'] = None nc_cfg['lte'] = None nc_cfg['lan'] = {'ipv4': {}} nc_cfg['lan']['ipv4'] = d_cfg['lan']['ipv4'] nc_cfg['lan']['name'] = d_cfg['lan']['name'] return nc_cfg
def first_not_null(str_one, str_two): """ It returns the first not null value, or null if both are null. Note that if the output of this function is null and it is used as string, the EL library converts it to an empty string. This is the common behavior when using firstNotNull() in node configuration sections. """ if str_one: return str_one return str_two if str_two else ""
def tab_in_leading(s): """Returns True if there are tabs in the leading whitespace of a line, including the whitespace of docstring code samples.""" n = len(s) - len(s.lstrip()) if not s[n:n + 3] in ['...', '>>>']: check = s[:n] else: smore = s[n + 3:] check = s[:n] + smore[:len(smore) - len(smore.lstrip())] return not (check.expandtabs() == check)
def add_box(width, height, depth): """ This function takes inputs and returns vertex and face arrays. no actual mesh data creation is done here. """ verts = [ (+1.0, +1.0, 0.0), (+1.0, -1.0, 0.0), (-1.0, -1.0, 0.0), (-1.0, +1.0, 0.0), (+1.0, +1.0, +2.0), (+1.0, -1.0, +2.0), (-1.0, -1.0, +2.0), (-1.0, +1.0, +2.0), ] faces = [ (0, 1, 2, 3), (4, 7, 6, 5), (0, 4, 5, 1), (1, 5, 6, 2), (2, 6, 7, 3), (4, 0, 3, 7), ] # apply size for i, v in enumerate(verts): verts[i] = v[0] * width, v[1] * depth, v[2] * height return verts, faces
def seven_interp(x, a0, a1, a2, a3, a4, a5, a6): """``Approximation degree = 7`` """ return ( a0 + a1 * x + a2 * (x ** 2) + a3 * (x ** 3) + a4 * (x ** 4) + a5 * (x ** 5) + a6 * (x ** 6) )
def _convert_bool_to_str(var, name): """Convert input to either 'yes' or 'no' and check the output is yes or no. Args: var (str or bool): user input name (str): name of the variable. Returns: out (str): "yes" or "no". """ if var is True: out = "yes" elif var is False: out = "no" else: out = var if out not in {"yes", "no"}: raise ValueError( f"{name} must be 'yes', 'no', True or False. You specified {var}." ) return out
def indict(thedict, thestring): """ https://stackoverflow.com/questions/55173864/how-to-find-whether-a-string-either-a-key-or-a-value-in-a-dict-or-in-a-dict-of-d """ if thestring in thedict: return True for val in thedict.values(): if isinstance(val, dict) and indict(val, thestring): return True elif isinstance(val, str) and thestring in val: return True return False
def two_strings_are_substrings(string1, string2): """ Check if either `string1` or `string2` is a substring of its partner. Useful for checking if one Sample ID is a substring of another Sample ID or vice versa :param string1: str :param string2: str :return: """ return (string1 in string2) or (string2 in string1)
def dp_fib_cs(n: int): """A dynamic programming version of Fibonacci, constant space""" a = 1 # f(n-2) b = 1 # f(n-1) for i in range(2, n): a, b = b, a + b return b
def _center_just(text: str, width: int): """Pads the provided string left and right such that it has a specified width and is centered. Args: text (str): The string to pad. width (int): The desired width of the padded ``text``. Returns: str: The padded ``text``. """ len_diff = width - len(text) if len_diff <= 0: return text pad_before = len_diff // 2 pad_after = len_diff - pad_before return (" " * pad_before) + text + (" " * pad_after)
def split_fields(fields: str = '', delimiter: str = ';') -> dict: """Split str fields of Demisto arguments to SNOW request fields by the char ';'. Args: fields: fields in a string representation. delimiter: the delimiter to use to separate the fields. Returns: dic_fields object for SNOW requests. """ dic_fields = {} if fields: if '=' not in fields: raise Exception( f"The argument: {fields}.\nmust contain a '=' to specify the keys and values. e.g: key=val.") arr_fields = fields.split(delimiter) for f in arr_fields: field = f.split('=', 1) # a field might include a '=' sign in the value. thus, splitting only once. if len(field) > 1: dic_fields[field[0]] = field[1] return dic_fields
def merge(old, new): """Merge dicts""" for key, value in new.items(): if key in old and isinstance(old[key], dict): old[key] = merge(old[key], value) else: old[key] = value return old
def selection(triple, variables): """Apply selection on a RDF triple""" bindings = set() if variables[0] is not None: bindings.add((variables[0], triple[0])) if variables[1] is not None: bindings.add((variables[1], triple[1])) if variables[2] is not None: bindings.add((variables[2], triple[2])) return bindings
def solve(_n, tree): """ Given a list of list of tokens: . (empty), or # (tree), compute the number of trees one would encounter if one traverses the 2D grid along a slope of (3, 1). :param _n: The number of rows in the 2D grid. :param tree: The 2D grid as a list of list. :return: The number of trees encountered on a traversal along the slope (3, 1). """ _i, _j = 0, 0 count = 0 _col = len(tree[0]) while _i + 1 < _n: _j = (_j + 3) % _col _i += 1 if tree[_i][_j] == "#": count += 1 return count
def _xmlcharref_encode(unicode_data, encoding): """Emulate Python 2.3's 'xmlcharrefreplace' encoding error handler.""" chars = [] # Step through the unicode_data string one character at a time in # order to catch unencodable characters: for char in unicode_data: try: chars.append(char.encode(encoding, 'strict')) except UnicodeError: chars.append('&#%i;' % ord(char)) return ''.join(chars)
def _get_batch_size(params, hparams, config): """Batch size determined by params dict, HParams, and RunConfig.""" # If params specifies batch size, use that. TPUEstimator passes batch size in # params. batch_size = params and params.get("batch_size") # If not set, then we're running on CPU/GPU, so use the batch size from the # hparams, and multiply by the number of data shards. if not batch_size: batch_size = hparams.tpu_batch_size_per_shard if config: batch_size *= config.t2t_device_info["num_shards"] return batch_size
def enum_value(value, text=None, is_default=False): """Create dictionary representing a value in an enumeration of possible values for a command parameter. Parameters ---------- value: scalar Enumeration value text: string, optional Text representation for the value in the front end is_default: bool, optional Flag indicating whether this is the default value for the list Returns ------- dict """ obj = {'value': value, 'isDefault': is_default} if not text is None: obj['text'] = text else: obj['text'] = str(value) return obj
def int_parameter(level, maxval): """Helper function to scale `val` between 0 and maxval . Args: level: Level of the operation that will be between [0, `PARAMETER_MAX`]. maxval: Maximum value that the operation can have. This will be scaled to level/PARAMETER_MAX. Returns: An int that results from scaling `maxval` according to `level`. """ return int(level * maxval / 10)
def write_txt(w_path, val): """Write text file from the string input. """ with open(w_path, "w") as output: output.write(val + '\n') return None
def dpdx(a, x, y, order=4): """Differential with respect to x :param a: :param x: :param y: :param order: :return: """ dpdx = 0.0 k = 1 # index for coefficients for i in range(1, order + 1): for j in range(i + 1): if i - j > 0: dpdx = dpdx + (i - j) * a[k] * x ** (i - j - 1) * y ** j k += 1 return dpdx
def reverse_complement(fragment): """ provides reverse complement to sequences Input: sequences - list with SeqRecord sequences in fasta format Output: complementary_sequences - list with SeqRecord complementary sequences in fasta format """ # complementary_sequences = [] # for sequence in sequences: # complementary_sequence = SeqRecord( # seq=Seq(sequence.seq).reverse_complement(), # id=sequence.id + "_reverse_complement", # ) # complementary_sequences.append(complementary_sequence) fragment = fragment[::-1].translate(str.maketrans('ACGT', 'TGCA')) return fragment
def impact_seq(impact_list): """String together all selected impacts in impact_list.""" impact_string = '' connector = '-' for impact in impact_list: impact_string += connector + impact.text.strip() return impact_string
def Af_to_stick(Af): """ Given the final-state amplitudy Af, return a stick list Af: a dictionary of array([energy, amplitude]) """ return [ [Af[conf][0].real, float(abs(Af[conf][1]) ** 2)] for conf in Af]
def get_rule_short_description(tool_name, rule_id, test_name, issue_dict): """ Constructs a short description for the rule :param tool_name: :param rule_id: :param test_name: :param issue_dict: :return: """ if issue_dict.get("short_description"): return issue_dict.get("short_description") return "Rule {} from {}.".format(rule_id, tool_name)
def map_to_duration(arr): """ This is a bit crude - creates many too many subdivisions """ arr = [int(x * 63 + 1)/16 for x in arr] return arr
def escape_string(s, encoding='utf-8'): """ escape unicode characters """ if not isinstance(s, bytes): s = s.encode(encoding=encoding) return s.decode('unicode-escape', errors='ignore')
def dataset_is_mnist_family(dataset): """returns if dataset is of MNIST family.""" return dataset.lower() == 'mnist' or dataset.lower() == 'fashion-mnist'
def _getMatchingLayers(layer_list, criterionFn): """Returns a list of all of the layers in the stack that match the given criterion function, including substacks.""" matching = [] for layer in layer_list: if criterionFn(layer): matching.append(layer) if hasattr(layer, 'layerStack'): matching.extend(_getMatchingLayers(layer.layerStack().layerList(), criterionFn)) if layer.hasMaskStack(): matching.extend(_getMatchingLayers(layer.maskStack().layerList(), criterionFn)) if hasattr(layer, 'hasAdjustmentStack') and layer.hasAdjustmentStack(): matching.extend(_getMatchingLayers(layer.adjustmentStack().layerList(), criterionFn)) return matching
def copy_dict_reset(source_dict): """Copy a dictionary and reset values to 0. Args: source_dict (dict): Dictionary to be copied. Returns: new_dict (dict): New dictionary with values set to 0. """ new_dict = {} for key in source_dict.keys(): new_dict[key] = 0 return new_dict
def trimmed(value): """ Join a multiline string into a single line '\n\n one\ntwo\n\n three\n \n ' => 'one two three' """ return ' '.join((line.strip() for line in value.splitlines() if line.strip()))
def has_letter(word): """ Returns true if `word` contains at least one character in [A-Za-z]. """ for c in word: if c.isalpha(): return True return False
def row_major_form_to_ragged_array(flat, indices): """Convert [1, 2, 3, 5, 6], [0, 3] to [[1,2,3], [5,6]] for serialization """ endices = indices[1:] + [None] return [flat[start:end] for start, end in zip(indices, endices)]
def get_shift_value(old_centre, new_centre): """ Calculates how much to shift old_centre to the new_centre :param old_centre: float :param new_centre: float :return: """ diff = old_centre - new_centre if old_centre < new_centre: # <= if diff > 0: return -diff if new_centre > old_centre: # => if diff < 0: return -diff return diff
def arnonA_long_mono_to_string(mono, latex=False, p=2): """ Alternate string representation of element of Arnon's A basis. This is used by the _repr_ and _latex_ methods. INPUT: - ``mono`` - tuple of pairs of non-negative integers (m,k) with `m >= k` - ``latex`` - boolean (optional, default False), if true, output LaTeX string OUTPUT: ``string`` - concatenation of strings of the form ``Sq(2^m)`` EXAMPLES:: sage: from sage.algebras.steenrod.steenrod_algebra_misc import arnonA_long_mono_to_string sage: arnonA_long_mono_to_string(((1,2),(3,0))) 'Sq^{8} Sq^{4} Sq^{2} Sq^{1}' sage: arnonA_long_mono_to_string(((1,2),(3,0)),latex=True) '\\text{Sq}^{8} \\text{Sq}^{4} \\text{Sq}^{2} \\text{Sq}^{1}' The empty tuple represents the unit element:: sage: arnonA_long_mono_to_string(()) '1' """ if latex: sq = "\\text{Sq}" else: sq = "Sq" if len(mono) == 0: return "1" else: string = "" for (m,k) in mono: for i in range(m,k-1,-1): string = string + sq + "^{" + str(2**i) + "} " return string.strip(" ")
def parse_float(val): """parses string as float, ignores -- as 0""" if val == '--': return 0 return float(val)
def packet_read(idn, reg0, width): """ Create an instruction packet to read data from the DXL control table. NOTE: The namesake function in dxl_commv1 serves a specfic purpose. However, this is just a filler here. We use this function to fit with the old code. Helps with backward compatibility. Args: idn: An integer representing the DXL ID number reg0: An integer representing the register index in the control table num_regs: An integer representing the number of registers to read from the control table starting at reg0 Returns: A tuple - (ID of DXL device, address of register, width of the register in bytes) """ return (idn, reg0, width)
def process_legislator_data(raw_data): """ Clean & (partially) flatten the legislator data Args: raw_data (list of nested dictionaries): Legislator data from Returns: dict where key is Bioguide ID and values are legislator info """ legislator_data = {} for leg in raw_data: speaker_id = leg["id"]["bioguide"] legislator_data[speaker_id] = { "first_name": leg["name"]["first"], "last_name": leg["name"]["last"], "gender": leg["bio"]["gender"], "terms": leg["terms"], } return legislator_data
def Cmatrix(rater_a, rater_b, min_rating=None, max_rating=None): """ Returns the confusion matrix between rater's ratings """ assert(len(rater_a) == len(rater_b)) if min_rating is None: min_rating = min(rater_a + rater_b) if max_rating is None: max_rating = max(rater_a + rater_b) num_ratings = int(max_rating - min_rating + 1) conf_mat = [[0 for i in range(num_ratings)] for j in range(num_ratings)] for a, b in zip(rater_a, rater_b): conf_mat[a - min_rating][b - min_rating] += 1 return conf_mat
def is_number(v): """Test if a value contains something recognisable as a number. @param v: the value (string, int, float, etc) to test @returns: True if usable as a number @see: L{normalise_number} """ try: float(v) return True except: return False
def is_alive(thread): """Helper to determine if a thread is alive (handles none safely).""" if not thread: return False return thread.is_alive()
def non_increasing(arr): """ Returns the monotonically non-increasing array """ best_min = arr[0] return_arr = [] for val in arr: return_arr.append(min(best_min, val)) if(val<best_min): best_min = val return return_arr
def string_to_int(value, dp=0): """Converts a homie string to a python bool""" try: return round(int(value), dp) except ValueError: return 0
def getvalueor(row, name, mapping={}, default=None): """Return the value of name from row using a mapping and a default value.""" if name in mapping: return row.get(mapping[name], default) else: return row.get(name, default)
def parse_configurable_as_list(value): """ For string values with commas in them, try to parse the value as a list. """ if ',' in value: return [token.strip() for token in value.split(',') if token] else: return [value]
def recover_path(goal: tuple, path_to: dict) -> list: """Recover and return the path from start to goal.""" path = [goal] previous = path_to[goal] while previous: path.append(previous) previous = path_to[previous] path.reverse() return path
def _linear_interpolation(x, X, Y): """Given two data points [X,Y], linearly interpolate those at x.""" return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])
def remove_prefix(text: str, prefix: str) -> str: """Removes a prefix from a string, if present at its beginning. Args: text: string potentially containing a prefix. prefix: string to remove at the beginning of text. """ if text.startswith(prefix): return text[len(prefix):] return text
def extract_variable_name(attribute_name: str): """ Function used to transform attribute names into cheetah variables attribute names look like standard shell arguments (--attr-a), so they need to be converted to look more like python variables (attr_a) Parameters ---------- attribute_name : str name of the attribute Returns ------- transformed name """ return attribute_name.lstrip("-").replace("-", "_")
def decode_result(found): """ Decode the result of model_found() :param found: The output of model_found() :type found: bool """ return {True: 'Countermodel found', False: 'No countermodel found', None: 'None'}[found]
def get_dtype(i): """ Identify bit depth for a matrix of maximum intensity i. """ depths = [8, 16] for depth in depths: if i <= 2 ** depth - 1: return "uint%d" % (depth,) return "uint"
def poly(x, coefficients): """ Compute a polynome, useful for transformation laws parameters: x: Variable for the polynome coefficients: list of coefficients returns: float result of the polynome """ poly = 0 for i, coef in enumerate(coefficients): poly += coef * x ** i return poly
def squarify(bbox, squarify_ratio, img_width): """ Changes is the ratio of bounding boxes to a fixed ratio :param bbox: Bounding box :param squarify_ratio: Ratio to be changed to :param img_width: Image width :return: Squarified boduning box """ width = abs(bbox[0] - bbox[2]) height = abs(bbox[1] - bbox[3]) width_change = height * squarify_ratio - width bbox[0] = bbox[0] - width_change/2 bbox[2] = bbox[2] + width_change/2 # Squarify is applied to bounding boxes in Matlab coordinate starting from 1 if bbox[0] < 0: bbox[0] = 0 # check whether the new bounding box goes beyond image boarders # If this is the case, the bounding box is shifted back if bbox[2] > img_width: # bbox[1] = str(-float(bbox[3]) + img_dimensions[0]) bbox[0] = bbox[0]-bbox[2] + img_width bbox[2] = img_width return bbox
def copy_project_id_into_json(context, json, project_id_key='project_id'): """Copy the project_id from the context into the JSON request body. :param context: The request context object. :param json: The parsed JSON request body. :returns: The JSON with the project-id from the headers added as the "project_id" value in the JSON. :rtype: dict """ json[project_id_key] = getattr(context, 'tenant', '') return json
def diff_dict(src, dst): """ find difference between src dict and dst dict Args: src(dict): src dict dst(dict): dst dict Returns: (dict) dict contains all the difference key """ diff_result = {} for k, v in src.items(): if k not in dst: diff_result[k] = v elif dst[k] != v: if isinstance(v, dict): diff_result[k] = diff_dict(v, dst[k]) else: diff_result[k] = v return diff_result
def should_run_stage(stage, flow_start_stage, flow_end_stage): """ Returns True if stage falls between flow_start_stage and flow_end_stage """ if flow_start_stage <= stage <= flow_end_stage: return True return False
def new(o, key, cls): """ Method will construct given class if key exists in a object or return None :param o: object from which key is extracted :param key: name of the filed which is tested and extracted later on :param cls: cls which is constructed :return: """ if key in o: if isinstance(o[key], dict): return cls(**o[key]) return cls(o[key]) return None
def make_safe(value, delimiter): """ Recursively parse transcription lists into strings for saving Parameters ---------- value : list or None Object to make into string delimiter : str Character to mark boundaries between list elements Returns ------- str Safe string """ if isinstance(value, list): return delimiter.join(map(lambda x: make_safe(x, delimiter), value)) if value is None: return '' return str(value)
def win(word_list): """ Check the user has guessed the right word or not. Arguments: word_list -- the word list. Returns: True/False -- return True if the word has been guessed right alse return false. """ if '_' not in word_list: return True else: return False
def det(r1, r2, r3): """Calculates the determinant of a 3x3 matrix with rows as args. Args: r1: First row r2: Second row r3: Third row Returns: Determinant of matrix [r1,r2,r3]. Functionally equivalent to jnp.linalg.det(jnp.array([r1,r2,r3])), but jits 10x faster for large batch. """ return r1[0] * r2[1] * r3[2] + r1[1] * r2[2] * r3[0] + r1[2] * r2[0] * r3[ 1] - r1[2] * r2[1] * r3[0] - r1[0] * r2[2] * r3[1] - r1[1] * r2[0] * r3[2]
def refresh_from_weebly_json(obj, resp_json, json_mapping): """ refresh an object from weebly json, returns true if changed """ changed = False for mapping in json_mapping: json_attr = mapping[0] obj_attr = mapping[1] mapping_fn = mapping[2] if len(mapping) >= 3 else None json_val = resp_json[json_attr] old_val = getattr(obj, obj_attr) new_val = mapping_fn(json_val) if mapping_fn else json_val if old_val != new_val: changed = True setattr(obj, obj_attr, new_val) return changed
def sort_x_by_y(x, y): """Sort a list of x in the order of sorting y""" return [xx for _, xx in sorted(zip(y, x), key=lambda pair: pair[0])]
def _power_fit(ln, lb0, gamm1): """A power law fit given some parameters""" return lb0 + gamm1 * (ln - 13.6)
def map_lp_status(lp_status): """Map a launchpad status to a storyboard priority. """ # ('todo', 'inprogress', 'invalid', 'review', 'merged') if lp_status in ('Unknown', 'New', 'Confirmed', 'Triaged', "Incomplete (with response)", "Incomplete (without response)"): return 'todo' elif lp_status in ("Opinion", "Invalid", "Won't Fix", "Expired"): return 'invalid' elif lp_status == 'In Progress': return 'inprogress' elif lp_status in ('Fix Committed', 'Fix Released'): return 'merged' return 'invalid'
def is_kind_of_class(obj, a_class): """create instance""" return True if (isinstance(obj, a_class)) else False
def get_pad_shape(auto_pad, input_spatial_shape, kernel_spatial_shape, strides_spatial, output_spatial_shape): """ return padding shape of conv2d or pooling, ! borrow from onnx Args: auto_pad: string Args: input_spatial_shape: list[int] Args: kernel_spatial_shape: list[int] Args: strides_spatial: list[int] Args: output_spatial_shape: list[int] Returns: list[int] """ pad_shape = [0] * len(input_spatial_shape) if auto_pad in ('SAME_UPPER', 'SAME_LOWER'): for i in range(len(input_spatial_shape)): pad_shape[i] = (output_spatial_shape[i] - 1) * strides_spatial[i] + \ kernel_spatial_shape[i] - input_spatial_shape[i] if (pad_shape[i] % 2) == 0: pad_shape[i] = pad_shape[i] // 2 elif auto_pad == 'VALID': pass if pad_shape[0] != pad_shape[1]: # once the padding is odd, it means we must add extra padding at one end of the input raise ValueError("Not implemented two directional padding") return pad_shape
def cumsum(x): """The cumulative sum of an array.""" total = 0 sums = [] for el in x: total += el sums.append(total) return sums
def changeFormatiCLIP(imgFormat): """ Changes the image format for the iCLIP plot. Positional arguments: imgFormat -- Image format to use. """ return {'toImageButtonOptions' : {'filename' : 'iCLIP', 'width' : None, 'scale' : 1.0, 'height' : None, 'format' : imgFormat} }