seed
stringlengths
1
14k
source
stringclasses
2 values
def documentize_sequence(seqs, tag, nt_seq): """This function converts raw nucleotide or amino acid sequences into documents that can be encoded with the Keras Tokenizer(). If a purification tag is supplied, it will be removed from the sequence document. """ # setup 'docs' for use with Tokenizer ...
bigcode/self-oss-instruct-sc2-concepts
def _alg(elt): """ Return the hashlib name of an Algorithm. Hopefully. :returns: None or string """ uri = elt.get('Algorithm', None) if uri is None: return None else: return uri
bigcode/self-oss-instruct-sc2-concepts
def wavelength_range(ini_wl, last_wl, step=1, prefix=''): """Creates a range of wavelengths from initial to last, in a defined nanometers step.""" return [f'{prefix}{wl}' for wl in range(ini_wl, last_wl + 1, step)]
bigcode/self-oss-instruct-sc2-concepts
def make_peak(width:int, height:float=100) -> list: """ This is an accessory function that generates a parabolic peak of width and height given in argments. width: integer width of the peak height: float height of peak Returns: list of values of the peak """ rightSide = [-x**2 for x i...
bigcode/self-oss-instruct-sc2-concepts
def filter_inputs(db, measure_inputs, retry=False): """ Filter a measure_inputs batch based on saved db results Parameters ---------- db: Database database object measure_inputs: Array of MeasureInput measure_inputs as expected in measure_batch retry: bool whether to...
bigcode/self-oss-instruct-sc2-concepts
def consume_next_text(text_file): """Consumes the next text line from `text_file`.""" idx = None text = text_file.readline() if text: tokens = text.strip().split() idx = tokens[0] tokens.pop(0) text = " ".join(tokens) return idx, text
bigcode/self-oss-instruct-sc2-concepts
def osavi(b4, b8): """ Optimized Soil-Adjusted Vegetation Index \ (Rondeaux, Steven, and Baret, 1996). .. math:: OSAVI = 1.16 * b8 - (b4 / b8) + b4 + 0.16 :param b4: Red. :type b4: numpy.ndarray or float :param b8: NIR. :type b8: numpy.ndarray or float :returns OSAVI: Index value ...
bigcode/self-oss-instruct-sc2-concepts
def _build_mix_args(mtrack, stem_indices, alternate_weights, alternate_files, additional_files): """Create lists of filepaths and weights to use in final mix. Parameters ---------- mtrack : Multitrack Multitrack object stem_indices : list stem indices to include ...
bigcode/self-oss-instruct-sc2-concepts
def is_str_int_float_bool(value): """Is value str, int, float, bool.""" return isinstance(value, (int, str, float))
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import Union def to_int_if_bool(value: Any) -> Union[int, Any]: """Transforms any boolean into an integer As booleans are not natively supported as a separate datatype in Redis True => 1 False => 0 Args: value (Union[bool,Any]): A boolean val...
bigcode/self-oss-instruct-sc2-concepts
import fnmatch def ExcludeFiles(filters, files): """Filter files based on exclusions lists Return a list of files which do not match any of the Unix shell-style wildcards provided, or return all the files if no filter is provided.""" if not filters: return files match = set() for file_filter in filte...
bigcode/self-oss-instruct-sc2-concepts
def get_object_name(file_name): """ Get object name from file name and add it to file YYYY/MM/dd/file """ return "{}/{}/{}/{}".format(file_name[4:8],file_name[8:10],file_name[10:12], file_name)
bigcode/self-oss-instruct-sc2-concepts
def binto(b): """ Maps a bin index into a starting ray index. Inverse of "tobin(i)." """ return (4**b - 1) // 3
bigcode/self-oss-instruct-sc2-concepts
def _list_at_index_or_none(ls, idx): """Return the element of a list at the given index if it exists, return None otherwise. Args: ls (list[object]): The target list idx (int): The target index Returns: Union[object,NoneType]: The element at the target index or None """ if ...
bigcode/self-oss-instruct-sc2-concepts
def find_result_node(desc, xml_tree): """ Returns the <result> node with a <desc> child matching the given text. Eg: if desc = "text to match", this function will find the following result node: <result> <desc>text to match</desc> </result> Parameters ----- x...
bigcode/self-oss-instruct-sc2-concepts
def sort_by_pitch(sounding_notes): """ Sort a list of notes by pitch Parameters ---------- sounding_notes : list List of `VSNote` instances Returns ------- list List of sounding notes sorted by pitch """ return sorted(sounding_notes, key=lambda x: x.pitch)
bigcode/self-oss-instruct-sc2-concepts
def check_clusters(labels_true_c, labels_pred_c): """ Check that labels_true_c and labels_pred_c have the same number of instances """ if len(labels_true_c) == 0: raise ValueError("labels_true_c must have at least one instance") if len(labels_pred_c) == 0: raise ValueError("labe...
bigcode/self-oss-instruct-sc2-concepts
def observed_species(counts): """Calculates number of distinct species.""" return (counts!=0).sum()
bigcode/self-oss-instruct-sc2-concepts
import torch def to_numpy(tensor): """ Converting tensor to numpy. Args: tensor: torch.Tensor Returns: Tensor converted to numpy. """ if not isinstance(tensor, torch.Tensor): return tensor return tensor.detach().cpu().numpy()
bigcode/self-oss-instruct-sc2-concepts
def lox_to_hass(lox_val): """Convert the given Loxone (0.0-100.0) light level to HASS (0-255).""" return (lox_val / 100.0) * 255.0
bigcode/self-oss-instruct-sc2-concepts
def bits_to_int(bits: list, base: int = 2) -> int: """Converts a list of "bits" to an integer""" return int("".join(bits), base)
bigcode/self-oss-instruct-sc2-concepts
def _date_proximity(cmp_date, date_interpreter=lambda x: x): """_date_proximity providers a comparator for an interable with an interpreter function. Used to find the closest item in a list. If two dates are equidistant return the most recent. :param cmp_date: date to compare list against :par...
bigcode/self-oss-instruct-sc2-concepts
def rescale(ys, ymin=0, ymax=1): """ Return rescaling parameters given a list of values, and a new minimum and maximum. """ bounds = min(ys), max(ys) ys_range = bounds[1] - bounds[0] new_range = ymax - ymin ys_mid = sum(bounds)*.5 new_mid = sum([ymax, ymin])*.5 scale = float(new_range)...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import shlex def str_command(args: List[str]) -> str: """ Return a string representing the shell command and its arguments. :param args: Shell command and its arguments :return: String representation thereof """ res = [] for arg in args: if "\n" in arg: ...
bigcode/self-oss-instruct-sc2-concepts
def fib_memo(n, memo=None): """ The standard recursive definition of the Fibonacci sequence to find a single Fibonacci number but improved using a memoization technique to minimize the number of recursive calls. It runs in O(n) time with O(n) space complexity. """ if not isinstance(n, int): ...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_logger(name): """ Proxy to the logging.getLogger method. """ return logging.getLogger(name)
bigcode/self-oss-instruct-sc2-concepts
def chroma_correlate(Lstar_P, S): """ Returns the correlate of *chroma* :math:`C`. Parameters ---------- Lstar_P : numeric *Achromatic Lightness* correlate :math:`L_p^\star`. S : numeric Correlate of *saturation* :math:`S`. Returns ------- numeric Correlate ...
bigcode/self-oss-instruct-sc2-concepts
def find_median(quantiles): """Find median from the quantile boundaries. Args: quantiles: A numpy array containing the quantile boundaries. Returns: The median. """ num_quantiles = len(quantiles) # We assume that we have at least one quantile boundary. assert num_quantiles > 0 median_index = ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import string def guess_pdb_type(pdb_file: str) -> str: """Guess PDB file type from file name. Examples -------- >>> _guess_pdb_type('4dkl.pdb') 'pdb' >>> _guess_pdb_type('/tmp/4dkl.cif.gz') 'cif' """ for suffix in reversed(Path(pdb_file).suffixes): ...
bigcode/self-oss-instruct-sc2-concepts
import re def replace_text(input_str, find_str, replace_str, ignore_case=False, regex=True, quiet=True): """Find and replace text in a string. Return the new text as a string. Arguments: input_str (str) -- the input text to modify find_str (str) -- the text to find in the input text replace_str (str) -- ...
bigcode/self-oss-instruct-sc2-concepts
async def _verify_provision_request(request, params): """Verifies a received 'provision' REST command. Args: request (aiohttp.Web.Request): The request from the client. params (dict-like): A dictionary like object containing the REST command request parameters. Returns: (boolean, s...
bigcode/self-oss-instruct-sc2-concepts
def verify_filename(filename: str) -> str: """ Check file name is accurate Args: filename (str): String for file name with extension Raises: ValueError: Provide filename with extensions ValueError: Specify a length > 0 Returns: str: Verified file name """ if le...
bigcode/self-oss-instruct-sc2-concepts
def _batchwise_fn(x, y, f): """For each value of `x` and `y`, compute `f(x, y)` batch-wise. Args: x (th.Tensor): [B1, B2, ... , BN, X] The first tensor. y (th.Tensor): [B1, B2, ... , BN, Y] The second tensor. f (function): The function to apply. Returns: (th.Tensor): [B1, B...
bigcode/self-oss-instruct-sc2-concepts
def _pairs(items): """Return a list with all the pairs formed by two different elements of a list "items" Note : This function is a useful tool for the building of the MNN graph. Parameters ---------- items : list Returns ------- list list of pairs formed by two dif...
bigcode/self-oss-instruct-sc2-concepts
def dt_minutes(dt): """Format a datetime with precision to minutes.""" return dt.strftime('%Y-%m-%d %H:%M')
bigcode/self-oss-instruct-sc2-concepts
def baryocentric_coords(pts,pt): """See e.g.: http://en.wikipedia.org/wiki/Barycentric_coordinate_system_%28mathematics%29""" xs,ys=list(zip(*pts)) x,y=pt det=(ys[1]-ys[2])*(xs[0]-xs[2])+(xs[2]-xs[1])*(ys[0]-ys[2]) l1=((ys[1]-ys[2])*(x-xs[2])+(xs[2]-xs[1])*(y-ys[2]))/float(det) l2=((ys...
bigcode/self-oss-instruct-sc2-concepts
def read_file(filename): """Returns the contents of a file as a string.""" return open(filename).read()
bigcode/self-oss-instruct-sc2-concepts
def create_dict_keyed_by_field_from_items(items, keyfield): """ given a field and iterable of items with that field return a dict keyed by that field with item as values """ return {i.get(keyfield): i for i in items if i and keyfield in i}
bigcode/self-oss-instruct-sc2-concepts
def get_item(value: dict, key: str): """Returns a value from a dictionary""" return value.get(key, None)
bigcode/self-oss-instruct-sc2-concepts
import re def camelcase(string, uppercase=True): """Converts a string to camelCase. Args: uppercase (bool): Whether or not to capitalize the first character """ if uppercase: return re.sub(r'(?:^|_)(.)', lambda s: s.group(1).upper(), string) else: return string[0].lower() ...
bigcode/self-oss-instruct-sc2-concepts
def read_file(file_path): """Loads raw file content in memory. Args: file_path (str): path to the target file. Returns: bytes: Raw file's content until EOF. Raises: OSError: If `file_path` does not exist or is not readable. """ with open(file_path, 'rb') as byte_file: ...
bigcode/self-oss-instruct-sc2-concepts
def Annotation(factories, index_annotations): """Create and index an annotation. Looks like factories.Annotation() but automatically uses the build() strategy and automatically indexes the annotation into the test Elasticsearch index. """ def _Annotation(**kwargs): annotation = factori...
bigcode/self-oss-instruct-sc2-concepts
def check_hermes() -> bool: """ Check if hermes-parser is available on the system.""" try: return True except ImportError: return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def _is_in_range(a_list: list, min: Optional[float] = None, max: Optional[float] = None) -> bool: """ Return True if `a_list` ontains values between `min` and `max`, False otherwise """ for el in a_list: if min is not None: ...
bigcode/self-oss-instruct-sc2-concepts
def calculateAvgMass(problemFile,windno): """ Calculate the average mass of a winds flow Inputs: - dict problemFile: problem file, containing mass fractions - int windno: wind number, counting from 1 Outputs: - avgMass: average mass of particles in wind (g) """ protonmass = 1.6726219e-24 ...
bigcode/self-oss-instruct-sc2-concepts
def get_reorg_matrix(m, m_size, transition_state_nb): """ Reorder the matrix to only keep the rows with the transition states By storing the new order in an array, we can have a mapping between new pos (idx) and old pos (value) For example reorg_states = [2,3,1,0] means the first new row/col was in posi...
bigcode/self-oss-instruct-sc2-concepts
import time def _get_time_diff_to_now(ts): """Calculate time difference from `ts` to now in human readable format""" secs = abs(int(time.time() - ts)) mins, secs = divmod(secs, 60) hours, mins = divmod(mins, 60) time_ago = "" if hours: time_ago += "%dh" % hours if mins: tim...
bigcode/self-oss-instruct-sc2-concepts
def _read_file(name, encoding='utf-8'): """ Read the contents of a file. :param name: The name of the file in the current directory. :param encoding: The encoding of the file; defaults to utf-8. :return: The contents of the file. """ with open(name, encoding=encoding) as f: return f...
bigcode/self-oss-instruct-sc2-concepts
def binary_array_search(A, target): """ Use Binary Array Search to search for target in ordered list A. If target is found, a non-negative value is returned marking the location in A; if a negative number, x, is found then -x-1 is the location where target would need to be inserted. """ lo =...
bigcode/self-oss-instruct-sc2-concepts
def _convert_float(value): """Convert an "exact" value to a ``float``. Also works recursively if ``value`` is a list. Assumes a value is one of the following: * :data:`None` * an integer * a string in C "%a" hex format for an IEEE-754 double precision number * a string fraction of the for...
bigcode/self-oss-instruct-sc2-concepts
def origin2center_of_mass(inertia, center_of_mass, mass): """ convert the moment of the inertia about the world coordinate into that about center of mass coordinate Parameters ---------- moment of inertia about the world coordinate: [xx, yy, zz, xy, yz, xz] center_of_mass: [x, y, z] ...
bigcode/self-oss-instruct-sc2-concepts
def _versionTuple(versionString): """ Return a version string in 'x.x.x' format as a tuple of integers. Version numbers in this format can be compared using if statements. """ if not isinstance(versionString, str): raise ValueError("version must be a string") if not versionString.count("...
bigcode/self-oss-instruct-sc2-concepts
import re def SplitBehavior(behavior): """Splits the behavior to compose a message or i18n-content value. Examples: 'Activate last tab' => ['Activate', 'last', 'tab'] 'Close tab' => ['Close', 'tab'] """ return [x for x in re.split('[ ()"-.,]', behavior) if len(x) > 0]
bigcode/self-oss-instruct-sc2-concepts
def reformat(keyword, fields): """ Reformat field name to url format using specific keyword. Example: reformat('comment', ['a','b']) returns ['comment(A)', 'comment(B)'] """ return ['{}({})'.format(keyword, f.upper()) for f in fields]
bigcode/self-oss-instruct-sc2-concepts
def diff_msg_formatter( ref, comp, reason=None, diff_args=None, diff_kwargs=None, load_kwargs=None, format_data_kwargs=None, filter_kwargs=None, format_diff_kwargs=None, sort_kwargs=None, concat_kwargs=None, report_kwargs=None, ): # pylint: disable=too-many-arguments ...
bigcode/self-oss-instruct-sc2-concepts
def corn() -> str: """Return the string corn.""" return "corn"
bigcode/self-oss-instruct-sc2-concepts
def celsius_to_rankine(temp: float) -> float: """ Converts temperature in celsius to temperature in rankine Args: temp (float): supplied temperature, in celsius Returns: float: temperature in rankine """ return (9 / 5) * temp + 491.67
bigcode/self-oss-instruct-sc2-concepts
def configs_check(difflist): """ Generate a list of files which exist in the bundle image but not the base image '- ' - line unique to lhs '+ ' - line unique to rhs ' ' - line common '? ' - line not present in either returns a list containing the items which are unique in the rhs ...
bigcode/self-oss-instruct-sc2-concepts
def _broadcast_bmm(a, b): """ Batch multiply two matrices and broadcast if necessary. Args: a: torch tensor of shape (P, K) or (M, P, K) b: torch tensor of shape (N, K, K) Returns: a and b broadcast multipled. The output batch dimension is max(N, M). To broadcast transforms a...
bigcode/self-oss-instruct-sc2-concepts
def _CommonChecks(input_api, output_api): """Checks common to both upload and commit.""" results = [] results.extend( input_api.canned_checks.CheckChangedLUCIConfigs(input_api, output_api)) return results
bigcode/self-oss-instruct-sc2-concepts
import re def _htmlPingbackURI(fileObj): """Given an interable object returning text, search it for a pingback URI based upon the search parameters given by the pingback specification. Namely, it should match the regex: <link rel="pingback" href="([^"]+)" ?/?> (source: http://www.hixie.ch/specs...
bigcode/self-oss-instruct-sc2-concepts
def add_train_args(parser): """Add training-related arguments. Args: * parser: argument parser Returns: * parser: argument parser with training-related arguments inserted """ train_arg = parser.add_argument_group('Train') train_arg.add_argument('--train_prep', ...
bigcode/self-oss-instruct-sc2-concepts
def _convert_graph(G): """Convert a graph to the numbered adjacency list structure expected by METIS. """ index = dict(zip(G, list(range(len(G))))) xadj = [0] adjncy = [] for u in G: adjncy.extend(index[v] for v in G[u]) xadj.append(len(adjncy)) return xadj, adjncy
bigcode/self-oss-instruct-sc2-concepts
import struct import socket def d2ip(d): """Decimal to IP""" packed = struct.pack("!L", d) return socket.inet_ntoa(packed)
bigcode/self-oss-instruct-sc2-concepts
import zlib def crc32_hex(data): """Return unsigned CRC32 of binary data as hex-encoded string. >>> crc32_hex(b'spam') '43daff3d' """ value = zlib.crc32(data) & 0xffffffff return f'{value:x}'
bigcode/self-oss-instruct-sc2-concepts
import re def fix_punct_spaces(string: str): """ fix_punct_spaces - replace spaces around punctuation with punctuation. For example, "hello , there" -> "hello, there" Parameters ---------- string : str, required, input string to be corrected Returns ------- str, corrected string ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def find_time_since(previous_time): """Just finds the time between now and previous_time.""" return datetime.now() - previous_time
bigcode/self-oss-instruct-sc2-concepts
def dansCercle(x,y, cx,cy, r): """ Teste l'appartenance à un cercle. Paramètres: (x,y) --> point à tester, (cx,cy) --> centre du cercle, r --> rayon du cercle. Retourne ``Vrai`` si le point est dans le cercle, ``Faux`` sinon. """ return (x-cx)**2 + (y-cy)**2 <= ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Collection def split_identifier(all_modules: Collection[str], fullname: str) -> tuple[str, str]: """ Split an identifier into a `(modulename, qualname)` tuple. For example, `pdoc.render_helpers.split_identifier` would be split into `("pdoc.render_helpers","split_identifier")`. This is n...
bigcode/self-oss-instruct-sc2-concepts
def read_txt(filename='filename.txt'): """Read a text file into a list of line strings.""" f = open(filename, 'r') data = f.readlines() f.close() return data
bigcode/self-oss-instruct-sc2-concepts
import re def _str_time_to_sec(s): """ Converts epanet time format to seconds. Parameters ---------- s : string EPANET time string. Options are 'HH:MM:SS', 'HH:MM', 'HH' Returns ------- Integer value of time in seconds. """ pattern1 = re.compile(r'^(\d+):(\d+):(\d+...
bigcode/self-oss-instruct-sc2-concepts
def apisecret(request): """Return API key.""" return request.config.getoption("--apisecret")
bigcode/self-oss-instruct-sc2-concepts
def pretty_hex_str(byte_seq, separator=","): """Converts a squence of bytes to a string of hexadecimal numbers. For instance, with the input tuple ``(255, 0, 10)`` this function will return the string ``"ff,00,0a"``. :param bytes byte_seq: a sequence of bytes to process. It must be compatible ...
bigcode/self-oss-instruct-sc2-concepts
def score2durations(score): """ Generates a sequence of note durations (in quarterLengths) from a score. Args: score (music21.Score): the input score Returns: list[float]: a list of durations corresponding to each note in the score """ return [n.duration.quarterLength for n in scor...
bigcode/self-oss-instruct-sc2-concepts
import torch def complex_abs_sq(data: torch.Tensor) -> torch.Tensor: """ Compute the squared absolute value of a complex tensor. Args: data: A complex valued tensor, where the size of the final dimension should be 2. Returns: Squared absolute value of data. """ if...
bigcode/self-oss-instruct-sc2-concepts
def has_attribute(object, name): """Check if the given object has an attribute (variable or method) with the given name""" return hasattr(object, name)
bigcode/self-oss-instruct-sc2-concepts
def filtro_ternario(cantidad_autos: int, numero_auto: int) -> int: """ Filtro ternario Parámetros: cantidad_autos (int): La cantidad de carros que recibe el operario en su parqueadero numero_auto (int): El número único del carro a ubicar en alguno de los tres lotes de parqueo. Se ...
bigcode/self-oss-instruct-sc2-concepts
def text_alignment(x: float, y: float): """ Align text labels based on the x- and y-axis coordinate values. This function is used for computing the appropriate alignment of the text label. For example, if the text is on the "right" side of the plot, we want it to be left-aligned. If the text i...
bigcode/self-oss-instruct-sc2-concepts
def _get_snap_name(snapshot): """Return the name of the snapshot that Purity will use.""" return "{0}-cinder.{1}".format(snapshot["volume_name"], snapshot["name"])
bigcode/self-oss-instruct-sc2-concepts
def is_even(n): """ True if the integer `n` is even. """ return n % 2 == 0
bigcode/self-oss-instruct-sc2-concepts
def original_choice(door): """ Return True if this door was picked originally by the contestant """ return door.guessed_originally is True
bigcode/self-oss-instruct-sc2-concepts
def get_neighbors(x, y): """Returns the eight neighbors of a point upon a grid.""" return [ [x - 1, y - 1], [x, y - 1], [x + 1, y - 1], [x - 1, y ], [x + 1, y ], [x - 1, y + 1], [x, y + 1], [x + 1, y + 1], ]
bigcode/self-oss-instruct-sc2-concepts
def user_to_dict(user): """ Convert an instance of the User model to a dict. :param user: An instance of the User model. :return: A dict representing the user. """ return { 'id': user.id, 'demoId': user.demoId, 'email': user.email, 'username': user.username...
bigcode/self-oss-instruct-sc2-concepts
def _suffix(name, suffix=None): """Append suffix (default _).""" suffix = suffix if suffix else '_' return "{}{}".format(name, suffix)
bigcode/self-oss-instruct-sc2-concepts
def test_orchestrator_backup_config( self, protocol: int, hostname: str, port: int, directory: str, username: str, password: str, ) -> dict: """Test specified settings for an Orchestrator backup .. list-table:: :header-rows: 1 * - Swagger Section - Method ...
bigcode/self-oss-instruct-sc2-concepts
def get_value_safe(d=None, key=None): """ Return value of a given dictionary for a key. @return: value for a key, None otherwise """ if d is None or key is None: return None if key not in d: return None return d[key]
bigcode/self-oss-instruct-sc2-concepts
def number_keys(a_dictionary): """ counts the number of keys in a dictionary and returns it """ return(len(a_dictionary))
bigcode/self-oss-instruct-sc2-concepts
def get_electricity_production(power_utilities): """Return the total electricity production of all PowerUtility objects in MW.""" return sum([i.production for i in power_utilities]) / 1000
bigcode/self-oss-instruct-sc2-concepts
def zcount(list) -> float: """ returns the number of elements in a list :param list: list of elements :return: int representing number of elements in given list """ c = 0 for _ in list: c += 1 return c
bigcode/self-oss-instruct-sc2-concepts
import math def must_tack_to_get_to(self, other, boat, wind): """Checks if tacks will be necessary to get to the other point from self""" bearing = wind.angle_relative_to_wind(other.bearing_from(self)) return math.fabs(bearing) < boat.upwind_angle
bigcode/self-oss-instruct-sc2-concepts
def get_city(df, city_name=None, city_index=None): """ returns an info dict for a city specified by `city name` containing {city_name: "São Paulo", city_ascii: "Sao Paulo", lat: -23.5504, lng: -46.6339, country: "Brazil", iso2: "BR", iso3: "BRA", admin_name: "São Paulo", capital: "adm...
bigcode/self-oss-instruct-sc2-concepts
def traceback(score_mat, state_mat, max_seen, max_list, seq_m, seq_n): """ This function accepts two m+1 by n+1 matrices. It locates the coordinates of the maximum alignment score (given by the score matrix) and traces back (using the state matrix) to return the alignment of the two sequences. Inpu...
bigcode/self-oss-instruct-sc2-concepts
def impute_missing(df): """ This function detects all missing values and imputes them with the Median of the column each missing value belongs to. """ df=df[df.columns].fillna(df[df.columns].median()) return(df)
bigcode/self-oss-instruct-sc2-concepts
import struct def get_chunk(filereader): """Utility function for reading 64 bit chunks.""" data = filereader.read(8) if not data: print("prematurely hit end of file") exit() bit64chunk = struct.unpack('Q', data)[0] return bit64chunk
bigcode/self-oss-instruct-sc2-concepts
def _allowed_file(filename): """Return True if file extension is allowed, False otherwise.""" extensions = ['csv', 'xls', 'xlsx'] return '.' in filename and filename.rsplit('.', 1)[1].lower() in extensions
bigcode/self-oss-instruct-sc2-concepts
import random def create_random_graph(nodes): """ Creates a random (directed) graph with the given number of nodes """ graph = [] for i in range(0, nodes): graph.append([]) for j in range(0, nodes): rand = random.randint(1, 100) if rand % 2 == 0 and i != j: ...
bigcode/self-oss-instruct-sc2-concepts
def critical_damping_parameters(theta, order=2): """ Computes values for g and h (and k for g-h-k filter) for a critically damped filter. The idea here is to create a filter that reduces the influence of old data as new data comes in. This allows the filter to track a moving target better. This goe...
bigcode/self-oss-instruct-sc2-concepts
def clo_dynamic(clo, met, standard="ASHRAE"): """ Estimates the dynamic clothing insulation of a moving occupant. The activity as well as the air speed modify the insulation characteristics of the clothing and the adjacent air layer. Consequently the ISO 7730 states that the clothing insulation shall be...
bigcode/self-oss-instruct-sc2-concepts
def easeInOutCubic(currentTime, start, end, totalTime): """ Args: currentTime (float): is the current time (or position) of the tween. start (float): is the beginning value of the property. end (float): is the change between the beginning and destination value of the propert...
bigcode/self-oss-instruct-sc2-concepts
def is_valid_part2(entry): """ Validate the password against the rule (part 2) Position 1 must contain the token and position 2 must not. """ # note that positions are 1 indexed pos1 = entry.param1 - 1 pos2 = entry.param2 - 1 result = (entry.password[pos1] == entry.token) \ and...
bigcode/self-oss-instruct-sc2-concepts