seed
stringlengths
1
14k
source
stringclasses
2 values
def reject_info_to_report(starid, reject_info): """ For a given agasc_id, get all of the related "reject" info in an array """ log = [] for entry in reject_info: if entry['id'] != starid: continue log.append(f"Not selected stage {entry['stage']}: {entry['text']}") ret...
bigcode/self-oss-instruct-sc2-concepts
def zoom(crop, factor): """Resizes a cropped bounding box about the centre.""" x, y, w, h = crop cx, cy = x + w / 2, y + h / 2 return (int(cx - factor * w / 2), int(cy - factor * h / 2), int(factor * w), int(factor * h))
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def parse_guid(guid: str) -> Dict[str, int]: """ Parse a guid back to its four constituents Args: guid: a valid guid str Returns: A dict with keys 'location', 'work_station', 'sample', and 'time' as integer values """ guid = guid.replace('-',...
bigcode/self-oss-instruct-sc2-concepts
def plot_evoked( epochs, picks, events, gfp, spatial_colors, topomap_times, ): """ Plot evoked potentials of different events for individual channels. If multiple events are selected, one figure will be returned for each. Parameters ---------- epochs : mne.epochs.Epochs...
bigcode/self-oss-instruct-sc2-concepts
def calculatechroma(color): """Returns chroma value of color """ chroma = max(color.rgbfraction) - min(color.rgbfraction) return chroma
bigcode/self-oss-instruct-sc2-concepts
def count_mpmcts(filename): """ Given a .pla file with a list of MPMCT gates, tally up the number of gates with each different number of controls Parameters: filename (str): Name of a .pla-formatted file Outputs: num_total_controls (int): the maximum number of control bits ...
bigcode/self-oss-instruct-sc2-concepts
def reverse_string_iterative(s): """ Returns the reverse of the input string Time complexity: O(n) Space complexity: O(n) More efficient, only 3 O(n) operations """ chars = list(s) # O(n) i, j = 0, len(s) - 1 while i < j: # O(n) chars[i], chars[j] = chars[j], chars[i] i += 1 j -= 1 return "".join(ch...
bigcode/self-oss-instruct-sc2-concepts
def remove_stopwords(text, sw): """Remove words that do not add to the meaning; simplifies sentences""" return [w for w in text if w not in sw]
bigcode/self-oss-instruct-sc2-concepts
def copy_node(graph, node_id): """Copy node. Create a copy of a node in a graph. A new id for the copy is generated by regraph.primitives.unique_node_id. Parameters ---------- graph : regraph.Graph node_id : hashable, node to copy. Returns ------- new_name Id of the co...
bigcode/self-oss-instruct-sc2-concepts
import re def is_valid_project_id(project_id): """ Validates project IDs, also known as the project "name". A valid project name should look like: proj-00000001 - It should always start with "proj-" and end with 8 hexadecimal characters in lower case. :type project_id: str :param project_id: ...
bigcode/self-oss-instruct-sc2-concepts
def str_signature(sig): """ String representation of type signature >>> from sympy.multipledispatch.dispatcher import str_signature >>> str_signature((int, float)) 'int, float' """ return ', '.join(cls.__name__ for cls in sig)
bigcode/self-oss-instruct-sc2-concepts
def get_start_time(points, time_zero): """Get the first forecast given a time for the first observation. Parameters ---------- points : list of dicts The data points to consider. time_zero : object like datetime.datetime The current time. Returns ------- start : object ...
bigcode/self-oss-instruct-sc2-concepts
def _calc_phi(time, params): """Calculates orbital phase assuming zero eccentricity Args: time: observational time (same units at orbital period) params: dict of floats/numpy arrays, including params.per - orbital period (any units) params.T0 - mid-transit time (same uni...
bigcode/self-oss-instruct-sc2-concepts
import struct import base64 def _encode_real(v): """Encode real numbers as base 64 encoded little endian 8 byte floats.""" bytes_ = struct.pack('<d', v) return base64.b64encode(bytes_)
bigcode/self-oss-instruct-sc2-concepts
import math def get_long_dmm(long): """Takes an OLEX float and converts it into DMM longitude notation (e.g. 51'6.432 W) :param long: An 'Olex float' representing a longitude coordinate. :type long: float :return: A longitude coordinate (e.g. 51'6.432 W) :rtype: str """ long_d = math.tru...
bigcode/self-oss-instruct-sc2-concepts
def factored_gaussian_params_fn(mean_x, cov_x, mean_y, cov_y): """calculate the parameters of the gaussian q(z | y)q(z | x) Given that the form of the gaussian q(z | x, y) \propto q(z | x)q(z | y) is another gaussian with closed form covariance and mean vectors, we can easily get it from the output of ...
bigcode/self-oss-instruct-sc2-concepts
def total_scored_goals(meta): """ Adds up the total number of scored goals from the match metadata. Note: Own goals are not scored goals, only goals and errors. Args: meta: Match metadata (dict). Returns: Number of scored goals by both teams (int). """ return meta["scored_goa...
bigcode/self-oss-instruct-sc2-concepts
def issue_type(insp, fiscaliza): """Checa se a Issue de nº `insp` do Redmine é de um dos tipos válidos: `Inspeção | Ação`""" if (tipo := fiscaliza.issue.get(insp).tracker["id"]) == 1: return "Inspeção" elif tipo == 2: return "Ação" return "Desconhecido"
bigcode/self-oss-instruct-sc2-concepts
def column_is_foreign_key(column): """Returns whether a column object is marked as a foreign key.""" foreign_key = column["is foreign key"] if isinstance(foreign_key, str): foreign_key = foreign_key.lower() if foreign_key in {"y", "n", "yes", "no", "-"}: foreign_key = foreign_ke...
bigcode/self-oss-instruct-sc2-concepts
def binstring_to_bit_list(binstring): """ Converts a string into a list, where each char in the string becomes an item in the list, with matching left to right ordering. Each char in the input string must be able to be casted to an int, as each item in the output list is casted to an int. Args: ...
bigcode/self-oss-instruct-sc2-concepts
import click def get_checkpoint(db, id_or_alias): """Returns checkpoint entry in `db` indicated by `id_or_alias`. First tries to match an ID, then an alias. For the case of repeated aliases, will first match local checkpoints and then remotes. In both cases, matching will be newest first. """ ...
bigcode/self-oss-instruct-sc2-concepts
def target_far_field(F, scaled, cheb, tree, indices, chunksize=int(1e6)): """Calculates the :ref:`far-field contributions <eval>` for each target. :param F: the :func:`far_field` contributions for each box. :param scaled: the :func:`scale'd` problem. :param cheb: a :class:`~pybbfmm.chebyshev.Chebyshev...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def check_version(available: str, needed: Tuple[int, int]) -> bool: """Check that an available version matches the needed version.""" major, minor = available.split(".") if int(major) < needed[0]: return False return int(minor) >= needed[1]
bigcode/self-oss-instruct-sc2-concepts
def get_list_from_interval(input_interval): """ Created 20180619 by Magnus Wenzer Updated 20180717 by Magnus Wenzer Takes an interval in a list and returns a list with the gange of the interval: Example: [2, 7] => [2, 3, 4, 5, 6, 7] If start value > stop value the interval in ...
bigcode/self-oss-instruct-sc2-concepts
def trials2events(events, messages): """Match trial meta information to individual events.""" return events.merge(messages, how="left", on=["trial"])
bigcode/self-oss-instruct-sc2-concepts
def get_nodes_by_id(ntwrk, nodeid): """ Return a dictionary of nodes (in ntwrk) whose key matches the given 'nodeid'. (Ideally, we shouldn't even need this function; if ntwrk is a simple dict, then simply return {nodeid: ntwrk[nodeid]}.) """ return {k: v for el in ntwrk for k, ...
bigcode/self-oss-instruct-sc2-concepts
import re def find_word_from_root(tokens, root): """Filter token (words) to retain only those containing a root term Args: tokens (iterable of str): the list of tokens. root (str): regular expression for the root term, to look for (e.g 'clay' or 'cl(a|e)y'), which will be padded with '[a-z]*'...
bigcode/self-oss-instruct-sc2-concepts
import torch def _concat_encoder_hidden_directions(h): """ do the following transformation: (#directions * #layers, #batch, hidden_size) -> (#layers, #batch, #directions * hidden_size) to compensate for two directions in a bidirectional encoder """ return torch.cat([h[0:h.size(0):2], h[1:h...
bigcode/self-oss-instruct-sc2-concepts
def _filter_runs(runs, args): """ Constructs a filter for runs from query args. """ try: run_id, = args["run_id"] except KeyError: pass else: runs = ( r for r in runs if r.run_id == run_id ) try: job_id, = args["job_id"] except KeyError: pass ...
bigcode/self-oss-instruct-sc2-concepts
def get_encoding_from_witness(witness_type=None): """ Derive address encoding (base58 or bech32) from transaction witness type. Returns 'base58' for legacy and p2sh-segwit witness type and 'bech32' for segwit :param witness_type: Witness type: legacy, p2sh-segwit or segwit :type witness_type: str ...
bigcode/self-oss-instruct-sc2-concepts
def _get_non_inhereted_function_names(cls): """Gets all methods that cls has that its parents don't have.""" names = set(dir(cls)) for parent in cls.__bases__: names -= set(dir(parent)) return list(names)
bigcode/self-oss-instruct-sc2-concepts
def engagement_rate(followers_who_engaged, total_followers): """Return the engagement rate for a social media account. Args: followers_who_engaged (int): Total unique followers who engaged. total_followers (int): Total number of followers. Returns: Engagement rate (float) as follow...
bigcode/self-oss-instruct-sc2-concepts
def RGB_to_color(r, g, b): """Convert three 8-bit red, green, blue component values to a single 24-bit color value. """ return ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | (b & 0xFF)
bigcode/self-oss-instruct-sc2-concepts
def AND(a: bool, b: bool) -> bool: """AND logical gate Args: a (bool): First input signal b (bool): Second input signal Returns: bool: Output signal """ return a and b
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def bounding_boxes_from_words(word_infos: List[Dict]) -> List[List[int]]: """Returns an array of arrays representing bounding boxes :param List[Dict] word_infos: the words found in the OCR results :returns List[List[int]]: a list of bounding boxes oft...
bigcode/self-oss-instruct-sc2-concepts
import random import string def get_random_name(length): """Returns a random string of given length Args: length (int): Name length Returns: (str): Random name """ return "".join(random.choices(string.ascii_lowercase, k=length))
bigcode/self-oss-instruct-sc2-concepts
def generate_readargs(feature_list): """ Generate bpf_usdt_readargs_p() calls for the given feature list. This function assumes that the following are in scope: - struct pt_regs *ctx - struct SUBST_OU_output *output Parameters ---------- feature_list : List[model.Feature] List ...
bigcode/self-oss-instruct-sc2-concepts
def abs(var): """ Wrapper function for __abs__ """ return var.__abs__()
bigcode/self-oss-instruct-sc2-concepts
def base64_remove_padding(data): """ Remove padding from base64 encoding Args: data: fully padded base64 data Return: base64: Unpadded base64 bytes """ if isinstance(data, str): data = data.encode('utf-8') return data.rstrip(b'=')
bigcode/self-oss-instruct-sc2-concepts
def getBestTextureFormat(ext_list, extensions): """ returns index to a texture from tex_list which has the highest priority in ext_list if none of texture extensions is in ext_list, will return None ext_list is list of extensions in ascending order (the latter, the higher priority), e.g.: ...
bigcode/self-oss-instruct-sc2-concepts
def encode_cell_id(dim: int, row: int, col: int) -> list: """ Get hierarchical encoding binary representation of cell (row, col) with the grid of dim x dim. See Section 3.2 in `https://dl.acm.org/citation.cfm?id=2557559` :param int dim: dimension of the grid :param int row: row index :param int col...
bigcode/self-oss-instruct-sc2-concepts
import torch def augment_light_colour(batch_size, device, ambient_intensity_range=(0.2, 0.8), diffuse_intensity_range=(0.2, 0.8), specular_intensity_range=(0.2, 0.8)): """ Samples batch of random light INTENSITIES (not colours because ...
bigcode/self-oss-instruct-sc2-concepts
import re import string def split_words(data_str): """ Takes a string, returns a list of pairs (word, 1), one for each word in the input, so [(w1, 1), (w2, 1), ..., (wn, 1)] """ def _scan(str_data): pattern = re.compile('[\W_]+') return pattern.sub(' ', str_data).lower().split...
bigcode/self-oss-instruct-sc2-concepts
def functional_equivalence_checking(query, fingerprints_client): """Checks functional equivalence. Args: query: Integer, the fingerprint to query. fingerprints_client: Client to check fingerprints. Returns: Float, the fitness of the equivalence if found, otherwise None. """ return fingerprints_c...
bigcode/self-oss-instruct-sc2-concepts
def calculate_dmr(delay_list: list, deadline: float) -> float: """Returns the node's deadline miss ratio (DMR).""" miss = 0 for delay in delay_list: if delay > deadline: miss += 1 return miss/len(delay_list)
bigcode/self-oss-instruct-sc2-concepts
import textwrap def AddressArgHelp(include_l7_internal_load_balancing): """Build the help text for the address argument.""" lb_schemes = '(EXTERNAL, INTERNAL, INTERNAL_MANAGED' if include_l7_internal_load_balancing: lb_schemes += ', INTERNAL_MANAGED' lb_schemes += ')' detailed_help = """\ IP addre...
bigcode/self-oss-instruct-sc2-concepts
def var_dist(v1, v2): """compute absolute distance between two variants """ assert v1.CHROM == v2.CHROM return abs(v1.POS-v2.POS)
bigcode/self-oss-instruct-sc2-concepts
def only_main(compound: str): """Convert a splitted compound into a compound only split into a main compound and its satelite e.g. fietsen_stalling_pas -> fietsenstalling_pas Args: compound (str): an underscore splitted compound """ splitted = compound.split("_") if len(splitted) ==...
bigcode/self-oss-instruct-sc2-concepts
import string def has_digits(word): """ True if word contains digits. """ return bool(set(string.digits).intersection(word))
bigcode/self-oss-instruct-sc2-concepts
def binary_labels(labels, in_class, column="inregister"): """ Converts a multiclass dataset to one with binary labels, where 1 represents the "in-class" and 0 represents the "out-classes" (i.e. all classes that are not the in-class or the negative examples.) Parameters ---------- labels : ...
bigcode/self-oss-instruct-sc2-concepts
def _year_days(year): """_year_days(year) Returns the number of days in a given year. Positional arguments: year (int) - a year Returns: int - number of days in the specified year This is computed according to the Gregorian calendar, under which a leap year occurs every 4 yea...
bigcode/self-oss-instruct-sc2-concepts
import json def load_journal_json(absolute_path): """ This method loads data collected on a single journal by the pybliometrics metadata collection module into a dictionary. Parameters ---------- absolute_path(str, required) - The path to the .json file containing metadata procured by the pybliom...
bigcode/self-oss-instruct-sc2-concepts
def create_filepath(ds, root_path="."): """ Generate a filepath when given an xarray dataset """ varname = [x for x in ds.data_vars][0] start = ds.generalVerticalLayer.data[0] end = ds.generalVerticalLayer.data[-1] filepath = f"{root_path}/{varname}_{start}_{end}.nc" return filepath
bigcode/self-oss-instruct-sc2-concepts
def difference_value_calculator(repository, undeployed_value_tuple, deployed_value_tuple): """ Generate a value based on difference between given undeployed and deployed value. """ return undeployed_value_tuple[2] - deployed_value_tuple[2]
bigcode/self-oss-instruct-sc2-concepts
def get_coord_by_attr(ds, attr, value): """ Returns a coordinate based on a known attribute of a coordinate. :param ds: Xarray Dataset or DataArray :param attr: (str) Name of attribute to look for. :param value: Expected value of attribute you are looking for. :return: Coordinate of xarray data...
bigcode/self-oss-instruct-sc2-concepts
def extract_object(dictionary, key_sequence): """ Extract the object inside the dictionary at a specific path :param dictionary (Dict): dictionary to extract from :param key_sequence (List[str]): list of strings represetning key accesses :return: the value inside dictionary specified by key_sequence...
bigcode/self-oss-instruct-sc2-concepts
import glob def get_all_files(basedir): """Get a list of all files in basedir, recursively :param basedir: base of the path where to look for the files :return : a list with all the file paths """ return [name.replace("%s/"%basedir, "", 1) for name in glob.iglob('%s/**/*'%basedir, recursive...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def append_date_time_to_string(input_string: str) -> str: """Append datetime string to input string. Returns datetime string if input is empty string. """ now = datetime.now() if not input_string: return now.strftime("%Y-%m-%d_%H-%M-%S") else: ret...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_html(zipcode): """ Get the html to be parsed. :param zipcode: :return: html from web. """ url = f'https://www.wunderground.com/weather-forecast/{zipcode}' response = requests.get(url) return response.text
bigcode/self-oss-instruct-sc2-concepts
import time def wait_for_condition(condition_predictor, timeout_ms=1000, retry_interval_ms=100): """A helper function that waits until a condition is met. Args: condition_predictor: A function that predicts the condition. timeout_ms: Maximum timeo...
bigcode/self-oss-instruct-sc2-concepts
def norm_cmap(values, cmap, normalize, cm, vmin=None, vmax=None): """ Normalize and set colormap Parameters ---------- values Series or array to be normalized cmap matplotlib Colormap normalize matplotlib.colors.Normalize cm ...
bigcode/self-oss-instruct-sc2-concepts
import re def to_snake_case(text: str) -> str: """ Transform string to snake_case. """ text = re.sub(" +", " ", text) text = text.lower().strip().replace(" ", "_") return text
bigcode/self-oss-instruct-sc2-concepts
import struct def get_char(encoded: bytearray, idx: int) -> tuple: """ Returns a char and next to be read index :param encoded: bytearray :param idx: index to start read from :return: tuple of char and next index """ return chr(struct.unpack(">h", encoded[idx:idx + 2])[0]), idx + 2
bigcode/self-oss-instruct-sc2-concepts
def testing_client(testing_app): """ Fixture to setup test client context. :param testing_app: Test app context. :type testing_app: object :return: object """ return testing_app.test_client()
bigcode/self-oss-instruct-sc2-concepts
def bytes_to_pascals(dg_bytes): """Takes a list of 3 bytes read from the DG-700 and returns a pressure in Pascals. Larry Palmiter originally wrote this code for TEC in Basic, which has proven immensely useful. """ bx, hi, lo = dg_bytes # unpack the array into individual values pressure =...
bigcode/self-oss-instruct-sc2-concepts
def expand_qgrams_word_list(wlist, qsize, output, sep='~'): """Expands a list of words into a list of q-grams. It uses `sep` to join words :param wlist: List of words computed by :py:func:`microtc.textmodel.get_word_list`. :type wlist: list :param qsize: q-gram size of words :type qsize: int :p...
bigcode/self-oss-instruct-sc2-concepts
def is_under_replicated(num_available, expected_count, crit_threshold): """Calculates if something is under replicated :param num_available: How many things are up :param expected_count: How many things you think should be up :param crit_threshold: Int from 0-100 :returns: Tuple of (bool, ratio) ...
bigcode/self-oss-instruct-sc2-concepts
def src_from_cell_col(cell_name_col, verbose=False): """ Extract the source name from sample names. Args: cell_name_col: the actual array of sample names verbose: print value_counts if True """ src_names_arr = cell_name_col.map(lambda x: x.split('.')[0].lower()) src_names_arr.name =...
bigcode/self-oss-instruct-sc2-concepts
def get_jobid(module, resp): """Get the Job ID from the response header.""" jobid = None if resp.status_code == 202: joburi = resp.headers.get('Location') if joburi is None: module.fail_json(msg="Failed to update firmware.") jobid = joburi.split("/")[-1] else: ...
bigcode/self-oss-instruct-sc2-concepts
import textwrap def wrap_paragraphs(text, width=70): """Wrap each paragraph in ``text`` to the specified ``width``. If the ``text`` is indented with any common leading whitespace, then that common leading whitespace is removed from every line in text. Further, any remaining leading and trailing white...
bigcode/self-oss-instruct-sc2-concepts
def lf_to_hash(lf_dict): """Create a unique string representing an LF Args: lf_dict (dict): A labeling function (LF) Returns: str: unique hash """ def conditions_to_string(cond_list): conds = [] for x in cond_list: conds.append("".join([str(val) ...
bigcode/self-oss-instruct-sc2-concepts
def strip_default(arg): """Return the argname from an 'arg = default' string""" i = arg.find('=') if i == -1: return arg t = arg[:i].strip() return t
bigcode/self-oss-instruct-sc2-concepts
def is_proper_position(dimension, position): """ Check whether the given position is a proper position for any board with the given dimension. - The given position must be a tuple of length 2 whose elements are both natural numbers. - The first element identifies the column...
bigcode/self-oss-instruct-sc2-concepts
def row_series_to_columns(series): """Turn a pandas series of row tuples into a list of column value tuples.""" return list(zip(*series))
bigcode/self-oss-instruct-sc2-concepts
def bind(socket, connection, port): """Binds a socket to a port, or a random port if needed. Returns the port.""" if port <= 0: return socket.bind_to_random_port(connection) else: socket.bind(f"{connection}:{port}") return port
bigcode/self-oss-instruct-sc2-concepts
def count(s, *args): """count(s, sub[, start[,end]]) -> int Return the number of occurrences of substring sub in string s[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return s.count(*args)
bigcode/self-oss-instruct-sc2-concepts
def get_lowercase_method(method: str) -> str: """Returns the lowercase name of the HTTP method""" return method.lower()
bigcode/self-oss-instruct-sc2-concepts
def reverse(x, axes): """Reverse a tensor along the specified axes """ if isinstance(axes, int): axes = [axes] slices = [slice(None, None, -1) if i in axes else slice(None, None, None) for i in range(x.ndim)] return x[slices]
bigcode/self-oss-instruct-sc2-concepts
def is_json_request_accept(req): """Test if http request 'accept' header configured for JSON response. :param req: HTTP request :return: True if need to return JSON response. """ return not req.accept or req.accept.header_value == 'application/json' \ or req.accept.header_value == '*/*'
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import Tuple def _is_file_with_supported_extensions(path: Path, extensions: Tuple[str, ...]) -> bool: """ Check if the file is supported for the media type :param path: File path to check :param extensions: Supported extensions for the media type :example: ...
bigcode/self-oss-instruct-sc2-concepts
def CW_ode(w, t, n): """ Defines the differential equation in terms of the moving frame (CW frame LVLH) Arguments: w : vector of state variables w = [x,y,z,dx,dy,dz] t : time n : mean motion """ x, y, z, dx, dy, dz = w ddx = 3*(n ** 2)*x + 2*n*dy ddy = -...
bigcode/self-oss-instruct-sc2-concepts
def read_mol_list_from_sdf_file(filepath, line_by_line=False): """Simple loader to load a SDF file by only splitting. Args: filepath (str): File path for SDF file. line_by_line (bool): Whether to read SDF file line by line. Returns: list: List of mol blocks as string. """ m...
bigcode/self-oss-instruct-sc2-concepts
def timeinfo(solar_midnight, utc_to_local): """ Get table of time info for current scheduling period. Parameters ---------- solar_midnight : '~astropy.time.core.Time' UTC solar midnight time. utc_to_local : 'astropy.units' hour difference to convert from UTC to local time. ...
bigcode/self-oss-instruct-sc2-concepts
def get_adjusted_aspect(ax, aspect_ratio): """Adjust the aspect ratio Parameters ---------- ax : :obj:`~matplotlib.axes.Axes` A :obj:`~matplotlib.axes.Axes` instance aspect_ratio : float The desired aspect ratio for :obj:`~matplotlib.axes.Axes` Returns ------- float ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def merge_dictionaries(dictionaries: Dict, key_type: str, reverse: bool = False) -> Dict: """Given any number of dictionaries, shallow copy and merge into a new dict, precedence goes to key value pairs in latter dictionaries. Function from StackOverFlow Post: https://stack...
bigcode/self-oss-instruct-sc2-concepts
def Dot_C3V(vec1, vec2): """Simple function for computing the dot product between two three dimensional vectors (index-able objects of length 3).""" return vec1[0] * vec2[0] + vec1[1] * vec2[1] + vec1[2] * vec2[2]
bigcode/self-oss-instruct-sc2-concepts
import torch def f_dD(x): """Simple example function defined on interval `[0, 1]` Parameters ---------- x : torch.Tensor coordinates for evaluation Returns ------- torch.Tensor function evaluations """ result = 4 * x[0] * (x[0] - 1) for x_i in x[1:]: r...
bigcode/self-oss-instruct-sc2-concepts
def setup(*setup_functions): """Decorator that reigsters setup functions with a test. The functions passed in as setup functions take an optional 'context' parameter of type checkers.Context. Note that the decorator takes in Test instances, so this decorator should be used *above* the @checkers.test decorat...
bigcode/self-oss-instruct-sc2-concepts
def get_lines(path, remove_comments=True): """Returns the lines in a C/C++ header file that are not empty. Also strips the whitespace from each line and can optionally remove the comments. Parameters ---------- path : :class:`str` The path to a C/C++ header file. remove_comme...
bigcode/self-oss-instruct-sc2-concepts
def is_route(tag): """ Checks if an HTML tag is a bus route. :param tag A BeautifulSoup tag :return True if the tag has a "data-routes" attribute, False otherwise""" return tag.has_attr("data-routes")
bigcode/self-oss-instruct-sc2-concepts
def _time_to_micros(time): """Convert a time into microseconds since midnight. Parameters ---------- time : datetime.time The time to convert. Returns ------- us : int The number of microseconds since midnight. Notes ----- This does not account for leap seconds or...
bigcode/self-oss-instruct-sc2-concepts
def get_team_avg_height(team): """calculate a new avg_height based on current team's player's heights. If no players on team, return 0 """ num_players = len(team['players']) if num_players == 0: # No players return 0 return 0 # calculate average height of existing players tot...
bigcode/self-oss-instruct-sc2-concepts
import re def uncoded(src): """Strips out any `# encoding: ???` lines found at the head of the source listing""" lines = src.split("\n") for i in range(min(len(lines), 2)): lines[i] = re.sub(r'#.*coding[=:]\s*([-\w.]+)', '#', lines[i]) return "\n".join(lines)
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def validate_discharge_efficiency(discharge_efficiency: Optional[float]) -> Optional[float]: """ Validates the discharge efficiency of an object. Discharge efficiency is always optional. :param discharge_efficiency: The discharge efficiency of the object. :return: The ...
bigcode/self-oss-instruct-sc2-concepts
def getCreditMultiplier(floorIndex): """ Returns the skill credit multiplier appropriate for a particular floor in a building battle. The floorIndex is 0 for the first floor, up through 4 for the top floor of a five-story building. """ # Currently, this is 1 for the first floor (floor 0), 1.5 f...
bigcode/self-oss-instruct-sc2-concepts
import json def get_json(data, pretty=False, **kwargs): """ A convenience wrapper around ``json.dumps`` that respects the ordering of keys in classes like ``OrderedDict``, ``SortedDict``, and ``DefinedOrderDict``. :param data: the object to encode in JSON :param pretty: whether or not...
bigcode/self-oss-instruct-sc2-concepts
def calc_force(df, close, volume, col_name="force"): """Calculate force indicator (Elder). :param df: Data frame to do and add calculations to :param close: Pandas dataframe column name close price :param volume: Pandas dataframe column name volume :param col_name: Pandas dataframe column name for ...
bigcode/self-oss-instruct-sc2-concepts
def combine_prediction_metadata_batches(metadata_list): """Combines a list of dicts with the same keys and lists as values into a single dict with concatenated lists for each corresponding key Args: metadata_list (list): list of dicts with matching keys and lists for values Returns: ...
bigcode/self-oss-instruct-sc2-concepts
import base64 def str_to_base64(data, encoding='utf-8'): """Codifica uma string (por padrão, UTF-8) em Base64. :param str data: String a ser codificada em Base64. :param str encoding: Opcional. O *encoding* da string `data`. Se não for especificado, o padrão é `'utf-8'`. :returns: Uma string...
bigcode/self-oss-instruct-sc2-concepts
def factor_out_twos(n): """ Returns the tuple (d,s) such that n = d*(2**s) for the smallest value of d """ d = n s = 0 while d % 2 == 0: s += 1 d //= 2 return d,s
bigcode/self-oss-instruct-sc2-concepts