seed
stringlengths
1
14k
source
stringclasses
2 values
def replace_tags(template, tags, tagsreplace): """Replace occurrences of tags with tagsreplace Example: >>> replace_tags('a b c d',('b','d'),{'b':'bbb','d':'ddd'}) 'a bbb c ddd' """ s = template for tag in tags: replacestr = tagsreplace.get(tag, '') if not replacestr: ...
bigcode/self-oss-instruct-sc2-concepts
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ zeros = [] ones = [] twos = [] for input in input_list: if input == 0: zeros.append(input) ...
bigcode/self-oss-instruct-sc2-concepts
def maybe_encode(value): """If the value passed in is a str, encode it as UTF-8 bytes for Python 3 :param str|bytes value: The value to maybe encode :rtype: bytes """ try: return value.encode('utf-8') except AttributeError: return value
bigcode/self-oss-instruct-sc2-concepts
def _broadcast_params(params, num_features, name): """ If one size (or aspect ratio) is specified and there are multiple feature maps, we "broadcast" anchors of that single size (or aspect ratio) over all feature maps. If params is list[float], or list[list[float]] with len(params) == 1, repeat ...
bigcode/self-oss-instruct-sc2-concepts
def get_fort46_info(NTRII, NATM, NMOL, NION): """Collection of labels and dimensions for all fort.46 variables, as collected in the SOLPS-ITER 2020 manual. """ fort46_info = { "PDENA": [r"Atom particle density ($cm^{-3}$)", (NTRII, NATM)], "PDENM": [r"Molecule particle density ($cm^{-3...
bigcode/self-oss-instruct-sc2-concepts
def modify_axis(axs, xtick_label, ytick_label, xoffset, yoffset, fontsize, grid=True): """Change properties of plot axis to make more beautiful""" axs.spines['top'].set_visible(False) axs.spines['bottom'].set_visible(True) axs.spines['left'].set_visible(True) axs.spines['right'].set_visible(False) ...
bigcode/self-oss-instruct-sc2-concepts
def remove_trailing_characters_from_list(element_list, char_list): """ This function removes trailing characters from a all strings in a list Args: element_list: list of strings to be formatted char_list: List of characters to be removed from each string in the list Returns: ele...
bigcode/self-oss-instruct-sc2-concepts
def norm_text_angle(a): """Return the given angle normalized to -90 < *a* <= 90 degrees.""" a = (a + 180) % 180 if a > 90: a = a - 180 return a
bigcode/self-oss-instruct-sc2-concepts
import sympy def is_quad_residue(n, p): """ Returns True if n is a quadratic residue mod p. """ return sympy.ntheory.residue_ntheory.is_quad_residue(n, p)
bigcode/self-oss-instruct-sc2-concepts
def dir(p_object=None): # real signature unknown; restored from __doc__ """ dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attribute...
bigcode/self-oss-instruct-sc2-concepts
import io def fread(file_path): """Read data from file""" with io.open(file_path, "r", encoding="utf8") as f: return f.read()
bigcode/self-oss-instruct-sc2-concepts
def action(maximize, total_util, payoffs): """ >>> action(True, 0.9, [1.1, 0, 1, 0.4]) 0 >>> action(True, 1.1, [1.1, 0, 1, 0.4]) 1 >>> action(False, 0.9, [1.1, 0, 1, 0.4]) 0.9 """ if maximize: return int(total_util > payoffs[2]) else: return total_util
bigcode/self-oss-instruct-sc2-concepts
def clean_view(view_orig, superunits): """ Define a view of the system that comes from a view of another one. Superunits are cleaned in such a way that no inconsistencies are present in the new view. Args: view_orig (dict): the original view we would like to clean superunits (list): l...
bigcode/self-oss-instruct-sc2-concepts
def bounds(total_docs, client_index, num_clients, includes_action_and_meta_data): """ Calculates the start offset and number of documents for each client. :param total_docs: The total number of documents to index. :param client_index: The current client index. Must be in the range [0, `num_clients')....
bigcode/self-oss-instruct-sc2-concepts
def is_valid_coordinate(x0: float, y0: float) -> bool: """ validates a latitude and longitude decimal degree coordinate pairs. """ if isinstance(x0, float) and isinstance(y0, float): if -90 <= x0 <= 90: if -180 <= y0 <= 180: return True return False
bigcode/self-oss-instruct-sc2-concepts
def fibonacci_py(v): """ Computes the Fibonacci sequence at point v. """ if v == 0: return 0 if v == 1: return 1 return fibonacci_py(v - 1) + fibonacci_py(v - 2)
bigcode/self-oss-instruct-sc2-concepts
import six def get_varval_from_locals(key, locals_, strict=False): """ Returns a variable value from locals. Different from locals()['varname'] because get_varval_from_locals('varname.attribute', locals()) is allowed """ assert isinstance(key, six.string_types), 'must have parsed key into ...
bigcode/self-oss-instruct-sc2-concepts
import math def rotate(v1, angle): """ rotates the vector by an angle around the z axis :param v1: The vector that will be rotated :param angle: The angle to rotate the vector by :return: The vector rotated around the z axis by the angle """ x, y, z = v1 # Rotation transformation ...
bigcode/self-oss-instruct-sc2-concepts
def is_waiting_state(state, num_of_servers): """Checks if waiting occurs in the given state. In essence, all states (u,v) where v > C are considered waiting states. Set of waiting states: S_w = {(u,v) ∈ S | v > C} Parameters ---------- state : tuple a tuples of the form (u,v) num_o...
bigcode/self-oss-instruct-sc2-concepts
import bz2 def bz2_open(file_name, mode): """ Wraps bz2.open to open a .bz2 file. Parameters ---------- file_name : str mode : str Returns ------- file Raises ------ RuntimeError If bz2 is not available. """ assert mode in ('r', 'w') if bz2 is None: raise RuntimeError('bz2 m...
bigcode/self-oss-instruct-sc2-concepts
def reshape_fortran(tensor, shape): """The missing Fortran reshape for mx.NDArray Parameters ---------- tensor : NDArray source tensor shape : NDArray desired shape Returns ------- output : NDArray reordered result """ return tensor.T.reshape(tuple(rever...
bigcode/self-oss-instruct-sc2-concepts
def get_non_conflicting_name(template, conflicts, start=None, get_next_func=None): """ Find a string containing a number that is not in conflict with any of the given strings. A name template (containing "%d") is required. You may use non-numbers (strings, floats, ...) as well. In this case ...
bigcode/self-oss-instruct-sc2-concepts
def onebindingsite(x, A, B, C, D): """One binding site model y = A * x / (B + x) + C * x + D A is max B is Kd C is nonspecific D is background """ return A * x / (B + x) + C * x + D
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import re import warnings def _parse_glibc_version(version_str: str) -> Tuple[int, int]: """Parse glibc version. We use a regexp instead of str.split because we want to discard any random junk that might come after the minor version -- this might happen in patched/forked vers...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def decode_cookies(string_to_decode: Optional[str] = None) -> Optional[str]: """ Decode the latin-1 string, and encode it to utf-8. Args: string_to_decode: string to decode Returns: Optional[str]: decoded string """ if string_to_decode: ret...
bigcode/self-oss-instruct-sc2-concepts
def perplexity(self, text): """ Calculates the perplexity of the given text. This is simply 2 ** cross-entropy for the text. :param text: words to calculate perplexity of :type text: Iterable[str] """ return pow(2.0, self.entropy(text))
bigcode/self-oss-instruct-sc2-concepts
def valid_limit(limit, ubound=100): """Given a user-provided limit, return a valid int, or raise.""" limit = int(limit) assert limit > 0, "limit must be positive" assert limit <= ubound, "limit exceeds max" return limit
bigcode/self-oss-instruct-sc2-concepts
def crop(image): """Crop the image (removing the sky at the top and the car front at the bottom) Credit: https://github.com/naokishibuya/car-behavioral-cloning """ return image[60:-25, :, :]
bigcode/self-oss-instruct-sc2-concepts
def get_content_type(result_set): """ Returns the content type of a result set. If only one item is included its content type is used. """ if len(result_set) == 1: return result_set[0].content_type else: return "multipart/related"
bigcode/self-oss-instruct-sc2-concepts
def chk_enum_arg(s): """Checks if the string `s` is a valid enum string. Return True or False.""" if len(s) == 0 or s[0].isspace() or s[-1].isspace(): return False else: return True
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _sqlite_uri_to_path(uri: str) -> Path: """Convert a SQLite URI to a pathlib.Path""" return Path(uri.split(':')[-1]).resolve()
bigcode/self-oss-instruct-sc2-concepts
def BytesFromFile(filename): """Read the EDID from binary blob form into list form. Args: filename: The name of the binary blob. Returns: The list of bytes that make up the EDID. """ with open(filename, 'rb') as f: chunk = f.read() return [int(x) for x in bytes(chunk)]
bigcode/self-oss-instruct-sc2-concepts
import pathlib def tmp_yaml(tmp_path: pathlib.Path) -> pathlib.Path: """Temporary copy of path.yaml.""" dest_path = tmp_path / "path.yaml" src_path = pathlib.Path("tests/data/path.yaml") text = src_path.read_text() dest_path.write_text(text) return dest_path
bigcode/self-oss-instruct-sc2-concepts
def get_parameter_for_sharding(sharding_instances): """Return the parameter for sharding, based on the given number of sharding instances. Args: sharding_instances: int. How many sharding instances to be running. Returns: list(str). A list of parameters to represent the sharding config...
bigcode/self-oss-instruct-sc2-concepts
def _set_default_junction_temperature( temperature_junction: float, temperature_case: float, environment_active_id: int, ) -> float: """Set the default junction temperature for integrated circuits. :param temperature_junction: the current junction temperature. :param temperature_case: the curre...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def erase_overlap_intervals_count(intervals: List[List[int]]) -> int: """ LeteCode 435: Non-overlapping Intervals Given a list of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping. Examples: 1. i...
bigcode/self-oss-instruct-sc2-concepts
def remove_title(soup): """Deletes the extra H1 title.""" h1 = soup.find('h1') if h1: h1.extract() return soup
bigcode/self-oss-instruct-sc2-concepts
import re def _convert_to_db_type(sval): """ Detect which database type (string, int, float) is most appropriate for sval and convert it to its corresponding database type. """ # floats: Ex. 1.23, 0.23, .23 if re.search(r'^\s*\d*\.\d+\s*$', sval): return float(sval) # ints: Ex. 0, 12...
bigcode/self-oss-instruct-sc2-concepts
def source_key(resp): """ Provide the timestamp of the swift http response as a floating point value. Used as a sort key. :param resp: httplib response object """ return float(resp.getheader('x-put-timestamp') or resp.getheader('x-timestamp') or 0)
bigcode/self-oss-instruct-sc2-concepts
def calculate_c_haines_index(t700: float, t850: float, d850: float) -> float: """ Given temperature and dew points values, calculate c-haines. Based on original work: Graham A. Mills and Lachlan McCaw (2010). Atmospheric Stability Environments and Fire Weather in Australia – extending the Haines Index. ...
bigcode/self-oss-instruct-sc2-concepts
def is_mol_parameter(param): """Identify if a parameter is a `mol` parameter.""" parts = param.split("_") return param.startswith("mol_") \ and parts[-1].isdigit() \ and len(parts) > 2
bigcode/self-oss-instruct-sc2-concepts
def get_word(word): """Return normalized contents of a word.""" return "".join([n.string.strip() for n in word.contents if n.name in [None, "s"]])
bigcode/self-oss-instruct-sc2-concepts
def to_str(bytes_or_string): """if bytes, return the decoded string (unicode here in python3). else return itself""" if isinstance(bytes_or_string, bytes): return bytes_or_string.decode('utf-8') return bytes_or_string
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def dynamic_import(import_path: str) -> Any: """Dynamically import the specified object. It can be a module, class, method, function, attribute, nested arbitrarily. Parameters: import_path: The path of the object to import. Raises: ImportError: When there ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def screen_to_world(screen_pos: tuple, pan: tuple, zoom: float) -> Tuple[float, float]: """ Converts screen coordinates to world coordinates using the pan and zoom of the screen """ result = (((screen_pos[0] - pan[0]) / zoom), ...
bigcode/self-oss-instruct-sc2-concepts
def count_empty(index, key): """ Count for any key how many papers leave the value unspecified. Note that this function only checks the first of the rows corresponding to a paper. """ count = 0 for paper, rows in index.items(): value = rows[0][key] if value in {"", "none given", ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def _convergent(continued_fractions: Tuple[int, ...],) -> Tuple[int, int]: """Get the convergent for a given continued fractions sequence of integers :param continued_fractions: Tuple representation of continued fraction :return: reduced continued fraction representation of conve...
bigcode/self-oss-instruct-sc2-concepts
def matches_release(allowed_releases, release): """ Check if the given `release` is allowed to upgrade based in `allowed_releases`. :param allowed_releases: All supported releases :type allowed_releases: list or dict :param release: release name to be checked :type release: string :return: ...
bigcode/self-oss-instruct-sc2-concepts
def is_valid_xml_char(char): """Check if a character is valid based on the XML specification.""" codepoint = ord(char) return (0x20 <= codepoint <= 0xD7FF or codepoint in (0x9, 0xA, 0xD) or 0xE000 <= codepoint <= 0xFFFD or 0x10000 <= codepoint <= 0x10FFFF)
bigcode/self-oss-instruct-sc2-concepts
def DecodeFileRecordSegmentReference(ReferenceNumber): """Decode a file record segment reference, return the (file_record_segment_number, sequence_number) tuple.""" file_record_segment_number = ReferenceNumber & 0xFFFFFFFFFFFF sequence_number = ReferenceNumber >> 48 return (file_record_segment_number,...
bigcode/self-oss-instruct-sc2-concepts
def firstjulian(year): """Calculate the Julian date up until the first of the year.""" return ((146097*(year+4799))//400)-31738
bigcode/self-oss-instruct-sc2-concepts
def sum_non_reds(s): """ Sum all numbers except for those contained in a dict where a value is "red". Parameters ---------- s : int, list, or dict An item to extract numbers from. Returns ------- int The total of all valid numbers. """ if isinstance(s, int): ...
bigcode/self-oss-instruct-sc2-concepts
import typing import struct def read_uint32(stream: typing.BinaryIO) -> int: """Reads a Uint32 from stream""" return struct.unpack("<I", stream.read(4))[0]
bigcode/self-oss-instruct-sc2-concepts
import requests def buscar_avatar(usuario: str) -> str: """ Busca avatar no GitHub Args: usuario (str): usuário no github Return: str com o link do avatar """ url = f'https://api.github.com/users/{usuario}' resp = requests.get(url) return resp.json()['avatar_url']
bigcode/self-oss-instruct-sc2-concepts
def get_ftp_dir(abspath: str) -> str: """ Returns path within ftp site Parameters ---------- abspath The full ftp url Returns ------- str The relative path within the ftp site Examples -------- >>> abspath = 'ftp://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/901/1...
bigcode/self-oss-instruct-sc2-concepts
def make_graph_abcde(node): """ A -> B | | | v +--> C -> D | +--> E """ d = node('D') e = node('E') c = node('C', cd=d) b = node('B', bc=c) a = node('A', ab=b, ac=c, ae=e) return a, b, c, d, e
bigcode/self-oss-instruct-sc2-concepts
import pathlib def process_path(path, parent, default): """Convert a path to an absolute path based on its current value. Arguments --------- path : PathLike The path to be processed. parent : PathLike The parent path that `path` will be appended to if `path` is a relative path. ...
bigcode/self-oss-instruct-sc2-concepts
def normalize_preferences(choices): """Removes duplicates and drops falsy values from a single preference order.""" new_choices = [] for choice in choices: if choice and (choice not in new_choices): new_choices.append(choice) return new_choices
bigcode/self-oss-instruct-sc2-concepts
from calendar import isleap import datetime def datetime_from_numeric(numdate): # borrowed from the treetime utilities # https://github.com/neherlab/treetime/blob/de6947685fbddc758e36fc4008ddd5f9d696c6d3/treetime/utils.py """convert a numeric decimal date to a python datetime object Note that this onl...
bigcode/self-oss-instruct-sc2-concepts
import re def sha_from_desc(desc): """ Extract the git SHA embedded in the description field """ m = re.match(".*\[SHA ([A-Za-z0-9]{7})[\]!].*", desc) if m: return m.groups()[0]
bigcode/self-oss-instruct-sc2-concepts
def find_irreducible_prefix(brackets): """Find minimal prefix of string which is balanced (equal Ls and Rs). Args: brackets: A string containing an equal number of (and only) 'L's and 'R's. Returns: A two-element tuple. The first element is the minimal "irreducible prefix" of `brackets`, which ...
bigcode/self-oss-instruct-sc2-concepts
def _extract_node_text(node): """Extracts `text` and `content-desc` attribute for a node.""" text = node.get('text') content = node.get('content-desc', []) all_text = [text, content] if isinstance(content, str) else [text] + content # Remove None or string with only space. all_text = [t for t in all_text if...
bigcode/self-oss-instruct-sc2-concepts
def substitute(message, substitutions=[[], {}], depth=1): """ Substitute `{%x%}` items values provided by substitutions :param message: message to be substituted :param substitutions: list of list and dictionary. List is used for {%number%} substitutions and dictionary for {%name%} subs...
bigcode/self-oss-instruct-sc2-concepts
def encodeDict(items): """ Encode dict of items in user data file Items are separated by '\t' characters. Each item is key:value. @param items: dict of unicode:unicode @rtype: unicode @return: dict encoded as unicode """ line = [] for key, value in items.items(): item = u'%...
bigcode/self-oss-instruct-sc2-concepts
def get_order_category(order): """Given an order string, return the category type, one of: {"MOVEMENT, "RETREATS", "DISBANDS", "BUILDS"} """ order_type = order.split()[2] if order_type in ("X", "D"): return "DISBANDS" elif order_type == "B": return "DISBANDS" elif order_type ...
bigcode/self-oss-instruct-sc2-concepts
import random def powerlaw_sequence(n,exponent=2.0): """ Return sample sequence of length n from a power law distribution. """ return [random.paretovariate(exponent-1) for i in range(n)]
bigcode/self-oss-instruct-sc2-concepts
def distance_between(origin_x, origin_y, destination_x, destination_y): """Takes origin X,Y and destination X,Y and returns the distance between them""" return ((origin_x - destination_x)**2 + (origin_y - destination_y)**2)**.5
bigcode/self-oss-instruct-sc2-concepts
def basic_data_context_config_dict(basic_data_context_config): """Wrapper fixture to transform `basic_data_context_config` to a json dict""" return basic_data_context_config.to_json_dict()
bigcode/self-oss-instruct-sc2-concepts
def split_elem_def(path): """Get the element name and attribute selectors from an XPath path.""" path_parts = path.rpartition('/') elem_spec_parts = path_parts[2].rsplit('[') # chop off the other ']' before we return return (elem_spec_parts[0], [part[:-1] for part in elem_spec_parts[1:]])
bigcode/self-oss-instruct-sc2-concepts
def _normalize_target_module(source_module, target_module, level): """ Normalize relative import, to absolute import if possible. Parameters ---------- source_module : str or None Name of the module where the import is written. If given, this name should be absolute. target_module :...
bigcode/self-oss-instruct-sc2-concepts
import copy def ApplyFunToRadii(fiber_bundle, fun): """ Applies function to fibers radii Parameters ---------- fiber_bundle : [(,4)-array, ...] list of fibers fun : function Returns ------- res : [(,4)-array, ...] translated fiber_bundle """ fiber_bundle ...
bigcode/self-oss-instruct-sc2-concepts
def get_file_info_from_url(url: str, spec_dir: str): """ Using a url string we create a file name to store said url contents. """ # Parse a url to create a filename spec_name = url.replace('https://raw.githubusercontent.com/', '')\ .replace('.yml', '')\ .replace...
bigcode/self-oss-instruct-sc2-concepts
def make_idx(*args, dim, ndim): """ Make an index that slices exactly along a specified dimension. e.g. [:, ... :, slice(*args), :, ..., :] This helper function is similar to numpy's ``_slice_at_axis``. Parameters ---------- *args : int or None constructor arguments for the slice o...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Any def contains(collection: Iterable, entity: Any) -> bool: """Checks whether collection contains the given entity.""" return entity in collection
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def extract_sequence(fasta: Path, target_contig: str) -> str: """ Given an input FASTA file and a target contig, will extract the nucleotide/amino acid sequence and return as a string. Will break out after capturing 1 matching contig. """ sequence = "" write_flag = Fal...
bigcode/self-oss-instruct-sc2-concepts
def obter_pos_c(pos): """ obter_pos_c: posicao -> str Recebe uma posicao e devolve a componente coluna da posicao. """ return pos['c']
bigcode/self-oss-instruct-sc2-concepts
def interval_len(aInterval): """Given a 3 column interval, return the length of the interval """ return aInterval[2] - aInterval[1] + 1
bigcode/self-oss-instruct-sc2-concepts
def get_emoji(hashtag): """Return a helpful emoji bashed on the hashtag of the earning report.""" if "miss" in hashtag: return "🔴" return "🟢"
bigcode/self-oss-instruct-sc2-concepts
from typing import List def find_occurrences_in_text(text: List[List[List[str]]], researched_tokens: List[str]) -> List[str]: """ Find occurrences of given tokens in a given text. Each occurrence has the following format: <chapter>-<line>-<half-line>-<word>. >>> text = r...
bigcode/self-oss-instruct-sc2-concepts
def read_reco2vol(volumes_file): """Read volume scales for recordings. The format of volumes_file is <reco-id> <volume-scale> Returns a dictionary { reco-id : volume-scale } """ volumes = {} with open(volumes_file) as volume_reader: for line in volume_reader.readlines(): if l...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha256(path): """Return the sha256 digest of a file.""" h = hashlib.sha256() with open(path, 'rb') as f: for chunk in iter(lambda: f.read(8192), b''): if not chunk: break h.update(chunk) return h.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
import yaml def jinja_filter_toyaml_dict(value) -> str: """Jinjafilter to return a dict as a Nice Yaml. Args: value (dict): value to convert Returns: Str formatted as Yaml """ return yaml.dump(value, default_flow_style=False)
bigcode/self-oss-instruct-sc2-concepts
def minibatch_fn(net, loss_fn, optimizer, batch): """ Trains network for a single batch. Args: net (torch network) ANN network (nn.Module) loss_fn (torch loss) loss function for SGD optimizer (torch optimizer) optimizer for SGD batch (torch.Tensor) ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def control_sum(fpath): """Returns the control sum of the file at ``fpath``""" f = open(fpath, "rb") digest = hashlib.sha512() while True: buf = f.read(4096) if not buf: break digest.update(buf) f.close() return digest.digest()
bigcode/self-oss-instruct-sc2-concepts
def tenant_is_enabled(tenant_id, get_config_value): """ Feature-flag test: is the given tenant enabled for convergence? :param str tenant_id: A tenant's ID, which may or may not be present in the "convergence-tenants" portion of the configuration file. :param callable get_config_value: config k...
bigcode/self-oss-instruct-sc2-concepts
def get_defined_pipeline_classes_by_key(module, key): """Return all class objects in given module which contains given key in its name.""" return [ cls for name, cls in module.__dict__.items() if isinstance(cls, type) and key in name ]
bigcode/self-oss-instruct-sc2-concepts
def calc_bits(offset, size): """ Generates the string of where the bits of that property in a register live Parameters ---------- offset : int, size : int, Returns ---------- ret_str : str, the string """ # Generate the register bits if size == 1: ret_str ...
bigcode/self-oss-instruct-sc2-concepts
def set_color_mask(A, M, c): """ Given image array A (h, w, 3) and mask M (h, w, 1), Apply color c (3,) to pixels in array A at locations M """ for i in range(3): A_i = A[:,:,i] A_i[M]=c[i] A[:,:,i] = A_i return A
bigcode/self-oss-instruct-sc2-concepts
def cents_to_pitchbend(cents, pb_range) -> int: """ Convert cent offset to pitch bend value (capped to range 0-16383) :param cents: cent offset :param pb_range: pitch bend range in either direction (+/-) as per setting on Roli Dashboard / Equator :return: """ pb = 8192 + 16384 * cents / (pb_...
bigcode/self-oss-instruct-sc2-concepts
import functools def _numel(arr): """ Returns the number of elements for an array using a numpy-like interface. """ return functools.reduce(lambda a, b: int(a) * int(b), arr.shape, 1)
bigcode/self-oss-instruct-sc2-concepts
import platform def get_architecture() -> str: """Return the Windows architecture, one of "x86" or "x64".""" return "x86" if platform.architecture()[0] == "32bit" else "x64"
bigcode/self-oss-instruct-sc2-concepts
def _get_numbers(directive): """ Retrieve consecutive floating point numbers from a directive. Arguments: directive: A 2-tuple (int, str). Returns: A tuple of floating point numbers and the remainder of the string. """ num, line = directive numbers = [] items = line.spl...
bigcode/self-oss-instruct-sc2-concepts
import math def format_amount( amount_pence, trim_empty_pence=False, truncate_after=None, pound_sign=True ): """ Format an amount in pence as pounds :param amount_pence: int pence amount :param trim_empty_pence: if True, strip off .00 :param truncate_after: if a number of pounds, will round in...
bigcode/self-oss-instruct-sc2-concepts
def bonferroni(false_positive_rate, original_p_values): """ Bonferrnoi correction. :param false_positive_rate: alpha value before correction :type false_positive_rate: float :param original_p_values: p values from all the tests :type original_p_values: list[float] :return: new critical value...
bigcode/self-oss-instruct-sc2-concepts
def get_max_vals(tree): """ Finds the max x and y values in the given tree and returns them. """ x_vals = [(i[0], i[2]) for i in tree] x_vals = [item for sublist in x_vals for item in sublist] y_vals = [(i[1], i[3]) for i in tree] y_vals = [item for sublist in y_vals for item in sublist] ...
bigcode/self-oss-instruct-sc2-concepts
def scienti_filter(table_name, data_row): """ Funtion that allows to filter unwanted data from the json. for this case: * fields with "FILTRO" * values with the string "nan" * passwords anything can be set here to remove unwanted data. Parameters: table_name:str n...
bigcode/self-oss-instruct-sc2-concepts
import math def compute_icns_data_length(ctx): """Compute the required data length for palette based images. We need this computation here so we can use `math.ceil` and byte-align the result. """ return math.ceil((ctx.width * ctx.height * ctx.bit_length) / 8)
bigcode/self-oss-instruct-sc2-concepts
import math def getHeading(q): """ Get the robot heading in radians from a Quaternion representation. :Args: | q (geometry_msgs.msg.Quaternion): a orientation about the z-axis :Return: | (double): Equivalent orientation about the z-axis in radians """ yaw = math.atan2(2 * ...
bigcode/self-oss-instruct-sc2-concepts
def wants_other_orders(responses, derived): """ Return whether or not the user wants other orders """ return 'Other orders' in derived['orders_wanted']
bigcode/self-oss-instruct-sc2-concepts
def removeAlignmentNumber(s): """ If the name of the transcript ends with -d as in ENSMUST00000169901.2-1, return ENSMUST00000169901.2 """ s = s[:] i = s.find('-') if i == -1: return s else: return s[0:i]
bigcode/self-oss-instruct-sc2-concepts