seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def greet_all(greeting: str, names: list) -> list:
"""Return a list of strings that consist of the greeting messages for each person in names.
The format of each greeting message is '<greeting>, <name>',
where greeting is the given greeting and <name> is an element of <names>.
The returned list should... | bigcode/self-oss-instruct-sc2-concepts |
def idx_word(idx, nlp):
"""
Returns the token/word at the specified index of the spaCy model.
:param idx: The index to query.
:param nlp: The spaCy model.
:return: Word at the index in the vocabulary.
"""
hash_code = nlp.vocab.vectors.find(row=idx)
if len(hash_code) == 0: return '<UNK>'
return nlp.vocab.stri... | bigcode/self-oss-instruct-sc2-concepts |
def get_entity_from_bio(tokens, entitys):
"""
Get {word:entity} from bio labeled sequence,.
Only accept BIO schema.
inputs:
tokens: A B C D E F
entitys: B-GPE I-GPE B-PER I-PER O O
return: {'AB': 'GPE', 'CD': 'PER'}
"""
word2entity = {}
left = 0
r... | bigcode/self-oss-instruct-sc2-concepts |
def all_same_suit(card_set):
"""
Determines whether the cards in the given collection are all of the same
suit.
"""
return all(card.suit == card_set[0].suit for card in card_set[1:]) | bigcode/self-oss-instruct-sc2-concepts |
def lorenz(in_, t, sigma, b, r):
"""Evaluates the RHS of the 3
Lorenz attractor differential equations.
in_ : initial vector of [x_0, y_0, z_0]
t : time vector (not used, but present for odeint() call)
sigma : numerical parameter 1
b : numerical parameter 2
r : numerical parameter ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Sequence
from typing import Dict
def get_masks(counterfactuals: Sequence[Sequence[str]],
vocab_to_indices: Dict[str, Sequence[int]]):
"""Returns masks indicating if counterfactual tokens are in original sentence.
Args:
counterfactuals: The tokens of the input's counterfactual... | bigcode/self-oss-instruct-sc2-concepts |
def zscore(raw, mean, stddev):
"""Returns the zscore (standard score) of a value"""
zscore = (raw - mean) / stddev
return zscore | bigcode/self-oss-instruct-sc2-concepts |
def get_filter_list(table):
"""Get the filter list and number of filter in a table."""
filters = set(table['filter'])
return filters, len(filters) | bigcode/self-oss-instruct-sc2-concepts |
def approximate_index(dataset, findvalue):
""" Return index value in dataset, with optimized find procedure.
This assumes a `dataset` with continuous, increasing values. Typically, these are timestamps.
:param list dataset: a continuous list of values (f.e. timestamps)
:param int findvalue: the value,... | bigcode/self-oss-instruct-sc2-concepts |
def _find_qubit_id(cmd):
"""Find qubit id in openqasm cmd."""
left = []
right = []
for i, j in enumerate(cmd):
if j == '[':
left.append(i)
elif j == ']':
right.append(i)
if len(left) != len(right):
raise ValueError(f"Parsing failed for cmd {cmd}")
... | bigcode/self-oss-instruct-sc2-concepts |
def get_upload_path(instance, filename):
"""
Construct the path to where the uploaded config file is to be stored.
"""
configtype = instance.config_type.lower()
# sanitize the filename here..
path = 'export/config/{0}/{1}'.format(configtype, instance.filename)
return path | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
def compute_product_string(product_string):
"""Takes `product_string` and returns the product of the factors as string.
Arguments:
- `product_string`: string containing product ('<factor>*<factor>*...')
"""
factors = [float(f) for f in product_string.split("*")]
... | bigcode/self-oss-instruct-sc2-concepts |
def get_battery_energy_full(battery_id):
"""
Get the maximum energy stored in the battery
:param battery_id: Battery ID/Number e.g. BAT0
:return: maximum energy (int)
"""
with open(f'/sys/class/power_supply/{battery_id}/energy_full') as f:
battery_percentage = int(f.read())
return b... | bigcode/self-oss-instruct-sc2-concepts |
def _GetTestSubPath(key):
"""Gets the part of the test path after the suite, for the given test key.
For example, for a test with the test path 'MyMaster/bot/my_suite/foo/bar',
this should return 'foo/bar'.
Args:
key: The key of the TestMetadata entity.
Returns:
Slash-separated test path part after... | bigcode/self-oss-instruct-sc2-concepts |
def get_string_without_quotes(str):
"""
Helper function to return a string without the quotes
:param str: Input String
:type str: String
:return: String with quotes replaced
:rtype: String
"""
return str.replace('"', '') | bigcode/self-oss-instruct-sc2-concepts |
def property_type(value):
"""
Return the type for given value in Neo4j land.
"""
if isinstance(value, str):
return "string"
elif isinstance(value, int):
return "int"
elif isinstance(value, float):
# Nb. Python floats are double precision
return "double"
elif ... | bigcode/self-oss-instruct-sc2-concepts |
def pivotCombinedInventories(combinedinventory_df):
"""Create a pivot table of combined emissions.
:param combinedinventory_df: pandas dataframe returned from a
'combineInventories..' function
:return: pandas pivot_table
"""
# Group the results by facility,flow,and compartment
combinedi... | bigcode/self-oss-instruct-sc2-concepts |
def fahrenheit_to_celsius(temperature):
"""Covert from Fahrenheit to Celsius
:param temperature: degree understood to be in Fahrenheit
NOTE:
Fahrenheit to Celsius formula: °C = (°F - 32) x 5/9
First subtract 32, then multiply by 5, then divide by 9.
"""
return (temperature - 32) * 5.0 / 9.0 | bigcode/self-oss-instruct-sc2-concepts |
def ranges_overlap(min1, max1, min2, max2):
"""
:param min1:
:param max1:
:param min2:
:param max2:
:return: return True if the 2 ranges overlap (edge inclusive), else False
"""
if min1 <= max2 and min2 <= max1:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import copy
def recursive_postprocessing(filter_, condition, replacement):
"""Recursively descend into the query, checking each dictionary
(contained in a list, or as an entry in another dictionary) for
the condition passed. If the condition is true, apply the
replacement to the dictionary.
Param... | bigcode/self-oss-instruct-sc2-concepts |
import bisect
def find_between(a, low, high):
"""Finds all elements of a between low and high.
Simple binary search algorithm using the bisect module. Searches the
array a for all elements between low and high.
Useful for finding mergers that occur between time t1 and t2.
Arguments:
a {... | bigcode/self-oss-instruct-sc2-concepts |
def get_attribute(element, attribute, default=0):
""" Returns XML element's attribute, or default if none.
"""
a = element.getAttribute(attribute)
if a == "":
return default
return a | bigcode/self-oss-instruct-sc2-concepts |
import zlib
import random
def find_credit_grade(email):
"""Returns the credit grade of the person identified by the given email address.
The credit grade is generated randomly using the email as the seed to the random
number generator.
The credit grade can be either A, B, C, D, E, F or G.
""... | bigcode/self-oss-instruct-sc2-concepts |
def _factor2(n):
"""Factorise positive integer n as d*2**i, and return (d, i).
>>> _factor2(768)
(3, 8)
>>> _factor2(18432)
(9, 11)
Private function used internally by the Miller-Rabin primality test.
"""
assert n > 0
i = 0
d = n
while 1:
q, r = divmod(d, 2)
... | bigcode/self-oss-instruct-sc2-concepts |
def ConsensusMotif(sequence_set):
"""Find the consensus motif for the input sequence set."""
k = len(sequence_set[0])
matrix = [[0] * k for i in range(4)] # Initiate a zero-filled nested list.
for col, colbases in enumerate(zip(*sequence_set)):
for row, letter in enumerate('ACGT'):
... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def cartesian_goals(x, y):
"""
Use a cartesian coordinate system to calculate goals from given X and Y
values.
:param x: x cartesian coordinate
:param y: y cartesian coordinate
:return: cartesian derived base, fibia, and tibia servo goal values
"""
# Convert 2D X and Y ... | bigcode/self-oss-instruct-sc2-concepts |
def has_overlap2(label1,label2):
"""
Returns TRUE if the two labels overlap
Otherwise returns FALSE
"""
label1,label2 = label1.lower(),label2.lower()
labeloverlaps = {"pron-subj":{'pron-obj': '1', 'copula': '2', 'present_marker_deletion': '4', 'lexical': '6', 'dem_pro': '9', 'gender': '14', 'mar... | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
def _get_artefacts_count_of_bootstrap_nodes(_: pathlib.Path) -> int:
"""Returns number of network bootstrap nodes.
"""
return 3 | bigcode/self-oss-instruct-sc2-concepts |
def pattern(vals: list) -> str:
"""
Return a regex string from a list of values
"""
return f"^({'|'.join(map(str, vals))})$" | bigcode/self-oss-instruct-sc2-concepts |
def isHidden(path_):
"""Hidden files are files which names starts of dot symbol. This method returns True if file is hidden or False otherwise."""
return path_[0] == '.' | bigcode/self-oss-instruct-sc2-concepts |
def to_root_latex(s):
"""
Converts latex expressions in a string *s* to ROOT-compatible latex.
"""
return s.replace("$", "").replace("\\", "#") | bigcode/self-oss-instruct-sc2-concepts |
def _lstrip(source: str, prefix: str) -> str:
""" Strip prefix from source iff the latter starts with the former. """
if source.startswith(prefix):
return source[len(prefix) :]
return source | bigcode/self-oss-instruct-sc2-concepts |
def format_time(function_name, time, nb_iterations, timeout):
"""
Provides a nicely formatted string given a function name, a time of execution
and the number of iterations.
Args:
function_name (str): The name of the function that was executed.
time (float): The time it took for the fun... | bigcode/self-oss-instruct-sc2-concepts |
def _index_keys(columns):
"""
Take all the key columns and build a list of possible index
tuples that can arise from them.
For example, given the following schema: "varId|dbSNP,gene"
these are the possible index key lists:
[['varId', 'gene'],
['dbSNP', 'gene']]
"""
keys = [k.split... | bigcode/self-oss-instruct-sc2-concepts |
def zigzag(n):
"""
Produce a list of indexes that traverse a matrix of size n * n using the JPEG zig-zag order.
Taken from https://rosettacode.org/wiki/Zig-zag_matrix#Alternative_version.2C_Translation_of:_Common_Lisp
:param n: size of square matrix to iterate over
:return: list of indexes in t... | bigcode/self-oss-instruct-sc2-concepts |
def file_to_str(fname):
"""
Read a file into a string
PRE: fname is a small file (to avoid hogging memory and its discontents)
"""
data = None
# rU = read with Universal line terminator
with open(fname, 'rU') as fd:
data = fd.read()
return data | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def is_primitive_type(arg_type: Any) -> bool:
"""Check if the input type is one of `int, float, str, bool`.
Args:
arg_type (typing.Any): input type to check.
Returns:
bool: True if input type is one of `int, float, str, bool`.
"""
try:
return isinst... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_range(r):
"""
Parse an integer sequence such as '0-3,8-11'.
'' is the empty sequence.
"""
if not r.strip():
return []
res = []
for piece in r.strip().split(","):
lr = piece.split("-")
if len(lr) == 1 and lr[0].isdigit():
res.append(int(... | bigcode/self-oss-instruct-sc2-concepts |
def normalize_list_params(params):
"""
Normalizes parameters that could be provided as strings separated by ','.
>>> normalize_list_params(["f1,f2", "f3"])
["f1", "f2", "f3"]
:param params: Params to normalize.
:type params: list
:return: A list of normalized params.
:rtype list
"... | bigcode/self-oss-instruct-sc2-concepts |
def normalize(img, radius=1):
"""
Normalize image to L2 norm of radius
"""
img = img - img.mean(-2, keepdim=True).mean(-1, keepdim=True)
norms = img.pow(2).sum(-2, keepdim=True).sum(-1, keepdim=True).sqrt()
return img / norms * radius | bigcode/self-oss-instruct-sc2-concepts |
def get_rerole_stats(rerole_ops):
"""
Gets a summary of information about the rerole operation.
"""
stats = {'base': {}, 'team':{}}
users = {'base': {}, 'team':{}}
for (user, role_spec) in rerole_ops:
to = role_spec[:2]
per_team = role_spec[2]
if len(per_team):
... | bigcode/self-oss-instruct-sc2-concepts |
def count_params(model, trainable=True):
""" Count number of parameters in pytorch model (optional: only count trainable params)
"""
if not trainable:
return sum(p.numel() for p in model.parameters())
else:
return sum(p.numel() for p in model.parameters() if p.requires_grad) | bigcode/self-oss-instruct-sc2-concepts |
def prepare_params(sort=None, filter=None, params=None):
"""
Prepares the different parameters we want to send as the query in a request
:param sort: str
The sorting (used in list commands issued to the DNSimple API)
:param filter: dict
The filtering (used in list commands issued to the... | bigcode/self-oss-instruct-sc2-concepts |
def is_palindromic_phrase(s):
""" (str) -> bool
Return True iff s is a palindrome, ignoring case and non-alphabetic
characters.
>>> is_palindromic_phrase('Appl05-#$elppa')
True
>>> is_palindromic_phrase('Mada123r')
False
"""
result = ''
for i in range(len(s)):
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_prediction_ids(predictions):
""" Get the label ids from the raw prediction outputs """
tensor = torch.tensor(predictions)
softmax = torch.nn.functional.softmax(tensor, dim=-1)
argmax = torch.argmax(softmax, dim=-1)
return argmax.tolist() | bigcode/self-oss-instruct-sc2-concepts |
def semester(date, *, base=1):
"""
Returns the semester of the given date.
The first semester runs from 1 January to 30 June; the second
from 1 July to 31 December.
Parameters
----------
date : datetime.date
the date from which to determine the semester
base : int, optional
... | bigcode/self-oss-instruct-sc2-concepts |
def jaccard_index_pair_counts(a, b, c):
"""
Compute the Jaccard index from pair counts; helper function.
Arguments:
a: number of pairs of elements that are clustered in both partitions
b: number of pairs of elements that are clustered in first but not second partition
c: number of pairs of elem... | bigcode/self-oss-instruct-sc2-concepts |
def create_lookup(stream, derived_fields, index_field):
"""
Build a lookup table from an indexed field to a set of derived fields.
Ensures that there is a unique relation, raises assertion if violated
:param stream: stream of records
:param derived_fields: list of derived fields assumed to be a func... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def fill_histogram(histograms, indices, hist_idx, normalize=True):
"""
Compute a histogram and fill in the designated entry in the array histograms.
:param histograms: Array that will contains histograms.
:param indices: Array with values from which a histogram should be co... | bigcode/self-oss-instruct-sc2-concepts |
def isKtServerRunning(logPath):
"""Check if the server started running."""
success = False
with open(logPath) as f:
for line in f:
if line.lower().find("listening") >= 0:
success = True
return success | bigcode/self-oss-instruct-sc2-concepts |
def split_numal(val):
"""Split, for example, '1a' into (1, 'a')
>>> split_numal("11a")
(11, 'a')
>>> split_numal("99")
(99, '')
>>> split_numal("a")
(0, 'a')
>>> split_numal("")
(0, '')
"""
if not val:
return 0, ''
for i in range(len(val)):
if not val[i].isdigit():
return int... | bigcode/self-oss-instruct-sc2-concepts |
import math
def hm(hours):
"""Convert hours to hour-minute
If hours is negative, only hour of the tuple is negative.
"""
if math.isinf(hours):
return None
minutes = int(math.ceil(hours * 60))
h, minutes = divmod(minutes, 60)
return (h, minutes) | bigcode/self-oss-instruct-sc2-concepts |
def is_nfs_have_host_with_host_obj(nfs_details):
""" Check whether nfs host is already added using host obj
:param nfs_details: nfs details
:return: True if nfs have host already added with host obj else False
:rtype: bool
"""
host_obj_params = ('no_access_hosts', 'read_only_hosts',
... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def pathlen(path):
"""Return folder level of the path string"""
return len(Path(path).parts) | bigcode/self-oss-instruct-sc2-concepts |
import re
def normalize_timestamp(ts):
"""Normalize a timestamp
For easier comparison
"""
if ts is None:
return
return re.sub(r'\d(\.\d+)?', '0', ts) | bigcode/self-oss-instruct-sc2-concepts |
def esval(es, tlist):
"""
Evaluates an exponential series at the times listed in ``tlist``.
Parameters
----------
tlist : ndarray
Times at which to evaluate exponential series.
Returns
-------
val_list : ndarray
Values of exponential at times in ``tlist``.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def google_fixed_width_font(style):
"""check if the css of the current element defines a fixed width font"""
font_family = ''
if 'font-family' in style:
font_family = style['font-family']
if 'Courier New' == font_family or 'Consolas' == font_family:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import math
def avg(current, previous, bpp):
"""
To compute the Average filter, apply the following formula to each
byte of the scanline:
Average(x) = Raw(x) - floor((Raw(x-bpp)+Prior(x))/2)
:param current: byte array representing current scanline.
:param previous: byte array representing th... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
def flatten_list_dict(lst: List[Dict[str, list]]) -> Dict[str, list]:
"""Flatten list of dicts to dict of lists
Parameters
----------
lst : List[Dict[str, list]]
list of dicts of lists
Returns
-------
Dict[str, list]
"""
ret... | bigcode/self-oss-instruct-sc2-concepts |
def evaluate_f1(tp: int, fp: int, fn: int) -> float:
"""F1-score.
*F1-score* $=\dfrac{2TP}{2TP + FP + FN}$
Args:
tp: True Positives
fp: False Positives
fn: False Negatives
"""
try:
return 2 * tp / (2 * tp + fp + fn)
except ZeroDivisionError:
return 0.0 | bigcode/self-oss-instruct-sc2-concepts |
import re
def FindProperties(data):
"""Finds extra properties for a file.
Finds strings of the form '@PROPS[name name name]'.
Args:
data: The contents of the file being checked.
Returns:
A list of properties from the PROPS line in the file.
"""
match = re.search(r'@PROPS\[([^\]]*)\]', data)
if... | bigcode/self-oss-instruct-sc2-concepts |
def construct_version_string(major, minor, micro, dev=None):
"""
Construct version tag: "major.minor.micro" (or if 'dev' is specified: "major.minor.micro-dev").
"""
version_tag = f"{major}.{minor}.{micro}"
if dev is not None:
version_tag += f"-{dev}"
return version_tag | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_valid_positive_mask(labels):
"""
To be a valid positive pair (a,p),
- a and p are different embeddings
- a and p have the same label
"""
indices_equal = torch.eye(labels.size(0)).byte()
indices_not_equal = ~indices_equal
label_equal = torch.eq(labels.unsqueeze(1), labels.unsqueeze(0))... | bigcode/self-oss-instruct-sc2-concepts |
def get_slicing_config(config):
"""Util function that generates config for visualization.
Args:
config: EvalConfig that contains example_weight_metric_key.
Returns:
A dictionary containing configuration of the slicing metrics evalaution.
"""
return {'weightedExamplesColumn': config.example_weight_me... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Optional
def sort_categories_key(category: str) -> Tuple[str, Optional[str], Optional[int]]:
"""A function which may be used as the key when sorting a list of categories.
This function assumes categories are based on chemical environments and
compositions (up to... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def get_month_options(year):
"""
Get the month options for the given year.
For the previous year, there is data available for each individual month.
However, for previous years only the aggregate statistics is available.
Parameters:
year: (int): The year for... | bigcode/self-oss-instruct-sc2-concepts |
def binomial_coefficient_faster(n, r):
"""
A faster way to calculate binomial coefficients
>>> binomial_coefficient_faster(10,5)
252
"""
if 0 <= r <= n:
#initializing two variables as 1
ntok = 1
rtok = 1
#we use the formula nCr = n!/(n-r)!r!
for t in ran... | bigcode/self-oss-instruct-sc2-concepts |
import math
def get_utm_zone_epsg(lon: float, lat: float) -> int:
"""
Calculates the suitable UTM crs epsg code for an input geometry point.
Args:
lon: Longitude of point
lat: Latitude of point
Returns:
EPSG code i.e. 32658
"""
zone_number = int((math.floor((lon + 180... | bigcode/self-oss-instruct-sc2-concepts |
def getY(line, x):
"""
Get a y coordinate for a line
"""
m, c = line
y = int((m * x) + c)
return y | bigcode/self-oss-instruct-sc2-concepts |
def get(a, i):
"""Retrieve the i-th element or return None"""
return a[i] if len(a) > i else None | bigcode/self-oss-instruct-sc2-concepts |
import torch
def GetLinear(w):
"""
Return the weights and bias of the Linear module 'w' as a flattened numpy array.
"""
return torch.cat([w.weight.data.flatten(), w.bias.data.flatten()],0).numpy() | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_signature(source, start):
"""
Get function signature and process it
"""
match = re.search(r'c?p?def.+\(', source[start].strip())
if not match:
return
start_j = match.span()[1]
open_brackets = 1
new_sign = match.group()
for i in range(start, len(source)):
... | bigcode/self-oss-instruct-sc2-concepts |
def adjust_detector_position(final_detector_length,
requested_distance_to_tls,
lane_length):
""" Adjusts the detector's position. If the detector's length
and the requested distance to TLS together are longer than
the lane itself, the positio... | bigcode/self-oss-instruct-sc2-concepts |
def interpolatePercentCover(percentDatePrev, percentDateAfter, percentCoverPrev, percentCoverAfter, cutDate):
"""
inputs: percentDatePrev - date obj - date prior to cut date that recorded the percent cover
percentDateAfter - date obj - date after the cut date that recorded the percent cover
... | bigcode/self-oss-instruct-sc2-concepts |
def filter_by_lines(units, lines):
"""Filter units by line(s)."""
return [i for i in units if i.line in lines] | bigcode/self-oss-instruct-sc2-concepts |
def lower_case(s: str) -> str:
"""Transforms an input string into its lower case version.
Args:
s: Input string.
Returns:
(str): Lower case of 's'.
"""
return s.lower() | bigcode/self-oss-instruct-sc2-concepts |
def read_text(filename):
"""
filename: string, name of file to read
Returns a string containing all file contents
"""
in_file = open(filename, 'r')
line = in_file.read()
return line | bigcode/self-oss-instruct-sc2-concepts |
def open_input(input_path: str) -> list[str]:
"""Opens and sanitizes the `input.txt` file for the day reading in each line as an element of a list.
- Remove any extra lines at the end of the input files (if present, due to auto-formatting)
- Remove newline characters for individual element strings
- St... | bigcode/self-oss-instruct-sc2-concepts |
import re
def match_pattern(pattern, value):
"""
Helper function to carry out pattern matching
"""
patt = re.compile(pattern)
match = patt.match(value)
return match is not None | bigcode/self-oss-instruct-sc2-concepts |
def match_id(dis_id):
"""Match a discord id depending on mention or raw ID"""
# ID is user mention or role mention
if any(x in dis_id for x in ["<@!", "<@&"]):
if len(dis_id) == 22:
return int(dis_id[3:-1])
# Simple mention
elif "<@" in dis_id:
if len(dis_id) == 21:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import TextIO
from typing import Dict
from typing import OrderedDict
import yaml
def yaml_load(stream: TextIO) -> Dict[str, str]:
"""
Load a yaml from a file pointer in an ordered way.
:param stream: the file pointer
:return: the yaml
"""
# for pydocstyle
def ordered_load(stre... | bigcode/self-oss-instruct-sc2-concepts |
def BoringCallers(mangled, use_re_wildcards):
"""Return a list of 'boring' function names (optinally mangled)
with */? wildcards (optionally .*/.).
Boring = we drop off the bottom of stack traces below such functions.
"""
need_mangling = [
# Don't show our testing framework:
("testing::Test::Run", ... | bigcode/self-oss-instruct-sc2-concepts |
def get_completed_only(mxml_df):
"""
Filter only completed activities
"""
complete = mxml_df[mxml_df.EventType == "complete"].rename({
"Timestamp": "Timestamp_Complete"
}, axis=1).set_index(["TraceId", "WorkflowModelElement"])
return complete.drop(["Originator", "EventType"], e... | bigcode/self-oss-instruct-sc2-concepts |
import random
def max_vote(votes):
"""Manual bilding of counts and selection randomly the max vote (count) in the case of a tie."""
counts = {}
for vote in votes:
if vote in counts.keys():
counts[vote] += 1
else:
counts[vote] = 1
# print(counts)
# Building t... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import requests
def api_call(method: str, endpoint: str, payload: Any = None):
"""Runs an API call to Transact API
Args:
method (str): HTTP method
endpoint (str): url endpoint (see documentation)
payload (Dict[str, Union[str, int, float]], optional): Data payloa... | bigcode/self-oss-instruct-sc2-concepts |
def remove_file_prefix(file_path, prefix):
"""
Remove a file path prefix from a give path. leftover
directory separators at the beginning of a file
after the removal are also stripped.
Example:
'/remove/this/path/file.c'
with a prefix of:
'/remove/this/path'
becomes:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Optional
from typing import List
from typing import Any
import json
def concatenate_json_lists(input_files: Iterable[str],
output_file: Optional[str] = None
) -> List[Any]:
"""
Given a list of JSON files that ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def bands_union(*args: List[str]) -> List[str]:
"""Take union of given lists/sets of bands"""
bands = []
for arg in args:
for a in arg:
if a not in bands:
bands.append(a)
return bands | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import importlib
def _get_optional_dependency_version(import_path: str) -> Optional[str]:
"""Attempts to retrieve the version of an optional dependency
Args:
import_path: The import path of the dependency.
Returns:
The version of the dependency if it can be im... | bigcode/self-oss-instruct-sc2-concepts |
def find_weather_emoji(weather_icon):
""" Given the `icon` description, finds a suitable emoji to represent weather
conditions, and returns it. Currently accepted values (more may be defined in
the future): clear-day, clear-night, rain, snow, sleet, wind, fog, cloudy,
partly-cloudy-day, partly-cloudy-ni... | bigcode/self-oss-instruct-sc2-concepts |
import six
def urlpathjoin(*parts):
"""Join multiple paths into a single url
>>> urlpathjoin('https://storage.scrapinghub.com:8002/', 'jobs', '1/2/3')
'https://storage.scrapinghub.com:8002/jobs/1/2/3'
>>> urlpathjoin('https://storage.scrapinghub.com:8002', 'jobs', '1/2/3', None)
'https://storage.... | bigcode/self-oss-instruct-sc2-concepts |
def subtree_leaf_positions(subtree):
"""Return tree positions of all leaves of a subtree."""
relative_leaf_positions = subtree.treepositions('leaves')
subtree_root_pos = subtree.treeposition()
absolute_leaf_positions = []
for rel_leaf_pos in relative_leaf_positions:
absolute_leaf_positions.a... | bigcode/self-oss-instruct-sc2-concepts |
def _get_file_as_string(path):
"""Get the contents of the file as a string."""
with open(path, 'r') as f:
data = f.read()
return data | bigcode/self-oss-instruct-sc2-concepts |
def get_transceiver_description(sfp_type, if_alias):
"""
:param sfp_type: SFP type of transceiver
:param if_alias: Port alias name
:return: Transceiver decsription
"""
if not if_alias:
description = "{}".format(sfp_type)
else:
description = "{} for {}".format(sfp_type, if_ali... | bigcode/self-oss-instruct-sc2-concepts |
def seq_2_features(seq, indices):
"""converts a single sequence to a list of features
based on indices
"""
result = []
for idxs in indices:
feature = ''.join([seq[i] for i in idxs])
result.append(feature)
return result | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
from typing import Iterable
def is_covered(path: pathlib.Path, sources: Iterable[pathlib.Path]) -> bool:
"""
Checks if `path` is contained in any of the subdirectories in sources.
See the test cases for details.
"""
path = path.resolve()
abs_path = [source.resolve() for source i... | bigcode/self-oss-instruct-sc2-concepts |
def solve(captcha):
"""Solve captcha.
:input: captcha string
:return: sum of all paired digits that match
>>> solve('1212')
6
>>> solve('1221')
0
>>> solve('123425')
4
>>> solve('123123')
12
>>> solve('12131415')
4
"""
a = len(captcha) // 2
return sum(i... | bigcode/self-oss-instruct-sc2-concepts |
import math
def theil_l_index(distribution):
"""Theil's L Index is sensitive to differences at the lower end of the
distribution (small incomes).
Args:
distribution (list): wealth distribution of the population
Returns:
(float): Theil's L Index (TL), inequality of wealth distribution... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def require_privmsg(message=None):
"""Decorate a function to only be triggerable from a private message.
If it is triggered in a channel message, `message` will be said if given.
"""
def actual_decorator(function):
@functools.wraps(function)
def _nop(*args, **kwargs):... | bigcode/self-oss-instruct-sc2-concepts |
def to_yy(year):
"""Returns the last 2 digits of the year."""
return str(year % 100).zfill(2) | 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.