seed
stringlengths
1
14k
source
stringclasses
2 values
def sample_var_var(std, n): """ The variance of the sample variance of a distribution. Assumes the samples are normally distributed. From: //math.stackexchange.com/q/72975 `std`: Distribution's standard deviation `n`: Number of samples """ return 2.0 * std ** 4 / (n - 1.0)
bigcode/self-oss-instruct-sc2-concepts
import re def is_input(line): """ Determines whether or not a read in line contains an uncommented out \input{} statement. Allows only spaces between start of line and '\input{}'. """ #tex_input_re = r"""^\s*\\input{[^}]*}""" # input only tex_input_re = r"""(^[^\%]*\\input{[^}]*})|(^[^\%]*\\in...
bigcode/self-oss-instruct-sc2-concepts
def DoSlash(sDirName): """Add a tailing slash if missing. """ return sDirName if sDirName[-1]=="/" else sDirName+"/"
bigcode/self-oss-instruct-sc2-concepts
def create_bucket_list(domain, affixes=[]): """ Create a set of buckets based on a domain name and a list of affixes. Note: This will be very large. Args: domain (str): Domain to add affixes to, such as google.com regions (list): List of AWS regions to query against. affixes (...
bigcode/self-oss-instruct-sc2-concepts
import secrets def get_random_number(min: int, max: int) -> int: """ Gets a random number between min and max inclusive. """ rand = secrets.SystemRandom() return rand.randint(min, max)
bigcode/self-oss-instruct-sc2-concepts
import math def round_decimals_up(number, decimals=2): """ Returns a value rounded up to a specific number of decimal places. """ if not isinstance(decimals, int): raise TypeError("decimal places must be an integer") elif decimals < 0: raise ValueError("decimal places has to be 0 o...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def disjunction_for_group(lines: List[str]) -> int: """ Returns the number of questions one group answered "yes" to, given the lines of input for that group. """ assert all(line.isalpha() for line in lines) return len(set(c for c in "".join(lines)))
bigcode/self-oss-instruct-sc2-concepts
def computeLastHitValues(blocks): """ given the query length and 'blacks' sting from a last hit return the: match length the blocks string looks something like this: "73,0:1,15,0:1,13,0:1,9" where integer elements indicate lenghts of matches and colon separated elements ...
bigcode/self-oss-instruct-sc2-concepts
import itertools def product(l1, l2): """ Returns all possible combinations of entries in two arrays Args: l1 -- list<str> l2 -- list<str> Returns: iterable """ return itertools.product(l1, l2)
bigcode/self-oss-instruct-sc2-concepts
def boolean(value: str) -> bool: """Convert a "human" boolean (Y, Yes, True, ...) to a Python boolean, raising a ValueError if it can't be converted. """ if value.lower() not in {"y", "yes", "n", "no", "true", "false"}: raise ValueError('Please enter either "y" or "n".') return value.lower()...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_range(min_max: List[int]) -> range: """Returns a range with the turtles min max choices. If the input is None then range(-25, 26) is returned. Parameters ---------- min_max : List[int] Returns ------- min_max : range """ if min_max is None: ...
bigcode/self-oss-instruct-sc2-concepts
def split_list(ls, num): """ 拆分list :param ls: 带截取的列表 [0, 1, 2, 3, 4, 5, 6] :param num: 除最后一个列表之外其他列表长度 3 :return: 所有拆分的列表 [[0, 1, 2], [3, 4, 5], [6]] """ a = len(ls) if a <= num: return [ls] quotient = a // num # 商 remainder = a % num # 余数 res_split = [] for i ...
bigcode/self-oss-instruct-sc2-concepts
import torch def impute(x, lengths, channels_last=True): """ Set elements of a batch of a sequence of tensors to zero according to sequence lengths. :param x: A tensor with shape [batch, time_step, ...] or [batch, ..., time_step] :param lengths: A tensor with shape [batch] :param channels_last: A bool...
bigcode/self-oss-instruct-sc2-concepts
def parse_header(header): """Parses the FASTQ header as specified by CASAVA 1.8.2 and returns the fields in a dictionary @<instrument>:<run number>:<flowcell ID>:<lane>:<tile>:<x-pos>:<y-pos> <read>:<is filtered>:<control number>:<index sequence> """ if header[0] != '@': return None ...
bigcode/self-oss-instruct-sc2-concepts
import math def pixel_coords_to_tile_address(x,y): """Create a tile address from pixel coordinates of point within tile.""" x = int(math.floor(x / 256)) y = int(math.floor(y / 256)) return (x, y)
bigcode/self-oss-instruct-sc2-concepts
def dict_to_string(m: dict) -> dict: """Convert dict values to strings Parameters ---------- m : dict Returns ------- dict """ for k, v in m.items(): if isinstance(v, dict): m[k] = dict_to_string(v) else: m[k] = str(v) return m
bigcode/self-oss-instruct-sc2-concepts
def bmi_classify(bmi, format="json"): """Helper function to get "BMI Category" and "Health Risk" from the bmi number Args: bmi (int): BMI of the concerned person format (str, optional): Json when for `native loop` method and anything else for `numpy` method. Defaults to "json". """ if b...
bigcode/self-oss-instruct-sc2-concepts
def _str_to_bool(s): """Convert string to bool (in argparse context).""" if s.lower() not in ['true', 'false']: raise ValueError('Need bool; got %r' % s) return {'true': True, 'false': False}[s.lower()]
bigcode/self-oss-instruct-sc2-concepts
def _explode_full_table_names(in_tables): """ Takes a list of schema-qualified names and creates a schema-key, table_list-value dict :param in_tables: A list of schema-qualified table/view names :return: schema-key, table_list-value dict """ schema_to_table = dict() for t in set(in_...
bigcode/self-oss-instruct-sc2-concepts
def get_file_name_from_url(url: str) -> str: """Get the last part of an URL.""" return url.rsplit('/', 1)[1]
bigcode/self-oss-instruct-sc2-concepts
def PrintMenu() -> int: """ Prints in console the menu of the app. """ option = 0 print("Select an option from the ones below") print("1 - Simple Permutation.\n2 - Simple Variation.\n3 - Simple Combination.") print("4 - Compound Permutation.\n5 - Compound Variation.\n6 - Compound Combination...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import math def get_minimum_subintervals_set_math(intvl_upper_limit: int, range_length: int = 1) -> List[int]: """ Method that returns the minimal set of placements that cover the full interval. This method uses the mathematical expresion that minimizes the number of points, howeve...
bigcode/self-oss-instruct-sc2-concepts
import json def resolve_json(text, resolver, recursive=True, fill_empty='{}'): """ Given a JSON Schema containing `$ref` keys, replace all referenced URI values with their values using trimesh Resolver objects. Parameters --------------- text : str JSON text including `$ref` to othe...
bigcode/self-oss-instruct-sc2-concepts
import torch def unpack_episode(episode): """ Helper function that extracts samples and labels from an episode in numpy Args: episode: the episode to unpack """ examples = torch.cat([episode["support_images"], episode["query_images"]], 1).numpy() labels = torch.cat([episode["support_class_...
bigcode/self-oss-instruct-sc2-concepts
def get_path_from_source(source_path): """ Get file path from source Args: source_path (str): relative module path e.g. this.module.Class """ file_path = "/".join(source_path.split('.')[:-1]) + '.py' return file_path
bigcode/self-oss-instruct-sc2-concepts
def name_to_crate_name(name): """Converts a build target's name into the name of its associated crate. Crate names cannot contain certain characters, such as -, which are allowed in build target names. All illegal characters will be converted to underscores. This is a similar conversion as that wh...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _extract_docstring_path_specification_comment_from_line( *, line: str, matches: List[str]) -> str: """ Extract a docstring path specification comment from a specified markdown line text. Parameters ---------- line : str Target markdown line text. ...
bigcode/self-oss-instruct-sc2-concepts
def _arg_no_mixin(num): """Return FindArgNoMixin for num.""" class FindArgNoMixin(object): # suppress(too-few-public-methods) """Mixin that provides generate() for finding args by number.""" def generate(self, # suppress(no-self-use) sub, other_transf...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def domains_check(domains: List[str]) -> List[str]: """ all input domains should have the same primary, e.g. * `example.com`, `a.example.com` are valid * `example.com`, `a.example1.com` are invalid * `domains=["a.x.com", "b.x.com"]` will be converted to `["x.c...
bigcode/self-oss-instruct-sc2-concepts
def generate_report_name(sim_type, talent_string, covenant_string): """create report name based on talents and covenant""" stripped_talents = talent_string.strip("_") stripped_covenant = covenant_string.strip("_") talents = f" - {stripped_talents}" if talent_string else "" covenant = f" - {stripped_...
bigcode/self-oss-instruct-sc2-concepts
def next_minute(dt): """ The next minute (as a datetime) for the given date time :param dt: the date time :return: the next minute (as a datetime) """ return dt.replace(minute=dt.minute + 1)
bigcode/self-oss-instruct-sc2-concepts
def get_pl_name(name, steps, counter=1): """Add a counter to a pipeline name if already in steps.""" og_name = name while name.lower() in [elem[0] for elem in steps]: counter += 1 name = og_name + str(counter) return name.lower()
bigcode/self-oss-instruct-sc2-concepts
def IsCoverageBuild(env): """Returns true if this is a coverage build. Args: env: The environment. Returns: whether this is a coverage build. """ return 'coverage' in env.subst('$BUILD_TYPE')
bigcode/self-oss-instruct-sc2-concepts
import json def get_json(response): """Get JSON from response.""" return json.loads(response.get_data(as_text=True))
bigcode/self-oss-instruct-sc2-concepts
def get_pdos_generator_inputs(fixture_code, generate_structure): """Generate a set of default inputs for the ``PdosWorkChain.get_builder_from_protocol()`` method.""" return { 'pw_code': fixture_code('quantumespresso.pw'), 'dos_code': fixture_code('quantumespresso.dos'), 'projwfc_code': f...
bigcode/self-oss-instruct-sc2-concepts
def opcode_4nnn(self, x, nn) -> int: """4XNN Skip the following instruction if the value of register VX is not equal to NN""" return self.pc + (4 if self.v[x] != nn else 2)
bigcode/self-oss-instruct-sc2-concepts
def is_degenerate(sides): """ Check to see if a triangle is 'degenerate'. :param sides: list[*int] - the length of the three sides of a triangle :return bool - whether a triangle is degenerate or not >>> is_degenerate([1, 2, 3]) True >>> is_degenerate([4, 5, 6]) False The sum of ...
bigcode/self-oss-instruct-sc2-concepts
def _both_names(meta, to_prom_name): """If the pathname differs from the promoted name, return a string with both names. Otherwise, just return the pathname. """ name = meta['pathname'] pname = to_prom_name[name] if name == pname: return "'%s'" % name else: return "'%s' (%s)"...
bigcode/self-oss-instruct-sc2-concepts
def string_7bit(string): """Strip hte highest bit of evey character in string""" s = "" for c in string: s += chr(ord(c) & 0x7f) return s
bigcode/self-oss-instruct-sc2-concepts
import yaml def parse_config(config_file: str) -> dict: """ Parses yaml config file (if indicated) :param str config_file: config file path :return: configuration dictionary """ if config_file is None: return {} with open(config_file) as f: return yaml.safe_load(f)
bigcode/self-oss-instruct-sc2-concepts
def get_test_data_rdd(sc, X_test_path): """ sc: type sparckContext X_test_path: type str, the path for the X_test data document, which contains the hash codes return: type rdd, a rdd where each record contains a document content and its zipped index in ascendind order (the zipped index will be used for ...
bigcode/self-oss-instruct-sc2-concepts
import re def test(pattern, string): """Determines whether a given string matches a given regular expression""" return bool(re.search(pattern, string))
bigcode/self-oss-instruct-sc2-concepts
import binascii def is_gzip_file(f): """ This is an elegant solution to test whether a file is gzipped by reading the first two characters. I also use a version of this in fastq_pair if you want a C version :) See https://stackoverflow.com/questions/3703276/how-to-tell-if-a-file-is-gzip-compressed for...
bigcode/self-oss-instruct-sc2-concepts
import click def progress_func(func, char='*'): """Use to wrap functions called in parallel. Prints a character for each function call. :param lambda-function func: A 'lambda wrapped' function to call after printing a progress character :param str char: The character (or multi-char string, if you ...
bigcode/self-oss-instruct-sc2-concepts
def vec_print_str(tv, pdvars): """ This returns a string that will be used to print a line of code. If the variable tv has not yet been used before, then the declaration of this variable must be included in the string. pdvars is the list of variables that have been previously defined. tv: ...
bigcode/self-oss-instruct-sc2-concepts
import time def format_duration(t0): """ Adapted from @john-fouhy: https://stackoverflow.com/questions/538666/python-format-timedelta-to-string """ duration = time.time() - t0 hours, remainder = divmod(duration, 3600) minutes, seconds = divmod(remainder, 60) return "{:02}:{:02}:{:02}"....
bigcode/self-oss-instruct-sc2-concepts
def channel_name_mapping(name_str): """ Turns a string like '1:foo,2:bar' into the dict {1: 'foo', 2: 'bar'} May raise an exception if the string doens't follow this format. Returns {} for an empty string. """ mapping_strs = str(name_str).split(',') str_pairs = [m.split(':') for m in map...
bigcode/self-oss-instruct-sc2-concepts
def calc_thick_spherical_lens(n, roc1, roc2, d, ne=1): """Calculate the properties of a thick spherical lens. Positive radius of curvature means center is further along the direction of travel. For a biconvex positive lens, roc1>0, roc2<0. The principal plane distances are from the vertex to the principal...
bigcode/self-oss-instruct-sc2-concepts
def nint(a): """return the nearest integer to a.""" i = int(a) if a > 0: if a - i > 0.5: i += 1 elif a < 0: if a - i < -0.5: i -= 1 return i
bigcode/self-oss-instruct-sc2-concepts
def example_group_indices(data, attr, values): """ Return lists of indices into `data` for each `values` item that matches the example value at `attr` attribute Example:: cls_ind1, cls_ind2 = example_group_indices(data, data.domain.classVar, ["Class 1", "Class 2"]) """ ret = [[] for _ i...
bigcode/self-oss-instruct-sc2-concepts
def longest_common_prefix(strings): """ Find the longest common prefix of a list of 2 or more strings. Args: strings (collection): at least 2 strings. Returns: string: The longest string that all submitted strings start with. >>> longest_common_prefix(["abcd", "abce"]) 'abc' ...
bigcode/self-oss-instruct-sc2-concepts
def r_to_rq(r): """ reduced coordinate inverse: (1+rq) r = ------ (1-rq) Hernquist & Ostriker 1992 eq. 2.16 """ return (r-1.0)/(r+1.0);
bigcode/self-oss-instruct-sc2-concepts
def flicker_amplitude_to_frequency(flicker_amplitude : float) -> float: """ Converts the flicker amplitude to the first filter frequency according to Kallinger et al. (2016) :param flicker_amplitude: Flicker amplitude calculated according to Bastien et. al (2013) :return: First filter frequency """ ...
bigcode/self-oss-instruct-sc2-concepts
import six def is_primitive(val): """ Checks if the passed value is a primitive type. >>> is_primitive(1) True >>> is_primitive("abc") True >>> is_primitive(True) True >>> is_primitive({}) False >>> is_primitive([]) False >>> is_primitive(set([])) :param ...
bigcode/self-oss-instruct-sc2-concepts
import math def get_distance(c1, c2): """ Returns approximate distance between two pairs of coordinates in km. Args: c1: coordinate pair 1 c2: coordinate pair 2 Returns: distance in km between c1 and c2 """ # approximate radius of earth in km R = 6373.0 lat1 = ma...
bigcode/self-oss-instruct-sc2-concepts
def dbt_project_dir(tmp_path_factory): """A temporary directory to store dbt test files.""" d = tmp_path_factory.mktemp("project") return d
bigcode/self-oss-instruct-sc2-concepts
def GetCbsdRegistrationRequest(cbsd): """Returns a CBSD registration request from the |Cbsd| object. """ return { 'cbsdCategory': cbsd.category, 'installationParam': { 'latitude': cbsd.latitude, 'longitude': cbsd.longitude, 'height': cbsd.height_agl, 'heightType...
bigcode/self-oss-instruct-sc2-concepts
def states_bedline_to_vector(bedlines, states_dic): """ Convert a line from a bedfile containing states in categorical data to vector format. Parameters ---------- bedline: [string,...] A line form a bedfile broken up into its contituent parts (e.g. ["chr1", "1000", "2000", "state"...
bigcode/self-oss-instruct-sc2-concepts
import re def is_valid_volume_id(volume_id): """ Validates drive and volume IDs, also known as the drive/volume "name". A valid volume name should look like: volume-00000001 - It should always start with "volume-" and end with 8 hexadecimal characters in lower case. :type volume_id: str :para...
bigcode/self-oss-instruct-sc2-concepts
def Not(query): """The negation of a query""" return '(NOT %s)' % (query,)
bigcode/self-oss-instruct-sc2-concepts
def lerp(xvar, xlim, ylim): """linearly interpolate a value of y given ranges for x, y. arguments: xvar: scalar xlim: array with xmin, xmax ylim: array with ymin, ymax """ delta_x = (xvar - xlim[0]) slope = ((ylim[1] - ylim[0]) / (xlim[1] - xlim[0])) yvar = ylim[0] +...
bigcode/self-oss-instruct-sc2-concepts
def incidentlist(xml): """ Takes the full incident XML and returns a list of dictionaries with 'agency code' and 'incident number' tag and text elements. """ i_list = [] for i in xml.iter('Incident'): i_dict = dict() i_dict['agency_code'] = i[2].text i_dict['incident_numb...
bigcode/self-oss-instruct-sc2-concepts
def fitAngleToBaxter(angle): """ Returns an angle fitted to use with Baxter. Parameters ---------- angle (float): Angle to convert. Returns ------- new_angle (float): Angle transformed into Baxter's yaw. """ new_angle = -90.0 + angle if angle <= 90.0 else -180.0 + (angle - 90....
bigcode/self-oss-instruct-sc2-concepts
def combine_adjacent(arr): """Sum like signed adjacent elements arr : starting array Returns ------- output: new summed array indexes: indexes indicating the first element summed for each group in arr """ output, indexes = [], [] curr_i = 0 while len(arr) > 0: ...
bigcode/self-oss-instruct-sc2-concepts
def gen_all_strings(word): """ Generate all strings that can be composed from the letters in word in any order. Returns a list of all strings that can be formed from the letters in word. This function should be recursive. """ if len(word) == 0: return [""] else: res...
bigcode/self-oss-instruct-sc2-concepts
def get_str_from_params(params: dict): """ Returns string from the parameters """ result = list() keys = list(params.keys()) length = len(keys) result.append("%s=%s" % (keys[0], params[keys[0]])) for i in range(1, length): result.append(":%s=%s" % (keys[i], params[keys[i]])) return...
bigcode/self-oss-instruct-sc2-concepts
def get_tokens(tagger, content): """ 文書内に出現した名詞のリストを取得する関数。 """ tokens = [] # この記事で出現した名詞を格納するリスト。 node = tagger.parseToNode(content) while node: # node.featureはカンマで区切られた文字列なので、split()で分割して # 最初の2項目をcategoryとsub_categoryに代入する。 category, sub_category = node.feature.spli...
bigcode/self-oss-instruct-sc2-concepts
def sort_points_by_Y(list_of_points): """Given a list of 2D points (represented as Point objects), uses "sorted" with the "key" argument to create and return a list of the SAME (not copied) points sorted in decreasing order based on their Y coordinates, without modifying the original list.""" return...
bigcode/self-oss-instruct-sc2-concepts
def tokens_to_index(token_list, vocab_dict): """ convert word tokens to number index INPUT: token_list: a list of string tokens vocab_dict: a dictionary with tokens(key)-integer(value) pairs OUTPUT: index_list: a list of integer indices """ index_list = [] for x in t...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def _(value: Union[bytes, bytearray]) -> bytes: """Convert ``bytes`` or ``bytearray`` to bytes""" return value
bigcode/self-oss-instruct-sc2-concepts
import sympy import six import random def _split_factors(integer): """Randomly factors integer into product of two integers.""" assert integer.is_Integer if integer == 0: return [1, 0] # Gives dict of form {factor: multiplicity} factors = sympy.factorint(integer) left = sympy.Integer(1) right = symp...
bigcode/self-oss-instruct-sc2-concepts
import json def get_test_ids(check_nightly_status=False): """Get the test ids from conf.json Keyword Arguments: check_nightly_status {bool} -- if we are running nightly test (default: {False}) Returns: tuple: (test_ids, skipped_tests) """ test_ids = [] with open("./Tests/conf...
bigcode/self-oss-instruct-sc2-concepts
def compare_location_and_region(first_file, second_file): """ Compares versions for osfstoragefiles - Compares location['bucket'] and location['object']. Also compares version region_ids. """ first_loc = first_file['versions__location'] second_loc = second_file['versions__location'] if ...
bigcode/self-oss-instruct-sc2-concepts
def spritecollide(sprite, group, dokill, collided=None): """ **pyj2d.sprite.spritecollide** Return list of sprites in group that intersect with sprite. The dokill argument is a bool, True removes sprites that collide from all groups. An optional collided is a callback function taking two sprite...
bigcode/self-oss-instruct-sc2-concepts
def make_error_logger(logger): """Make handlers that logs and ignores encoding errors.""" def log_errors(exc): logger.error('incorrect character encoding', exc_info=exc) return ('', exc.end) return log_errors
bigcode/self-oss-instruct-sc2-concepts
def is_compressed_key(pubkey_buffer): """ Checks whether or not a public key is compressed. :param pubkey_buffer: public keys as bytes obj. :return: true if public key is compressed; false otherwise """ if not isinstance(pubkey_buffer, bytes): raise ValueError length = len(pubkey_bu...
bigcode/self-oss-instruct-sc2-concepts
def _detect_skipped_track(remaining_duration: float, end_of_track_buffer: float, track: dict, prev_track: dict) -> bool: """Performs the detection logic for whether a track was skipped Args: remaining_duration: The remaining duration of the track in m...
bigcode/self-oss-instruct-sc2-concepts
def get_crashes_archive_name(cycle: int) -> str: """Return as crashes archive name given a cycle.""" return 'crashes-%04d.tar.gz' % cycle
bigcode/self-oss-instruct-sc2-concepts
def _output_filename(title): """Construct output filename.""" return title + ".html"
bigcode/self-oss-instruct-sc2-concepts
def is_palindrome(word): """Returns true if the word is a palindrome.""" return word == word[::-1]
bigcode/self-oss-instruct-sc2-concepts
def verify_approval_skip(data, env, env_configs): """Determines if a approval stage can be added/removed from a given environment pipeline stage based on environment setting. Defaults to false, and verifies administrators allow skips in given environments. Args: data (dict): environment config d...
bigcode/self-oss-instruct-sc2-concepts
def get_formatted_name(name): """ Return a 3-letters acronym in upper case and longer names in PascalCase. Exemple: 'sql' -> 'SQL'; 'hunting' -> 'Hunting' """ if len(name) == 3: neat_title = f"{name.upper()}" else: neat_title = f"{name.capitalize()}" return neat_title
bigcode/self-oss-instruct-sc2-concepts
def human_readable(value): """ Returns the number in a human readable format; for example 1048576 = "1Mi". """ value = float(value) index = -1 suffixes = 'KMGTPEZY' while value >= 1024 and index + 1 < len(suffixes): index += 1 value = round(value / 1024) if index == -1: ...
bigcode/self-oss-instruct-sc2-concepts
def rain(walls): """ walls is a list of non-negative integers. Return: Integer indicating total amount of rainwater retained. Assume that the ends of the list (before index 0 and after index walls[-1]) are not walls, meaning they will not retain water. If the list is empty return 0. """ ...
bigcode/self-oss-instruct-sc2-concepts
def separable_conv(graph, input, all_w, kernel_dim, layer_id): """Defines a separable convolution. Args: graph: The TASO graph. input: The input tensor. all_w: A list of lists of weights (one list for each layer). kernel_dim: The size of the kernel. layer_id: The ID o...
bigcode/self-oss-instruct-sc2-concepts
def get_slurm_header(slurm_dict, walltime_hrs, num_nodes=None): """ Write a SLURM script header from a set of slurm parameters. Parameters: slurm_dict (dict): dictionary of SLURM environment variables. walltime_hrs (int): allowed walltime in hours Keyword arguments: num_nodes (int)...
bigcode/self-oss-instruct-sc2-concepts
import functools def empty_energy_result(energy_result): """ Return False if the energy_result list contains only negative numbers, True otherwise """ return functools.reduce(lambda acc, x: acc or (x >= 0), energy_result, False)
bigcode/self-oss-instruct-sc2-concepts
def normalized_to_microseconds(normalized_setpoint: float, low: int, center: int, high: int) -> int: """ Converts a normalized setpoint (between -1.0 and 1.0) to a pulse width (in microseconds). Positive and negative values are computed separately, as they can span different intervals in terms of pulse wid...
bigcode/self-oss-instruct-sc2-concepts
import requests def post_request(url, body, headers): """ Method which makes a POST request to specified url :param url: url :param body: data in json format :param headers: headers :return: post response """ return requests.post(url, data=body, headers=headers)
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Union from typing import Iterable from typing import List def listify_decorator_args( argument: Optional[Union[str, Iterable[str]]], ) -> List[str]: """Converts a user-supplied "list" to an actual Python list. This helper supports a "string" list as follows: ...
bigcode/self-oss-instruct-sc2-concepts
def precision(confusion, classes, classifiers): """ Compute the precision from a confusion matrix. Parameters ---------- confusion : array, shape = [n_classes, n_classes] Where entry c_{ij} is the number of observations in class i but are classified as class j. ...
bigcode/self-oss-instruct-sc2-concepts
def insert_file_paths(command, file_paths, start_delim='<FILE:', end_delim='>'): """ Insert file paths into the command line at locations indicated by the starting and ending delimiters. """ tokens = command.split() final_tokens = [] for token in tokens: if token.startswith(start_del...
bigcode/self-oss-instruct-sc2-concepts
def getParameterFromCall(call, index=0): """ Returns a parameter node by index on the call node """ try: return call[1][index] except: return None
bigcode/self-oss-instruct-sc2-concepts
import math def triangle_geometry(triangle): """ Compute the area and circumradius of a triangle. Parameters ---------- triangle : (3x3) array-like The coordinates of the points which form the triangle. Returns ------- area : float The area of the triangle circum_...
bigcode/self-oss-instruct-sc2-concepts
import torch import random def gen_input_mask( shape, hole_size, hole_area=None, max_holes=1): """ * inputs: - shape (sequence, required): Shape of a mask tensor to be generated. A sequence of length 4 (N, C, H, W) is assumed. - hole_size (sequence or in...
bigcode/self-oss-instruct-sc2-concepts
def pack_2byte_to_hn(low_byte, high_byte): """ Pack 2 bytes to network order unsigned short """ return ((low_byte << 8) | high_byte) & 0xffff
bigcode/self-oss-instruct-sc2-concepts
def duration(duration, compact=False, unit=False): """Returns a time duration string representing the input value :param duration: value to format, must be convertible into an into :param compact: whether to show also seconds, defaults to False :param unit: whether to display he unit, defaults to False...
bigcode/self-oss-instruct-sc2-concepts
def getDBReleaseVersion(dbh, jobPars): # extra-wrapper function, to be deprecated? """ Get the DBRelease version from the job parameters """ return dbh.getDBReleaseVersion(jobPars=jobPars)
bigcode/self-oss-instruct-sc2-concepts
def read_bdseq(message): """Read the bdSeq number from a TAHU message.""" for metric in message.metrics: if metric.HasField('name') and metric.name == 'bdSeq': return metric.long_value return None
bigcode/self-oss-instruct-sc2-concepts
def _guessFileFormat(file, filename): """ Guess whether a file is PDB or PDBx/mmCIF based on its filename and contents. authored by pandegroup """ filename = filename.lower() if '.pdbx' in filename or '.cif' in filename: return 'pdbx' if '.pdb' in filename: return 'pdb' f...
bigcode/self-oss-instruct-sc2-concepts