content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import sys
def check_ft_grid(fv, diff):
"""Grid check for fft optimisation"""
if np.log2(np.shape(fv)[0]) == int(np.log2(np.shape(fv)[0])):
nt = np.shape(fv)[0]
else:
print("fix the grid for optimization \
of the fft's, grid:" + str(np.shape(fv)[0]))
sys.exit(1)
... | ee3746125be40ef374ef1008b1db5ecaf31c719b | 7,500 |
from typing import Callable
def _concat_applicative(
current: KindN[
_ApplicativeKind, _FirstType, _SecondType, _ThirdType,
],
acc: KindN[
_ApplicativeKind, _UpdatedType, _SecondType, _ThirdType,
],
function: KindN[
_ApplicativeKind,
Callable[[_FirstType], Callable[... | fb720d87f643592f3ebed01bd55364fec83e1b22 | 7,501 |
def goto_x(new_x):
"""
Move tool to the new_x position at speed_mm_s at high speed. Update curpos.x with new position.
If a failure is detected, sleep so the operator can examine the situation.
Since the loss of expected responses to commands indicates that the program does not know
the exact po... | fe49dde9349e18cea91d8f7ee1aae1f3545b5a04 | 7,502 |
def server_rename(adapter_id, server_id):
"""Renames a server using a certain adapter, if that adapter supports renaming."""
adapter = get_adapter(adapter_id)
if not adapter:
return output.failure("That adapter doesn't (yet) exist. Please check the adapter name and try again.", 501)
if not ada... | 55a25178a3ff9ec1e2e1d4a2f7cdd228bf0914cb | 7,503 |
import pathlib
import os
def _to_absolute_uri(uri):
"""
Converts the input URI into an absolute URI, relative to the current working
directory.
:param uri: A URI, absolute or relative.
:return: An absolute URI.
"""
if ":" in uri: #Already absolute. Is either a drive letter ("C:/") or already fully specified UR... | b80c56d298e16ed1abd958950cc45b5e45e26111 | 7,504 |
def index():
""" Root URL response, load UI """
return app.send_static_file("index.html") | fd793fadf7ecaf8e2c435b377c264aaf6e4da1d2 | 7,505 |
def restore_capitalization(word, example):
"""
Make the capitalization of the ``word`` be the same as in ``example``:
>>> restore_capitalization('bye', 'Hello')
'Bye'
>>> restore_capitalization('half-an-hour', 'Minute')
'Half-An-Hour'
>>> restore_capitalization('usa', 'I... | 77b074acb4d95de5d88f37495786f6679fa5f54d | 7,506 |
def test_loss_at_machine_precision_interval_is_zero():
"""The loss of an interval smaller than _dx_eps
should be set to zero."""
def f(x):
return 1 if x == 0 else 0
def goal(l):
return learner.loss() < 0.01 or learner.npoints >= 1000
learner = Learner1D(f, bounds=(-1, 1))
simp... | 61d2efd80054729aafbe11d67873860f96f2198b | 7,507 |
def params_document_to_uuid(params_document):
"""Generate a UUID5 based on a pipeline components document"""
return identifiers.typeduuid.catalog_uuid(params_document) | 32366dd5fa2ff4acfe848a7a4633baba23a1e993 | 7,508 |
import typing
def modify_account() -> typing.RouteReturn:
"""IntraRez account modification page."""
form = forms.AccountModificationForm()
if form.validate_on_submit():
rezident = flask.g.rezident
rezident.nom = form.nom.data.title()
rezident.prenom = form.prenom.data.title()
... | e67b553f0c7051d5be4b257824f495f0a0ad9838 | 7,509 |
def fizzbuzz(end=100):
"""Generate a FizzBuzz game sequence.
FizzBuzz is a childrens game where players take turns counting.
The rules are as follows::
1. Whenever the count is divisible by 3, the number is replaced with
"Fizz"
2. Whenever the count is divisible by 5, the number is replaced... | b68b1c39674fb47d0bd12d387f347af0ef0d26ca | 7,510 |
def generate_lane_struct():
""" Generate the datatype for the lanes dataset
:return: The datatype for the lanes dataset and the fill values for the lanes dataset
"""
lane_top_list = []
for item in [list1 for list1 in lane_struct if list1.__class__.__name__ == "LaneTop"]:
lane_top_list.appen... | 698fadc8472233ae0046c9bbf1e4c21721c7de48 | 7,511 |
def notification_list(next_id=None): # noqa: E501
"""notification_list
Get all your certificate update notifications # noqa: E501
:param next_id:
:type next_id: int
:rtype: NotificationList
"""
return 'do some magic!' | 4fe4467f89ad4bf1ba31bd37eace411a78929a26 | 7,512 |
import os
def _delete_dest_path_if_stale(master_path, dest_path):
"""Delete dest_path if it does not point to cached image.
:param master_path: path to an image in master cache
:param dest_path: hard link to an image
:returns: True if dest_path points to master_path, False if dest_path was
st... | cbe2387e5a0b9a27afcfc9a0bd34cfeb6f164ae4 | 7,513 |
import requests
def SendPost(user, password, xdvbf, cookie, session, url=URL.form):
"""
根据之前获得的信息,发送请求
:param user: 学号
:param password: 密码
:param xdvbf: 验证码内容
:param cookie: 之前访问获得的cookie
:param session: 全局唯一的session
:param url: 向哪个资源发送请求
:return: response
"""
form_data = {... | 932d869f048e8f06d7dbfe6032950c66a72224fa | 7,514 |
def css_flat(name, values=None):
"""Все значения у свойства (по порядку)
left -> [u'auto', u'<dimension>', u'<number>', u'<length>', u'.em', u'.ex',
u'.vw', u'.vh', u'.vmin', u'.vmax', u'.ch', u'.rem', u'.px', u'.cm',
u'.mm', u'.in', u'.pt', u'.pc', u'<percentage>', u'.%']
"""
cu... | a992d261d234f9c4712b00986cb6ba5ba4347b8f | 7,515 |
def prepare_mqtt(MQTT_SERVER, MQTT_PORT=1883):
"""
Initializes MQTT client and connects to a server
"""
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_SERVER, MQTT_PORT, 60)
return client | a5015d80c5c0222ac5eb40cbb1ba490826fcebae | 7,516 |
def record_iterator_class(record_type):
"""
Gets the record iterator for a given type
A way to abstract the construction of a record iterator class.
:param record_type: the type of file as string
:return: the appropriate record iterator class
"""
if record_type == 'bib':
return Bib... | b1fbd393819055b9468a96b5ec7e44d3773dcf52 | 7,517 |
from typing import Sequence
from typing import Dict
def sort_servers_closest(servers: Sequence[str]) -> Dict[str, float]:
"""Sorts a list of servers by http round-trip time
Params:
servers: sequence of http server urls
Returns:
sequence of pairs of url,rtt in seconds, sorted by rtt, exclu... | efa225e13f989d0b350138e111b7945b2bb04fb0 | 7,518 |
from typing import Any
def palgo(
dumbalgo: type[DumbAlgo], space: Space, fixed_suggestion_value: Any
) -> SpaceTransformAlgoWrapper[DumbAlgo]:
"""Set up a SpaceTransformAlgoWrapper with dumb configuration."""
return create_algo(algo_type=dumbalgo, space=space, value=fixed_suggestion_value) | 373f74ca675250b5a422ff965396a122c4b967fd | 7,519 |
def english_to_french(english_text):
"""
Input language translate function
"""
translation = language_translator.translate(text=english_text, model_id = "en-fr").get_result()
french_text = translation['translations'][0]['translation']
return french_text | ac9951d0362ccf511361dfc676b03f61f4fe8453 | 7,520 |
from typing import Sequence
def noise_get_turbulence(
n: tcod.noise.Noise,
f: Sequence[float],
oc: float,
typ: int = NOISE_DEFAULT,
) -> float:
"""Return the turbulence noise sampled from the ``f`` coordinate.
Args:
n (Noise): A Noise instance.
f (Sequence[float]): The point t... | f4af83726dd6f3badf2c2eaa86f647dd4ad71cb3 | 7,521 |
from typing import Union
import os
def read_data_file(file_path: str, filename: str) -> Union[pd.DataFrame, str]:
"""Check read data file."""
logger.info(f"Reading {file_path}")
try:
if file_path.endswith(CSV):
return pd.read_csv(file_path, sep=",")
elif file_path.endswith(TSV... | 1e737c421db3c9d1609b0bf16fecb1e15d506824 | 7,522 |
def mnist_loader(path="../../corruptmnist", n_files=8, image_scale=255):
"""
Loads .npz corruptedmnist, assumes loaded image values to be between 0 and 1
"""
# load and stack the corrupted mnist dataset
train_images = np.vstack(
[np.load(path + "/train_{}.npz".format(str(i)))["images"] for i... | a7e7328621819e0cbf163e1ef006df5183b6d25d | 7,523 |
def reduce_min(values, index, name='segmented_reduce_min'):
"""Computes the minimum over segments."""
return _segment_reduce(values, index, tf.math.unsorted_segment_min, name) | 473698ffd1295344dd8019b01b69d464f2db93b8 | 7,524 |
import glob
def _data_type(data_string: str):
""" convert the data type string (i.e., FLOAT, INT16, etc.) to the appropriate int.
See: https://deeplearning4j.org/api/latest/onnx/Onnx.TensorProto.DataType.html
"""
for key, val in glob.DATA_TYPES.items():
if key == data_string:
retu... | a0fce62a304ce8b61ad2ecf173b8723cf66f10c0 | 7,525 |
def bin_power(dataset, fsamp:int, band=range(0, 45)):
"""Power spec
Args:
dataset: n_epoch x n_channel x n_sample
fsamp:
band:
Returns:
n_epoch x n_channel x len(band)
"""
res = []
for i, data in enumerate(dataset):
res.append(power(data, fsamp=fsamp, ba... | e85815837d2cab8bd1b89132df29a439ec54bd34 | 7,526 |
import six
import base64
import zlib
def deflate_and_base64_encode(string_val):
"""
Deflates and the base64 encodes a string
:param string_val: The string to deflate and encode
:return: The deflated and encoded string
"""
if not isinstance(string_val, six.binary_type):
string_val = st... | 31fc19cf134bc22b3fc45b4158c65aef666716cc | 7,527 |
def smooth_reward_curve(x, y):
"""Smooths a reward curve--- how?"""
k = min(31, int(np.ceil(len(x) / 30))) # Halfwidth of our smoothing convolution
xsmoo = x[k:-k]
ysmoo = np.convolve(y, np.ones(2 * k + 1), mode='valid') / np.convolve(np.ones_like(y), np.ones(2 * k + 1), mode='valid')
downsample = max(int(np... | 3106cc75a8ceb58f29cded4353133eff7a737f8b | 7,528 |
def sdot(s):
"""Returns the time derivative of a given state.
Args:
s(1x6 numpy array): the state vector [rx,ry,rz,vx,vy,vz]
Returns:
1x6 numpy array: the time derivative of s [vx,vy,vz,ax,ay,az]
"""
mu_Earth = 398600.4405
r = np.linalg.norm(s[0:3])
a = -mu_Ear... | 4e79054e194b5395953fbda30794e819c6700feb | 7,529 |
def get_values(abf,key="freq",continuous=False):
"""returns Xs, Ys (the key), and sweep #s for every AP found."""
Xs,Ys,Ss=[],[],[]
for sweep in range(abf.sweeps):
for AP in cm.matrixToDicts(abf.APs):
if not AP["sweep"]==sweep:
continue
Ys.append(AP[key])
... | 8671d795410b8064fd70172da396ccbd4323c9a3 | 7,530 |
def geodetic2cd(
gglat_deg_array, gglon_deg_array, ggalt_km_array, decimals=2, year=2021.0
):
"""Transformation from Geodetic (lat, lon, alt) to Centered Dipole (CD) (lat, lon, alt).
Author: Giorgio Savastano (giorgiosavastano@gmail.com)
Parameters
----------
gglon_deg_array : np.ndarray
... | b5a3a8622051e05f31e3f087869b8bebfd213fd9 | 7,531 |
import pickle
def load_pickle(file_path):
"""
load the pickle object from the given path
:param file_path: path of the pickle file
:return: obj => loaded obj
"""
with open(file_path, "rb") as obj_des:
obj = pickle.load(obj_des)
# return the loaded object
return obj | 4770a152dad9c7d123f95a53642aff990f3590f7 | 7,532 |
def _expand_global_features(B, T, g, bct=True):
"""Expand global conditioning features to all time steps
Args:
B (int): Batch size.
T (int): Time length.
g (Tensor): Global features, (B x C) or (B x C x 1).
bct (bool) : returns (B x C x T) if True, otherwise (B x T x C)
Retur... | 9d0ab550147d8658f0ff8fb5cfef8fc565c5f3d3 | 7,533 |
import argparse
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Find common kmers',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file1',
help='Input file 1',
me... | fe999b12b65902ce51f8c3ea165012b17a0724ba | 7,534 |
def plot_CDF(data, ax=None, reverse=False, plot=True, **plotargs):
""" plot Cumulative Ratio. """
n_samples = len(data)
X = sorted(data, reverse=reverse)
Y = np.arange(1,n_samples+1)/n_samples
if plot or ax:
if ax is None:
fig, ax = plt.subplots()
ax.plot(X, Y, **plotarg... | 25d9a83a9b560a89137c0e4eb6cd63761f39901f | 7,535 |
def is_zsettable(s):
"""quick check that all values in a dict are reals"""
return all(map(lambda x: isinstance(x, (int, float, long)), s.values())) | ad51e7419a37bec071be6aa2c1a4e9d62bce913c | 7,536 |
from typing import Sequence
def initialize_simulator(task_ids: Sequence[str],
action_tier: str) -> ActionSimulator:
"""Initialize ActionSimulator for given tasks and tier."""
tasks = phyre.loader.load_compiled_task_list(task_ids)
return ActionSimulator(tasks, action_tier) | 8b54ae1c98d44839a33a8774de48e53f1ce9ca96 | 7,537 |
import asyncio
async def async_unload_entry(hass: core.HomeAssistant, config_entry: config_entries.ConfigEntry) -> bool:
"""Unload a config entry."""
_LOGGER.debug("%s: async_unload_entry", DOMAIN)
try:
all_ok = True
for platform in SUPPORTED_PLATFORMS:
_LOGGER.debug("%s - asyn... | 50e2011c35527608ba98c4cdb1729d7f909d295a | 7,538 |
def import_sensitivities(input, file_location):
"""
Ratio is the C/O starting gas ratio
file_location is the LSR C and O binding energy, false to load the base case
"""
tol, ratio = input
try:
data = pd.read_csv(file_location + '/all-sensitivities/' + tol + '{:.1f}RxnSensitivity.csv'.f... | c0b0c9d740335032b4d196232c3166818aa77a1a | 7,539 |
import re
import ntpath
def extract_files_to_process(options, company_file):
"""Extract the files from the ENER zip file and the ITR/DFP inside of it,
and collect all the XML files
"""
force_download = options.get("force_download", False)
local_base_path = _doc_local_base_path(options, company_fi... | 963dd738224c36311791c54d964ae5b95d345a7f | 7,540 |
import os
def pg_dump(dsn, output):
"""
Сохраняет схему БД в файл
:param dsn: Строка подключения. Например: username@localhost:5432/dname
:param output: Имя файла для сохранения DDL
:type dsn: str
:type output: str
"""
host, port, user, pwd, dbname, socket = parse_dsn(dsn)
args =... | cf131054daacd97f7673456c277e8ca6d3f9f066 | 7,541 |
def merge(source, dest):
""" Copy all properties and relations from one entity onto another, then
mark the source entity as an ID alias for the destionation entity. """
if source.id == dest.id:
return source
if dest.same_as == source.id:
return source
if source.same_as == dest.id:
... | 9cb6963ba0e15e639915e27d7c369394d7088231 | 7,542 |
import json
import re
def create_summary_text(summary):
"""
format a dictionary so it can be printed to screen or written to a plain
text file
Args:
summary(dict): the data to format
Returns:
textsummary(str): the summary dict formatted as a string
"""
summaryjson = json.... | 3a8dd508b760a0b9bfe925fa2dc07d53dee432af | 7,543 |
from datetime import datetime
import random
def random_datetime(start, end):
"""Generate a random datetime between `start` and `end`"""
return start + datetime.timedelta(
# Get a random amount of seconds between `start` and `end`
seconds=random.randint(0, int((end - start).total_seconds())),
... | c3cf7a0fb616b9f157d5eb86b3d76f1cd811308f | 7,544 |
def maximo_basico(a: float, b: float) -> float:
"""Toma dos números y devuelve el mayor.
Restricción: No utilizar la función max"""
if a > b:
return a
return b | f98db565243587015c3b174cf4130cbc32a00e22 | 7,545 |
def listas_mesmo_tamanho(lista_de_listas):
"""
Recebe uma lista de listas e retorna 'True' caso todas as listas
sejam de mesmo tamanho e 'False', caso contrário
"""
tamanho_padrao = len(lista_de_listas[0])
for lista in lista_de_listas:
if(len(lista) != tamanho_padrao):
retu... | 3a405f36bf8cd906fc603e9774cc23e07738e123 | 7,546 |
def compute_all_mordred_descrs(mols, max_cpus=None, quiet=True):
"""
Compute all Mordred descriptors, including 3D ones
Args:
mols: List of RDKit mol objects for molecules to compute descriptors for.
max_cpus: Max number of cores to use for computing descriptors. None means use all availab... | cc5002096e82fb0c53ca6aa5523d2f81e43ca760 | 7,547 |
def self_quarantine_policy_40():
"""
Real Name: b'self quarantine policy 40'
Original Eqn: b'1-PULSE(self quarantine start 40, self quarantine end 40-self quarantine start 40)*self quarantine effectiveness 40'
Units: b'dmnl'
Limits: (None, None)
Type: component
b''
"""
return 1 - fu... | 87ae16bd53bdd08a71231297949c3b995c7f9ba0 | 7,548 |
def fetch_mate_variant_record(vcfhandle, chr_mate, pos_mate, mateid, count=0, slop=50):
"""
We fetch the MateID variant Record for the breakend being process
:param vcfhandle:
:param chr_mate:
:param pos_mate:
:param mateid: must be a string and not a tuple
:param count: Normally the mate_r... | b09f37f8b2bf9fc3b9513c33c2857be7034629b4 | 7,549 |
def knapsack_bqm(cities, values, weights, total_capacity, value_r=0, weight_r=0):
"""
build the knapsack binary quadratic model
From DWave Knapsack examples
Originally from Andrew Lucas, NP-hard combinatorial problems as Ising spin glasses
Workshop on Classical and Quantum Optimization; ETH Zue... | 0a00c5fbcf30e36b7d6a03b9edc4029582b001fd | 7,550 |
from typing import List
def nltk_punkt_de(data: List[str], model=None) -> List[str]:
"""Sentence Segmentation (SBD) with NLTK's Punct Tokenizer
Parameters:
-----------
data : List[str]
list of N documents as strings. Each document is then segmented
into sentences.
model (Defaul... | 10b924070ebcb3062c9b40f4f6ca0a3a006f8d2e | 7,551 |
def is_pattern_error(exception: TypeError) -> bool:
"""Detect whether the input exception was caused by invalid type passed to `re.search`."""
# This is intentionally simplistic and do not involve any traceback analysis
return str(exception) == "expected string or bytes-like object" | 623246404bbd54bc82ff5759bc73be815d613731 | 7,552 |
import pdb
def iwave_modes_banded(N2, dz, k=None):
"""
!!! DOES NOT WORK!!!
Calculates the eigenvalues and eigenfunctions to the internal wave eigenvalue problem:
$$
\left[ \frac{d^2}{dz^2} - \frac{1}{c_0} \bar{\rho}_z \right] \phi = 0
$$
with boundary conditions
"""
nz... | f4016fb4acd1c5aa024d8ac1e69262dec9057713 | 7,553 |
def parse_fastq_pf_flag(records):
"""Take a fastq filename split on _ and look for the pass-filter flag
"""
if len(records) < 8:
pf = None
else:
fastq_type = records[-1].lower()
if fastq_type.startswith('pass'):
pf = True
elif fastq_type.startswith('nopass'):
... | 9a46022aa6e07ed3ca7a7d80933ee23e26d1ca9a | 7,554 |
def rule_manager():
""" Pytest fixture for generating rule manager instance """
ignore_filter = IgnoreFilter(None, verbose=False)
return RuleManager(None, ignore_filter, verbose=False) | ce5e9ecf482b5dfd0e3b99b2367605d6e488f7e7 | 7,555 |
def zeros(fn, arr, *args):
"""
Find where a function crosses 0. Returns the zeroes of the function.
Parameters
----------
fn : function
arr : array of arguments for function
*args : any other arguments the function may have
"""
# the reduced function, with only the argument to be s... | 129a162912f86ee52fc57b1a3a46acaf402598f5 | 7,556 |
import math
def create_low_latency_conv_model(fingerprint_input, model_settings,
is_training):
"""Builds a convolutional model with low compute requirements.
This is roughly the network labeled as 'cnn-one-fstride4' in the
'Convolutional Neural Networks for Small-footprint Key... | 3b03e84c9af5a6d1134736d8757e15039bb196b8 | 7,557 |
import argparse
def get_args(description: str = "YouTube") -> argparse.Namespace:
"""
Retrieve parsed arguments as a Namespace.
Parameters
----------
description : str
Description given to ArgumentParser.
Returns
-------
args : argparse.Namespace
Namespace with argume... | ca2013c476cf7df1dbdb458e4c4db0a5c4124195 | 7,558 |
import os
def _DropEmptyPathSegments(path):
"""Removes empty segments from the end of path.
Args:
path: A filesystem path.
Returns:
path with trailing empty segments removed. Eg /duck/// => /duck.
"""
while True:
(head, tail) = os.path.split(path)
if tail:
break
path = head
retu... | 23060efc37343bf7ccec483847264c5f6a7c811b | 7,559 |
def _format_author(url, full_name):
""" Helper function to make author link """
return u"<a class='more-info' href='%s'>%s</a>" % (url, full_name) | 50f001c2358b44bb95da628cc630a2ed3ea8ddfd | 7,560 |
def all_series(request: HttpRequest) -> JsonResponse:
"""
View that serves all the series in a JSON array.
:param request: The original request.
:return: A JSON-formatted response with the series.
"""
return JsonResponse([
_series_response(request, s)
for s in get_response(requ... | 01657615b53a4316a9ec0ad581e009928cfefed2 | 7,561 |
def stlx_powerset(s):
"""If s is a set, the expression pow(s) computes the power set of s. The power set of s is
defined as the set of all subsets of s."""
def powerset_generator(i):
for subset in it.chain.from_iterable(it.combinations(i, r) for r in range(len(i)+1)):
yield set(subset)... | 9297efa03636ff19da7aae4e60593bcc9933d6bb | 7,562 |
import copy
def get_entries_configuration(data):
"""Given the dictionary of resources, returns the generated factory xml file
Args:
data (dict): A dictionary similar to the one returned by ``get_information``
Returns:
str: The factory xml file as a string
"""
entries_configuratio... | db228df9062b8801f7edde5d1e2977ef1e451b5f | 7,563 |
def validinput(x0, xf, n):
"""Checks that the user input is valid.
Args:
x0 (float): Start value
xf (float): End values
n (int): Number of sample points
Returns:
False if x0 > xf or if
True otherwise
"""
valid = True
if x0 > xf:
valid = False
... | 096e0702eb8fe47486d4f03e5b3c55c0835807cd | 7,564 |
def multi_class_bss(predictions: np.ndarray, targets: np.ndarray) -> float:
"""
Brier Skill Score:
bss = 1 - bs / bs_{ref}
bs_{ref} will be computed for a model that makes a predictions according to the prevalance of each class in dataset
:param predictions: probability score. Expected Shape [N, C... | d932649e2eb1a1b91aa2cf3882b0f4b74531dea7 | 7,565 |
def get_arxiv_id_or_ascl_id(result_record):
"""
:param result_record:
:return:
"""
identifiers = result_record.get("identifier", [])
for identifier in identifiers:
if "arXiv:" in identifier:
return identifier.replace("arXiv:", "")
if "ascl:" in identifier:
... | 4270fe7ad8f2136ad5d53272acb02aaf60970ea3 | 7,566 |
from typing import Mapping
from typing import Tuple
import torch
def get_query_claim_similarities(
sim: Mapping[Tuple[str, int], float],
softmax: bool,
) -> Mapping[Tuple[str, int], float]:
"""
Preprocess query claim similarities.
:param sim:
A mapping from (premise_id, claim_id) to the l... | 6f1eb9495c7b7243f544564315ca3ae09f31da92 | 7,567 |
import re
def regexp(options: dict):
"""
Apply a regexp method to the dataset
:param options: contains two values:
- find: which string should be find
- replace: string that will replace the find string
"""
def apply_regexp(dataset, tag):
"""
Apply a regexp to the... | 20cfaf4f9286ad582dc9f4fea4184cf1c7d0de34 | 7,568 |
def do_one_subject(sub_curr, params, verbose=False):
"""
launch sessions processing for sub_curr
parameters:
-----------
sub_curr: dict
contains subject base directory
contains subject index
params: dict
parameters for layout, data and analysis
... | 68ba212eeccde0197c587a0b929198b2a042328d | 7,569 |
def comp_skin_effect(self, freq, T_op=20, T_ref=20, type_skin_effect=1):
"""Compute the skin effect factor for the conductor
Parameters
----------
self : Conductor
an Conductor object
freq: float
electrical frequency [Hz]
T_op: float
Conductor operational temperature [de... | b71f4385d600713f3fff559e0836d9c532b79b73 | 7,570 |
import copy
import scipy
def insert_point_into_G(G_, point, node_id=100000, max_distance_meters=5,
nearby_nodes_set=set([]), allow_renaming=True,
verbose=False, super_verbose=False):
"""
Insert a new node in the graph closest to the given point.
Notes
-... | b816ac5a050b5914c33dfe4e598d6997a8da5d0c | 7,571 |
import glob
def find_paths(initial_path, extension):
"""
From a path, return all the files of a given extension inside.
:param initial_path: the initial directory of search
:param extension: the extension of the files to be searched
:return: list of paths inside the initial path
"""
path... | 0220127050b765feaf423c195d020d65ece8d22e | 7,572 |
def ridge_line(df_act, t_range='day', n=1000):
"""
https://plotly.com/python/violin/
for one day plot the activity distribution over the day
- sample uniform from each interval
"""
df = activities_dist(df_act.copy(), t_range, n)
colors = n_colors('rgb(5, 200, 200)', 'rgb(200, 10, 10... | 7fa2e4946a8de5df6e5c7697236c939703133409 | 7,573 |
def op(name,
value,
display_name=None,
description=None,
collections=None):
"""Create a TensorFlow summary op to record data associated with a particular the given guest.
Arguments:
name: A name for this summary operation.
guest: A rank-0 string `Tensor`.
display_n... | f2a6b65299c417e460f6ca2e41fc82e061b29f30 | 7,574 |
def select_only_top_n_common_types(dataset: pd.DataFrame, n: int = 10) -> pd.DataFrame:
"""
First find the most popular 'n' types. Remove any uncommon types from the
dataset
:param dataset: The complete dataset
:param n: The number of top types to select
:return: Return the dataframe once the t... | b4d95682d1abbf062b4730213cefc6da71a5c605 | 7,575 |
import os
import torch
def load_checkpoint(filename='checkpoint.pth.tar'):
"""Load for general purpose (e.g., resume training)"""
filename = os.path.join(CHECKPOINTS_PATH, filename)
print(filename)
if not os.path.isfile(filename):
return None
state = torch.load(filename)
return state | c64d5a0ab76bb08b5fc982b1f06c61fec216cee7 | 7,576 |
def __one_both_closed(x, y, c = None, l = None):
"""convert coordinates to zero-based, both strand, open/closed coordinates.
Parameters are from, to, is_positive_strand, length of contig.
"""
return x - 1, y | ce4dfca3cc347de925f4c26460e486fb38a2d5e5 | 7,577 |
def get_corners(img, sigma=1, alpha=0.05, thresh=1000):
""" Returns the detected corners as a list of tuples """
ret = []
i_x = diff_x(img)
i_y = diff_y(img)
i_xx = ndimage.gaussian_filter(i_x ** 2, sigma=sigma)
i_yy = ndimage.gaussian_filter(i_y ** 2, sigma=sigma)
i_xy = ndimage.gaussian_fi... | d581df8daff7f20e2f15b5eb5af9ea686c0520e4 | 7,578 |
import numpy
def add_param_starts(this_starts, params_req, global_conf, run_period_len, start_values_min, start_values_max):
"""Process the param starts information taken from the generator, and add it to
the array being constructed.
Inputs:
this_starts: a tuple with (starts_min, starts_max),... | b50f538b9d5096fe6061b4b990ccb9ad6ba05ef6 | 7,579 |
def pareto(data, name=None, exp=None, minval=None, maxval=None, **kwargs):
"""the pareto distribution: val ~ val**exp | minval <= val < maxval
"""
assert (exp is not None) and (minval is not None) and (maxval is not None), \
'must supply exp, minval, and maxval!' ### done to make command-line argume... | 8607bf6783ba5e8be95d2b4319a42e8723b71da0 | 7,580 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_ansible_tower package"""
reload_params = {"package": u"fn_ansible_tower",
"incident_fields": [],
"action_fields": [u"ansible_tower_arguments", u"ansible_tower_credential", u"ansible_tower_hosts",... | 49dee7d9a1dc297ff31f51e4583740c353831cd9 | 7,581 |
from core.models.group import GroupMembership
def get_default_identity(username, provider=None):
"""
Return the default identity given to the user-group for provider.
"""
try:
filter_query = {}
if provider:
filter_query['provider'] = provider
memberships = GroupMemb... | 54fc7d546d41564ea025ca3d2e947a5e5f77004a | 7,582 |
def get_text_item(text):
"""Converts a text into a tokenized text item
:param text:
:return:
"""
if config['data']['lowercased']:
text = text.lower()
question_tokens = [Token(t) for t in word_tokenize(text)]
question_sentence = Sentence(' '.join([t.text for t in question_tokens]), q... | 79fdec4cdcb419751d49a564eff7c3b624c80a22 | 7,583 |
def Ltotal(scatter: bool):
"""
Graph for computing 'Ltotal'.
"""
graph = beamline(scatter=scatter)
if not scatter:
return graph
del graph['two_theta']
return graph | d38b7947b4c6397157e1bfec33b275a814dc1ec0 | 7,584 |
import os
def gen_dir(download_dir, main_keyword):
"""Helper function | generates a directory where pics will be downloaded"""
if not download_dir:
download_dir = './data/'
img_dir = download_dir + main_keyword + '/'
if not os.path.exists(img_dir):
os.makedirs(img_dir)
return img_d... | 2a8fe841ac4c2afdf64cd91f6dae1842e2c3c51d | 7,585 |
def is_valid_page_to_edit(prev_pg_to_edit, pg_to_edit):
"""Check if the page is valid to edit or not
Args:
prev_pg_to_edit (obj): page to edit object of previous page
pg_to_edit (obj): page to edit object of current page
Returns:
boolean: true if valid else false
"""
try:
... | ce594804f105b749062f79d63fc3021296631c1b | 7,586 |
def get_diffs(backups, backup_id, partner_backups, bound=10):
"""
Given a list `backups`, a `backup_id`, and `bound`
Compute the a dict containing diffs/stats of surronding the `backup_id`:
diff_dict = {
"stats": diff_stats_list,
"files": files_list,
"partners": partner_files... | fd896dc22270090eb88b41b3ab3fae2872d2ad06 | 7,587 |
from typing import List
def admits_voc_list(cid: CID) -> List[str]:
"""
Return list of nodes in cid with positive value of control.
"""
return [x for x in list(cid.nodes) if admits_voc(cid, x)] | a2db0dbb062a205ebb75f5db93ed14b11b25ccc1 | 7,588 |
def contour(data2d, levels, container=None, **kwargs):
"""HIDE"""
if container is None:
_checkContainer()
container = current.container
current.object = kaplot.objects.Contour(container, data2d, levels, **kwargs)
return current.object | a9f56a8bcd54cbc38687682f78e684c03315f85b | 7,589 |
def FilterSuboptimal(old_predictions,
new_predictions,
removed_predictions,
min_relative_coverage=0.0,
min_relative_score=0.0,
min_relative_pide=0.0):
"""remove suboptimal alignments.
"""
best_predicti... | 570399a0310f836261d5d65455cfee54e697a23c | 7,590 |
def process_pair(librispeech_md_file, librispeech_dir,
wham_md_file, wham_dir, n_src, pair):
"""Process a pair of sources to mix."""
utt_pair, noise = pair # Indices of the utterances and the noise
# Read the utterance files and get some metadata
source_info, source_list = read_ut... | 3dea4b1dc93b0bc54ad199e09db7612e6dad18d5 | 7,591 |
def getMultiDriverSDKs(driven, sourceDriverFilter=None):
"""get the sdk nodes that are added through a blendweighted node
Args:
driven (string): name of the driven node
sourceDriverFilter (list, pynode): Driver transforms to filter by,
if the connected SDK is not driven by this node it ... | 4f7fe2d959619d3eaca40ba6366a5d4d62e047ff | 7,592 |
def resnet_model_fn(features, labels, mode, model_class,
resnet_size, weight_decay, learning_rate_fn, momentum,
data_format, version, loss_filter_fn=None, multi_gpu=False):
"""Shared functionality for different resnet model_fns.
Initializes the ResnetModel representing t... | 4adc5fc3ca461d4eb4a051861e8c82d2c1aab5dd | 7,593 |
def dataframe_from_stomate(filepattern,largefile=True,multifile=True,
dgvmadj=False,spamask=None,
veget_npindex=np.s_[:],areaind=np.s_[:],
out_timestep='annual',version=1,
replace_nan=False):
"""
Paramete... | ba448d020ea8b41b75bd91d4b48ffca2d527b230 | 7,594 |
from applications.models import Application # circular import
def random_application(request, event, prev_application):
"""
Get a new random application for a particular event,
that hasn't been scored by the request user.
"""
return Application.objects.filter(
form__event=event
).excl... | 1d1b781b61328af67d7cc75c0fe9ec6f404b1b82 | 7,595 |
def flutter_velocity(pressures, speeds_of_sound,
root_chord, tip_chord, semi_span, thickness,
shear_modulus=2.62e9):
"""Calculate flutter velocities for a given fin design.
Fin dimensions are given via the root_chord, tip_chord, semi_span and
thickness arguments. ... | 6a6fcbc2fffe541ef85f824f282924bb38199f46 | 7,596 |
import re
def replace_within(begin_re, end_re, source, data):
"""Replace text in source between two delimeters with specified data."""
pattern = r'(?s)(' + begin_re + r')(?:.*?)(' + end_re + r')'
source = re.sub(pattern, r'\1@@REPL@@\2' , source)
if '@@REPL@@' in source:
source = source.replac... | 23320d11a8bf0d6387f4687555d1fa472ad4c4d0 | 7,597 |
import shutil
import os
def if_binary_exists(binary_name, cc):
"""
Returns the path of the requested binary if it exists and clang is being used, None if not
:param binary_name: Name of the binary
:param cc: Path to CC binary
:return: A path to binary if it exists and clang is being used, None if ... | 9f17748ba111a7ece33b8a0a7315c8832d15b014 | 7,598 |
import itertools
def random_outputs_for_tier(rng, input_amount, scale, offset, max_count, allow_extra_change=False):
""" Make up to `max_number` random output values, chosen using exponential
distribution function. All parameters should be positive `int`s.
None can be returned for expected types of failu... | eb3b7d813740e9aa9457fe62c4e0aaf86fad7bce | 7,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.