seed
stringlengths
1
14k
source
stringclasses
2 values
import re def get_indentation(keyword, search_str): """ In a multi-line string with new line characters, find the indentation of a search string. Currently assumes that spaces are used for indentation and the search string directly follows the indent. Args: keyword (string): The keyword t...
bigcode/self-oss-instruct-sc2-concepts
def generate_importer_base_name(dependent_task_name: str, input_name: str) -> str: """Generates the base name of an importer node. The base name is formed by connecting the dependent task name and the input artifact name. It's used to form task name, component ref, and executor la...
bigcode/self-oss-instruct-sc2-concepts
def smart_split(line): """ split string like: "C C 0.0033 0.0016 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'" in the list like: ['C', 'C', '0.0033', '0.0016', 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'] """ flag_in = False l_val, val = [], [] for hh in line.s...
bigcode/self-oss-instruct-sc2-concepts
def clip_boxes_opr(boxes, im_info): """ Clip the boxes into the image region.""" w = im_info[1] - 1 h = im_info[0] - 1 boxes[:, 0::4] = boxes[:, 0::4].clamp(min=0, max=w) boxes[:, 1::4] = boxes[:, 1::4].clamp(min=0, max=h) boxes[:, 2::4] = boxes[:, 2::4].clamp(min=0, max=w) boxes[:, 3::4] = ...
bigcode/self-oss-instruct-sc2-concepts
def parse_mappings(mapping_list): """Parse mapping devices list parses mapping device list in the form: physnet:pci_dev_1,pci_dev_2 or function:pci_dev_1,pci_dev_2 :param mapping_list: list of string pairs in "key:value" format the key part represents the physnet or function nam...
bigcode/self-oss-instruct-sc2-concepts
import math def part2(data): """Return least fuel to move all submarines to same position. Fuel to go from current to desired position is 1 + 2 + ... + abs(d - c). """ numbers = list(map(int, data.split(','))) # puzzle has 100s of numbers in a range of 1000, so brute-force is OK min_fuel = ma...
bigcode/self-oss-instruct-sc2-concepts
import math def compute_distance(loc1, loc2): """ params: - loc1 (location of start vertex) - loc2 (location of destination vertex) output: euclidean distance between the two vertices """ distance = math.sqrt(math.pow((loc1[0]-loc2[0]),2) + math.pow((loc1[1]-loc2[1]),2)) ...
bigcode/self-oss-instruct-sc2-concepts
def extract_document_size(block_data): """ Args: block_data(str): A data block with an entanglement header Returns: int: The size of the original document """ if not block_data or not isinstance(block_data, str): raise ValueError("argument block_data must be a non-empty seque...
bigcode/self-oss-instruct-sc2-concepts
import requests def aggregate_urns(urnlist): """Sum up word frequencies across urns""" if isinstance(urnlist[0], list): urnlist = [u[0] for u in urnlist] r = requests.post("https://api.nb.no/ngram/book_aggregates", json={'urns':urnlist}) return r.json()
bigcode/self-oss-instruct-sc2-concepts
def create_dict(keys_list): """ Creates a dictionary from a given list of keys """ dict_ = {} for key_ in keys_list: dict_[key_] = [] return dict_
bigcode/self-oss-instruct-sc2-concepts
def get_app_instances_ids(instances): """ Accepts a dictionary of id: AppInstance and returns a set of keys """ return set(instances.keys())
bigcode/self-oss-instruct-sc2-concepts
def layer_output(model, layer_name=None): """Output tensor of a specific layer in a model. """ conv_index = -1 for i in range(len(model.layers) - 1, -1, -1): layer = model.layers[i] if layer_name in layer.name: conv_index = i break if conv_index < 0: print('Error: could not find the interested layer...
bigcode/self-oss-instruct-sc2-concepts
def unpack_lemma_batch(batch, use_cuda): """ Unpack a batch from the data loader. """ if use_cuda: inputs = [b.cuda() if b is not None else None for b in batch[:6]] else: inputs = [b if b is not None else None for b in batch[:6]] orig_idx = batch[6] return inputs, orig_idx
bigcode/self-oss-instruct-sc2-concepts
def fillNaToMode(data): """Iterates through NA values and changes them to the mode Parameters: dataset (pd.Dataset): Both datasets Returns: data (pd.Dataset) : Dataset with any NA values in the columns listed changed to the mode """ columns = ["MSZoning", "Functional", "Electrical", "Kitch...
bigcode/self-oss-instruct-sc2-concepts
def _csize(counter): """ Computes the size of (number of elements in) a given Counter. Parameters ---------- counter : Counter The counter to get the size of. Returns ------- int """ return len(list(counter.elements()))
bigcode/self-oss-instruct-sc2-concepts
def list_to_hp(li: list) -> str: """ Converts a list (used for toolz get_in, assoc_in, update_in) to a hp (hierarchy path). Input: ['root', 0, 'thing',2] Output: /root/0/thing/2 """ assert isinstance(li, list), "The input type for li must be a list." assert "/" not in li, "Can't have ...
bigcode/self-oss-instruct-sc2-concepts
def l2s(x): """ [1,2,3,4,5,6,7,8] -> '1,2,...,7,8' """ if len(x)>5: x = x[:2] + ['...'] + x[-2:] y = [str(z) for z in x] # convert to list of strings, eg if list of int y = ",".join(y) return y
bigcode/self-oss-instruct-sc2-concepts
def count_word_occurrence_in_string(text, word): """ Counts how often word appears in text. Example: if text is "one two one two three four" and word is "one", then this function returns 2 """ words = text.split() return words.count(word)
bigcode/self-oss-instruct-sc2-concepts
import ipaddress import re def host_valid(host): """Return True if hostname or IP address is valid.""" try: if ipaddress.ip_address(host).version == (4 or 6): return True except ValueError: disallowed = re.compile(r"[^a-zA-Z\d\-]") return all(x and not disallowed.search...
bigcode/self-oss-instruct-sc2-concepts
def multiproduct(seq=(), start=1): """ Return the product of a sequence of factors with multiplicities, times the value of the parameter ``start``. The input may be a sequence of (factor, exponent) pairs or a dict of such pairs. >>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4 279936...
bigcode/self-oss-instruct-sc2-concepts
def make_comment(content: str) -> str: """Return a consistently formatted comment from the given `content` string. All comments (except for "##", "#!", "#:", '#'", "#%%") should have a single space between the hash sign and the content. If `content` didn't start with a hash sign, one is provided. ...
bigcode/self-oss-instruct-sc2-concepts
def get_alphabet(number): """ Helper function to figure out alphabet of a particular number Remember: * ASCII for lower case 'a' = 97 * chr(num) returns ASCII character for a number e.g. chr(65) ==> 'A' """ return chr(number + 96)
bigcode/self-oss-instruct-sc2-concepts
def make_doc1_url(court_id, pacer_doc_id, skip_attachment_page): """Make a doc1 URL. If skip_attachment_page is True, we replace the fourth digit with a 1 instead of a zero, which bypasses the attachment page. """ if skip_attachment_page and pacer_doc_id[3] == '0': # If the fourth digit is ...
bigcode/self-oss-instruct-sc2-concepts
import inspect from typing import Dict from typing import List def parse_method_signature( signature: inspect.Signature, param_dict: Dict[str, str] ) -> List[List[str]]: """Combines Signature with the contents of a param_dict to create rows for a parameter table. Args: signature: the output from ...
bigcode/self-oss-instruct-sc2-concepts
def part_one(password_list): """Count the number of passwords that meet their accompanying criteria. In this case, a password must have a specified character occur between a minimum and maximum number of times. :param password_list: A list of tuples from parse_input :return: int """ valid_p...
bigcode/self-oss-instruct-sc2-concepts
def create_stack( cfn_client, template_path, stack_name, params={}, capabilities=[], timeout=300, interval=30, ): """ Creates a cloudformation stack from a cloudformation template """ with open(template_path) as file: body = file.read() stack_params = [ ...
bigcode/self-oss-instruct-sc2-concepts
import random import string def letter(random=random, *args, **kwargs): """ Return a letter! >>> mock_random.seed(0) >>> letter(random=mock_random) 'a' >>> letter(random=mock_random) 'b' >>> letter(random=mock_random, capitalize=True) 'C' """ return random.choice(string.a...
bigcode/self-oss-instruct-sc2-concepts
def get_list_as_str(list_to_convert): """Convert list into comma separated string, with each element enclosed in single quotes""" return ", ".join(["'{}'".format(list_item) for list_item in list_to_convert])
bigcode/self-oss-instruct-sc2-concepts
def flatten(children, sidx, lidx): """ Helper function used in Visitor to flatten and filter lists of lists """ ret = [children[sidx]] rest = children[lidx] if not isinstance(rest, list): rest = [rest] ret.extend(list(filter(bool, rest))) return ret
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import NoReturn def _get_file_str(file: int) -> Union[str, NoReturn]: """Convert a given integer to a file letter on a chessboard.""" file_dict = { # Used for int to str lookup for files 0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h' } return file_dict[...
bigcode/self-oss-instruct-sc2-concepts
def vars_to_dic(vars): """ Converts list of tf variables to a dictionary where the var names are the keys Args: vars: list of variables Returns: dic """ return dict((var.name.split(":")[0], i) for i, var in enumerate(vars))
bigcode/self-oss-instruct-sc2-concepts
def all_routes(cities, i=0): """Return all possible routes, where cities[i:] have been permuted. Args: cities (list of string): The cities that make up each route. i (int, optional): The starting index of the subarray of cities to be permuted. Returns: list...
bigcode/self-oss-instruct-sc2-concepts
def _strip_h5(value: str) -> str: """ remove trailing .h5, if present """ if value.endswith(".h5"): value = value[:-3] return value
bigcode/self-oss-instruct-sc2-concepts
import torch def invariant_loss(x, y, symmetry): """ Finds permutation invariant loss, for fixed set of allowed permutations. Computes picking minimal loss under all permutations. Uses L2 loss. :param x: Input of shape (..., d) :param y: Output of shape (..., d) :param symmetry: Symmetry ...
bigcode/self-oss-instruct-sc2-concepts
def unique_edge_sizes(H): """A function that returns the unique edge sizes. Parameters ---------- H : Hypergraph object The hypergraph of interest Returns ------- list() The unique edge sizes """ return list({len(H.edges.members(edge)) for edge in H.edges})
bigcode/self-oss-instruct-sc2-concepts
def is_valid_str(s: str) -> bool: """ Check if the input string is not empty. :param s: Input string. :return: True if the string is not empty. """ if s is None: return False if not isinstance(s, str): return False if len(s) <= 0: return False return True
bigcode/self-oss-instruct-sc2-concepts
def sem_to_minor(version): """ Returns a minor release part of the semantic version @param version: semantic version in format x.x.x @return: minor release in format x.x """ return ".".join(version.split(".")[:2])
bigcode/self-oss-instruct-sc2-concepts
def _grid_location_equals(xarr,grid_location=None): """Return True when the xarr grid_location attribute is grid_location Parameters ---------- xarr : xarray.DataArray xarray dataarray which attributes should be tested. grid_location : str string describing the grid location : eg 'u'...
bigcode/self-oss-instruct-sc2-concepts
import logging def makeRecord(self, name, level, fn, lno, msg, args, exc_info, # noqa: N802 func=None, extra=None, sinfo=None): """ A factory method which can be overridden in subclasses to create specialized LogRecords. """ rv = logging.LogRecord(name, level, fn, lno, msg, args, e...
bigcode/self-oss-instruct-sc2-concepts
def set_chain(base, key_chain, value): """Sets a value in a chain of nested dictionaries. """ if base is None: base = {} cur = base n = len(key_chain) for i, key in enumerate(key_chain): if i + 1 < n: if key not in cur: cur[key] = {} cur = ...
bigcode/self-oss-instruct-sc2-concepts
def multiply_sequences(seq1: list, seq2: list): """ A function to multiply two sequences and return the result seq1: A list of integers seq2: A list of integers returns: seq1 * seq2 as a list """ if len(seq1) == len(seq2): return [x * y for x, y in zip(seq1, seq2)] elif len(seq1)...
bigcode/self-oss-instruct-sc2-concepts
def reprojection(gdf, tgt_crs): """Reproject in given the GeoDataFrame. Args: gdf (geopandas.GeoDataFrame): GeoDataFrame of reprojection target. tgt_crs (int): EPSG code of target crs. Returns: geopandas.GeoDataFrame: Reprojected GeoDataFrame. """ gdf = gdf.to_crs(tgt_crs) ...
bigcode/self-oss-instruct-sc2-concepts
import torch def fix_K_camera(K, img_size=137): """Fix camera projection matrix. This changes a camera projection matrix that maps to [0, img_size] x [0, img_size] to one that maps to [-1, 1] x [-1, 1]. Args: K (np.ndarray): Camera projection matrix. img_size (float): Size of im...
bigcode/self-oss-instruct-sc2-concepts
def get_bit(n: int, i: int) -> int: """ Description: Récupère le i-ème bit de n. Paramètres: n: {int} -- Le nombre à traiter i: {int} -- L'index du bit à récupérer Retourne: {int} -- 0 ou 1 Exemple: >>> get_bit(2, 0) 0 >>> get_bit(2, 1...
bigcode/self-oss-instruct-sc2-concepts
import socket def unbracket_ipv6(address): """Remove a bracket around addresses if it is valid IPv6 Return it unchanged if it is a hostname or IPv4 address. """ if '[' in address and ']' in address: s = address[address.find("[") + 1:address.find("]")] try: socket.inet_pton...
bigcode/self-oss-instruct-sc2-concepts
import re def extract_version_changelog(changelog, version): """Extract the changelog for a particular version from the entire changelog.""" escaped_version = re.escape(version) pattern = rf"""(?m:^)# Data Hub API {escaped_version} \([0-9-]+\) (?P<content>.*?) (# Data Hub API|$)""" match = re.search...
bigcode/self-oss-instruct-sc2-concepts
def _create_indice(chip): """Account for missing indices (Duo and PrixPowr) and create them. Even if these indices do not actually exist, we still need one for relational data purposes. """ if not chip['game'] == 'bn4': # Nothing to do here. return chip['indice'] indice = ...
bigcode/self-oss-instruct-sc2-concepts
import math def get_dxy(region: tuple): """ Get the grid spacing size that will be used to open a grd file Note: h5py will crash when opening grd with less than 2^14 gridpoints, so keep dx and dy small enough relative to domain Parameters ---------- region : (min lon, max lon, min lat, ma...
bigcode/self-oss-instruct-sc2-concepts
def extractDatSignerParts(dat, method="igo"): """ Parses and returns did index keystr from signer field value of dat as tuple (did, index, keystr) raises ValueError if fails parsing """ # get signer key from read data. assumes that resource is valid try: did, index = dat["signer"].rs...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_name(path): """Gets the name of the dynophore trajectory without the .pml extension Args: path (str): File path to the dynophore trajectory Returns: str: dynophore_pml """ file = Path(path).stem return file
bigcode/self-oss-instruct-sc2-concepts
import torch def select_embs(embs, pred_cands, M): """Select the embeddings for the predicted indices. Args: embs: embedding tensor (M x K x H) pred_cands: indices into the K candidates to select (M) M: M Returns: selected embedding (M x H) """ return embs[torch.arange(M)...
bigcode/self-oss-instruct-sc2-concepts
def get_uid_warning(uid: str) -> str: """ Returns the templated message for the warning of existing `UID`, while creating a `Student` """ uid_href = f"/students/{uid}/#:~:text={uid}" msg = f"Student with UID <a class=\"alert-link text-secondary font-weight-medium text-decoration-none\"\ ...
bigcode/self-oss-instruct-sc2-concepts
def cdf_TPL(x, a, beta, b): """ Cumulative function for truncated power law. pdf(x) = (beta-1)/(a*(1-c^(beta-1))) * (a/x)^beta for a <= x <= b """ F = (1-(a/x)**(beta-1))/(1-(a/b)**(beta-1)) return F
bigcode/self-oss-instruct-sc2-concepts
def remove_special_chars(text: str): """ Removes the special characters. :param text: text to be modified :return: modified data """ filtered = text.strip().replace('\'', '').replace('"', '').replace('”', '')\ .replace('–', '').replace('“', '').replace('!', '.').replace(...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import json def error_response(text: str = '', status_code: int = 400, content_type: str = 'text/html; charset=utf-8') -> Dict: """ Creates an error response with parameterizable values. :param text: Optional explanatory error text :type text: str :param status_code: Respo...
bigcode/self-oss-instruct-sc2-concepts
def get_severity_detail(severity_detail): """ Retrieve details of severity related fields. :param severity_detail: severity details from response :return: severity detail :rtype: dict """ return { 'Combined': severity_detail.get('combined', ''), 'Overridden': severity_detail...
bigcode/self-oss-instruct-sc2-concepts
def dirstats(path): """Get stats for the specified directory. Parameters ---------- path : Path Directory to calculate stats of. Returns ------- num_files : int Number of files under the directory (recursive). total_size : int Total size in bytes of all files un...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def to_affiliations_list(dict_: Dict): """Convert affiliation dict into a list. :param dict_: affiliation dict. :return: affiliation list. """ l_ = [] for k, v in dict_.items(): v["members"] = list(v["members"]) v["members"].sort() if "count" i...
bigcode/self-oss-instruct-sc2-concepts
def get_lawyer_id(obj): """ Returns string representing an lawyer object. Returns obj.organization if it exists, else returns concatenated obj.name_first + '|' + obj.name_last """ if obj.organization: return obj.organization try: return obj.name_first + '|' + obj.name_last ex...
bigcode/self-oss-instruct-sc2-concepts
def rosenbrock(x): """Rosenbrock test fitness function""" n = len(x) if n < 2: raise ValueError('dimension must be greater than one') return -sum(100 * (x[i+1] - x[i]**2)**2 + (1 - x[i])**2 for i in range(n-1))
bigcode/self-oss-instruct-sc2-concepts
def model_name_to_rest(name): """Gets a name of a :mod:`atomx.models` and transforms it in the resource name for the atomx api. E.g.:: >>> assert model_name_to_rest('ConversionPixels') == 'conversion-pixels' >>> assert model_name_to_rest('OperatingSystem') == 'operating-system' >>> ...
bigcode/self-oss-instruct-sc2-concepts
def geometricSeries(*, u_1: int, r: int, n: int) -> int: """Compute geometric series up to 'n', given initial value 'u_1' and common ratio 'r'.""" return (u_1 * n) if r == 1 else (u_1 * (u_1 ** n - 1) / (r - 1))
bigcode/self-oss-instruct-sc2-concepts
def _audience_condition_deserializer(obj_dict): """ Deserializer defining how dict objects need to be decoded for audience conditions. Args: obj_dict: Dict representing one audience condition. Returns: List consisting of condition key with corresponding value, type and match. """ return [ ...
bigcode/self-oss-instruct-sc2-concepts
def _use_ssl(addr): """Decide if SSL should be used for the given server address.""" if isinstance(addr, str): return addr.endswith(':993') return len(addr) == 2 and addr[1] == 993
bigcode/self-oss-instruct-sc2-concepts
def sbr(data, weights): """Stolen Base Runs (SBR) SBR = runSB * SB + runCS * CS :param data: DataFrame or Series of player, team, or league totals :param weights: DataFrame or Series of linear weights :returns: Series of SBR values """ return weights["lw_sb"] * data["sb"] + weights["lw_cs"]...
bigcode/self-oss-instruct-sc2-concepts
import json def already_run(db, configuration): """Checks whether the given configuration is already present in the database""" configuration = configuration.copy() configuration['threads'] = configuration.get('threads', 1) configuration['params']['threads'] = configuration.get('threads', 1) confi...
bigcode/self-oss-instruct-sc2-concepts
def does_entry_exist(conn, tweet_id): """ Check weather entry with exact tweet_id already exists :param conn: DB connection :param tweet_id: tweet_id to check :return: True if story already in db, else False """ cur = conn.cursor() cur.execute("SELECT * FROM tweets WHERE tweet_id=?", (tweet_...
bigcode/self-oss-instruct-sc2-concepts
import re def check_list_name(name): """checks that list_name begins with an alphanumeric character Parameters ---------- name: string name of the new listing. Return ------ bool True if listing name conforms to requirements """ return re.search(r'^\w+', name) ...
bigcode/self-oss-instruct-sc2-concepts
def total_norm(tensors, norm_type=2): """ Computes total norm of the tensors as if concatenated into 1 vector. """ if norm_type == float('inf'): return max(t.abs().max() for t in tensors) return sum(t.norm(norm_type) ** norm_type for t in tensors) ** (1. / norm_type)
bigcode/self-oss-instruct-sc2-concepts
import re def charges_clean_up(charges): """ Returns cleaned charges. Charges are typically separated by newlines and can often be in all caps, which we want to avoid.""" charges = charges.split("\n") charges = [charge.capitalize() for charge in charges] charges = "; ".join(charges) # we want...
bigcode/self-oss-instruct-sc2-concepts
def make_ordinal(number): """ Coverts an integer to an ordinal string :param number: integer to convert :return: ordinal string """ number = int(number) suffix = ['th', 'st', 'nd', 'rd', 'th'][min(number % 10, 4)] if 11 <= (number % 100) <= 13: suffix = 'th' return str(numbe...
bigcode/self-oss-instruct-sc2-concepts
def _get_displayed_page_numbers(current, final): """ This utility function determines a list of page numbers to display. This gives us a nice contextually relevant set of page numbers. For example: current=14, final=16 -> [1, None, 13, 14, 15, 16] This implementation gives one page to each side ...
bigcode/self-oss-instruct-sc2-concepts
def OP_start(counter_state): """Our start state initializes counter_state.count = 0""" counter_state.count = 0 operator = "counter" return(operator, counter_state)
bigcode/self-oss-instruct-sc2-concepts
def get_train_test_data(all_fc_data, train_subs, test_subs, behav_data, behav): """ Extracts requested FC and behavioral data for a list of train_subs and test_subs """ train_vcts = all_fc_data.loc[train_subs, :] test_vcts = all_fc_data.loc[test_subs, :] train_behav = behav_data.loc[train_subs...
bigcode/self-oss-instruct-sc2-concepts
import uuid def _get_uuids(cnt): """ Return things like this 75659c39-eaea-47b7-ba26-92e9ff183e6c """ uuids = set() while len(uuids) < cnt: uuids.add(str(uuid.uuid4())) return uuids
bigcode/self-oss-instruct-sc2-concepts
def exp_smooth(new_n, new_s, new_m, old_n, old_s, old_m, a = 0.05): """ This function takes in new and old smoothed values for mean, sd and sample size and returns an exponentially smoothed mean, sd and sample size. """ smooth_n = a*new_n + (1-a)*old_n smooth_s = a*new_s + (1-a)*old_s sm...
bigcode/self-oss-instruct-sc2-concepts
def istoken(docgraph, node_id, namespace=None): """returns true, iff the given node ID belongs to a token node. Parameters ---------- node_id : str the node to be checked namespace : str or None If a namespace is given, only look for tokens in the given namespace. Otherwise,...
bigcode/self-oss-instruct-sc2-concepts
def convert_meV_to_GHz(w): """ Convert an energy from unit meV to unit GHz. Parameters ---------- w : float / array The energy in the old unit. Returns ------- w_new_unit : float / array The energy in the new unit. """ # 1 meV = 1.0/4.1357e-3 GHz w_GHz = w /...
bigcode/self-oss-instruct-sc2-concepts
def exactly_one(iterable): """Obtain exactly one item from the iterable or raise an exception.""" i = iter(iterable) try: item = next(i) except StopIteration: raise ValueError("Too few items. Expected exactly one.") try: next(i) except StopIteration: return item ...
bigcode/self-oss-instruct-sc2-concepts
def generate_final_vocabulary(reserved_tokens, char_tokens, curr_tokens): """Generates final vocab given reserved, single-character, and current tokens. Args: reserved_tokens: list of strings (tokens) that must be included in vocab char_tokens: set of single-character strings curr_tokens: stri...
bigcode/self-oss-instruct-sc2-concepts
def _strip_markup_line(line, sigil): """Strip sigil and whitespace from a line of markup""" return line.lstrip(sigil).rstrip()
bigcode/self-oss-instruct-sc2-concepts
def is_prim_rou(modulus: int, degree: int, val: int) -> bool: """ Test whether input x is a primitive 2d^th root of unity in the integers modulo q. Does not require q and d to be NTT-friendly pair. :param modulus: Input modulus :type modulus: int :param degree: Input degree :type degree: in...
bigcode/self-oss-instruct-sc2-concepts
def ordinal( value ): """ Converts zero or a *postive* integer (or their string representations) to an ordinal value. >>> for i in range(1,13): ... ordinal(i) ... '1st' '2nd' '3rd' '4th' '5th' '6th' '7th' '8th' '9th' '10th' '11th' '12th' >>> for i in (100, '111', '112',1011): ... ordinal(i) ...
bigcode/self-oss-instruct-sc2-concepts
def _clean_netloc(netloc): """Remove trailing '.' and ':' and tolower. >>> _clean_netloc('eXample.coM:') 'example.com' """ try: return netloc.rstrip('.:').lower() except: return netloc.rstrip('.:').decode('utf-8').lower().encode('utf-8')
bigcode/self-oss-instruct-sc2-concepts
def load_kitti_odom_intrinsics(file_name, new_h, new_w): """Load kitti odometry data intrinscis Args: file_name (str): txt file path Returns: intrinsics (dict): each element contains [cx, cy, fx, fy] """ raw_img_h = 370.0 raw_img_w = 1226.0 intrinsics = {} with open...
bigcode/self-oss-instruct-sc2-concepts
def build_titles_list(title, args): """Build a list of titles from the 'title' option and arguments. Args: title: NoneType or unicode Title given to options.title args: list Leftover arguments on the command line, presumably extra titles. Returns: List of strings or [None]. """ # If args is non...
bigcode/self-oss-instruct-sc2-concepts
def norm(s: str) -> str: """Normalize a string for dictionary lookup.""" return s.lower().replace(" ", "").replace("-", "").replace(".", "")
bigcode/self-oss-instruct-sc2-concepts
def dig_pow(n, p): """ Some numbers have funny properties. For example: 89 --> 8¹ + 9² = 89 * 1 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51 Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p we w...
bigcode/self-oss-instruct-sc2-concepts
def _get_boundary_date_string(date_sr, boundary, date_format='%Y-%m-%d'): """ Returns the first or last date of the series date_sr based on the value passed in boundary. date_sr: Series consisting of date boundary: Allowed values are 'first' or 'last' date_format: Format to be used for co...
bigcode/self-oss-instruct-sc2-concepts
def detach_nic(fco_api, server_uuid, nic_uuid): """ Detach NIC from server :param fco_api: FCO API object :param server_uuid: Server UUID :param nic_uuid: NIC UUID :return: Job-compatible object """ return fco_api.detachNic(serverUUID=server_uuid, networkInt...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_rays_shapenet(hwf, poses): """ shapenet camera intrinsics are defined by H, W and focal. this function can handle multiple camera poses at a time. Args: hwf (3,): H, W, focal poses (N, 4, 4): pose for N number of images Returns: rays_o (N, H, W...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_random_index(x: torch.Tensor) -> torch.Tensor: """Given a tensor it compute random indices between 0 and the number of the first dimension :param x: Tensor used to get the number of rows """ batch_size = x.size()[0] index = torch.randperm(batch_size) return index
bigcode/self-oss-instruct-sc2-concepts
def instance_attributes(inst): """Given an instance, lists the name of all public non-callable members. Attributes: inst (obj): The instance of the object. """ return [n for n in dir(inst) if not n.startswith('_') and not callable(getattr(inst, n))]
bigcode/self-oss-instruct-sc2-concepts
def calc_shield_power(block_count, active=False): """ Calculate the power usage of Shield Rechargers Given the number of Shield Rechargers, this function will calculate how much power they draw in 'e/sec'. It will calculate both inactive (shields full) and active (shields charging) power consumption b...
bigcode/self-oss-instruct-sc2-concepts
def type_to_class_string(type): """ Takes a ROS msg type and turns it into a Python module and class name. E.g >>> type_to_class_string("geometry_msgs/Pose") geometry_msgs.msg._Pose.Pose :Args: | type (str): The ROS message type to return class string :Returns: | str: A py...
bigcode/self-oss-instruct-sc2-concepts
def dfs(reactions, chemical, seen): """DFS to traverse all reaction requirements for chemical.""" seen.add(chemical) if chemical == 'ORE': return [] order = [] _, needed_chemicals = reactions[chemical] for next_chemical, _ in needed_chemicals.items(): if next_chemical not in seen...
bigcode/self-oss-instruct-sc2-concepts
def get_survey_local_time_dayofweek(dt): """Get day of week when survey was taken.""" try: weekday = dt.weekday() weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] return weekdays[weekday] except: return None
bigcode/self-oss-instruct-sc2-concepts
def sort_links(links): """Sorts endpoint links alphabetically by their href""" return sorted(links, key=lambda link: link["href"])
bigcode/self-oss-instruct-sc2-concepts
def convertBytes(nbytes): """Convert a size in bytes to a string.""" if nbytes >= 1e9: return '{:.1f} GB'.format(nbytes / 1e9) elif nbytes >= 1e6: return '{:.1f} MB'.format(nbytes / 1e6) elif nbytes >= 1e3: return '{:.1f} KB'.format(nbytes / 1e3) else: return '{:.1f} ...
bigcode/self-oss-instruct-sc2-concepts
from six import string_types import logging def log_level(level): """ Attempt to convert the given argument into a log level. Log levels are represented as integers, where higher values are more severe. If the given level is already an integer, it is simply returned. If the given level is a s...
bigcode/self-oss-instruct-sc2-concepts