seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def cond(x, singular=False, order=0):
"""
If It is singular, return 1 if x>0 else 0.
If It is not singular, return x**order if x>0 else 0
"""
if singular:
return 1 if x>0 else 0
return x**order if x>0 else 0 | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_summary(filename):
"""Reads the summary dict from a JSON file."""
with open(filename) as f:
return json.load(f) | bigcode/self-oss-instruct-sc2-concepts |
def rho(parameters, theta_v, pi):
"""
Returns an expression for the dry density rho in kg / m^3
from the (virtual) potential temperature and Exner pressure.
:arg parameters: a CompressibleParameters object.
:arg theta_v: the virtual potential temperature in K.
:arg pi: the Exner pressure.
"... | bigcode/self-oss-instruct-sc2-concepts |
def check_column(col, sep=":"):
"""Convert input column string to list of columns
:param col: input string
:param sep: default ":"
:return: list of columns
"""
if isinstance(col, str):
col = col.split(sep)
elif not isinstance(col, list):
raise TypeError(f'Columns "{col}" nee... | bigcode/self-oss-instruct-sc2-concepts |
def is_palindrome(value):
"""Check if a string is a palindrome."""
return value == value[::-1] | bigcode/self-oss-instruct-sc2-concepts |
def _mult_diag_matrix(D, mtx, on_right=False):
""" Multiply diagonal matrix D to mtx
Args:
D (N ndarray) - diagonal matrix
mtx (ndarray) - matrix to multiply
on_right (bool) - whether to return D * mtx (False) or mtx * D (True)
"""
if not on_right:
return (D*mtx.T).T
else:
... | bigcode/self-oss-instruct-sc2-concepts |
import random
import string
def generate_id(length: int = 6) -> str:
"""Helper function for generating an id."""
return "".join(random.choices(string.ascii_uppercase, k=length)) | bigcode/self-oss-instruct-sc2-concepts |
def combine_expression_columns(df, columns_to_combine, remove_combined=True):
"""
Combine expression columns, calculating the mean for 2 columns
:param df: Pandas dataframe
:param columns_to_combine: A list of tuples containing the column names to combine
:return:
"""
df = df.copy()
... | bigcode/self-oss-instruct-sc2-concepts |
import click
def stack_options(func):
"""
stack_options is a decorator which adds the stack and environment arguments
to the click function ``func``.
:param func: The click function to add the arguments to.
:type func: function
:returns: function
"""
func = click.argument("stack")(fun... | bigcode/self-oss-instruct-sc2-concepts |
def format_pdb_code_for_inputs(pdb_code: str, source_type: str):
"""Format given PDB code for prediction inputs."""
return pdb_code[1:3] if source_type.lower() == 'input' else pdb_code.upper() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
def create_callable(func: Callable, *args, **kwargs) -> Callable:
"""
Function creates a callable function where the called function gets passed as an argument along with its
args and kwargs.
Args:
func (Callable): Function to be called
*args (any): Args pa... | bigcode/self-oss-instruct-sc2-concepts |
def flatten_deps(deps):
"""Converts deps.lock dict into a list of go packages specified there."""
out = []
for p in deps['imports']:
# Each 'p' here have a form similar to:
#
# - name: golang.org/x/net
# version: 31df19d69da8728e9220def59b80ee577c3e48bf
# repo: https://go.googlesource.com/... | bigcode/self-oss-instruct-sc2-concepts |
def transpose(a):
"""
transposes a matrix
"""
return list(zip(*a)) | bigcode/self-oss-instruct-sc2-concepts |
def reduce_names(l):
"""Reduce the names in the list to acronyms, if possible.
Args:
l (list(str)): list of names to convert.
Returns:
(list(str)): list of converted names.
"""
for i, item in enumerate(l):
if item == 'QuadraticDiscriminantAnalysis':
l[i] = 'QDA'... | bigcode/self-oss-instruct-sc2-concepts |
def breit_wigner_fano_alt(x, height=1.0, center=0.0, sigma=1.0, q=-3.0):
"""
An alternate Breit-Wigner-Fano lineshape that uses height rather than amplitude.
breit_wigner_fano(x, height, center, sigma, q) =
height * (1 + (x - center) / (q * sigma))**2 / (1 + ((x - center) / sigma)**2)
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import json
def load(file: str):
"""
load json file with default options
:param file: file path to load
:return: json data as python object
"""
with open(file, 'r', encoding='utf-8') as jsonfile:
config = json.load(jsonfile, encoding='utf-8')
return config | bigcode/self-oss-instruct-sc2-concepts |
def update_and_return(dictionary: dict, **kwargs) -> dict:
"""
Utilises the standard dictionary update() function but instead of
returning None it will return the updated dictionary.
:param dictionary: The dictionary that should be updated
:param kwargs: Kwargs of the update method
:return: The... | bigcode/self-oss-instruct-sc2-concepts |
def mtx_zip_url(expression_accession):
"""Make the url to grab the zipped mtx experssion data from the ebi's accessionI_id"""
url = "https://www.ebi.ac.uk/gxa/sc/experiment/%s/download/zip?fileType=quantification-filtered&accessKey=" \
% expression_accession
return url | bigcode/self-oss-instruct-sc2-concepts |
def readSif(fn):
"""reads in the sif file fn and ouptputs a
dictionary and a list:
interDict : has "interaction" as key
and [(node1,node2), (node3,node4)] as values
nodes list : is the list of unique node names
(both on the right or left hand of an interaction)
"""
interDict = {}
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def airmass(Z, units='degrees'):
"""Calculate the airmass for a source according to Airmass=sec(Z) where
Z is the zenith distnce
Z--zenith distance
units--units of Z
"""
if units=='degrees': Z=math.radians(Z)
return 1.0/math.cos(Z) | bigcode/self-oss-instruct-sc2-concepts |
def enum_words(words_iterable):
"""Return string:
() -> ''
('a') -> 'a'
('a', 'b') -> 'a and b'
('a', 'b', 'c') -> 'a, b and c'
"""
ws = words_iterable
if not ws:
return ''
elif len(ws) == 1:
return ws[0]
elif len(ws) == 2:
return f'{ws[0]} and {ws[1]}'
... | bigcode/self-oss-instruct-sc2-concepts |
def shift(txt, indent = ' ', prepend = ''):
"""Return a list corresponding to the lines of text in the `txt` list
indented by `indent`. Prepend instead the string given in `prepend` to the
beginning of the first line. Note that if len(prepend) > len(indent), then
`prepend` will be truncated (doing be... | bigcode/self-oss-instruct-sc2-concepts |
def redact_after_symbol(text:str, symbol:str) ->str:
"""Replaces all characters after a certain symbol appears with XXXXX"""
r_start = text.find(symbol)
r_len = len(text) - r_start
to_redact = text[r_start:]
return text.replace(to_redact, "X"*r_len) | bigcode/self-oss-instruct-sc2-concepts |
def is_aware(dt):
"""Return whether the datetime is aware.
See https://docs.python.org/3/library/datetime.html#determining-if-an-object-is-aware-or-naive
:param dt: The datetime object to check.
:returns: True if ``datetime`` is aware, False otherwise.
"""
return dt.tzinfo is not None and dt.t... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def load_txt_to_string(file_path):
"""
Loads a txt file and returns a str representation of it.
:param file_path: str or Path object
:return: The file's text as a string
>>> from pathlib import Path
>>> from gender_analysis.testing.common import TEST_DATA_DIR
>>>... | bigcode/self-oss-instruct-sc2-concepts |
def _to_extended_delta_code(seconds):
"""Return the deltaCode encoding for the ExtendedZoneProcessor which is
roughtly: deltaCode = (deltaSeconds + 1h) / 15m. With 4-bits, this will
handle deltaOffsets from -1:00 to +2:45.
"""
return f"({seconds // 900} + 4)" | bigcode/self-oss-instruct-sc2-concepts |
def fmtticks(fmt, fmt0, ticks, tickscle, tickscle0):
"""Formats x and y axis tick labels for a seaborn plot
Parameters
----------
fmt : str
The formatting string to use for all tick labels
fmt0 : str
The formatting string to use for only the first tick label
ticks : numpy.ndarra... | bigcode/self-oss-instruct-sc2-concepts |
import re
def regex_validator(regex):
""" Creates a callable which will validate text input against the
provided regex string.
Parameters
----------
regex : unicode
A regular expression string to use for matching.
Returns
-------
results : callable
A callable which ta... | bigcode/self-oss-instruct-sc2-concepts |
def unpack_uncertainty_parameter(u):
"""Unpack uncertainty parameter (integer or single character).
See:
https://www.minorplanetcenter.net/iau/info/MPOrbitFormat.html
Args:
u (str): Packed uncertainty parameter.
Returns:
int: Uncertainty parameter, or -1 if invalid.
s... | bigcode/self-oss-instruct-sc2-concepts |
def prefs_line_to_string(line):
""" Converts a prefs line to a string.
Prefs line is in the format tb(..);tc(..);..;..;.
tb(x, y) are "no preference" intervals (i.e., white) that last for
y 15-minute intervals (x has no meaning):
e.g., tb(0, 4) is an hour of white; tb(2, 8) is two hours.
... | bigcode/self-oss-instruct-sc2-concepts |
def match_file(matcher, analyzer, ht, filename, hashList):
""" Read in an audio file, calculate its landmarks, query against
hash table. Return top N matches as (id, filterdmatchcount,
timeoffs, rawmatchcount), also length of input file in sec,
and count of raw query hashes extracted
""... | bigcode/self-oss-instruct-sc2-concepts |
def splitBase(idx):
""" Return a named used when a big case is split into several pieces """
name = ''
if len(idx) == 0:
return 'base'
for ii, n in enumerate(idx):
name += 'sp%d-split-%d-' % (ii, n)
name = name[0:-1]
return name | bigcode/self-oss-instruct-sc2-concepts |
def average(numlist):
"""
Find average of a list of numbers.
Uses for loop to iterate through parameter NUMLIST
and adds the sum of each element until the end of
the list. AVERAGE then returns the sum divided by
the length of NUMLIST.
"""
numlist_sum = 0 # initialize sum to zero
# ... | bigcode/self-oss-instruct-sc2-concepts |
def orig_atom(atom,big_table):
"""
Returns the 0-indexed position of atom from the full list of atoms in the
supercell mapped back into the original unit cell
"""
n = 0
bonds_per_pair = len(big_table[0])/len(big_table)
while atom > bonds_per_pair:
atom -= bonds_per_pair
n += ... | bigcode/self-oss-instruct-sc2-concepts |
def bottom_remineralization(vs, source, sink, scale):
"""Exported material falling through the ocean floor is converted to nutrients
Note
----
There can be no source, because that is handled by the sinking code
Parameters
----------
scale
Factor to convert remineralized material to... | bigcode/self-oss-instruct-sc2-concepts |
def create_lookup(results):
"""Create a lookup table by key name."""
return {key["key_name"]["web"]: key for key in results} | bigcode/self-oss-instruct-sc2-concepts |
def parse_line(line):
""" Parse a queue trace line into a dict
"""
result = {}
line = line.split()
if len(line) < 5 or line[0][0] == "#":
return result
result["time"] = float(line[0])
result["from"] = int(line[1])
result["to"] = int(line[2])
result["len_bytes"] = float(line[3... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Tuple
from pathlib import Path
def dataset_adress(
adress_archive_root: Optional[str],
corpus_name: str,
dataset_type: str,
preprocess_args: str,
) -> Tuple[str, Path]:
"""Path of dataset archive file and contents directory.
Args:
adr... | bigcode/self-oss-instruct-sc2-concepts |
def distribute(items, n):
"""
Distributes items into n (almost) equally large batches.
Example: items = [1,2,3,4,5,6,7,8,9], n = 4 gives batches = [[1,5,9], [2,6], [3,7], [4,8]]
Args:
data ([any]): List of items of any type
n (int): Number of max items of a batch
... | bigcode/self-oss-instruct-sc2-concepts |
async def ping():
"""Inspects if the API instance is running."""
return {"ping": "pong"} | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _parabolic_trend_crosscov(S1, L1, S2, L2, gamma0, sigma0s, betas, s0):
""" Same as above, but for non-stationary variance models.
The model is the following:
\sigma_i(s) = \sigma0_i + \beta_i * (s - s0)**2
The genial simplicity of the implementation is this: instead of having an... | bigcode/self-oss-instruct-sc2-concepts |
def is_left_bracket(token):
""" returns true if token is left bracket """
return token == "(" | bigcode/self-oss-instruct-sc2-concepts |
def dummy_tx_hist_file_content() -> dict:
"""
Return initial tx file content.
"""
content = {
'txid_stake_previous': '',
'txcount_previous': '0'
}
return content | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def is_ref(entry: Any) -> bool:
"""
Checks if entry is a reference
"""
return isinstance(entry, dict) \
and '$ref' in entry | bigcode/self-oss-instruct-sc2-concepts |
def derive_unique_id(row, is_fabs):
""" Derives the unique ID of a row and puts it in the proper format for the error/warning report.
Args:
row: the dataframe row to derive the unique ID for
is_fabs: a boolean indicating if the submission is a FABS submission or not
Returns... | bigcode/self-oss-instruct-sc2-concepts |
def trim_attribs(elem_attribs, attrib_type="question"):
"""deletes non-useful data from attribs dict for questions / answers, returns remaining"""
if attrib_type == "question":
to_keep = ['Id', 'Body', 'Title', 'Tags', 'AnswerCount', 'AcceptedAnswerId', 'PostTypeId', 'Score', 'BodyParsed', 'TitlePArsed'... | bigcode/self-oss-instruct-sc2-concepts |
def convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from ... | bigcode/self-oss-instruct-sc2-concepts |
def _get_next_chunk(stream, chunk_size):
"""Get a chunk from an I/O stream.
The ``stream`` may have fewer bytes remaining than ``chunk_size``
so it may not always be the case that
``end_byte == start_byte + chunk_size - 1``.
Args:
stream (IO[bytes]): The stream (i.e. file-like object).
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
def enabled(gParameters: Dict, key):
"""Is this parameter set to True?"""
return key in gParameters and gParameters[key] | bigcode/self-oss-instruct-sc2-concepts |
import typing
def noop(data: typing.Any) -> typing.Any:
"""Return the input value
Arguments:
data {typing.Any} -- any value
Returns:
typing.Any -- input value
"""
return data | bigcode/self-oss-instruct-sc2-concepts |
def contains_digit(input_string):
"""
check if string contains digit
>>> contains_digit("5")
True
>>> contains_digit("5a")
True
>>> contains_digit("cat")
False
"""
return any(_.isdigit() for _ in input_string) | bigcode/self-oss-instruct-sc2-concepts |
def get_unique_parents(entity_list):
"""Translate a list of entities to a list of their (unique) parents."""
unique_parents = set(entity.parent for entity in entity_list)
return list(unique_parents) | bigcode/self-oss-instruct-sc2-concepts |
from PIL import Image, ImageChops
def apply_mask(layer, image, bbox=None):
"""
Apply raster mask to the image.
This might change the size and offset of the image. Resulting offset wrt
the psd viewport is kept in `image.info['offset']` field.
:param layer: `~psd_tools.api.layers.Layer`
:param... | bigcode/self-oss-instruct-sc2-concepts |
import re
def parse_dockerimage_string(instr):
"""
Parses a string you'd give 'docker pull' into its consitutent parts: registry, repository, tag and/or digest.
Returns a dict with keys:
host - hostname for registry
port - port for registry
repo - repository name and user/namespace if present... | bigcode/self-oss-instruct-sc2-concepts |
import json
def create_eupeg_json(df):
"""Transforms a Pandas dataframe to a EUPEG json"""
filtered = df.reset_index()[['locations','loc_spans','coord_points']]
all_toponyms = []
for i in range(len(filtered)):
row = filtered.iloc[i]
json_entry = {'start':row['loc_spans'][0], 'end'... | bigcode/self-oss-instruct-sc2-concepts |
def partial_word(secret_word, guessed_letters):
"""
Return the secret_word in user-visible format, with underscores used
to replace characters that have not yet been guessed.
"""
result = ''
for letter in secret_word:
if letter in guessed_letters:
result = result + letter
... | bigcode/self-oss-instruct-sc2-concepts |
import math
def hexagon_points(radius, center, rotate):
"""
Computes the (x,y) points of a hexagon with the given properties.
:param radius: radius of the hexagon
:param center: (x,y) pair, the center of the hexagon
:param rotate: degrees the hexagon is rotated. 0 -> flat top, 30 -> pointed top
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_elastic_loss(jacobian, eps=1e-6, loss_type="log_svals"):
"""Compute the elastic regularization loss.
The loss is given by sum(log(S)^2). This penalizes the singular values
when they deviate from the identity since log(1) = 0.0,
where D is the diagonal matrix containing the singular v... | bigcode/self-oss-instruct-sc2-concepts |
def convert_bool_to_int(value):
"""convert True/False to 1/0."""
if value is True:
return int(1)
if value is False:
return int(0)
return int(-1) | bigcode/self-oss-instruct-sc2-concepts |
import requests
def set_website_preference_for_header(
url_pref: str,
session: requests.Session,
) -> requests.Session:
"""
Set the 'Email Headers' of the 'Archive Preferences' for the auth session
to 'Show All Headers'. Otherwise only a restricted list of header fields is
shown.
"""
u... | bigcode/self-oss-instruct-sc2-concepts |
def getMedianvalue(lst, points):
"""
Returns the median of a list of numerics.
:param lst: A list of numerics from which the median will be retrieved. \t
:type lst: [numerics] \n
:returns: The median. \t
:rtype: : Numeric \n
"""
if points[1] == -1:
if len(lst) == 1:
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def compute_entropy_loss(logits, mask):
"""Return the entropy loss, i.e., the negative entropy of the policy."""
policy = torch.nn.functional.softmax(logits, dim=-1)
log_policy = torch.nn.functional.log_softmax(logits, dim=-1)
return torch.sum(policy * log_policy * mask.unsqueeze(-1)) / (... | bigcode/self-oss-instruct-sc2-concepts |
def get_aws_env(args):
"""Returns a dictionary of AWS related environment variables based on command line args"""
env = {}
env_values = {
"AWS_PROFILE": args.aws_profile,
"AWS_ACCESS_KEY_ID": args.aws_access_key_id,
"AWS_SECRET_ACCESS_KEY": args.aws_secret_access_key,
"AWS_SE... | bigcode/self-oss-instruct-sc2-concepts |
import math
def string_similarity(string1, string2):
"""
This implements a "cosine-similarity" algorithm as described for example in
*Proceedings of the 22nd International Conference on Computation
Linguistics* (Coling 2008), pages 593-600, Manchester, August 2008.
The measure-vectors used i... | bigcode/self-oss-instruct-sc2-concepts |
import mpmath
def invcdf(p, mu=0, b=1):
"""
Laplace distribution inverse CDF.
This function is also known as the quantile function or the percent
point function.
"""
if b <= 0:
raise ValueError('b must be positive.')
with mpmath.extradps(5):
p = mpmath.mpf(p)
mu = ... | bigcode/self-oss-instruct-sc2-concepts |
def wrap_p(value):
"""
Adds enclosing <p> and </p> tags to value.
"""
return '<p>%s</p>' % value | bigcode/self-oss-instruct-sc2-concepts |
def sub2indSH (m,n):
"""
i = sub2indSH(m,n)
Convert Spherical Harmonic (m,n) indices to array index i
Assumes that i iterates from 0 (Python style)
"""
i = n**2 + n + m
return i | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
from typing import Match
import re
def is_attr_private(attrname: str) -> Optional[Match[str]]:
"""Check that attribute name is private (at least two leading underscores,
at most one trailing underscore)
"""
regex = re.compile('^_{2,}.*[^_]+_?$')
return regex.match(attrn... | bigcode/self-oss-instruct-sc2-concepts |
def drop_constant_column(dataframe):
"""
Drops constant value columns of pandas dataframe.
"""
return dataframe.loc[:, (dataframe != dataframe.iloc[0]).any()] | bigcode/self-oss-instruct-sc2-concepts |
def parse_file_string(filestring):
"""
>>> parse_file_string("File 123: ABC (X, Y) Z")
('ABC (X, Y) Z', '')
>>> parse_file_string("File 123: ABC (X) Y (Z)")
('ABC (X) Y', 'Z')
>>> parse_file_string("File: ABC")
('ABC', '')
>>> parse_file_string("File 2: A, B, 1-2")
('A, B, 1-2', '')
... | bigcode/self-oss-instruct-sc2-concepts |
def VStack_Calc(N, Vcell):
"""
Calculate VStack.
:param N: number of single cells
:type N :int
:param Vcell: cell voltage [V}
:type Vcell:float
:return: VStack [V] as float
"""
try:
result = N * (Vcell)
return result
except TypeError:
print(
... | bigcode/self-oss-instruct-sc2-concepts |
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1]) | bigcode/self-oss-instruct-sc2-concepts |
def positive_fft_bins(n_bin, include_zero=False):
"""Give the range of positive frequencies of a complex FFT.
This assumes we are using Numpy's FFT, or something compatible
with it, like ``pyfftw.interfaces.numpy_fft``, where the positive
frequencies come before the negative ones, the Nyquist frequency... | bigcode/self-oss-instruct-sc2-concepts |
def get_risk_score(track, other):
"""
Get "risk" score between a track an another track. The "risk" evaluates
how likely the two tracks are to be the same, lower being better, with
0 being a perfect match. This is a super handcrafted score, with little
to no tuning, will probably not catch all possi... | bigcode/self-oss-instruct-sc2-concepts |
def fill_model(
model, time_stop, time_step, initial_state, seed, n_points):
""" Fill up model with output file and initial state and write it down
in an input file
Parameters
----------
model: str
smoldyn model description
time_stop: Float
Simulation duration
time_s... | bigcode/self-oss-instruct-sc2-concepts |
import importlib
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute designated by the
last name in the path. Raise ImportError if the import failed.
"""
module_path, attribute_name = dotted_path.rsplit('.', 1)
module = importlib.import_module(module_path)
... | bigcode/self-oss-instruct-sc2-concepts |
import networkx as nx
def nxMarkovGraph(self, all_vars=False):
"""Get networkx Graph object of the Markov graph of the model
Example:
>>> G = nxMarkovGraph(model)
>>> nx.draw(G)
"""
G = nx.Graph()
G.add_nodes_from( [v.label for v in self.X if (all_vars or v.states > 1)] )
for f in sel... | bigcode/self-oss-instruct-sc2-concepts |
def get_message_type_from_message(message: str) -> str:
"""Parses the message_type from the message."""
return message.split(" ")[2].replace("\n", "") | bigcode/self-oss-instruct-sc2-concepts |
import re
import struct
def GetFormatType(format_):
"""
Get format type and bitsize without prefix
@param format_:
format specifier
@return:
(format_, 0) or (format without prefix, bitsize)
"""
formattype = format_
bitsize = 0
if isinstance(format_, str):
mat... | bigcode/self-oss-instruct-sc2-concepts |
def retrieve_parameters(monitor, gradients=False):
"""Retrieves the parameters of the model or their gradients
:param monitor: either a training or evaluation monitor
:param gradients: whether to retrieve the gradients instead of the values
:returns: the values of the parameters (or gradients) for each... | bigcode/self-oss-instruct-sc2-concepts |
def sum_mat_bins(mat):
"""
Compute the sum of matrices bins (i.e. rows or columns) using
only the upper triangle, assuming symmetrical matrices.
Parameters
----------
mat : scipy.sparse.csr_matrix
Contact map in sparse format, either in upper triangle or
full matrix.
Re... | bigcode/self-oss-instruct-sc2-concepts |
def register_sql(spark, files, schema=None, sep=None, table_name="table", return_count=False):
"""
Register a list of files as a SQL temporary view.
parameters:
- files is overloaded: can be one file path or list of file paths.
- spark: pyspark.sql.SparkSession
- table_name: this is how we will... | bigcode/self-oss-instruct-sc2-concepts |
def coloringToColorList(G, coloring):
"""
coloringToColorList(G, coloring)
Calculate node colors based on an input graph and color dict.
Parameters
----------
G : networkit.Graph
The input graph.
coloring : dict()
Coloring scheme as dict.
Returns
-------
list(tuple(float, float, float))
List with col... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def get_ray_directions(H, W, focal):
"""
Get ray directions for all pixels in camera coordinate.
Reference: https://www.scratchapixel.com/lessons/3d-basic-rendering/
ray-tracing-generating-camera-rays/standard-coordinate-systems
Inputs:
H, W, focal: image height, w... | bigcode/self-oss-instruct-sc2-concepts |
def openai(base_lr, num_processed_images, num_epochs, num_warmup_epochs):
"""
Learning rate scheduling strategy from openai/glow
:param base_lr: base learning rate
:type base_lr: float
:param num_processed_images: number of processed images
:type num_processed_images: int
:param num_epochs:... | bigcode/self-oss-instruct-sc2-concepts |
def calculate_symmetric_kl_divergence(p, q, calculate_kl_divergence):
""" This function calculates the symmetric KL-divergence between
distributions p and q. In particular, it defines the symmetric
KL-divergence to be:
.. math::
D_{sym}(p||q) := \frac{D(p||q) + D(p||p)}{2}
Args:
... | bigcode/self-oss-instruct-sc2-concepts |
from dateutil import tz
from datetime import datetime
def fordtime_to_datetime(fordTimeString, useUTC=True):
"""Convert Ford UTC time string to local datetime object"""
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
try:
utc_dt = datetime.strptime(fordTimeString, "%m-%d-%Y %H:%M:%S.%f")
exc... | bigcode/self-oss-instruct-sc2-concepts |
def create_obj(vertices, textures, normals, faces, filename=None):
"""
Create content of the OBJ file given the vertices, textures, normals, and faces.
Args:
vertices (list): list of vertices (for each corner of a triangular mesh)
textures (list): list of textures
normals (list): li... | bigcode/self-oss-instruct-sc2-concepts |
def transform_data(data_to_transform: list):
"""
Transforms data_to_transform from a 2d array to a 1d array
Parameters
----------
data_to_transform: list
the data which needs to be transformed
Returns
-------
new_data:list
the transformed data
"""
new_data = []
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def half_masker(batch_size, mask_shape, dim=0):
"""Return a mask which masks the top half features of `dim`."""
mask = torch.zeros(mask_shape).bool()
slcs = [slice(None)] * (len(mask_shape))
slcs[dim] = slice(0, mask_shape[dim] // 2)
mask[slcs] = 1
# share memory
return mask.u... | bigcode/self-oss-instruct-sc2-concepts |
def clean_minmax(dic):
"""
Clean (set to zero) the MAX/MIN dictionary keys.
"""
# maximum and minimum values
dic["FDMAX"] = 0.0
dic["FDDISPMAX"] = 0.0
dic["FDMIN"] = 0.0
dic["FDDISPMIN"] = 0.0
dic["FDSCALEFLAG"] = 0.0 # FDMIN/MAX not valid
return dic | bigcode/self-oss-instruct-sc2-concepts |
import torch
def tanh(x: torch.Tensor) -> torch.Tensor:
"""Return torch.tanh(x)"""
return torch.tanh(x) | bigcode/self-oss-instruct-sc2-concepts |
import re
def remove_hanging_parenthesis(sample_string):
"""
Removes parenthesis at the end of strings.
Args:
sample_string (str): Input string
Returns:
str
"""
return re.sub(r"[^.*]\($", "", sample_string).strip() | bigcode/self-oss-instruct-sc2-concepts |
def _lemma_extractor(tokens):
"""Turn an iterable of tokens into language model input.
:param tokens: An iterable of tokens (see :meth:`tokenize` for the token
representation).
:return: An iterable of token identifiers of the form ``(<graphic lemma
variant>, <phonetic lemma variant>)``.
"... | bigcode/self-oss-instruct-sc2-concepts |
def isWord(wordList, word):
"""
Determines if word is a valid word.
wordList: list of words in the dictionary.
word: a possible word.
returns True if word is in wordList.
Example:
>>> isWord(wordList, 'bat') returns
True
>>> isWord(wordList, 'asdf') returns
False
"""
wo... | bigcode/self-oss-instruct-sc2-concepts |
def color_to_hex(color):
"""
Converts a (R, G, B) tuple into a hex color string.
"""
return "#" + "".join('{:02X}'.format(x) for x in color) | bigcode/self-oss-instruct-sc2-concepts |
import re
def assets_from_string(text):
"""Correctly split a string containing an asset pair.
Splits the string into two assets with the separator being on of the
following: ``:``, ``/``, or ``-``.
"""
return re.split(r'[\-:/]', text) | bigcode/self-oss-instruct-sc2-concepts |
def get_min_rooms(lectures):
"""
Given an array of start and end times for lectures,
find the minimum number of classrooms necessary.
"""
starts = sorted(start for start, _ in lectures)
ends = sorted(end for _, end in lectures)
num_rooms = 0
current_overlap = 0
start_idx, end_idx = ... | bigcode/self-oss-instruct-sc2-concepts |
def _axis_label(label, unit=None):
"""Return a formatted label with units."""
return f"{label} / ({unit})" if unit not in [None, ""] else label | bigcode/self-oss-instruct-sc2-concepts |
def cents_to_frequency(cents):
"""Converts cents to frequency in Hz"""
return 10 * 2 ** (cents / 1200) | 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.