seed
stringlengths
1
14k
source
stringclasses
2 values
def num2filename(x,d): """ Takes a number and returns a string with the value of the number, but in a format that is writable into a filename. s = num2filename(x,d) Gets rid of decimal points which are usually inconvenient to have in a filename. If the number x is an integer, then s = s...
bigcode/self-oss-instruct-sc2-concepts
import unicodedata import re def clean(value): """Replaces non-ascii characters with their closest ascii representation and then removes everything but [A-Za-z0-9 ]""" normalized = unicodedata.normalize('NFKD', value) cleaned = re.sub(r'[^A-Za-z0-9 ]','',normalized) return cleaned
bigcode/self-oss-instruct-sc2-concepts
def filter_params(model, prefix): """Return a list of model parameters whose names begin with a prefix""" return [p for p in model.parameters if p.name.startswith(prefix)]
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Optional from typing import Tuple from typing import Dict def make_dataset( paths: List[str], extensions: Optional[Tuple[str, ...]] = None, ) -> Tuple[List[Tuple[str, int]], Dict[bytes, int]]: """ Map folder+classnames into list of (imagepath, class_i...
bigcode/self-oss-instruct-sc2-concepts
def do_nothing(list_of_words): """Return the argument unchanged.""" return list_of_words
bigcode/self-oss-instruct-sc2-concepts
def num_examples_per_epoch(split): """Returns the number of examples in the data set. Args: split: name of the split, "train" or "validation". Raises: ValueError: if split name is incorrect. Returns: Number of example in the split. """ if split.lower().startswith('train'): return 100000 el...
bigcode/self-oss-instruct-sc2-concepts
import re def find_(word, stream, ignore_case=True): """Find the `word` in the `stream`. :param word: str, word or pattern to be searched in stream :param stream: str, stream to be searched in :param ignore_case: whether to ignore the case :returns: the corresponding `word` (could be of different...
bigcode/self-oss-instruct-sc2-concepts
def coroutine(func): """ A decorator to create our coroutines from generator definitions. Calling a generator function does not start running the function! Instead, it returns a generator object. All co-routines must be "primed" by calling ``next`` or ``send` to run up until the first ``yield``. ...
bigcode/self-oss-instruct-sc2-concepts
def clean_component(doc): """ Clean up text. Make lowercase and remove punctuation and stopwords """ # Remove punctuation, symbols (#) and stopwords doc = [tok.text.lower() for tok in doc if (not tok.is_stop and tok.pos_ != 'PUNCT' and ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _get_key_hashes(rec: dict) -> List[str]: """Get key hashes in ledger state snapshot record.""" return [r[0]["key hash"] for r in rec]
bigcode/self-oss-instruct-sc2-concepts
import re def parse_output_areas(msg): """Parse create area message and return area number""" res = re.search(r"(OUTPUT AREAS =\s*)([0-9]+)", msg) if res is not None: return int(res.group(2))
bigcode/self-oss-instruct-sc2-concepts
def filter(df,column_name,field_value): """Filter a data frame to only include matches with field value in column_name""" tmp_df = df[df[column_name].isnull() == False] return tmp_df[tmp_df[column_name]==field_value]
bigcode/self-oss-instruct-sc2-concepts
import fnmatch def ignore_rule_matches_result(ignore_rule, pa11y_result): """ Returns a boolean result of whether the given ignore rule matches the given pa11y result. The rule only matches the result if *all* attributes of the rule match. """ return all( fnmatch.fnmatch(pa11y_result.g...
bigcode/self-oss-instruct-sc2-concepts
def DecodeMAC(macbin): """Turn the given binary MAC address into a printable string.""" assert len(macbin) == 6 return ':'.join(['%02x' % ord(i) for i in macbin])
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def get_data(filename): """Gets a data file from the package. Args: filename: The name of the data file as located in the package data directory. Returns: A readable file-like object for the data file. """ path = "data/" + filename return pkg_r...
bigcode/self-oss-instruct-sc2-concepts
def get_time_groupby_name(time_groups): """Return a name reflecting the temporal groupby operation.""" # Define time groupby name time_groups_list = [] for k, v in time_groups.items(): if v == 1: time_groups_list.append(k) else: time_groups_list.append(str(v) +...
bigcode/self-oss-instruct-sc2-concepts
def to_numpy(tensor): """ If the tensor requires gradients, then detach it from the computation graph, move it to the CPU, and convert it to a NumPy array. Otherwise, just move it to the CPU and convert it to a NumPy array :param tensor: A PyTorch tensor :return: the tensor as a numpy array. ...
bigcode/self-oss-instruct-sc2-concepts
def BinsTriangleInequality(d1, d2, d3): """ checks the triangle inequality for combinations of distance bins. the general triangle inequality is: d1 + d2 >= d3 the conservative binned form of this is: d1(upper) + d2(upper) >= d3(lower) """ if d1[1] + d2[1] < d3[0]: return False i...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import Set def get_local_projects(path: Path) -> Set[str]: """ Returns all the projects (directories) under `path`. """ return {f.name for f in path.iterdir() if f.is_dir() and not f.name.startswith(".")}
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import lzma import pickle def load(input_path: str) -> Any: """ Unpickle the object. :param input_path: Input path of pickled object. :return: The object. """ with lzma.open(input_path, 'rb') as reader: reto = pickle.load(reader) return reto
bigcode/self-oss-instruct-sc2-concepts
def _parse_values(value_string): """Parse comma-delimited values from a string""" values = list() for raw in value_string.split(','): raw = raw.strip() if len(raw) > 1 and raw[0] == '"' and raw[-1] == '"': raw = raw[1:-1].strip() values.append(raw) return values
bigcode/self-oss-instruct-sc2-concepts
import time def datecode(t=None, local=False): """The date code incorporates both the unix time and the date in either the local timezone (respecting DST) or UTC (aka GMT). It is convenient for naming ops subdirectories or tagging events for easy sorting.""" if t == None: t = time.time() zt = tim...
bigcode/self-oss-instruct-sc2-concepts
def valid_request_body_with_existing_priority(valid_request_model): """ A fixture for creating a request body with existing priority number for a client. Args: valid_request_model (Model): a valid request model created by a fixture. """ return { 'title': 'Add PayPal ...
bigcode/self-oss-instruct-sc2-concepts
def read_elastodyn_dat(path): """Get dictionary from an elastodyn dat file""" d = {} with open(path, 'r') as ed: end = False for line in ed: contents = line.split() if contents[0] == 'OutList': end = True if end: break ...
bigcode/self-oss-instruct-sc2-concepts
import json def get_file_json(path): """Read a file and return parsed JSON object.""" with open(path, 'r') as f: return json.load(f)
bigcode/self-oss-instruct-sc2-concepts
def swagger_escape(s): # pragma: no cover """ / and ~ are special characters in JSON Pointers, and need to be escaped when used literally (for example, in path names). https://swagger.io/docs/specification/using-ref/#escape """ return s.replace('~', '~0').replace('/', '~1')
bigcode/self-oss-instruct-sc2-concepts
def make_ffmpeg_section_args( filename, start, length, *, before_options=(), options=(), ): """Returns a list of arguments to FFmpeg It will take the required amount of audio starting from the specified start time and convert them into PCM 16-bit stereo audio to be piped to stdout. ...
bigcode/self-oss-instruct-sc2-concepts
def mse_node(w_samples, y_sum, y_sq_sum): """Computes the variance of the labels in the node Parameters ---------- w_samples : float Weighted number of samples in the node y_sum : float Weighted sum of the label in the node y_sq_sum : float Weighted sum of the squared ...
bigcode/self-oss-instruct-sc2-concepts
def GetKeyIdFromResourceName(name): """Gets the key id from a resource name. No validation is done.""" return name.split('/')[5]
bigcode/self-oss-instruct-sc2-concepts
def encode(value, encoding='utf-8'): """Encode given Unicode value to bytes with given encoding :param str value: the value to encode :param str encoding: selected encoding :return: bytes; value encoded to bytes if input is a string, original value otherwise >>> from pyams_utils.unicode import enc...
bigcode/self-oss-instruct-sc2-concepts
import math def rotate(x, y, alpha, xCenter = 0, yCenter = 0): """ rotate a point by a given angle @param x x-coordinate of the point that needs to be rotated @param y y-coordinate of the point that needs to be rotated @param alpha rotation angle [0..2pi radians] @param xCenter x-coordinate of the origin (0 is ...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_tag(entry, alltag=False): """remove SRT and ASS tags if alltag, NoTagApp specials ([b]/[i]/[u]) tag are removed too """ tag_pattern = r"{\\.*?}|</?font.*?>|</?.*?>" if alltag: tag_pattern += r"|\[/?.?\]" return re.sub(tag_pattern, "", entry)
bigcode/self-oss-instruct-sc2-concepts
def sqrt(n: int) -> int: """Gets the integer square root of an integer rounded toward zero.""" return int(n ** 0.5)
bigcode/self-oss-instruct-sc2-concepts
def convert_diameter_sigma_to_fwhm(diameter): """ Converts a beam diameter expressed as the full with at half maximum (FWHM) to a beam diameter expressed as 2-sigma of a Gaussian distribution (radius = sigma). :arg diameter: 2-sigma diameter diameter. """ # d_{FWHM} = 1.177411 (2\sigma) ...
bigcode/self-oss-instruct-sc2-concepts
def construct_exec_result(result, exec_result): """ Transform an ImpalaBeeswaxResult object to a QueryResult object. Args: result (ImpalaBeeswasResult): Tranfers data from here. exec_result (QueryResult): Transfers data to here. Returns: QueryResult """ # Return immedietely if the query failed....
bigcode/self-oss-instruct-sc2-concepts
def table_from_fk(fks): """Get the table name of the fk constraint, ignoring the cordis_projects table Args: fks (:obj:`list` of SqlAlchemy.ForeignKey): All foreign keys for a given table. Returns: tablename (str): The table name corresponding to the non-Project foreign key. """...
bigcode/self-oss-instruct-sc2-concepts
import gzip def write_fastq(filename): """ return a handle for FASTQ writing, handling gzipped files """ if filename: if filename.endswith('gz'): filename_fh = gzip.open(filename, mode='wt') else: filename_fh = open(filename, mode='w') else: filename...
bigcode/self-oss-instruct-sc2-concepts
def intersection(set1, set2): """ Calculates the intersection size between two sets, used to compute overlap between a word context and a definition's signature. @param set1 - First set @param set2 - Second set @return Intersection size """ return len(set(set1) & set(set2))
bigcode/self-oss-instruct-sc2-concepts
def groupby(keys, values): """Group values according to their key.""" d = {} for k, v in zip(keys, values): d.setdefault(k, []).append(v) return d
bigcode/self-oss-instruct-sc2-concepts
def square_loss(a, b): """ Returns the value of L(a,b)=(1/2)*|a-b|^2 """ return 0.5 * (a - b)**2
bigcode/self-oss-instruct-sc2-concepts
def is_filetype(filename: str) -> bool: """ Return true if fname is ends with .csv, .xlsx, or .xls. Otherwise return False. :filename: filename string Returns bool """ cfname = filename.lower() if cfname.endswith(".csv") and not cfname.startswith("pdappend"): return True ...
bigcode/self-oss-instruct-sc2-concepts
def image_meta(system_metadata): """Format image metadata for use in notifications from the instance system metadata. """ image_meta = {} for md_key, md_value in system_metadata.items(): if md_key.startswith('image_'): image_meta[md_key[6:]] = md_value return image_meta
bigcode/self-oss-instruct-sc2-concepts
def get_tech_installed(enduse, fuel_switches): """Read out all technologies which are specifically switched to of a specific enduse Parameter --------- enduse : str enduse fuel_switches : dict All fuel switches where a share of a fuel of an enduse is switched to a specif...
bigcode/self-oss-instruct-sc2-concepts
def x_label(epoch_axis): """ Get the x axis label depending on the boolean epoch_axis. Arguments: epoch_axis (bool): If true, use Epoch, if false use Minibatch Returns: str: "Epoch" or "Minibatch" """ return "Epoch" if epoch_axis else "Minibatch"
bigcode/self-oss-instruct-sc2-concepts
import ast def count_number_of_functions(filepath): """Count number of functions inside a .py file.""" # Taken from: https://stackoverflow.com/a/37514895/1274908 with open(filepath, "r+") as f: tree = ast.parse(f.read()) return sum(isinstance(exp, ast.FunctionDef) for exp in tree.body)
bigcode/self-oss-instruct-sc2-concepts
import inspect def parse_comments(func): """ parse function comments First line of comments will be saved as summary, and the rest will be saved as description. """ doc = inspect.getdoc(func) if doc is None: return None, None doc = doc.split('\n', 1) if len(doc) == 1: ...
bigcode/self-oss-instruct-sc2-concepts
def __tokenify(number): """ 生成随机验证字符串 :param number: :return: 随机验证字符串 """ token_buf = [] # char map 共64个字符 char_map = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ*$' remainder = number while remainder>0: token_buf.append(char_map[remainder&0x3F]) remainder = remainder // 64 return ''....
bigcode/self-oss-instruct-sc2-concepts
def remove_at_index(lst, index): """ Creates a new list which is a copy of the input one with a single element removed from it """ removed = lst[:] del removed[index] return removed
bigcode/self-oss-instruct-sc2-concepts
def early_stop(metrics, steps, min_improvement=0, higher_is_better=False): """Early stopping condition. Args: metrics: A list of metric values. steps: Consider the improvement over this many steps. min_improvement: Continue if the metric improved less than this value: higher_is_better: Whether a hi...
bigcode/self-oss-instruct-sc2-concepts
def r19o(factor: float = 1) -> float: """ The outer size of the mounting rails of a 19-inch full rack giving it its name. """ return 482.6 * factor
bigcode/self-oss-instruct-sc2-concepts
def decode_message(encoded_text, dictionary): """Decodes encoded text according to the given dictionary. Huffman encoded messages can be decoded only if we have the original dictionary that is used to encode the message. If the encoded message includes an unknown code function raises an error. Arg...
bigcode/self-oss-instruct-sc2-concepts
def detail_line(e): """Given an expectation, return a readable one-line explanation of it.""" fields = [fname for fname in ('mutable', 'optional', 'volatile') if getattr(e, fname, None)] if e.depends_on: fields.append("depends_on=%s" % e.depends_on) line = ', '.join(fields) i...
bigcode/self-oss-instruct-sc2-concepts
def clamp(n, maxabs): """Clamp a number to be between -maxabs and maxabs""" return max(-maxabs, min(n, maxabs))
bigcode/self-oss-instruct-sc2-concepts
import random def mutation_single_customer_rerouting(vehicle, p1, quality, duration, setup_time, setup_cost, demand): """Re-routing involves randomly selecting one customer, and removing that customer from the existing route. The customer is then inserted in the best...
bigcode/self-oss-instruct-sc2-concepts
def parse_context_name(context_obj): """Parses context name from Dialogflow's contextsession prefixed context path""" return context_obj["name"].split("/contexts/")[1]
bigcode/self-oss-instruct-sc2-concepts
def options2args(options): """Convert a list of command line options to a args and kwargs """ args = list() kwargs = dict() for a in options: if "=" in a: a = a.split("=", maxsplit=1) kwargs[a[0].lstrip("-")] = a[1] else: args.append(a) return args...
bigcode/self-oss-instruct-sc2-concepts
def rename_variable(formula, old_name, new_name): """ Function that traverses the formula and changes the appearance of one variable. The renaming is done to the values of the id and field attributes. :param formula: Root node of the formula object :param old_name: Old variable name :param ...
bigcode/self-oss-instruct-sc2-concepts
def convert_list_to_string(org_list, seperator=' '): """ Convert list to string, by joining all item in list with given separator. Returns the concatenated string """ return seperator.join(org_list)
bigcode/self-oss-instruct-sc2-concepts
def _pad_with_nulls(data, len_): """ Pad string with null bytes. Parameters ---------- data : str/bytes the string/bytes to pad len_ : int the final desired length """ return data + (b'\x00' * (len_ - len(data)))
bigcode/self-oss-instruct-sc2-concepts
def generated_tag_data(tags): """Convert :obj:`dict` to S3 Tag list. Args: tags (dict): Dictonary of tag key and tag value passed. Returns: list: List of dictionaries. """ generated_tags = [] for key, value in tags.items(): generated_tags.append({ 'Key': ke...
bigcode/self-oss-instruct-sc2-concepts
def fitness(individual, problem): """ Score the fitness of an indivdual based on a MAXSAT problem. :param individual: An "individual" represented as an array :param problem: MAXSAT problem to compute fitness in ref to, usually stored as global MAXSAT_PROBLEM :return: An int representation of ind...
bigcode/self-oss-instruct-sc2-concepts
def is_excluded(path, dirs): """ if path is excluded in list of dirs/files :param path: path to check for exclude :param dirs: list of excludes :return: Boolean """ for directory in dirs: if path.startswith(directory): return True return False
bigcode/self-oss-instruct-sc2-concepts
def rearrange_name(s: str) -> str: """Converts last, first to first last Args: s (str): the original string Returns: str: the standardized string """ return ' '.join(reversed([i.strip() for i in s.split(', ')]))
bigcode/self-oss-instruct-sc2-concepts
def int_pow(x: float, exponent: float) -> int: """Finds the nearest integer to ``pow(x, exponent)``. Args: x: The number whose power will be found. exponent: The number to which ``x`` will be raised. Returns: The result of rounding ``pow(x, exponent)`` to the nearest integer. "...
bigcode/self-oss-instruct-sc2-concepts
def mock_moira(mocker): """Return a fake mit_moira.Moira object""" return mocker.patch("moira_lists.moira_api.Moira")
bigcode/self-oss-instruct-sc2-concepts
def _trapz_simps_overlap2(dy, dx): """Correction term in the squared error when combining trapezoidal and Simpson's rule. Only exact for equal spacing *dx* left and right of *dy*. err^2 = (h/6)^2 ((3 Df0)^2 + ((3+2)Df1)^2 + (8Df2)^2 + (4Df3)^2 + ...) |-- trapz ---| |--------- Simpson...
bigcode/self-oss-instruct-sc2-concepts
import ast def _safe_eval(node, default): """ Safely evaluate the Boolean expression under the given AST node. Substitute `default` for all sub-expressions that cannot be evaluated (because variables or functions are undefined). We could use eval() to evaluate more sub-expressions. However, this...
bigcode/self-oss-instruct-sc2-concepts
def percentage(context, num, total_num): """ Works out the percentage of num over total_num and then appends the percentage sign """ p = float(num)/float(total_num) * 100 percent = str(p) + "%" return percent
bigcode/self-oss-instruct-sc2-concepts
def bdev_nvme_set_options(client, action_on_timeout=None, timeout_us=None, timeout_admin_us=None, keep_alive_timeout_ms=None, retry_count=None, arbitration_burst=None, low_priority_weight=None, medium_priority_weight=None, high_priority_weight=None, ...
bigcode/self-oss-instruct-sc2-concepts
import json def update_json(row, fields): """Add data to the taxon_json field.""" taxon_json = json.loads(row.taxon_json) for field in fields: if row[field]: taxon_json[field] = row[field] return json.dumps(taxon_json, ensure_ascii=False)
bigcode/self-oss-instruct-sc2-concepts
def fix_ambiguous_cl(column=4): """awk command to replace non-N ambiguous REF bases with N. Some callers include these if present in the reference genome but GATK does not like them. """ return r"""awk -F$'\t' -v OFS='\t' '{if ($0 !~ /^#/) gsub(/[KMRYSWBVHDXkmryswbvhdx]/, "N", $%s) } {print}'""" % ...
bigcode/self-oss-instruct-sc2-concepts
def make_list(nb_letters): """Makes the list of words. Args: nb_letters (int): number of letters in the words of the list Returns: list: the list of words """ words_list = [] # Open the file that contains the words with the required number of letters with open(f'data/mots_{nb...
bigcode/self-oss-instruct-sc2-concepts
def get_travel_requests_of_timetables(timetables): """ Retrieve a list containing all the travel_request_documents, which are included in a list of timetable_documents. :param timetables: [timetable_documents] :return: travel_requests: [travel_request_documents] """ travel_requests = [] ...
bigcode/self-oss-instruct-sc2-concepts
def number_vowels(w): """ Returns: number of vowels in string w. Vowels are defined to be 'a','e','i','o', and 'u'. 'y' is a vowel if it is not at the start of the word. Repeated vowels are counted separately. Both upper case and lower case vowels are counted. Examples: number...
bigcode/self-oss-instruct-sc2-concepts
def div_by_nums(i, nums): """ Test if number (i) is divisible by array of numbers (nums) :param i: :param nums: :return: """ for n in nums: if i % n == 0: return True return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from pydantic import BaseModel # noqa: E0611 from enum import Enum async def clean_python_types(data: "Any") -> "Any": """Turn any types into MongoDB-friendly Python types. Use `dict()` method for Pydantic models. Use `value` property for Enums. Turn tuples and sets into lists...
bigcode/self-oss-instruct-sc2-concepts
def temporal_affine_forward(x, w, b): """ Inputs: - x: Input data of shape (N, T, D) - w: Weights of shape (D, M) - b: Biases of shape (M,) Returns a tuple of: - out: Output data of shape (N, T, M) - cache: Values needed for the backward pass """ N, T, D = x.shape M = b.shap...
bigcode/self-oss-instruct-sc2-concepts
def get_history_resource_data(session, team, date, hour, storage): """Return the history energy usage of the team for the date and hour.""" return storage.get_history_resource_data(session, team, date, hour)
bigcode/self-oss-instruct-sc2-concepts
def list2cmdline(lst): """ convert list to a cmd.exe-compatible command string """ nlst = [] for arg in lst: if not arg: nlst.append('""') else: nlst.append('"%s"' % arg) return " ".join(nlst)
bigcode/self-oss-instruct-sc2-concepts
def get_directory_contents(directory): """ return a sorted list of the contents of a directory """ contents = [] for child in directory.iterdir(): contents.append(child) return sorted(contents)
bigcode/self-oss-instruct-sc2-concepts
def is_date_time(file_type, path): """ Return True if path is an object that needs to be converted to date/time string. """ date_time_objects = {} date_time_objects["Gzip"] = ("mod_time",) date_time_objects["PE"] = ("pe.coff_hdr.time_date_stamp",) date_time_objects["Windows shortcut"] = ("he...
bigcode/self-oss-instruct-sc2-concepts
def sent_ngrams_list(words, n): """ Create a list with all the n-grams in a sentence Arguments: words: A list of strings representing a sentence n: The ngram length to consider Returns: A list of n-grams in the sentence """ return [tuple(words[i:i + n]) for i in range(len(words) - n ...
bigcode/self-oss-instruct-sc2-concepts
def index_fact(fact, index, negated=False): """ Returns a representation of 'fact' containing the step number and a leading 'not-' if the fact is negated """ name = str(fact) if negated: name = 'not-' + name return "%s-%d" % (name, index)
bigcode/self-oss-instruct-sc2-concepts
def sum67_loop(nums): """ A basic loop method. the key is to keep a flag set to know whether a 6 has been encountered """ total = 0 is6 = False for num in nums: print("adding:", num, is6) if num == 6 or is6: is6 = True else: total += num ...
bigcode/self-oss-instruct-sc2-concepts
def __predict(X_test, model, X_scaler): """ Do prediction for provided fetures Arguments: X_test: the test data [n_samples, n_features] model: the classification predictive model X_scaler: the standard scaler used to scale train features Return: predicted labels as array ...
bigcode/self-oss-instruct-sc2-concepts
def get_num_channels(image5d): """Get the number of channels in a 5D image. Args: image5d (:obj:`np.ndarray`): Numpy arry in the order, `t,z,y,x[,c]`. Returns: int: Number of channels inferred based on the presence and length of the 5th dimension. """ return 1 if image5d i...
bigcode/self-oss-instruct-sc2-concepts
def is_e164_format(phone): """Return true if string is in E.164 format with leading +, for example "+46701740605" """ return len(phone) > 2 and phone[0] == "+" and phone[1:].isdigit() and len(phone) <= 16
bigcode/self-oss-instruct-sc2-concepts
def dcf_to_swap(dcf): """ Helper function transforms sorted discount factors to swap rates. :param dcf: discount factors :return: par swap rates """ num_dcf = len(dcf) swap_rates = num_dcf * [0] for index, dcf_ in enumerate(dcf): if index == 0: swap_rates[index] = (1...
bigcode/self-oss-instruct-sc2-concepts
def search_ancestor(node, *node_types): """ Recursively looks at the parents of a node and returns the first found node that matches node_types. Returns ``None`` if no matching node is found. :param node: The ancestors of this node will be checked. :param node_types: type names that are searched fo...
bigcode/self-oss-instruct-sc2-concepts
import torch def to_torch(tensor): """Converts an array-like object (either numpy or pytorch) into a pytorch tensor.""" if tensor is None: return None elif isinstance(tensor, torch.Tensor): return tensor torch_tensor = torch.from_numpy(tensor) if torch_tensor.dtype == torch.fl...
bigcode/self-oss-instruct-sc2-concepts
def measure_lexical_diversity(tokenized_string): """ Given a tokenized string (list of tokens), return the fraction of unique tokens to total tokens. """ return len(set(tokenized_string)) / len(tokenized_string)
bigcode/self-oss-instruct-sc2-concepts
def get_primary_language(programming_language_tallies): """ Return the most common detected programming language as the primary language. """ programming_languages_by_count = { entry['count']: entry['value'] for entry in programming_language_tallies } primary_language = '' if program...
bigcode/self-oss-instruct-sc2-concepts
def wind_consistency(windspeed, winddirection, variablelimit): """ Test to compare windspeed to winddirection. :param windspeed: wind speed :param winddirection: wind direction in range 1-362 :param variablelimit: maximum wind speed consistent with variable wind direction :type windspeed: float...
bigcode/self-oss-instruct-sc2-concepts
def filter_deleted_items(items, flag): """Filter deleted items :param items: target :param flag: deleted flag name, always True means deleted :return: list does not contain deleted items """ # just return if parameter is not a list if not isinstance(items, list): return items ...
bigcode/self-oss-instruct-sc2-concepts
def number(selection_string: str, minimum: int, maximum: int, default = None) -> int: """ Asks the user for a number within the provided minimum and maximum with optional default and returns their response """ while True: if default: input_string = f"{selection_string} default={defau...
bigcode/self-oss-instruct-sc2-concepts
def get_list_nodes_from_tree(tree, parameters=None): """ Gets the list of nodes from a process tree Parameters --------------- tree Process tree parameters Parameters Returns --------------- list_nodes List of nodes of the process tree """ if paramet...
bigcode/self-oss-instruct-sc2-concepts
def getrecursionlimit(space): """Return the last value set by setrecursionlimit(). """ return space.newint(space.sys.recursionlimit)
bigcode/self-oss-instruct-sc2-concepts
def get_sort_dirs(sorts, page_reverse=False): """Extract sort directions from sorts, possibly reversed. :param sorts: A list of (key, direction) tuples. :param page_reverse: True if sort direction is reversed. :returns: The list of extracted sort directions optionally reversed. """ if page_reve...
bigcode/self-oss-instruct-sc2-concepts
def make_header(pandoc_format, title, categories): """ Generate pandoc header based on given metadata. """ lines = [ "---", "format: " + pandoc_format, "title: " + title, "...", ] if categories is not None and len(categories) > 0: lines.insert(2, "cate...
bigcode/self-oss-instruct-sc2-concepts
def null_safe(rule): """Return original expr if rule returns None.""" def null_safe_rl(expr): result = rule(expr) if result is None: return expr else: return result return null_safe_rl
bigcode/self-oss-instruct-sc2-concepts