seed
stringlengths
1
14k
source
stringclasses
2 values
def stations_by_river(stations): """Returns a dictionary mapping the names of rivers with a list of their monitoring stations""" # Creates a dictionary of rivers that map to a list of their monitoring stations rivers = dict() for station in stations: # Adds names of monitoring stations into the...
bigcode/self-oss-instruct-sc2-concepts
def create_field_matching_dict(airtable_records, value_field, key_field = None, swap_pairs = False): """Uses airtable_download() output to create a dictionary that matches field values from the same record together. Useful for keeping track of relational data. If second_field is `None`, then the dictio...
bigcode/self-oss-instruct-sc2-concepts
def gen_rect(t, b, l, r): """ :param t: top latitude :param b: bottom latitude :param l: left longitude :param r: right longitude :return: GeoJSON rect with specified borders """ ret = { 'type': 'Feature', 'properties': {}, 'geometry': { 'type': 'Polyg...
bigcode/self-oss-instruct-sc2-concepts
import copy def exact_to_1st_order_model(model): """Convert model training on exact augmented objective to model training on 1st order approximation. """ model_1st = copy.deepcopy(model) model_1st.approx = True model_1st.feature_avg = True model_1st.regularization = False return model_...
bigcode/self-oss-instruct-sc2-concepts
def kmp(S): """Runs the Knuth-Morris-Pratt algorithm on S. Returns a table F such that F[i] is the longest proper suffix of S[0...i] that is also a prefix of S[0...i]. """ n = len(S) if n == 0: return [] F = [0] * n for i in range(1, n): k = F[i - 1] while k ...
bigcode/self-oss-instruct-sc2-concepts
def quat_real(quaternion): """Return real part of quaternion. >>> quat_real([3, 0, 1, 2]) 3.0 """ return float(quaternion[0])
bigcode/self-oss-instruct-sc2-concepts
def calc_plan(plan, beam_set, norm): """Calculate and normalize treatment plan. Parameters ---------- plan : connect.connect_cpython.PyScriptObject Current treatment plan. beam_set : connect.connect_cpython.PyScriptObject Current beam set. norm : (str, float, float) Regi...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha256sum(body): """Get a SHA256 digest from a string.""" h = hashlib.sha256() if body: h.update(body) return h.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import List import pkg_resources def get_version( package_name: str, raise_on_error: bool, alternate_package_names: Optional[List[str]] = None, ) -> Optional[str]: """ :param package_name: The name of the full package, as it would be imported, to get...
bigcode/self-oss-instruct-sc2-concepts
def get_simulation(open_rocket_helper, ork_file_path, i_simulation): """Return the simulation with the given index from the .ork file. :arg open_rocket_helper: Instance of ``orhelper.Helper()`` :raise IndexError: If `i_simulation` is negative or >= the number of simulations in the ...
bigcode/self-oss-instruct-sc2-concepts
def within_time_period(t, time_period): """ Check if time is in the time period Argument: t = given time in format (half, min, sec) time_period = tuple of (start_time, end_time) in format (half, min, sec) Return: boolean """ start_time = time_period[0] end_time = t...
bigcode/self-oss-instruct-sc2-concepts
def compute_agreement_score(arcs1, arcs2, method, average): """Agreement score between two dependency structures Parameters ---------- arcs1: list[(int, int, str)] arcs2: list[(int, int, str)] method: str average: bool Returns ------- float """ assert len(arcs1) == len(...
bigcode/self-oss-instruct-sc2-concepts
def read_image(file_path): """ Read an image file """ with open(file_path, "rb") as ifile: return ifile.read()
bigcode/self-oss-instruct-sc2-concepts
def manhattan_distance(params): """ Manhattan distance from current position to target Args: current (tuple): x, y coordinates of the current position target (tuple): x, y coordinates of the target Returns: (float): Manhattan distance from current position to target """ current, target, solution = par...
bigcode/self-oss-instruct-sc2-concepts
def row_normalize(x): """ Scale a matrix such that each row sums to one """ return x / x.sum(axis=1)[:, None]
bigcode/self-oss-instruct-sc2-concepts
import re def error_has_gloss(value): """Checks if the value has at least a hyphen followed by two capital letters""" return bool(re.match(r'.*\-[A-Z]{2,}', value))
bigcode/self-oss-instruct-sc2-concepts
def argmin(arr, f): """Return the index, i, in arr that minimizes f(arr[i])""" m = None i = None for idx, item in enumerate(arr): if item is not None: if m is None or f(item) < m: m = f(item) i = idx return i
bigcode/self-oss-instruct-sc2-concepts
def divide_toward_zero(x, y): """Divides `x` by `y`, rounding the result towards zero. The division is performed without any floating point calculations. For exmaple: divide_toward_zero(2, 2) == 1 divide_toward_zero(1, 2) == 0 divide_toward_zero(0, 2) == 0 divide_toward_ze...
bigcode/self-oss-instruct-sc2-concepts
def comma_join(fields): """ Converts everything in the list to strings and then joins them with commas. """ return ",".join(map(str, fields))
bigcode/self-oss-instruct-sc2-concepts
def sort_x_by_y(x, y): """Sort the iterable x by the order of iterable y""" x = [x for (_, x) in sorted(zip(y, x))] return x
bigcode/self-oss-instruct-sc2-concepts
import psycopg2 def _execute_psyco(command, **kwargs): """ executes a postgres commandline through psycopg2 :param command: A psql command line as a str :param kwargs: will be forwarded to psycopg2.connect """ # Note: Ubuntu 18.04 uses "peer" as the default postgres configuration # which...
bigcode/self-oss-instruct-sc2-concepts
def pair(s1, s2, track_id_pairs): """Returns pairs of tracks, i.e., tracks that can be compared. s1 -- all tracks of sensor 1. s2 -- all tracks of sensor 2. track_id_pairs -- ID pairs of tracks of s1 and s2. """ pairs = [] # collect available ids of the sensor's tracks for tid1, tid2 i...
bigcode/self-oss-instruct-sc2-concepts
import functools def lsp_rpc(f): """A decorator for LanguageServerProtocol-methods. This wrapper filters out calls that are made before initializing the server and after shutdown and returns an error message instead. This decorator should only be used on methods of LanguageServerProtocol-objects a...
bigcode/self-oss-instruct-sc2-concepts
import json from typing import OrderedDict def validate_payload(payload): """Validate that the payload is of type OrderedDict. If the payload is of type str, then it assumes that the string is able to be parsed via json. Args: payload (str or OrderedDict): Payload object Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def clean_cluster_seq_id(id): """Returns a cleaned cd-hit sequence id The cluster file has sequence ids in the form of: >some_id... """ return id[1:-3]
bigcode/self-oss-instruct-sc2-concepts
def longVal(x): """ longVal(x): if 'x' is a z3 constant (i.e. function of arity 0) whose value is an integer, then return that integer as a python long else return 'None'""" if(hasattr(x, 'as_long')): return x.as_long() elif(hasattr(x, 'numerator_as_long')): if(x.de...
bigcode/self-oss-instruct-sc2-concepts
def bytes_to_str(bytes, base=2, precision=0): """Convert number of bytes to a human-readable format Arguments: bytes -- number of bytes base -- base 2 'regular' multiplexer, or base 10 'storage' multiplexer precision -- number of decimal places to output Returns: Human-readable string such...
bigcode/self-oss-instruct-sc2-concepts
import textwrap def _wrap(content, indent_level): """wrap multiple lines keeping the indentation""" indent = ' ' * indent_level wrap_opt = { 'initial_indent': indent, 'subsequent_indent': indent, } lines = [] for paragraph in content.splitlines(): if not paragraph: ...
bigcode/self-oss-instruct-sc2-concepts
def fwd_slash(file_path): """Ensure that all slashes are '/' Args: file_path (st|Path): The path to force '/' Returns: (str): Formatted path """ return str(file_path).replace("\\", "/")
bigcode/self-oss-instruct-sc2-concepts
def flatten_sub(sub, game_id): """Flatten the schema of a sub""" sub_id = sub[0] sub_data = sub[1] return {'game_id': game_id, 'sub_id': sub_id, 'sub_type': sub_data['type'], 'time_of_event(min)': (sub_data['t']['m'] + (sub_data['t']['s'] / 60 )), 'team_i...
bigcode/self-oss-instruct-sc2-concepts
def remove_by_idxs(ls, idxs): """Remove list of indexes from a target list at the same time""" return [i for j, i in enumerate(ls) if j not in idxs]
bigcode/self-oss-instruct-sc2-concepts
def gcd(a, b): """ Find GCD(a, b).""" # GCD(a, b) = GCD(b, a mod b). while b != 0: # Calculate the remainder. remainder = a % b # Calculate GCD(b, remainder). a = b b = remainder # GCD(a, 0) is a. return a
bigcode/self-oss-instruct-sc2-concepts
def _max_factor(n, factor, max_size): """ Return the largest factor within the provided max; e.g., the most images of size n thet can fit in max_size """ if max_size is None or n * factor <= max_size: return factor return max_size // n
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import math def get_new_coordinates(curr_x: float, curr_y: float, angle: float, speed: float) -> Tuple[float, float]: """ Works out the next x, y coordinate given the current coordinate, an angle (from the x axis in radians) and the speed (i.e distance of travel). :param curr...
bigcode/self-oss-instruct-sc2-concepts
def move(cm, from_start, from_end, insert_pos): """ Move rows from_start - from_end to insert_pos in-place. Examples -------- >>> cm = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 0, 1], [2, 3, 4, 5]]) >>> move(cm, 1, 2, 0) array([[5, 6, 4, 7], [9, 0, 8, 1], [1, 2, 0, ...
bigcode/self-oss-instruct-sc2-concepts
def evaluate_training_result(env, agent): """ Evaluates the performance of the current DQN agent by using it to play a few episodes of the game and then calculates the average reward it gets. The higher the average reward is the better the DQN agent performs. :param env: the game environment :p...
bigcode/self-oss-instruct-sc2-concepts
import re def checkBadFormat(pattern, id): """ Returns False if the format looks okay, True if it's not a match """ if (id == id): if re.match(pattern, id): return(False) else: return(True)
bigcode/self-oss-instruct-sc2-concepts
def always_https(url): """ ensures that urls are always using HTTPS :param url: An URL (as string) :type url: str :return: The passed in URL with HTTPS :rtrype: str """ if not url.startswith('http'): return url elif url.startswith('https'): return url else: ...
bigcode/self-oss-instruct-sc2-concepts
def get_default_living(rows, cols): """If number of intitial living cells is not specified for the game, calculate as a function of grid size.""" return round((rows * cols) / 4)
bigcode/self-oss-instruct-sc2-concepts
def convert_temperature(val, old_scale="fahrenheit", new_scale="celsius"): """ Convert from a temperatuure scale to another one among Celsius, Kelvin and Fahrenheit. Parameters ---------- val: float or int Value of the temperature to be converted expressed in the original scale....
bigcode/self-oss-instruct-sc2-concepts
def percent(num, div, prec=2): """ Returns the percentage of num/div as float Args: num (int): numerator div (int): divisor prec (None, int): rounding precision Returns: p (float) p = 100 * num/div """ num = float(num) div = float(div) if div...
bigcode/self-oss-instruct-sc2-concepts
def slurp(path): """Returns the contents of the file at the given path.""" f = None try: f = open(path) return f.read() finally: if f: f.close()
bigcode/self-oss-instruct-sc2-concepts
def get_paralogs_data(paral_file): """Extract paralogous projections.""" if paral_file is None: return set() paral_proj = [] with open(paral_file, "r") as f: paral_proj = set(x.rstrip() for x in f.readlines()) return paral_proj
bigcode/self-oss-instruct-sc2-concepts
import json import requests def get_onboard_certificates(clearpass_fqdn, access_token, username): """Get all valid certificates (not revoked or expired) for user""" url = "https://{}/api/certificate".format(clearpass_fqdn) queryfilter = {'mdps_user_name': username, 'is_valid':'true'} payload = {'fil...
bigcode/self-oss-instruct-sc2-concepts
import time def generate_stats_table(stats: dict) -> str: """Function to generate md table with questions stats. Args: stats: Stats dict. { "category": { "title" str, "cnt": int, } } Returns: Md...
bigcode/self-oss-instruct-sc2-concepts
def connex(data,K,L): """ Return the list of members of the connex component containing the elements originaly in L. Parameters: ----------- data: pandas dataframe data must contain at least one column named neighbors. K: list The list of members of the connex component so f...
bigcode/self-oss-instruct-sc2-concepts
def get_variant_id(variant_dict): """Build a variant id The variant id is a string made of CHROM_POS_REF_ALT The alt field for svs needs some massage to work downstream. Args: variant_dict (dict): A variant dictionary Returns: v...
bigcode/self-oss-instruct-sc2-concepts
import random def mcpi_samples(n): """ Compute the number of points in the unit circle out of n points. """ count = 0 for i in range(n): x, y = random.random(), random.random() if x*x + y*y <= 1: count += 1 return count
bigcode/self-oss-instruct-sc2-concepts
def batchify(batch): """Gather a batch of individual examples into one batch.""" questions = [ex['question'] for ex in batch] question_tokens = [ex['question_tokens'] for ex in batch] answers = [ex['answer'] for ex in batch] answer_tokens = [ex['answer_tokens'] for ex in batch] if 'answer_tokens' i...
bigcode/self-oss-instruct-sc2-concepts
def lv_unpack(txt): """ Deserializes a string of the length:value format :param txt: The input string :return: a list og values """ txt = txt.strip() res = [] while txt: l, v = txt.split(":", 1) res.append(v[: int(l)]) txt = v[int(l):] return res
bigcode/self-oss-instruct-sc2-concepts
def tmp_data_directory(tmp_path_factory): """Creates temporary directory and returns its path. """ return str(tmp_path_factory.mktemp("getdera"))
bigcode/self-oss-instruct-sc2-concepts
def _Mabove(dat, surf_th): """Return total gas mass above threshold density surf_th.""" surf = dat.surf M = surf.where(surf>surf_th).sum()*dat.domain['dx'][0]*dat.domain['dx'][1] return M.values[()]
bigcode/self-oss-instruct-sc2-concepts
import string import operator def getFisrtCharThatAppearsOnce(myString): """ Get the first char that appears once in the provided string. Only alphabetic chars are considered. """ myString = "".join(myString.lower().split()) charDict = {key:[0, 0] for key in string.ascii_lowercase} for pos, char i...
bigcode/self-oss-instruct-sc2-concepts
def _strip_quotes(str_q): """ Helper function to strip off the ' or " off of a string """ if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q
bigcode/self-oss-instruct-sc2-concepts
def inverse2d(a): """ Returns the matrix inverse of 2x2 matrix "a". :param a: The original 2x2 matrix. :return: Its matrix inverse. """ result = [[0, 0], [0, 0]] det_a = (a[1][1] * a[0][0]) - (a[0][1] * a[1][0]) for a_row in range(len(result)): for a_col in range(len(result[a_...
bigcode/self-oss-instruct-sc2-concepts
def number2binary(v, dynamic_padding=False, padded_length=None): """ Convert an integer value to the equivalent string of 1 and 0 characters. """ s = "" while v: s = [ "0", "1" ][v & 1] + s v >>= 1 if dynamic_padding: w = 4 while w < len(s): w <<= 1 else: ...
bigcode/self-oss-instruct-sc2-concepts
def propset_dict(propset): """Turn a propset list into a dictionary PropSet is an optional attribute on ObjectContent objects that are returned by the VMware API. You can read more about these at: | http://pubs.vmware.com/vsphere-51/index.jsp | #com.vmware.wssdk.apiref.doc/ | vmo...
bigcode/self-oss-instruct-sc2-concepts
def strip_and_split(line): """ Helper function which saves a few lines of code elsewhere :param line: :return: """ line = line.strip().split() stripped_line = [subline.strip() for subline in line] return stripped_line
bigcode/self-oss-instruct-sc2-concepts
import re def first_upper(s): """Capitalizes the first letter, leaves everything else alone""" return re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), s, 1)
bigcode/self-oss-instruct-sc2-concepts
def get_repo_information(repo_obj): """ Using the current repository, we obtain information on the repository, which includes - owner_name - repo_name Requires for there to be a remote named "origin" in the current local repo clone Returns a dict with said values. If it cannot find both, retur...
bigcode/self-oss-instruct-sc2-concepts
import itertools def to_combinations(list_of_objs: list): """ Create array of all combinations of a list of length n of the shape (1, 2, ..., n) :param list_of_objs: :return: Combinations """ combinations = [] for i in range(2, len(list_of_objs)): combinations.extend(itertools.com...
bigcode/self-oss-instruct-sc2-concepts
def fmt(x, pos): """ A utility function to improve the formatting of plot labels """ a, b = '{:.2e}'.format(x).split('e') b = int(b) return r'${} \times 10^{{{}}}$'.format(a, b)
bigcode/self-oss-instruct-sc2-concepts
def is_binary(plist_path): """Checks if a plist is a binary or not.""" result = False with open(plist_path, 'rb') as _f: for _block in _f: if b'\0' in _block: result = True break return result
bigcode/self-oss-instruct-sc2-concepts
def validate_ppoi_tuple(value): """ Validates that a tuple (`value`)... ...has a len of exactly 2 ...both values are floats/ints that are greater-than-or-equal-to 0 AND less-than-or-equal-to 1 """ valid = True while valid is True: if len(value) == 2 and isinstance(value, tuple...
bigcode/self-oss-instruct-sc2-concepts
def dec2dec(dec): """ Convert sexegessimal RA string into a float in degrees. Parameters ---------- dec : str A string separated representing the Dec. Expected format is `[+- ]hh:mm[:ss.s]` Colons can be replaced with any whit space character. Returns ------- de...
bigcode/self-oss-instruct-sc2-concepts
import torch def cosine_similarity(x1, x2): """Calculates cosine similarity of two tensor.""" dist = torch.sum(torch.multiply(x1, x2), dim=-1) dist = dist / (torch.linalg.norm(x1, dim=-1) * torch.linalg.norm(x2, dim=-1)) return dist
bigcode/self-oss-instruct-sc2-concepts
from typing import List def generate_board( row: int, column: int, ) -> List[List[str]]: """ Generate a new board in a row * column manner. Parameters ---------- row: int A number that indicate how many row should be generated. column: int ...
bigcode/self-oss-instruct-sc2-concepts
def cpd_int(p, r, t, n=12): """ Calculate compound interest :param p: (float) - principal :param r: (float) - annual interest rate :param t: (int) - time(years) :param n: (int) - number of times interest is compounded each year :return a: (float) - compound interest """ a = p * (1 + ...
bigcode/self-oss-instruct-sc2-concepts
import re def clean_newline(line): """Cleans string so formatting does not cross lines when joined with \\n. Just looks for unpaired '`' characters, other formatting characters do not seem to be joined across newlines. For reference, discord uses: https://github.com/Khan/simple-markdown/blob/mas...
bigcode/self-oss-instruct-sc2-concepts
def lu_decomposition(matrix_in, q=0): """ LU-Factorization method using Doolittle's Method for solution of linear systems. Decomposes the matrix :math:`A` such that :math:`A = LU`. The input matrix is represented by a list or a tuple. If the input matrix is 1-dimensional, i.e. a list or tuple of integ...
bigcode/self-oss-instruct-sc2-concepts
def count_user_type(data_list): """ Conta os tipos de usuário nos registros de uma lista. Argumentos: data_list: Lista de registros contendo o tipo do usuário em uma das colunas. Retorna: Número de usuários 'Subscriber' e 'Customer', nesta ordem. """ subscriber = 0 customer ...
bigcode/self-oss-instruct-sc2-concepts
def index_api_data(parsed_json, id_field): """Transform a list of dicts into a dict indexed by one of their fields. >>> index_api_data([{'id': 'eggs', 'val1': 42, 'foo': True}, ... {'id': 'spam', 'val1': 1, 'foo': True}], 'id') {'eggs': {'val1': 42, 'foo': True}, 'spam': {'val1': 1,...
bigcode/self-oss-instruct-sc2-concepts
def client_factory(client_cls, dispatcher, settings): """Shared logic to instantiate a configured torque client utility.""" torque_url = settings.get('torque.url') torque_api_key = settings.get('torque.api_key') return client_cls(dispatcher, torque_url, torque_api_key)
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import torch from typing import List def encode_supervisions( supervisions: dict, subsampling_factor: int ) -> Tuple[torch.Tensor, List[str]]: """ Encodes Lhotse's ``batch["supervisions"]`` dict into a pair of torch Tensor, and a list of transcription strings. The supervi...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def fetch_links_from_html(html_doc): """ Given a blob of HTML, this function returns a list of PDF links """ soup = BeautifulSoup(html_doc) pdf_attachments = [] for link in soup.findAll('a'): value = link.get('href') if "http" in value: ...
bigcode/self-oss-instruct-sc2-concepts
import torch def depth_map_to_3d_torch(depth, cam_K, cam_W): """Derive 3D locations of each pixel of a depth map. Args: depth (torch.FloatTensor): tensor of size B x 1 x N x M with depth at every pixel cam_K (torch.FloatTensor): tensor of size B x 3 x 4 representing ca...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def flatten_iterable(its: Iterable, deep: bool = False) -> list: """ flatten instance of Iterable to list Notes: 1. except of str, won't flatten 'abc' to 'a', 'b', 'c' demo: [[[1], [2], [3]], 4] if deep is True: flatten to [1, 2, 3, 4] if deep is Fal...
bigcode/self-oss-instruct-sc2-concepts
def find_frequency_bandwidth(frequency, simulation_parameters): """ Finds the correct bandwidth for a specific frequency from the simulation parameters. """ simulation_parameter = 'channel_bandwidth_{}'.format(frequency) if simulation_parameter not in simulation_parameters.keys(): KeyEr...
bigcode/self-oss-instruct-sc2-concepts
def isLoopClockwise(loop): """Gets if a loop of line segments is clockwise Parameters ---------- loop : List or np array of shape (-1, 2, 2) -1 number of line segments, [startPoint, endPoint], [x,y] Returns ------- bool Note ------- https://stackoverflow.com/questions/...
bigcode/self-oss-instruct-sc2-concepts
def is_smile_inside_face(smile_coords, face_coords): """Function to check if the smile detected is inside a face or not Args: smile_coords (list): list of smaile coordinates of form [x, y, (x+w), (y+h)] face_coords (list): list of face coordinates of form [x, y, (x+w), (y+h)] Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def get_max_drawdown_from_series(r): """Risk Analysis from asset value cumprod way Parameters ---------- r : pandas.Series daily return series """ # mdd = ((r.cumsum() - r.cumsum().cummax()) / (1 + r.cumsum().cummax())).min() mdd = (((1 + r).cumprod() - (1 + r).cumprod().cumma...
bigcode/self-oss-instruct-sc2-concepts
import math def dist_to_line(line, point): """ Finds a point's distance from a line of infinite length. To find a point's distance from a line segment, use dist_to_line_seg instead. line: ((lx0,ly0), (lx1,ly1)) Two points on the line point: (px, py) The point to find the distance from returns: the distance...
bigcode/self-oss-instruct-sc2-concepts
def personal_best(scores): """ Return the highest score in scores. param: list of scores return: highest score in scores """ return max(scores)
bigcode/self-oss-instruct-sc2-concepts
def identify_value_block(block: dict) -> str: """Given a key block, find the ID of the corresponding value block.""" return [x for x in block["Relationships"] if x["Type"] == "VALUE"][0]["Ids"][0]
bigcode/self-oss-instruct-sc2-concepts
import logging def mergeDoc(existing_doc, new_doc): """ existing_doc is merged with new_doc. Returns true/false if existing_doc is modified. """ records = existing_doc.setdefault("records", []) if 'records' not in new_doc: return False isModified = False for new_record in ...
bigcode/self-oss-instruct-sc2-concepts
def convert_mip_type_to_python_type(mip_type: str): """ Converts MIP's types to the relative python class. The "MIP" type that this method is expecting is related to the "sql_type" enumerations contained in the CDEsMetadata. """ type_mapping = { "int": int, "real": float, ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Tuple import math def quaternion_to_euler(quat: Sequence[float]) -> Tuple[float,float,float]: """ Convert WXYZ quaternion to XYZ euler angles, using the same method as MikuMikuDance. Massive thanks and credit to "Isometric" for helping me discover the transformation m...
bigcode/self-oss-instruct-sc2-concepts
import jinja2 def load_jinja( path, file, vrf_name, bandwidth, packet_size, ref_packet_size, time_interval, ipp4_bps, ipp2_bw_percent, ipp0_bw_percent, interface, ): """Use Jinja templates to build the device configuration Args: device (`obj`): Devi...
bigcode/self-oss-instruct-sc2-concepts
async def ladders(database, platform_id): """Get ladders for a platform.""" query = "select id as value, name as label from ladders where platform_id=:platform_id" return list(map(dict, await database.fetch_all(query, values={'platform_id': platform_id})))
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_unique_str(seed: str) -> str: """Generate md5 unique sting hash given init_string.""" return hashlib.md5(seed.encode("utf-8")).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_characters_from_file(file_path: str) -> List[str]: """ Opens the specified file and retrieves a list of characters. Assuming each character is in one line. Characters can have special characters including a space character. Args: file_path (str): path to th...
bigcode/self-oss-instruct-sc2-concepts
def _get_edge(layer_idx_start, layer_idx_end): """ Returns a tuple which is an edge. """ return (str(layer_idx_start), str(layer_idx_end))
bigcode/self-oss-instruct-sc2-concepts
def _fasta_slice(fasta, seqid, start, stop, strand): """ Return slice of fasta, given (seqid, start, stop, strand) """ _strand = 1 if strand == '+' else -1 return fasta.sequence({'chr': seqid, 'start': start, 'stop': stop, \ 'strand': _strand})
bigcode/self-oss-instruct-sc2-concepts
def set_coordinates(atoms, V, title="", decimals=8): """ Print coordinates V with corresponding atoms to stdout in XYZ format. Parameters ---------- atoms : list List of atomic types V : array (N,3) matrix of atomic coordinates title : string (optional) Title of molec...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def strip_leading_underscores_from_keys(d: Dict) -> Dict: """ Clones a dictionary, removing leading underscores from key names. Raises ``ValueError`` if this causes an attribute conflict. """ newdict = {} for k, v in d.items(): if k.startswith('_'): ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Optional from typing import Tuple def split_by(items: List[str], separator: Optional[str] = None) -> Tuple[List[str], List[str]]: """If the separator is present in the list, returns a 2-tuple of - the items before the separator, - all items after the sepa...
bigcode/self-oss-instruct-sc2-concepts
def value_of_ace(hand_value): """ :param hand_value: int - current hand value. :return: int - value of the upcoming ace card (either 1 or 11). """ if hand_value + 11 > 21: value = 1 else: value = 11 return value
bigcode/self-oss-instruct-sc2-concepts
def _parse_ports(ports_text): """ Handle the case where the entry represents a range of ports. Parameters ---------- ports_text: str The text of the given port table entry. Returns ------- tuple A tuple of all ports the text represents. """ ports = p...
bigcode/self-oss-instruct-sc2-concepts
import socket import struct def long2ip(l): """Convert big-endian long representation of IP address to string """ return socket.inet_ntoa(struct.pack("!L", l))
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def get_soup(html): """ Get the Beautiful Soup tree from HTML. """ # return BeautifulSoup(req.content, "html.parser") # return BeautifulSoup(req.text, "html5lib") # Haven't tested this yet return BeautifulSoup(html, "html.parser")
bigcode/self-oss-instruct-sc2-concepts