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 def seq_to_doc(seq): # drop initial tag if it is supplied if tag: if tag not in seq: return None seq = seq.split(tag)[1] # split the sequence at every letter if not a nt_seq if not nt_seq: return ' '.join([aa for aa in seq]) # split the sequence every 3 letters if it is a nt_seq return ' '.join([seq[i:i + 3] for i in range(0, len(seq), 3)]) return seqs.apply(seq_to_doc)
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 in range(width+1)] leftSide = [x for x in rightSide[:0:-1]] peak = leftSide+rightSide scale = -height/leftSide[0] peak = [(x*scale)+height for x in peak] return peak
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 retry if the saved result is a failure Returns ------- partial_results: Array of MeasureResult a full list of result, where None denotes no corresponding saved result unsaved: Array of MeasureInput a list that only contains unsaved inputs """ partial_results = list() unsaved = list() for inp in measure_inputs: res = db.load(inp) if res is None or (retry and res.error_no != 0): unsaved.append(inp) partial_results.append(None) else: partial_results.append(res) return partial_results, unsaved
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 .. Tip:: Rondeaux, G., Steven, M., Baret, F. 1996. \ Optimization of soil-adjusted vegetation indices. \ Remote Sensing of Environment 55, 95-107. \ doi:10.1016/0034-4257(95)00186-7. """ OSAVI = 1.16 * b8 - (b4 / b8) + b4 + 0.16 return OSAVI
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 in mix. If None, mixes all stems alternate_weights : dict Dictionary with stem indices as keys and mixing coefficients as values. Stem indices present that are not in this dictionary will use the default estimated mixing coefficient. alternate_files : dict Dictionary with stem indices as keys and filepaths as values. Audio file to use in place of original stem. Stem indices present that are not in this dictionary will use the original stems. additional_files : list of tuples List of tuples of (filepath, mixing_coefficient) pairs to additionally add to final mix. Returns ------- filepaths : list List of filepaths that were included in mix. weights : list List of weights that were used in mix """ if stem_indices is None: stem_indices = list(mtrack.stems.keys()) if alternate_files is None: alternate_files = {} if alternate_weights is None: alternate_weights = {} weights = [] filepaths = [] for index in stem_indices: if index in alternate_files.keys(): filepaths.append(alternate_files[index]) else: filepaths.append(mtrack.stems[index].audio_path) if index in alternate_weights.keys(): weights.append(alternate_weights[index]) else: if mtrack.stems[index].mixing_coefficient is not None: mix_coeff = mtrack.stems[index].mixing_coefficient else: print( '[Warning] Multitrack does not have mixing coefficients. ' 'Using uniform stem weights.' ) mix_coeff = 1 weights.append(mix_coeff) if additional_files is not None: for fpath, weight in additional_files: filepaths.append(fpath) weights.append(weight) return filepaths, weights
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 value Returns: Union[int, Any]: Integer reprepresentataion of the bool """ return int(value) if isinstance(value, bool) else value
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 filters: excludes = set(fnmatch.filter(files, file_filter)) match |= excludes return [name for name in files if name not in match]
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 len(ls) > idx: return ls[idx] return None
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 ----- xmlTree : `xml.etree.ElementTree` the xml tree to search for the <result> node desc : string the text contained in the desc node Returns ----- node : the <result> node containing the child with the given desc """ result_nodes = xml_tree.findall("result") for result_node in result_nodes: result_desc = result_node.find("desc").text.strip() if result_desc == desc: return result_node return None
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("labels_pred_c must have at least one instance") l1, l2 = 0, 0 for k in labels_true_c: l1 += len(labels_true_c[k]) for k in labels_pred_c: l2 += len(labels_pred_c[k]) if l1 != l2: raise ValueError('Cluster labels are not the same number of instances') return labels_true_c, labels_pred_c
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 :param date_interprater: function applied to the list to transform items into dates """ def _proximity_comparator(date): _date = date_interpreter(date) return ( abs(_date - cmp_date), -1 * _date.year, -1 * _date.month, -1 * _date.day ) return _proximity_comparator
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) / ys_range return scale, ys_mid, new_mid
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: res.append(repr(arg)) else: res.append(shlex.quote(arg)) return " ".join(res)
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): raise TypeError("n must be an int") if n < 0: raise ValueError("n must be non-negative") if n < 2: return n elif memo is None: memo = {} elif n in memo: return memo[n] f0 = memo[n - 1] if n - 1 in memo else fib_memo(n - 1, memo) f1 = memo[n - 2] if n - 2 in memo else fib_memo(n - 2, memo) memo[n] = f0 + f1 return memo[n]
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 of *chroma* :math:`C`. Examples -------- >>> Lstar_P = 49.99988297570504 >>> S = 0.013355029751777615 >>> chroma_correlate(Lstar_P, S) # doctest: +ELLIPSIS 0.0133550... """ C = ((Lstar_P / 50) ** 0.7) * S return C
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 = int(num_quantiles / 2) if num_quantiles % 2 == 0: # If we have an even number of quantile boundaries, take the mean of the # middle boundaries to be the median. return (quantiles[median_index - 1] + quantiles[median_index])/2.0 else: # If we have an odd number of quantile boundaries, the middle boundary is # the median. return quantiles[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): suffix = suffix.lower().strip(string.digits) if suffix in [".pdb", ".ent"]: return "pdb" elif suffix in [".cif", ".mmcif"]: return "cif" elif suffix in [".mmtf"]: return "mmtf" raise Exception(f"Could not guess pdb type for file '{pdb_file}'!")
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) -- the text to replace the find text with Keyword arguments: ignore_case (bool) -- perform case-insensitive search if True regex (bool) -- interpret the find text string as a regular expression quiet (bool) -- don't print any output if True """ try: # If find_str is not designated as regex, escape all special characters if not regex: find_str = re.escape(find_str) if ignore_case: pattern = re.compile(r"(?i)%s" % find_str) else: pattern = re.compile(r"%s" % find_str) # Perform replacement and return new name if input is valid if find_str: new_name = pattern.sub(replace_str, input_str) return new_name else: if not quiet: print("Warning: No search string specified.") return input_str except: if not quiet: print("Warning: Regular expression is invalid.")
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, str): A boolean indicating if the request is valid. The other parameter is an error message if the boolean is True, and is None otherwise. """ if not params: return False, "ERROR: Request parameters must not be null!" if not isinstance(params, dict): return False, "ERROR: Request parameters must be a JSON object!" if "target" not in params: return False, "ERROR: Request params requires 'target' field!" target = params["target"] if target != "sensor" and target != "group": return False, "ERROR: Invalid 'target' specified! Must be one of {'sensor', 'group'}." if target == "sensor": if "groupid" not in params: return False, "ERROR: Request params requires 'groupid' field!" try: groupid = int(params["groupid"]) except Exception: return False, "ERROR: Request parameter 'groupid' must be an integer!" if groupid <= 0: return False, "ERROR: Request parameter 'groupid' must be >= 0!" if "alias" in params: if not params["alias"]: return False, "ERROR: Request parameter 'alias' must contain at least one (1) character!" return True, None
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 len(filename) <= 0: raise ValueError("Specify filename") if ( isinstance(filename, str) and "." not in filename or len(filename.split(".")[1]) <= 0 ): raise ValueError("`filename` must be provided & have an extension") return filename
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, B2, ... , BN, X, Y] A tensor containing the result of the function application. """ if x.shape[:-1] != y.shape[:-1]: raise ValueError( "Shape of `x` ({}) incompatible with shape of y ({})".format( x.shape, y.shape)) x = x.unsqueeze(-1) # [B1, B2, ... , BN, X, 1] y = y.unsqueeze(-2) # [B1, B2, ... , BN, 1, Y] result = f(x, y) # [B1, B2, ... , BN, X, Y] return result
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 different elements of the items """ return [(items[i],items[j]) for i in range(len(items)) for j in range(i+1, len(items))]
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[2]-ys[0])*(x-xs[2])+(xs[0]-xs[2])*(y-ys[2]))/float(det) return l1, l2, 1-l1-l2
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() + camelcase(string)[1:]
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: return byte_file.read()
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 = factories.Annotation.build(**kwargs) index_annotations(annotation) return annotation return _Annotation
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: if el < min: return False if max is not None: if el > max: return False return True
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 # Find original values from problem file xH = float(problemFile["xH"+str(windno)]) xHe = float(problemFile["xHe"+str(windno)]) xC = float(problemFile["xC"+str(windno)]) xN = float(problemFile["xN"+str(windno)]) xO = float(problemFile["xO"+str(windno)]) # Calculate mass contributon mH = xH * 1.0 mHe = xHe * 4.0 mC = xC * 12.0 mN = xN * 14.0 mO = xO * 16.0 # Calculate average mass, in proton masses, convert to grams and return! avgMass = mH + mHe + mC + mN + mO avgMass *= protonmass return avgMass
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 position 2 before, and so on... :param m: the original matrix :param m_size: the original matrix size :param transition_state_nb: the number of transision states :return: a QR matrix of the size transition_state_nb*m_size (because we have the transition states first here) """ # Get the new position for the transision and the final states transition_states = [i for i in range(m_size) if sum(m[i]) > 0] final_states = [i for i in range(m_size) if sum(m[i]) == 0] reorg_states = transition_states + final_states # Init an empty matrix the same size of RQ reorg_m = [[0 for _ in range(m_size)] for _ in range(transition_state_nb)] # for each transition row, we rearrange them for i in range(transition_state_nb): for j in range(m_size): reorg_m[i][j] = m[reorg_states[i]][reorg_states[j]] return reorg_m
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: time_ago += "%dm" % mins if secs: time_ago += "%ds" % secs if time_ago: time_ago += " ago" else: time_ago = "just now" return time_ago
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.read()
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 = 0 hi = len(A) - 1 while lo <= hi: mid = (lo + hi) // 2 if target < A[mid]: hi = mid-1 elif target > A[mid]: lo = mid+1 else: return mid return -(lo+1)
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 format "N/D" * a list of one of the accepted types (incl. a list) Args: value (Union[int, str, list]): Values to be converted. Returns: Union[float, list]: The converted value (or list of values). """ if value is None: return None elif isinstance(value, list): return [_convert_float(element) for element in value] elif isinstance(value, int): return float(value) elif value.startswith("0x") or value.startswith("-0x"): return float.fromhex(value) else: numerator, denominator = value.split("/") return float(numerator) / float(denominator)
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] Returns ---------- moment of inertia about center of mass : [xx, yy, zz, xy, yz, xz] """ x = center_of_mass[0] y = center_of_mass[1] z = center_of_mass[2] translation_matrix = [y**2+z**2, x**2+z**2, x**2+y**2, -x*y, -y*z, -x*z] return [round(i - mass*t, 6) for i, t in zip(inertia, translation_matrix)]
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(".") == 2: raise ValueError("version string must be 'x.x.x' format") versionParts = versionString.split(".") versionParts = [int(x) for x in versionParts] return tuple(versionParts)
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 """Format a difference message. Args: ref (str): The path to the reference file. comp (str): The path to the compared file. reason (bool or str): If the reason is False, False is returned. If it is a str, a formatted message is returned. diff_args (list): (optional) The args used for the comparison. diff_kwargs (list): (optional) The kwargs used for the comparison. load_kwargs (dict): The kwargs used for loading the data. format_data_kwargs (dict): The kwargs used for formatting the data. filter_kwargs (dict): The kwargs used for filtering the differences. format_diff_kwargs (dict): The kwargs used for formatting the differences. sort_kwargs (dict): The kwargs used for sorting the differences. concat_kwargs (dict): The kwargs used for concatenating the differences. report_kwargs (dict): The kwargs used for reporting the differences. Returns: False or the difference message. """ if not reason: return False if reason is not None and reason is not True: reason_used = f"{reason}" else: reason_used = "" if diff_args: args_used = f"Args used for computing differences: {list(diff_args)}\n" else: args_used = "" def format_kwargs(kwargs, name): if kwargs: return f"Kwargs used for {name}: {kwargs}\n" return "" diff_kwargs_used = format_kwargs(diff_kwargs, "computing differences") load_kwargs_used = format_kwargs(load_kwargs, "loading data") format_data_kwargs_used = format_kwargs(format_data_kwargs, "formatting data") filter_kwargs_used = format_kwargs(filter_kwargs, "filtering differences") format_diff_kwargs_used = format_kwargs(format_diff_kwargs, "formatting differences") sort_kwargs_used = format_kwargs(sort_kwargs, "sorting differences") concat_kwargs_used = format_kwargs(concat_kwargs, "concatenating differences") report_kwargs_used = format_kwargs(report_kwargs, "reporting differences") kwargs_used = "\n".join( i for i in [ load_kwargs_used, format_data_kwargs_used, diff_kwargs_used, filter_kwargs_used, format_diff_kwargs_used, sort_kwargs_used, concat_kwargs_used, report_kwargs_used, ] if i ) eol = "." if reason_used or args_used or kwargs_used: eol = ":\n" return ( f"The files '{ref}' and '{comp}' are different{eol}" f"{args_used}" f"{kwargs_used}" f"{reason_used}" )
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 difflist --- a list containing the output of difflib.Differ.compare where the lhs (left-hand-side) was the base image and the rhs (right-hand-side) was base image + extras (the bundle image). """ cont = [] for ln in difflist: if ln[0] == '+' and len(ln) >= 4: cont.append(ln[0:]) if ln[0] == '-' and len(ln) >= 4: cont.append(ln[0:]) return cont
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 across a batch dimension if M != N then expect that either M = 1 or N = 1. The tensor with batch dimension 1 is expanded to have shape N or M. """ if a.dim() == 2: a = a[None] if len(a) != len(b): if not ((len(a) == 1) or (len(b) == 1)): msg = "Expected batch dim for bmm to be equal or 1; got %r, %r" raise ValueError(msg % (a.shape, b.shape)) if len(a) == 1: a = a.expand(len(b), -1, -1) if len(b) == 1: b = b.expand(len(a), -1, -1) return a.bmm(b)
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/pingback/pingback) We could search the text using an actual HTML parser easily enough, or expand the regex to be a little more forgiving, but for the moment we'll follow the spec.""" regex = re.compile('<link rel="pingback" href="([^"]+)" ?/?>', re.I) # might as well be case-insensitive for line in fileObj: m = regex.search(line) if m != None: uri = m.group(1) # The pingback spec demands we expand the four allowed entities, # but no more. uri = uri.replace("&lt;", "<") uri = uri.replace("&gt;", ">") uri = uri.replace("&quot;", '"') uri = uri.replace("&amp;", "&") return uri return None
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', required=True, help='Where to load preprocessed data') #train_arg.add_argument('--property', required=True) train_arg.add_argument('--vocab', required=True, help='Where to load cluster vocabulary') train_arg.add_argument('--train_save_dir', required=True, help='Where to save model') train_arg.add_argument('--load_epoch', type=int, default=0, help='Where to load model for given epoch') train_arg.add_argument('--batch_size', type=int, default=32, help='Minibatch size') train_arg.add_argument('--lr', type=float, default=1e-3, help='Learning rate') train_arg.add_argument('--clip_norm', type=float, default=50.0, help='Performing gradient clippiing when great than clip_norm') train_arg.add_argument('--beta', type=float, default=0.0, help='Initial value of the weight for the KL term') train_arg.add_argument('--step_beta', type=float, default=0.001, help='Incremental increase added to Beta') train_arg.add_argument('--max_beta', type=float, default=1.0, help='Max allowed value for beta') train_arg.add_argument('--warmup', type=int, default=40000, help='Warmming up') train_arg.add_argument('--epoch', type=int, default=20, help='Number of training epoches') train_arg.add_argument('--anneal_rate', type=float, default=0.9, help='Anneal rate') train_arg.add_argument('--anneal_iter', type=int, default=40000, help='Anneal iter') train_arg.add_argument('--kl_anneal_iter', type=int, default=1000, help='Anneal iteration for KL term') train_arg.add_argument('--print_iter', type=int, default=50, help='Number of iter for printing') train_arg.add_argument('--save_iter', type=int, default=5000, help='How many iters to save model once') return parser
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 """ fix_spaces = re.compile(r"\s*([?!.,]+(?:\s+[?!.,]+)*)\s*") string = fix_spaces.sub(lambda x: "{} ".format(x.group(1).replace(" ", "")), string) string = string.replace(" ' ", "'") string = string.replace(' " ', '"') string = string.replace("- _", "-") string = string.replace("_ -", "-") string = string.replace(" _ ", "-") string = string.replace("_ ", "-") string = string.strip("_") return string.strip()
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 <= r**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 necessary to generate links to the correct module. """ if not fullname: raise ValueError("Invalid identifier.") if fullname in all_modules: return fullname, "" else: parent, _, name = fullname.rpartition(".") modulename, qualname = split_identifier(all_modules, parent) if qualname: return modulename, f"{qualname}.{name}" else: return modulename, name
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+)$') time_tuple = pattern1.search(s) if bool(time_tuple): return (int(time_tuple.groups()[0])*60*60 + int(time_tuple.groups()[1])*60 + int(round(float(time_tuple.groups()[2])))) else: pattern2 = re.compile(r'^(\d+):(\d+)$') time_tuple = pattern2.search(s) if bool(time_tuple): return (int(time_tuple.groups()[0])*60*60 + int(time_tuple.groups()[1])*60) else: pattern3 = re.compile(r'^(\d+)$') time_tuple = pattern3.search(s) if bool(time_tuple): return int(time_tuple.groups()[0])*60*60 else: raise RuntimeError("Time format in " "INP file not recognized. ")
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 with the "bytes" type. :param str separator: the string to be used to separate each byte in the returned string (default ","). """ # Check the argument and convert it to "bytes" if necessary. # This conversion assert "byte_seq" items are in range (0, 0xff). # "TypeError" and "ValueError" are sent by the "bytes" constructor if # necessary. if isinstance(byte_seq, int): byte_seq = bytes((byte_seq, )) else: byte_seq = bytes(byte_seq) return separator.join(['%02x' % byte for byte in byte_seq])
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 score.flat.notes for p in n.pitches]
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 data.shape[-1] != 2: raise ValueError("Tensor does not have separate complex dim.") return (data**2).sum(dim=-1)
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 garantiza que es un número menor o igual que n, y mayor o igual que 1. Retorno: int: El lote de parqueadero donde el carro con el número que llega por parámetro deberá parquear. Debe ser un valor entre 1 y 3. """ capacidad_lote = cantidad_autos // 3 if 1 <= numero_auto <= capacidad_lote: lote = 1 elif (capacidad_lote + 1) <= numero_auto <= (2 * capacidad_lote): lote = 2 else: lote = 3 return lote
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 is on the "top" side of the plot, we want it to be bottom-aligned. :param x, y: (`int` or `float`) x- and y-axis coordinate respectively. :returns: A 2-tuple of strings, the horizontal and vertical alignments respectively. """ if x == 0: ha = "center" elif x > 0: ha = "left" else: ha = "right" if y == 0: va = "center" elif y > 0: va = "bottom" else: va = "top" return ha, va
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, 'roles': user.roles }
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 - Endpoint * - gmsBackup - POST - /gms/backup/testConnection :param protocol: The protocol of the remote server, ``3`` - SCP, ``4`` - HTTP, ``5`` - HTTPS, ``6`` - SFTP, any other number corresponds to FTP :type protocol: int :param hostname: The hostname or ip of the remote server :type hostname: :param port: Port to connect to remove server on :type port: int :param directory: The directory for the backup on the remote server :type directory: str :param username: The username to connect to the remote server :type username: str :param password: The password to connect to the remote server :type password: str :return: Returns dictionary of backup test results \n * keyword **message** (`str`): Orchestrator backup test results :rtype: dict """ data = { "protocol": protocol, "hostname": hostname, "port": port, "directory": directory, "username": username, "password": password, "maxBackups": 0, } return self._post("/gms/backup/testConnection", data=data)
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: "admin", population: 22046000.0, id: 1076532519} :param df: pandas df containing cities data from simplemaps.com :return: """ assert any([city_name is not None, city_index is not None]) if city_name is not None: return df.loc[df['city_ascii'].str.lower() == city_name.lower()].to_dict('records')[0] if city_index is not None: return df.iloc[[city_index]].to_dict('records')[0]
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. Inputs: score_mat: scoring matrix state_mat: matrix indicating the source of each cell's maximum score ("align" if it's from an alignment, "ins" if it's from insertion i.e. from north cell, or "del" if it's from deletion i.e. from west cell) Output: consensus alignment of the two sequences """ # Find optimal alignments for each max cell alignments = [] score = max_seen residues_m = [] #keep track of residues in alignment residues_n = [] i, j = max_list while score > 0: # Alignment score if state_mat[i][j] == "align": residues_m.append(seq_m[i-1]) residues_n.append(seq_n[j-1]) i = i-1 j = j-1 # Insertion score (came from north cell) elif state_mat[i][j] == "ins": residues_m.append("-") residues_n.append(seq_n[j-1]) i = i-1 # Deletion score (came from west cell) elif state_mat[i][j] == "del": residues_m.append(seq_m[i-1]) residues_n.append("-") j = j-1 # Update score of focal cell score = score_mat[i][j] return list(reversed(residues_m)), list(reversed(residues_n))
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: graph[i].append(rand) else: graph[i].append(-1) return graph
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 goes by different names. It may be called the discounted least-squares g-h filter, a fading-memory polynomal filter of order 1, or a critically damped g-h filter. In a normal least-squares filter we compute the error for each point as .. math:: \epsilon_t = (z-\\hat{x})^2 For a crically damped filter we reduce the influence of each error by .. math:: \\theta^{t-i} where .. math:: 0 <= \\theta <= 1 In other words the last error is scaled by theta, the next to last by theta squared, the next by theta cubed, and so on. Parameters ---------- theta : float, 0 <= theta <= 1 scaling factor for previous terms order : int, 2 (default) or 3 order of filter to create the parameters for. g and h will be calculated for the order 2, and g, h, and k for order 3. Returns ------- g : scalar optimal value for g in the g-h or g-h-k filter h : scalar optimal value for h in the g-h or g-h-k filter k : scalar optimal value for g in the g-h-k filter Examples -------- .. code-block:: Python from filterpy.gh import GHFilter, critical_damping_parameters g,h = critical_damping_parameters(0.3) critical_filter = GHFilter(0, 0, 1, g, h) References ---------- Brookner, "Tracking and Kalman Filters Made Easy". John Wiley and Sons, 1998. Polge and Bhagavan. "A Study of the g-h-k Tracking Filter". Report No. RE-CR-76-1. University of Alabama in Huntsville. July, 1975 """ if theta < 0 or theta > 1: raise ValueError('theta must be between 0 and 1') if order == 2: return (1. - theta**2, (1. - theta)**2) if order == 3: return (1. - theta**3, 1.5*(1.-theta**2)*(1.-theta), .5*(1 - theta)**3) raise ValueError('bad order specified: {}'.format(order))
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 corrected [2]_. The ASHRAE 55 Standard, instead, only corrects for the effect of the body movement, and states that the correction is permitted but not required. Parameters ---------- clo : float clothing insulation, [clo] met : float metabolic rate, [met] standard: str (default="ASHRAE") - If "ASHRAE", uses Equation provided in Section 5.2.2.2 of ASHRAE 55 2017 Returns ------- clo : float dynamic clothing insulation, [clo] """ if standard.lower() not in ["ashrae"]: raise ValueError( "PMV calculations can only be performed in compliance with ISO or ASHRAE " "Standards" ) if 1.2 < met < 2: return round(clo * (0.6 + 0.4 / met), 3) else: return clo
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 property. totalTime (float): is the total time of the tween. Returns: float: normalized interpoltion value """ currentTime /= totalTime/2 if currentTime < 1: return end/2*currentTime*currentTime*currentTime + start currentTime -= 2 return end/2*(currentTime*currentTime*currentTime + 2) + start
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 (entry.password[pos2] != entry.token) print(f"{entry} -> {result}") return result
bigcode/self-oss-instruct-sc2-concepts