seed
stringlengths
1
14k
source
stringclasses
2 values
def isintlike(value): """ Checks if an object can be converted to an integer. @param value: {object} @return {bool} """ try: int(value) return True except (TypeError, ValueError): return False
bigcode/self-oss-instruct-sc2-concepts
def map_outputs(building_name, outputs, mapping): """ Maps outputs from EnergyPlus to OPC tags Inputs: building_name- The name of the building outputs- List of values from EnergyPlus Outputs: [(OPC_tag, value)]- List of tuples of tags and values """ output_tags = mapping[building_name]["Outputs"] ret = [] ...
bigcode/self-oss-instruct-sc2-concepts
def slack_escape(text: str) -> str: """ Escape special control characters in text formatted for Slack's markup. This applies escaping rules as documented on https://api.slack.com/reference/surfaces/formatting#escaping """ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;...
bigcode/self-oss-instruct-sc2-concepts
def strip_none(none_list): """ Given a list that might contain None items, this returns a list with no None items. :params list none_list: A list that may contain None items. :returns: A list stripped of None items. """ if none_list is None: return [] results = [x for x in none...
bigcode/self-oss-instruct-sc2-concepts
def coding_problem_49(arr): """ Given an array of numbers, find the maximum sum of any contiguous subarray of the array. For example, given the array [34, -50, 42, 14, -5, 86], the maximum sum would be 137, since we would take elements 42, 14, -5, and 86. Given the array [-5, -1, -8, -9], the maximum su...
bigcode/self-oss-instruct-sc2-concepts
import typing import re def get_package_namespace(package: str, namespaces: typing.Dict[typing.Union[str, None], str]) -> typing.Tuple[str, str]: """ Get the prefix and URI for the namespace of an SBML package Args: package (:obj:`str`): SBML package id (e.g., ``fbc``, ``qual``) namespaces (:...
bigcode/self-oss-instruct-sc2-concepts
import math def atan_norm(value): """The arctan function grows more and more slowly as its input increases, so it is applied in hope of reducing the influence of possible outliers. Args: value (int): Byte frequency of a byte integer between 0-255. Returns: float: arctan nor...
bigcode/self-oss-instruct-sc2-concepts
def _edgeness(hxx, hyy, hxy): """Compute edgeness (eq. 18 of Otero et. al. IPOL paper)""" trace = hxx + hyy determinant = hxx * hyy - hxy * hxy return (trace * trace) / determinant
bigcode/self-oss-instruct-sc2-concepts
def parse_wgac_alignment(wgac_alignment): """ Parses a WGAC alignment from a list into a tuple of tuples for each sequence in the alignment. """ wgac_alignment[1:3] = map(int, wgac_alignment[1:3]) wgac_alignment[5:7] = map(int, wgac_alignment[5:7]) return ( tuple(wgac_alignment[:4]),...
bigcode/self-oss-instruct-sc2-concepts
def format_taxon(taxonomy): """ Format the taxonomy string. """ genus = taxonomy.split(';')[-2] organism = taxonomy.split(';')[-1] return [genus, organism]
bigcode/self-oss-instruct-sc2-concepts
import torch import math def matern_spectrum( w: torch.Tensor, amplitudes: torch.Tensor, lengthscales: torch.Tensor, nu: float = 1.5, ) -> torch.Tensor: """Evaluate the Matern 5/2 power spectrum element-wise at ``w``. Args: w: The (dimensionless) frequencies at which to evaluate the p...
bigcode/self-oss-instruct-sc2-concepts
def is_in_list(item, list_, kind): """Check whether an item is in a list; kind is just a string.""" if item not in list_: raise KeyError(f"Specify {kind} from {list_}: got {item}") return True
bigcode/self-oss-instruct-sc2-concepts
def none_bool(x): """Implementation of `none_bool`.""" return False
bigcode/self-oss-instruct-sc2-concepts
def validate_management_key_id_against_chain_id(key_id, chain_id): """ Checks if the chain in the key_id matches the value supplied in chain_id. Parameters ---------- key_id: bytes or str The partial or full key identifier chain_id: str The chain ID Raises ------ Un...
bigcode/self-oss-instruct-sc2-concepts
def get_lomb_amplitude(lomb_model, i, j): """ Get the amplitude of the jth harmonic of the ith frequency from a fitted Lomb-Scargle model. """ return lomb_model['freq_fits'][i-1]['amplitude'][j-1]
bigcode/self-oss-instruct-sc2-concepts
def _can_create(model): """Returns True if the given model has implemented the autocomplete_create method to allow new instances to be creates from a single string value. """ return callable(getattr( model, 'autocomplete_create', None, ))
bigcode/self-oss-instruct-sc2-concepts
def selection_sort(t_input): """ Selection Sort Algorithm Simple, stable algorithm with in-place sorting http://en.wikipedia.org/wiki/Selection_sort Best case performance: O(n^2) Worst case performance: O(n^2) Worst Case Auxiliary Space Complexity: O(n) :param t_input: [list] of numbers ...
bigcode/self-oss-instruct-sc2-concepts
def isQualified(name): """ Check if a property name is qualified """ return name.find(':') != -1
bigcode/self-oss-instruct-sc2-concepts
def patch(program: list[int], noun: int, verb: int) -> list[int]: """Restore the gravity assist program :param program: Intcode program :param noun: updated noun value :param verb: updated verb value :return: patched Intcode program """ program[1] = noun program[2] = verb return pro...
bigcode/self-oss-instruct-sc2-concepts
def build_json_response(status, value): """ Generate json format from input params :param status: string :param value: string :return: json array """ return { 'status': status, 'message': value }
bigcode/self-oss-instruct-sc2-concepts
import re def parse_chains(chains): """Parses a given chains string returned from the MySQL DB """ ## Turns "A:100:1:aa" -> "A", "100", "1", "aa" ## I.e.: chain_id = A, num_residues = 100, ## selected = 1/True, type = aa/amino acids ## NOTE: ## - aa = amino acid ## - na = nuc...
bigcode/self-oss-instruct-sc2-concepts
def _StoryToGtestFilter(story_name): """Returns a gtest_filter to run only tests generating data for |story_name|. WebRTC perf tests story names and gtest names are different and use different formats (e.g. snake case vs camel case). This function uses some heuristics to create a gtest filter that will allow P...
bigcode/self-oss-instruct-sc2-concepts
def _transform_to_rc_coords(start, end, read_length): """Transforms the given start and end coordinates into the RC equivalents using the given read_length.""" return read_length - end - 1, read_length - start - 1
bigcode/self-oss-instruct-sc2-concepts
def segment(*segments): """Select a (list of) segment(s).""" vsegment = [t for t in segments] return {"segment": vsegment}
bigcode/self-oss-instruct-sc2-concepts
def _var_names(var_names): """Handle var_names input across arviz. Parameters ---------- var_names: str, list, or None Returns ------- var_name: list or None """ if var_names is None: return None elif isinstance(var_names, str): return [var_names] else: ...
bigcode/self-oss-instruct-sc2-concepts
def get_partial_failure_messages(client, response): """Get a list of all partial failure error objects for a given response. Shows how to retrieve partial_failure errors from a response message (in the case of this example the message will be of type MutateAdGroupsResponse) and how to unpack those erro...
bigcode/self-oss-instruct-sc2-concepts
def fast_zeta_transform(counts, size): """ 高速ゼータ変換 ret[s]: sum of counts[t] (t ⊆ s) https://qiita.com/Euglenese/items/260f9ddf513f772d7e42#本題 O(2^N * N); len(counts) == 2^N :param list of int counts: :param int size: """ assert (1 << size) == len(counts) dp = list(counts) for...
bigcode/self-oss-instruct-sc2-concepts
def _limit(query, hints): """Applies a limit to a query. :param query: query to apply filters to :param hints: contains the list of filters and limit details. :returns: updated query """ # NOTE(henry-nash): If we were to implement pagination, then we # we would expand this method to suppo...
bigcode/self-oss-instruct-sc2-concepts
def get_power( df ): """ Creates a Pandas DataFrame containing the power of the JV curves. :param df: DataFrame containing the JV curves. Values are currents, index is voltage. :returns: A Pandas DataFrame containg the power at each voltage index value. """ pwr = df.mul( df.index, axis ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def get_operating_json(json: Dict) -> Dict: """ Get operating in rawsec json. Parameters ---------- json: Dict rawsec json. Returns ------- Dict operating dict. """ return json["operating_systems"] if "operating_systems" in json else {}
bigcode/self-oss-instruct-sc2-concepts
def init_record(msg): """Initialize a TaskRecord based on a request.""" header = msg['header'] return { 'msg_id' : header['msg_id'], 'header' : header, 'content': msg['content'], 'metadata': msg['metadata'], 'buffers': msg['buffers'], 'submitted': header['date...
bigcode/self-oss-instruct-sc2-concepts
import re def template_token_subst(buf, key, val): """ Given a string (buf), a key (e.g. '@@MASTER_IP@@') and val, replace all occurrences of key in buf with val. Return the new string. """ targetre = re.compile(re.escape(key)) return re.sub(targetre, str(val), buf)
bigcode/self-oss-instruct-sc2-concepts
def expand(dirs): """ Expands four directions per CSS convention. `dirs` may be a four-element iterable of (top, right, bottom, left), or a two-element iterable of (top-bottom, left-right), or a single-element iterable or a plan value for all four directions. @return A `tuple` of top, ri...
bigcode/self-oss-instruct-sc2-concepts
def isint(x): """Test whether an object is an instance of int.""" return isinstance(x, int)
bigcode/self-oss-instruct-sc2-concepts
import glob def get_globfiles(fileglob, minfiles=1, maxfiles=1): """ Get file(s) matching ``fileglob``. If the number of matching files is less than minfiles or more than maxfiles then an exception is raised. :param fileglob: Input file glob :param minfiles: Minimum matching files (None => n...
bigcode/self-oss-instruct-sc2-concepts
def is_at_least_one_not_none(*args): """ >>> is_at_least_one_not_none(1, 2, 3) True >>> is_at_least_one_not_none(None, 2, 3) True >>> is_at_least_one_not_none(1, None, 3) True >>> is_at_least_one_not_none(1, 2, None) True >>> is_at_least_one_not_none(1, None, None) True >...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import Mapping def is_mapping(obj: Any) -> bool: """Just a shorthand for instancecheck on :py:class:`typing.Mapping`. """ return isinstance(obj, Mapping)
bigcode/self-oss-instruct-sc2-concepts
def _highest_error_only(errors): """Removes any duplicate concentrations that have lower errors. This script take a list of errors and concentrations and returns only the highest error for each concentration. Parameters ---------- errors : list of lists of floats A list containing [err...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import Iterable def is_atom(entity: Any) -> bool: """Everything that is NOT an iterable(except strings) are considered atoms. >>> is_atom("plain string") True >>> is_atom(1) True >>> is_atom([1, 2]) False Added in version: 0.1.0 """ ...
bigcode/self-oss-instruct-sc2-concepts
def find_name(slaves, name): """Function: find_name Description: Locates and returns a slave's instance from an array of slave instances. Arguments: (input) slaves -> List of slave instances. (input) name -> Name of server being searched for. (output) Slave instance or N...
bigcode/self-oss-instruct-sc2-concepts
def format(keyword: str, keyword_style: str) -> str: """Returns formatted keyword Args: keyword: target keyword keyword_style: formatting style Returns: formatted keyword """ expected: str = keyword if keyword_style == 'lower': expected = keyword.lower() if...
bigcode/self-oss-instruct-sc2-concepts
import socket def get_hostname() -> str: """Returns the fully-qualified domain name of the server this code is running on. """ return socket.getfqdn()
bigcode/self-oss-instruct-sc2-concepts
import requests import json def get_ipaddr(url='http://httpbin.org/ip', proxy=None): """ gets the external IP address """ if proxy: proxy = 'http://{0}'.format(proxy) proxies = {'http': proxy, 'https': proxy} response = requests.get(url, proxies=proxies) else: response = r...
bigcode/self-oss-instruct-sc2-concepts
def ensure_divisible_by(feats, N): """Ensure that the number of frames is divisible by N. Args: feats (np.ndarray): Input features. N (int): Target number of frames. Returns: np.ndarray: Input features with number of frames divisible by N. """ if N == 1: return feat...
bigcode/self-oss-instruct-sc2-concepts
import json def load_json(path: str) -> dict: """Get json schema to format from file. Args: path(str): path to json. Returns: (dict): db. """ with open(path, "r", encoding="utf-8") as file: return json.load(file)
bigcode/self-oss-instruct-sc2-concepts
import torch def get_column(data: torch.Tensor, i): """get a column from a tensor. Args: data (torch.Tensor): a matrix i (int): the index of column Return: column (torch.Tensor): a vector with a shape (:, 1). """ d = data.size(dim=-1) x = data.view(-1, d) retur...
bigcode/self-oss-instruct-sc2-concepts
def get_table(table, expand=False): """ Return GRIB2 code table as a dictionary. Parameters ---------- **`table`**: Code table number (e.g. '1.0'). NOTE: Code table '4.1' requires a 3rd value representing the product discipline (e.g. '4.1.0'). **`expand`**: If `True`, expand output dicti...
bigcode/self-oss-instruct-sc2-concepts
def b(s): """Byte string with LSB first into an integer. >>> b("1") 1 >>> b("01") 2 >>> b("101") 5 """ return int(s[::-1], 2)
bigcode/self-oss-instruct-sc2-concepts
def add_points_to_skills(skills, embedding_2d): """Add x and y points from 2 dimensional skills embedding to skills dataframe Args: skills (df): skills dataframe embedding_2d (array): skills embedding with 2 dimensions Returns: df: skills dataframe with additional columns for x...
bigcode/self-oss-instruct-sc2-concepts
import math def specify_significant_figures(float_value, num_sig_figs): """Round float_value to num_sig_figs significant figures.""" try: # Find my_mult, my_exp such that float_value = my_mult*10^my_exp # such that 1. <= my_mult < 10. my_exp = math.floor(math.log10(abs(float_value))...
bigcode/self-oss-instruct-sc2-concepts
def duplicate(N, Elem): """ N = integer() >= 0 Elem = T List = [T] T = term() Returns a list which contains N copies of the term Elem. For example: > lists:duplicate(5, xx). [xx,xx,xx,xx,xx] Note: Function taken from Erlang - http://erldocs.com/17.3/stdlib/lists.html#duplicat...
bigcode/self-oss-instruct-sc2-concepts
import torch def confidence_mask(tensor: torch.Tensor, confidence: float) -> torch.Tensor: """ Returns the masked form of the input tensor with respect to given confidence Arguments: tensor (torch.Tensor): tensor to be masked by confidence confidence (float): confi...
bigcode/self-oss-instruct-sc2-concepts
def slug_from_id(page_id: str) -> str: """Extract Notion page slug from the given id, e.g. lwuf-kj3r-fdw32-mnaks -> lwufkj3rfdw32mnaks.""" return page_id.replace("-", "")
bigcode/self-oss-instruct-sc2-concepts
def contains_memory(memoryrange, memory): """Returns True if the given `memory` is in `memoryrange`, False if not.""" for field, value in memoryrange.lower.ListFields(): if getattr(memory, field.name) < value: return False for field, value in memoryrange.upper.ListFields(): if ge...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Optional def distance(v1: List[int], v2: List[int]) -> Optional[int]: """ Determine the distance between two vectors, i.e. the number of positions in which their value differs. :param v1: first vector :param v2: second vector :return: distance as describe...
bigcode/self-oss-instruct-sc2-concepts
def endswithoneof(inputstr, seq): """ Check if *inputstr* ends with one of the items in seq. If it does, return the item that it ends with. If it doe not, return ``None``. :param inputstr: input string :param seq: sequences of items to check :return: the item the the input string ends wit...
bigcode/self-oss-instruct-sc2-concepts
import yaml def save_dict_as_yaml(input_dict, path): """ Save a dictionary to a YAML file. Args: input_dict: Dictionary which will be saved to file path: Path to the YAML file which will be (over-) written. """ with open(path, 'w') as f: return yaml.dump(input_dict, f)
bigcode/self-oss-instruct-sc2-concepts
import yaml import random def get_random_subject(species='human'): """ Function to get a random data config file and subject for a given species. Note: only human data are configured at the moment Parameters ---------- species: str 'human', 'rodent', or 'nhp' Returns -------...
bigcode/self-oss-instruct-sc2-concepts
def compute_fixed_point(g, x0, tol=1e-8, print_n=False): """ Compute the fixed point of g(x). """ prev_x = x0 x = g(x0) n = 1 while(abs(prev_x - x) > 0.5 * tol): prev_x = x x = g(x) n += 1 if(print_n): print("\tn = %d" % n) return x
bigcode/self-oss-instruct-sc2-concepts
import math def is_triangle_number(num): """Returns whether a number is a triangle number. A triangle number n is one for which there exists an integer x with n = (x^2 + x) / 2. Solving this quadratic equation gives x = (-1 +- sqrt(1 + 8n)) / 2 which will be an integer if and only if 1 + 8n...
bigcode/self-oss-instruct-sc2-concepts
def _user_get_full_name(user): """ Override regular get_full_name which returns first_name + last_name """ return user.profile.full_name if user.has_profile() else " ".join([user.first_name, user.last_name]).strip()
bigcode/self-oss-instruct-sc2-concepts
def tle_scientific_2_float(number): """ This method transforms a scientific suffix from the TLE format into a string format that can be parsed into a float by Python. The format is the following: 15254-5 = 0.15254 >>> 15254E-5 -333-3 = -0.333 >>> 333E-3 @param number String where the decim...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def print_time(x): """ Print the current Description ----------- Appends the current time into a print statement Parameters ---------- x : String A message to be printed """ ts = datetime.now().strftime("%y-%m-%d %H:%M:%S") print(f"[{ts}]...
bigcode/self-oss-instruct-sc2-concepts
def _imshow_formater(arr): """Creates a formating function to show the values of imshow in the status bar. :param arr: Array to be shown :returns: function formater(x, y) that should be set to ax.format_coord """ def format_coord(x, y): col, row = int(x + .5), int(y + .5) if (c...
bigcode/self-oss-instruct-sc2-concepts
def _copy_dir_entry(workdir: str, user_id: int, user_group: int, dirname: str) -> str: """Returns the Dockerfile entry necessary to copy a single extra subdirectory from the current directory into a docker container during build. """ owner = "{}:{}".format(user_id, user_group) return """#...
bigcode/self-oss-instruct-sc2-concepts
def collatz_sequence_length(starting_value: int) -> int: """ Given solution relies on just calculating the length, which takes out the longer and more expensive collatz calculation that requires storing the sequence. Passing the integer parameter is cheaper than storing, appending, and passing a list da...
bigcode/self-oss-instruct-sc2-concepts
def has_admin_privileges(user): """Return whether the specified user has admin privileges.""" # Finding this is the point of the challenge... return user["position"].lower() == "admin"
bigcode/self-oss-instruct-sc2-concepts
import csv def load_urls(src): """ Load given url file csv into memory. It assumes that only two columns are present. One is key, other is value. """ with open(src) as f_h: data = csv.reader(f_h, delimiter=",") return dict((int(row[0]), row[1]) for row in data)
bigcode/self-oss-instruct-sc2-concepts
def _is_num(x): """Return: True if x is an int or float""" return type(x) in [int,float]
bigcode/self-oss-instruct-sc2-concepts
def strftime(datetime, formatstr): """ Uses Python's strftime with some tweaks """ # https://github.com/django/django/blob/54ea290e5bbd19d87bd8dba807738eeeaf01a362/django/utils/dateformat.py#L289 def t(day): "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'r...
bigcode/self-oss-instruct-sc2-concepts
def get_heart_rate(message_fields): """ get_heart_rate return the heart rate as float from a message.as_dict()['fields'] object Args: message_fields: a message.as_dict()['fields'] object (with name 'record') Returns: heart rate in bpm or 50. if not found """ for message_field i...
bigcode/self-oss-instruct-sc2-concepts
def drake(Rs, fp, ne, fl, fi, fc, L): """ Ecuación de Drake. Parámetros ---------- Rs : float Tasa anual de formación de estrellas en la galaxia. fp : float Fracción de estrellas que tienen planetas en su órbita. ne : float Número de esos planetas orbitando d...
bigcode/self-oss-instruct-sc2-concepts
def tile_to_quadkey(tile_x, tile_y, level): """This is a function that converts tile coordinates at a certain level of detail of a Bing Map to a unique string identifier (QuadKey). :param tile_x: The x axis coordinate of the tile at `level` level of detail :param tile_y: The y axis coordinate of th...
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 def create_abundance_dict(database, datasets): """Process the abundance table by dataset in order to create a dictionary data structure organized like this: transcript_ID -> dataset -> abundance in that dataset """ abundance = {} conn = sqlite3.connect(database) ...
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources import pathlib def _get_ee_sources_path() -> str: """Gets the ee-sources folder path. Returns: The ee-sources folder path. """ ee_extra_py_file = pkg_resources.resource_filename("ee_extra", "ee_extra.py") pkgdir = pathlib.Path(ee_extra_py_file).parent return pkgdi...
bigcode/self-oss-instruct-sc2-concepts
def merge_optional_trees(tree, big_tree): """Merge two MacroConditionTrees when one or both objects may be `None`.""" if tree is not None: if big_tree is None: return tree else: return big_tree.merge(tree) else: return big_tree
bigcode/self-oss-instruct-sc2-concepts
def ibis_test_file(tmp_path): """Return a golden ibis model file to test with.""" ibis_file = tmp_path.joinpath("test.ibs") with open(ibis_file, "w", encoding="UTF-8") as output: output.write( r"""[IBIS Ver] 5.1 [File Name] example_tx.ibs [File Rev] v0.1 [Date] 2019-02-10 ...
bigcode/self-oss-instruct-sc2-concepts
def _calc_trsp_at_density_levels(trsp_ds, rho_w, rho_s, ufld, vfld, lat=None): """Helper function to compute transport at binned density levels given the maskW and maskS. Extracted here to do the same operations for latitude or section masks Parameters ---------- trsp_ds : xarray Dataset ...
bigcode/self-oss-instruct-sc2-concepts
def tower(n): """computes 2^(2^(2^...)) with n twos, using recursion""" if(n==0): return 1 return 2**tower(n-1)
bigcode/self-oss-instruct-sc2-concepts
import re def _single_quote_strings(sql: str) -> str: """Replace unquoted double-quotes with single-quotes.""" return re.sub(r"(?<![\\])\"", "'", sql)
bigcode/self-oss-instruct-sc2-concepts
def _mul(x, y): """ Multiply x and y. :param x: First element :param y: Second element :return: The multiplication result of x and y. """ return x * y
bigcode/self-oss-instruct-sc2-concepts
def is_overlap(object1, object2): """Detects overlap between two rectangles. Taking two objects, detects whether they overlap. Assumes the presence of the following attributes: - x - y - width - height Tests whether the rectangles are above/below each other, or left/right of ea...
bigcode/self-oss-instruct-sc2-concepts
def lst_depth(lst): """Check max depth of nested list.""" if isinstance(lst, list): return 1 + max(lst_depth(item) for item in lst) return 0
bigcode/self-oss-instruct-sc2-concepts
def is_operator(node): """This function checks whether a validation node is an operator or not. Args: node(str): The node key you want to check. Returns: : bool. """ return node.startswith('$')
bigcode/self-oss-instruct-sc2-concepts
import re def remove_punctuation(body): """ - Removes punctuation, symbols, and numbers - Changes to lower case - Strips new lines and extra spaces Args: body: a body of text Returns: A string with clean-up procedures applied """ punctuation_removed = re.sub(r'[^\sa-zA-...
bigcode/self-oss-instruct-sc2-concepts
def convertToCPM(dose, period): """ Converts from milliSieverts/hr to CPM Parameters: dose (double): The dosage period (double): The time period over which the dosage is administered Returns the measurement in CPM """ conversionFactor = 350000 / 1.0 return conversionFactor * dose / period
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _read_from_path(config:dict, path:List[str]): """Reads nested dictionary. Eg `_read_config({'foo':{'bar':1}}, ['foo','bar']) = 1` """ if len(path) == 1: return config[path[0]] return _read_from_path(config[path[0]], path[1:])
bigcode/self-oss-instruct-sc2-concepts
def should_cache_download(url: str) -> bool: # pragma: no cover """ Determine whether this specific result should be cached. Here, we don't want to cache any files containing "-latest-" in their filenames. :param url: url string which is used to decide if result is cached :return: When cache shou...
bigcode/self-oss-instruct-sc2-concepts
def smallest_with(expr, symbol): """ Return the smallest sub-tree in an expression that contains a given symbol. """ assert symbol in expr.free_symbols candidates = [arg for arg in expr.args if symbol in arg.free_symbols] if len(candidates) > 1 or candidates[0] == symbol: return expr ...
bigcode/self-oss-instruct-sc2-concepts
def pipe_commands(commands): """Pipe commands together""" return ' | '.join(commands)
bigcode/self-oss-instruct-sc2-concepts
def parseColorLine(ls, keys, flags=set()): """ >>> parseColorLine("CODE 0 VALUE #05131D FOO".split(), {"CODE", "VALUE", "EDGE", "BAR"}) ({'CODE': '0', 'VALUE': '#05131D'}, set()) """ d = {} s = set() for idx, val in enumerate(ls): if val in keys and idx+1 < len(ls): d[val...
bigcode/self-oss-instruct-sc2-concepts
import json def get_json(x): """Convert Python dict to JSON. Convert Python dictionary into a JSON string. Args: x: Python dictionary Returns: JSON string """ return json.dumps(x)
bigcode/self-oss-instruct-sc2-concepts
def max_degree(graph): """ Return the maximum degree in the graph """ return max(graph.degree, key=lambda kv: kv[1])[1]
bigcode/self-oss-instruct-sc2-concepts
def sequential(inputs, layers, ): """Applies a sequence of layers to an input.""" output = inputs for layer in layers.values(): output = layer(output) return output
bigcode/self-oss-instruct-sc2-concepts
def unscramble(word, unscramble_map: dict) -> str: """ Takes a scrambled input word, and converts to unscrambled. Args: word (str): Scrambled input unscramble_map (dict): Map of scrambled char->unscrambled char """ return "".join(sorted([unscramble_map[char] for char in word]))
bigcode/self-oss-instruct-sc2-concepts
def prepend_parts(parts_prefix, n): """ Recursively preprend parts_prefix to the parts of the node n. Parts is a list of markers that indicates where you are in the regulation text. """ n.label = parts_prefix + n.label for c in n.children: prepend_parts(parts_prefix, c) return n
bigcode/self-oss-instruct-sc2-concepts
import warnings import copy def clone_trainer(trainer, is_reinit_besides_param=False): """Clone a trainer with optional possibility of reinitializing everything besides parameters (e.g. optimizers.)""" with warnings.catch_warnings(): warnings.simplefilter("ignore") trainer_new = copy.deep...
bigcode/self-oss-instruct-sc2-concepts
def onlydigits(value): """ Filtre `value` pour ne garder que les chiffres. On peut ainsi retirer toutes les sauts de lignes présents dans le fichier `score.txt`. Parameters ---------- value : str La chaîne à filtrer Returns ------- str La chaîne obtenue après f...
bigcode/self-oss-instruct-sc2-concepts
def get_same_padding(kernel_size): """Return SAME padding size for convolutions.""" if isinstance(kernel_size, tuple): assert len(kernel_size) == 2, 'invalid kernel size: %s' % kernel_size p1 = get_same_padding(kernel_size[0]) p2 = get_same_padding(kernel_size[1]) return p1, p2 ...
bigcode/self-oss-instruct-sc2-concepts
def _tofloat(obj): """Convert to float if object is a float string.""" if "inf" in obj.lower().strip(): return obj try: return int(obj) except ValueError: try: return float(obj) except ValueError: return obj
bigcode/self-oss-instruct-sc2-concepts