seed
stringlengths
1
14k
source
stringclasses
2 values
def check_dictionary_values(dict1: dict, dict2: dict, *keywords) -> bool: """Helper function to quickly check if 2 dictionaries share the equal value for the same keyword(s). Used primarily for checking against the registered command data from Discord. Will not work great if values inside the dictionary ca...
bigcode/self-oss-instruct-sc2-concepts
import re def well_formatted_reps(exercises: list) -> list: """Filter out badly formatted reps from the list of exercises""" good_format = lambda exc: re.match(r'\d+-\d+', exc[1]) return list(filter(good_format, exercises))
bigcode/self-oss-instruct-sc2-concepts
def storage_max_constraint_rule(backend_model, loc_tech, timestep): """ Set maximum stored energy. Supply_plus & storage techs only. .. container:: scrolling-wrapper .. math:: \\boldsymbol{storage}(loc::tech, timestep) \\leq storage_{cap}(loc::tech) """ return bac...
bigcode/self-oss-instruct-sc2-concepts
import torch def nll(x_pred, x_true, log_p, t_pred=None, t_xz=None, hidden=None): """ Negative log likelihood """ return -torch.mean(log_p)
bigcode/self-oss-instruct-sc2-concepts
def score(word, f): """ word, a string of length > 1 of alphabetical characters (upper and lowercase) f, a function that takes in two int arguments and returns an int Returns the score of word as defined by the method: 1) Score for each letter is its location in the alphabet...
bigcode/self-oss-instruct-sc2-concepts
def pick_icon(icon): """Convert Dark Sky API icon data-point to weather-icons.css format""" icon = "wi-forecast-io-" + icon return icon
bigcode/self-oss-instruct-sc2-concepts
def stripdefaults(target, removeempty=list(), removeexact=dict()): """ Make output dicts smaller by removing default entries. Keys are removed from `target` in place Args: target (dict): dictionary to remove entries from removeempty (list): Remove keys in this list from target if the key ...
bigcode/self-oss-instruct-sc2-concepts
def prep_s3(biodata_bucket, run_bucket, output_folder): """Prepare configuration for shipping to S3. """ return {"type": "S3", "buckets": {"run": run_bucket, "biodata": biodata_bucket}, "folders": {"output": output_folder}}
bigcode/self-oss-instruct-sc2-concepts
def apparent_extract_to_real_extract(original_extract, apparent_extract): """ Apparent Extract to Real Extract in degrees Plato :param float original_extract: Original degrees Plato :param float apparent_extract: Apparent degrees Plato of finished beer :return: Real degrees Plato of finished beer ...
bigcode/self-oss-instruct-sc2-concepts
def envs_to_exports(envs): """ :return: line with exports env variables: export A=B; export C=D; """ exports = ["export %s=%s" % (key, envs[key]) for key in envs] return "; ".join(exports) + ";"
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _index_of_first_non_option(tokens: List[str]): """ Find the index of the first token that doesn't start with `-` Returns len(tokens) if none is found. """ return next( (index for index, token in enumerate(tokens) if token[0] != "-"), len(tokens), )
bigcode/self-oss-instruct-sc2-concepts
def to_list(str_rep_list: str) -> list: """ Convenience function to change a string representation of a Python list into an actual list object. :param str str_rep_list: String that represents a Python list. e.g. "['0.5', '2.0']" :return: The parsed representative string. :rtype: list """ in...
bigcode/self-oss-instruct-sc2-concepts
import stringprep def b1_mapping(char): """Do RFC 3454 B.1 table mapping. :Parameters: - `char`: Unicode character to map. :returns: u"" if there is `char` code in the table, `None` otherwise. """ if stringprep.in_table_b1(char): return u"" else: return None
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def operate(func, *dicts): """Apply func to values of *dicts and return the result.""" result = [value for d in dicts for value in d.values()] result = reduce(func, result, 1) return result
bigcode/self-oss-instruct-sc2-concepts
def get_altitude_from_level(level_number): """Get geopotential altitude from level number. Args: level_number (int): Number of level. Returns: float: Altitude in meters above mean sea level. """ # Altitudes (heights above mean sea level) corresponding to barometric altitude levels...
bigcode/self-oss-instruct-sc2-concepts
def parse_subcommand(command_text): """ Parse the subcommand from the given COMMAND_TEXT, which is everything that follows `/iam`. The subcommand is the option passed to the command, e.g. 'wfh' in the case of `/pickem wfh tomorrow`. """ return command_text.strip().split()[0].lower()
bigcode/self-oss-instruct-sc2-concepts
def _account_for_bubble_fields(sg_entity_type, field_name): """Detect bubble fields and return the proper entity type and field name. :param str sg_entity_type: The intput entity type name. If the field name is a bubbled field notation, this value will be replaced by the parsed entity type in t...
bigcode/self-oss-instruct-sc2-concepts
def _get_index(indices, index_name): """ Get Index from all the indices. :param indices: DED indices list :param index_name: Name of the index :return: DED Index """ for index in indices: if str(index) == index_name: return index
bigcode/self-oss-instruct-sc2-concepts
def stan_init(m): """Retrieve parameters from a trained model. Retrieve parameters from a trained model in the format used to initialize a new Stan model. Parameters ---------- m: A trained model of the Prophet class. Returns ------- A Dictionary containing retrieved parameters of...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def _human_readable_delta(start, end): """ Return a string of human readable time delta. """ start_date = datetime.fromtimestamp(start) end_date = datetime.fromtimestamp(end) delta = end_date - start_date result = [] if delta.days > 0: result.appe...
bigcode/self-oss-instruct-sc2-concepts
def get_subclasses(c): """Get all subclasses of a class. Args: c (type): Class to get subclasses of. Returns: list[type]: List of subclasses of `c`. """ scs = c.__subclasses__() return scs + [x for sc in scs for x in get_subclasses(sc)]
bigcode/self-oss-instruct-sc2-concepts
def data_from(file_: "str") -> list: """Returns data from given file.""" data = [] with open(file_, "r") as f: for line in f.readlines(): data.append(line.replace("-", " ").replace(":", "").split()) return data
bigcode/self-oss-instruct-sc2-concepts
def process_request_items(items): """takes a list of 2-tuples returns dict of list items uses first value of tuple as key, and uses second value of tuple as value """ request_dict = {} for item in items: request_dict[item[0]] = item[1] return request_dict
bigcode/self-oss-instruct-sc2-concepts
def bbox_crop(x, bbox): """ Crop image by slicing using bounding box indices (2D/3D) Args: x: (numpy.ndarray, shape (N, ch, *dims)) bbox: (list of tuples) [*(bbox_min_index, bbox_max_index)] Returns: x cropped using bounding box """ # slice all of batch and channel ...
bigcode/self-oss-instruct-sc2-concepts
import requests import json def request_dataset_metadata_from_data_portal(data_portal_api_base: str, explorer_url: str): """ Check the data portal metadata api for datasets stored under the given url_path If present return dataset metadata object else return None """ headers = {"Content-Type": "ap...
bigcode/self-oss-instruct-sc2-concepts
def add_currency_filter_to_query(query, currency): """ Adds the currency filter to the query :param query: the query dictionary :type query: dict :param currency: currency type :type currency: str :return: the query dictionary :rtype: dict """ if "filters" not in query["query"]:...
bigcode/self-oss-instruct-sc2-concepts
def swe_headerfile_name(dt, infile_type): """Return SWE headerfile name for a given datetime""" dtstr = dt.strftime('%Y%m%d') if infile_type.upper() == 'UNMASKED': return 'zz_ssmv11034tS__T0001TTNATS{}05HP001.txt.gz'.format(dtstr) elif infile_type.upper() == 'MASKED': return 'us_ssmv11...
bigcode/self-oss-instruct-sc2-concepts
import torch def to_concatenated_real(input, flatten=None, dim=-1): """Map real tensor input `... x [2 * D]` to a pair (re, im) with dim `... x D`.""" assert flatten is None return torch.cat([input.real, input.imag], dim=dim)
bigcode/self-oss-instruct-sc2-concepts
def get_books_by_publisher(data, ascending=True): """Returns the books by each publisher as a pandas series Args: data: The pandas dataframe to get the from ascending: The sorting direction for the returned data. Defaults to True. Returns: The sorted data as a pandas series...
bigcode/self-oss-instruct-sc2-concepts
import socket def from_address(address): """ Reverse resolve an address to a hostname. Given a string containing an IPv4 or IPv6 address, this functions returns a hostname associated with the address, using an LRU cache to speed up repeat queries. If the address does not reverse, the function ret...
bigcode/self-oss-instruct-sc2-concepts
def update_route_events(veh, timeind): """Check if the next event from a vehicle's route_events should be applied, and apply it if so. route_events are a list of events which handles any lane changing behavior related to a vehicle's route, i.e. route events ensure that the vehicle follows its route. Ea...
bigcode/self-oss-instruct-sc2-concepts
def modified_dict(input_dict, modification_dict): """Returns a dict, with some modifications applied to it. Args: input_dict: a dictionary (which will be copied, not modified in place) modification_dict: a set of key/value pairs to overwrite in the dict """ output_dict = input_dict.copy() output_dict...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def parse_bool(value: str, default: Optional[bool] = None) -> Optional[bool]: """ Parse bool from some quintly tables being a string with the value "1" or "0" Args: value (str): The value from the quintly dataframe default (Optional[bool]): Default value in cas...
bigcode/self-oss-instruct-sc2-concepts
def notes(*num, sit=False): # Function to return a dictionary and check all the conditions """ => Program that checks the quantify of school grades, highest, lowest, the class mean and the student's situation :param num: variable that receive the amount of notes :param sit: (optional) if wish know the...
bigcode/self-oss-instruct-sc2-concepts
def convert_units(typ,constant,f,t): """Converts units type should be one of them 'metric','time' f and t should be one of them: 'pico','nano','micro','mili','centi','deci','base','deca','hecta','kilo','mega','giga','tera' Attributes ---------- constant: int constant numb...
bigcode/self-oss-instruct-sc2-concepts
import textwrap def wrap(text, width, *args, **kwargs): """ Like :func:`textwrap.wrap` but preserves existing newlines which :func:`textwrap.wrap` does not otherwise handle well. See Also -------- :func:`textwrap.wrap` """ return sum([textwrap.wrap(line, width, *args, **kwargs) ...
bigcode/self-oss-instruct-sc2-concepts
def example_image_shape(example): """Gets the image shape field from example as a list of int64.""" if len(example.features.feature['image/shape'].int64_list.value) != 3: raise ValueError('Invalid image/shape: we expect to find an image/shape ' 'field with length 3.') return example.featu...
bigcode/self-oss-instruct-sc2-concepts
def _eval_expr(expr, vals, x): """ This function tries calling expr.eval. Calls expr.cpp_object().eval if the first fails. This is for FEniCS 2018.1.0 compatibility. """ try: expr.eval(vals, x) except AttributeError: expr.cpp_object().eval(vals, x) return None
bigcode/self-oss-instruct-sc2-concepts
def format_zet(state, speler, zet): """Opmaak van de status, speler en de zet.""" return "State: {0:<20} {1:<20} Move: {2}".format(str(state), str(speler), str(zet))
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def voto(ano_nascimento): """ Recebe o ano de nascimento introduzido e calcula a idade do usuario, utilizando a data atual. :param ano_nascimento: recebe o ano de nascimento :return: idade e status do voto """ idade = datetime.today().year - ano_nascimento ...
bigcode/self-oss-instruct-sc2-concepts
def discard_search_results(searchId: str) -> dict: """Discards search results from the session with the given id. `getSearchResults` should no longer be called for that search. Parameters ---------- searchId: str Unique search session identifier. **Experimental** """ return...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def parse_sgm_file(sgm_data): """ Returns a dictionary with titles + articles of an SGM file :param sgm_data: Data read from an SGM file :return: A dictionary mapping titles to article contents """ soup = BeautifulSoup(sgm_data, features="html5lib") texts = ...
bigcode/self-oss-instruct-sc2-concepts
def range_overlap(ranges): """Return common overlap among a set of [left, right] ranges.""" lefts = [] rights = [] if ranges: for (left, right) in ranges: lefts.append(left) rights.append(right) max_left = max(lefts) min_right = min(rights) if min...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Optional def get_homogeneous_type(type_dict) -> Tuple[Optional[str], bool]: """ Returns ------- Optional[str] Homogeneous-type, if any. Ex) 'dict', 'list', 'str', 'int', 'float', 'bool', 'None', or None bool Whether optionally typ...
bigcode/self-oss-instruct-sc2-concepts
def _quote_wrap(value): """Wrap a value in quotes.""" return '"{}"'.format(value)
bigcode/self-oss-instruct-sc2-concepts
def listBranchUsage(err=''): """ Prints the usage stmt for listBranch """ m = '' if len(err): m += '%s\n\n' %err m += 'List status information for a single branch.\n' m += '\n' m += 'Usage:\n' m += ' lsbr -s <stream> -b <branch_Name>\n' return m
bigcode/self-oss-instruct-sc2-concepts
import gzip def get_handle(filen, rw): """ Returns file handle using gzip if file ends in .gz """ if filen.split('.')[-1] == 'gz': return gzip.open(filen, rw) else: return open(filen, rw)
bigcode/self-oss-instruct-sc2-concepts
def has(i): """Returns the form of the verb 'avoir' based on the number i.""" # Note: this function is used only for the third person if i == 1: return 'a' else: return 'ont'
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def get_bool(value: str) -> Union[bool, None]: """When given a string, returns a boolean value based on the string Parameters ---------- value : str A string representing a user response Returns ------- Union[bool, None] whether the string is true...
bigcode/self-oss-instruct-sc2-concepts
def magtoflux(marr, fzero): """Convert from magnitude to flux. marr--input array in mags fzero--zero point for the conversion """ return fzero * 10 ** (-0.4 * marr)
bigcode/self-oss-instruct-sc2-concepts
def partition(arr, left, right): """ *--------*----------*-----------* left mid frontier right left is the pivot, it has been moved to the beginning of the array. frontier marks all the elements we've alreay looked at. mid is the new index of the pivot, everything to the left i...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def _time_of_day(dt: datetime) -> float: """Convert a given datetime `dt` to a point on the unit circle, where the 'period' corresponds to one day. :param datetime.datetime dt: input datetime UTC :returns: `float` between 0 and 1 corresponding to the phase """ midnig...
bigcode/self-oss-instruct-sc2-concepts
import torch def objtrack_collect(batch): """Collect the objtrack data for one batch. """ targets = [] imgs = [] frame_id = [] indexs = [] for sample in batch: imgs.append(sample[0]) targets.append(sample[1]) frame_id.append(sample[2]) indexs.append(sample[3...
bigcode/self-oss-instruct-sc2-concepts
def frequency(total: float, percentage: float, value: float, invert: bool = False) -> float: """Return frequency of a given value . Freq = v*t/p v-> value t-> total p-> percentage Args: total (float): total value percentage (float): percentage value between 0 and 1 val...
bigcode/self-oss-instruct-sc2-concepts
def get_query_string(params) -> str: """ Gets the query string of a URL parameter dictionary.abs :param params: URL params. :return: Query string. """ if not params: return '' return '?' + '&'.join([str(k) + '=' + str(v) for k, v in params.items()])
bigcode/self-oss-instruct-sc2-concepts
def flatt_on_level(it, d=-1, level=None): """ >>> list(flatt_on_level([[[['a']]]], level=3)) [['a']] """ if d == -1: return list(flatt_on_level(it, d=d + 1, level=level)) if d == level: return (i for i in [it]) res = [] for x in it: res.extend( flatt_on_level(x...
bigcode/self-oss-instruct-sc2-concepts
import re def format_string(prop_string): """ Formats a property string to remove spaces and go from CamelCase to pep8 from: http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-camel-case """ if prop_string is None: return '' st_r = re.sub...
bigcode/self-oss-instruct-sc2-concepts
def average_index(n1, n2, v1=None, v2=None, vr=None): """Compute volume weighted average refractive index Args: n1, n2 (float/ndarray): refractive index of material 1 and 2 v1, v2 (float): volume of materials 1 and 2 vr (float): volume ratio of v1/(v1+v2) used instead of v1 and v2 ""...
bigcode/self-oss-instruct-sc2-concepts
def verify_name(prior_name, inferred_name): """Verfies that the given/prior name matches with the inferred name. """ if prior_name is None: prior_name = inferred_name else: assert prior_name == inferred_name, f"""given name {prior_name} does not mach with ...
bigcode/self-oss-instruct-sc2-concepts
import math def dist(a0, a1, b0, b1): """Returns the Eucleadean distance between two points in 2D.""" da = a1-a0 db = b1-b0 return math.sqrt(da*da + db*db)
bigcode/self-oss-instruct-sc2-concepts
def _create_interface(phase, graph, references): """Creates an interface instance using a dynamic type with graph and references as attributes. """ interface = {'graph': graph} interface.update(references) return type(phase + 'Interface', (object,), interface)
bigcode/self-oss-instruct-sc2-concepts
def emtpy_cols(cols, rows, plas, model): """ Helper function for shrink_dict. Iterates over the given model and removes all numbers of the coordinates from the items in the model. this way there will be remaining lists of empty cols, rows and plas. Returns a list of the 3 lists. """ for (x_c...
bigcode/self-oss-instruct-sc2-concepts
import math def rbf_kernel(a, b, sigma=1): """An implementation of the radial basis function kernel. Args: a: A vector b: A vector sigma: The radius of the kernel """ distance = (a - b).dot(a - b) scaled_distance = -distance / (2 * (sigma) ** 2) return math.exp(scaled_...
bigcode/self-oss-instruct-sc2-concepts
def user_unicode(self): """Use email address for string representation of user.""" return self.email
bigcode/self-oss-instruct-sc2-concepts
import string def term_frequency(term: str, document: str) -> int: """ Return the number of times a term occurs within a given document. @params: term, the term to search a document for, and document, the document to search within @returns: an integer representing the number of times a...
bigcode/self-oss-instruct-sc2-concepts
import pickle def data_pickle_load(city, year, month): """ Load data from a Data class object pickle. See Data.pickle_dump Parameters ---------- city : str The identification of the city. For a list of supported cities, see the documentation for the Data class. year : int ...
bigcode/self-oss-instruct-sc2-concepts
def clean_caesar(text): """Convert text to a form compatible with the preconditions imposed by Caesar cipher""" return text.upper()
bigcode/self-oss-instruct-sc2-concepts
def make_wheel(run_setup_file): """ Make a wheel distribution from a given package dir. """ def _make_wheel(package_dir, dist_dir, *args): return run_setup_file( package_dir, "bdist_wheel", "--dist-dir", str(dist_dir), *args ) return _make_wheel
bigcode/self-oss-instruct-sc2-concepts
def kin2dyn(kin, density): """ Convert from kinematic to dynamic viscosity. Parameters ---------- kin: ndarray, scalar The kinematic viscosity of the lubricant. density: ndarray, scalar The density of the lubricant. Returns ------- dyn: ndarray, scalar The ...
bigcode/self-oss-instruct-sc2-concepts
def convert_to_bool(data): """ convert_to_bool converts input to bool type in python. The following values are converted to True: 1. 'true' 2. 'yes' 3. '1' 4. 'y' 5. 1 The following values are converted to False: 1. 'false' 2. 'no' 3. '0' 4. 'n' 5. 0 :par...
bigcode/self-oss-instruct-sc2-concepts
def is_int(obj, int_like=False): """ Checks for int types including the native Python type and NumPy-like objects Args: obj: Object to check for integer type int_like (boolean): Check for float types with integer value Returns: Boolean indicating whether the supplied value is o...
bigcode/self-oss-instruct-sc2-concepts
def format_filename(string): """ Converts a string to an acceptable filename e.g. "Go! series - F1" into "Go_series_-_F1" Parameters: string (str): raw filename Returns: formatted_filename (str): formatted filename Raises: """ # NOTE: Periods (.) and dashes (-) are a...
bigcode/self-oss-instruct-sc2-concepts
def get_ion_state(line): """ Get the ionization state of a `VoigtFit.Line` instance or of `line_tag` string: ex: Line<'FeII_2374'> --> II ex: Line<'CIa_1656'> --> I ex: 'CIV_1550' --> IV """ if isinstance(line, str): ion = line.split('_')[0] else: ion = line.ion ...
bigcode/self-oss-instruct-sc2-concepts
def extract_content(last_metadata_line, raw_content): """Extract the content without the metadata.""" lines = raw_content.split("\n") content = "\n".join(lines[last_metadata_line + 1 :]) return content
bigcode/self-oss-instruct-sc2-concepts
import binascii def get_tflite_data(tflite_path: str) -> list: """ Reads a binary file and returns a C style array as a list of strings. Argument: tflite_path: path to the tflite model. Returns: list of strings """ with open(tflite_path, 'rb') as tflite_model: ...
bigcode/self-oss-instruct-sc2-concepts
import csv def read_sleepasandroid_file(saa_filename): """ read in a SleepAsAndroid backup file and return it as a parsed list """ with open(saa_filename) as file: file_as_list = list(csv.reader(file, delimiter=',')) return file_as_list
bigcode/self-oss-instruct-sc2-concepts
def snake_to_pascal_case(s: str) -> str: """Convert a string from snake_case to PascalCase""" if not s: return s return "".join( map( lambda segment: (segment[0].upper() + segment[1:]) if segment else segment, s.split("_"), ), )
bigcode/self-oss-instruct-sc2-concepts
def who_create(user_id, ticket = None): """ Create a TTBD user descriptor from a user id name and a ticket :params str user_id: user's name / ID :params str ticket: (optional) ticket for the reservation :returns: (str) user id descriptor """ if ticket != None and ticket != "": retu...
bigcode/self-oss-instruct-sc2-concepts
def get_loc_offset(box_gt, box_anchor): """Computes the offset of a groundtruth box and an anchor box. Args: box_gt (array): groundtruth box. box_anchor (array): anchor box. Returns: float: offset between x1 coordinate of the two boxes. float: offset between y1 coordinate o...
bigcode/self-oss-instruct-sc2-concepts
def deep_getattr(obj, attr_string, default=None): """ Returns the attribute of `obj` at the dotted path given by `attr_string` If no such attribute is reachable, returns `default` >>> deep_getattr(cass, "cluster") <cassandra.cluster.Cluster object at 0xa20c350 >>> deep_getattr(cass, "cluster.m...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def funkcia2(cisla: List[int]) -> List[int]: """Vyfiltruj iba čísla delitelné 3 alebo 5. >>> funkcia2([7, 12, 35, 15, 45, 16, 18]) [12, 35, 15, 45, 18] """ # 1. riešenie vysledok = [] for i in range(0,len(cisla)): if(cisla[i] % 3 == 0) or (cisla[i] % 5 == 0)...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_activity_streams_json(activity_id, access_token, types=None): """Get streams (time series) for a particular activity. https://developers.strava.com/docs/reference/#api-Streams-getActivityStreams `stravalib` implementation for reference: `streams = client.get_activity_streams(id)` ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def __has_term_from_list__(text: str, string_list: List[str]) -> bool: """ Check if a string contains an item in a list """ for item in string_list: if item in text: return True return False
bigcode/self-oss-instruct-sc2-concepts
import re def extract_udf_name(udf_path): """ Parse out the name of the UDF from the SQL DDL :param udf_path: Path to the UDF DDL .sql file :return: Name of the UDF """ with open(udf_path) as udf_file: udf_sql = udf_file.read() udf_sql = udf_sql.replace('\n', ' ') pattern = re...
bigcode/self-oss-instruct-sc2-concepts
import json def lerArquivoJSON(caminho_arquivo): """ Retorna conteúdo de um arquivo JSON de comandos SQL, delegando tratamento para bloco de função reservado :param caminho_arquivo: :return: data (JSON) """ with open(caminho_arquivo, "r") as read_file: data = json.load(read_file) ...
bigcode/self-oss-instruct-sc2-concepts
import calendar def days_in_year(year: int) -> int: """Returns the number of days in the year Args: year (int): The year. Returns: int: The number of days in the year. """ return 366 if calendar.isleap(year) else 365
bigcode/self-oss-instruct-sc2-concepts
def extract_output(out): """ Extracts output for one filing unit in out and returns extracted output as a dictionary. Parameters ---------- out: pandas DataFrame row containing tc --dump output for one filing unit Returns ------- ovar: dictionary of output variables indexed from 1 ...
bigcode/self-oss-instruct-sc2-concepts
def _get_subclasses(cls): """Get subclasses of passed in class and return a dictionary of them""" return {subclass.__name__: subclass for subclass in cls.__subclasses__()}
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Dict def load_k8s_secrets() -> Tuple[Dict[str, str], str]: """ Loads secrets needed to access K8s resources. Returns: headers (dict): Headers with K8s access token verify (str): Path to certificate """ with open("/var/run/secrets/kuberne...
bigcode/self-oss-instruct-sc2-concepts
import random def char_mlm_mask_random_words(tokens, max_predictions_per_seq=38, masked_lm_prob=0.20): """ Masks tokens using a algorithm designed for character level masking. The idea is to ensure groups and dense clusters of characters as masked so that the task won't be too easy. :param tokens: tokeni...
bigcode/self-oss-instruct-sc2-concepts
def delimit(delimiters, content): """ Surround `content` with the first and last characters of `delimiters`. >>> delimit('[]', "foo") [foo] >>> delimit('""', "foo") '"foo"' """ if len(delimiters) != 2: raise ValueError( "`delimiters` must be of length 2. Got %r" % de...
bigcode/self-oss-instruct-sc2-concepts
import time def convert_timestamp(s): """ convert the N1MM+ timestamp into a python time object. """ return time.strptime(s, '%Y-%m-%d %H:%M:%S')
bigcode/self-oss-instruct-sc2-concepts
def annotation_filter(annotations, condition): """ Filter annotations. `annotations`: the annotations to filter `condition`: the filter callback return: the filtered annotations """ filtered = dict() for (key, value) in annotations.items(): if condition(key, value): f...
bigcode/self-oss-instruct-sc2-concepts
def adjacency_to_edges(nodes, adjacency, node_source): """ Construct edges for nodes based on adjacency. Edges are created for every node in `nodes` based on the neighbors of the node in adjacency if the neighbor node is also in `node_source`. The source of adjacency information would normally ...
bigcode/self-oss-instruct-sc2-concepts
import requests def follow_shortlinks(shortlinks): """Follow redirects in list of shortlinks, return dict of resulting URLs""" links_followed = {} for shortlink in shortlinks: url = shortlink request_result = requests.get(url) redirect_history = request_result.history # his...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path from typing import Tuple import shlex def get_emittances_from_madx_output(madx_output_file: Union[str, Path], to_meters: bool = False) -> Tuple[float, float, float]: """ Parse MAD-X output file and return the X, Y and Z emittances from the output of the last c...
bigcode/self-oss-instruct-sc2-concepts
def parse_by_integration(sensors): """Returns a list of devices that can be integrated.""" can_integrate = [] for sensor in sensors.values(): if sensor.get('integrate'): can_integrate.append(sensor) return can_integrate
bigcode/self-oss-instruct-sc2-concepts
import configparser def get_config(config_path): """ Get config data :param config_path: filepath of config ini file :return: instance of ini config file """ config = configparser.ConfigParser() config.read(config_path) return config
bigcode/self-oss-instruct-sc2-concepts
def as_int(attribute): """ Treat attribute as int if it looks like one. """ try: return int(attribute) except ValueError: return attribute
bigcode/self-oss-instruct-sc2-concepts
def cubic_rbf(r, kappa): """ Computes the Cubic Radial Basis Function between two points with distance `r`. Parameters ---------- r : float Distance between point `x1` and `x2`. kappa : float Shape parameter. Returns ------- phi : float Radial basis function...
bigcode/self-oss-instruct-sc2-concepts