seed
stringlengths
1
14k
source
stringclasses
2 values
def fetch_ref_codon(ref_pos, curr_gene, curr_seq): """ Fetch codon within gene for given site """ # position of site in gene within_gene_pos = ref_pos - curr_gene['start'] if curr_gene['strand'] == '+' else curr_gene['end'] - ref_pos # position of site in codon within_codon_pos = within_gene_pos % 3...
bigcode/self-oss-instruct-sc2-concepts
import numbers def _scale(scale): """ Given a numeric input, return a 2-tuple with the number repeated. Given a 2-tuple input, return the input >>> _scale(2) (2, 2) >>> _scale((1, 2,)) (1, 2) >>> _scale('nonsense') Traceback (most recent call last): ... TypeError: argu...
bigcode/self-oss-instruct-sc2-concepts
def checkValid(s, row, col): """ Returns True if a given cell is valid in a Sudoku puzzle, and False if not. A cell is valid if the number in that cell is not present in any of the cells in the same row, or the same column, or the same block. """ block_row = row // 3 block_col = col // 3 ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def _len(x: Any) -> int: """Return len of x if it is iterable, else 0.""" return max(1, len(x)) if isinstance(x, list) else 0
bigcode/self-oss-instruct-sc2-concepts
def timedelta_to_seconds(td): """ Converts a timedelta to total seconds, including support for microseconds. Return value is (potentially truncated) integer. (This is built-in in Python >= 2.7, but we are still supporting Python 2.6 here.) :param td: The timedelta object :type td: :cla...
bigcode/self-oss-instruct-sc2-concepts
def luhn_checksum(num: str) -> str: """Calculate a checksum for num using the Luhn algorithm. :param num: The number to calculate a checksum for as a string. :return: Checksum for number. """ check = 0 for i, s in enumerate(reversed(num)): sx = int(s) sx = sx * 2 if i % 2 == 0 e...
bigcode/self-oss-instruct-sc2-concepts
def test_chess_cell(x, y): """ Source https://pythontutor.ru/lessons/ifelse/problems/chess_board/ Condition Two checkerboard squares are set. If they are painted the same color, print the word YES, and if in different colors - then NO. The program receives four numbers from 1 to 8 each, specifyi...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_description(dsc): """ Parse the given string into a hash. The string format is `key: value`, where key gets converted to upper case and value extends until a new line. A special last field `Abstract:` extends until the end of string. """ meta, abstract = re.split('a...
bigcode/self-oss-instruct-sc2-concepts
def decode(packet): """ https://raw.githubusercontent.com/telldus/telldus/master/telldus-core/service/ProtocolOregon.cpp >>> decode(dict(data=0x201F242450443BDD, model=6701))["data"]["temp"] 24.2 >>> decode(dict(data=0x201F242450443BDD, model=6701))["data"]["humidity"] 45.0 """ if pack...
bigcode/self-oss-instruct-sc2-concepts
import codecs def is_ascii_encoding(encoding): """Checks if a given encoding is ASCII.""" try: return codecs.lookup(encoding).name == "ascii" except LookupError: return False
bigcode/self-oss-instruct-sc2-concepts
def _find_idx_without_numerical_difference(df, column1, column2, delta, idx=None, equal_nan=False): """ Returns indices which have bigger numerical difference than delta. INPUT: **df** (DataFrame) **column1** (str) - name of first column within df to compare. The values of df[c...
bigcode/self-oss-instruct-sc2-concepts
def getDomainOnly(url): """Return the domain out from a url url = the url """ # print ("getDomainOnly : ", url) tmp = url.split('.')[-2] + '.' + url.split('.')[-1] tmp = tmp.split('/')[0] return tmp
bigcode/self-oss-instruct-sc2-concepts
import time def sb_session_login(sb_session, sb_username, sb_password=None): """ login in to sb session using the input credentials. Checks to see if you are already logged in. If no password is given, the password will be requested through the command prompt. .. note:: iPython shells will echo...
bigcode/self-oss-instruct-sc2-concepts
def subroutine_type(name): """Returns type of subroutine, 'setup' or 'teardown' if it has either of those names, or module setup or teardown, otherwise None.""" lowername = name.lower() if lowername == 'setup': subtype = 'global setup' elif lowername == 'teardown': subtype = 'global ...
bigcode/self-oss-instruct-sc2-concepts
def permutation(s): """ @s: list of elements, eg: [1,2,3] return: list of permutations, eg: [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]] """ ret = [] length = len(s) if length == 0: return ret if length == 1: return [s] curr = s[0] for prev in permutat...
bigcode/self-oss-instruct-sc2-concepts
import torch def rot90(input_, k=1, axes=(0, 1)): """Wrapper of `torch.rot90` Parameters ---------- input_ : DTensor Input dense tensor. k : int, optional Number of rotation times, by default 1 axes : tuple, optional The axes in which the input is rotated, by default (...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_optimizer(model, learning_rate, optimizer_state_dict=None, verbose=False): """ Returns an ADAM optimizer attached to the given model (and stored on the same device). If optimizer_state_dict is not None, it will fill in the optimizer state. However, learning_rate will override ...
bigcode/self-oss-instruct-sc2-concepts
def inc(x): """ Returns a number one greater than num. """ return x + 1
bigcode/self-oss-instruct-sc2-concepts
import requests def get_latest_release_from_pypi(*, package: str) -> str: """Get the latest release of a package on pypi""" response = requests.get(f"https://pypi.org/pypi/{package}/json").json() return response["info"]["version"]
bigcode/self-oss-instruct-sc2-concepts
def filter_to_sentry(event, hint): """filter_to_sentry is used for filtering what to return or manipulating the exception before sending it off to Sentry (sentry.io) The 'extra' keyword is part of the LogRecord object's dictionary and is where the flag for sending to Sentry is set. Example...
bigcode/self-oss-instruct-sc2-concepts
def _capture_callback(x): """Validate the passed options for capturing output.""" if x in [None, "None", "none"]: x = None elif x in ["fd", "no", "sys", "tee-sys"]: pass else: raise ValueError("'capture' can only be one of ['fd', 'no', 'sys', 'tee-sys'].") return x
bigcode/self-oss-instruct-sc2-concepts
def get_new_sol_file(test_nr): """ Get name of new solution file """ return "test/{0}-new.sol".format(test_nr)
bigcode/self-oss-instruct-sc2-concepts
import re def unwrap_wrapped_text(text): """ Unwraps multi-line strings, but keeps paragraphs separated by two or more newlines separated by newlines. """ result = [] _re_indentation = re.compile(r'^[ \t]*|[ \t]*$', re.MULTILINE) for paragraph in re.split(r'\n{2,}', text): paragraph = ...
bigcode/self-oss-instruct-sc2-concepts
def test_hindcast_verify_brier_logical(hindcast_recon_1d_ym): """Test that a probabilistic score requiring a binary observations and probability initialized inputs gives the same results whether passing logical as kwarg or mapping logical before for hindcast.verify().""" he = hindcast_recon_1d_ym d...
bigcode/self-oss-instruct-sc2-concepts
import re def could_be_content_page(url: str) -> bool: """ Try to guess if the link is a content page. It's not a perfect check, but it can identify URLs that are obviously not content. """ url = url.lower().rstrip('/') if url.endswith('/signin') or url.endswith('/login') or \ url....
bigcode/self-oss-instruct-sc2-concepts
def collide_rect(sprite1, sprite2): """ **pyj2d.sprite.collide_rect** Check if the rects of the two sprites intersect. Can be used as spritecollide callback function. """ return sprite1.rect.intersects(sprite2.rect)
bigcode/self-oss-instruct-sc2-concepts
def compute_image_data_statistics(data_loader): """ Return the channel wise mean and std deviation for images loaded by `data_loader` (loads WebDataset defined in `datasets.py`) """ mean = 0. std = 0. n_samples = 0. for images, bboxes, labels in data_loader: batch_samples = images.s...
bigcode/self-oss-instruct-sc2-concepts
def int_to_roman(n): """ Convert an integer to its standard Roman Numeral representation """ V = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] S = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] out = "" for val,sym in zip(V,S): while n >= v...
bigcode/self-oss-instruct-sc2-concepts
def _get_module_ver_hash(prov): """Get module commit hash, falling back to semantic version, and finally 'UNKNOWN'""" ver = None subacts = prov[0].get('subactions') if subacts: ver = subacts[0].get('commit') if not ver: ver = prov[0].get('service_ver', 'UNKNOWN') return ver
bigcode/self-oss-instruct-sc2-concepts
def get_nominal_conc(df, species): """ Get the nominal hector concentration for a given species Parameters ---------- df : Pandas DataFrame DataFrame containing output from a nominal hector run species : str Species to retrieve output for Return ------ speci...
bigcode/self-oss-instruct-sc2-concepts
def gpib_control_ren(library, session, mode): """Controls the state of the GPIB Remote Enable (REN) interface line, and optionally the remote/local state of the device. Corresponds to viGpibControlREN function of the VISA library. :param library: the visa library wrapped by ctypes. :param session:...
bigcode/self-oss-instruct-sc2-concepts
def truncate(string: str, width: int, ending: str = "...") -> str: """Truncate string to be no longer than provided width. When truncated, add add `ending` to shortened string as indication of truncation. Parameters ---------- string: str String to be truncated. width: int Maxim...
bigcode/self-oss-instruct-sc2-concepts
def split_ver_str(ver_str): """Split version string into numeric components. Return list of components as numbers additionally checking that all components are correct (i.e. can be converted to numbers). """ ver_list = [] for c in ver_str.split('.')[0:3]: if not c.isdecimal(): ...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_first_idx(numel_per_tensor): """Returns the first indices of each tensor in the :ref:`packed tensor <packed>`. See :ref:`first_idx definition <packed_first_idx>` for more information. Args: numel_per_tensor (torch.LongTensor): The number of elements (vertices, fa...
bigcode/self-oss-instruct-sc2-concepts
def shipping_charge(method, basket, postcode): """ Template tag for calculating the shipping charge for a given shipping method and basket, and injecting it into the template context. """ return method.calculate(basket, postcode)
bigcode/self-oss-instruct-sc2-concepts
import re def _re_compile(regex): """Compile a string to regex, I and UNICODE.""" return re.compile(regex, re.I | re.UNICODE)
bigcode/self-oss-instruct-sc2-concepts
from io import StringIO def df_to_csv_string(df): """Converts pandas DataFrame to a CSV string.""" out = StringIO() df.to_csv(out, encoding='utf-8') return out.getvalue()
bigcode/self-oss-instruct-sc2-concepts
def left_shift(number, n): """ Left shift on 10 base number. Parameters ---------- number : integer the number to be shift n : integer the number of digit to shift Returns ------- shifted number : integer the number left shifted by n digit Examples ...
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_distance(location1, location2): """ Calculates the distance between two pairs of lat, long coordinates using the Haversine formula Inputs: location1 - [lat, lon] array with first location location2 - [lat, lon] array with second location Outputs: ...
bigcode/self-oss-instruct-sc2-concepts
import re def rmsp(s): """Replace multiple spaces with one. """ return re.sub(r"\ +", ' ', s.strip())
bigcode/self-oss-instruct-sc2-concepts
def ir(some_value): """ Rounds and casts to int Useful for pixel values that cannot be floats Parameters ---------- some_value : float numeric value Returns -------- Rounded integer Raises ------ ValueError for non scalar types """ return int(round(so...
bigcode/self-oss-instruct-sc2-concepts
def decibels_to_amplitude_ratio(decibels): """The ratio between two amplitudes given a decibel change""" return 2 ** (decibels/10)
bigcode/self-oss-instruct-sc2-concepts
import requests def get_stock_data(symbol, token): """Send a request to the API with the symbol and token. Return the stock data we want: Symbol, Company Name, Current Price""" url = f"https://cloud.iexapis.com/stable/stock/{symbol}/quote?token={token}" response = requests.get(url) if response.st...
bigcode/self-oss-instruct-sc2-concepts
def handle_exhibition_desc(company: str, desc: str) -> str: """ Handles exhibition description special formatting needs. Returns the updated description. :param company: company name :param desc: company description """ if company.lower() == "mathworks": desc = desc.replace(" o ", "\...
bigcode/self-oss-instruct-sc2-concepts
import click def soft_nprocs(soft, nprocs): """Reduce the number of ranks to the largest acceptable soft value""" # If no soft specification given, use -n value if not soft: return nprocs # Filter to values between 1 and nprocs try: return max([x for x in soft if 0 < x <= nprocs])...
bigcode/self-oss-instruct-sc2-concepts
def _IsOverlapping(alert_entity, start, end): """Whether |alert_entity| overlaps with |start| and |end| revision range.""" return (alert_entity.start_revision <= end and alert_entity.end_revision >= start)
bigcode/self-oss-instruct-sc2-concepts
import torch def GTA_prop_to_hot(img, n_classes: int, width: int, height: int): """ This function turns the output of the network (given in probability format) into the most likely onehot encoded output. Args: img (tensor): The tensor with probabilities. n_classes (int): Amount of cla...
bigcode/self-oss-instruct-sc2-concepts
import math def polar2cart(r, x0, y0, theta): """Changes polar coordinates to cartesian coordinate system. :param r: Radius :param x0: x coordinate of the origin :param y0: y coordinate of the origin :param theta: Angle :return: Cartesian coordinates :rtype: tuple (int, int) """ x...
bigcode/self-oss-instruct-sc2-concepts
def binary_search(query, array): """ Determine whether the query is in an sorted array. Return the index of the query if it is present in the array. If the query is not in the array, return -1 >>> binary_search(4, [1, 2, 3, 4, 5, 6, 7, 8, 9]) 3 >>> binary_search(8, [1, 2, 3, 4, 5, 6, 7, 8, 9...
bigcode/self-oss-instruct-sc2-concepts
import torch def calculate_output_dim(net, input_shape): """Calculates the resulting output shape for a given input shape and network. Args: net (torch.nn.Module): The network which you want to calculate the output dimension for. input_shape (int | tuple[int]): The shape of the in...
bigcode/self-oss-instruct-sc2-concepts
def markdown_escape_filter(text): """Escape special characters in Markdown.""" return text.replace("\\", "\\\\").replace("`", "\\`").replace( "*", "\\*").replace("_", "\\_").replace("{", "\\{").replace( "}", "\\}").replace("[", "\\[").replace("]", "\\]").replace( "(", "\\(")....
bigcode/self-oss-instruct-sc2-concepts
def thousands_separator(value): """ 千位分隔符 例如传入 1000000000,返回 1,000,000,000 :param value: 需要转换的数字 :return: 格式化后的字符串 """ return '{:,}'.format(value)
bigcode/self-oss-instruct-sc2-concepts
from typing import List import math def equal_split(s: str, width: int) -> List[str]: """ Split the string, each split has length `width` except the last one. """ num = int(math.ceil(len(s) / width)) # python3 return [s[i * width: (i + 1) * width] for i in range(num)]
bigcode/self-oss-instruct-sc2-concepts
def prob1(l): """Accept a list 'l' of numbers as input and return a list with the minimum, maximum, and average of the original list. """ ans = [] ans.append(min(l)) ans.append(max(l)) ans.append(float(sum(l))/len(l)) return ans
bigcode/self-oss-instruct-sc2-concepts
def get_ns_name(uri): """ Get the namespace (the namespace is placed before the first '#' character or the last '/' character) """ hash_index = uri.find('#') index = hash_index if hash_index != -1 else uri.rfind('/') namespace = uri[0: index + 1] return namespace
bigcode/self-oss-instruct-sc2-concepts
import struct def pack_date(date): """ Packs a date (assumed to be UTC) as a struct with of 16-bit, unsigned `year` (big endian), 1 byte `month`, and 1 byte `day`. """ return struct.pack("!HBB", date.year, date.month, date.day)
bigcode/self-oss-instruct-sc2-concepts
from typing import Set def allocate_mid(mids: Set[str]) -> str: """ Allocate a MID which has not been used yet. """ i = 0 while True: mid = str(i) if mid not in mids: mids.add(mid) return mid i += 1
bigcode/self-oss-instruct-sc2-concepts
def _xor(a,b): """Return true iff exactly one of and b are true. Used to check some conditions.""" return bool(a) ^ bool(b)
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import get_args from typing import get_origin from typing import Literal def is_str_literal(hint: Any) -> bool: """Check if a type hint is Literal[str].""" args = get_args(hint) origin = get_origin(hint) if origin is not Literal: return False if not len...
bigcode/self-oss-instruct-sc2-concepts
def get_pitch_at_time(genotype, time): """given genotype and durk time point, returns pitch being played at that durk point and whether or not pitch ends perfectly on time Args: genotype ((int, int)[]): genotype of chromosome, which is list of (pitch, dur) time (int): time point in durks ...
bigcode/self-oss-instruct-sc2-concepts
def _get_source_files(commands): """Return a list of all source files in the compilation.""" return list(commands.keys())
bigcode/self-oss-instruct-sc2-concepts
def dnode(period): """ Orbit nodal precession on each rev. Orbits below GEO move (drift) Westerly while orbits above GEO move Easterly. Orbits at GEO are stationary, 0 deg drift. Use siderial day rotation for better accuracy. Arg: period [sec] Return: node precession (dn) [deg] """ ...
bigcode/self-oss-instruct-sc2-concepts
def process_search_term(lookup): """ Removes any whitespace from the search string, and replaces them with the appropriate character to pass as a URL :param lookup: :return: lookup """ lookup = lookup.replace(" ", "+") return lookup
bigcode/self-oss-instruct-sc2-concepts
import torch def check_gpu(gpu): """ Fuction takes one argument as boolean and provides support for gpu or cpu selection and print out the current device being used. Command Line Arguments: 1. GPU as True value that enables GPU support and use cuda for calculation, and False to enable CPU. Functio...
bigcode/self-oss-instruct-sc2-concepts
import csv import re def load_peptides(input_file, peptide_column, column_separator): """ Parses the input file and extracts all peptides occuring within the file. Peptide strings are cleaned (only valid characters retained) and returned as a set. :param input_file: The file to parse :param pepti...
bigcode/self-oss-instruct-sc2-concepts
def input_prompt(prompt): """ Get user input """ return input(prompt)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def alphabetical_binary_search(sorted_list: List, search_name: str) -> int: """Alphabetical binary search (for study purpuses) Args: sorted_list (List): A list of names (must be ordered) search_name (str): name to search Returns: int: found index or -1 ...
bigcode/self-oss-instruct-sc2-concepts
import torch def compute_loss(inputs, outputs, criterion, edge_criterion): """Compute loss automatically based on what the model output dict contains. 'doc_logits' -> document-label CE loss 'para_logits' -> paragraph-label CE loss 'pare_edge_weights' -> additional edge CE loss """ if 'para_log...
bigcode/self-oss-instruct-sc2-concepts
import base64 def decode_base64(input_string: str) -> bytes: """Decode an unpadded standard or urlsafe base64 string to bytes.""" input_bytes = input_string.encode("ascii") input_len = len(input_bytes) padding = b"=" * (3 - ((input_len + 3) % 4)) # Passing altchars here allows decoding both stan...
bigcode/self-oss-instruct-sc2-concepts
def normalize_extension(extension): """ Normalize extension Converts given extension to canonical format for storage :param extension: original extension :return: normalized extension """ extension = extension.lower() exts = dict() exts['jpg'] = ['jpeg','jpe','jif','jfif','jfi''jp2'...
bigcode/self-oss-instruct-sc2-concepts
def parseTrackLog(line): """Parse trackLog line and return important fields: db, year, month, hgsid, and a list of tracks""" #### Sample line being processed #### # [Sun Mar 05 04:11:27 2017] [error] [client ###.###.###.##] trackLog 0 hg38 hgsid_### cytoBandIdeo:1,cloneEndCTD:2 #### spli...
bigcode/self-oss-instruct-sc2-concepts
import re def getWords(text): """From a text input as a string, get the words separated by a space and return it as a list of strings""" return re.compile('\w+').findall(text)
bigcode/self-oss-instruct-sc2-concepts
def sqdist(point1, point2, rotmat): """ This routine calculates the anisotropic distance between two points given the coordinates of each point and a definition of the anisotropy. This method only consider a single anisotropy senario. Parameters ---------- point1 : tuple Coordi...
bigcode/self-oss-instruct-sc2-concepts
def _is_path_within_scope(scope, fullpath): """Check whether the given `fullpath` is within the given `scope`""" if scope == '/': return fullpath is not None fullpath = fullpath.lstrip('/') if fullpath else '' scope = scope.strip('/') return (fullpath + '/').startswith(scope + '/')
bigcode/self-oss-instruct-sc2-concepts
def age_interp(request): """Fixture for age_interp flag.""" return request.param
bigcode/self-oss-instruct-sc2-concepts
def avoids(word, forbidden): """ Predicate that asks whether word avoids letters in the forbidden string """ # Feels like there should be a more efficient way to do this using # set intersection, but I'll just check the word character by character for letter in forbidden: if word.find(letter...
bigcode/self-oss-instruct-sc2-concepts
def get_vocabulary(path_to_vocab): """ Return a list of prefixes defining the vocabulary. """ vocab = [] with open(path_to_vocab) as f: for line in f: line = line.rstrip() vocab.append(line) return vocab
bigcode/self-oss-instruct-sc2-concepts
def b_delta(rewards,states,alpha): """ Implements the Resorla-Wagner (delta) learning rule. V_intial is 0. Note: Null (0 or '0') states are silently skipped. Returns two dictionaries containing value and RPE timecourses, for each state. """ # Init s_names = set(states) V_dict...
bigcode/self-oss-instruct-sc2-concepts
def get_weight_shapes(num_inputs, layer_sizes, num_outputs): """ adapted from original tf_model.get_weight_shapes() to convert from method to function """ weight_shapes = [] input_size = num_inputs for i, layer in enumerate(layer_sizes): weight_shapes.append((input_size, layer)) weight_shapes.append((layer,...
bigcode/self-oss-instruct-sc2-concepts
import warnings def format_channel_id(ch): """ Function for formatting an `idelib.dataset.Channel` or `SubChannel` for display. Renders as only the channel and subchannel IDs (the other information is shown in the rest of the table). :param ch: The `idelib.dataset.Channel` or `idelib.data...
bigcode/self-oss-instruct-sc2-concepts
def _IsBold(weight): """Is this weight considered bold? Per Dave C, only 700 will be considered bold. Args: weight: Font weight. Returns: True if weight is considered bold, otherwise False. """ return weight == 700
bigcode/self-oss-instruct-sc2-concepts
def add_attributes(rsrc_id, manifest): """Add additional attributes to the manifest.""" proid = rsrc_id[0:rsrc_id.find('.')] environment = 'prod' updated = { 'proid': proid, 'environment': environment } updated.update(manifest) return updated
bigcode/self-oss-instruct-sc2-concepts
def setup_walkers(cfg_emcee, params, level=0.1): """Initialize walkers for emcee. Parameters ---------- cfg_emcee: dict Configuration parameters for emcee. params: asap.Parameter object Object for model parameters. level: float, optional Returns ------- ini_position...
bigcode/self-oss-instruct-sc2-concepts
def pack_4_4(x: int, y: int) -> int: """Pack two 4-bit values into an 8-bit value. x and y must be in range 0..15 inclusive. Result is in range 0..255 inclusive. """ assert 0 <= x <= 15 assert 0 <= y <= 15 return (x << 4) | y
bigcode/self-oss-instruct-sc2-concepts
def _GetLibMetadata(layer): """ Return a dictionary of library-specific data found in layer.""" globalPrim = layer.GetPrimAtPath('/GLOBAL') if not globalPrim: raise Exception("Code generation requires a \"/GLOBAL\" prim with " "customData to define at least libraryName. GLOBAL prim ...
bigcode/self-oss-instruct-sc2-concepts
def build_system_info(platform=None, platform_type=None, accel_type=None, cpu_cores=None, cpu_type=None, cpu_sockets=None): """Information about the system the test was executed on. Args: platform (str...
bigcode/self-oss-instruct-sc2-concepts
import re def strip_spaces(string): """Remove white-space from a string Parameters ---------- string: str Returns ------- str """ pattern = re.compile(r'\s+') return re.sub(pattern, '', string)
bigcode/self-oss-instruct-sc2-concepts
def hexint_parser(arg: str) -> int: """Parse a hexadecimal starting with 0x into an integer.""" if not arg.startswith("0x"): raise Exception("Received non-hex integer where hex expected") return int(arg, 16)
bigcode/self-oss-instruct-sc2-concepts
def orbtell(orb): """Query current connection read-head position""" return orb.tell()
bigcode/self-oss-instruct-sc2-concepts
import random def random_bbox(config): """Generate a random tlhw with configuration. Args: config: Config should have configuration including IMG_SHAPES, VERTICAL_MARGIN, HEIGHT, HORIZONTAL_MARGIN, WIDTH. Returns: tuple: (top, left, height, width) """ img_shape = config...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def from_epoch(seconds): """Given seconds since epoch, return a datetime object Args: seconds: Seconds since epoch Returns: datetime representation of seconds since epoch """ return datetime.utcfromtimestamp(float(seconds))
bigcode/self-oss-instruct-sc2-concepts
def _word_feats(words): """ NLTK word feature generator for the NaiveBayesClassifier """ return dict([(word, True) for word in words])
bigcode/self-oss-instruct-sc2-concepts
def build_machine(network=None, machine_type=None, preemptible=None, service_account=None, boot_disk_size_gb=None, disks=None, accelerators=None, labels=None, cpu_platform=None...
bigcode/self-oss-instruct-sc2-concepts
def copy_event_attributes(ev1, ev2): """Copy all attributes from one roxar event to another. Args: ev1: roxar event to copy into ev2: roxar event to copy attributes from Returns: An updated version of ev1. Unaltered if the two events are not of same type. """ if ev1.type == e...
bigcode/self-oss-instruct-sc2-concepts
def group_by(object_list, key_function): """ Return dictionary of objects grouped by keys returned by `key_function` for each element in `object_list`. `object_list` does not need to be sorted. >>> group_by([1, 2, 3, 4, 5], lambda x: x % 2) {0: [2, 4], 1: [1, 3, 5]} """ groups = dict()...
bigcode/self-oss-instruct-sc2-concepts
def mass_hpa_tail_boom( length_tail_boom, dynamic_pressure_at_manuever_speed, mean_tail_surface_area, ): """ Finds the mass of a tail boom structure of a human powered aircraft (HPA), following Juan Cruz's correlations in http://journals.sfu.ca/ts/index.php/ts/article/viewFile/760/71...
bigcode/self-oss-instruct-sc2-concepts
def find_first2(l, pred1, pred2): """ Find first occurrence in list satisfying two-step predicate. :param l: list. :param pred1: predicate on the list elements. :param pred2: predicate on two list elements. :return: index of first occurrence in list satisfying pred2(l[index-1], l[index]) or ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def meta_from_pid(product_id): """Extract metadata contained in a Landsat Product Identifier.""" meta = {} parts = product_id.split("_") meta["product_id"] = product_id meta["sensor"], meta["correction"] = parts[0], parts[1] meta["path"], meta["row"] = int(parts[2...
bigcode/self-oss-instruct-sc2-concepts
import requests def check_status(datum): """Check that both the url and image link are valid URLs and that the image link isn't just a redirect. """ if requests.get(datum["url"], verify=False).status_code != 200: return False get_ = requests.get(datum["image"], verify=False) if get_.st...
bigcode/self-oss-instruct-sc2-concepts
def recursive_find_xml_element( xmlnode, name, _nodes=None ): """ recursively finds all XML sub-elements with the name 'name', such as for nd in recursive_find_xml_element( xmlnode, 'TestList' ): pass """ if _nodes == None: _nodes = [] for nd in xmlnode: if nd.t...
bigcode/self-oss-instruct-sc2-concepts