seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def get_seating_row(plan, seat_number):
"""
Given a seating plan and a seat number, locate and return the dictionary
object for the specified row
:param plan: Seating plan
:param seat_number: Seat number e.g. 3A
:raises ValueError: If the row and/or seat number don't exist in the seating plan
... | bigcode/self-oss-instruct-sc2-concepts |
def hex_to_int(hexa):
"""Convert a hexadecimal string to an int"""
vals = {'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15}
num = 0
power = 0
for d in hexa[::-1]:
try:
num += int(d) * 16 ** power
except ValueError:
num += vals[d] * 16 ** power
po... | bigcode/self-oss-instruct-sc2-concepts |
def get_e_rtd(e_dash_rtd, bath_function):
"""「エネルギーの使用の合理化に関する法律」に基づく「特定機器の性能の向上に関する製造事業者等の 判断の基準等」(ガス温水機器)
に定義される「エネルギー消費効率」 から 当該給湯器の効率を取得 (9)
Args:
e_dash_rtd(float): エネルギーの使用の合理化に関する法律」に基づく「特定機器の性能の向上に関する製造事業者等の 判断の基準等」(ガス温水機器)に定義される「エネルギー消費効率」
bath_function(str): ふろ機能の種類
Returns:
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def flatten(lst):
"""
Flattens a list or iterable. Note that this chunk allocates more memory.
Argument:
lst (list or iteratble): input vector to be flattened
Returns:
one dimensional tensor with all elements of lst
"""
tmp = [i.contiguous().view(-1, 1) for i in lst]
... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def parse_duration(string):
"""Parse a duration of the form ``[hours:]minutes:seconds``."""
if string == "":
return None
duration = string.split(":")[:3]
try:
duration = [int(i) for i in duration]
except ValueError:
logger = logging.getLogger(__name__)
... | bigcode/self-oss-instruct-sc2-concepts |
def get_all_subclasses(cls):
"""
Get all subclasses of a given class. Note that the results will depend on current imports.
:param cls: a class.
:return: the set of all subclasses.
"""
return set(cls.__subclasses__()).union(
[s for c in cls.__subclasses__() for s in get_all_subclasses(c... | bigcode/self-oss-instruct-sc2-concepts |
def module_level_function(param1, param2=None, *args, **kwargs):
"""Evaluate to true if any paramaters are greater than 100.
This is an example of a module level function.
Function parameters should be documented in the ``Parameters`` section.
The name of each parameter is required. The type and descr... | bigcode/self-oss-instruct-sc2-concepts |
def readList_fromFile(fileGiven):
"""Reads list from the input file provided. One item per row."""
# open file and read content into list
lineList = [line.rstrip('\n') for line in open(fileGiven)]
return (lineList) | bigcode/self-oss-instruct-sc2-concepts |
def rho_dust(f):
"""
Dust density
"""
return f['u_dustFrac'] * f['rho'] | bigcode/self-oss-instruct-sc2-concepts |
def findMedian(x):
"""Compute the median of x.
Parameters
----------
x: array_like
An array that can be sorted.
Returns
-------
median_x: float
If there are an odd number of elements in x, median_x is the
middle element; otherwise, median_x is the average of the two... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def remove_existing_nodes_from_new_node_list(new_nodes, current_nodes) -> List[str]:
"""Return a list of nodes minus the nodes (and masters) already in the inventory (groups 'nodes' and 'masters')."""
return [node for node in new_nodes if node not in current_nodes] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def get_anthropometrics(segment_name: str,
total_mass: float) -> Dict[str, float]:
"""
Get anthropometric values for a given segment name.
For the moment, only this table is available:
D. A. Winter, Biomechanics and Motor Control of Human Movement,
... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_voting_method(method):
"""Flatten a voting method data structure.
The incoming ``method`` data structure is as follows. At the time of
writing, all elections have an identical structure. In practice. the None
values could be different scalars. ::
{
"instructions": {
... | bigcode/self-oss-instruct-sc2-concepts |
def get_youtube_url(data: dict) -> str:
"""
Returns the YouTube's URL from the returned data by YoutubeDL, like
https://www.youtube.com/watch?v=dQw4w9WgXcQ
"""
return data['entries'][0]['webpage_url'] | bigcode/self-oss-instruct-sc2-concepts |
def expand_request_pixels(request, radius=1):
""" Expand request by `radius` pixels. Returns None for non-vals requests
or point requests. """
if request["mode"] != "vals": # do nothing with time and meta requests
return None
width, height = request["width"], request["height"]
x1, y1, x2, ... | bigcode/self-oss-instruct-sc2-concepts |
def enumerate_tagged_methods(instance, tag, expected_value=None):
"""Enumerates all methods of instance which has an attribute named tag."""
methods = []
for attr in dir(instance):
value = getattr(instance, attr)
if callable(value):
try:
tagged_value = getattr(va... | bigcode/self-oss-instruct-sc2-concepts |
def get_bit(z, i):
"""
gets the i'th bit of the integer z (0 labels least significant bit)
"""
return (z >> i) & 0x1 | bigcode/self-oss-instruct-sc2-concepts |
import torch
def unit_sphere(points, return_inverse=False):
"""Normalize cloud to zero mean and within unit ball"""
mean = points[:, :3].mean(axis=0)
points[:, :3] -= mean
furthest_distance = torch.max(torch.linalg.norm(points[:, :3], dim=-1))
points[:, :3] = points[:, :3] / furthest_distance
... | bigcode/self-oss-instruct-sc2-concepts |
def check_dims(matIn1, matIn2):
"""
function to check if dimensions of two matrices are compatible for multiplication
input: two matrices matIn1(nXm) and matIn2(mXr)
returns: Boolean whether dimensions compatible or not
"""
m,n = matIn1.shape
r,k = matIn2.shape
if r == n:
return True
else:
return False | bigcode/self-oss-instruct-sc2-concepts |
def check_ascending(ra, dec, vel, verbose=False):
"""
Check if the RA, DEC and VELO axes of a cube are in ascending order.
It returns a step for every axes which will make it go in ascending order.
:param ra: RA axis.
:param dec: DEC axis.
:param vel: Velocity axis.
:returns: Step for R... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_estimator(estimator):
""" Returns an estimator object given an estimator object or class
Parameters
----------
estimator : Estimator class or object
Returns
-------
estimator : Estimator object
"""
if inspect.isclass(estimator):
estimator = estimat... | bigcode/self-oss-instruct-sc2-concepts |
def cmd_erasure_code_profile(profile_name, profile):
"""
Return the shell command to run to create the erasure code profile
described by the profile parameter.
:param profile_name: a string matching [A-Za-z0-9-_.]+
:param profile: a map whose semantic depends on the erasure code plugin
:ret... | bigcode/self-oss-instruct-sc2-concepts |
from pkgutil import iter_modules
from typing import Iterable
from typing import List
def check_dependencies(dependencies: Iterable[str], prt: bool = True) -> List[str]:
"""
Check whether one or more dependencies are available to be imported.
:param dependencies: The list of dependencies to check the availability ... | bigcode/self-oss-instruct-sc2-concepts |
def outName(finpName):
"""Returns output filename by input filename"""
i = finpName.rfind('.')
if i != -1:
finpName = finpName[0:i]
return finpName + '.hig' | bigcode/self-oss-instruct-sc2-concepts |
def _convert_node_attr_types(G, node_type):
"""
Convert graph nodes' attributes' types from string to numeric.
Parameters
----------
G : networkx.MultiDiGraph
input graph
node_type : type
convert node ID (osmid) to this type
Returns
-------
G : networkx.MultiDiGraph... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
import requests
def resolve_gravatar(email):
"""
Given an email, returns a URL if that email has a gravatar set.
Otherwise returns None.
"""
gravatar = 'https://gravatar.com/avatar/' + hashlib.md5(email).hexdigest() + '?s=512'
if requests.head(gravatar, params={'d': '404'}):
... | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def get_custom_class_mapping(modules):
"""Find the custom classes in the given modules and return a mapping with class name as key and class as value"""
custom_class_mapping = {}
for module in modules:
for obj_name in dir(module):
if not obj_name.endswith("Custom"):
... | bigcode/self-oss-instruct-sc2-concepts |
def labels_trick(outputs, labels, criterion):
"""
Labels trick calculates the loss only on labels which appear on the current mini-batch.
It is implemented for classification loss types (e.g. CrossEntropyLoss()).
:param outputs: The DNN outputs of the current mini-batch (torch Tensor).
:param labels... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_tweaked_uc_pc(job):
"""Calculate unit cell and primitive cell coordinates with tweaked Hydrogen coordinates"""
return "../../../codes/calc_htweaked_pc_uc" | bigcode/self-oss-instruct-sc2-concepts |
def fill_context_mask(mask, sizes, v_mask, v_unmask):
"""Fill attention mask inplace for a variable length context.
Args
----
mask: Tensor of size (B, N, D)
Tensor to fill with mask values.
sizes: list[int]
List giving the size of the context for each item in
the batch. Posit... | bigcode/self-oss-instruct-sc2-concepts |
def build_dictionary(chars):
"""
Organizes data read from files in a dictionary
:param chars: all chars read from files to learn
:return: the dictionary
"""
d = {}
for key in chars:
for c in chars[key]:
if c[3] not in d:
d[c[3]] = set(c[1])
e... | bigcode/self-oss-instruct-sc2-concepts |
def celsius_to_fahrenheit(T_celsius):
"""
Convert celsius temperature to fahrenheit temperature.
PARAMETERS
----------
T_celsiu: tuple
A celsius expression of temperature
RETURNS
----------
T_fahrenheit: float
The fahrenheit expression of temperature T_celsius
... | bigcode/self-oss-instruct-sc2-concepts |
def application(environ, start_response):
"""
符合WSGI标准的一个HTTP处理函数,web程序入口
:param environ: 请求的信息
:param start_response: 返回响应的回调函数
:return:
"""
# 响应信息
start_response("200 OK", [("Content-Type", "text/html")])
text = "<h1>hello world</h1>"
for i in environ.items():
print(i)... | bigcode/self-oss-instruct-sc2-concepts |
def merge(dct1, dct2):
"""Merges two dictionaries"""
return {**dct1, **dct2} | bigcode/self-oss-instruct-sc2-concepts |
def validFSUNum(req):
"""
Valid FSU Num
- returns False if FSU Num contains characters, True otherwise
"""
return str(req['FsuNum']).isdigit() | bigcode/self-oss-instruct-sc2-concepts |
def remove_duplicates(lst):
""" Return input list without duplicates. """
seen = []
out_lst = []
for elem in lst:
if elem not in seen:
out_lst.append(elem)
seen.append(elem)
return out_lst | bigcode/self-oss-instruct-sc2-concepts |
def add_dicts(*args, **kwargs):
"""
Utility to "add" together zero or more dicts passed in as positional
arguments with kwargs. The positional argument dicts, if present, are not
mutated.
"""
result = {}
for d in args:
result.update(d)
result.update(kwargs)
return result | bigcode/self-oss-instruct-sc2-concepts |
def in_board(pos, board):
"""returns True if pos (y, x) is within the board's Rect."""
return bool(board.rect.collidepoint(pos)) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def update_nested_dict(d: Dict, u: Dict) -> Dict:
"""
Merge two dicts.
https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
:param d: dict to be overwritten in case of conflicts.
:param u: dict to be merged into d.
:return:
... | bigcode/self-oss-instruct-sc2-concepts |
def to_list(v):
"""Convert any non list to a singleton list"""
if isinstance(v, list):
return v
else:
return [v] | bigcode/self-oss-instruct-sc2-concepts |
import pickle
def debrine(filename, encoding='latin1'):
"""pickle.load(open(filename))
Use encoding='latin1' to load datetime, numpy, or scikit objects pickled in
Python 2 in Python 3. (Latin-1 works for any input as it maps the byte
values 0-255 to the first 256 Unicode codepoints directly:
http... | bigcode/self-oss-instruct-sc2-concepts |
def __indent_text_block(text):
""" Indent a text block """
lines = text.splitlines()
if len(lines) > 1:
out = lines[0] + "\r\n"
for i in range(1, len(lines)-1):
out = out + " " + lines[i] + "\r\n"
out = out + " " + lines[-1]
return out
return tex... | bigcode/self-oss-instruct-sc2-concepts |
def get_tag_list(element_tree):
"""
Function to generate a list of all element tags from an xml file
:param element_tree:
:return:
"""
return list(set([c.tag for c in element_tree.iter()])) | bigcode/self-oss-instruct-sc2-concepts |
def scan(ln, char_maps, tokenize=True):
"""Scan beginning of each line for BASIC keywords, petcat special
characters, or ascii characters, convert to tokenized bytes, and
return remaining line segment after converted characters are removed
Args:
ln (str): Text of each line segment to pars... | bigcode/self-oss-instruct-sc2-concepts |
def discrete_signal(signal0, step_size):
"""
SNIPPET 10.3 - SIZE DISCRETIZATION TO PREVENT OVERTRADING
Discretizes the bet size signal based on the step size given.
:param signal0: (pandas.Series) The signal to discretize.
:param step_size: (float) Step size.
:return: (pandas.Series) The discre... | bigcode/self-oss-instruct-sc2-concepts |
def overlap_coefficient(label1, label2):
""" Distance metric comparing set-similarity. """
#the original formula used float, but it doesn't seem to make any difference
#return float(len(label1 & label2)) / min(len(label1), len(label2))
if min(len(label1), len(label2)) == 0:
return 0
else:
return len(label1.int... | bigcode/self-oss-instruct-sc2-concepts |
from typing import OrderedDict
def separate_orders_by_ticket_type(list_in, ticket_types):
"""
Inputs:
list_in - List containing ticket orders
ticket_types - List of all ticket types
Outputs:
dict_out - A dictionary keyed to ticket types, containing a list of
ticket ord... | bigcode/self-oss-instruct-sc2-concepts |
def import_module(dotted_path):
"""Import a module path like 'a.b.c' => c module"""
mod = __import__(dotted_path, globals(), locals(), [])
for name in dotted_path.split('.')[1:]:
try:
mod = getattr(mod, name)
except AttributeError:
raise AttributeError("Module %r has ... | bigcode/self-oss-instruct-sc2-concepts |
def getOverlap(a, b):
"""Return the overlap of two ranges. If the values of a overlap with
the values of b are mutually exclusive then return 0"""
return max(0, 1 + min(a[1], b[1]) - max(a[0], b[0])) | bigcode/self-oss-instruct-sc2-concepts |
def html_path(request, goldendir):
"""NYU Academic Calendar HTML file path"""
path = 'New York University - University Registrar - Calendars - Academic Calendar.html' # noqa
return goldendir.join(path) | bigcode/self-oss-instruct-sc2-concepts |
def brightness_from_percentage(percent):
"""Convert percentage to absolute value 0..255."""
return (percent * 255.0) / 100.0 | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _log_sum_exp(mat, axis=0):
"""
Computes the log-sum-exp of a matrix with a numerically stable scheme,
in the user-defined summation dimension: exp is never applied
to a number >= 0, and in each summation row, there is at least
one "exp(0)" to stabilize the sum.
For instance, ... | bigcode/self-oss-instruct-sc2-concepts |
import json
def to_json_sorted(text):
"""
Converts text to sorted(alphabetically on the attribute names) json value
:param text:
text to be converted to json
:return:
sorted json value
"""
json_value = json.dumps(json.loads(text), sort_keys=True, indent=0)
retur... | bigcode/self-oss-instruct-sc2-concepts |
def get_column_headers(results):
"""Return the columnHeaders object from a Google Analytics API request.
:param results: Google Analytics API results set
:return: Python dictionary containing columnHeaders data
"""
if results['columnHeaders']:
return results['columnHeaders'] | bigcode/self-oss-instruct-sc2-concepts |
def true_fracture_stress(fracture_force, initial_cross_section, reduction_area_fracture):
"""
Calculation of the true fracture stress (euqation FKM Non-linear (static assessment))
Parameters
----------
fracture_force : float
from experimental results
initial_cross_section : float
... | bigcode/self-oss-instruct-sc2-concepts |
def build_url(video_id: str) -> str:
"""Converts a YouTube video ID into a valid URL.
Args:
video_id: YouTube video ID.
Returns:
YouTube video URL.
"""
return f"https://youtube.com/watch?v={video_id}" | bigcode/self-oss-instruct-sc2-concepts |
def partition_seq(seq, size):
"""
Splits a sequence into an iterable of subsequences. All subsequences are of the given size,
except the last one, which may be smaller. If the input list is modified while the returned
list is processed, the behavior of the program is undefined.
:param seq: the list... | bigcode/self-oss-instruct-sc2-concepts |
def write_file(filename="", text=""):
"""
Writes a string to a text file (UTF8) and
returns the number of characters written.
"""
with open(filename, 'w') as f:
return f.write(text) | bigcode/self-oss-instruct-sc2-concepts |
def ts(avroType):
"""Create a human-readable type string of a type.
:type avroType: codec.datatype.AvroType
:param avroType: type to print out
:rtype: string
:return: string representation of the type.
"""
return repr(avroType) | bigcode/self-oss-instruct-sc2-concepts |
import ntpath
def path_leaf(path):
"""Return the base name of a path: '/<path>/base_name.txt'."""
head, tail = ntpath.split(path)
return tail or ntpath.basename(head) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def generate_attention_masks(batch, source_lengths):
"""Generate masks for padded batches to avoid self-attention over pad tokens
@param batch (Tensor): tensor of token indices of shape (batch_size, max_len)
where max_len is length of longest sequence in the batch
@... | bigcode/self-oss-instruct-sc2-concepts |
def new_in_list(my_list, idx, element):
"""Replace an element in a copied list at a specific position."""
if idx < 0 or idx > (len(my_list) - 1):
return (my_list)
copy = [x for x in my_list]
copy[idx] = element
return (copy) | bigcode/self-oss-instruct-sc2-concepts |
def canonicalize_eol(text, eol):
"""Replace any end-of-line sequences in TEXT with the string EOL."""
text = text.replace('\r\n', '\n')
text = text.replace('\r', '\n')
if eol != '\n':
text = text.replace('\n', eol)
return text | bigcode/self-oss-instruct-sc2-concepts |
import torch
def soft_cross_entropy_tinybert(input, targets):
""" Soft Cross Entropy loss for hinton's dark knowledge
Args:
input (`Tensor`): shape of [None, N]
targets (`Tensor`): shape of [None, N]
Returns:
loss (`Tensor`): scalar tensor
"""
student_l... | bigcode/self-oss-instruct-sc2-concepts |
def sanitize_sacred_arguments(args):
"""
This function goes through and sanitizes the arguments to native types.
Lists and dictionaries passed through Sacred automatically become
ReadOnlyLists and ReadOnlyDicts. This function will go through and
recursively change them to native lists and dicts.
... | bigcode/self-oss-instruct-sc2-concepts |
def get_psr_name(psr):
"""
Get the pulsar name from the Tempo(2)-style parameter files by trying the
keys "PSRJ", "PSRB", "PSR", and "NAME" in that order of precedence.
Parameters
----------
psr: PulsarParameter
A :class:`~cwinpy.parfile.PulsarParameters` object
Returns
-------... | bigcode/self-oss-instruct-sc2-concepts |
def read_smi_file(filename, unique=True, add_start_end_tokens=False):
"""
Reads SMILES from file. File must contain one SMILES string per line
with \n token in the end of the line.
Args:
filename (str): path to the file
unique (bool): return only unique SMILES
Returns:
smiles... | bigcode/self-oss-instruct-sc2-concepts |
def predict(interpreter, audio):
"""Feed an audio signal with shape [1, len_signal] into the network and get the predictions"""
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Enable dynamic shape inputs
interpreter.resize_tensor_input(input_deta... | bigcode/self-oss-instruct-sc2-concepts |
def convert_tuple_to_string(creds_tuple):
"""Represent a MAAS API credentials tuple as a colon-separated string."""
if len(creds_tuple) != 3:
raise ValueError(
"Credentials tuple does not consist of 3 elements as expected; "
"it contains %d."
% len(creds_tuple))
r... | bigcode/self-oss-instruct-sc2-concepts |
def detectEavesdrop(key1, key2, errorRate):
"""Return True if Alice and Bob detect Eve's interference, False otherwise."""
if len(key1) == 0 or len(key2) == 0:
return True
if len(key1) != len(key2):
return True
tolerance = errorRate * 1.2
mismatch = sum([1 for k in range(len(key1)) ... | bigcode/self-oss-instruct-sc2-concepts |
def get_interaction(element_1, element_2, matrix_dimension):
"""Gets singular interaction between 2 elements of an ising matrix and returns the hamiltonion
Args:
element_1 ([int, int]): x, y coordinate of element 1 on the ising matrix
element_2 ([int, int]): x, y coordinate of element 2 on the ... | bigcode/self-oss-instruct-sc2-concepts |
def bps2human(n, _format='%(value).1f%(symbol)s'):
"""Converts n bits per scond to a human readable format.
>>> bps2human(72000000)
'72Mbps'
"""
symbols = ('bps', 'Kbps', 'Mbps', 'Gbps', 'Tbps', 'Pbps', 'Ebps', 'Zbps', 'Ybps')
prefix = {}
for i, s in enumerate(symbols[1:]):
prefix[s... | bigcode/self-oss-instruct-sc2-concepts |
def get_pos(i):
""" return key positions in N253 (1..10) from Meier's Table 2:
0 = blank, if you want to use the peak in the cube
11 = map center, the reference position of N253
"""
pos = [ [], # 0 = blank
['00h47m33.041s', '-25d17m26.61s' ], ... | bigcode/self-oss-instruct-sc2-concepts |
def check_weekend(x: int) -> int:
"""
Checks if the extracted day from the date is a weekend or not.
"""
return 1 if x > 5 else 0 | bigcode/self-oss-instruct-sc2-concepts |
def get_first(mapping, *keys):
"""
Return the first value of the `keys` that is found in the `mapping`.
"""
for key in keys:
value = mapping.get(key)
if value:
return value | bigcode/self-oss-instruct-sc2-concepts |
def calc_exposure_time(num_integrations, ramp_time):
"""Calculates exposure time (or photon collection duration as told
by APT.)
Parameters
----------
num_integrations : int
Integrations per exposure.
ramp_time : float
Ramp time (in seconds).
Returns
-------
exposur... | bigcode/self-oss-instruct-sc2-concepts |
import re
def _is_camel_case(string: str) -> bool:
"""
Helper method used to determine if a given string is camel case or not. See the below details on the
exact rules that are applied.
1. First series of characters should be lower case
2. Every character group afterwards should string with an up... | bigcode/self-oss-instruct-sc2-concepts |
def str2intlist(s, repeats_if_single=None):
"""Parse a config's "1,2,3"-style string into a list of ints.
Args:
s: The string to be parsed, or possibly already an int.
repeats_if_single: If s is already an int or is a single element list,
repeat it this many times to create ... | bigcode/self-oss-instruct-sc2-concepts |
def parseStyle(s):
"""Create a dictionary from the value of an inline style attribute"""
if s is None:
return {}
else:
return dict([[x.strip() for x in i.split(":")] for i in s.split(";") if len(i)]) | bigcode/self-oss-instruct-sc2-concepts |
def get_top_n_kmers(kmer_count, num):
"""Get a list of top_n most frequent kmers."""
return [item[0] for item in sorted(kmer_count.items(), key=lambda x: x[1], reverse=True)[:num]] | bigcode/self-oss-instruct-sc2-concepts |
def _break(req, *opts):
"""
Break out of a pipeline.
:param req: The request
:param opts: Options (unused)
:return: None
This sets the 'done' request property to True which causes the pipeline to terminate at that point. The method name
is '_break' but the keyword is 'break' to avoid conflicting with python built... | bigcode/self-oss-instruct-sc2-concepts |
def w12(x):
"""12bit unsigned int"""
return 0b1111_1111_1111 & x | bigcode/self-oss-instruct-sc2-concepts |
def get_padded_second_seq_from_alignment(al):
"""For a single alignment, return the second padded string."""
alignment_str = str(al).split("\n")[2]
return alignment_str | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_json(json_file):
""" (file) -> dict
Read in json_file, which is in json format, and
output a dict with its contents
"""
with open(json_file) as data_file:
data = json.load(data_file)
return data | bigcode/self-oss-instruct-sc2-concepts |
def mask_bits(n: int, bits: int) -> int:
"""mask out (set to zero) the lower bits from n"""
assert n > 0
return (n >> bits) << bits | bigcode/self-oss-instruct-sc2-concepts |
def l2rowg(X, Y, N, D):
"""
Backpropagate through Normalization.
Parameters
----------
X = Raw (possibly centered) data.
Y = Row normalized data.
N = Norms of rows.
D = Deltas of previous layer. Used to compute gradient.
Returns
-------
L2 normalized gradient.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def seq2batch(x):
"""Converts 6D tensor of size [B, S, C, P, P, P] to 5D tensor of size [B * S, C, P, P, P]"""
return x.view(x.size(0) * x.size(1), *x.size()[2:]) | bigcode/self-oss-instruct-sc2-concepts |
def get_sort_key(sorting) -> list:
"""Return the sort colum value for sorting operations."""
return sorting["hostname"] | bigcode/self-oss-instruct-sc2-concepts |
import json
def open_json(_file):
"""Loads the json file as a dictionary and returns it."""
with open(_file) as f:
return json.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def math_wrap(tex_str_list, export):
"""
Warp each string item in a list with latex math environment ``$...$``.
Parameters
----------
tex_str_list : list
A list of equations to be wrapped
export : str, ('rest', 'plain')
Export format. Only wrap equations if export format is ``re... | bigcode/self-oss-instruct-sc2-concepts |
def read_file(filename):
"""
opens and read a file from file system
returns file content as data if ok
returns None is error while reading file
"""
try:
fhnd = open(filename)
data = fhnd.read()
fhnd.close()
return data
except:
return None | bigcode/self-oss-instruct-sc2-concepts |
def remove_from(message, keyword):
"""
Strip the message from the keyword
"""
message = message.replace(keyword, '').strip()
return message | bigcode/self-oss-instruct-sc2-concepts |
import math
def poisson_distribution(gamma):
"""Computes the probability of events for a Poisson distribution.
Args:
gamma: The average number of events to occur in an interval.
Returns:
The probability distribution of k events occuring.
This is a function taking one parameter (k... | bigcode/self-oss-instruct-sc2-concepts |
def repo(request) -> str:
"""Return ECR repository to use in tests."""
return request.config.getoption("--repo") | bigcode/self-oss-instruct-sc2-concepts |
def list_unique_values(dictionary):
"""
Return all the unique values from `dictionary`'s values lists except `None`
and `dictionary`'s keys where these values appeared
Args:
dictionary: dictionary which values are lists or None
Returns:
dict where keys are unique values from `dicti... | bigcode/self-oss-instruct-sc2-concepts |
def py2(h, kr, rho, cp, r):
"""
Calculate the pyrolysis number.
Parameters
----------
h = heat transfer coefficient, W/m^2K
kr = rate constant, 1/s
rho = density, kg/m^3
cp = heat capacity, J/kgK
r = radius, m
Returns
-------
py = pyrolysis number, -
"""
py = h ... | bigcode/self-oss-instruct-sc2-concepts |
def format_for_IN(l):
""" Converts input to string that can be used for IN database query """
if type(l) is tuple:
l = list(l)
if type(l) is str:
l = [l]
return "(" + ','.join(['"' + str(x) + '"' for x in l]) + ")" | bigcode/self-oss-instruct-sc2-concepts |
def _sortByModified(a, b):
"""Sort function for object by modified date"""
if a.modified < b.modified:
return 1
elif a.modified > b.modified:
return -1
else:
return 0 | bigcode/self-oss-instruct-sc2-concepts |
def impedance(vp, rho):
"""
Given Vp and rho, compute impedance. Convert units if necessary.
Test this module with:
python -m doctest -v impedance.py
Args:
vp (float): P-wave velocity.
rho (float): bulk density.
Returns:
float. The impedance.
Examples:
>>>... | bigcode/self-oss-instruct-sc2-concepts |
def zaid2za(zaid):
"""
Convert ZZAAA to (Z,A) tuple.
"""
# Ignores decimal and stuff after decimal.
zaid = str(int(zaid))
Z = int(zaid[:-3])
A = int(zaid[-3:])
return (Z, A) | 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.