seed
stringlengths
1
14k
source
stringclasses
2 values
def get_indexes(lst, sub_lst, compare_function=None): """Return the indexes of a sub list in a list. :param lst: the list to search in :param sub_lst: the list to match :param compare_function: the comparaison function used :type lst: list :type sub_lst: list :type compare_function: functi...
bigcode/self-oss-instruct-sc2-concepts
def _join_modules(module1, module2): """Concatenate 2 module components. Args: module1: First module to join. module2: Second module to join. Returns: Given two modules aaa.bbb and ccc.ddd, returns a joined module aaa.bbb.ccc.ddd. """ if not module1: return module2 if not module2: ...
bigcode/self-oss-instruct-sc2-concepts
def from_723(u: bytes) -> int: """Convert from ISO 9660 7.2.3 format to uint16_t Return the little-endian part always, to handle non-specs-compliant images. """ return u[0] | (u[1] << 8)
bigcode/self-oss-instruct-sc2-concepts
import base64 def decode_textfield_base64(content): """ Decodes the contents for CIF textfield from Base64. :param content: a string with contents :return: decoded string """ return base64.standard_b64decode(content)
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def default_key(obj: object, key: str, default: Any = None) -> Any: """Get value by attribute in object or by key in dict. If property exists returns value otherwise returns `default` value. If object not exist or object don't have property returns `default`. Args: obj...
bigcode/self-oss-instruct-sc2-concepts
def _get_lua_base_module_parts(base_path, base_module): """ Get a base module from either provided data, or from the base path of the package Args: base_path: The package path base_module: None, or a string representing the absence/presence of a base module override ...
bigcode/self-oss-instruct-sc2-concepts
def broken_bond_keys(tra): """ keys for bonds that are broken in the transformation """ _, _, brk_bnd_keys = tra return brk_bnd_keys
bigcode/self-oss-instruct-sc2-concepts
def named_field(key, regex, vim=False): """ Creates a named regex group that can be referend via a backref. If key is None the backref is referenced by number. References: https://docs.python.org/2/library/re.html#regular-expression-syntax """ if key is None: # return regex ...
bigcode/self-oss-instruct-sc2-concepts
import torch def _set_finite_diff_coeffs(ndim, dx, device, dtype): """Calculates coefficients for finite difference derivatives. Currently only supports 4th order accurate derivatives. Args: ndim: Int specifying number of dimensions (1, 2, or 3) dx: Float Tensor containing cell spacing i...
bigcode/self-oss-instruct-sc2-concepts
def build_regex(pattern, pattern_name=None, **kwargs): """ Return regex string as a named capture group. See: https://tonysyu.github.io/readable-regular-expressions-in-python.html """ pattern = pattern.format(**kwargs) if pattern_name is not None: return r'(?P<{name}>{pattern})'.format(...
bigcode/self-oss-instruct-sc2-concepts
def number_of_patients(dataset, feature_files, label_files): """ Calculates number of unique patients in the list of given filenames. :param dataset: string. Dataset train/val/test. :param feature_files: list of strings. List of filenames with patient names containing features. :param label_files: ...
bigcode/self-oss-instruct-sc2-concepts
def invert_dict(dic, sort=True, keymap={}, valmap={}): """Inverts a dictionary of the form key1 : [val1, val2] key2 : [val1] to a dictionary of the form val1 : [key1, key2] val2 : [key2] Parameters ----------- dic : dict Returns ----------- dict """ dic_...
bigcode/self-oss-instruct-sc2-concepts
def byte_ord(b): """ Return the integer representation of the byte string. This supports Python 3 byte arrays as well as standard strings. """ try: return ord(b) except TypeError: return b
bigcode/self-oss-instruct-sc2-concepts
import re def parse_time(time_string) -> int: """ Parse a time stamp in seconds (default) or milliseconds (with "ms" unit) The "s" unit is optional and implied if left out. Args: time_string(str): timestamp, e.g., "0.23s", "5.234" (implied s), "1234 ms" must be a number followed b...
bigcode/self-oss-instruct-sc2-concepts
def confidence_intervals_overlap(old_score, old_ci, new_score, new_ci): """Returns true if the confidence intervals of the old and new scores overlap, false otherwise. """ if old_score < new_score: old_score += old_ci new_score -= new_ci return old_score >= new_score else: ...
bigcode/self-oss-instruct-sc2-concepts
def data2str(data): """ Convert some data to a string. An empty or None value is returned unchanged (helpful for testing), e.g.: '57 75 6e 64 65 72 62 61 72 49 52' -> 'WunderbarIR' '' -> '' """ if not data: return data text = ''.join([chr(int(v, 16)) for v in data.split()]) return ...
bigcode/self-oss-instruct-sc2-concepts
import re def get_task_args_and_kwargs(file_path): """Get the args and kwargs for the task.""" text = '' with open(file_path, 'r') as f: for line in f: text += line.strip() + ' ' reg = re.search('Task was called with args: (\(.*?\)) ' 'kwargs: ({.*?})', text) ...
bigcode/self-oss-instruct-sc2-concepts
import yaml def gen_lookup(file): """ Generating the lookup table between api-endpoints and elasticsearch instances from the configuration of the lod-api. lookup table is of the form: {"/api/endpoint": "http://elasticsearchhost:port/index/doctype", "/resource": "http://el...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def default_tile_extras_provider(hyb: int, ch: int, z: int) -> Any: """ Returns None for extras for any given hyb/ch/z. """ return None
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def copa_preformat_fn(ex: Dict[str, Any]) -> Dict[str, Any]: """format for COPA tasks. Args: ex: Dictionary with one sample Returns: ex: Formatted dictionary """ premise, question = ex['premise'].decode(), ex['question'].decode() input_prompt = f'{p...
bigcode/self-oss-instruct-sc2-concepts
def bfs(G, s, f): """ Breadth-first search :param G: The graph object :param s: The start node :param f: The goal node :return: The explored set """ explored, frontier = [], [s] while frontier: v = frontier.pop(0) if v == f: pass else: ...
bigcode/self-oss-instruct-sc2-concepts
import copy def norm_rda_deficit(norm_rda_arr): """ Returns a modified list of nutrient dicts in which value represents a fraction of how much a given nutrient has been satisfied. A value of 0 represents full satisfaction, and 1 represents no satisfaction. """ r_nut = copy.deepcopy(norm_rda_arr) ...
bigcode/self-oss-instruct-sc2-concepts
def add_dicts(*args): """ Combine dicts. If there are duplicate keys, raise an error. """ new = {} for arg in args: for key in arg: if key in new: raise ValueError("Duplicate key: %r" % key) new[key] = arg[key] return new
bigcode/self-oss-instruct-sc2-concepts
import re def get_confirm_lines(code): """ Takes the block of code submitted to RESOLVE and returns a list of the lines that start with Confirm or ensures, keeping the semicolons attached at the end, and removing all spaces (starting, ending, or in between) @param code: All code submitted to RESOLVE v...
bigcode/self-oss-instruct-sc2-concepts
def rotate_90(grid): """ Rotate a given grid by 90 degrees. Args: grid: Grid to rotate. Returns: Grid after being rotated by 90 degrees. """ new_grid = [] for col, _ in enumerate(grid): new_row = [] # Go through the rows, # and form new rows dependin...
bigcode/self-oss-instruct-sc2-concepts
def get_single_key_value_pair(d): """ Returns the key and value of a one element dictionary, checking that it actually has only one element Parameters ---------- d : dict Returns ------- tuple """ assert isinstance(d, dict), f'{d}' assert len(d) == 1, f'{d}' return lis...
bigcode/self-oss-instruct-sc2-concepts
def donner_carte(nombre:int, joueur:dict, paquet:list) -> bool: """Donne une carte Args: nombre (int): nombre de cartes à donner joueur (dict): profil du joueur paquet (list): paquet de jeu Returns: bool: True si pas d'erreurs """ for _ in range(nombre): ...
bigcode/self-oss-instruct-sc2-concepts
def command(cmd, *parameters): """ Helper function. Prints the gprMax #<cmd>: <parameters>. None is ignored in the output. Args: cmd (str): the gprMax cmd string to be printed *parameters: one or more strings as arguments, any None values are ignored Returns: s ...
bigcode/self-oss-instruct-sc2-concepts
import inspect import types def find_classes_subclassing(mods, baseclass): """ Given a module or a list of modules, inspect and find all classes which are a subclass of the given baseclass, inside those modules """ # collect all modules found in given modules if not isinstance(mods, list): ...
bigcode/self-oss-instruct-sc2-concepts
def bdev_get_iostat(client, name=None): """Get I/O statistics for block devices. Args: name: bdev name to query (optional; if omitted, query all bdevs) Returns: I/O statistics for the requested block devices. """ params = {} if name: params['name'] = name return cli...
bigcode/self-oss-instruct-sc2-concepts
def simplify_whitespace(name): """Strip spaces and remove duplicate spaces within names""" if name: return ' '.join(name.split()) return name
bigcode/self-oss-instruct-sc2-concepts
import toml def data_from_toml_lines(lines): """ Return a mapping of data from an iterable of TOML text ``lines``. For example:: >>> lines = ['[advisory]', 'id = "RUST1"', '', '[versions]', 'patch = [">= 1"]'] >>> data_from_toml_lines(lines) {'advisory': {'id': 'RUST1'}, 'versions': {'patch'...
bigcode/self-oss-instruct-sc2-concepts
def unames_are_equivalent(uname_actual: str, uname_expected: str) -> bool: """Determine if uname values are equivalent for this tool's purposes.""" # Support `mac-arm64` through Rosetta until `mac-arm64` binaries are ready # Expected and actual unames will not literally match on M1 Macs because # they ...
bigcode/self-oss-instruct-sc2-concepts
def part_1b_under_equilb_design_ensemble_run_limit(job): """Check that the equilbrium design ensemble run is under it's run limit.""" try: if ( job.doc.equilb_design_ensemble_number >= job.doc.equilb_design_ensemble_max_number ): job.doc.equilb_design_ensemble...
bigcode/self-oss-instruct-sc2-concepts
def get_column(grid, column_index): """Return the column from the grid at column_index as a list.""" return [row[column_index] for row in grid]
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import requests def create_sq_project(sq_server: str, auth: Tuple, proj_id: str) -> str: """Creates a SonarQube project for the current project""" url = f"{sq_server}/api/projects/create" name = f"project-{proj_id}" args = {"name": name, "project": name, "visibility": "public...
bigcode/self-oss-instruct-sc2-concepts
def fit(approach, train_dict): """ Given a train data (features and labels), fit a dummy classifier. Since we can actually not fit a model, it returns the probability of complaint. Parameters ---------- approach: dictionary Approach configuration coming from the experiment yaml trai...
bigcode/self-oss-instruct-sc2-concepts
def count_words(my_string): """ This function counts words :param my_string: str - A string of words or characters :return: int - length of words """ if not isinstance(my_string, str): raise TypeError("only accepts strings") special_characters = ['-', '+', '\n'] for character i...
bigcode/self-oss-instruct-sc2-concepts
import re def toSentenceCase(text): """ Converts the given text to sentence case. Args: text (string): Text to convert to sentence case. Returns: (string): Sentence case version of given text. """ return re.sub(r"(?<=\w)([A-Z])", r" \1", text).title()
bigcode/self-oss-instruct-sc2-concepts
import re def readLinking(goldStdFile): """ Reads a file containing Entity Linking output according to the KBP 2013 format. Each line in the systeming output file consists of 2 or 3 fields: mention_id KB_ID (optional confidence, default is 1.0) Each line in the gold standard file may contain 2 o...
bigcode/self-oss-instruct-sc2-concepts
def _compute_nfp_uniform(l, u, cum_counts, sizes): """Computes the expected number of false positives caused by using u to approximate set sizes in the interval [l, u], assuming uniform distribution of set sizes within the interval. Args: l: the lower bound on set sizes. u: the upper bo...
bigcode/self-oss-instruct-sc2-concepts
def class_counts(rows): """Counts the number of each type of example in a dataset.""" counts = {} # a dictionary of label -> count. for row in rows: # in our dataset format, the label is always the last column label = row[-1] if label not in counts: counts[label] = 0 ...
bigcode/self-oss-instruct-sc2-concepts
def is_pandigital(n: int) -> bool: """Determine if n is pandigital.""" lst = set(sorted([int(i) for i in str(n)])) return len(lst) == 10
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def traverse_dict(d: Dict, key_path: str) -> Any: """ Traverse nested dictionaries to find the element pointed-to by key_path. Key path components are separated by a ':' e.g. "root:child:a" """ if type(d) is not dict: raise TypeError(f"u...
bigcode/self-oss-instruct-sc2-concepts
def is_prime(n): """ Decide whether a number is prime or not. """ if n < 2: return False if n == 2: return True if n % 2 == 0: return False i = 3 maxi = n**0.5 + 1 while i <= maxi: if n % i == 0: return False i += 2 return Tru...
bigcode/self-oss-instruct-sc2-concepts
def fluid_needed(molarity : float, mw : float , mass : float) -> float: """How much liquid do you need for a solution of a specific molarity?""" return mass/mw/molarity
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_backups_in_path(folder, file_type): """Return a collection of all backups of a specified type in a path. Use the rglob utility function to recursively search a directory for all backup files of the type `file_type`. Pass an empty string to not spe :param fold...
bigcode/self-oss-instruct-sc2-concepts
def format_xi_stats(users_as_nodes, exp, xi_mean, xi_std, tot): """Formats the curvature estimates for logging. Args: users_as_nodes: Bool indicating which interaction graph was generated. If True (False), a user-user (item-item) interaction graph was generated. exp: Boolean indicating if the interac...
bigcode/self-oss-instruct-sc2-concepts
def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co...
bigcode/self-oss-instruct-sc2-concepts
def _build_xpath_expr(attrs) -> str: """ Build an xpath expression to simulate bs4's ability to pass in kwargs to search for attributes when using the lxml parser. Parameters ---------- attrs : dict A dict of HTML attributes. These are NOT checked for validity. Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def insert_symbol(symbol: str, fbid: str, dict: dict): """ Modifies the dictionary in place by inserting the symbol as the key and the fbid as the value. If the symbol is already present in the dictionary the fbid is added to the unique set of FlyBase IDs in the value :param symbol:str - A single ...
bigcode/self-oss-instruct-sc2-concepts
import ntpath def path_leaf(path): """ guaranteed filename from path; works on Win / OSX / *nix """ head, tail = ntpath.split(path) return tail or ntpath.basename(head)
bigcode/self-oss-instruct-sc2-concepts
import re def win_path_to_unix(path, root_prefix=""): """Convert a path or ;-separated string of paths into a unix representation Does not add cygdrive. If you need that, set root_prefix to "/cygdrive" """ path_re = '(?<![:/^a-zA-Z])([a-zA-Z]:[\/\\\\]+(?:[^:*?"<>|]+[\/\\\\]+)*[^:*?"<>|;\/\\\\]+?(?![...
bigcode/self-oss-instruct-sc2-concepts
def entry_to_bytes(arch, entry: dict) -> bytes: """ Pack a U-Boot command table *entry* (struct cmd_tbl_s), as defined by the following dictionary keys and return it's representation in bytes. +---------------+---------------+----------------------------------------------+ | Key | Value T...
bigcode/self-oss-instruct-sc2-concepts
import requests import json def api_call(page, username, password): """ This function makes an API call to the leitos ocupaca API within DataSUS Arguments: page: a string or integer with the number of the page to request username: a string with the username login information for the API ...
bigcode/self-oss-instruct-sc2-concepts
def ref(i): """ref returns a string with a reference to object number `i`""" return b'%d 0 R' % i
bigcode/self-oss-instruct-sc2-concepts
def structure_metadata(structure): """ Generates metadata based on a structure """ comp = structure.composition elsyms = sorted(set([e.symbol for e in comp.elements])) meta = { "nsites": structure.num_sites, "elements": elsyms, "nelements": len(elsyms), "compositi...
bigcode/self-oss-instruct-sc2-concepts
def swap(L, i, j): """Swaps elements i and j in list L.""" tmp = L[i] L[i] = L[j] L[j] = tmp return L
bigcode/self-oss-instruct-sc2-concepts
def parse_gav(gav, defaults=(None, None, None)): """Parses the given GAV as a tuple. gav the GAV to parse. It must be a string with two colons separating the GAV parts. defaults a triple of default coordinates to return if a part from the input is missing Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def _get_indices(term, chunk): """Get indices where term appears in chunk Parameters ---------- term : str The token to look for in the `chunk` chunk : [str] A chunk of text in which to look for instances of `term` Returns ------- [int] Indices in `chunk` where ...
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def meta_tostring(metadata): """Convert the metadata dictionary to text header""" lines = [] lines.append('# {}\n'.format(metadata.get('title', ''))) for k, v in metadata.items(): if k != 'title': lines.append(f'{k}: {v}') return unicodedata.normalize('NFC'...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def get_cameras_and_objects(config: dict[str, Any]) -> set[tuple[str, str]]: """Get cameras and tracking object tuples.""" camera_objects = set() for cam_name, cam_config in config["cameras"].items(): for obj in cam_config["objects"]["track"]: camera_objects.add(...
bigcode/self-oss-instruct-sc2-concepts
def dt_to_camli_iso(dt): """ Convert a datetime to iso datetime compatible with camlistore. """ return dt.isoformat() + 'Z'
bigcode/self-oss-instruct-sc2-concepts
def floatOrNone(v, default=0.0, exctype=Exception): """Returns the float value of the given value, or default (which is normally 0.0) on error. Catches exceptions of the given exctype (Exception by default)""" try: return float(v) except exctype: return default
bigcode/self-oss-instruct-sc2-concepts
import torch def get_mrr(indices, targets): #Mean Receiprocal Rank --> Average of rank of next item in the session. """ Calculates the MRR score for the given predictions and targets Args: indices (Bxk): torch.LongTensor. top-k indices predicted by the model. targets (B): torch.LongTensor....
bigcode/self-oss-instruct-sc2-concepts
def get_valid_results(df_res): """Splits up results into valid and invalid results. Based on properties computed in data.py.""" # Select valid results (one pair of resized ellipses) cond_valid = df_res['inside'] & df_res['resized'] & (df_res['num_annot']==2) df_res_valid = df_res.loc[cond_valid...
bigcode/self-oss-instruct-sc2-concepts
import inspect from typing import Dict from typing import Any def _build_bool_option(parameter: inspect.Parameter) -> Dict[str, Any]: """Provide the argparse options for a boolean option.""" params = {"action": "store_false" if parameter.default is True else "store_true"} return params
bigcode/self-oss-instruct-sc2-concepts
def _get_default_image_id(module): """ Return the image_id if the image_id was specified through "source_details" or None. """ if "source_details" in module.params and module.params["source_details"]: source_details = module.params["source_details"] source_type = source_details.get("sour...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_test_path_services(filename, data_type): """ Gets the path of the filename for a given data type Args: filename (str): Name of file, not path data_type (str): Data type, CRDS, GC, ICOS etc Returns: pathlib.Path: Absolute path to...
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def readfile(filename: str) -> str: """Read a file that is contained in the openclean_notebook package. This is a helper method to read Javascript files and HTML templates that are part of the openclean_notebook package. Returns a string containing the file contents. Paramet...
bigcode/self-oss-instruct-sc2-concepts
import string def add_numbering(ax, i=0, loc=(0.8, 0.8), label='', style='APS', numbering='abc', **kwargs): """ Add numbering (a,b,c,...) to axis. Parameters ---------- ax : matplotlib.pyplot.axis object i : int The axis index, e.g., i=1 -> (a) loc : tuple or list Position of label, relative to...
bigcode/self-oss-instruct-sc2-concepts
import re def normalize_tag_name(name): """ Normalize an EC2 resource tag to be compatible with shell environment variables. Basically it means the the following regex must be followed: [a-Z][a-Z0-9_]*. This function is not meant to handle all possible corner cases so try not to be stupid with tag naming....
bigcode/self-oss-instruct-sc2-concepts
def cmd_name(python_name): """Convert module name (with ``_``) to command name (with ``-``).""" return python_name.replace('_', '-')
bigcode/self-oss-instruct-sc2-concepts
def hash_string(s, is_short_hash=False): """Fowler–Noll–Vo hash function""" if not is_short_hash: h = 14695981039346656037 for c in s: h = ((h ^ ord(c)) * 1099511628211) & 0xFFFFFFFFFFFFFFFF if h == 0: h = 1 # Special case for our application (0 is reserved inter...
bigcode/self-oss-instruct-sc2-concepts
import csv def create_mapping(path, src, dest, key_type=None) -> dict: """ Create a dictionary between two attributes. """ if key_type is None: key_type = int with open(path, 'r') as f: reader = csv.DictReader(f) raw_data = [r for r in reader] mapping = {key_type(row[src])...
bigcode/self-oss-instruct-sc2-concepts
def set_axis(mode_pl): """Sets Active Axes for View Orientation. Note: Sets indices for axes from taper vectors Axis order: Rotate Axis, Move Axis, Height Axis Args: mode_pl: Taper Axis Selector variable as input Returns: 3 Integer Indicies. """ order = { ...
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_pickle(pickle_path): """Utility function for loading .pkl pickle files. Arguments --------- pickle_path : str Path to pickle file. Returns ------- out : object Python object loaded from pickle. """ with open(pickle_path, "rb") as f: ...
bigcode/self-oss-instruct-sc2-concepts
def update_params(params, **kwargs): """ Updates a dictionary with the given keyword arguments Parameters ---------- params : dict Parameter dictionary **kwargs : kwargs New arguments to add/update in the parameter dictionary Returns ------- params : dict Up...
bigcode/self-oss-instruct-sc2-concepts
def docker_push_age(filename): """Check when the Docker image was last pushed to Docker Hub.""" try: with open(filename, "r") as handle: return float(handle.read().strip()) except FileNotFoundError: return 0
bigcode/self-oss-instruct-sc2-concepts
def is_triangle(triangle: int): """any tn in triangle sequence is t = ½n(n+1): Solving with quadratic formula reveals n is only an integer if (1+8t) ** 0.5 is an integer and odd""" if int((1+8*triangle)**0.5) == (1+8*triangle)**0.5 and ((1+8*triangle)**0.5)%2 == 1: return True return False
bigcode/self-oss-instruct-sc2-concepts
import re def make_write_file_block(content:str, outname:str, directory:str='/usr/local/etc/ehos/'): """ makes a yaml write_file content block Args: content: what to enter as content into the block outname: the filename the yaml points to directory: the directory the yaml points to ...
bigcode/self-oss-instruct-sc2-concepts
def flatten_dict(a_dict, parent_keys=None, current_parent_key=None): """Given a dict as input, return a version of the dict where the keys are no longer nested, and instead flattened. EG: >>> flatten_dict({"a": {"b": 1}}) {"a.b": 1} NB: The kwargs are only for internal use of the functi...
bigcode/self-oss-instruct-sc2-concepts
def filter(record): """ Filter for testing. """ return record if record["str"] != "abcdef" else None
bigcode/self-oss-instruct-sc2-concepts
def sort(source_list, ignore_case=False, reverse=False): """ :param list source_list: The list to sort :param bool ignore_case: Optional. Specify true to ignore case (Default False) :param bool reverse: Optional. Specify True to sort the list in descending order (Default False) :return: The sorted ...
bigcode/self-oss-instruct-sc2-concepts
def get_scene(videoname): """ActEV scene extractor from videoname.""" s = videoname.split("_S_")[-1] s = s.split("_")[0] return s[:4]
bigcode/self-oss-instruct-sc2-concepts
def VtuFieldComponents(vtu, fieldName): """ Return the number of components in a field """ return vtu.ugrid.GetPointData().GetArray(fieldName).GetNumberOfComponents()
bigcode/self-oss-instruct-sc2-concepts
def get_note_title(note): """get the note title""" if 'title' in note: return note['title'] return ''
bigcode/self-oss-instruct-sc2-concepts
def merge(source, target): """Merge a source dictionary into a target dictionary :param source: source dictionary :param target: target dictionary :return: source merged into target """ for key, value in source.items(): if isinstance(value, dict): # get node or create one ...
bigcode/self-oss-instruct-sc2-concepts
def get_type_and_tile(erow): """ Trivial function to return the OBSTYPE and the TILEID from an exposure table row Args: erow, Table.Row or dict. Must contain 'OBSTYPE' and 'TILEID' as keywords. Returns: tuple (str, str), corresponding to the OBSTYPE and TILEID values of the input erow....
bigcode/self-oss-instruct-sc2-concepts
def inject(variables=None, elements=None): """ Used with elements that accept function callbacks. :param variables: Variables that will be injected to the function arguments by name. :param elements: Elements that will be injected to the function arguments by name. """ def wrapper(fn): ...
bigcode/self-oss-instruct-sc2-concepts
def increment(number): """Increases a give number by 1.""" return number + 1
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple def three_variables_large_mean_differences() -> List[Tuple[Tuple[float, float, float], float]]: """Each entry represents three random variables. The format is: ( (mean1, mean2, mean3), covariance_scale ) and covariance scale controls how...
bigcode/self-oss-instruct-sc2-concepts
def pivot_genres(df): """Create a one-hot encoded matrix for genres. Arguments: df -- a dataFrame containing at least the columns 'movieId' and 'genre' Output: a matrix containing '0' or '1' in each cell. 1: the movie has the genre 0: the movie does not have the genre """ r...
bigcode/self-oss-instruct-sc2-concepts
def check_error(http): """ Checks for http errors (400 series) and returns True if an error exists. Parameters ---------- http : addinfourl whose fp is a socket._fileobject Returns ------- has_error : bool """ err = http.code if 400<= err < 500: print("HTTP error {}...
bigcode/self-oss-instruct-sc2-concepts
def bproj(M, P): """Project batched marices using P^T M P Args: M (torch.tensor): batched matrices size (..., N, M) P (torch.tensor): Porjectors size (..., N, M) Returns: torch.tensor: Projected matrices """ return P.transpose(1, 2) @ M @ P
bigcode/self-oss-instruct-sc2-concepts
def is_sequence(nums): """Return True if a set of numbers is sequential i.e. 8, 11, 14, 17.""" nums = sorted(list(nums)) if len(nums) < 3: return False while nums: first_difference = nums[1] - nums[0] second_difference = nums[2] - nums[1] if first_difference != second_di...
bigcode/self-oss-instruct-sc2-concepts
def PickUpTextBetween(text,startstr,endstr): """ Pick up lines between lines having "stratstr" and "endstr" strings :param str text: text data :param str startstr: start string :param str endstr: end string :return: text list :rtype: lst """ rtext=""; start=False for ss in text:...
bigcode/self-oss-instruct-sc2-concepts
from typing import Set from pathlib import Path import yaml def _ci_patterns() -> Set[str]: """ Return the CI patterns given in the CI config file. """ repository_root = Path(__file__).parent.parent ci_file = repository_root / '.github' / 'workflows' / 'ci.yml' github_workflow_config = yaml.sa...
bigcode/self-oss-instruct-sc2-concepts
def get_center(bounds): """ Returns given element center coords:: from magneto.utils import get_center element = self.magneto(text='Foo') (x, y) = get_center(element.info['bounds']) :param dict bounds: Element position coordinates (top, right, bottom, left) :return: x and y co...
bigcode/self-oss-instruct-sc2-concepts
def check_kwargs(input_kwargs, allowed_kwargs, raise_error=True): """Tests if the input `**kwargs` are allowed. Parameters ---------- input_kwargs : `dict`, `list` Dictionary or list with the input values. allowed_kwargs : `list` List with the allowed keys. raise_error : `bool...
bigcode/self-oss-instruct-sc2-concepts