seed
stringlengths
1
14k
source
stringclasses
2 values
import importlib def get_class_from_qualname(name): """ Resolve a fully qualified class name to a class, attempting any imports that need to be done along the way. :raises: ImportError or AttributeError if we can't figure out how to import it """ tokens = name.split(".") module_name = "."....
bigcode/self-oss-instruct-sc2-concepts
import boto from typing import Optional def get_aws_zone_from_boto() -> Optional[str]: """ Get the AWS zone from the Boto config file, if it is configured and the boto module is available. """ try: zone = boto.config.get('Boto', 'ec2_region_name') if zone is not None: z...
bigcode/self-oss-instruct-sc2-concepts
def restrict_to_setting(df, setting, run='eval'): """Restrict an experiment dataframe to one hyperparameter setting.""" setting_df = df[df['run'] == run] for k, v in setting.items(): if k in df.columns.values: setting_df = setting_df[setting_df[k] == v] return setting_df
bigcode/self-oss-instruct-sc2-concepts
import functools def synchronized(lock): """ Synchronizes a function call access on the given lock object. `lock` must have an `acquire()` and a `release()` method. Function call cannot proceed until the lock is acquired. Deadlocks are possible be careful Args: lock: the lock upon which to syn...
bigcode/self-oss-instruct-sc2-concepts
import struct def gatt_dec_svc_attr(data): """Decodes Service Attribute data from Discovery Response data. BTP Single Service Attribute 0 16 32 40 +--------------+------------+-------------+------+ | Start Handle | End Handle | UUID Length | UUID | +----------...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_log_level(name="cleverhans"): """ Gets the current threshold for the cleverhans logger :param name: the name used for the cleverhans logger """ return logging.getLogger(name).getEffectiveLevel()
bigcode/self-oss-instruct-sc2-concepts
def calc_labor_restriction(x_0,l_0,l_t): """ A function to compute sector output with the available labor force. Parameters ---------- x_0 : np.array sector output under business-as-usual (in M€/d) l_0 : np.array number of employees per sector under business-as-usual l_t : n...
bigcode/self-oss-instruct-sc2-concepts
def hash_object(x): """Given a variable or object x, returns an object suitable for hashing. Equivalent variables should return equivalent objects.""" if hasattr(x, 'hash_object'): return x.hash_object() else: return x
bigcode/self-oss-instruct-sc2-concepts
def interpolate(v1, v2, delta): """Interpolates between 2 arrays of vectors (shape = N,3) by the specified delta (0.0 <= delta <= 1.0). :param numpy.array v1: an Nd array with the final dimension being size 3. (a vector) :param numpy.array v2: an Nd array with the final dimension being ...
bigcode/self-oss-instruct-sc2-concepts
def convert_spaces(file_name): """Return file_name with all spaces replaced with "-".""" return file_name.replace(" ", "-")
bigcode/self-oss-instruct-sc2-concepts
def allowed_file(file_name_list: list) -> bool: """Return True if file extension of all passed file names is allowed""" allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'} for file_name in file_name_list: if not file_name: return False if file_name.split('.')[-1].lower() not in al...
bigcode/self-oss-instruct-sc2-concepts
def parkes_error_zone_detailed(act, pred, diabetes_type): """ This function outputs the Parkes Error Grid region (encoded as integer) for a combination of actual and predicted value for type 1 and type 2 diabetic patients Based on the article 'Technical Aspects of the Parkes Error Grid': https:...
bigcode/self-oss-instruct-sc2-concepts
def get_project(directory): """ Get the project in the given directory. Figure out the project name, and return a dictionary with the project name, the readable project path, the absolute project path, and a unique ID. """ namefile = directory.expanduser() / '.idea' / '.name' try: n...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Iterable import torch from typing import Tuple def recursive_to_device( iterable: Union[Iterable, torch.Tensor], device: Union[str, torch.device], ) -> Iterable: """Recursively puts an Iterable of (Iterable of (...)) tensors on the given device :param iter...
bigcode/self-oss-instruct-sc2-concepts
def _get_actor_name(message): """Returns actor name by parsing incoming message. """ return str(message).split('(')[0]
bigcode/self-oss-instruct-sc2-concepts
def format_timedelta(td): """ Format a timedelta Args: td (datetime.timedelta): A timedelta Returns: str: A string which represents the timedelta Examples: >>> import datetime >>> td = datetime.timedelta(days=3) >>> format_timedelta(td) '3 days' ...
bigcode/self-oss-instruct-sc2-concepts
def combine_status_info(obj, status_info, attrs, separator='\n= {attr} ='): """ Combine status information from the given attributes. Parameters ---------- obj : OphydObj The parent ophyd object. status_info : dict The status information dictionary. attrs : sequence of str...
bigcode/self-oss-instruct-sc2-concepts
def get_saturation(rgb): """Returns the saturation (hsl format) of a given rgb color :param rgb: rgb tuple or list :return: saturation """ c_max = max(rgb) / 255 c_min = min(rgb) / 255 d = c_max - c_min return 0 if d == 0 else d / (1 - abs(c_max + c_min - 1))
bigcode/self-oss-instruct-sc2-concepts
def _get_segmentation_strategy(segmentation): """Get the baci string for a geometry pair strategy.""" if segmentation: return 'segmentation' else: return 'gauss_point_projection_without_boundary_segmentation'
bigcode/self-oss-instruct-sc2-concepts
def selection_sort(array): """ Selection sort algorithm for sorting an array of ints. Returns sorted array. Running time = O(n2) to O(n2) """ A = array.copy() n = len(array) # Loop over the first to penultimate elements in array for i in range(0, n - 1): # Find smallest eleme...
bigcode/self-oss-instruct-sc2-concepts
import math def generalized_logistic_curve(t, a, k, b, eta, q, c=1): """See https://en.wikipedia.org/wiki/Generalised_logistic_function.""" return a + (k - a) / math.pow((c + q * math.exp(-b * t)), 1.0 / eta)
bigcode/self-oss-instruct-sc2-concepts
def sort_by_inclusion(array: list) -> list: """ Сортировка простым включением. Суть: массив делится на две части - отсортированную и неотсортированную. На каждом шаге берется очередной элемент из неотсортированной части и "включается" в отсортированную часть массива. Максимальная временная сложност...
bigcode/self-oss-instruct-sc2-concepts
def quadFit(x, a, b, c): """ Quadratic fit function. """ return a*x*x + b*x +c
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def to_timestamp(ts): """ Return a date/time in UTC from a timestamp """ return datetime.utcfromtimestamp(ts/1000.0)
bigcode/self-oss-instruct-sc2-concepts
def get_line_data(line, separator=None): """Converts a line scraped from a web page into a list. Parameters: - line, a line scraped (read) from a web page. The type is <class 'bytes'>. - separator (optional, default value None). If set, becomes the optional separator argument to th...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def cognito_user_id(event: dict) -> Optional[str]: """ Returns the User ID (sub) from cognito or None """ try: return event["requestContext"]["authorizer"]["claims"]["sub"] except (TypeError, KeyError): return None
bigcode/self-oss-instruct-sc2-concepts
def nsec_to_usec_round(DatetimeNanos) -> int: """Round nanoseconds to microseconds Timestamp in zipkin spans is int of microseconds. See: https://zipkin.io/pages/instrumenting.html """ inttimestamp = DatetimeNanos.timestamp() * 1e9 return int((inttimestamp + 500) // 10 ** 3)
bigcode/self-oss-instruct-sc2-concepts
def describe_selection(selection): """Create a human-readable description of the given selection Parameters ---------- selection: FileSelectionFile Returns ------- str """ return ( f"Selection containing {len(selection.selected_paths)} files:\n" f"Description: {se...
bigcode/self-oss-instruct-sc2-concepts
def check_complexity(check_bytes: bytes, complexity: int) -> bool: """Check the complexity of a bystream to see if it has the proper amount of leading 0 bits Args: bytes: byte stream to check for complexity bits complexity: number of leading bits that must be 0 in order to pass complexity Re...
bigcode/self-oss-instruct-sc2-concepts
def remove_new_lines_in_paragraph(article): """When we publish articles to dev.to sometimes the paragraphs don't look very good. So we will remove all new lines from paragraphs before we publish them. This means we don't have to have very long lines in the document making it easier to edit. Some elemen...
bigcode/self-oss-instruct-sc2-concepts
def delta_percent(decimals=1): """A delta formatter to display the delta as a float with a given number of decimals. Args: decimals: The number of decimals to display. Returns: A delta formatter function (f(a,b)) returning (b-a)/a displayed as a percentage. """ return (lambda a, b...
bigcode/self-oss-instruct-sc2-concepts
def key_values_to_tags(dicts): """ Converts the list of key:value strings (example ["mykey:myValue", ...]) into a list of AWS tag dicts (example: [{'Key': 'mykey', 'Value': 'myValue'}, ...] """ return [{'Key': tag_key_value[0], 'Value': tag_key_value[1]} for tag_key_value in [key_value_o...
bigcode/self-oss-instruct-sc2-concepts
def fixed(b1, b2): """ XORs two given sets of bytes, of equal length, together. """ # Ensure that byte arrays are of equal length. if len(b1) != len(b2): raise Exception('Byte arrays are not of equal length.') # XOR byte arrays together and return. return bytearray([x ^ y for x, y i...
bigcode/self-oss-instruct-sc2-concepts
def assert_(condition, message=None, *args, val=None): # pylint: disable=keyword-arg-before-vararg """ Return `value` if the `condition` is satisfied and raise an `AssertionError` with the specified `message` and `args` if not. """ if message: assert condition, message % args else: ...
bigcode/self-oss-instruct-sc2-concepts
def coerce_to_list(data, key): """ Returns the value of the ``key`` key in the ``data`` mapping. If the value is a string, wraps it in an array. """ item = data.get(key, []) if isinstance(item, str): return [item] return item
bigcode/self-oss-instruct-sc2-concepts
import struct def writeRegisterRequestValue(data): """Return the value to be written in a writeRegisterRequest Packet.""" packet = struct.unpack('>H', data[10:]) return packet[0]
bigcode/self-oss-instruct-sc2-concepts
def dict_to_r_vec(d): """Convert a skylark dict to a named character vector for R.""" return ", ".join([k + "=" + v for k, v in d.items()])
bigcode/self-oss-instruct-sc2-concepts
def find_any(words, case_sens = False): """Tests if any of the given words occurs in the given string. This filter is case INsensitive by default. """ if not case_sens: used_words = [w.lower() for w in words] else: used_words = words def apply_to(s): if not case...
bigcode/self-oss-instruct-sc2-concepts
def is_iterable(obj): """ Check if the object is iterable. """ has_iter = hasattr(obj, "__iter__") has_get_item = hasattr(obj, "__getitem__") return has_iter or has_get_item
bigcode/self-oss-instruct-sc2-concepts
def _decode_ctrl(key): """ Convert control codes ("\x01" - "\x1A") into ascii representation C-x """ assert len(key) == 1 if key == '\n': return 'RET' code = ord(key) if not 0 < code <= 0x1A: # Not control code return key letter = code + ord('a') - 1 return ("...
bigcode/self-oss-instruct-sc2-concepts
def start_gamma2_imp(model, lval: str, rval: str): """ Calculate starting value for parameter in data given data in model. For Imputer -- just copies values from original model. Parameters ---------- model : Model Imputer instance. lval : str L-value name. rval : str ...
bigcode/self-oss-instruct-sc2-concepts
def get_yes_no_input(question_text): """ :return True/False as answer to the passed yes-no question""" confirm = "" while confirm.lower() not in ["y", "n"]: confirm = input(f"{question_text} [y/n]: ") return confirm.lower() == 'y'
bigcode/self-oss-instruct-sc2-concepts
def usage(progname): """ print program usage """ print(("Usage: %s /path/to/tables " "/path/to/generated output[_amalgamation.cpp]") % progname) return 1
bigcode/self-oss-instruct-sc2-concepts
def agent_portrayal(agent): """ Properties of the agent visualization. """ portrayal = {"Shape": "circle", "Color": f"rgb({140-(agent.speed*3.6)},{50+(agent.speed*3.6)},0)", "Filled": "true", "r": 4} return portrayal
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import Dict from typing import Any import json def read_json_file(json_file: Path) -> Dict[Any, Any]: """Parse the application JSON file into native dict :param json_file (Path): JSON file to parse""" with open(json_file, 'r') as f: return json.load(f)
bigcode/self-oss-instruct-sc2-concepts
from enum import Enum from typing import Dict from typing import Any def enum_to_dict_fn(e: Enum) -> Dict[str, Any]: """ Converts an ``Enum`` to a ``dict``. """ return { 'name': e.name }
bigcode/self-oss-instruct-sc2-concepts
def blksLeftStakeWindow(height, netParams): """ Return the number of blocks until the next stake difficulty change. Args: height (int): Block height to find remaining blocks from. netParams (module): The network parameters. Returns: int: The number of blocks left in the current...
bigcode/self-oss-instruct-sc2-concepts
def _normalize_columns(columns: list[str]) -> list[str]: """Normalize column names.""" new_columns = [ "".join([substr.capitalize() for substr in col.split("_")]) for col in columns ] return new_columns
bigcode/self-oss-instruct-sc2-concepts
import json def _parse_callout_ffdc(version: int, data: memoryview) -> str: """ Parser for callout list FFDC. """ # The data in this section is simply a string representation of JSON data. # When the JSON data is written to the section, it will include a null # character at the end because it...
bigcode/self-oss-instruct-sc2-concepts
import torch def numpy2tensor(x): """Transter type numpy.ndarray to type torch.Tensor and change the precision to float Write in function so that can be used in functional programming :param x: The numpy data to be transformed :type x: numpy.ndarray :return: The torch data after transformatio...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def sort(sequence, values): """ Sort using the counting sort algorithm. sequence -- the sequence to sort values -- all the possible values of elements in the sequence (values must be in sorted order) Returns a list with the given sequence's elemen...
bigcode/self-oss-instruct-sc2-concepts
def always(_): """Predicate function that returns ``True`` always. :param _: Argument :returns: ``True``. """ return True
bigcode/self-oss-instruct-sc2-concepts
def sanitize_page_number(page): """A helper function for cleanup a ``page`` argument. Cast a string to integer and check that the final value is positive. If the value is not valid returns 1. """ if isinstance(page, str) and page.isdigit(): page = int(page) if isinstance(page, int) and (...
bigcode/self-oss-instruct-sc2-concepts
import re def read_and_prep_file(filename): """Read contents of a file,remove html tags Args: filename(str): a filename with full path to be loaded Returns: text(str): a string containing all words We read in all lines in a file, join into one long string, remove all html, turn any character that isnt...
bigcode/self-oss-instruct-sc2-concepts
def key_sort(data): """ sort by dict key and return sorted list :param data: dict to sort :type data: dict :return: sorted list of k,v tuple :rtype: list """ return [(k, data[k]) for k in sorted(data.keys())]
bigcode/self-oss-instruct-sc2-concepts
def sort_words_case_insensitively(words): """Sort the provided word list ignoring case, one twist: numbers have to appear after letters!""" char = [c for c in words if not c[0].isnumeric()] num = [n for n in words if n[0].isnumeric()] sorted_words = sorted(char, key = lambda word: word.lower()) +...
bigcode/self-oss-instruct-sc2-concepts
def extract_line(text_list, keyword, vname, col): """Takes a list of text and for every line containing the keyword, creates a dictionary where vname is key and the word at col is the value. Used for extracting one value from output file. """ dictionary = {} for line in text_list: if keyword in line: diction...
bigcode/self-oss-instruct-sc2-concepts
def update_event_visibility(review): """ Update event's `is_published` flag according to review :param review: EventReview object :return: event review updated object """ review.event.is_published = False if review.is_approved: review.event.is_published = True review.event.save...
bigcode/self-oss-instruct-sc2-concepts
def hierarchical_merge(dicts): """Merge a list of dictionaries. Parameters ---------- dicts: List[Dict] Dicts are given in order of precedence from lowest to highest. I.e if dicts[0] and dicts[1] have a shared key, the output dict will contain the value from dicts[1]. Retur...
bigcode/self-oss-instruct-sc2-concepts
def check_if_all_tss_are_bad(tss): """ Check if all time series in a list are not good. 'Not good' means that a time series is None or all np.nan """ def bad(ts): return True if ts is None else ts.isnull().all() return all([bad(ts) for ts in tss])
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_meta(fname, data_id=''): """Load a metadata file. Parameters ---------- fname : str Path to TFRecord folder Returns ------- meta : dict Metadata file """ with open(fname+data_id+'_meta.pkl', 'rb') as f: meta = pickle.load(f) ret...
bigcode/self-oss-instruct-sc2-concepts
def composite_identity(f, g): """ Return a function with one parameter x that returns True if f(g(x)) is equal to g(f(x)). You can assume the result of g(x) is a valid input for f and vice versa. >>> add_one = lambda x: x + 1 # adds one to x >>> square = lambda x: x**2 >>> b1 = compo...
bigcode/self-oss-instruct-sc2-concepts
import contextvars def RunInNewContextMiddleware(app, wsgi_env, start_response): """Runs the app in a copy of the current context. Start every request by calling contextvars.copy_context() and running the rest of the request in the newly copied context. This ensures that each request has its own context that...
bigcode/self-oss-instruct-sc2-concepts
def strip_comments(content): """Manual striping of comments from file content. Many localized content pages contain original English content in comments. These comments have to be stripped out before analyzing the links. Doing this using regular expression is difficult. Even the grep tool is not su...
bigcode/self-oss-instruct-sc2-concepts
def hsl_to_str(hue, sat, light): """ Convert an HSL color value into a string. Args: hue (int): value between 0-360 sat (int): value between 0-100 light (int): value between 0-100 Returns: str: string representation of the HSL tuple. Note that the hue is an integer...
bigcode/self-oss-instruct-sc2-concepts
def mean(values, empty=0): """ calculates mean of generator or iterator. Returns `empty` in case of an empty sequence """ n, mean = 0, 0 for value in values: n += 1 mean += (value - mean) / n return mean if n > 0 else empty
bigcode/self-oss-instruct-sc2-concepts
def sum_payout(cost_matrix, confusion_matrix): """ Calculate the profit from cost and confusion matrices. """ return (confusion_matrix * cost_matrix).sum()
bigcode/self-oss-instruct-sc2-concepts
import torch def batch_matmul(input: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: """ Batch matrix multiply different batch elements of the input with different weights. If weights are 3D, Input batch is divided in N groups, and each group element is matrix multiplied by a different filter. I...
bigcode/self-oss-instruct-sc2-concepts
def spawn(awaitable): """Start running a coroutine asynchronously. Returns the associated task.""" return (yield ("create_task", awaitable))
bigcode/self-oss-instruct-sc2-concepts
def get_iso_time(date_time): """ Converts the provided datetime object to an ISO-format time-tag. Parameters ---------- date_time : datetime.datetime Datetime object to convert to ISO format. Returns ------- time_in_iso : str Provided time in ISO format: YYYY-MM-DDTHH:M...
bigcode/self-oss-instruct-sc2-concepts
def is_any_in_txt(txt_list, within_txt): """ Within (txt_list), is there one item contained in within_txt ? Example: (['a', 'b'], 'ab') --> Yes, a is contained in ab """ for x in txt_list: if x in within_txt: return True return False
bigcode/self-oss-instruct-sc2-concepts
import math def format_count(number, maxlen=3): """ Returns a formatted count number, e.g. "1.3K" if number is longer than allowed maximum. """ result = str(number) if len(result) > maxlen: UNITS = "KMGTPEZY" log = min(len(UNITS) - 1, math.floor(math.log(number, 1000))) ...
bigcode/self-oss-instruct-sc2-concepts
def redcap_default_ship_to_vbr_location() -> str: """Returns the VBR Location ID shipment location for UCSD""" # Response is a location_id mapped to these locations # See src/scripts/data/location.csv return "1"
bigcode/self-oss-instruct-sc2-concepts
import re def process(s): """Process the file name as input string s to ensure that it adheres to Windows file naming requirements. """ if len(s) > 240: s = s[0, 240] return ''.join(re.split(r"[\\\:\*\?\"\<\>\|]", s.strip()))
bigcode/self-oss-instruct-sc2-concepts
def ignore_filename(fn, include_dotdirs=False): """ Ignores particular file name patterns output by TSK. Detecting new and renamed files becomes difficult if there are 3+ names for an inode (i.e. "dir", "dir/.", and "dir/child/.."). """ return (not include_dotdirs and (fn.endswith("/.") or fn.e...
bigcode/self-oss-instruct-sc2-concepts
def find_neighbor(x,y): """if y is within +-10bp of x""" # print (x,y) chr_x = x[:-1].split(":")[0] start_x = int(x[:-1].split(":")[-1].split("-")[0]) chr_y = y[:-1].split(":")[0] start_y = int(y[:-1].split(":")[-1].split("-")[0]) # print (chr_x,chr_y,start_x,start_y) if chr_x != chr_y: return False if abs...
bigcode/self-oss-instruct-sc2-concepts
def mask_sequence(seq, maskchar, fpos, tpos): """Given a sequence, mask it with maskchar starting at fpos (including) and ending at tpos (excluding) """ if len(maskchar) > 1: raise RuntimeError("Internal error: more than one character given to mask_sequence") if fpos < 0: fpos = 0 ...
bigcode/self-oss-instruct-sc2-concepts
def fibonacci(n): """ this function has one parameter (n). this function should return the nth value in the fibonacci series. the function is implemented using recursion. each number in the fibonacci sequence is the sum of the two numbers that precede it. the sequence goes: 0, 1, 1, 2, 3, 5, 8...
bigcode/self-oss-instruct-sc2-concepts
def clear(df,col,val): """ Check distribution of variable This function accepts a dataframe,column(feature) and value which returns count of the value, containing the value counts of a variable(value_counts) Keyword arguments: df - Pandas dataframe col - Feature of the datagrame va...
bigcode/self-oss-instruct-sc2-concepts
def gen_backend_tfvars_files(environment, region): """Generate possible Terraform backend tfvars filenames.""" return [ "backend-%s-%s.tfvars" % (environment, region), "backend-%s.tfvars" % environment, "backend-%s.tfvars" % region, "backend.tfvars" ]
bigcode/self-oss-instruct-sc2-concepts
def get_prot_res_seq_cif(CifDict, EntNum): """ Gives sequence as taken from mmCIF file, entity poly pdbx seq section Takes the canonical sequence. Parameters ---------- CifDict: dict EntNum: int Returns ------- canonseq: str """ # canon_seqlist = CifDict["_entity_poly.p...
bigcode/self-oss-instruct-sc2-concepts
def get_direct_deps(graph, top_node): """Gets the direct dependencies of given top_node. @param graph The graph to read for dependencies. @param top_node The node, which dependencies are wanted. @return The dependencies in a set. """ deps = set() for i in range(len(graph.body)): if ...
bigcode/self-oss-instruct-sc2-concepts
import math def applyDeadZone(val, deadZone): """ Apply a dead zone to an input with no other smoothing. Values outsize the dead zone are correctly scaled for 0 to 1.0 :return: The float value of the adjusted intput """ sign = 1.0 if val < 0.0: sign = -1.0 val = math.fabs(val)...
bigcode/self-oss-instruct-sc2-concepts
import torch def xyxy2xywh(box: torch.Tensor) -> torch.Tensor: """ Returns the xywh format of the input bounding box tensor Arguments: box (torch.Tensor): Bounding box tensor in xyxy format Output: output (torch.Tensor): Bounding box tensor in xywh format """ ...
bigcode/self-oss-instruct-sc2-concepts
def parse_email_remediation_key(key): """Returns the tuple (message_id, recipient) for the key created using create_email_remediation_key.""" return key.split(':', 1)
bigcode/self-oss-instruct-sc2-concepts
def read_text(file_name): """ Parameters ---------- file_name : string, name of file to read Returns ------- line : string of the file contents """ inFile = open(file_name,'r') # Python function to open a file via name line = inFile.read() # Function to read contents into ...
bigcode/self-oss-instruct-sc2-concepts
def bezier2(t, ps): """ evaluate quadratic bezier curve at t given three points in list ps """ umt = 1 - t return umt * umt * ps[0] + 2 * umt * t * ps[1] + t * t * ps[2]
bigcode/self-oss-instruct-sc2-concepts
def is_valid_filename_extension(ext: str) -> bool: """ By convention extensions are the initial `.`. E.g., "tgz" is valid, but not ".tgz". """ valid = not ext.startswith(".") return valid
bigcode/self-oss-instruct-sc2-concepts
def beautify_url(url): """ Remove the URL protocol and if it is only a hostname also the final '/' """ try: ix = url.index('://') except ValueError: pass else: url = url[ix+3:] if url.endswith('/') and url.index('/') == len(url)-1: url = url[:-1] return ur...
bigcode/self-oss-instruct-sc2-concepts
import json def story(request): """ Provides a detailed HPACK story to test with. """ path = request.param with open(path, 'r', encoding='utf-8') as f: details = json.loads(f.read()) return details
bigcode/self-oss-instruct-sc2-concepts
def parse_model_cfg(path): """Parses the yolo-v3 layer configuration file and returns module definitions""" file = open(path, 'r') lines = file.read().split('\n') lines = [x for x in lines if x and not x.startswith('#')] lines = [x.rstrip().lstrip() for x in lines] # get rid of fringe whitespaces ...
bigcode/self-oss-instruct-sc2-concepts
def make_str_content(content): """ In python3+ requests.Response.content returns bytes instead of ol'good str. :param content: requests.Response.content :return: str representation of the requests.Response.content data """ if not isinstance(content, str): content = str(content.decode()) ...
bigcode/self-oss-instruct-sc2-concepts
def beta(R0, gamma): """ R0 from model parameters. """ return R0 * gamma
bigcode/self-oss-instruct-sc2-concepts
import re def get_build_number_from_body(body): """Extracts the build number from the given body. Arguments: body {dict} -- The body as extracted by `extract_body()` Returns: str -- The build number if given. If there's an error extracting this or if the build numb...
bigcode/self-oss-instruct-sc2-concepts
def format_time(decisecond): """ Convert time in tenths of seconds into formatted string m:ss.t :param decisecond: int >= 0 :return: str """ assert isinstance(decisecond, int) assert decisecond >= 0 decisecond, tenths = decisecond//10, decisecond % 10 minutes, seconds = decise...
bigcode/self-oss-instruct-sc2-concepts
def make_iterator(args, lock, queue): """ Makes an iterator over args and passes the lock an queue to each element. """ return ((arg, lock, queue) for arg in args)
bigcode/self-oss-instruct-sc2-concepts
import pickle def pickle_save(obj, fp, verbose=1): """Save an object as a pickle file.""" try: with open(fp, 'wb') as f: pickle.dump(obj, f) except Exception as err: if verbose: print("Saving object failed. Error:", err) return False else: if verbose: print(...
bigcode/self-oss-instruct-sc2-concepts
import socket def is_valid_ip_address(ip_addr): """This method checks if string provided is a valid IP address Args: ip_addr (str): IP Address String Returns: (boolean): True/False """ try: socket.inet_aton(ip_addr) return True except (socket.error, TypeError): ...
bigcode/self-oss-instruct-sc2-concepts
def sync_batch_request(func, params, get_data=lambda x: x["info"], limit=500): """ 同步请求接口 :param func: 请求方法 :param params: 请求参数 :param get_data: 获取数据函数 :param limit: 一次请求数量 :return: 请求结果 """ # 如果该接口没有返回count参数,只能同步请求 data = [] start = 0 # 根据请求总数并发请求 while True: ...
bigcode/self-oss-instruct-sc2-concepts
import torch def batch_torch_denormalize_box_params(box_params, scale=3): """ Denormalize the box parameters utilizing the accumulated dateaset statistics :param box_params: float tensor of shape [N, 6] containing the 6 box parameters, where N is the number of boxes :param scale: float scalar that scales...
bigcode/self-oss-instruct-sc2-concepts