seed
stringlengths
1
14k
source
stringclasses
2 values
def percentile(n): """Create function that calculates percentile for list""" return lambda xs: sorted(xs)[int(len(xs)*n)]
bigcode/self-oss-instruct-sc2-concepts
from typing import Set def _extract_args(input_str: str) -> Set[str]: """Extract the argument names from a string representation of a lambda function. Args: input_str: The string to be inspected. Something like 'x, opt=5:". Returns: The argument names from the `input_str`. Something like...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Any from typing import Tuple from typing import Optional def validate_provided_image_paths(image_paths: Sequence[Any]) -> Tuple[Optional[str], bool]: """Given a list of image_paths (list length at least 1), validate them and determine if metadata is available. ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Optional from datetime import datetime def epoch_to_timestamp(epoch: Union[int, str]) -> Optional[str]: """Converts epoch timestamp to a string. Args: epoch: Time to convert Returns: A formatted string if succeeded. if not, returns None. ""...
bigcode/self-oss-instruct-sc2-concepts
def parse_timestamp(my_dt): """ Param my_dt (datetime.datetime) like status.created_at Converts datetime to string, formatted for Google BigQuery as YYYY-MM-DD HH:MM[:SS[.SSSSSS]] """ return my_dt.strftime("%Y-%m-%d %H:%M:%S")
bigcode/self-oss-instruct-sc2-concepts
def chooseHighestFromTuple(arr): """ Pick the id of the highest element of a list of tuples of the form (id, key), where they key determines which value is the highest :param arr: The array of elements :return: A tuple of the form (id, key) of the element with the highest key """ high = ...
bigcode/self-oss-instruct-sc2-concepts
def replace_string(metadata, field, from_str, to_str): """Replace part of a string in given metadata field""" new = None if from_str in metadata[field]: new = metadata[field].replace(from_str, to_str) return new
bigcode/self-oss-instruct-sc2-concepts
def great_circle_pole_pts(lon_p, lat_p): """Find two orthogonal points on the great circle from its polar axis. Parameters ---------- lon_p: float Polar axis west longitude (degree). lat_p: float Polar axis latitude (degree). Returns ------- float West longitude...
bigcode/self-oss-instruct-sc2-concepts
def _mkUniq(collection, candidate, ignorcase = False, postfix = None): """ Repeatedly changes `candidate` so that it is not found in the `collection`. Useful when choosing a unique column name to add to a data frame. """ if ignorcase: col_cmp = [i.lower() for i in collection] can_cmp...
bigcode/self-oss-instruct-sc2-concepts
def _assertable(queryset, list_item='name'): """ From a Django queryset return a list of one attribute that can be passed to an assert statement. The default model attribute to compare is name. :param django.db.models.query.QuerySet queryset: :returns: A list of the specified attrributes from each ...
bigcode/self-oss-instruct-sc2-concepts
import torch def create_loss_function(loss_name): """ Create a loss function from its name by creating a wrapper to the corresponding torch.nn.functional function (e.g. torch.nn.functional.mse_loss for 'MSE') and preparing the targets if necessary. Args: loss_name: The name of the loss functi...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def __parsePageFilings(page_parsed: BeautifulSoup) -> list: """Function to extract filings from a parsed HTML EDGAR listings page. Arguments: page_parsed {BeautifulSoup} -- Parsed HTML for filing extraction. Returns: list -- Structured list of dictio...
bigcode/self-oss-instruct-sc2-concepts
def convert_process(x): """ Converts process column in wikipedia transistor count table to numeric. """ # NANs are floats if isinstance(x, float): return x else: return x.replace('nm', '').replace(',', '').strip()
bigcode/self-oss-instruct-sc2-concepts
import re def read_fb_file(fb_fname): """Return the total number of simulations covered by the folder from a fb file. The actual simulation is written by Matlab. The first part of the simulation code is to provide the total number of simulations the code will calculate. The function read the outp...
bigcode/self-oss-instruct-sc2-concepts
def get_file_contents(file_path): """Return a string containing the file contents of the file located at the specified file path """ with open(file_path, encoding="utf-8") as f: file_contents = f.read() return file_contents
bigcode/self-oss-instruct-sc2-concepts
def find_faces_at_index(layer_qs, coord_val, index): """Find all the faces that intersect `coord_val` along `index` Example Slice a list of faces along the x-axis so that you can tell where to fill the shape in, by drawing lines across the polygon. """ return [face for face_q in layer_qs for fa...
bigcode/self-oss-instruct-sc2-concepts
def is_password_parameter(data_model, source_type: str, parameter: str) -> bool: """Return whether the parameter of the source type is a password.""" # If the parameter key can't be found (this can happen when the parameter is removed from the data model), # err on the safe side and assume it was a password...
bigcode/self-oss-instruct-sc2-concepts
def dropIdColumn(train, test): """Detaches Id column from both datasets Parameters: train (pd.Dataset): Training set test (pd.Dataset): Testing set Returns: train (pd.Dataset): Training set without Id test (pd.Dataset): Testing set without Id trainId (pd.Dataset) : Training Id fields ...
bigcode/self-oss-instruct-sc2-concepts
def rbg_to_hex(c): """Convert an rgb-formatted color to hex, ignoring alpha values.""" return f"#{c[0]:02x}{c[1]:02x}{c[2]:02x}"
bigcode/self-oss-instruct-sc2-concepts
def DetectEncoding(data, default_encoding='UTF-8'): """Detects the encoding used by |data| from the Byte-Order-Mark if present. Args: data: string whose encoding needs to be detected default_encoding: encoding returned if no BOM is found. Returns: The encoding determined from the BOM if present or |...
bigcode/self-oss-instruct-sc2-concepts
def append_pkcs7_padding(s): """ Function to return s padded to a multiple of 16-bytes by PKCS7 padding. :param s: string to apply padding to :return: padded string """ # numpads = 16 - (len(s) % 16) return s + numpads * chr(numpads)
bigcode/self-oss-instruct-sc2-concepts
import re def atomwise_tokenizer(smi, exclusive_tokens = None): """ Tokenize a SMILES molecule at atom-level: (1) 'Br' and 'Cl' are two-character tokens (2) Symbols with bracket are considered as tokens exclusive_tokens: A list of specifical symbols with bracket you want to keep. e.g., ['...
bigcode/self-oss-instruct-sc2-concepts
def reverse_loop(value): """Reverse string using a loop.""" result = "" for char in value: result = char + result return result
bigcode/self-oss-instruct-sc2-concepts
def downsample_image(image, n): """Downsample 2D input image n x n. Parameters ---------- image : ndarray 2D input image. n : int Downsampling factor, applied to both image dimensions. Returns ------- result : ndarray Resampled image with shape = image.shape//n. ...
bigcode/self-oss-instruct-sc2-concepts
def text_to_int(text): """ Converts text into an integer for use in encryption. input: text - a plaintext message output: integer - an integer encoding text """ integer = 0 for char in text: if integer > 0: integer = integer*256 integer = integer + ord(char) r...
bigcode/self-oss-instruct-sc2-concepts
def underscore_to_dash(name: str) -> str: """Convert underscore to dash and drop final dash if present.""" converted = name.replace('_', '-') return converted if converted[-1] != '-' else converted[:-1]
bigcode/self-oss-instruct-sc2-concepts
import requests import json def update_network(platform, key, client, net_id, new_name): """ Updates the name of a network via the API. :param platform: URL of the RiskSense Platform to be queried. :type platform: str :param key: API Key. :type key: str :param c...
bigcode/self-oss-instruct-sc2-concepts
import torch def create_the_slices(image, label, slices: int = 5, dim: int = 0): """ Splitting raw input image into slices Args: image (torch.tensor): Input image label (torch.tensor): Target label slices (int, optional): Split size. Defaults to 5. dim (int, optional): Dimensi...
bigcode/self-oss-instruct-sc2-concepts
def make_python_name(name): """ Convert Transmission RPC name to python compatible name. """ return name.replace('-', '_')
bigcode/self-oss-instruct-sc2-concepts
def from_tensor(tensor_item): """ Transform from tensor to a single numerical value. :param tensor_item: tensor with a single value :return: a single numerical value extracted from the tensor """ value = tensor_item.item() if value == -1: return None return value
bigcode/self-oss-instruct-sc2-concepts
from typing import List import re def excluded_pattern(root: str, excludes: List[str]) -> bool: """ Check if the given path or filename matches any of the provided exclude patterns. """ for pattern in excludes: if re.search(pattern, root): return True return False
bigcode/self-oss-instruct-sc2-concepts
def _endswith(value): """ Maps to `string.endswith`. """ return lambda v: v.endswith(value)
bigcode/self-oss-instruct-sc2-concepts
def lstm_mask_layer(proj, mask): """ Removes any spurious output from the LSTM that's not covered by a label or doesn't correspond to any real input. :param proj: Output of the LSTM layer :param mask: 1 if the position is valid, 0 otherwise :return: The masked values """ return proj * m...
bigcode/self-oss-instruct-sc2-concepts
def user_info_query(user_id: str) -> dict: """ Build User information query. :param user_id: User id :return: Query """ return { "operationName": "ProfileGet", "query": """query ProfileGet($user_id: ID!) { userprofile { get(user_id: $user_id) { ...
bigcode/self-oss-instruct-sc2-concepts
def knot2ms(ws_knot): """ Convert unit of wind speed from knots to meter per seconds. Examples --------- >>> ws_ms = kkpy.util.knot2ms(ws_knot) Parameters ---------- ws_knot : array_like Array containing wind speed in **knots**. Returns --------- ws...
bigcode/self-oss-instruct-sc2-concepts
import struct def encode_varint(number): """ Write a VarInt to a string. :param number: Number to encode as a VarInt. :return: The encoded VarInt. """ # Python ints are variable length, which means there's no fixed size. # Typical programming language implementation exploits the sign bit moving # when doing...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def str_md5(_str): """ 字符串MD5 :param _str:字符串 :return:字符串的MD5值 """ m = hashlib.md5() m.update(_str.encode()) return m.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def _polygon_area(x, y): """ Function to compute the area of a polygon by giving its coordinates in counter-clockwise order. """ area = 0 j = len(x)-1; for i in range (0, len(x)): area += (x[j]+x[i]) * (y[i]-y[j]); j = i return area/2;
bigcode/self-oss-instruct-sc2-concepts
import torch def top_k_ranking(embeddings, labels, prototypes, prototype_labels, top_k=3): """Compute top-k accuracy based on embeddings and prototypes affinity. Args: embeddings: An N-D float tensor with last dimension as `num_c...
bigcode/self-oss-instruct-sc2-concepts
def make_empty_table(row_count, column_count): """ Make an empty table Parameters ---------- row_count : int The number of rows in the new table column_count : int The number of columns in the new table Returns ------- table : list of lists of str Each cell ...
bigcode/self-oss-instruct-sc2-concepts
def _try_convert_str_to_float(value, label): """ Try to convert input value to float value. """ try: return float(value) except Exception: msg = 'Invalid parameter: {} cannot cast string to float.'.format(label) raise ValueError(msg)
bigcode/self-oss-instruct-sc2-concepts
def _validate_arg(value, expected): """Returns whether or not ``value`` is the ``expected`` type. """ if type(value) == expected: return True return False
bigcode/self-oss-instruct-sc2-concepts
def parse_requirements(path): """ Return the contents of a requirements file as a string separated by spaces. """ with open(path, 'r') as fp: return ' '.join(line.strip() for line in fp)
bigcode/self-oss-instruct-sc2-concepts
def enum_names_aslist(c, lower=True): """Get an Enum class as a list of enum names. Args: c (:class:`Enum`): Enum class. lower (bool): True to get names as lower case; defaults to True for easier comparison with other strings. Returns: List: List of enum names. """...
bigcode/self-oss-instruct-sc2-concepts
def min_length(word, thresh): """ Predicate for the length of a word """ return len(word) >= thresh
bigcode/self-oss-instruct-sc2-concepts
def build_lstm_vocab(tokens): """ Builds vocab from list of sequences :param sentences: list of sequences, each a list of tokens :return: tuple of (dictionary: word --> unique index, pad_token_idx) """ all_tokens = list(set(tokens)) vocab = {token: i for i, token in enumerate(all_tokens)...
bigcode/self-oss-instruct-sc2-concepts
def _parse_gcs_path(path: str): """Parses the provided GCS path into bucket name and blob name Args: path (str): Path to the GCS object Returns: bucket_name, blob_name: Strings denoting the bucket name and blob name """ header, rest = path.strip().split('//') if header != '...
bigcode/self-oss-instruct-sc2-concepts
def object_sort_key(obj): """ Define a predictable sort ordering for Kubernetes objects. This should be the same ordering that Kubernetes itself imposes. """ return ( # Not all objects have a namespace. getattr(obj.metadata, "namespace", None), obj.metadata.name, )
bigcode/self-oss-instruct-sc2-concepts
def is_punct(text): """ returns true if the text consists solely of non alpha-numeric characters """ for letter in text.lower(): if letter in set('abcdefghijklmnopqrstuvwxyz1234567890'): return False return True
bigcode/self-oss-instruct-sc2-concepts
def _JsonChecks(input_api, output_api): """Run checks on any modified json files.""" failing_files = [] for affected_file in input_api.AffectedFiles(None): affected_file_path = affected_file.LocalPath() is_json = affected_file_path.endswith('.json') is_metadata = (affected_file_path.startswith('site/'...
bigcode/self-oss-instruct-sc2-concepts
def get_mean_pore_size(img, nx): """ Finds the mean pore diameter of the domain Parameters: ---------- :param np.ndarray img: binary image array of domain :param int nx: number of pixels in x direction of fluid domain Returns ------- :return: Model domain mean pore ...
bigcode/self-oss-instruct-sc2-concepts
def parsed_data(provides, data): """ Function that parse data. :param provides: action name :param data: response data :return: parsed response """ boolean_dict = {"True": "Yes", "False": "No"} if provides == "list patches": for item in data: try: item["...
bigcode/self-oss-instruct-sc2-concepts
import math def diff(a, b): """Returns the difference between two values.""" return int(math.fabs(a - b))
bigcode/self-oss-instruct-sc2-concepts
def normalizeShape(shape): """ Method used to convert shape to tuple Arguments: -shape: int, tuple, list, or anything convertible to tuple Raises: -TypeError: If conversion to tuple failed Returns: A tuple representing the shape """ if isins...
bigcode/self-oss-instruct-sc2-concepts
def _PrettyPrintSize(x): """Pretty print sizes in bytes, e.g. 123456 -> 123.45kB. Args: x: (int) size Returns: (str) Pretty printed version, 2 decimal places. """ if x < 1e3: return '%dB' % x elif 1e3 <= x < 1e6: return '%.2fkB' % (x / 1e3) elif 1e6 <= x < 1e9: return '%.2fMB' % (x /...
bigcode/self-oss-instruct-sc2-concepts
import re def default_get_arg_names_from_class_name(class_name): """Converts normal class names into normal arg names. Normal class names are assumed to be CamelCase with an optional leading underscore. Normal arg names are assumed to be lower_with_underscores. Args: class_name: a class name,...
bigcode/self-oss-instruct-sc2-concepts
def _tid_to_slice_ix(tid, train_ids, stop=False): """Convert a train ID to an integer index for slicing the dataset Throws ValueError if the slice won't overlap the trains in the data. The *stop* parameter tells it which end of the slice it is making. """ if tid is None: return None tr...
bigcode/self-oss-instruct-sc2-concepts
def group_metrics(metric): """Return the group of a metric""" if metric in ['nme', 'mbe', 'sd_diff', 'corr']: return "common" elif metric in ['extreme_5', 'extreme_95']: return 'extremes' elif metric in ['skewness', 'kurtosis', 'overlap']: return 'distribution' else: ...
bigcode/self-oss-instruct-sc2-concepts
def _parse_bool_str(attr, key, default='False'): """Parse bool string to boolean.""" return attr.get(key, default).strip().lower() in ['true', '1', 't', 'y', 'yes']
bigcode/self-oss-instruct-sc2-concepts
def arrayCheck(nums): """ Function to find a sequence 1, 2, 3. Given a list of integers, return True if the sequence of numbers 1, 2, 3 appears in the list somewhere. Args: nums (Array): Array of integer """ for i in range(len(nums)-2): if nums[i] == 1 and nums[i+1] == 2 a...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def _extract_serialization_type(first_file: pathlib.Path) -> str: """ Deduce the serialization type :param first_file: serialized file :return: one from ["msgpack", "pickle", "json"]. """ msg_pack = first_file.suffixes == ['.msgpack', '.xz'] msg_pickle = first_file.suffixes ...
bigcode/self-oss-instruct-sc2-concepts
def edges_between_nodes(graph, nodes): """ Return all edges in graph that connect the nodes :param graph: :param nodes: :return: """ edge_selection = [] for edge in graph.edges: if edge[0] in nodes and edge[1] in nodes: edge_selection.append(edge) return edge_s...
bigcode/self-oss-instruct-sc2-concepts
def pos2iso6709(lat: float, lon: float, alt: float, crs: str = "WGS_84") -> str: """ convert decimal degrees and alt to iso6709 format. :param float lat: latitude :param float lon: longitude :param float alt: altitude :param float crs: coordinate reference system (default = WGS_84) :return:...
bigcode/self-oss-instruct-sc2-concepts
def lowercase(word): """ LOWERCASE word outputs a copy of the input word, but with all uppercase letters changed to the corresponding lowercase letter. """ return word.lower()
bigcode/self-oss-instruct-sc2-concepts
import re def get_day_number_from_heading_string(heading_string: str) -> int: """ Extract day number from heading string. >>> get_day_number_from_heading_string( ... "Day 1: October 16, 2019, Wednesday", ... ) 1 Arguments: heading_string (str): Day's log header string from whi...
bigcode/self-oss-instruct-sc2-concepts
import json def parse_sns_message(event: dict) -> dict: """ Parses SNS record and returns its message. :param event: SNS event that triggered the lambda :return: parsed SNS message """ return json.loads(event["Records"][0]["Sns"]["Message"])
bigcode/self-oss-instruct-sc2-concepts
def generate_interpolation_trajectory(x_start, x_final, traj_to_match): """Generate a 1d interpolation profile, where the velocity is constant over the duration of the trajectory. Args: x_start: Start position of the trajectory. x_final: End position of the trajectory. traj_to_match:...
bigcode/self-oss-instruct-sc2-concepts
def deal(deck): """Draws a card and returns card""" card = deck.draw_card() return card
bigcode/self-oss-instruct-sc2-concepts
def step_reduce(reducee, reducer, order): """ Return the reduced polynomial of reducee by reducer. That is, if one of reducee's bases is divisible by the leading base of reducer with respect to the order, the returned polynomial is the result of canceling out the term. """ lb, lc = order.le...
bigcode/self-oss-instruct-sc2-concepts
import re def _extract_parameters(s:str)->dict: """ The functions parses all parameters from a ShipFlow Motions indata file. The function searches for: x = ... and saves all those occurences as a key value pair in a dict. Parameters ---------- s : str Motions indata file c...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def get_readable_date(datetime_str): """ Convert UTC datetime to readable form of date """ date_str = datetime_str.split('T')[0] return datetime.strptime(date_str, "%Y-%m-%d").strftime("%d/%m/%Y")
bigcode/self-oss-instruct-sc2-concepts
def crop_center(im): """ Crops the center out of an image. Args: im (numpy.ndarray): Input image to crop. Returns: numpy.ndarray, the cropped image. """ h, w = im.shape[0], im.shape[1] if h < w: return im[0:h, int((w - h) / 2):int((w - h) / 2) + h, :] else: ...
bigcode/self-oss-instruct-sc2-concepts
def update_param_vals(pars, prefix, **kwargs): """Update parameter values with keyword arguments.""" for key, val in kwargs.items(): pname = "%s%s" % (prefix, key) if pname in pars: pars[pname].value = val return pars
bigcode/self-oss-instruct-sc2-concepts
import glob import json def load_recipes(path): """Load recipes from json files Parameters ---------- path : str Path to json files e.g. ./json/*.json Returns ------- list List of dicts """ jsonfiles = glob.glob(f'{path}/*.json') recipes = [] ...
bigcode/self-oss-instruct-sc2-concepts
import binascii def get_partition(num_partitions, queue, project=None): """Get the partition number for a given queue and project. Hashes the queue to a partition number. The hash is stable, meaning given the same queue name and project ID, the same partition number will always be returned. Note also...
bigcode/self-oss-instruct-sc2-concepts
import pathlib import io import yaml def load_nondev_yaml(dev_path: pathlib.Path) -> bool: """ Partially reads a yaml file and stores results in a dictionary. Parameters ---------- dev_path : pathlib.Path Path to the conda file with dependencies (e.g. `environment-dev.yml`). This ...
bigcode/self-oss-instruct-sc2-concepts
def upper(text): """ Creates a copy of ``text`` with all the cased characters converted to uppercase. Note that ``isupper(upper(s))`` might be False if ``s`` contains uncased characters or if the Unicode category of the resulting character(s) is not "Lu" (Letter, uppercase). The uppercas...
bigcode/self-oss-instruct-sc2-concepts
def FileName(dir,stat,alg,avg,min,max): """get svg graph file name from dimensions. For stat use 'perf|size(min|avg|max)' used for the y axis. Use 't' for the dimension used as the timeseries label. Use 'x' for dimension used as x axis. Use 'o' for the optimal value for the algorithm. Use 's' for the stand...
bigcode/self-oss-instruct-sc2-concepts
import random def get_next(th): """ Decide if will proceede to next stage or not """ sort = random.randint(0, 100) if (sort < th): return True return False
bigcode/self-oss-instruct-sc2-concepts
def number_of_publications(publications: list[dict]) -> int: """Computes the number of publications. (This function exists rather for consistency.) :param: a list of publications. :return: the number of publications. """ return len(publications)
bigcode/self-oss-instruct-sc2-concepts
import torch def calculate_R_pi(R, pi): """ calculates R_pi R_pi(s) = \sum_a pi(s,a) r(s,a) :param R: reward matrix of size |S| x |A| :param pi: matrix of size |S| x |A| indicating the policy :return: """ return torch.einsum('sa,sa->s', R, pi)
bigcode/self-oss-instruct-sc2-concepts
def rename_list_to_dict(rlist): """ Helper for main to parse args for rename operator. The args are assumed to be a pair of strings separated by a ":". These are parsed into a dict that is returned with the old document key to be replaced as the (returned) dict key and the value of the return ...
bigcode/self-oss-instruct-sc2-concepts
import io import gzip import json def load_cloudtrail_log(s3_client, bucket, key): """ Loads a CloudTrail log file, decompresses it, and extracts its records. :param s3_client: Boto3 S3 client :param bucket: Bucket where log file is located :param key: Key to the log file object in the bucket ...
bigcode/self-oss-instruct-sc2-concepts
import requests def bio(name): """ Provides paragraph biography/background description of 1 individual or entity from an entity get request on LittleSis API. Resorts to entity with the highest number of relationships listed for entries that point to multiple entites (like last name only entries). ...
bigcode/self-oss-instruct-sc2-concepts
def get_device_family_chipset(vendor_id, device_id, device_map): """Get the family and chipset strings given the vendor and device ids. Args: vendor_id: a string representing the vendor id (e.g. '0xabcd'). device_id: a string representing the device id (e.g. '0xbcde'). Returns: A s...
bigcode/self-oss-instruct-sc2-concepts
def default_split(data: str, separator: str=' ', default: str='', maxsplits: int=0) -> list: """ Function to split a string and return a list of substring. If more splits requested than there are substrings then a default value is used. Args: data (str): String to be split. separato...
bigcode/self-oss-instruct-sc2-concepts
def read_file(file_str): """ Return file lines for a file """ file_obj = open(file_str, "r") file_lines = file_obj.readlines() return file_lines
bigcode/self-oss-instruct-sc2-concepts
import itertools def generate_test_list(settings): """All options that need to be tested are multiplied together. This creates a full list of all possible benchmark permutations that need to be run. """ loop_items = settings["loop_items"] dataset = [] for item in loop_items: resul...
bigcode/self-oss-instruct-sc2-concepts
def solve(passphrases): """Calculate number of valid passphrases. :passphrases: string of passphrases, separated by newlines :return: number of valid passphrases >>> solve('abcde fghij') 1 >>> solve('abcde xyz ecdab') 0 >>> solve('a ab abc abd abf abj') 1 >>> solve('iiii oiii o...
bigcode/self-oss-instruct-sc2-concepts
def group_by_xs(datasets): """ Return datasets grouped by polarization cross section. """ cross_sections = {} for data in datasets: cross_sections.setdefault(data.polarization, []).append(data) #print("datasets", [":".join((d.name, d.entry, d.polarization, d.intent)) for d in datasets])...
bigcode/self-oss-instruct-sc2-concepts
def _comment_ipython_line_magic(line, magic): """Adds suffix to line magics: # [magic] %{name} Converts: %timeit x = 1 Into: x = 1 # [magic] %timeit """ return line.replace(magic, '').strip() + f' # [magic] {magic.strip()}'
bigcode/self-oss-instruct-sc2-concepts
def _compose_sources(compose): """ Get compose sources . :param compose dict: Compose info from ODCS. :return: a list of lists in format [[N1, S1, V1, C1], [N2, S2, V2, C2]...]. :rtype: list """ source_value = compose.get("source", "") sources = [] for source in source_value.split()...
bigcode/self-oss-instruct-sc2-concepts
import importlib def import_func(func): """ Imports a function from the autocnet package. Parameters ---------- func : str import path. For example, to import the place_points_in_overlap function, this func can be called with: 'spatial.overlap.place_points_in_overlap' R...
bigcode/self-oss-instruct-sc2-concepts
def calc_delta_capacitance_ratio(capacitance_doublelayer, capacitance_dielectric): """ Ratio of the double layer to dielectric capacitance units: ~ Notes: Squires, 2010 - "Ratio of the double layer to dielectric capacitance" Adjari, 2006 - "Surface capacitance ratio" ...
bigcode/self-oss-instruct-sc2-concepts
import torch def load_waveglow_model(waveglow_path): """ Loads the Waveglow model. Uses GPU if available, otherwise uses CPU. Parameters ---------- waveglow_path : str Path to waveglow model Returns ------- Torch Loaded waveglow model """ waveglow = torch....
bigcode/self-oss-instruct-sc2-concepts
def _to(f, x, nearest): """ :param f: rounding function, e.g. ceiling, floor, round :param x: number to round :param nearest: number to round to :return: x rounded to `nearest` """ return nearest * f(float(x) / nearest)
bigcode/self-oss-instruct-sc2-concepts
import json def read_JSON_file(path): """ Given a line-by-line JSON file, this function converts it to a Python dict and returns all such lines as a list. :param path: the path to the JSON file :returns items: a list of dictionaries read from a JSON file """ items = list() with open(...
bigcode/self-oss-instruct-sc2-concepts
def unesc(s, esc_chars): """ UnEscape special characters """ for c in esc_chars: esc_str = '\\' + c s = s.replace(esc_str, c) return s
bigcode/self-oss-instruct-sc2-concepts
def _read(filename: str) -> str: """ Reads in the content of the file. :param filename: The file to read. :return: The file content. """ with open(filename, "r") as file: return file.read()
bigcode/self-oss-instruct-sc2-concepts
def all_boolean_reductions(request): """Fixture for boolean reduction names.""" return request.param
bigcode/self-oss-instruct-sc2-concepts