seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def strtobool (val, yesvals = ["yes", "y"], novals = ["no", "n"]):
"""Convert a string representation of truth to true (1) or false (0).
Raises ValueError if 'val' is anything else."""
val = val.lower()
if val in yesvals:
return 1
elif val in novals:
return 0
else:
raise ... | bigcode/self-oss-instruct-sc2-concepts |
def title_is_in_row(title_search_string, title_row):
"""Returns true if the target title in the passed row."""
return title_search_string.lower() in title_row.lower() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def _is_iterable(value):
"""
Check whether the value is an iterable (excludes strings).
*value* is the value to check,
Returns whether *value* is a iterable (:class:`bool`).
"""
return isinstance(value, Iterable) and not isinstance(value, (str, bytes)) | bigcode/self-oss-instruct-sc2-concepts |
import tarfile
def scan_gz(filepath):
""" Scan a .tar.gz file. """
return tarfile.open(filepath, 'r:gz').getnames() | bigcode/self-oss-instruct-sc2-concepts |
def printAngle(angle, shift, molecule, alchemicalTransformation):
"""Generate angle line
Parameters
----------
angle : Angle Object
Angle Object
shift : int
Shift produced by structural dummy atoms
molecule : molecule object
Molecule object
alchemicalTransformation :... | bigcode/self-oss-instruct-sc2-concepts |
def label_case(snake_case):
"""Specialized helper function to replace underscore with spaces and capitalize first letter of string, but keep WMR and WMQ capitalized
Args:
snake_case (str): String written in snake case to be reformatted.
Returns:
str: The reformatted string.
... | bigcode/self-oss-instruct-sc2-concepts |
def ComptonRotationAngle(azimuth):
"""Reference frame rotation so that MuellerMatrixCompton holds
Args:
azimuth(num): scattering azimuth (degree)
Returns:
angle: rotation of the axes in degrees
"""
# First component axis perpendicular to the scattering plane
return azimuth - 90 | bigcode/self-oss-instruct-sc2-concepts |
def get_user_pool_domain(prefix, region):
"""Return a user pool domain name based on the prefix received and region.
Args:
prefix (str): The domain prefix for the domain
region (str): The region in which the pool resides
"""
return '%s.auth.%s.amazoncognito.com' % (prefix, region) | bigcode/self-oss-instruct-sc2-concepts |
def is_vcf_chrom_header(line):
"""
Returns ``True`` if ``line`` is a VCF chrom-definition header line, ``False`` otherwise.
:param line: line from VCF file
:return: ``bool``
"""
if line.startswith('##contig='):
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_top_users_and_orgs(user_data_df, top_repos_df):
"""Gets the top 25 Github Users and top 25 Organizations.
Note: Top 25 Users are determined based on total followers.
Top 25 Organizations are determined based on total stars
for all of an organizations repos.
Parameters
-----... | bigcode/self-oss-instruct-sc2-concepts |
def check_dtype(**kwds):
""" Check a dtype for h5py special type "hint" information. Only one
keyword may be given.
vlen = dtype
If the dtype represents an HDF5 vlen, returns the Python base class.
Currently only builting string vlens (str) are supported. Returns
None if the dtype... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
from typing import Tuple
def recurse_tsv(contents: str, fnc: Callable, delim: str = "\t") -> Tuple[str, bool]:
"""Recurse with a callback function in TSV contents.
Just visit each line and look at values only.
Args:
contents:
TSV/CSV contents string
... | bigcode/self-oss-instruct-sc2-concepts |
def Step(v, threshold=0, act_value=1, inact_value=0):
"""
Step function where the threshold,
activated and inactivated value can be defined.
"""
return act_value if v > threshold else inact_value | bigcode/self-oss-instruct-sc2-concepts |
def _format_result(counts, cl_reg_index, cl_reg_nbits):
"""Format the result bit string.
This formats the result bit strings such that spaces are inserted
at register divisions.
Args:
counts (dict): dictionary of counts e.g. {'1111': 1000, '0000':5}
cl_reg_index (list): starting bit in... | bigcode/self-oss-instruct-sc2-concepts |
def one_is_not_none(*args) -> bool:
"""
Return True if exactly one arg is not None.
"""
return sum([arg is not None for arg in args]) == 1 | bigcode/self-oss-instruct-sc2-concepts |
def calculate(action, a, b):
"""
Calculate the result of the action and the two numbers.
"""
print(f'{action}ing a = {a} and b = {b}')
if action == 'add':
return a + b
elif action == 'subtract':
return a - b
elif action == 'multiply':
return a * b
elif action =... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def any_not_none(iterable: Iterable) -> bool:
"""
Verify if any of the elements of the iterable is not None.
The default behaviour of the builtin any function checks the value
with `if element` and causes the values like zero (0) to be
treated as Falsy values. This func... | bigcode/self-oss-instruct-sc2-concepts |
def average_overlap(similarity_fn, samples, *ignore_params):
"""Returns the arithmetic mean of each candidate sentence in the samples
Args:
similarity_fn (function): similarity function used to compute the overlap
samples (list of lists): tokenized version of the translated sentences
*i... | bigcode/self-oss-instruct-sc2-concepts |
def to_primitive(rho, rhou, rhov, ener, gamma=1.4):
"""Converts conservative variables to primitive variables rho, u, v, and p."""
u = rhou / rho
v = rhov / rho
p = (gamma - 1.0) * (ener - 0.5 * rho * (u**2 + v**2))
return rho, u, v, p | bigcode/self-oss-instruct-sc2-concepts |
import torch
def torch_eye(n, m=None, out=None):
"""
Like `torch.eye()`, but works with cuda tensors.
"""
if m is None:
m = n
try:
return torch.eye(n, m, out=out)
except TypeError:
# Only catch errors due to torch.eye() not being available for cuda tensors.
modu... | bigcode/self-oss-instruct-sc2-concepts |
def calculations_rain_module(basin, rain_intensity, timestep):
"""
Calculates the volume of rain falling on a basin during 1 timestep.
:param basin: Basin in which the rain is falling
:param rain_intensity: amount of rain falling per hour [mm/hour]
:param timestep: amount of seconds per timestep
... | bigcode/self-oss-instruct-sc2-concepts |
def linear10(value):
"""Convert dB value to linear units (power-like)."""
return 10 ** (value / 10) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _set_dir_iol(dir_in, dir_out, dir_log=None):
""" Set directory name for input, output, and logs.
"""
dir_in = Path(dir_in)
dir_out = Path(dir_out)
if dir_log is None:
dir_log = dir_out.parent
else:
dir_log = Path(dir_log)
return dir_in, dir_out,... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def encode_password(string):
"""
Encodes a password using SHA-256 algorithm.
"""
# Converts the string into bytes
encoded_string = string.encode()
# Create the SHA-256 object
result = hashlib.sha256(encoded_string)
# Get the hexadecimal format of the encoded data
hex... | bigcode/self-oss-instruct-sc2-concepts |
def base128Size(n):
""" Return the length in bytes of a UIntBase128-encoded sequence with value n.
>>> base128Size(0)
1
>>> base128Size(24567)
3
>>> base128Size(2**32-1)
5
"""
assert n >= 0
size = 1
while n >= 128:
size += 1
n >>= 7
return size | bigcode/self-oss-instruct-sc2-concepts |
def reduced_chi_squared(yfit, y, sigma, degrees):
"""Given yfit, y, sigma, and (the number of) degrees of freedom,
return the reduced chi-squared value.
"""
error = yfit - y
return sum(error*error/sigma/sigma) / degrees | bigcode/self-oss-instruct-sc2-concepts |
def find_no_text_pages(page_texts):
"""Find the pages in the page text list `page_texts` (created by make_page_corpus.py) that
contain no text
Returns: list of empty page numbers (page numbers start at zero)
"""
return [i for i, text in enumerate(page_texts) if not text] | bigcode/self-oss-instruct-sc2-concepts |
def remove_characters_without_dialog(screenplay):
"""
remove double 'character' instances from screenplay (happens when a character
does something, but doesn't actually speak, e.g. GEORGE: (gasps)
"""
redundant_indices_in_screenplay = []
for i in range(len(screenplay)-1):
if screenplay[i... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import re
from textwrap import dedent
import textwrap
def wrap_paragraphs(text: str, ncols: int = 80) -> List[str]:
"""Wrap multiple paragraphs to fit a specified width.
This is equivalent to textwrap.wrap, but with support for multiple
paragraphs, as separated by empty lines.
... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def match(path: Path) -> bool:
"""Return True if the path is a ZIP archive."""
return path.suffix.lower() == ".zip" and path.is_file() | bigcode/self-oss-instruct-sc2-concepts |
def _find_first_degree_branches(branch, branch_id):
"""Find all branches connected to a given branch.
:param pandas.DataFrame branch: branch DataFrame from Grid object.
:param int branch_id: index of branches to find neighbors of.
:return: (*set*) -- set of branch indexes (integers).
"""
from_b... | bigcode/self-oss-instruct-sc2-concepts |
import string
def fill_template_filename(template_string, substitution_dict):
"""
Replace variables in the template with the respective substitution dict entries.
Checks the `template_string` for variables (i.e., something like '${VAR_NAME}') that are listed as keys in `substitution_dict`. If such entrie... | bigcode/self-oss-instruct-sc2-concepts |
def bulk_create_or_get(session, mapper, ids):
"""
For given model, return a list of entries with given primary keys.
Any entries that don't exist will be created.
"""
entries = list(
session.query(mapper)
.filter(mapper.id.in_(ids))
)
existing_ids = set([entry.id for entry i... | bigcode/self-oss-instruct-sc2-concepts |
def delete_before(list, key):
"""
Return a list with the the item before the first occurrence of the
key (if any) deleted.
"""
if list == ():
return ()
else:
head1, tail1 = list
if tail1 == ():
return list
else:
head2, tail2 = tail1
... | bigcode/self-oss-instruct-sc2-concepts |
def get_stock_exchange(stock_code: str) -> str:
"""
Get the stock market according to the code rule.
:param stock_code: The stock code that need to check/
:return: Exchange. SSE - Shanghai, SZSE - Shenzhen. Empty string if not recognized.
"""
if len(stock_code) != 6:
return ''
if sto... | bigcode/self-oss-instruct-sc2-concepts |
def convert_gold_to_str_set(test_instance):
""" Helper method to convert the gold labels into readable text strings """
return {test_instance[0][x[0]:x[1]] + '_' + x[2] for x in test_instance[1]['entities']} | bigcode/self-oss-instruct-sc2-concepts |
def charToString(charArray):
""" Takes an array of chars and returns the corresponding string."""
result = ""
for i in charArray:
result += i.decode("UTF-8")
return result | bigcode/self-oss-instruct-sc2-concepts |
def snap_key_to_snapnum(snap_key):
"""
Given the name of a snapshot key, finds the associated snapshot number.
This is necessary because the 0th snapshot key may not be snapshot 000 and
there could be missing snapshots. This function searches backwards for a
group of digits that identify the snapsh... | bigcode/self-oss-instruct-sc2-concepts |
def ip_str_from4bytes(s: bytes) -> str: # b'\xc0\xa8\xfa\xe5' => 192.168.250.229
""" Convert bytestring to string representation of IPv4 address
Args:
s: source bytestring
Returns:
IPv4 address in traditional notation
"""
return str(s[0]) + "." + str(s[1]) + "." + str(s[2]) + "." ... | bigcode/self-oss-instruct-sc2-concepts |
def set_significant_digits(radar) -> None:
"""
Set _Least_significant_digit netcdf attribute.
"""
fieldnames = [
("VEL", 2),
("VEL_UNFOLDED", 2),
("DBZ", 2),
("DBZ_CORR", 2),
("DBZ_CORR_ORIG", 2),
("RHOHV_CORR", 2),
("ZDR", 2),
("ZDR_CORR_A... | bigcode/self-oss-instruct-sc2-concepts |
def limited_join(sep, items, max_chars=30, overflow_marker="..."):
"""Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_string
"""
full_str = sep.join(items)
if len(fu... | bigcode/self-oss-instruct-sc2-concepts |
def get_indexes_from_best_path(best_path):
"""Grab the reference and event index of the best path from the maximum_expected_accuracy_alignment function.
:param best_path: output from maximum_expected_accuracy_alignment
:return: list of events [[ref_pos, event_pos]...]
"""
path = []
while best_pa... | bigcode/self-oss-instruct-sc2-concepts |
def removesuffix(text, suffix):
"""Removes a suffix from a string.
If the string ends with the suffix string and the suffix is not empty,
returns string[:-len(suffix)]. Otherwise, returns the original string.
This function has been added in Python3.9 as the builtin
`str.removesuffix`, but is define... | bigcode/self-oss-instruct-sc2-concepts |
def get_all_morph(df):
"""
Returns all morphemes and Part-of-Speech.
- input : dataframe
- output : string
"""
ret=''
for index, row in df.iterrows():
if row['type'] == 'Inflect' or row['type'] == 'Compound':
tag=row['expression']
ret+=tag.replace('+',' ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def filter_releases_by_channel(releases: List[dict], channel: str):
"""
Filter releases by channel (stable, beta, or alpha).
:param releases: a list of releases
:param channel: a software channel (
:return: a filtered list of releases
"""
if channel not in ["stabl... | bigcode/self-oss-instruct-sc2-concepts |
def parse_show_qos_cos_map(raw_result):
"""
Parse the show command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the 'show qos cos-map' command in a \
dictionary where each key is a code point in the cos map:
::
{
... | bigcode/self-oss-instruct-sc2-concepts |
def guess_band(filename):
""" Guess the passband using the image's filename"""
if '_B_' in filename:
passband = 'B'
elif '_V_' in filename:
passband = 'V'
elif '_R_' in filename:
passband = 'R'
elif '_I_' in filename:
passband = 'I'
else:
passband = 'clear... | bigcode/self-oss-instruct-sc2-concepts |
def indent(txt, indent_level):
"""
Indent a piece of text
>>> indent('foo', 2)
' foo'
"""
indent = " " * indent_level
return "\n".join(indent + x for x in txt.splitlines()) | bigcode/self-oss-instruct-sc2-concepts |
def get_op_name(tensor_name):
"""
Given a tensor name, return the corresponding op name.
Args:
tensor_name: The name of a tensor.
Returns:
str: The op name
"""
return tensor_name.replace('^', '').split(':')[0] | bigcode/self-oss-instruct-sc2-concepts |
def is_number(number):
"""
Check whether this is a number (int, long, float, hex) .
Aruguments:
number: {string}, input string for number check.
"""
try:
float(number) # for int, long, float
except ValueError:
try:
int(number, 16) # for possible hex
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Pattern
def parse_substring(full_string: str, rex: Pattern[str]) -> str | None:
"""Parse an url for substring matching the given regular expression.
Args:
url (str): String representation of the URL
rex (Pattern[str]): String represenation of a regular expression
Retur... | bigcode/self-oss-instruct-sc2-concepts |
def extensions(includes):
"""Formats a list of header files to include.
"""
return ["".join([i.split(".")[0], ".h"]) for i in includes if i.split(".")[0] != "types"] | bigcode/self-oss-instruct-sc2-concepts |
def calc_delta_theta_int_inc_heating(bpr):
"""
Model of losses in the emission and control system for space heating and cooling.
Correction factor for the heating and cooling setpoints. Extracted from EN 15316-2
(see cea\databases\CH\Systems\emission_systems.xls for valid values for the heating and co... | bigcode/self-oss-instruct-sc2-concepts |
import re
def matches(target, search_query):
"""
Uses a regex to match the header title with the desired title
:param target: The title to compare against
:param search_query: The field to compare with
:return: Boolean
"""
title_regex = re.compile(search_query, re.IGNORECASE)
res = tit... | bigcode/self-oss-instruct-sc2-concepts |
def sievePath(fDB, path):
"""Recursively removes all files in path that are already in the fDB.
:param fDB: the information regarding files
:type fDB: FileDB
:param path: the path
:type path: str
:rtype: int
Returns the number of deleted files.
"""
return fDB.sievePath(path) | bigcode/self-oss-instruct-sc2-concepts |
def num2columnletters(num, power=0):
"""
Takes a column number and converts it to the equivalent excel column letters
:param int num: column number
:param int power: internal power multiplier for recursion
:return str: excel column letters
"""
if num <= 26:
return chr(num % 27 + 64)... | bigcode/self-oss-instruct-sc2-concepts |
def _APINameFromCollection(collection):
"""Get the API name from a collection name like 'api.parents.children'.
Args:
collection: str, The collection name.
Returns:
str: The API name.
"""
return collection.split('.')[0] | bigcode/self-oss-instruct-sc2-concepts |
import random
def pick_from_distribution(input_map):
"""
Generates an item from a distribution map
:param input_map: The dictionary of items to their probabilities
:return: An item from the dictionary
"""
rand = random.random()
total = 0.0
for item, prob in input_map.iteritems():
... | bigcode/self-oss-instruct-sc2-concepts |
def get_line_by_offset(file_path: str, offset: int) -> str:
"""Get line by byte offset from the given file.
:param file_path: path to the file
:param offset: byte offset
:return: read line
"""
with open(file_path, "r") as data_file:
data_file.seek(offset)
line = data_file.readli... | bigcode/self-oss-instruct-sc2-concepts |
def plot_raw(fig):
"""Set up the basic plotting paramaters"""
ax = fig.add_subplot(111, projection='3d')
ax.set_autoscale_on(False)
ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')
ax.set_xlim3d([0.0, 100.0])
ax.set_ylim3d([0.0, 100.0])
ax.set_zlim3d([0.0, 100.... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_end_stream_request(stream_id: str, request_id: int, api_version: str) -> str:
"""
Parameters
----------
stream_id:
ID of stream we want to stop
request_id:
ID of EndStreamRequest
Returns
-------
Serialized EndStreamRequest
"""
api_message = ... | bigcode/self-oss-instruct-sc2-concepts |
import time
def timer(f):
"""Calcule et affiche la durée d'exécution d'une fonction unaire"""
def wrapped(x):
start = time.time()
value = f(x)
end = time.time()
print(f"Durée {end - start} secs")
return value
return wrapped | bigcode/self-oss-instruct-sc2-concepts |
def rendered_source_for_lang(page_pk, lang):
"""Create cache key for rendered page source based on current language"""
return 'powerpages:rendered_source_lang:{0}:{1}'.format(page_pk, lang) | bigcode/self-oss-instruct-sc2-concepts |
def render_comment(comment):
"""
Inclusion tag for rendering a comment.
Context::
Comment
Template::
questions/comment.html
"""
return dict(comment=comment) | bigcode/self-oss-instruct-sc2-concepts |
def match(line, keyword):
""" If the first part of line (modulo blanks) matches keyword,
returns the end of that line. Otherwise checks if keyword is
anywhere in the line and returns that section, else returns None"""
line = line.lstrip()
length = len(keyword)
if line[:length] == keyword:
... | bigcode/self-oss-instruct-sc2-concepts |
def convert_bool(column):
"""
Convert text into bool in given column.
- column: series to be converted
- return: converted column
"""
def _convert_bool(text):
if text in ["Y", "y", "1"]:
return True
else:
return False
if column.name in ["acti... | bigcode/self-oss-instruct-sc2-concepts |
def vec_dot_star(v1,v2):
""" Returns dot* (dot star) product of 2 2D vectors
the sign of the dot* shows if the v2 is to the left or to the right from the v1"""
dot_star = v1[0]*(v2[1])-v1[1]*v2[0]
return dot_star | bigcode/self-oss-instruct-sc2-concepts |
def sum(x, y):
"""Sum x and y
>>> sum(10, 20)
30
>>> sum(-10, 20)
10
>>> sum('10', 20)
Traceback (most recent call last):
...
AssertionError: x needs to be in or float
"""
assert isinstance(x, (int, float)), 'x needs to be in or float'
assert isinstance(y, (int, float)), 'x needs to be in or float'
re... | bigcode/self-oss-instruct-sc2-concepts |
def SGD(lr=0.001, momentum=0):
"""SGD Optimiser.
:param lr: Learning rate
:type lr: float
:param momentum: Momentum
:type momentum: float
"""
return {
"optimiser": "SGD",
"opt_args": {
"lr": lr,
"momentum": momentum
}... | bigcode/self-oss-instruct-sc2-concepts |
def get_event_log(isdsAppliance, check_mode=False, force=False):
"""
Get Event Log
"""
return isdsAppliance.invoke_get("Retrieving Event Log", "/events/system") | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def generate_reason(total_points: int, message: str, recipients: List[str]) -> str:
"""
:param total_points: the amount of points that should be distributed
:param message: the message used when awarding points
:param recipients: a list of email addressed for users who should r... | bigcode/self-oss-instruct-sc2-concepts |
def elapsed_time_format(seconds):
"""Returns human readable string for elapsed time"""
negative = seconds < 0
seconds = abs(int(seconds))
periods = [
('year', 60 * 60 * 24 * 365),
('month', 60 * 60 * 24 * 30),
('day', 60 * 60 * 24),
('hour', 60 * 60),
('minute', 6... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_bytes_hash(bytes, hash_function=hashlib.md5, chunk_size=4096):
"""
Return hash of byte stream.
Adapted from quantumSoup at https://stackoverflow.com/a/3431838.
"""
hash = hash_function()
for chunk in iter(lambda: bytes.read(chunk_size), b""):
hash.update(chunk)
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
from typing import Tuple
def tanh_warp_transform(
coords: torch.Tensor, matrix: torch.Tensor,
warp_factor: float, warped_shape: Tuple[int, int]):
""" Tanh-warp function.
Args:
coords (torch.Tensor): b x n x 2 (x, y). The original coordinates.
matrix: b x 3 x 3. A ... | bigcode/self-oss-instruct-sc2-concepts |
def _get_installed_version(name, installed_list):
"""Return installed version of package"""
try:
return [x for x in installed_list if x.name == name][0]
except IndexError:
return None | bigcode/self-oss-instruct-sc2-concepts |
def request(label, selection, blocklist=()):
"""
Request an input from the user against an allowlist and/or a blocklist.
Will continue to request user until an acceptable value is entered.
...
Parameters
---
label: string
a instruction for the user
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def parse_vector(text: str, count: int) -> List[float]:
"""Parse a space-delimited vector."""
parts = text.split()
if len(parts) != count:
raise ValueError(f'{text!r} is not a {count}-dimensional vector!')
return list(map(float, parts)) | bigcode/self-oss-instruct-sc2-concepts |
def screen(a, b, max_possible=255):
"""Blend two arrays together using the 'screen' mode.
Good for combining color-tinted fluorescence images with brightfield, for example.
Parameter 'max_possible' refers to the brightest-possible value in the array.
E.g. 1 for images scaled from 0 to 1, or 255 for ima... | bigcode/self-oss-instruct-sc2-concepts |
def populated_attrs(lst):
"""Set with attr names which are not None in all objects in `lst`."""
attr_lists = [[name for name in obj.attr_lst \
if getattr(obj,name) is not None] for obj in lst]
return set.intersection(*(set(x) for x in attr_lists)) | bigcode/self-oss-instruct-sc2-concepts |
import random
def rand_byte(value=(0, 255)):
""" random byte """
if type(value) is int:
return value
elif type(value) is tuple:
return random.randint(value[0], value[1])
return random.randint(0, 255) | bigcode/self-oss-instruct-sc2-concepts |
def _check_params(p, speciesDict,xb):
"""
Check to see if any of the parameters in p fall outside the range
given in speciesDict or on the boundaries
**Parameters**
:p: (3,) ndarray
array with form [[N1, b1, z1], ...]
:speciesDict: dictionary
dictionary with properties g... | bigcode/self-oss-instruct-sc2-concepts |
def to_bytes(object):
"""
Convert an object to bytes-like object.
:param object:<object> The object to be converted.
:return:<bytes> A bytes-like object.
"""
if type(object) is str:
return object.encode()
return bytes(object) | bigcode/self-oss-instruct-sc2-concepts |
def _path_is_under_fragments(path, path_fragments):
"""Helper for _ensure_asset_types().
Checks that the given path is under the given set of path fragments.
Args:
path: String of the path to check.
path_fragments: List of string to check for in the path (in order).
Returns:
True/Fa... | bigcode/self-oss-instruct-sc2-concepts |
def n_wise(iterable, n):
"""Use to separate an iterable by n-elements groups"""
a = iter(iterable)
return zip(*[a] * n) | bigcode/self-oss-instruct-sc2-concepts |
from operator import xor
def find_bezier_t_intersecting_with_closedpath(bezier_point_at_t, inside_closedpath,
t0=0., t1=1., tolerence=0.01):
""" Find a parameter t0 and t1 of the given bezier path which
bounds the intersecting points with a provided closed
pa... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def latest(session: requests.Session, package: str) -> str:
"""Find latest version of package on PyPI.
Args:
package: Python package name.
Returns:
Latest package version.
"""
endpoint = f"https://pypi.org/pypi/{package}/json"
with session.get(endpoint) as re... | bigcode/self-oss-instruct-sc2-concepts |
def confirm(prompt, expected=('yes', 'y')):
""" Prompts the user to continue with the script
:param prompt: What to show the user
:param expected: Valid answers to continue
:return:
"""
response = input(prompt + f": ({'/'.join(expected)}) ")
if response.lower() not in expected:
print... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def load_bytes(storage: str, value: str) -> bytes:
"""
Given a storage, load bytes
Storage may be a 'raw', 'base64', 'base85', 'file'
Value is an encoded string or a path to local file
"""
if storage == 'raw':
return value.encode('utf-8')
if storage == 'base64':
... | bigcode/self-oss-instruct-sc2-concepts |
def handle_base_indices_arg(base_periods):
"""Converts arg to list if int, or raises error if not int or list."""
if not isinstance(base_periods, list):
if isinstance(base_periods, int):
return [base_periods]
else:
raise ValueError(
"base_periods must be i... | bigcode/self-oss-instruct-sc2-concepts |
def to_hashable(obj):
"""
Convert nested data structure (e.g. with dicts and lists)
to something immutable and hashable (tuples, ...)
"""
if isinstance(obj, (int, float, str)):
return obj
elif isinstance(obj, (list, tuple)):
return tuple(to_hashable(x) for x in obj)
elif isin... | bigcode/self-oss-instruct-sc2-concepts |
def parse_label_file(path_to_label_file):
"""Parses file with labels and converts into dict. For object detection."""
labels = open(path_to_label_file)
label_dict = {}
index = 0
for label in labels:
label_dict[str(label.strip())] = index
index = index + 1
return label_dict | bigcode/self-oss-instruct-sc2-concepts |
def customiseFor34120(process):
"""Ensure TrackerAdditionalParametersPerDetRcd ESProducer is run"""
process.load("Geometry.TrackerGeometryBuilder.TrackerAdditionalParametersPerDet_cfi")
return process | bigcode/self-oss-instruct-sc2-concepts |
import torch
def fake_image_batch(H: int, W: int, C: int) -> torch.Tensor:
"""Fake batch of images."""
return torch.rand(16, C, H, W) | bigcode/self-oss-instruct-sc2-concepts |
def yes_or_no(question):
"""
Ask the user a question that can be answered with yes or no.
:question: str, The question
:returns: bool, True if the answer was yes, False otherwise
"""
answer = input("{} (y/n): ".format(question)).lower()
if answer == "y":
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def _split_time_units_attr(units_attr: str) -> Tuple[str, str]:
"""Splits the time coordinates' units attr into units and reference date.
Parameters
----------
units_attr : str
The units attribute (e.g., "months since 1800-01-01").
Returns
-------
Tuple[s... | bigcode/self-oss-instruct-sc2-concepts |
from typing import AsyncIterable
from typing import Set
async def contains_all(async_gen: AsyncIterable[str], keywords: Set[str]) -> bool:
"""
Check wether an ``AsyncIterable[str]`` contains all of the given keywords. The keywords
can be embedded in some larger string. Return ``True`` as soon as all keywo... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def md5(filename):
"""Helper method to find the Md5 checksum of the file.
Args:
filename (str): Path to the file.
Returns:
str: Hexdigest of the file.
"""
try:
hash_md5 = hashlib.md5()
with open(filename, "rb") as in_file:
for chunk in... | bigcode/self-oss-instruct-sc2-concepts |
def convert_list_of_link_ids_to_network_nodes(network, link_ids: list):
"""
Extracts nodes corresponding to link ids in the order of given link_ids list. Useful for extracting network routes.
:param network:
:param link_ids:
:return:
"""
paths = []
connected_path = []
for link_id in ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def _merge_points(
player: Tuple[int, ...], opponent: Tuple[int, ...]
) -> Tuple[int, ...]:
"""Merge player and opponent board positions and return the combined points."""
return tuple(
i + j for i, j in zip(player, tuple(map(lambda n: -n, opponent[::-1])))
) | bigcode/self-oss-instruct-sc2-concepts |
def median(values):
"""Returns the central (median) value of a list.
If the list has an even amount of numbers,
then the average of the two
central numbers shall be returned.
Args:
values (list)
Returns:
float: The central value"""
if len(values) == 0:
return None
... | 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.