seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def split_user_goals(all_user_goals):
"""
Helper method to split the user goals in two sets of goals, with and without request slots
"""
user_goals_no_req_slots = []
user_goals_with_req_slots = []
for user_goal in all_user_goals:
if len(user_goal["request_slots"].keys()) == 0:
user_goals_no_req_slots.append(user_goal)
else:
user_goals_with_req_slots.append(user_goal)
return user_goals_no_req_slots, user_goals_with_req_slots | bigcode/self-oss-instruct-sc2-concepts |
def get_phi0(self, b_, bp_):
"""
Get the reduced density matrix element corresponding to
many-body states b and bp.
Parameters
----------
self : Builder or Approach
The system given as Builder or Approach object.
b_,bp_ : int
Labels of the many-body states.
Returns
--------
phi0bbp : complex
A matrix element of the reduced density matrix (complex number).
"""
b = self.si.states_order[b_]
bp = self.si.states_order[bp_]
bcharge = sum(self.si.get_state(b))
bpcharge = sum(self.si.get_state(bp))
phi0bbp = 0.0
if self.funcp.kerntype == 'Pauli':
if b == bp:
ind = self.si.get_ind_dm0(b, b, bcharge, maptype=1)
phi0bbp = self.phi0[ind]
elif bcharge == bpcharge:
ind = self.si.get_ind_dm0(b, bp, bcharge, maptype=1)
conj = self.si.get_ind_dm0(b, bp, bcharge, maptype=3)
if ind != -1:
if type(self.si).__name__ == 'StateIndexingDMc':
phi0bbp = self.phi0[ind]
else:
ndm0, npauli = self.si.ndm0, self.si.npauli
phi0bbp = (self.phi0[ind] + 1j*self.phi0[ndm0-npauli+ind]
* (+1 if conj else -1)
* (0 if ind < npauli else 1))
return phi0bbp | bigcode/self-oss-instruct-sc2-concepts |
import torch
def train_test_split(dataset, params):
"""Grabs random Omniglot samples and generates test samples from same class.
The random seed is taken from params.sampler_seed, the test_shift is which sample
to grab as a test. If it ends up being a different class, the sampler is
walked back until the class is same, and the sample is different.
Args:
dataset: (Dataset) Sampler from Omniglot dataset.
params: (json dict) Params.json file.
Returns:
train_dataloader, test_dataloader: (tuple) Containing matched train test pairs.
"""
train_dataset = []
test_dataset = []
# Random seed from params file.
torch.manual_seed(params.sampler_seed)
# Create batch_size random indices from dataset.
# Subtract params.test_shift so that we don't pick a random sample
# so close to the end of the set that it looks for a test pair in
# the blackness of 'index out of range'.
idxs = torch.randint(len(dataset) - params.test_shift, (1, params.batch_size))
# Make sure one of them is our control.
idxs[0, 0] = 19
for i, idx in enumerate(idxs[0]):
shift_idx = params.test_shift
train_sample, train_lbl = dataset[idx]
test_sample, test_lbl = dataset[idx + shift_idx]
# Make sure labels are the same, and it is not the same sample.
while (train_lbl != test_lbl) or (torch.equal(train_sample, test_sample)):
test_sample, test_lbl = dataset[idx + shift_idx]
shift_idx -= 1
train_dataset.append(train_sample)
test_dataset.append(test_sample)
#=====MONITORING=====#
# Uncomment to see train_samples or change selection to test_sample.
# utils.animate_weights(train_sample, auto=True)
#=====END MONITORING=====#
train_dataloader = torch.stack(train_dataset)
train_dataloader.unsqueeze_(1)
test_dataloader = torch.stack(test_dataset)
test_dataloader.unsqueeze_(1)
return train_dataloader, test_dataloader | bigcode/self-oss-instruct-sc2-concepts |
import math
def dist(a, b):
""" euclidean distance """
return math.sqrt((a[0]-b[0])**2 + (a[1]-b[1])**2) | bigcode/self-oss-instruct-sc2-concepts |
def gt10(val):
"""
Predicate testing if a value is less than 10
"""
return val > 10 | bigcode/self-oss-instruct-sc2-concepts |
def gender(mention):
""" Compute gender of a mention.
Args:
mention (Mention): A mention.
Returns:
The tuple ('gender', GENDER), where GENDER is one of 'MALE',
'FEMALE', 'NEUTRAL', 'PLURAL' and 'UNKNOWN'.
"""
return "gender", mention.attributes["gender"] | bigcode/self-oss-instruct-sc2-concepts |
def GetBytes(byte, size):
"""Get a string of bytes of a given size
Args:
byte: Numeric byte value to use
size: Size of bytes/string to return
Returns:
A bytes type with 'byte' repeated 'size' times
"""
return bytes([byte]) * size | bigcode/self-oss-instruct-sc2-concepts |
import re
def string_to_tags_list(string):
"""
Given a string representing tags in TiddlyWiki
format parse them into a list of tag strings.
"""
tags = []
tag_matcher = re.compile(r'([^ \]\[]+)|(?:\[\[([^\]]+)\]\])')
for match in tag_matcher.finditer(string):
if match.group(2):
tags.append(match.group(2))
elif match.group(1):
tags.append(match.group(1))
return tags | bigcode/self-oss-instruct-sc2-concepts |
def beginsField(line):
"""
Does the given (stripped) line begin an epytext or ReST field?
"""
if line.startswith("@"):
return True
sphinxwords = """
param params return type rtype summary var ivar cvar raises raise except
exception
""".split()
for word in sphinxwords:
if line.startswith(":" + word):
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from threading import local
def make_tls_property(default=None):
"""Creates a class-wide instance property with a thread-specific value."""
class TLSProperty(object):
def __init__(self):
self.local = local()
def __get__(self, instance, cls):
if not instance:
return self
return self.value
def __set__(self, instance, value):
self.value = value
def _get_value(self):
return getattr(self.local, 'value', default)
def _set_value(self, value):
self.local.value = value
value = property(_get_value, _set_value)
return TLSProperty() | bigcode/self-oss-instruct-sc2-concepts |
def _transform_session_persistence(persistence):
"""Transforms session persistence object
:param persistence: the session persistence object
:returns: dictionary of transformed session persistence values
"""
return {
'type': persistence.type,
'cookie_name': persistence.cookie_name
} | bigcode/self-oss-instruct-sc2-concepts |
def byte_notation(size: int, acc=2, ntn=0):
"""Decimal Notation: take an integer, converts it to a string with the
requested decimal accuracy, and appends either single (default), double,
or full word character notation.
- Args:
- size (int): the size to convert
- acc (int, optional): number of decimal places to keep. Defaults to 2.
- ntn (int, optional): notation name length. Defaults to 0.
- Returns:
- [tuple]: 0 = original size int unmodified; 1 = string for printing
"""
size_dict = {
1: ['B', 'B', 'bytes'],
1000: ['k', 'kB', 'kilobytes'],
1000000: ['M', 'MB', 'megabytes'],
1000000000: ['G', 'GB', 'gigabytes'],
1000000000000: ['T', 'TB', 'terabytes']
}
return_size_str = ''
for key, value in size_dict.items():
if (size / key) < 1000:
return_size_str = f'{size / key:,.{acc}f} {value[ntn]}'
return size, return_size_str | bigcode/self-oss-instruct-sc2-concepts |
import copy
def _DeepCopySomeKeys(in_dict, keys):
"""Performs a partial deep-copy on |in_dict|, only copying the keys in |keys|.
Arguments:
in_dict: The dictionary to copy.
keys: The keys to be copied. If a key is in this list and doesn't exist in
|in_dict| this is not an error.
Returns:
The partially deep-copied dictionary.
"""
d = {}
for key in keys:
if key not in in_dict:
continue
d[key] = copy.deepcopy(in_dict[key])
return d | bigcode/self-oss-instruct-sc2-concepts |
def prandtl(cp=None, mu=None, k=None, nu=None, alpha=None):
"""
Calculate the dimensionless Prandtl number for a fluid or gas.
.. math:: Pr = \\frac{c_p \\mu}{k} = \\frac{\\nu}{\\alpha}
Parameters
----------
cp : float
Specific heat [J/(kg⋅K)]
mu : float
Dynamic viscosity [kg/(m⋅s)]
k : float
Thermal conductivity [W/(m⋅K)]
nu : float, optional
Kinematic viscosity [m²/s]
alpha : float, optional
Thermal diffusivity [m²/s]
Returns
-------
pr : float
Prandtl number [-]
Examples
--------
>>> prandtl(cp=4188, mu=0.001307, k=0.5674)
9.647
>>> prandtl(nu=1.5064e-5, alpha=2.1002e-5)
0.71726
Raises
------
ValueError
Must provide (cp, mu, k) or (nu, alpha)
References
----------
Daizo Kunii and Octave Levenspiel. Fluidization Engineering.
Butterworth-Heinemann, 2nd edition, 1991.
"""
if cp and mu and k:
pr = (cp * mu) / k
elif nu and alpha:
pr = nu / alpha
else:
raise ValueError('Must provide (cp, mu, k) or (nu, alpha)')
return pr | bigcode/self-oss-instruct-sc2-concepts |
def sentence_selection(sentences):
"""
select sentences that are not only space and have more than two tokens
"""
return [
sent.strip()
for sent in sentences
if (sent or not sent.isspace()) and len(sent.split()) > 2
] | bigcode/self-oss-instruct-sc2-concepts |
def check_consistency(header1,
header2):
"""
Return true if all critical fields of *header1* equal those of
*header2*.
"""
return (header1.Station_Name == header2.Station_Name and
header1.IAGA_CODE == header2.IAGA_CODE and
header1.Geodetic_Latitude == header2.Geodetic_Latitude and
header1.Geodetic_Longitude == header2.Geodetic_Longitude and
header1.Elevation == header2.Elevation and
header1.Reported == header2.Reported and
header1.Sensor_Orientation == header2.Sensor_Orientation and
header1.Digital_Sampling == header2.Digital_Sampling and
header1.Data_Interval_Type == header2.Data_Interval_Type and
header1.Data_Type == header2.Data_Type) | bigcode/self-oss-instruct-sc2-concepts |
def is_feature_component_start(line):
"""Checks if a line starts with '/', ignoring whitespace."""
return line.lstrip().startswith("/") | bigcode/self-oss-instruct-sc2-concepts |
def header(img, author, report_date, report_time, report_tz, title) -> str:
"""Creates reports header
Parameters
----------
img : str
Image for customizable report
author : str
Name of author responsible by report
report_date : str
Date when report is run
report_time : str
Time when report is run
report_tz : str
Timezone associated with datetime of report being run
title : str
Title of the report
Returns
-------
str
HTML code for interactive tabs
"""
return f"""
<div style="display:flex; margin-bottom:1cm;">
{img}
<div style="margin-left:2em">
<p><b>Analyst:</b> {author}</p>
<p><b>Date :</b> {report_date}</p>
<p><b>Time :</b> {report_time} {report_tz}</p>
<br/>
<p>{title}</p>
</div>
</div>""" | bigcode/self-oss-instruct-sc2-concepts |
import requests
def handle_response(r, http_method, custom_err):
"""
Handles the HTTP response and returns the JSON
Parameters
----------
r: requests module's response
http_method: string
"GET", "POST", "PUT", etc.
custom_err: string
the custom error message if any
Returns
-------
json : dict
"""
json = {}
if r.status_code == requests.codes.ok:
if r.text:
json = r.json()
else:
print("{0} returned an empty response.".format(http_method))
else:
if custom_err is not None:
print(custom_err)
print("Status code: " + str(r.status_code))
if r.text:
print(r.text)
r.raise_for_status()
return json | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def _Net_blobs(self):
"""
An OrderedDict (bottom to top, i.e., input to output) of network
blobs indexed by name
"""
return OrderedDict([(bl.name, bl) for bl in self._blobs]) | bigcode/self-oss-instruct-sc2-concepts |
def is_cg_developed(properties):
"""Check if a colorgroup is fully developed."""
# check validity of colorgroup
assert len(set([c.color for c in properties])) == 1
return all([c.has_hotel for c in properties]) | bigcode/self-oss-instruct-sc2-concepts |
def _matrix_to_vector(X):
"""
Returns a vector from flattening a matrix.
"""
u = X.reshape((1, -1)).ravel()
return u | bigcode/self-oss-instruct-sc2-concepts |
def pad_guid_bytes(raw_bytes: bytes) -> bytes:
"""Pads a sequence of raw bytes to make them the required size of a UUID.
Note that if you're using an int as your source for instantiating a UUID,
you should not use this function. Just use UUID(your_int_here).
"""
if not (0 < len(raw_bytes) <= 16):
raise ValueError("Byte length must be between 1 and 16.")
return raw_bytes + (b'\x00' * (16 - len(raw_bytes))) | bigcode/self-oss-instruct-sc2-concepts |
def file_info_equal(file_info_1, file_info_2):
"""Return true if the two file-infos indicate the file hasn't changed."""
# Negative matches are never equal to each other: a file not
# existing is not equal to another file not existing.
if (None, None, None) in (file_info_1, file_info_2):
return False
# Equal if the size and the mtimes match.
if file_info_1[:2] == file_info_2[:2]:
return True
# Even if mtimes don't match, they're equal if the size and the
# crcs match. But we have to be careful, since crcs are optional,
# so we don't do this test if the crcs are None.
if file_info_1[2] is not None and file_info_1[1:] == file_info_2[1:]:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
import random
def generateIndices(n_blocks, N, D):
"""
generates indices for block matrix computation.
Checked.
Input:
n_blocks: number of blocks to use.
N: number of samples.
D: number of genes.
Output:
y_indices_to_use[i][j] is the indices of block j in sample i.
"""
y_indices_to_use = []
idxs = list(range(D))
n_in_block = int(1. * D / n_blocks)
for i in range(N):
partition = []
random.shuffle(idxs)
n_added = 0
for block in range(n_blocks):
start = n_in_block * block
end = start + n_in_block
if block < n_blocks - 1:
idxs_in_block = idxs[start:end]
else:
idxs_in_block = idxs[start:]
partition.append(sorted(idxs_in_block))
n_added += len(idxs_in_block)
y_indices_to_use.append(partition)
if i == 0:
print('Block sizes', [len(a) for a in partition])
assert(n_added == D)
return y_indices_to_use | bigcode/self-oss-instruct-sc2-concepts |
def compute_delays(SOA):
""" calculate the delay time for color/word input
positive SOA => color is presented earlier, v.v.
Parameters
----------
SOA : int
stimulus onset asynchrony == color onset - word onset
Returns
-------
int,int
the delay time for color/word input, repsectively
"""
color_delay = max(0, -SOA)
word_delay = max(0, SOA)
return color_delay, word_delay | bigcode/self-oss-instruct-sc2-concepts |
import math
def dist(p,q):
"""
Helper function to compute the "distance" of two
2D points.
"""
return math.sqrt((p[0] - q[0]) ** 2+(p[1] - q[1]) ** 2) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def sra_id_to_app_input(sra_id: str) -> Dict:
"""Generate input from app for sra_fastq_importer
Set split files to false so we no merging is needed
Args:
sra_id:
Returns:
dictionary containing
"""
return {"accession": sra_id, "split_files": False} | bigcode/self-oss-instruct-sc2-concepts |
def div(num1, num2):
"""
Divide two numbers
"""
return num1 / num2 | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def to_excel_ts(ts):
"""
Converts a datetime timestamp into Excel format date time
"""
EPOCH = datetime(1899, 12, 30)
delta = ts - EPOCH
return float(delta.days) + (float(delta.seconds) / 86400) | bigcode/self-oss-instruct-sc2-concepts |
def get_content_id(item):
"""Extract content id or uri."""
if item.item_class == "object.item.audioItem.musicTrack":
return item.get_uri()
return item.item_id | bigcode/self-oss-instruct-sc2-concepts |
def getkey(dict_, key, default=None):
"""Return dict_.get(key, default)
"""
return dict_.get(key, default) | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def _to_collected_format(date):
"""Convert input date format from '%Y%-m-%d' to '%Y%m%d'"""
return str(datetime.strptime(date, "%Y-%m-%d").strftime("%Y%m%d")) | bigcode/self-oss-instruct-sc2-concepts |
def _unpersist_broadcasted_np_array(broadcast):
"""
Unpersist a single pyspark.Broadcast variable or a list of them.
:param broadcast: A single pyspark.Broadcast or list of them.
"""
if isinstance(broadcast, list):
[b.unpersist() for b in broadcast]
else:
broadcast.unpersist()
return None | bigcode/self-oss-instruct-sc2-concepts |
def _to_str(s):
"""Downgrades a unicode instance to str. Pass str through as-is."""
if isinstance(s, str):
return s
# This is technically incorrect, especially on Windows. In theory
# sys.getfilesystemencoding() should be used to use the right 'ANSI code
# page' on Windows, but that causes other problems, as the character set
# is very limited.
return s.encode('utf-8') | bigcode/self-oss-instruct-sc2-concepts |
def Intersect(list1,list2):
"""
This function takes two lists and returns a list of items common to both
lists.
"""
ReturnList = []
for x in list1:
if x in list2: ReturnList.append(x)
return ReturnList | bigcode/self-oss-instruct-sc2-concepts |
import math
def euler_problem_9(n=1000):
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
assert n > 10
# first assume that a <= b < c < n/2. Then, for c to be an integer we can't have a=b.
# hence assume that a < b < c and that n/3 < 3.
# brute-force O(n^2) approach
for c in range(n // 2, n // 3, -1):
c_sq = c ** 2
for b in range(c - 1, int(c / math.sqrt(2)), -1):
a = n - c - b
if a ** 2 + b ** 2 == c_sq:
return a * b * c
return -1 | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def _get_inputs(values):
""" Generate the list of all possible ordered subsets of values. """
power_set = set(
[
tuple(set(prod))
for prod in itertools.product(values, repeat=len(values))
]
)
power_perms = [itertools.permutations(comb) for comb in power_set]
ordered_power_set = []
for perm in power_perms:
for item in perm:
ordered_power_set.append(list(item))
return ordered_power_set | bigcode/self-oss-instruct-sc2-concepts |
import re
def next_look_say(current_value):
"""
Given a numeric string, find it's 'look-and-say' value to determine the
next value in the sequence.
"""
# Split into groups of same consecutive digits
r = '(1+|2+|3+|4+|5+|6+|7+|8+|9+|0+)'
matches = re.findall(r, current_value)
return ''.join([str(len(m)) + m[0] for m in matches]) | bigcode/self-oss-instruct-sc2-concepts |
def set_union(sets):
"""Non variadic version of set.union.
"""
return set.union(*sets) | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def resolve_python_path(path):
"""
Turns a python path like module.name.here:ClassName.SubClass into an object
"""
# Get the module
module_path, local_path = path.split(':', 1)
thing = importlib.import_module(module_path)
# Traverse the local sections
local_bits = local_path.split('.')
for bit in local_bits:
thing = getattr(thing, bit)
return thing | bigcode/self-oss-instruct-sc2-concepts |
def cut_below() -> str:
"""Return a "cut after this line" line."""
return "\n.--Cut after this line --.\n" | bigcode/self-oss-instruct-sc2-concepts |
def effect_on_response(codes, effect, result):
"""
Returns the specified effect if the resulting HTTP response code is
in ``codes``.
Useful for invalidating auth caches if an HTTP response is an auth-related
error.
:param tuple codes: integer HTTP codes
:param effect: An Effect to perform when response code is in ``codes``.
:param result: The result to inspect, from an Effect of :obj:`Request`.
"""
response, content = result
if response.code in codes:
return effect.on(success=lambda ignored: result)
else:
return result | bigcode/self-oss-instruct-sc2-concepts |
def format_markdown(content, params):
"""Format content with config parameters.
Arguments:
content {str} -- Unformatted content
Returns:
{str} -- Formatted content
"""
try:
fmt = content.format(**params)
except KeyError:
fmt = content
return fmt | bigcode/self-oss-instruct-sc2-concepts |
def snake_to_camel(s: str):
"""
Convert a snake_cased_name to a camelCasedName
:param s: the snake_cased_name
:return: camelCasedName
"""
components = s.split("_")
return components[0] + "".join(y.title() for y in components[1:]) | bigcode/self-oss-instruct-sc2-concepts |
from typing import AbstractSet
def add_to_set(set_: AbstractSet[str] | None, new: str) -> set[str]:
"""Add an entry to a set (or create it if doesn't exist).
Args:
set_: The (optional) set to add an element to.
new: The string to add to the set.
"""
return set(set_).union([new]) if set_ is not None else {new} | bigcode/self-oss-instruct-sc2-concepts |
import torch
def invert_convert_to_box_list(x: torch.Tensor, original_width: int, original_height: int) -> torch.Tensor:
""" takes input of shape: (*, width x height, ch)
and return shape: (*, ch, width, height)
"""
assert x.shape[-2] == original_width * original_height
return x.transpose(dim0=-1, dim1=-2).view(list(x.shape[:-2]) + [x.shape[-1], original_width, original_height]) | bigcode/self-oss-instruct-sc2-concepts |
import re
def convert_crfpp_output(crfpp_output):
"""
Convert CRF++ command line output.
This function takes the command line output of CRF++ and splits it into
one [gold_label, pred_label] list per word per sentence.
Parameters
----------
crfpp_output : str
Command line output obtained from a CRF++ command.
Returns
-------
result : list
List of [gold_label, pred_label] per word per sentence.
"""
res = [[re.split(r'\t', token_output)[-2:] for token_output
in re.split(r'\n', sentence_output)]
for sentence_output in re.split(r'\n\n+', crfpp_output.strip())]
return res | bigcode/self-oss-instruct-sc2-concepts |
import math
def normalize_values_in_dict(dictionary, factor=None, inplace=True):
""" Normalize the values in a dictionary using the given factor.
For each element in the dictionary, applies ``value/factor``.
Parameters
----------
dictionary: dict
Dictionary to normalize.
factor: float, optional (default=None)
Normalization factor value. If not set, use the sum of values.
inplace : bool, default True
if True, perform operation in-place
"""
if factor is None:
factor = sum(dictionary.values())
if factor == 0:
raise ValueError('Can not normalize, normalization factor is zero')
if math.isnan(factor):
raise ValueError('Can not normalize, normalization factor is NaN')
if not inplace:
dictionary = dictionary.copy()
for key, value in dictionary.items(): # loop over the keys, values in the dictionary
dictionary[key] = value / factor
return dictionary | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_times(filename="cvt_add_times.json"):
"""Loads the results from the given file."""
with open(filename, "r") as file:
data = json.load(file)
return data["n_bins"], data["brute_force_t"], data["kd_tree_t"] | bigcode/self-oss-instruct-sc2-concepts |
def add_leading_zero(number: int, digit_num: int = 2) -> str:
"""add_leading_zero function
Args:
number (int): number that you want to add leading zero
digit_num (int): number of digits that you want fill up to. Defaults to 2.
Returns:
str: number that has the leading zero
Examples:
>>> add_leading_zero(5, 3)
"005"
"""
return str(number).zfill(digit_num) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _find_streams(text):
"""Finds data streams in text, returns a list of strings containing
the stream contents"""
re_stream = re.compile(r"<< /Length \d+ >>\n(stream.*?endstream)", re.DOTALL)
streams = []
for m in re_stream.finditer(text):
streams.append(text[m.start(1):m.end(1)])
return streams | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _create_1d_regression_dataset(n: int = 100, seed: int = 0) -> torch.Tensor:
"""Creates a simple 1-D dataset of a noisy linear function.
:param n: The number of datapoints to generate, defaults to 100
:param seed: Random number generator seed, defaults to 0
:return: A tensor that contains X values in [:, 0] and Y values in [:, 1]
"""
torch.manual_seed(seed)
x = torch.rand((n, 1)) * 10
y = 0.2 * x + 0.1 * torch.randn(x.size())
xy = torch.cat((x, y), dim=1)
return xy | bigcode/self-oss-instruct-sc2-concepts |
def decrease_parameter_closer_to_value(old_value, target_value, coverage):
"""
Simple but commonly used calculation for interventions. Acts to decrement from the original or baseline value
closer to the target or intervention value according to the coverage of the intervention being implemented.
Args:
old_value: Baseline or original value to be decremented
target_value: Target value or value at full intervention coverage
coverage: Intervention coverage or proportion of the intervention value to apply
"""
return old_value - (old_value - target_value) * coverage if old_value > target_value else old_value | bigcode/self-oss-instruct-sc2-concepts |
def remove_subtitle(title):
"""Strip a book's subtitle (if it exists). For example, 'A Book: Why Not?' becomes 'A Book'."""
if ':' in title:
return title[:title.index(':')].strip()
else:
return title | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_samples_from_datasets(datasets, wav):
"""Gets samples (noise or speech) from the datasets.
Arguments
---------
datasets : list
List containing datasets. More precisely, we expect here the pointers
to the object used in speechbrain for data augmentation
(e.g, speechbrain.lobes.augment.EnvCorrupt).
wav : torch.tensor
The original waveform. The drawn samples will have the same
dimensionality of the original waveform.
Returns
-------
samples: torch.tensor
A batch of new samples drawn from the input list of datasets.
"""
# We want a sample of the same size of the original signal
samples = torch.zeros(
wav.shape[0], wav.shape[1], len(datasets), device=wav.device
)
# Let's sample a sequence from each dataset
for i, dataset in enumerate(datasets):
# Initialize the signal with noise
wav_sample = (torch.rand_like(wav) * 2) - 1
len_sample = torch.ones(wav.shape[0], device=wav.device)
# Sample a sequence
wav_sample = dataset(wav_sample, len_sample)
# Append it
samples[:, :, i] = wav_sample
# Random permutations of the signal
idx = torch.randperm(samples.shape[-1], device=wav.device)
samples[:, :] = samples[:, :, idx]
return samples | bigcode/self-oss-instruct-sc2-concepts |
import math
import torch
def _get_log_freq(sample_rate, max_sweep_rate, offset):
"""Get freqs evenly spaced out in log-scale, between [0, max_sweep_rate // 2]
offset is used to avoid negative infinity `log(offset + x)`.
"""
half = sample_rate // 2
start, stop = math.log(offset), math.log(offset + max_sweep_rate // 2)
return torch.exp(torch.linspace(start, stop, sample_rate, dtype=torch.double)) - offset | bigcode/self-oss-instruct-sc2-concepts |
def identifier_path(items):
"""Convert identifier in form of list/tuple to string representation
of filesystem path. We assume that no symbols forbidden by
filesystem are used in identifiers.
"""
return '/'.join(items) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
from typing import Iterable
def find_pictures(folder: Path) -> Iterable[Path]:
"""
find pictures in folder
"""
return folder.glob("*.jpg") | bigcode/self-oss-instruct-sc2-concepts |
def get_result_from_payload(json_resp):
"""Try to get result node from the payload."""
assert json_resp is not None
assert 'result' in json_resp
# read the actual result
return json_resp.get('result') | bigcode/self-oss-instruct-sc2-concepts |
import socket
def is_port_used(ip, port):
"""
check whether the port is used by other program
:param ip:
:param port:
:return: True(in use) False(idle)
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, port))
return True
except OSError:
return False
finally:
s.close() | bigcode/self-oss-instruct-sc2-concepts |
import re
def check_indent_keys(document):
""" Check whether the word before the cursor was an indent key (which
will trigger a reevaluation of the line's indent)"""
lw_start = document.find_previous_word_beginning() or 0
lw_end = 0# document.find_previous_word_ending() or 0
col = document.cursor_position_col
#print('Prev token from', lw_start, 'to', lw_end)
last_tok = document.current_line[col+lw_start:col+lw_end]
#print('Prev token from', lw_start, 'to', lw_end, ':', last_tok)
return re.match(
r'\{|\}|\(|\)|\[|\]|,|where|let|deriving|in|::|->|=>|\||=',
last_tok) | bigcode/self-oss-instruct-sc2-concepts |
def get_syscall_name(event):
"""Get the name of a syscall from an event.
Args:
event (Event): an instance of a babeltrace Event for a syscall
entry.
Returns:
The name of the syscall, stripped of any superfluous prefix.
Raises:
ValueError: if the event is not a syscall event.
"""
name = event.name
if name.startswith('sys_'):
return name[4:]
elif name.startswith('syscall_entry_'):
return name[14:]
else:
raise ValueError('Not a syscall event') | bigcode/self-oss-instruct-sc2-concepts |
def in_all_repository_dependencies( repository_key, repository_dependency, all_repository_dependencies ):
"""Return True if { repository_key : repository_dependency } is in all_repository_dependencies."""
for key, val in all_repository_dependencies.items():
if key != repository_key:
continue
if repository_dependency in val:
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def close(fulfillment_state: str, message: Dict[str, str]) -> dict:
"""Close dialog generator"""
return {
'dialogAction': {
'type': 'Close',
'fulfillmentState': fulfillment_state,
'message': message
}
} | bigcode/self-oss-instruct-sc2-concepts |
def customer_table(data):
"""Return dataframe with all customers."""
customers = data['olist_customers_dataset'].copy()
customers = customers[['customer_unique_id']].reset_index(drop=True)
return customers | bigcode/self-oss-instruct-sc2-concepts |
def _dummy_boxstream(stream, **kwargs):
"""Identity boxstream, no tansformation."""
return stream | bigcode/self-oss-instruct-sc2-concepts |
import random
def random_hex(digits = 12):
"""Generate a string of random hexadecimal digit and return as a string.
Arguments:
digits: the number of hexadecimal digits to create
"""
str_hex = ''.join([''.join(random.choice("0123456789ABCDEF")) for _ in range(digits)])
return str_hex | bigcode/self-oss-instruct-sc2-concepts |
def _compute_min_event_ndims(bijector_list, compute_forward=True):
"""Computes the min_event_ndims associated with the give list of bijectors.
Given a list `bijector_list` of bijectors, compute the min_event_ndims that is
associated with the composition of bijectors in that list.
min_event_ndims is the # of right most dimensions for which the bijector has
done necessary computation on (i.e. the non-broadcastable part of the
computation).
We can derive the min_event_ndims for a chain of bijectors as follows:
In the case where there are no rank changing bijectors, this will simply be
`max(b.forward_min_event_ndims for b in bijector_list)`. This is because the
bijector with the most forward_min_event_ndims requires the most dimensions,
and hence the chain also requires operating on those dimensions.
However in the case of rank changing, more care is needed in determining the
exact amount of dimensions. Padding dimensions causes subsequent bijectors to
operate on the padded dimensions, and Removing dimensions causes bijectors to
operate more left.
Args:
bijector_list: List of bijectors to be composed by chain.
compute_forward: Boolean. If True, computes the min_event_ndims associated
with a forward call to Chain, and otherwise computes the min_event_ndims
associated with an inverse call to Chain. The latter is the same as the
min_event_ndims associated with a forward call to Invert(Chain(....)).
Returns:
min_event_ndims
"""
min_event_ndims = 0
# This is a mouthful, but what this encapsulates is that if not for rank
# changing bijectors, we'd only need to compute the largest of the min
# required ndims. Hence "max_min". Due to rank changing bijectors, we need to
# account for synthetic rank growth / synthetic rank decrease from a rank
# changing bijector.
rank_changed_adjusted_max_min_event_ndims = 0
if compute_forward:
bijector_list = reversed(bijector_list)
for b in bijector_list:
if compute_forward:
current_min_event_ndims = b.forward_min_event_ndims
current_inverse_min_event_ndims = b.inverse_min_event_ndims
else:
current_min_event_ndims = b.inverse_min_event_ndims
current_inverse_min_event_ndims = b.forward_min_event_ndims
# New dimensions were touched.
if rank_changed_adjusted_max_min_event_ndims < current_min_event_ndims:
min_event_ndims += (
current_min_event_ndims - rank_changed_adjusted_max_min_event_ndims)
rank_changed_adjusted_max_min_event_ndims = max(
current_min_event_ndims, rank_changed_adjusted_max_min_event_ndims)
# If the number of dimensions has increased via forward, then
# inverse_min_event_ndims > forward_min_event_ndims, and hence the
# dimensions we computed on, have moved left (so we have operated
# on additional dimensions).
# Conversely, if the number of dimensions has decreased via forward,
# then we have inverse_min_event_ndims < forward_min_event_ndims,
# and so we will have operated on fewer right most dimensions.
number_of_changed_dimensions = (
current_min_event_ndims - current_inverse_min_event_ndims)
rank_changed_adjusted_max_min_event_ndims -= number_of_changed_dimensions
return min_event_ndims | bigcode/self-oss-instruct-sc2-concepts |
def is_anonymous(user_id):
""" Returns whether or not the given user is an anonymous user.
:param user_id: The id of the user.
:return: True, if the user is anonymous; False, otherwise.
"""
return user_id.startswith("hmrtmp") | bigcode/self-oss-instruct-sc2-concepts |
def calc_flesch_readability(wordcount, sentcount, syllcount):
""" Calculates the Flesch Readability Score. """
return round(float(float(206.835 - float(1.015 * float(wordcount / sentcount))) - float(84.6 * float(syllcount / wordcount))), 1) | bigcode/self-oss-instruct-sc2-concepts |
def centers(signal, axes):
"""
Returns the centers of the axes.
This works regardless if the axes contain bin boundaries or centers.
"""
def findc(axis, dimlen):
if axis.shape[0] == dimlen+1:
return (axis.nxdata[:-1] + axis.nxdata[1:]) / 2
else:
assert axis.shape[0] == dimlen
return axis.nxdata
return [findc(a,signal.shape[i]) for i,a in enumerate(axes)] | bigcode/self-oss-instruct-sc2-concepts |
def signing_bytes(uid, nonce):
"""
Returns list of bytes.
Parameters:
uid: string
nonce: int
"""
sbs = f'{uid}{nonce}'
return sbs.encode('utf-8')
#return bytearray(sbs.encode()) | bigcode/self-oss-instruct-sc2-concepts |
def stdDevOfLengths(L):
"""
L: a list of strings
returns: float, the standard deviation of the lengths of the strings,
or NaN if L is empty.
"""
try:
X = []
for l in L:
X.append(len(l))
mean = sum(X)/float(len(X))
tot = 0.0
for x in X:
tot += (x- mean)**2
std = (tot/len(X)) ** 0.5
except:
return float('NaN')
return std | bigcode/self-oss-instruct-sc2-concepts |
def _get_date(msg):
"""Returns the date included into the message.
Args:
msg: A json message.
Returns:
The date string
"""
return msg['date'] | bigcode/self-oss-instruct-sc2-concepts |
def convert_dict_of_sets_to_dict_of_lists(dictionary):
"""
Returns the same dictionary, but the values being sets are now lists
@param dictionary: {key: set(), ...}
"""
out = dict()
for key, setvalue in dictionary:
out[key] = list(setvalue)
return out | bigcode/self-oss-instruct-sc2-concepts |
def remove_every_other(my_list: list) -> list:
""" This function removes every second element from the array. """
new_list = []
for i, k in enumerate(range(len(my_list))):
if i % 2 == 0:
new_list.append(my_list[i])
return new_list | bigcode/self-oss-instruct-sc2-concepts |
def tick_percent(decimals=1):
"""A tick formatter to display the y-axis as a float percentage with a given number of decimals.
Args:
decimals = 1: The number of decimals to display.
Returns:
A tick formatter function (f(y, position)) displaying y as a percentage.
"""
return (lambda y, position: '{:.{decimals}f}%'.format(100.0 * y, decimals=decimals)) | bigcode/self-oss-instruct-sc2-concepts |
def cereal_protein_fractions(cereals):
"""
For each cereal, records its protein content as a fraction of its total mass.
"""
result = {}
for cereal in cereals:
total_grams = float(cereal["weight"]) * 28.35
result[cereal["name"]] = float(cereal["protein"]) / total_grams
return result | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Dict
def flatten(l: List[List[Dict]]) -> List[Dict]:
"""
Flattens list of lists.
:param l: list containing lists of table dictionaries
:return: list containing table dictionaries
"""
return[item for sublist in l for item in sublist] | bigcode/self-oss-instruct-sc2-concepts |
def button_string(channel, red, blue):
"""Returns the string representation of a Combo PWM Mode button."""
return 'CH{:s}_{:s}_{:s}'.format(channel, red, blue) | bigcode/self-oss-instruct-sc2-concepts |
def get_msg_count(bag, topic):
"""Get number of instances for the topic.
# Parameters
bag : rosbag.Bag
a target rosbag
topic : string
a valid topic name
# Returns
num_msgs : int
number of messages in the topic
"""
return bag.get_message_count(topic) | bigcode/self-oss-instruct-sc2-concepts |
def bilinear_interpolation_01(x, y, values):
"""Interpolate values given at the corners of
[0,1]x[0,1] square.
Parameters:
x : float
y : float
points : ((v00, v01), (v10, v11))
input grid with 4 values from which to interpolate.
Inner dimension = x, thus v01 = value at (x=1,y=0).
Returns:
float
interpolated value
"""
return (values[0][0] * (1 - x) * (1 - y) +
values[0][1] * x * (1 - y) +
values[1][0] * (1 - x) * y +
values[1][1] * x * y) | bigcode/self-oss-instruct-sc2-concepts |
def CommandInGoEnv(input_api, output_api, name, cmd, kwargs):
"""Returns input_api.Command that wraps |cmd| with invocation to go/env.py.
env.py makes golang tools available in PATH. It also bootstraps Golang dev
environment if necessary.
"""
if input_api.is_committing:
error_type = output_api.PresubmitError
else:
error_type = output_api.PresubmitPromptWarning
full_cmd = [
'vpython',
input_api.os_path.join(input_api.change.RepositoryRoot(), 'go', 'env.py'),
]
full_cmd.extend(cmd)
return input_api.Command(
name=name,
cmd=full_cmd,
kwargs=kwargs,
message=error_type) | bigcode/self-oss-instruct-sc2-concepts |
import math
def sigmoid(x, derivative=False):
"""Sigmoid activation function."""
if derivative:
return x * (1 - x)
return 1 / (1 + math.e ** (-x)) | bigcode/self-oss-instruct-sc2-concepts |
def _osfify_urls(data):
"""
Formats `data` object with OSF API URL
Parameters
----------
data : object
If dict with a `url` key, will format OSF_API with relevant values
Returns
-------
data : object
Input data with all `url` dict keys formatted
"""
OSF_API = "https://files.osf.io/v1/resources/{}/providers/osfstorage/{}"
if isinstance(data, str):
return data
elif 'url' in data:
data['url'] = OSF_API.format(*data['url'])
try:
for key, value in data.items():
data[key] = _osfify_urls(value)
except AttributeError:
for n, value in enumerate(data):
data[n] = _osfify_urls(value)
return data | bigcode/self-oss-instruct-sc2-concepts |
def gcd(x: int, m: int) -> int:
"""
最大公約数を求める
ユークリッドの互除法
"""
if m == 0:
return x
return gcd(m, x % m) | bigcode/self-oss-instruct-sc2-concepts |
def linear_map( values, new_min=0.0, new_max=1.0 ):
"""Return a NumPy array of linearly scaled values between new_min and new_max.
Equivalent to Matlab's mat2gray, I believe.
"""
new_values = (((values - values.min()) * (new_max - new_min)) / (values.max() - values.min())) + new_min
return new_values
# End linear_map() definition | bigcode/self-oss-instruct-sc2-concepts |
def inttodate(i, lim=1965, unknown='U', sep='-', order="asc", startsatyear=0):
"""
transforms an int representing days into a date
Args:
i: the int
lim: the limited year below which we have a mistake
unknown: what to return when unknown (date is bellow the limited year)
sep: the sep between your date (e.g. /, -, ...)
order: if 'asc', do d,m,y else do y,m,d
startsatyear: when is the year to start counting for this int
Returns:
str: the date or unknown
"""
a = int(i // 365)
if a > lim:
a = str(a + startsatyear)
r = i % 365
m = str(int(r // 32)) if int(r // 32) > 0 else str(1)
r = r % 32
d = str(int(r)) if int(r) > 0 else str(1)
else:
return unknown
return d + sep + m + sep + a if order == "asc" else a + sep + m + sep + d | bigcode/self-oss-instruct-sc2-concepts |
def parse_ref_words(argstr):
# address: (expect, mask)
"""
All three of thse are equivilent:
./solver.py --bytes 0x31,0xfe,0xff dmg-cpu/rom.txt
./solver.py --bytes 0x00:0x31,0x01:0xfe,0x02:0xff dmg-cpu/rom.txt
./solver.py --bytes 0x00:0x31:0xFF,0x01:0xfe:0xFF,0x02:0xff:0xFF dmg-cpu/rom.txt
Which maps to:
ref_words = {
0x00: (0x31, 0xFF),
0x01: (0xfe, 0xFF),
0x02: (0xff, 0xFF),
}
"""
ret = {}
auto_addr = 0
for constraint in argstr.split(","):
parts = constraint.split(":")
assert len(parts) <= 3
# One arg: assume offset and just use value
if len(parts) == 1:
offset = auto_addr
value = int(parts[0], 0)
# two arg: offset:value
else:
offset = int(parts[0], 0)
value = int(parts[1], 0)
mask = 0xFF
# three arg: allow masking value
if len(parts) >= 3:
mask = int(parts[2], 0)
ret[offset] = (value, mask)
auto_addr += 1
return ret | bigcode/self-oss-instruct-sc2-concepts |
def degrees2gradians(value:float)->float:
"""Convert degrees to gradians.
"""
return value * 200/180 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Tuple
from typing import List
def get_intents_keywords(entities: Dict) -> Tuple[List[str], List[str]]:
"""Obtains the list of intents and the list of keywords from an Wit.ai entity."""
intents = []
keywords = []
for key, val in entities.items():
if key == "intent":
intents.extend([dct.get("value") for dct in val])
else:
keywords.append(key)
return intents, keywords | bigcode/self-oss-instruct-sc2-concepts |
def application_case_func(decorator_application_scenario, current_cases):
"""Returns the case function used behind `decorator_application_scenario`."""
return current_cases["decorator_application_scenario"]["p"].func | bigcode/self-oss-instruct-sc2-concepts |
def _splits_for_summary_description_openapi_doc(lines):
"""Splites a list of docstring lines between the summary, description,
and other properties for an API route openapi spec.
For the openapi spec block, it should start with '````openapi' and close
with '```'.
Parameters
----------
lines : list[str]
Returns
-------
tuple
summary : str
description : str
openapi : str
"""
info = []
openapi = []
in_openapi = False
for line in lines:
if '```openapi' == line:
in_openapi = True
continue
if in_openapi and '```' == line:
in_openapi = False
continue
if not in_openapi:
info.append(line)
else:
openapi.append(line)
return info[0], info[1:], openapi | bigcode/self-oss-instruct-sc2-concepts |
def blosxom_sort_list_handler(args):
"""Sorts the list based on ``_mtime`` attribute such that
most recently written entries are at the beginning of the list
and oldest entries are at the end.
:param args: args dict with ``request`` object and ``entry_list``
list of entries
:returns: the sorted ``entry_list``
"""
entry_list = args["entry_list"]
entry_list = [(e._mtime, e) for e in entry_list]
entry_list.sort()
entry_list.reverse()
entry_list = [e[1] for e in entry_list]
return entry_list | bigcode/self-oss-instruct-sc2-concepts |
def notes(feature):
"""
Get all notes from this feature. If none a present then an empty list is
returned.
"""
return feature.qualifiers.get("note", []) | bigcode/self-oss-instruct-sc2-concepts |
def text2float(txt: str) -> float:
"""Converts text to float.
If text is not number, then returns `0.0`
"""
try:
return float(txt.replace(",", "."))
except:
return 0.0 | bigcode/self-oss-instruct-sc2-concepts |
def get_atom_indices(labels, atom):
"""
labels - a list of coordinate labels ("Elements")
atom - the atom whose indices in labels are sought
Returns a list of all location of [atom] in [labels]
"""
indices = []
for i in range(len(labels)):
if labels[i] == atom:
indices.append(i)
return indices | bigcode/self-oss-instruct-sc2-concepts |
def validate_manifest(manifest_data, validator):
"""Validate provided manifest_data against validator, returning list of all raised exceptions during validation"""
return list(validator.iter_errors(manifest_data)) | bigcode/self-oss-instruct-sc2-concepts |
def get_prop(obj, *prop_list):
"""
Get property value if property exists. Works recursively with a list representation of the property hierarchy.
E.g. with obj = {'a': 1, 'b': {'c': {'d': 2}}}, calling get_prop(obj, 'b', 'c', 'd') returns 2.
:param obj: dictionary
:param prop_list: list of the keys
:return: the property value or None if the property doesn't exist
"""
if obj is None:
return None
if len(prop_list) == 1:
if prop_list[0] in obj.keys():
return obj[prop_list[0]]
else:
return None
if prop_list[0] in obj.keys():
return get_prop(obj[prop_list[0]], *prop_list[1:])
else:
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.