seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import torch
def generate_final_context_matrix(context_matrix_dict, ending_key_to_exclude="_nokg"):
"""Takes the average of the context matrices where their key does not end
in ending_key_to_exclude.
Args:
context_matrix_dict: Dict of batch x M x K x H matrices of embeddings for each candidate
... | bigcode/self-oss-instruct-sc2-concepts |
def _columns(cursor, table):
"""Return the columns of a table as a list."""
cursor.execute('''
SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = %s
''', (table, ))
return [column['column_name'] for column in cursor.fetchall()] | bigcode/self-oss-instruct-sc2-concepts |
import json
def pre_proc(batch, **kwargs):
"""
Pre-processing of batch.
Assumes format (n_samples, n_channels, height, width).
"""
#opening stats file
with open(kwargs["stats_fp"]) as f:
stats = json.load(f)
#converting keys from str to int
stats = {int(k): v for k, v in stats... | bigcode/self-oss-instruct-sc2-concepts |
def _strip_match(matchobj):
"""Strip whitespace from a RE-match-object
Parameters
----------
matchobj : re.Match
Match-object of regular-expression.
Returns
-------
str
Stripped string
"""
return matchobj.group(0).strip() | bigcode/self-oss-instruct-sc2-concepts |
import math
def equal(a, b, abstol=1e-16, reltol=0, mathlib=math):
"""Check if two values are equal.
By default, we test with (absolute) tolerances. This can be changed as desired.
For exact equality, set abstol=reltol=0.
mathlib allows to specify the module from which isclose should be used: numpy,... | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_json(res):
"""Return json response as a dictionary or list."""
return json.loads(res.data.decode('utf-8')) | bigcode/self-oss-instruct-sc2-concepts |
def _slice_ndfilter(data, filter_func, slices, args, size, footprint, kwargs):
"""
Helper function passing image slices to `scipy.ndimage` filters that is
pickleable for threading with `multiprocessing`
Parameters
----------
data, filter_func, args, size, footprint :
See `multiproc... | bigcode/self-oss-instruct-sc2-concepts |
def isIntraChrom(read1, read2):
"""
Return true is the reads pair is intrachromosomal
read1 : [AlignedRead]
read2 : [AlignedRead]
"""
if read1.tid == read2.tid:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def parse_tract_fips(tract_fips):
"""
turn a full tract fips code into a tuple of state, county, tract
"""
return tract_fips[:2], tract_fips[2:5], tract_fips[5:] | bigcode/self-oss-instruct-sc2-concepts |
def _get_indices(item, seq):
"""Return the indices where `item` occurs in `seq`
Returns
-------
Generator[int]"""
return (n for n, x in enumerate(seq) if x == item) | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json_file(path):
"""Returns JSON parsed data from file."""
with open(path, "r") as file:
return json.load(file) | bigcode/self-oss-instruct-sc2-concepts |
def reaction_int2str( reaction_int, silent=True ):
#;{{{
"""
Translate reaction number to reaction string.
The idea of this functions is to ensure that in all function within
this file the same reaction is meant when referring to reaction 3
(or any other number).
The integer provided to this f... | bigcode/self-oss-instruct-sc2-concepts |
def z_to_params(z, P, n_m, n_t):
"""Convert single vectors of unknowns z into separate vectors of unknowns."""
lambda_ = z[0:n_m]
beta = z[n_m : 2 * n_m]
betat = z[2 * n_m : 2 * n_m + n_t]
T = z[2 * n_m + n_t :]
return lambda_, beta, betat, T | bigcode/self-oss-instruct-sc2-concepts |
def _ParamExists(param_obj, param_name):
"""Tests whether param_name is contained in param_obj."""
if not param_obj:
return
for k, _ in param_obj.IterParams():
if k == param_name:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def cleanup_frame(frame):
"""Make the columns have better names, and ordered in a better order."""
frame = frame.rename(columns={"Non- Hispanic white": "White"})
frame = frame.reindex(columns=["Asian", "White", "Hispanic", "Black"])
return frame | bigcode/self-oss-instruct-sc2-concepts |
def get_service_dependency_tree(yml_dict, run_exclude_images):
"""Method to generate a dict of services and services it depends on
:param yml_dict: dict generated from docker-compose yml
:type yml_dict: dict
:param run_exclude_images: List of name of dependency services which
... | bigcode/self-oss-instruct-sc2-concepts |
def get_job_tasks(rank, ranks, tasks_tot):
"""
Return a tuple of job task indices for a particular rank.
This function distribute the job tasks in tasks_tot
over all the ranks.
Note
----
This is a primerly a MPI help function.
Parameters
----------
rank : int
Current M... | bigcode/self-oss-instruct-sc2-concepts |
def _graph_string(graph):
"""Helper to serialize a graph to string."""
if graph:
return graph.as_graph_def(add_shapes=True).SerializeToString()
else:
return b'' | bigcode/self-oss-instruct-sc2-concepts |
def filtered_packageversion(version, revision):
""" Emit "version-revision" if version and revision are not null
else "version" if version is not null
else ""
"""
return "" if (not version or version == "") else version if (not revision or revision == "") else version + "-" + revision | bigcode/self-oss-instruct-sc2-concepts |
def checkSameLoop(ra, rb):
"""
check if two anchors are exact same
"""
if ra[1] == rb[1] and ra[2] == rb[2] and ra[4] == rb[4] and ra[5] == rb[5]:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def uniqueness(container):
"""
Checks if the container is unique.
In case of uniqueness it returns True
"""
return len(container) == len(list(set(container))) | bigcode/self-oss-instruct-sc2-concepts |
def create_query_parameters(filter_expressions: list, sorting_expressions: list) -> dict:
"""
Create query parameters
Parameters
----------
filter_expressions: List[dict]
Filtering parameters [{'name': draft, 'op': gt, 'val':30}]
sorting_expressions: List[dict]
Sorting parameter... | bigcode/self-oss-instruct-sc2-concepts |
def _write_triggers_from_sequence_free_spell(array, trigger_file):
"""
Write triggers from free spell.
Helper Function to write trigger data to provided trigger_file.
It writes in the following order:
(I) presented letter, (II) timestamp
"""
for i in array:
# extract the lett... | bigcode/self-oss-instruct-sc2-concepts |
def string_split(input_string):
"""Split a string based on the presence of commas
Each line of the file is read in as a single string, so it is necessary
to separate this string into two categories: time and voltage. Given that
the file is comma separated, this function is used to split each string
... | bigcode/self-oss-instruct-sc2-concepts |
def expand_id_map(id_map, all_ids):
""" Ensures all ids within all_ids are included as keys in the mapping """
unmapped_ids = list(set(all_ids).difference(id_map.keys()))
for i in unmapped_ids:
id_map[i] = i
return id_map | bigcode/self-oss-instruct-sc2-concepts |
def MakeRanges(codes):
"""Turn a list like [1,2,3,7,8,9] into a range list [[1,3], [7,9]]"""
ranges = []
last = -100
for c in codes:
if c == last+1:
ranges[-1][1] = c
else:
ranges.append([c, c])
last = c
return ranges | bigcode/self-oss-instruct-sc2-concepts |
def indexOf(a, b):
"""Return the first index of b in a."""
for i, j in enumerate(a):
if j == b:
return i
else:
raise ValueError('sequence.index(x): x not in sequence') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
import inspect
import types
def get_class_that_defined_method(method: object) -> Optional[object]:
"""Retrieves the class that defines a method.
Taken from https://stackoverflow.com/a/25959545/4293396
:param method: The method
:return: The class that defines the method
... | bigcode/self-oss-instruct-sc2-concepts |
def aes_to_scale(var):
"""
Look up the scale that should be used for a given aesthetic
"""
if var in {'x', 'xmin', 'xmax', 'xend', 'xintercept'}:
var = 'x'
elif var in {'y', 'ymin', 'ymax', 'yend', 'yintercept'}:
var = 'y'
return var | bigcode/self-oss-instruct-sc2-concepts |
import queue
def get_all_from_queue(q):
"""
Returns at least one element from the queue, tries to return as many as possible.
:param q: The queue to get elements from
:return: A list of elements fetched from the queue
"""
data = [q.get()]
while True:
try:
data.append(q.... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def find_now(start):
"""
Calculate the amount of time passed from the start
of the algorithm
"""
return str(datetime.now() - start) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _get_badchars(data: str) -> str:
"""Returns the badchars contained in a string."""
regex = r"[^a-zA-Z0-9\s]"
match = re.findall(regex, data)
match = sorted(set(match)) # unique and sort
return "".join(match) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def to_datetime(timestamp):
"""
Convert MediaWiki timestamp to a datetime object.
Assumes the format to be in "MW" ISO with "Z" instead of +00:00 for timezone.
:type timestamp: str
:rtype datetime
"""
return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ') | bigcode/self-oss-instruct-sc2-concepts |
def get_datastore_id(client, name):
"""return the id of a datastore
arguments:
client -- an authenticated trove client
name -- the name of the datastore to find
returns:
the id of the datastore or None if not found
"""
try:
store = client.datastores.find(name=name)
retu... | bigcode/self-oss-instruct-sc2-concepts |
def _populate_set_with_patches(new_set, unused_patches, bundle, logger):
"""
Adds entries to set new_set from the bundle's patch_order if they are unique.
Entries that are not unique are logged as warnings.
Returns True if warnings were logged; False otherwise
"""
warnings = False
try:
... | bigcode/self-oss-instruct-sc2-concepts |
def wav_packing_string(num_frames, num_channels, bit_depth):
"""
Get the string for packing or unpacking a given number of frames using the struct module.
Args:
num_frames: int - The number of frames to cover in the packing string
num_channels: int - The number of channels in the audio, e.... | bigcode/self-oss-instruct-sc2-concepts |
def charcount(string, char):
"""counts occurrences of c at the start of s."""
i = 0
while i < len(string) and string[i] == char:
i += 1
return i | bigcode/self-oss-instruct-sc2-concepts |
def sequence2dict(seq):
"""Helper function for cx_Oracle.
For each element in the sequence, creates a dictionary item equal
to the element and keyed by the position of the item in the list.
>>> sequence2dict(("Matt", 1))
{'1': 'Matt', '2': 1}
Source:
http://www.gingerandjohn.com/archives/2... | bigcode/self-oss-instruct-sc2-concepts |
import pkg_resources
def get_highest_installed(project_name):
"""Return highest version of installed package.
@param project_name: PyPI project name
@type project_name: string
@return: string of highest installed version
"""
environment = pkg_resources.Environment()
return environment[p... | bigcode/self-oss-instruct-sc2-concepts |
def allelic_balance(gt):
"""Return allelic balance from genotype value."""
if not gt.get("dp"):
return 0.0
else:
return gt.get("ad") / gt.get("dp") | bigcode/self-oss-instruct-sc2-concepts |
def get_coordinates(axis_value, ranges):
"""Get coordinates pairs from axis_value and other_values."""
start, end = ranges
return [(axis_value, other_value) for other_value in range(start, end + 1)] | bigcode/self-oss-instruct-sc2-concepts |
def generate_mock_method(method):
"""Generate MOCK_METHOD google macro."""
return (
f"MOCK_METHOD({method.ret_type}, {method.name}, "
f"({method.parameters}), ({method.qualifiers}));"
) | bigcode/self-oss-instruct-sc2-concepts |
def _calc_overlap(geom1, geom2):
"""Return area overlap"""
return geom1.intersection(geom2).area | bigcode/self-oss-instruct-sc2-concepts |
def url_from_icon_id(id: str) -> str:
"""Get a downloadable URL from a string ID
Args:
id (str): Flaticon ID
Returns:
str: URL pointing to the .png file for this icon
"""
return f"https://image.flaticon.com/icons/png/512/{id[:-3]}/{id}.png" | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
from typing import Tuple
def _normalize_slice_key(key: Any) -> Tuple:
""" Normalizes slice key into always being a top-level tuple.
Args:
key: Slicing key that is passed within __getitem__.
Returns:
Expanded slice as a tuple.
"""
if not isinstance(key, tupl... | bigcode/self-oss-instruct-sc2-concepts |
import random
def chunk_list(examples, chunk_size=2, pad_to_divisible=True):
"""
Args:
examples: iterable, examples grouped by image/video
chunk_size: int, number of examples in each chunk.
pad_to_divisible: bool, pad the examples to be divisible by chunk_size.
>>> test_examples = ... | bigcode/self-oss-instruct-sc2-concepts |
def snakecase_key(key):
"""
Convert the key to snake_case by replacing ':' with '_'
and remove any leading '_'
This is so the keys are valid as Python kwargs and can be used to filter
the page models on on keys in the wp_post_meta which is a JSONField().
"""
return (
str(key) # some... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def testfile_checker(pytester, checker):
"""Return callable that compares pre existing file to testfile.
This fixture is designed to run in a test case that injects the
pytester fixture. pytester sets the current working directory
to a temporary directory while it is active. ... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def clsname(obj):
"""Get objects class name.
Args:
obj (:obj:`object`):
The object or class to get the name of.
Returns:
(:obj:`str`)
"""
if inspect.isclass(obj) or obj.__module__ in ["builtins", "__builtin__"]:
return obj.__name__
return o... | bigcode/self-oss-instruct-sc2-concepts |
def getAxis(node):
"""Parse rotation axis of a joint."""
axis = [0.0, 0.0, 0.0]
axisElement = node.getElementsByTagName('axis')[0].getAttribute('xyz').split()
axis[0] = float(axisElement[0])
axis[1] = float(axisElement[1])
axis[2] = float(axisElement[2])
return axis | bigcode/self-oss-instruct-sc2-concepts |
def preprocess_channel_types(channel_types):
"""
Preprocesses the given channel type values.
Parameters
----------
channel_types : `None`, `iterable` of `int`
Channel types to limit a slash command parameter to.
Returns
-------
processed_channel_types : `None` or `tuple... | bigcode/self-oss-instruct-sc2-concepts |
def cipher(text, shift, encrypt=True):
"""
Function to encipher or decipher the string by using different shift number.
Parameters
----------
text : string
A string that you wish to encipher or decipher.
shift : integer
An integer that you wish to shift.
encrypt : boolea... | bigcode/self-oss-instruct-sc2-concepts |
def get_sorted_key_index(class_key, class_dict):
"""
Given class_dict, returns an index that would result from ordering the keys
in class_dict according to their values and accessing one of the keys (class_key).
That index can be used to access multiclass prediction scores
"""
assert(isinstance... | bigcode/self-oss-instruct-sc2-concepts |
def build_dummy_module_call(group_name, fifo_name, module_in, PE_ids):
"""Build the call of the dummy module
Parameters
----------
group_name: str
fifo_name: str
module_in: int
PE_ids: list
"""
dir_str = "out" if module_in == 0 else "in"
lines = []
lines.append("\n")
li... | bigcode/self-oss-instruct-sc2-concepts |
def fact(n):
"""Calculate the value of n factorial."""
# n! = n*(n-1)*...*2*1
product = 1
for i in range(1, n+1):
product *= i
return product | bigcode/self-oss-instruct-sc2-concepts |
def has_variable(obj, variable):
"""Tries to check if an object has a variable."""
if hasattr(obj, "has_variable"):
return obj.has_variable(variable)
return False | bigcode/self-oss-instruct-sc2-concepts |
def _check_lunch_hours(time, lunch_start, lunch_end):
"""Checks if the time is during lunch"""
return (time < lunch_start) or (time >= lunch_end) | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_deal_code(deal_code):
"""
Converts an sku and it's quantity into separate parts.
eg.
A -> 1, A
3A -> 3, A
Args:
deal_code (string) - contains sku item and an optional quantity
(defaults to 1)
Returns:
int - quantity of item
... | bigcode/self-oss-instruct-sc2-concepts |
def _links(x):
"""Helper function to link states with one another."""
return [(x[i],x[i+1]) for i,_ in enumerate(x[:-1])] | bigcode/self-oss-instruct-sc2-concepts |
def get_total_figure_number(axis_matrix):
"""
Gets the number of figures from an axis_matrix generated by pyplot. Used by the hash to place configs in the
correct part of the axis_matrix
Parameters:
axis_matrix (1D or 2D numpy array) = Array returned by pyplot once multiple figu... | bigcode/self-oss-instruct-sc2-concepts |
def sanitize(str, strip=[" "], remove=["\r", "\n"]):
"""Return a whitespace-stripped, newline-stripped string.
Args:
str (str): The string to be sanitized.
strip (str[], optional) Additional things to be stripped.
remove (str[], optional) Additional things to be removed.
Returns:
(str) ... | bigcode/self-oss-instruct-sc2-concepts |
def get_timeout(filesize):
"""
Get a proper time-out limit based on the file size.
:param filesize: file size (int).
:return:
"""
timeout_max = 3 * 3600 # 3 hours
timeout_min = 300 # self.timeout
timeout = timeout_min + int(filesize / 0.5e6) # approx < 0.5 Mb/sec
return min(ti... | bigcode/self-oss-instruct-sc2-concepts |
def get_effective_batch_size(opts):
"""Returns effective batch size
:param dict opts: A dictionary containing benchmark parameters. Must contain
`batch_size`, `device` and optionally `num_gpus`.
:return: Effective batch size.
:rtype: int
"""
num_devices = 1 if opts['device... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def MaskedDenseMM(X, Y, rows, cols):
"""Helper routine for Backward computation for spmm
Z = X[rows,:] x Y[cols,:]
Args:
X: dense matrix
Y: dense matrix
rows: row indices of X
cols: row indices of Y
Returns:
Z as defined above
"""
#Z = X * ... | bigcode/self-oss-instruct-sc2-concepts |
def _strip_whitespace(text_content: str) -> str:
"""Return text_content with leading and trailing whitespace removed
"""
output_content: str = str(text_content)
if text_content is not None and len(text_content) > 0:
output_content = text_content.strip()
return output_content | bigcode/self-oss-instruct-sc2-concepts |
import torch
from datetime import datetime
from typing import Counter
def train_seed_generator(graph, args):
"""Generate Seed (Edges) based on some techniques
[1] chronologically split, use fresh data (e.g. latest one year)
[2] filter by edge type, here use the edge features dim=0, may use edge type exp... | bigcode/self-oss-instruct-sc2-concepts |
def get_first(iterable, default=None):
"""Get the first not None item from an iterable or default."""
if iterable:
for item in iterable:
if item:
return item
return default | bigcode/self-oss-instruct-sc2-concepts |
import base64
def base64_encode(bot, trigger):
"""Encodes a message into base64."""
if not trigger.group(2):
return bot.reply('I need something to encode.')
encodedBytes = base64.b64encode(trigger.group(2).encode('utf-8'))
encodedStr = str(encodedBytes, 'utf-8')
bot.say(encodedStr) | bigcode/self-oss-instruct-sc2-concepts |
def second_moment(data):
"""`second_moment` feature function
:param data: data to evaluate feature function on
:return: squared data
"""
return data**2 | bigcode/self-oss-instruct-sc2-concepts |
def as_iterable(iterable_or_scalar):
"""Utility for converting an object to an iterable.
Parameters
----------
iterable_or_scalar : anything
Returns
-------
l : iterable
If `obj` was None, return the empty tuple.
If `obj` was not iterable returns a 1-tuple containing `obj`.
Ot... | bigcode/self-oss-instruct-sc2-concepts |
def decodeXMLName(name):
"""
Decodes an XML (namespace, name) pair from an ASCII string as
encoded by encodeXMLName().
"""
def invalid():
raise ValueError("Invalid encoded name: %r" % (name,))
if not name:
invalid()
if name[0] is "{":
index = name.find("}")
... | bigcode/self-oss-instruct-sc2-concepts |
def build_input_map(protomap, inputs):
"""Builds a map to feed tensors in `protomap` using `inputs`.
Args:
protomap: A proto map<string,TensorInfo>.
inputs: A map with same keys as `protomap` of Tensors and SparseTensors.
Returns:
A map from nodes refered by TensorInfo protos to corresponding input
... | bigcode/self-oss-instruct-sc2-concepts |
def _named_tempfile_func(error_class):
"""Create a mock function for NamedTemporaryFile that always raises.
Parameters
----------
error_class : exception class
The error that should be raised when asking for a NamedTemporaryFile.
Returns
-------
named_temp_file : callable
A... | bigcode/self-oss-instruct-sc2-concepts |
def split_sample_name(s):
"""Split sample name into numerical and non-numerical parts
Utility function which splits the supplied sample name
into numerical (i.e. integer) and non-numerical (i.e. all
other types of character) parts, and returns the parts as
a list.
For example:
>>> split_s... | bigcode/self-oss-instruct-sc2-concepts |
def get_page(request):
"""Returns the page parameter from the request.GET dictionary if it exists else default to page = 1"""
if 'page' in request.GET.keys():
page = request.GET['page']
else:
page = 1
return page | bigcode/self-oss-instruct-sc2-concepts |
def aggregation(item1, item2):
"""
For an (airport, counters) item, perform summary aggregations.
"""
count1, total1, squares1, min1, max1 = item1
count2, total2, squares2, min2, max2 = item2
minimum = min((min1, min2))
maximum = max((max1, max2))
count = count1 + count2
total =... | bigcode/self-oss-instruct-sc2-concepts |
def get_round_id(rounds_list, tourn_id, tourn_day):
"""
Helper function to get the round_id
based on the specified tourn_id and tourn_day
"""
for item in rounds_list:
if item.get_tourn_id() == tourn_id:
if item.get_day() == tourn_day:
return item.get_round_id()
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def load_pth_embeddings(params, source):
"""
Reload pretrained embeddings from a PyTorch binary file.
"""
# reload PyTorch binary file
lang = params.src_lang if source else params.tgt_lang
data = torch.load(params.src_emb if source else params.tgt_emb)
dico = data['dico']
... | bigcode/self-oss-instruct-sc2-concepts |
def hyphen_to_underscore_string(string):
"""
Convert hyphens to underscores in the given string
"""
return string.replace('-', '_') | bigcode/self-oss-instruct-sc2-concepts |
def extract_spectrum(fit_table, binNumber):
"""
Get the ``NBurst`` fitted spectrum for a given bin number.
Parameters
----------
fit_table :
the fit_table containg the fitted spectra
binNumber : int
the binNumber
Returns
-------
tuple of :class:`~numpy:numpy.ndarray`
... | bigcode/self-oss-instruct-sc2-concepts |
def read_as_list(filename):
"""Read the file at filename and store its contents into a list."""
with open(filename) as f:
result = [line.rstrip() for line in f.readlines()]
f.close()
return result | bigcode/self-oss-instruct-sc2-concepts |
def harmonize_entities(default_ents, requested_ents):
"""Harmonizes two dictionaries representing default_ents and requested requested_ents.
Given two dictionaries of entity: boolean key: value pairs, returns a
dictionary where the values of entities specified in `requested_ents` override those specified
... | bigcode/self-oss-instruct-sc2-concepts |
def trim_short_sentences(text: list):
"""
Trims short sentences from a list of sentences.
"""
text = [t for t in text if len(t) > 120]
return text | bigcode/self-oss-instruct-sc2-concepts |
def safeformat(str, **kwargs):
"""Function safeformat
A quick python (3.2+) way to avoid errors with missing keywords in strings.
Taken from https://stackoverflow.com/questions/17215400/python-format-string-unused-named-arguments
:param str: The list of strings with brackets
:param **kwargs: Argumen... | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_id(length): # This function has two doctests inside it to give an example on how to make doctests
"""
Creates a random configuration key for the session - for safety of session variables.
>>> len(random_id(50)) == 50
True
>>> random_id('hello')
Traceback (most recent... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def weighted_nll_loss(inpt: torch.Tensor, target: torch.Tensor, weight: torch.Tensor):
"""What `torch.nll_loss` with `reduction='weighted_average'` should be"""
return (
torch.nn.functional.nll_loss(inpt, target, weight=weight, reduction="sum")
/ weight.take(target).sum()
) | bigcode/self-oss-instruct-sc2-concepts |
import aiohttp
async def get(url, indicator):
"""
A simple async get function, tailored to tracking failures
Parameters
----------
url : str
The URL to make a request to
indicator : str
The name of the indicator being retrieved (to make tracking easier)
Returns
-------... | bigcode/self-oss-instruct-sc2-concepts |
def new_capacity_rule(mod, g, p):
"""
New capacity built at project g in period p.
"""
return mod.DRNew_Power_Capacity_MW[g, p] | bigcode/self-oss-instruct-sc2-concepts |
import math
def rescale_js(
value: float, deadzone: float = 0, exponential: float = 0, rate: float = 1
) -> float:
"""Rescale a joystick input, applying a deadzone, exponential, and max rate.
Args:
value: the joystick value, in the interval [-1, 1].
deadzone: the deadzone to apply.
... | bigcode/self-oss-instruct-sc2-concepts |
def get_log_slice(db, job_id, start, stop):
"""
Get a slice of the calculation log as a JSON list of rows
:param db:
a :class:`openquake.server.dbapi.Db` instance
:param job_id:
a job ID
:param start:
start of the slice
:param stop:
end of the slice (the last ele... | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
def normalize(text: str) -> str:
"""Prepare the `text` for string comparison.
Replaces composed characters by basic ones and converts to lowercase.
"""
text = unicodedata.normalize('NFKD', text)
output = []
for c in text:
if not unicodedata.combining(c):
... | bigcode/self-oss-instruct-sc2-concepts |
def lines(a, b):
"""Return lines in both a and b"""
# Get lines
lines_of_a = a.split('\n')
lines_of_b = b.split('\n')
# Use a set to store the line, beacuse
# it's a better structure for string
# and avoids duplicates values
equal_lines = set()
# Compares the lines
for line_of_... | bigcode/self-oss-instruct-sc2-concepts |
import random
def reservoir_sample(filename, n_samples=1, random_seed=None):
"""Return a random subset of lines from a file
Parameters
----------
filename: path
File to be loaded
n_samples: int
number of lines to return
random_seed: int or None
If set, use this as the ... | bigcode/self-oss-instruct-sc2-concepts |
import re
def batch_settings( content ):
"""
Gets the batch settings.
:param content: Content to search.
:returns: Dictionary of settings with their index.
:raises RuntimeError: If settings section could not be found.
"""
section_pattern = '\*{3} Overview of batch settings \*{3}\n\n(.+?)\... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def calculate_duration(start):
"""
Returns the difference in seconds between start and now
:param: start: datetime to begin
:returns: Seconds between start and end
"""
timing = datetime.utcnow() - start
duration = timing.seconds + timing.microseconds / 1000000... | bigcode/self-oss-instruct-sc2-concepts |
import re
def output_content(content, print_output, text_filter, headline):
"""
Builds the human readable output return from stdout commands according to print_output and text_filter
Args:
content: stdout returned from running ad hoc command or job
print_output: if True human readable is s... | bigcode/self-oss-instruct-sc2-concepts |
import math
def calculate_sinwave(i):
"""Create a sinusoidal statistic."""
return 10 + math.sin(math.radians(i)) * 50 | bigcode/self-oss-instruct-sc2-concepts |
def packman_api_name(api_name):
"""Changes an pipeline kwarg API name to format expected by Packman"""
return api_name.replace('-', '/') | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def is_reference(key: Any) -> bool:
"""Is this key a reference to output from elsewhere in the chores.
A reference has the form ^chore(.output)? where `chore` is the name of the
node you are consuming output from and `output` is either a name or a
number to tell which part of t... | bigcode/self-oss-instruct-sc2-concepts |
def dirhandler(directory, defaultdir):
"""
If directory is None, turn it into defaultdir.
:param directory: Target directory.
:type directory: str
:param defaultdir: Default directory.
:type defaultdir: str
"""
directory = defaultdir if directory is None else directory
return direc... | 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.