content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_model(task):
"""Create model."""
model_setenv()
if task == "clean":
checkpoint = "models/TOFlowClean.pth"
model = CleanFlow()
elif task == "slow":
checkpoint = "models/TOFlowSlow.pth"
model = SlowFlow()
elif task == "zoom":
checkpoint = "models/TOFlo... | 29c27a33ca0e4216021ea93712cbc281ab06c7a9 | 60,239 |
from typing import Union
from typing import Dict
from typing import Any
def translate_info(item: Union[str, Dict[str, Any]]) -> Dict[str, Any]:
"""Translate info from the client to as per fsspec requirements."""
assert not isinstance(item, str)
return {mapping.get(key, key): value for key, value in item.i... | 2fcc68e56776a43ad838b38c46e93e411543c28d | 60,240 |
def asmatrix(data, dtype=None):
""" Returns 'data' as a matrix. Unlike matrix(), no copy is performed
if 'data' is already a matrix or array. Equivalent to:
matrix(data, copy=False)
"""
return matrix(data, dtype=dtype, copy=False) | c9841930680b1f63067f829d78b415d6db4b20ce | 60,241 |
def get_message_hash(*, message):
"""Return has of given message"""
return sha3(sort_and_encode(message)).digest().hex() | 95b4982009bc342f53be5460a9a16dba36e8a81d | 60,242 |
def setup_movemap_from_resselectors(designable_selector, repackable_selector):
"""
Temporary function. Ultimately we want a more sophisticated movemap,
probably a neighbor movemap or something using clash-based shell selector.
"""
mm = rosetta.core.kinematics.MoveMap()
mm.set_chi(False)
mm.s... | 79e48d7d64999d2760efbae091fb4fc5a2d5dce0 | 60,243 |
def scoreWords(wordlist):
"""
Takes a list of words
Create dictionary of word=key and score=val
"""
return dict() | e6afb09790c6fb0c1b9ebc5c0694ac00af8bb669 | 60,245 |
import re
def find_latest_checkpoint(bucket_name, checkpoint_dir):
"""
Find the latest checkpoint file
Returns tuple of (extra_data_file, tune_metadata_file)
"""
# Google Storage API not smart enough, need to end the checkpoint_dir with '/'
if checkpoint_dir[-1] != '/':
checkpoint_dir ... | 131a2cd6dc4f522f20c1bc3209e0960f1eeb6274 | 60,246 |
import random
def random_hex_seeded(length, seed):
"""Get a random hex string of a given lenth with a specific seed."""
random.seed(seed)
return bytearray(random.getrandbits(8) for _ in range(length)).hex() | 5737057a33063cd9c62bc6071f0ef98552001117 | 60,247 |
def Parse(token, token_end, error_handler):
"""Parses a type annotation and returns a TypeAnnotation object."""
return TypeAnnotationParser(error_handler).Parse(token.next, token_end) | 56c38d6268b1b5f89d6c15d9375e3bdadf07cd6d | 60,248 |
def conv_celcius_to_kelvin(celcius):
"""
Convert Celcius to Kelvin
Returns
-------
double : Kelvin
"""
return celcius + const.zero_celcius_in_kelvin | e25f23e38e0b578cdb0b63bacd5af126e94a6c14 | 60,249 |
import configparser
def _get_config():
"""
Either returns an already loaded configparser
Or creates a configparser and loads ini config at /etc/cwlogd.ini
"""
global _config
if _config is None:
_config = configparser.ConfigParser()
_config.read(CONFIG_PATH)
return _config | a766e4c685d35862ed0e54861c0d001fe85059c2 | 60,250 |
def get_ratio_w_h(ratio):
"""
returns width and height from string e.g. '1-2' or '4-3' as integer
"""
w, h = ratio.split('-')
return float(w), float(h) | 41751e6056d4797e973d60c1e3691e7915a9e1ae | 60,251 |
def message_get_multiplexor(message_info, message_binary_msb, message_binary_lsb, message_binary_length):
"""Extract the multiplexor information of the message if any.
Arguments:
message_info: dict, information about the message (name, signals)
message_binary_msb: str, data of CAN message in MS... | facbb8fa1f7d7639f27dfacf134818f547af0694 | 60,252 |
def train_dictionary(train_dict: dict, test_dict: dict, iterations: int, model_dir: str, batch_size: int, tensors_to_log={}):
"""Trains the nn for given number of iterations
from the given model directory with a given batch_size"""
print("Given {} training examples and {} testing examples".format(
... | 7cfa22995436e5832ee52ede7ea634a7351a2fdf | 60,253 |
def create_app(config_object=None, blueprints=None):
"""Application factory.
Explained in greater detail here:
http://flask.pocoo.org/docs/patterns/appfactories/
"""
if blueprints is None:
blueprints = DEFAULT_BLUEPRINTS
app = Flask(__name__, template_folder="browser/templates",
... | 08454fab61996ddd13787fdce42c5341528462ea | 60,254 |
def metropolis(initial_theta,proposal_params,lnpdf,pdf_params,symmetric=False,
sample_proposal=sample_gaussian_proposal,
eval_ln_proposal=eval_ln_gaussian_proposal,
nsamples=1,randomize_directions=True,callback=None):
"""
NAME:
metropolis
PURPOSE:
m... | 96020af6c906a7cd68e615340a1d540514f25e42 | 60,255 |
def get_payment_plans():
"""
Returns all financial payment plans.
:returns: String containing xml or an lxml element.
"""
return get_anonymous('getPaymentPlans') | 88651000305fc023bb3b82dc20124f8a30720b05 | 60,256 |
import torch
def get_model(args: dict, device: torch.device, save=False):
"""
Returns a PyTorch Neural Net with specifications found in <args> and
attached to the <device>. If <save> is True, saves the model locally with
filename <args.save_as>.
:param args: Dictionary of training specifications ... | 007bf195eef3edda485afcd4e1ce81b61d2afc9d | 60,257 |
def array_equal(a1, a2):
"""
True if two arrays have the same shape and elements, False otherwise.
Parameters
----------
a1, a2 : array_like
Input arrays.
Returns
-------
b : bool
Returns True if the arrays are equal.
See Also
--------
allclose: Returns Tru... | 018f3d3899f30efed2bca52dec7c63e6187140ba | 60,258 |
import re
def parse_define(line):
"""Check if the specified line contains an #define directive"""
pattern = r'#(?:\s)*define\s*([\w_]+)(?:\s)*["\']?(.*)["\']'
match = re.match(pattern, line, re.IGNORECASE)
if match:
return (match.group(1), match.group(2)) | 5fc15e792e1f457c7466d9ff0a97241cbdf0873f | 60,259 |
def _save_v3(
*,
dataset: tf.data.Dataset,
tfdata_path: str,
num_shards: int,
):
"""
tfdata saver v3.
This implementation is identical to tfdata saver v2
because the backwards-compatible changes are on the
loading side.
"""
return _save_v2(dataset=dataset, tfdata_path=tfdata... | 3ca99f11e6c5e5b3336b3b0a04c988cd646ee7cf | 60,261 |
import warnings
def srtm(lon, lat):
"""
Return (elevation, crs, extent) for the given longitude latitude.
Elevation is in meters.
"""
warnings.warn("This method has been deprecated. "
"See the \"What's new\" section for v0.12.",
DeprecationWarning,
... | d8a457f338d26424f9be13fb0db2d59d8ff0558d | 60,262 |
from re import T
def get_training_pair_images(file, centre_fraction, acceleration):
"""
:param file: The training image
:param centre_fraction: randomly generated centre fraction
:param acceleration: randomly generated
:return: true gold standard and the fft of the masked k-space image
"""
... | a10b05fa5b38e877334402d2e5aace7488913e56 | 60,264 |
def pileupCorrespondences(bam, bamId, referenceLength, includeSoftClipped,
progress):
"""
Get bases for offsets that correspond to the reference using pysam's
pileup funciton.
@param bam: An open BAM file.
@param bamId: A C{str} reference name indicating which reference to... | b8cea33636f6b0862ee4987deda1c86f80caa313 | 60,266 |
def create_small_test_odml():
"""
creates a small odml-document with only one section, property and value
"""
doc = odml.Document()
doc.append(odml.Section(name='section1'))
parent = doc['section1']
parent.append(odml.Property(name='property1',
values='bla... | 94172c9dcda913e45887c2a106161ce386c9bc5c | 60,267 |
def format_iter(body: list) -> str:
"""
Formats an iterable into a multi-line bulleted string of its values.
"""
return "\n".join(sorted([f" - {getattr(v, 'value', v)}" for v in body])) | 0f55b06276c45ef652e89df3dfd24d1fe9a4e844 | 60,268 |
def confidence_interval_std(std, num, confidence=0.95):
""" calculates the confidence interval of the standard deviation given a
standard deviation and a number of observations, assuming a normal
distribution """
c = stats.chi(num - 1).ppf(0.5 + 0.5*confidence)
lower_bound = np.sqrt(num - 1)*std/c
... | 7b0f101095a7c5166d9c8ba7817d76359501afa6 | 60,269 |
def btc_to_sats(value_btc: Bitcoin) -> Satoshi:
"""Converts BTC to Sats.
Args:
value_btc: The value in BTC.
Returns:
The value in Sats.
"""
return value_btc * Decimal(1e8) | 61cc55cc8f88b550e20affde667cb8669b26af95 | 60,270 |
def isolate_area_interval(df_loc: pd.DataFrame, loc_col: str, loc_name: str,
start_date: str, end_date: str) -> pd.DataFrame:
"""Quickly isolate an area or region of intrest within a given timeframe.
Args:
df_loc: The timeseries DataFrame with location identifiers and cases.
... | c1325686c4b12f411df408552022c549db3dfb8d | 60,271 |
def cert_chain_url_valid(cert_url):
"""
Ensure that the provided URL for the certificate chain is valid, by checking that:
* it's HTTPS
* the host is s3.amazonaws.com
* the port, if specified, is 443
* the path starts with '/echo.api/'
"""
normalized = url_normalize(cert_url)
parsed ... | 1d9e58d9c66c6fc8fb6d797f1cebdcd1ba95cab5 | 60,272 |
import scipy
def null_space(A: tn.Tensor) -> tn.Tensor:
"""
Returns the null space of the matrix A.
Args:
A: The tensor.
pivot_axis: Where to matricize.
Returns:
The null space, shaped as a matrix.
"""
if A.backend.name == "numpy":
N_arr = scipy.linalg.null_space(A.array)
elif A.backend.... | a466dc21117a9ae24699b528229c30e15621aca3 | 60,273 |
from mirp.imageFilters.waveletFilter import WaveletFilter
from mirp.imageFilters.laplacianOfGaussian import LaplacianOfGaussianFilter
from mirp.imageFilters.lawsFilter import LawsFilter
from mirp.imageFilters.meanFilter import MeanFilter
def transform_images(img_obj, roi_list, settings, compute_features=False, extrac... | ec7ca8a444662d1abf617c4eed5c44c7b99e3275 | 60,275 |
def preprocess_t5_data(dataset,
training,
n_devices,
dynamic_batching = False,
pack_examples = True,
shuffle_buffer_size = 1024,
max_length = 512,
batch_size =... | 908bfdb87bfb60f7c8647ebd8da3fa8285257ef9 | 60,276 |
def get_number_greenbonds_with_year():
"""calculates the nb of green bonds the ECB invested in per year"""
EIKON_greenbonds = readEikonData.eikon_data_environment[["ISIN", "Green Bond Flag"]]
EIKON_greenbonds= EIKON_greenbonds.rename(columns={'Green Bond Flag' : 'Green_Bond_Flag'})
EIKON_greenbonds = E... | c5e600489dac2597c3e5859ceefeeb783b4d61a2 | 60,277 |
def processMK1(a_np,b_np):
""" Wrapper method that calls the various methods to create the merged map.
:param a_np: Contains the map values, from one of the bigger maps, usualy Gmapping.
:type a_np: Float matrix.
:param b_np: Contains the map values, from the smaller map, usualy Karto.
:type b_np: Float matrix.
... | 38361c2bff0f328db4f24dbb22c4dc72b167d93c | 60,279 |
import functools
def model_inference_fn(features, training):
"""Builds just the inference part of the model graph.
Args:
features: input features tensor.
training: True if the model is training.
Returns:
(policy_output, value_output, logits) tuple of tensors.
"""
my_batc... | f54560157574628193ac943366bcb0603543e94a | 60,280 |
def ln_gx(w,S,X_i,x, kernel_type='Gaussian'):
"""logarithm of gradient of Kernel density function fx(w,S,X_i,x, kernel_type='Gaussian')
∇_f(x)=g(x)/f(x)
inputs
w: A python list which consists of weights of each kernel(weights should be floats)
S: A python list which consists of coverian... | d1b8fb946d0830feabbf3a1701870b2998af5e56 | 60,282 |
def route_list_public_auctions():
"""
Returns list of public auctions
"""
skip = int_or_default(request.args.get("skip"), 0)
limit = int_or_default(request.args.get("limit"), 20)
(auctions, total) = get_public_auctions(skip, limit)
response = {
"auctions": [convert_auction(a) for a... | e786a3001a9681d214a581861708b2f56786a2c2 | 60,283 |
def _Modify(resources, args, url_map, url_map_ref, backend_bucket_arg,
backend_service_arg):
"""Returns a modified URL map message."""
replacement = encoding.CopyProtoMessage(url_map)
if args.default_service:
default_backend_uri = url_maps_utils.ResolveUrlMapDefaultService(
args, backend_... | 38c59b9e5daa05fd60d8a637633e96403e11286f | 60,284 |
def copy_page_content(original_content):
"""Copy the PageContent object and deepcopy its
placeholders and plugins.
"""
# Copy content object
content_fields = {
field.name: getattr(original_content, field.name)
for field in PageContent._meta.fields
# Don't copy the pk as we're... | 704ede2e6e6965d57048fd09cd5341fc61732926 | 60,285 |
def backward_softmax(x, grad_outputs):
"""
Compute the gradient of the loss with respect to x.
grad_outputs is the gradient of the loss with respect to the outputs of the softmax.
Args:
x: A 1d numpy float array of shape number_of_classes
grad_outputs: A 1d numpy float array of shape n... | ca4a7d11e060357d083391e3a023f51e13162340 | 60,286 |
from pathlib import Path
def calcpath(paths,streams):
"""calcpath(paths, streams)
Takes an initial iterable of paths and an in-order iterable of jetstreams to add, and returns whatever finalminimum() returns.
Which is a tuple of the lowest-cost path and the final cost over that path.
Function signat... | 961ebbb1598b09ad4f9d2fd7c694933f21b517d1 | 60,287 |
from pathlib import Path
from re import T
def frame3d_curv(file: Path, var: set[str], xg: dict[str, T.Any] = None) -> xarray.Dataset:
"""
curvilinear
Parameters
----------
file: pathlib.Path
filename to read
var: set of str
variable(s) to read
"""
if isinstance(var, ... | 50ff85b8f914755ab38d5be04fc7803372c61d46 | 60,288 |
import json
def request_token(auth_code, code_verifier):
"""Uses authorization code to request tokens."""
request_args = {
'code': auth_code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'grant_type': 'authorization_code',
'code_verifie... | 9cf962486d6d6f670575ab0b1c98df373541d78a | 60,289 |
from typing import List
def lang_codes_to_one_hot(data: List[str], wili_codes: List[str]) -> np.ndarray:
"""
Convert an iterable of ISO 369-3 codes to a one-hot array.
Parameters
----------
data : List[str]
Each str is a WiLI language code
wili_codes : List[str]
List of WiLi l... | 465e2eb5756e718aae7241e782330838dd109712 | 60,290 |
import warnings
def availability_summary_plots(power_system, power_subsystem, loss_total,
energy_cumulative, energy_expected_rescaled,
outage_info):
"""
Create a figure summarizing the availability analysis results.
Because all of the paramete... | bf32ed3377e8aba847960f9a5c0fe53aef6a5efd | 60,292 |
def lwrap(s, width=64):
"""
Wrap a C-prototype like string into a number of lines.
"""
ll = []
p = ""
while len(s) > width:
y = s[:width].rfind(',')
if y == -1:
y = s[:width].rfind('(')
if y == -1:
break
ll.append(p + s[:y + 1])
s =... | 9e01a1b956f37a648ff507ce65a2f6844844d28d | 60,293 |
def get_button(text: str, *callback_postfixes) -> InlineKeyboardButton:
"""
Generates an InlineKeyboardButton with given text and callback contents
:param text: Text of button
:param callback_postfixes: collection of strings which'll form a dash(`-`) separated callback data
:return:
"""
retu... | c3349dfa614d047c26aad5c9dbed341a6de963f2 | 60,294 |
def dmtx_light(frametimes, paradigm=None, hrf_model='canonical',
drift_model='cosine', hfcut=128, drift_order=1, fir_delays=[0],
add_regs=None, add_reg_names=None, min_onset=-24, path=None):
"""Make a design matrix while avoiding framework
Parameters
----------
see make_dm... | 3dd4ce78a50c40ae1ef4e8c2a6e2c3027c7d6368 | 60,296 |
def NominalLink(ratio='canonical', **kwargs):
"""
"""
return _ratio(ratio, dict(canonical = NominalCanonicalLink,
reference = ReferenceLink), **kwargs) | 85b60b8ce796e466f66b07e2a187863ef289591f | 60,297 |
def subquery(alias, *args, **kwargs):
"""Return an :class:`.Alias` object derived
from a :class:`.Select`.
name
alias name
\*args, \**kwargs
all other arguments are delivered to the
:func:`select` function.
"""
return Select(*args, **kwargs).alias(alias) | d03bf955301286329461df9c44cc009d637dc41f | 60,298 |
from typing import List
def include_model(func=None, *, operations: List[str] = None, fields: List[str] = None):
"""
Decorator used for including specific models, despite potentially being ignored
by the exclusion preferences set in the configuration.
:param func: function to be decorated
:param ... | ac0ce5be6f851b38084b802230f743a1e65a43ff | 60,299 |
def col2im(input, kernel_size, stride, padding):
"""Converts columns back to NCHW format.
This is used in backward wrt inputs in GEMM-based convolution.
"""
return Col2Im(kernel_size, stride, padding)(input) | 4980fbcb4e8a6fed1f355cb27efe27f856504b13 | 60,300 |
import collections
def _create_p13n_fn_dict(learning_rate):
"""Creates a dictionary containing two personalization strategies."""
p13n_fn_dict = collections.OrderedDict()
opt_fn = lambda: tf.keras.optimizers.SGD(learning_rate=learning_rate)
# The two personalization strategies use different training batch si... | 1127d172e08654af35fe2dfeee47c22aec328494 | 60,301 |
def _es_documents_for(locale, topics=None, products=None):
"""ES implementation of documents_for."""
s = (Document.search()
.values_dict('id', 'document_title', 'url', 'document_parent_id',
'document_summary')
.filter(document_locale=locale, document_is_archived=False,
... | a4ff9a6cddcf25174ff2ec88e5154b426acc16c4 | 60,302 |
from typing import Dict
def output(jobId : str = '', **params) -> Dict:
"""
Displays results for a job in the current Azure Quantum workspace.
See https://docs.microsoft.com/qsharp/api/iqsharp-magic/azure.output for more details.
"""
result = qsharp.client._execute_magic(f"azure.output {jobId}", r... | f8f5c3235c09ce94dfb6f593485a164ce802c51b | 60,303 |
import torch
def calc_displacement(displacement, n_iter = 1000):
"""
Calculates the displacement estimate given the displacement matrix (decentralized registration)
"""
p = torch.zeros(displacement.shape[0]).cuda()
displacement = torch.from_numpy(displacement).cuda().float()
n_batch = displac... | bbaa51463b0a9f606a2c179ef48f07e244cc772c | 60,304 |
import time
def monitor_inference_service(name: str):
"""Waits for an InferenceService to become ready.
An InferenceService is considered ready when two conditions are met:
1. the ``status.conditions`` field of the CR contains a condition of
type ``Ready`` with a ``True`` status.
2. The... | 0a101a14fb31ecea0162c5b82faf747aec635725 | 60,305 |
def explained_var(y_true, y_pred):
"""
Custom metric for Keras, explained variance.
"""
return 1 - K.mean((y_true - y_pred) ** 2) / K.var(y_true) | 529cbf7665ab4aa996ff534111005e28859443c6 | 60,306 |
def is_registered(label):
"""
Checks whether a specific label has already been registered.
Args:
label (str): Label to check for.
Return:
bool: True if registered, False if not.
"""
if not isinstance(label, (str, bytes)):
raise TypeError("Only strings allowed as labels!")
... | c6c7d76791f77bc77bebe0f29fbc24a0d898f678 | 60,307 |
def load_saved_json(concepts_file):
"""
Read a saved termset as a JSON to format it as a dataframe.
"""
df = pd.read_json(concepts_file, orient="index")
df = df.reset_index().rename(columns={"index": "concept"})
df = df.melt(id_vars=["concept"], value_vars=df.columns[1:], value_name="term")
... | 96157391f5d9ccf39dfb3905e235e211012201aa | 60,308 |
import zlib
def deflate_encode(data, level=6, raw=False, out=None):
"""Compress Deflate/Zlib."""
if raw:
raise NotImplementedError
return zlib.compress(data, level) | 2b7b369c4d2e837dfcab00a1dfa60f6f0ef8775a | 60,309 |
def _component_display_name(
component_type: StackComponentType, plural: bool = False
) -> str:
"""Human-readable name for a stack component."""
name = component_type.plural if plural else component_type.value
return name.replace("_", " ") | 1c4f137b9efadb4b516d99e99d25b53680bd1f90 | 60,310 |
def build_add_user_to_group_request(
hub, # type: str
group, # type: str
user_id, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Add a user to the target group.
Add a user to the target group.
See https://aka.ms/azsdk/python/llcwiki for how to incorporate this ... | 32ed15fd35f84bb3af830496f60b22bcc99de331 | 60,312 |
import click
def n_protocols_option(required=True, **kwargs):
"""Get option for number of protocols."""
def custom_n_protocols_option(func):
def callback(ctx, param, value):
value = abs(value)
ctx.meta["protocols_number"] = value
return value
return click.... | bcdd204ea9b9cd7d09e159ba45ea54b349c648b6 | 60,313 |
def copy_fields(model):
"""
Creates copies of the model's original fields, returning
a dictionary mapping field name to copied field object.
"""
fields = {
PK: AutoField(verbose_name=PK,
primary_key=True,
auto_created=True),
CU: create_user... | e13a76099f80559e3047cdf16535b907b5d5ae3e | 60,314 |
def fibonacci(number: int) -> int:
"""Returns fibonacci number.
Args:
number: number to count fibonacci sequence
"""
counter, handler = 1, 1
for next_number in range(number - 1): # type: int
counter, handler = handler, counter + handler
return counter | 88931af6f1d22ea4d01fe77a46eaec504eff9020 | 60,315 |
def next_bound_var(bound_vars, type):
"""
Helper function: generate the next bound variable in a context where there
are currently the bound variables `bound_vars` (assumed to be generated by
this function).
"""
name_length = 1 + len(bound_vars) // 26
name_id = len(bound_vars) % 26
name = chr(97 + name_... | bd9a6027ecce2b2ea1e7980a72ed8768ab465c0f | 60,316 |
def _estimate_covar(cweights, proppts, mean, covmat):
"""See BFaS; p. 88.
Parameters
----------
cweights: np.ndarray, shape (2*dimension + 1,)
Constant kernels weights for unscented transform.
proppts: np.ndarray, shape (2*dimension + 1, dimension)
Propagated sigma points
mean: ... | 514d892c25bac16853e98c31d4b47ab20d99800f | 60,317 |
def profile(request, username):
"""Возвращение информации об авторе и его постов"""
user = get_object_or_404(User, username=username)
post_list = user.posts.all()
paginator = Paginator(post_list, 10)
page_number = request.GET.get('page')
page = paginator.get_page(page_number)
return render(... | 84fd19e3d80a3f13bdac749c8e8bc3835daae038 | 60,318 |
from typing import List
from typing import Tuple
def update_comment_segments(comment_segments: List[Tuple[int, int]], pos: int, offset: int) -> List[Tuple[int, int]]:
"""
Update comment segments with an offset
"""
new_comment_segments = []
for begin, end in comment_segments:
if end >= pos... | 79a1d748b2672f675b85e2fb180645bf99e269c3 | 60,319 |
from operator import add
def identity_block(input_tensor, kernel_size, filters, stage, block):
"""The identity block is the block that has no conv layer at shortcut.
# Arguments
input_tensor: input tensor
kernel_size: default 3, the kernel size of
middle conv layer at main path
... | b0831023dff5cbe895f193fcc161b70612336800 | 60,320 |
def gyromagnetic_ratio(elem="mu", iso=None):
"""Return the gyromagnetic ratio of a given particle
Return the gyromagnetic ratio of either an atomic nucleus,
an electron or a muon. The value returned is in MHz/T. It
corresponds to a frequency, not a pulsation (so it's gamma,
not gammabar = 2*pi*gamm... | 89e241c26cd295e3dc4d4e7883f15b3c10728179 | 60,322 |
def load_trace(logfile, root_dir, api, blacklist):
"""Loads a trace file and returns the Results instance.
Arguments:
- logfile: File to load.
- root_dir: Root directory to use to determine if a file is relevant to the
trace or not.
- api: A tracing api instance.
- blacklist: Optional blackli... | e51ad3e61ee4206e74800f1c24b14fd20f51e477 | 60,323 |
def geez_alpha(s1, s2, pos1 = 0, pos2 = 0):
"""Comparator function for two strings or lists using Geez order."""
if s1 == s2:
return 0
elif pos1 >= len(s1):
return -1
elif pos2 >= len(s2):
return 1
else:
seg1 = s1[pos1]
seg2 = s2[pos2]
if seg1 == seg2:... | 0d713f8438c72c4471f621c296472e0fff0d8f05 | 60,324 |
def mean(series):
"""
"""
avg = 0
for i in series:
avg += i
avg /= len(series)
return avg | 3795938f0cb3ebe3d1d1fed7b90980e2fd02690b | 60,326 |
def user_sign_up(request):
"""User Sign up view"""
if request.method == 'GET': # open sign up page
return render(request, 'image_repo/user_sign_up.html', {'form': UserCreationForm()})
else:
# create a new user with a built-in model
if request.POST.get('password1') == request.POST.ge... | 9d88d378fc211b86158e0acc49841f5341958fce | 60,327 |
def Endnote_text_split(f):
"""Parse the EndNote output in Text format
split into records
"""
records = []
blocks = []
with open(f, 'rt') as fi:
for line in fi:
line = line.strip()
if line.startswith('#') or not line:
continue # skip '#' and blank l... | 2aa63e222d23a3827828cf838dbc96dd60fb5f3e | 60,328 |
def get_evidence_fields_for_variant(genome_build: GenomeBuild, variant: Variant,
refseq_transcript_accession, ensembl_transcript_accession,
evidence_keys_list: list, annotation_version: AnnotationVersion) -> AutopopulateData:
""" annotation_ver... | 0125e2a2575aee968eb20cf5802f7ecc16a20fd7 | 60,329 |
def from_csv(*args, **kwargs):
"""Read from csv."""
gen = kwargs.pop("gen", True)
iterator = _csv_gen(*args, **kwargs)
return iterator if gen else _fix_and_split(iterator) | 64878e468fe3945f0d7c32281365cd1f9c30a235 | 60,330 |
def sendMail(weekday):
"""This is a page which cron job requests to send an email.
If 'today' is defined in config.ini, and call was made from cron,
get the current forecast and send an email. Otherwise redirect.
Args:
weekday from url
Returns:
A message content of the email or redirection to Google
... | 828dd2334b149a98e12e16876ccb12ee7e98383f | 60,333 |
def splitUIAElementAttribs(attribsString):
"""Split an UIA Element attributes string into a dict of attribute keys and values.
An invalid attributes string does not cause an error, but strange results may be returned.
@param attribsString: The UIA Element attributes string to convert.
@type attribsString: str
@ret... | db472d90b2dacdda4606b39e2e1f1d959ae056ca | 60,334 |
def get_ident():
"""
Return a unique number for the current greenlet in the current thread.
"""
return hash((get_current_thread(), get_current_greenlet())) | 2c6361805acc1b13921f467d3f6e6b575ed9ff70 | 60,335 |
def apply_filter_include_exclude(
filename, include_filters, exclude_filters):
"""Apply inclusion/exclusion filters to filename
The include_filters are tested against
the given (relative) filename.
The exclude_filters are tested against
the stripped, given (relative), and absolute filenames... | 12d1f56436bfbee606d5a75f8aab5ad34e930981 | 60,336 |
def gen_indx(x_locs):
"""
Return the indexes for each node to be iterated over.
Uses the x_locs array as an array to mimic.
"""
n_elem = x_locs.shape[0] * x_locs.shape[1]
indx = np.arange(n_elem).reshape(x_locs.shape[0], x_locs.shape[1])
pindx = np.zeros_like(indx)
pindx[:] = -1
ret... | dfa66fd62465f1938deb8d14c22e91aef731cd1a | 60,337 |
def getNbtestOk(results):
"""
based on default value (PASS) count the number of test OK
"""
nb_test_ok = 0
for my_result in results:
for res_k, res_v in my_result.iteritems():
try:
if "PASS" in res_v:
nb_test_ok += 1
except TypeErro... | 6cac82e138ac17b1cc70bda0d892542db6fdecf0 | 60,340 |
def format_time(start, end):
"""Format length of time between ``start`` and ``end``.
Args:
start (:class:`time.time`): The start time.
end (:class:`time.time`): The end time.
Returns:
str: A formatted string of hours, minutes, and seconds.
"""
hours, rem = divmod(end - sta... | 5650fe13f51821056b2e0be3be04ddcfa35bb1c6 | 60,341 |
import scipy
def calc_fft(feature_vec, smooth = False):
"""
takes in feature vector, splits it into its 3 components, and does the fft of each
returns magnitude of fft for each component
"""
# separate components
xline = feature_vec[0::3]
yline = feature_vec[1::3]
zline = feature_vec[... | d30433a0758dbdee590b89edf8a9851c94a915e2 | 60,342 |
def suggest_box():
"""Custom commands.guild_only with different error checking."""
def pred(ctx):
if ctx.guild is None:
raise UnavailableTagCommand()
return True
return commands.check(pred) | 5772fd7c279f844644eebc40cb7270269863719a | 60,343 |
def shadow_model():
"""The architecture of the shadow model is same as target model, because the attack is white-box,
hence the attacker is assumed to know this architecture too.
:return: shadow model
"""
classifier = Sequential()
classifier.add(Conv1D(num_kernels,
ke... | 17b0d6df8046a1cda0e85c84d29102af019b8e72 | 60,344 |
def retrieve_runinfo(sra_accession):
"""Retrieve a SRA runinfo using search and efetch utilities"""
esearch_proc = Popen(['esearch', '-db', 'sra', '-query', sra_accession], stdout=PIPE)
runinfo_data = check_output(['efetch', '-format', 'runinfo'], universal_newlines=True, stdin=esearch_proc.stdout)
if n... | e57bb46ec4a969d9c03901ad321fcd1b3b388957 | 60,347 |
def fetch_all_metadata(client):
"""Fetches all the files.
Args:
client: Authorized drive api client.
Returns:
"""
results = []
page = ended = None
while not ended:
resp = client.files().list(pageToken=page, maxResults=100,
q='trashed=false',
fields='nextPageToken,items(id,md5Check... | 11fff0cbaa3ceecb57aa7ebefaaf7a52811fa9c4 | 60,348 |
from typing import Optional
from typing import Iterable
from typing import List
def extract_bounding_boxes(
diff_image: np.ndarray,
page_number: int,
hue: float,
masks: Optional[Iterable[FloatRectangle]] = None,
) -> List[BoundingBox]:
"""
See 'PixelMerger' for description of how bounding boxe... | fc3f95d56019a52ea44d2bb3594f69151dbbf996 | 60,349 |
def size(current):
"""Fuzz image size header field."""
constraints = UINT64_V
return selector(current, constraints) | b6ed4c5da118e1f2a74cab0dd8012c96ed6a9779 | 60,350 |
import torch
import torchvision
def _adjust_brightness(video: torch.Tensor, factor: float, **kwargs) -> torch.Tensor:
"""
Adjust brightness of a video.
Args:
video (torch.Tensor): Video tensor with shape (T, C, H, W).
sharpness_factor (float): How much to adjust the sharpness. Can be any
... | 9234167077968c1e36ee799eeb0c5918aacb32c7 | 60,351 |
def get_stationary_distribution(f_rate, f_noise, x_view, x_points, iters=100):
"""
Get the stationary distribution with a particular rate and noise function.
:param f_rate f(x): rate function
:param f_noise f(x): density function of noise (integral 1)
:param x_view (float, float): range of paramete... | 079489c0fd25440fac02526bcd586eb912a445f4 | 60,352 |
def getHostWhiteboard():
"""
:rtype: list<Host>
:return: NestedHost """
nestedHostSeq = Cuebot.getStub('host').GetHostWhiteboard(
host_pb2.HostGetHostWhiteboardRequest(),
timeout=Cuebot.Timeout).nested_hosts
return [NestedHost(nh) for nh in nestedHostSeq.nested_hosts] | c294c1378e2fb225825d91fff53d366a89bdff3f | 60,353 |
def keep_login_url(func):
"""
Adds attribute g.keep_login_url in order to pass the current
login URL to login/signup links.
"""
@wraps(func)
def wrapper(*args, **kwargs):
g.keep_login_url = True
return func(*args, **kwargs)
return wrapper | 1d785680846cfe2272d3ec6803d5c2434d44a21c | 60,355 |
from typing import Tuple
from typing import Sequence
import builtins
def builtin_lookup(name: str) -> Tuple["nodes.Module", Sequence["nodes.NodeNG"]]:
"""Lookup a name in the builtin module.
Return the list of matching statements and the ast for the builtin module
"""
# pylint: disable-next=global-st... | 2caf57dc6d3d335d2b59e9740df0d243d6a7edd2 | 60,356 |
def toggle_article_hidden():
"""
Method POST
Form:
- aid int
- hidden bool
"""
aid = get_int_field('aid')
hidden = get_bool_field('hidden')
a = Article.query.get(aid)
if a is None:
raise RequestArgumentError("Article %d is not found" % aid)
if a.h... | 2fa58070625ba1aef96249e45d6f5cf05010d2f3 | 60,357 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.