seed
stringlengths
1
14k
source
stringclasses
2 values
def split_fullname(fullname: bytes): """ Split full backend string name into (namespace, box_id) tuple. >>> split_fullname(b'name.space.box_id') [b'name.space', b'box_id'] """ return fullname.rsplit(b'.', maxsplit=1)
bigcode/self-oss-instruct-sc2-concepts
def _evaluate_results(results): """ Evaluate resulting assertions. Evaluation is OK if all assertions are true, otherwise it is KO Parameters ---------- results: list(bool) List of all assertion execution results. Returns ------- str 'OK' if all assertions are true, 'K...
bigcode/self-oss-instruct-sc2-concepts
def sec_to_str(sec): """ Return a nice string given a number of seconds, such as 21:53. Takes into account hours, minutes, and seconds. """ s = "" if sec < 0: return "Unknown" hours = sec / 3600 min = (sec % 3600) / 60 sec = sec % 60 if hours: ...
bigcode/self-oss-instruct-sc2-concepts
def CreateZoneRef(resources, data): """Create zone reference from object with project and zone fields.""" return resources.Parse( None, params={'project': data.project, 'zone': data.zone}, collection='compute.zones')
bigcode/self-oss-instruct-sc2-concepts
def cost_of_equity_growth(div, Mv, g): """ Calculates the cost of capital or equity shareholder required rate of return for an investment in which dividend is expected to grow at a constant growth rate (dividend is about to be paid) parameters: ----------- d = dividend per share. Mv = ex-dividend share pri...
bigcode/self-oss-instruct-sc2-concepts
def get_ground_truth(reader_study, display_set, question): """Get the ground truth value for the display_set/question combination in reader_study.""" ground_truths = reader_study.statistics["ground_truths"] return ground_truths[display_set][question]
bigcode/self-oss-instruct-sc2-concepts
def find_columns(num): """Build the table headings for the assignment sections""" return ' '.join([str(i) for i in range(1, num + 1)])
bigcode/self-oss-instruct-sc2-concepts
def verify_interval_in_state_vector(statevector, start, finish): """ Verifies if there is at least one non zero entry in a given interval in the state vectors cells, and returns true if positive :param statevector: state vector to be processed :param start: start of the interval ...
bigcode/self-oss-instruct-sc2-concepts
def absolute_latencies(relative_latencies): """ Compute absolute delay + stride for a each in a stack of layers. Arguments: ---------- relative_latencies: list of tuples each tuple is (rel_delay, rel_stride) Returns: -------- absolute_latencies: list of tuples each tupl...
bigcode/self-oss-instruct-sc2-concepts
def format_version(value, hero_version=False): """Formats integer to displayable version name""" label = "v{0:03d}".format(value) if not hero_version: return label return "[{}]".format(label)
bigcode/self-oss-instruct-sc2-concepts
def get_file_line_count(filename): """ Get the line count for the specified file """ with open(filename) as f: return sum(1 for _ in f)
bigcode/self-oss-instruct-sc2-concepts
import copy def flatten_dict(data: dict, delimiter: str = "/") -> dict: """ Overview: flatten the dict, see example Arguments: data (:obj:`dict`): Original nested dict delimiter (str): Delimiter of the keys of the new dict Returns: - (:obj:`dict`): Flattened nested dict...
bigcode/self-oss-instruct-sc2-concepts
def lowpass_filter_trace(tr, filter_order=5, number_of_passes=2): """ Lowpass filter. Args: tr (StationTrace): Stream of data. filter_order (int): Filter order. number_of_passes (int): Number of passes. Returns: StationTrace: Filtered...
bigcode/self-oss-instruct-sc2-concepts
def objects(obj_list): """Helper to return singular or plural of the word "object". Parameters: obj_list - any list Returns: string "object" or "objects" depending on the list length """ ret = 'objects' if len(obj_list) != 1 else 'object' return ret
bigcode/self-oss-instruct-sc2-concepts
def write_rex_file(bytes, path: str): """Write to disk a rexfile from its binary format""" new_file = open(path + ".rex", "wb") new_file.write(bytes) return True
bigcode/self-oss-instruct-sc2-concepts
def write_gao_weber_potential(parameters): """Write gao-weber potential file from parameters Parameters ---------- parameters: dict keys are tuple of elements with the values being the parameters length 14 """ lines = [] for (e1, e2, e3), params in parameters.items(): if ...
bigcode/self-oss-instruct-sc2-concepts
def symbol_filename(name): """Adapt the name of a symbol to be suitable for use as a filename.""" return name.replace("::", "__")
bigcode/self-oss-instruct-sc2-concepts
def viz_b(body): """Create HTML b for graphviz""" return '<B>{}</B>'.format(body)
bigcode/self-oss-instruct-sc2-concepts
def op_table_md(op_sel, op_name, L1, L2): """Generate this (ish): | 6'h00 | add | a+b+d |(a+b+d) gte 2^16 | Addition | | 6'h01 | sub | a+~b+1 |(a+~b+1) gte 2^16 | Subtraction | | 6'h03 | abs |(a lt 0)? (0-a) : a | a[15] | Abso...
bigcode/self-oss-instruct-sc2-concepts
def _unscale(x,rmin,rmax,smin,smax): """ Undo linear scaling. """ r = (smax-smin)/(rmax-rmin) x_ = smin + r * (x-rmin) return x_
bigcode/self-oss-instruct-sc2-concepts
def _escape_filename(filename): """Escape filenames with spaces by adding quotes (PRIVATE). Note this will not add quotes if they are already included: >>> print _escape_filename('example with spaces') "example with spaces" >>> print _escape_filename('"example with spaces"') "example with ...
bigcode/self-oss-instruct-sc2-concepts
def validate_instructions(instructions, _): """Check that the instructions dict contains the necessary keywords""" instructions_dict = instructions.get_dict() retrieve_files = instructions_dict.get('retrieve_files', None) if retrieve_files is None: errmsg = ( '\n\n' 'no...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from datetime import datetime def from_litter_robot_timestamp( timestamp: Optional[str], ) -> Optional[datetime]: """Construct a UTC offset-aware datetime from a Litter-Robot API timestamp. Litter-Robot timestamps are in the format `YYYY-MM-DDTHH:MM:SS.ffffff`, so to get t...
bigcode/self-oss-instruct-sc2-concepts
def calculate_score(move): """ Calculate the chance of this being a "good move" based on the following criteria: :moves_available: number of moves to choose between\n :move_num: how many moves we are into the game\n :num_pieces_self: how many pieces pieces we have left\n :num_pieces_opp: how ma...
bigcode/self-oss-instruct-sc2-concepts
def upload_path(instance, filename): """Return path to save FileBackup.file backups.""" return f'examiner/FileBackup/' + filename
bigcode/self-oss-instruct-sc2-concepts
def is_palindrome(number): """Check if number is the same when read forwards and backwards.""" if str(number) == str(number)[::-1]: return True return False
bigcode/self-oss-instruct-sc2-concepts
def convertAttributeProto(onnx_arg): """ Convert an ONNX AttributeProto into an appropriate Python object for the type. NB: Tensor attribute gets returned as the straight proto. """ if onnx_arg.HasField('f'): return onnx_arg.f elif onnx_arg.HasField('i'): return onnx_arg.i ...
bigcode/self-oss-instruct-sc2-concepts
def simple_goal_subtract(goal, achieved_goal): """ We subtract the achieved goal from the desired one to see how much we are still far from the desired position """ assert goal.shape == achieved_goal.shape return goal - achieved_goal
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from datetime import datetime def determine_vaccine_date(vaccine_year: str, vaccine_month: str) -> Optional[str]: """ Determine date of vaccination and return in datetime format as YYYY or YYYY-MM """ if vaccine_year == '' or vaccine_year == 'Do not know': retur...
bigcode/self-oss-instruct-sc2-concepts
import torch def renormalize(log_p, alpha): """ Take the model-computed log probabilities over candidates (log_p), apply a smoothing parameter (alpha), and renormalize to a q distribution such that the probabilities of candidates sum to 1. Return the log of q. """ alpha_log_p = alpha * log_p ...
bigcode/self-oss-instruct-sc2-concepts
def format_table(table, key_space=5): """ Accepts a dict of {string: string} and returns a string of the dict formatted into a table """ longest = 0 for k in table: if len(k) > longest: longest = len(k) result = '' for k, v in table.iteritems(): k += (longest...
bigcode/self-oss-instruct-sc2-concepts
import json def loads(s): """Potentially remove UTF-8 BOM and call json.loads()""" if s and isinstance(s, str) and s[:3] == '\xef\xbb\xbf': s = s[3:] return json.loads(s)
bigcode/self-oss-instruct-sc2-concepts
def query_hash(query_url): """ Generate a compact identifier from a query URL. This idenifier is then used for @ids of Ranges and Annotations. IIIF URI pattern: {scheme}://{host}/{prefix}/{identifier}/range/{name} {scheme}://{host}/{prefix}/{identifier}/annotation/{name} ...
bigcode/self-oss-instruct-sc2-concepts
import json def get_dataset_metadata(dataset_path: str): """ Many datasets outputted by the sklearn bot have a first comment line with important meta-data """ with open(dataset_path) as fp: first_line = fp.readline() if first_line[0] != '%': raise ValueError('arff data ...
bigcode/self-oss-instruct-sc2-concepts
def _get_metric_value(metrics, metric_name, sample_name, labels): """Get value for sample of a metric""" for metric in metrics: if metric.name == metric_name: for sample in metric.samples: if sample.name == sample_name and sample.labels == labels: return s...
bigcode/self-oss-instruct-sc2-concepts
def tf(tokens): """ Compute TF Args: tokens (list of str): input list of tokens from tokenize Returns: dictionary: a dictionary of tokens to its TF values """ d = {} s = len(tokens) for w in tokens: if w not in d: d[w] = 1.00/s else: d...
bigcode/self-oss-instruct-sc2-concepts
def find_range(nums): """Calculate the range of a given set of numbers.""" lowest = min(nums) highest = max(nums) r = highest - lowest return lowest, highest, r
bigcode/self-oss-instruct-sc2-concepts
def distance_calculator(focal_length, real_width_of_object, width_in_frame): """ This function is used to calculate the estimated distnace using triangle similarity :param1 (focal_length): The focal_length in the reference image as calculated :param2 (real_width_of_object): The real width of the ob...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import List def get_sorted_version_directories(changelog_path: Path) -> List[Path]: """Get all version directories and return them sorted as list.""" directories = [item for item in changelog_path.iterdir() if item.is_dir()] return sorted( directories, ...
bigcode/self-oss-instruct-sc2-concepts
def _shape_to_size(shape): """ Compute the size which corresponds to a shape """ out = 1 for item in shape: out *= item return out
bigcode/self-oss-instruct-sc2-concepts
def time_to_str(time_min:str, time_max:str): """ Replace ':' to '-' from the time variables. Parameters ---------- time_min: str Time variable with ':'. time_max: str Time variable with ':'. Returns ------- time_min_str: str Time vari...
bigcode/self-oss-instruct-sc2-concepts
def GetCaId(settings): """Get ca_id to be used with GetCaParameters(). Args: settings: object with attribute level access to settings parameters. Returns: str like "FOO" or None (use primary parameters) """ return getattr(settings, 'CA_ID', None)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _find_interval_range(category_configs, interval: float) -> List[dict]: """Finds the range the interval is in and returns the configured mappings to the TransportGroups""" for interval_category in category_configs: min_interval = interval_category['min-interval'] if 'min-int...
bigcode/self-oss-instruct-sc2-concepts
def convert_segmentation_bbox(bbox: dict, page: dict) -> dict: """ Convert bounding box from the segmentation result to the scale of the characters bboxes of the document. :param bbox: Bounding box from the segmentation result :param page: Page information :return: Converted bounding box. """ ...
bigcode/self-oss-instruct-sc2-concepts
def resize_image(image, width, height): """Resize image to explicit pixel dimensions.""" width = int(width) height = int(height) aspect_ratio = image.width / image.height if height == 0: new_width = width new_height = int(round(width / aspect_ratio, 0)) elif width == 0: n...
bigcode/self-oss-instruct-sc2-concepts
def round_to_nearest(value, round_value=1000): """Return the value, rounded to nearest round_value (defaults to 1000). Args: value: Value to be rounded. round_value: Number to which the value should be rounded. Returns: Value rounded to nearest desired integer. """ if round...
bigcode/self-oss-instruct-sc2-concepts
def is_bbox_correct(bbox, width, height): """ :param bbox: bbox composed of 4 integer values [xmin, ymin, xmax, ymax] :param height: height of the image :param width: width of the image :return: True if bbox inside image, False otherwise """ # Check bbox inside image if b...
bigcode/self-oss-instruct-sc2-concepts
def to_time (wmi_time): """ Convenience wrapper to take a WMI datetime string of the form yyyymmddHHMMSS.mmmmmm+UUU and return a 9-tuple containing the individual elements, or None where string contains placeholder stars. @param wmi_time The WMI datetime string in yyyymmddHHMMSS.mmmmmm+UUU format @...
bigcode/self-oss-instruct-sc2-concepts
import ast def is_yield(statement): """ Is this a statement of the form `yield <expr>` """ return (isinstance(statement, ast.Expr) and isinstance(statement.value, ast.Yield))
bigcode/self-oss-instruct-sc2-concepts
def get_genes(prefix, percentile): """ Gets a list of genes from three files. One representing all genes in a sample, one representing the upper tail of a distribution of those genes, and one representing the lower tail of a distribution of those genes. """ allList = [] botList = [] topList = []...
bigcode/self-oss-instruct-sc2-concepts
def feet_to_meters(feet): """Convert feet to meters.""" try: value = float(feet) except ValueError: print("Unable to convert to float: %s", feet) else: return (0.3048 * value * 10000.0 + 0.5) / 10000.0
bigcode/self-oss-instruct-sc2-concepts
def concatenate_files(filenames): """ Concatenate the specified files, adding `line directives so the lexer can track source locations. """ contents = [] for filename in filenames: contents.append('`line 1 "%s" 1' % filename) with open(filename, 'rb') as f: contents.append(f....
bigcode/self-oss-instruct-sc2-concepts
def get_request_value(req, key): """ Return the value of the request object's JSON dictionary. """ request_json = req.get_json() if req.args and key in req.args: return req.args.get(key) elif request_json and key in request_json: return request_json[key] else: return ...
bigcode/self-oss-instruct-sc2-concepts
def parse(resp: dict): """ Parse response data for the repo commits query. """ branch = resp["repository"]["defaultBranchRef"] branch_name = branch.get("name") commit_history = branch["target"]["history"] total_commits = commit_history["totalCount"] commits = commit_history["nodes"] ...
bigcode/self-oss-instruct-sc2-concepts
def strip_hyphen(s): """ Remove hyphens and replace with space. Need to find hyphenated names. """ if not s: return '' return s.replace('-', ' ')
bigcode/self-oss-instruct-sc2-concepts
def last_column(worksheet) -> int: """ Quick way to determine the number of columns in a worksheet. Assumes that data is within the `CurrentRegion` of cell A1. :param worksheet: Excel Worksheet COM object, such as the one created by code like: app = win32com.client.Dispatch("Excel.Application") ...
bigcode/self-oss-instruct-sc2-concepts
def GetTag(node): """Strips namespace prefix.""" return node.tag.rsplit('}', 1)[-1]
bigcode/self-oss-instruct-sc2-concepts
def pad_func(before, after): """ Padding function. Operates on vector *in place*, per the np.pad documentation. """ def pad_with(x, pad_width, iaxis, kwargs): x[:pad_width[0]] = before[-pad_width[0]:] x[-pad_width[1]:] = after[:pad_width[1]] return return pad_with
bigcode/self-oss-instruct-sc2-concepts
def merge_blocks(a_blocks, b_blocks): """Given two lists of blocks, combine them, in the proper order. Ensure that there are no overlaps, and that they are for sequences of the same length. """ # Check sentinels for sequence length. assert a_blocks[-1][2] == b_blocks[-1][2] == 0 # sentinel size...
bigcode/self-oss-instruct-sc2-concepts
def transform_list_of_dicts_to_desired_list(curr_list, nested_key_name, new_list=[]): """ Returns a list of key values specified by the nested key Args: curr_list (list): list of dicts to be dissected nested_key_name (str): key name within nested dicts desired new_list (list): used ...
bigcode/self-oss-instruct-sc2-concepts
import mmap def map_fb_memory(fbfid, fix_info): """Map the framebuffer memory.""" return mmap.mmap( fbfid, fix_info.smem_len, mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE, offset=0 )
bigcode/self-oss-instruct-sc2-concepts
def square_of_digits(number: int) -> int: """Return the sum of the digits of the specified number squared.""" output = 0 for digit in str(number): output += int(digit) * int(digit) return output
bigcode/self-oss-instruct-sc2-concepts
def check_int(x): """ Check whether a int is valid :param x: The int :return: The result """ return 0 <= x <= 2147483647
bigcode/self-oss-instruct-sc2-concepts
def index(predicate, seq): """ Returns the index of the element satisfying the given predicate, or None. """ try: return next(i for (i, e) in enumerate(seq) if predicate(e)) except StopIteration: return None
bigcode/self-oss-instruct-sc2-concepts
def get_score(winner): """ You get 1 point for winning, and lose 1 point for losing. >>> get_score('tie') 0 >>> get_score('human') 1 >>> get_score('ai') -1 """ if winner == 'human': return +1 if winner == 'ai': return -1 return 0
bigcode/self-oss-instruct-sc2-concepts
def strip_markup(text): """Strip yWriter 6/7 raw markup. Return a plain text string.""" try: text = text.replace('[i]', '') text = text.replace('[/i]', '') text = text.replace('[b]', '') text = text.replace('[/b]', '') except: pass return text
bigcode/self-oss-instruct-sc2-concepts
def tokenize_spec(spec): """Tokenize a GitHub-style spec into parts, error if spec invalid.""" spec_parts = spec.split('/', 2) # allow ref to contain "/" if len(spec_parts) != 3: msg = 'Spec is not of the form "user/repo/ref", provided: "{spec}".'.format(spec=spec) if len(spec_parts) == 2 ...
bigcode/self-oss-instruct-sc2-concepts
def get_overall_misclassifications(H, training_points, classifier_to_misclassified): """Given an overall classifier H, a list of all training points, and a dictionary mapping classifiers to the training points they misclassify, returns a set containing the training points that H misclassifies. H is repr...
bigcode/self-oss-instruct-sc2-concepts
def list_to_string(list_): """ Returns a string from the given list >>> list_to_string(['1,', '2', '3']) >>> # 1, 2, 3 :param list_: list :return:str """ list_ = [str(item) for item in list_] list_ = str(list_).replace("[", "").replace("]", "") list_ = list_.replace("'", "").rep...
bigcode/self-oss-instruct-sc2-concepts
import torch def _gaussian_kernel_1d(size: int, sigma: float) -> torch.Tensor: """ Create 1-D Gaussian kernel with shape (1, 1, size) Args: size: the size of the Gaussian kernel sigma: sigma of normal distribution Returns: 1D kernel (1, 1, size) """ coords = torch.arange(size).to(dtype=torch.flo...
bigcode/self-oss-instruct-sc2-concepts
def merge_paths(base_uri, relative_path): """Merge a base URI's path with a relative URI's path.""" if base_uri.path is None and base_uri.authority is not None: return '/' + relative_path else: path = base_uri.path or '' index = path.rfind('/') return path[:index] + '/' + rel...
bigcode/self-oss-instruct-sc2-concepts
def _df_to_vector(distance_matrix, df, column): """Return a grouping vector from a ``DataFrame`` column. Parameters ---------- distance_marix : DistanceMatrix Distance matrix whose IDs will be mapped to group labels. df : pandas.DataFrame ``DataFrame`` (indexed by distance matrix ID...
bigcode/self-oss-instruct-sc2-concepts
def _compute_negative_examples( label, all_items, pos_items, item_to_labels, label_graph, assert_ambig_neg ): """ Compute the set of negative examples for a given label. This set consists of all items that are not labelled with a descendant of the ...
bigcode/self-oss-instruct-sc2-concepts
def get_or_create(table, **fields): """ Returns record from table with passed field values. Creates record if it does not exist. 'table' is a DAL table reference, such as 'db.spot' fields are field=value pairs Example: xpto_spot = get_or_create(db.spot, filename="xptoone.swf", \ descrip...
bigcode/self-oss-instruct-sc2-concepts
def get_py_param_type(context): """convert a param type into python accepted format. Related to the formats accepted by the parameter under dynamic reconfigure Args: context (dict): context (related to an interface description) Returns: str: variable type in python format related to pa...
bigcode/self-oss-instruct-sc2-concepts
def get_city_by_id(item_id): """Get City by Item ID. Given the item ID of a luxury good, return which city it needs to be brought to. Args: item_id (str): Item ID Returns: str: City name the item should be brought to. """ ids_to_city = { "RITUAL": "Caerleon", ...
bigcode/self-oss-instruct-sc2-concepts
import json def get_url_mapping(api, headers=None): """Fetch the mapping of project id to url from luci-config. Args: headers: Optional authentication headers to pass to luci-config. Returns: A dictionary mapping project id to its luci-config project spec (among which there is a repo_url key). "...
bigcode/self-oss-instruct-sc2-concepts
def low16(i): """ :param i: number :return: lower 16 bits of number """ return i % 65536
bigcode/self-oss-instruct-sc2-concepts
def gcd(a,b): """gcd(a,b) returns the greatest common divisor of the integers a and b.""" a = abs(a); b = abs(b) while (a > 0): b = b % a tmp=a; a=b; b=tmp return b
bigcode/self-oss-instruct-sc2-concepts
def average_height(team, num_team_players): """Calculates the average height(inches) for the team""" team_total_height = 0 for player in team['team_players']: team_total_height += player['height'] return round(team_total_height / num_team_players, 1)
bigcode/self-oss-instruct-sc2-concepts
def flesch_kincaid_grade_level(word_count, syllable_count): """Given a number of words and number of syllables in a sentence, computes the flesch kincaid grade level. Keyword arguments: word_count -- number of words in the sentence syllable_count -- number of syllables in the sentence """ r...
bigcode/self-oss-instruct-sc2-concepts
def merge(defaults, file, env): """Merge configuration from defaults, file, and environment.""" config = defaults # Merge in file options, if they exist in the defaults. for (k, v) in file.items(): if k in config: config[k] = v # Merge in environment options, if they exist in t...
bigcode/self-oss-instruct-sc2-concepts
def factorial(number): """Return the factorial of a number.""" accumulator = 1 for n in range(1, number + 1): accumulator *= n return accumulator
bigcode/self-oss-instruct-sc2-concepts
def remove_whitespace(x): """ Helper function to remove any blank space from a string x: a string """ try: # Remove spaces inside of the string x = "".join(x.split()) except: pass return x
bigcode/self-oss-instruct-sc2-concepts
def get_clean_messages(author, dataframe, limit=None, min_interval=None, max_interval=None, rand=False): """Retrieve the cleaned messages by a given author from a dataframe. min_interval, max_interval allow for only messages with a certain range of messageInterval to be selected. if True, rand will randomiz...
bigcode/self-oss-instruct-sc2-concepts
def progressBar(curr, total, b_length=60, prefix='', suffix='', decimals=0): """Return the progress bar Code from https://gist.github.com/aubricus/f91fb55dc6ba5557fbab06119420dd6a """ str_format = "{0:." + str(decimals) + "f}" percents = str_format.format(100 * (curr/ float(total))) filled_len ...
bigcode/self-oss-instruct-sc2-concepts
import binascii def hex_decode(string): """ Hex decode string Parameters ---------- string : str String to be decoded from hexadecimal Returns ------- str Text string with ASCII / unicode representation of hexadecimal input string """ return binascii.a2b_hex(st...
bigcode/self-oss-instruct-sc2-concepts
def parse_mdout(file): """ Return energies from an AMBER `mdout` file. Parameters ---------- file : str Name of output file Returns ------- energies : dict A dictionary containing VDW, electrostatic, bond, angle, dihedral, V14, E14, and total energy. """ vdw, ...
bigcode/self-oss-instruct-sc2-concepts
import re def changeAllAttributesInText(text, attribute, newValue, append): """ Changes the specified attribute in all tags in the provided text to the value provided in newValue. If append is 0, the value will be replaced. If append is anything else, the value will be appended to the end of the o...
bigcode/self-oss-instruct-sc2-concepts
def make_count_column(array): """Make column name for arrays elements count >>> make_count_column('/tender/items') '/tender/itemsCount' >>> make_count_column('/tender/items/additionalClassifications') '/tender/items/additionalClassificationsCount' >>> make_count_column('/tender/items/') '/t...
bigcode/self-oss-instruct-sc2-concepts
def camelcase(s): """Turn strings_like_this into StringLikeThis""" return ''.join([word.capitalize() for word in s.split('_')])
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime, timedelta def check_date_past_interval(check_date, interval=None): """Return True if given check_date is past the interval from current time. :param check_date: Datetime string like '2021-08-23 18:14:05' :type check_date: str :param interval: Hours amount to check in pa...
bigcode/self-oss-instruct-sc2-concepts
def fix_negatives(num): """ Some scopes represent negative numbers as being between 128-256, this makes shifts those to the correct negative scale. :param num: an integer :return: the same number, shifted negative as necessary. """ if num > 128: return num - 255 else: re...
bigcode/self-oss-instruct-sc2-concepts
def identifyCategoricalFeatures(x_data,categorical_cutoff): """ Takes a dataframe (of independent variables) with column labels and returns a list of column names identified as being categorical based on user defined cutoff. """ categorical_variables = [] for each in x_data: if x_data[each].nuni...
bigcode/self-oss-instruct-sc2-concepts
def _net_get_tx_id(id_offset: int, index: int) -> int: """ Returns the transmission id of a board, given its type's start_id and its index. """ return 2 * (id_offset + index)
bigcode/self-oss-instruct-sc2-concepts
import pickle def read_results(pickle_file_name): """Reads results from Pickle file. :param pickle_file_name: Path to input file. :return: result_dict: Dictionary created by `run_sfs`. """ pickle_file_handle = open(pickle_file_name, 'rb') result_dict = pickle.load(pickle_file_handle) pic...
bigcode/self-oss-instruct-sc2-concepts
import string def capitalize(string_raw): """Capitalize a string, even if it is between quotes like ", '. Args: string_raw (string): text to capitalize. Returns: string """ # return re.sub(r"\b[\w']", lambda m: m.group().capitalize(), string.lower()) return string.capwords(...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter from typing import OrderedDict def get_stats_document(document: Counter) -> OrderedDict: """ Résumé --- Pour un document donné calcule des statistiques liées à ce document comme le nombre unique de terme, la fréquence maximum d'un terme dans le document ou la fréquence m...
bigcode/self-oss-instruct-sc2-concepts
def fastq_infer_rg(read): """ Infer the read group from appended read information, such as produced by the samtools fastq command. Requires the read to be formatted such the rg tag is added to the end of the read name delimited by a ``_``. Returns the read group tag. """ rgstr = read.name.s...
bigcode/self-oss-instruct-sc2-concepts
import re def replace_g5_search_dots(keywords_query): """Replaces '.' with '-' in G5 service IDs to support old ID search format.""" return re.sub( r'5\.G(\d)\.(\d{4})\.(\d{3})', r'5-G\1-\2-\3', keywords_query )
bigcode/self-oss-instruct-sc2-concepts