content
stringlengths
42
6.51k
def str2bool(value): """Convert a string into boolean. :Parameters: * **value** (:obj:`str`): Value to be converted to boolean. :Example: >>> pycof.str2bool('true') ... True >>> pycof.str2bool(1) ... True >>> pycof.str2bool(0) ... False :Returns...
def pointer_top(body_output, targets, model_hparams, vocab_size): """Like identity_top() with is_pointwise annotation.""" del targets, model_hparams, vocab_size # unused arg return body_output
def make_coffee(resources, menue, drink): """make a coffee and deduct from the resources""" resources['water'] -= menue[drink]['ingredients']['water'] resources['coffee'] -= menue[drink]['ingredients']['coffee'] if drink != 'espresso': resources['milk'] -= menue[drink]['ingredients']['milk...
def pay_excess(principal, minimum, remainder): """Pay any excess remaining after making minimum payments.""" excess = remainder if principal - excess <= 0: excess = principal remainder = remainder - principal else: remainder = 0 return principal - excess, minimum + excess, ...
def ktoe_to_twh(ktoe): """Conversion of ktoe to TWh Arguments ---------- ktoe : float Energy demand in ktoe Returns ------- data_gwh : float Energy demand in TWh Notes ----- https://www.iea.org/statistics/resources/unitconverter/ """ data_twh = ktoe * 0...
def ExtractWordsFromLines(lines): """Extract all words from a list of strings.""" words = set() for line in lines: for word in line.split(): words.add(word) return words
def _munge_node_attribute(node, attribute='name'): """Munge node attribute.""" if node.get(attribute) is None: return str(node) else: return node.get(attribute)
def Fib(n): """Return the n-th Fibonacci number.""" assert type(n) is int and n >= 0, "ERROR (Fib): index should be positive and integer!" return Fib(n-1) + Fib(n-2) if n > 1 else 1 if n is 1 else 0
def merge(intervals): """ intervals: list of tuples representing context windows """ ans = [] i = 1 intervals.sort() tempans = intervals[0] while i < len(intervals): # seeing if context windows overlap with each other - if they do merge them together if tempans[0]...
def strip_suffix(s, suffix): """Remove suffix frm the end of s is s = "aaa.gpg" and suffix = ".gpg", return "aaa" if s is not a string return None if suffix is not a string, return s :param str s: string to modify :param str suffix: suffix to remove :rtype: Optional[str]=None """ i...
def useful_tokens(tokens): """Gets rid of noise, where possible. Currently just removes 'AUTO CR - LOG SUMMARY' lines""" ret_tokens = [] lines = {} for token in tokens: line_key = (token['line_num'], token['par_num'], token['block_num']) if line_key not in lines: lines[line_k...
def human_tidy(agents, self_state, self_name, cube, box): """ @semantic_name: @param agents: @param self_state: @param self_name: @param cube: @return: @ontology_type cube: Cube """ return [("human_pick_cube", cube), ("human_drop_cube", box)]
def num_of_indels(locus): """Count number of indels at end sequence, and return number of bps to trim from end""" indels = 0 for ind in locus: ind = ind.split() #check if sequence ends with gaps if ind[1].endswith('-'): #Reverse sequence and count number of '-'s ...
def subscription_update_request_feedback(flag): """ The subscription message sent to the person requesting pausing or restarting the subscription. :param flag: True, means subscription should be made active, False, means subscription should be made inactive. None, means there was some error. :retur...
def _ecmaCodeTableCoordinate(column, row): """ Return the byte in 7- or 8-bit code table identified by C{column} and C{row}. "An 8-bit code table consists of 256 positions arranged in 16 columns and 16 rows. The columns and rows are numbered 00 to 15." "A 7-bit code table consists of 128 posi...
def freq_in_doc(word, doc_bow): """ Returns the number of iterations of a given word in a bag of words. """ return doc_bow.get(word, 0)
def _flatten_keys(key_seq): """returns a flat list of keys, i.e., ``('foo', 'bar')`` tuples, from a nested sequence. """ flat_keys = [] for key in key_seq: if not isinstance(key, tuple): flat_keys += _flatten_keys(key) else: flat_keys.append(key) return...
def cnf_paths_from_locs(cnf_fs, cnf_locs): """ Get paths """ cnf_paths = [] if cnf_locs: for locs in cnf_locs: cnf_paths.append(cnf_fs[-1].path(locs)) return cnf_paths
def score_substitute(a_c1, a_c2): """Score substitution of two characters. Args: a_c1 (str): first word to compare a_c2 (str): second word to compare Returns: int: 2 if the last characters of both words are equal, -3 otherwise """ return 2 if a_c1[-1] == a_c2[-1] else -3
def countNodes(root): """ Parameters ---------- root : Returns ------- """ if root is None: return 0 return countNodes(root.lesser) + countNodes(root.greater) + 1
def import_class(name): """ Import a class a string and return a reference to it. THIS IS A GIANT SECURITY VULNERABILITY. See: http://stackoverflow.com/questions/547829/how-to-dynamically-load-a-python-class """ if not isinstance(name, str): return name package = "."...
def default_medication(): """Generate default medication features. Used in case a patient has a missing medication. """ return { 'count': 0, 'boolean': False, }
def get_consensus_through_voting(seq1, weight1, seq2, weight2): """ Use majority vote. This is a temporary replacement for get_consensus_through_pbdagcon() since I don't want to deal with dependency right now. """ #pdb.set_trace() if weight1 > weight2: return seq1 else: return seq2
def find_header_index(lines): """returns a position to insert an header into a file (just before the first header, if it exists, or on the first line)""" for i,line in enumerate(lines): if line.startswith("#include"): return i return 0
def add_helpfulness(row): """ Add helpfulness scores and ratio as separate variables to a row :param row: A python dict containing data for a single review :return: A python dict containing the original data plus the number of users that rated this review as helpful, the total votes received by the ...
def _slice_at_axis(sl, axis): """ Construct tuple of slices to slice an array in the given dimension. This function is copied from numpy's arraypad.py Parameters ---------- sl : slice The slice for the given dimension. axis : int The axis to which `sl` is applied. All other...
def flatten(seq): """ For [[1, 2], [3, 4]] returns [1, 2, 3, 4]. Does not recurse. """ return [x for sub in seq for x in sub]
def json_get(item, path, default=None): """ Return the path of the field in a dict. Arguments: item (dict): The object where we want to put a field. path (unicode): The path separated with dots to the field. default: default value if path not found. Return: The value. ...
def bounding_box2D(pts): """ bounding box for the points pts """ dim = len(pts[0]) # should be 2 bb_min = [min([t[i] for t in pts]) for i in range(dim)] bb_max = [max([t[i] for t in pts]) for i in range(dim)] return bb_min[0], bb_min[1], bb_max[0] - bb_min[0], bb_max[1] - bb_min[1]
def primerDictToNEBPrimerSeq(primerDict): """turn a primer dict from primer3 in fastCloningPrimer to the NEB readdable format""" NEBPrimerString = "" for primerPairName, primerPairInfo in primerDict.items(): currentLPrimerName = str(primerPairName) + "Left" currentLPrimerSeq = primerPairInfo...
def clip(value: float, min_value: float, max_value: float) -> float: """Clip a value to the given range.""" if value < min_value: return min_value if value > max_value: return max_value return value
def merge_lines_scores(lines, scores): """ both type dict """ ret = {} for k, v in lines.items(): score_data = scores.get(k) if not score_data: score_data = [None for _ in range(5)] row = v[0] + score_data + v[1] ret[k] = row return ret
def pagination(context, page, paginator, where=None): """ Shows pagination links:: {% pagination current_page paginator %} The argument ``where`` can be used inside the pagination template to discern between pagination at the top and at the bottom of an object list (if you wish). The defau...
def inclusion_params_and_context(context, arg): """Expected inclusion_params_and_context __doc__""" return {"result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)}
def find_subroutine_call_insertion_point(lines,ifbranch,varname): """ The assumption is that the symbolic algebra optimization will always break out the function evaluation. Therefore there always is a line where the functional value is assigned to a variable. The actual functional subroutine call, at t...
def numberify(x): """convert hex numbers, return original string on failure""" try: return int(x, 16) except ValueError: return x
def get_counts_per_label(y_true, n_classes): """ Return a map of {label: number of data points with that label} for the given list of labels Parameters: - y_true: (integer) a list of labels - n_classes: (integer) the number of classes """ label_counts = [0] * n_classes for label...
def check_valid_sequence(sequence: str) -> bool: """ Check that the sequence string only contains valid sequence characters """ return set(sequence.upper()).issubset(set("WSKMYRVHDBNZNATCGU-"))
def _check_header(header): """ Check that header has the minimum mandatory fields """ # Check mandatory fields present: num_samples = 0 matching = [] mandatory_fields = ["source-ontology", "COLDATA", "VERSION"] for field in mandatory_fields: match = ([s for s in header if field i...
def party_from_president(name, year): """ Assigning political party label from president lastname. Taken from: https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States Using "?" to represent parties before 1964. """ if year < 1964: return "?" d = { "Trump": "R"...
def get_subproblems(base_elements, solutes, p_lagrange, enable_NS, enable_PF, enable_EC, **namespace): """ Returns dict of subproblems the solver splits the problem into. """ subproblems = dict() if enable_NS: subproblems["NS"] = [dict(name...
def untag(tagged_sentence): """ Remove the tag for each tagged term. :param tagged_sentence: a POS tagged sentence :type tagged_sentence: list :return: a list of tags :rtype: list of strings """ return [w for w, _ in tagged_sentence]
def format_error(string: str, is_warning: bool) -> str: """ Formats a given message in an error color using ANSI escape sequences (see https://stackoverflow.com/a/287944/5299750 and https://stackoverflow.com/a/33206814/5299750) :param string: to be printed :param is_warning: determines the color...
def get_precision(input_number): """ Return precision of input number. :param input_number: input number :type input_number: float :return: precision as int """ try: number_str = str(input_number) _, decimalpart = number_str.split(".") return len(decimalpart) exc...
def indexes_of_word(words: list, word: str): """ Return a list of indexes with the given word. """ return [i for i, s in enumerate(words) if s.lower() == word]
def add_one(data): """Adds 1 to every cell in Range""" return [[cell + 1 for cell in row] for row in data]
def get_sector_size(partition): """Return the sector size of a partition. Used by disk_io_counters(). """ try: with open("/sys/block/%s/queue/hw_sector_size" % partition, "rt") as f: return int(f.read()) except (IOError, ValueError): # man iostat states that sectors are e...
def to_csharp(bool): """ Python to C# booleans. """ return ['false', 'true'][bool]
def strToBool(s): """ Converts a string into a bool using the following sets: True: ['true', '1', 't', 'y', 'yes'] False: ['false', '0', 'f', 'n', 'no'] Throws ValueError s is neither None nor in either true or false value set. :param s: :return: True if s is in true value set, False if ...
def pack_byte_to_hn(val): """ Pack byte to network order unsigned short """ return (val << 8) & 0xffff
def get_size(bytes, suffix="B"): """ Scale bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ factor = 1024 for unit in ["", "K", "M", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{u...
def matchActor(name,targets): """ Determines whether a given actor name is one of a given list of targets @type name: str @type targets: str[] @rtype: bool """ if len(targets) == 0: # Nobody given, assume everybody is a target return True if name is None: # There'...
def is_prime(num : int) -> bool: """is_prime will return if a number is prime or not Args: num (int): the number that wil be checked if it's prime Returns: bool: True if the number is prime, false if not """ if num == 0 or num == 1: return False else: for i in r...
def add_data_to_json(json_obj, query_data, candidate_data): """Adds query and candidate datasets to json object. """ json_obj['query_data'] = query_data json_obj['candidate_data'] = candidate_data return json_obj
def validate_subject_samples_factors(mwtabfile): """Validate ``SUBJECT_SAMPLE_FACTORS`` section. :param mwtabfile: Instance of :class:`~mwtab.mwtab.MWTabFile`. :type mwtabfile: :class:`~mwtab.mwtab.MWTabFile` or :py:class:`collections.OrderedDict` """ subject_samples_factors_er...
def unpack_str(byteseq): """Unpack a byte sequence into a string.""" return byteseq.decode()
def compare_versions(version_1: str, version_2: str) -> int: """Compares two version strings with format x.x.x.x Returns: -1, if version_1 is higher than version_2 0, if version_1 is equal to version_2 1, if version_1 is lower than version_2 """ if not version_1: return 1 version_1 ...
def accuracy_metric(actual, predicted, correct=0) -> float: """calculate accuracy of the dataset comparing the actual test label vs the predicted label""" for i in range(len(actual)): if actual[i] == predicted[i]: correct += 1 return correct / len(actual) * 100.0
def get_other_title(title_to_entities_all, other_title, token_location): """Handle the case when other titles have been mentioned""" other_title_found = False if title_to_entities_all.get(token_location) is not None: other_title_found = True other_title["found"] = True other_title["l...
def euler_step(f, y, t, dt, params): """ Returns the forward euler approximation of the change in `y` over the timestep `dt` Parameters ---------- f (callable): accepts `y`, `t` and all of the parameters in `params` y (ndarray or float): current system state ...
def find_dup(arr): """This will find the duplicated int in the list""" dup = set([x for x in arr if arr.count(x) > 1]) answer = list(dup) return answer[0]
def make_mission_id(mission_definition, specifics_hash): """ Returns the string mission_id which is composed from the mission_definition and specifics_hash. """ return "%s-%s" % (mission_definition, specifics_hash)
def is_subclass(cls, subclass) -> bool: """A more robust version.""" try: return issubclass(cls, subclass) except TypeError: return False
def parse_soxi_out(cmd:bytes): """ this gross parser takes the bytes from the soxi output, decodes to utf-8, splits by the newline "\n", takes the second element of the array which is the number of channels, splits by the semi-colon ':' takes the second element which is the string of the num channe...
def single_point_crossover(population, single_point_info): """ Combine each two chromosomes in population by using single point crossover. """ crossover_points = [int(p) for p in single_point_info.split("|") if p != ''] new_population = [] for i in range(0, len(population) - 1, 2): ...
def pentagonal(n: int) -> int: """Returns the n_th pentagonal number. If fed with a negative number, it returns an extended pentagonal number. """ return n * (3 * n - 1) // 2
def Legendre_poly(n, x): """ """ if(n == 0): return 1 # P0 = 1 elif(n == 1): return x # P1 = x else: return (((2 * n)-1)*x * Legendre_poly(n-1, x)-(n-1) * Legendre_poly(n-2, x))/float(n)
def color_variant(hex_color, brightness_offset=1): """ takes a color like #87c95f and produces a lighter or darker variant """ if len(hex_color) != 7: raise Exception( "Passed %s into color_variant(), needs to be in #87c95f format." % hex_color ) rgb_hex = [hex_color[x : x + 2] f...
def search_types(params, results, meta): """ Convert Elasticsearch results into RPC results conforming to the spec for the "search_types" method. """ # Now we need to convert the ES result format into the API format search_time = results['search_time'] buckets = results['aggregations']['type...
def _is_time_between(timestamp, from_timestamp, to_timestamp): """ self-explanatory """ return (timestamp > from_timestamp) & (timestamp < to_timestamp)
def break_words(stuff): """This funciton will break up words for us.""" words = stuff.split(' ') return words
def get_dict_depth(_dict): """ Get dictionary's depth or 'nestedness' """ if isinstance(_dict, dict): return 1 + (min(map(get_dict_depth, _dict.values())) if _dict else 0) return 0
def score_global(x, y): """ Verifica o valor de scoring dos aminoacidos informados :param x: primeiro aminoacido :param y: segundo aminoacido :return: valor de scoring """ if x == y: return 5 return -4
def key_size(message): """ Calculate the desired key size in 64 byte blocks. """ return (len(message) // 64) + 1
def __trailing_newline(eof): """ Helper function returning an empty string or a newling character to append to the current output line depending on whether we want that line to be the last line in the file (eof == True) or not (eof == False). """ if eof: return "" return ...
def get_row_multiplied(row, coefficient): """multiply row elements by coefficient """ result = [] for element in row: result.append(element * coefficient) return result
def string_to_int(string): """ Convert string to int :param string: An instance of type string :return: Integer """ return int(string.replace(',', ''))
def _get_token(results): """Get the token from the property results.""" return getattr(results, 'token', None)
def hax(string: str) -> str: """ funky things in the raw data that we fix here currently for addresses only.. d is a dictionary of key-value pairs where: key is the (company number) and, value is the Registered Address of the Company with that company number """ d = {'(C2237836)': '184...
def verify_command(command): """Verify a given command is legal.""" command_length = len(command) if command_length > 0: if command_length == 1: if command[0] in ["Q", "t"]: return (command[0], None) if command_length == 2: if ((command[0] == 'S' and c...
def unwrap_args(form_query_argument_list): """Turn the serialized key/value pairs back into a dict.""" kwargs = {} for arg in form_query_argument_list: kwargs[arg['key']] = arg['value'] return kwargs
def reverse_sequence(sequence): """ Return the reverse of sequence :param sequence: either a string or Sequence object :return: the reverse string or Sequence object """ if isinstance(sequence, str): return sequence[::-1] else: raise ValueError("Cannot complement object of {...
def smart_min(v1, v2): """ Returns min value even if one of the value is None. By default min(None, x) == None per Python default behavior. """ if v1 is None: return v2 if v2 is None: return v1 return min(v1, v2)
def get_nucleotide_count(dna): """ Count the number of each nucleotide in the given DNA string. :param dna: a string of DNA :return: the number of A's, C's, G's, and T's """ a, c, g, t = 0, 0, 0, 0 for i in range(len(dna)): val = dna[i].upper() if val == 'A': ...
def safeint(x): """Converts to an integer if possible""" try: return int(x) except BaseException: return x
def parse_time(t): """ Convert time string to time for saving in django :param d: date string in "%H%M%S" :return: """ z = t.split(':') return int(z[0]) * 3600 + int(z[1]) * 60 + int(z[2])
def remove_punctuation(data): """Remove punctuation from data.""" try: if data[-1:] == ',': data = data[:-1] if data[-2:] == ' :': data = data[:-2] if data[-2:] == ' ;': data = data[:-2] if data[-2:] == ' /': data = data[:-2] ...
def _sudoku_syntax(file): """ Return the full name of the given sudoku syntax based on the base name. """ return "Packages/Sudoku/resources/syntax/%s.sublime-syntax" % file
def human_bytes(n): """ Return the number of bytes n in more human readable form. Examples: >>> human_bytes(42) '42 B' >>> human_bytes(1042) '1 KB' >>> human_bytes(10004242) '9.5 MB' >>> human_bytes(100000004242) '93.13 GB' """ if n < ...
def instanceof(value, type_): """Check if `value` is an instance of `type_`. :param value: an object :param type_: a type """ return isinstance(value, type_)
def encode_golomb(x, p): """converts a number x to a golomb-encoded array of 0's and 1's""" # quotient when dividing x by 2^p q = x >> p # q 1's and a 0 at the end result = [1] * q + [0] # the last p bits of x result += [x & (1 << (p - i - 1)) > 0 for i in range(p)] return result
def m2ft(meters: float) -> float: """ Convert meters to feet. :param float meters: meters :return: feet :rtype: float """ if not isinstance(meters, (float, int)): return 0 return meters * 3.28084
def get_url(server_name, listen_port, topic_name): """ Generating URL to get the information from namenode/namenode :param server_name: :param listen_port: :param topic_name: :return: """ if listen_port < 0: print ("Invalid Port") exit() if not server_n...
def _build_localename(localetuple): """ Builds a locale code from the given tuple (language code, encoding). No aliasing or normalizing takes place. """ try: language, encoding = localetuple if language is None: language = 'C' if encoding is None: ...
def process_immediate(immediate): """ Returns a integer object from a string object. """ if not isinstance(immediate, str): raise TypeError('Immediate must be a String object.') if immediate.startswith("0x"): return int(immediate, 16) else: return int(immediate)
def note_to_freq(note): """ Return the frequency value for a given MIDI note value. """ return 440.0 * pow(2.0, (note - 69) / 12.0)
def get_reads(seq_file): """ Creates reads of according to the parameters in the argument input: The full sequence as a string output: reads in string format INSIDE a list called "my_reads" """ my_reads = [] read_length = 150 overlap = 50 read_pos = 0 # have verified that the d...
def extract_annealing_log(log): """ Parses a VPR log line by line. Extracts the table with simulated annealing data. Returns the table header and data line lists as separate. """ # Find a line starting with "# Placement" for i, line in enumerate(log): if line.startswith("# Placement"): ...
def creates_cycle(connections, test): """ Returns true if the addition of the 'test' connection would create a cycle, assuming that no cycle already exists in the graph represented by 'connections'. """ i, o = test if i == o: return True visited = {o} while True: num_add...
def is_key(config) -> list: """Check for interface key, two possibilities""" try: int_type = config.get('name', {}).get('#text', {}) except AttributeError: int_type = config['name'] return int_type