seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def n_values(obj, keys):
"""Extract multiple values from `obj`
Parameters
----------
obj : dict
A grow or data "object"
keys : list
A list of valid key names
Must have at least one element
Returns
-------
tuple
The values for each key in `args`
Notes
... | bigcode/self-oss-instruct-sc2-concepts |
def fibonacci(n):
""" fibonacci function
Args:
n (int): the number for the n numbers of fibonacci
Returns:
a list of finobacci numbers
"""
result = [1] # fibonacci number starts from 1
t1 = 1
t2 = 1
if n > 0:
for _ in range(n-1):
result.append(t2)... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def log_func_decorator(func):
"""
Decorator to log the execution of a function: its start, end, output and exceptions
"""
logger = logging.getLogger()
def wrapper(*args, **kwargs):
logger.info(
'Executing function "{}" (args: {}, kwargs: {})'.format(
... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def int2byte(i):
"""Encode a positive int (<= 256) into a 8-bit byte.
>>> int2byte(1)
b'\x01'
"""
return struct.pack('B', i) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import random
def sample_vector(dimensions: int, seed: int) -> List[float]:
"""Sample normalized vector given length.
Parameters:
dimensions: int - space size
seed: Optional[int] - random seed value
Returns:
List[float] - normalized random vector of given ... | bigcode/self-oss-instruct-sc2-concepts |
def add_to_visited_places(x_curr: int, y_curr: int, visited_places: dict) -> dict:
"""
Visited placs[(x,y)] contains the number of visits
that the cell (x,y). This updates the count to the
current position (x_curr, y_curr)
Args:
x_curr: x coordinate of current position
y_curr: ... | bigcode/self-oss-instruct-sc2-concepts |
def remove_keys(dict_, seq):
"""Gracefully remove keys from dict."""
for key in seq:
dict_.pop(key, None)
return dict_ | bigcode/self-oss-instruct-sc2-concepts |
def reverse_score(dataset, mask, max_val=5, invalid_response=None):
"""Reverse scores a set of ordinal data.
Args:
data: Matrix [items x observations] of measured responses
mask: Boolean Vector with True indicating a reverse scored item
max_val: (int) maximum value in the Likert (-like... | bigcode/self-oss-instruct-sc2-concepts |
def flat_dataset_dicts(dataset_dicts):
"""
flatten the dataset dicts of detectron2 format
original: list of dicts, each dict contains some image-level infos
and an "annotations" field for instance-level infos of multiple instances
=> flat the instance level annotations
flat format:
... | bigcode/self-oss-instruct-sc2-concepts |
import copy
def v3_to_v2_package(v3_package):
"""Converts a v3 package to a v2 package
:param v3_package: a v3 package
:type v3_package: dict
:return: a v2 package
:rtype: dict
"""
package = copy.deepcopy(v3_package)
package.pop('minDcosReleaseVersion', None)
package['packagingVe... | bigcode/self-oss-instruct-sc2-concepts |
def multidict_split(bundle_dict):
"""Split multi dict to retail dict.
:param bundle_dict: a buddle of dict
:type bundle_dict: a dict of list
:return: retails of dict
:rtype: list
"""
retails_list = [dict(zip(bundle_dict, i)) for i in zip(*bundle_dict.values())]
return retails_list | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
import zlib
def compute_hash(*args: Any) -> str:
"""
Creates a 'version hash' to be used in envoy Discovery Responses.
"""
data: bytes = repr(args).encode()
version_info = (
zlib.adler32(data) & 0xFFFFFFFF
) # same numeric value across all py versions & platform... | bigcode/self-oss-instruct-sc2-concepts |
def get_coordinates(sub_turn):
"""
Obtain coordinates entered by human user
Attributes
----------
sub_turn: str
Game's sub turn. Used to prompt user.
"""
print(sub_turn, 'phase')
user_input = input("Please input in following format: xy ")
column, row = -1, -1 # Adding this ... | bigcode/self-oss-instruct-sc2-concepts |
def flip(str_array: list[str]) -> list[str]:
"""
Flip a list of strings on a top-left to bottom-right diagonal
:param str_array: array as a list of strings
:return: array flipped
"""
return list(reversed(str_array.copy())) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hash_file(filepath):
"""
Hashes the contents of a file. SHA1 algorithm is used.
:param filepath: Path to file to hash.
:type filepath: ``str``
:return: Hashed value as a string
:rtype: ``str``
"""
HASH_BLOCKSIZE = 65536
hasher = hashlib.sha1()
with open(fil... | bigcode/self-oss-instruct-sc2-concepts |
def make_xz_ground_plane(vertices):
"""
Given a vertex mesh, translates the mesh such that the lowest coordinate of the mesh
lies on the x-z plane.
:param vertices: (N, 6890, 3)
:return:
"""
lowest_y = vertices[:, :, 1].min(axis=-1, keepdims=True)
vertices[:, :, 1] = vertices[:, :, 1] - ... | bigcode/self-oss-instruct-sc2-concepts |
def make_title(text):
"""
turn a text string of words into a title by capitalizing each word
"""
words = text.split()
new_words = []
for word in words:
new_words.append(word[0].upper()+word[1:])
return ' '.join(new_words) | bigcode/self-oss-instruct-sc2-concepts |
def load_file_as_list(file_path: str) -> list:
"""
Loads the file at a specificed path, returns an error otherwise
:param file_path (str): The path to the file you want to load
:return _file a file of the contents of the file
"""
_file = ""
try:
with open(file_path, "r") as ... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def _has_kwarg_or_kwargs(f, kwarg):
"""Checks if the function has the provided kwarg or **kwargs."""
# For gin wrapped functions, we need to consider the wrapped function.
if hasattr(f, "__wrapped__"):
f = f.__wrapped__
(args, _, kwargs, _, _, _, _) = inspect.getfullargspec(f)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_tes_status(tes, buffer_low, buffer_high):
"""
Returns tes status:
1 - No further power input allowed
2 - Only thermal input of efficient devices (e.g. CHP, HP) allowed
3 - All devices can provide energy
Parameters
----------
tes : object
Thermal energy storage object of ... | bigcode/self-oss-instruct-sc2-concepts |
def extract_encoder_model(model):
"""
Extract the encoder from the original Sequence to Sequence Model.
Returns a keras model object that has one input (body of issue) and one
output (encoding of issue, which is the last hidden state).
Input:
-----
model: keras model object
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
def slider_command_to_str(arguments):
"""
Convert arguments for slider and arrowbox command into comment string
for config file.
:param arguments: slider arguments
:return: Formatted string for config file.
"""
return '; '.join(arguments) | bigcode/self-oss-instruct-sc2-concepts |
def factorial(n):
"""Computes factorial of n."""
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result | bigcode/self-oss-instruct-sc2-concepts |
import torch
import math
def log_poisson_loss(targets, log_input, compute_full_loss=False):
"""Computes log Poisson loss given `log_input`.
FOLLOWS TF IMPLEMENTATION
Gives the log-likelihood loss between the prediction and the target under the
assumption that the target has a Poisson distribution.
... | bigcode/self-oss-instruct-sc2-concepts |
def receiver(signal):
"""
A decorator for connecting receivers to events.
Example:
@receiver(on_move)
def signal_receiver(source_path, destination_path):
...
"""
def _decorator(func):
signal.connect(func)
return func
return _decorator | bigcode/self-oss-instruct-sc2-concepts |
def define_options(enable=[], disable=[]):
"""
Define the options for the subscribed events.
Valid options:
- CRfile: file created
- CRdir: directory created
- MDfile: file modified
- MDdir: directory modified
- MVfile: file moved
- MVdir: directory moved
... | bigcode/self-oss-instruct-sc2-concepts |
def safeindex(v, s):
"""Safe index for v in s, returns -1 if v is not in s"""
if v not in s:
return -1
return s.index(v) | bigcode/self-oss-instruct-sc2-concepts |
def rot13_decode(decvalue):
""" ROT13 decode the specified value. Example Format: Uryyb Jbeyq """
return(decvalue.decode("rot13")) | bigcode/self-oss-instruct-sc2-concepts |
def get_image_url(status):
"""
Get image url from tweet status
Parameters
----------
status: Tweet
Tweet status that mentions img2palette
Returns
------
image_url: str
Image url
"""
if "media" not in status["entities"]:
raise ValueError("No phot... | bigcode/self-oss-instruct-sc2-concepts |
def is_full_section(section):
"""Is this section affected by "config.py full" and friends?"""
return section.endswith('support') or section.endswith('modules') | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def delete_items(keys: List[str], s3_bucket):
"""Delete the specified keys from the provided S3 bucket and return the S3 response."""
delete_request = {
'Objects': [{'Key': key} for key in keys]
}
print(f'Deleting keys {keys} from bucket {s3_bucket.name}')
return s... | bigcode/self-oss-instruct-sc2-concepts |
from operator import add
from functools import reduce
def sum_node_list(node_list):
"""Custom sum function in order to avoid create redundant nodes in Python sum implementation."""
return reduce(add, node_list) | bigcode/self-oss-instruct-sc2-concepts |
def translate_task(contest: str, contest_no: int, task: str) -> str:
"""
Atcoderは第N回目コンテストのNの値によって、
URLに含まれるタスク名がアルファベット(a, b, c, d)表される場合と
数字(1, 2, 3, 4)で表される場合がある
数字だった場合は、タスク名(A, B, C, D)をアルファベットの小文字に変換、
アルファベットだった場合は小文字に変換する
Parameters
----------
contest : str
コンテスト名. AB... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def read_bin_fragment(struct_def, fileh, offset=0, data=None, byte_padding=None):
"""It reads a chunk of a binary file.
You have to provide the struct, a file object, the offset (where to start
reading).
Also you can provide an optional dict that will be populated with the
extracted... | bigcode/self-oss-instruct-sc2-concepts |
import six
def scale_result(result, scaler):
"""Return scaled result.
Args:
result (dict): Result.
scaler (number): Factor by which results need to be scaled.
Returns:
dict: Scaled result.
"""
scaled_result = {}
for key, val in six.iteritems(result):
scaled_r... | bigcode/self-oss-instruct-sc2-concepts |
def cross(o, a, b):
"""Cross-product for vectors o-a and o-b
"""
xo, yo = o
xa, ya = a
xb, yb = b
return (xa - xo)*(yb - yo) - (ya - yo)*(xb - xo) | bigcode/self-oss-instruct-sc2-concepts |
import re
def findall(string, substring):
"""
Find the index of all occurences of a substring in a string.
@arg string:
@type string: string
@arg substring:
@type substring: string
@returns: List of indices.
@rtype: list[int]
"""
occurences = []
for i in re.finditer(subs... | bigcode/self-oss-instruct-sc2-concepts |
def set_kwargs_from_dflt(passed: dict, dflt: dict) -> dict:
"""Updates ++passed++ dictionary to add any missing keys and
assign corresponding default values, with missing keys and
default values as defined by ++dflt++"""
for key, val in dflt.items():
passed.setdefault(key, val)
return pass... | bigcode/self-oss-instruct-sc2-concepts |
import math
def ph_from_hydroxide(concentration):
"""Returns the pH from the hydroxide ion concentration."""
return 14 + math.log(concentration) | bigcode/self-oss-instruct-sc2-concepts |
def dont_linkify_urls(attrs, new=False):
"""Prevent file extensions to convert to links.
This is a callback function used by bleach.linkify().
Prevent strings ending with substrings in `file_exts` to be
converted to links unless it starts with http or https.
"""
file_exts = ('.py', '.md', '.sh'... | bigcode/self-oss-instruct-sc2-concepts |
def check_if_odd(sum: int = 36) -> int:
"""
Check if the last digit in the sum is even or odd. If even return 0.
If odd then floor division by 10 is used to remove the last number.
Process continues until sum becomes 0 because no more numbers.
>>> check_if_odd(36)
0
>>> check_if_odd(33)
... | bigcode/self-oss-instruct-sc2-concepts |
def OUTPUT(out):
"""Get dictionary serialization for an output object.
Parameters
----------
out: vizier.viztrail.module.output.OutputObject
Object in module output stream
Returns
-------
dict
"""
return {'type': out.type, 'value': out.value} | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Any
import json
def load_model_data(filename: str) -> Dict[Any, Any]:
"""
Loads some model_data that was generated by the model.
:param filename:
The name of the model_data file to open.
:return:
The JSON model_data, loaded as a `dict`.
... | bigcode/self-oss-instruct-sc2-concepts |
def _leisure_test(norw):
"""Tests if a node or way is a leisure place"""
return 'leisure' in norw.tags | bigcode/self-oss-instruct-sc2-concepts |
def sanitize_properties(properties):
"""
Ensures we don't pass any invalid values (e.g. nulls) to hubspot_timestamp
Args:
properties (dict):
the dict of properties to be sanitized
Returns:
dict:
the sanitized dict
"""
return {
key: value if valu... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_conll_identifier(
value: str, line: int, field: str, *, non_zero=False
) -> int:
"""Parse a CoNLL token identifier, raise the appropriate exception if it is invalid.
Just propagate the exception if `value` does not parse to an integer.
If `non_zero` is truthy, raise an exception if `va... | bigcode/self-oss-instruct-sc2-concepts |
def _process_line(line):
"""Escape string literals and strip newline characters."""
if not isinstance(line, str):
raise TypeError("Routine lines should be strings.")
if line.endswith('\n'):
line = line[:-1]
return line | bigcode/self-oss-instruct-sc2-concepts |
def HasSeparator(line):
"""To tell if a separator ends in line"""
if line[-1] == '\n':
return True
return False | bigcode/self-oss-instruct-sc2-concepts |
def get_set_sizes(df):
"""
get sizes of training and test sets based on size of dataset.
testing set: 10% of training set
:return: training_set_size, testing_set_size
"""
data_set_size = len(df.index)
training_set_size = data_set_size * 0.9
testing_set_size = data_set_size * 0.1
r... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def get_logger(name):
"""
Return a multiprocess safe logger.
:param str name: Name of the logger.
:return: A multiprocess safe logger.
:rtype: :py:class:`logging.Logger`.
"""
return logging.getLogger(name) | bigcode/self-oss-instruct-sc2-concepts |
import re
def ask_yes_no_question(question):
"""
Asks the user to answer the given question with yes or no.
Yes, Y, No and N are accepted as valid responses (case insensitive).
:param question: the question to be answered
:type question: str
:return: the user's answer
:rtype: bool
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def _wiki_request(**params):
"""
Make a request to the Wikipedia API using the given search parameters.
Returns a parsed dict of the JSON response.
"""
api_url = "http://en.wikipedia.org/w/api.php"
params['format'] = "json"
params['action'] = "query"
headers = {
'User-Agent': "wikipedia/0.... | bigcode/self-oss-instruct-sc2-concepts |
def HTMLColorToRGB(colorstring):
""" convert #RRGGBB to an (R, G, B) tuple """
colorstring = colorstring.strip()
if colorstring[0] == '#': colorstring = colorstring[1:]
if len(colorstring) != 6:
raise ValueError, "input #%s is not in #RRGGBB format" % colorstring
r, g, b = colorstring[:2], colorstring[2:4], colo... | bigcode/self-oss-instruct-sc2-concepts |
def calc_distance(mol, atom1, atom2):
"""
Calculates the distance between two atoms on a given molecule.
Args:
mol (RDKit Mol): The molecule containing the two atoms.
atom1 (int): The index of the first atom on the molecule.
atom2 (int): The index if the second atom on the molecule.... | bigcode/self-oss-instruct-sc2-concepts |
import re
import glob
def get_ergowear_trial_files(ergowear_trial_path):
"""Find all files of an ergowear trial inside a directory.
Args:
ergowear_trial_path(str): path to the trial directory
containing ergowear files.
Returns:
(list[str]): list with all ergowear trial paths ... | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def load_data(in_file):
"""load data from file
Parameters
----------
in_file: str
input file path
Returns
-------
data:
loaded data
"""
with open(in_file, 'rb') as f:
data = pickle.load(f)
return data | bigcode/self-oss-instruct-sc2-concepts |
def is_logged_in(session):
"""Return whether user is logged into session `session`"""
return 'user' in session | bigcode/self-oss-instruct-sc2-concepts |
def addListsByValue(a, b):
"""
returns a new array containing the sums of the two array arguments
(c[0] = a[0 + b[0], etc.)
"""
c = []
for x, y in zip(a, b):
c.append(x + y)
return c | bigcode/self-oss-instruct-sc2-concepts |
def get_wait_for_acknowledgement_of(response_modifier):
"""
Gets the `wait_for_acknowledgement` value of the given response modifier.
Parameters
----------
wait_for_acknowledgement : `None`, ``ResponseModifier``
The respective response modifier if any,
Returns
-------
w... | bigcode/self-oss-instruct-sc2-concepts |
def clamp_bbox(bbox, shape):
"""
Clamp a bounding box to the dimensions of an array
Parameters
----------
bbox: ndarray([i1, i2, j1, j2])
A bounding box
shape: tuple
Dimensions to which to clamp
"""
[i1, i2, j1, j2] = bbox
j1 = max(0, int(j1))
i1 = max(0, int(i1))... | bigcode/self-oss-instruct-sc2-concepts |
import re
def sanitise_username(username):
"""
Sanitise a username for use in a keypair name.
"""
return re.sub("[^a-zA-Z0-9]+", "-", username) | bigcode/self-oss-instruct-sc2-concepts |
def read_config(in_name):
"""
Read a fromage config file.
Parameters
----------
in_name : str
Name of the file to read
Returns
-------
settings : dict
A dictionary with the keywords and the user inputs as strings
"""
with open(in_name, "r") as data:
line... | bigcode/self-oss-instruct-sc2-concepts |
import re
def trim_data_file_name(name):
""""Remove date in name for easier tracking in the repo."""
return re.sub(r"(.*DOH COVID Data Drop_ \d{8} - )", r"", name) | bigcode/self-oss-instruct-sc2-concepts |
def alwaysTrue( x ):
"""This function always returns True - its used for multiple value selection function
to accept all other values"""
return True | bigcode/self-oss-instruct-sc2-concepts |
def index(request):
""" Simple Hello IgglePigglePartyPants
"""
return 'Hello IgglePigglePartyPants!' | bigcode/self-oss-instruct-sc2-concepts |
def str2float(str_val, err_val=None):
"""
Convert a string to a float value, returning an error
value if an error occurs. If no error value is provided
then an exception is thrown.
:param str_val: string variable containing float value.
:param err_val: value to be returned if error occurs. If N... | bigcode/self-oss-instruct-sc2-concepts |
def reverseComplement(dna_seq):
"""
Returns the reverse complement of the DNA sequence.
"""
tmpseq = dna_seq.upper();
revcomp = ''
for nucleotide in tmpseq:
if nucleotide == 'A':
revcomp += 'T'
elif nucleotide == 'T':
revcomp += 'A'
elif nucleotide... | bigcode/self-oss-instruct-sc2-concepts |
def non_empty(title: str, value: str, join_with: str = " -> ", newline=True) -> str:
"""
Return a one-line formatted string of "title -> value" but only if value is a
non-empty string. Otherwise return an empty string
>>> non_empty(title="title", value="value")
'title -> value\\n'
>>> non_empty... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def build_and_check_sets_experiments(all_vars):
"""
Description:
First we create a variable called 'setExps',
which is a dict that goes from set name
to a list of experiments belonging
to that set (set is equivalent to 'lane').
We then double check that ... | bigcode/self-oss-instruct-sc2-concepts |
def prob_mass_green_from_ndvi(ndvi, old_min=0.3, old_max=0.9):
"""
Calculate probability mass for greenness from NDVI values
:param ndvi:
:param old_min:
:param old_max:
:return:
"""
if ndvi < old_min:
return 0
elif ndvi >= old_max:
return 1
else:
new_max ... | bigcode/self-oss-instruct-sc2-concepts |
def identify_meshes(dir_):
"""List meshes and identify the challenge/track in a directory tree."""
meshes_track1 = list(dir_.glob("**/*_normalized.npz"))
meshes_track2 = list(dir_.glob("**/fusion_textured.npz"))
meshes_challenge2 = list(dir_.glob("**/model_*.obj"))
if meshes_track1:
meshes =... | bigcode/self-oss-instruct-sc2-concepts |
async def trigger_mot_unique(message):
"""Règle d'IA : réaction à un mot unique (le répète).
Args:
message (~discord.Message): message auquel réagir.
Returns:
- ``True`` -- si le message correspond et qu'une réponse a été
envoyée
- ``False`` -- sinon
"""
if len(me... | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def read_file(filename):
"""Read a file and return the text content."""
inputfile = codecs.open(filename, "r", "utf-8")
data = inputfile.read()
inputfile.close()
return data | bigcode/self-oss-instruct-sc2-concepts |
import csv
import json
def file_to_dict_list(filepath):
"""Accept a path to a CSV, TSV or JSON file and return a dictionary list"""
if '.tsv' in filepath:
reader = csv.DictReader(open(filepath), dialect='excel-tab')
elif '.csv' in filepath:
reader = csv.DictReader(open(filepath))
elif ... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def getMountPoint (path):
""" Return mount point of path """
path = Path (path).resolve ()
while True:
if path.is_mount ():
return path
path = path.parent | bigcode/self-oss-instruct-sc2-concepts |
import textwrap
def hex_to_rgb(value):
"""
Convert color`s value in hex format to RGB format.
>>> hex_to_rgb('fff')
(255, 255, 255)
>>> hex_to_rgb('ffffff')
(255, 255, 255)
>>> hex_to_rgb('#EBF442')
(235, 244, 66)
>>> hex_to_rgb('#000000')
(0, 0, 0)
>>> hex_to_rgb('#000')
... | bigcode/self-oss-instruct-sc2-concepts |
def map_range(x, X_min, X_max, Y_min, Y_max):
"""
Linear mapping between two ranges of values
"""
X_range = X_max - X_min
Y_range = Y_max - Y_min
XY_ratio = X_range / Y_range
y = ((x - X_min) / XY_ratio + Y_min) // 1
return int(y) | bigcode/self-oss-instruct-sc2-concepts |
def simple_interest_fv(P, r, t):
"""The future value of a simple interest product consists of the initial deposit, called the
principal and denoted by P, plus all the interest earned since the money was deposited in the account
Parameters
----------
P: float
Principal, initial deposit.
... | bigcode/self-oss-instruct-sc2-concepts |
def list_tables(conn):
"""List all tables in a SQLite database
Args:
conn: An open connection from a SQLite database
Returns:
list: List of table names found in the database
"""
cur = conn.cursor()
cur.execute("SELECT name FROM sqlite_master")
return [i[0] for i in cur.fetc... | bigcode/self-oss-instruct-sc2-concepts |
def sum_multiples(limit):
"""Sums all multiples of 3 and 5 under `limit`
Args:
limit (int): The limit that the sums will be calculated up to
Returns:
int : The sum of all multiples of 3 and 5 up to `limit`
"""
return sum(x for x in range(limit) if x % 3 == 0 or x % 5 == 0) | bigcode/self-oss-instruct-sc2-concepts |
def get_filename_from_path(text):
"""Get the filename from a piece of text.
Find the last '/' and returns the words after that.
"""
return text[text.rindex('/') + 1:] | bigcode/self-oss-instruct-sc2-concepts |
import six
def ensure_unicode_string(value: str) -> str:
"""Ensure the value is a string, and return it as unicode."""
if not isinstance(value, six.string_types):
raise TypeError("Expected string value, got: {}".format(value))
return six.text_type(value) | bigcode/self-oss-instruct-sc2-concepts |
def mask_tensor(tensor, mask):
"""Mask the provided tensor
Args:
tensor - the torch-tensor to mask
mask - binary coefficient-masking tensor. Has the same type and shape as `tensor`
Returns:
tensor = tensor * mask ;where * is the element-wise multiplication operator
"""
ass... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hash_url(url):
"""Returns a sha256 hash of the given URL."""
h = hashlib.sha256()
h.update(url.encode('ascii', errors='ignore'))
return h.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def bin(number, prefix="0b"):
"""
Converts a long value to its binary representation.
:param number:
Long value.
:param prefix:
The prefix to use for the bitstring. Default "0b" to mimic Python
builtin ``bin()``.
:returns:
Bit string.
"""
if number is None:
raise TypeError("'%... | bigcode/self-oss-instruct-sc2-concepts |
import random
def bernoulli_trial(p):
"""베르누이 확률 변수 1 또는 0를 확률 p의 따라서 리턴"""
x = random.random() # random(): 0이상 1미만의 난수 리턴
return 1 if x < p else 0 | bigcode/self-oss-instruct-sc2-concepts |
def session_num_pageviews(session):
"""Number of pageviews in session."""
return len([r for r in session if 'is_pageview' in r and r['is_pageview'] == 'true']) | bigcode/self-oss-instruct-sc2-concepts |
def as_int(tokens):
""" Converts the token to int if possible. """
return int(tokens[0]) if tokens else None | bigcode/self-oss-instruct-sc2-concepts |
import mpmath
def cdf(x, mu=0, sigma=1):
"""
Normal distribution cumulative distribution function.
"""
# Defined here for consistency, but this is just mpmath.ncdf
return mpmath.ncdf(x, mu, sigma) | bigcode/self-oss-instruct-sc2-concepts |
def swizzle(pixels, width, height, blockW=4, blockH=4):
"""Swizzle pixels into format used by game.
pixels: buffer of pixels, which should be an np.array of
at least 2 dimensions.
width, height: size of buffer.
blockW, blockH: swizzle block size, which depends on pixel format.
Returns a li... | bigcode/self-oss-instruct-sc2-concepts |
def safeadd(*values):
""" Adds all parameters passed to this function. Parameters which are None
are ignored. If all parameters are None, the function will return None
as well.
"""
values = [v for v in values if v is not None]
return sum(values) if values else None | bigcode/self-oss-instruct-sc2-concepts |
def apply_fn_over_range(fn, start_time, end_time, arglist):
"""Apply a given function per second quanta over a time range.
Args:
fn: The function to apply
start_time: The starting time of the whole duration
end_time: The ending time of the whole duration
arglist: Additional argument list
Returns... | bigcode/self-oss-instruct-sc2-concepts |
def delimit(items):
"""
Delimit the iterable of strings
"""
return '; '.join(i for i in items) | bigcode/self-oss-instruct-sc2-concepts |
def get_scale(W, H, scale):
"""
Computes the scales for bird-eye view image
Parameters
----------
W : int
Polygon ROI width
H : int
Polygon ROI height
scale: list
[height, width]
"""
dis_w = int(scale[1])
dis_h = int(scale[0])
ret... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def gram(m: torch.Tensor) -> torch.Tensor:
"""
Return the Gram matrix of `m`
Args:
m (tensor): a matrix of dim 2
Returns:
The Gram matrix
"""
g = torch.einsum('ik,jk->ij', m, m) / m.shape[1]
return g | bigcode/self-oss-instruct-sc2-concepts |
def find_lowest(tem, l):
"""
:param tem:int, the temperature that user entered.
:param l:int, the lowest temperature so far.
This function finds the lowest temperature.
"""
min = l
if tem < l:
return tem
return l | bigcode/self-oss-instruct-sc2-concepts |
def find_sol(c, ws, vs, memo):
"""
Finds an optimal solution for the given instance of the knapsack problem
with weight capacity c, item weights ws, and item values vs, provided
maximum total value for subproblems are memoized in memo.
"""
sol = []
for n in reversed(range(len(ws))):
... | bigcode/self-oss-instruct-sc2-concepts |
def _masked_idx(mask, indices):
"""Return index expression for given indices, only if mask is also true there.
Parameters:
mask: True/False mask
indices: indices into array, of shape (n, mask.ndim)
Returns:
idx: numpy index expression for selected indices
idx_mask: mask of s... | bigcode/self-oss-instruct-sc2-concepts |
def GMLreverser(pointlist):
"""Reverses the order of the points, i.e. the normal of the ring."""
revlist = pointlist[::-1]
return revlist | bigcode/self-oss-instruct-sc2-concepts |
def natMult3and5(limit):
"""Find the sum of all the multiples of 3 or 5 below 'limit'"""
sum = 0
for i in range(limit):
if i % 5 == 0 or i % 3 == 0:
sum += i
return sum | 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.