content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def watershed(src):
"""
Performs a marker-based image segmentation using the watershed algorithm.
:param src: 8-bit 1-channel image.
:return: 32-bit single-channel image (map) of markers.
"""
# cv2.imwrite('{}.png'.format(np.random.randint(1000)), src)
gray = src.copy()
img = cv2.cvtColo... | 31,900 |
def sub(x, y):
"""Returns the difference of compositions.
Parameters
----------
x : NumPy array, shape (n,) or (k,n)
The composition that will be subtracted from.
y : NumPy array, shape (n,) or (k,n)
The composition to be subtracted.
Returns
-------
z : NumPy array, sha... | 31,901 |
def _broadcast_concatenate(arrays, axis):
"""Concatenate arrays along an axis with broadcasting."""
arrays = _broadcast_arrays(arrays, axis)
res = np.concatenate(arrays, axis=axis)
return res | 31,902 |
def get_final_bmi(data_dic, agex_low, agex_high, mrnsForFilter=[], filter=True):
"""
Function to get the distinct bmi percentile readings for predictions.
Returns outcome percentiles and labels
#### PARAMETERS ####
data_dic: dictionary of patient data
agex_low: low age range for outcome predicti... | 31,903 |
def add_group_sub(uid:int, group_id:int) -> bool: #添加订阅信息
"""
向已存在的表中插入群记录, 如果群已经存在则什么都不做
:param uid: 唯一标识用户的数字uid
:param group_id: 监听该用户的群id
"""
connection = sqlite3.connect(DB_PATH)
cursor = connection.cursor()
success = True
group_exist = cursor.execute(
f'select count(*) ... | 31,904 |
def text_parse_two_placeholders() -> None:
"""It parses two placeholders."""
types, tokens = tokenize("Parse {THIS} and {THAT}")
assert len(tokens) == len(types) == 9
assert types == [
Text,
Generic.Punctuation,
Generic.Emph,
Generic.Punctuation,
Text,
Ge... | 31,905 |
def preprocess(corpora, divide_by_three_dots):
"""
Process corpora for the input of the translation algorithms
:param corpora: corpora to process
:return: nothing
"""
chars_sentences, mapping = build_full_line_translation_process(corpora,
... | 31,906 |
def chunks(lst, n):
"""Yield successive n-sized chunks from lst.
Example
-----
original_list = [0,1,2,3,4,5,6,7,8,9]
chunked_list = list(chunks(original_list, 3))
-> [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
"""
for i in range(0, len(lst), n):
yield lst[i:i + n] | 31,907 |
def inference(cluster_info, qname='input'):
"""
Feeds Spark partitions into the shared multiprocessing.Queue and returns inference results.
"""
def _inference(iter):
# get shared queue, reconnecting if necessary
mgr = _get_manager(cluster_info, socket.gethostname(), os.getppid())
... | 31,908 |
def is_array_of(obj, classinfo):
"""
Check if obj is a list of classinfo or a tuple of classinfo or a set of classinfo
:param obj: an object
:param classinfo: type of class (or subclass). See isinstance() build in function for more info
:return: flag: True or False
"""
flag = False
if is... | 31,909 |
def create_acronym(fullname):
"""Create an acronym for an estimator.
The acronym consists of the capital letters in the name if
there are at least two. If not, the entire name is used.
Parameters
----------
fullname: str
Estimator's __name__.
Returns
-------
str
Cr... | 31,910 |
def activate_through_friendbot(address: str):
"""
Activates and funds a testnet account using friendbot
"""
resp = requests.get(url="https://friendbot.stellar.org", params={"addr": address})
resp.raise_for_status() | 31,911 |
def test_colored_svg(qtbot):
"""Test that we can create a colored icon with certain color."""
icon = QColoredSVGIcon.from_resources('new_points')
assert isinstance(icon, QIcon)
assert isinstance(icon.colored('#0934e2', opacity=0.4), QColoredSVGIcon)
assert icon.pixmap(250, 250) | 31,912 |
def transact_update_path(path):
"""input transact update to DynamoDB"""
# transact_write_itemsはclientAPIなので注意
def update_path(path):
"""input put learning path to DynamoDB"""
input = defaultdict(
dict,
TableName="primary_table",
Key={"PK": {"S": path.PK... | 31,913 |
def report_model_metrics(
data: pd.DataFrame,
model_params: Dict[str, Any],
y_pred: str,
active_run_id: str,
name_prefix: str = '',
group_values : list = ['train','test']
) -> None:
"""Node for reporting the performance metrics of the predictions performed
by the previous node. Notice th... | 31,914 |
def Tc(filename,):
"""Extract Curie temperature
"""
job = AkaikkrJob(".")
v = job.get_resistivity(filename)
print(sys._getframe().f_code.co_name, v) | 31,915 |
def codon_usage(seq, aminoacid):
"""Provides the frequency of each codon encoding a given aminoacid in a DNA sequence"""
tmpList = []
for i in range(0, len(seq) - 2, 3):
if DNA_Codons[seq[i:i + 3]] == aminoacid:
tmpList.append(seq[i:i + 3])
freqDict = dict(Counter(tmpList))
tota... | 31,916 |
def make_check_stderr_message(stderr, line, reason):
"""
Create an exception message to use inside check_stderr().
"""
return dedent("""\
{reason}:
Caused by line: {line!r}
Complete stderr: {stderr}
""").format(stderr=stderr, line=line, reason=reason) | 31,917 |
def mesh2shp(infile):
"""
"""
output_shp = infile[:-3] + 'shp'
output_shp = output_shp.replace('mesh', 'scenario')
file_length = file_len(infile)
print file_length
# Work out lines that have the required data
top_lons = 0
bottom_lons = int(file_length/3 - 1)
top_lats = int(... | 31,918 |
def write_to_ch(df, date_field_name, table_name, mode, config, logger, pk_columns=None) -> None:
""" Dumps PySpark DataFrame to ClickHouse, create or recreate table if needed.
Args:
df: PySpark DataFrame
mode: describe, what do if table already exists
must be one of 'overwrite' / '... | 31,919 |
def leaderboard(input):
"""Generates a link to the leaderboard for the current category in chat.
Parameters
----------
input : str
the name of the chat command that calls this function
"""
if input == message.lower().strip():
#get user ID of current channel
try:
... | 31,920 |
def diffusion_step(matrix, row_damping=0, column_damping=0):
"""
Return the diffusion adjacency matrix produced by the input matrix
with the specified row and column normalization exponents.
Note: the row normalization is performed second, so if a value
of row_damping=1 is used, the output will be a... | 31,921 |
def go_to_sleep(current_time):
"""Enter deep sleep for time needed."""
# compute current time offset in seconds
hour, minutes, seconds = time.localtime(current_time)[3:6]
seconds_since_midnight = 60 * (hour * 60 + minutes) + seconds
three_fifteen = (3 * 60 + 15) * 60
# wake up 15 minutes after 3... | 31,922 |
def verb_context(filtertype, aidcfg, verbose):
""" closure helper """
class VerbosityContext(object):
"""
Printing filter info in a way that avoids polluting the function
namespace. This is a hack.
This is a with_statement context class that expect a variable avail_aids
... | 31,923 |
def get_add_many_columns_function(row_function, data_types):
"""Returns a function which adds several columns to a row based on given row function"""
def add_many_columns(row):
result = row_function(row)
data = []
for i, data_type in enumerate(data_types):
try:
... | 31,924 |
def determine_peaks(spectrum, peak='both', amp_threshold=None):
"""Find peaks in a spectrum.
Parameters
----------
spectrum : numpy.ndarray
Array of the data values of the spectrum.
peak : 'both' (default), 'positive', 'negative'
Description of parameter `peak`.
amp_threshold : ... | 31,925 |
def sumlike_wrap(fun_name):
"""Handle torch.sum and torch.mean"""
# Define appropriate torch function, the rest of the logic is the same
assert fun_name in ['sum', 'mean']
torch_fun = getattr(torch, fun_name)
@wraps(torch_fun)
def sumlike_fun(input, dim=None, keepdim=False):
nodim = dim... | 31,926 |
def _generate_adapted_paths(ed_operation, Path):
"""Receives a 'Path' through a DFA where each element is a tuple
(state index reached, character set that triggered transition)
According to the three edit distance operations 'insert', 'delete',
and 'substitute' the path is adapted. The result... | 31,927 |
def __crossover(n: int, g: np.matrix, m_list: np.array, f_list: np.array) -> np.matrix:
"""
:param n: half of g.shape[0]
:param g: bin mat of genes
:param m_list: male nums
:param f_list: female nums
:return: crossed-over bin mat of genes
"""
cros = np.random.randint(low=0, high=g.shape[1], size=n)
g_cros = n... | 31,928 |
def setup_system():
"""
Galacitic center potential and Arches cluster
position from Kruijssen 2014
"""
potential = static_potentials.Galactic_Center_Potential_Kruijssen()
cluster = Particle()
# At time 2.05 in KDL15
cluster.position = [-17.55767, -53.26560, -9.39921] | units.par... | 31,929 |
def MCM_data_scraper(species_list, get_image: bool = False, display: bool = False,
filename:str='', savepath: str = ''):
"""Function that takes a list of species, and rips all the info off the
MCM Webpage about that species.(e.g. SMILES, INCHI, etc)...
Inputs:
------... | 31,930 |
def collect_dynamic_libs(name: str, dest: str = ".", dependencies: bool = True,
excludes: Iterable[str] = None) -> List:
"""
Collect DLLs for distribution **name**.
Arguments:
name:
The distribution's project-name.
dest:
Target destination, d... | 31,931 |
def make_agreements(file) -> pd.DataFrame:
"""In some of the human conditions, we hold out questions. Each randomly generated agent is
given our test and then asked it's opinion on every hold out question.
agreements.pkl is a Dict[Experiment, Tuple(ndarray, ndarray)] where each array element
contains t... | 31,932 |
def column_as_html(column, table):
"""Return column as an HTML row."""
markup = "<tr>"
markup += "<td class='field'>{0}</td>".format(column.name, column.comment)
markup += "<td>{0}</td>".format(column.formattedType)
# Check for Primary Key
if table.isPrimaryKeyColumn(column):
markup += ... | 31,933 |
def covariation(x, y):
"""
Covariation of X and Y.
:param list or tuple x: 1st array.
:param list or tuple y: 2nd array.
:return: covariation.
:rtype: float
:raise ValueError: when x or y is empty
"""
if x and y:
m_x = mean(x)
m_y = mean(y)
dev_x = [i - m_x f... | 31,934 |
def review_requests(ctx, url, counts_only, time_added_from, time_added_to):
"""Print the Review Requests List Resource.
The date and time format is YYYY-MM-DD HH:MM:SS or
{yyyy}-{mm}-{dd}T{HH}:{MM}:{SS} with an optional timezone appended as
-{HH:MM}.
Args:
ctx: RBTLIB context.
url:... | 31,935 |
def stripped_spaces_around(converter):
"""Make converter that strippes leading and trailing spaces.
``converter`` is called to further convert non-``None`` values.
"""
def stripped_text_converter(value):
if value is None:
return None
return converter(value.strip())
ret... | 31,936 |
def ootf_inverse(
value: FloatingOrArrayLike,
function: Union[
Literal["ITU-R BT.2100 HLG", "ITU-R BT.2100 PQ"], str
] = "ITU-R BT.2100 PQ",
**kwargs: Any
) -> FloatingOrNDArray:
"""
Maps relative display linear light to scene linear light using given
inverse opto-optical transfer fu... | 31,937 |
def GetMemoryUsageOfProcess(pid):
"""Queries the system for the current memory usage of a specified process.
This function only works in Linux and ChromeOS.
Args:
pid: The integer process identifier for the process to use.
Returns:
The memory usage of the process in MB, given as a float. If the proc... | 31,938 |
def modified_query(benchmark, model_spec, run_index: int, epochs=108, stop_halfway=False):
"""
NOTE:
Copied from https://github.com/google-research/nasbench/blob/b94247037ee470418a3e56dcb83814e9be83f3a8/nasbench/api.py#L204-L263 # noqa
We changed the function in such a way that we now can specified the... | 31,939 |
def stop():
"""
Stop the service.
"""
print('Sorry, not implemented yet.') | 31,940 |
def gauss(x, mu=0, sigma=1):
"""
Unnormalized Gaussian distribution.
Parameters
----------
Returns
-------
y : type(x)
Gaussian evaluated at x.
Notes
-----
Some people use alpha (1/e point)
instead of the sigma (standard deviation)
to define the width of the Gaussian.
They are r... | 31,941 |
def GetSpd(ea):
"""
Get current delta for the stack pointer
@param ea: end address of the instruction
i.e.the last address of the instruction+1
@return: The difference between the original SP upon
entering the function and SP for the specified address
"""
... | 31,942 |
def is_fugashi_ipadic_available():
"""
Check if the library is available.
This function checks if sentencepiece is available in your environment
and returns the result as a bool value.
Returns
-------
_fugashi_ipadic_available : bool
If True, fugashi wiht ipadic is available in you... | 31,943 |
def create_new_layer(layer_name):
"""
Works on the active tab with selected glyphs.
This function takes a str (layer_name) and check if there is a layer with
this name. If the layer doesn't exists, then creates a new layer.
"""
for glyph in font.glyphs:
for layer in glyph.layers:
... | 31,944 |
def test_normalize_standardize_allsamples_fromfile():
"""
Testing normalize pycytominer function
data_file provided
method = "standardize"
meta_features = "none"
samples="all"
"""
normalize_result = normalize(
profiles=data_file,
features=["x", "y", "z", "zz"],
me... | 31,945 |
def print_top_N_words(text, top_N=10):
"""
This function accepts a text data (in the form of string) and extracts the top N words from it.
N is supplied to the function. If not, default 10 is taken.
"""
# Initialize a dictionary
counts = dict()
txt_dump=text
top_N=top_N
words = txt_dump.split()
for word in wo... | 31,946 |
def pad_to_sidelength(schematic, labels=None, nothing_id=0, sidelength=32):
"""Add padding to schematics to sidelength"""
szs = list(schematic.size())
szs = np.add(szs, -sidelength)
pad = []
# this is all backwards bc pytorch pad semantics :(
for s in szs:
if s >= 0:
pad.appe... | 31,947 |
def segmentation_gaussian_measurement_batch(
y_true,
y_pred,
gaussian_sigma=3,
measurement=segmentation_losses.binary_crossentropy):
""" Apply metric or loss measurement to a batch of data incorporating a 2D gaussian.
Only works with batch size 1.
Loop and call this ... | 31,948 |
def test_can_use_std_lattice():
"""Test of can_use_std_lattice."""
conv_lat = [[6.06531185, 0.0, 0.0], [0.0, 0.0, 6.06531185], [0.0, -6.06531185, 0.0]]
std_lattice = [
[6.06531185, 0.0, 0.0],
[0.0, 6.06531185, 0.0],
[0.0, 0.0, 6.06531185],
]
tmat = [[0.0, 0.5, 0.5], [-0.5, -0... | 31,949 |
def save_image(img: Image, img_format=None, quality=85):
""" Сохранить картинку из потока в переменную для дальнейшей отправки по сети
"""
if img_format is None:
img_format = img.format
output_stream = BytesIO()
output_stream.name = 'image.jpeg'
# на Ubuntu почему-то нет jpg, но есть jpe... | 31,950 |
def main__log_exprs_multiline():
"""
Embedding newlines in a single message:
>>> @log_calls()
... def f(a):
... log_calls.print("Even multiline messages\\n"
... "are properly indented!")
... return g(a, 2*a)
>>> @log_calls()
... def g(x, y):
... ... | 31,951 |
def check_input(args: dict) -> dict:
"""
Check if user entries latitude and longitude are well formated. If ok, retruns a dict with
lat and lng converted as flaots
- args: dict. request.args
"""
lat = args.get("lat")
lng = args.get("lng")
if lat is None:
abort(400, "Latitude... | 31,952 |
def adjust_learning_rate(epoch, total_epochs, only_ce_epochs, learning_rate, optimizer):
"""Adjust learning rate during training.
Parameters
----------
epoch: Current training epoch.
total_epochs: Total number of epochs for training.
only_ce_epochs: Number of epochs for ... | 31,953 |
def dummy_nullgeod():
"""
Equatorial Geodesic
"""
return Nulllike(
metric="Kerr",
metric_params=(0.5,),
position=[4., np.pi / 2, 0.],
momentum=[0., 0., 2.],
steps=50,
delta=0.5,
return_cartesian=False,
suppress_warnings=True,
) | 31,954 |
def test_format_net_gain_returns_negative_number_in_parentheses_with_locale_formatting():
"""It formats negative number with locacle formatting."""
pacioli = Pacioli(config_file="tests/resources/sample_config.yml")
locale.setlocale(locale.LC_ALL, "")
n = int(-1000)
n_positive = n * -1
result = p... | 31,955 |
def test_find_many_settings_precedence(monkeypatch) -> None:
"""test more than one in cwd"""
expected = os.path.join(os.getcwd(), "ansible-navigator.yml")
paths = [expected, os.path.join(os.path.expanduser("~"), ".ansible-navigator.json")]
def check_path_exists(arg):
return arg in paths
m... | 31,956 |
def flatten(tensor):
"""Flattens a given tensor such that the channel axis is first.
The shapes are transformed as follows:
(N, C, D, H, W) -> (C, N * D * H * W)
"""
C = tensor.size(1)
# new axis order
axis_order = (1, 0) + tuple(range(2, tensor.dim()))
# Transpose: (N, C, D, ... | 31,957 |
def compare_scalar_grids(gvecs0, nkm0, gvecs1, nkm1, atol=1e-6):
"""Compare two scalar fields sampled on regular grids
Args:
gvecs0 (np.array): first grid, (npt0, ndim)
nkm0 (np.array): values, (npt0,)
gvecs1 (np.array): second grid, (npt1, ndim), expect npt1<=npt0
nkm1 (np.array): values, (npt1,)
... | 31,958 |
def a_dot(t):
"""
Derivative of a, the scale factor
:param t:
:return:
"""
return H0 * ((3 / 2) * H0 * t) ** (-1 / 3) | 31,959 |
def test_basic_dewpoint_rh():
"""Test dewpoint_rh function."""
temp = np.array([30., 25., 10., 20., 25.]) * units.degC
rh = np.array([30., 45., 55., 80., 85.]) / 100.
real_td = np.array([11, 12, 1, 16, 22]) * units.degC
assert_array_almost_equal(real_td, dewpoint_rh(temp, rh), 0) | 31,960 |
def frame(x, frame_length, hop_length, axis=-1, name=None):
"""
Slice the N-dimensional (where N >= 1) input into (overlapping) frames.
Args:
x (Tensor): The input data which is a N-dimensional (where N >= 1) Tensor
with shape `[..., seq_length]` or `[seq_length, ...]`.
frame_le... | 31,961 |
def wrapped_partial(func: callable, *args, **kwargs) -> callable:
"""Wrap a function with partial args and kwargs.
Args:
func (callable): The function to be wrapped.
*args (type): Args to be wrapped.
**kwargs (type): Kwargs to be wrapped.
Returns:
callable: The wrapped func... | 31,962 |
def with_sfw_check(
command: typing.Optional[CommandT] = None,
/,
*,
error_message: typing.Optional[str] = "Command can only be used in SFW channels",
halt_execution: bool = False,
) -> CallbackReturnT[CommandT]:
"""Only let a command run in a channel that's marked as sfw.
Parameters
--... | 31,963 |
def algorithm_id_to_generation_class(algorithm_id):
"""
Returns the Generation class corresponding to the
provided algorithm ID (as defined in settings).
"""
return _algorithm_id_to_class_data(algorithm_id)[1] | 31,964 |
def search(session, **kwargs):
"""
Searches the Discogs API for a release object
Arguments:
session (requests.Session) - API session object
**kwargs (dict) - All kwargs are added as query parameters in the search call
Returns:
dict - The first result returned in the search
Raises:
... | 31,965 |
def test_tensors_equal():
""" Test tensors_equal comparison function
"""
tensor1 = { '0' : numpy.zeros((2,2), dtype=numpy.complex128), \
'1' : numpy.zeros((2,2), dtype=numpy.complex128) }
tensor2 = { '0' : numpy.zeros((2,2), dtype=numpy.complex128), \
'1' : numpy.ones((2... | 31,966 |
def plot_demand_supply(
all_dict, commod, test, demand_driven, log_scale, calculated
):
""" Plots demand, supply, calculated demand and calculated supply
on a curve for a non-driving commodity
Parameters
----------
4 dicts: dictionaries of supply, demand, calculated
demand and calculated sup... | 31,967 |
def test_array_field_exact_empty_list(Query):
"""
Test exact filter on a array field of string.
"""
schema = Schema(query=Query)
query = """
query {
events (tags: []) {
edges {
node {
name
}
}
}
}
... | 31,968 |
def _conv_general_precision_config_proto(precision):
"""Convert an integer to an XLA.PrecisionConfig."""
if precision is None:
return None
proto = xla_data_pb2.PrecisionConfig()
proto.operand_precision.append(int(precision))
return proto | 31,969 |
def find_installed_packages_in_environment():
"""
Find packages under the COLCON_PREFIX_PATH.
For each prefix path the package index is being read and the first time a
package is being found its install prefix is being added to the result.
:returns: The mapping from a package name to the prefix pa... | 31,970 |
def list_in_list(a, l):
"""Checks if a list is in a list and returns its index if it is (otherwise
returns -1).
Parameters
----------
a : list()
List to search for.
l : list()
List to search through.
"""
return next((i for i, elem in enumerate(l) if elem == a), -1) | 31,971 |
def test_service_check_instance_name_normalization(aggregator, http_check):
"""
Service check `instance` tag value is normalized.
Note: necessary to avoid mismatch and backward incompatiblity.
"""
# Run the check for the one instance
http_check.check(CONFIG_UNORMALIZED_INSTANCE_NAME['instances... | 31,972 |
def start_host(session=None, load_plugins=True, plugins=None):
"""Promote the current process into python plugin host for Nvim.
Start msgpack-rpc event loop for `session`, listening for Nvim requests
and notifications. It registers Nvim commands for loading/unloading
python plugins.
The sys.stdout... | 31,973 |
def parse_args():
"""Command line argument parsing."""
global flag_target_arch, flag_echo, flag_dryrun, flag_show_output
global binutils_version, flag_parfactor, flag_do_only_gcc_build
global flag_gcc_subdir, flag_debug_gcc, flag_langs
global flag_need_android_sysroot, flag_ndk_dir
global flag_use_multilib,... | 31,974 |
def sent_to_idx(sent, word2idx, sequence_len):
"""
convert sentence to index array
"""
unknown_id = word2idx.get("UNKNOWN", 0)
sent2idx = [word2idx.get(word, unknown_id) for word in sent.split("_")[:sequence_len]]
return sent2idx | 31,975 |
def fcall(node, file, ctx, open="(", close=")", sep=", "):
"""
C-style function call from a node that has (func_name, args) elements.
Can control the opening/closing bracket and argument separator.
"""
func_name, args = node.value
yield func_name
array(args, file, ctx, items=lambda x: x, o... | 31,976 |
def expand_sqs_results(settings: Settings, sqs_results: T.Iterable[SQSResult],
timings: T.Optional[TimingDictionary] = None, include=('configuration',),
inplace: bool = False) -> Settings:
"""
Serializes a list of :py:class:`sqsgenerator.public.SQSResult` into a JSO... | 31,977 |
def test_files_atlas(test_files):
"""ATLAS files"""
# ssbio/test/test_files/atlas
return op.join(test_files, 'atlas') | 31,978 |
def _get_xaxis_polynomial_(xyv, degree=DEGREE, legendre=LEGENDRE,
xmodel=None, clipping = [5,5]):
""" """
from modefit.basics import get_polyfit
x,y,v = xyv
flagin = ((np.nanmean(y) - clipping[0] * np.nanstd(y)) < y) * (y< (np.nanmean(y) + clipping[1] * np.nanstd(y)))
... | 31,979 |
def generateKey():
"""
Method to generate a encryption key
"""
try:
key = Fernet.generate_key()
updateClipboard(f"export LVMANAGER_PW={str(key)[2:-1]}")
print(f"Key: {key}")
print("Export command copied to clipboard. Save this value!")
return True
except Excep... | 31,980 |
def _zpkbilinear(z, p, k, fs):
""" Return a digital filter from an analog one using a bilinear transform """
z = np.atleast_1d(z)
p = np.atleast_1d(p)
degree = _relative_degree(z, p)
fs2 = 2.0 * fs
# Bilinear transform the poles and zeros
z_z = (fs2 + z) / (fs2 - z)
p_z = (fs2 + p) / (fs... | 31,981 |
def preprocess(input_file: str, output_file: str):
"""
Reformat and augment the dataset.
Writes data to './data/chords.csv' by default.
Args:
input_file: the filepath to the dataset
"""
# getting chord progressions from input file
progressions = []
with open(input_file) as f... | 31,982 |
def so3exp(w):
"""
Maps so(3) --> SO(3) group with closed form expression.
"""
theta = np.linalg.norm(w)
if theta < _EPS * 3:
return np.eye(3)
else:
w_hat = S03_hat_operator(w)
R = np.eye(3) + (np.sin(theta) / theta) * w_hat + ((1 - np.cos(theta)) / theta**2) * np.dot... | 31,983 |
def bin2ppm(nproc_old, model_tags, region, npts, nproc,
old_mesh_dir, old_model_dir, output_dir):
"""
convert the bin files to the ppm model.
"""
result = ""
julia_path = get_julia("specfem_gll.jl/src/program/get_ppm_model.jl")
latnproc, lonnproc = map(int, nproc.split("/"))
npro... | 31,984 |
def st_sdata(obs, cols):
"""return string data in given observation numbers as a list of lists,
one sub-list for each row; obs should be int or iterable of int;
cols should be a single str or int or iterable of str or int
"""
obs, cols, _ = _parseObsColsVals(obs, cols)
if not all(st_i... | 31,985 |
def list_data(args, data):
"""List all servers and files associated with this project."""
if len(data["remotes"]) > 0:
print("Servers:")
for server in data["remotes"]:
if server["name"] == server["location"]:
print(server["user"] + "@" + server["location"])
... | 31,986 |
def vecInt(xx, vv, p, interpolation = 'weighted'):
"""
Interpolates the field around this position.
call signature:
vecInt(xx, vv, p, interpolation = 'weighted')
Keyword arguments:
*xx*:
Position vector around which will be interpolated.
*vv*:
... | 31,987 |
def anchor_inside_flags(flat_anchors, valid_flags, img_shape,
allowed_border=0, device='cuda'):
"""Anchor inside flags.
:param flat_anchors: flat anchors
:param valid_flags: valid flags
:param img_shape: image meta info
:param allowed_border: if allow border
:return: ins... | 31,988 |
def notinLRG_mask(primary=None, rflux=None, zflux=None, w1flux=None,
rflux_snr=None, zflux_snr=None, w1flux_snr=None):
"""See :func:`~desitarget.sv1.sv1_cuts.isLRG` for details.
Returns
-------
:class:`array_like`
``True`` if and only if the object is NOT masked for poor quali... | 31,989 |
def create_ps_realisation(
out_dir,
fault_name,
lat,
lon,
depth,
mw_mean,
mom,
strike,
rake,
dip,
n_realisations=50,
additional_options={},
dt=0.005,
vs=3.20,
rho=2.44,
target_area_km=None,
target_slip_cm=None,
stype="cos",
rise_time=0.5,
i... | 31,990 |
def capture_ops():
"""Decorator to capture ops created in the block.
with capture_ops() as ops:
# create some ops
print(ops) # => prints ops created.
"""
micros = int(time.time()*10**6)
scope_name = str(micros)
op_list = []
with tf.name_scope(scope_name):
yield op_list
g = tf.get_default_gra... | 31,991 |
def get_theta_def(pos_balle:tuple, cote:str):
"""
Retourne les deux angles theta (voir les explications) pour que le goal soit aligné avec la balle.
Ceux-ci sont calculés en fonction des deux poteaux pour avoir les deux "extrémités" pour être correctement alignées.
Paramètres:
- pos_balle : tuple - conti... | 31,992 |
def test_layout_design_versus_relative_sizing():
"""
this also examines such problems with empty spaces.
"""
with pytest.raises(Exception) as e_info:
mylayout = cow.layout(design = """
A#BB
ACC#
... | 31,993 |
def public_doc():
"""Documentation for this api."""
return auto.html(groups=['public'], title='Ocean App Web Service Public Documentation') | 31,994 |
def _prepend_force_name_to_params(force):
"""
This function is called by :py:mod:`polychrom.simulation.Simulation.add_force` method.
It's goal is to avoid using the same names of global parameters defined in different forces.
To this end, it modifies names of parameters of each force to start with the... | 31,995 |
def getAllTeams():
"""
returns the entire list of teams
"""
return Team.objects.order_by('name').all() | 31,996 |
def task_check(rollout: RolloutStorage) -> None:
"""
Given a rollout, checks that task indices are returned from observations correctly
and that tasks are resampled correctly within and between processes.
"""
# Get initial task indices.
task_indices = get_task_indices(rollout.obs[0])
episod... | 31,997 |
def parse_lamp_flags(flags):
"""Parses flags and returns a dict that represents the lamp states."""
# flags: [0123]{8}
values = _swap_key_and_value(_LAMP_STATES) # {value: state}
states = dict([
(color, values[flags[digit]]) for color, digit in _LAMP_DIGITS.items()
])
return {'lamps': s... | 31,998 |
def user_owns_item(function):
""" Decorator that checks that the item was created by current user. """
@wraps(function)
def wrapper(category_name, item_name, *args, **kwargs):
category = db_session.query(Category
).filter_by(name=category_name).one()
user_... | 31,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.