content
stringlengths
42
6.51k
def set_pox_opts( components, info_level, logfile_opts, log_format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'): """Generate a string with custom pox options. :components: dot notation paths (eg: forwarding.l2_learning web.webcore --port=8888) :info_level: DEBUG, INFO, etc. :logfile_opts: path and other options (eg: file.log,w to overwrite each time) :returns: options string for ./pox.py command """ info_level = info_level.upper() pox_opts = '%s log.level --%s log --file=%s --format="%s" &' % ( components, info_level, logfile_opts, log_format) # print 'DEBUG:', opts return pox_opts
def mutate(mushroom, i): """ Randomly flips one bit in a mushroom bit string""" return mushroom ^ 1 << i
def slicer(s: str, slice_pos: int) -> tuple: """Return a tuple of strings which are the parm string cleaved at its parm slice position.""" return s[0:slice_pos], s[slice_pos:]
def get_codebook(ad_bits, codebook): """Returns the exhaustive codebooks for a given codeword length :param ad_bits: codewor length :type ad_bits: int :return: Codebook :rtype: list(str) """ return codebook[ad_bits-2]
def get_getmodel_cov_cmd( number_of_samples, gul_threshold, use_random_number_file, coverage_output, item_output, process_id, max_process_id, **kwargs): """ Gets the getmodel ktools command (version < 3.0.8) gulcalc coverage stream :param number_of_samples: The number of samples to run :type number_of_samples: int :param gul_threshold: The GUL threshold to use :type gul_threshold: float :param use_random_number_file: flag to use the random number file :type use_random_number_file: bool :param coverage_output: The coverage output :type coverage_output: str :param item_output: The item output :type item_output: str :return: The generated getmodel command """ cmd = 'eve {0} {1} | getmodel | gulcalc -S{2} -L{3}'.format( process_id, max_process_id, number_of_samples, gul_threshold) if use_random_number_file: cmd = '{} -r'.format(cmd) if coverage_output != '': cmd = '{} -c {}'.format(cmd, coverage_output) if item_output != '': cmd = '{} -i {}'.format(cmd, item_output) return cmd
def fst(l): """Returns the first item in any list Parameters --------- l : list the list we want to extract the first item from Returns ------- first item in list """ if isinstance(l, list): return fst(l[0]) else: return l
def rank_names(names): """ Given a list of tuples with ranking, male name and female return a list of male and female names with their ranking. :param names: the tuple with the data. :return: a list with names and its ranking """ names_rank = [] for i in range(len(names)): names_rank.append(names[i][1] + ' ' + names[i][0]) names_rank.append(names[i][2] + ' ' + names[i][0]) return names_rank
def merge_paths_and_videos(paths, videos): """Merge paths and videos, playback orders""" for i, path in enumerate(paths, 1): path["id"] = i path["videos"] = [] for video in videos: if path.get("PK") == video.get("PK"): _d = {} _d["uri"] = video.get("SK", None) _d["order"] = video.get("order", 0) path["videos"].append(_d) path["videos"].sort(key=lambda x: x["order"]) return paths
def sw_id_to_pos_index(id): """Switch ID (ex: 4 if SW4) to row/col""" if id < 1 or id > 33: raise Exception("Invalid index: {}".format(id)) # From here, we can calculate the row/col by mod operation col_offset = 0 if id > 18: col_offset = 3 id_0 = int(id) - 1 row = id_0 % 3 col = col_offset + id_0 // 3 return row, col
def tz_syntax(string): """ returns 'good' and clean reply if reply to adjust the current time zone is fine """ signs = ['+','-'] cond = all(len(s) <= 2 for s in string[1:].replace(',','.').split('.')) if string[0] in signs and cond == True or string == '0': return 'good', string.replace(',','.').strip() else: return None, None
def findDuplicates(nums): """ :type nums: List[int] :rtype: List[int] """ i = 0 repeat = [] for j in range(len(nums)): if nums[j] == j+1: continue temp = nums[j] nums[j] = 0 while temp != 0: if nums[temp-1] == temp: repeat.append(temp) temp = 0 break nums[temp-1], temp = temp, nums[temp-1] if j+1 == temp: nums[j] = temp return repeat
def isNestedInstance(obj, cl): """ Test for sub-classes types I could not find a universal test keywords -------- obj: object instance object to test cl: Class top level class to test returns ------- r: bool True if obj is indeed an instance or subclass instance of cl """ tree = [] for k in cl.__subclasses__(): tree += k.__subclasses__() tree += cl.__subclasses__() + [cl] return issubclass(obj.__class__, tuple(tree))
def f4(N): """Fragment for exercise.""" ct = 1 while N >= 2: ct = ct + 1 N = N ** 0.5 return ct
def hex_to_rgb(hex_colors,): """ """ res = [] for color in hex_colors: res.append([int(color[i:i+2], 16) for i in (1, 3, 5)]) return res
def uneven(value): """Returns the closest uneven value equal to or lower than provided""" if value == 0: newvalue = 1 else: newvalue = value -1 if value % 2 == 0 else value return newvalue
def echo(ctx, text, newline): """ Echo back arguments passed in. Strips extra whitespace. """ if not text: text = [ctx.obj['stdout']] joiner = ' ' if not newline else '\n' return joiner.join(text)
def format_timedelta(td): """ Format timedelta object nicely. Args: td: timedelta object """ if td is None: return '' hours, remainder = divmod(td.total_seconds(), 3600) minutes, seconds = divmod(remainder, 60) return '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
def hashcode(s): """Compute hash for a string, in uint32_t""" hash = 2166136261 for c in s.encode('utf8'): hash = ((hash ^ c) * 16777619) & 0xFFFFFFFF return hash
def format_milestone_class(issue_data): """Return the correct class for a milestone, depending on state.""" state = issue_data.get('state') milestone = issue_data.get('milestone') title = '' if state == 'closed': return 'closed' elif milestone: title = milestone.get('title') return title
def filter_out_none(**kwargs) -> dict: """Filters out all None values from parameters passed.""" for key in list(kwargs): if kwargs[key] is None: kwargs.pop(key) return kwargs
def parse_environment(env_string): """ Parse the output of 'env -0' into a dictionary. """ if isinstance(env_string, bytes): env_string = env_string.decode() return dict( item.split('=', 1) for item in env_string.rstrip('\0').split('\0') )
def write_lines(new_lines, lines, edit_index): """ Inserts new lines where specified :param new_lines: the new lines to be added :param lines: holds all the current lines of output html file :param edit_index: the index to insert new lines :return: new contents of output html file """ lines[edit_index:edit_index] = new_lines edit_index += len(new_lines) return lines, edit_index
def normalize_directory_path(path): """Normalizes a directory path.""" return path.rstrip('/')
def strict_between(q, qmin, qmax): """ >>> strict_between(2, 1, 3) True >>> strict_between(2, 3, 1) True >>> strict_between(4, 1, 3) False >>> strict_between(4, 3, 1) False >>> strict_between(0, 1, 3) False >>> strict_between(0, 1, 3) False >>> strict_between(1, 1, 3) False >>> strict_between(3, 1, 3) False """ if qmin > qmax: qmin, qmax = qmax, qmin return qmin < q and q < qmax
def checkMultipleOptions(content): """ Print list of links for available pages for a search content = list of html elements outputs a list of lists """ paragraphs = "" paragraphs += "<p>There were multiple things found for that item</p>" for item in content: #Get the lists of links provided by the page if item.find('<ul>') > -1 and item.find('class="toc"') == -1: paragraphs += str(item) return paragraphs
def _search(name, obj): """Breadth-first search for name in the JSON response and return value.""" q = [] q.append(obj) while q: obj = q.pop(0) if hasattr(obj, '__iter__'): isdict = type(obj) is dict if isdict and name in obj: return obj[name] for k in obj: q.append(obj[k] if isdict else k) else: return None
def check_if_already_found(key, result): """ checks if data element exists in result dict and if so, if the value is not None :param key: key from result dict :type key: basestring :param result: dictionary of results :return: boolean """ if key not in result.keys(): return False elif result[key] is None: return False else: return True
def get_category(raw_outputs, threshold): """multi class""" # in future, when list: result = [1 if p > threshold else 0 for p in raw_outputs[0]] pred_dict_m = {2: 'Animals', 3: 'Environment', 1: 'People', 4: 'Politics', 5: 'Products & Services'} list_vals = list(raw_outputs[0]) max_val = max(list_vals) if max_val > threshold: k = list_vals.index(max_val) + 1 cat_id = k print('category is', pred_dict_m[k]) else: cat_id = None return cat_id
def is_safe(value: str) -> bool: """Evaluate if the given string is a fractional number safe for eval()""" return len(value) <= 10 and all(c in "0123456789./ " for c in set(value))
def convert_dict_key_type(dict, type): """Convert keys in dictionary to ints (loading json loads keys as strs)""" return {type(k): v for k, v in dict.items()}
def use_gpu(opt): """ Creates a boolean if gpu used """ return (hasattr(opt, "gpu_ranks") and len(opt.gpu_ranks) > 0) or ( hasattr(opt, "gpu") and opt.gpu > -1 )
def str2bytes(string): """Converts '...' string into b'...' string. On PY2 they are equivalent. On PY3 its utf8 encoded.""" return string.encode("utf8")
def suffix(pattern): """ return every symbol in pattern except the first """ if len(pattern) == 1: return "" Sufx = pattern[1:] return Sufx
def heuristic(network, node, goal, dist_func): """ Heuristic function for estimating distance from specified node to goal node. Args: network (object): Networkx representation of the network node (int): Node for which to compute the heuristic goal (int): Goal node dist_func (function): Function used to compute distance between two nodes. Returns: (float): Computed heuristic """ # Compute distance from node to goal. return dist_func(node, goal)
def maskStats(wins, last_win, mask, maxLen): """ return a three-element list with the first element being the total proportion of the window that is masked, the second element being a list of masked positions that are relative to the windown start=0 and the window end = window length, and the third being the last window before breaking to expidite the next loop """ chrom = wins[0].split(":")[0] a = wins[1] L = wins[2] b = a + L prop = [0.0,[],0] try: for i in range(last_win, len(mask[chrom])): x, y = mask[chrom][i][0], mask[chrom][i][1] if y < a: continue if b < x: return prop else: # i.e. [a--b] and [x--y] overlap if a >= x and b <= y: return [1.0, [[0,maxLen]], i] elif a >= x and b > y: win_prop = (y-a)/float(b-a) prop[0] += win_prop prop[1].append([0,int(win_prop * maxLen)]) prop[2] = i elif b <= y and a < x: win_prop = (b-x)/float(b-a) prop[0] += win_prop prop[1].append([int((1-win_prop)*maxLen),maxLen]) prop[2] = i else: win_prop = (y-x)/float(b-a) prop[0] += win_prop prop[1].append([int(((x-a)/float(b-a))*maxLen), int(((y-a)/float(b-a))*maxLen)]) prop[2] = i return prop except KeyError: return prop
def splitdrive(p): """Split a pathname into drive and path. On Posix, drive is always empty.""" return ( '', p)
def table(line): """ Converting Org table to Md format :param line: :return: """ if line[:2] == '|-': line = line.replace('+', '|') # format of the grid line return line
def _is_uint(candidate): """Returns whether a value is an unsigned integer.""" return isinstance(candidate, int) and candidate >= 0
def hyphenate(text: str) -> str: """ Converts underscores to hyphens. Python functions use underscores while Argo uses hyphens for Argo template names by convention. """ return text.replace("_", "-")
def curvature(x, dfunc, d2func, *args, **kwargs): """ Curvature of function: `f''/(1+f'^2)^3/2` Parameters ---------- x : array_like Independent variable to evalute curvature dfunc : callable Function giving first derivative of function f: f', to be called `dfunc(x, *args, **kwargs)` d2func : callable Function giving second derivative of function f: f'', to be called `d2func(x, *args, **kwargs)` args : iterable Arguments passed to `dfunc` and `d2func` kwargs : dict Keyword arguments passed to `dfunc` and `d2func` Returns ------- float or ndarray Curvature of function f at `x` """ return ( d2func(x, *args, **kwargs) / (1. + dfunc(x, *args, **kwargs)**2)**1.5 )
def assort_values(d): """ Collect every values stored in dictionary, then return them as a set :param d: :return: """ values = set() for key in d.keys(): values |= set(d[key]) return values
def extract(input_data: str) -> tuple: """take input data and return the appropriate data structure""" sheet = set() folds = list() s_instr, f_instr = input_data.split('\n\n') for line in s_instr.split('\n'): sheet.add(tuple(map(int, line.split(',')))) for line in f_instr.split('\n'): equal_pos = line.index('=') folds.append((line[equal_pos-1], int(line[equal_pos+1:]))) return (sheet, folds)
def match_args(macro, args): """ Match args names with their values """ if 'args' not in macro: return {} return dict(list(zip(macro['args'], args)))
def get_content(filename): """ Gets the content of a file and returns it as a string Args: filename(str): Name of file to pull content from Returns: str: Content from file """ with open(filename, "r") as full_description: content = full_description.read() return content
def take_workers(dic, l = 10): """ return list of workers with more than l labels """ res = [] for (w, val) in dic.items(): if val[2] > l: res.append(w) return res
def pool_to_HW(shape, data_frmt): """ Convert from NHWC|NCHW => HW """ if len(shape) != 4: return shape # Not NHWC|NCHW, return as is if data_frmt == "NCHW": return [shape[2], shape[3]] return [shape[1], shape[2]]
def fast_modular_multiply(g, k, p): """Calculates the value g^k mod p Args: g: an integer representing the base k: an integer representing the exponent p: an integer (prime number) Returns: an integer representing g^k mod p """ u = g y = 1 while k != 0: if k % 2 == 1: y = y * u % p u = u * u % p k //= 2 return y
def dict_pivot(x_in, key): """ Before: >>>{"ts": 123, "A": "A", "B": "B", "sub": [{"C": 10}, {"C": 8}]} After: >>>[ >>> {'B': 'B', 'A': 'A', 'ts': 123, 'sub.C': 10}, >>> {'B': 'B', 'A': 'A', 'ts': 123, 'sub.C': 8} >>>] :param x_in: :param key: :return: """ return [dict([(k, v) for k, v in x_in.items() if k != key] + ch) for ch in [[(key + '.' + k, v) for k, v in y.items()] for y in x_in[key]]]
def mat_mul(mat1, mat2): """mat_mul: performs matrix multiplication Args: mat1: First matrix to multiplicate mat2: First matrix to multiplicate """ result = [] if len(mat1[0]) == len(mat2): for i in range(0, len(mat1)): temp = [] for j in range(0, len(mat2[0])): s = 0 for k in range(0, len(mat1[0])): s += mat1[i][k]*mat2[k][j] temp.append(s) result.append(temp) return result else: return None
def ex_timeout(): """Timeout error response in bytes.""" return b"SPAMD/1.5 79 EX_TIMEOUT\r\n\r\n"
def _deal_time_units(unit='s'): """Return scaling factor and string representation for unit multiplier modifications. Parameters ---------- unit : 'str' The unit to be used Returns ------- factor : float Factor the data is to be multiplied with, i.e. 1e-3 for milliseconds string : str String representation of the unit using LaTeX formatting. """ if unit == 's': factor = 1 string = 's' elif unit == 'ms': factor = 1 / 1e-3 string = 'ms' elif unit == 'mus': factor = 1 / 1e-6 string = r'$\mathrm{\mu s}$' elif unit == 'samples': factor = 1 string = 'samples' else: factor = 1 string = '' return factor, string
def down(pos): """ Move down """ return (pos[0], pos[1]-1)
def transform_response_if_html(text): """removes HTML code from skill response""" if text.find("<a", 0) > -1 and text.find("</a", 0) > -1: anchor_start = text.find("<a", 0) anchor_end = text.find("/a>", anchor_start) + 3 text_begin = text.find(">", 0) + 1 text_end = text.find("<", text_begin) href_begin = text.find("href= ", 0) + len("href= ") href_end = text.find(" ", href_begin) return text[0:anchor_start] + " " + text[text_begin:text_end] + " " + text[anchor_end:len(text)] + "\n" + text[href_begin:href_end] return text
def __num_digits(num: int): """internal helper to get the number of digits""" return len(str(num))
def minmax(*data): """Return the minimum and maximum of a series of array/list/tuples (or combination of these) You can combine list/tuples/arrays pretty much any combination is allowed :Example: .. doctest:: utils_minmax >>> s = range(7) >>> vcs.minmax(s) (0.0, 6.0) >>> vcs.minmax([s, s]) (0.0, 6.0) >>> vcs.minmax([[s, list(s) * 2], 4., [6., 7., s]],[ 5., -7., 8, (6., 1.)]) (-7.0, 8.0) :param data: A comma-separated list of lists/arrays/tuples :type data: `list`_ :returns: A tuple in the form (min, max) :rtype: `tuple`_ """ mx = -1.E77 mn = 1.E77 if len(data) == 1: data = data[0] global myfunction def myfunction(d, mx, mn): if d is None: return mx, mn from numpy.ma import maximum, minimum, count if isinstance(d, (int, float)): return maximum(d, mx), minimum(d, mn) try: if count(d) == 0: return mx, mn mx = float(maximum(mx, maximum.reduce(d, axis=None))) mn = float(minimum(mn, minimum.reduce(d, axis=None))) except BaseException: for i in d: mx, mn = myfunction(i, mx, mn) return mx, mn mx, mn = myfunction(data, mx, mn) if mn == 1.E77 and mx == -1.E77: mn, mx = 1.E20, 1.E20 return mn, mx
def message(instance_id, state, changed=0): """Create a message function to send info back to the original function.""" # Changed parameter determines what message to return if changed != 0: return_message = ("Instance {} is in {} state").format(instance_id, state) else: return_message = "No change for Instance# {}. Currently in {} state".format( instance_id, state) return return_message
def mean(num_list): """ Computes the mean of a list of numbers Parameters ---------- num_list: list of numbers Returns ------- res: float Mean of the numbers in num_list """ if not isinstance(num_list, list): raise TypeError('Invalid input %s Input must be a list' % (num_list)) if len(num_list) < 1: raise ZeroDivisionError('Cannot calculate mean of an empty list') res = sum([ float(x) for x in num_list]) / len(num_list) return res
def upper_first(text: str) -> str: """ Capitalizes the first letter of the text. >>> upper_first(text='some text') 'Some text' >>> upper_first(text='Some text') 'Some text' >>> upper_first(text='') '' >>> upper_first(text='_some text') '_some text' :param text: to be capitalized :return: text with the first letter capitalized """ if len(text) == 0: return '' return text[0].upper() + text[1:]
def icingByteFcnPRB(c): """Return probability value of icing pixel. Args: c (unicode): Unicode icing pixel. Returns: int: Value of probability portion of icing pixel. """ return ord(c) & 0x07
def ChangeExtension(file_name, old_str, new_str): """ Change the 'extension' at the end a file or directory to a new type. For example, change 'foo.pp' to 'foo.Data' Do this by substituting the last occurance of 'old_str' in the file name with 'new_str'. This is required because the file name may contain 'old_str' as a legal part of the name which is not at the end of the directory name. This assumes anything after the last '.' is the file extension. If there isn't a file extention, then just return the original name. @return string with file name & new extension """ pos = file_name.rfind(old_str) if pos == -1: # old_str not found, just return the file_name # return file_name return file_name[:pos] + new_str
def wrap_degrees(a, da): """ add da to a, but make sure that the resulting angle stays within the -180 to 180 range """ a2 = a + da while a2 > 180: a2 -= 360 while a2 < -180: a2 += 360 return a2
def filter_logs(ip, log_lines): """Filter the log lines to only those relevant to a particular IP address.""" # First, collect all tokens used by the IP address. tokens = [] for line in log_lines: if ip and ip in line: tok = line.split(', serving ', 1)[1] tokens.append(tok) # Filter to only lines which contain the IP address or one of its tokens. filtered = [] for line in log_lines: if ip in line: filtered.append(line) else: for tok in tokens: # We don't care about other bots which used the token. if tok in line and not 'Token requested by' in line: filtered.append(line) return filtered
def hex_str_to_bytes(s_in: str) -> bytes: """Used to convert a string from CLI to a bytearray object. .. warning:: This function assumes that the string consists of only hexadecimal characters. """ return bytes([int(i, 16) for i in s_in.split()])
def is_xmfa_blank_or_comment(x): """Checks if x is blank or an XMFA comment line.""" return (not x) or x.startswith("=") or x.isspace()
def sortListsInDict(data, reverse=False): """Recursively loops through a dictionary and sorts all lists. Args: data(dict): data dictionary reverse: (Default value = False) Returns: : dict -- sorted dictionary """ if isinstance(data, list): if not data: return data if isinstance(data[0], dict): if all('name' in elem for elem in data): return sorted(data, key=lambda k: k['name'], reverse=reverse) elif isinstance(data[0], str): return sorted(data, reverse=reverse) return data elif isinstance(data, dict): return {key: sortListsInDict(value, reverse) for key, value in data.items()} else: # any other type, such as string return data
def _str2inttuple(s): """parse string as tuple of integers""" return tuple([int(v) for v in s.split('(',1)[1].split(')',1)[0].split(',')])
def strtobool(val): """ This function was borrowed from distutils.utils. While distutils is part of stdlib, it feels odd to use distutils in main application code. The function was modified to walk its talk and actually return bool and not int. """ val = val.lower() if val in ("y", "yes", "t", "true", "on", "1"): return True elif val in ("n", "no", "f", "false", "off", "0"): return False else: raise ValueError("invalid truth value %r" % (val,))
def valid(passport: dict) -> bool: """Return true if all required fields are in passport.""" required = set(["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]) return required.issubset(set(passport.keys()))
def strformatted(value, arg): """Perform non-magical format of `value` with the format in `arg`. This is similar to Django's stringformat filter, but don't add the initial '%' they do. Which allows you to put your value in the middle of other string. """ try: return str(arg) % value except (ValueError, TypeError): return ''
def element_setup(element_name: str, element_description: dict) -> dict: """This is where secondary processing of the YAML data takes place. These method is applied to every widget. :param element_name: The base name of the widget being added. :param element_description: The name of the element being added :returns element_description: A description of an element, ready to add. """ element_description["_name"] = element_name # Every element must have a widget type if "widget" not in element_description: raise KeyError(f"Missing 'widget:' type in UI element {element_name}") return element_description
def update_parameter_dict(source_dict, update_dict, copy=True): """Merges two dictionaries (source and update) together. It is similar to pythons dict.update() method. Furthermore, it assures that all keys in the update dictionary are already present in the source dictionary. Otherwise a KeyError is thrown. Arguments: source_dict(dict): Source dictionary to be updated. update_dict(dict): The new dictionary with the entries to update the source dict. copy(bool): Flag, if the source dictionary shall be copied before updating. (Default True) Returns: dict: The updated source dictionary. Exceptions: KeyError: Thrown, if a key in the update dict is not available in the source dict. """ source_keys = source_dict.keys() for key in update_dict.keys(): if key not in source_keys: raise KeyError(f'Cannot update_dict the source_dict. The key "{key}" is not available.') new_dict = source_dict.copy() if copy else source_dict new_dict.update(update_dict) return new_dict
def print_cutoffs(cutoffs): """Print cutoff counts.""" lines = [] for key, val in sorted(cutoffs.items()): lines.append(f' {key}: {val}') return '\n'.join(lines)
def complement_base(base, material='DNA'): """Return the Watson-Crick complement of a base""" if base in 'Aa': if material == 'DNA': return 'T' elif material == 'RNA': return 'U' elif base in 'TtUu': return 'A' elif base in 'Gg': return 'C' else: return 'G'
def parse_inputspec(input_spec): """input_spec=<path>[;rows=<rows>;cols=<cols>;type=<dtype>] (dtype as in cv_image.iterator)""" parts = input_spec.split(';') header = dict([tuple(part.split('=')) for part in parts if '=' in part]) rows = int(header['rows']) if 'rows' in header else None cols = int(header['cols']) if 'cols' in header else None dtype = header['type'] if 'type' in header else None return parts[0], rows, cols, dtype
def dictDeleteEmptyKeys(dictionary, ignoreKeys): """ Delete keys with the value ``None`` in a dictionary, recursively. This alters the input so you may wish to ``copy`` the dict first. Courtesy Chris Morgan and modified from: https://stackoverflow.com/questions/4255400/exclude-empty-null-values-from-json-serialization """ for key, value in list(dictionary.items()): if value is None or (hasattr(value, '__iter__') and len(value) == 0): del dictionary[key] elif isinstance(value, dict): if key not in ignoreKeys: dictDeleteEmptyKeys(value, ignoreKeys) elif isinstance(value, list): for item in value: if isinstance(item, dict): dictDeleteEmptyKeys(item, ignoreKeys) return dictionary
def str_to_pos(chess_notation): """converts from chess notation to co-ordinates >>> str_to_pos("A3") (0, 5) >>> str_to_pos("B6") (1, 2) """ letter = chess_notation[0] x = ord(letter) - ord("A") y = 8 - int(chess_notation[1]) return x, y
def _tuples(key, values): """list of key-value tuples""" return [(key, value) for value in values]
def list_minus(list1, list2): """ this function takes in two lists and will return a list containing the values of list1 minus list2 """ result = [] zip_object = zip(list1, list2) for list1_i, list2_i in zip_object: result.append(list1_i - list2_i) return result
def mulr(registers, opcodes): """mulr (multiply register) stores into register C the result of multiplying register A and register B.""" test_result = registers[opcodes[1]] * registers[opcodes[2]] return test_result
def fahr_to_celsius(temp): """ Convert Fahrenheit to Celsius. Parameters ---------- temp : int or double The temperature in Fahrenheit. Returns ------- double The temperature in Celsius. Examples -------- >>> from convertempPy import convertempPy as tmp >>> tmp.fahr_to_celsius(32) 0 """ return (temp - 32) * (5 / 9)
def compute(x, y): """ Return the sum of two integers. param x: a positive integer between 0-100 param y: a positive integer between 0-100 @return: an Integer representing the sum of the two numbers """ if not (isinstance(x, int) and isinstance(y, int)): return 'Please enter only integers, example: 40' if not ((x >= 0 and x <= 100) and (y >= 0 and y <= 100)): return 'Please enter only integers between 0 and 100.' return x + y
def _clockwise(pnt1, pnt2, pnt3): """Return True if pnt2->pnt2->pnt3 is clockwise""" vec1 = (pnt2[0] - pnt1[0], pnt2[1] - pnt1[1]) vec2 = (pnt3[0] - pnt2[0], pnt3[1] - pnt2[1]) return vec1[0] * vec2[1] - vec1[1] * vec2[0] < 0
def get_cigar_by_color(cigar_code): """ ***NOT USED YET*** :param is_in_support: :return: """ if cigar_code == 254: return 0 if cigar_code == 152: return 1 if cigar_code == 76: return 2
def simtelSingleMirrorListFileName( site, telescopeModelName, modelVersion, mirrorNumber, label ): """ sim_telarray mirror list file with a single mirror. Parameters ---------- site: str South or North. telescopeModelName: str North-LST-1, South-MST-FlashCam, ... modelVersion: str Version of the model. mirrorNumber: int Mirror number. label: str Instance label. Returns ------- str File name. """ name = "CTA-single-mirror-list-{}-{}-{}".format( site, telescopeModelName, modelVersion ) name += "-mirror{}".format(mirrorNumber) name += "_{}".format(label) if label is not None else "" name += ".dat" return name
def _get_n_opt_and_check_type_list_argument( candidate, scalar_type, argument_required, name ): """Calculate number of inputs and check input types for argument that is expected as scalar or list/tuple. Args: candidate: Argument scalar_type: Expected type of a scalar argument argument_required (bool): Whether an empty argument is allowed name (str): Name of argument used in error message """ msg = f"{name} has to be a {scalar_type} or list of {scalar_type}s." # list/tuple if isinstance(candidate, (list, tuple)): # Empty argument if len(candidate) == 0: n_optimizations = 1 if argument_required: raise ValueError(f"{name} needs to be specified") # Non-empty list/tuple else: n_optimizations = len(candidate) # Assert that all values are of the correct type for c in candidate: if not isinstance(c, scalar_type): raise ValueError(msg) # Scalar else: n_optimizations = 1 # Assert that scalar is of the correct type if not isinstance(candidate, scalar_type): raise ValueError(msg) return n_optimizations
def irangef(start, stop, step=1): """ Inclusive range with floating point step. Returns a list. Args: start : First element stop : Last element step : Amount to increment by each time Returns: list >>> irangef(0, 5, 1) [0, 1, 2, 3, 4, 5] """ result = [] i = start while i <= stop: result.append(i) i += step return result
def FilterFnTable(fn_table, symbol): """Remove a specific symbol from a fn_table.""" new_table = list() for entry in fn_table: # symbol[0] is a str with the symbol name if entry[0] != symbol: new_table.append(entry) return new_table
def _to_camel_case(label, divider = '_', joiner = ' '): """ Converts the given string to camel case, ie: :: >>> _to_camel_case('I_LIKE_PEPPERJACK!') 'I Like Pepperjack!' :param str label: input string to be converted :param str divider: word boundary :param str joiner: replacement for word boundaries :returns: camel cased string """ words = [] for entry in label.split(divider): if len(entry) == 0: words.append('') elif len(entry) == 1: words.append(entry.upper()) else: words.append(entry[0].upper() + entry[1:].lower()) return joiner.join(words)
def phpencode(text, quotechar="'"): """Convert Python string to PHP escaping. The encoding is implemented for `'single quote' <http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single>`_ and `"double quote" <http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double>`_ syntax. heredoc and nowdoc are not implemented and it is not certain whether this would ever be needed for PHP localisation needs. """ if not text: return text if quotechar == '"': # \n may be converted to \\n but we don't. This allows us to preserve # pretty layout that might have appeared in muliline entries we might # lose some "blah\nblah" layouts but that's probably not the most # frequent use case. See bug 588 escapes = [("\\", "\\\\"), ("\r", "\\r"), ("\t", "\\t"), ("\v", "\\v"), ("\f", "\\f"), ("\\\\$", "\\$"), ('"', '\\"'), ("\\\\", "\\"), ] for a, b in escapes: text = text.replace(a, b) return text else: return text.replace("%s" % quotechar, "\\%s" % quotechar)
def aliased(aliased_class): """ Decorator function that *must* be used in combination with @alias decorator. This class will make the magic happen! @aliased classes will have their aliased method (via @alias) actually aliased. This method simply iterates over the member attributes of 'aliased_class' seeking for those which have an '_aliases' attribute and then defines new members in the class using those aliases as mere pointer functions to the original ones. Usage: @aliased class MyClass(object): @alias('coolMethod', 'myKinkyMethod') def boring_method(): # ... i = MyClass() i.coolMethod() # equivalent to i.myKinkyMethod() and i.boring_method() """ original_methods = aliased_class.__dict__.copy() #for name, method in original_methods.iteritems(): for name, method in original_methods.items(): if hasattr(method, '_aliases'): # Add the aliases for 'method', but don't override any # previously-defined attribute of 'aliased_class' for alias in method._aliases - set(original_methods): setattr(aliased_class, alias, method) return aliased_class
def eqn_of_line(x1: float, y1: float, x2: float, y2: float) -> str: """ Finds equation of a line passing through two given points. Parameters: x1, y1 : The x and y coordinates of first point x2, y2 : The x and y coordinates of second point Returns: Equation of the line as a string. """ a = y2 - y1 b = x1 - x2 c = a*(x1) + b*(y1) if b<0: s=( f"{a}x - {abs(b)}y = {c}") else: s=( f"{a}x + {b}y = {c}") return s
def poly_integral(poly, C=0): """ Calculates the integral of a polynomial: poly is a list of coefficients representing a polynomial the index of the list represents the power of x that the coefficient belongs to Example: if [f(x) = x^3 + 3x +5] , poly is equal to [5, 3, 0, 1] C is an integer representing the integration constant If a coefficient is a whole number, it should be represented as an integer If poly or C are not valid, return None Return a new list of coefficients representing the integral of the polynomial The returned list should be as small as possible """ if type(poly) == list and len(poly) > 0 and type(C) == int: itg = [C] if len(poly) > 1: for i in range(1, len(poly)): if isinstance(poly[i], (int, float)): coef = poly[i - 1] / i if coef.is_integer(): itg.append(int(coef)) else: itg.append(coef) else: return None else: if poly[0] == 0: return itg else: return [C, poly[0]] coef = poly[len(poly) - 1] / len(poly) if coef.is_integer(): itg.append(int(coef)) else: itg.append(coef) for i in range(len(itg)): if (sum(itg[i:]) == 0): return itg[:i] return itg return None
def cmod(n, base): """ Compute the modulus of a number like in languages such as C. :param n: the number to modulus :param base: the divisor """ return n - int(n / base) * base
def A12_5_2_1(A, Fy, GammaRTt): """ Fy = yield stress as defined in A.12.2.2 A = total cross-sectional area GammaRTt = partial resistance factor for axial tension, 1,05 """ # Tubular members subjected to axial tensile forces, Put, # should satisfy: Put = A * Fy / GammaRTt # return Put #
def _is_string(v): """ Returns True if the given value is a String. :param v: the value to check. :return: True if the value is a String, False if not. """ return isinstance(v, str)
def stripnl(s): """remove newlines from a string""" return str(s).replace("\n", " ")
def uri_to_fname(uri): """ """ fname = uri.strip().replace('http://', '') fname = fname.replace('dbpedia.org/ontology', 'dbo') fname = fname.replace('dbpedia.org/property', 'dbp') fname = fname.replace('dbpedia.org/resource', 'dbr') fname = fname.replace('xmlns.com/foaf/0.1', 'foaf') fname = fname.replace('www.w3.org/2002/07/owl', 'owl') fname = fname.replace('www.w3.org/2000/01/rdf-schema', 'rdfs') fname = fname.replace('www.w3.org/1999/02/22-rdf-syntax-ns', 'rdf') fname = fname.replace('/', '-') fname = fname.replace('#', '-') return fname
def count_kmers(k,genome,length): """ Summary -- Count the kmers of size k in a given sequence Description -- Determine all of the possible kmers of size k for a given sequence. Record and count all of the unique (observed) kmers for the sequence. Parameters: - k: size of the the subsets - genome: sequence given by the user through the command line - length: length of the genome sequence Returns -- A tuple of the unique kmers that were found for the specifed k. The first value of the tuple is the total possible kmers for size k and the second value is a list of unique kmers of size k. The number of observed kmers is obtained by taking the length of this list. """ sequences = [] count = 0 # all observed kmers for i in range(length): if length < (i + k): break # exit loop if you are on element length-k # if value of the k is equal to the size of the sequence if length == k: sequences.append(genome) return (1, sequences) # if k is smaller than the length of the sequence else: seq = genome[i:i + k] if seq not in sequences: sequences.append(seq) count += 1 if k == 1: count = 4 return count,sequences
def format_url(url): """Fixes telegram url format""" # Prevent e.g. www.example.com from being interpreted as relative url if not url.startswith("http") and not url.startswith("//"): url = f"//{url}" return url
def _crc_algo_define(opt, sym): """ Get the the identifier for header files. """ name = sym['crc_algorithm'].upper().replace('-', '_') return 'CRC_ALGO_' + name