seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def _check_pixel(tup):
"""Check if a pixel is black, supports RGBA"""
return tup[0] == 0 and tup[1] == 0 and tup[2] == 0 | bigcode/self-oss-instruct-sc2-concepts |
def deprecated_argument_lookup(new_name, new_value, old_name, old_value):
"""Looks up deprecated argument name and ensures both are not used.
Args:
new_name: new name of argument
new_value: value of new argument (or None if not used)
old_name: old name of argument
old_value: value of old argument (... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def total_variation(x):
"""
Total Variation Loss.
"""
return torch.sum(torch.abs(x[:, :, :, :-1] - x[:, :, :, 1:])
) + torch.sum(torch.abs(x[:, :, :-1, :] - x[:, :, 1:, :])) | bigcode/self-oss-instruct-sc2-concepts |
def match_asset(asset_name, goos, goarch):
"""
Compate asset name with GOOS and GOARCH.
Return True if matched.
"""
asset_name = asset_name.lower()
goarch = {
"386": ["386"],
"amd64": ["amd64", "x86_64"]
}[goarch]
match_goos = goos in asset_name
match_goarch = any([wo... | bigcode/self-oss-instruct-sc2-concepts |
def create_fill_row_string(slot1: str, slot2: str, gap_space: int):
""" creates a gap with variable spaces according to the length of the slot string """
return '|' + slot1 + (' ' * (gap_space-(2 + len(slot1) + len(slot2)))) + slot2 + '|' | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Any
def list_union(a: List[Any], b: List[Any]) -> List[Any]:
"""Return union of two lists maintaining order of the first list."""
return a + [x for x in b if x not in a] | bigcode/self-oss-instruct-sc2-concepts |
def sum_two(num_1, num_2):
"""
This function returns the sum of two numbers
"""
return num_1 + num_2 | bigcode/self-oss-instruct-sc2-concepts |
def fix_config_list(config_list):
"""
transforms a list of the form ['a, b'] to ['a', 'b']
"""
if not config_list:
return []
t = config_list
item = t[0]
list_items = item.split(',')
return [nr.strip() for nr in list_items] | bigcode/self-oss-instruct-sc2-concepts |
def collabel_2_index(label):
"""Convert a column label into a column index (based at 0), e.g., 'A'-> 1,
'B' -> 2, ..., 'AA' -> 27, etc.
Returns -1 if the given labe is not composed only of upper case letters A-Z.
Parameters
----------
label : string
Column label (expected to be composed... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_total_votes(poll):
"""Calculate the total number of votes of a poll."""
total = 0
for vote in poll.votes:
total += vote.vote_count
return total | bigcode/self-oss-instruct-sc2-concepts |
def __none_mult(x, y):
"""PRIVATE FUNCTION, If x or y is None return None, else return x * y"""
if x is not None and y is not None:
return x * y
return None | bigcode/self-oss-instruct-sc2-concepts |
def get_rescale_ratio(image, target):
"""Gets the required ratio to rescale an image to a target resolution
:param image: An image to resize.
:param target: The target resolution to resize to.
:type image: Image
:type target: int
:return: The min of the ratio between the target resolution and t... | bigcode/self-oss-instruct-sc2-concepts |
def option_name(path, delimiter="--"):
"""
Returns a cli option name from attribute path
**Arguments**
- path (`list`): attribute path
- delimiter (`str`): delimiter for nested attributes
**Returns**
cli option name (`str`)
"""
return "--{}".format(delimiter.join(path).replace("... | bigcode/self-oss-instruct-sc2-concepts |
def ledaLines(lines):
"""Filter sequence of lines to keep only the relevant ones for LEDA.GRAPH"""
def relevant(line):
return line and not line.startswith('#')
return filter(relevant, lines) | bigcode/self-oss-instruct-sc2-concepts |
import colorsys
def rgb_to_hls(r, g ,b):
"""Convert R(0-255) G(0-255) B(0-255) to H(0-360) L(0-255) S(0-255).
"""
rgb = [x / 255.0 for x in (r, g, b)]
h, s, v = colorsys.rgb_to_hls(*rgb)
return (h * 360, s * 255, v * 255) | bigcode/self-oss-instruct-sc2-concepts |
def int_or_float(x):
"""Return `x` as `int` if possible, or as `float` otherwise."""
x = float(x)
if x.is_integer():
return int(x)
return x | bigcode/self-oss-instruct-sc2-concepts |
def aggregate_group(df, aggregate_me, name="aggregated_group"):
"""
Aggregates several rows into one row.
df: str
aggregate_me: list.
One or more values from the new_var column may be given as a list.
This function takes those values (rows), aggregates them, and
returns one ro... | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_relative_imports(source) -> str:
"""
Remove all the relative imports from the source code
:param source:
:return:
"""
return re.sub(r"^#include \"(.+)\"$", "", source, flags=re.MULTILINE) | bigcode/self-oss-instruct-sc2-concepts |
def get_table_names(connection):
"""
Gets all table names in the specified database file.
:param connection: Connection to the DB file.
:return: List of table names
"""
connection.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = []
for table in connection.fetchall(... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def binary_cartesian_product(nb_bits: int):
"""
Compute binary possibilities of an nb_bits variable.
"""
ranges = [range(0, 2) for i in range(nb_bits)]
# In possibilities, we compute the nb_bits cartesian product of set([0, 1]}
possibilities = list()
for xs in itertools.pr... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def brute_force(num_lst: List[int], pivot: int) -> List[int]:
"""
Given a list and a pivot, sort so that all elements to the left of the pivot(s) are less than the pivot
and all elements to the right of the pivot(s) are greater than the pivot. Runs in O(3n) but not constant storage... | bigcode/self-oss-instruct-sc2-concepts |
def degree(a):
""" returns the degree of the atom """
return a.GetDegree() | bigcode/self-oss-instruct-sc2-concepts |
import decimal
def format_value(value):
"""Returns the given value rounded to one decimal place if it is a
decimal, or integer if it is an integer.
"""
value = decimal.Decimal(str(value))
if int(value) == value:
return int(value)
# On Python 3, an explicit cast to float is required
... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def exclude_meta(src_obj):
"""return copy of src_obj, without path, img, full_path, and objects keys"""
obj = copy.copy(src_obj)
for key in ['path', 'img', 'full_path', 'objects']:
if key in obj:
del obj[key]
return obj | bigcode/self-oss-instruct-sc2-concepts |
def part1(input_lines):
"""
The captcha requires you to review a sequence of digits (your puzzle input) and find
the sum of all digits that match the next digit in the list. The list is circular,
so the digit after the last digit is the first digit in the list.
For example:
- 1122 produces... | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def import_and_get_task(task_path):
"""
Given a modular path to a function, import that module
and return the function.
"""
module, function = task_path.rsplit(".", 1)
app_module = importlib.import_module(module)
app_function = getattr(app_module, function)
return app_... | bigcode/self-oss-instruct-sc2-concepts |
def MDD(series):
"""Maximum Drawdown (MDD) is an indicator of downside
risk over a specified time period.
MDD = (TroughValue – PeakValue) ÷ PeakValue
"""
trough = min(series)
peak = max(series)
mdd = (peak - trough) / peak
return round(mdd, 3) | bigcode/self-oss-instruct-sc2-concepts |
def named_value(dictionary):
"""
Gets the name and value of a dict with a single key (for example SenzaInfo
parameters or Senza Components)
"""
return next(iter(dictionary.items())) | bigcode/self-oss-instruct-sc2-concepts |
def _get_conjuncts(tok):
"""
Return conjunct dependents of the leftmost conjunct in a coordinated phrase,
e.g. "Burton, [Dan], and [Josh] ...".
"""
return [right for right in tok.rights
if right.dep_ == 'conj'] | bigcode/self-oss-instruct-sc2-concepts |
def last_common_item(xs, ys):
"""Search for index of last common item in two lists."""
max_i = min(len(xs), len(ys)) - 1
for i, (x, y) in enumerate(zip(xs, ys)):
if x == y and (i == max_i or xs[i+1] != ys[i+1]):
return i
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def gen_anytext(*args):
"""
Convenience function to create bag of words for anytext property
"""
bag = []
for term in args:
if term is not None:
if isinstance(term, list):
for term2 in term:
if term2 is not None:
bag.a... | bigcode/self-oss-instruct-sc2-concepts |
def bool_on_off(value):
"""Convert True/False to on/off correspondingly."""
return 'on' if value else 'off' | bigcode/self-oss-instruct-sc2-concepts |
def getStereoPair(pipeline, monoLeft, monoRight):
"""
Generates a stereo node. Takes left and right camera streams as inputs and generates outputs
"""
stereo = pipeline.createStereoDepth()
stereo.setLeftRightCheck(True)
monoLeft.out.link(stereo.left)
monoRight.out.link(stereo.right)
return stereo | bigcode/self-oss-instruct-sc2-concepts |
from fractions import Fraction
def compile_continued_fraction_representation(seq):
"""
Compile an integer sequence (continued fraction representation) into its corresponding fraction.
"""
# sanity check
assert seq
# initialize the value to be returned by working backwards from the last number... | bigcode/self-oss-instruct-sc2-concepts |
def get_skin_num(id, skin_id):
"""
Returns Skin Number from the Skin ID
"""
skin = str(id)
length = len(skin)
new_id = str(skin_id)[length:]
return int(new_id) | bigcode/self-oss-instruct-sc2-concepts |
def check_int(value: int) -> bool:
"""Check whether value can be written as 2^p * 5^q where p and q are
natural numbers."""
if value == 1:
return True
else:
if value % 2 == 0:
return check_int(value//2)
if value % 5 == 0:
return check_int(value//5)
ret... | bigcode/self-oss-instruct-sc2-concepts |
def make_ngrams(tokens: list, n: int) -> list:
"""Creates n-grams for the given token sequence.
Args:
tokens (list): a list of tokens as strings
n (int): the length of n-grams to create
Returns:
list: list of tuples of strings, each tuple being one of the individual n-grams
"""
n_grams ... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_channelmethods(obj):
"""
Returns a sorted list of the names of all channelmethods defined for an object.
"""
channelmethods = list()
# getmembers() returns a list of tuples already sorted by name
for name, method in inspect.getmembers(obj, inspect.ismethod):
# To... | bigcode/self-oss-instruct-sc2-concepts |
def map_range(value, from_lower, from_upper, to_lower, to_upper):
"""Map a value in one range to another."""
mapped = (value - from_lower) * (to_upper - to_lower) / (
from_upper - from_lower
) + to_lower
return round(min(max(mapped, to_lower), to_upper)) | bigcode/self-oss-instruct-sc2-concepts |
def default_logfile_names(script, suffix):
"""Method to return the names for output and error log files."""
suffix = script.split('.')[0] if suffix is None else suffix
output_logfile = '{}_out.txt'.format(suffix)
error_logfile = '{}_err.txt'.format(suffix)
return output_logfile, error_logfile | bigcode/self-oss-instruct-sc2-concepts |
import re
def str_split(string, split_length=1):
"""Method splits string to substrings
Args:
string (str): original string
split_length (int): substrin length
Returns:
list: list of strings
"""
return list(filter(None, re.split('(.{1,%d})' % split_length... | bigcode/self-oss-instruct-sc2-concepts |
def flatten(l):
"""Flattens a list of lists to the first level.
Given a list containing a mix of scalars and lists,
flattens down to a list of the scalars within the original
list.
Args:
l (list): Input list
Returns:
list: Flattened list.
"""
if not isinstance(l, list... | bigcode/self-oss-instruct-sc2-concepts |
def is_annotation_size_unusual(annotation, minimum_size, minimum_aspect_ratio, maximum_aspect_ratio):
"""
Checks if object described by annotation has unusual size - is too small or has unusual aspect ratio
:param annotation: net.utilities.Annotation instance
:param minimum_size: int, minimum size objec... | bigcode/self-oss-instruct-sc2-concepts |
def to_json_list(objs):
"""
Wrap strings in lists. Other iterables are converted to lists directly.
"""
if isinstance(objs, str):
return [objs]
if not isinstance(objs, list):
return list(objs)
return objs | bigcode/self-oss-instruct-sc2-concepts |
def make_list(item_or_items):
"""
Makes a list out of the given items.
Examples:
>>> make_list(1)
[1]
>>> make_list('str')
['str']
>>> make_list(('i', 'am', 'a', 'tuple'))
['i', 'am', 'a', 'tuple']
>>> print(make_list(None))
None
>>> # ... | bigcode/self-oss-instruct-sc2-concepts |
def check(these_bytes):
"""Tests a file for presence of a valid header"""
test = str(these_bytes[8:12])
if test[2:6] != 'logo':
return 1
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def safe_get(lst, index, default=None):
"""
An implementation of the similar :meth:`get` of the dictionary class.
:param lst: the list to perform the operation on
:param index: the index to query
:param default: the default value if not found
:return: the result if exists or the def... | bigcode/self-oss-instruct-sc2-concepts |
def calculate(x: int, y: int = 1, *, subtract: bool = False) -> int:
"""Calculates the sum (or difference) of two numbers.
Parameters:
`x` : int
The first number
`y` : int, optional
The second number (default is 1)
`subtraction`: bool, optional
Whether to perform subtraction... | bigcode/self-oss-instruct-sc2-concepts |
def elevation_line(client, format_in, geometry,
format_out='geojson',
dataset='srtm',
validate=True,
dry_run=None):
"""
POSTs 2D point to be enriched with elevation.
:param format_in: Format of input geometry. One of ['geojson'... | bigcode/self-oss-instruct-sc2-concepts |
import sqlite3
def commit_data(conn):
"""Commit data to db"""
try:
conn.commit()
conn.close()
except sqlite3.Error as e:
print(e)
return None | bigcode/self-oss-instruct-sc2-concepts |
import re
def _strip_terminal_commas(data: str) -> str:
"""Remove all terminal commas.
Samples sheets have a large number of commas append to the end of the
various sections. I think this is an artifact of exporting to a CSV
forcing each row to have the same number of columns as the main Data
sec... | bigcode/self-oss-instruct-sc2-concepts |
def _get_runfile_path(ctx, f):
"""Return the runfiles relative path of f."""
if ctx.workspace_name:
return ctx.workspace_name + "/" + f.short_path
else:
return f.short_path | bigcode/self-oss-instruct-sc2-concepts |
def calculate_cn_values(m, sigma_veff):
"""
CN parameter from CPT, Eq 2.15a
"""
CN = (100 / sigma_veff) ** m
if CN > 1.7:
CN = 1.7
return CN | bigcode/self-oss-instruct-sc2-concepts |
import torch
def shuffle_data(inputs, outputs):
"""Shuffle the first dimension of a set of input/output data"""
n_examples = outputs.shape[0]
shuffled_indices = torch.randperm(n_examples)
inputs = inputs[shuffled_indices]
outputs = outputs[shuffled_indices]
return inputs, outputs | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_valid_entity(line: str) -> bool:
"""Check if the line is a valid entity annotation."""
regex = r'^T\d+\t\w+ \d+ \d+(;\d+ \d+)*\t.+$'
return re.search(regex, line) is not None | bigcode/self-oss-instruct-sc2-concepts |
def _blob_and_weights(net, layer_name):
"""Get the activation blob and the weights blob for the named layer
in the Caffe network.
"""
# Get the activation blob for this layer and its parameters
# (weights).
blob = net.blobs[net.top_names[layer_name][0]]
weights = net.params[layer_name][0]
... | bigcode/self-oss-instruct-sc2-concepts |
def null_val(val):
"""Return True if the value is a mmCIF NULL charactor: ? or .
"""
if val == "?" or val == ".":
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import torch
def radius_gaussian(sq_r, sig, eps=1e-9):
"""
Compute a radius gaussian (gaussian of distance)
:param sq_r: input radiuses [dn, ..., d1, d0]
:param sig: extents of gaussians [d1, d0] or [d0] or float
:return: gaussian of sq_r [dn, ..., d1, d0]
"""
return torch.exp(-sq_r / (2 *... | bigcode/self-oss-instruct-sc2-concepts |
def human_to_mb(s):
"""Translates human-readable strings like '10G' to numeric
megabytes"""
if len(s) == 0:
raise Exception("unexpected empty string")
md = dict(M=1, G=1024, T=1024 * 1024, P=1024 * 1024 * 1024)
suffix = s[-1]
if suffix.isalpha():
return float(s[:-1]) * md[suffi... | bigcode/self-oss-instruct-sc2-concepts |
import collections
def longest_substring_deque_rotations(s: str) -> int:
"""
find the longest substring without repeating characters
512 ms 14.5 MB
>>> longest_substring_deque_rotations("abac")
3
>>> longest_substring_deque_rotations("abcabcbb")
3
>>> longest_substring_deque_rotations... | bigcode/self-oss-instruct-sc2-concepts |
def CodepointsToUTF16CodeUnits( line_value, codepoint_offset ):
"""Return the 1-based UTF-16 code unit offset equivalent to the 1-based
unicode codepoint offset |codepoint_offset| in the Unicode string
|line_value|"""
# Language server protocol requires offsets to be in utf16 code _units_.
# Each code unit is... | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def _import_name(generator):
"""Import a class from its module name."""
# A generator 'path'
try:
mod_name, func_name = generator.rsplit(".", 1)
except ValueError:
raise ValueError("Invalid generator class name %s" % generator)
try:
mod = importlib.import_... | bigcode/self-oss-instruct-sc2-concepts |
def sciNot(x):
"""Returns scientific notation of x value"""
return '%.2E' % x | bigcode/self-oss-instruct-sc2-concepts |
import ctypes
def struct_to_dict(struct: ctypes.Structure) -> dict:
"""Create a dict from a struct's fields and their values."""
return {name: getattr(struct, name) for name, _ in getattr(struct, "_fields_")} | bigcode/self-oss-instruct-sc2-concepts |
def parse_hkey(idx):
"""parse index and convert to str
Args:
idx (pd.DatetimeIndex): datetime index
Returns:
str: zero padded 24-clock hour(%H)
"""
return str(idx.hour).zfill(2) | bigcode/self-oss-instruct-sc2-concepts |
def apparent_latitude(t='now'): # pylint: disable=W0613
"""Returns the true latitude. Set to 0 here."""
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def normalise_activity_by_sector_month(
topic_activity, sector_month_labels, sector_variable="sector"
):
"""Normalise s.t. each [sector, month] sums to 1."""
norm_factor = (
sector_month_labels.dropna()
.groupby(
[
"month",
sector_variable,
... | bigcode/self-oss-instruct-sc2-concepts |
def is_permutation(a: int, b: int) -> bool:
"""Returns boolean if a and b are permutations of each other."""
s_a, s_b = str(a), str(b)
if set(s_a) != set(s_b):
return False
if len(s_a) != len(s_b):
return False
return sorted(list(s_a)) == sorted(list(s_b)) | bigcode/self-oss-instruct-sc2-concepts |
from collections import Counter
def related_by_digit_permutation(num_a, num_b):
"""
Check if two numbers are related by digit permutation.
"""
return Counter(str(num_a)) == Counter(str(num_b)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
from typing import Optional
def get_name(hook: Dict[Any, Any]) -> Optional[str]:
"""
Creates a name based on the webhook call it recieved
Format: Timestamp_Devicename.mp4
Removes any characters that are not regular characters, numbers, '_' '.' or '-'
... | bigcode/self-oss-instruct-sc2-concepts |
def iterator(it):
"""
Convenience function to toggle whether to consume dataset and forecasts as iterators or iterables.
:param it:
:return: it (as iterator)
"""
return iter(it) | bigcode/self-oss-instruct-sc2-concepts |
def normalize_date(date):
"""Round datetime down to midnight."""
return date.replace(hour=0, minute=0, second=0, microsecond=0) | bigcode/self-oss-instruct-sc2-concepts |
import math
def hits_to_kill(damage, health):
"""
Returns the number of hits it takes to kill the target.
"""
if damage > 0:
hits = health / damage
else:
hits = math.inf
if hits < 1:
hits = 1
elif hits < math.inf:
hits = math.ceil(hits)
return hits | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def generate_unique_id(text):
"""
Generate a unique UUID based on a string
Args:
text(str): The string to base the uuid on
Returns:
str: The UUID in hex string format
"""
return uuid.uuid3(uuid.NAMESPACE_URL, text).hex | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def generate_random_key() -> str:
"""
Creates and returns a randomly generated 10 character alphanumeric string.
:return:
"""
return "".join(
random.SystemRandom().choice(string.ascii_uppercase + string.digits)
for _ in range(10)
) | bigcode/self-oss-instruct-sc2-concepts |
def _df_meta_to_arr(df):
"""Check what kind of data exists in pandas columns or index. If string return as numpy array 'S' type, otherwise regular numpy array.
"""
if len(df.columns):
if isinstance(df.columns[0], str):
columns = df.columns.values.astype("S")
else:
co... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
import yaml
def load_yaml(yamlpath: str):
"""
Loads a yaml file from a path.
:param yamlpath: Path to yaml settings file
:returns: dict settings object """
yamlpath_full = Path(yamlpath).absolute()
with open(yamlpath_full, 'r', encoding="utf-8") as stream:
try... | bigcode/self-oss-instruct-sc2-concepts |
def has_field(analysis, field):
"""Return true or false if given field exists in analysis"""
for f in field:
try:
analysis = analysis[f]
except:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import multiprocessing
def queue_loader(q_list):
"""
Copy values from a List into a SimpleQueue.
"""
q = multiprocessing.SimpleQueue()
for item in q_list:
q.put(item)
return q | bigcode/self-oss-instruct-sc2-concepts |
def generate_method(method_name):
"""Generate a method for a given Thrift service.
Uses the provided TChannelSyncClient's threadloop in order
to convert RPC calls to concurrent.futures
:param method_name: Method being called.
:return: A method that invokes the RPC using TChannelSyncClient
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def color_to_int(rgb):
"""Converts a color from floating point range 0-1 to integer range 0-255."""
return tuple(int(round(c * 255)) for c in rgb) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _get_before_pronounce_sentence(words, index):
"""Return before pronounce sentence
Args:
words (List[Words]): stanfordnlp word object list.
index (int): Pronounce index.
Return:
sentence (str): target word contains sentence to pronounce.
"""
roots = [(i, w) fo... | bigcode/self-oss-instruct-sc2-concepts |
def _get_kaggle_type(competition_or_dataset: str) -> str:
"""Returns the kaggle type (competitions/datasets).
Args:
competition_or_dataset: Name of the kaggle competition/dataset.
Returns:
Kaggle type (competitions/datasets).
"""
# Dataset are `user/dataset_name`
return 'datasets' if '/' in compet... | bigcode/self-oss-instruct-sc2-concepts |
def token_response_json(token_response):
"""
Return the JSON from a successful token response.
"""
return token_response.json | bigcode/self-oss-instruct-sc2-concepts |
def get_subgraph(G, attribute, attribute_value):
"""
This function returns the subgraph of G with the attribute
attribute_value.
Input:
------
G: networkx graph
attribute: attribute of the nodes
attribute_value: value of the attribute
Output:
-------
subgra... | bigcode/self-oss-instruct-sc2-concepts |
import re
def verifyFormat(ATS_LIST):
"""
Matches a list of input ATS coordinates against the AltaLIS format in a regex.
Returns True if any of the coordinates match the regex,
False if none return.
"""
# Defines a list of expressions to check against the coordinates.
# Anything in s... | bigcode/self-oss-instruct-sc2-concepts |
def SanityCheck(s):
"""
Class performs a simple text-based SanityCheck
to validate generated SMILES. Note, this method
does not check if the SMILES defines a valid molecule,
but just if the generated SMILES contains the
correct number of ring indices as well as opening/closing
brackets.
... | bigcode/self-oss-instruct-sc2-concepts |
def priormonthToDay(freq, j_mth, k_mth):
"""
Consistent w/ Fama and French (2008, 2016), map the prior `(j-k)` monthly return strategy into a daily strategy
(see `Ken French's online documentation <https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html>`_).
Parameters
__________... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _filter_zones(wanted_zones_prefix, zone_list):
"""Filter unwanted zones from a zone list using a prefix."""
target_zones = []
for zone in zone_list:
for prefix in wanted_zones_prefix:
pattern = re.compile(f'^{prefix}')
if pattern.match(zone):
... | bigcode/self-oss-instruct-sc2-concepts |
def _cut_if_too_long(text: str, max_length: int) -> str:
"""Cut a string down to the maximum length.
Args:
text: Text to check.
max_length: The maximum length of the resulting string.
Returns:
Cut string with ... added at the end if it was too long.
"""
if len(text) <= max_... | bigcode/self-oss-instruct-sc2-concepts |
import ipaddress
def is_address(entry):
""" Check if entry is a valid IP address """
try:
_ = ipaddress.ip_address(entry)
except ValueError:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def tuple_or_list(target):
"""Check is a string object contains a tuple or list
If a string likes '[a, b, c]' or '(a, b, c)', then return true,
otherwise false.
Arguments:
target {str} -- target string
Returns:
bool -- result
"""
# if the target is a tuple or ... | bigcode/self-oss-instruct-sc2-concepts |
def get_ext(file):
"""Return the extension of the given filename."""
return file.split('.')[-1] | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_wrapped_sourcelines(f):
"""
Gets a list of source lines and starting line number for the given function
:param f: Input function
:return: Source lines
"""
if hasattr(f, "__wrapped__"):
# has __wrapped__, going deep
return get_wrapped_sourcelines(f.__wrapp... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
import ast
import textwrap
def ast_object(obj):
"""Convert a Python object to its AST representation."""
src = inspect.getsource(obj)
# ast wraps always into a module
node = ast.parse(textwrap.dedent(src)).body[0]
return node | bigcode/self-oss-instruct-sc2-concepts |
def txt2str(filename):
"""Reads the plain text of a .txt file and returns a string"""
with open(filename, 'r') as myfile:
data=myfile.read().replace('\n', '')
myfile.close()
return data | bigcode/self-oss-instruct-sc2-concepts |
def _monitor_pvs(*pv_names, context, queue, data_type='time'):
"""
Monitor pv_names in the given threading context, putting events to `queue`.
Parameters
----------
*pv_names : str
PV names to monitor.
context : caproto.threading.client.Context
The threading context to use.
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def column_widths(table: List[List[str]]) -> List[int]:
"""Get the maximum size for each column in table"""
return [max(map(len, col)) for col in zip(*table)] | bigcode/self-oss-instruct-sc2-concepts |
def commands(command):
""" Check if command is to get available Commands (c | commands). """
return (command.strip().lower() == 'c' or command.strip().lower() == 'commands') | bigcode/self-oss-instruct-sc2-concepts |
def build_concentartion(species_id, number):
"""
Builds the concentration component for each species
Parameters
----------
species_id : int
species id from the species_indices dictionary
number : float
stoichiometric co-eff of the species
... | 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.