seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def import_optional(mod, import_from=None):
"""
import module or object 'mod', possibly from module 'import_from', and
return the module object or object. If the import raises
ModuleNotFoundError, returns None.
This method was written to support importing "optional" dependencies so
code can be... | bigcode/self-oss-instruct-sc2-concepts |
def fixedPoint(f, epsilon):
"""
f: a function of one argument that returns a float
epsilon: a small float
returns the best guess when that guess is less than epsilon
away from f(guess) or after 100 trials, whichever comes first.
"""
guess = 1.0
for i in range(100):
if abs(f(gues... | bigcode/self-oss-instruct-sc2-concepts |
def mdhtmlEsc(val):
"""Escape certain Markdown characters by HTML entities or span elements.
To prevent them to be interpreted as Markdown
in cases where you need them literally.
"""
return (
""
if val is None
else (
str(val)
.replace("&", "&")
... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def isbuiltin(object):
""" Convinience method to check if object is builtin. """
if inspect.isbuiltin(object):
return True
return getattr(object, '__module__', None) == 'builtins' | bigcode/self-oss-instruct-sc2-concepts |
def linkable_longitude(value):
"""
Append proper direction to a float represented longitude.
Example:
In: -83.472899
Out: 83.472899W
"""
value = float(value)
direction = 'E' if value > 0 else 'W'
value = abs(value)
return '{0}{1}'.format(value, direction) | bigcode/self-oss-instruct-sc2-concepts |
def _merge_set_groups(group_1, group_2):
"""
Mergers the two set groups.
Merging groups is a pre-operation of difference calculation, so copying is not required.
Parameters
----------
group_1 : `None`, `set` of `Any`
The first group to merge.
group_2 : `None`, `set` of `Any... | bigcode/self-oss-instruct-sc2-concepts |
def is_formatted_text(value: object) -> bool:
"""
Check whether the input is valid formatted text (for use in assert
statements).
In case of a callable, it doesn't check the return type.
"""
if callable(value):
return True
if isinstance(value, (str, list)):
return True
if... | bigcode/self-oss-instruct-sc2-concepts |
def lerp(channel1, channel2, current_step, total_steps):
"""
:lerp: linear interpolation function for traversing a gradient
:param channel1: int | the rgb channel for the starting color in the gradient.
:param channel2: int | the rgb channel for the ending color in the gradient.
:param curr... | bigcode/self-oss-instruct-sc2-concepts |
def getQLColliderNode(target):
"""
get the Qualoth qlColliderShape node related to the target.
:param target: `PyNode` node from where to get the related qlColliderShape node.
:return: `PyNode`
"""
if target.nodeType() == "transform":
target = target.getShape()
if not target: ret... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_models_json(service):
"""Get the models/versions from the service along with service version."""
r = requests.get(service + 'models?format=json')
service_version = r.headers['User-Agent'].split(' ')[0].split('/')[1]
return r.json(), service_version | bigcode/self-oss-instruct-sc2-concepts |
def norm255_tensor(arr):
"""Given a color image/where max pixel value in each channel is 255
returns normalized tensor or array with all values between 0 and 1"""
return arr / 255. | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
from typing import Dict
from typing import Union
def _read_dat_single_line(
package: str,
) -> Tuple[
int, Dict[str, Dict[str, Tuple[float, float, float]]], Dict[str, Union[str, tuple]]
]:
"""Extracts all relevant information from a single line of TRACAB's .dat file
(i.e. one ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import get_origin
from typing import Union
from typing import get_args
def is_Optional_type(t: type):
""" Check if the given type is Optional[] """
# https://stackoverflow.com/questions/56832881/check-if-a-field-is-typing-optional
# An Optional[] type is actually an alia... | bigcode/self-oss-instruct-sc2-concepts |
import shutil
def hfill(s, sequence):
"""Pad a string s with a sequence to fill the terminal horizontally."""
width = shutil.get_terminal_size().columns
return (s + sequence * ((width - len(s)) // len(sequence))) | bigcode/self-oss-instruct-sc2-concepts |
def path_exists(source, path, separator='/'):
"""Check a dict for the existence of a value given a path to it.
:param source: a dict to read data from
:param path: a key or path to a key (path is delimited by `separator`)
:keyword separator: the separator used in the path (ex. Could be "." for a
... | bigcode/self-oss-instruct-sc2-concepts |
def collision_check(tile_rects, bus_rect):
"""
Function to check for bus collisions
:param tile_rects: The nested list of all tile rects on the map
:param bus_rect: The rect of the shuttle bus
:return: Whether there is a collision or not as a boolean value
"""
for rects in tile_rects:
... | bigcode/self-oss-instruct-sc2-concepts |
def cbrt(x):
"""Cube root."""
if 0 <= x:
return x ** (1.0 / 3.0)
return -(-x) ** (1.0 / 3.0) | bigcode/self-oss-instruct-sc2-concepts |
def fit_line(x1,x2,y1,y2):
"""Return the coefficients a,b in y(x)=a*x+b, given two points"""
a = (y2-y1)/(x2-x1)
b = (x2*y1 - x1*y2)/(x2-x1)
return a,b | bigcode/self-oss-instruct-sc2-concepts |
def hex_nring(npix):
"""
For a hexagonal layout with a given number of pixels, return the
number of rings.
"""
test = npix - 1
nrings = 1
while (test - 6 * nrings) >= 0:
test -= 6 * nrings
nrings += 1
if test != 0:
raise RuntimeError(
"{} is not a vali... | bigcode/self-oss-instruct-sc2-concepts |
def restexpose(func):
"""
Decorate a function to clearly mark it as an exposed REST method
"""
setattr(func, 'restexposed', True)
setattr(func, 'exposed', False)
return func | bigcode/self-oss-instruct-sc2-concepts |
def read_True_steps_suffix_map(txtfile_name_with_path):
"""
This function reads the text file that contains all the steps in the configuration file, the
corresponding suffix, and whether they were completed or not.
Args:
txtfile_name_with_path: string, full name and path of the text file
R... | bigcode/self-oss-instruct-sc2-concepts |
def distance_between(origin_x, origin_y, destination_x, destination_y):
"""Calculate the distance between two points. """
return ((origin_x - destination_x)**2 + (origin_y - destination_y)**2)**.5 | bigcode/self-oss-instruct-sc2-concepts |
def isPrime(n):
"""Return True if n is a prime."""
if n > 2 and n % 2 == 0:
return False
for x in range(3, int(n**0.5 + 1), 2):
if n % x == 0:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def partition_hostname(hostname):
"""Return a hostname separated into host and domain parts."""
parts = hostname.partition('.')
return dict(hostname=parts[0],
domainname=parts[2] if parts[1] == '.' else None) | bigcode/self-oss-instruct-sc2-concepts |
def solve(tokens):
"""
Given a list of tokens where
each token is subdivided into
a frequency range, a character,
and a string, count the total
number of tokens that are valid
where a token is valid if and only
if the frequency of the character
appearing in the given string lies
... | bigcode/self-oss-instruct-sc2-concepts |
def remove_multiple_blank_lines(instring):
"""
Takes a string and removes multiple blank lines
"""
while '\n\n' in instring:
instring = instring.replace('\n\n', '\n')
return instring.strip() | bigcode/self-oss-instruct-sc2-concepts |
def parse_custom_command(command: str) -> list:
"""
Convert custom medusa command from string to list to be usable in subprocess.
:param command: Custom medusa command
:return: Parameters for medusa command
"""
command_split = command.split(" ")
command_list = []
for parameter in comma... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_element_from_list(element_list):
"""Returns a random element from list."""
return element_list[random.SystemRandom().randint(0, len(element_list) - 1)] | bigcode/self-oss-instruct-sc2-concepts |
import math
def sqrt(x):
"""Return sqare root of input"""
square = math.sqrt(x)
return square | bigcode/self-oss-instruct-sc2-concepts |
def get_or_create_metrics(run):
"""Returns the "subfolder" of the HDF5 file "run/metric" where metrics may be stored."""
if "metrics" not in run:
run.create_group("metrics")
return run["metrics"] | bigcode/self-oss-instruct-sc2-concepts |
import random
def flip_coin(bias=0.5):
"""Flip a biased coin."""
return random.random() <= bias | bigcode/self-oss-instruct-sc2-concepts |
def rev_c(seq):
"""
simple function that reverse complements a given sequence
"""
tab = str.maketrans("ACTGN", "TGACN")
# first reverse the sequence
seq = seq[::-1]
# and then complement
seq = seq.translate(tab)
return seq | bigcode/self-oss-instruct-sc2-concepts |
def refresh(session, *entities):
"""Refresh entities from the current session."""
if not entities:
return []
return [session.query(entity.__class__).get(entity.id) for entity in entities] | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_spaces(text):
"""
Remove all the tabs, spaces, and line breaks from the raw text
Args:
text(str) -- raw text
Returns:
text(str) -- text clean from tabs, and spaces
"""
# remove \t, \n, \r
text = text.replace("\t", "").replace("\r", "").replace("\n", "")... | bigcode/self-oss-instruct-sc2-concepts |
from io import StringIO
from typing import Tuple
import re
import json
def parse_timewarrior_data(input_stream: StringIO) -> Tuple[dict, list]:
"""
Parse data passed to report from timewarrior.
"""
header = 1
config = dict()
body = ""
for line in input_stream.readlines():
# Extract... | bigcode/self-oss-instruct-sc2-concepts |
def mint(string):
"""
Convert a numeric field into an int or None
"""
if string == "-":
return None
if string == "":
return None
return int(string) | bigcode/self-oss-instruct-sc2-concepts |
import string
def remove_punctuation_and_lower(s):
"""
This will return a string without puntuation and all words are in lower-case.
The punctuation symbols are get from the module 'string'.
The set of punctuation symbols are '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
"""
return s.translate(str.make... | bigcode/self-oss-instruct-sc2-concepts |
def to_bool(bool_str):
"""Convert a string to bool.
"""
return True if bool_str.lower() == 'true' else False | bigcode/self-oss-instruct-sc2-concepts |
def hs_library_pattern(name, mode = "static", profiling = False):
"""Convert hs-libraries entry to glob patterns.
Args:
name: The library name. E.g. HSrts or Cffi.
mode: The linking mode. Either "static" or "dynamic".
profiling: Look for profiling mode libraries.
Returns:
L... | bigcode/self-oss-instruct-sc2-concepts |
import struct
import fcntl
import termios
def terminal_size() -> tuple:
"""
Get terminal width and height
"""
packed_struct = struct.pack('HHHH', 0, 0, 0, 0)
h, w, hp, wp = struct.unpack('HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ,
packed_struct)... | bigcode/self-oss-instruct-sc2-concepts |
def split_by_lines(text, remove_empty=False):
"""
Split text into lines. Set <code>remove_empty</code> to true to filter out
empty lines
@param text: str
@param remove_empty: bool
@return list
"""
lines = text.splitlines()
return remove_empty and [line for line in lines if line.strip()] or lines | bigcode/self-oss-instruct-sc2-concepts |
import re
def expand_distances(d_expression):
"""
Check if a distance expression contains at least one term d[x]. If yes, then
the distances are expanded and we assume the user has specified an
expression such as d[0] + d[2].
"""
regexpr = re.compile(r'.*d\[\d*\].*')
if regexpr.match(d_exp... | bigcode/self-oss-instruct-sc2-concepts |
def eliminate_from_neighbors(csp, var) :
"""
Eliminates incompatible values from var's neighbors' domains, modifying
the original csp. Returns an alphabetically sorted list of the neighboring
variables whose domains were reduced, with each variable appearing at most
once. If no domains were reduce... | bigcode/self-oss-instruct-sc2-concepts |
def generate_triangular_board(edge=7, mirrored=False):
"""
Creates a board with a shape of equilateral triangle.
The size of the triangle's side (in fields) is specified by the edge argument.
By default the resulting board will be a triangle pointing down (pointy top)
of right (flat top). Setting m... | bigcode/self-oss-instruct-sc2-concepts |
def compose(func_1, func_2, unpack=False):
"""
compose(func_1, func_2, unpack=False) -> function
The function returned by compose is a composition of func_1 and func_2.
That is, compose(func_1, func_2)(5) == func_1(func_2(5))
"""
if not callable(func_1):
raise TypeError("First argum... | bigcode/self-oss-instruct-sc2-concepts |
import logging
import json
def loadjson(jsonfile):
"""Load content from json file as dictionary.
Parameters
----------
jsonfile : str
Path to json file to be read.
Returns
-------
d : dict
Dictionary of the content stored in the json file.
"""
logging.info("... | bigcode/self-oss-instruct-sc2-concepts |
def datetime_to_ds_nodash(dt):
"""Convert a Python datetime object to a string with the format YYYYMMDD"""
return dt.strftime('%Y%m%d') | bigcode/self-oss-instruct-sc2-concepts |
def init_model_with_data(model_obj, data_dict):
"""instantiate the generated tfp model object with data
Parameters
----------
model_obj : tfd.Distribution
an un-instantiated model object
data_dict : dict
data for the model
Returns
-------
tfd.Distribution
... | bigcode/self-oss-instruct-sc2-concepts |
def quintic_easein(pos):
"""
Easing function for animations: Quintic Ease In
"""
return pos * pos * pos * pos * pos | bigcode/self-oss-instruct-sc2-concepts |
def _format_exception(exception):
"""Formats the exception into a string."""
exception_type = type(exception).__name__
exception_message = str(exception)
if exception_message:
return "{}: {}".format(exception_type, exception_message)
else:
return exception_type | bigcode/self-oss-instruct-sc2-concepts |
def query_attr_where(params, table_ref=True):
"""
Construct where conditions when building neighbors query
Create portion of WHERE clauses for weeding out NULL-valued geometries
Input: dict of params:
{'subquery': ...,
'numerator': 'data1',
'denominator': ... | bigcode/self-oss-instruct-sc2-concepts |
def round_nearest(value, multiple_of):
"""round to `multiple_of` value.
based on: https://stackoverflow.com/a/28425782/574981
"""
return round(value / multiple_of) * multiple_of | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_connection_string(credential_path):
"""Converts credentials JSON to a connection string."""
with open(credential_path) as file_ptr:
credential_dict = json.load(file_ptr)
connection_string = credential_dict['connection_string']
full_connection_string = connection_string.f... | bigcode/self-oss-instruct-sc2-concepts |
def sextodec(xyz, delimiter=None):
"""Decimal value from numbers in sexagesimal system.
The input value can be either a floating point number or a string
such as "hh mm ss.ss" or "dd mm ss.ss". Delimiters other than " "
can be specified using the keyword ``delimiter``.
"""
divisors = [1, 60.0, 3600... | bigcode/self-oss-instruct-sc2-concepts |
def from_db(x):
"""
Convert from decibels to original units.
Inputs:
- x [float]: Input data (dB)
Outputs:
- y [float]: Output data
"""
return 10**(0.1*x) | bigcode/self-oss-instruct-sc2-concepts |
def index(seq):
"""
Build an index for a sequence of items. Assumes
that the items in the sequence are unique.
@param seq the sequence to index
@returns a dictionary from item to position in the sequence
"""
return dict((k,v) for (v,k) in enumerate(seq)) | bigcode/self-oss-instruct-sc2-concepts |
def calc_variables(df, var_list):
"""Calculate area-weighted values for variables.
Formula: x_pre=A_intersect1 / A_pre * x_bg1 + A_intersect2 / A_pre * x_bg2
Args:
df (DataFrame): the dataframe containing census spatially merged with precincts
var_list (list): names of variables to calcul... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def request_ct(url):
"""Performs a get request that provides a (somewhat) useful error message."""
try:
response = requests.get(url)
except:
raise IOError(
"Couldn't retrieve the data, check your search expression or try again later."
)
else:
... | bigcode/self-oss-instruct-sc2-concepts |
def replace_spaces(text):
"""
Replace spaces with a dash.
"""
if not isinstance(text, str):
return text
return text.replace(" ", "-") | bigcode/self-oss-instruct-sc2-concepts |
def log_format_metadata(metadata):
"""Return a string representation of the metadata formatted for log output.
"""
return ", ".join("{}={}".format(k, v) for k, v in metadata.items()) | bigcode/self-oss-instruct-sc2-concepts |
import math
def shubert04(ind):
"""Shubert04 function defined as:
$$ f(x) = \sum_{i=1}^n \sum_{j=1}^5 j cos((j+1)x_i) + j $$
with a search domain of $-10 < x_i < 10, 1 \leq i \leq n$.
"""
return sum(( sum((-j * math.cos((j+1) * ind[i] + j) for j in range(1, 6))) for i in range(len(ind)))), | bigcode/self-oss-instruct-sc2-concepts |
def safe_sum(v1, v2):
"""Sum two integers (string type) accounting for the possibility that one or both
is missing; returns an integer."""
if v1:
if v2:
return int(v1) + int(v2)
else:
return int(v1)
if v2:
return int(v2)
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def render_services(args, df):
""" replace service number with service name, for common services"""
for col in ['srcport', 'dstport']:
df[col][df[col] == '22'] = 'ssh'
df[col][df[col] == '23'] = 'telnet'
df[col][df[col] == '53'] = 'domain'
df[col][df[col] == '80'] = 'http'
... | bigcode/self-oss-instruct-sc2-concepts |
def tuple_add(tuple_a: tuple, tuple_b: tuple) -> tuple:
"""Return the result of the addition of two tuples."""
return tuple(map(lambda x, y: x + y, tuple_a, tuple_b))
# Source: https://stackoverflow.com/questions/497885/python-element-wise-tuple-operations-like-sum | bigcode/self-oss-instruct-sc2-concepts |
def signal_percent_to_dbm(percent: int) -> int:
"""
arbitrary conversion factor from Windows WiFi signal % to dBm
assumes signal percents map to dBm like:
* 100% is -30 dBm
* 0% is -100 dBm
Parameters
----------
percent: int
signal strength as percent 0..100
Returns
--... | bigcode/self-oss-instruct-sc2-concepts |
def fibonacci(n):
"""
This is the original function, it will be used to compare execution times.
"""
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2) | bigcode/self-oss-instruct-sc2-concepts |
def find_by_name(name, items):
"""
Find the object with the specified name attribute.
:param name: str: name to look for
:param items: [object]: list of objects to look for
:return: first item matching name or None if not found
"""
for item in items:
if item.name == name:
... | bigcode/self-oss-instruct-sc2-concepts |
def disc(x):
"""
Returns 'x' rounded to the nearest integer.
"""
return int(round(x)) | bigcode/self-oss-instruct-sc2-concepts |
def _read_filepath(source: str) -> str:
"""
Read file contents
"""
with open(source, 'r', encoding='utf-8') as infile:
contents = infile.read()
return contents | bigcode/self-oss-instruct-sc2-concepts |
def is_podcast_series_id(item_id):
"""Validate if ID is in the format of a Google Music series ID."""
return len(item_id) == 27 and item_id.startswith('I') | bigcode/self-oss-instruct-sc2-concepts |
import torch
def format_abstract_tensile(cycles, predictions):
"""
Format abstracted tensile test data, where only the yield strength
and ultimate tensile strength are available.
This method relies on the input cycles being:
* 0: in the elastic regime
* 1: for the first 1/2 of the remaining t... | bigcode/self-oss-instruct-sc2-concepts |
def get_set_vertices_u_0(g_or_n):
"""Get indexes for the belief vector:"
0: capture
1,...n: vertices"""
if isinstance(g_or_n, int):
n = g_or_n
else:
n = len(g_or_n.vs)
V = list(range(1, n + 1))
V_ext = [0] + V
return V_ext | bigcode/self-oss-instruct-sc2-concepts |
def instance_dist(novel, word):
"""
Takes in a particular word, returns a list of distances between each instance of that word in the novel.
>>> from gender_novels import novel
>>> summary = "Hester was her convicted of adultery. "
>>> summary += "which made her very sad, and then her Arthur was als... | bigcode/self-oss-instruct-sc2-concepts |
def define_constants_for_fixed_srht_with_momentum(n, d, m):
"""
As defined in Jonathan Lacotte, Mert Pilanci, Optimal Randomized First-Order Methods for Least-Squares Problems (https://arxiv.org/abs/2002.09488)
Args:
n: Number of rows of data matrix
d: Number of columns of data matrix
... | bigcode/self-oss-instruct-sc2-concepts |
def _get_action_profile(x, indptr):
"""
Obtain a tuple of mixed actions from a flattened action profile.
Parameters
----------
x : array_like(float, ndim=1)
Array of flattened mixed action profile of length equal to n_0 +
... + n_N-1, where `out[indptr[i]:indptr[i+1]]` contains play... | bigcode/self-oss-instruct-sc2-concepts |
def fromSI(value: str) -> float:
"""converts from SI unit values to metric
Args:
value (str): a value in SI units, e.g. 1.3u
Returns:
float: the value in metric units.
"""
return float(value.replace("u", "e-6")) | bigcode/self-oss-instruct-sc2-concepts |
def _get_jsonld_property(jsonld, property, default=None):
"""Return property value from expanded JSON-LD data."""
value = jsonld.get(property)
if not value:
return default
if isinstance(value, list) and len(value) == 1 and isinstance(value[0], dict) and "@value" in value[0]:
value = valu... | bigcode/self-oss-instruct-sc2-concepts |
def dfa_word_acceptance(dfa: dict, word: list) -> bool:
""" Checks if a given **word** is accepted by a DFA,
returning True/false.
The word w is accepted by a DFA if DFA has an accepting run
on w. Since A is deterministic,
:math:`w ∈ L(A)` if and only if :math:`ρ(s_0 , w) ∈ F` .
:param dict df... | bigcode/self-oss-instruct-sc2-concepts |
def avseth_gassmann(ksat1, kf1, kf2, kmin, phi):
"""
Applies the Gassmann equation.
Args:
ksat1 (float): Ksat1.
kf1 (float): Kfluid1.
kf2 (float): Kfluid2.
kmin (float): Kmineral.
phi (float): Porosity.
Returns:
float: Ksat2.
"""
s = ksat1 / (km... | bigcode/self-oss-instruct-sc2-concepts |
import re
def snakify(name: str, *, sep: str = '_',
_re_upper=re.compile(r'([A-Z])')) -> str:
"""Lowercase ``name`` adding ``sep`` before in-word-uppercase letters.
>>> snakify('CamelCase')
'camel_case'
"""
return (name[:1] + _re_upper.sub(rf'{sep}\1', name[1:])).lower() | bigcode/self-oss-instruct-sc2-concepts |
def model_values(model):
"""Get the values out of a Z3 model.
"""
return {
d.name(): model[d]
for d in model.decls()
} | bigcode/self-oss-instruct-sc2-concepts |
def add_suffix(string,suffix):
"""if suffix, appends suffix to string with underscore. otherwise return it unchanged."""
if suffix is None:
return string
else:
return "{}_{}".format(string, suffix) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _collate_fn(batch):
"""
Custom collate function to manually specify how samples are batched from the DataLoader.
See https://pytorch.org/tutorials/beginner/data_loading_tutorial.html#iterating-through-the-dataset
for an introduction.
In particular, the batch represents a collection of
... | bigcode/self-oss-instruct-sc2-concepts |
def findTerm(ont,name):
"""
Searches an ontology for a specific term name and returns the first hit
Args:
ont (pronto Ontology): Ontology to search
name (str): Search query
Returns:
pronto Ontology: Term that matched name or None if not found
"""
for term in ont:
if term.name == name:
return term
re... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
def find_file(path="~", file="LabRecorderCLI.exe") -> Union[Path, None]:
"""find a file recursively
args
----
path:str
the root folder
file:str
the file name
returns
-------
filepath: Union[Path, None]
... | bigcode/self-oss-instruct-sc2-concepts |
def make_strategy_id(strategy):
"""
Return a string that will identify a strategy - just concatenate
the numbers of transfers per gameweek.
"""
strat_id = ",".join([str(nt) for nt in strategy[0].values()])
return strat_id | bigcode/self-oss-instruct-sc2-concepts |
import torch
def focal_loss(input,
target,
reduction='mean',
beta=0.5,
gamma=2.,
eps=1e-7,
**kwargs):
"""
Focal loss, see arXiv:1708.02002
input: [B, 1, H, W] tensor that contains predictions to compare
target: [B, 1, H,... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def create_xyz_tensor(sl):
"""
Return an 32 x 32 x 32 x 3 tensor where each len 3 inner tensor is
the xyz coordinates of that position
"""
incr_t = torch.arange(sl, dtype=torch.float64)
z = incr_t.expand(sl, sl, sl).unsqueeze(3)
y = incr_t.unsqueeze(1).expand(sl, sl, sl).unsqu... | bigcode/self-oss-instruct-sc2-concepts |
def _build_rtw88_config(rtw88_config):
"""Builds the wifi configuration for the rtw88 driver.
Args:
rtw88_config: Rtw88Config config.
Returns:
wifi configuration for the rtw88 driver.
"""
result = {}
def power_chain(power):
return {
'limit-2g': power.limit_2g,
'limit-5g-1': po... | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_process_id_and_name(header):
"""Get process id from header."""
m_process_num = re.match(r'(.*)[(]\s*(\d+)[)]', header)
if not m_process_num:
return None
return int(m_process_num.group(2)), m_process_num.group(1).strip() | bigcode/self-oss-instruct-sc2-concepts |
def get_n_control_ts(model):
"""Get number of timesteps in the model's control variable"""
return len(model.wells.event_dates) | bigcode/self-oss-instruct-sc2-concepts |
def allow(whitelist):
"""
Decorates a handler to filter all except a whitelist of commands
The decorated handler will only be called if message.command is in the
whitelist:
@allow(['A', 'B'])
def handle_only_a_and_b(client, message):
pass
Single-item whitelists may be ... | bigcode/self-oss-instruct-sc2-concepts |
def stats_file_values(pop_size, gene_number, generation_number, diversity, viability_ratios, viability_ratios_db):
"""Return a dict usable with csv.DictWriter for stats file"""
values = {
'popsize': pop_size,
'genenumber': gene_number,
'generationnumber':generation_number,
... | bigcode/self-oss-instruct-sc2-concepts |
def selection_sort_counting(A):
"""
Instrumented Selection Sort to return #swaps, #compares.
"""
N = len(A)
num_swap = num_compare = 0
for i in range(N - 1):
min_index = i
for j in range(i + 1, N):
num_compare += 1
if A[j] < A[min_index]:
m... | bigcode/self-oss-instruct-sc2-concepts |
def to_fahrenheit(temp):
"""
Converts a temperature in celsius to fahrenheit.
"""
return (temp * 1.8) + 32 | bigcode/self-oss-instruct-sc2-concepts |
import re
def regression_test_almost_match_file_names(old_fname, new_fname):
"""Checks whether the two file names match (if the files match up to name_i*.ext, it counts
as if they match)
"""
if old_fname == new_fname:
return True
if '_i' in old_fname:
if re.sub('_i[0-9]*', '', old... | bigcode/self-oss-instruct-sc2-concepts |
def site_client(client, site):
"""Returns a client tied to a specific site."""
client.config['default_site'] = site['id']
client.default_site = site['id']
return client | bigcode/self-oss-instruct-sc2-concepts |
def time_frog_jumps(other_side_position: int, leaf_positions: list) -> int:
"""
Returns the earliest time that a frog can jump to the other side of the river.
Uses a Set to store unique values from leaf_positions[].
When the size equals to other_side_position, means the leaves have covered all position... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def calc_pad_value(src_value: int,
dst_value: int) -> Tuple[int, int]:
"""
Calculate a padding values for a pair of source and destination numbers.
Parameters:
----------
src_value : int
Source number.
dst_value : int
Destination num... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_line(line):
""" parse model.js line-by-line using voodoo-regexp:
'{title: "Bungeejumper", url: "modellen/Bungeejumper.xml"},\n'
=> ["Bungeejumper", "modellen/Bungeejumper.xml"]
[\"|'] --> match " or '
(.[^'|\"]*) --> group: match anything except " or '
[\"|'] ... | 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.