seed
stringlengths
1
14k
source
stringclasses
2 values
def is_dlang(syntax): """Returns whether the given syntax corresponds to a D source file""" return syntax == 'Packages/D/D.sublime-syntax'
bigcode/self-oss-instruct-sc2-concepts
def get_confirmation(warningtext): """ Prints a warning message and asks for user confirmation Return Values: True: User selected Yes False: User selected No """ print() print(warningtext) while True: try: user_input = input("Please confirm (Y/N): ") ...
bigcode/self-oss-instruct-sc2-concepts
def package_resource_url(package_url, resource_path): """ Converts a package and resource path into a fuchsia pkg url with meta. """ return package_url + "#" + resource_path
bigcode/self-oss-instruct-sc2-concepts
def signExtend(x, n=8): """ Returns signed integer that is the sign extention of n bit unsigned integer x in twos complement form where x has n significant bits This is useful when unpacking bit fields where the bit fields use two's complement to represent signed numbers. Assumes the the upper bits...
bigcode/self-oss-instruct-sc2-concepts
def ans_match_wh(wh_word, new_ans): """Returns a function that yields new_ans if the question starts with |wh_word|.""" def func(a, tokens, q, **kwargs): if q.lower().startswith(wh_word + ' '): return new_ans return None return func
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_caller_name(steps=2): """ When called inside a function, it returns the name of the caller of that function. Keyword arguments: steps - the number of steps up the stack the calling function is """ return inspect.stack()[steps][3]
bigcode/self-oss-instruct-sc2-concepts
def thermalConductivity(T, tCP): """ thermalConductivity(T, tCP) thermalConductivity (W/m/K) = A + B*T + C*T^2 Parameters T, temperature in Kelvin tCP, A=tCP[0], B=tCP[1], C=tCP[2] A, B, and C are regression coefficients Returns thermal conductivity in W/m/K at T ...
bigcode/self-oss-instruct-sc2-concepts
def chance(dice): """Score the given role in the 'Chance' category """ return sum(dice)
bigcode/self-oss-instruct-sc2-concepts
def get_average_velocity(model): """ Gets the total average velocity over all the agents :param model: The model (environment) where the agents exist :return: The total average velocity over all the agents """ df = model.datacollector.get_agent_vars_dataframe() df.reset_index(inplace=True)...
bigcode/self-oss-instruct-sc2-concepts
def xor(x, y): """Return truth value of ``x`` XOR ``y``.""" return bool(x) != bool(y)
bigcode/self-oss-instruct-sc2-concepts
def fetch_production_configuration(service): """Safely fetches production configuration from 3scale""" return service.proxy.list().configs.list(env="production")
bigcode/self-oss-instruct-sc2-concepts
import base64 def binary_to_base64(path: str) -> str: """ Transforms a binary file to base64 :param path: file's path :return: base code """ with open(path, 'rb') as binary_file: binary_file_data = binary_file.read() base64_encoded_data = base64.b64encode(binary_file_data) ...
bigcode/self-oss-instruct-sc2-concepts
def chan_list_to_mask(chan_list): # type: (list[int]) -> int """ This function returns an integer representing a channel mask to be used with the MCC daqhats library with all bit positions defined in the provided list of channels to a logic 1 and all other bit positions set to a logic 0. Ar...
bigcode/self-oss-instruct-sc2-concepts
def greedy_cow_transport(cows,limit=10): """ Uses a greedy heuristic to determine an allocation of cows that attempts to minimize the number of spaceship trips needed to transport all the cows. The returned allocation of cows may or may not be optimal. The greedy heuristic should follow the followin...
bigcode/self-oss-instruct-sc2-concepts
def learner_name(learner): """Return the value of `learner.name` if it exists, or the learner's type name otherwise""" return getattr(learner, "name", type(learner).__name__)
bigcode/self-oss-instruct-sc2-concepts
def is_skippable(string: str): """A string is skippable if it's empty or begins with a '#'""" return not string or string[0] == "#"
bigcode/self-oss-instruct-sc2-concepts
def get_24_bit_bg_color(r, g, b): """"Returns the 24 bit color value for the provided RGB values. Note: not all terminals support this""" return '48;2;%d;%d;%d' % (r, g, b)
bigcode/self-oss-instruct-sc2-concepts
def merge(left, right, lt): """Assumes left and right are sorted lists. lt defines an ordering on the elements of the lists. Returns a new sorted(by lt) list containing the same elements as (left + right) would contain.""" result = [] i,j = 0, 0 while i < len(left) and j < len(right): ...
bigcode/self-oss-instruct-sc2-concepts
def compPubKey(keyObj): """ get public key from python-bitcoin key object :param keyObj: python-bitcoin key object :return: public bytes """ keyObj._cec_key.set_compressed(True) pubbits = keyObj._cec_key.get_pubkey() return pubbits
bigcode/self-oss-instruct-sc2-concepts
def make_backreference(namespace, elemid): """Create a backreference string. namespace -- The OSM namespace for the element. elemid -- Element ID in the namespace. """ return namespace[0].upper() + elemid
bigcode/self-oss-instruct-sc2-concepts
def _get_default_slot_value(spellbook, level): """ Get the default value of a slot maximum capacity: - the existing maximum capacity if the slot already exists - 0 in other cases """ try: return spellbook.slot_level(level).max_capacity except AttributeError: return 0
bigcode/self-oss-instruct-sc2-concepts
def new_patch_description(pattern: str) -> str: """ Wrap the pattern to conform to the new commit queue patch description format. Add the commit queue prefix and suffix to the pattern. The format looks like: Commit Queue Merge: '<commit message>' into '<owner>/<repo>:<branch>' :param pattern: The...
bigcode/self-oss-instruct-sc2-concepts
def same_neighbourhood_size(atom_index_1, molecule_1, atom_index_2, molecule_2): """ Checks whether the same atoms in two different molecules (e.g., reactant and product molecules) have the same neighbourhood size. """ if len(molecule_1.GetAtomWithIdx(atom_index_1).GetNeighbors()) != \ len(...
bigcode/self-oss-instruct-sc2-concepts
def _FilterFile(affected_file): """Return true if the file could contain code requiring a presubmit check.""" return affected_file.LocalPath().endswith( ('.h', '.cc', '.cpp', '.cxx', '.mm'))
bigcode/self-oss-instruct-sc2-concepts
import decimal def prettyprint(x, baseunit): """ Just a function to round the printed units to nice amounts :param x: Input value :param baseunit: Units used :return: rounded value with correct unit prefix """ prefix = 'yzafpnµm kMGTPEZY' shift = decimal.Decimal('1E24') d = (decim...
bigcode/self-oss-instruct-sc2-concepts
def get_prep_pobj_text(preps): """ Parameters ---------- preps : a list of spacy Tokens Returns ------- info : str The text from preps with its immediate children - objects (pobj) Raises ------ IndexError if any of given preps doesn't have any children """ ...
bigcode/self-oss-instruct-sc2-concepts
import requests def api_retrieve_category_history(category_id): """ Allows the client to call "retrieve --all" method on the server side to retrieve the historical states of category from the ledger. Args: category_id (str): The uuid of the category Returns: type: str ...
bigcode/self-oss-instruct-sc2-concepts
def is_in_roi(x, y, roi_x, roi_y, roi_width, roi_height): """ Returns true if in region of interest and false if not """ return ((x >= roi_x and x <= roi_x + roi_width) and (y >= roi_y and y <= roi_y + roi_height))
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def create_choice(value: Union[str, int], name: str): """ Creates choices used for creating command option. :param value: Value of the choice. :param name: Name of the choice. :return: dict """ return { "value": value, "name": name }
bigcode/self-oss-instruct-sc2-concepts
def UD(value): """ Tags the given value with User Data tags. """ return "<ud>{0}</ud>".format(value)
bigcode/self-oss-instruct-sc2-concepts
def get_tokens(line): """tokenize a line""" return line.split()
bigcode/self-oss-instruct-sc2-concepts
def next_tag(el): """ Return next tag, skipping <br>s. """ el = el.getnext() while el.tag == 'br': el = el.getnext() return el
bigcode/self-oss-instruct-sc2-concepts
def isCacheInitialized(addr): """ Cache address is initialized if the first bit is set """ return (int.from_bytes(addr, byteorder='little') & 0x80000000) != 0
bigcode/self-oss-instruct-sc2-concepts
import re def get_chr(bam_alignment, canonical=False): """Helper function to return canonical chromosomes from SAM/BAM header Arguments: bam_alignment (pysam.AlignmentFile): SAM/BAM pysam object canonical (boolean): Return only canonical chromosomes Returns: regions (list[str]): R...
bigcode/self-oss-instruct-sc2-concepts
import six def row_to_dict(row): """Convert a `pymssql` row object into a normal dictionary (removing integer keys). >>> returned = row_to_dict({1: 'foo', 'one': 'foo', 2: 'bar', 'two': 'bar'}) >>> returned == {'one': 'foo', 'two': 'bar'} True """ retval = dict() for key, value in six.iteritems(row): ...
bigcode/self-oss-instruct-sc2-concepts
def cve_harvest(text): """ looks for anything with 'CVE' inside a text and returns a list of it """ array = [] #look inside split by whitespace for word in text.split(): if 'CVE' in word: array.append(word) return array
bigcode/self-oss-instruct-sc2-concepts
def _is_tuple_of_dyads(states): """Check if the object is a tuple or list of dyads """ def _is_a_dyad(dd): return len(dd) == 2 ret = False for st in states: if _is_a_dyad(st): ret = True else: ret = False break r...
bigcode/self-oss-instruct-sc2-concepts
def calculate_fitness(reference, population): """ Calculate how many binary digits in each solution are the same as our reference solution. """ # Create an array of True/False compared to reference identical_to_reference = population == reference # Sum number of genes that are identical to t...
bigcode/self-oss-instruct-sc2-concepts
def coin_amount_for_usd(coin: str, usd: float, tickers: dict) -> float: """ Get amount of {coin} for {usd} :param coin: coin symbol :param usd: amount in USD :param tickers: raw tickers fetched from binance :return: amount of coin for usd value as float """ price_in_btc = float(tickers[f...
bigcode/self-oss-instruct-sc2-concepts
import click def validate_user(context, param, value): """ Validates the existence of user by username. """ users = context.obj.api.users() user = next((u for u in users if u["username"] == value), None) if not user: raise click.BadParameter("User \"%s\" was not found" % value) re...
bigcode/self-oss-instruct-sc2-concepts
def parse_odbc(url): """ Parse Redshift ODBC URL ----------------------- :param url: Fully Qualified ODBC URL :type url: str :return parsed: ODBC fields parsed into respective fields. :rtype parsed: dict .. example:: Driver={Amazon Redshift (x64)}; Server=server_name...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Dict from typing import List import json def read_json(filename: str) -> Union[Dict, List]: """Read a JSON object or list from the given output file. By convention, the Java wrapper for Metanome algorithms stores all algorithm as JSON seriaizations. Paramet...
bigcode/self-oss-instruct-sc2-concepts
def _ImportPythonModule(module_name): """Imports a Python module. Args: module_name (str): name of the module. Returns: module: Python module or None if the module cannot be imported. """ try: module_object = list(map(__import__, [module_name]))[0] except ImportError: return None # If t...
bigcode/self-oss-instruct-sc2-concepts
def statistics(*args): """ Compute the average, minimum and maximum of a list of numbers. Input: a variable no of arguments (numbers). Output: tuple (average, min, max). """ # this function takes variable argument lists avg = 0; n = 0 # avg and n are local variables for term in args: ...
bigcode/self-oss-instruct-sc2-concepts
def get_invalid_keys(validation_warnings): """Get the invalid keys from a validation warnings list. Args: validation_warnings (list): A list of two-tuples where the first item is an iterable of string args keys affected and the second item is a string error message. Returns...
bigcode/self-oss-instruct-sc2-concepts
def _islinetype(line, testchar): """Checks for various kinds of line types based on line head""" return line.strip().startswith(testchar)
bigcode/self-oss-instruct-sc2-concepts
import random import string def generate_random_string(length=7): """Generates random string""" return ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(length))
bigcode/self-oss-instruct-sc2-concepts
def get_max(arr: list) -> int: """Returns the maximum value in an list Args: arr (list): the list to find the value in Returns: int: the value itself """ max_value = arr[0] for value in arr: if value > max_value: max_value = value return max_value
bigcode/self-oss-instruct-sc2-concepts
def hyps2word(hyps): """ Converts a list of hyphens to a string. :param hyps: a list of strings (hyphens) :return: string of concatenated hyphens """ return ''.join(hyps)
bigcode/self-oss-instruct-sc2-concepts
import re def get_shorttext(text): """Get the initial 200 characters of text. Remove HTML and line breaks.""" shorttext = re.sub(r"<.*?>|\n|\t", " ", text) shorttext = shorttext.strip() shorttext = re.sub(r" ", " ", shorttext) return shorttext[:200]
bigcode/self-oss-instruct-sc2-concepts
def get_factors(n): """Return a list of the factors of a number n. Does not include 1 or the number n in list of factors because they're used for division questions. """ factors = [] for i in range(2, n): if n % i == 0: factors.append(i) return factors
bigcode/self-oss-instruct-sc2-concepts
from typing import List def sequence (lower:int, upper:int) -> List[int]: """ generate an integer sequence between two numbers. """ seq = [ ] current = lower while current <= upper: seq.append(current) current += 1 return seq
bigcode/self-oss-instruct-sc2-concepts
from redis.client import Redis def from_url(url, **kwargs): """ Returns an active Redis client generated from the given database URL. Will attempt to extract the database id from the path url fragment, if none is provided. """ return Redis.from_url(url, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any from typing import List def set_user_defined_results( fha: Dict[str, Any], results: List[float] ) -> Dict[str, Any]: """Set the user-defined results for the user-defined calculations. This allows the use of the results fields to be manually set to float ...
bigcode/self-oss-instruct-sc2-concepts
def cria_copia_posicao(pos): """ cria_copia_posicao: posicao -> posicao Recebe uma posicao e devolve uma copia nova da posicao. """ return {'c': pos['c'], 'l': pos['l']}
bigcode/self-oss-instruct-sc2-concepts
def reg8_delta(a, b): """Determine 8-bit difference, allowing wrap-around""" delta = b - a if b > a else 256 + b - a return delta - 256 if delta > 127 else delta
bigcode/self-oss-instruct-sc2-concepts
def group_list(actions, agent_states, env_lens): """ Unflat the list of items by lens :param items: list of items :param lens: list of integers :return: list of list of items grouped by lengths """ grouped_actions = [] grouped_agent_states = [] cur_ofs = 0 for g_len in env_lens: ...
bigcode/self-oss-instruct-sc2-concepts
def find_settings(element, alternate_name): """Given an ElementTree.Element and a string, searches the element for a subelement called "settings". If it doesn't find it, searches for a subelement using the alternate_name. Prior to Vespa 0.7.0, the settings in Analysis blocks had unique class and ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from pathlib import Path import torch def average_checkpoints(filenames: List[Path]) -> dict: """Average a list of checkpoints. Args: filenames: Filenames of the checkpoints to be averaged. We assume all checkpoints are saved by :func:`save_checkpoint`. Retur...
bigcode/self-oss-instruct-sc2-concepts
def docs_append_to_section(docstring, section, add): """Append extra information to a specified section of a docstring. Parameters ---------- docstring : str Docstring to update. section : str Name of the section within the docstring to add to. add : str Text to append t...
bigcode/self-oss-instruct-sc2-concepts
def denpify(f): """ Transforms a function over a tuple into a function over arguments. Suppose that `g` = ``denpify(f)``, then `g(a_1, a_2, ..., a_n) = f((a_1, a_2, ..., a_n))`. Examples -------- >>> flip((0, 1)) (1, 0) >>> f = denpify(flip) >>> f(0, 1) # note the the...
bigcode/self-oss-instruct-sc2-concepts
import math def prob_no_match(n): """analytical result using integers - python can handle arb large numbers""" return math.factorial(n)*math.comb(365,n)/(365**n)
bigcode/self-oss-instruct-sc2-concepts
import re def fuzzy_match_repo_url(one, other): """Compares two repository URLs, ignoring protocol and optional trailing '.git'.""" oneresult = re.match(r'.*://(?P<oneresult>.*?)(\.git)*$', one) otherresult = re.match(r'.*://(?P<otherresult>.*?)(\.git)*$', other) if oneresult and otherresult: ...
bigcode/self-oss-instruct-sc2-concepts
def get_file_extension(url): """Return file extension""" file_extension = ''.join(('.', url.split('.')[-1:][0])) return file_extension
bigcode/self-oss-instruct-sc2-concepts
def get_min_max_credits(day_count, max_credits_month): """ get the max and min credits with total avg :param day_count: days of the month :param max_credits_month: the maximum credits :return: max_credits and min credits """ avg_credit = max_credits_month / day_count max_credits = (3*avg...
bigcode/self-oss-instruct-sc2-concepts
def comment_out_details(source): """ Given the source of a cell, comment out any lines that contain <details> """ filtered=[] for line in source.splitlines(): if "details>" in line: filtered.append('<!-- UNCOMMENT DETAILS AFTER RENDERING ' + line + ' END OF LINE TO UNCOMMENT -->...
bigcode/self-oss-instruct-sc2-concepts
def create_anc_lineage_from_id2par(id2par_id, ott_id): """Returns a list from [ott_id, ott_id's par, ..., root ott_id]""" curr = ott_id n = id2par_id.get(curr) if n is None: raise KeyError('The OTT ID {} was not found'.format(ott_id)) lineage = [curr] while n is not None: lineage...
bigcode/self-oss-instruct-sc2-concepts
import logging def _get_stream_handler() -> logging.StreamHandler: """ Define parameters of logging in the console. Returns: logging.StreamHandler: console handler of the logger. """ stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) stream_handler.setF...
bigcode/self-oss-instruct-sc2-concepts
import torch def merge_list_feat(list_feat, list_batch_cnt): """ Merge a list of feat into a single feat Args: list_feat (list): each element is (N, C) list_batch_cnt (list): each element is (B) - [N0, N1, ...]; sum(Ni) == N Returns: merge_feat (torch.Tensor): (M, C) ...
bigcode/self-oss-instruct-sc2-concepts
def format_error(ex): """Creates a human-readable error message for the given raised error.""" msg = 'Error occurred in the Google Cloud Storage Integration' if hasattr(ex, '__class__'): class_name = ex.__class__.__name__ details = str(ex) if isinstance(ex, BaseException) and detail...
bigcode/self-oss-instruct-sc2-concepts
def py_slice2(obj,a,b): """ >>> [1,2,3][1:2] [2] >>> py_slice2([1,2,3], 1, 2) [2] >>> [1,2,3][None:2] [1, 2] >>> py_slice2([1,2,3], None, 2) [1, 2] >>> [1,2,3][None:None] [1, 2, 3] >>> py_slice2([1,2,3], None, None) [1, 2, 3] """ return obj[a:b]
bigcode/self-oss-instruct-sc2-concepts
from typing import List def remove_ad_search_refs(response: List[dict]) -> List[dict]: """ Many LDAP queries in Active Directory will include a number of generic search references to say 'maybe go look here for completeness'. This is especially common in setups where there's trusted domains or other domai...
bigcode/self-oss-instruct-sc2-concepts
def get_non_text_messages_grouped(groups): """Filters and structures messages for each group and non-text message type. Args: groups (list of lists of MyMessage objects): Messages grouped. Returns: A list of message types grouped: [ { "groups": [list of ...
bigcode/self-oss-instruct-sc2-concepts
def tn(n): """ This function calculates, for a given integer n, the result of the operation n*(n+1)/2 """ return n*(n+1)/2
bigcode/self-oss-instruct-sc2-concepts
def extract_content(soup): """Extract resources based on resource tags from a page.""" images = [ image.get('src') for image in soup.find_all('img') ] stylesheets = [ sheet.get('href') for sheet in soup.find_all('link') ] scripts = [ script.get('src') for script in soup.find_all('script') ] videos =...
bigcode/self-oss-instruct-sc2-concepts
import warnings def index_condensed_matrix(n, i, j): """ Return the index of an element in a condensed n-by-n square matrix by the row index i and column index j of the square form. Arguments --------- n: int Size of the squareform. i: int Row index of the...
bigcode/self-oss-instruct-sc2-concepts
def to_repo(gh, owner, name): """Construct a Repo from a logged in Github object an owner and a repo name""" return gh.get_user(owner).get_repo(name)
bigcode/self-oss-instruct-sc2-concepts
def bubble_sort(a: list): """ Bubble sorting a list. Big-O: n^2 (average/worst) time; 1 on space. """ siz = len(a) for i in range(siz): swapped = False top = siz - i - 1 for j in range(top): if a[j] > a[j+1]: a[j], a[j+1] = a[j+1], a[j] ...
bigcode/self-oss-instruct-sc2-concepts
def parse_smi(files): """ Return parsed files as list of dicts. .. note: parse_smi uses the x and y coordinate of the left eye. Parameters ---------- files : sequence of str file names. For every subject one tab separated file. Returns ------- subjects : sequence o...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def days_from_date(strdate): """ Returns the number of days between strdate and today. Add one to date as date caclulate is relative to time """ currentdate = datetime.today() futuredate = datetime.strptime(strdate, '%Y-%m-%d') delta = futuredate - currentdate ...
bigcode/self-oss-instruct-sc2-concepts
def next_zero(signal, x0, steps=1000, precision=10e-6, gamma=0.01): """ Finds a position of zero of a signal using Newton's method Args: signal (SignalExp): bandlimited function which will be searched for a zero x0 (float): starting point for the search steps (int): maximal possible...
bigcode/self-oss-instruct-sc2-concepts
def getStr(target, pos): """ Get a string from a list/whatever. Returns the string if in-range, False if out of range. """ try: result=str(target[pos]) return result except IndexError: return False
bigcode/self-oss-instruct-sc2-concepts
import json def get_netsel_urls(netsel_file): """Return list of CSK urls.""" # use sorted list of urls of the InSAR inputs to create hash with open(netsel_file) as f: netsel_json = json.load(f) urls = [] for i in netsel_json: for j in i: urls.append(j['url']) return urls
bigcode/self-oss-instruct-sc2-concepts
def get_or_insert(etcd_cl, key, value, **kwargs): """ Performs atomic insert for a value if and only if it does not exists. If the value exists, no insert/update is performed. No exception is raised if value already exists. :param etcd_cl: :param key: :param value: :param kwargs: :r...
bigcode/self-oss-instruct-sc2-concepts
def sum_squared_xy_derivative(xy_point, coeff_mat): """For a coordinate, and function, finds df/dx and df/dy and returns the sum of the squares Arguments: xy_point (tuple): (x,y) coeff_mat (np.array): Matrix of coefficients of the n order polynomial Returns: (float): (df/dx + d...
bigcode/self-oss-instruct-sc2-concepts
def reversed_string(node): """ Print out string representation of linked list but in reverse order :param node: value of head node, start of list :return: string: string of linked list, comma delimited """ if node is not None and node.next_node is not None: # not last element in linked list ...
bigcode/self-oss-instruct-sc2-concepts
def get_option_usage_string(name, option): """Returns a usage string if one exists else creates a usage string in the form of: -o option_name OPTIONNAME """ usage_str = option.get("usage") if not usage_str: usage_str = f"-o {name} {str.upper(name.replace('_',''))}" return usage_...
bigcode/self-oss-instruct-sc2-concepts
import re def split_execution_info_into_groups(execution_info): """Splits execution information into groups according to '--' separator. Args: execution_info: A textual representation of the execution_info. Returns: A grouped representation of the execution_info """ r...
bigcode/self-oss-instruct-sc2-concepts
def is_short_option(argument): """ Check if a command line argument is a short option. :param argument: The command line argument (a string). :returns: ``True`` if the argument is a short option, ``False`` otherwise. """ return len(argument) >= 2 and argument[0] == '-' and argument[1] != '-'
bigcode/self-oss-instruct-sc2-concepts
import logging def logger_for_transaction(name: str, t_id: int): """Provide a specific default_logger for a transaction. The provided transaction id will always be logged with every message. Parameters ---------- name: str The default_logger ID t_id: int Th...
bigcode/self-oss-instruct-sc2-concepts
def is_guess_good(word, guess): """Returns whether guess is in the word For example, is_guess_good('hello', 'e') should return True while is_guess_good('hello', 'p') should return False. Args: word: a string guess: a string Returns: bool: True if guess is in word, else returns ...
bigcode/self-oss-instruct-sc2-concepts
def match_resource(resource, bid, cid): """Helper that returns True if the specified bucket id and collection id match the given resource. """ resource_name, matchdict = resource resource_bucket = matchdict['id'] if resource_name == 'bucket' else matchdict['bucket_id'] resource_collection = matc...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import heapq def kNN(distances: List[float], k: int): """ Computes k-nearest-neighbors. :param distances: A collection of distances from some point of interest. :param k: The number of neighbors to average over. :return: The mean of the smallest 'k' values in 'distances'. ...
bigcode/self-oss-instruct-sc2-concepts
import random def randomer(n): """ Generate random DNA (not a randomer (NNNNN) which is a mix of random DNA) :param n: length :return: string """ alphabet = ['A', 'T', 'G', 'C'] return ''.join([random.choice(alphabet) for x in range(n)])
bigcode/self-oss-instruct-sc2-concepts
def get_field_meta(field): """ returns a dictionary with some metadata from field of a model """ out = { 'name' : field.name, 'is_relation' : field.is_relation, 'class_name' : field.__class__.__name__} if field.is_relation: out['related_model'] = "%s.%s" % (field.related_model._meta.app_labe...
bigcode/self-oss-instruct-sc2-concepts
def get_slurm_dict(arg_dict,slurm_config_keys): """Build a slurm dictionary to be inserted into config file, using specified keys. Arguments: ---------- arg_dict : dict Dictionary of arguments passed into this script, which is inserted into the config file under section [slurm]. slurm_conf...
bigcode/self-oss-instruct-sc2-concepts
import time def Retry(retry_checker, max_retries, functor, sleep_multiplier, retry_backoff_factor, *args, **kwargs): """Conditionally retry a function. Args: retry_checker: A callback function which should take an exception instance and return True if functor(*args, *...
bigcode/self-oss-instruct-sc2-concepts
def cleanse(tarinfo): """Cleanse sources of nondeterminism from tar entries. To be passed as the `filter` kwarg to `tarfile.TarFile.add`. Args: tarinfo: A `tarfile.TarInfo` object to be mutated. Returns: The same `tarinfo` object, but mutated. """ tarinfo.uid = 0 tarinfo.gid =...
bigcode/self-oss-instruct-sc2-concepts
def get_states(event_data): """ Returns a tuple containing the old and new state names from a state_changed event. """ try: old_state = event_data["old_state"]["state"] except Exception as e: old_state = None try: new_state = event_data["new_state"]["state"] exce...
bigcode/self-oss-instruct-sc2-concepts
def inherits_from(obj, a_class): """ Return: True if obj is instance of class that it inherits from or is subcls of """ return (type(obj) is not a_class and issubclass(type(obj), a_class))
bigcode/self-oss-instruct-sc2-concepts