content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
def disconnect() -> Tuple[str, int]:
"""Deletes the DroneServerThread with a given id.
Iterates over all the drones in the shared list and deletes the one with a
matching drone_id. If none are found returns an error.
Request:
drone_id (str): UUID of the drone.
R... | c69192ccdc73c27089952d3a27c3ff79dfb932a5 | 3,639,948 |
import torch
def get_graph_feature(x, k=20, idx=None, x_coord=None):
"""
Args:
x: (B, d, N)
"""
batch_size = x.size(0)
num_points = x.size(2)
x = x.view(batch_size, -1, num_points)
if idx is None:
if x_coord is None: # dynamic knn graph
idx = knn(x, k=k)
... | e895a1663fb716846af0976a3203045509591a6e | 3,639,949 |
def get_markers(
image_array: np.ndarray,
evened_selem_size: int = 4,
markers_contrast_times: float = 15,
markers_sd: float = 0.25,
) -> np.ndarray:
"""Finds the highest and lowest grey scale values for image flooding."""
selem = smo.disk(evened_selem_size)
evened = sfi.rank.mean_bilateral(
... | 865d2f5170b85a54902aabdfaee61199359e7d90 | 3,639,950 |
def pd_bigdata_read_csv(file, **pd_read_csv_params):
"""
读取速度提升不明显
但是内存占用显著下降
"""
reader = pd.read_csv(file, **pd_read_csv_params, iterator=True)
loop = True
try:
chunk_size = pd_read_csv_params['chunksize']
except:
chunk_size = 1000000
chunks = []
while loop:
... | 0350e543bc10da5165b97b18c83d6f848cbbc503 | 3,639,951 |
import numpy
def PCA(Y_name, input_dim):
"""
Principal component analysis: maximum likelihood solution by SVD
Adapted from GPy.util.linalg
Arguments
---------
:param Y: NxD np.array of data
:param input_dim: int, dimension of projection
Returns
-------
:rval X: - Nxinput_dim np.array of dimensionality redu... | 0d49a1c8470cba2d6d56a4ce191449b3106e8a93 | 3,639,952 |
import collections
def _get_sequence(value, n, channel_index, name):
"""Formats a value input for gen_nn_ops."""
# Performance is fast-pathed for common cases:
# `None`, `list`, `tuple` and `int`.
if value is None:
return [1] * (n + 2)
# Always convert `value` to a `list`.
if isinstance(value, list):... | e2ac408cf299f186bb74fa4b1decc885b1229f9d | 3,639,954 |
def make_linear(input_dim, output_dim, bias=True, std=0.02):
"""
Parameters
----------
input_dim: int
output_dim: int
bias: bool
std: float
Returns
-------
torch.nn.modules.linear.Linear
"""
linear = nn.Linear(input_dim, output_dim, bias)
init.normal_(linear.weight, ... | 57361cadbf3121501da65c3f2f37e61404bc26e3 | 3,639,955 |
def matnorm_logp_conditional_col(x, row_cov, col_cov, cond, cond_cov):
"""
Log likelihood for centered conditional matrix-variate normal density.
Consider the following partitioned matrix-normal density:
.. math::
\\begin{bmatrix}
\\operatorname{vec}\\left[\\mathbf{X}_{i j}\\right] \\\... | 0970ba5a2f67a6156a6077dbd05e2d1cca331476 | 3,639,956 |
def get_next_by_date(name, regexp):
"""Get the next page by page publishing date"""
p = Page.get(Page.name == name)
query = (Page.select(Page.name, Page.title)
.where(Page.pubtime > p.pubtime)
.order_by(Page.pubtime.asc())
.dicts())
for p in ifilter(lambda x: regexp.m... | 16e956508c1ccbdf444e84ad769848124449ab84 | 3,639,958 |
def generate_raw_mantissa_extraction(optree):
""" generate an operation graph to extraction the significand field
of floating-point node <optree> (may be scalar or vector).
The implicit bit is not injected in this raw version """
if optree.precision.is_vector_format():
base_precision = o... | f1f0b38f0c68e997ade20ead827f71427104d138 | 3,639,960 |
import time
def read_temp_f(p):
"""
read_temp_f
Returns the temperature from the probe in degrees farenheit
p = 1-Wire device file
"""
lines = read_temp_raw(p)
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw(p)
equals_pos = lines[1].find... | 52114550688f06c8f58dfe37f7c0faa4d93715a2 | 3,639,961 |
def count_parameters(model, trainable_only=True, is_dict=False):
"""
Count number of parameters in a model or state dictionary
:param model:
:param trainable_only:
:param is_dict:
:return:
"""
if is_dict:
return sum(np.prod(list(model[k].size())) for k in model)
if trainable_... | 8e95c3302eca217c694bb4c5262c0196254505fb | 3,639,962 |
def setup_conf(conf=cfg.CONF):
"""Setup the cfg for the status check utility.
Use separate setup_conf for the utility because there are many options
from the main config that do not apply during checks.
"""
common_config.register_common_config_options()
neutron_conf_base.register_core_common_co... | c5ebcc4516e317fc558d8bddeb74343b7006c999 | 3,639,963 |
import pathlib
def release_kind():
"""
Determine which release to make based on the files in the
changelog.
"""
# use min here as 'major' < 'minor' < 'patch'
return min(
'major' if 'breaking' in file.name else
'minor' if 'change' in file.name else
'patch'
for fi... | 115f75c1e0f1e8b02916db518e3983462d9bc19c | 3,639,964 |
import re
def edit_text_file(filepath: str, regex_search_string: str, replace_string: str):
"""
This function is used to replace text inside a file.
:param filepath: the path where the file is located.
:param regex_search_string: string used in the regular expression to find what has to be replaced.
... | e0f5945a96f755a9c289262c3d19552c0e1b40fd | 3,639,965 |
def find_sums(sheet):
"""
Tallies the total assets and total liabilities for each person.
RETURNS:
Tuple of assets and liabilities.
"""
pos = 0
neg = 0
for row in sheet:
if row[-1] > 0:
pos += row[-1]
else:
neg += row[-1]
return pos, neg | 351e13d6915288268a56d8292c470fe354fa9842 | 3,639,966 |
def read_links(title):
"""
Reads the links from a file in directory link_data.
Assumes the file exists, as well as the directory link_data
Args:
title: (Str) The title of the current wiki file to read
Returns a list of all the links in the wiki article with the name title
"""
with... | 50f128bcf4cd36bc783bc848ab2e6b6280973ea3 | 3,639,967 |
def test_compile_model_from_params():
"""Tests that if build_fn returns an un-compiled model,
the __init__ parameters will be used to compile it
and that if build_fn returns a compiled model
it is not re-compiled.
"""
# Load data
data = load_boston()
X, y = data.data[:100], data.target[:... | a4cbc7b4dbc4d9836766c37d8eb1cfdd3d5c324e | 3,639,968 |
import numpy
def writeFEvalsMaxSymbols(fevals, maxsymbols, isscientific=False):
"""Return the smallest string representation of a number.
This method is only concerned with the maximum number of significant
digits.
Two alternatives:
1) modified scientific notation (without the trailing + and ze... | a5434c5f6e845473f2187b969e4fa42538a95633 | 3,639,969 |
def closedcone(r=1, h=5, bp=[0,0,0], sampH=360, sampV=50, fcirc=20):
"""
Returns parametrization of a closed cone with radius 'r' and height 'h at
basepoint (bpx,bpy,bpz), where 'sampH' and 'sampV' specify the amount of
samples used horizontally, i.e. for circles, and vertically, i.e.
for height,... | 8cbf46f0a626d8cc858bab004a21dd9eb189a3eb | 3,639,970 |
def E_lndetW_Wishart(nu,V):
"""
mean of log determinant of precision matrix over Wishart <lndet(W)>
input
nu [float] : dof parameter of Wichart distribution
V [ndarray, shape (D x D)] : base matrix of Wishart distribution
"""
if nu < len(V) + 1:
raise ValueError, "dof parameter n... | 1fa84eb843c91b66b3937b7542be31c00faf002d | 3,639,971 |
def crop_range_image(range_images, new_width, shift=None, scope=None):
"""Crops range image by shrinking the width.
Requires: new_width is smaller than the existing width.
Args:
range_images: [B, H, W, ...]
new_width: an integer.
shift: a list of integer of same size as batch that shifts the crop wi... | 364dc2e1e77052327e3517fb35c0223463179a69 | 3,639,972 |
import string
import random
def randomString(length):
"""Generates a random string of LENGTH length."""
chars = string.letters + string.digits
s = ""
for i in random.sample(chars, length):
s += i
return s | fff13713271b3064b4e42c42c420aad190475d85 | 3,639,973 |
def DrawMACCloseButton(colour, backColour=None):
"""
Draws the wxMAC tab close button using wx.GraphicsContext.
:param `colour`: the colour to use to draw the circle.
"""
bmp = wx.EmptyBitmapRGBA(16, 16)
dc = wx.MemoryDC()
dc.SelectObject(bmp)
gc = wx.GraphicsContext.Create(dc)
... | 96982b68aa926341d7ab74d7ed705c19c232392e | 3,639,974 |
def dispatch(args, validator):
"""
'dispath' set in the 'validator' object the level of validation
chosen by the user. By default, the validator
makes topology level validation.
"""
print("Printing all the arguments: {}\n".format(args))
if args.vnfd:
print("VNFD validati... | b2625b5cb46295d0790b37fa691b8a4d60341e47 | 3,639,975 |
def create_app():
"""Create and configure and instance of the Flask application"""
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
DB.init_app(app)
@app.route('/')
def home():
return ren... | 1e122846bfdfc68a1143eb2d53b87eda9ae9cff6 | 3,639,976 |
def get_motif_class(motif: str) -> str:
"""Return the class of the given motif."""
for mcls in gen_motif_classes(len(motif), len(motif) + 1):
for m in motif_set(mcls):
if m == motif:
return mcls
else:
raise ValueError(
"Unable to find the class of the ... | fea293fcf25b77bbf78c400facf450067c94be2b | 3,639,978 |
def resnet_v1(inputs,
blocks,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
include_root_block=True,
spatial_squeeze=True,
store_non_strided_activations=False,
reuse=... | b2008da41f5ada502941c058134ded4d95c3d5c0 | 3,639,979 |
def findConstell(cc):
"""
input is one character (from rinex satellite line)
output is integer added to the satellite number
0 for GPS, 100 for Glonass, 200 for Galileo, 300 for everything else?
author: kristine larson, GFZ, April 2017
"""
if (cc == 'G' or cc == ' '):
out = 0
eli... | d7a85fc5f7324acdb5277fd6db458523cd4ad4b8 | 3,639,980 |
def Controller(idx):
"""(read-only) Full name of the i-th controller attached to this element. Ex: str = Controller(2). See NumControls to determine valid index range"""
return get_string(lib.CktElement_Get_Controller(idx)) | 5adb2f806133319546ea627c705579a3a7e662dd | 3,639,981 |
def smooth_2d_map(bin_map, n_bins=5, sigma=2, apply_median_filt=True, **kwargs):
"""
:param bin_map: map to be smooth.
array in which each cell corresponds to the value at that xy position
:param n_bins: number of smoothing bins
:param sigma: std for the gaussian smoothing
:return: sm_map: s... | a1d8c9b2b8107663746d2c1af9e129d7226e9d0b | 3,639,982 |
import socket
def _select_socket(lower_port, upper_port):
"""Create and return a socket whose port is available and adheres to the given port range, if applicable."""
sock = socket(AF_INET, SOCK_STREAM)
found_port = False
retries = 0
while not found_port:
try:
sock.bind(('0.0.0... | 19427fd0146b5537c6fab898b5e3e0868c8c4a21 | 3,639,983 |
def _factory(cls_name, parent_cls, search_nested_subclasses=False):
"""Return subclass from parent
Args:
cls_name (basestring)
parent_cls (cls)
search_nested_subclasses (bool)
Return:
cls
"""
member_cls = None
subcls_name = _filter_out_underscore(cls_name.lower())
members = (_all_subclasses(p... | 2eb5fb4c3333aaddec418ebac8ecdd824ff4e8ba | 3,639,985 |
def tabuleiro_actualiza_pontuacao(t,v):
"""list x int -> list
Esta funcao recebe um elemento tabuleiro do tipo lista e um elemento v do tipo inteiro e modifica o tabuleiro, acrescentando ao valor da pontuacao v pontos"""
if isinstance(v,int) and v%4==0 and v>=0:
t[4]=tabuleiro_pontuacao(t)+v
... | a247f2c14ffd42fc4d77ae9871ccc08bd967296d | 3,639,986 |
def showcase_code(pyfile,class_name = False, method_name = False, end_string = False):
"""shows content of py file"""
with open(pyfile) as f:
code = f.read()
if class_name:
#1. find beginning (class + <name>)
index = code.find(f'class {class_name}')
code = code[index:]
... | fe62a99adf5f97164ac69e68554f31d20e126dfa | 3,639,988 |
def get_hyperparams(data, ind):
"""
Gets the hyperparameters for hyperparameter settings index ind
data : dict
The Python data dictionary generated from running main.py
ind : int
Gets the returns of the agent trained with this hyperparameter
settings index
Returns
-----... | 3734f4cf00564a1aa7c852091d366e6e42b6d55b | 3,639,989 |
from typing import Dict
from typing import Any
from typing import Tuple
def _check_df_params_require_iter(
func_params: Dict[str, ParamAttrs],
src_df: pd.DataFrame,
func_kwargs: Dict[str, Any],
**kwargs,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""Return params that require iteration and those ... | e66a42a173f24a33f2457bf6b8cfe4124984f646 | 3,639,990 |
def _inverse_permutation(p):
"""inverse permutation p"""
n = p.size
s = np.zeros(n, dtype=np.int32)
i = np.arange(n, dtype=np.int32)
np.put(s, p, i) # s[p] = i
return s | 0e8a4cf7156c9dac6a3bb89eb3edb8960478d7b6 | 3,639,995 |
def blend0(d=0.0, u=1.0, s=1.0):
"""
blending function trapezoid
d = delta x = xabs - xdr
u = uncertainty radius of xabs estimate error
s = tuning scale factor
returns blend
"""
d = float(abs(d))
u = float(abs(u))
s = float(abs(s))
v = d - u #offset by radius
... | d501db66c34f28421c1517dcd3052fa7b2ee8643 | 3,639,996 |
def median(a, dim=None):
"""
Calculate median along a given dimension.
Parameters
----------
a: af.Array
The input array.
dim: optional: int. default: None.
The dimension for which to obtain the median from input data.
Returns
-------
output: af.Array
Array... | 0a117fe2f072747e752e77613dc658812630dacc | 3,639,997 |
from typing import Union
async def is_photo(obj: Union[Message, CallbackQuery]) -> bool:
"""
Checks if message content is photo
:return: True if so
"""
obj = await _to_message(obj)
return obj.content_type == 'photo' | 13207a44dba000ad0486997f364f011cfffa9d26 | 3,639,998 |
def check_win(mat):
"""
Returns either:
False: Game not over.
True: Game won, 2048 is found in mat
"""
if 2048 in mat: # If won, teriminal state is needed for RL agent
return True # Terminal state
else:
return False | 0824bc059cfa32b275c7b63f98d22e8a5b667e06 | 3,639,999 |
def mtl_to_json(mtl_text):
""" Convert Landsat MTL file to dictionary of metadata values """
mtl = {}
for line in mtl_text.split('\n'):
meta = line.replace('\"', "").strip().split('=')
if len(meta) > 1:
key = meta[0].strip()
item = meta[1].strip()
if key !... | 310be04e9fbf756e9cf5ead60e53aae974d2ed50 | 3,640,000 |
def endian_swap(word):
"""Given any string, swap bits and return the result.
:rtype: str
"""
return "".join([word[i:i+2] for i in [6, 4, 2, 0]]) | dfca46a012602150957a0830cf30cc6b6790df80 | 3,640,001 |
import logging
def get_grundsteuer(request_id: str):
"""
Route for retrieving job status of a grundsteuer tax declaration validation from the queue.
:param request_id: the id of the job.
"""
try:
raise NotImplementedError()
except NotImplementedError:
logging.getLogger().info("... | d92431ff1e09652d78b7beeaeabdeb2d502d0829 | 3,640,002 |
def str_to_col_grid_lists(s):
"""
Convert a string to selected columns and selected grid ranges.
Parameters:
s: (str) a string representing one solution.
For instance, *3**9 means 2 out of 5 dimensions are selected; the second and the last columns are selected,
and their co... | 4f5c67afa0dc97070b08223acbe6764010fd213a | 3,640,003 |
from typing import Union
import uuid
from typing import List
def get_installation_indices_by_installation_id(
db_session: Session, installation_id: Union[str, uuid.UUID]
) -> List[SlackIndexConfiguration]:
"""
Gets all the indices set up in an installation given on the ID of that installation.
"""
... | 0025599259a8f23e1da462d465448f3ed9a1701f | 3,640,004 |
def convert_hdf(proj_dir, dir_list, hdf_filepath_list, hdf_filename_list):
"""Converts downloaded HDF file into geotiff file format."""
global src_xres
global src_yres
geotiff_list = []
"""Converts MODIS HDF files to a geotiff format."""
print "Converting MODIS HDF files to geotiff format..."
... | f74b3e89b957746aaec9c04b4615bc5a3f7388e7 | 3,640,005 |
def _join_type_and_checksum(type_list, checksum_list):
"""
Join checksum and their correlated type together to the following format:
"checksums": [{"type":"md5", "checksum":"abcdefg}, {"type":"sha256", "checksum":"abcd12345"}]
"""
checksums = [
{
"type": c_type,
"chec... | 7f09ee72c6f51ad87d75a9b5e74ad8ef4776323f | 3,640,006 |
def _local_groupby(df_rows, axis=0):
"""Apply a groupby on this partition for the blocks sent to it.
Args:
df_rows ([pd.DataFrame]): A list of dataframes for this partition. Goes
through the Ray object store.
Returns:
A DataFrameGroupBy object from the resulting groupby.
""... | d78cd88bac7b03136bbe8401d207ee10c2d031f9 | 3,640,007 |
def colors_terrain() -> dict:
"""
Age of Empires II terrain colors for minimap.
Credit for a list of Age of Empires II terrain and player colors goes to:
https://github.com/goto-bus-stop/recanalyst.
This function has great potential for contributions from designers
and other specialists.
... | 8e8f00d689ce00203127a9d810b6017ee5a04e18 | 3,640,008 |
def _load_dataset(dataset_config, *args, num_batches=None, **kwargs):
"""
Loads a dataset from configuration file
If num_batches is None, this function will return a generator that iterates
over the entire dataset.
"""
dataset_module = import_module(dataset_config["module"])
dataset_fn = ge... | 5a35be1cac9bf405206ebc29b24aa0c08c27a18f | 3,640,010 |
def mock_checks_health(mocker: MockFixture):
"""Fixture for mocking checks.health."""
return mocker.patch("website_checker.checks.health") | aa6dff915bc1559838e46cc3e486d916a2c9f117 | 3,640,012 |
from typing import Dict
from typing import Any
def decode_jwt(
jwt_string: str
) -> Dict[Any, Any]:
""" Decodes the given JWT string without performing any verification.
Args:
jwt_string (str): A string of the JWT to decode.
Returns:
dict: A dictionary of the body of the JWT.
""... | 39b3e14a3eb63723b2a8df21d5252ea937b0a41b | 3,640,013 |
import collections
def _resolve_references(navigation, version, language):
"""
Iterates through an object (could be a dict, list, str, int, float, unicode, etc.)
and if it finds a dict with `$ref`, resolves the reference by loading it from
the respective JSON file.
"""
if isinstance(navigation... | cb955d74844a86afc4982199ec81b18899466b0e | 3,640,014 |
from typing import Optional
from typing import Union
from typing import Sequence
def phq(data: pd.DataFrame, columns: Optional[Union[Sequence[str], pd.Index]] = None) -> pd.DataFrame:
"""Compute the **Patient Health Questionnaire (Depression) – 9 items (PHQ-9)**.
The PHQ-9 is a measure for depression.
.... | 73b925b29a51b7f0575b3449b015d41d3287ca35 | 3,640,015 |
def mbc_choose_any_program(table_path):
"""
randomly select one item of MBCRadioProgramTable
:param table_path:
:return:
"""
table = playlist.MBCRadioProgramTable(table_path=table_path)
programs = list(filter(lambda x: x.playlist_slug, table.programs))
random_id = randint(0, len(programs... | 397c56f4a4d79bf3cd2ede5eba13414fcb1836ae | 3,640,016 |
def logout_view(request):
"""Logout a user."""
logout(request)
return redirect('users:login') | e14292c1fc78d8fb6f395129a1b77f141ce93627 | 3,640,017 |
def _cast(vtype, value):
"""
Cast a table type into a python native type
:param vtype: table type
:type vtype: string
:param value: value to cast
:type value: string
"""
if not vtype:
return None
if isinstance(value, str):
return_value = value.strip()
... | 27ffdb0dac7d7e5f092a798630e6b874626a27b2 | 3,640,019 |
def L2Norm(inputs, axis=0, num_axes=-1, eps=1e-5, mode='SUM', **kwargs):
"""L2 Normalization, introduced by `[Liu et.al, 2015] <https://arxiv.org/abs/1506.04579>`_.
Parameters
----------
inputs : Tensor
The input tensor.
axis : int
The start axis of stats region.
num_axes : int
... | 20c0a1677874adfbd6c24cb6f662d1c0dc6c93f1 | 3,640,020 |
from typing import Union
from typing import Sequence
import inspect
def has_option(obj, keywords: Union[str, Sequence[str]]) -> bool:
"""
Return a boolean indicating whether the given callable `obj` has the `keywords` in its signature.
"""
if not callable(obj):
return False
sig = inspect.s... | de2c6d4d458a8db6f0ff555d04570897e3440c10 | 3,640,021 |
import mmh3
import struct
def create_element_rand(element_id):
"""
This function simply returns a 32 bit hash of the element id.
The result value should be used a random priority.
:param element_id: The element unique identifier
:return: an random integer
"""
if isinstance(element_id, int... | 095ced835235bec4b042a8a8b5eb3c44e967390e | 3,640,022 |
def _ul_add_action(actions, opt, res_type, stderr):
"""Create new and append it to the actions list"""
r = _UL_RES[opt]
if r[0] is None:
_ul_unsupported_opt(opt, stderr)
return False
# we always assume the 'show' action to be requested and eventually change it later
actions.append(
... | 098492f8bd875c611650fa773fd308d1097bcd18 | 3,640,023 |
from typing import List
from typing import Any
import time
def _pack(cmd_id: int, payload: List[Any], privkey: datatypes.PrivateKey) -> bytes:
"""Create and sign a UDP message to be sent to a remote node.
See https://github.com/ethereum/devp2p/blob/master/rlpx.md#node-discovery for information on
how UDP... | 11ade65dc4ceceab509d13456845d37671b8abfb | 3,640,024 |
def clip_boxes(boxes, shape):
"""
:param boxes: (...)x4, float
:param shape: h, w
"""
orig_shape = boxes.shape
boxes = boxes.reshape([-1, 4])
h, w = shape
boxes[:, [0, 1]] = np.maximum(boxes[:, [0, 1]], 0)
boxes[:, 2] = np.minimum(boxes[:, 2], w)
boxes[:, 3] = np.minimum(boxes[:... | 60dbdb4d3aee5a4a0f7dc076ad6d8415ddc82ba0 | 3,640,025 |
def loss_fn(
models, backdoored_x, target_label, l2_factor=settings.BACKDOOR_L2_FACTOR,
):
"""loss function of backdoor model
loss_student = softmax_with_logits(teacher(backdoor(X)), target)
+ softmax_with_logits(student(backdoor(X)), target)
+ L2_norm(mask_matrix)
Args:
models(Python dict): teacher... | d13fa05f4f5ac7adbebb62a48774cfc552c3d42e | 3,640,026 |
from .models import OneTimePassword, compute_expires_at
def create_otp(slug, related_objects=None, data=None, key_generator=None, expiration=None, deactivate_old=False):
"""
Create new one time password. One time password must be identified with slug.
Args:
slug: string for OTP identification.
... | 20cbfd88b676ff0357fa5a37a51a3ffa24b4f76b | 3,640,027 |
def get_pod_from_dn(dn):
"""
This parses the pod from a dn designator. They look like this:
topology/pod-1/node-101/sys/phys-[eth1/6]/CDeqptMacsectxpkts5min
"""
pod = POD_REGEX.search(dn)
if pod:
return pod.group(1)
else:
return None | 23b790bf7b216239916ba86829bb5bee0e346a4a | 3,640,028 |
import trace
def extend_table(rows, table):
"""
appends the results of the array to the existing table by an objectid
"""
try:
dtypes = np.dtype(
[
('_ID', np.int),
('DOM_DATE', '|S48'),
('DOM_DATE_CNT', np.int32),
('D... | fc34b897d7e23e8833a63b0fd7ce72cd090f35ab | 3,640,029 |
def drawblock(arr, num_class=10, fixed=False, flip=False, split=False):
"""
draw images in block
:param arr: array of images. format='NHWC'. sequence=[cls1,cls2,cls3,...,clsN,cls1,cls2,...clsN]
:param num_class: number of class. default as number of images across height. Use flip=True to set number of w... | 221dc90d8a674963221abe11720d23ac92af6225 | 3,640,030 |
def with_key(output_key_matcher):
"""Check does it have a key."""
return output_key_matcher | 5bcb64550ce202f66ac43325fe8876249b45c52d | 3,640,031 |
def generatePersistenceManager(inputArgument, namespace = None):
"""Generates a persistence manager base on an input argument.
A persistence manager is a utility object that aids in storing persistent data that must be saved after the interpreter shuts
down. This function will interpret the input argum... | a1042764974d1b8030c6b6dd2add444bea9e521c | 3,640,032 |
def get_app():
"""
Creates a Sanic application whose routes are documented using the `api` module.
The routes and their documentation must be kept in sync with the application created
by `get_benchmark_app()`, so that application can serve as a benchmark in test cases.
"""
app = Sanic("test_api... | 1f8a11ee404082dcca0c1df91910157e5c169854 | 3,640,033 |
import base64
def predict(request):
"""View to predict output for selected prediction model
Args:
request (json): prediction model input (and parameters)
Returns:
json: prediction output
"""
projects = [{"name":"Erschließung Ob den Häusern Stadt Tengen", "id":101227},
... | 364db414d2c5811df0fe36e516868e0db76f896b | 3,640,034 |
def is_dict(etype) -> bool:
""" Determine whether etype is a Dict """
return type(etype) is GenericMeta and etype.__extra__ is dict | fb0e422e08abd3b20611a8817300334d32638b49 | 3,640,035 |
import torch
from typing import List
def hidden_state_embedding(hidden_states: torch.Tensor, layers: List[int],
use_cls: bool, reduce_mean: bool = True) -> torch.Tensor:
"""
Extract embeddings from hidden attention state layers.
Parameters
----------
hidden_states
... | f732e834f9c3437a4a7278aa6b9bfc54589b093b | 3,640,036 |
from datetime import datetime
def is_new_user(day: datetime.datetime, first_day: datetime.datetime):
"""
Check if user has contributed results to this project before
"""
if day == first_day:
return 1
else:
return 0 | 8da8039d1c8deb5bb4414565d3c9dc19ce15adb6 | 3,640,037 |
def to_ndarray(X):
"""
Convert to numpy ndarray if not already. Right now, this only converts
from sparse arrays.
"""
if isinstance(X, np.ndarray):
return X
elif sps.issparse(X):
print('Converting from sparse type: {}'.format(type(X)))
return X.toarray()
else:
... | 337a78066316f32cf3a4f541d38c78de18750264 | 3,640,038 |
def _2d_gauss(x, y, sigma=2.5 / 60.0):
"""A Gaussian beam"""
return np.exp(-(x ** 2 + y ** 2) / (2 * sigma ** 2)) | c010989499682e4847376a162852c9f758907385 | 3,640,039 |
def attach_task_custom_attributes(queryset, as_field="task_custom_attributes_attr"):
"""Attach a json task custom attributes representation to each object of the queryset.
:param queryset: A Django projects queryset object.
:param as_field: Attach the task custom attributes as an attribute with this name.
... | 584d2f918ae1844beb5cab71318691094de6d56d | 3,640,040 |
import torch
def softmax_like(env, *, trajectory_model, agent_model, log=False):
"""softmax_like
:param env: OpenAI Gym environment
:param trajectory_model: trajectory probabilistic program
:param agent_model: agent's probabilistic program
:param log: boolean; if True, print log info
"""
... | 7b51e0336399914e357b4dbed0490e93fb22f70a | 3,640,041 |
def bulk_add(packages, user):
"""
Support bulk add by processing entries like:
repo [org]
"""
added = 0
i = 0
packages = packages.split('\n')
num = len(packages)
org = None
results = str()
db.set(config.REDIS_KEY_USER_SLOTNUM_PACKAGE % user, num)
results += "Add... | 7b027b45e6e3385fc3bc3da8916b8322dde7cfda | 3,640,042 |
def laser_heater_to_energy_spread(energy_uJ):
"""
Returns rms energy spread in induced in keV.
Based on fits to measurement in SLAC-PUB-14338
"""
return 7.15*sqrt(energy_uJ) | 59feb872f0c652e0ef28b0958d2b25c174a79152 | 3,640,043 |
def apparent_attenuation(og, fg):
"""Apparent attenuation
"""
return 100.0 * (float(og) - float(fg)) / float(og) | e22ce07229baa4eacb7388280630d6097e21f364 | 3,640,044 |
def most_similar(W, vocab, id2word, word, n=15):
"""
Find the `n` words most similar to the given `word`. The provided
`W` must have unit vector rows, and must have merged main- and
context-word vectors (i.e., `len(W) == len(word2id)`).
Returns a list of word strings.
"""
assert len(W) == ... | 3e13a1e24935c7eacea9973c9af315d0a2a0fca4 | 3,640,045 |
def build_cell(num_units,
num_layers,
cell_fn,
initial_state=None,
copy_state=True,
batch_size=None,
output_dropout_rate=0.,
input_shape=None,
attention_mechanism_fn=None,
memory=None,
... | 85d284ba314bea94ba015f7a85d0ba6685103292 | 3,640,047 |
def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Use config values to set up a function enabling status retrieval."""
conf = config[DOMAIN]
host = conf[CONF_HOST]
port = conf[CONF_PORT]
apcups_data = APCUPSdData(host, port)
hass.data[DOMAIN] = apcups_data
# It doesn't really ... | ccb2061fe8c36b799e5179f113c380d379ebec9d | 3,640,048 |
import signal
def _lagged_coherence_1freq(x, f, Fs, N_cycles=3, f_step=1):
"""Calculate lagged coherence of x at frequency f using the hanning-taper FFT method"""
# Determine number of samples to be used in each window to compute lagged coherence
Nsamp = int(np.ceil(N_cycles * Fs / f))
# For each N-... | 8a1cefe6fa2ef87dbc71f3f4449afc4406fa2c5f | 3,640,049 |
def program_hash(p:Program)->Hash:
""" Calculate the hashe of a program """
string=";".join([f'{nm}({str(args)})' for nm,args in p.ops if nm[0]!='_'])
return md5(string.encode('utf-8')).hexdigest() | f12ed910bc94070f64fe673ddd81925a704c700a | 3,640,050 |
async def get_events(user_creds, client_creds, list_args, filter_func=None):
"""List events from all calendars according to the parameters given.
The supplied credentials dict may be updated if tokens are refreshed.
:param user_creds: User credentials from `obtain_user_permission`.
:param client_creds... | 00a99194c993c5155a03b985ba46fec84fd82ad7 | 3,640,051 |
import logging
import pickle
def process_file(input_file, input_type, index, is_parallel):
"""
Process an individual SAM/BAM file.
How we want to process the file depends on the input type and whether we
are operating in parallel. If in parallel the index must be loaded for each
input file. If th... | a10c6b520fb586f4320f538b91adf7e7add4ace3 | 3,640,052 |
def add_dictionaries(coefficients, representatives, p):
""" Computes a dictionary that is the linear combination of `coefficients`
on `representatives`
Parameters
----------
coefficients : :obj:`Numpy Array`
1D array with the same number of elements as `representatives`. Each
entry ... | ffdb894b11509a72bc6baadc4c8c0d0d15f98110 | 3,640,053 |
def dropsRowsWithMatchClassAndDeptRemainderIsZero(df, Col, RemainderInt, classToShrink):
"""
Takes as input a dataframe, a column, a remainder integer, and a class within the column.
Returns the dataframe minus the rows that match the ClassToShrink in the Col and have a depth from the DEPT col with a remain... | f88ec5e8293d753defe0a6d31f083e52218011ba | 3,640,054 |
import requests
import json
def get_token():
""" returns a session token from te internal API.
"""
auth_url = '%s/sessions' % local_config['INTERNAL_API_BASE_URL']
auth_credentials = {'eppn': 'worker@pebbles',
'password': local_config['SECRET_KEY']}
try:
r = request... | da875c11dd887a895fe6c133cba3d30e3b73082c | 3,640,057 |
def setlist(L):
""" list[alpha] -> set[alpha] """
# E : set[alpha]
E = set()
# e : alpha
for e in L:
E.add(e)
return E | 7607d3d47ea5634773298afaea12d03759c0f1d4 | 3,640,058 |
def _pixel_at(x, y):
"""
Returns (r, g, b) color code for a pixel with given coordinates (each value is in
0..256 limits)
"""
screen = QtGui.QGuiApplication.primaryScreen()
color = screen.grabWindow(0, x, y, 1, 1).toImage().pixel(0, 0)
return ((color >> 16) & 0xFF), ((color >> 8) & 0xFF), ... | 62341d5d7edc3529b5184babddf475bc35f407bf | 3,640,060 |
from datetime import datetime
import time
def parse_tibia_time(tibia_time: str) -> datetime:
"""Gets a time object from a time string from tibia.com"""
tibia_time = tibia_time.replace(",","").replace(" ", " ")
# Getting local time and GMT
t = time.localtime()
u = time.gmtime(time.mktime(t))
... | da9e8f4a9b8a94161d215ff1119d8510de57b434 | 3,640,061 |
def a3v(V: Vector3) -> np.ndarray:
"""Converts vector3 to numpy array.
Arguments:
V {Vector3} -- Vector3 class containing x, y, and z.
Returns:
np.ndarray -- Numpy array with the same contents as the vector3.
"""
return np.array([V.x, V.y, V.z]) | f32476c613a8032bf7119d5b99a89e72c56628d2 | 3,640,062 |
def _p_value_color_format(pval):
"""Auxiliary function to set p-value color -- green or red."""
color = "green" if pval < 0.05 else "red"
return "color: %s" % color | ae58986dd586a1e6cd6b6281ff444f18175d1d32 | 3,640,063 |
def generator(seed):
"""
build the generator network.
"""
weights_initializer = tf.truncated_normal_initializer(stddev=0.02)
# fully connected layer to upscale the seed for the input of
# convolutional net.
target = tf.contrib.layers.fully_connected(
inputs=seed,
num_outputs... | 93258f49ba0fc7d7d03507bdc7dc413b2a9e23d5 | 3,640,065 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.