content
stringlengths
42
6.51k
def begin_import_marker(import_file: str) -> str: """ Creates an begin import marker based on the import file path. :param import_file: The path of the import file. :returns: The begin import marker. """ return f'# nb--import-begin "{import_file}"\n'
def main(textlines, messagefunc, config): """ KlipChop func to to convert CSV into seperate lines """ result = list() count = 0 for line in textlines(): if line not in result: result.extend(line.split(config['separator'])) count += 1 if config['sort']: ...
def ODEStep(u, um, t, dt, F): """2nd order explicit scheme for u''=F(u,t).""" up = 2*u - um + dt*dt*F(u, t) return up
def __validate_integer_fields(value: int, error_msg: str) -> int: """Validate integer values from a dictionary. Parameters ---------- value : int Value to be validated. error_msg : str Error message for an invalid value. Returns ------- int Validated value. ...
def get(identifier): """Returns an activation function from a string. Returns its input if it is callable (already an activation for example). Args: identifier (str or Callable or None): the activation identifier. Returns: :class:`nn.Module` or None """ if identifier is None: ...
def surround(text: str, tag: str): """Surround provided text with a tag. :param text: text to surround :param tag: tag to surround the text with :return: original text surrounded with tag """ return "<{tag}>{text}</{tag}>".format(tag=tag, text=text)
def hasNonPropertyAttr(obj, attr): """Return true if obj has a non-property attribute 'attr'.""" if hasattr(obj, attr) and \ (not hasattr(type(obj), attr) or not isinstance(getattr(type(obj), attr), property)): return True else: return False
def _is_valid_password(password): """ Evaluates if a given password is valid. Its length must be higher than 0. :param str password: Password to be evaluated. :return: Returns True if the password is valid and False otherwise. :rtype: bool """ if password is None or len(password) == 0: ...
def generate_urls(layer, unit, k): """Generate fake URLs for the given layer and unit.""" return [ f'https://images.com/{layer}/{unit}/im-{index}.png' for index in range(k) ]
def to_byte(val): """Cast an int to a byte value.""" return val.to_bytes(1, 'little')
def reverse_complement(dna_sequence): """Return reverse complement DNA sequence.""" complement = [{'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}[base] for base in dna_sequence] reverse_complement = reversed(complement) return ''.join(reverse_complement)
def idx2coord(vec_idx): """Convert row index in response data matrix into 3D coordinate in (original) ROI volume. """ data_size = (18, 64, 64) coord_z = vec_idx % data_size[2] coord_x = vec_idx / (data_size[1]*data_size[2]) coord_y = (vec_idx % (data_size[1]*data_size[2])) / data_size[2] ...
def add_n_smooth(identifier, smooth_input, smooth_time, initial_value, order, subs, subscript_dict): """ Constructs stock and flow chains that implement the calculation of a smoothing function. Parameters ---------- identifier: basestring the python-safe name of the sto...
def add_to_list_if_new(dep_list, new_dep): """ Add new_dep to dep_list if not already present """ new_dep_in_list = False for dep in dep_list: if dep == new_dep: new_dep_in_list = True exit if not new_dep_in_list: dep_list.append(new_dep) return dep_li...
def rescale_values(x, input_min=-1, input_max=1, output_min=0, output_max=255): """ Rescale the range of values of `x` from [input_min, input_max] -> [output_min, output_max]. """ assert input_max > input_min assert output_max > output_min return (x - input_min) * (output_max - output_min) / (...
def perim_area_centroid(perim): """Calculates the area and centroid of sections defined by closed 2D polylines (a list of 2D tuples - e.g. [(x1, y1), (x2, y2), ...]). It will also accept 3D coordinates [(x1, y1, z1), (x2, y2, z2), ...] but ignores the z-coordinate in calculating the area (and cen...
def multi_bracket_validation(input): """ should take a string as its only argument, and should return a boolean representing whether or not the brackets in the string are balanced """ if ('(' in input and ')' not in input) or (')' in input and '(' not in input): return False elif ('{' in ...
def _pytest_get_option(config, name, default): """Get pytest options in a version independent way, with allowed defaults.""" try: value = config.getoption(name, default=default) except Exception: try: value = config.getvalue(name) except Exception: return def...
def list_is_unique(ls): """Check if every element in a list is unique Parameters ---------- ls: list Returns ------- bool """ return len(ls) == len(set(ls))
def update_max_for_sim(m, init_max, max_allowed): """ updates the current maximal number allowed by a factor :param m: multiplication factor :param init_max: initial maximum chromosome number allowed :param max_allowed: previous maximum chromosome number allowed :return: the current updated maxi...
def merge_sort2(lst): """ """ if len(lst) <= 1: return lst def merge(left, right): x = 0 y = 0 z_list = [] while len(left) > x and len(right) > y: if left[x] > right[y]: z_list.append(right[y]) y += 1 else: ...
def check_param_validation(parsed_param, valid_values): """Check whether parsed_param contains any valid param value lised in valid_values. if yes, return the valid param value appearing in parsed_param; if no, return False""" if not valid_values: return parsed_param for value in valid_valu...
def threshold_matrix(threshold, score_matrix): """Returns a matrix indicating which pairs are good according to the given threshold""" matrix = [] for row in score_matrix: scores = [] for entry in row: if entry >= threshold: scores.append(1) else: ...
def convertd2b_(res, decimals): """Round the result.""" cad = str(round(res, decimals)) return cad
def validate(s): """Validate that a given square is valid..""" # START SOLUTION # Base case: it's a simple square, so as long as it's either 0 or 1 # it's valid. if type(s) == int: return s == 0 or s == 1 # Base case: if not a list of 4, it's invalid if type(s) != list or len(s)...
def _get_model(vehicle): """Clean the model field. Best guess.""" model = vehicle['model'] model = model.replace(vehicle['year'], '') model = model.replace(vehicle['make'], '') return model.strip().split(' ')[0]
def get_numeric_value(string_value): """ parses string_value and returns only number-like part """ num_chars = ['.', '+', '-'] number = '' for c in string_value: if c.isdigit() or c in num_chars: number += c return number
def time_formatter(milliseconds: int) -> str: """Inputs time in milliseconds, to get beautified time, as string""" seconds, milliseconds = divmod(int(milliseconds), 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) tmp = ( ...
def group(requestContext, *seriesLists): """ Takes an arbitrary number of seriesLists and adds them to a single seriesList. This is used to pass multiple seriesLists to a function which only takes one """ seriesGroup = [] for s in seriesLists: seriesGroup.extend(s) return seriesGroup
def parse_mask(value, mask_enum): """Parse a mask into indivitual mask values from enum. :params ``int`` value: (Combined) mask value. :params ``enum.IntEnum`` mask_enum: Enum of all possible mask values. :returns: ``list`` - List of enum values and optional remainder. """ ...
def color_negative_red(value): """ Colors elements in a dateframe green if positive and red if negative. Does not color NaN values. """ if value < 0: color = "red" elif value > 0: color = "green" else: color = "black" return "color: %s" % color
def fib(n): """prints fibonacci sequence pass a number to the function fib(x) """ a, b = 0, 1 #Note multiple assignment! counter = 1 while counter < n: print (a, end=' ') a, b = b, a+b counter += 1 print(a) print(__name__) return(0)
def intersection(lst1, lst2): """returns the intersection between two lists""" if (lst1 == None or lst2 == None): return [] lst3 = [value for value in lst1 if value in lst2] return lst3
def _count_dependencies(graph): """Assigns the total number of dependencies to each node.""" dependency_counter = {parent: 0 for parent in graph} for current_node in graph: stack = [[current_node, iter(graph[current_node])]] visited = set() visited.add(current_node) while sta...
def y(filen): """ Returns the integer in the filename 'filen'. For example, for 'image_13.npy', this function returns 13 as an integer """ cname = '' for c in filen: if c.isdigit(): cname += c return int(cname)
def create_image(src, size=None): """Creates HTML image tag. Optionaly, twitter size param can be passed.""" if size is None: return "<image src=\"{}\" />".format(src) else: return "<image src=\"{}:{}\" />".format(src, size)
def order_columns(pks, columns): """ Orders column list to include primary keys first and then non primary key columns :param pks: primary key list :param columns: columns :return: primary key columns + non primary key columns ordered """ pk_list = [] non_pk_list = [] for c in c...
def cleanfield(value): """ remove spaces """ # values like 0 should not be converted to None if value is None or value.strip() == "": return None value = str(value) value = value.strip() return value
def note2num(note_str): """ The function NOTE2NUM takes in one string called NOTE_STR and returns the tone number associated to the given note. """ # Below is the note dictionary. We will add to this as # we process each jazz standard. note_list = {'C':0, 'C#': 1, 'D-':1, 'D':2, 'D#':3, 'E-':3, 'E':4, 'E#':...
def float2latex(f, ndigits=1): """ USAGE ----- texstr = float2latex(f, ndigits=1) Converts a float input into a latex-formatted string with 'ndigits' (defaults to 1). Adapted from: http://stackoverflow.com/questions/13490292/format-number-using-latex-notation-in-python """ float_str = "{0:.%se}"%ndigits fl...
def get_help(format, tool_name, rule_id, test_name, issue_dict): """ Constructs a full description for the rule :param format: text or markdown :param tool_name: :param rule_id: :param test_name: :param issue_dict: :return: Help text """ issue_text = issue_dict.get("issue_text",...
def _name_clash(candidate, path_list, allowed_occurences=1): """Determine if candidate leads to a name clash. Args: candidate (tuple): Tuple with parts of a path. path_list (list): List of pathlib.Paths. allowed_occurences (int): How often a name can occur before we call it a clash. ...
def _get_timeout_ms(timeout, payload_size): """Conservatively assume minimum 5 seconds or 3 seconds per 1MB.""" if timeout is not None: return int(1000 * timeout) return int(1000 * max(3 * payload_size / 1024 / 1024, 5))
def parse_port_pin(name_str): """Parses a string and returns a (port-num, pin-num) tuple.""" if len(name_str) < 3: raise ValueError("Expecting pin name to be at least 3 charcters.") if name_str[0] != 'P': raise ValueError("Expecting pin name to start with P") if name_str[1] < 'A' or name...
def _digi_bounds(fmt): """ Return min and max digital values for each format type. Parmeters --------- fmt : str, list The WFDB dat format, or a list of them. Returns ------- tuple (int, int) The min and max WFDB digital value per format type. """ if isinstance...
def drill_for_value(record, fields): """Descends into record using an array of fields, returning final value or None""" result = record for f in fields: if result is None: break else: result = result.get(f) return result
def solution(n): """Returns the largest palindrome made from the product of two 3-digit numbers which is less than n. >>> solution(20000) 19591 >>> solution(30000) 29992 >>> solution(40000) 39893 """ # fetchs the next number for number in range(n - 1, 10000, -1): # ...
def max_hcc_value(nelem, nlayers, slope): """Computes the correct hcc value""" dx = 1.0/nelem dz = 1.0/nlayers hcc = slope*dx/dz return hcc
def duration_cost(y, y_pred): """" A Loss function for duration costs """ return (y - y_pred)**2
def postprocess_html(html, metadata): """Returns processed HTML to fit into the slide template format.""" if metadata.get('build_lists') and metadata['build_lists'] == 'true': html = html.replace('<ul>', '<ul class="build">') html = html.replace('<ol>', '<ol class="build">') return html
def check_image_extension(filename): """Checks filename extension.""" ext = ['.jpg', '.jpeg', '.png'] for e in ext: if filename.endswith(e): return True return False
def group_mod(group_id, gtype, buckets): """ group mod """ return dict( type=gtype, group_id=group_id, buckets=buckets() if callable(buckets) else buckets, )
def set_difference(tree, context, attribs): """A meta-feature that will produce the set difference of two boolean features (will have keys set to 1 only for those features that occur in the first set but not in the second). @rtype: dict @return: dictionary with keys for key occurring with the first...
def _value_properties_are_referenced(val): """ val is a dictionary :param val: :return: True/False """ if ((u'properties' in val.keys()) and (u'$ref' in val['properties'].keys())): return True return False
def linkers(sequence_descriptors): """Provide possible linker component input data.""" return [ { "component_type": "linker_sequence", "linker_sequence": sequence_descriptors[0] }, { "component_type": "linker_sequence", "linker_sequence": s...
def knuth_morris_pratt(s, t): """Find a substring by Knuth-Morris-Pratt :param s: the haystack string :param t: the needle string :returns: index i such that s[i: i + len(t)] == t, or -1 :complexity: O(len(s) + len(t)) """ assert t != '' len_s = len(s) len_t = len(t) r = [0] * l...
def _invalid_particle_errmsg(argument, mass_numb=None, Z=None): """ Return an appropriate error message for an `~plasmapy.utils.InvalidParticleError`. """ errmsg = f"The argument {repr(argument)} " if mass_numb is not None or Z is not None: errmsg += "with " if mass_numb is not None:...
def _standardize_markups(markups): """ When terminals dont support the extended set of markup values """ newmarkups = [] if markups: if not isinstance(markups, list): markups = [markups] for markup in markups: if markup > 90: newmarkups.append(...
def parse_tuple(my_str): """ Parse input parameters which can be tuples. """ # remove any kind of parenthesis for c in (")", "]", "}"): my_str = my_str.rstrip(c) for c in ("(", "[", "{"): my_str = my_str.lstrip(c) # split tuple elements if any str_list = my_str.split(",")...
def get_file(filename, result): """Get a file by its filename from the results list.""" return next((f for f in result if f['filename'] == filename), None)
def cpp_type_name(type_as_str): """Returns a human readable form of the cpp type.""" return { 'uint8_t': 'UInt8', 'uint16_t': 'UInt16', 'uint32_t': 'UInt32', 'uint64_t': 'UInt64', 'int8_t': 'Int8', 'int16_t': 'Int16', 'int32_t': 'Int32', 'int64_t': 'Int64', 'bo...
def response_plain_text_promt(output, reprompt_text, endsession): """ create a simple json plain text response """ return { 'outputSpeech': { 'type': 'PlainText', 'text': output }, 'reprompt': { 'outputSpeech': { 'type': 'PlainText', 'text': reprompt_...
def filter_empty(input_list, target_list): """Filter empty inputs or targets Arguments: input_list {list} -- input list target_list {list} -- target list Returns: input_list, target_list -- data after filter """ return_input, return_target = [], [] for inp, tar in zip(i...
def _process_app_path(app_path): """ Return an app path HTML argument to add to a Bokeh server URL. Args: app_path (str) : The app path to add. If the app path is ``/`` then it will be ignored and an empty string returned. """ if app_path == "/": return "" ...
def encode_string_to_url(str): """ takes as string (like a name) and replaces the spaces for underscores to make a string for a url :param str: string :return: encoded string with underscores for spaces >>> encode_string_to_url('hello') 'hello' >>> encode_string_to_url('hello world') 'hello_...
def formatted_number(number): """try to format a number to formatted string with thousands""" try: number = int(number) if number < 0: return '-' + formatted_number(-number) result = '' while number >= 1000: number, number2 = divmod(number, 1000) ...
def obj_to_dict(obj, *args, _build=True, _module=None, _name=None, _submodule=None, **kwargs): """Encodes an object in a dictionary for serialization. Args: obj: The object to encode in the dictionary. Other parameters: _build (bool): Whether the object is to be built on de...
def as_unicode(b): """ Convert a byte string to a unicode string :param b: byte string :return: unicode string """ try: b = b.decode() except (AttributeError, UnicodeDecodeError): pass return b
def largest_product(number, series): """Calculate the largest product from continuous substring of given length.""" if len(number) < series or series < 0: raise ValueError if not series: return 1 maximum = 0 for i in range(len(number) + 1 - series): partial_sum = int(numb...
def uniquecounts(rows): """ Returns the belonging of the instances to the classes param rows -- the dataset in the current branch, the class is the argument in the last column """ results = {} for row in rows: r = row[len(row) - 1] if r not in results: results[r] = 0 results[r]...
def get_positions(start_idx, end_idx, length): """ Get subj/obj position sequence. """ return list(range(-start_idx, 0)) + [0]*(end_idx - start_idx + 1) + list(range(1, length-end_idx))
def invert_mask(bin_mask: str) -> str: """ Return inverted binary mask from binary mask (bin_mask). >>> invert_mask('11111111.11111111.11111111.00000000') '00000000.00000000.00000000.11111111' """ inverted_mask = '' for char in bin_mask: if char == "1": inverted_mask +=...
def score_to_flag(score: float): """Classify an inappropriateness probability into discreet categories. "param score: float (0.0 -> 1.0), required. Returns: int: 0 = OK, 1 = REVIEW, 2 = BLOCK """ assert isinstance(score, float), f'score type ({type(score)}) not float.' assert score >= 0.0 ...
def test_for_blank_line(source: str) -> bool: """ Returns True if 'source' is effectively a blank line, either "\n", " ", or "", or any combination thereof. Returns False, otherwise. """ return not bool(source.strip())
def sql_cleaner(s): """Replace period and space with underscore Args: s (string): string to be cleaned Returns: string: cleaned sql string """ return s.replace(".","_").replace(" ","_")
def clean_up_spacing(sentence: str) -> str: """Clean up leading and trailing space characters from the string. :param sentence: str - a sentence to clean of leading and trailing space characters. :return: str - a sentence that has been cleaned of leading and trailing space characters. """ return s...
def wfc3_biasfile_filter(kmap): """Filter to customize WFC3 BIASFILE for hst_gentools/gen_rmap.py. Adds precondition_header() hook to rmap header. Driven by CDBS special case code. """ header_additions = { "hooks" : { "precondition_header" : "precondition_header_wfc3_biasfile_...
def predecessors_query(var_name, node_id, node_label, edge_label, predecessor_label=None): """Generate query for getting the ids of all the predecessors of a node. Parameters ---------- var_name Name of the variable corresponding to the node to match node_id I...
def char2code(c): """Convert character to unicode numeric character reference. """ try: return "&#%03d;" % ord(c) except Exception: # fallback; pylint: disable=broad-except return c
def write_file(file_to_write, text): """Write a file specified by 'file_to_write' and returns (True,NOne) in case of success or (False, <error message>) in case of failure""" try: f = open(file_to_write, 'w') f.write(text) f.close() except Exception as e: return (False, str(e...
def get_fashion_mnist_labels(labels): #@save """Return text labels for the Fashion-MNIST dataset.""" text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot'] return [text_labels[int(i)] for i in labels]
def two_arrays(k, A, B): """Hackerrank Problem: https://www.hackerrank.com/challenges/two-arrays/problem Consider two n-element arrays of integers, A = [A[0], A[1], ...., A[n-1]] and B = [B[0], B[1], ..., B[n-1]]. You want to permute them into some A' and B' such that the relation A'[i] + B'[i] >= k holds ...
def matrix_to_string(matrix, header): """ Note: this function is from: http://mybravenewworld.wordpress.com/2010/09/19/print-tabular-data-nicely-using-python/ i modified it a bit. ;-) Return a pretty, aligned string representation of a nxm matrix. This representation can be used to print any tabular data, suc...
def build_error_msg(error, code=10): """Builds an error message to add to the queue""" msg = { 'jsonrpc': '2.0', 'error': { 'code': code, 'message': f'{error}' }, 'id': 'app_error' } return msg
def from_wandb_format(config: dict) -> dict: """ Create a usable config from the wandb config format. Args: config: The config to convert. Returns: The converted config. """ wandb_config = {} for key, value in config.items(): if '.' in key: sub_keys = ke...
def clean_name(s): """Strip accents and remove interpunctuation.""" import unicodedata new = s.split("-")[0] return ''.join(c for c in unicodedata.normalize('NFD', new) if unicodedata.category(c) != 'Mn')
def next_with_custom_error(iterator, custom_error, *args): """Get next element of iterator and call a custom function when failing """ try: return next(iterator, None) except Exception as error: custom_error(error, *args) raise Exception(error)
def fib(n): """Print the Fibonacci series up to n.""" a, b = 0, 1 c = [] while b < n: c.append(b) a, b = b, a + b return c
def irb_decay_to_gate_error(irb_decay: float, rb_decay: float, dim: int): """ Eq. 4 of [IRB]_, which provides an estimate of the error of the interleaved gate, given both the observed interleaved and standard decay parameters. :param irb_decay: Observed decay parameter in irb experiment with desired ga...
def extract_tables_from_query(sql_query: str): """ return a list of table_names """ return [word for word in sql_query.split(" ") if len(word.split(".")) == 3]
def convert_to_resource_name(string): """ Deletes commas and equal signs, replaces colons with dashes and * with "any" """ return ( string.replace(":", "-").replace(",", "").replace("=", "").replace("*", "any") )
def _parse_version(version): """Parses a VHDL version string or int, 2- or 4-digit style, to a full 4-digit version identifier integer.""" if version is None: return None version = int(version) if version < 70: version += 2000 elif version < 100: version += 1900 retur...
def hello(name): """ Custom function. """ return {"text": "Hello, {}".format(name)}
def has_scheduled_methods(cls): """Decorator; use this on a class for which some methods have been decorated with :func:`schedule` or :func:`schedule_hint`. Those methods are then tagged with the attribute `__member_of__`, so that we may serialise and retrieve the correct method. This should be consider...
def tag_contents_xpath(tag, content): """Constructs an xpath matching element with tag containing content""" content = content.lower() return '//{}[contains(translate(*,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz"),"{}")]'.format(tag, content)
def P_Murn(V,a): """ As :py:func:`E_MurnV` but input parameters are given as a single list *a=[a0,a1,a2,a3]* and it returns the pressure not the energy from the EOS. """ return a[2]/a[3]*(pow(a[1]/V,a[3])-1.0)
def pullCountryName(countryObj): """ Pull out the country name from a country id. If there's no "name" property in the object, returns null """ try: return(countryObj['name']) except: pass
def build_note(text, level=1, limit=180, strip=True, keyword="NOTE"): """ Format a note for gedcom output """ note = [] key = int(level) tag = keyword data = text if strip: data = data.strip() while data != "": index = limit if len(data) < limit: i...
def isAncestor(types, name, base): """ Returns true if 'base' is an ancestor of 'name'. Particularly useful for checking if a given Vulkan type descends from VkDevice or VkInstance. """ if name == base: return True type = types.get(name) if type is None: return False pare...
def lookuptable_decoding(training_results, real_results): """ Calculates the logical error probability using postselection decoding. This postselects all results with trivial syndrome. Args: training_results: A results dictionary, as produced by the `process_results` method of a cod...