content
stringlengths
42
6.51k
def adapt_impedance_params(Z, sign=1, adaption=1e-15): """ In some extreme cases, the created admittance matrix of the zpbn network is singular. The routine is unsolvalbe with it. In response, an impedance adaption is created and added. """ rft_pu = Z.real + sign*adaption xft_pu = Z.imag + s...
def hex_to_rgb(x): """Turns a color hex representation into a tuple representation.""" return tuple([int(x[i:i + 2], 16) for i in (0, 2, 4)])
def _correct_quandl_request_stock_name(names): """If given input argument is of type string, this function converts it to a list, assuming the input argument is only one stock name. """ # make sure names is a list of names: if isinstance(names, str): names = [names] return names
def unique(source): """ Returns unique values from the list preserving order of initial list. :param source: An iterable. :type source: list :returns: List with unique values. :rtype: list """ seen = set() return [seen.add(x) or x for x in source if x not in seen]
def collect_psi4_options(options): """Is meant to look through the dictionary of psi4 options being passed in and pick out the basis set and QM method used (Calcname) which are appened to the list of psi4 options """ keywords = {} for opt in options['PSI4']: keywords[opt] = options['PSI4...
def obj_dist_from_EFL_and_m(f,m): """Calculate object distance (z) from focal length (f) and magnification (m) """ obj_dist = -1*((1-m)/m)*f return obj_dist # todo: clarify assumptions in terms of +/- distances.
def eh_peca(arg): """ eh_peca: universal -> booleano Devolve True caso o seu argumento seja um TAD peca ou False em caso contrario. """ return type(arg) == dict and \ len(arg) == 1 and \ 'peca' in arg and \ type(arg['peca']) == str and \ len(arg['peca']) == 1 and ...
def s_and(*args): """Logical and.""" result = True for i in args: result = result and i if not result: break return result
def getxy(a, b): """x*a + y*b = gcd(a,b)""" """ input requirement: a > b """ """ get x for a and y for b""" remainder = a % b k = a // b if b % remainder == 0: return 1, -k else: x1, y1 = getxy(b, remainder) return y1, y1 * (-k) + x1
def locationSlice(lmA, prefix): """Recovers locations with a given prefix Keyword arguments: lmA -- Location map to recover location from prefix -- Key or part of key in location map dictionary Creates a copy of provided location map lmA Copy contains all key-value pairs from l...
def _merge_opts(opts, new_opts): """Helper function to merge options""" if isinstance(new_opts, str): new_opts = new_opts.split() if new_opts: opt_set = set(opts) new_opts = [opt for opt in new_opts if opt not in opt_set] return opts + new_opts return opts
def if_function(condition, true_result, false_result): """Return true_result if condition is a true value, and false_result otherwise. >>> if_function(True, 2, 3) 2 >>> if_function(False, 2, 3) 3 >>> if_function(3==2, 3+2, 3-2) 1 >>> if_function(3>2, 3+2, 3-2) 5 """ if ...
def is_constant(s: str) -> bool: """Checks if the given string is a constant. Parameters: s: string to check. Returns: ``True`` if the given string is a constant, ``False`` otherwise. """ return s == 'T' or s == 'F'
def is_power_of_2(num): """ Returns whether num is a power of two or not :param num: an integer positive number :return: True if num is a power of 2, False otherwise """ return num != 0 and ((num & (num - 1)) == 0)
def sol_1(ar: list) -> list: """using count (not inplace)""" return [0]*ar.count(0) + [1]*ar.count(1) + [2]*ar.count(2)
def _normalize_deps(deps, more_deps = None): """ Create a single list of deps from one or 2 provided lists of deps. Additionally exclude any deps that have `/facebook` in the path as these are internal and require internal FB infra. """ _deps = deps or [] _more_deps = more_deps or [] _deps...
def vector_subtract(first: tuple, second: tuple) -> tuple: """ 2-D simple vector subtraction w/o numpy overhead. Tuples must be of the same size""" return first[0] - second[0], first[1] - second[1]
def _useBotoApi(storage_schema): """Decides if the caller should use the boto api given a storage schema. Args: storage_schema: The schema represents the storage provider. Returns: A boolean indicates whether or not to use boto API. """ if storage_schema == 'gs' or storage_schema == 's3': retur...
def single_quote(name: str) -> str: """Represent a string constants in SQL.""" if name.startswith("'") and name.endswith("'"): return name return "'%s'" % name
def recursive_knapsack(profits, profits_length, weights, capacity): """ Parameters ---------- profits : list integer list containing profits profits_length : int number of profits in profit list weights : list integer list of weights capacity : int capacity o...
def validate_required_fields(metadata): """Check if the metadata can be used on analysis. This is evolving""" required = ['RESULTS-BALANCED_ACCURACY'] val = True for field in required: val = val & (field in metadata) return val
def trim_proximal_primer(primer_list, seq): """Doc string here..""" p_primer_found = ""; offset = 0; for primer in primer_list: #print primer prim_len = len(primer) idx = seq.find(primer) if(idx != -1): if(idx == 0): p_primer_found = pr...
def parse_comma_separated_list(s): """ Parse comma-separated list. """ return [word.strip() for word in s.split(',')]
def odd_check(number: int) -> bool: """[summary] Args: number (int): [positive number] Returns: bool: [Return True If The Number Is Odd And False If The Number Is Even] """ if number % 2 == 0: return False else: return True
def iob1_iob2(tags): """ Check that tags have a valid IOB format. Tags in IOB1 format are converted to IOB2. """ new_tags = [] for i, tag in enumerate(tags): if tag == 'O': new_tags.append(tag) else: split = tag.split('-') if len(split) != 2 or...
def get_average(img, u, v, n): """img as a square matrix of numbers""" s = 0 for i in range(-n, n+1): for j in range(-n, n+1): s += img[u+i][v+j] return float(s)/(2*n+1)**2
def h2(text): """h2 tag >>> h2('my subheading') '<h2>my subheading</h2>' """ return '<h2>{}</h2>'.format(text)
def sort(seq): """ Takes a list of integers and sorts them in ascending order. This sorted list is then returned. :param seq: A list of integers :rtype: A list of sorted integers """ L = len(seq) for _ in range(L): for n in range(1, L): if seq[n] < seq[n - 1]: ...
def make_counter_summary(counter_element, covered_adjustment=0): """Turns a JaCoCo <counter> element into an llvm-cov totals entry.""" summary = {} covered = covered_adjustment missed = 0 if counter_element is not None: covered += int(counter_element.attrib['covered']) missed += int(counter_element.at...
def get_disk_label_no(drive_partitions, ip_label): """ Returns the swift disk number of a partition that has already been labelled """ partitions = drive_partitions.split() num = "-1" for part in partitions: if (ip_label + "h") in part: _, num = part.strip("]'").split("...
def fp_boyer_freqs(ups_r, ups_theta, ups_phi, gamma, aa, slr, ecc, x, M=1): """ Boyer frequency calculation Parameters: ups_r (float): radial frequency ups_theta (float): theta frequency ups_phi (float): phi frequency gamma (float): time frequency aa (float): spin pa...
def human2bytes(s): """ convert human readable size string to int """ symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') letter = s[-1:].strip().upper() num = s[:-1] assert num.isdigit() and letter in symbols num = float(num) prefix = {symbols[0]:1} for i, s in enumerate(symbols[1:]...
def getAllReachable1Step(original_nodes): """ return all node, value pairs reachable from any of the pairs in the original nodes in a single step :param original_nodes: a set of node, value, complete_path pairs from which we check what they can reach in 1 step :return: a set of node, value pairs that ca...
def summarizeBeatInfo(note_centers_list): """ Convert list of note centers to map of note centers for each beat. """ x_positions = list(map(lambda center: center[0], note_centers_list)) return max(set(x_positions), key=x_positions.count)
def colored(fmt, fg=None, bg=None, style=None): """ Return colored string. List of colours (for fg and bg): k black r red g green y yellow b blue m magenta c cyan w white List of styles: b bold i italic...
def list2dict(L, value=None): """creates dict using elements of list, all assigned to same value""" return dict([(k, value) for k in L])
def convert_energy_unit(energy_val, current_unit, new_unit): """ Convert `energy_val` from the `current_unit` to `new_unit`. Only support kJ/mol, kcal/mol, and J/mol. """ if current_unit == 'kJ/mol' and new_unit == 'kcal/mol': return energy_val / 4.184 elif current_unit == 'kJ/mol' and n...
def unescape_text(text): """Replace HTML escape codes with special characters. Args: text: The text to unescape. Returns: The unescaped text. """ if text: text = text.replace("&quot;", "\"") text = text.replace("&#039;", "'") text = text.replace("&lt;", "<"...
def S_crop_values(_data_list, _max, _min): """ Returns a filtered data where values are discarded according to max, min limits. """ f_data = [] ds = len(_data_list) i = 0 while i < ds: if _data_list[i] >= _max: f_data.append(_max) elif _data_list[i] <= _min: ...
def str2bool(s): """ Converts an on/off, yes/no, true/false string to True/False. Booleans will be returned as they are, as will non-boolean False-y values. Anything else must be a string. """ if type(s) == bool: return s if s and s.upper() in [ 'ON', 'YES', 'Y', 'TRUE', '1' ]: return True else: return ...
def specificHumidity(qv): """ specificHumidity() Purpose: Calculate the specific humidity from mixing ratio Parameters: qv - Water vapor mixing ratio in kg/kg Returns: Specific humidity in kg/kg """ return qv/(1 + qv)
def time_setting_dict(time_str): """Convert a time string like 90s, 3h, 1d, to a dictionary with a single keyword-value pair appropriate for keyword value settings to the python datetime.timedelta function. For example, input of "3h" should return {"hours": 3}. Args: time_str: Time string ...
def htheta_function(x1, x2, theta_0, theta_1, theta_2): """ Linear function that is to optimized """ return theta_0 + theta_1 * x1 + theta_2 * x2
def nbsp(text): """ Replace spaces in the input text with non-breaking spaces. """ return str(text).replace(' ', '\N{NO-BREAK SPACE}')
def pairs_sort(k, arr): """ Runtime: O(n^2) By sorting, we can avoid some unnecessary comparisons. """ if len(arr) < 2: return [] pairs = [] arr.sort() for i, n1 in enumerate(arr): for n2 in arr[i+1:]: if n1 + n2 > k: # All other pairs will ...
def quad_BACT_to_gradient(bact, l): """Convert a SLAC quad BACT (kG) into BMAD b1_gradient T/m units""" return -bact/(10.0*l)
def show_hidden(str,show_all=False): """Return true for strings starting with single _ if show_all is true.""" return show_all or str.startswith("__") or not str.startswith("_")
def text_reformat(text): """lowercase without punctuation""" import re return re.sub(r'[^\w\s]', '', text.lower())
def split_composites(old_composites): """ Split the old composites in 5 equal parts. :param old_composites: The old composites that need to be split. :return: returns a list of composite lists. Where each composite list has count ~= len(old_composites) // 5. """ new_composites = [] if len(o...
def to_hex(b, sep=''): """Converts bytes into a hex string.""" if isinstance(b, int): return ("00" + hex(b)[2:])[-2:] elif isinstance(b, (bytes, bytearray)): s = b.hex() if len(s) > 2 and sep and len(sep) > 0: nlen = len(s) + (len(sep) * int(len(s) / 2)) for i...
def toFahrenheit(temp): """ A function to convert given celsius temperature to fahrenheit. param number: intger or float returns fahrenheit temperature """ fahrenheit = 1.8 * temp + 32 return fahrenheit
def key_info_url(key: str) -> str: """ Get the URL for the key endpoint with the key parameter filled in. :param key: The given key. :return: The corresponding URL. """ return f'https://api.hypixel.net/key?key={key}'
def _listify(x): """ If x is not a list, make it a list. """ return list(x) if isinstance(x, (list, tuple)) else [x]
def _serializeOnce_eval(parentUnit, priv): """ Decide to serialize only first obj of it's class :param priv: private data for this function (first object with class == obj.__class__) :return: tuple (do serialize this object, next priv, replacement unit) where priv is private data for t...
def process_test_result(passed, info, is_verbose, exit): """ Process and print test results to the console. """ # if the environment does not contain necessary programs, exit early. if passed is False and "merlin: command not found" in info["stderr"]: print(f"\nMissing from environment:\n\t{...
def msToPlayTime(ms): """ Convert milliseconds to play time""" secs = int(ms / 1000) mins = int(secs / 60) if mins < 60: return "{}:{:02d}".format(mins, secs % 60) else: hrs = int(mins / 60) mins = int(mins % 60) return "{}:{:02d}:{:02d}".format(hrs, mins, secs % 60)
def get_short_annotations(annotations): """ Converts full GATK annotation name to the shortened version :param annotations: :return: """ # Annotations need to match VCF header short_name = {'QualByDepth': 'QD', 'FisherStrand': 'FS', 'StrandOddsRatio': 'SOR...
def doubleStuff(a_list): """ Return a new list in which contains doubles of the elements in a_list. """ new_list = [] for value in a_list: new_elem = 2 * value new_list.append(new_elem) return new_list
def Color(red, green, blue, white = 0): """Convert the provided red, green, blue color to a 24-bit color value. Each color component should be a value 0-255 where 0 is the lowest intensity and 255 is the highest intensity. """ return (white << 24) | (green << 16)| (red << 8) | bl...
def check_syntax(code): """Return True if syntax is okay.""" try: return compile(code, '<string>', 'exec') except (SyntaxError, TypeError, UnicodeDecodeError): return False
def nmap(value, fr=(0, 1), to=(0, 1)): """ Map a value from a two-value interval into another two-value interval. Both intervals are `(0, 1)` by default. Values outside the `fr` interval are still mapped proportionately. """ value = (value - fr[0]) / (fr[1] - fr[0]) return to[0] + value * (t...
def cheap_factor(x): """ Cheap prime factors without repetition >>> cheap_factor(91) [7, 13] >>> cheap_factor(12) [2, 3] """ ret = list() i = 2 while i <= x: if x % i == 0: ret.append(i) while x % i == 0: x //= i i += 1 ...
def find(item, collection, keys): """Find the item in the specified collection whose keys/values match those in the specified item""" for other_item in collection: is_match = True for key in keys: if other_item[key] != item[key]: is_match = False brea...
def hasShapeType(items, sort): """ Detect whether the list has any items of type sort. Returns :attr:`True` or :attr:`False`. :param shape: :class:`list` :param sort: type of shape """ return any([getattr(item, sort) for item in items])
def base2str(value): """Produces the binary string representation of an integer value""" return "{:032b}".format(value)
def extract_pdf_links(urls): """Filters the input list of urls to look for PDF files. Also removes the rest of the path after the filename Parameters ---------- urls : [string] A list of urls Returns ------- [string] A filtered list of input urls """ pdfs = [] f...
def _ones_at(*bits): """Number with all bits zero except at the given positions ones""" assert len(bits) == len(set(bits)) value = 0 for b in bits: value += 1 << b return value
def adjust_coordinates(regtype, start, end, strand): """ :param regtype: :param start: :param end: :param strand: :return: """ norm = 1 if strand in ['+', '.'] else -1 if regtype == 'reg5p': if norm > 0: s, e = start - 1000, start + 500 else: s...
def dotProduct(x, y): """ Gets the dot product between the two given vectors. Args: x (list): First vector. y (list): Second vector. Returns: (float): Dot product result, scalar. """ return sum([x[i] * y[i] for i in range(len(x))])
def get_auth_header(token): """Get authorization header.""" return {"Authorization": f"Bearer {token}"}
def ignore(name): """ Files to ignore when diffing These are packages that we're already diffing elsewhere, or files that we expect to be different for every build, or known problems. """ # We're looking at the files that make the images, so no need to search them if name in ['IMAGES']: return Tru...
def dot(p1, p2): """ Dot product for 4-vectors of the form (E, px, py, pz). Returns: E1*E2 - p1*p2 """ return p1[0] * p2[0] - p1[1] * p2[1] - p1[2] * p2[2] - p1[3] * p2[3]
def convert_to_iris(dict_): """Change all appearances of ``short_name`` to ``var_name``. Parameters ---------- dict_ : dict Dictionary to convert. Returns ------- dict Converted dictionary. Raises ------ KeyError :obj:`dict` contains keys``'short_name'`...
def check_if_prime(number): """checks if number is prime Args: number (int): Raises: TypeError: if number of type float Returns: [bool]: if number prime returns ,True else returns False """ if type(number) == float: raise TypeError("TypeError: entered float ty...
def thresholdOutput(bInt, yInt): """ returns an output of 1 if the intensity is greater than 1% of the sum of the intensities, 0 if not. """ # Where does 0.005 come from??? if bInt > 0.005: bOutput = 1 else: bOutput = 0 if yInt > 0.005: yOutput = 1 else: y...
def error_to_win(r): """Change one's error to other's win""" flip = lambda c: c == 'x' and 'o' or 'x' if r[0] == 'error': return flip(r[1]) elif r[0] == 'ok': return r[1] else: raise RuntimeError("Invalid r[0]: %s", str(r[0]))
def embed(information:dict) -> str: """ input: item:dict ={"url":str,"text":str} """ embed_link = information["url"] block_md =f"""<p><div class="res_emb_block"> <iframe width="640" height="480" src="{embed_link}" frameborder="0" allowfullscreen></iframe> </div></p>""" return block_md
def numericalize(sequence): """Convert the dtype of sequence to int""" return [int(i) for i in sequence]
def extract_lists (phrase): """IF <phrase> = [ITEM1,ITEM2,[LIST1,LIST2]] yields [ITEM1,ITEM2,LIST1,LIST2]""" def list_of_lists (phrase): # TRUE if every element of <phrase> is a list for x in phrase: if not isinstance(x,list): return ...
def valid_sample(sample): """Check whether a sample is valid. :param sample: sample to be checked """ return (sample is not None and isinstance(sample, dict) and len(list(sample.keys())) > 0 and not sample.get("__bad__", False))
def depth(obj): """ Calculate the depth of a list object obj. Return 0 if obj is a non-list, or 1 + maximum depth of elements of obj, a possibly nested list of objects. Assume: obj has finite nesting depth @param int|list[int|list[...]] obj: possibly nested list of objects @rtype:...
def to_fahrenheit(x): """ Returns: x converted to fahrenheit The value returned has type float. Parameter x: the temperature in centigrade Precondition: x is a float """ assert type(x) == float, repr(x)+' is not a float' return 9*x/5.0+32
def bbox_for_points(points): """Finds bounding box for provided points. :type points: list or tuple :param points: sequince of coordinate points :rtype: list :return: bounding box """ xmin = xmax = points[0][0] ymin = ymax = points[0][1] for point in points: xmin = min(xmin, point[0]) xmax =...
def org_enwiki(orgname, url_map): """ """ lst = url_map.get(orgname, []) for d in lst: if "enwiki_url" in d: return d["enwiki_url"] return ""
def calculateXVertice(termA, termB): """ Calculates the value of the vertice X. """ vertice = ((-termB)/(2*termA)) return vertice
def quote(s, always=False): """Adds double-quotes to string if it contains spaces. :Parameters: s : str or unicode String to add double-quotes to. always : bool If True, adds quotes even if the input string contains no spaces. :return: If the given string contains spaces or <al...
def maskbits(x: int, n:int) -> int: """Mask x & bitmask(n)""" if n >= 0: return x & ((1 << n) - 1) else: return x & (-1 << -n)
def prepare_row(row): """Formats CSV so commas within quotes are not split upon.""" row = row.split(",") st = None proc_row = [] for i in range(len(row)): if st is None: if row[i][0] == "\"" and row[i][-1] != "\"": st = i else: pro...
def dict_from_dotted_key(key, value): """ Make a dict from a dotted key:: >>> dict_from_dotted_key('foo.bar.baz', 1) {'foo': {'bar': {'baz': 1}}} Args: key (str): dotted key value: value Returns: dict """ d = {} if '.' not in key: d[key] = ...
def escapeAndJoin(strList): """ .. deprecated:: 3.0 Do not use, will be removed in QGIS 4.0 """ from warnings import warn warn("processing.escapeAndJoin is deprecated and will be removed in QGIS 4.0", DeprecationWarning) joined = '' for s in strList: if s[0] != '-' and ' ' in s...
def w_fct(stim, color_control): """function for word_task, to modulate strength of word reading based on 1-strength of color_naming ControlSignal""" print('color control: ', color_control) return stim * (1 - color_control)
def rayTracingFileName( site, telescopeModelName, sourceDistance, zenithAngle, offAxisAngle, mirrorNumber, label, base, ): """ File name for files required at the RayTracing class. Parameters ---------- site: str South or North. telescopeModelName: str ...
def make_tuple(tuple_like): """ Creates a tuple if given ``tuple_like`` value isn't list or tuple Returns: tuple or list """ tuple_like = ( tuple_like if isinstance(tuple_like, (list, tuple)) else (tuple_like, tuple_like) ) return tuple_like
def neighbor_char(c, r): """ This function will return all the neighboring alphabet position by taking the point we needed and then ignoring the point outside the zone. ---------------------------------------------------------------------------- :param c: (int) the columns index position in the grid(list) (c, r) ...
def is_pandigital(*args): """ Check numbers is pandigital through 9. """ return '123456789'.startswith( ''.join(sorted(x for arg in args for x in str(arg))))
def make_fraud(seed, card, user, latlon): """ return a fraudulent transaction """ amount = (seed+1)*1000 payload = {"userid": user, "amount": amount, "lat": latlon[0], "lon": latlon[1], "card": card } return payload
def bits_str(bits): """Convert a set into canonical form""" return ' '.join(sorted(list(bits)))
def round_up(x, r): """ Round x up to the nearest multiple of r. Always rounds up, even if x is already divisible by r. """ return x + r - x % r
def hash_shard(word): """Assign data to servers using Python's built-in hash() function.""" return 'server%d' % (hash(word) % 4)
def countChoices(matrix, i, j): """Gives the possible Numbers at a position on a sudoku grid. """ canPick = [True for _ in range(10)] # canPick[0] = False for k in range(9): canPick[matrix[i][k]] = False for k in range(9): canPick[matrix[k][j]] = False r = i//3 c = j//3 ...