seed
stringlengths
1
14k
source
stringclasses
2 values
def _is_list_like(x): """Helper which returns `True` if input is `list`-like.""" return isinstance(x, (tuple, list))
bigcode/self-oss-instruct-sc2-concepts
import re import string def replace_numbers(text): """Transform every number of the string into space.""" return re.sub('[%s]' % string.digits, ' ', text)
bigcode/self-oss-instruct-sc2-concepts
def convert(color): """Get (0-1, 0-1, 0-1) color code and converts it to (0-255, 0-255, 0-255). Parameters ---------- color : tuple RGB code in format (0-1, 0-1, 0-1) Returns ------- list a list representing RBG color code in format (0-255, 0-255, 0-255) """ return ...
bigcode/self-oss-instruct-sc2-concepts
def set_accuracy_95(num: float) -> float: """Reduce floating point accuracy to 9.5 (xxxx.xxxxx). Used by Hedron and Dihedron classes writing PIC and SCAD files. :param float num: input number :returns: float with specified accuracy """ # return round(num, 5) # much slower return float(f"{n...
bigcode/self-oss-instruct-sc2-concepts
def ClusterKey(cluster, key_type): """Return a cluster-generated public encryption key if there is one. Args: cluster: Cluster to check for an encryption key. key_type: Dataproc clusters publishes both RSA and ECIES public keys. Returns: The public key for the cluster if there is one, otherwise None...
bigcode/self-oss-instruct-sc2-concepts
def _GetProcJiffies(timer_list): """Parse '/proc/timer_list' output and returns the first jiffies attribute. Multi-CPU machines will have multiple 'jiffies:' lines, all of which will be essentially the same. Return the first one.""" if isinstance(timer_list, str): timer_list = timer_list.splitlines() fo...
bigcode/self-oss-instruct-sc2-concepts
def figure_asthetics(ax): """Change the asthetics of the given figure (operators in place). Parameters ---------- ax : matplotlib ax object """ ax.yaxis.grid() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.yaxis.set_ticks_position('left') ax.xaxi...
bigcode/self-oss-instruct-sc2-concepts
def pairs_quality(cand_rec_id_pair_list, true_match_set): """Pairs quality measures the efficiency of a blocking technique. Pairs quality is calculated as the number of true matches included in the candidate record pairs divided by the number of candidate record pairs generated by blocking. Para...
bigcode/self-oss-instruct-sc2-concepts
def is_power_of_two(n): """Check whether `n` is an exponent of two >>> is_power_of_two(0) False >>> is_power_of_two(1) True >>> is_power_of_two(2) True >>> is_power_of_two(3) False >>> if_power_of_two(16) True """ return n != 0 and ((n & (n - 1)) == 0)
bigcode/self-oss-instruct-sc2-concepts
def WaitForOpMaybe(operations_client, op, asyncronous=False, message=None): """Waits for an operation if asyncronous flag is on. Args: operations_client: api_lib.ml_engine.operations.OperationsClient, the client via which to poll op: Cloud ML Engine operation, the operation to poll asyncronous: b...
bigcode/self-oss-instruct-sc2-concepts
def is_func_bound(method, instance=None): """ check function is bound in class instance. >>> is_func_bound(lambda :None) False >>> is_func_bound(dict().get) True >>> x = dict(a=1) >>> is_func_bound(x.get, x) True >>> y = dict(a=1) >>> is_func_bound(x.get, y) False :param...
bigcode/self-oss-instruct-sc2-concepts
def toBin3(v): """Return a string (little-endian) from a numeric value.""" return '%s%s%s' % (chr(v & 255), chr((v >> 8) & 255), chr((v >> 16) & 255))
bigcode/self-oss-instruct-sc2-concepts
def is_present(value: str) -> str: """ Ensure that a string is present :param value: the string to validate :return: a valid string """ if value == "": raise ValueError("must be present") return value
bigcode/self-oss-instruct-sc2-concepts
import re def replace_emoticons_with_tags(tweet): """ Replaces emoticons in a tweet with tags. INPUT: tweet: original tweet as a string OUTPU: tweet with emoticons replaced """ hearts = set(['<3', '❤']) happy_faces = set([ ':)', ":')", '=)', ':-)', ':]', ":']", '=]...
bigcode/self-oss-instruct-sc2-concepts
def message_filter(msg): """Return True if the message cannot be considered as a repeat.""" if msg == '' or '--' in msg or 'List:\n' in msg: return True return False
bigcode/self-oss-instruct-sc2-concepts
import re def split_hname(hname): """split a hierarchical name (hname) into parts. double '/' is used to escape the '/'. and is transformed into a into single '/' e.g. hname = "network/network-fd02:://64" => ["network", "network-fd02::/64"] :param str hname: hierarchical name ...
bigcode/self-oss-instruct-sc2-concepts
def _get_dependencies_in_namespace(msg_desc, namespace): """Return all message dependencies in the given namespace.""" dependencies = [] for key in msg_desc.message_dependencies: if key.startswith(namespace): dependencies.append(key) return dependencies
bigcode/self-oss-instruct-sc2-concepts
import re def validar_cpf(cpf): """Rotina para validação do CPF - Cadastro Nacional de Pessoa Física. :Return: True or False :Parameters: - 'cpf': CPF to be validate. """ # Limpando o cpf if not cpf.isdigit(): cpf = re.sub('[^0-9]', '', cpf) if len(cpf) != 11 or cpf == c...
bigcode/self-oss-instruct-sc2-concepts
import re def process_string_and_remove_tags(raw_string: str): """Removes tags and converts newlines to match ace offsets alignment""" raw_string = raw_string.replace('\r\n', '\n') return re.sub(r'<[\s\S]*?>', '', raw_string)
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def get_client_region(client: Any) -> str: """Get the region from a boto3 client. Args: client: The client to get the region from. Returns: AWS region string. """ return client._client_config.region_name
bigcode/self-oss-instruct-sc2-concepts
def _compute_depth_recursively(event): """Return the depth of the current event. The depth is the largest number of possible successive descend into the children field. Args: event (json): Json representing the current event. Returns: The depth of the current event. """ if event['c...
bigcode/self-oss-instruct-sc2-concepts
import random import string def random_pass(length=20): """Generate a random string of letters and digits """ return "".join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
bigcode/self-oss-instruct-sc2-concepts
import re def read_urls(filename): """Returns a list of the puzzle urls from the given log file, extracting the hostname from the filename itself. Screens out duplicate urls and returns the urls sorted into increasing order.""" # NOTE: Hostname not longer exists hostName = 'http://'+ filename...
bigcode/self-oss-instruct-sc2-concepts
def namedtuple_to_dict(data): """ Converts a namedtuple to a dictionary with the top-level key being the class name. """ return {type(data).__name__.lower(): dict(data._asdict())}
bigcode/self-oss-instruct-sc2-concepts
import math def prime_sieve(num: int) -> list[int]: """ Returns a list with all prime numbers up to n. >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] >>> prime_sieve(25) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> prime_sieve(10) [2, 3, 5, 7] >>> prime_sieve...
bigcode/self-oss-instruct-sc2-concepts
def shipDown(self): """ Returns True if alien bolt collides with ship and removes bolt from _bolts""" for bolt in self._bolts: if self._ship is not None and self._animator is None: if self._ship.collides(bolt): # Sound(self._soundList[0]).play() self._bolts.re...
bigcode/self-oss-instruct-sc2-concepts
import wave def read_audio(path): """ Read the audio from path into a wave_read object. Parameters ---------- path : string Specifies path of the audio file. Returns ------- wave_reader : class : 'wave.Wave_read' wave_params : class : 'wave._wave_params' """ wave...
bigcode/self-oss-instruct-sc2-concepts
def ask_question(question, not_done): """Method to ask the user a simple yes or no question""" while not_done: answer = input("\n[?] {} ['yes' or 'no']: ".format(question)) if answer[0].lower() == "y": break if answer[0].lower() == "n": not_done = False ...
bigcode/self-oss-instruct-sc2-concepts
def locus_generator(start, stop, length, n, f): """Generate index positions Parameters ---------- start : int A starting or minimum index stop : int The largest possible index length : int The length of a substring to extract n : int The number of indices to ...
bigcode/self-oss-instruct-sc2-concepts
def get_gRNAs(db): """get gRNAs :param db: ultra or g_ultra list :return: set object with sequences as elements """ hold = [] for j in range(len(db)): hold.append(db[j].split(',')[0]) hold_set = set(hold) return hold_set
bigcode/self-oss-instruct-sc2-concepts
import math def floor(value): """Rounds a number down to the nearest whole number.""" return math.floor(value)
bigcode/self-oss-instruct-sc2-concepts
def build_feature_dict(opt): """Make mapping of feature option to feature index.""" feature_dict = {} if opt['use_in_question']: feature_dict['in_question'] = len(feature_dict) feature_dict['in_question_uncased'] = len(feature_dict) if opt['use_tf']: feature_dict['tf'] = len(feat...
bigcode/self-oss-instruct-sc2-concepts
import operator def ParseIpRanges(messages, ip_ranges): """Parse a dict of IP ranges into AdvertisedPrefix objects. Args: messages: API messages holder. ip_ranges: A dict of IP ranges of the form ip_range=description, where ip_range is a CIDR-formatted IP and description is an optional ...
bigcode/self-oss-instruct-sc2-concepts
def iscellular(kit_name): """ Determine if a kit is a cellular kit or a WiFi kit based on kit name. :param kit_name: Name of the kit the LTE-M name is only used in prototype kits """ return "CELLULAR" in kit_name.upper() or "LTE-M" in kit_name
bigcode/self-oss-instruct-sc2-concepts
def rb_epc(fit, rb_pattern): """Take the rb fit data and convert it into EPC (error per Clifford) Args: fit (dict): dictionary of the fit quantities (A, alpha, B) with the keys 'qn' where n is the qubit and subkeys 'fit', e.g. {'q0':{'fit': [1, 0, 0.9], 'fiterr': [0, 0, 0]}}} ...
bigcode/self-oss-instruct-sc2-concepts
import ntpath import posixpath def MakeZipPath(os_path, isdir, iswindows): """Changes a path into zipfile format. # doctest doesn't seem to honor r'' strings, so the backslashes need to be # escaped. >>> MakeZipPath(r'C:\\users\\foobar\\blah', False, True) 'users/foobar/blah' >>> MakeZipPath('/tmp/tmpfoo...
bigcode/self-oss-instruct-sc2-concepts
def bytes_from_str( size_str ): """ Given a string description of directory size, return float bytes. Supports B, K, M, G, T suffixes. B can be ommitted. """ unit_conversions = { char: 1024**power for ( power, char ) in enumerate( [ "B", "K", "M", "G", "T" ] ) } try: coeff = unit_convers...
bigcode/self-oss-instruct-sc2-concepts
import functools def _str_table_result(cols, rows): """Turn a Civis Query result into a readable table.""" str_rows = [['' if _v is None else _v for _v in row] for row in rows] # Determine the maximum width of each column. # First find the width of each element in each row, then find the max # wid...
bigcode/self-oss-instruct-sc2-concepts
def get_recipients(connection, search_term, search_pattern="CONTAINS_ANY_WORD", offset=0, limit=-1, enabled_status='ALL'): """Get information for a set of recipients. Args: connection(object): MicroStrategy connection object returned by `connection.Connection()`. ...
bigcode/self-oss-instruct-sc2-concepts
def bin_centers(bins): """ Centers of histogram bins to plothistograms as lines :param bins: Bins limits. :return: Centers of bins. """ return bins[:-1] + (bins[1:] - bins[:-1]) / 2.0
bigcode/self-oss-instruct-sc2-concepts
def get_max_row_column(train, val, test): """Returns the total number of rows, columns from train, validation and test arrays in COO form.""" r = max(max(train[:, 0]), max(val[:, 0]), max(test[:, 0])).astype(int) + 1 c = max(max(train[:, 1]), max(val[:, 1]), max(test[:, 1])).astype(int) + 1 return r, c
bigcode/self-oss-instruct-sc2-concepts
def residualSumOfSquares(xs,ys,func): """Return the residual sum of squares.""" return sum([(func(xs[i])-ys[i])**2 for i in range(len(xs))])
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def _get_common_letters(box_id1: str, box_id2: str) -> str: """Returns common letters in the box ids Arguments: box_id1 {String} box_id2 {String} Returns: [String] """ # I can iterate through both the string and find out the diff in one iteration...
bigcode/self-oss-instruct-sc2-concepts
def _reGroupDict(d, newgr): """Regroup keys in the d dictionary in subdictionaries, based on the scheme in the newgr dictionary. E.g.: in the newgr, an entry 'LD label': ('laserdisc', 'label') tells the _reGroupDict() function to take the entry with label 'LD label' (as received from the sql databas...
bigcode/self-oss-instruct-sc2-concepts
import time def date_to_TS(date, form='%Y-%m-%d %H:%M:%S'): """ Use your local time-zone to convert date in specific format to timestamp. Parameters ---------- date : str A date to convert. form : str (default '%Y-%m-%d %H:%M:%S') Time format. Returns ------- TS :...
bigcode/self-oss-instruct-sc2-concepts
def sqlite_list_text(elements): """Return text to create a repr of a python list.""" return "'[' || %s || ']'" % "|| ', ' ||".join(elements)
bigcode/self-oss-instruct-sc2-concepts
import re def extract_url(input_string): """Extracts a URL from a blob of text. Params: - input_string: (type: string) string to parse. Returns: - result: (type: string) extracted URL. """ if input_string: url_search = re.search( r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&...
bigcode/self-oss-instruct-sc2-concepts
def get_unmatched_part(abbr: str, text: str): """ Returns a part of `abbr` that wasn’t directly matched against `str`. For example, if abbreviation `poas` is matched against `position`, the unmatched part will be `as` since `a` wasn’t found in string stream """ last_pos = 0 for i, ch in enum...
bigcode/self-oss-instruct-sc2-concepts
def create_output_header(data_type, species_list, biomet_var_list=[]): """ A helper function to create the header for output data frame. Parameters ---------- data_type : str The type of output dataframe * 'flux' - flux data * 'diag' - curve fitting diagnostics species_l...
bigcode/self-oss-instruct-sc2-concepts
def split_sections(diff): """ takes a git diff and breaks it up into sections :param diff: a diff piped from git :return: a list of sections """ sections = [] section = '' for line in diff.splitlines(): line = line.strip() if line.startswith('@@'): if section...
bigcode/self-oss-instruct-sc2-concepts
def calculate_fpl(household_size, annual_income): """Calculate income as a percentage of the Federal Poverty Level.""" fpl = 4160 * int(household_size) + 7610 return float(annual_income) / fpl * 100
bigcode/self-oss-instruct-sc2-concepts
def zero_module(module): """ Zero out the parameters of a module and return it. """ for p in module.parameters(): p.detach().zero_() return module
bigcode/self-oss-instruct-sc2-concepts
def factorial( *, number: int, ) -> int: """Recursive Factorial Function Args: number (int): number Returns: int: factorial of the number """ if number <= 1: return 1 return number * factorial(number=number - 1)
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def norm1(x: Iterable[int]) -> int: """ Returns the manhattan distance (1-norm) of x """ return sum(map(abs, x))
bigcode/self-oss-instruct-sc2-concepts
def getlink(tag): """ Get the hyperlink and title from a tag. Return None tuple if there isn't a link. """ if not tag or isinstance(tag, str): return None, None if "href" not in tag.attrs: return None, None return tag["href"], tag["title"]
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def __parse_gav(full_artifact_path: str, root="/") -> Tuple[str, str, str]: """Parse maven groupId, artifactId and version from a standard path in a local maven repo. e.g: org/apache/maven/plugin/maven-plugin-plugin/1.0.0/maven-plugin-plugin-1.0.0.pom -> (org.apache.maven.plugin, ...
bigcode/self-oss-instruct-sc2-concepts
def getTimestamps(data): """ Get the time stamps for each position :param data: JSON Object :return: Array of timestamps """ timestamps = data['time'] return timestamps
bigcode/self-oss-instruct-sc2-concepts
import math def update_alg_squarert(score): """Change the score by taking the square root.""" return math.sqrt(score)
bigcode/self-oss-instruct-sc2-concepts
def lifetime_init(rule='1/e'): """Initialize a lifetime object. Parameters ---------- rule : str {'1/e', 'trapz', 'simpson'}, optional Name of the method to integrate the correlation curve. \n '1/e' uses the 1/e rule and assumes an exponential decay. It linearly interpolates the...
bigcode/self-oss-instruct-sc2-concepts
import string import random def random_string(lenght: int = 10) -> str: """Generate a random string composed of lower cased ascii characters Args: lenght (int, optional): lenght of the string to generate. Defaults to 10. Returns: str: random string of lenght `lenght` composed of lower ca...
bigcode/self-oss-instruct-sc2-concepts
def parse_column_names(df): """ Method used to parse the column names :param df: Original data frame :type df: pd.DataFrame :return: pd.DataFrame -- Formatted data frame """ cols = set(df.columns.tolist()) if "StreamID" in cols: df.rename(columns={"StreamID": "stream_id"}, inpl...
bigcode/self-oss-instruct-sc2-concepts
def find_containerName_by_containerId(containers_list, container_id): """ Function to get containername based on container ID. Parameters ---------- containers_list : list Containers list extracted from CVP. container_id : string ID of the container to search Returns --...
bigcode/self-oss-instruct-sc2-concepts
def distance_from_speed_and_time(movement_speed, movement_time): """Returns distance from speed and time""" return movement_time * movement_speed * 1000 / 3600
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_image_paths(image_folder: Path) -> list: """ Get all images in image folder ending in .jpg or .png """ suffix_set = {'.jpg', '.png'} return [ image for image in image_folder.iterdir() if image.suffix in suffix_set ]
bigcode/self-oss-instruct-sc2-concepts
def personal_top_three(scores): """ Return top three score from the list. if there are less than 3 scores then return in a decending order the all elements """ # sorted the list in a decending order sorted_scores = sorted(scores, reverse=True) # check if there are at least 3 elements...
bigcode/self-oss-instruct-sc2-concepts
def lines( *, base_width=0.5, line_base_ratio=2.0, tick_major_base_ratio=1.0, tick_minor_base_ratio=0.5, tick_size_width_ratio=3.0, tick_major_size_min=3.0, tick_minor_size_min=2.0, axisbelow=True, ): """Adjust linewidth(s) according to a base width.""" tick_major_width = ti...
bigcode/self-oss-instruct-sc2-concepts
def stack_template_key_name(blueprint): """Given a blueprint, produce an appropriate key name. Args: blueprint (:class:`stacker.blueprints.base.Blueprint`): The blueprint object to create the key from. Returns: string: Key name resulting from blueprint. """ name = bluep...
bigcode/self-oss-instruct-sc2-concepts
def _set_log_format(color: bool, include_caller: bool) -> str: """ Set log format :param color: Log message is colored :param include_caller: At the end, put a [caller:line-of-code], e.g. [script:123] :return: string of log format """ level_name = "* %(levelname)1s" time = "%(asctime)s,%...
bigcode/self-oss-instruct-sc2-concepts
def bitceil(N): """ Find the bit (i.e. power of 2) immediately greater than or equal to N Note: this works for numbers up to 2 ** 64. Roughly equivalent to int(2 ** np.ceil(np.log2(N))) """ # Note: for Python 2.7 and 3.x, this is faster: # return 1 << int(N - 1).bit_length() N = int(N) ...
bigcode/self-oss-instruct-sc2-concepts
def _loop_action_in_command_line(command_line: str) -> bool: """Does the command line contain a loop statement Args: command_line (str): The command line to test. Returns: bool: True if there's a loop in this command line. """ return any( word in command_line.split() for wo...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def format_date( date: datetime, base: datetime = datetime.now(), all_day: bool = False ) -> str: """Convert dates to a specified format Arguments: <date>: The date to format [base]: When the date or time matches the info from base, it will be skipped. This helps avoid repeated i...
bigcode/self-oss-instruct-sc2-concepts
import hmac import hashlib import base64 def authenticate(request, channel_secret): """Validates the incoming HTTP requests. Args: request (flask.Request): HTTP request object. channel_secret (str): channel secret got from LINE developer console. Returns: bool: true when ...
bigcode/self-oss-instruct-sc2-concepts
import base64 def string_to_base64(string): """ Encodes a string in base64 (> str) """ string_bytes = string.encode('ascii') base64_encoded = base64.b64encode(string_bytes) base64string = base64_encoded.decode('ascii') return base64string
bigcode/self-oss-instruct-sc2-concepts
import re def get_vcpus_per_osd_from_ironic(ironic, tripleo_environment_parameters, num_osds): """ Dynamically sets the vCPU to OSD ratio based the OSD type to: HDD | OSDs per device: 1 | vCPUs per device: 1 SSD | OSDs per device: 1 | vCPUs per device: 4 NVMe | OSDs per device: 4 | vCPUs p...
bigcode/self-oss-instruct-sc2-concepts
import torch def create_pinhole(fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz): """Creates pinhole model encoded to a torch.Tensor. """ return torch.Tensor([ [fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz]])
bigcode/self-oss-instruct-sc2-concepts
import base64 def _posh_encode(command): """Encode a powershell command to base64. This is using utf-16 encoding and disregarding the first two bytes :param command: command to encode """ return base64.b64encode(command.encode('utf-16')[2:])
bigcode/self-oss-instruct-sc2-concepts
import six def _convert_str(data, to_binary=False): """Helper to convert str to corresponding string or binary type. `data` has `str` type (in both Python 2/3), the function converts it to corresponding string or binary representation depending on Python version and boolean `to_binary` parameter. ...
bigcode/self-oss-instruct-sc2-concepts
import re def _is_valid_import(source_module, target_module, disallowed): """ Return whether an import is allowed. Parameters ---------- source_module : str Name of the module where the import statement is. target_module : str Name being imported. disallowed : str Regu...
bigcode/self-oss-instruct-sc2-concepts
import torch def extract_indices(seq, which_one): """ Helper method to extract the indices of elements which have the specified label. :param labels: (torch.tensor) Labels of the context set. :param which_class: Label for which indices are extracted. :return: (torch.tensor) Indices in the form of ...
bigcode/self-oss-instruct-sc2-concepts
import random def decision(probability: float): """Function that gives you a decision based on a given probability :param probability: float between 0 and 1 :type: float :return: True or False :rtype: bool """ if random.random() < probability: print("You know what let's do it...") ...
bigcode/self-oss-instruct-sc2-concepts
def speed_ms_to_kmh(speed_ms): """Converts to m/s to km/h""" return speed_ms * 3.6
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def temp_directory(tmpdir): """Return path to temporary directory, and cleanup afterwards.""" return Path(tmpdir).resolve()
bigcode/self-oss-instruct-sc2-concepts
def ipv6_mask_to_long(mask): """Convert an IPv6 prefixlen to long >>> ipv6_mask_to_long(64) 340282366920938463444927863358058659840L >>> ipv6_mask_to_long(128) 340282366920938463463374607431768211455L """ mask_binary = ("1" * mask) + ("0" * (128-mask)) return int(mask_binary, 2)
bigcode/self-oss-instruct-sc2-concepts
def normalize_volume(audio, dBFS=-15): """Normalizes the volume of an audio clip. Normalizes the amplitude of and audio clip to match a specified value of decibels relative to full scale. Args: audio (pydub AudioSegment): The audio clip to be normalized. dBFS (int): the desired...
bigcode/self-oss-instruct-sc2-concepts
def findMatching(device, device_arr): """ Check the array of devices to see if there is a matching element. Args: device (string): The name of the device attempting to be added. device_arr (array): An array of the devices attached to a profile. """ matches = [x for x in device_arr i...
bigcode/self-oss-instruct-sc2-concepts
import re def sanitize_host(host): """ Removes extraneous characters from a hostname, leaves an IP untouched. """ if re.match(r'[a-zA-Z]', host): return host.split()[0].strip().replace('_', '-').replace('.', '') else: return host
bigcode/self-oss-instruct-sc2-concepts
def _insert_token_to_repo_url(url, token): """Insert the token to the Git repo url, to make a component of the git clone command. This method can only be called when repo_url is an https url. Args: url (str): Git repo url where the token should be inserted into. token (str): Token to be ins...
bigcode/self-oss-instruct-sc2-concepts
def indent(input_str, prefix): """ Given a multiline string, return it with every line prefixed by "prefix" """ return "\n".join([f"{prefix}{x}" for x in input_str.split("\n")])
bigcode/self-oss-instruct-sc2-concepts
import re from typing import Dict def _parse_group(pr_txt: str, header_pattern: str, entry_regex: re.Pattern) -> Dict[str, int]: """General function to parse and extract a listing from the press release. Args: pr_txt: The text of the press release. header_pattern: A string rep...
bigcode/self-oss-instruct-sc2-concepts
import uuid def create_boundary(prefix, compact=False): """Creates a string that can be used as a multipart request boundary. :param bool compact: :param str prefix: String to use as the start of the boundary string """ if compact: return prefix + str(uuid.uuid4())[:8] else: r...
bigcode/self-oss-instruct-sc2-concepts
def check_lru(sc): """ Check LRU replacement of sim_cache. """ sc.reset() # Setup 5 addresses with different tags but in the same set address = [sc.merge_address(i, 0, 0) for i in range(5)] # Write different data to each address for i in range(5): sc.write(address[i], "1111", i + 1) ...
bigcode/self-oss-instruct-sc2-concepts
import math def is_prime(n: int) -> bool: """ Check wether a certain number is prime or not. Parameters ---------- n: int The number to check. Returns ------- bool True if the number is prime, False if it isn't. """ if n <= 1: return False if n == ...
bigcode/self-oss-instruct-sc2-concepts
import re def enclose(s): """Enclose the string in $...$ if needed""" if not re.match(r'.*\$.+\$.*', s, re.MULTILINE | re.DOTALL): s = u"$%s$" % s return s
bigcode/self-oss-instruct-sc2-concepts
def dot_notation(dict_like, dot_spec): """Return the value corresponding to the dot_spec from a dict_like object :param dict_like: dictionary, JSON, etc. :param dot_spec: a dot notation (e.g. a1.b1.c1.d1 => a1["b1"]["c1"]["d1"]) :return: the value referenced by the dot_spec """ attrs = dot_spec....
bigcode/self-oss-instruct-sc2-concepts
def m_hook(self, node): """Alias .mm files to be compiled the same as .cpp files, gcc/clang will do the right thing.""" return self.create_compiled_task('cxx', node)
bigcode/self-oss-instruct-sc2-concepts
def parse_pattern(pattern): """Convert a string of 1s and 0s into a pattern of Trues and Falses. >>> parse_pattern('1010010') [True, False, True, False, False, True, False] """ return map(lambda x: True if x == '1' else False, pattern)
bigcode/self-oss-instruct-sc2-concepts
def _check_installed_pkg(module, package, repository_path): """ Check the package on AIX. It verifies if the package is installed and informations :param module: Ansible module parameters spec. :param package: Package/fileset name. :param repository_path: Repository package path. :return: B...
bigcode/self-oss-instruct-sc2-concepts
def cross3D(v1, v2): """Calculates the vector cross product of two 3D vectors, v1 and v2""" return (v1[1]*v2[2] - v1[2]*v2[1], v1[2]*v2[0] - v1[0]*v2[2], v1[0]*v2[1] - v1[1]*v2[0])
bigcode/self-oss-instruct-sc2-concepts
def cubrt(x): """Returns the cubed root of x""" return round(x ** (1/3), 12)
bigcode/self-oss-instruct-sc2-concepts
import functools def if_true(toggle_attr): """Returns a decorator that executes its method if a condition is met.""" def if_true_decorator(instance_method): """Execute the decorated method conditional on a toggle attribute.""" @functools.wraps(instance_method) def wrapper(self, *args, ...
bigcode/self-oss-instruct-sc2-concepts