seed
stringlengths
1
14k
source
stringclasses
2 values
def _select_compcor(compcor_cols, n_compcor): """Retain a specified number of compcor components.""" # only select if not "auto", or less components are requested than there actually is if (n_compcor != "auto") and (n_compcor < len(compcor_cols)): compcor_cols = compcor_cols[0:n_compcor] return ...
bigcode/self-oss-instruct-sc2-concepts
def generalize_version(package): """Add `.*` to package versions when it is needed.""" dep = package if ("=" in dep or (dep[-1].isdigit() and "." in dep)) and not dep[-2:] == ".*": dep += ".*" if " " in dep and not "." in dep.split()[1]: dep += ".*" return dep
bigcode/self-oss-instruct-sc2-concepts
def ph_color_code(value): """ :param value: This is a pH value which is having its color multiplexed. Description: This takes a pH value as input and returns a color to be used in the form of a string. """ if value > 12.6: return 'navy' elif value >11.2: return 'blue' elif value >9.8: return 'dodgerb...
bigcode/self-oss-instruct-sc2-concepts
import torch def gaussian_kl(mu, logsigma): """ Analytically compute KL divergence between the multivariate gaussian defined by the input params (assuming diagonal covariance matrix) and N(0, I). Arguments: mu (torch.Tensor): Mean. Expected size (N x num_variables) logsigma (torch.T...
bigcode/self-oss-instruct-sc2-concepts
def query_merge(query: dict, **kwargs: dict) -> dict: """ Merge a dictionary and key word arguments into a single dictionary. Used to merge a MongoDB query and key word arguments into a single query. :param query: The dictionary to merge. :param kwargs: The key word arguments to merge. :return...
bigcode/self-oss-instruct-sc2-concepts
def search_to_url(search: str) -> str: """Transform user search terms into ready to use URL""" search = search.lower().replace(" ", "%20") return f"https://uk.indeed.com/jobs?q={search}&l=United%20Kingdom"
bigcode/self-oss-instruct-sc2-concepts
def determine_format(tileSource): """ Given a tile source, return the vendor format. :param tileSource: a large_image tile source. :returns: the vendor or None if unknown. """ metadata = tileSource.getInternalMetadata() or {} if tileSource.name == 'openslide': if metadata.get('opens...
bigcode/self-oss-instruct-sc2-concepts
def __find_number_of_repeats(seq_before, seq, seq_after): """ Finds the number of repeats before or after a mutation. :param seq_before: the genomic sequence before the mutation (str) :param seq: the genomic sequence of the mutation (str) :param seq_after: the sequence after the mutation (str) ...
bigcode/self-oss-instruct-sc2-concepts
def kelvin_to_celsius(kelvin): """ Convert kelvin temperature to celsius. """ return kelvin-273.15
bigcode/self-oss-instruct-sc2-concepts
def sec2hour_min_sec(seconds): """ Convert elapsed seconds to hours, minutes and seconds #Credits: https://codereview.stackexchange.com/questions/174796/convert-seconds-to-hours-minutes-seconds-and-pretty-print Parameters ---------- seconds : long int elapsed seconds Returns ------- str string with conve...
bigcode/self-oss-instruct-sc2-concepts
def _LLF(job, t): """ Least-Laxity-First assigns higher priority to jobs with lesser laxity (slack). The laxity (slack) of a job of a job with deadline d at time t is equal to deadline - t - (time required to complete the remaining portion of the job) """ return job.deadline - t - job.remai...
bigcode/self-oss-instruct-sc2-concepts
def calc_ttr(df_ttr): """Calculates travel time reliability. Args: df_ttr, a pandas dataframe. Returns: df_ttr, a pandas dataframe with new ttr column. """ # Working vehicle occupancy assumptions: VOCt = 1 df_ttr['VOLt'] = df_ttr['pct_truck'] * df_ttr['dir_aadt'] * 365 df_ttr['ttr'] = df...
bigcode/self-oss-instruct-sc2-concepts
def trunc(s,min_pos=0,max_pos=75,ellipsis=True): """Return a nicely shortened string if over a set upper limit (default 75 characters) What is nicely shortened? Consider this line from Orwell's 1984... 0---------1---------2---------3---------4---------5---------6---------7----> When we are omn...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _check_is_list(obj): """Check whether obj is a list""" return isinstance(obj, (list, List))
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Sequence def get_involved_bits(instruction) -> Tuple[Sequence[int], Sequence[int]]: """Returns the bits involved in the instruction. :param instruction: The instruction of interest. :return: The quantum and classical bits used by the considered instruction. ...
bigcode/self-oss-instruct-sc2-concepts
import socket import struct import random def gen_random_ip() -> str: """ Generate random ip From: https://stackoverflow.com/questions/21014618/python-randomly-generated-ip-address-of-the-string """ return socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff)))
bigcode/self-oss-instruct-sc2-concepts
def leaf_size(request): """ Fixture to specify IntervalTree leaf_size parameter; to be used with the tree fixture. """ return request.param
bigcode/self-oss-instruct-sc2-concepts
import math def is_equal(aabb1, aabb2, rel_tol=1e-9, abs_tol=1e-7): """ Check if two AABBs aabb1 and aabb2 are approximately equal. The two AABBs are considered equal if the min and max points of the AABBs are componentwise approximately equal. For the componentwise equality check, the standard funct...
bigcode/self-oss-instruct-sc2-concepts
def CountName(name): """Returns the name of the auxiliary count member used for array typed.""" return '%s_bytes' % name
bigcode/self-oss-instruct-sc2-concepts
import random def any_int(min_value=0, max_value=100, **kwargs): """ Return random integer from the selected range >>> result = any_int(min_value=0, max_value=100) >>> type(result) <type 'int'> >>> result in range(0,101) True """ return random.randint(min_value, max_value)
bigcode/self-oss-instruct-sc2-concepts
def _get_field_name(svl_axis): """ Extracts the name of the field for the SVL plot. Parameters ---------- svl_axis : dict The SVL axis specifier. Returns ------- str The name of the field in the axis, or the transform statement. """ if "transform" in svl_axis: ...
bigcode/self-oss-instruct-sc2-concepts
def copy_factory(src, dest): """Copy Dash I/O Factory When a Dash component has been wrapped in additional layout to make a composite it is necessary to copy the embedded component I/O definition to the outermost component. This will then allow the composite component to be referenced in Dash callb...
bigcode/self-oss-instruct-sc2-concepts
def read_file(file_path, ignore_error=False): """Safely read file and return empty str in case ignore_error fla is set.""" try: with open(file_path, encoding="utf-8") as file: return file.read() except OSError as err: if ignore_error: return '' raise err
bigcode/self-oss-instruct-sc2-concepts
def read_input(input_path: str) -> list: """take input file path and return appropriate data structure""" with open(input_path, 'r') as input_file: lines = list() for line in input_file.readlines(): lines.append(line.strip()) return lines
bigcode/self-oss-instruct-sc2-concepts
import json def get_sub_suite(database, sub_suite_id): """Sub suite gets a sub suite by suite_id from database. :param database: The database to get sub suites from. :type database: :obj:`etos_lib.lib.database.Database` :param sub_suite_id: The suite ID of the sub suite in database. :type sub_sui...
bigcode/self-oss-instruct-sc2-concepts
from typing import Type import enum def is_enum(typ: Type) -> bool: """ Test if class is Enum class. """ try: return issubclass(typ, enum.Enum) except TypeError: return isinstance(typ, enum.Enum)
bigcode/self-oss-instruct-sc2-concepts
def get_iou(pred_box, gt_box): """ pred_box : the coordinate for predict bounding box (x, y, w, h) gt_box : the coordinate for ground truth bounding box (x, y, w, h) return : the iou score """ # 1.get the coordinate of inters ixmin = max(pred_box[0], gt_box[0]) ixmax = min(pred_box[0...
bigcode/self-oss-instruct-sc2-concepts
def distance(coords): """Calculate the distance of a path between multiple points Arguments received: coords — list of coordinates representing a path Arguments returned: distance -- total distance as a float """ distance = 0 for p1, p2 in zip(coords[:-1], coords[1:]): distance...
bigcode/self-oss-instruct-sc2-concepts
def compute_indentation(props): """ Compute the indentation in inches from the properties of a paragraph style. """ res = 0 for k, v in props.items(): if k in ['margin-left', 'text-indent']: try: res += float(v.replace('in', '')) except: ...
bigcode/self-oss-instruct-sc2-concepts
def unbalance(A, B, C, all=False): """ Voltage/Current Unbalance Function. Performs a voltage/current unbalance calculation to determine the maximum current/voltage unbalance. Returns result as a decimal percentage. Parameters ---------- A: float Phase-A value ...
bigcode/self-oss-instruct-sc2-concepts
def valiant_license() -> str: """The expected app license.""" return "MIT"
bigcode/self-oss-instruct-sc2-concepts
import uuid def nsuuid_to_uuid(nsuuid): """Convert Objective-C NSUUID type to native Python UUID type.""" return uuid.UUID(nsuuid.UUIDString())
bigcode/self-oss-instruct-sc2-concepts
import operator def size_maxed(inner, outer, exact=False): """Return True if the inner QSize meets or exceeds the outer QSize in at least one dimension. If exact is True, return False if inner is larger than outer in at least one dimension.""" oper = operator.eq if exact else operator.ge ret...
bigcode/self-oss-instruct-sc2-concepts
import json import base64 def json_safe(string, content_type='application/octet-stream'): """Returns JSON-safe version of `string`. If `string` is a Unicode string or a valid UTF-8, it is returned unmodified, as it can safely be encoded to JSON string. If `string` contains raw/binary data, it is Base6...
bigcode/self-oss-instruct-sc2-concepts
def get_multiplicative_cooling_schedule_function(cooling_ratio_multiplier): """ Returns a cooling schedule function of the form f(T) = a*T, "a" being the cooling ratio multiplier - a real number between 0 and 1 (As specified in the proforma) :param cooling_ratio_multiplier: real number a, 0 <= a <= 1 :...
bigcode/self-oss-instruct-sc2-concepts
def prepare_id(id_): """ if id_ is string uuid, return as is, if list, format as comma separated list. """ if isinstance(id_, list): return ','.join(id_) elif isinstance(id_, str): return id_ else: raise ValueError(f'Incorrect ID type: {type(id_)}')
bigcode/self-oss-instruct-sc2-concepts
def make_description(comment): """Construct a single comment string from a fancy object.""" ret = '\n\n'.join(text for text in [comment.get('shortText'), comment.get('text')] if text) return ret.strip()
bigcode/self-oss-instruct-sc2-concepts
import calendar def _month_number(x): """Return the month number for the fullname of a month""" return list(calendar.month_name).index(x)
bigcode/self-oss-instruct-sc2-concepts
import torch def tlbr2cthw(boxes): """ Convert top/left bottom/right format `boxes` to center/size corners." :param boxes: bounding boxes :return: bounding boxes """ center = (boxes[..., :2] + boxes[..., 2:])/2 sizes = boxes[..., 2:] - boxes[..., :2] return torch.cat([center, sizes], d...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def ensure_list(obj): """Accepts a thing, a list of things or None and turns it into a list.""" if isinstance(obj, Iterable): return list(obj) if obj is None: return [] return [obj]
bigcode/self-oss-instruct-sc2-concepts
import re def parse_results_with_regex(output, regex): """Find and returns the regex matching results in output Looks through the output line by line looking for a matching regex. The function assembles a list of lists where each parent list is the results for that position in the regex string and ea...
bigcode/self-oss-instruct-sc2-concepts
def parse_none(data: bytes) -> bytes: """Return `data` as is.""" return data
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def convert_to_date(s): """ Convert the date into a useful format. """ return datetime.strptime(s, '%m/%d/%Y')
bigcode/self-oss-instruct-sc2-concepts
def linear_growth( start: float, end: float, start_time: int, end_time: int, trade_time: int ) -> float: """ Simple linear growth function. Grows from start to end after end_time minutes (starts after start_time minutes) """ time = max(0, trade_time - start_time) rate = (end - start) / (end_time...
bigcode/self-oss-instruct-sc2-concepts
def policy_compare(sen_a, sen_b, voting_dict): """ Input: last names of sen_a and sen_b, and a voting dictionary mapping senator names to lists representing their voting records. Output: the dot-product (as a number) representing the degree of similarity between two senators' voting p...
bigcode/self-oss-instruct-sc2-concepts
def get_leaves(nodes): """Return a list containing the leaves of the graph defined by nodes.""" leaves = [] for n in nodes: if not n.children: leaves.append(n) return leaves
bigcode/self-oss-instruct-sc2-concepts
def H_to_Rt(H): """Converts 4x4 homogeneous transformation matrix into 3x3 rotation matrix and 3x1 translation vector.""" return H[0:3, 0:3], H[0:3, 3]
bigcode/self-oss-instruct-sc2-concepts
def comparePoEVREQ(po1, po2): """ Compare two Package or PackageEVR objects for equality. """ (e1, v1, r1) = (po1.epoch, po1.version, po1.release) (e2, v2, r2) = (po2.epoch, po2.version, po2.release) if r1 != r2: return False if v1 != v2: return False if e1 != e2: return False return...
bigcode/self-oss-instruct-sc2-concepts
def _FindRuleTriggerFiles(rule, sources): """Find the list of files which a particular rule applies to. Arguments: rule: the rule in question sources: the set of all known source files for this project Returns: The list of sources that trigger a particular rule. """ rule_ext = rule['extension'] ...
bigcode/self-oss-instruct-sc2-concepts
import yaml def load_yaml(filename): """ Load YAML data from a file """ with open(filename) as f: # yaml.BaseLoader leaves everything as a string, # so doesn't convert "no" to False data = yaml.load(f, Loader=yaml.BaseLoader) return data
bigcode/self-oss-instruct-sc2-concepts
def aggregate_sart(data, sub_num): """ Aggregate data from the SART task. Calculates various summary statistics for the SART task for a given subject. Parameters ---------- data : dataframe Pandas dataframe containing a single subjects trial data for the task. sub_num : str ...
bigcode/self-oss-instruct-sc2-concepts
def stat_to_string(name, value, nice_names): """ Method that converts a metric object into a string for displaying on a plot Args: name: (str), long name of a stat metric or quantity value: (float), value of the metric or quantity Return: (str), a string of the metric name, ...
bigcode/self-oss-instruct-sc2-concepts
def tail(iterable): """Returns all elements excluding the first out of an iterable. :param iterable: Iterable sequence. :returns: All elements of the iterable sequence excluding the first. """ return iterable[1:]
bigcode/self-oss-instruct-sc2-concepts
def to_title(text): """ Description: Convert text to title type and remove underscores :param text: raw text :return: Converted text """ return str(text).title().replace('_', ' ')
bigcode/self-oss-instruct-sc2-concepts
def first(x, y): """First argument""" return x
bigcode/self-oss-instruct-sc2-concepts
def diff_view(str1, str2): """ Calculate the lengths of the longest common prefix and suffix between str1 and str2. Let str1 = axb of length m and str2 = ayb of length n, then this function finds and returns i and j such that: str1[0:i] = str2[0:i] = a and str1[m-j:] = str2[n-j:] = b. In the ca...
bigcode/self-oss-instruct-sc2-concepts
def parse_list_to_string(tags): """ Parses a list of tags into a single string with the tags separated by comma :param tags: A list of tags :return: A string with tags separated by comma """ return ', '.join(tags)
bigcode/self-oss-instruct-sc2-concepts
def parseResult(rst): """Parse the results returned by snopt and convert to a dict.""" return {'flag': rst.flag, 'obj': rst.obj, 'x': rst.sol, 'f': rst.fval}
bigcode/self-oss-instruct-sc2-concepts
def sum_env_dict(envs): """Sums counts from the data structure produced by count_envs.""" return sum([sum(env.values()) for env in envs.values()])
bigcode/self-oss-instruct-sc2-concepts
def has_file_extension(file_path: str, file_extension: str) -> bool: """ Checks if a file path ends with a given file extension. """ return file_path.lower().endswith('.' + file_extension)
bigcode/self-oss-instruct-sc2-concepts
def sekunde_v_format(sek): """ Pretvori sekunde `sek` v format hh:mm:ss. """ if isinstance(sek, str): return sek h = sek // 3600 m = (sek % 3600) // 60 s = sek % 60 return "{:0>2d}:{:0>2d}:{:0>2d}".format(h, m, s)
bigcode/self-oss-instruct-sc2-concepts
def colon_labels2binary(report_labels): """ Convert the pre-defined labels extracted from colon reports to binary labels used for classification Params: report_labels (dict(list)): the dict containing for each colon report the pre-defined labels Returns: a dict containing for each colon report the set of binary...
bigcode/self-oss-instruct-sc2-concepts
def grain_to_dry_malt_weight(malt): """ Grain to DME Weight :param float grain: Weight of Grain :return: DME Weight :rtype: float """ return malt * 3.0 / 5.0
bigcode/self-oss-instruct-sc2-concepts
import re def get_title_display(title: str, year: int, url: str) -> str: """ Extract simplified title. Parameters ---------- title (str): movie title year (int): date of the movie url (str): url of the movie poster Returns ---------- title_display (str): format "title, year, ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import TextIO def read_pvarcolumns(path: str) -> List[str]: """Get the column names from the pvar file (not constrained like bim, especially when converted from VCF)""" f_pvar: TextIO = open(path, 'rt') line: str = '#' header: List[str] = [] while line.startswit...
bigcode/self-oss-instruct-sc2-concepts
def _get_taxon(tid, taxdump): """Get information of a given taxId from taxonomy database. Parameters ---------- tid : str taxId to query taxdump : dict taxonomy database Returns ------- dict information of taxon Raises ------ ValueError If t...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def product_filename_retrieve(filename): """ Retrieve information from the standard product filename. :param filename: file name. :return: filename information dictionary. """ file_name = pathlib.PureWindowsPath(filename) file_stem = file_name.stem.split("_") return di...
bigcode/self-oss-instruct-sc2-concepts
def get_text_color(background_color): """Select the appropriate text color (black or white) based on the luminance of the background color. Arguments: background_color (tuple): The record color (RGB or RGBA format). Returns: tuple: The chosen text color (black or white). """ # Cou...
bigcode/self-oss-instruct-sc2-concepts
def transition_filename(tr): """Get the part of the filename specifying the transition (e.g. BKstar) from a transition string (e.g. B->K*).""" return tr.replace('->', '').replace('*', 'star')
bigcode/self-oss-instruct-sc2-concepts
def assert_endpoint_capabilities(endpoint, *interfaces): """Assert the endpoint supports the given interfaces. Returns a set of capabilities, in case you want to assert more things about them. """ capabilities = endpoint["capabilities"] supported = set(feature["interface"] for feature in capabi...
bigcode/self-oss-instruct-sc2-concepts
def normalize(numbers, total=1.0): """Multiply each number by a constant such that the sum is 1.0 (or total). >>> normalize([1,2,1]) [0.25, 0.5, 0.25] """ k = total / sum(numbers) return [k * n for n in numbers]
bigcode/self-oss-instruct-sc2-concepts
def convert_ms_object(ms_object): """ Converts the list of dictionaries with keys "key" and "value" into more logical value-key pairs in a plain dictionary. """ out_dict = {} for item in ms_object: out_dict[item["Key"]] = item["Value"] return out_dict
bigcode/self-oss-instruct-sc2-concepts
def percentage_scores(hits_list, p_list, nr_of_groups): """Calculates the percent score which is the cumulative number of hits below a given percentage. The function counts the number of hits in the hits_list contains below a percentage of the maximum hit score (nr_of_groups). It then subtracts the expected...
bigcode/self-oss-instruct-sc2-concepts
import collections def get_interface_config_common(device, mtu=None): """ Return the interface configuration parameters that is common to all device types. """ parameters = collections.OrderedDict() parameters['BOOTPROTO'] = 'none' parameters['ONBOOT'] = 'yes' parameters['DEVICE'] = de...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_angles_2qutrit() -> List[str]: """Return a list of angles for 2-qutrit gates.""" l = [] l.append("90") l.append("180") return l
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence def filter_overrides(overrides: Sequence[str]) -> Sequence[str]: """ :param overrides: overrides list :return: returning a new overrides list with all the keys starting with hydra. filtered. """ return [x for x in overrides if not x.startswith("hydra.")]
bigcode/self-oss-instruct-sc2-concepts
def get_attribute_terms(product): """ Function to iterate through all variants of a variable product and compile a list of attribute terms from them. :param product: Variable product and variants information :return: list of term names """ attribute_terms = list() for variation in product['...
bigcode/self-oss-instruct-sc2-concepts
def convert_feature_to_result_document(feature): """ "feature": { "number": 6, "type": "number" }, "feature": { "api": "ws2_32.WSASocket", "type": "api" }, "feature": { "match": "create TCP socket", "type": "match" }, "feature": { ...
bigcode/self-oss-instruct-sc2-concepts
def tensor_unsort(sorted_tensor, oidx): """ Unsort a sorted tensor on its 0-th dimension, based on the original idx. """ assert sorted_tensor.size(0) == len(oidx), "Number of list elements must match with original indices." backidx = [x[0] for x in sorted(enumerate(oidx), key=lambda x: x[1])] re...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_duplicate_sentencestops(text, stop_chars=".;!?:"): """Remove duplicate sentence stops eg hello world... --> hello world. Args: text (str or list): text to be cleaned. stop_chars (str, optional): Sentence stop characters to check for duplicates. Defaults to ".;!?:". ""...
bigcode/self-oss-instruct-sc2-concepts
def calc_rho_and_rho_bar_squared(final_log_likelihood, null_log_likelihood, num_est_parameters): """ Calculates McFadden's rho-squared and rho-bar squared for the given model. Parameters ---------- final_log_likelihood : float. ...
bigcode/self-oss-instruct-sc2-concepts
def d1r(dx, fc, i): """ first-order, right-sided derivative at index i """ D = (fc[i+1] - fc[i])/dx return D
bigcode/self-oss-instruct-sc2-concepts
import re def get_initial_query_limit(query: str): """Returns the LIMIT within a SPARQL query string. Args: query (str): SPARQL query string. Returns: int: Limit or 0 if no limit. """ pattern = r"(LIMIT )([\d]+)" match = re.search(pattern, query) if match is None: ...
bigcode/self-oss-instruct-sc2-concepts
def _get_resource_name(user_id, name): """ Get resource name by resource type. :param str user_id: PipelineAI 8 character user id that uniquely identifies the user that created the resource for super users this user_id is not ...
bigcode/self-oss-instruct-sc2-concepts
def coalesce_volume_dates(in_volumes, in_dates, indexes): """Sums volumes between the indexes and ouputs dates at the indexes in_volumes : original volume list in_dates : original dates list indexes : list of indexes Returns ------- volumes: new volume array dates: new dates array ...
bigcode/self-oss-instruct-sc2-concepts
def is_solution_valid(board, solution): """ Check if a generated solution is valid for a given board. :param board: The original, starting board. :param solution: A full solution, i.e. a list of Coordinates. :return: True if the solution is valid; False otherwise. """ if not solution: ...
bigcode/self-oss-instruct-sc2-concepts
def map_phred33_ascii_to_qualityscore(phred33_char: str) -> float: """Maps a ASCII phred33 quality character to a quality score >>> map_phred33_ascii_to_qualityscore("#") 2 >>> map_phred33_ascii_to_qualityscore("J") 41 """ return ord(phred33_char) - 33
bigcode/self-oss-instruct-sc2-concepts
def assert_keys(source_dict, keys): """ Check key presence within a dict. Args: - source_dict (dict): the dict for which key presence should be checked - keys (list): the list of keys whose presence should be checked Returns: list: empty list if all checks succeeded, list of erro...
bigcode/self-oss-instruct-sc2-concepts
def get_tri_category(score): """Get a 3 class integer classification label from a score between 0 and 1.""" if score >= 0 and score < 0.3333333333: return 0 elif score >= 0.3333333333 and score < 0.6666666666: return 1 else: return 2
bigcode/self-oss-instruct-sc2-concepts
def _get_nested(data, key): """ Return value for a hierrachical key (like a.b.c). Return None if nothing found. If there is a key with . in the name, and a subdictionary, the former is preferred: >>> print(_get_nested({'a.b': 10, 'a':{'b': 20}}, 'a.b')) 10 >>> print(_get_nested({'a': {'...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def build_pwsh_analyze_command(file: Path) -> str: """ Build command for powershell analyze Args: file(Path): files to execute lint Returns: str: powershell analyze command """ # Invoke script analyzer command = "Invoke-ScriptAnalyzer" # Return exi...
bigcode/self-oss-instruct-sc2-concepts
def l2i(path): """ Formats a list (['bla',0,'bla']) into a IMAS path ('bla[0].bla') :param path: ODS path format :return: IMAS path format """ ipath = path[0] for step in path[1:]: if isinstance(step, int) or step == ':': ipath += "[%s]" % step else: ...
bigcode/self-oss-instruct-sc2-concepts
def logOutUser(command): """ Check if command is to log out (o | logout). """ return (command.strip().lower() == "o" or command.strip().lower() == "logout")
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable import functools from operator import getitem def get_in(keys: Iterable): """Creates a function that returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys. >>> get_in(["a", "b", 1])({"a": {"b": [0, 1, 2]}}) 1 """ def get_in(coll): return functools.reduce(...
bigcode/self-oss-instruct-sc2-concepts
import re def escapeRegexChars(txt, escapeRE=re.compile(r'([\$\^\*\+\.\?\{\}\[\]\(\)\|\\])')): """Return a txt with all special regular expressions chars escaped.""" return escapeRE.sub(r'\\\1', txt)
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def is_coco_polygon(coco_label: Dict) -> bool: """Check if a given label is a valid polygon only label.""" has_bbox = "bbox" in coco_label and len(coco_label["bbox"]) == 4 has_segment = len(coco_label.get("segmentation", [])) > 0 no_keypoints = not coco_label.get("keypoints") ...
bigcode/self-oss-instruct-sc2-concepts
def _equivalence_partition(iterable, relation): """Partitions a set of objects into equivalence classes canned function taken from https://stackoverflow.com/a/38924631 Args: iterable: collection of objects to be partitioned relation: equivalence relation. I.e. relation(o1,o2) evaluates to ...
bigcode/self-oss-instruct-sc2-concepts
def _select_month_reindex(indices, month): """Subsets indices for given month then reindexes to original size.""" select_month = indices[indices.index.month == month] return select_month.reindex(index=indices.index)
bigcode/self-oss-instruct-sc2-concepts
import re def old_to_new_tracks(old_tracks: str) -> str: """ >>> old_to_new_tracks(EXAMPLE_INPUT) 'make_tracks li1 -x_offset 0.23 -x_pitch 0.46 -y_offset 0.17 -y_pitch 0.34\\nmake_tracks met1 -x_offset 0.17 -x_pitch 0.34 -y_offset 0.17 -y_pitch 0.34\\nmake_tracks met2 -x_offset 0.23 -x_pitch 0.46 -y_offse...
bigcode/self-oss-instruct-sc2-concepts
import ast def parse(data:str) -> object: """ Given a string with python source code, returns a python ast tree. """ return ast.parse(data)
bigcode/self-oss-instruct-sc2-concepts