seed
stringlengths
1
14k
source
stringclasses
2 values
def dfs_topological_sort(arr, n): """ Topological sort with DFS. Return an empty list if there is a cycle. """ graph = [[] for _ in range(n)] for u, v in arr: graph[u].append(v) visited, stack = [0] * n, [] def dfs(u): if visited[u] == -1: return False i...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def get_profile(line, listOfFeatures): """ Returns a tuple of feature values for the profile in question. line is a string that contains key:value pairs separated by whitespace. Each key is a feature and each value is its value. profile is a list of f...
bigcode/self-oss-instruct-sc2-concepts
def convert_to_html(model): """ Takes a model instance and produces an HTML table that represents the results in a nice way for us to look at. Parameters ---------- model : dict Dictionary of layers and their properties as a list in the form of [Vp, Vs, rho, thickness, top] Returns...
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def matched_by_list(package, version, requirements): """ Verify whether the given version of the package is matched by the given requirements file. :param package: Name of the package to look for :param version: Version of the package to look for :param requirements: A list o...
bigcode/self-oss-instruct-sc2-concepts
import math def downsampled_image_dims_from_desired_num_pixels(image_dims, num_pixels, maximum=False): """ Compute the best downsampled image dimensions, given original image dimensions and the ideal total number of pixels for the downsampled image. The final number of pixels in the downsampled image dime...
bigcode/self-oss-instruct-sc2-concepts
def ParseSortByArg(sort_by=None): """Parses and creates the sort by object from parsed arguments. Args: sort_by: list of strings, passed in from the --sort-by flag. Returns: A parsed sort by string ending in asc or desc, conforming to https://aip.dev/132#ordering """ if not sort_by: return N...
bigcode/self-oss-instruct-sc2-concepts
import re def find_exported_class_path(spark_config_env_sh): """ find any current class path :param spark_config_env_sh: all the text from the cloudera manager spark_env.sh :return: the entire line containing the exported class path """ return re.search('SPARK_CLASSPATH=.*', spark_config_env_s...
bigcode/self-oss-instruct-sc2-concepts
def dictify(x): """Ensure `x` is a dict. """ if isinstance(x, dict): return x elif x: return dict(x) else: return dict()
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def _check_criteria(last_nouns: list, looking_for_singular: Union[bool, None], looking_for_female: Union[bool, None], looking_for_person: bool, is_exact: bool) -> list: """ Checks the values of the nouns in last_nouns for matches of the specified gender/number ...
bigcode/self-oss-instruct-sc2-concepts
def string2fields(string, lengths): """Slice string into fixed-length fields.""" return (string[pos:pos + length].strip() for idx, length in enumerate(lengths) for pos in [sum(map(int, lengths[:idx]))])
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def extract_url(url, values=None): """Given an url, extracts the contents as a BeautifulSoup object. Args: url: URL to parse. Returns: The site contents as a BeautifulSoup object """ if values: r = requests.post(url, data=value...
bigcode/self-oss-instruct-sc2-concepts
def l1_bit_rate(l2br, pps, ifg, preamble): """ Return the l1 bit rate :param l2br: l2 bit rate int bits per second :param pps: packets per second :param ifg: the inter frame gap :param preamble: preamble size of the packet header in bytes :return: l1 bit rate as float """ return l2br...
bigcode/self-oss-instruct-sc2-concepts
def imap_helper(args): """ Helper function for imap. This is needed since built-in multiprocessing library does not have `istarmap` function. If packed arguments are passed, it unpacks the arguments and pass through the function. Otherwise, it just pass the argument through the given function. ...
bigcode/self-oss-instruct-sc2-concepts
def check_subset(list_one:list, list_two:list): """ You are given two lists of integers list_one and list_two. If list_two is a subset of list_one, return true, otherwise return list of items that are in list_two but NOT in list_one. Note: subset can be empty, if so return False Example 1: Input: list_one = ...
bigcode/self-oss-instruct-sc2-concepts
def appear_only_at_sentence_beginning(word, title, sents): """ if the token appears in the text only at the beginning of the sentences >>> title = [u"Feng", u"Chao", u"Liang", u"Blah"] >>> doc = [[u"Feng", u"Chao", u"Liang", u"is", u"in", u"Wuhan", u"."], [u"Chao", u"Liang", u"is", u"not", u"."], [u"Li...
bigcode/self-oss-instruct-sc2-concepts
def bubble_sort(L): """ Implementation of the bubble sort algorithm Complexity: O(n^2) :param L: List-object :return: Sorted list-object """ swap = False while not swap: swap = True for j in range(1, len(L)): if L[j-1] > L[j]: swap = False ...
bigcode/self-oss-instruct-sc2-concepts
def ensure_list(i): """If i is a singleton, convert it to a list of length 1""" # Not using isinstance here because an object that inherits from a list # is not considered a list here. That is, I only want to compare on the final-type. if type(i) is list: return i return [i]
bigcode/self-oss-instruct-sc2-concepts
import operator def crop_nd_arr(img, bounding): """Crop the central portion of an array so that it matches shape 'bounding'. Parameters ---------- img : array An nd array that needs to be cropped. bounding : tuple Shape tupple smaller than shape of img to crop img to. Returns...
bigcode/self-oss-instruct-sc2-concepts
def listify(value): """ Convert an option specified as a string to a list. Allow both comma and space as delimiters. Passes lists transparently. """ if isinstance(value, (list, tuple)): # Already a sequence. Return as a list return list(value) else: # assume `value` is a...
bigcode/self-oss-instruct-sc2-concepts
def _extend(M, sym): """Extend window by 1 sample if needed for DFT-even symmetry""" if not sym: return M + 1, True else: return M, False
bigcode/self-oss-instruct-sc2-concepts
def parse_by_line(input_string, prefix_string, offset): """breaks input string by lines and finds the index of the prefix_line. Returns the line that is offset past the prefix_line""" split_by_line = input_string.splitlines() prefix_line = split_by_line.index(prefix_string) return split_by_line[p...
bigcode/self-oss-instruct-sc2-concepts
import re def add_css_class(component, className): """ Update the className property of a Dash component to include a CSS class name. If one or more classes already exist, the provided className will be appended to the list. If the provided className is already present, no change will be made to ...
bigcode/self-oss-instruct-sc2-concepts
def log_get_flags(client): """Get log flags Returns: List of log flags """ return client.call('log_get_flags')
bigcode/self-oss-instruct-sc2-concepts
def error_500(error): """Return a custom 500 error.""" return 'Sorry, internal server error.'
bigcode/self-oss-instruct-sc2-concepts
def get_ta_status_flag(funding_status): """Generate TA status flag for student entry. This flag is from a "teaching preference request" perspective, not a funding perspective. Arguments: funding_status (str): funding entry for current term Returns: (str) : flag ("" for non-TA, "*"...
bigcode/self-oss-instruct-sc2-concepts
import torch def safe_divide(input_tensor: torch.Tensor, other_tensor: torch.Tensor) -> torch.Tensor: """ Divide input_tensor and other_tensor safely, set the output to zero where the divisor b is zero. Parameters ---------- input_tensor : torch.Tensor other_tensor : torch.Tensor Returns...
bigcode/self-oss-instruct-sc2-concepts
def decodeBytesToUnicode(value, errors="strict"): """ Accepts an input "value" of generic type. If "value" is a string of type sequence of bytes (i.e. in py2 `str` or `future.types.newbytes.newbytes`, in py3 `bytes`), then it is converted to a sequence of unicode codepoints. This function is u...
bigcode/self-oss-instruct-sc2-concepts
def calc_result_myteam_first(score): """ Determines whether the team won, drew or lost based on the score Returns a 'W', 'L', 'D' """ result = ('W' if score[0] > score[1] else ('L' if score[0] < score[1] else 'D')) return result
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def find_case_sensitive_path(path: Path, platform: str) -> Path: """Find the case-sensitive path. On case-insensitive file systems (mostly Windows and Mac), a path like ``text.txt`` and ``TeXt.TxT`` would point to the same file but not on case-sensitive file systems. On ...
bigcode/self-oss-instruct-sc2-concepts
def findOwner(cursor, tableName): """ Finds the owner of a table. """ cursor.execute("""SELECT OWNER FROM ALL_OBJECTS WHERE object_name = '"""+tableName.upper()+"'") return cursor.fetchone()[0]
bigcode/self-oss-instruct-sc2-concepts
def best_days(dragon, me): """ >>> d = {'Monday': (1, 6), 'Friday': (3, 5)} >>> m = {'Monday': (2, 4), 'Friday': (3, 6)} >>> best_days(d, m) ['Monday'] >>> d = {'Monday': (1, 6), 'Friday': (3, 5)} >>> m = {'Monday': (0, 4), 'Friday': (3, 6)} >>> best_days(d, m) [] >>> d = {'Mon...
bigcode/self-oss-instruct-sc2-concepts
import requests import json def post(url, params, proxies, headers): """Send a request with the POST method.""" response = requests.post(url, data=json.dumps(params),proxies=proxies, headers=headers) return response
bigcode/self-oss-instruct-sc2-concepts
def resource_filename(lang_code: str, resource_type: str, resource_code: str) -> str: """ Return the formatted resource_filename given lang_code, resource_type, and resource_code. """ return "{}_{}_{}".format(lang_code, resource_type, resource_code)
bigcode/self-oss-instruct-sc2-concepts
def get_epsilon_array(gamma_array): """Flip 0 and 1 for epsilon from gamma""" return list(map(lambda d: '1' if d == '0' else '0', gamma_array))
bigcode/self-oss-instruct-sc2-concepts
def extract_build_cmds(commands, exe_name): """Extracts build command information from `ninja -t commands` output. Args: commands: String containing the output of `ninja -t commands` for the libcxx_test_template. exe_name: The basename of the built executable. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def check_request_params(data, params): """ Checks that a JSON request contains the proper parameters. Parameters ---------- data : json The JSON request params: list The parameters that should appear in the JSON request Returns ------- str A message det...
bigcode/self-oss-instruct-sc2-concepts
def calculate_total_bags(graph): """ Given a graph, return the total bags required """ value = 0 for node in graph: value += int(node["count"]) + int(node["count"]) * calculate_total_bags( node["inside"] ) return value
bigcode/self-oss-instruct-sc2-concepts
def min_ge(seq, val): """ Same as min_gt() except items equal to val are accepted as well. >>> min_ge([1, 3, 6, 7], 6) 6 >>> min_ge([2, 3, 4, 8], 8) 8 """ for v in seq: if v >= val: return v return None
bigcode/self-oss-instruct-sc2-concepts
def _has_docker_file(repo, project_path): """Checks if project has a Dockerfile.""" return any(content_file.name == 'Dockerfile' for content_file in repo.get_contents(project_path))
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Tuple import click def print_table(rows: Sequence) -> None: """Print a formatted table.""" head, *rows = rows col_lengths = list(map(len, head)) for row in rows: col_lengths = list(map(max, zip(col_lengths, map(len, row)))) # type: ignore d...
bigcode/self-oss-instruct-sc2-concepts
def simHeatpump(T_cold, T_hot=50.0, efficiency=0.45, T_limit=-20.0, COP_limit=7.0): """ Creates a timedepent Coefficient of Performance (COP) based on the potential carnot efficiency and a quality grade/efficiency of the system. Parameters ----------- T_cold: float, np.array or list, required ...
bigcode/self-oss-instruct-sc2-concepts
def fetch_vest_scores(vest_dict, ref_aa, somatic_aa, codon_pos, default_vest=0.0): """Get VEST scores from pre-computed scores in dictionary. Note: either all mutations should be missense or non-missense intended to have value equal to default. Parameters ...
bigcode/self-oss-instruct-sc2-concepts
def xstr(s): """ Returns the given object as a string or if None then returns the empty string """ return str(s) if s else ""
bigcode/self-oss-instruct-sc2-concepts
def ma(df, ma_ranges=[10, 21, 50]): """ Simple Moving Average Parameters ---------- df : pandas.DataFrame, must include columns ['Close'] Dataframe where the ma is extracted from ma_ranges: list, default [10, 21, 50] List of periods of Simple Moving Average to be extracted Retur...
bigcode/self-oss-instruct-sc2-concepts
def elchgeraeusch(wiederholungen): """Gibt einen String mit einer bestimmten Anzahl an Mööös aus.""" elchausspuch = "" for i in range(wiederholungen): # das wird einfach wiederholungen-mal ausgeführt elchausspuch += "Mööö " # a += b bedeutet a = a + b return elchausspuch
bigcode/self-oss-instruct-sc2-concepts
def is_no_cache_key_option(number): """Return ``True`` iff the option number identifies a NoCacheKey option. A :coapsect:`NoCacheKey option<5.4.2>` is one for which the value of the option does not contribute to the key that identifies a matching value in a cache. This is encoded in bits 1 through 5 o...
bigcode/self-oss-instruct-sc2-concepts
import torch def to_sparse(tensor): """Given a one-hot encoding vector returns a list of the indexes with nonzero values""" return torch.nonzero(tensor)
bigcode/self-oss-instruct-sc2-concepts
def _try_rsplit(text, delim): """Helper method for splitting Email Received headers. Attempts to rsplit ``text`` with ``delim`` with at most one split. returns a tuple of (remaining_text, last_component) if the split was successful; otherwise, returns (text, None) """ if delim in text: ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def chk_dir(src_dir): """To check if the directory exists. Returns boolean """ src_is_dir = Path(src_dir).is_dir() if src_is_dir is False: print(f"Test Directory '{src_dir}' does not exist.") print("Add a directory containing the source images to run this test...
bigcode/self-oss-instruct-sc2-concepts
import zlib import pickle def _compress_obj(obj, level): """Compress object to bytes. """ return zlib.compress(pickle.dumps(obj, protocol=2), level)
bigcode/self-oss-instruct-sc2-concepts
def display_2Dlist(p): """Prints a piece, or each Piece in a list, to output. Args: p (Union[Piece, List[Piece]]): Piece, or list of Pieces, to print to output """ # helper function to display a piece def dis(p): for row in p: print(row) def is_piece(p): ret...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def parse_fasta_header(fasta_header: str) -> Tuple[str, str, str]: """Parse a fasta header with the following format: db|UniqueIdentifier|EntryName. https://www.uniprot.org/help/fasta-headers Parameters ---------- fasta_header : str A fasta header in the format: d...
bigcode/self-oss-instruct-sc2-concepts
def rangify(value): """Return a range around a given number.""" span = 5 min_val = max(value - span, 1) max_val = max(value + span, span * 2) return range(min_val, max_val)
bigcode/self-oss-instruct-sc2-concepts
def read(filename): """Read content of specified test file. :param str filename: Name of file in 'testdata' folder. :return: Content of file :rtype: str """ with open('testdata/' + filename) as f: return f.read()
bigcode/self-oss-instruct-sc2-concepts
def num_to_emoji(n): """ Convert number to discord emoji Parameters ---------- n : str string number Returns ------- str discord emoji if valid, False otherwise """ num_emoji_map = { "1": ":one:", "2": ":two:", "3": ":three:", "4": ":four...
bigcode/self-oss-instruct-sc2-concepts
def is_2numbers(astring): """ (str) -> Boolean returns True if astring has at least two numbers. else return False. >>> is_2numbers('CIS122') True >>> is_2numbers('Ducks') False >>> is_2numbers('ABC-1') False """ digits_ctr = 0 for c in astring: if c.is...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def run_prediction(predictor, inputs, cleanup_functions): """ Run the predictor on the inputs, and append resulting paths to cleanup functions for removal. """ result = predictor.predict(**inputs) if isinstance(result, Path): cleanup_functions.append(result.unl...
bigcode/self-oss-instruct-sc2-concepts
def num_words(text: str) -> int: """ Counts the number of words using whitespace as delimiter. Args: text: Sentence Returns: Number of words """ return len(text.split())
bigcode/self-oss-instruct-sc2-concepts
def DnsRequestsAndCost(trace): """Returns the number and cost of DNS requests for a trace.""" requests = trace.request_track.GetEvents() requests_with_dns = [r for r in requests if r.timing.dns_start != -1] dns_requests_count = len(requests_with_dns) dns_cost = sum(r.timing.dns_end - r.timing.dns_start ...
bigcode/self-oss-instruct-sc2-concepts
import shutil def which(program): """Find the program executable Args: program (str): program name Raises: ValueError: Raise if the program isn't found Returns: obj: program executable path """ _executable = shutil.which(program) if not _executable: raise...
bigcode/self-oss-instruct-sc2-concepts
def delslash(value): """ Remove slash from start and end >>> delslash('/foo/bar/') 'foo/bar' :type str: :rtype: str """ if value.startswith('/'): value = value[1:] if value.endswith('/'): value = value[:-1] return value
bigcode/self-oss-instruct-sc2-concepts
def int2hex(number: int, chars: int = 2) -> str: """ Converts integers to human-readable HEX :param number: integer to convert :param chars: minimal amount of chars(bytes) to show :return: HEX string w/o prefix """ a = hex(number)[2:].upper() chars = max(len(a) // 2, chars) return ('...
bigcode/self-oss-instruct-sc2-concepts
def tuple_incr(t1, idx, val=1): """Return a tuple with the index idx incremented by val""" return t1[:idx] + (t1[idx]+val,) + t1[idx+1:]
bigcode/self-oss-instruct-sc2-concepts
import json def _output_object(name): """Format an object ID as JSON output, for returning from a narr. function. """ return json.dumps({'output': name})
bigcode/self-oss-instruct-sc2-concepts
def script(script_file, **context): """ User-defined script to be loaded into administrative page. :param script_file: location of javascript file (in the service's working directory). Must be a javascript function. :param context: context will be passed to the called script. """ with o...
bigcode/self-oss-instruct-sc2-concepts
def get_isa_field_name(field): """ Return the name of an ISA field. In case of an ontology reference, returns field['name']. :param field: Field of an ISA Django model :return: String """ if type(field) == dict: return field['name'] return field
bigcode/self-oss-instruct-sc2-concepts
import torch def nd_cross_entropy_with_logits(logits: torch.Tensor, targets: torch.Tensor, weights: torch.Tensor): """ Multidimensional version of `util.cross_entropy_with_logits`. # Shape: (batch_size, d_1, ..., d_n, num_classes) logi...
bigcode/self-oss-instruct-sc2-concepts
def smooth_series(data, window, method="average"): """Apply a moving average or mean with window of size "window" Arguments: data {Dataframe} -- Pandas dataframe window {int} -- size of window to apply Keyword Arguments: method {str} -- the method applied to smooth the data...
bigcode/self-oss-instruct-sc2-concepts
def adjacent_enemy(inp, rowI, colI, enemy): """Check for enemy in adjacent square""" if any(x[0]==enemy for x in [inp[rowI+1][colI], inp[rowI-1][colI], inp[rowI][colI+1], inp[rowI][colI-1]]): return True return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def validate_detail(detail: Dict[str, int]) -> bool: """Validates the given detail Parameters ---------- detail : Dict[str, int] The detail to be validated Returns ------- bool True if the detail follows the schema, else False """ detail_ke...
bigcode/self-oss-instruct-sc2-concepts
import json def read_json(input_file_path, verbose=False): """ Function reads json file from path and returns list of records :param input_file_path: path to json input file :param verbose: defines if verbose mode :return: list of records """ with open(input_file_path) as json_file: ...
bigcode/self-oss-instruct-sc2-concepts
def passthrough(result): """Simply return the result.""" return result
bigcode/self-oss-instruct-sc2-concepts
def score(data_row, positives, negatives, strategy = "+"): """ -- DESCRIPTION -- Implementations of the scoring functions described in the thesis in /docs. This function is designed to be applied row-wise to a pandas dataframe. For example usage refer to the scoring wo...
bigcode/self-oss-instruct-sc2-concepts
def confirm_action(message: str) -> bool: """Basic (Y/n)? wrapper for `input`""" return input(message)[0:1] in "Yy"
bigcode/self-oss-instruct-sc2-concepts
def split_df(df, columns_split): """Split a dataframe into two by column. Args: df (pandas dataframe): input dataframe to split. columns_split (int): Column at which to split the dataframes. Returns: df1, df2 (pandas dataframes): Split df into two dataframe based on column. The first has the fir...
bigcode/self-oss-instruct-sc2-concepts
def _cli_bytes_from_str(text): """ Python 2/3 compatibility function to ensure that what is sent on the command line is converted into bytes. In Python 2 this is a no-op. """ if isinstance(text, bytes): return text else: return text.encode("utf-8", errors="surrogateescape")
bigcode/self-oss-instruct-sc2-concepts
import re def getVarList(strLine): """this function takes a string in the format 'i{Am}AString{With}Variables' and parse it for included var entries '{.+}'. The return of the function in case of the example would be: ('Am','With') """ result = [] if strLine is None: return result ...
bigcode/self-oss-instruct-sc2-concepts
import itertools def get_all_comb(array, r=None): """ Get all combinations of items in the given array Specifically used for generating variant combination Parameters ---------- array: 1D array. input array r: int. The number of items in a combination Returns ------- result: List...
bigcode/self-oss-instruct-sc2-concepts
def format_url(category: str, year: int, month: str, day: str) -> str: """ It returns a URL from The Guardian website with links for the articles of the given date and category :param category: A String representing the category :param year: An integer representing the year :param month: A Str...
bigcode/self-oss-instruct-sc2-concepts
def patch_string_from_method(method: str) -> str: """Get the string that indicates the method to be patched for a calling method.""" switch_dict = { "get": "tentaclio_gs.clients.GSClient._get", "put": "tentaclio_gs.clients.GSClient._put", "remove": "tentaclio_gs.clients.GSClient._remove"...
bigcode/self-oss-instruct-sc2-concepts
def remove_duplicates(list1): """ Eliminate duplicates in a sorted list. Returns a new sorted list with the same elements in list1, but with no duplicates. This function can be iterative. """ result_list = [] for idx in range(len(list1)): if idx == 0: result_list.ap...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def time_to_resolve(time_received, time_resolved): """Returns the time taken to resolve an issue. Args: time_received (datetime): Datetime showing when ticket was received. time_resolved (datetime): Datetime showing when ticket was received. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def count_spaces(line): """ Counting the spaces at the start of a line """ return len(line)-len(line.lstrip(' '))
bigcode/self-oss-instruct-sc2-concepts
def search_node_from_coord(x, y, nodes): """Get node's number from coordinates""" return int(nodes.loc[(nodes['x'] == x) & (nodes['y'] == y)]['n'])
bigcode/self-oss-instruct-sc2-concepts
def data_section(values): """ >>> data_section(range(0, 260)) '0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,...
bigcode/self-oss-instruct-sc2-concepts
def compare_dicts(dict_a, dict_b, excluded_keys=None): """Compare two dict with same keys, with optional keys to exclude from compare""" if excluded_keys is None: excluded_keys = [] return all(dict_a[k] == dict_b[k] for k in dict_a if k not in excluded_keys)
bigcode/self-oss-instruct-sc2-concepts
import torch def boxes_to_cornels(box_xy, box_wh): """Convert boxes from x_center,y_center, width, height to x_min, y_min, x_max, ymax Parameters ---------- box_xy : torch.Tensor Predicted xy value shape [batch_size, num_anchors, 2, conv_height, conv_width] box_wh : torch.Tensor ...
bigcode/self-oss-instruct-sc2-concepts
def json_default_repr(obj): """Converts an object into a suitable representation for JSON-ification. If obj is an object, this returns a dict with all properties not beginning in '_'. Otherwise, the original object is returned. """ if isinstance(obj, object): return {k: v for k, v in obj.__dict__.ite...
bigcode/self-oss-instruct-sc2-concepts
def get_col_encryption_type(col_name, integrity_info): """ Returns type based on whether the column is encrypted as number (OPE) or symmetrically (Fernet) or asymmetrically (ABE)- this is based on "type" attribute in TinyDB :param integrity_info: { 'device_data': { 'added': {...
bigcode/self-oss-instruct-sc2-concepts
def _interpolate_crop(start: complex, stop: complex, loc: float, axis: int) -> complex: """Interpolate between two points at a given coordinates.""" start_dim, stop_dim = (start.real, stop.real) if axis == 0 else (start.imag, stop.imag) diff = stop_dim - start_dim if diff == 0: raise ValueErro...
bigcode/self-oss-instruct-sc2-concepts
def make_fispact_material(mat): """ Returns a Fispact material card for the material. This contains the required keywords (DENSITY and FUEL) and the number of atoms of each isotope in the material for the given volume. The Material.volume_in_cm3 must be set to use this method. See the Fispact FUEL k...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def check_keystore_json(jsondata: Dict) -> bool: """ Check if ``jsondata`` has the structure of a keystore file version 3. Note that this test is not complete, e.g. it doesn't check key derivation or cipher parameters. Copied from https://github.com/vbuterin/pybitcointools Ar...
bigcode/self-oss-instruct-sc2-concepts
def build_tree(items): """ This function takes a Python list of items and turns it into a binary tree of the items, suitable for casting to an s-expression. """ size = len(items) if size == 0: return [] if size == 1: return items[0] half_size = size >> 1 left = build_...
bigcode/self-oss-instruct-sc2-concepts
def get_depth_fn(depth_multipler, min_depth): """Builds a callable to compute depth (output channels) of conv filters. Args: depth_multiplier: a multiplier for the nominal depth. min_depth: a lower bound on the depth of filters. Returns: A callable that takes in a nominal depth and...
bigcode/self-oss-instruct-sc2-concepts
def acceleration(force, mass): """ Calculates the acceleration through force devided by mass. @param force: force as a vector @param mass: mass as a numeric value. This should be not 0. @return: acc the acceleration >>> acceleration(300, 30) 10.0 """ #print "mass: ", mass #p...
bigcode/self-oss-instruct-sc2-concepts
def uniform_t_sequence(steps: int): """ Creates a sequence of t parameters whose values are equally spaced and go from 0 to 1 using the given number of steps. :param steps: number of steps :return: sequence of t values """ return [t / steps for t in range(steps + 1)]
bigcode/self-oss-instruct-sc2-concepts
def _validate_not_subset(of, allow_none=False): """ Create validator to check if an attribute is not a subset of ``of``. Parameters ---------- of: str Attribute name that the subject under validation should not be a subset of. Returns ------- validator: Callable Validat...
bigcode/self-oss-instruct-sc2-concepts
import random import string def random_char_sequence(y: int) -> str: """Creates a random char sequence of length y for the job_id name randomization""" return "".join(random.choice(string.ascii_letters) for x in range(y))
bigcode/self-oss-instruct-sc2-concepts
import copy def copy_miscellanious(misc): """ Returns a deepcopy of an object """ return copy.deepcopy(misc)
bigcode/self-oss-instruct-sc2-concepts
def join(*paths): """ Joins multiple paths into a single path. Arguments: *paths -- path components """ path = "" for component in paths: path += ("/" if path and not path.endswith("/") else "") + component.replace( "\\", "/" ) return path
bigcode/self-oss-instruct-sc2-concepts