seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_index_basename() -> str:
"""Get the basename for a streaming dataset index.
Returns:
str: Basename of file.
"""
return 'index.mds' | bigcode/self-oss-instruct-sc2-concepts |
def convert_subscripts(old_sub, symbol_map):
"""Convert user custom subscripts list to subscript string according to `symbol_map`.
Examples
--------
>>> oe.parser.convert_subscripts(['abc', 'def'], {'abc':'a', 'def':'b'})
'ab'
>>> oe.parser.convert_subscripts([Ellipsis, object], {object:'a'})
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
def _str_none(dct: Dict[str, Any]) -> Dict[str, Any]:
"""Make all the None value to string 'none'."""
return {key: "none" if value is None else value for key, value in dct.items()} | bigcode/self-oss-instruct-sc2-concepts |
import re
def re_filter(text, regexps):
"""Filter text using regular expressions."""
if not regexps:
return text
matched_text = []
compiled_regexps = [re.compile(x) for x in regexps]
for line in text:
if line in matched_text:
continue
for regexp in compiled_re... | bigcode/self-oss-instruct-sc2-concepts |
def getAddressSuggestions(connection, pattern, limit):
"""Fetching address suggestions for a given search pattern
Parameters
----------
connection : psygopg2.connection
psycopg2 connection object
pattern : str
search pattern
limit : int
maximum number of suggestions to r... | bigcode/self-oss-instruct-sc2-concepts |
def _cvtfield(f):
"""
If str passed in via 'f' parameter is '-' then
return empty string otherwise return value of 'f'
:param f:
:return: empty string if 'f' is '-' otherwise return 'f'
:rtype: str
"""
if f is None or f != '-':
return f
return '' | bigcode/self-oss-instruct-sc2-concepts |
def to_power_three(number):
"""
Returns the number to the power of three.
:param number: The number
:return: The number to the power of three
"""
return number ** 3 | bigcode/self-oss-instruct-sc2-concepts |
def VARIANCE(src_column):
"""
Builtin variance aggregator for groupby. Synonym for tc.aggregate.VAR
Example: Get the rating variance of each user.
>>> sf.groupby("user",
... {'rating_var':tc.aggregate.VARIANCE('rating')})
"""
return ("__builtin__var__", [src_column]) | bigcode/self-oss-instruct-sc2-concepts |
def _trim_ds(ds, epochs):
"""Trim a Dataset to account for rejected epochs.
If no epochs were rejected, the original ds is rturned.
Parameters
----------
ds : Dataset
Dataset that was used to construct epochs.
epochs : Epochs
Epochs loaded with mne_epochs()
"""
if len(e... | bigcode/self-oss-instruct-sc2-concepts |
def PIsA (inImage):
"""
Tells if input really a Python Obit ImageMF
return True, False
* inImage = Python Image object
"""
################################################################
try:
return inImage.ImageMFIsA()!=0
except:
return False
# end PIsA | bigcode/self-oss-instruct-sc2-concepts |
def linear_sieve(max_n):
"""Computes all primes < max_n and lits of
all smallest factors in O(max_n) time
Returns
-------
primes: list of all primes < max_n
smallest_factors: list such that if q = smallest_factors[n],
then n % q == 0 and q is minimal.
"""
smallest_factors = [0] ... | bigcode/self-oss-instruct-sc2-concepts |
def apply_threshold(heatmap, threshold):
"""
Apply threshold to the heatmap to remove false positives.
Parameters:
heatmap: Input heatmap.
threshold: Selected threshold.
"""
heatmap[heatmap < threshold] = 0
return heatmap | bigcode/self-oss-instruct-sc2-concepts |
def get_number_rows(ai_settings,ship_height,alien_height):
"""determine the number of rows of aliens that fits on a screen"""
available_space_y=(ai_settings.screen_height - (5 * alien_height)-ship_height)
number_rows=int(available_space_y/(2 * alien_height))
return number_rows | bigcode/self-oss-instruct-sc2-concepts |
def split_schema_obj(obj, sch=None):
"""Return a (schema, object) tuple given a possibly schema-qualified name
:param obj: object name or schema.object
:param sch: schema name (defaults to 'public')
:return: tuple
"""
qualsch = sch
if sch is None:
qualsch = 'public'
if '.' in ob... | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def a2bits(chars: str) -> str:
"""Converts a string to its bits representation as a string of 0's and 1's.
>>> a2bits("Hello World!")
'010010000110010101101100011011000110111100100000010101110110111101110010011011000110010000100001'
"""
return bin(reduce(lambda x, y: ... | bigcode/self-oss-instruct-sc2-concepts |
def get_all_combinations(node_lists):
"""
Generate a list of all possible combinations of items in the list of
lists `node_lists`. Each combination takes one item from each list
contained within `node_lists`. The order of items in the returned lists
reflects the order of lists in `node_lists`. For e... | bigcode/self-oss-instruct-sc2-concepts |
def recover_flattened(flat_params, indices, model):
"""
Gives a list of recovered parameters from their flattened form
:param flat_params: [#params, 1]
:param indices: a list detaling the start and end index of each param [(start, end) for param]
:param model: the model that gives the params with co... | bigcode/self-oss-instruct-sc2-concepts |
def make_dict(keys, values):
"""
Returns a dictionary that maps keys to values correspondingly.
Assume inputs are of same length.
"""
return dict(zip(keys,values)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def extract_phrases(text):
""" extract phrases, i.e. group of continuous words, from text """
return re.findall('\w[\w ]+', text, re.UNICODE) | bigcode/self-oss-instruct-sc2-concepts |
def dict_reorder(item: dict) -> dict:
"""
Sorts dict by keys, including nested dicts
:param item: dict to sort
"""
if isinstance(item, dict):
item = {k: item[k] for k in sorted(item.keys())}
for k, v in item.items():
if isinstance(v, dict):
item[k] = dict_... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_name(name):
"""Capitalize all words in name."""
words = name.split()
res = ""
for w in words:
if res != "":
res += " "
res += w.capitalize()
return res | bigcode/self-oss-instruct-sc2-concepts |
def get_date_formatted(date):
"""
Return the date in the format: 'YEAR-MONTH-DAY'
"""
year = str(date.year)
month = str(date.month)
day = str(date.day)
single_digits = range(1, 10)
if date.month in single_digits:
month = '0' + month
if date.day in single_digits:
d... | bigcode/self-oss-instruct-sc2-concepts |
import jinja2
def render_happi_template_arg(template, happi_item):
"""Fill a Jinja2 template using information from a happi item."""
return jinja2.Template(template).render(**happi_item) | bigcode/self-oss-instruct-sc2-concepts |
def getParentPath(path):
"""Get the parent path from C{path}.
@param path: A fully-qualified C{unicode} path.
@return: The C{unicode} parent path or C{None} if C{path} represents a
root-level entity.
"""
unpackedPath = path.rsplit(u'/', 1)
return None if len(unpackedPath) == 1 else unpa... | bigcode/self-oss-instruct-sc2-concepts |
def two2one(x, y):
"""Maps a positive (x,y) to an element in the naturals."""
diag = x + y
bottom = diag * (diag + 1) / 2
return bottom + y | bigcode/self-oss-instruct-sc2-concepts |
def get_complementary_orientation(orientation):
"""Used to find the outcoming orientation given the incoming one (e.g. N ->
S; E-> W; S -> N; W -> E)."""
return (orientation + 2) % 4 | bigcode/self-oss-instruct-sc2-concepts |
import requests
def send_token_request(form_values, add_headers={}):
"""Sends a request for an authorization token to the EVE SSO.
Args:
form_values: A dict containing the form encoded values that should be
sent with the request
add_headers: A dict containing additional h... | bigcode/self-oss-instruct-sc2-concepts |
def _get_previous_month(month, year):
"""Returns previous month.
:param month: Month (integer from 1...12).
:param year: Year (integer).
:return: previous_month: Previous month (integer from 1...12).
:return: previous_year: Previous year (integer).
"""
previous_month = month - 1
if pr... | bigcode/self-oss-instruct-sc2-concepts |
import math
def get_rows_cols_for_subplot(num_subplots:int)->tuple:
"""
This function calculates the rows and cols required
for the subplot..
Args:
num_subplots:int
Returns:
nrows:int
ncols:int
odd:bool
"""
try:
nrows=ncols=0
o... | bigcode/self-oss-instruct-sc2-concepts |
def strip_surrounding(word):
"""
Strip spaces in the front or back of word.
:param word: A word (or sentence) of which we want to strip the surrounding spaces.
:return: A string that doesn't start or end with a space.
"""
while word and (word[0] != ' ' or word[-1] != ' '):
if word[0] ==... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def run_length_encode(tags_to_encode):
"""Perform run length encoding.
Args:
tags_to_encode: A string, usually of DeletionTags.
Returns:
the RLE string. For example, if the input was NNNNNCNNTTC,
the function would return 5N1C2N2T1C
"""
rle_list = [(... | bigcode/self-oss-instruct-sc2-concepts |
def assign_x_coord(row):
"""
Assigns an x-coordinate to Statcast's strike zone numbers. Zones 11, 12, 13,
and 14 are ignored for plotting simplicity.
"""
# left third of strik zone
if row.zone in [1,4,7]:
return 1
# middle third of strike zone
if row.zone in [2,5,8]:
ret... | bigcode/self-oss-instruct-sc2-concepts |
def dsf_func(d50, theta ):
"""
Calculate sheet flow thickess
Input:
d50 - median grain size (m)
Theta - maximum (crest or trough) Shields paramter
Returns:
dsf - thickness of sheet flow layer (m)
Based on Janssen (1999) in van der A et al. (2013), Appendix C.
See also Do... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def MM_mult(x, y):
"""A function that returns x*y, where x and y are complex tensors.
:param x: A complex matrix.
:type x: torch.doubleTensor
:param y: A complex matrix.
:type y: torch.doubleTensor
:raises ValueError: If x and y do not have 3 dimensions or their first dimens... | bigcode/self-oss-instruct-sc2-concepts |
def id(left_padding=None, right_padding=None, offset=None):
"""Constructs an implicit-duration spec dictionary."""
result = {}
if left_padding is not None:
result['left_padding'] = left_padding
if right_padding is not None:
result['right_padding'] = right_padding
if offset is no... | bigcode/self-oss-instruct-sc2-concepts |
def isac(c):
"""
A simple function, which determine whether the
string element char c is belong to a decimal number
:param c: a string element type of char
:return: a bool type of determination
"""
try:
int(c)
return True
except:
if c == '.' or c == '-' or c == 'e... | bigcode/self-oss-instruct-sc2-concepts |
import math
def rhs(y1, y2):
""" RHS function. Here y1 = u, y2 = u'
This means that our original system is:
y2' = u'' = -0.25*pi**2 (u+1) """
dy1dx = y2
dy2dx = -0.25*math.pi**2 * (y1 + 1.0)
return dy1dx, dy2dx | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def load_current_user(request_context) -> Optional[str]:
"""Load the current user from the request."""
if (authorizer := request_context.get("authorizer")) is not None:
claims = authorizer.get("claims", {})
return claims.get("sub")
return None | bigcode/self-oss-instruct-sc2-concepts |
def process_subset(subset, separator="\t"):
"""Processes the given subset.
Extracts the input tokens (words) and labels for each sequence in the subset.
Forms a representation string for each sample in the following format:
SEQ_LEN [SEPARATOR] INPUT_TOKENS [SEPARATOR] LABELS
where:
... | bigcode/self-oss-instruct-sc2-concepts |
def fibonacci(count:int)->list:
"""
This function takes a count an input and generated Fibonacci series element count equal to count
# input:
count : int
# Returns
list
# Funcationality:
Calcualtes the sum of last two list elements and appends it to the list until ... | bigcode/self-oss-instruct-sc2-concepts |
def parse_row(row, cols, sheet):
"""
parse a row into a dict
:param int row: row index
:param dict cols: dict of header, column index
:param Sheet sheet: sheet to parse data from
:return: dict of values key'ed by their column name
:rtype: dict[str, str]
"""
vals = {}
for header, ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Mapping
from typing import Any
from typing import Tuple
def gate_boundaries(gate_map: Mapping[str, Any]) -> Mapping[str, Tuple[float, float]]:
""" Return gate boundaries
Args:
gate_map: Map from gate names to instrument handle
Returns:
Dictionary with gate boundaries
... | bigcode/self-oss-instruct-sc2-concepts |
def get_name(s, isconj=False):
"""Parse variable names of form 'var_' as 'var' + conjugation."""
if not type(s) is str:
if isconj:
return str(s), False
else:
return str(s)
if isconj:
return s.rstrip("_"), s.endswith("_") # tag names ending in '_' for conj
... | bigcode/self-oss-instruct-sc2-concepts |
def hide_string_content(s):
"""
Replace contents of string literals with '____'.
"""
if (not isinstance(s, str)):
return s
if ('"' not in s):
return s
r = ""
start = 0
while ('"' in s[start:]):
# Out of string. Add in as-is.
end = s[start:].index('"')... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_files_by_pattern(directory: str, glob_pattern: str) -> list[Path]:
"""Return list of files matching pattern"""
path = Path(directory)
return [file for file in path.glob(glob_pattern) if file.is_file()] | bigcode/self-oss-instruct-sc2-concepts |
def calc_num_beats(rpeak_locs, metrics):
"""Calculates the number of beats in an ECG
This function takes an array of the ECG R-peaks. The number of R-peaks
is equivalent to the number of beats in the ECG.
Args:
rpeak_locs (1D numpy array): index locations of R-peaks in an ECG.
metrics ... | bigcode/self-oss-instruct-sc2-concepts |
def _get_revision(config):
"""
Extracts branch and revision number from the given config parameter.
@return: (branch, revision number)
"""
if config.revision:
tokens = config.revision.split(":")
svn_branch = tokens[0]
if len(tokens) > 1:
revision = config.revision... | bigcode/self-oss-instruct-sc2-concepts |
def get_header(token):
""" Return a header with authorization info, given the token. """
return {
'Authorization': 'token %s' % token,
'Content-Type': 'application/json; charset=UTF-8'
} | bigcode/self-oss-instruct-sc2-concepts |
def determine_color(memory_limit_gb, memory_usage_gb, dark_background=False):
"""Determine a display color based on percent memory usage
Parameters
----------
memory_limit_gb : int
Overall memory limit in gigabytes
memory_usage_gb : int
Memory usage value in gigabytes
dark_b... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def count_user_type(user_type_list:List[str]) -> List[int]:
""" Calcula a quantidade de Clientes e Assinantes.
Por meio de uma lista calcula a quantidade de clientes "Customer" e assinantes "Subscriber".
:param data_list: Lista contendo os tipos de usuário.
:returns: Lista de ... | bigcode/self-oss-instruct-sc2-concepts |
def datetime_to_float(datetime):
"""
SOPC_DateTime* (the number of 100 nanosecond intervals since January 1, 1601)
to Python time (the floating point number of seconds since 01/01/1970, see help(time)).
"""
nsec = datetime[0]
# (datetime.date(1970,1,1) - datetime.date(1601,1,1)).total_seconds() ... | bigcode/self-oss-instruct-sc2-concepts |
def regularize_reliability(rel_1, rel_2):
"""
Regularizes the reliability estimates for a pair of graders.
Parameters
----------
rel_1 : float.
Estimated reliability of grader 1.
rel_2 : float.
Estimated reliability of grader 2.
Returns
-------
t_1 : float... | bigcode/self-oss-instruct-sc2-concepts |
def cs_rad(altitude, ext_rad):
"""
Estimate clear sky radiation from altitude and extraterrestrial radiation.
Based on equation 37 in Allen et al (1998) which is recommended when
calibrated Angstrom values are not available.
:param altitude: Elevation above sea level [m]
:param ext_rad: Extrat... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import pathlib
def get_core_lists() -> List[pathlib.Path]:
"""Return a list of paths for all rutrivia lists packaged with the bot."""
core_lists_path = pathlib.Path(__file__).parent.resolve() / "data/lists"
return list(core_lists_path.glob("*.yaml")) | bigcode/self-oss-instruct-sc2-concepts |
def is_string_type(thetype):
"""Returns true if the type is one of: STRING, TIMESTAMP, DATE, or
TIME."""
return thetype in [
'STRING', 'TIMESTAMP', 'DATE', 'TIME', 'QINTEGER', 'QFLOAT', 'QBOOLEAN'
] | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def convert_data_set(data_set, data_set_writer, transformation=None,
count_dist=False, prime_wise=False, remove_duplicities=False):
"""
Convert data set to a different format.
If transformation is provided, compute features and add them to the key
key that gets sav... | bigcode/self-oss-instruct-sc2-concepts |
def get_picam(c):
""" Return a dict of the attributes in a PiCamera"""
d = {}
if type(c).__name__ == "PiCamera":
all_settings = ['analog_gain', 'awb_mode', 'awb_gains', 'contrast', 'drc_strength', 'digital_gain',
'exposure_mode', 'exposure_speed', 'framerate', 'hflip', 'iso',... | bigcode/self-oss-instruct-sc2-concepts |
def get_engine_turbo(t):
"""
Function to get turbo or regular for engine type
"""
tt = t.split(" ")[-1]
if "turbo" in tt:
return "turbo"
return "regular" | bigcode/self-oss-instruct-sc2-concepts |
def is_point_in_range(p, p_min=None, p_max=None) -> bool:
"""Check if point lays between two other points.
Args:
p: tuple (x, y)
p_min (optional): min border point
p_max (optional): max border point
Returns:
True if p_max >= p >= p_min
"""
if p_min is None and p_max... | bigcode/self-oss-instruct-sc2-concepts |
def even(x):
"""
even :: Integral a => a -> Bool
Returns True if the integral value is even, and False otherwise.
"""
return x % 2 == 0 | bigcode/self-oss-instruct-sc2-concepts |
def split_estimates(df, org):
"""Split the passed dataframe into either Sakai or DH10B subsets"""
if org == 'dh10b':
subset = df.loc[df['locus_tag'].str.startswith('ECDH10B')]
else:
subset = df.loc[~df['locus_tag'].str.startswith('ECDH10B')]
return subset | bigcode/self-oss-instruct-sc2-concepts |
def only_true(*elts):
"""Returns the sublist of elements that evaluate to True."""
return [elt for elt in elts if elt] | bigcode/self-oss-instruct-sc2-concepts |
def is_prime(n: int) -> bool:
"""
Checks if n is a prime number
"""
if n < 1:
return False
for i in range(2, n // 2):
if n % i == 0:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def valid_ipv4_host_address(host):
"""Determine if the given host is a valid IPv4 address."""
# If the host exists, and it might be IPv4, check each byte in the
# address.
return all([0 <= int(byte, base=10) <= 255 for byte in host.split('.')]) | bigcode/self-oss-instruct-sc2-concepts |
def format_sex_string(sex_str):
"""
Converts 'M', 'F', or else to 'male', 'female', or empty string (e.g. '').
Args:
sex_str (str): String consisting of 'M', 'F', '', or None.
Returns:
str: 'M', 'F', or ''
"""
if sex_str == "M":
sex = "male"
elif sex_str == "F":
... | bigcode/self-oss-instruct-sc2-concepts |
def mandel(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
c = complex(x, y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
if (z.r... | bigcode/self-oss-instruct-sc2-concepts |
def one_or_more(string):
"""
A regex wrapper for an arbitrary string.
Allows an arbitrary number of successive valid matches (at least one) to be matched.
"""
return r'(?:{:s}){{1,}}'.format(string) | bigcode/self-oss-instruct-sc2-concepts |
def get_elev_abbrev(cell):
"""
Parse elevation and station abbreviation.
"""
tc = cell.text_content().strip()
return int(tc[:-6]), tc[-4:-1] | bigcode/self-oss-instruct-sc2-concepts |
import json
def str_format_dict(jdict, **kwargs):
"""Pretty-format a dictionary into a nice looking string using the `json` package.
Arguments
---------
jdict : dict,
Input dictionary to be formatted.
Returns
-------
jstr : str,
Nicely formatted string.
"""
kwarg... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import re
def _normalize(x: Optional[str]) -> Optional[str]:
"""
Normalize string to lowercase, no whitespace, and no underscores.
Examples
--------
>>> _normalize('Offshore Wind')
'offshorewind'
>>> _normalize('OffshoreWind')
'offshorewind'
>>> _normal... | bigcode/self-oss-instruct-sc2-concepts |
def AddAssay(adata, data, key, slot="obsm"):
"""Add a new data as a key to the specified slot
Parameters
----------
adata: :AnnData
AnnData object
data: `pd.DataFrame`
The data (in pandas DataFrame format) that will be added to adata.
key: `str`
T... | bigcode/self-oss-instruct-sc2-concepts |
def create_mosaic_pars(mosaic_wcs):
"""Return dict of values to use with AstroDrizzle to specify output mosaic
Parameters
-----------
mosaic_wcs : object
WCS as generated by make_mosaic_wcs
Returns
--------
mosaic_pars : dict
This dictionary can be used as input to astrodri... | bigcode/self-oss-instruct-sc2-concepts |
import math
def cent_diff(freq1, freq2):
"""Returns the difference between 2 frequencies in cents
Parameters
----------
freq1 : float
The first frequency
freq2 : float
The second frequency
Returns
-------
float
The difference between the 2 frequencies
"""... | bigcode/self-oss-instruct-sc2-concepts |
def class_in_closure(x):
"""
>>> C1, c0 = class_in_closure(5)
>>> C1().smeth1()
(5, ())
>>> C1.smeth1(1,2)
(5, (1, 2))
>>> C1.smeth1()
(5, ())
>>> c0.smeth0()
1
>>> c0.__class__.smeth0()
1
"""
class ClosureClass1(object):
@staticmethod
def smeth1(*... | bigcode/self-oss-instruct-sc2-concepts |
def _get_obj_file(ctx, src):
"""Returns the obj file for the given src."""
extension_index = src.short_path.rindex(".c")
obj_file = src.short_path[0:extension_index] + ".o"
return ctx.new_file(obj_file) | bigcode/self-oss-instruct-sc2-concepts |
def find_nested_parentheses(string):
"""
An equation that could contain nested parentheses
:param str string: An equation to parse
:return: A dict with the indexes of opening/closing parentheses per nest level
:rtype: dict
"""
indexes = {}
nested_level = 0
for i, char in enumerate(st... | bigcode/self-oss-instruct-sc2-concepts |
def _append_ns(in_ns, suffix):
"""
Append a sub-namespace (suffix) to the input namespace
:param in_ns Input namespace
:type in_ns str
:return: Suffix namespace
:rtype: str
"""
ns = in_ns
if ns[-1] != '/':
ns += '/'
ns += suffix
return ns | bigcode/self-oss-instruct-sc2-concepts |
def render(line, prefix_arg=None, color=-1):
"""
Turn a line of text into a ready-to-display string.
If prefix_arg is set, prepend it to the line.
If color is set, change to that color at the beginning of the rendered line and change out before the newline (if
there is a newline).
:param str lin... | bigcode/self-oss-instruct-sc2-concepts |
def onek_unk_encoding(x, set):
"""Returns a one-hot encoding of the given feature."""
if x not in set:
x = 'UNK'
return [int(x == s) for s in set] | bigcode/self-oss-instruct-sc2-concepts |
def hamming_distance(str1, str2):
"""Computes the hamming distance (i.e. the number of
differing bits) between two byte strings.
Keyword arguments:
str1 -- the first byte string
str2 -- the second byte string
"""
distance = 0
for b1, b2 in zip(str1, str2):
# xor in each place is... | bigcode/self-oss-instruct-sc2-concepts |
import fnmatch
def is_copy_only_path(path, context):
"""Check whether the given `path` should only be copied and not rendered.
Returns True if `path` matches a pattern in the given `context` dict,
otherwise False.
:param path: A file-system path referring to a file or dir that
should be rend... | bigcode/self-oss-instruct-sc2-concepts |
def jaccard_coefficient(x,y):
"""
Jaccard index used to display the similarity between sample sets.
:param A: set x
:param y: set y
:return: similarity of A and B or A intersect B
"""
return len(set(x) & set(y)) / len(set(x) | set(y)) | bigcode/self-oss-instruct-sc2-concepts |
import ssl
def get_ssl_context(account):
"""Returns None if the account doesn't need to skip ssl
verification. Otherwise returns ssl context with disabled
certificate/hostname verification."""
if account["skip_ssl_verification"]:
ssl_context = ssl.create_default_context()
ssl_context.c... | bigcode/self-oss-instruct-sc2-concepts |
def removeBelowValue(requestContext, seriesList, n):
"""
Removes data below the given threshold from the series or list of series provided.
Values below this threshold are assigned a value of None.
"""
for s in seriesList:
s.name = 'removeBelowValue(%s, %d)' % (s.name, n)
s.pathExpression = s.name
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def request_issues(url):
"""Request issues from the given GitHub project URL.
Parameters
----------
url : str
URL of GitHub project.
Returns
-------
response : Response
Response data.
"""
response = requests.get(url)
return response | bigcode/self-oss-instruct-sc2-concepts |
def create_snapshot_dict(pair, revision_id, user_id, context_id):
"""Create dictionary representation of snapshot"""
parent, child = pair.to_2tuple()
return {
"parent_type": parent.type,
"parent_id": parent.id,
"child_type": child.type,
"child_id": child.id,
"revision_id": revision_i... | bigcode/self-oss-instruct-sc2-concepts |
def new_evidence_file(network_filename, variable, value):
"""Creates a new evidence file for a given goal variable-value pair (and
returns its filename)."""
new_filename = network_filename + '.inst'
with open(new_filename, 'w') as evidence_file:
evidence_file.write(
'<?xml version="1... | bigcode/self-oss-instruct-sc2-concepts |
def erd_encode_bytes(value: bytes) -> str:
"""Encode a raw bytes ERD value."""
return value.hex('big') | bigcode/self-oss-instruct-sc2-concepts |
def quaternion_is_valid(quat, tol=10e-3):
"""Tests if a quaternion is valid
:param quat: Quaternion to check validity of
:type quat: geometry_msgs.msg.Quaternion
:param tol: tolerance with which to check validity
:return: `True` if quaternion is valid, `False` otherwise
:rtype: bool
"""... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_program_type(program_type):
""" Function that normalizes a program type string for use in a cache key. """
return str(program_type).lower() | bigcode/self-oss-instruct-sc2-concepts |
def _strip_path_prefix(path, prefix):
"""Strip a prefix from a path if it exists and any remaining prefix slashes
Args:
path: <string>
prefix: <string>
Returns:
<string>
"""
if path.startswith(prefix):
path = path[len(prefix):]
if path.startswith("/"):
pa... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def is_eof(char: Optional[str]) -> bool:
"""Check if a character is EOF."""
return char is None | bigcode/self-oss-instruct-sc2-concepts |
def clean_backticks(msg):
"""Prevents backticks from breaking code block formatting"""
return msg.replace("`", "\U0000ff40") | bigcode/self-oss-instruct-sc2-concepts |
def pythonify_metrics_json(metrics):
"""Converts JSON-style metrics information to native Python objects"""
metrics = metrics.copy()
for key in metrics.keys():
if key.endswith("_histogram") or key.endswith("_series"):
branch = metrics[key]
for sub_key in branch.keys():
... | bigcode/self-oss-instruct-sc2-concepts |
def newline_to_br(base):
"""Replace newline with `<br />`"""
return base.replace('\n', '<br />') | bigcode/self-oss-instruct-sc2-concepts |
def is_key(sarg):
"""Check if `sarg` is a key (eg. -foo, --foo) or a negative number (eg. -33)."""
if not sarg.startswith("-"):
return False
if sarg.startswith("--"):
return True
return not sarg.lstrip("-").isnumeric() | bigcode/self-oss-instruct-sc2-concepts |
def find_empty_cell(board):
"""
finds the empty cell going left to right, top to bottom on the board
"""
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j)
return None | bigcode/self-oss-instruct-sc2-concepts |
def splitLast(myString, chunk):
"""
returns a tuple of two strings, splitting the string at the last occurence of a given chunk.
>>> splitLast('hello my dear friend', 'e')
('hello my dear fri', 'nd')
"""
p = myString.rfind(chunk)
if p > -1:
return myString[0:p], myString[p + len(chun... | bigcode/self-oss-instruct-sc2-concepts |
def server_no_key(server_factory):
"""
Return a :class:`saltyrtc.Server` instance that has no permanent
key pair.
"""
return server_factory(permanent_keys=[]) | bigcode/self-oss-instruct-sc2-concepts |
def lower_tree(tree):
"""
Change all element names and attribute names to lower case.
"""
root = tree.getroot()
for node in root.iter():
node.tag = node.tag.lower()
attributes = dict()
for attribute in node.attrib:
attributes[attribute.lower()] = node.attrib[a... | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.