seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import re
def replacenth(string, sub, wanted, n):
"""Replace nth word in a sentence
string: Complete string
sub: Substring to be replaced
wanted: Replace by wanted
n: index of the occurence of sub to be replaced
"""
where = [m.start() for m in re.finditer(sub, string)][n-1]
before... | bigcode/self-oss-instruct-sc2-concepts |
def _SNR(coef):
"""
Return the signal-to-noise ratio for each constituent.
"""
if "Lsmaj" in coef:
SNR = (coef["Lsmaj"] ** 2 + coef["Lsmin"] ** 2) / (
(coef["Lsmaj_ci"] / 1.96) ** 2 + (coef["Lsmin_ci"] / 1.96) ** 2
)
else:
SNR = (coef["A"] ** 2) / (coef["A_ci"] / ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
import re
def is_valid_sentence(str):
"""
Check if a sentence is valid:
- Does not contain mismatched brackets
- Does not start with 'and' or 'but'
- Ends with a punctuation [.?!]
- Has a minimum length of 5
"""
start_pattern = r"^\"*[A-Z]+"
end_pattern ... | bigcode/self-oss-instruct-sc2-concepts |
def prepend(base, prefix):
"""Prepend a prefix to a string"""
return f"{prefix}{base}" | bigcode/self-oss-instruct-sc2-concepts |
def point_touches_rectangle(point, rect):
"""Returns ``True`` (``1``) if the point is in the rectangle
or touches it's boundary, otherwise ``False`` (``0``).
Parameters
----------
point : {libpysal.cg.Point, tuple}
A point or point coordinates.
rect : libpysal.cg.Rectangle
A rec... | bigcode/self-oss-instruct-sc2-concepts |
import glob
def get_photos(folder_path, pics_extension):
"""Function create a list of photos from given folder"""
pics_path = folder_path + "/*." + pics_extension
return glob.glob(pics_path) | bigcode/self-oss-instruct-sc2-concepts |
def _full_index(sample_id_col):
"""Return all columns necessary to uniquely specify a junction"""
return [sample_id_col, 'chrom', 'intron_start', 'intron_stop', 'strand'] | bigcode/self-oss-instruct-sc2-concepts |
def chain(*args):
"""Applies a list of chainable update transformations.
Given a sequence of chainable transforms, `chain` returns an `init_fn`
that constructs a `state` by concatenating the states of the individual
transforms, and returns an `update_fn` which chains the update transformations
feeding the ap... | bigcode/self-oss-instruct-sc2-concepts |
def _solve_method_3(arr):
"""
https://github.com/JaredLGillespie/HackerRank/blob/master/Python/minimum-swaps-2.py
Couldn't really figure it out via my method, but I found this solution that
was very small and I understand.
One thing I did was factor out a portion of it into a function call, for
... | bigcode/self-oss-instruct-sc2-concepts |
def _calculate_build_timeout(features):
"""Return maximum allowed time for build (in seconds)."""
timeout = 60
if 'mysql' in features:
timeout += 60
timeout *= 60
return timeout | bigcode/self-oss-instruct-sc2-concepts |
import io
def trim_spaces_and_tabs_from_lines_in_txt(txt: str) -> str:
""" This function will remove leading spaces and tabs from lines of text.
:param txt: a str containing the text to be cleaned up.
:return: a str containing text with all of the leading spaces removed from each line.
"""
clean... | bigcode/self-oss-instruct-sc2-concepts |
from operator import add
def vadd(V1,V2):
""" add the components of 2 vectors
<div class=jython>
VADD (V1, V2) = [ u1+u2, v1+v2 ]
</div>
"""
return add(V1,V2) | bigcode/self-oss-instruct-sc2-concepts |
def log_mean_exp(ops, x, axis=None, keepdims=False):
"""
Compute :math:`\\log \\frac{1}{K} \\sum_{k=1}^K \\exp(x_k)`.
.. math::
\\begin{align*}
\\log \\frac{1}{K} \\sum_{k=1}^K \\exp(x_k)
&= \\log \\left[\\exp(x_{max}) \\frac{1}{K}
\\sum_{k=1}^K \\ex... | bigcode/self-oss-instruct-sc2-concepts |
def _use_and_del(d, k, v):
"""
Use a values from a dict and remove it.
"""
if k in d:
v = d[k]
del d[k]
return v | bigcode/self-oss-instruct-sc2-concepts |
import re
def canonical(value):
"""Replace anything but 'a-z', 'A-Z' and '0-9' with '_'.
"""
return re.sub(r'[^a-zA-Z0-9]', '_', value) | bigcode/self-oss-instruct-sc2-concepts |
def channel_shuffle(x, groups):
"""shuffle channels of a 4-D Tensor"""
batch_size, channels, height, width = x.size()
assert channels % groups == 0
channels_per_group = channels // groups
# split into groups
x = x.view(batch_size, groups, channels_per_group, height, width)
# transpose 1, 2 a... | bigcode/self-oss-instruct-sc2-concepts |
import re
def language(text, wtl):
"""Return language from given text and using the provided language classifier and regex"""
words = [
"recomendo", "amei", "entrega", "otim[ao]", "excelente", "rapida", "celular", "gostei",
"facil", "lindo", "bonito", "comprei", "legal", "perfume", "preco", "... | bigcode/self-oss-instruct-sc2-concepts |
import json
def readParams(control_file):
"""Reads a JSON control file for the paramaters.
List of parameters:
trajectoryFolder : string, folder where the trajectory data is
trajectoryBasename : string, names of the trajectory files is
numClusters : int, number of clusters to partition... | bigcode/self-oss-instruct-sc2-concepts |
def operatingexpenses(taxes, insurance, pmi, managementfee, hoafee):
"""Annual expenses occured through normal cost of business.
:param taxes: Annual taxes.
:type taxes: double
:param insurance: Annual insurance.
:type insurance: double
:param pmi: Annual pmi payment.
:type pmi: double
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
import json
def parse_json(path: str) -> Dict[str, Any]:
"""
Parse a json file.
Args:
path (str): Json file path.
Returns:
Dict: Dictionary of parsed data.
"""
with open(path, "r") as stream:
return json.load(stream) | bigcode/self-oss-instruct-sc2-concepts |
import base64
import six
def UrlSafeB64Encode(message):
"""wrapper of base64.urlsafe_b64encode.
Helper method to avoid calling six multiple times for preparing b64 strings.
Args:
message: string or binary to encode
Returns:
encoded data in string format.
"""
data = base64.urlsafe_b64encode(six.e... | bigcode/self-oss-instruct-sc2-concepts |
def mmcc(ds, xs, ys):
"""Fit a straight line
(x, y) = (mx, my) * d + (cx, cy)
to ordinates x, y in xs, ys as a function of d in ds."""
assert len(ds) == len(xs)
assert len(ds) == len(ys)
ds = [float(i) for i in ds]
xs = [float(i) for i in xs]
ys = [float(i) for i in ys]
_d = su... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def ego_coordinate_to_world_coordinate(
egocentric_x: float,
egocentric_y: float,
current_location_x: float,
current_location_y: float,
current_forward_x: float,
current_forward_y: float,
) -> Tuple[float, float]:
"""
:param location_x: The x-component of an eg... | bigcode/self-oss-instruct-sc2-concepts |
def _unique_list(df_col):
"""Return a list of unique values without NA."""
return list(df_col.unique().dropna()) | bigcode/self-oss-instruct-sc2-concepts |
def normalize(text: str) -> str:
"""Remove whitespace, lowercase, convert spaces to underscores"""
return text.strip().lower().replace(' ', '_') | bigcode/self-oss-instruct-sc2-concepts |
def unique_slug(manager, slug_field, slug):
"""
Ensure slug is unique for the given manager, appending a digit
if it isn't.
"""
i = 0
while True:
if i > 0:
if i > 1:
slug = slug.rsplit("-", 1)[0]
slug = "%s-%s" % (slug, i)
if not manager.fi... | bigcode/self-oss-instruct-sc2-concepts |
def AddAuthFieldMask(unused_ref, args, request):
"""Adds auth-specific fieldmask entries."""
if args.auth_type is None: # Not set, not the 'none' choice
return request
if request.updateMask:
request.updateMask += ',authentication'
else:
request.updateMask = 'authentication'
return request | bigcode/self-oss-instruct-sc2-concepts |
def _flip_masks_up_down(masks):
"""Up-down flip masks.
Args:
masks: rank 3 float32 tensor with shape
[num_instances, height, width] representing instance masks.
Returns:
flipped masks: rank 3 float32 tensor with shape
[num_instances, height, width] representing instance masks.
"""
return... | bigcode/self-oss-instruct-sc2-concepts |
import re
def tamper(payload, **kwargs):
"""
Replaces greater than operator ('>') with 'NOT BETWEEN 0 AND #' and equals operator ('=') with 'BETWEEN # AND #'
Tested against:
* Microsoft SQL Server 2005
* MySQL 4, 5.0 and 5.5
* Oracle 10g
* PostgreSQL 8.3, 8.4, 9.0
Not... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import json
def read_geometries(file_geometries: str) -> List[str]:
"""Read a list of geometries."""
with open(file_geometries, 'r') as f:
data = json.load(f)
return data | bigcode/self-oss-instruct-sc2-concepts |
def extract_annealing_log(log):
"""
Parses a VPR log line by line. Extracts the table with simulated annealing
data. Returns the table header and data line lists as separate.
"""
# Find a line starting with "# Placement"
for i, line in enumerate(log):
if line.startswith("# Placement"):
... | bigcode/self-oss-instruct-sc2-concepts |
def get_subscribed_reports_addresses(location_reports): # workds
"""returns list of string addresses for given LocationReports"""
addresses = []
for lr in location_reports:
addresses.append(lr.address)
return addresses | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def wordle_judge(input_word: str, answer_word: str)-> int:
"""
Judge input word based on the wordle rule
We assume input_word and answer_word are of the same length (but no check is conducted)
Judge results are defined as a sequence of {0, 1, 2}, where
2: exact, ... | bigcode/self-oss-instruct-sc2-concepts |
def is_list_match(item, value):
"""Check if a item match a value or
(if it is a list) if it contains only one item and the item matches the value
"""
if isinstance(item, list):
if len(item) == 1 and item[0] == value:
return True
else:
return False
else:
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def collatz(number: int) -> List[int]:
"""Проверка гипотезы Коллатца
Подробнее:
https://en.wikipedia.org/wiki/Collatz_conjecture
Параметры:
:param number: число для которого проверяется гипотеза
:type number: int
:return: Сипсок чисел, соответствующих шагам п... | bigcode/self-oss-instruct-sc2-concepts |
def choose_unit_from_multiple_time_units_series(time_serie, time_key="seconds"):
"""Given a time series in the form
[(x, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0}),
(y, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0}),
(z, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def read_lines_from_file(path: str, strip: bool = False) -> List[str]:
"""Read file into stripped lines."""
with open(path, "r") as f:
lines = f.readlines()
if not strip:
return lines
return list([line.strip() for line in lines]) | bigcode/self-oss-instruct-sc2-concepts |
def read_hc_tape(file_path, order=2):
"""
read_hc_tape :Read Hilbert Curve command from the table
Read Hilbert Curve command from the table in this package.
The command including these English alphabet {'o', 'u', 'd', 'l', 'r'}
:param file_path: a path of HC table
:type file_path: string
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def from_flattened_numpy(x, shape):
"""Form a torch tensor with the given `shape` from a flattened numpy array `x`."""
return torch.from_numpy(x.reshape(shape)) | bigcode/self-oss-instruct-sc2-concepts |
def create_bit_mask(data_array, valid_bits, no_data=-9999):
"""Create a boolean bit mask from a list of valid bits
Args:
data_array: xarray data array to extract bit information for.
valid_bits: array of ints representing what bits should be considered valid.
no_data: no_data value for ... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_len_get(headers):
"""
# Desc : Function to calculate total length of data received for a get request.
# Calculated as sum of header length and the content length
# Input : Header from a get request
# Output: Returns the total length of data received
"""
sock_header_len = 0
sock_c... | bigcode/self-oss-instruct-sc2-concepts |
def get_samples_panfamilies(families, sample2family2presence):
"""Get the sorted list of all the families present in the samples
Can be a subset of the pangenome's set of families"""
panfamilies = set()
for f in families:
for s in sample2family2presence:
if sample2family2presence[s][... | bigcode/self-oss-instruct-sc2-concepts |
def parse_rank_score(rank_score_entry, case_id):
"""Parse the rank score
Args:
rank_score_entry(str): The raw rank score entry
case_id(str)
Returns:
rank_score(float)
"""
rank_score = None
if rank_score_entry:
for family_info in rank_score_entry.split(","):
... | bigcode/self-oss-instruct-sc2-concepts |
def str2bool(s):
"""Convert string to bool for argparse"""
if isinstance(s, bool):
return s
values = {
"true": True,
"t": True,
"yes": True,
"y": True,
"false": False,
"f": False,
"no": False,
"n": False,
}
if s.lower() not in ... | bigcode/self-oss-instruct-sc2-concepts |
def classify(model, filepath):
""" return a dictionary formatted as follows:
{
'predicted y': <'2016' or '2020'>,
'log p(y=2016|x)': <log probability of 2016 label for the document>,
'log p(y=2020|x)': <log probability of 2020 label for the document>
... | bigcode/self-oss-instruct-sc2-concepts |
def unique_paths_with_obstacles(obstacle_grid: list[list[int]]) -> int:
"""
>>> print(unique_paths_with_obstacles([[0,0,0],[0,1,0],[0,0,0]]))
2
>>> print(unique_paths_with_obstacles([[0,1],[0,0]]))
1
>>> print(unique_paths_with_obstacles([[0,1,0],[0,0,0],[0,0,1]]))
0
"""
# If the ob... | bigcode/self-oss-instruct-sc2-concepts |
def get_parameter_value(parameters, parameter_name, value_key='value'):
"""Returns the parameter value.
:param parameters: parameter list
:param parameter_name: parameter name
:param value_key: parameter key containing the value
:rtype : str
"""
for item in parameters:
if item['name... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
import six
import re
def expand_docstring(**kwargs):
"""Decorator to programmatically expand the docstring.
Args:
**kwargs: Keyword arguments to set. For each key-value pair `k` and `v`,
the key is found as `${k}` in the docstring and replaced with `v`.
Returns:
Decorated function... | bigcode/self-oss-instruct-sc2-concepts |
def unique_vals(rows, column_number):
"""Find the unique values from a column in a dataset based on column number"""
return set([row[column_number] for row in rows]) | bigcode/self-oss-instruct-sc2-concepts |
def collapse_repeats(sequence):
"""Collapse repeats from sequence to be used for PER"""
result = []
prev = None
for x in sequence:
if x == prev:
continue
result.append(x)
prev = x
return result | bigcode/self-oss-instruct-sc2-concepts |
def _load_data_spacy(data_path, inc_outside=True):
"""
Load data in Spacy format:
X = list of sentences (plural) / documents ['the cat ...', 'some dog...', ...]
Y = list of list of entity tags for each sentence
[[{'start': 36, 'end': 46, 'label': 'PERSON'}, {..}, ..], ... ]
inc_outside = Fal... | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_trajectory(ext):
""" Checks if trajectory format is compatible with GROMACS """
formats = ['xtc', 'trr', 'cpt', 'gro', 'g96', 'pdb', 'tng']
return ext in formats | bigcode/self-oss-instruct-sc2-concepts |
def is_hilbert_number(n):
"""
Simply check whether n is positive and the remainder of n is equal to 1
modulus 4.
"""
return n > 0 and n % 4 == 1 | bigcode/self-oss-instruct-sc2-concepts |
def string_to_list_only_digit(word):
"""
Take each character of the 'word' parameter and return a list
populated with all the characters. The if clause allows only
the digits to be added to the list.
:param word: string
:return: list of digit inside 'word'
"""
return [c for c in word if ... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_beam_dim(x):
"""Flattens the first two dimensions of a non-scalar array."""
if x.ndim == 0: # ignore scalars (e.g. cache index)
return x
return x.reshape((x.shape[0] * x.shape[1],) + x.shape[2:]) | bigcode/self-oss-instruct-sc2-concepts |
def calendars_config_track() -> bool:
"""Fixture that determines the 'track' setting in yaml config."""
return True | bigcode/self-oss-instruct-sc2-concepts |
def verificar_arquivo(nome_arquivo='passwords'):
"""Verifica se o arquivo que conterá as senhas já existe.
Keyword Arguments:
nome_arquivo {str} -- (default: {'passwords'})
Returns:
[bool] -- [Se já existir recebe True, senão recebe False]
"""
try:
arquivo = open(n... | bigcode/self-oss-instruct-sc2-concepts |
def get_fields_with_datatype(
dataset_ids: list, field_info: dict, data_format: str
) -> dict:
"""
Returns the column name and its data type by looking up stream and log_fields json file.
If a mapping column name is not present in log_fields.json it returns
the column name as `col<idx>` and its dat... | bigcode/self-oss-instruct-sc2-concepts |
def pRDP_asymp_subsampled_gaussian_best_case(params, alpha):
"""
:param params:
:param alpha: The order of the Renyi Divergence
:return: Evaluation of the pRDP's epsilon
See Example 20 of Wang, Balle, Kasiviswanathan (2018)
"""
sigma = params['sigma']
prob = params['prob']
n = param... | bigcode/self-oss-instruct-sc2-concepts |
import string
def make_title(line):
"""
Edits the given line so that it can be used as a title.
Edit operations include removing unnecessary punctuations and converting the text into title case
:param line: line of the poem chosen as the title
:return: title of the poem
"""
# Removing pun... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def filter_min(counter: Counter, min_freq: int):
""" Filter counter by min frequency """
return Counter({t: c for t, c in counter.items() if c >= min_freq}) | bigcode/self-oss-instruct-sc2-concepts |
def stack_map(topology):
"""Return dict mapping node ID to stack type
Parameters
----------
topology : Topology
The topology
Returns
-------
stack_map : dict
Dict mapping node to stack. Options are:
source | receiver | router | cache
"""
stack = {}
for v... | bigcode/self-oss-instruct-sc2-concepts |
def add(I1, I2):
"""Calculate the addition of two intervals as another interval
Keyword arguments:
I1 -- the first interval given as a tuple (a, b)
I2 -- the second interval given as a tuple (c, d)
"""
(from1, to1) = I1
(from2, to2) = I2
return (from1 + from2, to1 + to2) | bigcode/self-oss-instruct-sc2-concepts |
def _is_lt_position(first: tuple, second: tuple, position):
"""Compare the tuple at given position."""
if len(first) > position and first[position] is not None:
if len(second) > position and second[position] is not None:
return first[position] < second[position]
return False # canno... | bigcode/self-oss-instruct-sc2-concepts |
def mk_time_info_extractor(spec):
"""
Returns a function that will extract information from timestamps in a dict format.
The specification should be a list of timetuple attributes
(see https://docs.python.org/2/library/time.html#time.struct_time) to extract,
or a {k: v, ...} dict where v are the tim... | bigcode/self-oss-instruct-sc2-concepts |
def validate(identifier):
"""Validates a student id from the Pontifical Catholic University of Chile
Args:
identifier: student identifier (string or number)
Returns:
True if it is valid, False otherwise
"""
if not identifier:
return False
identifier = str(identifier)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_unique_notes_in_channel(notes_in_channel):
""" Utility function to get an ordered set of unique notes in the channel """
all_notes = []
for notes in notes_in_channel:
all_notes.append(notes.note)
return sorted(set(all_notes)) | bigcode/self-oss-instruct-sc2-concepts |
def get_whitespace_cnt(line):
""" Return a count of leading tabs/spaces as (tab_cnt, space_cnt). """
tab_cnt = 0
space_cnt = 0
testline = line
while testline.startswith('\t'):
tab_cnt += 1
testline = testline[1:]
testline = line
while testline.startswith(' '):
space_c... | bigcode/self-oss-instruct-sc2-concepts |
import re
def argv_to_pairs(argv):
"""Convert a argv list to key value pairs. For example,
-x 10 -y 20 -z=100
{x: 10, y: 20, z: 100}
"""
arg_dict = {}
i = 0
while i < len(argv):
if argv[i].startswith('-'):
entry = re.sub('-+', '', argv[i])
items = entry.s... | bigcode/self-oss-instruct-sc2-concepts |
def _pixel_distance(a_x1, a_x2, b_x1, b_x2):
"""Calculates the pixel distance between bounding box a and b.
Args:
a_x1: The x1 coordinate of box a.
a_x2: The x2 coordinate of box a.
b_x1: The x1 coordinate of box b.
b_x2: The x2 coordinate of box b.
Returns:
The pixel distanc... | bigcode/self-oss-instruct-sc2-concepts |
def extract_function_from_command(command):
"""
Extracts and returns the function used in the current command.
for example: `lc.ln(a,52)` -> ln
:return: function name
"""
function_name = command.split(".")[1]
end_index = function_name.index("(")
function_name = function_name[:end_index]... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def _partition_satellite_input(
line: Tuple[str, str],
num_partitions: int = 2) -> int: # pylint: disable=unused-argument
"""Partitions Satellite input into tags (0) and rows (1).
Args:
line: an input line Tuple[filename, line_content]
num_partitions: number of partition... | bigcode/self-oss-instruct-sc2-concepts |
def cleanup_vm_data(vm_data, uuids):
""" Remove records for the VMs that are not in the list of UUIDs.
:param vm_data: A map of VM UUIDs to some data.
:type vm_data: dict(str: *)
:param uuids: A list of VM UUIDs.
:type uuids: list(str)
:return: The cleaned up map of VM UUIDs to data.
:... | bigcode/self-oss-instruct-sc2-concepts |
def extract_solution(G, model):
""" Get a list of vertices comprising a maximal clique
:param G: a weighted :py:class:`~graphilp.imports.ilpgraph.ILPGraph`
:param model: a solved Gurobi model for maximum clique
:return: a list of vertices comprising a maximal clique
"""
clique_node... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_horizontal_flip(image, bboxes):
"""
Randomly horizontal flip the image and correct the box
:param image: BGR image data shape is [height, width, channel]
:param bboxes: bounding box shape is [num, 4]
:return: result
"""
if random.random() < 0.5:
_, w, _ = i... | bigcode/self-oss-instruct-sc2-concepts |
def make_graph(values, lower_limit=0.0, upper_limit=100.0, style="blocks"):
"""
Draws a graph made of unicode characters.
:param values: An array of values to graph.
:param lower_limit: Minimum value for the y axis (or None for dynamic).
:param upper_limit: Maximum value for the y axis (or None for... | bigcode/self-oss-instruct-sc2-concepts |
def do_two(Sol=341.0, epsilon=0.55, albedo=0.3):
"""
Calculate equlibrium fluxes for a two-layer atmosphere
Parameters
----------
Sol: float
day/night averaged TOA shortwave flux (W/m^2)
epsilon: float
longwave emissivity of layers 1 and 2
albedo: float
... | bigcode/self-oss-instruct-sc2-concepts |
def intersect_ray_plane(o,w,p,n):
"""[Compute the intersection point between a ray and a plane]
Args:
o ([ndarray]): [ray origin]
w ([ndarray]): [ray direction]
p ([ndarray]): [plane origin]
n ([ndarray]): [plane normal vector]
Returns:
[ndarray]: [intersection point... | bigcode/self-oss-instruct-sc2-concepts |
def widget_generator(klass, fields):
"""
Takes in a class and a list of tuples consisting of field_name and an attribute dictionary
:param klass: Class of the input widget
:param fields: List of tuples mapping field names to attribute dictionaries
:return: A dict of input widget instances
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def cap_allele(allele, cap=5):
""" Cap the length of an allele in the figures """
if len(allele) > cap:
allele = allele[:cap] + '*'
return allele | bigcode/self-oss-instruct-sc2-concepts |
def rhs_replace(rhs, sublist, replacement):
"""Replace occurrences of sublist in rhs with replacement."""
sublist = tuple(sublist)
rhs = tuple(rhs)
if len(sublist) > len(rhs):
raise ValueError
if not sublist:
raise ValueError
new_list = []
idx = 0
while idx < len(rhs):
if rhs[idx:idx + len(s... | bigcode/self-oss-instruct-sc2-concepts |
import importlib
import pkgutil
def get_submodule_names(module_name):
"""
Returns a list of the module name plus all importable submodule names.
"""
module = importlib.import_module(module_name)
submodule_names = [module_name]
try:
module_path = module.__path__
except AttributeErr... | bigcode/self-oss-instruct-sc2-concepts |
def two_bytes_to_int(hi_byte: int, low_byte: int) -> int:
"""
Converts two bytes to a normal integer value.
:param hi_byte: the high byte
:param low_byte: the low byte
:return: converted integer that has a value between [0-65535]
"""
return ((hi_byte & 0xFF)*256) + (low_byte & 0xFF) | bigcode/self-oss-instruct-sc2-concepts |
def time_interval_since(date_1, date_2):
""" Calculate seconds between two times
Arguments:
date_1 -- datetime object #1
date_2 -- datetime object #2
Output:
Num of seconds between the two times (with a sign)
"""
return (date_1 - date_2).total_seconds() | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def convert_to_datetime(globus_time):
"""
Converts a time given in Globus format to datetime.
Globus format for time is as follows:
YYYY-MM-DD HH:MM:SS+00:00
"""
# use space separator to seperate date and time
times = globus_time.split(" ")
date_part ... | bigcode/self-oss-instruct-sc2-concepts |
def sum67(nums):
"""Solution to the problem described in http://codingbat.com/prob/p108886
Ex:
>>> sum67([1, 2, 2])
5
>>> sum67([1, 2, 2, 6, 99, 99, 7])
5
>>> sum67([1, 1, 6, 7, 2])
4
:param nums: list
:return: int
"""
sum = 0
between_6_and_7 = False
for n in n... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def get_temp_data(filename, directory='temp', extension='.temp'):
"""get temp data from disk"""
if '.temp' not in filename:
filename += extension
try:
with open(directory + '/'+ filename, 'rb') as f:
data_file = pickle.load(f)
f.close()
pr... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_accumulation_distribution(open, high, low, close, volume):
"""
Calculates changes in accumulation/distribution line.
A/D = ((Close - Low) - (High - Close))/(High - Low)
Args:
open: Float representing exchange rate at the beginning of an interval
high: Float representing th... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def datetime_name(output_name):
"""Creates a filename for the output according to the given format."""
now = datetime.now()
return f'{output_name}-{now.strftime("%Y-%m-%d-%H-%M")}.csv' | bigcode/self-oss-instruct-sc2-concepts |
def boxes_required(qty, box_capacity=6):
"""
Calculate how many egg boxes will be required for a given quatity of eggs.
:param qty: Number of eggs
:param box_capacity: How many eggs will fit in a box
:return: The number of boxes that are required
"""
return int(qty / box_capacity) + 1 | bigcode/self-oss-instruct-sc2-concepts |
def legend_from_ee(ee_class_table):
"""Extract legend from an Earth Engine class table on the Earth Engine Data Catalog page
such as https://developers.google.com/earth-engine/datasets/catalog/MODIS_051_MCD12Q1
Value Color Description
0 1c0dff Water
1 05450a Evergreen needleleaf forest
2 086a10... | bigcode/self-oss-instruct-sc2-concepts |
def _pseudo_alpha(rgb, opacity):
"""
Given an RGB value in [0, 1], return a new RGB value which blends in a
certain amount of white to create a fake alpha effect. This allosws us to
produce an alpha-like effect in EPS, which doesn't support transparency.
"""
return tuple((value * opacity - opa... | bigcode/self-oss-instruct-sc2-concepts |
def convert_gps_degress_to_minutes(lat, lon):
"""
Convert GPS in degrees to degrees, minutes, seconds as needed for the Exif
:param lat: Latitude in degrees
:param lon: Longitude in degrees
:return: Latitude and longitude in degrees, minutes, seconds
"""
lat_positive = lat >= 0
lon_posit... | bigcode/self-oss-instruct-sc2-concepts |
def has_os_path_join(block_dets):
"""
path = os.path.join('a', 'b')
os.path.join('a/', 'b')
<value>
<Call lineno="2" col_offset="7">
<func>
<Attribute lineno="2" col_offset="7" type="str" attr="join">
<value>
<Attribute lineno="2" col_offset="7" type="st... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def patch_request(base_request):
"""
Performs PATCH request for the class provided.
:param: base_request: Class with which to make request.
:type: BaseRequest
:return: response
:rtype: requests.Response
"""
(headers, _, _, _, service) = base_request.get_request_vars()
... | bigcode/self-oss-instruct-sc2-concepts |
def get_intercept(coords, m):
"""Calculates the intercept of a line from coordinates and slope"""
x, y = coords[0], coords[1]
b = y - m * x
return b | bigcode/self-oss-instruct-sc2-concepts |
def lte(x, y):
"""Creates an SMTLIB less than or equal to statement formatted string
Parameters
----------
x, y: float
First and second numerical arguments to include in the expression
"""
return "(<= " + x + " " + y + ")" | bigcode/self-oss-instruct-sc2-concepts |
def parse_none_results(result_dict):
"""
Replace `None` value in the `result_dict` to a string '-'
"""
for key, value_list in result_dict.items():
for i in range(len(value_list)):
if value_list[i] is None:
result_dict[key][i] = '-'
return result_dict | bigcode/self-oss-instruct-sc2-concepts |
def imagenet_mean_preprocess_image_tensor_fun(x):
"""
In:
x - image tensor of size (#images, #channels, #dim1, #dim2)
Out:
image tensor x with subtracted imagenet mean
"""
y = x
y[:,0,:,:] -= 103.939
y[:,1,:,:] -= 116.779
y[:,2,:,:] -= 123.68
return y | bigcode/self-oss-instruct-sc2-concepts |
def build_url(city_data, api_info):
"""Return a `request` compatible URL from api properties."""
# type: (Dict, Dict) -> str
return "{}:{}{}".format(
api_info["host"], str(api_info["port"]), api_info["path"].format(
city=city_data["city"], state=city_data["state"])) | 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.