seed
stringlengths
1
14k
source
stringclasses
2 values
import re def solution(s): """ Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). """ if not len(s) % 2 == 0: ...
bigcode/self-oss-instruct-sc2-concepts
def compute_conv_output_dim(ifm_dim, k, stride, total_pad=0, dilation=1): """Returns spatial output dimension size for convolution with given params. total_pad gives the total amount of padding along the entire axis (both sides included). """ if ifm_dim == 1: # indicates dummy dimension, kee...
bigcode/self-oss-instruct-sc2-concepts
import re def find_str(string: str, pattern: str) -> list: """ Find all indices of patterns in a string Parameters ---------- string : str input string pattern : str string pattern to search Returns ------- ind : list list of starting indices """ i...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import List def _continuous_columns(feature_types: Dict) -> List[str]: """ Parameters ---------- feature_types : Dict Column name mapping to list of feature types ordered by most to least relevant. Returns ------- List[str] List of colum...
bigcode/self-oss-instruct-sc2-concepts
import builtins def any(iterable, pred): """Returns True if ANY element in the given iterable is True for the given pred function""" return builtins.any(pred(x) for x in iterable)
bigcode/self-oss-instruct-sc2-concepts
def tri_ravel(l, m1, m2): """Ravel indices for the 'stack of triangles' ordering.""" # m1 must be >= m2 if m1 < m2 or m1 > l or m2 > l or m1 < 0 or m2 < 0: raise ValueError("Invalid indices") base = l * (l + 1) * (l + 2) // 6 offset = (l - m1) * (l + 3 + m1) // 2 + m2 ind = base + offset...
bigcode/self-oss-instruct-sc2-concepts
def _create_dictionary(sequences): """ Create id/token mappings for sequences. :param sequences: list of token sequences :return: mappings from id to token, and token to id """ tokens = {} for s in sequences: for token in s: tokens[token] = tokens.get(token, 0) + 1 s...
bigcode/self-oss-instruct-sc2-concepts
import lzma import json def raw_numpy_to_object(numpy_bytes_array): """Convert numpy array to a Python object. Args: numpy_bytes_array: a numpy array of bytes. Returns: Return a Python object. """ return json.loads( lzma.decompress(numpy_bytes_array.tobytes()).decode('ut...
bigcode/self-oss-instruct-sc2-concepts
def repeated(pattern, sep, least=1, most=None): """ Returns a pattern that matches a sequence of strings that match ``pattern`` separated by strings that match ``sep``. For example, for matching a sequence of ``'{key}={value}'`` pairs separated by ``'&'``, where key and value contains only lowercas...
bigcode/self-oss-instruct-sc2-concepts
def norm_rows(X, stats=None): """ Normalize the rows of the data. X is an M-by-N array to normalize. It is modified in-place. The data is not returned. If stats is given it must be a sequence of 2 M-length arrays for the min and max statistics to normalize by instead of calculating them fr...
bigcode/self-oss-instruct-sc2-concepts
def createboard(rows,columns): """ Creates a string given rows and columns desired that can be converted into a matrix through numpy >>> createboard(5,4) '0,0,0,0,0; 0,0,0,0,0; 0,0,0,0,0; 0,0,0,0,0' >>> createboard(3,7) '0,0,0; 0,0,0; 0,0,0; 0,0,0; 0,0,0; 0,0,0; 0,0,0' """ row_size ...
bigcode/self-oss-instruct-sc2-concepts
def make_histogram(s): """Make a map from letters to number of times they appear in s. s: string Returns: map from letter to frequency """ hist = {} for x in s: hist[x] = hist.get(x, 0) + 1 return hist
bigcode/self-oss-instruct-sc2-concepts
import time def profile(func): """profile execution time of provided function""" func_start = time.time() func() func_end = time.time() func_delta = func_end - func_start label = str(func).split()[4].split('.')[2] return f"'{label}' passed in {func_delta:.2f}s"
bigcode/self-oss-instruct-sc2-concepts
import types def rebuild_code_object(co, code=None, constants=None, filename=None): """Rebuild the code object.""" code = code or co.co_code constants = tuple(constants or co.co_consts) filename = filename or co.co_filename params = [co.co_argcount, co.co_kwonlyargcount, co.co_nlocal...
bigcode/self-oss-instruct-sc2-concepts
import time def time2int(time_struct, format24=False): """Convert time, passed in as a time.struct_time object, to an integer with hours in the hundreds place and minutes in the units place. Returns 24 hour format if format24 is True, 12 hour format (default) otherwise. """ if not isinstance(time_...
bigcode/self-oss-instruct-sc2-concepts
def error_response(message): """ Construct error response for API containing given error message. Return a dictionary. """ return {"error": message}
bigcode/self-oss-instruct-sc2-concepts
def Slope(pt1, pt2): """ Calculates the slope of the line connecting 2 points. :param `pt1`: an instance of `wx.Point`; :param `pt2`: another instance of `wx.Point`. """ y = float(pt2.y - pt1.y) x = float(pt2.x - pt1.x) if x: return y/x else: return None
bigcode/self-oss-instruct-sc2-concepts
def is_sorted(items): """Return a boolean indicating whether given items are in sorted order. DONE: Running time: O(n), because the worst-case scenario would require iterating through the entire array once. DONE: Memory usage: O(1), because the input array is modified in-place (if at all).""" # DON...
bigcode/self-oss-instruct-sc2-concepts
import mpmath def cdf(x, dfn, dfd): """ Cumulative distribution function of the F distribution. `dfn` and `dfd` are the numerator and denominator degrees of freedom, resp. """ if x <= 0: return mpmath.mp.zero with mpmath.mp.extradps(5): x = mpmath.mp.mpf(x) dfn = mpmat...
bigcode/self-oss-instruct-sc2-concepts
def is_iter(obj): """ Checks if an object behaves iterably. Args: obj (any): Entity to check for iterability. Returns: is_iterable (bool): If `obj` is iterable or not. Notes: Strings are *not* accepted as iterable (although they are actually iterable), since string...
bigcode/self-oss-instruct-sc2-concepts
def _make_rows(data, headers, defaults={}): """ extract the values from the data based on the headers data is a list of dicts headers is a list of keys defaults is a dict, where the keys are from the headers list returns the data in a list or rows (tabulate data format) """ ...
bigcode/self-oss-instruct-sc2-concepts
def sampling(array, interval=1, offset=0): """ Down-sample the input signal with certain interval. input: array: numpy array. The input temporal signal. 1d or with multiple dimensions interval: int. The interval to sample EEG signal. Default is 1, which means NO down-sampling is applied ...
bigcode/self-oss-instruct-sc2-concepts
def acquire_page_list_urls_books(soup): """ Take a BeautifulSoup content of a category page. Return a list of the urls of the books in the first page for a unique category. """ page_list_partial_urls_books = map( lambda x: x.a['href'][8:], soup.find_all('h3'), ) page_list_urls_books = map( lambda x: f"ht...
bigcode/self-oss-instruct-sc2-concepts
def _convert_to_dict(caps_str: str) -> dict: """ Parses the VCP capabilities string to a dictionary. Non continuous capabilities will include an array of all supported values. Returns: Dict with all capabilities in hex Example: Expected string "04 14(05 06) 16" is converted to:...
bigcode/self-oss-instruct-sc2-concepts
import torch def pck(x, x_gt, perm_mat, dist_threshs, ns): """ Percentage of Correct Keypoints evaluation metric. :param x: candidate coordinates :param x_gt: ground truth coordinates :param perm_mat: permutation matrix or doubly stochastic matrix indicating correspondence :param dist_threshs:...
bigcode/self-oss-instruct-sc2-concepts
def get_line_end( is_last_line: bool, ) -> str: """ Get the characters needed for the end of a row of a TeX table being created by one of the functions below. Note that for some TeX-related reason, we can't put the \\ on the last line. Args: is_last_line: Whether this is the last line o...
bigcode/self-oss-instruct-sc2-concepts
def change_log_level_console(logger, new_level): """Change the minimum level that will be logged to the console Parameters ---------- logger : logger object As created by "init_root_logger" method new_level : int New minimum level to log to console """ logger.handlers[1].se...
bigcode/self-oss-instruct-sc2-concepts
def writeLabels(label): """Format text to be output by LaTeX.""" return label.replace('_', r'\_')
bigcode/self-oss-instruct-sc2-concepts
def get_public_translation(instance, language_slug): """ This tag returns the most recent public translation of the requested content object in the requested language. :param instance: The content object instance :type instance: ~integreat_cms.cms.models.pages.page.Page, ~integreat_cms.cms.models.event...
bigcode/self-oss-instruct-sc2-concepts
def ext_checker(fname, ext): """Replaces the extension of fname with ext, or adds ext to fname if fname doesn't already have an extension.""" ext_begin = -len(fname) for ind in range(1, len(fname) + 1): if fname[-ind] == ".": ext_begin = ind break return fname[:-ext_b...
bigcode/self-oss-instruct-sc2-concepts
def asa_scp_handler(ssh_conn, cmd='ssh scopy enable', mode='enable'): """Enable/disable SCP on Cisco ASA.""" if mode == 'disable': cmd = 'no ' + cmd return ssh_conn.send_config_set([cmd])
bigcode/self-oss-instruct-sc2-concepts
def progress(status_code): """Translate PROGRESS status codes from GnuPG to messages.""" lookup = { 'pk_dsa': 'DSA key generation', 'pk_elg': 'Elgamal key generation', 'primegen': 'Prime generation', 'need_entropy': 'Waiting for new entropy in the RNG', 'tick': 'Generic t...
bigcode/self-oss-instruct-sc2-concepts
def per_target(imgs): """Arrange samples per target. Args: imgs (list): List of (_, target) tuples. Returns: dict: key (target), value (list of data with this target) """ res = {} for index in range(len(imgs)): _, target = imgs[index] if target not...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime import time def uptime(since): """Turn an date and time into an uptime value. The returned value is a number of seconds from the provided value to the current time. The date/time provided is expected to be a local time using the following format: 2017-01-10 16:32:21. ...
bigcode/self-oss-instruct-sc2-concepts
def interpret_word_seg_results(char_seq, label_seq): """Transform model output into user-friendly contents. Example: In CWS, convert <BMES> labeling into segmented text. :param char_seq: list of string, :param label_seq: list of string, the same length as char_seq Each entry is one of ('B',...
bigcode/self-oss-instruct-sc2-concepts
import importlib def try_import(path, keys=None, _as=True): """Try to import from a module. Parameters ---------- path : str Path to module or variable in a module keys : str or list[str], optional Keys to load from the module _as : bool, defualt=True If False, perform...
bigcode/self-oss-instruct-sc2-concepts
def normalize_path_for_settings(path, escape_drive_sep=False): """ Normalize a path for a settings file in case backslashes are treated as escape characters :param path: The path to process (string or pathlib.Path) :param escape_drive_sep: Option to escape any ':' driver separator (wi...
bigcode/self-oss-instruct-sc2-concepts
def round_robin(w) -> bool: """Implements a round-robin association strategy where iots are associated their ssid modulo number of APs. Return: Returns true on successful association. False otherwise. """ m = len(w.aps) i = 0 for device in w.iots: if device.do_associate(w.aps[i%m]) == False: return False...
bigcode/self-oss-instruct-sc2-concepts
def check_dict_is_contained_in_another(filter_data: dict, data: dict) -> bool: """ Check if a dict is contained in another one. * Works with nested dicts by using _dot notation_ in the filter_data keys so a filter with `{"base_key.sub_key": "value"}` will look for dicts containing `...
bigcode/self-oss-instruct-sc2-concepts
def inside_bounding_box(bb_minlat, bb_minlon, bb_maxlat, bb_maxlon, start_lat, start_lon, end_lat, end_lon): """ Check if two given sets of coordinates (start_lat, start_lon) and (end_lat, end_lon) are within a bounding box (bb_minlat, bb_minlon, bb_maxlat, bb_maxlon) Examples: >>> inside_bounding_...
bigcode/self-oss-instruct-sc2-concepts
import typing def get_destination_for_notebook(relative_path: str) -> typing.Any: """ Get the destination for a notebook. The destination can be of a type of your choice, but it must be serializable with itsdangerous. It will be used by the other methods defining local behavior to determine where...
bigcode/self-oss-instruct-sc2-concepts
def _update_change_dec(func): """ Decorator to track property changes in class. Apply @property.setter after @_update_change_dec :param func: function object to decorate :return: decorated function """ def _wrapper(self, val): self._changed = True func(self, val) return _wr...
bigcode/self-oss-instruct-sc2-concepts
def nice_pypy_mem(mem: str) -> str: """Improves formatting of the memory statistics produced by pypy's garbage collector (which are provided as strings)""" return mem.replace("KB", " KiB").replace("MB", " MiB").replace("GB", " GiB")
bigcode/self-oss-instruct-sc2-concepts
def swap_short_telos_group_number(row): """ swaps all group 1 patients to group 2 & all group 2 patients to group 1 this is done purely for visualization reasons and has no impact whatsoever on interpretation of results; just swapping #s for interpretability """ if row == 1: row = 2 ...
bigcode/self-oss-instruct-sc2-concepts
def calculate_board_dim(img_mat, start_pos): """ Calculates the length of one side of the board (all info we need to find specific tiles) """ x, y = start_pos dim = 0 # size of one side of the chess board while img_mat[x, y, 0] != 0 and img_mat[x, y, 1] != 0 and img_mat[x, y, 0] != 0: d...
bigcode/self-oss-instruct-sc2-concepts
def add_fdcuk_meta_data(df, filepath): """ Accepts a dataframe and a filepath parses the filepath to get strings representing nation, league, and season writes this data to the dataframe Returns the changed dataframe """ season = filepath.stem str_filepath = str(filepath) str_fil...
bigcode/self-oss-instruct-sc2-concepts
def can_link_to(person, contact, model): """ Determines whether or not the specified person can form a social network link to the specified contact. :param person: The person wanting to link. :param contact: The contact to determine link eligibility. :param model: The model to use. """ ...
bigcode/self-oss-instruct-sc2-concepts
def should_show_entry_state(entry, current_api_id): """Returns wether or not entry state should be shown. :param entry: Contentful entry. :param current_api_id: Current API selected. :return: True/False """ return ( current_api_id == 'cpa' and ( entry.__dict__.get('...
bigcode/self-oss-instruct-sc2-concepts
def parse_args_and_kwargs(cmdline): """ cmdline: list returns tuple of: args (list), kwargs (dict) """ # Parse args and kwargs args = [] kwargs = {} if len(cmdline) > 1: for item in cmdline[1:]: if '=' in item: (key, value) = item.split('=', 1) ...
bigcode/self-oss-instruct-sc2-concepts
def isodate(dt): """Takes a date, returns ISO8601 date format""" return dt.strftime('%Y-%m-%d')
bigcode/self-oss-instruct-sc2-concepts
def _cell_index(dataframe, template='phderi'): """Return cell index (column, row) of first value on pivot. Parameters ---------- dataframe : DataFrame Raw dataframe imported from excel template : str, optional Template, by default 'phderi' Returns ------- list R...
bigcode/self-oss-instruct-sc2-concepts
def splitIntoTetrahedra(poly = "const PolyClipperPolyhedron&", tol = ("const double", "0.0")): """Split a PolyClipper::Polyhedron into tetrahedra. The result is returned as a vector<vector<int>>, where each inner vector is a set of four ints representing vertex indices in the input Polyhedro...
bigcode/self-oss-instruct-sc2-concepts
def add_members_to_policy(role: str, iam_policy: list, members: list, command_name: str) -> list: """ Append members to policy role members. Args: role (str): The name of policy role. iam_policy (list): IAM policies. members (list): Members to append to policy. command_name (...
bigcode/self-oss-instruct-sc2-concepts
def _is_decoy_suffix(pg, suffix='_DECOY'): """Determine if a protein group should be considered decoy. This function checks that all protein names in a group end with `suffix`. You may need to provide your own function for correct filtering and FDR estimation. Parameters ---------- pg : dict ...
bigcode/self-oss-instruct-sc2-concepts
import mpmath def calc(algorithm: str, accuracy: int) -> mpmath.mpf: """Return Pi. Args: accuracy (int): accuracy algorithm (str): algorithm by which pi is calcurated Returns: mpmath.mpf: Pi value """ pi: mpmath.mpf = globals()[algorithm].pi(accuracy) # pylint: disable=i...
bigcode/self-oss-instruct-sc2-concepts
def get_grant_name(grant): """Get grant name based on Grantee type.""" grant_name = "" if grant["Grantee"]["Type"] == "Group": uri = grant["Grantee"]["URI"] grant_name = uri.rsplit("/", 1)[-1] if grant["Grantee"]["Type"] == "CanonicalUser": grant_name = grant["Grantee"]["Display...
bigcode/self-oss-instruct-sc2-concepts
def validate_params(params): """ Validate the parameters passed to KBParallel.run_batch Also refer to the type def for run_batch in KBParallel.spec """ if 'tasks' not in params or not params['tasks']: raise ValueError('"tasks" field with a list of tasks is required.') if 'runner' not in ...
bigcode/self-oss-instruct-sc2-concepts
def check_for_negatives(terms): """ Returns `True` for a list of sympy expressions contains any expressions that are negative. Parameters ---------- terms : list of sympy expressions A list where expressions may be either positive or negative. Returns ------- bool ...
bigcode/self-oss-instruct-sc2-concepts
import re def filt(seq, lst): """ filters lst. returns sublist Args: seq: list used to build a regex for matching lst: list Returns: slst: list elements of lst that match at least one element of seq """ regex = "(" + ")|(".join(seq) + ")" regex = re.compile(...
bigcode/self-oss-instruct-sc2-concepts
import re def get_task_name_without_suffix(task_name, variant_name): """Return evergreen task name without suffix added to the generated task. Remove evergreen variant name, numerical suffix and underscores between them from evergreen task name. Example: "noPassthrough_0_enterprise-rhel-80-64-bit-dynamic...
bigcode/self-oss-instruct-sc2-concepts
def get_decision_sequence(size): """ Get the decision sequence for generating valid cycles with DGMG for teacher forcing optimization. """ decision_sequence = [] for i in range(size): decision_sequence.append(0) # Add node if i != 0: decision_sequence.append(0) # ...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_list_str(setting_str): """ Split a string like 'foo, bar' into ('foo', 'bar'). Also handles 'irregular' spacing like "foo ,bar". """ return re.split('\s*,\s*', setting_str)
bigcode/self-oss-instruct-sc2-concepts
def _generate_reset_key(user): """Return a reset key for the given User factory stub object.""" return "{0}_reset_key".format(user.name).lower()
bigcode/self-oss-instruct-sc2-concepts
def getFactoryMeritMultiplier(factoryId): """ Returns the skill merit multiplier for a particular factory. factoryId is the factory-interior zone defined in ToontownGlobals.py. """ # Many people complained about how many runs you must make now that # we lowered the cog levels so I have upped thi...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import math def _seconds_to_frame_index( time_in_seconds: float, fps: int, zero_indexed: Optional[bool] = True ) -> int: """ Converts a point in time (in seconds) within a video clip to its closest frame indexed (rounding down), based on a specified frame rate. Args: ...
bigcode/self-oss-instruct-sc2-concepts
def cost_part1(crabs: list[int], target: int) -> int: """ Calculates the total fuel that would be required for all crabs to move to the given position if the assumption from part 1 was true """ return sum(abs(target - crab) for crab in crabs)
bigcode/self-oss-instruct-sc2-concepts
def parse_n_features(n_features, total): """Parse either the `n_features` for forward and backward selection. Namely (a) if `param` is an int, ensure it lies on (0, `total`), (a) if `param` is a float, ensure it lies on (0, 1). Args: n_features : int An `n_features` parameter pa...
bigcode/self-oss-instruct-sc2-concepts
def where(self, test): """ Create a new :class:`.Table` with only those rows that pass a test. :param test: A function that takes a :class:`.Row` and returns :code:`True` if it should be included in the new :class:`.Table`. :type test: :class:`function` :returns: A n...
bigcode/self-oss-instruct-sc2-concepts
def fields_to_batches(d, keys_to_ignore=[]): """ The input is a dict whose items are batched tensors. The output is a list of dictionaries - one per entry in the batch - with the slices of the tensors for that entry. Here's an example. Input: d = {"a": [[1, 2], [3,4]], "b": [1, 2]} Output: r...
bigcode/self-oss-instruct-sc2-concepts
def my_import(name): """Function converts a string based import into a module object, used for dynamically importing modules from config. Parameters ---------- :str: `str` A string name of the module to import Returns ------- :obj: `module` A module object converted fro...
bigcode/self-oss-instruct-sc2-concepts
def gen_Message(message): """Create a new Message.""" message = { "@type": "Message", "MessageString": message, } return message
bigcode/self-oss-instruct-sc2-concepts
def seconds_to_datetime(second: int) -> str: """Convert seconds to datetime string.""" mins, secs = divmod(int(second), 60) hours, mins = divmod(mins, 60) return f'{hours:02d}:{mins:02d}:{secs:02d}'
bigcode/self-oss-instruct-sc2-concepts
def safe_int_cast(val, default=0): """Safely casts a value to an int""" try: return int(val) except (ValueError, TypeError): return default
bigcode/self-oss-instruct-sc2-concepts
def _get_regular_HD_name(name): """Convert an HD name in *Henry Draper Catalogue* to its regular form `"HD NNNN"` or `"HD NNNN C"`. Args: name (str or int): Name or HD number of a star (e.g. `"HD8276"`, `"HD 8276A"`, `8443`). Returns: str: Regular HD name `"HD NNNN"` or ...
bigcode/self-oss-instruct-sc2-concepts
def or_of_bits(*bits): """OR the given bits. Args: *bits (int): Bits for OR. More than one argument required. Return: or_bit (int): OR of the given bits. Example: >>> or_of_bits(1, 4, 16) 21 # 0b10101, 0x15 >>> or_of_bits(0b00010, 0b10000) 18 # 0b10010,...
bigcode/self-oss-instruct-sc2-concepts
import yaml def parse_yaml(config): """Safely loads yaml data Args: config: YAML configuration file Returns: Dictionary representation of given YAML """ return yaml.safe_load(config)
bigcode/self-oss-instruct-sc2-concepts
import torch def apply_distance_bound(data_region_i, data_region_i_orig, args): """ Input: data_region_i: (S,3) tensor, current region i points data_region_i_orig: (S,3) tensor, original region i points Return: data_region_i: modified data_region_i count: number of points t...
bigcode/self-oss-instruct-sc2-concepts
def attach_disk(fco_api, server_uuid, disk_uuid, index): """ Attach disk to server. :param fco_api: FCO API object :param server_uuid: Server UUID :param disk_uuid: Disk UUID :param index: Disk index on the server :return: Job-compatible object """ return fco_api.attachDisk(serverUU...
bigcode/self-oss-instruct-sc2-concepts
def median_zero_normalization(data, normalize='samples'): """ This function normalizes each sample by using its median. :param data: :param str normalize: whether the normalization should be done by 'features' (columns) or 'samples' (rows) :return: Pandas dataframe. Example:: data = pd...
bigcode/self-oss-instruct-sc2-concepts
def sse_pack(event_id: int, event: str, data: int, retry: str = "2000") -> str: """Pack data in Server-Sent Events (SSE) format.""" return f"retry: {retry}\nid: {event_id}\nevent: {event}\ndata: {data}\n\n"
bigcode/self-oss-instruct-sc2-concepts
def _lyn(w): """ Returns the length of the longest prefix of ``w`` that is a Lyndon word. EXAMPLES:: sage: import sage.combinat.necklace as necklace sage: necklace._lyn([0,1,1,0,0,1,2]) 3 sage: necklace._lyn([0,0,0,1]) 4 sage: necklace._lyn([2,1,0,0,2,2,1]) ...
bigcode/self-oss-instruct-sc2-concepts
def valid_int_id(int_id: int) -> bool: """Validates an ID value as a signed 32-bit integer used in ID fields in MySQL tables. :param int_id: ID number to validate :return: True or False, based on if the integer falls inclusively between 0 and 2147483647 """ try: if not int_id: ...
bigcode/self-oss-instruct-sc2-concepts
def _build_localename(localetuple): """ Builds a locale code from the given tuple (language code, encoding). No aliasing or normalizing takes place. """ try: language, encoding = localetuple if language is None: language = 'C' if encoding is None: ...
bigcode/self-oss-instruct-sc2-concepts
import torch def train_model(model, optimizer, criterion, epochs, trainloaders, validloaders, device): """ Trains a network with an optimizer according to a criterion over a number of epochs on data provided by trainloaders and validloaders using device. Returns None """ # Push model to cp...
bigcode/self-oss-instruct-sc2-concepts
import math def lcm(a: int, b: int) -> int: """Return lowest common multiple.""" return a * b // math.gcd(a, b)
bigcode/self-oss-instruct-sc2-concepts
import re def validate_url(url, playlist=False): """ Confirms the validity of the provided YouTube video/playlist URL Args: url: A YouTube video/playlist URL playlist: A boolean flag to determine playlist URL Returns: A bool indicating the validity of the provided URL """ pattern = r'^(https?\...
bigcode/self-oss-instruct-sc2-concepts
def _multiple_of_n(a, n_boundary): """Calculates ceil like operation to make 'a' to be multiple of n boundary.""" ceil_like = (a + n_boundary - 1) // n_boundary return ceil_like * n_boundary
bigcode/self-oss-instruct-sc2-concepts
def find(pred, iterable): """ Find the first occurrence of the predicate function returning true over the iterable; otherwise None. >>> find(lambda e: e.startswith('g'), ['alpha', 'beta', 'gamma', 'delta']) 'gamma' >>> find(lambda e: e.startswith('p'), ['alpha', 'beta', 'gamma', 'delta']) No...
bigcode/self-oss-instruct-sc2-concepts
def _softUpdateWrapper(wrapper, wrapped): """ Update a wrapper function to look like the wrapped function. Like functools.update_wrapper, but doesn't fail when attributes are not found. """ attrs = ['__name__', '__doc__'] for attr in attrs: if hasattr(wrapped, attr): seta...
bigcode/self-oss-instruct-sc2-concepts
def topological_sort(graph): """ Preforms a topological sort on the given graph. Code by Paul Harrison in the public domain. graph should be a dictionary mapping node names to lists of successor nodes. """ # Count the occurrences of each node as a successor count = { } for node in ...
bigcode/self-oss-instruct-sc2-concepts
def _convert_json_properties(properties): """ Convert a geojson expression of the properties of a sector into a list of properties. Properties are in a dictionary. The geojson has no object id field so we inject one. """ return [properties['AC_ID'], properties['AV_AIRSPACE_ID'], pro...
bigcode/self-oss-instruct-sc2-concepts
def _group_by_labels(cbdbscan_topics): """Group all the learned cores by their label, which was assigned in the cluster_model. Parameters ---------- cbdbscan_topics : list of :class:`Topic` A list of topic data resulting from fitting a :class:`~CBDBSCAN` object. After calling .fit on a ...
bigcode/self-oss-instruct-sc2-concepts
def posIntInput(string): """Function to ensure that the input is a positive integer Arguments: string {str} -- string to print while taking input from user """ while True: try: while True: value = int(input(string)) if value > 0: ...
bigcode/self-oss-instruct-sc2-concepts
def flip_ctrlpts_u(ctrlpts, size_u, size_v): """ Flips a list of 1-dimensional control points in u-row order to v-row order. **u-row order**: each row corresponds to a list of u values (in 2-dimensions, an array of [v][u]) **v-row order**: each row corresponds to a list of v values (in 2-dimensions, an arr...
bigcode/self-oss-instruct-sc2-concepts
def divup(x: int, y: int) -> int: """Divide x by y and round the result upwards.""" return (x + y - 1) // y
bigcode/self-oss-instruct-sc2-concepts
def create_test_results(suite_name, test_name, timestamp, command_args_printable, rc): """ Create a minimal test results object for test cases that did not produce their own :param suite_name: the name of the subdirectory for the suite this test was run in :param test_name: the name of the subdirectory...
bigcode/self-oss-instruct-sc2-concepts
import string import random def gen_passwd(size: int) -> str: """Generate password for ray.init call. See https://docs.ray.io/en/latest/configure.html?highlight=security#redis-port-authentication This function was adapted from https://stackoverflow.com/a/2257449 Example ------- ray.init...
bigcode/self-oss-instruct-sc2-concepts
def compare_extension(filename: str, expected_extension: str): """ Compare the extension of the given file with the expected extension """ return filename.endswith(expected_extension)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def md5(content): """ Generates md5 hash of content 2019-03-10 :param content: a data for md5 generation :return: an md5 hash of a content """ hash_md5 = hashlib.md5() hash_md5.update(content) return hash_md5.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def aprs_object_name(par): """ Return global name for the aprs object """ if "object_name" in par: return par["object_name"].strip() return par["from"]
bigcode/self-oss-instruct-sc2-concepts