seed
stringlengths
1
14k
source
stringclasses
2 values
import functools def flat_map(l): """Transform a list of list in a list with all the elements of the nested lists >>> flat_map([[1, 2, 3], [4, 5]]) [1, 2, 3, 4, 5] """ l = list(l) return functools.reduce(list.__add__, l) if l else []
bigcode/self-oss-instruct-sc2-concepts
def _must_contain_scenarios(must_contain_conf, scenario_model): """ Return a set of scenarios and process names that are entries of must contain configuration. :param must_contain_conf: dict. :param scenario_model: ScenarioModel. :return: set of process names, set of Scenario objects. """ n...
bigcode/self-oss-instruct-sc2-concepts
def using_split2(text, _len=len): """ LEGACY Takes a text in input and returns a list of tuples with surface, start and end offsets for each token. From: http://stackoverflow.com/questions/9518806/how-to-split-a-string-on-whitespace-and-retain-offsets-and-lengths-of-words :param text: a string of t...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import importlib import inspect def create_init_line_library(module_path: str, lib_name: str) -> str: """Creates an __init__ entry of the library dir for the corresponding metadatablocks file""" # Get the module name from file module_name = Path(module_path).stem # Import pa...
bigcode/self-oss-instruct-sc2-concepts
def decode_bin(bin_array): """Takes in an array of bits and returns the number associated""" bitstring = ''.join(bin_array) number = int(bitstring, 2) return number
bigcode/self-oss-instruct-sc2-concepts
def max_degree(g): """ Returns the maximum number of edges of any node in the graph """ return max([g.degree[n] for n in g])
bigcode/self-oss-instruct-sc2-concepts
import re def natural_sort(item): """ Sort strings that contain numbers correctly. >>> l = ['v1.3.12', 'v1.3.3', 'v1.2.5', 'v1.2.15', 'v1.2.3', 'v1.2.1'] >>> l.sort(key=natural_sort) >>> print l "['v1.2.1', 'v1.2.3', 'v1.2.5', 'v1.2.15', 'v1.3.3', 'v1.3.12']" """ if item is None: ...
bigcode/self-oss-instruct-sc2-concepts
def build_alignment_param_metrics(align): """ Transform alignment param dict -> alignment metrics for output to json""" aln_param_metrics = {} for key, value in align.iteritems(): aln_param_metrics['alignment_' + key] = value return aln_param_metrics
bigcode/self-oss-instruct-sc2-concepts
def _reduce_sampled_fluxes(sampled_fluxes, reactions): """ Reduces the input dataframe of sampled fluxes to a subset of selected reactions. Parameters ---------- sampled_fluxes : pandas.Dataframe The calculated fluxes, output of sampling. For each reaction, n fluxes will be calc...
bigcode/self-oss-instruct-sc2-concepts
import pwd def uidFromString(uidString): """ Convert a user identifier, as a string, into an integer UID. @type uid: C{str} @param uid: A string giving the base-ten representation of a UID or the name of a user which can be converted to a UID via L{pwd.getpwnam}. @rtype: C{int} @retu...
bigcode/self-oss-instruct-sc2-concepts
def istrue(value): """ Accepts a string as input. If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it returns ``True``. If the string is one of ``False``, ``Off``, ``No``, or ``0`` it returns ``False``. ``istrue`` is not case sensitive. Any other input ...
bigcode/self-oss-instruct-sc2-concepts
import re def decode_bytes(data: bytearray) -> str: """ Decodes a bytes array from a file upload :param data: a UTF-8 encoded byte array :return: a cleaned string """ pattern = re.compile('\r', re.UNICODE) res = data.decode('utf-8', 'ignore') res = pattern.sub('', res) return res
bigcode/self-oss-instruct-sc2-concepts
def slice_for_range(data, fromVal, toVal): """ Returns a slice indicating the region [fromVal, toVal] in a 1D ndarray data Example: >>> data = linspace(1, 50, 50) >>> s = slice_for_range(data, 4, 10) >>> data[s] array([ 4., 5., 6., 7., 8., 9., 10.]) """ if (data[-1] - da...
bigcode/self-oss-instruct-sc2-concepts
import dill def load(filename): """ This function opens a serialized file and returns the object. Parameters: ---------- filename: str, the name of the serialized file to be opened. Returns: ------- obj: The object contained in the serialized file. """ input_file = open(filename, 'rb') obj = dill.load(...
bigcode/self-oss-instruct-sc2-concepts
def timesTwo(input_array): """ Multiples the input array times two. """ return 2*input_array
bigcode/self-oss-instruct-sc2-concepts
def get_login_tokens(login_response_body_dict): """Creates dictionary of login keys to use to make additional request calls to USPS Args: login_response_body_dict: response body (type dictionary) returned by the USPS logon endpoint. Returns: Dictionary containing logon key and...
bigcode/self-oss-instruct-sc2-concepts
import torch def from_tanh_space(x, box=(-1., 1.)): """ Convert a batch of tensors from tanh-space to oridinary image space. This method complements the implementation of the change-of-variable trick in terms of tanh. :param x: the batch of tensors, of dimension [B x C x H x W] :param box: a ...
bigcode/self-oss-instruct-sc2-concepts
def read_file_str(filename): """Read the file and return as a string.""" with open(filename, "r") as f: file_str = f.read() return file_str
bigcode/self-oss-instruct-sc2-concepts
import requests from pathlib import Path import tempfile import shutil def download_file(url: str) -> str: """ Download ngrok binary file to local Args: url (:code:`str`): URL to download Returns: :code:`download_path`: str """ local_filename = url.split("/")[-1] ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import List def compute_recall_at_k( question_id_to_docs: Dict[str, List[dict]], k: int, relevance_threshold: float ) -> float: """ Given a dictionary mapping a question id to a list of docs, find the recall@k. We define recall@k = 1.0 if any document in the top-k ...
bigcode/self-oss-instruct-sc2-concepts
def _(s, truncateAt=None): """Nicely print a string to sys.stdout, optionally truncating it a the given char.""" if truncateAt is not None: s = s[:truncateAt] return s
bigcode/self-oss-instruct-sc2-concepts
from typing import List import warnings def find_warning(caught: List[warnings.WarningMessage], msg: str) -> bool: """Return whether exactly one matching warning was caught. This only works for UserWarning subclasses. Arguments: caught: The messages to check. msg: The warning message str...
bigcode/self-oss-instruct-sc2-concepts
def get_files() -> list: """Gets a list of paths of files the user wants to compare""" files = [] while True: file = input("Enter the path of a file to compare (or enter to quit): ") if file == "": break files.append(file) return files
bigcode/self-oss-instruct-sc2-concepts
def _atomic_hotspot_ins(jobname, probename, settings): """ template for atomic hotspot input file (SuperStar ins) :param str jobname: general format (<probe_type>.ins) :param str probename: probe identifier :param `hotspots.atomic_hotspot_calculation.AtomicHotspot.Settings`settings: :return: str...
bigcode/self-oss-instruct-sc2-concepts
def all_anagrams(chars: str) -> list[str]: """ Returns: A list of all permutations of a given string of characters, without character repetition. Example: >>> print(all_anagrams('abc')) >>> ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] """ result: list[str] = [] if len(cha...
bigcode/self-oss-instruct-sc2-concepts
def _inject_encrypted_credentials(dataproc, project, region, cluster_name, cluster_uuid, credentials_ciphertext): """Inject credentials into the given cluster. The credentials must have already been encrypted before calling this method. Args: dataproc: The API client for ca...
bigcode/self-oss-instruct-sc2-concepts
def from_file(filename): """Open a file and read its first line. :param filename: the name of the file to be read :returns: string -- the first line of filename, stripped of the final '\n' :raises: IOError """ with open(filename) as f: value = f.readline().rstrip('\n') return value
bigcode/self-oss-instruct-sc2-concepts
def psf_sample_to_pupil_sample(psf_sample, samples, wavelength, efl): """Convert PSF sample spacing to pupil sample spacing. Parameters ---------- psf_sample : float sample spacing in the PSF plane samples : int number of samples present in both planes (must be equal) wavelength...
bigcode/self-oss-instruct-sc2-concepts
def average(data): """ Calculate the average of values of the data. Args: data (list): values. Returns the average of values of the data. """ return 1.0*sum(data)/len(data)
bigcode/self-oss-instruct-sc2-concepts
def od2list(od): """Convert an ordered dictionary to a list.""" return list(od.values())
bigcode/self-oss-instruct-sc2-concepts
def I(x): """Returns its argument as it is. This allows to call Python code within the formula interface. Examples ---------- >>> x + I(x**2) >>> x + {x**2} >>> {(x + y) / z} """ return x
bigcode/self-oss-instruct-sc2-concepts
def get_group(name, match_obj): """return a blank string if the match group is None""" try: obj = match_obj.group(name) except: return '' else: if obj is not None: return obj else: return ''
bigcode/self-oss-instruct-sc2-concepts
def setGauss(points): """ Create a system of equations for gaussian elimination from a set of points. """ n = len(points) - 1 A = [[0 for i in range(n+2)] for j in range(n+1)] for i in range(n+1): x = points[i]["x"] for j in range(n+1): A[i][j] = x**j A[i][n+...
bigcode/self-oss-instruct-sc2-concepts
def sort_012(input_list): """ Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal. Args: input_list(list): List to be sorted """ if not input_list: return [] if len(input_list) == 0 or len(input_list) == 1: return input_list lo ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _mklib(topdir: str, pkgname: str, libname: str) -> Path: """Make a for-testing library. Args: topdir: the toplevel directory in which the package will be created. This directory must already exist. pkgname: the name of the package to create in the top...
bigcode/self-oss-instruct-sc2-concepts
def deprecated_or_revoked(obj): """ Return true if object has a truthy "revoked" or "deprecated" attribute, otherwise False """ return getattr(obj, "revoked", None) or getattr(obj, "deprecated", None)
bigcode/self-oss-instruct-sc2-concepts
def prepare_search_string(string: str) -> list: """ Transform a search string into a list of strings if "|" was used inside the string Agrees with escaped pipes. :param string: String to prepare :return: List of strings to search for """ value = string.replace('\\|', '¤$¤') value = [v.repl...
bigcode/self-oss-instruct-sc2-concepts
def rank(tensor): """Get tensor rank as python list""" return len(tensor.shape.as_list())
bigcode/self-oss-instruct-sc2-concepts
def json_set(item, path, value): """ Set the value corresponding to the path in a dict. Arguments: item (dict): The object where we want to put a field. path (str): The path separated with dots to the field. value: The value to set on the field. Return: (dict): The update...
bigcode/self-oss-instruct-sc2-concepts
import six def binary(v, encoding='utf-8', errors='strict'): """cast value to binary type, Args: v (typing.Any): value encoding (str, optional): encoding when value is not binary. Defaults to 'utf-8'. errors (str, optional): errors setting when value is not binary. Defaults to 'strict...
bigcode/self-oss-instruct-sc2-concepts
import re def process_question(question): """Process question. Keep punctuations and use lower cases. Args: question: a string of a sentence Returns: question_words: a list of words in this sentence """ question_words = re.findall(r"[\w']+|[.,!?;]", question) return [w.encode('utf-8').lower()...
bigcode/self-oss-instruct-sc2-concepts
def str_or_none(value): """Returns string casted value if given value is not None""" return str(value) if value is not None else value
bigcode/self-oss-instruct-sc2-concepts
def semi_deviation(r): """ Returns the semi deviation, aka negative semi deviation of r r must be a Series or a DataFrame """ is_negative = r < 0 return r[is_negative].std(ddof=0)
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple def row_col_cell_ids(tiling: List[List[int]]) -> List[Tuple[int, int, int]]: """ Infers absolute rows and columns for every cell from the tiling of a table. :param tiling: A list of list of tiling of a table as returned from the :meth:`_tile_table` :re...
bigcode/self-oss-instruct-sc2-concepts
def step_factor(t): """ Euler integration suppression factor.""" return (1+t)
bigcode/self-oss-instruct-sc2-concepts
def GetHealthAlertRecipients(builder_run): """Returns a list of email addresses of the health alert recipients.""" recipients = [] for entry in builder_run.config.health_alert_recipients: if '@' in entry: # If the entry is an email address, add it to the list. recipients.append(entry) return re...
bigcode/self-oss-instruct-sc2-concepts
def set_fixstim_color(stim, color): """Set the fill and line color of a stim.""" stim.setFillColor(color) stim.setLineColor(color) return stim
bigcode/self-oss-instruct-sc2-concepts
def buscar_posicion_minimo(lista, i): """Devuelve la posición del elemento mínimo en lista[i:]""" posicion_minimo = i while i < len(lista): if lista[i] < lista[posicion_minimo]: posicion_minimo = i i += 1 return posicion_minimo
bigcode/self-oss-instruct-sc2-concepts
def is_init_st(id): """Used in p_one_line() --- Checks if id begins with i or I. """ return id[0] in {'i','I'}
bigcode/self-oss-instruct-sc2-concepts
import torch import math def closest_angle_error(angle_a: torch.Tensor, angle_b: torch.Tensor) -> torch.Tensor: """ Finds the closest angle between angle_b - angle_a in radians. :param angle_a: a Tensor of angles in radians :param angle_b: a Tensor of angles in radians :return: The relative angle err...
bigcode/self-oss-instruct-sc2-concepts
def to_numbers(string_array): """ Convert an array of strings to floating point numbers """ return [float(string) for string in string_array]
bigcode/self-oss-instruct-sc2-concepts
def get_tenant_verify(tenant): """Return whether to turn on SSL verification.""" # sandboxes and the develop instance have a self-signed certs if 'SANDBOX' in tenant.upper(): return False if tenant.upper() == 'DEV-DEVELOP': return False return True
bigcode/self-oss-instruct-sc2-concepts
def span_overlap(span_indices1, span_indices2): """Boolean check if two spans overlap. This does an exclusive overlap check (i.e. (0-2) and (2-3) does not overlap). """ return span_indices1[0] < span_indices2[1] and span_indices2[0] < span_indices1[1]
bigcode/self-oss-instruct-sc2-concepts
import operator def sort_vocab_by_frequency(vocab_freq_map): """ sorts vocab_freq_map by count args: vocab_freq_map: dict<str term, int count>, vocabulary terms with counts. returns list<tuple<str term, int count>>, sorted by count, descending """ return sorted(vocab_freq_map...
bigcode/self-oss-instruct-sc2-concepts
def zipdict(ks, vs): """Returns a dict with the keys mapped to the corresponding vals.""" return dict(zip(ks, vs))
bigcode/self-oss-instruct-sc2-concepts
import multiprocessing def _check_n_jobs(n_jobs): """Check n_jobs in particular for negative values Parameters ---------- n_jobs : int The number of jobs. Returns ------- n_jobs : int The checked number of jobs. Always positive. """ if not isinstance(n_jobs, int):...
bigcode/self-oss-instruct-sc2-concepts
def copy(src, dest): """ Copy a file using -f so it doesn't fail if the destination exists. :type src: string :param src: Source file. :type dest: string :param dest: File destination. """ return ["cp -f %s %s" % (src, dest)]
bigcode/self-oss-instruct-sc2-concepts
def xstr(s): """Handle NoneType in strings""" if s is None: return "Unknown" return str(s)
bigcode/self-oss-instruct-sc2-concepts
from math import floor def uniform_int_from_avg(a, m, seed): """ Pick a random integer with uniform probability. Returns a random integer uniformly taken from a distribution with minimum value 'a' and average value 'm', X~U(a,b), E[X]=m, X in N where b = 2*m - a. Notes ----- p = (b-floor...
bigcode/self-oss-instruct-sc2-concepts
def ascii_join(data): """Convert sequence of numbers to ASCII characters""" return ''.join([chr(n) for n in data])
bigcode/self-oss-instruct-sc2-concepts
def is_decorated_with_attrs( node, decorator_names=('attr.s', 'attr.attrs', 'attr.attributes')): """Return True if a decorated node has an attr decorator applied.""" if not node.decorators: return False for decorator_attribute in node.decorators.nodes: if decorator_attribute.as_s...
bigcode/self-oss-instruct-sc2-concepts
def a_is_not_b(a, b): """ This is `not (a is b)` """ return a is not b
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping def _remove_empty_dicts(dct: dict, recurse=True) -> dict: """Remove all (nested) keys with empty dict values from `dct`""" for k, v in list(dct.items()): if isinstance(v, Mapping) and recurse: _remove_empty_dicts(dct[k]) if v == {}: del dct[k]...
bigcode/self-oss-instruct-sc2-concepts
def input_checker(s): """ This function takes a string input and returns false if it contains one or more non terminal spaces. If not, the function returns an integer. Args: s (string): string which needs to be checked Returns: boolean: False if the string contains one or more non ...
bigcode/self-oss-instruct-sc2-concepts
def reverse_complement(dna): """Takes a RNA or DNA sequence string and returns the reverse complement""" complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'U':'A', 'N':'N'} return ''.join([complement[base] for base in dna[::-1]])
bigcode/self-oss-instruct-sc2-concepts
from typing import List def join_list_into_message(lst: List[str], joiner="-") -> str: """ Helper function that converts a list into a *bulleted list* :param lst: the list of strings that we want to convert into bullets :param joiner: the character that will be used to denote a bullet :returns: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import Optional from typing import Union def convert_literal(literal: Any) -> Optional[Union[bool, str]]: """Convert JSON literals to Python ones.""" # Map for the literals map_ = { "true": True, "false": False, "null": None } # Check if l...
bigcode/self-oss-instruct-sc2-concepts
def _get_hdr_values(extns, key): """ Helper function to get the all header values from a list of extensions. The return value is a dict keyed on the EXPID value. Parameters ---------- extns : iterable of :any:`astrodata.Astrodata` AstroData extensions to be examined key : str ...
bigcode/self-oss-instruct-sc2-concepts
def _GetGradSource(op_or_tensor): """Identify which call to tf.gradients created this gradient op or tensor. TensorArray gradient calls use an accumulator TensorArray object. If multiple gradients are calculated and run in the same session, the multiple gradient nodes may accidentally flow through the same ac...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import random def generate_new_symbol(symbol: List[str]) -> str: """ Select a new currency symbol. Parameters: symbol: The list of currency symbols available. Returns: str: The symbol selected randomly """ index = random.randint(0, len(symbol) - 1) ...
bigcode/self-oss-instruct-sc2-concepts
def title(text, level=0): """Given a title, format it as a title/subtitle/etc.""" return '\n' + text + '\n' + '=-~_#%^' [level] * len(text) + '\n\n'
bigcode/self-oss-instruct-sc2-concepts
def boundary_conditions(layer_outer_radii, boundary_temp): """ This function defines the temperature on the outer radius of the particle Inputs -------- -layer_outer_radii: calls on layer_outer_radii for the last point -boundary_temp: User input of the temperature at the outer radius [K] Outp...
bigcode/self-oss-instruct-sc2-concepts
def has_nan(x): """Checks if a Tensor/Array has NaNs.""" return bool((x != x).sum() > 0)
bigcode/self-oss-instruct-sc2-concepts
import binascii def _read_signify_ed25519_signature(signature_file): """ Read a Ed25519 signature file created with OpenBSD signify. http://man.openbsd.org/OpenBSD-current/man1/signify.1 """ with open(signature_file) as f: # signature file format: 2nd line is base64 of 'Ed' || 8 random oc...
bigcode/self-oss-instruct-sc2-concepts
def is_positive(x: float) -> bool: """ Return if x is positive :param x: float :return: bool """ return x > 0
bigcode/self-oss-instruct-sc2-concepts
import array def isarray(x): """Same as ``isinstance(x, array)``. """ return isinstance(x, array)
bigcode/self-oss-instruct-sc2-concepts
def unit_conversion(current_values, unit_type, current_unit, new_unit): """ Converts given values between the specified units :param current_values: the current values that you want converted between units. It can be any type, so long as arithmetic operations with scalars behave appropriately. A numpy a...
bigcode/self-oss-instruct-sc2-concepts
import csv def create_list_dict(map_data_file): """read file and create list of dictionaries Args: map_data_file (string): filename of .csv file with cities Returns: [list]: list of dictionaries (each dictionary is one city) """ with open(map_data_file, encoding="utf8") as f: ...
bigcode/self-oss-instruct-sc2-concepts
def trunc_time(time, freq): """ Truncates values in provided time array to provided frequency. E.g. 2018-01-15T12:00 with freq = 'M' becomes 2018-01-01. """ return time.astype('<M8[' + freq + ']')
bigcode/self-oss-instruct-sc2-concepts
def _check_sequence(graph_seq, known_seq): """ Check that the sequence matches up to a certain point for the known sequence. If it does return the index to where it matches. If it doesn't return 0. :param graph_seq: Actual sequence in the graph :param known_seq: One of the known sequences :retur...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _median_even(xs: List[float]) -> float: """If len(xs) is even, it's the average of the middle two elements""" sorted_xs = sorted(xs) hi_midpoint = len(xs) // 2 # e.g. length 4 => hi_midpoint 2 return (sorted_xs[hi_midpoint - 1] + sorted_xs[hi_midpoint]) / 2
bigcode/self-oss-instruct-sc2-concepts
def expct_val(Op, psi): """ compute expecation value of operator 'Op' with state 'psi' Args: Op - operator corresponding to observable to be measured psi - state-vector (on sub-Hilbertspace) Returns: <psi| Op |psi> """ return (psi.conj().T).dot(Op.dot(psi))
bigcode/self-oss-instruct-sc2-concepts
from typing import List def find_closest_value_in_list(list_request: List, value_request: int) -> int: """ Find the closest value within one list to the value of interest. """ return min(list_request, key=lambda list_value: abs(list_value - value_request))
bigcode/self-oss-instruct-sc2-concepts
def create_colocation_group_to_ops_map(op_graph): """Generate a dict that maps a colocation group to its op id list.""" retval = {} for op_id, op_data in op_graph.nodes().items(): # assume there is only one group group = op_data['colocation_group'] if group in retval: re...
bigcode/self-oss-instruct-sc2-concepts
import decimal def scinotation(x,n=2): """ Displays a number in scientific notation. :param x: number :param n: number of significant digits to display """ fmt='%.'+str(n)+'E' s= fmt % decimal.Decimal(str(x)) return s
bigcode/self-oss-instruct-sc2-concepts
import json def load(filename): """Load the configuration file""" config = None # Try to load config try: fin = open(filename, 'r') config = json.load(fin) except Exception as e: print("Failed to load config file: {}".format(filename)) print("Please ensure the...
bigcode/self-oss-instruct-sc2-concepts
import requests def callWakatimeAPI(params, route): """handles the API requests :params: object :route: string :returns: json """ headers = {'Accept':'application/x-www-form-urlencoded'} r = requests.get(route, headers=headers, params=params) return r.json()
bigcode/self-oss-instruct-sc2-concepts
def apply_to(x, f): """Takes a value and applies a function to it. This function is also known as the thrush combinator""" return f(x)
bigcode/self-oss-instruct-sc2-concepts
def dump_populations(populations): """ Dump a dictionary of populations in a archive Args: populations(dict): the dictionary of the populations Returns: set: the set of filenames (extension '.npy') which have been produced """ files = [] for label, pop in pop...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_percentile_min_max(input, lower_percentile, upper_percentile, output_tensor=False): """ Calculate the percentile max and min values in a given tensor Parameters: ---------- input: tensor the tensor to calculate percentile max and min lower_percentile: float ...
bigcode/self-oss-instruct-sc2-concepts
def check_incompatible(dict_in, inc_list): """ Check any conflicting keys in the dictionary """ for incomp in inc_list: c = 0 for k in dict_in: if k in incomp: c += 1 if c > 1: return incomp return
bigcode/self-oss-instruct-sc2-concepts
def return_config_without_apis(*, config: dict): # pylint: disable=redefined-outer-name """ A helper test function to help when mocking functions such as filter_config Returns the provided config dict after removing the "apis" keys """ del config["apis"] return config
bigcode/self-oss-instruct-sc2-concepts
def build_url(serializer, url): """ Return the full url for a file or picture :param serializer: serializer object :param url: the ending url locating the file :return: full url """ request = serializer.context.get('request', None) if request is not None and url[0] == '/': url = ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def datetime_fromisoformat(datestr: str): """Convert iso formatted datetime string to datetime object This is only needed for compatibility, as datetime.fromisoformat() was added in Python 3.7 """ return datetime.strptime(datestr, "%Y-%m-%dT%H:%M:%S")
bigcode/self-oss-instruct-sc2-concepts
import re def sanitize_results_filename(filename: str) -> str: """Sanitizes results file name. Args: filename: original filename Returns: sanitized filename """ return re.sub(r'[^\w\-\=]+', '_', filename)
bigcode/self-oss-instruct-sc2-concepts
import click def get_checkpoint_by_class(db, class_path): """Returns checkpoint entry in `db` indicated by `class_path`. Parameters ---------- class_path : str Fully specified path to class (e.g. `terran.pose.openpose.OpenPose`) of the model to get the checkpoint for. Returns ...
bigcode/self-oss-instruct-sc2-concepts
def distinct_powers(a, b): """Generate distinct terms in a**b""" numbers = [] for i in range(a[0], a[1]+1): for j in range(b[0], b[1]+1): numbers.append(i**j) # Set makes it the numbers values unique return set(numbers)
bigcode/self-oss-instruct-sc2-concepts
def get_network_bits(mask_binary): """ Returns number of network bits of given mask :param mask_binary: Subnet Mask in binary :return: Number of network bits """ count = 0 for i in mask_binary: if int(i) == 1: count += 1 return count
bigcode/self-oss-instruct-sc2-concepts
def request_authorized(request) -> bool: """Return ``true`` if ``request`` was authorized using :py:func:`authorize`.""" return getattr(request, "_oso_authorized", False)
bigcode/self-oss-instruct-sc2-concepts
def encodeWord(word: str, isNormalVersionForLogicallyThinkingHuman: bool) -> str: """Encode single word into its numerical representation in given system (e.g. "koko" -> "3131")""" map1 = {1:['w', 'e', 'r', 'u', 'i', 'o', 'a', 's', 'z', 'x', 'c', 'v', 'n', 'm', 'ę', 'ó', 'ą', 'ś', 'ń', 'ć', 'ż', 'ź'], 2: [...
bigcode/self-oss-instruct-sc2-concepts