content
stringlengths
42
6.51k
def removeDuplicates(nums): """ :type nums: List[int] :rtype: int """ i = 0 # current check point for val in nums: if val != nums[i]: i += 1 nums[i] = val return i + 1
def needs_ascii(fh): """ Answer whether to encode as ascii for the given file handle, which is based on whether the handle has an encoding (None under py2 and UTF-8 under py3) and whether the handle is associated with a tty. """ if fh.encoding and fh.encoding != "UTF-8": return True ...
def marker_pulse_width(session, Type='Real64', RepCap='', AttrID=1150064, buffsize=0, action=['Get', '']): """[Marker Pulse Width <real64>] Sets/Gets the pulse width value, in seconds, for the marker connection identified through the Active Marker attribute. Markers are always output as pulses of a program...
def parse_export_env(env): # type: (str) -> dict[str, str] """Parse environment variables to a dictionary. Exmple: env_vars = parse_export_env(job.attr_export_env_to_job) primary_file = env_vars['PAS_PRIMARY_FILE'] Args: env: Environment variables. Returns: Pairs o...
def formula_map(num): """ Creat formula map for parsing error in url """ formulamap = {18: "-I", 30: ".alpha-Pa", 39: ".beta-Po", 40: ".alpha-Hg", 41: ".alpha-As", 43: ".beta-O", 350: ".alpha-CO"...
def split_indexes(indexes): """Split indexes list like 1 2 5 in 1 2 and 5.""" left, right = [indexes[0], ], [] left_now = True for i in range(1, len(indexes)): prev = indexes[i - 1] curr = indexes[i] if curr > prev + 1 and left_now: left_now = False if left_no...
def summation(n, term): """Return the sum of the first n terms in the sequence defined by term. Implement using recursion! >>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3 225 >>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 54 >>> summation(5, lamb...
def trim(val, n, ellipsis='...'): """Trim value to max of n chars.""" val_str = str(val) trim_len = max(n - len(ellipsis), 0) return (val_str[:trim_len] + ellipsis if len(val_str) > n else val_str)
def eq7p3d1_pf(Ce, Ct, Is, pg): """Equation 7.4-1 flat roof snow load, pf: pf = Ce*Ct*Is*pg """ return Ce*Ct*Is*pg
def is_identical(root1, root2): """ checks if two bst are identical """ if root1 is None and root2 is None: return True if root1 is not None and root2 is None: return False if root1 is None and root2 is not None: return False if (root1.data == root2.data and is_ide...
def fsm_submit_button(transition): """ Render a submit button that requests an fsm state transition for a single state. """ fsm_field_name, button_value, transition_name = transition return { 'button_value': button_value, 'fsm_field_name': fsm_field_name, 'transition_name...
def normalize_path(path: str) -> str: """Normalize path.""" return path.replace('\\', '/')
def index_array(col): """ Assemble an array of (head, text) tuples into an array of {"section_head": head, "section_text": text, "section_idx": i} """ indexed_text = [{"section_head": h, "section_text": t, "section_idx": i} for i, (h, t) in enumerate(col)] return indexed_text
def AverageOverlap(l1, l2, depth = 10): """Calculates Average Overlap score. l1 -- Ranked List 1 l2 -- Ranked List 2 depth -- depth @author: Ritesh Agrawal @Date: 13 Feb 2013 @Description: This is an implementation of average overlap measure for comparing two score (R...
def factors(number): """ Find all of the factors of a number and return it as a list. :type number: integer :param number: The number to find the factors for. """ if not (isinstance(number, int)): raise TypeError( "Incorrect number type provided. Only integers are accepted....
def tryfunc(func, arg): """ Return func(arg) or None if there's an exception. """ try: return func(arg) except: return None
def get_prop(obj, *prop_list): """ Get property value if property exists. Works recursively with a list representation of the property hierarchy. E.g. with obj = {'a': 1, 'b': {'c': {'d': 2}}}, calling get_prop(obj, 'b', 'c', 'd') returns 2. :param obj: dictionary :param prop_list: list of the keys ...
def get_selection_gap (sel1, sel2) : """ Compute the gap or overlap between two selections (order-independent). Returns 0 if the selections are directly adjacent, or the number of residues overlapped (as a negative number) or missing between the selections (positive). """ if (type(sel1).__name__ == 'bool'...
def convert_numeric_code_with_pad(x): """ Codes like M49 and ISO 3166 numeric should be treated as strings, as their leading zeros are meaningful and must be preserved. """ try: return str(int(x)).zfill(3) except ValueError: return ''
def tamper_payload(scripted_url): """ If the payload doesn't work we'll try to tamper it >>> tamper_payload("http://127.0.0.1/php?id=<script>alert('test');</script>") http://127.0.0.1/php?id=%3Cscript%3Ealert(%27test%27)%3B%3C%2Fscript%3E """ tampered = [] tampering = {"<": "%3C", ">": "%3E", "'": "...
def keys_as_sorted_list(dict): """ Given a dictionary, get the keys from it, and convert it into a list, then sort the list of keys """ keys = dict.keys() keys_list = list(keys) sorted_keys_list = sorted(keys_list) return sorted_keys_list
def interpolate(r1, r2, x=None, y=None): """Perform simple linear interpolation between two points in 2D - one of x or y must be defined Parameters ---------- r1,r2 : float x,y coordinates from which to interpolate x : float x-value from which to interpolate y (default: None) ...
def get_col_coords(vert_line_coords): """Get top-left and bottom-right coordinates for each column from a list of vertical lines""" col_coords = [] for i in range(1, len(vert_line_coords)): if vert_line_coords[i][0] - vert_line_coords[i-1][0] > 1: col_coords.append((vert_line_coords[i-1]...
def format_delta(t): """ format seconds as days:hh:mm:ss""" m,s = divmod(t,60) if m >= 60: h,m = divmod(m,60) if h > 23: d,h = divmod(h,24) return "%d:%02d:%02d:%02d"%(d,h,m,s) return "%d:%02d:%02d"%(h,m,s) return "%d:%02d"%(m,s)
def create_lab_ui_steps(data, current_section): """ :param data: :param current_section: This function creates an HTML string around specific Cisco UI steps position to give the user a sense of where they are located in the lab. """ html = "<div class='progress_step'>" #html += "<div cla...
def parse_debug(response): """ Parse the result of Redis's DEBUG command into a Python dict :param bytearray response: :return disc: """ info = {} response = response.decode('utf8') for line in response.split(','): if line.find(':') != -1: key, value = line.split(':'...
def arrayCheck(nums): """ Function to find a sequence 1, 2, 3. Given a list of integers, return True if the sequence of numbers 1, 2, 3 appears in the list somewhere. Args: nums (Array): Array of integer """ for i in range(len(nums)-2): if nums[i] == 1 and nums[i+1] == 2 a...
def has_bad_continuation(line): """Tell whether or not a non-comment line is bad.""" stripped = line.strip() return stripped.endswith("\\") and not ( stripped.startswith("assert") or stripped.startswith("with") )
def diff21(n: int) -> int: """Absolute difference between n and 21. Returns abs(n-21) if n <= 21 and abs(n-21) * 2 if n > 21. """ diff = abs(n - 21) if n > 21: return diff * 2 return diff
def get_smc_sample_iter(filename): """Returns the iteration number of an SMC filename""" if filename.endswith(".smc.gz"): filename = filename[:-len(".smc.gz")] elif filename.endswith(".gz"): filename = filename[:-len(".gz")] i = filename.rindex(".") return int(filename[i+1:])
def located_message(loc, filename, message): """ Add location informations to a message string. """ if loc: return "at %s: %s" % (loc, message) else: return "in %s: %s" % (filename, message)
def mandatory_arguments(parameters, parent=None): """Get a list of parameter names that are mandatory. The optional parent parameter allows to request mandatory parameter for nested components. Parameters ---------- parameters: dict(benchtmpl.workflow.parameter.base.TemplateParameter) Dicti...
def get_stuff_from_net(url): """ This function accepts a URL as input and attempts to retrieve this resource from the Net. :param url: The required resource URL, fully qualified, i.e. http{s}://... Add a space at the end or else you'll attempt to launch a browser :return: The content of the resour...
def to_hex(image_id) -> str: """Given Image Id, return its hex value""" return '{0:0{1}x}'.format(image_id, 16)
def check_overlap(stem1, stem2): """ Checks if 2 stems use any of the same nucleotides. Args: stem1 (tuple): 4-tuple containing stem information. stem2 (tuple): 4-tuple containing stem information. Returns: bool: Boolean indicating if the two stems overlap....
def scale_vector_parts_to_certain_product(values, dynamic, goal_result): """Warning: This is pure epic logic/magic Our Goal: Find a list, named return_list, such that return_list[0]*return_list[1]*return_list[2]*...*return_list[-1] = goal_result That means the product of all entries in the list is our goal_result. Oth...
def store_val(arg, val, args, acc): """ lambda that store the value of the argument on the parser result """ if val == '': val = None acc[arg] = val return args, acc
def decompressish(s): """ returns tuple (X, S) where X is the size of the decompressed parts, and S is the remaining string to decompress """ count = 0 while s[0] != '(': count += 1 s = s[1:] if len(s) == 0: return (count, "") s = s[1:...
def cck(dist, alpha): """ Cauchy Kernel Function (CCK). Parameters ---------- dist : float or numpy.ndarray, shape=(m,) Distances. alpha : float Control the decay of the function. Returns ------- sim : float or numpy.ndarray, shape=(m) Similatity result. ...
def paginator(context, adjacent_pages=1): """ To be used in conjunction with the object_list generic view. Adds pagination context variables for use in displaying first, adjacent and last page links in addition to those created by the object_list generic view. """ if 'page_obj' in context:...
def length(scope, mylist): """ Returns the number of items in the list. :rtype: string :return: The model of the remote device. """ return [len(mylist)]
def url_scheme_is_secure(url): """Check if the URL is one that requires SSL/TLS.""" scheme, _dest = url.split("://") return scheme == "elks"
def binary_search(arr, low, high): """ Purpose : This function find the smallest element using Binary search Input : arr : The array from which the smallest element has to be returned low : Starting index of the array high : End index of the array Output : ...
def is_valid_machine_config(cfg, service_exploits): """ Check if a machine config is valid or not given the list of service exploits available N.B. each machine config must contain at least one of the services """ if type(cfg) != list or len(cfg) == 0: return False for service in cfg: ...
def _format_size(num, suffix='B'): """ Format sizes """ for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix)
def organism_filter(organism_list, *conditions): """ Selects organisms from organism list according to a set of conditions. Each condition should be a function that receives an Organism object as input and returns a boolean as output. Example: organism_filter( population_dict['prey1']['...
def get_lengths_from_mix(ttspec): """ Get set of shift lengths and order them ascending by length Inputs: ttspec - yaml representation of tour type mix parameters Output: A sorted list of shift lengths. Example: [8, 16, 20, 24] """ # lenset = set([]) for m in tts...
def eeff(e_1, nu_1, e_2, nu_2): """ Calculate the effective (Young's) modulus of two contact bodies according to Hertzian contact theory. Parameters ---------- e_1: ndarray, scalar The Young's modulus of contact body 1. nu_1: ndarray, scalar The Poisson ratio of contact bod...
def qtr_offset(qtr_string, delta=-1): """ Takes in quarter string (2005Q1) and outputs quarter string offset by ``delta`` quarters. """ old_y, old_q = map(int, qtr_string.split('Q')) old_q -= 1 new_q = (old_q + delta) % 4 + 1 if new_q == 0: new_q = 4 new_y = old_y + (old_q + ...
def flatten(struct): """ Creates a flat list of all all items in structured output (dicts, lists, items): .. code-block:: python >>> sorted(flatten({'a': 'foo', 'b': 'bar'})) ['bar', 'foo'] >>> sorted(flatten(['foo', ['bar', 'troll']])) ['bar', 'foo', 'troll'] >>> f...
def simple_file_name(file): """ Given a path for a file, this strips away the directory information and returns the file name only. """ if '\\' in file: return file.split('\\')[-1] if '/' in file: return file.split('/')[-1] return file
def is_palindrome(str): """ Returns is str palindrome or not """ if len(str) == 1: return True if len(str) == 2: return str[0] == str[1] if str[0] == str[-1]: return is_palindrome(str[1:-1]) return False
def max_trials(elements): """Max number of trials in a buffer""" if not elements: return 0 return max(e["trials"] for e in elements)
def is_resource_name_parameter_name(param_name: str) -> bool: """Determines if the mb_sdk parameter is a resource name.""" return param_name != 'display_name' and \ not param_name.endswith('encryption_spec_key_name') and \ param_name.endswith('_name')
def prediction(n: float, r: float, s: float) -> int: """ Returns label of the class with maximum probability :param n: probability of being Neutral :param r: probability of being Racist :param s: probability of being Sexism :return: label of the class with maximum probability """ lst = [...
def dns_name_encode(name): """ DNS domain name encoder (string to bytes) name -- example: "www.example.com" return -- example: b'\x03www\x07example\x03com\x00' """ name_encoded = [b""] # "www" -> b"www" labels = [part.encode() for part in name.split(".") if len(part) != 0] for labe...
def containsDuplicate(nums): """ :type nums: List[int] :rtype: bool """ if len(nums) <= 1: return False return True if len(nums) != len(set(nums)) else False
def IsActionPresent(current_actions, metric_name, is_boolean): """Checks if metric_name is defined in the actions file. Checks whether there's matching entries in an actions.xml file for the given |metric_name|, depending on whether it is a boolean action. Args: current_actions: The content of the actions...
def str2bool(s, default=False): """Convert str to bool value >>> str2bool('') or str2bool(u'') or str2bool(None) False >>> str2bool('on') and str2bool(u'on') and str2bool(u'1') and str2bool('1') True """ if not s: return False if s in ('', u''): return False s = s.lo...
def check_lenght(xs): """ transform list to tuples fixing the lenght """ if len(xs) == 1: return xs[0], '' else: return tuple(xs)
def choose(n, k): """ A fast way to calculate binomial coefficients by Andrew Dalke (contrib). """ if 0 <= k <= n: ntok = 1 ktok = 1 for t in range(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: ...
def isLimitExceed(NFA0Delta, NFA1Delta): """Decide if the size of NFA0 and NFA1 exceed the limit. Size of NFA0 is denoted as N, and size of NFA1 is denoted as M. If N*N*M exceeds 1000000, return False, else return True. If bothNFA is False, then NFA0 should be NFA, and NFA1 should be Transducer. If both NF...
def os_walk(thepath: str): """Performs an os.walk on the given path. Examples: >>> test = os_walk('../worksheet_dir') >>> pprint(test)\n [('../worksheet_dir',\n ['__pycache__'],\n ['worksheet_sets.py', 'worksheet_match_str_len_with_padding.py', 'worksheet...
def matches(line, query): """Both arguments must be of a type bytes""" return line == query or line.startswith(query + b' ')
def peg_by_value(current_peg, current_val): """ Returns for each PEG stage the share value """ result = {} result[current_peg] = {} result[0.5] = {} result[1] = {} result[2] = {} result[3] = {} result[3.6] = {} result[current_peg]['value'] = current_val result[current_peg...
def cpu_mandel(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ c = complex(x, y) z = 0.0j for i in range(max_iters): z = z * z + c if ...
def smart_bytes(s, encoding="utf-8", errors="strict"): """Return a bytes version of 's' encoded as specified in 'encoding'.""" if isinstance(s, bytes): if encoding == "utf-8": return s else: return s.decode("utf-8", errors).encode(encoding, errors) if isinsta...
def calculate_combinations(user_dict): """ Read user inut from 'param_combos' sheet in input Excel file and calculate all combnations of the parameters entered. Args: user_dict: Dict of user-defined input from the 'param_combos' sheet in the input Excel template. ...
def sim_bma(terms1, terms2, sem_sim): """Similarity between two term sets based on Best-Match Average (BMA) """ sims = [] for t1 in terms1: row = [] for t2 in terms2: sim = sem_sim(t1, t2) if sim is not None: row.append(sim) if row: ...
def sort(data): """ Sort list of reminders by time (oldest first). """ return sorted(data, key=lambda k: (k['time']))
def _get_transaction_stack_depth(transaction): """ build history stack by transaction depth """ depth = 0 current = transaction while current: depth += 1 current = transaction.parent return depth
def dns_server_port(zone): """ Parses the server and port based on the connection info on the zone :param zone: a populated zone model :return: a tuple (host, port), port is an int """ name_server = zone['connection']['primaryServer'] name_server_port = 53 if ':' in name_server: ...
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 """ sorted_arr = [] count_zero = 0 for i in input_list: if i == 0: sorted_arr = [i] + sorted_arr ...
def isdbLoadTemplateCall(line, verbose): """ See if a string is a dbLoadTemplate command.""" if (line.find('dbLoadTemplate(') == -1): return (0) # e.g., dbLoadTemplate("myTemplate.substitutions") words = line.split('"',2) if (len(words) > 2): # e.g., 'dbLoadTemplate(', 'myTemplate.substitutions', ')' return (...
def byte2bin(byte_val): """ Transform a byte (8-bit) value into a bitstring """ return bin(byte_val)[2:].zfill(8)
def EscapeMakeVariableExpansion(s): """Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.""" return s.replace('$', '$$')
def get_c_dict(clusters): """ Count all genes which appear in any cluster :param clusters: dictionary :return: dictionary """ c_dict = {} for c in clusters.keys(): for gene in clusters[c].keys(): if gene in c_dict.keys(): c_dict[gene] += 1 els...
def split_input_target(chunk): """ Creates input/target pairs for text generation: sequence up to second-to-last element and sequence from second element to last. """ input_text = chunk[:-1] target_text = chunk[1:] return input_text, target_text
def make_add_identifier(identifier, build_names): """ Takes an existing used Python identifier and attatch a unique identifier with ADD_# ending. Used for add new information to an existing external object. build_names will be updated inside this functions as a set is mutable. Parameters ...
def unwrap(text): """Unwrap text.""" lines = text.split('\n') result = '' for i in range(len(lines) - 1): result += lines[i] if not lines[i]: # Paragraph break result += '\n\n' elif lines[i + 1]: # Next line is not paragraph break, add space ...
def chk(val, n0, offset): """Finds a list of palindromes from substring given a position within the string. Offset Args: val (string): The string that we are examining for palindromes. n0 (integer): Position of the pivot character that we using to find palindromes. ...
def replace_file_ext(fname): """Format a string from file_timeseries.tsv to file.nii.gz. Parameters ---------- fname : str Filename ending with _timeseries.tsv Returns ------- str _timeseries.tsv file to be used for output """ return fname.replace('_timeseries.tsv','...
def clean_candidates(vehicles, last_known_id): """Only report new vehicles.""" results = [] last_id = last_known_id for vehicle in vehicles: if vehicle['id'] > last_known_id: results.append(vehicle) if vehicle['id'] > last_id: last_id = vehicle['id'] ...
def _get_datetime_original(exif): """Get DateTimeOriginal from EXIF. Args: exif (dict): Returns: str: DateTimeOriginal """ if not exif: return None datetime_original = exif.get(0x9003) # EXIF: DateTimeOriginal return datetime_original
def get_html_redirect_link(page): """ Check if the page souce contains a redirect in html and extrat it :param page: the page source code :return: link to redirect or None """ if 'http-equiv=\"refresh\"' in page.lower(): page = str(page).replace("\\n", "\n") # each line ...
def cross_combine(x): """ Combine every two of a list, as well as give every one of them.??? Can be put to utils.py :param x: :return: """ if not x: # if x is [] return [] head = x[0] tail = x[1:] ret = [] other = cross_combine(tail) for i in head: if no...
def mts_parse(tsstr, mbase=1): """ parse MediaInfo-style absolute timestamp (eg. '00:06:11.950000000') use @mbase=1000 to rebase the number in millseconds rather than seconds """ tacc = 0.0 tparts = tsstr.split(':') tparts.reverse() for tplace, tseg in enumerate(tparts): tmul = f...
def dprod(l0, l1): """WoW, generator expression, zip and sum.""" return sum(x * y for x, y in zip(l0, l1))
def normalize_newlines(s): """Normalize line breaks in a string.""" return s.replace('\r\n', '\n').replace('\r', '\n') if s else s
def packageParameters(gK, gNa, gL, Cm, EK, ENa, EL, Vm_0, T): """ Takes all HH class parameters, packages and returns a dictionary class object; the keys are hardcoded in the Hodgkin Huxley class definition """ parameterDictionary = { "gK": gK, "gNa": gNa, "gL": gL, ...
def node_cata(alg, node): """A twist on cata: somewhat non-canonical because we pass child_results explicitly as a parameter to alg, rather than constructing a new node which has the already transformed values at .children. Works for any rose-tree which has its children in .children""" node_children =...
def try_int(val, default=None): """Return int or default value.""" try: return int(val) except (ValueError, TypeError): return default
def dotvv(a, b, check=True): """ Vector-vector dot product, optimized for small number of components containing large arrays. For large numbers of components use numpy.dot instead. Unlike numpy.dot, broadcasting rules only apply component-wise, so components may be a mix of scalars and numpy arrays ...
def getMonthIndex(my_str): """ Given a string representing a month or a season (common abrev) Returns the ordered indices of the month. Author: Krishna Achutarao Date: April 2001 :param my_str: string reperesenting month or season :type my_str: str :returns: The ordered indices of the ...
def inPypi(lines): """ Returns True if the package is hosted by pypi / pythonhosted. False otherwise """ isInPypi = False for line in lines: if "Source" in line and ("pypi.python.org" in line or "files.pythonhosted.org" in line): isInPypi = True return isInPypi
def str_to_be(data: str) -> bytes: """Convert bencoded data from string to bytes""" result = bytearray() seq_marker = False seq_chars = "" for char in data: if char == "[": seq_marker = True continue if char == "]": result.append(int(seq_chars, 16...
def palindrome(word: str) -> bool: """Palindrome check example :param word: {str} :return: {bool} is the word palindrome """ word = word.lower() return word[::-1] == word
def lix(n_words, n_long_words, n_sents): """ Readability score commonly used in Sweden, whose value estimates the difficulty of reading a foreign text. Higher value => more difficult text. References: https://en.wikipedia.org/wiki/LIX """ return (n_words / n_sents) + (100 * n_long_words ...
def find_combination(value, stream): """ >>> find_combination(127, [35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576]) 62 """ x = 0 y = 2 while True: total = sum(stream[x:y]) if total < value: y += 1 elif total > ...
def get_rotation(lttextlh, lttextlv, ltchar): """Detects if text in table is rotated or not using the current transformation matrix (CTM) and returns its orientation. Parameters ---------- lttextlh : list List of PDFMiner LTTextLineHorizontal objects. lttextlv : list List of PDF...