seed
stringlengths
1
14k
source
stringclasses
2 values
def is_object_translated(verbose, object_id, strings_by_object): """ Checks if there are any translations for the given file id """ if object_id in strings_by_object: return True if verbose: print(f"No translations for {object_id} in dump file -- skipping") return False
bigcode/self-oss-instruct-sc2-concepts
def median_val(vals): """ :param vals: an iterable such as list :return: the median of the values from the iterable """ n = len(vals) sorted_vals = sorted(vals) if n % 2 == 0: return (sorted_vals[n // 2] + sorted_vals[n // 2 - 1]) / 2 else: return sorted_vals[n // 2]
bigcode/self-oss-instruct-sc2-concepts
def extension(path_): """Returns extension from given path. Skips end slash if any.""" if path_.endswith('/'): path_ = path_[:-1] filename = path_.split('/')[-1] if not '.' in filename: return None return '.'+filename.split('.')[1]
bigcode/self-oss-instruct-sc2-concepts
def has_workflow_stage(artifact, workflow_step_name): """ Checks that the artifact's sample's root artifact has been through the given workflow. :return True if it has False otherwise """ for w, status, name in artifact.samples[0].artifact.workflow_stages_and_statuses: if name == workflow_st...
bigcode/self-oss-instruct-sc2-concepts
import collections def build_vocab(data): """Build vocabulary. Given the context in list format. Return the vocabulary, which is a dictionary for word to id. e.g. {'campbell': 2587, 'atlantic': 2247, 'aoun': 6746 .... } Parameters ---------- data : a list of string the context in ...
bigcode/self-oss-instruct-sc2-concepts
def get_data_science_bookmarks(bookmarks): """Function to select the top level data science folder of bookmarks. Returns the first element of bookmarks where 'Data Science' is one of the keys. """ for item in bookmarks: if type(item) is dict: if 'Data Science' in item.keys():...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def project_path() -> Path: """Find project directory.""" current_dir = Path.cwd() if (current_dir / 'pyproject.toml').exists(): return current_dir raise ValueError('This is not a project dir!')
bigcode/self-oss-instruct-sc2-concepts
def multivariate_regression_predict(X, w_opt): """Predict with multivariate regression. Arguments: X {DataFrame} -- Independent variables. w_opt {ndarray} -- Parameter values. Returns: ndarray -- Predicted values. """ X = X.values y_pred = X.dot(w_opt) return y_pre...
bigcode/self-oss-instruct-sc2-concepts
import tempfile, os, shutil def createSampleAssembly(workdir, template_dir, sa_xml): """Create a sampleassembly folder in the workdir using files in template directory and the given sampleassembly.xml file return the path to the new directory """ d = tempfile.mkdtemp(dir=workdir) for fn in os....
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Optional def _parse_url(url : str) -> Tuple[str,int,Optional[str]]: """ Parses the url in the following format if authentication enabled: tcp://<hostname/url>:<port>?token=<token> If authentication is not enabled, the url is expected to be in the format: ...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_data(url: str): """Get the data from the url. :param url: The link used to get the data. :return: The raw response from requests. """ response = requests.get(url, stream=True) return response.raw
bigcode/self-oss-instruct-sc2-concepts
def get_links(soup): """Gets the story links from the given hacker soup.""" links = soup.select(".storylink") return links
bigcode/self-oss-instruct-sc2-concepts
def _cache(f): """Decorator to cache return value of a function.""" cached = {} def cached_function(): """Cache return value in closure before calling function.""" if 'value' not in cached: cached['value'] = f() return cached['value'] return cached_function
bigcode/self-oss-instruct-sc2-concepts
def make_list(var): """ Convert a variable to a list with one item (the original variable) if it isn't a list already. :param var: the variable to check. if it's already a list, do nothing. else, put it in a list. :return: the variable in a one-item list if it wasnt already a list. """ if...
bigcode/self-oss-instruct-sc2-concepts
def win_safe_name(trackname): """Edit the track name so as the resulting file name would be allowed in Windows. """ # In order: strip the whitespace at both ends, replace a trailing # full stop by an underscore. Replace any forbidden characters by # underscores. trackname = trackname.strip(...
bigcode/self-oss-instruct-sc2-concepts
import re def clean_path(dirty): """Convert a string of python subscript notation or mongo dot-notation to a list of strings. """ # handle python dictionary subscription style, e.g. `"['key1']['key2']"`: if re.match(r'^\[', dirty): return re.split(r'\'\]\[\'', re.sub(r'^\[\'|\'\]$'...
bigcode/self-oss-instruct-sc2-concepts
def is_primitive(pyobj): """Determine if pyobj is one of (what other languages would deem) a primitive""" if type(pyobj) in (int, float, bool, str, bytes): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def _next_significant(tokens): """Return the next significant (neither whitespace or comment) token. :type tokens: :term:`iterator` :param tokens: An iterator yielding :term:`component values`. :returns: A :term:`component value`, or :obj:`None`. """ for token in tokens: if token.type ...
bigcode/self-oss-instruct-sc2-concepts
import itertools def compact_batches(batches): """Pack down batches to lists of continuous batches.""" return [ [x[1] for x in g] for k, g in itertools.groupby(enumerate(batches), lambda i_x: i_x[0] - i_x[1]) ]
bigcode/self-oss-instruct-sc2-concepts
def korean_year(cycle, year): """Return equivalent Korean year to Chinese cycle, cycle, and year, year.""" return (60 * cycle) + year - 364
bigcode/self-oss-instruct-sc2-concepts
def fmt_bytes(bytes: int) -> str: """ Prints out a human readable bytes amount for a given number of bytes """ if bytes > 1000000000: return '{:.2f} GB'.format(bytes / 1000000000) if bytes > 1000000: return '{:.2f} MB'.format(bytes / 1000000) if bytes > 1000: return '{:.2...
bigcode/self-oss-instruct-sc2-concepts
def __k_chk(k): """ Ensures a kelvin value is not below absolute zero. If it is not, we raise a ValueError instead. If it is valid, we return it. """ if k < 0: if k % 1 == 0: k = int(k) raise ValueError(f'{k}K is below absolute zero, and is invalid.') return k
bigcode/self-oss-instruct-sc2-concepts
def rounded(n, base): """Round a number to the nearest number designated by base parameter.""" return int(round(n/base) * base)
bigcode/self-oss-instruct-sc2-concepts
def bits_to_array(num, output_size): """ Converts a number from an integer to an array of bits """ ##list(map(int,bin(mushroom)[2:].zfill(output_size))) bit_array = [] for i in range(output_size - 1, -1, -1): bit_array.append((num & (1 << i)) >> i) return bit_array
bigcode/self-oss-instruct-sc2-concepts
import pickle def read_chains(in_dir): """Read chains file.""" pickle_in = open(in_dir, 'rb') chains = pickle.load(pickle_in) pickle_in.close() return chains
bigcode/self-oss-instruct-sc2-concepts
def _convert_pandas_csv_options(pandas_options, columns): """ Translate `pd.read_csv()` options into `pd.DataFrame()` especially for header. Args: pandas_options (dict): pandas options like {'header': None}. columns (list): list of column name. """ _columns = pa...
bigcode/self-oss-instruct-sc2-concepts
def ask_player_for_location(player): """Ask the player where they would like to use their turn""" move = None while not move: try: move = int(input(f"{player} where would you like to go? ")) if move not in range(1, 10): move = None raise ValueE...
bigcode/self-oss-instruct-sc2-concepts
def age_restricted(content_limit, age_limit): """ Returns True iff the content should be blocked """ if age_limit is None: # No limit set return False if content_limit is None: return False # Content available for everyone return age_limit < content_limit
bigcode/self-oss-instruct-sc2-concepts
def T(parameters, theta_v, pi, r_v=None): """ Returns an expression for temperature T in K. :arg parameters: a CompressibleParameters object. :arg theta_v: the virtual potential temperature in K. :arg pi: the Exner pressure. :arg r_v: the mixing ratio of water vapour. """ R_d = paramet...
bigcode/self-oss-instruct-sc2-concepts
def rshift(x, n): """For an integer x, calculate x >> n with the fastest (floor) rounding. Unlike the plain Python expression (x >> n), n is allowed to be negative, in which case a left shift is performed.""" if n >= 0: return x >> n else: return x << (-n)
bigcode/self-oss-instruct-sc2-concepts
def phrase2seq(phrase, word2idx, vocab): """ This function turns a sequence of words into a sequence of indexed tokens according to a vocabulary and its word2idx mapping dictionary. :param phrase: List of strings :param word2idx: Dictionary :param vocab: Set or list containing entire v...
bigcode/self-oss-instruct-sc2-concepts
def is_json_validation_enabled(schema_keyword, configuration=None): """Returns true if JSON schema validation is enabled for the specified validation keyword. This can be used to skip JSON schema structural validation as requested in the configuration. Args: schema_keyword (string): the name of...
bigcode/self-oss-instruct-sc2-concepts
def combine_runs(runsets): """ Combine the output results of many runs into a single dictionary. Parameters ---------- runsets : list Outputs of multiple calls to 'chnbase.MOSOSolver.solve' Returns ------- rundatdict : dict """ rundatdict = dict() for i, st in enume...
bigcode/self-oss-instruct-sc2-concepts
import json def load_cexfreqtable(fname): """ Loads a Context Feature frequency table """ with open(fname) as fp: cexfreqtable = json.load(fp) return cexfreqtable
bigcode/self-oss-instruct-sc2-concepts
def extend(key, term): """ extend a key with a another element in a tuple Works if they key is a string or a tuple >>> extend('x', '.dtype') ('x', '.dtype') >>> extend(('a', 'b', 'c'), '.dtype') ('a', 'b', 'c', '.dtype') """ if isinstance(term, tuple): pass elif isinstance(...
bigcode/self-oss-instruct-sc2-concepts
def str_or_list(value): """ String to list of string. """ if isinstance(value, list): return value return [value]
bigcode/self-oss-instruct-sc2-concepts
def contains_test_passer(t, test): """ Return whether t contains a value that test(value) returns True for. @param Tree t: tree to search for values that pass test @param function[Any, bool] test: predicate to check values with @rtype: bool >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4.5,...
bigcode/self-oss-instruct-sc2-concepts
import json def ReadMeasurements(test_result): """Read ad hoc measurements recorded on a test result.""" try: artifact = test_result['outputArtifacts']['measurements.json'] except KeyError: return {} with open(artifact['filePath']) as f: return json.load(f)['measurements']
bigcode/self-oss-instruct-sc2-concepts
def calculate_fibonacci(num: int) -> int: """ >>> calculate_fibonacci(-1) Traceback (most recent call last): ... ValueError: num must not be negative. >>> calculate_fibonacci(0) 0 >>> calculate_fibonacci(1) 1 >>> calculate_fibonacci(2) 1 >>> calculate_fibonacci(3) ...
bigcode/self-oss-instruct-sc2-concepts
def make_tweet_content(preamble: str, message: str, link: str) -> str: """ Make formatted tweet message from preamble, message and link. Arguments: preamble (str): Preamble to be used in the beginning of the tweet. message (str): Main message of the tweet. link (str): Link to be add...
bigcode/self-oss-instruct-sc2-concepts
import torch def linear_quantize(input, scale, zero_point, inplace=False): """ Quantize single-precision input tensor to integers with the given scaling factor and zeropoint. Args: input (`torch.Tensor`): Single-precision input tensor to be quantized. scale (`torch.Tensor`): ...
bigcode/self-oss-instruct-sc2-concepts
def parser(response): """Parses the json response from CourtListener /opinions endpoint.""" results = response.get("results") if not results: return [] ids = [] for result in results: _id = result.get("id", None) if _id is not None: ids.append(_id) return ...
bigcode/self-oss-instruct-sc2-concepts
def equal_test_conditions(testapi_input, nfvbench_input): """Check test conditions in behave scenario results record. Check whether a behave scenario results record from testapi matches a given nfvbench input, ie whether the record comes from a test done under the same conditions (frame size, flow coun...
bigcode/self-oss-instruct-sc2-concepts
def merge_n_reduce(f, arity, data): """ Apply f cumulatively to the items of data, from left to right in n-tree structure, so as to reduce the data. :param f: function to apply to reduce data :param arity: Number of elements in group :param data: List of items to be reduced :return: List of...
bigcode/self-oss-instruct-sc2-concepts
def is_substring_in_list(needle, haystack): """ Determine if any string in haystack:list contains the specified needle:string as a substring. """ for e in haystack: if needle in e: return True return False
bigcode/self-oss-instruct-sc2-concepts
def deep_access(x, keylist): """Access an arbitrary nested part of dictionary x using keylist.""" val = x for key in keylist: val = val.get(key, 0) return val
bigcode/self-oss-instruct-sc2-concepts
def getcommontype(action): """Get common type from action.""" return action if action == 'stock' else 'product'
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def olt_value_str_to_str(value:str, field_id:int) -> Union[str, int]: """ convert value str in show oltqinq-domain to str value Args: value (str): 要处理的值 field_id (int): 字段类型ID Returns: str or int: 处理后的值 """ # 1(Dst Mac) 00 00 00 00 00 00 ...
bigcode/self-oss-instruct-sc2-concepts
def format_import(source_module_name, source_name, dest_name): """Formats import statement. Args: source_module_name: (string) Source module to import from. source_name: (string) Source symbol name to import. dest_name: (string) Destination alias name. Returns: An import statement string. """ ...
bigcode/self-oss-instruct-sc2-concepts
def longest_in_dict( d:dict ) -> str: """ Returns longest item's string insde a dict """ longest:str = '' for i in d: if len(str(i)) > len(longest): longest=i return longest
bigcode/self-oss-instruct-sc2-concepts
import math def RelToAbsHumidity(relativeHumidity, temperature): """Convert Relative Humidity to Absolute Humidity, for a given temperature.""" absoluteHumidity = 6.112 * math.exp((17.67 * temperature)/(temperature+243.5)) * relativeHumidity * 2.1674 / (273.15+temperature) return absoluteHumidity
bigcode/self-oss-instruct-sc2-concepts
import hashlib import json def get_app_hash(raw_cwl): """If the CWL has a field "sbg:hash" (as used by sevenbridges-cwl) use that, else compute it (again, just like sevenbridges-cwl) :param raw_cwl: :return: """ if "sbg:hash" in raw_cwl: return raw_cwl["sbg:hash"] else: sh...
bigcode/self-oss-instruct-sc2-concepts
import yaml def data_file_read_yaml(filename): """ Reads a file as a yaml file. This is used to load data from fuzz-introspectors compiler plugin output. """ with open(filename, 'r') as stream: try: data_dict = yaml.safe_load(stream) return data_dict except ...
bigcode/self-oss-instruct-sc2-concepts
def clsn(obj): """Short-hand to get class name. Intended for use in __repr__ and such.""" if isinstance(obj, str): return obj else: return obj.__class__.__name__
bigcode/self-oss-instruct-sc2-concepts
def count_values(tokens): """Identify the number of values ahead of the current token.""" ntoks = 0 for tok in tokens: if tok.isspace() or tok == ',': continue elif tok in ('=', '/', '$', '&'): if ntoks > 0 and tok == '=': ntoks -= 1 break ...
bigcode/self-oss-instruct-sc2-concepts
def quoteIfNeeded(txt, quoteChar='"'): """ quoteIfNeededtxt) surrounds txt with quotes if txt includes spaces or the quote char """ if isinstance(txt, bytes): txt=txt.decode() if txt.find(quoteChar) or txt.find(' '): return "%s%s%s" % (quoteChar, txt.replace(quoteChar, "\\%s" % quoteChar), quoteC...
bigcode/self-oss-instruct-sc2-concepts
def get_slurm_script_gpu(log_dir, command): """Returns contents of SLURM script for a gpu job.""" return """#!/bin/bash #SBATCH -N 1 #SBATCH --ntasks-per-node=1 #SBATCH --gres=gpu:tesla_p100:1 #SBATCH --mem=32GB #SBATCH --output={}/slurm_%j.out #SBATCH -t 5:59:00 module load anaconda3/2019.10 cudatoolkit/10.1 cudnn...
bigcode/self-oss-instruct-sc2-concepts
def make_jobjects(entities, transformer, *args): """Run a sequence of entities through a transformer function that produces objects suitable for serialization to JSON, returning a list of objects and a dictionary that maps each entity's key_name to its index in the list. Item 0 of the list is always Non...
bigcode/self-oss-instruct-sc2-concepts
import ctypes def _encode_string(value): """Encode a Python3 string in preparation to be passed across DLL boundary""" return ctypes.c_char_p(value.encode('utf-8'))
bigcode/self-oss-instruct-sc2-concepts
def _get_bin_sum(bin_result): """ Get the [min, max] of the sample; best-fit scatter and error. """ min_val = bin_result['samples'].min() max_val = bin_result['samples'].max() sig = bin_result['sig_med_bt'] err = bin_result['sig_err_bt'] return min_val, max_val, sig, err
bigcode/self-oss-instruct-sc2-concepts
import platform import pwd def GetUserId(user): """ On a Linux system attempt to get the UID value for a give 'user'. This uses a system call to obtain this data. :param user: User name to lookup. :return: UID value if the user is found, otherwise None """ if isinstance(user, int): ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def cmyk_to_rgb(c: float, m: float, y: float, k: float) -> Tuple[int, int, int]: """Convert CMYK (Cyan Magenta Yellow Black) to RGB (Red Green Blue). :param c: Cyan (0.0 to 1.0 inclusive). :param m: Magenta (0.0 to 1.0 inclusive). :param y: Yellow (0.0 to 1.0 inclusive). ...
bigcode/self-oss-instruct-sc2-concepts
def get_url(artist): """ Get the url link for the artist in www.lyrics.com """ return f"https://www.lyrics.com/artist/{artist}"
bigcode/self-oss-instruct-sc2-concepts
def resolve(var_name, scope): """ Finds the given symbol (a function or a variable) in the scope. Reports error if not found. Args: var_name (str): Name of the symbol to be found. scope (dict): Local variables. Returns: Found variable or a function. """ variable = scope...
bigcode/self-oss-instruct-sc2-concepts
def anySubs(UserDetails): """ Checks if the user has any subscriptions yet """ if('subscriptions' in UserDetails.keys()): return True return False
bigcode/self-oss-instruct-sc2-concepts
def __parse_version_from_service_name(service_name): """ Parse the actual service name and version from a service name in the "services" list of a scenario. Scenario services may include their specific version. If no version is specified, 'latest' is the default. :param service_name: The name of the ser...
bigcode/self-oss-instruct-sc2-concepts
import random def class_colors(names): """ Create a dict with one random BGR color for each class name """ return {name: ( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for name in names}
bigcode/self-oss-instruct-sc2-concepts
def collect(delta): """Return the states and alphabet used in the transition function delta.""" Q = set() Sigma = set() for (q, a), r in delta.items(): Q.add(q) Q.add(r) Sigma.add(a) return Q, Sigma
bigcode/self-oss-instruct-sc2-concepts
import torch def convert_to_one_hot(tensor, num_classes=None): """Convert dense classification targets to one-hot representation Parameters ---------- tensor : torch.Tensor Tensor of dimensionality N num_classes : int Number of entries C of the one-hot representation. If None, use maximum value...
bigcode/self-oss-instruct-sc2-concepts
def enum_list_to_bitfield(enum_list, bitfield_enum_type): """ Converts a list of enums to a bitfield value. Args: enum_list (List[enum.Enum]): Specifies the list of enums. bitfield_enum_type (enum.Enum): Specifies the bitfield enum type from which to mask and extract the enum va...
bigcode/self-oss-instruct-sc2-concepts
def calcSurroundingIdxs(idxs, before, after, idxLimit=None): """ Returns (idxs - before), (idxs + after), where elements of idxs that result in values < 0 or > idxLimit are removed; basically, this is useful for extracting ranges around certain indices (say, matches for a substring) that are contained fully in an ...
bigcode/self-oss-instruct-sc2-concepts
def islist(thing): """ return True if a thing is a list thing, False otherwise """ return isinstance(thing, list)
bigcode/self-oss-instruct-sc2-concepts
def readLines(file, map=lambda line: line.strip()): """ Read and return a file as a list of files. Optionally, @map argument can be set to process the lines. """ # Read file line by line. results = [] with open(file, 'r') as infile: for line in infile: results.append(map(line)) return results
bigcode/self-oss-instruct-sc2-concepts
import torch def load_checkpoint(model, optimizer, device, checkpoint_file: str): """Loads a model checkpoint. Params: - model (nn.Module): instantised model to load weights into - optimizer (nn.optim): instantised optimizer to load state into - device (torch.device): device the model is on. -...
bigcode/self-oss-instruct-sc2-concepts
def image_resize(image, resize=None): """ Given an image and resize tuple (w,h), return an image with new size. """ if resize is not None: image = image.resize(resize) return image
bigcode/self-oss-instruct-sc2-concepts
def process_views(df): """Takes a dataframe and quits commas. Parameters ---------- df : The dataframe to search. Returns ------- The dataframe processed. """ df['views'] = df['views'].str.replace(',', '').astype(float) return df
bigcode/self-oss-instruct-sc2-concepts
def temperature_trans(air_in, fuel_in, ex_out): """ Convert degree celsius to kelvin. Optional keyword arguments: --------------------------- :param air_in: temperature of air coming in to fuel cell(FC) :param fuel_in: temperature of fuel coming into (FC)/ temperature of refo...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_url(url): """Return a tuple of ``(host, port, ssl)`` from the URL specified in the ``url`` parameter. The returned ``ssl`` item is a boolean indicating the use of SSL, and is recognized from the URL scheme (http vs. https). If none of these schemes is specified in the URL, the...
bigcode/self-oss-instruct-sc2-concepts
def get_bytes_from_gb(size_in_gb): """ Convert size from GB into bytes """ return size_in_gb*(1024*1024*1024)
bigcode/self-oss-instruct-sc2-concepts
def v12_add(*matrices): """Add corresponding numbers in given 2-D matrices.""" matrix_shapes = { tuple(len(r) for r in matrix) for matrix in matrices } if len(set(matrix_shapes)) > 1: raise ValueError("Given matrices are not the same size.") return [ [sum(values) for ...
bigcode/self-oss-instruct-sc2-concepts
def mib_to_gib(value): """ Returns value in Gib. """ return float(float(value) / 1024.0)
bigcode/self-oss-instruct-sc2-concepts
def read_smi_file(file_path): """ Reads a SMILES file. :param file_path: Path to a SMILES file. :return: A list with all the SMILES. """ with open(file_path, "r") as smi_file: return [smi.rstrip().split()[0] for smi in smi_file]
bigcode/self-oss-instruct-sc2-concepts
import six def encode_ascii_xml(x): """Encode a string as fixed-length 7-bit ASCII with XML-encoding for characters outside of 7-bit ASCII. Respect python2 and python3, either unicode or binary. """ if isinstance(x, six.text_type): return x.encode('ascii', 'xmlcharrefreplace') elif is...
bigcode/self-oss-instruct-sc2-concepts
def get_boolean_from_request(request, key, method='POST'): """ gets the value from request and returns it's boolean state """ value = getattr(request, method).get(key, False) if value == 'False' or value == 'false' or value == '0' or value == 0: value = False elif value: value = True ...
bigcode/self-oss-instruct-sc2-concepts
def build_insert(table: str, to_insert: list): """ Build an insert request. Parameters ---------- table : str Table where query will be directed. to_insert: iterable The list of columns where the values will be inserted. Returns ------- str Built query strin...
bigcode/self-oss-instruct-sc2-concepts
def clean_nodata(series, nodata=None): """ Given a series remove the values that match the specified nodata value and convert it to an int or float if possible Parameters ---------- series : pandas series nodata : string, int, or float Nodata placeholder Returns ------- pandas ...
bigcode/self-oss-instruct-sc2-concepts
def field_values_valid(field_values): """ Loop over a list of values and make sure they aren't empty. If all values are legit, return True, otherwise False. :param field_values: A list of field values to validate. :returns: False if any field values are None or "", True otherwise. """ for ...
bigcode/self-oss-instruct-sc2-concepts
def normalize_name(s): """Normalizes the name of a file. Used to avoid characters errors and/or to get the name of the dataset from a config filename. Args: s (str): The name of the file. Returns: new_s (str): The normalized name. """ if s is None: return '' s = s....
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def fromtimestamp(timestamp): """ Return datetime object from provided timestamp. If timestamp argument is falsy, datetime object placed in January 1970 will be retuned. """ if not timestamp: return datetime.utcfromtimestamp(0) return datetime.fromtimestam...
bigcode/self-oss-instruct-sc2-concepts
def get_x_y_values(tg, num_words=50): """ Gets a list of most frequently occurring words, with the specific number of occurrences :param tg: (TermGenerator) Object with the parsed sentences. :param num_words: (int) Number of words to be processed for the top occurring terms. :return: (List) List of ...
bigcode/self-oss-instruct-sc2-concepts
import select def wait(fd, timeout=2): """ Wait until data is ready for reading on `fd`. """ return select.select([fd], [], [], timeout)[0]
bigcode/self-oss-instruct-sc2-concepts
def parse_module(module, keyword): """ Returns a list of keywords for a single module :param module: list of strings :param keyword: Module keyword you are looking for :return: list of lines with the specified keyword """ keys = [] for line in module: keyw = line.split(" ")[0] ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Sequence from typing import Iterable def check_parity( bitstring: Union[str, Sequence[int]], marked_qubits: Iterable[int] ) -> bool: """Determine if the marked qubits have even parity for the given bitstring. Args: bitstring: The bitstring, either as a ...
bigcode/self-oss-instruct-sc2-concepts
def fnv1a(data): """Fowler–Noll–Vo hash function; FNV-1a hash.""" hash_ = 2166136261 data = bytearray(data) for c in data: hash_ = ((hash_ ^ c) * 16777619) & 0xffffffff return hash_
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def _GetIpv4CidrMaskSize(ipv4_cidr_block): """Returns the size of IPV4 CIDR block mask in bits. Args: ipv4_cidr_block: str, the IPV4 CIDR block string to check. Returns: int, the size of the block mask if ipv4_cidr_block is a valid CIDR block string, otherwise None. """ networ...
bigcode/self-oss-instruct-sc2-concepts
import functools def memoize_full(func): """ >>> @memoize_full ... def f(*args, **kwargs): ... ans = len(args) + len(kwargs) ... print(args, kwargs, '->', ans) ... return ans >>> f(3) (3,) {} -> 1 1 >>> f(3) 1 >>> f(*[3]) 1 >>> f(a=1, b=2) () {'a...
bigcode/self-oss-instruct-sc2-concepts
def max_sum_from_start(array): """ This function finds the maximum contiguous sum of array from 0 index Parameters : array (list[int]) : given array Returns : max_sum (int) : maximum contiguous sum of array from 0 index """ array_sum = 0 max_sum = float("-inf") for num in ar...
bigcode/self-oss-instruct-sc2-concepts
import typing import pathlib def parse_requirements_file (filename: str) -> typing.List: """read and parse a Python `requirements.txt` file, returning as a list of str""" with pathlib.Path(filename).open() as f: # pylint: disable=C0103 return [ l.strip().replace(" ", "") for l in f.readlines() ]
bigcode/self-oss-instruct-sc2-concepts
def dl1_tmp_path(tmp_path_factory): """Temporary directory for global dl1 test data""" return tmp_path_factory.mktemp("dl1")
bigcode/self-oss-instruct-sc2-concepts
def PrintSeconds(seconds): """Return a string representing the given time in seconds.""" orig = seconds minutes = seconds // 60 seconds %= 60 hours = minutes // 60 minutes %= 60 days = hours // 24 hours %= 24 s = "" if days > 0: s += "%dd " % days if hours > 0: s += "%02dh " % hours if ...
bigcode/self-oss-instruct-sc2-concepts