seed
stringlengths
1
14k
source
stringclasses
2 values
def categorical_features(df): """ Return categorical features of dataframe :param df: pandas dataframe :return: summary: list that contains categorical features """ categorical_col = df.select_dtypes(include=['object']).columns.tolist() return categorical_col
bigcode/self-oss-instruct-sc2-concepts
def check_predicates(goal, atom): """ Checks if the predicates match in name and arity. :param goal: the goal :type goal: Atom :param atom: the atom :type atom: Atom :return: `True`, if they match; otherwise, `False` :rtype: bool """ return goal.predicate == atom.predicate
bigcode/self-oss-instruct-sc2-concepts
import random import math def randomPointOnSphere(r=1., center=(0.,0.,0.)): """compute random point on sphere with uniform distribution on surface. Usage can be as simple as that: >>> p = randomPointOnSphere() We expect a point with 3 coordinates and distance 1 from the origin: >>> len(p) # three c...
bigcode/self-oss-instruct-sc2-concepts
def linereader_int(file): """Read input file and return a tuple with content converted to ints.""" file = open(file, "r") return tuple(map(int, [line.rstrip("\n") for line in file.readlines()]))
bigcode/self-oss-instruct-sc2-concepts
def q_to_q(q): """ identity map from q to q Surrogates with this parameterization expect its user intput to be the mass ratio q, and "map" to the internal surrogate's parameterization which is also q The surrogates training interval is in mass ratio """ return q
bigcode/self-oss-instruct-sc2-concepts
def is_project_user(user, project): """Return if user is a member of project.users.""" return user in project.users.all()
bigcode/self-oss-instruct-sc2-concepts
def partition(sequence, predicate): """ Partition the sequence into two lists, according to the function provided. Args: sequence: A sequence of elements. predicate: A function of one argument, returning bool. Returns: A tuple of lists, where the first list contains all ...
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 def get_db_connection(db_file: str): """ Connect to DB :param db_file - a string filepath to the sqlite db file :return: sqlite_connection and cursor """ conn = sqlite3.connect(db_file) cursor = conn.cursor() return conn, cursor
bigcode/self-oss-instruct-sc2-concepts
def _combine_odds(odds): """Combine the odds of different outcomes.""" combined_odds = 1 / (1 / odds).sum(axis=1) return combined_odds
bigcode/self-oss-instruct-sc2-concepts
def zeros_matrix(rows, cols): """ Creates a matrix filled with zeros. :param rows: the number of rows the matrix should have :param cols: the number of columns the matrix should have :return: list of lists that form the matrix """ M = [] while len(M) < rows: M.append(...
bigcode/self-oss-instruct-sc2-concepts
def getPageContent(r): """ Returns the source code of a web page """ return r.text
bigcode/self-oss-instruct-sc2-concepts
def get_processing_speech(vocab_speech = None): """ Function: Return function that maps the speech key to a set of interval and word ids Args: vocab: dict[key] = idx Returns: f("2005-A-10-1-5") = ([12, 4, 32], 12345) = (list of interval ids, word id) """ ...
bigcode/self-oss-instruct-sc2-concepts
import re def is_mixed_case(s): """ >>> is_mixed_case('HiThere') True >>> is_mixed_case('Hi There') True >>> is_mixed_case('hi there') False >>> is_mixed_case('h') False >>> is_mixed_case('H') False >>> is_mixed_case(None) False """ if not isinstance(s...
bigcode/self-oss-instruct-sc2-concepts
def to_binary(n, N): """ Get binary representation of input n :param n: Integer of which to get binary representation :param N: Length of bitstring :return: str """ return bin(n).replace('0b', '').zfill(N)
bigcode/self-oss-instruct-sc2-concepts
def _encode_module(module): """Encode a :class:`~schedsi.module.Module` to a :obj:`dict`.""" return {'name': module.name}
bigcode/self-oss-instruct-sc2-concepts
def _extract_name_arg(args, kwargs, name_index): """Extracts the parameter `name` and returns `(args, kwargs, name_value)`.""" if name_index < 0: name_value = None elif name_index < len(args): name_value = args[name_index] args = args[:name_index] + args[name_index + 1:] else: name_value = kwarg...
bigcode/self-oss-instruct-sc2-concepts
def coefficient_of_drag_morrison(state, only_in_range=False): """ Calculate the coefficient of drag using the equation provided from http://www.chem.mtu.edu/~fmorriso/DataCorrelationForSphereDrag2013.pdf Enter: state: a dictionary of the current state. Includes Reynolds and mach numb...
bigcode/self-oss-instruct-sc2-concepts
def factors_pairs(num): """ (int) -> list Builds a list of factor pairs for a positive integer <num>. for example, tuple (2, 15) is a factor pair for the number 30 because 2 x 15 is 30. Returns the list of factor-pair tuples """ return [(x, num//x) for x in range(1, num + 1) if num % x ==...
bigcode/self-oss-instruct-sc2-concepts
def non_fm_sex(row): """Return True if sex is not F or M.""" return row["sex"] not in ["F", "M"]
bigcode/self-oss-instruct-sc2-concepts
def getFormat( self ) : """Checks if self has a getFormat method. If it does not, then None is returned. If it does then: 1) if getFormat returns a string or None then it is returned else getFormat must return an integer, n1. If n1 is 12 (default for legacy ENDL) then None is returned else returns string ...
bigcode/self-oss-instruct-sc2-concepts
import math def quantize(number, stepsize): """Quantizes number to a given step size.""" return math.floor( (number/stepsize) + .5) * stepsize
bigcode/self-oss-instruct-sc2-concepts
import re def safe_content(content: str) -> str: """Make content safe. Replaces variable with ellipsis and strips any HTML tags. :param (str) content: Input string. :returns (str): Modified string. """ if content is not None: # Replace piping with ellipsis content = re.sub(r"...
bigcode/self-oss-instruct-sc2-concepts
def sum_runs(df): """Adds together all the runs to get a value for total profit Parameters: df (pandas.core.frame.DataFrame): data frame containing the simulation Returns: dictionary: dictionary containing the results summed up for the total profit visualisation. """ lists = [i for i i...
bigcode/self-oss-instruct-sc2-concepts
def to_id(file_name): """ Converts the file name of an image to the corresponding base name. Example: image.jpg -> image :param file_name: the name of an image file (JPG) :return: the base name of the given image file """ if file_name[-4:] == ".jpg": file_name = file_name[:-4] re...
bigcode/self-oss-instruct-sc2-concepts
def parse_sintax_fasta_entry(text, known_species=None): """Extract the species from SINTAX taxonomy annotation. See https://drive5.com/usearch/manual/tax_annot.html which defines this taxonomy annotation convention as used in USEARCH and VSEARCH. The tax=names field is separated from other fields in th...
bigcode/self-oss-instruct-sc2-concepts
def parse_html(soup): """Parses BeautifulSoup object and returns the table :param soup: BeautifulSoup object :return: List of the rows that make up the table """ table = soup.find("table", {"id": "minecraft_items"}) data = [ [td.get_text() for td in row.find_all("td")] for row in table....
bigcode/self-oss-instruct-sc2-concepts
import torch def sequence_masking(x: torch.Tensor, mask: torch.Tensor, axis=1, mode='add', inf=1e12): """序列 mask Args: x: 2D 或 2D 以上张量,必须包含 batch_size 和 seq_len 两个维度 mask: 形如 (batch_size, seq_len) 的 0/1 矩阵 axis: 需要 mask 的维度,即 seq_len 所在维度,默认为...
bigcode/self-oss-instruct-sc2-concepts
def compute_iou_tk(rec1, rec2): """ computing IoU :param rec1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param rec2: (y0, x0, y1, x1) :return: scala value of IoU """ # computing area of each rectangles S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1]) ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def anomaly(dset, clim_freq, slice_mon_clim_time=None, time_coord_name=None): """Compute anomalies for a specified time frequency Parameters ---------- dset : xarray.Dataset The data on which to operate clim_freq : str Climatology frequency alias....
bigcode/self-oss-instruct-sc2-concepts
import grp def get_group_from_gid(gid): """Return group name from GID Looks up group name matching the supplied GID; returns None if no matching name can be found. """ try: return grp.getgrgid(int(gid)).gr_name except (KeyError,ValueError,OverflowError): return None
bigcode/self-oss-instruct-sc2-concepts
def readfile_to_list(pathin, strip=True): """Read file into a list of lines. Strip off newline symbols if strip=True""" f=open(pathin,'r') listin=f.readlines() f.close() if strip: listout = [line.strip() for line in listin] else: listout = listin return listout
bigcode/self-oss-instruct-sc2-concepts
import torch def normalize_batch_per_example(tensor, normalize_mean=True, normalize_std=True): """Normalize batch of tensors by mean and variance Mean and variance are computed per channel and example Parameters ---------- tensor : torch.Tens...
bigcode/self-oss-instruct-sc2-concepts
def pad_b64(b64s): """Pad Base64 encoded string so that its length is a multiple of 4 bytes""" pad = len(b64s) % 4 if pad != 0: return b64s + '=' * pad return b64s
bigcode/self-oss-instruct-sc2-concepts
def _dataframe_formatter(x): """Format a dataframe element.""" return f"<DF {x.shape[0]}x{x.shape[1]}>"
bigcode/self-oss-instruct-sc2-concepts
def remove_formatting(formatted_text): """Throw away style info from prompt_toolkit formatted text tuples.""" return ''.join([formatted_tuple[1] for formatted_tuple in formatted_text])
bigcode/self-oss-instruct-sc2-concepts
def contains(indices1, indices2): """Returns a boolean indicating whether indices1 contain indices2""" if indices1[0] <= indices2[0] and indices1[1] >= indices2[1]: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def is_classifier(estimator): """Return True if the given estimator is (probably) a classifier. Parameters Function from base.py in sklearn ---------- estimator : object Estimator object to test. Returns ------- out : bool True if estimator is a classifier and False othe...
bigcode/self-oss-instruct-sc2-concepts
def create_two_embedding_dicts(dict_snapshots, dict_projections): """ First initialization of the two wanted embedding dictionaries. They are first embed with the nodes of the first snapshot and their embeddings. :param dict_snapshots: Dict where keys are times and values are a list of edges for each ti...
bigcode/self-oss-instruct-sc2-concepts
def collided_with_level(player_state, previous_position): """ Called whenever the player bumps into a wall. Usually, you just want to set player_state["position"] = previous_position :param player_state: Our state :param previous_position: Where were we before be bumped into the wall? :...
bigcode/self-oss-instruct-sc2-concepts
def sort(df, sort_column, ascending=True): """ Sorts a given DataFrame by a given column and returns it. :param df: (pandas DataFrame) the data to be sorted. :param sort_column: (string) describes which column on the given DataFrame to sort. Raises KeyError if the column does no...
bigcode/self-oss-instruct-sc2-concepts
def to_weekly(series, method='ffill', how='end'): """ Convenience method that wraps asfreq_actual with 'M' param (method='ffill', how='end'). """ return series.asfreq_actual('W', method=method, how=how)
bigcode/self-oss-instruct-sc2-concepts
import hashlib import struct def _hash_dimensions(dimensions_json): """Returns a 32 bits int that is a hash of the dimensions specified. dimensions_json must already be encoded as json. The return value is guaranteed to be non-zero so it can be used as a key id in a ndb.Key. """ digest = hashlib.md5(dim...
bigcode/self-oss-instruct-sc2-concepts
def get_edge(from_node, to_node, properties, edge_relationship_name, encoder): """converts a NetworkX edge into a Geoff string. :param from_node: the ID of a NetworkX source node :param to_node: the ID of a NetworkX target node :param properties: a dictionary of edge attributes :param edge_relation...
bigcode/self-oss-instruct-sc2-concepts
def _bold() -> str: """Internal function returning ANSI escape sequence bolding foreground color""" return '\033[1m'
bigcode/self-oss-instruct-sc2-concepts
import inspect def call_func(f_callable, only_mandatory=False, **kwargs): """Calls a function with the given parameters given in kwargs if they exist as parameters in f_callable. Parameters ---------- f_callable : callable The function or object that is to be called only_mandatory : b...
bigcode/self-oss-instruct-sc2-concepts
import torch def load_model(model, checkpoint_path, gpu_ids, return_step=True): """Load model parameters from disk. Args: model (torch.nn.DataParallel): Load parameters into this model. checkpoint_path (str): Path to checkpoint to load. gpu_ids (list): GPU IDs for DataParallel. ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import pathlib def _covert_legacy_entry(entry: Tuple[str, ...], info: Tuple[str, ...]) -> str: """Convert a legacy installed-files.txt path into modern RECORD path. The legacy format stores paths relative to the info directory, while the modern format stores paths relative to the...
bigcode/self-oss-instruct-sc2-concepts
def findAlleleIndex(record, allele): """ Find the index of an allele in a VCF record """ alleles = [record.ref] + record.alt; if allele not in alleles: return -1; else: return alleles.index(allele);
bigcode/self-oss-instruct-sc2-concepts
import struct def int_to_float(n): """ convert from an 4-byte integer to 4-byte floating point number :param n: 4-byte integer :return: 4-byte floating point number """ return struct.unpack('@f', struct.pack('@I', n))[0]
bigcode/self-oss-instruct-sc2-concepts
def read_target_source(target): """ Processes file so we can write newly minted docstrings. :param target: Target file :returns: List of lines in target file """ f = open(target.__file__) file_contents = f.readlines() return file_contents
bigcode/self-oss-instruct-sc2-concepts
def grad_flow(model): """ Returns a dictionary containing the mean of each layer gradient Parameters ---------- model : torch.nn.Module the module to extract the gradient flow from Returns ------- dict a dictionary with the key being the layer name and its value being t...
bigcode/self-oss-instruct-sc2-concepts
def _create_neighbor_dict(codons): """ Create minimum neighbor distances for each amino acid given the genetic code. Parameters ---------- codons : dict dictionary mapping codons to single-letter amino acid codes Returns ------- neighbor_dict : dict dictionary mappi...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def patch_extr_svs_npy_read(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction svs_read npy. Download sample patch extraction svs_read npy for pytest. """ return remote_sample("patch-extraction-svs-read-npy")
bigcode/self-oss-instruct-sc2-concepts
def _rounder(val, tol): """ Utility function to round numbers to arbitrary tolerance """ return round((1.0 * val) / tol) * tol
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources async def version(): """Get dependency versions """ versions = {} for name in ('instagrapi', ): item = pkg_resources.require(name) if item: versions[name] = item[0].version return versions
bigcode/self-oss-instruct-sc2-concepts
def merge(x, y): """Merge two ordered lists :param x: :param y: x,y are non decreasing ordered lists :returns: union of x and y in order :complexity: linear """ z = [] i = 0 j = 0 while i < len(x) or j < len(y): if j == len(y) or i < len(x) and x[i] <= y[j]: # priority ...
bigcode/self-oss-instruct-sc2-concepts
import re def station_name_hyphenate(sub: str) -> str: """Hyphenates names like 'Dapto to Wollongong' as 'Dapto-Wollongong'.""" return re.sub(r"\ To\ ", "-", sub, re.IGNORECASE)
bigcode/self-oss-instruct-sc2-concepts
def center_trim(tensor, reference): """ Center trim `tensor` with respect to `reference`, along the last dimension. `reference` can also be a number, representing the length to trim to. If the size difference != 0 mod 2, the extra sample is removed on the right side. """ if hasattr(reference, "s...
bigcode/self-oss-instruct-sc2-concepts
def factorial(n): """return n factorial The factorial is defined as n! = n*(n-1)! Note: The recursive factoial implementation will break down if n is too large """ if(n==0): return 1 else: return n*factorial(n-1)
bigcode/self-oss-instruct-sc2-concepts
import glob def make_filelist(path): """Makes a list of files through which the program may iterate Args: path (str): a string indicating the path in which the tweets are stored """ #initial array for the read-in tweets files = glob.glob(path) files.sort() return files
bigcode/self-oss-instruct-sc2-concepts
def add_lines(name, content, is_file, boundary, lines): """Add content to lines with proper format needed for multipart content type. :param name: name of the request parameter :param content: contents of the request parameter :param is_file: is the parameter a file type (for adding filename) :...
bigcode/self-oss-instruct-sc2-concepts
def square_frame_size(radius): """Compute the number of pixels of the external frame of square neighbourhoods of the given radii. Parameters ---------- radius : list of int Radii of the local neighborhoods. Returns ---------- points : list of int Number of pixels of the...
bigcode/self-oss-instruct-sc2-concepts
def bNoNL(p): """check if contains any RC, NL or FF chars""" for c in p: if c in [0xA, 0xC, 0xD]: return False return True
bigcode/self-oss-instruct-sc2-concepts
def y(P): """ Return :class:`P.y` or :class:`P[1]`. Args: P (:class:`list`): ``secp256k1`` point Returns: :class:`int`: y """ return P[1]
bigcode/self-oss-instruct-sc2-concepts
import uuid def generate_request_id(original_id=''): """Generate request id.""" new_id = uuid.uuid4() if original_id: new_id = '{}, {}'.format(original_id, new_id) return new_id
bigcode/self-oss-instruct-sc2-concepts
import torch def are_broadcastable(a: torch.Tensor, b: torch.Tensor) -> bool: """ Returns True if the two tensor are broadcastable to each other, False otherwise. """ return all((m == n) or (m == 1) or (n == 1) for m, n in zip(a.shape[::-1], b.shape[::-1]))
bigcode/self-oss-instruct-sc2-concepts
import textwrap def dedent(text): """Equivalent of textwrap.dedent that ignores unindented first line. This means it will still dedent strings like: '''foo is a bar ''' For use in wrap_paragraphs. Taken from https://github.com/ipython/ipython_genutils/text.py """ if text.star...
bigcode/self-oss-instruct-sc2-concepts
def bdev_split_create(client, base_bdev, split_count, split_size_mb=None): """Create split block devices from a base bdev. Args: base_bdev: name of bdev to split split_count: number of split bdevs to create split_size_mb: size of each split volume in MiB (optional) Returns: ...
bigcode/self-oss-instruct-sc2-concepts
import socket import struct def tcp_socket_constructor(linger_time=10, tcp_no_delay=1): """ Create a new TCP socket with reasonable socket options set. :param linger_time: The linger time after closing the socket to allow buffers to flush. Default: 10 :type linger_time: int :param tcp_no_delay: 1...
bigcode/self-oss-instruct-sc2-concepts
def is_pos_int(val): """Check if value is positive integer""" return isinstance(val, int) and val > 0
bigcode/self-oss-instruct-sc2-concepts
def append_all(src_str, append, delimiter): """ Add the append string into each split sub-strings of the first string(=src=). The split is performed into src string using the delimiter . E.g. appendAll("/a/b/,/c/b/,/c/d/", "ADD", ",") will return /a/b/ADD,/c/b/ADD,/c/d/ADD. A append string with null...
bigcode/self-oss-instruct-sc2-concepts
import click def confirm_choice(choice, default=True, abort=True): """Returns a bool from a yes/no question presented to the end user. Args: choice (str): the question presented to the end user. default (bool): the default for the confirmation answer. If True the default is Y(es),...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_logger(name): """ Return a :class:`~py:logging.Logger` object with the specified name. A :class:`~py:logging.NullHandler` handler is added to the logger if it does not have any handlers yet and if it is not the Python root logger. This prevents the propagation of log reques...
bigcode/self-oss-instruct-sc2-concepts
import yaml def read_yaml(fname): """Parse yaml file and return a dict.""" metadict = {} try: with open(fname, 'r') as yaml_file: metadict = yaml.safe_load(yaml_file) except Exception as e: print("Error loading {file}\n{error}".format(file=fname, error=e)) return meta...
bigcode/self-oss-instruct-sc2-concepts
def ansible_hostname(hostname: str): """Convert hostname to ansible format""" return hostname.replace("-", "_")
bigcode/self-oss-instruct-sc2-concepts
def cobb_douglas_output(k, alpha, **params): """Cobb-Douglas output (per unit effective labor supply).""" return k**alpha
bigcode/self-oss-instruct-sc2-concepts
import torch def from_coord_to_patch(ortho, fps, big_fp): """Returns an n batch of the input ortho using fps (footprints).""" image_patches = [] for fp in fps: partial_patch = ortho[:, fp.slice_in(big_fp)[0], fp.slice_in(big_fp)[1]] image_patches.append(partial_patch) image_patches = t...
bigcode/self-oss-instruct-sc2-concepts
def zero_dose(t, X): """Dose function returns zero dose at all times. :param t: current time point :type t: float :param X: amount of dose administered :type X: float :return: zero :rtype: float """ return 0.
bigcode/self-oss-instruct-sc2-concepts
def localize_url(url, locale_code): """Append language tag to URL and return""" if not locale_code: return url if url and 'languageId' not in url: delimiter = '&' if '?' in url else '?' return "{url}{delimiter}languageId={locale_code}".format( url=url, delimiter=delimiter...
bigcode/self-oss-instruct-sc2-concepts
def autorange(timer, callback=None): """Return the number of loops so that total time >= 10. timer should be a timeit.Timer instance. Calls the timeit method with *number* set to successive powers of two (1, 2, 4, 8, ...) up to a maximum of 2**21, until the time taken is at least 10 seconds, or th...
bigcode/self-oss-instruct-sc2-concepts
import math def shield_rating(shield, max_shield): """ Calculate a 0%-100% shield recharge/capacity rating for a ship Given the actual shield recharge or capacity value as well as the perfect value for the total mass of a ship, give it a rating between 0% and 100% using a smoothed curve that increase...
bigcode/self-oss-instruct-sc2-concepts
def version_update_handler(version, version_update_strategy): """ This method takes the current version and a function that produces a new version, and removes and re-adds non-numeric version qualifiers (such as "-SNAPSHOT"), if necessary. 1st argument: the current version 2nd argument: a func...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def make_ngrams(n: int, tokens: List[str]): """ Create N-grams for given set of tokens. example: -------- > make_ngrams(2, ["have", "a", "good", "day"]) < [("have", "a), ("a", "good"), ("good", "day")] """ ngrams = zip(*[tokens[i:] for i in range(n)]) retu...
bigcode/self-oss-instruct-sc2-concepts
def readInQuery(textFile): """Read in a textfile with an HTSQL query""" #read in text file query='' for line in open(textFile): query+=line query=query.strip() return query
bigcode/self-oss-instruct-sc2-concepts
import re def parse_python_version(output): """Parse a Python version output returned by `python --version`. Return a dict with three keys: major, minor, and micro. Each value is a string containing a version part. Note: The micro part would be `'0'` if it's missing from the input string. """ ...
bigcode/self-oss-instruct-sc2-concepts
def get_filename(start, stop): """ Create filename for time interval Parameters ---------- start : integer Start year stop : integer Stop year Returns ------- filename : string Filename """ # Set filename filename = '_%4.4d-%4.4d' % (start, stop)...
bigcode/self-oss-instruct-sc2-concepts
def get_cropped_array(png_array): """Crop the array neatly to the center 100x100 points Notes: - this has only been tested on 1000x1000 size lattice images """ xlen, ylen, _ = png_array.shape cropped_png_array = png_array[0.4165*xlen:0.5143*xlen, 0.4627*ylen:0.5623*ylen, :] return croppe...
bigcode/self-oss-instruct-sc2-concepts
def move_to_ctx(arr, ctx): """Move a nested structure of array to the given context Parameters ---------- arr The input array ctx The MXNet context Returns ------- new_arr The array that has been moved to context """ if isinstance(arr, tuple): re...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def calc_package_index_hash(deb_names): """ Calculates a hash of all the given deb file names. This is deterministic so we can use it for short-circuiting. """ md5 = hashlib.md5() md5.update("\n".join(sorted(deb_names)).encode('utf-8')) return md5.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def _is_via_hub(node): """Check if a node is a Via Labs hub. The topology of this device is a 4-port hub, with another 4-port hub connected on port 4. """ if '2109:2812' not in node.desc and '2109:0812' not in node.desc: return False if not node.HasPort(4): return False return ('2109:2812' in node...
bigcode/self-oss-instruct-sc2-concepts
def CheckAttr(f): """Automatically set mock_attr based on class default. This function decorator automatically sets the mock_attr keyword argument based on the class default. The mock_attr specifies which mocked attribute a given function is referring to. Raises an AssertionError if mock_attr is left unspec...
bigcode/self-oss-instruct-sc2-concepts
import math def lsf_format_bytes_ceil(n, lsf_units="mb"): """ Format bytes as text Convert bytes to megabytes which LSF requires. Parameters ---------- n: int Bytes lsf_units: str Units for the memory in 2 character shorthand, kb through eb Examples -------- >>> ...
bigcode/self-oss-instruct-sc2-concepts
def rmin(a, b): """ Min function for real numbers Parameters ---------- a: scalar b: scalar Returns ------- scalar """ # seems to be much faster than the built-in return a if a < b else b
bigcode/self-oss-instruct-sc2-concepts
def get_user_printable_name(user, errstring="???"): """ Gets name of user in printable form. :param user: user object :param errstring: string to return if name could not be resolved :return: user.nick if exists, user.name otherwise (if exists), errstring if nick and name are missing """ i...
bigcode/self-oss-instruct-sc2-concepts
def define_interval(weight, eps, method): """ :param weight: element weight :param eps: measurement error :param method: method for interval construction (0 - error is absolute, 1 - error is relative) :return: interval value """ if method == 0: return weight - eps, weight + eps e...
bigcode/self-oss-instruct-sc2-concepts
def _infer_n_folds(cv_results): """ Gets the number of CV folds from a cv_results object Parameters ---------- cv_results: dict The cv results. Output ------ cv: int The number of cv folds """ split_keys = [k for k in cv_results.keys() if k.spl...
bigcode/self-oss-instruct-sc2-concepts
import random import hashlib def md5(*args): """Generates MD5 based on the provided string or a random int""" value = "" if len(args) > 0: value = args[0] if value == "": value = str(random.getrandbits(128)) return hashlib.md5(value.encode('utf-8')).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def cigarops2string(cigarOps): """ Takes in a list of cigar tuples (c.op in the set MID, c.size is an int) and returns a cigar string (all concatenated together) """ # common case if len(cigarOps)== 1: return str(cigarOps[0].size) + cigarOps[0].op # general return "".join( [str(c.size) + c.op for c ...
bigcode/self-oss-instruct-sc2-concepts
def checkFilter(filters, record): """Check record against filters.""" for i in filters: if i.http: if not record.http: return False value = record.http else: value = record.header string = value.get(i.k, None) if not string or ...
bigcode/self-oss-instruct-sc2-concepts
def contains_3_consecutive(list_of_nums): """Return True if the list contains 3 consecutive numbers each increasing by 1.""" for i in range(len(list_of_nums) - 2): if (list_of_nums[i+1] == list_of_nums[i] + 1 and list_of_nums[i+2] == list_of_nums[i] + 2): return True return ...
bigcode/self-oss-instruct-sc2-concepts