content
stringlengths
42
6.51k
def get_condition_label(condition_id: str) -> str: """Convert a condition ID to a label. Labels for conditions are used at different locations (e.g. ensemble prediction code, and visualization code). This method ensures that the same condition is labeled identically everywhere. Parameters ---------- condition_id: The condition ID that will be used to generate a label. Returns ------- The condition label. """ return f'condition_{condition_id}'
def normalize_str(input_str): """ Normalize an input string """ return input_str.strip().lower().replace(" ", " ")
def list_from_i_to_n(i,n): """ make list [i,i+1,...,n] for example: list_from_i_to_n(3,7) => [3,4,5,6,7] list_from_i_to_n(4,6) => [4,5,6] """ result = [] for j in range(i,n+1): result = result + [j] return result
def subexpr_from_unbalanced(expr, ltok, rtok): """Attempts to pull out a valid subexpression for unbalanced grouping, based on opening tokens, eg. '(', and closing tokens, eg. ')'. This does not do full tokenization, but should be good enough for tab completion. """ lcnt = expr.count(ltok) if lcnt == 0: return expr rcnt = expr.count(rtok) if lcnt == rcnt: return expr subexpr = expr.rsplit(ltok, 1)[-1] subexpr = subexpr.rsplit(',', 1)[-1] subexpr = subexpr.rsplit(':', 1)[-1] return subexpr
def binary_search_two_pointers_recur(sorted_nums, target, left, right): """Util for binary_search_feast_recur().""" # Edge case. if left > right: return False # Compare middle number and recursively search left or right part. mid = left + (right - left) // 2 if sorted_nums[mid] == target: return True elif sorted_nums[mid] < target: return binary_search_two_pointers_recur( sorted_nums, target, mid + 1, right) else: return binary_search_two_pointers_recur( sorted_nums, target, left, mid - 1)
def up_to_unmatched_closing_paren(s): """Splits a string into two parts up to first unmatched ')'. Args: s: a string which is a substring of line after '(' (e.g., "a == (b + c))"). Returns: A pair of strings (prefix before first unmatched ')', remainder of s after first unmatched ')'), e.g., up_to_unmatched_closing_paren("a == (b + c)) { ") returns "a == (b + c)", " {". Returns None, None if there is no unmatched ')' """ i = 1 for pos, c in enumerate(s): if c == '(': i += 1 elif c == ')': i -= 1 if i == 0: return s[:pos], s[pos + 1:] return None, None
def on_square(number: int) -> int: """Return the number of grains on a given square.""" return 1 << (number - 1)
def is_alnum_or_in_str(c, s): """ checks if a character is a-z, A-Z, 0-9, or in the string s. :return: True if c is alphanumaric or in s. """ return c.isalnum() or c in s
def stringbytes(elems: list) -> list: """Chain bytes() instances next to each other in elems together. """ out = [] while len(elems) > 0: elem = elems.pop(0) while isinstance(elem, bytes) and len(elems) > 0 and isinstance(elems[0], bytes): elem += elems.pop(0) out.append(elem) return out
def export_data(processed_data, all_drugs_sorted, export_path, cost_usd): """ Formats and writes all entries to export file. Args: processed_data (dictionary): contains all analyzed data. Primary key is drug name (string), and primary value is tuple containing number of prescribers (integer, index 0) and total cost (float, index 1). all_drugs_sorted (list of strings): contains all drug names in sequential list sorted by drug cost and alphanumeric name. export_path (string): path to output file. Returns: None. """ # Safely opens and closes file for writing with open(export_path, 'w') as target_file: # Creates header for output file target_file.write("drug_name,num_prescriber,total_cost\n") # Iterates over whole drug name list for drug in all_drugs_sorted: # Sets number of prescribers num_prescriber = "{}".format(processed_data[drug][0]) # If True, sets cost display in dollars only if cost_usd: # Sets total drug cost in dollars total_cost = "{:.0f}".format(processed_data[drug][1]) # Cost is displayed in dollars and cents else: # Sets total drug cost in dollars and cents total_cost = "{:.2f}".format(processed_data[drug][1]) # Creates final export string for given drug export_text = ",".join([drug,num_prescriber,total_cost]) #If not the last drug, add line break if drug != all_drugs_sorted[-1]: # Adds line break to final export string export_text = "".join([export_text,"\n"]) # Writes data entry to output file target_file.write(export_text) # Completes analyzed data export during file writing return None
def get_computer_move_history(piece, board_state): """Get the move history of the computer""" move_history = [] for move in board_state: if move[0] == piece: move_history.append(int(move[1])) return move_history
def lstrip(s): """lstrip(s) -> string Return a copy of the string s with leading whitespace removed. """ return s.lstrip()
def str2colour(colstr = None): """Return a valid colour from supplied string.""" ret = [0.0, 0.0, 0.0] if colstr: cvec = colstr.split(',') if len(cvec) == 3: try: for c in range(0,3): ret[c] = float(cvec[c]) if ret[c] < 0.0: ret[c] = 0.0 elif ret[c] > 1.0: ret[c] = 1.0 except ValueError: pass return ret
def get_completions(text, options): """ Returns a list of options, which could be used to complete provided text. """ completions = [] l = len(text) for x in options: if len(x) < l: continue if x.startswith(text): completions.append(x) return completions
def safe_equals(x,y): """Handle "x = y" where x and y could be some combination of ints and strs. @param x (any) LHS of the equality check. @param y (any) RHS of the equality check. @return (boolean) The result of the equality check, taking into account the implicit type conversions VB performs to "help" the programmer. """ # Handle NULLs. if (x == "NULL"): x = 0 if (y == "NULL"): y = 0 # Handle equality checks on a wildcarded file name. The # current file name is never going to be equal to "". if (((x == "CURRENT_FILE_NAME") and (y == "")) or ((y == "CURRENT_FILE_NAME") and (x == "")) or ((x == "SOME_FILE_NAME") and (y == "")) or ((y == "SOME_FILE_NAME") and (x == ""))): return False # Handle wildcard matching. wildcards = ["CURRENT_FILE_NAME", "SOME_FILE_NAME", "**MATCH ANY**"] if ((x in wildcards) or (y in wildcards)): return True # Easy case first. # pylint: disable=unidiomatic-typecheck if (type(x) == type(y)): return x == y # Booleans and ints can be directly compared. if ((isinstance(x, bool) and (isinstance(y, int))) or (isinstance(y, bool) and (isinstance(x, int)))): return x == y # Punt. Just convert things to strings and hope for the best. return str(x) == str(y)
def _parse_node_to_coords(element): """ Parse coordinates from a node in the overpass response. The coords are only used to create LineStrings and Polygons. Parameters ---------- element : dict element type "node" from overpass response JSON Returns ------- coords : dict dict of latitude/longitude coordinates """ # return the coordinate of a single node element coords = {"lat": element["lat"], "lon": element["lon"]} return coords
def create_reference(obj) -> str: """Return a ``module:varname`` reference to the given object.""" obj_name = obj.__qualname__ if '<locals>' in obj_name: raise ValueError('cannot create a reproducible reference to a nested function') return '%s:%s' % (obj.__module__, obj_name)
def _getColor(color, ref): """ _getColor(color, reference) Get the real color as a 4 element tuple, using the reference color if the given color is a scalar. """ if isinstance(color, float): return (color*ref[0], color*ref[1], color*ref[2], ref[3]) else: return color
def get_doc_changes(original, new, base_prefix=()): """ Return a list of changed fields between two dict structures. :type original: dict :rtype: list[(tuple, object, object)] >>> get_doc_changes({}, {}) [] >>> get_doc_changes({'a': 1}, {'a': 1}) [] >>> get_doc_changes({'a': {'b': 1}}, {'a': {'b': 1}}) [] >>> get_doc_changes({'a': 1}, {'a': 2}) [(('a',), 1, 2)] >>> get_doc_changes({'a': 1}, {'a': 2}) [(('a',), 1, 2)] >>> get_doc_changes({'a': 1}, {'b': 1}) [(('a',), 1, None), (('b',), None, 1)] >>> get_doc_changes({'a': {'b': 1}}, {'a': {'b': 2}}) [(('a', 'b'), 1, 2)] >>> get_doc_changes({}, {'b': 1}) [(('b',), None, 1)] >>> get_doc_changes({}, None, base_prefix=('a',)) [(('a',), {}, None)] """ changed_fields = [] if original == new: return changed_fields if not isinstance(new, dict): changed_fields.append((base_prefix, original, new)) return changed_fields all_keys = set(original.keys()).union(new.keys()) for key in all_keys: key_prefix = base_prefix + (key,) original_val = original.get(key) new_val = new.get(key) if original_val == new_val: continue if isinstance(original_val, dict): changed_fields.extend(get_doc_changes(original_val, new_val, key_prefix)) else: changed_fields.append( (key_prefix, original_val, new_val) ) return sorted(changed_fields, key=lambda a: a[0])
def _merge_general_metadata(meta_list): """ Combine list of "general" metadata dicts into a single dict """ if not meta_list: return {} meta = None for md in meta_list: if meta: meta["data_paths"] += md["data_paths"] meta["file_stats"] += md["file_stats"] else: meta = md.copy() return meta
def calculate_average_price_sl_percentage_short(sl_price, average_price): """Calculate the SL percentage based on the average price for a short deal""" return round( 100.0 - ((sl_price / average_price) * 100.0), 2 )
def err(ranking, max=10, max_grade=2): """ todo """ if max is None: max = len(ranking) ranking = ranking[:min(len(ranking), max)] ranking = map(float, ranking) result = 0.0 prob_step_down = 1.0 for rank, rel in enumerate(ranking): rank += 1 utility = (pow(2, rel) - 1) / pow(2, max_grade) result += prob_step_down * utility / rank prob_step_down *= (1 - utility) return result
def is_subset(subset, settt): """ Determines if 'subset' is a subset of 'set' :param subset: The subset :param set: The set :return: True if 'subset' is a subset of 'set, False otherwise """ cpos = 0 for c in settt: """ too slow if c > subset[cpos]: return False """ cpos += c == subset[cpos] # Found the char if cpos == len(subset): return True return False
def capitalize_header(key): """ Returns a capitalized version of the header line such as 'content-type' -> 'Content-Type'. """ return "-".join([ item if item[0].isupper() else item[0].upper() + item[1:] for item in key.split("-") ])
def extract_bibtex_key(system_control_numbers): """Get bibtex key from 'system_control_numbers' field Unfortunately, this seems to be the only way to get the bibtex key. I have seen suggestions around the github issues for inspirehep/invenio that this should always be present """ if isinstance(system_control_numbers, dict): system_control_numbers = [system_control_numbers,] bibtex_keys = [number.get('value', '') for number in system_control_numbers if number.get('institute', '') in ['INSPIRETeX', 'SPIRESTeX']] bibtex_keys = [key for key in bibtex_keys if key] if not bibtex_keys: return '' return bibtex_keys[0]
def add_the_commas_diy(i): """ Most complex method using my own implementation. :param i: Integer value to format. :return: Value with thousands separated with commas. """ number = str(i) # Simple case 1: no commas required if len(number) < 4: return number decimal_part = False is_negative = False # Special case 2: negative values if number[0] is '-': is_negative = True number = number[1:] # Special case 3: decimal values if number.find('.') is not -1: decimal_part = number.split('.')[1] number = number.split('.')[0] number_list = list(number) good_number = [] # Find number of leading digits before first comma first_comma = len(number) % 3 if first_comma is 0: first_comma = 3 # Last comma always has three digits after last_comma = len(number) - 3 commas = list(range(first_comma, last_comma + 1, 3)) position = 0 while position is not len(number_list): if position in commas: good_number.append(',') good_number.append(number_list[position]) position += 1 good_number = ''.join(good_number) if decimal_part is not False: good_number = '.'.join([good_number, decimal_part]) if is_negative is True: good_number = ''.join(['-', good_number]) return good_number
def parse_paid(value): """ Parses a specific portuguese word "Sim"(=Yes) to a bool. """ if value == 'Sim': return True else: return False
def extender (l, tail) : """Return list `l` extended by `tail` (`l` is changed in place!) >>> extender ([1, 2, 3], (4, 5)) [1, 2, 3, 4, 5] >>> extender ([], [1]) [1] """ xtend = l.extend if isinstance (tail, (list, tuple)) else l.append xtend (tail) return l
def matches(expanded_solution, constraints): """ solution is a tuple of spaces, the output of solve1 constraints is a tuple of values from 1, 0 and -1, that mean: 0 -> OFF 1 -> ON -1 -> not constrained """ for s, c in zip(expanded_solution, constraints): if c == -1: continue if c != s: return False return True
def check_index(index, valid_min, valid_max): """Check that an index doesn't exceed the valid bounds.""" if index >= valid_max: index = index - valid_max if index < valid_min: index = index + valid_max return index
def get_trader_scada_ramp_rate(trader_id, ramp_rates): """ Extract SCADA ramp rate for a given trader. If the SCADA ramp rate is 0 or missing return None. """ if (trader_id in ramp_rates.keys()) and (ramp_rates[trader_id] > 0): return ramp_rates[trader_id] else: return None
def _split_channels(num_chan, num_groups): """Split range(num_chan) in num_groups intervals. The first one is larger if num_chan is not a multiple of num_groups""" split = [num_chan // num_groups for _ in range(num_groups)] # add the remaining channels to the first group split[0] += num_chan - sum(split) return split
def song_text(string_num=3, la_num=3, last_symbol=1): """ The method generates strings which consist of 1 same word with separator "-". Takes 3 params: :param string_num: - number of lines :param la_num: - number of words :param last_symbol: - the last symbol for the last line. 1 == !, 0 == . :var word: - contains word you want to use while generate your strings :return: string """ word = "la" song_string = [word for i in range(la_num)] counter = 0 res = '' for i in range(string_num): counter += 1 if counter == string_num and last_symbol==1: res += "-".join(song_string)+"!" elif counter == string_num and last_symbol==0: res += "-".join(song_string) + "." else: res += "-".join(song_string) return res
def stirling(n_items, k_sets): """ Takes as its inputs two positive integers of which the first is the number of items and the second is the number of sets into which those items will be split. Returns total number of k_sets created from n_items. """ if n_items < k_sets: return 0 if k_sets == 1 or k_sets == n_items: return 1 return k_sets * stirling(n_items-1, k_sets) + stirling(n_items-1, k_sets-1)
def str2hex(s): """Convert string to hex-encoded string.""" res = ["'"] for c in s: res.append("\\x%02x" % ord(c)) res.append("'") return "".join(res)
def _serialize_rules(rules): """Serialize all the Rule object as string.""" result = [(rule_name, str(rule)) for rule_name, rule in rules.items()] return sorted(result, key=lambda rule: rule[0])
def _parse_auth(auth): """ Parse auth string and return dict. >>> _parse_auth('login:user,password:secret') {'login': 'user', 'password': 'secret'} >>> _parse_auth('name:user, token:top:secret') {'name': 'user', 'token': 'top:secret'} """ if not auth: return None items = auth.split(',') return dict(i.strip().split(':', 1) for i in items)
def find_job_debug_data(job_name, tasks): """Find the stack analysis debug data for given job.""" for task in tasks: if task["task_name"] == job_name: return task return None
def pre_process(line): """ Return a ``line`` cleaned from comments markers and space. """ if '#' in line: line = line[:line.index('#')] return line.strip()
def pathjoin(*args): """Join a /-delimited path. """ return "/".join([p for p in args if p])
def complete_sulci_name(sulci_list, side): """Function gathering sulci and side to obtain full name of sulci It reads suli prefixes from a list and adds a suffix depending on a given side. Args: sulci_list: a list of sulci side: a string corresponding to the hemisphere, whether 'L' or 'R' Returns: full_sulci_list: a list with full sulci names, ie with side included """ if any("right" in s for s in sulci_list) or any("left" in s for s in sulci_list): return sulci_list else: side = 'right' if side=='R' else 'left' suffix = '_' + side if isinstance(sulci_list, list): full_sulci_list = [] for sulcus in sulci_list: sulcus += suffix full_sulci_list.append(sulcus) return full_sulci_list else: return sulci_list + suffix
def _list_to_dict(artifact_list): """Returns a dict of artifact name to version.""" tuples = [tuple(item.rsplit(":", 1)) for item in artifact_list] return {name: version for (name, version) in tuples}
def flatten(List): """ Make a list of nested lists a simple list Doesn't seem to work or else I don't recall what it should do. """ if type(List[0]) == list: newlist = sum(List, []) else: newlist = List return newlist
def get_multiples(n): """Returns 2,3,4,5,6x multiples on n""" return [i*n for i in range(2, 7)]
def contains_digit(s): """Find all files that contain a number and store their patterns. """ isdigit = str.isdigit return any(map(isdigit, s))
def clamp(num, smallest, largest): """ Propose a number and a range (smallest, largest) to receive a number that is clamped within that range. :param num: a number to propose :param smallest: minimum of range :param largest: maximum of range :return: number in range """ return max(smallest, min(num, largest))
def DFS_cycle(graph, start, path = []): """ Detect Cycles with a Depth First Search """ # append to path path = path + [start] # graph start for node in graph[start]: # check if node != path init if node not in path: # return true after termination case if DFS_cycle(graph, node, path): return True # return true before termination case elif node == path[0]: return True
def relative_viewname(viewname, resolver): """ Helper for building a fully namespaced `viewname` given a URL resolver. (This is typically from the current request.) """ if resolver is None: return viewname return ':'.join( [_f for _f in [ resolver.app_name, resolver.namespace, viewname ] if _f] )
def is_scalar(vect_array): """Test if a "fully-vectorized" array represents a scalar. Parameters ---------- vect_array : array-like Array to be tested. Returns ------- is_scalar : bool Boolean determining if vect_array is a fully-vectorized scalar. """ if isinstance(vect_array, tuple): return False if isinstance(vect_array, list): return False has_ndim_2 = vect_array.ndim == 2 if not has_ndim_2: return False has_singleton_dim_1 = vect_array.shape[1] == 1 return has_singleton_dim_1
def mpd_duration(timespec): """ return duration string. """ try: timespec = int(timespec) except ValueError: return 'unknown' timestr = '' m = 60 h = m * 60 d = h * 24 w = d * 7 if timespec > w: w, timespec = divmod(timespec, w) timestr = timestr + '%02dw' % w if timespec > d: d, timespec = divmod(timespec, d) timestr = timestr + '%02dd' % d if timespec > h: h, timespec = divmod(timespec, h) timestr = timestr + '%02dh' % h if timespec > m: m, timespec = divmod(timespec, m) timestr = timestr + '%02dm' % m return timestr + '%02ds' % timespec
def mm2ns(distance, velocity): """Return the time (ns) from distance (mm) and signal velcity (m/ns). Attributes: distance <float>: travel distance (ns) of radio signal; velocity <float>: travel velocity (m/ns) of radio signal. """ d, v = distance / 1000, velocity time = d / v return(time)
def inch_to_canvas(value,x): """returns the cm value in the correct needed value for canvas""" value = value*72 if(x == False): value = 11.7*72-value return value
def _process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (Dictionary) raw structured data to process Returns: Dictionary. Structured data to conform to the schema. """ # # process the data here # rebuild output for added semantic information # use helper functions in jc.utils for int, float, bool conversions and timestamps # return proc_data
def kronecker_delta(i, j): """ kronecker_delta Delta function: \delta_{i, j} Parameters ---------- i: tensor index j: tensor index Returns ------- 1 if i==j, 0 otherwise """ if i == j: return 1 else: return 0
def from_text(text): """Convert text into a Name object""" if not text.endswith('.'): text += '.' return text
def sort_probs(probs_list): """Sort probabilities list for consistent comparison.""" return sorted(probs_list, key=lambda x: x[1])
def GetNestedAttr(content, nested_attr, default=None): """Get the (nested) attribuite from content. Get the (nested) attribute from the content dict. E.X. content is {key1: {key2: {key3: value3}}, key4: value4} nested_attr = [key1] gets {key2: value2, {key3: value3}} nested_attr = [key1, key2] gets {key3: value3} nested_attr = [key1, key2, key3] gets value3 nested_attr = [key5] gets the default value. Args: content: A dict of (nested) attributes. nested_attr: String list presenting the (nested) attribute to get. default: Default value to return if the attribute doesn't exist. Returns: The corresponding value if the attribute exists; else, default. """ assert isinstance(nested_attr, list), 'nested_attr must be a list.' if content is None: return default assert isinstance(content, dict), 'content must be a dict.' value = content for attr in nested_attr: assert isinstance(attr, str), 'attribute name must be a string.' if not isinstance(value, dict): return default value = value.get(attr, default) return value
def fibonacci(n: int) -> int: """Compute the N-th fibonacci number.""" if n in (0, 1): return 1 return fibonacci(n - 1) + fibonacci(n - 2)
def match_piecewise(candidates: set, symbol: str, sep: str='::') -> set: """ Match the requested symbol reverse piecewise (split on ``::``) against the candidates. This allows you to under-specify the base namespace so that ``"MyClass"`` can match ``my_namespace::MyClass`` Args: candidates: set of possible matches for symbol symbol: the symbol to match against sep: the separator between identifier elements Returns: set of matches """ piecewise_list = set() for item in candidates: split_symbol = symbol.split(sep) split_item = item.split(sep) split_symbol.reverse() split_item.reverse() min_length = len(split_symbol) split_item = split_item[:min_length] if split_symbol == split_item: piecewise_list.add(item) return piecewise_list
def get_names( keys): """ Transforms full classifier strings into names""" names = [] # shorten keys to names for k in keys: if k.startswith( "OneVsRestClassifier(estimator="): k = k[30:] if k.find("(") > 0: k = k[:k.find("(")] if k.endswith( "Classifier"): k = k[:-10] names.append( k) return names
def dequote(s): """ If a string has single or double quotes around it, remove them. Make sure the pair of quotes match. If a matching pair of quotes is not found, return the string unchanged. """ if (s[0] == s[-1]) and s.startswith(("'", '"')): return s[1:-1] return s
def heap_parent(d, i): """Parent in d-ary heap of element at position i in list.""" return (i-1)//d
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.append(options[i]) return { "contentType": "ImageResponseCard", "imageResponseCard": { "title": title, "subtitle": subtitle, "imageUrl": "string", "buttons": buttons } }
def sv_length(pos, end, chrom, end_chrom, svlen=None): """Return the length of a structural variant Args: pos(int) end(int) chrom(str) end_chrom(str) svlen(int) Returns: length(int) """ if chrom != end_chrom: return int(10e10) if svlen: return abs(int(svlen)) # Some software does not give a length but they give END if not end: return -1 if end == pos: return -1 return end - pos
def parse_list(list_str): """Parse comma-separated list""" if list_str.strip(): return [t.strip() for t in list_str.split(',') if t.strip()] else: return []
def mock_input_default(prompt, choices="", clear=False): """Enter default choice at prompts""" res = [x for x in choices if x.isupper()] return res[0] if res else ""
def _GetModuleOrNone(module_name): """Returns a module if it exists or None.""" module = None if module_name: try: module = __import__(module_name) except ImportError: pass else: for name in module_name.split('.')[1:]: module = getattr(module, name) return module
def rayleigh_coefficients(zeta, omega_1, omega_2): """ Compute the coefficients for rayleigh damping such, that the modal damping for the given two eigenfrequencies is zeta. Parameters ---------- zeta : float modal damping for modes 1 and 2 omega_1 : float first eigenfrequency in [rad/s] omega_2 : float second eigenfrequency in [rad/s] Returns ------- alpha : float rayleigh damping coefficient for the mass matrix beta : float rayleigh damping for the stiffness matrix """ beta = 2*zeta/(omega_1 + omega_2) alpha = omega_1*omega_2*beta return alpha, beta
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ if len(input_list) == 0: return [] if len(input_list) == 1: return input_list index = 0 # skip 0 at the begin, they are already in-place while input_list[index] == 0 and index < len(input_list) -1: index += 1 while index < len(input_list) -1: if not (0 and 1) in input_list[index:]: index = len(input_list) -1 if input_list[index] == 0: input_list = [0] + input_list[:index] + input_list[index +1:] if input_list[index] == 2: input_list = input_list[:index] + input_list[index +1:] + [2] if input_list[index] == 1: index += 1 return input_list
def round_down(i: float, k: int) -> int: """Round down an integer.""" return int(k * (i // k))
def iShiftRows(state): """Performs inverse shiftRows operation on the state.""" # put your code here newstate = bytearray(16) newstate[0] = state[0] newstate[4] = state[4] newstate[8] = state[8] newstate[12] = state[12] newstate[1] = state[13] newstate[5] = state[1] newstate[9] = state[5] newstate[13] = state[9] newstate[2] = state[10] newstate[6] = state[14] newstate[10] = state[2] newstate[14] = state[6] newstate[3] = state[7] newstate[7] = state[11] newstate[11] = state[15] newstate[15] = state[3] return newstate
def rgb_to_int(x): """Converts an rgb/rgba tuple into an int""" r = x[0] g = x[1] b = x[2] return (r * 0x10000) + (g * 0x100) + b
def FormatNameToPython(i): """ Transform a (method) name into a form which can be used as a python attribute example:: >>> FormatNameToPython('<clinit>') 'clinit' :param i: name to transform :rtype: str """ i = i.replace("<", "") i = i.replace(">", "") i = i.replace("$", "_") return i
def cleanGender(x): """ This is a helper funciton that will help cleanup the gender variable. """ if x in ['female', 'mostly_female']: return 'female' if x in ['male', 'mostly_male']: return 'male' if x in ['couple'] : return 'couple' else: return 'unknownGender'
def parse_header(line): """Parse output of tcpdump of pcap file, extract: time date ethernet_type protocol source ip source port (if it exists) destination ip destination port (if it exists) length of the data """ ret_dict = {} h = line.split() date = h[0] time = h[1] ret_dict['raw_header'] = line ret_dict['date'] = date ret_dict['time'] = time src_a = h[3].split(".", 3) if "." in src_a[-1]: port_a = src_a[-1].split('.') ret_dict['src_port'] = port_a[-1] ret_dict['src_ip'] = ".".join(h[3].split('.')[:-1]) else: ret_dict['src_ip'] = h[3] dest_a = h[5].split(".", 3) if "." in dest_a[-1]: port_a = dest_a[-1].split('.') ret_dict['dest_port'] = port_a[-1].split(":")[0] ret_dict['dest_ip'] = ".".join(h[5].split('.')[:-1]) else: ret_dict['dest_ip'] = h[5].split(":")[0] ret_dict['protocol'] = h[6] ret_dict['ethernet_type'] = h[2] try: ret_dict['length'] = int(h[-1]) except Exception as e: print("failed to get length because: {0}, setting it to 0".format(str(e))) ret_dict['length'] = 0 if h[2] == 'IP': #do something meaningful pass else: pass #do something else ret_dict['tool'] = "tcpdump_hex_parser" return ret_dict
def removePOS(sentence): """ Removes the part of speech from a string sentence. """ cleansentence = [] for word in sentence.split(): cleansentence.append(word.split('/')[0]) return ' '.join(cleansentence)
def stringify_tuple(tup, sep=","): """ Takes in a tuple and concatante its elements as string seperated by a given char. Parameters ---------- tup: tuple Tuple to make string sep: str, default "," Seperator between tuple elements in the concataned string """ return str(sep.join([str(e) for e in tup]))
def NameAndAttribute(line): """ Split name and attribute. :param line: DOT file name :return: name string and attribute string """ split_index = line.index("[") name = line[:split_index] attr = line[split_index:] return name, attr
def merge_sort(array): """ ### Merge sort Implementation of one of the most powerful sorting algorithms algorithms.\n Return a sorted array, """ def merge(L, R): res = [] left_ind = right_ind = 0 while left_ind < len(L) and right_ind < len(R): if L[left_ind] < R[right_ind]: res.append(L[left_ind]) left_ind += 1 elif L[left_ind] > R[right_ind]: res.append(R[right_ind]) right_ind += 1 else: res.append(R[right_ind]) res.append(L[right_ind]) left_ind += 1 right_ind += 1 res.extend(L[left_ind:]) res.extend(R[right_ind:]) return res length = len(array) if length <= 1: return array middle_ind = int(length/2) right = merge_sort(array[middle_ind:]) left = merge_sort(array[:middle_ind]) return merge(right, left)
def sched_exp(start, end, pos): """Exponential scheduler.""" return start * (end / start) ** pos
def make_list(unused_s, unused_l, toks): """Makes a list out of a token tuple holding a list.""" result = [] for item in toks: result.append(item.asList()) return result
def bterm(f,p,pv0,e,B,R,eta): """ For the cubic equation for nu in the four-variable model with CRISPR, this is the coefficient of nu^2 """ return -(e*f*pv0*(pv0*(f + R) + p*(1 + f*(-1 + B*(-eta + (1 + e + eta)*pv0)) - R + B*(eta + pv0*(-1 - e - eta + 2*R)))))
def get_value_from_tuple_list(list_of_tuples, search_key, value_index): """ Find "value" from list of tuples by using the other value in tuple as a search key and other as a returned value :param list_of_tuples: tuples to be searched :param search_key: search key used to find right tuple :param value_index: Index telling which side of tuple is returned and which is used as a key :return: Value from either side of tuple """ for i, v in enumerate(list_of_tuples): if v[value_index ^ 1] == search_key: return v[value_index]
def ping(host): """ Returns True if host responds to a ping request """ import subprocess, platform, os # Ping parameters as function of OS ping_str = "-n1" if platform.system().lower()=="windows" else "-c1" args = ["ping", ping_str, host] # Ping return subprocess.call(args, stdout=open(os.devnull, 'wb')) == 0
def html_title(title): """Generates an HTML-formatted title. """ return '<center><h1>%s</h1></center>' % (title)
def constrain(value, min_value, max_value): """ Constrains the `value` to the specified range `[min_value, max_value]` Parameters ---------- `value` : The value to be constrained `min_value` : The lower limit of range (inclusive) `max_value` : The upper limit of range (inclusive) Returns ------- `min_value` : if `value` is less than `min_value` `max_value` : if `value` is greater than `max_value` `value` : otherwise Examples -------- >>> constrain(10, 20, 40) 20 >>> constrain(30, 20, 40) 30 >>> constrain(50, 20, 40) 40 """ return min(max(value, min_value), max_value)
def b36encode(number: int) -> str: """Convert the number to base36.""" alphabet, base36 = ["0123456789abcdefghijklmnopqrstuvwxyz", ""] while number: number, i = divmod(number, 36) base36 = alphabet[i] + base36 return base36 or alphabet[0]
def is_serialised(serialised): """ Detects whether some bytes represent a real number. :param serialised: A ``bytes`` object which must be identified as being a real number or not. :return: ``True`` if the ``bytes`` likely represent a real number, or ``False`` if it does not. """ #This works with a simple finite state automaton in a linear fashion: #initial -> integer_start -> integer -> fractional_start -> fractional -> exponent_initial -> exponent_start -> exponent #Each state represents what character is expected next. #The FSA solution is not pretty, but it's the only way it could be made to work with a possibly infinite byte stream. state = "initial" for byte in serialised: if state == "initial": #Initial state: May be a negative sign or integer_start. if byte == b"-"[0]: state = "integer_start" elif byte >= b"0"[0] and byte <= b"9"[0]: state = "integer" else: return False elif state == "integer_start": #First character of integer. An integer must have at least 1 digit. if byte >= b"0"[0] and byte <= b"9"[0]: state = "integer" else: return False elif state == "integer": #Consecutive characters of the integer. May be a period, indicating start of fractional, or an E, indicating start of exponent. if byte >= b"0"[0] and byte <= b"9"[0]: pass #Still integer. elif byte == b"."[0]: state = "fractional_start" elif byte == b"e"[0] or byte == b"E"[0]: state = "exponent_initial" else: return False elif state == "fractional_start": #Start of fractional part. if byte >= b"0"[0] and byte <= b"9"[0]: state = "fractional" else: return False elif state == "fractional": #Continuation of factional part. May be an E, indicating start of exponent. if byte >= b"0"[0] and byte <= b"9"[0]: pass #Still fractional part. elif byte == b"e"[0] or byte == b"E"[0]: state = "exponent_initial" else: return False elif state == "exponent_initial": #Initial state of exponent, may be negative or a number. if byte == b"-"[0] or byte == b"+"[0]: state = "exponent_start" elif byte >= b"0"[0] and byte <= b"9"[0]: state = "exponent" else: return False elif state == "exponent_start": #First character of an exponent. Not an end state. if byte >= b"0"[0] and byte <= b"9"[0]: state = "exponent" else: return False elif state == "exponent": #Continuation of an exponent. if byte >= b"0"[0] and byte <= b"9"[0]: pass #Still exponent. else: return False return state == "fractional" or state == "exponent"
def compare_fingerprints(fp1, fp2): """ compute the 'distance' between two fingerprints. it consists of the sum of the distance of each frame of fp1 from the frame at the same index in fp2. since each frame is a sorted list of frequencies, the distance between two frames is the sum of the |difference| of the values at the same indices in both frames :param fp1: a fingerprint (list) :param fp2: a fingerprint (list) :return: the difference between fp1 fp2 (int) """ s = 0 x = min(len(fp1), len(fp2)) y = min(len(fp1[0]), len(fp2[0])) for i in range(x): t1 = fp1[i] t2 = fp2[i] for j in range(y): s += abs(t1[j] - t2[j]) return s
def upper(_, text): """ Convert all letters in content to uppercase. """ return text.upper()
def cubic_bezier_point(p0, p1, p2, p3, t): """ https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves """ a = (1.0 - t)**3 b = 3.0 * t * (1.0 - t)**2 c = 3.0 * t**2 * (1.0 - t) d = t**3 return { "x": a * p0["x"] + b * p1["x"] + c * p2["x"] + d * p3["x"], "y": a * p0["y"] + b * p1["y"] + c * p2["y"] + d * p3["y"], }
def dictitems(d): """ A pickleable version of dict.items >>> dictitems({'x': 1}) [('x', 1)] """ return list(d.items())
def hashtable(l, tablesize): """ http://interactivepython.org/courselib/static/pythonds/SortSearch/Hashing.html hash table, linear probing implementation """ ht = {} for i in range(tablesize): ht[i] = None for i, v in enumerate(l): idx = v % tablesize while ht[idx]!=None: if idx == tablesize -1: idx == 0 else: idx+=1 ht[idx] = v return ht
def _is_class(s): """Imports from a class/object like import DefaultJsonProtocol._""" return s.startswith('import ') and len(s) > 7 and s[7].isupper()
def number_equal(element, value, score): """Check if element equals config value Args: element (float) : Usually vcf record value (float) : Config value score (integer) : config score Return: Float: Score """ if element == value: return score
def check_ch(row: str) -> bool: """ This function will check if the input is legal or illegal. """ row_lst = row.lower().split() ans = True if len(row_lst) == 4: for i in range(4): if row_lst[i].isalpha() is False or len(row_lst[i]) != 1: ans = False else: ans = False return ans
def pg_connect_bits(meta): """Turn the url into connection bits.""" bits = [] if meta['username']: bits.extend(['-U', meta['username']]) if meta['hostname']: bits.extend(['-h', meta['hostname']]) if meta['port']: bits.extend(['-p', str(meta['port'])]) return bits
def get_grant_key(grant_statement): """ Create the key from the grant statement. The key will be used as the dictionnary key. :param grant_statement: The grant statement :return: The key """ splitted_statement = grant_statement.split() grant_privilege = splitted_statement[1] if "." in splitted_statement[3]: grant_table = splitted_statement[3].split('.')[1] else: grant_table = splitted_statement[3] return grant_privilege + "_" + grant_table
def str_format(s, *args, **kwargs): """Return a formatted version of S, using substitutions from args and kwargs. (Roughly matches the functionality of str.format but ensures compatibility with Python 2.5) """ args = list(args) x = 0 while x < len(s): # Skip non-start token characters if s[x] != '{': x += 1 continue end_pos = s.find('}', x) # If end character can't be found, move to next character if end_pos == -1: x += 1 continue name = s[x + 1:end_pos] # Ensure token name is alpha numeric if not name.isalnum(): x += 1 continue # Try find value for token value = args.pop(0) if args else kwargs.get(name) if value: value = str(value) # Replace token with value s = s[:x] + value + s[end_pos + 1:] # Update current position x = x + len(value) - 1 x += 1 return s
def is_sns_event(event): """ Determine if the event we just received is an SNS event """ if "Records" in event: return True return False