seed
stringlengths
1
14k
source
stringclasses
2 values
def format_odometer(raw: list) -> dict: """Formats odometer information from a list to a dict.""" instruments: dict = {} for instrument in raw: instruments[instrument["type"]] = instrument["value"] if "unit" in instrument: instruments[instrument["type"] + "_unit"] = instrument["u...
bigcode/self-oss-instruct-sc2-concepts
def try_parse_ticket_ids(title): """Get ticket id from PR title. Assumptions: - ticket id or special prefix before PR title - no whitespace before ticket id - whitespace between ticket id and PR title Transformations (for the worst case): "ggrc-1234/1235: Do something" -> ["GGRC-1234", "GGRC-123...
bigcode/self-oss-instruct-sc2-concepts
import json def string_to_dict(value): """str to dict, replace '' with None""" if not value: return None values = json.loads(value) for key in values: if values[key] == "": values[key] = None return values
bigcode/self-oss-instruct-sc2-concepts
def make_readable(res): """ Eliminates the namespace from each element in the results of a SPARQL query. """ return [[uri.split("#")[-1] for uri in row] for row in res]
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def strf_timestamp(timestamp, form): """ Helper function to safely create string date time from a timestamp value :return: string - date time in the specified form """ try: return datetime.utcfromtimestamp(timestamp).strftime(form) except Exception: # py...
bigcode/self-oss-instruct-sc2-concepts
import csv def close_history(args): """close the history file and print the best record in the history file""" args.hist_file.close() args.hist_file = open(args.results_dir+'/history.csv', 'r', newline='') reader = csv.DictReader(args.hist_file) best_epoch = 0 best = {} for epoch, record i...
bigcode/self-oss-instruct-sc2-concepts
def reduce_by_ident(retain_data, reduce_data, idents, cutoff=0.3): """ Remove the proteins from a list of ids which are sequence similar to the ids in another list of ids. Args: retain_data: List of ids which should be retained. reduce_data: List of ids which should be reduced according to ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_hash(dict_obj): """ Return hash of a dict of strings """ rec = [] for k, v in dict_obj.items(): if isinstance(v, str): rec.append(k + ":" + v) elif isinstance(v, list): rec.append(k + "".join(v)) # Update, use sorted so the origin...
bigcode/self-oss-instruct-sc2-concepts
def dup_factions(factions, num_winners): """Expand a list of factions by a factor of num_winners into a list of candidates >>> dup_factions(['A', 'B'], 3) ['A1', 'A2', 'A3', 'B1', 'B2', 'B3'] """ return [f'{f}{n}' for f in factions for n in range(1, num_winners+1)]
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple from typing import Optional def _get_homos_lumos( moenergies: List[List[float]], homo_indices: List[int] ) -> Tuple[List[float], Optional[List[float]], Optional[List[float]]]: """ Calculate the HOMO, LUMO, and HOMO-LUMO gap energies in eV. Parameters ...
bigcode/self-oss-instruct-sc2-concepts
def is_oneliner(txt) -> bool: """Checks if the given string contains no newlines.""" assert isinstance(txt, str) return len(txt.splitlines()) == 1
bigcode/self-oss-instruct-sc2-concepts
import pathlib import pkg_resources def get_requirements(source): """Get the requirements from the given ``source`` Parameters ---------- source: str The filename containing the requirements """ with pathlib.Path(source).open() as requirements_txt: install_requires = [ ...
bigcode/self-oss-instruct-sc2-concepts
def agestr2years(age_str: str) -> int: """Convert an Age String into a int where the age unit is in years. Expected formats are: nnnD, nnnW, nnnM, nnnY. Notes ----- The return value may not yield precise results as the following assumptions are made: there are 365 days in a year, there are 52 ...
bigcode/self-oss-instruct-sc2-concepts
def format_label(fld, skip_last=False): """return a label consisting of subfields in a Field, properly formatted""" subfields = fld.get_subfields('a','b','n','d','c') if len(subfields) > 0: if skip_last: subfields = subfields[:-1] return ' '.join(subfields) else: return None
bigcode/self-oss-instruct-sc2-concepts
def to_intpmf(values, counts, simplify=True): """ Convert an integer probability mass function to a stochastic expression. """ if len(counts) != len(values): raise ValueError("Mismatching number of values and counts.") if len(values) == 0: raise ValueError("Cannot construct distribution fro...
bigcode/self-oss-instruct-sc2-concepts
def isPathExcluded(curPath,excludePath): """ Returns True if excludePath is part of parameter curPath, otherwise False. """ try: curPath.relative_to(excludePath) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
from typing import List def head_commit_query(user: str, repo: str, branches: List[str]) -> str: """ Fetch the head commit for a list of branches """ def branch_part(branch: str, num: int) -> str: return f""" r{num}: repository(name: "{repo}", owner: "{user}") {{ ref(quali...
bigcode/self-oss-instruct-sc2-concepts
def holling_type_0(X,idx_A,coefficient): """ linear response with respect to *destination/predator* compartment For examples see: `Examples <https://gist.github.com/465b/cce390f58d64d70613a593c8038d4dc6>`_ Parameters ---------- X : np.array containing the current state of the conta...
bigcode/self-oss-instruct-sc2-concepts
def parse_intf_status(lines): """ @summary: Parse the output of command "show interface description". @param lines: The output lines of command "show interface description". @return: Return a dictionary like: { "Ethernet0": { "oper": "up", "admin": "up...
bigcode/self-oss-instruct-sc2-concepts
def distanc(*args): """Calcs squared euclidean distance between two points represented by n dimensional vector :param tuple args: points to calc distance from :return: euclidean distance of points in *args """ if len(args) == 1: raise Exception('Not enough input arguments (expected two)') ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def role_playing_hubs() -> Dict[str, str]: """Build role playing hubs definition.""" return {"h_customer_role_playing": "h_customer"}
bigcode/self-oss-instruct-sc2-concepts
def _is_nested_type(field_type: type) -> bool: """Determine whether a typing class is nested (e.g. Union[str, int]).""" return type(field_type._subs_tree()) is tuple
bigcode/self-oss-instruct-sc2-concepts
def calc_formation_enthalpy(ergs_react,erg_prod,coeffs): """ Calculate the formation enthalpy using energies and coefficients of reactants, and energy of product. """ if len(ergs_react) != len(coeffs): raise ValueError('len(ergs_react) != len(coeffs)') dH = erg_prod for i in range(le...
bigcode/self-oss-instruct-sc2-concepts
def format_all_sides(value): """Convert a single value (padding or border) to a dict with keys 'top', 'bottom', 'left' and 'right'""" all = {} for pos in ('top', 'bottom', 'left', 'right'): all[pos] = value return all
bigcode/self-oss-instruct-sc2-concepts
def remember_umbrella(weather_arg: str) -> bool: """Remember umbrella Checks current weather data text from :meth:`get_weather` for keywords indicating rain. Args: weather_arg: String containing current weather text of specified city. Returns: True if any of the rain keywords are foun...
bigcode/self-oss-instruct-sc2-concepts
def make_bool(s): """ Convert string to bool """ return True if s.lower() == 'true' else False
bigcode/self-oss-instruct-sc2-concepts
def dict_item(d, k): """Returns the given key from a dictionary.""" return d[k]
bigcode/self-oss-instruct-sc2-concepts
def extract_tests(api_response, defined_tests): """ Create and return a dict of test name to test data. If api_response is None, return a dict with an empty dict. api_response: the JSON response from the Proctor API in Python object form. defined_tests: an iterable of test name strings defining th...
bigcode/self-oss-instruct-sc2-concepts
import math def calc_distance(pos1, pos2): """ Calculate euclidean distance between two positions """ return round(math.sqrt((pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2), 3)
bigcode/self-oss-instruct-sc2-concepts
def get_account_id_from_arn(trail_arn): """Gets the account ID portion of an ARN""" return trail_arn.split(':')[4]
bigcode/self-oss-instruct-sc2-concepts
import json def load_model_config(filename): """ Load model configuration from json file and return it """ with open(filename, 'r') as fp: data = json.load(fp) return data
bigcode/self-oss-instruct-sc2-concepts
def tensor2numpy(tensor): """Convert tensor to ndarray """ return tensor.cpu().detach().numpy()
bigcode/self-oss-instruct-sc2-concepts
def _get_normalized_vm_statuses(vm_iv): """Iterate over a list of virtual machine statuses and normalize them. Arguments: vm_iv (dict): Raw virtual machine instance view record. Returns: dict: Normalized virtual machine statuses """ normalized_statuses = {} for s in vm_iv.get(...
bigcode/self-oss-instruct-sc2-concepts
def extension_without_gz(path): """Get the file extension ignoring .gz if present""" suffixes = path.suffixes last = len(suffixes) if suffixes[last] == ".gz": extension = suffixes[last - 1] else: extension = suffixes[last] return extension
bigcode/self-oss-instruct-sc2-concepts
def _dol_to_lod(dol): """Convert a dict of lists to a list of dicts.""" return [{key: dol[key][ii] for key in dol.keys()} for ii in range(len(dol[list(dol.keys())[0]]))]
bigcode/self-oss-instruct-sc2-concepts
def create_mapping(dico): """ Create a mapping (item to ID / ID to item) from a dictionary. Items are ordered by decreasing frequency. """ sorted_items = sorted(dico.items(), key=lambda x: (-x[1], x[0])) id_to_item = {i: v[0] for i, v in enumerate(sorted_items)} item_to_id = {v: k for k, v i...
bigcode/self-oss-instruct-sc2-concepts
import torch def add_id(df): """ Add the identity to a tensor with the shape of the Jacobian Args: df (torch.tensor): batched `(n,m,m)` tensor Returns: torch.tensor: :code:`df` plus a batched identity of the right shape """ return df + torch.eye(df.shape[1], device=df.devi...
bigcode/self-oss-instruct-sc2-concepts
def list_users(iam_conn, path_prefix): """List IAM users.""" users = [] marker = None while True: if marker: response = iam_conn.list_users(PathPrefix=path_prefix, Marker=marker) else: response = iam_conn.list_users(Pat...
bigcode/self-oss-instruct-sc2-concepts
def _get_max_size(x, y, map_info): """ Get the size of the biggest square matrix in the map with first point: (x, y) Arguments: x -- column index y -- line index map_info -- a dict of the map and its information Returns: size -- biggest square matrix size """ x_max ...
bigcode/self-oss-instruct-sc2-concepts
import requests def pulsar_list(addr, auth): """ Return a list of the all the pulars in the database. Args: addr: hostname or ip address of database server. auth: tuple of username and password. """ path = '{0}/{1}/'.format(addr, 'pulsar_list') r = requests.get(url=path, ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_product_name_from_path(path): """ Extract S2 product name from the path. """ parents = list(Path(path).parents) if len(parents) > 1: first_dir = Path(parents[len(parents) - 2]) if first_dir.suffix == '.SAFE': return first_dir.stem
bigcode/self-oss-instruct-sc2-concepts
def isPrime(x): """ Checks whether the given number x is prime or not """ if x == 2: return True if x % 2 == 0: return False for i in range(3, int(x ** 0.5) + 1, 2): if x % i == 0: return False return True
bigcode/self-oss-instruct-sc2-concepts
def genwhctrs(anchor): """Return width, height, x center, and y center for an anchor (window). """ base_w = anchor[2] - anchor[0] + 1 # 15 + 1 base_h = anchor[3] - anchor[1] + 1 x_ctr = anchor[0] + 0.5 * (base_w - 1) y_ctr = anchor[1] + 0.5 * (base_h - 1) return base_w, base_h, x_ctr, y_ctr
bigcode/self-oss-instruct-sc2-concepts
def _get_coordinator(hostname, port=9001): """ Generates the coordinator section of a Myria deployment file """ return '[master]\n' \ '0 = {}:{}\n\n'.format(hostname, port)
bigcode/self-oss-instruct-sc2-concepts
def look_and_say(seq, times): """ Recursively play look-and-say on the sequence """ if times == 0: return seq newseq = '' currentc = '' count = 1 for c in seq: if c == currentc: count += 1 else: if currentc != '': newseq += str(coun...
bigcode/self-oss-instruct-sc2-concepts
def mocked_system(mocker): """Mocking `plaform.system`""" return mocker.patch("platform.system")
bigcode/self-oss-instruct-sc2-concepts
def test_triangle(dim): """ Tests if dimensions can come from a triangle. dim is a list of the three dimensions (integers) """ dim = [int(x) for x in dim] dim.sort() if dim[0] + dim[1] > dim[2]: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def asymptotic_relation_radial(enn,numax,param): """ Compute the asymptotic frequency for a radial mode. Parameters ---------- enn : int The radial order of the mode. numax : float The frequency of maximum oscillation power param : array_like Collection of the asypm...
bigcode/self-oss-instruct-sc2-concepts
def cipher(text, shift, encrypt=True): """ Encrypt or Decrypt a string based on Caesar cipher.Each letter is replaced by a letter some fixed number of position down the alphabet. Parameters ---------- text : string A string you wish to encrypt or decrypt. shift : integer A in...
bigcode/self-oss-instruct-sc2-concepts
def minimise_xyz(xyz): """Minimise an (x, y, z) coordinate.""" x, y, z = xyz m = max(min(x, y), min(max(x, y), z)) return (x-m, y-m, z-m)
bigcode/self-oss-instruct-sc2-concepts
def transpose(data): """ Utility function for transposing a 2D array of data. """ return zip(*data)
bigcode/self-oss-instruct-sc2-concepts
import torch def to(input, dtype): """Convert input to dtype.""" if dtype == 'long': dtype = torch.long elif dtype == 'uint8': dtype = torch.uint8 elif dtype == 'float32': dtype = torch.float32 return input.to(dtype)
bigcode/self-oss-instruct-sc2-concepts
import re def clean_column(s): """ utils function that clean a string to be a cleaner name of column Parameter --------- s : string the string to clean Return ------ cleaned string """ if s is None: return None r = s.strip().lower() r = ...
bigcode/self-oss-instruct-sc2-concepts
def count_increase(list_int): """ This function calculates the number of times a measurement increases. This is the answer to the first puzzle. Parameters: list_int (list): list of measurements(integers) Returns: n (int): number of times a measurement inctreases. """ n = 0...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import json def load_data(file_path: str) -> Dict[str, list]: """ Loads the json file in as a Python dictionary. Parameters ---------- file_path : str Absolute file path to the Frew model. Returns ------- json_data : Dict[str, list] A Python dictio...
bigcode/self-oss-instruct-sc2-concepts
def _s3_glob(s3_filepath, my_bucket): """ Searches a directory in an S3 bucket and returns keys matching the wildcard Parameters ---------- s3_filepath : str the S3 filepath (with wildcard) to be searched for matches my_bucket : boto3 bucket object the S3 bucket object containing th...
bigcode/self-oss-instruct-sc2-concepts
def v2_to_internal(menu): """Convert a v2 menu object to an internal menu object""" if not menu['open']: return {'open': False} def soup_to_soup(soup): return { 'price': soup['price'], 'name': soup['name'] } def other_to_other(other): return { ...
bigcode/self-oss-instruct-sc2-concepts
import re import random def scramble(word): """For words over 3 characters, shuffle the letters in the middle""" if len(word) > 3 and re.match(r'\w+', word): middle = list(word[1:-1]) random.shuffle(middle) word = word[0] + ''.join(middle) + word[-1] return word
bigcode/self-oss-instruct-sc2-concepts
def max_bitrate_ext(val): """ Given ESM value, return extended maximum bit rate (Kbps). Please refer to 10.5.6.5, TS24.008 for more details. :param val: the value encoded in the ESM NAS message """ if val <= 74: return 8600 + val * 100 elif val <= 186: return 16000 + (val - ...
bigcode/self-oss-instruct-sc2-concepts
import torch def ConstantTensor(value, *size, dtype=torch.float, device='cuda:0'): """ Returns a Tensor containing only value Parameters ---------- value : int or float the value of every item in the Tensor *size : int... the shape of the tensor dtype : type (optional) ...
bigcode/self-oss-instruct-sc2-concepts
def get_figsize(columnwidth=241.14749, wf=1.0, hf=(5. ** 0.5 - 1.0) / 2.0, b_fixed_height=False): """Parameters: - wf [float]: width fraction in columnwidth units - hf [float]: height fraction in columnwidth units. Set by default to golden ratio. - columnwidth [float]: width...
bigcode/self-oss-instruct-sc2-concepts
def isKanji(char): """ return true if char is a kanji or false if not """ code = ord(char) return 0x4E00 <= code <= 0x9FFF
bigcode/self-oss-instruct-sc2-concepts
def is_track_in_tracks(song_uri, tracks): """ Checks whether song is within a list of songs :param song_uri: ID of target song :param tracks: Page object of track or playlist track objects :return: Whether or a not a song is within a list of tracks """ for track in tracks['items']: t...
bigcode/self-oss-instruct-sc2-concepts
import re import json import collections def LoadJSON(filename): """ Read `filename`, strip its comments and load as JSON. """ with open(filename, "r") as f: match_cpp_comments = re.compile("//.*\n") # The order in which structures are described in JSON matters as we use them # as a seed. Computin...
bigcode/self-oss-instruct-sc2-concepts
def update_speed_limit(intersection, new_speed): """ Updates the speed limit of the intersection :param intersection: intersection :param new_speed: new speed value :type intersection: Intersection :type new_speed: int :return: updated intersection """ return intersection.update_spee...
bigcode/self-oss-instruct-sc2-concepts
def hash_key(key: int, size: int) -> int: """ Return an integer for the given key to be used as an index to a table of the given size. >>> hash_key(10, 7) 3 """ return key % size
bigcode/self-oss-instruct-sc2-concepts
def isWord(s): """ See if a passed-in value is an identifier. If the value passed in is not a string, False is returned. An identifier consists of alphanumerics or underscore characters. Examples:: isWord('a word') ->False isWord('award') -> True isWord(9) -> False ...
bigcode/self-oss-instruct-sc2-concepts
def is_better_sol(best_f, best_K, sol_f, sol_K, minimize_K): """Compares a solution against the current best and returns True if the solution is actually better accordint to minimize_K, which sets the primary optimization target (True=number of vehicles, False=total cost).""" if sol_f is None or so...
bigcode/self-oss-instruct-sc2-concepts
def lineAtPos ( s, pos ): """ lineAtPos: return the line of a string containing the given index. s a string pos an index into s """ # find the start of the line containing the match if len(s) < 1: return "" if pos > len(s): pos = len(s)-1 while pos > 0: if s[pos] == '\n': pos = pos + 1 break ...
bigcode/self-oss-instruct-sc2-concepts
import inspect def wants_args(f): """Check if the function wants any arguments """ argspec = inspect.getfullargspec(f) return bool(argspec.args or argspec.varargs or argspec.varkw)
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def split_templated_class_name(class_name: str) -> Tuple: """ Example: "OctreePointCloud<PointT, LeafContainerT, BranchContainerT>::Ptr" ("OctreePointCloud", (PointT, LeafContainerT, BranchContainerT), "::Ptr") """ template_types = tuple() pos = class_name....
bigcode/self-oss-instruct-sc2-concepts
def validate_type(data_dict: dict, type_name: str) -> dict: """Ensure that dict has field 'type' with given value.""" data_dict_copy = data_dict.copy() if 'type' in data_dict_copy: if data_dict_copy['type'] != type_name: raise Exception( "Object type must be {}, but was i...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Any def all_same(list: List[Any]) -> bool: """Decide whether or not a list's values are all the same""" return len(set(list)) == 1
bigcode/self-oss-instruct-sc2-concepts
import torch def linear_2_oklab(x): """Converts pytorch tensor 'x' from Linear to OkLAB colorspace, described here: https://bottosson.github.io/posts/oklab/ Inputs: x -- pytorch tensor of size B x 3 x H x W, assumed to be in linear srgb colorspace, scaled between 0. and 1. Re...
bigcode/self-oss-instruct-sc2-concepts
def point_in_polygon(S, q): """determine if a point is within a polygon The code below is from Wm. Randolph Franklin <wrf@ecse.rpi.edu> (see URL below) with some minor modifications for integer. It returns true for strictly interior points, false for strictly exterior, and ub for points on the boun...
bigcode/self-oss-instruct-sc2-concepts
def query(question, default_answer="", help=""): """Ask user a question :param question: question text to user :param default_answer: any default answering text string :param help: help text string :return: stripped answer string """ prompt_txt = "{question} [{default_answer}] ".format(que...
bigcode/self-oss-instruct-sc2-concepts
def path_to_major_minor(node_block_devices, ndt, device_path): """ Return device major minor for a given device path """ return node_block_devices.get(ndt.normalized_device_path(device_path))
bigcode/self-oss-instruct-sc2-concepts
def except_text(value): """ Creates messages that will appear if the task number is entered incorrectly :param value: 'список', 'задача', 'цифра'. Depends on what messages are needed :return: 2 messages that will appear if the task number is entered incorrectly """ if value == 'список': ...
bigcode/self-oss-instruct-sc2-concepts
def RemoveAllJetPtCuts(proc): """ Remove default pt cuts for all jets set in jets_cff.py """ proc.finalJets.cut = "" # 15 -> 10 proc.finalJetsAK8.cut = "" # 170 -> 170 proc.genJetTable.cut = "" # 10 -> 8 proc.genJetFlavourTable.cut = "" # 10 -> 8 proc.genJetAK8Table.c...
bigcode/self-oss-instruct-sc2-concepts
import importlib def validate_external_function(possible_function): """ Validate string representing external function is a callable Args: possible_function: string "pointing" to external function Returns: None/Callable: None or callable function Raises: N/A # noqa ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_mirror_path(path_from: Path, path_to: Path) -> Path: """Return the mirror path from a path to another one. The mirrored path is determined from the current working directory (cwd) and the path_from. The path_from shall be under the cwd. The mirrored relative path is t...
bigcode/self-oss-instruct-sc2-concepts
def htk_int_to_float(value): """ Converts an integer value (time in 100ns units) to floating point value (time in seconds)... """ return float(value) / 10000000.0
bigcode/self-oss-instruct-sc2-concepts
def parse_name(name): """ Parse name of the form 'namespace_name.unit_name' into tuple ('namespace_name', 'unit_name'). """ if '.' not in name: raise ValueError('`func` parameter must be provided or name must be "namespace_name.unit_name"') name_components = name.split('.') if len(name_component...
bigcode/self-oss-instruct-sc2-concepts
def loglinear_rule_weight(feature_dict, feature_weights_dict): """ Compute log linear feature weight of a rule by summing the products of feature values and feature weights. :param feature_dict: Dictionary of features and their values :param feature_weights_dict: Dictionary of features and their weights...
bigcode/self-oss-instruct-sc2-concepts
def folder_from_egtb_name(name: str) -> str: """ Determine EGTB folder (Xvy_pawn(less|ful)) from EGTB name :param name: EGTB name """ l, r = name.split('v') prefix = f'{len(l)}v{len(r)}' suffix = '_pawnful' if ('P' in l or 'P' in r) else '_pawnless' return prefix + suffix
bigcode/self-oss-instruct-sc2-concepts
import torch def householder_matrix(v, size=None): """ householder_matrix(Tensor, size=None) -> Tensor Arguments v: Tensor of size [Any,] size: `int` or `None`. The size of the resulting matrix. size >= v.size(0) Output I - 2 v^T * v / v*v^T: Tensor of size [size, ...
bigcode/self-oss-instruct-sc2-concepts
def count_first_word(str_list): """Count the first word of each string in the list. Args: str_list: List of strings Returns: {"word": count, ...} """ ret_count = dict() for phrase in str_list: words = phrase.split("-") ret_count[words[0]] = ret_count.get(words[...
bigcode/self-oss-instruct-sc2-concepts
def quantify(iterable, pred=bool): """Count the number of items in iterable for which pred is true.""" return sum(1 for item in iterable if pred(item))
bigcode/self-oss-instruct-sc2-concepts
def windows_low_high_to_int(windows_int_low, windows_int_high): """Returns an int given the low and high integers""" return (windows_int_high << 32) + windows_int_low
bigcode/self-oss-instruct-sc2-concepts
import time def filename_stamped(filename, number): """Create a time-stamped filename""" time_str = time.strftime("%Y%m%d-%H%M%S") return '{}_{}_{}'.format(filename, number, time_str)
bigcode/self-oss-instruct-sc2-concepts
def say_hello() -> str: """Say hello function.""" return "Hello"
bigcode/self-oss-instruct-sc2-concepts
def parse_hash_id(seq): """Return a list of protein numbers within the given string. Example ------- "#10,41,43,150#" -> ["10", "41", "43", "150"] """ ans = seq.strip("#").split(",") return ans
bigcode/self-oss-instruct-sc2-concepts
def shorten_dfs(dfs, plot_start=None, plot_end=None): """Shorten all incidence DataFrames. All DataFrames are shortened to the shortest. In addition, if plot_start is given all DataFrames start at or after plot_start. Args: dfs (dict): keys are the names of the scenarios, values are the incide...
bigcode/self-oss-instruct-sc2-concepts
def nt2over_gn_groupings(nt): """Return the number of grouping ``over'' a note. For beamings trees this is the number of beams over each note. Args: nt (NotationTree): A notation tree, either beaming tree or tuplet tree. Returns: list: A list of length [number_of_leaves], with integer...
bigcode/self-oss-instruct-sc2-concepts
def center_crop(data, shape): """ Apply a center crop to the input real image or batch of real images. Args: data (torch.Tensor): The input tensor to be center cropped. It should have at least 2 dimensions and the cropping is applied along the last two dimensions. sh...
bigcode/self-oss-instruct-sc2-concepts
def fetch_method(obj, method): """ fetch object attributes by name Args: obj: class object method: name of the method Returns: function """ try: return getattr(obj, method) except AttributeError: raise NotImplementedError(f"{obj.__class__} has not impl...
bigcode/self-oss-instruct-sc2-concepts
def extend_dict(dict_1: dict, dict_2: dict) -> dict: """Assumes that dic_1 and dic_2 are both dictionaries. Returns the merged/combined dictionary of the two dictionaries.""" return {**dict_1, **dict_2}
bigcode/self-oss-instruct-sc2-concepts
import requests def download_zip(url:str, dest_path:str, chunk_size:int = 128)->bool: """Download zip file Downloads zip from the specified URL and saves it to the specified file path. see https://stackoverflow.com/questions/9419162/download-returned-zip-file-from-url Args: url (str): sl...
bigcode/self-oss-instruct-sc2-concepts
def trash_file(drive_service, file_id): """ Move file to bin on google drive """ body = {"trashed": True} try: updated_file = drive_service.files().update(fileId=file_id, body=body).execute() print(f"Moved old backup file to bin.") return updated_file except Exception: ...
bigcode/self-oss-instruct-sc2-concepts
import inspect def extract_kwargs(docstring): """Extract keyword argument documentation from a function's docstring. Parameters ---------- docstring: str The docstring to extract keyword arguments from. Returns ------- list of (str, str, list str) str The name of the...
bigcode/self-oss-instruct-sc2-concepts