seed
stringlengths
1
14k
source
stringclasses
2 values
def number_of_lines(filename=""): """returns number of lines in a file""" lines = 0 with open(filename, mode='r', encoding='utf-8') as a_file: for i, l in enumerate(a_file): lines += 1 return lines
bigcode/self-oss-instruct-sc2-concepts
import inspect import types def _repr_obj(obj, show_modules: bool = False, depth: int = 0) -> str: """Return a pretty representation of an object.""" rep = f"{obj.__class__.__name__} (" if show_modules: rep = f"{obj.__class__.__module__}.{rep}" tab = "\t" params = { name: getattr...
bigcode/self-oss-instruct-sc2-concepts
import json import base64 def b64_json_enc(data): """ encode data to b64 encoded json :data: data to encode :returns: encoded str """ json_str = json.dumps(data) return base64.b64encode(json_str.encode()).decode()
bigcode/self-oss-instruct-sc2-concepts
import re def is_valid_project_id(project_id): """True if string looks like a valid Cloud Project id.""" return re.match(r'^(google.com:)?[a-z0-9\-]+$', project_id)
bigcode/self-oss-instruct-sc2-concepts
from random import shuffle def k_fold_split(X, Y, k=10, shuffleDataset=True): """ Split both list X and Y into k folds random will shuffle the data before, so two calls would not return the same folds ex: print(k_fold_split(["A", "B", "C", "D", "E", "F", "G"], ["a", "b", "c", "d", "e", "f", "g"], k=3...
bigcode/self-oss-instruct-sc2-concepts
def indent(num_spaces): """Gets spaces. Args: num_spaces: An int describes number of spaces. Returns: A string contains num_spaces spaces. """ num = num_spaces spaces = '' while num > 0: spaces += ' ' num -= 1 return spaces
bigcode/self-oss-instruct-sc2-concepts
import time def exampleWorker(in_str, in_num): """ An example worker function. """ print('Got:', in_str, in_num) t1 = time.time() while True: if time.time() - t1 > 10: break return in_str + " " + str(in_num) + " X"
bigcode/self-oss-instruct-sc2-concepts
def _get_proxy_type(type_id): """ Return human readable proxy type Args: type_id: 0=frontend, 1=backend, 2=server, 3=socket/listener """ proxy_types = { 0: 'frontend', 1: 'backend', 2: 'server', 3: 'socket/listener', } return proxy_types.get(in...
bigcode/self-oss-instruct-sc2-concepts
def print_number_and_permutations(permutations): """ Given a newline-separated list of combinations, return the number of combinations as well as the original list. """ number = len(permutations.split("\n")) return("%s\n%s" % (number, permutations))
bigcode/self-oss-instruct-sc2-concepts
def is_white(r, g, b): """ Check if an RGB code is white. :param r: Red byte. :param g: Green byte. :param b: Blue byte. :return: True if the pixel is white, False otherwise. """ if r == 255 and g == 255 and b == 255: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def set_simulation(config, components, exclude): """Choose which components to simulate, and which parts to exclude.""" sim_config = """ simulation: components: [{components}] exclude: [{exclude}] """.format(components=", ".join(components), exclude=", ".join(exclude)) return config + sim...
bigcode/self-oss-instruct-sc2-concepts
import torch def calc_bbox_iou_matrix(pred: torch.Tensor): """ calculate iou for every pair of boxes in the boxes vector :param pred: a 3-dimensional tensor containing all boxes for a batch of images [N, num_boxes, 4], where each box format is [x1,y1,x2,y2] :return: a 3-dimensional ma...
bigcode/self-oss-instruct-sc2-concepts
def get_locations(twitter_data: dict) -> dict: """ Returns a dictionary where keys are users' accounts and the values are their locations. """ locations_dct = dict() for user in twitter_data['users']: if user['location']: locations_dct.update({user['screen_name']: user['location'...
bigcode/self-oss-instruct-sc2-concepts
def propagateParents(currentTerm, baseGOid, GOdict, parentSet): """ Propagates through the parent hierarchy of a provided GO term to create a set of all higher order parents. Each term's recursive_parents attribute will be filled with all recursively found parent terms. Parameters ---------- c...
bigcode/self-oss-instruct-sc2-concepts
import json def load_config(config_file="config.json"): """ Load configration information from a .json file. In the future: The DISCORD_TOKEN should be read from an environment variable and the channel ids should be pulled down from webhooks. """ conf = json.load(open(config_file)) ...
bigcode/self-oss-instruct-sc2-concepts
def partition(rows, question): """ Partitions a dataset. For each row in the dataset, check if it matches the question. If so, add it to 'true rows', otherwise, add it to 'false rows'. PARAMETERS ========== rows: list A list of lists to store the rows of the datase...
bigcode/self-oss-instruct-sc2-concepts
import torch import math def pose_error(R0: torch.Tensor, t0: torch.Tensor, R1: torch.Tensor, t1: torch.Tensor): """Compute the rotation and translation error. Adapted from PixLoc (author: Paul-Edouard Sarlin) https://psarlin.com/pixloc/ Args: * R0: The [3 x 3] first rotation matrix. * t0:...
bigcode/self-oss-instruct-sc2-concepts
def adl(file_name, is_weight=False, default_weight=0, bonus_key=""): """The function returns adjacency list representation of a graph. bonus_key if set, will be added to all nested dictionaries. Input data format: With weights: 1 2,4 3,111 2 4,55 5,7 Output: {1: {2: 4, 3: 111...
bigcode/self-oss-instruct-sc2-concepts
import re def extract_stop_words(body: str) -> set: """Parse stop words in a text body as delimited by whitespace. :param body: the body of the text to parse :returns: a set of "stop-words" """ return {word for word in re.findall(r'\w+', body)}
bigcode/self-oss-instruct-sc2-concepts
import requests def request_json(url, **kwargs): """Send a GET request to one of the API endpoints that returns JSON. Send a GET request to an endpoint, ideally a URL from the urls module. The endpoint is formatted with the kwargs passed to it. This will error on an invalid request (requests.Request...
bigcode/self-oss-instruct-sc2-concepts
def str_to_bool(parameter): """ Utility for converting a string to its boolean equivalent. """ if isinstance(parameter, bool): return parameter if parameter.lower() in {'false', 'f', '0', 'no', 'n'}: return False elif parameter.lower() in {'true', 't', '1', 'yes', 'y'}: r...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_vocab_version(typename): """Parses a controlled vocabulary version from an instance ``xsi:type`` value. Args: typename: The ``xsi:type`` value found on a controlled vocabulary instance. Returns: The version portion of a controlled vocabulary type insta...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def is_class_view(handler: Callable) -> bool: """ Judge handler is django.views.View subclass """ return hasattr(handler, "view_class")
bigcode/self-oss-instruct-sc2-concepts
def default_filter(files): """Function to filter folders based on content Parameters ---------- files : list A list containing strings of filenames in directory Returns ------- bool : a flag indicating whether the list contains '1.mkv', '2.mkv' and 'Labels.json' ...
bigcode/self-oss-instruct-sc2-concepts
import re def bump_version(version, bump='patch'): """ Increases version number. :param version: str, must be in version format "int.int.int" :param bump: str, one of 'patch, minor, major' :returns: version with the given part increased, and all inferior parts reset to 0 """ # split the v...
bigcode/self-oss-instruct-sc2-concepts
def ordinaryAnnuity(pymt, p, r, c, n): """Ordinary annuity formula Returns: future value Input values: pymt : payment made during compounding period p : principal r : annual interest rate c : number of compounding periods in a year n : total number of payments """ blo...
bigcode/self-oss-instruct-sc2-concepts
def ext_euclid(x, y): """ Returns (g, a, b) such that g = gcd(x, y) = ax + by """ if y == 0: # gcd = x and gcd = x = (1)x + (0)y return (x, 1, 0) else: # Recursively, g = a1 * (y) + b1 * (x % y) (g, a1, b1) = ext_euclid(y, x % y) # a1 * (y) + b1 * (x % y) = b1...
bigcode/self-oss-instruct-sc2-concepts
def shell_config(shell): """ Returns a dict in the following form, depending on the given shell: return { 'prefix': '<preffix-to-use>', 'suffix': 'suffix-to-use', 'delimiter': '<delimiter-to-use>', } Logic from Docker Machine: https://github.com/docker/machine/blob/master...
bigcode/self-oss-instruct-sc2-concepts
import re def format_symbol(symbol): """HGNC rules say symbols should all be upper case except for C#orf#. However, case is variable in both alias and previous symbols as well as in the symbols we get in submissions. So, upper case everything except for the one situation where mixed-case is allowed, w...
bigcode/self-oss-instruct-sc2-concepts
def build_tr_create_module_page_link(region, module_type_id): """ Build the direct link to the corresponding Threat Response page in the given region for creating a module of the given type. """ if module_type_id is None: return 'N/A' return ( f'https://securex.{region}.securit...
bigcode/self-oss-instruct-sc2-concepts
def _message_with_time(source, message, time): """Create one line message for logging purposes. Parameters ---------- source : str String indicating the source or the reference of the message. message : str Short message. time : int Time in seconds. """ start_m...
bigcode/self-oss-instruct-sc2-concepts
import bisect def leftmostBinSearch(vec, val): """ Return the leftmost position in the vector vec of val. If val is absent then we return the lefternmost position for the value: max(vec[vec < val]). The time complexity here is potentially worse than log(n) because of the extra step of walking back...
bigcode/self-oss-instruct-sc2-concepts
def computeHSL(hexValue): """ Given a six-digit hex code (no #), compute the hue, saturation, and luminosity. Returns a list consisting of the hue, saturation, and luminosity values. Hue is a (float?) between 0 and 360, luminosity and saturation floats between 0 and 1 """ red = int('0x' + h...
bigcode/self-oss-instruct-sc2-concepts
def last_player(played_cards, players): """ Return person who played the last card. E.g.: last_player([(1, "S"), (2, "S")], ["Abi", "Bob"]) returns: "Bob" Args: played_cards (list): players (list): Returns: return (str): The players name """ ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def CalculateMD5Checksum(filename): """Calculate the MD5 checksum for filename.""" md5 = hashlib.md5() with open(filename, 'rb') as f: data = f.read(65536) while len(data) > 0: md5.update(data) data = f.read(65536) return md5.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def nullify(data: dict) -> dict: """ Nullify empty strings in a dict """ for key, val in data.items(): if val == "": data[key] = None return data
bigcode/self-oss-instruct-sc2-concepts
def compute_chunksize(src, w, h, chunksize=None, max_mem=None): """ Attempts to compute a chunksize for the resampling output array that is as close as possible to the input array chunksize, while also respecting the maximum memory constraint to avoid loading to much data into memory at the same tim...
bigcode/self-oss-instruct-sc2-concepts
def listify(s): """ Converts s into a list if not already. If s is None, an empty list will be returned. """ if s is None: s = [] elif isinstance(s, (set, tuple)): s = [i for i in s] elif not isinstance(s, list): s = [s] return s
bigcode/self-oss-instruct-sc2-concepts
import re def normalize_keys(dict_, lowercase=True, separator='_'): """ Recoursively changes keys to their normalized version: - replaces any special symbol by `separator` - lowercases (if necessary). Example: In [1]: input_ = {"Content-Type": "text/html", ...: "Last-Modified": { ...
bigcode/self-oss-instruct-sc2-concepts
def dedent_initial(s: str, n: int = 4) -> str: """Remove identation from first line of text.""" return s[n:] if s[:n] == ' ' * n else s
bigcode/self-oss-instruct-sc2-concepts
def manage_none_value(diff_result, column_list): """ To handle None values,it appends Null to the missing column name in the result. Args: diff_result(list):Result of the datavalidation. column_list(list):List of column names of the table. Returns: Return the list of dictio...
bigcode/self-oss-instruct-sc2-concepts
def sum_to_leftmost(value, dim): """Sum out `value.ndim-dim` many rightmost dimensions of a given tensor. Args: value (Tensor): A tensor of `.ndim` at least `dim`. dim (int): The number of leftmost dims to remain. Returns: The result tensor whose ndim is `min(dim, value.dim)`. "...
bigcode/self-oss-instruct-sc2-concepts
def load(filename): """ 读文件 Args: filename: str, 文件路径 Returns: 文件所有内容 字符串 """ with open(filename, 'r', encoding='utf-8') as f: content = f.read() return content
bigcode/self-oss-instruct-sc2-concepts
def _human_size(size_bytes): """ format a size in bytes into a 'human' file size, e.g. B, KB, MB, GB, TB, PB Note that bytes will be reported in whole numbers but KB and above will have greater precision. e.g. 43 B, 443 KB, 4.3 MB, 4.43 GB, etc """ UNIT_SIZE = 1000.0 suffixes_table = [('B'...
bigcode/self-oss-instruct-sc2-concepts
def _include_branding_code_in_app(dist): """Returns whether to omit the branding code from the Chrome .app bundle. If a distribution is packaged in a PKG (but is not also packaged in a DMG), then the brand code is carried in the PKG script, and should not be added to the .app bundle's Info.plist. ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def check_str(data: Any) -> str: """Check if data is `str` and return it.""" if not isinstance(data, str): raise TypeError(data) return data
bigcode/self-oss-instruct-sc2-concepts
def _parse_memory(s: str) -> int: """ Parse a memory string in the format supported by Java (e.g. 1g, 200m) and return the value in MiB Examples -------- >>> _parse_memory("256m") 256 >>> _parse_memory("2g") 2048 """ units = {"g": 1024, "m": 1, "t": 1 << 20, "k": 1.0 / 1024}...
bigcode/self-oss-instruct-sc2-concepts
import json def Read_Message_Dict(BB, msg_name): """ Read_Message_Dict(BB, msg_name): Reads the named BB message contents, json.loads it, and returns the resulting dict. Returns an empty dict if the message is not found or could not be read back. """ try: msg_item = BB.ReadMessage(msg_...
bigcode/self-oss-instruct-sc2-concepts
def parse_scoped_selector(scoped_selector): """Parse scoped selector.""" # Conver Macro (%scope/name) to (scope/name/macro.value) if scoped_selector[0] == '%': if scoped_selector.endswith('.value'): err_str = '{} is invalid cannot use % and end with .value' raise ValueError(err_str.format(scoped_s...
bigcode/self-oss-instruct-sc2-concepts
def prettyprint_tokenized(tokenized: str) -> str: """Returns a pretty-printable version of a document that contains tokens.""" return tokenized.replace('\x1b', '<').replace('\x1c', '|').replace('\x1d', '>')
bigcode/self-oss-instruct-sc2-concepts
def copy_params_dict(model, copy_grad=False): """ Create a list of (name, parameter), where parameter is copied from model. The list has as many parameters as model, with the same size. :param model: a pytorch model :param copy_grad: if True returns gradients instead of parameter values """ ...
bigcode/self-oss-instruct-sc2-concepts
import math def select_ghostdag_k(x, delta): """ Selects the k parameter of the GHOSTDAG protocol such that anticones lager than k will be created with probability less than 'delta' (follows eq. 1 from section 4.2 of the PHANTOM paper) :param x: Expected to be 2Dλ where D is the maximal network delay and λ is th...
bigcode/self-oss-instruct-sc2-concepts
def list_search(lst, key, value): """Search a list of dictionaries for the dict where dict[key] == value.""" try: return next(dct for dct in lst if dct[key] == value) except StopIteration: raise KeyError()
bigcode/self-oss-instruct-sc2-concepts
def sum_of_squares(n): """ returns the sum of squares of first n numbers """ iter = 1 sum = 0 while iter <= n: sum += iter**2 iter += 1 return sum
bigcode/self-oss-instruct-sc2-concepts
def xyxy_to_normalized_xywh(box, size, center=True): """ Converts bounding box format from 'xyxy' to 'xywh'. Args: box: [Upper Left x, Upper Left y, Lower Right x, Lower Right y]; unnormalized. size: [image width, image height] center (bool): If True, then the x, y refer to cent...
bigcode/self-oss-instruct-sc2-concepts
import json import codecs def json_load(file_path): """ Loads an UTF-8 encoded JSON :param file_path: Path to the JSON file :type file_path: string :rtype: dict :return: The JSON dictionary """ return json.load(codecs.open(file_path, "r", encoding="utf-8"))
bigcode/self-oss-instruct-sc2-concepts
def load_timestamps(filename): """ load timestamps of a recording. Each line of the file contains two numbers: the frame index and the corresponding time in milliseconds. Parameters ---------- filename: str The file to extract timestamps from. Returns ------- dict: Dictionary with fram...
bigcode/self-oss-instruct-sc2-concepts
import math def distance(a, b): """ Helper function for checking distance between any two points on a cartesian grid :param a: First point :type a: tuple :param b: Second point :type b: tuple :return: Distance between two points :rtype: float """ return math.sqrt((b[...
bigcode/self-oss-instruct-sc2-concepts
def get_items_of_type(type_, mapping): """Gets items of mapping being instances of a given type.""" return {key: val for key, val in mapping.items() if isinstance(val, type_)}
bigcode/self-oss-instruct-sc2-concepts
def mean(iterator, length): """ Returns the arithmetic mean of the values in the given iterator. """ return sum(iterator) / float(length or 1)
bigcode/self-oss-instruct-sc2-concepts
def inplace_return_series(dataframe, column, series, inplace, return_series, target_column=None): """ helper function to reuse throughout library. It applies logic for performing inplace series transformations and returning copies of modified series :param dataframe: panda...
bigcode/self-oss-instruct-sc2-concepts
def no_tests(tests): """Predicate for number of tests.""" return not tests or len(tests) == 0
bigcode/self-oss-instruct-sc2-concepts
def _get_widget_selections(widgets, widget_selections): """Return lists of widgets that are selected and unselected. Args: widgets (list): A list of widgets that we have registered already. widget_selections (dict): A dictionary mapping widgets (:py:class:`review...
bigcode/self-oss-instruct-sc2-concepts
def search4vowels(phrase: str) -> set: # Informando ao usuário que deve retornar um conjunto no fim """ Função que procura vogais em palavras :param phrase:str palavra provida para procurar vogais :return: retorna a inserseção de vowels com word """ return set('aeiou').intersection(set(phrase.lo...
bigcode/self-oss-instruct-sc2-concepts
from io import StringIO def get_number(token): """ Turn leading part of a string into a number, if possible. """ num = StringIO() for ch in token: if ch.isdigit() or ch == '.' or ch == '-': num.write(ch) else: break val = num.getvalue() num.close() r...
bigcode/self-oss-instruct-sc2-concepts
def remove(pred): """Remove any item from collection on traversal if that item meets condition specified in pred.""" def generator(coll): for item in coll: if not pred(item): yield item return generator
bigcode/self-oss-instruct-sc2-concepts
def new_task_id(sources, prefix=""): """Generate a new unique task ID The task ID will be unique for the given sources, and with the given prefix. """ existing_ids = set() for source in sources: existing_ids |= {int(key[len(prefix):]) for key in source.task_ids if ke...
bigcode/self-oss-instruct-sc2-concepts
def distance_difference_calc(r2, s1, gap): """ Computes the necessary distance between mocks given geometrical components of the survey. Parameters ----------- r2 : `float` s1 : `float` gap : `float` Returns ---------- dist_diff : `float` """ # Converting to float...
bigcode/self-oss-instruct-sc2-concepts
import csv def read_gold_qdmrs(file_path): """Reads csv file of QDMR strings and converts it into a csv containing processed QDMRs Parameters ---------- file_path : str Path to csv file containing, question_id, question text, question decomposition Returns --...
bigcode/self-oss-instruct-sc2-concepts
def get_attr_groups(attr_name_file): """ Read attribute names one by one from attr_name_file and based on the common prefix, separate them into different attribute groups Return list of starting indices of those groups """ new_group_idx = [0] with open(attr_name_file, 'r') as f: all_line...
bigcode/self-oss-instruct-sc2-concepts
def _service_and_endpoint_labels_from_method(method_name): """Get normalized service_label, endpoint_label tuple from method name""" name_parts = method_name.split("/") if len(name_parts) != 3 or name_parts[0] != "" or name_parts[1] == "" or name_parts[2] == "": raise AssertionError("Invalid method ...
bigcode/self-oss-instruct-sc2-concepts
def old_hindu_lunar_leap(date): """Return the leap field of an Old Hindu lunar date = [year, month, leap, day].""" return date[2]
bigcode/self-oss-instruct-sc2-concepts
def get_duplicates(setlist): """ Takes a list of sets, and returns a set of items that are found in more than one set in the list """ duplicates = set() for i, myset in enumerate(setlist): othersets = set().union(*setlist[i+1:]) duplicates.update(myset & othersets) return dup...
bigcode/self-oss-instruct-sc2-concepts
import binascii import itertools def xor(data, key): """Return `data` xor-ed with `key`.""" key = key.lstrip("0x") key = binascii.unhexlify(key) return bytearray([x ^ y for x, y in zip(data, itertools.cycle(key))])
bigcode/self-oss-instruct-sc2-concepts
def step_count(group_idx): """Return the amount of index changes within group_idx.""" cmp_pos = 0 steps = 1 if len(group_idx) < 1: return 0 for i in range(len(group_idx)): if group_idx[cmp_pos] != group_idx[i]: cmp_pos = i steps += 1 return steps
bigcode/self-oss-instruct-sc2-concepts
def ds_read_mock(data_set, *args, **kwargs): """ Mock of IkatsApi.ts.fid method Same parameters and types as the original function """ return {"description": "description of my data set", "ts_list": ['00001', '00002', '00003', ...
bigcode/self-oss-instruct-sc2-concepts
def ns(s): """remove namespace, but only it there is a namespace to begin with""" if '}' in s: return '}'.join(s.split('}')[1:]) else: return s
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_mro(cls): """ Wrapper on top of :func:`inspect.getmro` that recognizes ``None`` as a type (treated like ``type(None)``). """ if cls is type(None) or cls is None: return (type(None), object) else: assert isinstance(cls, type) return inspect.getmro(...
bigcode/self-oss-instruct-sc2-concepts
def create_new_code(questionnaire, configuration): """ Create a new code for a Questionnaire based on the configuration. Args: questionnaire (Questionnaire): The Questionnaire object. configuration (str): The code of the configuration. Returns: str. """ return '{}_{}'.f...
bigcode/self-oss-instruct-sc2-concepts
def get_dbot_level(threat_level_id: str) -> int: """ MISP to DBOT: 4 = 0 (UNDEFINED to UNKNOWN) 3 = 2 (LOW to SUSPICIOUS) 1 | 2 = 3 (MED/HIGH to MALICIOUS) Args: threat_level_id (str): Returns: int: DBOT score """ if threat_level_id in ('1', '2'): return 3 ...
bigcode/self-oss-instruct-sc2-concepts
def project_using_projection_matrix(data_to_transform, projection_matrix): """ Projects given data into lower dimentional subspace using the provided projection_matrix. """ projected_data = data_to_transform * projection_matrix; return projected_data
bigcode/self-oss-instruct-sc2-concepts
import math def constrain_angle(angle: float) -> float: """Wrap an angle to the interval [-pi, pi].""" return math.atan2(math.sin(angle), math.cos(angle))
bigcode/self-oss-instruct-sc2-concepts
def get_meta_file_metainfo(img_file, labels): """Return meta information about image in 'img_file' file. This information includes synset (str), numerical class label and human readeable set of class labels (comma separated str) """ synset = img_file.split('/')[-2] if synset not in labels:...
bigcode/self-oss-instruct-sc2-concepts
import itertools def generate_final_heads(*iterables): """ Generate unique headers from files :param iterables: headers file :return: a unique set of headers """ return { head for head in itertools.chain(*iterables) }
bigcode/self-oss-instruct-sc2-concepts
def bytearray_to_hex(data): """Convert bytearray into array of hexes to be printed.""" return ' '.join(hex(ord(byte)) for byte in data)
bigcode/self-oss-instruct-sc2-concepts
def get_attr_connections(source_attr): """ It returns the inputs and outputs connections of an attribute. :param source_attr: Attribute Object. :return: dictionary with the inputs and outputs connections. """ return {'inputs': source_attr.inputs(p=True), 'outputs': source_attr.outputs(p=True)}
bigcode/self-oss-instruct-sc2-concepts
def _to_lower(items): """ Converts a list of strings into a list of lower case strings. Parameters ---------- items : list A list of strings. Returns ------- The list of items all converted to lower case. """ return [item.lower() for item in items]
bigcode/self-oss-instruct-sc2-concepts
import codecs def _convert_text_eb2asc(value_to_convert): """ Converts a string from ebcdic to ascii :param value_to_convert: The ebcdic value to convert :return: converted ascii text """ val = codecs.encode(codecs.decode(value_to_convert, "cp500"), "latin-1") return val
bigcode/self-oss-instruct-sc2-concepts
def get_all(isamAppliance, check_mode=False, force=False): """ Get management authorization - roles """ return isamAppliance.invoke_get("Get management authorization - roles", "/authorization/roles/v1")
bigcode/self-oss-instruct-sc2-concepts
def generate_global(keep, scores, check_keep, check_scores): """ Use a simple global threshold sweep to predict if the examples in check_scores were training data or not, using the ground truth answer from check_keep. """ prediction = [] answers = [] for ans, sc in zip(check_keep, check_...
bigcode/self-oss-instruct-sc2-concepts
import pathlib import sqlite3 def open_db( path: pathlib.Path = pathlib.Path(__file__).parent.parent.joinpath( "data" ).resolve() ) -> sqlite3.Connection: """Opens a connection to the bot_o_mat.db file. Configures the row_factory to return a List[dict] instead of List[tuple]. Returns the c...
bigcode/self-oss-instruct-sc2-concepts
def isIterable(obj, returnTrueForNone=False): """ # To test out of the systemtools-venv: isIterable(np.arange(0.0, 0.5, 0.1) :example: >>> isIterable([]) True >>> isIterable([1]) True >>> isIterable([None]) True >>> isIterable(None) ...
bigcode/self-oss-instruct-sc2-concepts
def vp_from_ke(m): """ Computes the vanishing point from the product of the intrinsic and extrinsic matrices C = KE. The vanishing point is defined as lim x->infinity C (x, 0, 0, 1).T """ return (m[0, 0]/m[2,0], m[1,0]/m[2,0])
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict import yaml def load_website_sources_list( config_filename: str = "website_sources.yaml", ) -> List[Dict]: """ Loads a list of websites with attributes about those websites as a List of Dicts. """ # loads the websites to scrape from with open(con...
bigcode/self-oss-instruct-sc2-concepts
def case_fold(text): """Converts text to lower case.""" return text.lower()
bigcode/self-oss-instruct-sc2-concepts
import torch def smooth_l1_loss(pred, target, beta=1.0): """ Smooth L1 Loss introduced in [1]. Args: pred (:obj:`torch.Tensor`): The predictions. target (:obj:`torch.Tensor`): The learning targets. beta (float, optional): The threshold in the piecewise function. Defaul...
bigcode/self-oss-instruct-sc2-concepts
def get_ta(tr, n_slices): """ Get slice timing. """ return tr - tr/float(n_slices)
bigcode/self-oss-instruct-sc2-concepts
def is_left(p0, p1, p2): """ Tests if a point is on left or right of an infinite line input: three points p0, p1, p2 returns: >0 if p2 is left of line thru p0 and p1 =0 if p2 is on line <0 if p2 is right of the line """ return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) *...
bigcode/self-oss-instruct-sc2-concepts
def get_message_index(response, message): """Returns the index of message in search response, -1 if not found""" for n, result in enumerate(response): if result.object == message: return n return -1
bigcode/self-oss-instruct-sc2-concepts
import math import functools import operator def log_beta(x, y, tol=0.): """ Computes log Beta function. When ``tol >= 0.02`` this uses a shifted Stirling's approximation to the log Beta function. The approximation adapts Stirling's approximation of the log Gamma function:: lgamma(z) ≈ (...
bigcode/self-oss-instruct-sc2-concepts