seed
stringlengths
1
14k
source
stringclasses
2 values
def bgr_to_rbg(img): """Given a BGR (cv2) numpy array, returns a RBG (standard) array.""" dimensions = len(img.shape) if dimensions == 2: return img return img[..., ::-1]
bigcode/self-oss-instruct-sc2-concepts
def filter_instances(instances, filter_expr): """Filter instances using a lambda filter function.""" return list(filter(filter_expr, instances))
bigcode/self-oss-instruct-sc2-concepts
def denormalize(x,centroid,scale): """Denormalize a point set from saved centroid and scale.""" x = x*scale + centroid return x
bigcode/self-oss-instruct-sc2-concepts
def minmaxrescale(x, a=0, b=1): """ Performs a MinMax Rescaling on an array `x` to a generic range :math:`[a,b]`. """ xresc = (b - a) * (x - x.min()) / (x.max() - x.min()) + a return xresc
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def test_data_root_dir() -> Path: """Return the absolute path to the root directory for test data.""" return Path(__file__).resolve().parent / "test_data"
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple def flat(data: List[Tuple]): """ Removes unnecessary nesting from list. Ex: [(1,), {2,}, {3,}] return [1, 2, 3] """ if not data: return data return [d for d, in data]
bigcode/self-oss-instruct-sc2-concepts
def is_number(num): """Tests to see if arg is number. """ try: #Try to convert the input. float(num) #If successful, returns true. return True except: #Silently ignores any exception. pass #If this point was reached, the i...
bigcode/self-oss-instruct-sc2-concepts
def subset(data, size): """Get a subset of the dataset.""" return { 'data': data['data'][:size, :], 'labels': data['labels'][:size], }
bigcode/self-oss-instruct-sc2-concepts
def compute2x2(obs, pred): """Compute stats for a 2x2 table derived from observed and predicted data vectors Parameters ---------- obs,pred : np.ndarray or pd.Series of shape (n,) Returns ------- a : int True positives b : int False positives c : int Fal...
bigcode/self-oss-instruct-sc2-concepts
import six def morph_dict(d, convert_function): """ Convert a nested dictionary from one convention to another. Args: d (dict): dictionary (nested or not) to be converted. convert_function (func): function that takes the string in one convention and returns it in the other one. ...
bigcode/self-oss-instruct-sc2-concepts
def fixture_family_tag_name() -> str: """Return a tag named 'family'""" return "family"
bigcode/self-oss-instruct-sc2-concepts
def conslice(sim_mat, sep): """Slices a confusion matrix out of similarity matrix based on sep""" images = sim_mat[:sep] slices = [] for i in range(len(images)): slices.append(images[i][sep:]) return slices
bigcode/self-oss-instruct-sc2-concepts
def decode_word(word): """ Return the decoding of a run-length encoded string """ idx = 0 res = [] while idx < len(word): count = int(word[idx]) char = word[idx+1] res.append(char * count) idx += 2 return ''.join(res)
bigcode/self-oss-instruct-sc2-concepts
def _extents(f): """Helper function to determine axis extents based off of the bin edges""" delta = f[1] - f[0] return [f[0] - delta/2, f[-1] + delta/2]
bigcode/self-oss-instruct-sc2-concepts
def remove_oneof(data): """ Removes oneOf key from a dict and recursively calls this function on other dict values. """ if 'oneOf' in data: del data['oneOf'] for key in data: if isinstance(data[key], dict): remove_oneof(data[key]) return data
bigcode/self-oss-instruct-sc2-concepts
import re def clean_string_whitespace(text: str) -> str: """Clean whitespace from text that should only be a single paragraph. 1. Apply ``str.strip`` method 2. Apply regular expression substitution of the ``\\s`` whitespace character group with `` `` (a single whitespace). """ text = text....
bigcode/self-oss-instruct-sc2-concepts
def find_item(items, key, value): """Find an item with key or attributes in an object list.""" filtered = [ item for item in items if (item[key] if isinstance(item, dict) else getattr(item, key)) == value ] if len(filtered) == 0: return None return filtered[0]
bigcode/self-oss-instruct-sc2-concepts
def get_collected_vertex_list_name(full_path_name): """Return the name of the list generated by folding vertices with name full_path_name.""" return "collected_" + full_path_name
bigcode/self-oss-instruct-sc2-concepts
def has_won(player): """ Test to see if the player has won. Returns true if the player has the gold and is also at the tile (0,0). """ return player.x == 0 and player.y == 0 and player.has_gold
bigcode/self-oss-instruct-sc2-concepts
def normalize_unit_box(V, margin = 0.0): """ NORMALIZE_UNIT_BOX normalize a set of points to a unit bounding box with a user-specified margin Input: V: (n,3) numpy array of point locations margin: a constant of user specified margin Output: V: (n,3) numpy array of point locations bounded by margin ~ 1-...
bigcode/self-oss-instruct-sc2-concepts
def get_form_weight(form): """Try to get form weight attribute""" try: return form.weight except AttributeError: return 0
bigcode/self-oss-instruct-sc2-concepts
def create_delete_marker_msg(id): """ Creates a delete marker message. Marker with the given id will be delete, -1 deletes all markers Args: id (int): Identifier of the marker Returns: dict: JSON message to be emitted as socketio event """ return {'id': id}
bigcode/self-oss-instruct-sc2-concepts
def multi_to_one_dim(in_shape, in_index): """ Convert an index from a multi-dimension into the corresponding index in flat array """ out_index = 0 for dim, index in zip(in_shape, in_index): out_index = dim * out_index + index return out_index
bigcode/self-oss-instruct-sc2-concepts
def scc(graph): """ Finds what strongly connected components each node is a part of in a directed graph, it also finds a weak topological ordering of the nodes """ n = len(graph) comp = [-1] * n top_order = [] Q = [] stack = [] new_node = None for root in range(n): ...
bigcode/self-oss-instruct-sc2-concepts
def sort_012(nums): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: nums(list): List to be sorted Returns: Sorted nums """ # Linear search, O(1) in time, O(1) in space pos0, pos2 = 0, len(nums)-1 i = 0 while i <= pos2 and p...
bigcode/self-oss-instruct-sc2-concepts
def max_chan_width(ref_freq, fractional_bandwidth): """ Derive max_𝞓𝝼, the maximum change in bandwidth before decorrelation occurs in frequency Fractional Bandwidth is defined by https://en.wikipedia.org/wiki/Bandwidth_(signal_processing) for Wideband Antennas as: (1) 𝞓𝝼/𝝼 = fb = (fh...
bigcode/self-oss-instruct-sc2-concepts
def build_request_url(method, output_format='tsv'): """Create url to query the string database Allows us to create stubs for querying the string api with various methods Parameters ---------- method: str options - get_string_ids, network, interaction_partners, homology, homology_best, ...
bigcode/self-oss-instruct-sc2-concepts
def _add_formset_field_ids(form_field_ids, formset): """ Add all input fields of a given form set to the list of all field ids in order to avoid keyboard navigation while entering text in form fields. """ for i, form in enumerate(formset): for field in form.base_fields.keys(): f...
bigcode/self-oss-instruct-sc2-concepts
def check_brackets_match(text): """ Checks, whether brackets in the given string are in correct sequence. Any opening bracket should have closing bracket of the same type. Bracket pairs should not overlap, though they could be nested. Returns true if bracket sequence is correct, false otherwise. ...
bigcode/self-oss-instruct-sc2-concepts
def GetBaseResourceId(resource_id): """Removes common suffixes from a resource ID. Removes suffixies that may be added by macros like IMAGE_GRID or IMAGE_BORDER. For example, converts IDR_FOO_LEFT and IDR_FOO_RIGHT to just IDR_FOO. Args: resource_id: String resource ID. Returns: A string with the b...
bigcode/self-oss-instruct-sc2-concepts
def add_additional_columns(data): """ adds "highlighted" and "profile_selected" column :param data: ptcf data frane :return: ptcf data frame with additional information """ highlighted = [True] * len(data.index) data['highlighted'] = highlighted profile_selected = [False] * len(data.index) da...
bigcode/self-oss-instruct-sc2-concepts
def is_hidden_file(filename): """Does the filename start with a period?""" return filename[0] == '.'
bigcode/self-oss-instruct-sc2-concepts
def do_nothing_decorator(*_args, **_kws): """ Callable decorator that does nothing. Arguments are catched, but ignored. This is very useful to provide proxy for decorators that may not be defined. Args: *_args: Positional arguments. **_kws: Keyword arguments. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
import struct def unpack_dint(st): """unpack 4 bytes little endian to int""" return int(struct.unpack('<i', st[0:4])[0])
bigcode/self-oss-instruct-sc2-concepts
import torch def scale_boxes(bboxes, scale): """Expand an array of boxes by a given scale. Args: bboxes (Tensor): shape (m, 4) scale (float): the scale factor of bboxes Returns: (Tensor): shape (m, 4) scaled bboxes """ w_half = (bboxes[:, 2] - bboxe...
bigcode/self-oss-instruct-sc2-concepts
def seismic_suspension_fitered(sus, in_trans): """Seismic displacement noise for single suspended test mass. :sus: gwinc suspension structure :in_trans: input translational displacement spectrum :returns: tuple of displacement noise power spectrum at :f:, and horizontal and vertical components. ...
bigcode/self-oss-instruct-sc2-concepts
import re def clean_string(t, keep_dot=False, space_to_underscore=True, case="lower"): """Sanitising text: - Keeps only [a-zA-Z0-9] - Optional to retain dot - Spaces to underscore - Removes multiple spaces , trims - Optional to lowercase The purpose is just for easier typing, exporting, sa...
bigcode/self-oss-instruct-sc2-concepts
def only_letter(s: str) -> str: """Filter out letters in the string.""" return ''.join([c for c in s if c.isalpha()])
bigcode/self-oss-instruct-sc2-concepts
def test_begin_str(test_name,max_len=40): """ Use with test_end_str(test_name) to make string like this:\n ******** Test Begin ********\n ******** Test End ********** """ if (len(test_name)%2==1): star_len=(max_len-len(test_name))//2+1 return '*'*star_len+" "+test_name+" Begin "+...
bigcode/self-oss-instruct-sc2-concepts
import time def time_func_call(func): """ Prints the processing time of the wrapped function after its context is left. :param func: Function to be wrapped. Usage: @time_func_call def func(): pass """ def wrapped_func(*args, **kwargs): start = time.process_time() ...
bigcode/self-oss-instruct-sc2-concepts
def phase_rms(antbl, scale_prms = 1.0, nu_scale = None): """Function that computes phase rms for a given baseline. The structure function here gives 30 deg phase rms at 10000m = 10km, which is the limit "go" conditions when performing a go-nogo at ALMA. Args: antbl: Antenna baseline in m...
bigcode/self-oss-instruct-sc2-concepts
def set_shape_element(shape, index, value): """Set element of shape tuple, adding ones if necessary. Examples: set_shape_element((2,3),2,4)=(2,3,1,4) set_shape_element((2,3),-4,4)=(4,1,2,3) """ if index >= 0: return shape[:index] + (1,)*(index - len(shape)) + (value,) + shape[ind...
bigcode/self-oss-instruct-sc2-concepts
def GetNextTokenIndex(tokens, pos): """Get the index of the next token after pos.""" for index, token in enumerate(tokens): if (token.lineno, token.column) >= pos: return index return None
bigcode/self-oss-instruct-sc2-concepts
def eq_column(table, column, value): """column == value""" return getattr(table.c, column) == value
bigcode/self-oss-instruct-sc2-concepts
def func_with_args(a: int, b: int, c: int = 3) -> int: """ This function has some args. # Parameters a : `int` A number. b : `int` Another number. c : `int`, optional (default = `3`) Yet another number. Notes ----- These are some notes. # Returns ...
bigcode/self-oss-instruct-sc2-concepts
def compute_total_unique_words_fraction(sentence_list): """ Compute fraction os unique words :param sentence_list: a list of sentences, each being a list of words :return: the fraction of unique words in the sentences """ all_words = [word for word_list in sentence_list for word in word_list] ...
bigcode/self-oss-instruct-sc2-concepts
def factorialFinderLoops(n): """Returns the factorial of the positive integer n using loops.""" if not isinstance(n, int): raise TypeError('n should be a positive integer.') return None if n < 0: raise ValueError('n should be a positive integer.') return None resul...
bigcode/self-oss-instruct-sc2-concepts
def string_to_interactions(string): """ Converts a compact string representation of an interaction to an interaction: 'CDCDDD' -> [('C', 'D'), ('C', 'D'), ('D', 'D')] """ interactions = [] interactions_list = list(string) while interactions_list: p1action = interactions_list.pop...
bigcode/self-oss-instruct-sc2-concepts
def make_po_file_function_dict(pos, filefilter=lambda f: True): """Create a file, function dictionary from a list of proof obligations. Args: pos: list of proof obligations (primary or supporting) filefilter: predicate that specifies which c files to include Returns: dictionary that organ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import List def collect_app_bundles(source_dir: Path) -> List[Path]: """ Collect all app bundles which are to be put into DMG If the source directory points to FOO.app it will be the only app bundle packed. Otherwise all .app bundles from given directory are ...
bigcode/self-oss-instruct-sc2-concepts
def obter_exercito (unidade): """Esta funcao devolve o nome do exercito da unidade dada como argumento""" return unidade[3]
bigcode/self-oss-instruct-sc2-concepts
def UserOwnsProject(project, effective_ids): """Return True if any of the effective_ids is a project owner.""" return not effective_ids.isdisjoint(project.owner_ids or set())
bigcode/self-oss-instruct-sc2-concepts
def flatten(nested_list): """Flatten a nested list.""" return [item for sublist in nested_list for item in sublist]
bigcode/self-oss-instruct-sc2-concepts
import random def randomword(length=12): """ Generate a string of random alphanumeric characters """ valid_chars = \ 'abcdefghijklmnopqrstuvyxwzABCDEFGHIJKLMNOPQRSTUVYXWZ012345689' return ''.join(random.choice(valid_chars) for i in range(length))
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def _get_price_statistics(trading_day_feed): """Calculate and print the following data for each Symbol as a comma-delimiter string. Rows should be printed in alphabetical order based on Symbol i. Time: Most recent timestamp for that Symbol in YYYY-mm-dd HH:MM:SS format ...
bigcode/self-oss-instruct-sc2-concepts
def rectangle_clip(recta, rectb): """ Return the clipped rectangle of ``recta`` and ``rectb``. If they do not intersect, ``None`` is returned. >>> rectangle_clip((0, 0, 20, 20), (10, 10, 20, 20)) (10, 10, 10, 10) """ ax, ay, aw, ah = recta bx, by, bw, bh = rectb x = max(ax, bx) ...
bigcode/self-oss-instruct-sc2-concepts
def polygon_from_bbox(bbox): """ Generate a polygon geometry from a ESWN bouding box :param bbox: a 4 float bounding box :returns: a polygon geometry """ return [ [ [bbox[0], bbox[1]], [bbox[2], bbox[1]], [bbox[2], bbox[3]], [bbox[0], bbox[3]]...
bigcode/self-oss-instruct-sc2-concepts
import re def simplify_string(string: str) -> str: """Remove special symbols end extra spaces. :param string: what is needed to simplify :return: simplified string """ simpl1 = re.sub(r'[^\w\d\-. ]', '', string) simpl2 = re.sub(r'[ ]+', ' ', simpl1) return simpl2
bigcode/self-oss-instruct-sc2-concepts
import re def normalize_target(target: str) -> str: """Normalize targets to allow easy matching against the target database: normalize whitespace and convert to lowercase.""" return re.sub(r"\s+", " ", target).lower()
bigcode/self-oss-instruct-sc2-concepts
def get_dict_path(base, path): """ Get the value at the dict path ``path`` on the dict ``base``. A dict path is a way to represent an item deep inside a dict structure. For example, the dict path ``["a", "b"]`` represents the number 42 in the dict ``{"a": {"b": 42}}`` """ path = list(path) ...
bigcode/self-oss-instruct-sc2-concepts
def hms_to_s(h=0, m=0, s=0): """ Get total seconds from tuple (hours, minutes, seconds) """ return h * 3600 + m * 60 + s
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_params(opcode: int) -> List[int]: """Get params from an `opcode`. Args: opcode (int): the opcode to extract params Returns: list: of length 0-2 """ if opcode < 100: return [] return [int(p) for p in str(opcode//100)]
bigcode/self-oss-instruct-sc2-concepts
def expense_by_store(transactions_and_receipt_metadata): """Takes a transaction df of expenses and receipt metadata and groups on receipt id, in addition to year, month and cat input: df (pd.DataFrame): dataframe of transactions to group and filter returns: df (pd.DataFrame): grouped datafra...
bigcode/self-oss-instruct-sc2-concepts
def __get_tweet_content_from_res(gh_res): """From the response object returned by GitHub's API, this function builds the content to be tweeted Args: gh_res (dict): A dictionary of repository details Returns: str: The string to be tweeted. """ tweet_content = gh_res["name"] if gh_res["langua...
bigcode/self-oss-instruct-sc2-concepts
def protocol_type(request): """ used to parametrized test cases on protocol type :param request: pytest request object :return: protocol type """ return request.param
bigcode/self-oss-instruct-sc2-concepts
def continuous_fraction_coefs (a, b): """ Continuous fraction coefficients of a/b """ ret = [] while a != 0: ret.append( int(b//a) ) a, b = b%a, a return ret
bigcode/self-oss-instruct-sc2-concepts
def GroupBuildsByConfig(builds_timings): """Turn a list of BuildTiming objects into a map based on config name. This is useful when looking at waterfall groups (cq, canary, etc), if you want stats per builder in that group. Args: builds_timings: List of BuildTiming objects to display stats for. Returns...
bigcode/self-oss-instruct-sc2-concepts
import ntpath def get_relpath(path): """ gets the relative path without file Args: path (string): path to the file Returns: string: the relative path """ return ntpath.split(path)[0]
bigcode/self-oss-instruct-sc2-concepts
def get_db(entity): """ Returns the #pony.orm.Database backing the #Entity instance *entity*. """ return entity._database_
bigcode/self-oss-instruct-sc2-concepts
def make_mission_id(mission_definition, specifics_hash): """ Returns the string mission_id which is composed from the mission_definition and specifics_hash. """ return "%s-%s" % (mission_definition, specifics_hash)
bigcode/self-oss-instruct-sc2-concepts
import math def work(force, displacement, theta): """ Calculates the work done by the force while displacing an object at an angle theta Parameters ---------- force : float displcement : float theta : float Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def string_attributes(domain): """ Return all string attributes from the domain. """ return [attr for attr in domain.variables + domain.metas if attr.is_string]
bigcode/self-oss-instruct-sc2-concepts
def wordcount(text): """ Return the number of words in the given text. """ if type(text) == str: return len(text.split(" ")) elif type(text) == list: return len(text) else: raise ValueError("Text to count words for must be of type str or of type list.")
bigcode/self-oss-instruct-sc2-concepts
def get_neighbor_top_left_corner_from_explore(direction): """ Return the relative offsets where the top left corner of the neighbor card would be situated, from an exploration cell. Direction must be one of "up", "down", "left", or "right". """ return {"l": (-2, -4), "d": (1, -2), "u": (-4, -1), "r": (-...
bigcode/self-oss-instruct-sc2-concepts
import imaplib def get_mail_by_uid(imap, uid): """ The full email as determined by the UID. Note: Must have used imap.select(<mailbox>) before running this function. Args: imap <imaplib.IMAP4_SSL>: the server to fetch Returns: Dictionary, with the keys 'flags', 'date_time', ...
bigcode/self-oss-instruct-sc2-concepts
import decimal def round_int(dec): """Round float to nearest int using expected rounding.""" return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_DOWN))
bigcode/self-oss-instruct-sc2-concepts
def empty_config_path(tmp_path_factory): """Create an empty config.ini file.""" config_path = tmp_path_factory.getbasetemp() / "config.ini" config_path.touch() return config_path
bigcode/self-oss-instruct-sc2-concepts
def resta_complejos(num1:list,num2:list) -> list: """ Funcion que realiza la resta de dos numeros complejos. :param num1: lista que representa primer numero complejo :param num2: lista que representa segundo numero complejo :return: lista que representa la resta de los numeros complejos. """ ...
bigcode/self-oss-instruct-sc2-concepts
def Main(a, b): """ :param a: an integer :param b: an integer :return: a + b :rtype: int """ c = a + b return c
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping from typing import List def _mapping_to_mlflow_hyper_params(mp: Mapping) -> List[str]: """ Transform mapping to param-list arguments for `mlflow run ...` command Used to pass hyper-parameters to mlflow entry point (See MLFlow reference for more information) All mapping value...
bigcode/self-oss-instruct-sc2-concepts
import click def confirm_yesno(text, *args, **kwargs): """Like ``click.confirm`` but returns ``Y`` or ``N`` character instead of boolean. """ default = "[N]" # Default is always N unless default is set in kwargs if "default" in kwargs and kwargs["default"]: default = "[Y]" confirm...
bigcode/self-oss-instruct-sc2-concepts
def threshold_filter(elevation_series, threshold=5.0): """Filter elevation series by breaking it into vertical increments. Args: elevation_series (pd.Series): elevation coordinates along a path. threshold (float): Threshold beyond which a change in elevation is registered by the algorithm, in the u...
bigcode/self-oss-instruct-sc2-concepts
def test_datadir(request, datadir): """ Inject the datadir with resources for the specific test function. If the test function is declared in a class then datadir is ClassName/FunctionName otherwise it is only FunctionName. """ function_name = request.function.__name__ if not request.cls: ...
bigcode/self-oss-instruct-sc2-concepts
def _l(self, paper, **_): """Display long form of the paper (all details)""" print("=" * 80) paper.format_term_long() print("=" * 80) return None
bigcode/self-oss-instruct-sc2-concepts
import json def serialize_json_data(data, ver): """ Serialize json data to cassandra by adding a version and dumping it to a string """ dataOut = data.copy() dataOut["_ver"] = ver return json.dumps(dataOut)
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def enforce_state(property_name: str, expected_value): """ A decorator meant for class member functions. On calling a member, it will first check if the given property matches the given value. If it does not, a value error will be thrown. """ def dec(func: Callable)...
bigcode/self-oss-instruct-sc2-concepts
def get_headers(referer): """Returns the headers needed for the transfer request.""" return { "Content-Type": "application/json; charset=UTF-8", "X-Requested-With": "XMLHttpRequest", "Referer": referer }
bigcode/self-oss-instruct-sc2-concepts
def getPointCoords(row, geom, coord_type): """Calculates coordinates ('x' or 'y') of a Point geometry""" if coord_type == 'x': return row[geom].x elif coord_type == 'y': return row[geom].y
bigcode/self-oss-instruct-sc2-concepts
def are_users_same(users): """True if all users are the same and not Nones""" x = set(u.get('seq') for u in users) return len(x) == 1 and None not in x
bigcode/self-oss-instruct-sc2-concepts
def efit_transform(object, data): """Fit-Transform an object on data.""" return object.fit_transform(data)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def count_total_keywords(keywords: List[str]) -> int: """ Returns the count of total keywords of a list of keywords as a integer. Parameters: keywords (List[str]): list with all keywords as strings. """ return len(keywords)
bigcode/self-oss-instruct-sc2-concepts
def linearise(entry, peak1_value, peak2_value, range_1to2, range_2to1): """ Converts a phase entry (rotating 360 degrees with an arbitrary 0 point) into a float between 0 and 1, given the values of the two extremes, and the ranges between them Parameters ---------- entry : int or float ...
bigcode/self-oss-instruct-sc2-concepts
import re def search_for_perf_sections(txt): """ Returns all matches in txt for performance counter configuration sections """ perf_src_srch_str = r'\n<source>\n type oms_omi.*?object_name "(.*?)".*?instance_regex "(.*?)".*?counter_name_regex "(.*?)".*?interval ([0-9]+[a-z])(.*?)</source>\n' ...
bigcode/self-oss-instruct-sc2-concepts
def getLocation( min_point: tuple, max_point: tuple ) -> tuple: """Gets the bottom center location from the bounding box of an occupant.""" # Unpack the tuples into min/max values xmin, ymin = min_point xmax, ymax = max_point # Take midpoint of x-coordinate and ymax for bottom middle of box x_re...
bigcode/self-oss-instruct-sc2-concepts
import copy def wrap_grant(grant_details): """Utility function wrapping grant details for return from a POST.""" details_list = [copy.deepcopy(grant_details)] if grant_details else [] return {'results': details_list}
bigcode/self-oss-instruct-sc2-concepts
def get_dom_np(sents, pos): """ Finds the position of the NP that immediately dominates the pronoun. Args: sents: list of trees (or tree) to search pos: the tree position of the pronoun to be resolved Returns: tree: the tree containing the pronoun dom_pos: the position ...
bigcode/self-oss-instruct-sc2-concepts
def check_filters(filters): """Checks that the filters are valid :param filters: A string of filters :returns: Nothing, but can modify ``filters`` in place, and raises ``ValueError``s if the filters are badly formatted. This functions conducts minimal parsing, to make sure that the relationship exist...
bigcode/self-oss-instruct-sc2-concepts
def decodeMsg(aStr): """Decode a message received from the hub such that multiple lines are restored. """ return aStr.replace("\v", "\n")
bigcode/self-oss-instruct-sc2-concepts
def make_freq_table(stream): """ Given an input stream, will construct a frequency table (i.e. mapping of each byte to the number of times it occurs in the stream). The frequency table is actually a dictionary. """ freq_dict = {} bsize = 512 # Use variable, to make FakeStrea...
bigcode/self-oss-instruct-sc2-concepts
def count_factors(n): """Return the number of positive factors that n has. >>> count_factors(6) # 1, 2, 3, 6 4 >>> count_factors(4) # 1, 2, 4 3 """ i, count = 1, 0 while i <= n: if n % i == 0: count += 1 i += 1 return count
bigcode/self-oss-instruct-sc2-concepts