content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def preprocess_cv(vec_idx_patient, cfg):
"""
Cross validation mode of the preprocessing function
:param vec_idx_patient: list containing start and end indices of the patients
:param cfg: object holding all the training parameters
:return:
"""
# Exception detection
if not cfg.binary_cla... | 73b12b155eb4329d39d3c625826af02339cf2584 | 53,700 |
def is_happy(n: int) -> bool:
"""
is_happy
:param n:
:return:
"""
global happy_flag
happy_flag = False
total, counter = n, 0
while True:
num_list, total= list(str(total)), 0
for i in num_list:
total += pow(int(i), 2)
counter += 1
if total... | 091ca74fcfd50c01197cd9a38a24cf1ae951f769 | 53,701 |
import cmath
def rotate_points(points, phase_shift):
"""
Rotate a point about the origin.
Arguments:
points: iterable(complex)
Points to rotate in the complex plane.
phase_shift:
Magnitude of rotation in radians.
Returns:
rotated_points: list(complex)
... | e9ae43774bc8f5ac770413f6e758d41223fb3c00 | 53,702 |
import tkinter
def add_choice(path, choices, default=None, *, var=None, **kwargs):
"""Add an action for choosing one from a list of choices.
:source:`The menubar plugin <porcupine/plugins/menubar.py>` displays
these actions as submenus that contain radio button items.
If given, *default* should be a... | 6a629a0860791d9d9241c5cbeceeabab893b8376 | 53,703 |
def get_bprop_max_pool_grad_grad(self):
"""Grad definition for `MaxPoolGrad` operation."""
maxpool_grad_grad = G.MaxPoolGradGrad(
kernel_size=self.kernel_size,
strides=self.strides,
pad_mode=self.pad_mode)
def bprop(x1, x2, grad, out, dout):
dx1 = zeros_like(x1)
dx2 ... | 79b3ced82ac660e4ad03e8b0834f61d0f8eea9d8 | 53,704 |
def line_style(
type=None,
line_width=1,
line_opacity=1,
line_curve=0,
line_type="solid",
line_color=None,
**kwargs
):
"""
带线图形的线的风格选项
:param type:
图形类型
:param line_width:
线的宽度,默认为 1
:param line_opacity:
线的透明度,0 为完全透明,1 为完全不透明。默认为 1
:param lin... | f816bd30e9bda9d21f6607e8dc21e010982e0f07 | 53,705 |
def generate_scale(scale, note, mode=1, r_type="list", octaves=True): # scale, start, type
"""
Generate a scale
scale (string): major, melodic_minor, harmonic_minor, chromatic, major_pentatonic
note: start note
"""
if scale in SCALE_STEPS:
steps = _get_mode(SCALE_STEPS[scale], mode)
... | 18ee2df974f5b8e70589341860885af07d90a049 | 53,706 |
def _serialize_slot_variables(checkpointable_objects, path_to_root,
non_slot_variables, object_graph_proto):
"""Name slot variables and add them to `object_graph_proto`."""
named_slot_variables = {}
for optimizer_checkpoint_id, checkpointable_ref in enumerate(
checkpointable_ob... | 83439dbc483c4269b6ac71596f2017f981823593 | 53,707 |
def tupleize(func):
"""A decorator that tuple-ize the result of a function. This is useful
when the evaluation function returns a single value.
"""
def wrapper(*args, **kargs):
return func(*args, **kargs),
return wrapper | 2a2a9d709177868bd47571f86ae026d666b2593b | 53,708 |
from typing import Any
def regress_level_on_first_known(y:Y_TYPE, s:dict, k, a:A_TYPE=None, t:T_TYPE =None, e:E_TYPE =None)->([float] , Any , Any):
""" Very basic online regression skater, mostly for offlinetesting
- Only one known in advance variable is utilized
- Last value is ignored, unl... | e5f798679c98a3a95494110bb85f97ed1014474a | 53,709 |
def _gen_capture_chain_fo(nt_names, fname=None):
"""
Given a list of NT names, generate a function object (function_object_t)
that calls corresponding xed3 NT capturing functions.
Each such function captures everything that xed2 decode graph would
capture for a given pattern with NTs (nt_names) in i... | 86deb3222c5d09c081ff604cce1e65a22a14ebb5 | 53,710 |
import scipy.signal as sig
def weight2fun(grid_rowcol):
"""Make a function from a SICD data structure description of a complex image weighting
Input:
grid_rowcol Either the Grid.Row or Grid.Col SICD field depending on
which direction is being processed. Should have ei... | aa4c7ddf609e1a57573dff2433dbb9b34c97f007 | 53,711 |
def public_point(private_key, curve='secp256k1'):
"""Retrieve the public key as a point object"""
try:
curve_obj = KNOWN_CURVES[curve.lower()][0]
except KeyError:
raise ValueError("Unknown curve name {}".format(repr(curve)))
return curve_obj.public_point(key) | 5263a932a6c49a08fa587605633184639f84c283 | 53,712 |
def get_five_landmarks_from_net(landmarks):
"""
Return 5 landmarks needed in face alignment
"""
num_lmks = landmarks.shape[0]
if num_lmks == 5:
left_eye = landmarks[0]
right_eye = landmarks[1]
nose = landmarks[2]
mouse_left = landmarks[3]
mouse_right = landma... | e0e856d2b32e62bb1a0eacb5a51e55b2a065b8ea | 53,713 |
def det_vectors(h=1.0,v=1.0,nu=0.0,delta=0.0):
"""
Compute detector apperature vectors in lab frame
Parameters:
-----------
* h = detector horz width (total slit width in lab-z,
or the horizontal scattering plane)
* v = detector vert hieght (total slit width in lab-x,
or the vertica... | b4556d580d33a544565842a8a7a01535e7769918 | 53,714 |
def TopOpeBRepBuild_Tools_FindStateThroughVertex(*args):
"""
:param aShape:
:type aShape: TopoDS_Shape &
:param aShapeClassifier:
:type aShapeClassifier: TopOpeBRepTool_ShapeClassifier &
:param aMapOfShapeWithState:
:type aMapOfShapeWithState: TopOpeBRepDS_IndexedDataMapOfShapeWithState &
... | dcbc68393122f73e8c78971b0c0db0b9055066bb | 53,715 |
from typing import List
def remove_registered_at(input_list: List[dict]) -> List[dict]:
"""
Removes the field 'registered_at' frm a list of connection results, for comparing two results without
considering the time.
"""
node_to_remove = 'registered_at'
output_list = deepcopy(input_list)
fo... | f99a21853411e0247fc4aa0ce1bdfdbbb0bb3353 | 53,716 |
import logging
def extract_melodies(sequence, steps_per_beat=4, min_bars=7,
min_unique_pitches=5):
"""Extracts a list of melodies from the given NoteSequence proto.
A time signature of BEATS_PER_BAR is assumed for each sequence. If the
sequence has an incompatable time signature, like 3/4,... | 934a5a9a9f6c068191f0ed6386caac3cafdc7736 | 53,717 |
def vocabulary(word_counts):
"""
:param word_counts: dictionary of each word count
:return: list of vocabulary
"""
vocabulary = list(map(lambda x: x[0], sorted(word_counts.items(), key=lambda x: -x[1])))
return vocabulary | 2e7b77fe8e69ba4dd6c9136c3e80b16f02a56d49 | 53,718 |
import matplotlib.pyplot as plt
def partial_deriv_plot(of, wrt, check_partials_data, title=None, jac_method='J_fwd', tol=1e-10,
binary=True):
"""
Visually examine the computed and finite differenced Jacobians.
Parameters
----------
of : string
Variable whose derivat... | d863d69256de2c7907dcf2cf12987c8ae8bc8830 | 53,719 |
def new_scaled_crossentropy(index=2, scaling=1.0):
"""
Returns masked crossentropy with extra scaling:
Scales the loss for given stop_index by stop_scaling
"""
def masked_crossentropy(targets: tf.Tensor, logits: tf.Tensor) -> tf.Tensor:
crossentropy = tf.keras.losses.SparseCategoricalCr... | 4d932dc663e3bb13436f7efe96b112b06d5051a3 | 53,720 |
def version():
"""
Report the version of this module
"""
return __version__ | 2ca61a973d7dfb2f2cee3dcca21d535c8c6f22ff | 53,721 |
import torch
def rejoin(chunked, initial_shape):
"""
Rejoins chunked tensor, removing the padding as necessary
>>> eq = lambda a, b: torch.all(torch.lt(torch.abs(torch.add(a, -b)), 1e-12))
>>> x = torch.arange(end=4) + 3
>>> y = torch.arange(end=15) + 2
>>> mesh = x.view(-1, 1) @ y.view(1, -1... | 6bcf5bf07b813b79245b50c72e67a98e575df5f9 | 53,722 |
def single() -> dict:
""" 1x1 block """
temp = {
0 : {
0 : Conway(Position(0,0),True)
}
}
return temp | 531495b6d5236ea41d6646490b0de0e293d8ad4a | 53,723 |
def h4(content, accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: str="", translate... | dca57db0ad6a21d85743fd7fc111c0db35ae29f0 | 53,724 |
def svn_wc_delete2(*args):
"""
svn_wc_delete2(char path, svn_wc_adm_access_t adm_access, svn_cancel_func_t cancel_func,
svn_wc_notify_func2_t notify_func,
apr_pool_t pool) -> svn_error_t
"""
return _wc.svn_wc_delete2(*args) | 504a22b3591a5fea7db280a0a7e8d70d145c0886 | 53,725 |
def tile(address, tile_x, tile_y, tile_z, tilesize=256, **kwargs):
"""
Create mercator tile from any images.
Attributes
----------
address : str
file url.
tile_x : int
Mercator tile X index.
tile_y : int
Mercator tile Y index.
tile_z : int
Mercator tile Z... | 1b879ca79d2d8ae4dbb5cd46c6aac09a069406c7 | 53,726 |
import json
def JsonError(error_text):
"""Constructs a JSON response from an error."""
response = make_response(json.dumps({'error': error_text}, indent=4))
response.headers['Content-Type'] = 'application/json'
return response | 8de3b48da09420806094f042b3dfb795dde956d8 | 53,727 |
def calc_b_stress_xx( x, y = 0, z = 1, Fv = 1, mu = 1, lamb = 1 ):
"""
Boussonesq solution for stresses acting on x in the x direction,
from Liu and Zoback 1992 JGR (equation 68)
"""
r = get_r( x, y, z)
term1 = Fv / (2 * np.pi)
term2 = 3 * x **2 * z / r **5
term3 = mu * ( y **2 + z *... | 31ca419ecebbe4a8fe84e49f1d29818a8fe0ac3a | 53,728 |
def stress_from_momentum_budget(H, dhdx, dSxxdx, dpdx, taub, rhow):
"""Returns the stress estimate from momentum budget components."""
return rhow * GRAV * H * dhdx + H * dpdx + dSxxdx - taub | 68001cd3296ef510f4e9b1ab9f82091f93ddb2f2 | 53,729 |
def transient_provider(func):
"""
Decorator to mark a provider as transient
"""
func.transient = True
return func | 2f540fc3099c3fc71ac49ce44dbd69a042b9e39f | 53,730 |
def getObsPETs(mat, binSize=5000):
"""
Get the number of PETs in bins.
@param mat: [[x,y]]
@param binSize:int, contact matrix bin size
"""
minC = np.min(mat)
a = (mat[:, 0] - minC) / binSize
b = (mat[:, 1] - minC) / binSize
a = a.astype(int)
b = b.astype(int)
ss = {}
for ... | c4cc020f9ea32f0912cd6f5df585a7063680336b | 53,731 |
import os
import time
def query(query_list, feature_list, out_dir, top=200,
pca_thresh=0.9, out_dim=None, pca_file='-1', qe_fn=None,
mask_pred=False, euclidean_dist=False, rmac=False, mac=False, aml=False):
"""Query by list."""
print(Notify.INFO, 'Read feature', Notify.ENDC)
print(No... | 699e9c6386eec061576fb7113f5d6bf0d23db0d4 | 53,732 |
from operator import concat
def crf1d(cost, xs, ys, reduce='mean'):
"""Calculates negative log-likelihood of linear-chain CRF.
It takes a transition cost matrix, a sequence of costs, and a sequence of
labels. Let :math:`c_{st}` be a transition cost from a label :math:`s` to
a label :math:`t`, :math:`... | 86a0b9e963db1cb27cff6b0a8bf418489608defa | 53,733 |
import re
def abs_date_from_phrase(text):
"""
Identify the first absolute date in text
Returns ((month, day), start, end) or None
Doesn't currently support British dates (e.g. '28 February')
"""
dates = set()
months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august... | 8306469ce9b1a1098a9d6fb406994375820eb7ad | 53,734 |
from pathlib import Path
import sys
def load_fonts(path: Text = None):
"""Discover all files in the directory given by `path`
and load them as fonts.
font filename format:
[font name]_[char width]x[line height].[image extension]
"""
# if no path is supplied the fonts are loaded into the m... | 1a60cd6cd150232d83a584835b24b8c156cd94cb | 53,735 |
def _read_CD_Chirascan( infile, outfile=None ):
"""CD read method for the Chirascan output format.
.. seealso::
:func:`.read_CD`
"""
def reshape(row):
df = ru.add_column(pd.DataFrame(row.iloc[1:]).reset_index(), 'w', row.iloc[0])
df = df.assign(bin=range(1, df.shape[0] + 1))
... | 7a38fcb1f1140ef69ab7f5241069cddf248f7dc6 | 53,736 |
def new(key, *args, **kwargs):
"""Create a new XOR cipher
:Parameters:
key : byte string
The secret key to use in the symmetric cipher.
Its length may vary from 1 to 32 bytes.
:Return: an `XORCipher` object
"""
return XORCipher(key, *args, **kwargs) | 8ba3567e30a032bd74069c766877f50898e5cc2a | 53,737 |
def _quadsum1(x0, a, n, ind):
"""
sum_i (yi-x0)^2/(ai*ai) = 1 with i in ind
Args:
x0(array):
a(array):
n(int): number of dimensions
ind(list(int)): number of dimensions involved
Returns:
array: n+1 x n+1
"""
x0 = np.asarray(x0)
a = np.asarray(a)
... | 52ffed9c680dbd28274b68522c86dd6b5401009c | 53,738 |
def remove_indicator(request, _id):
"""
Remove an Indicator from CRITs.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param _id: The ObjectId of the indicator to remove.
:type _id: str
:returns: :class:`django.http.HttpResponse`,
... | 6039ba42e009142ac1e5799fbd389ea7b1de9887 | 53,739 |
def zharkov_panh(v, temp, v0, a0, m, n, z, t_ref=300.,
three_r=3. * constants.R):
"""
calculate pressure from anharmonicity for Zharkov equation
the equation is from Dorogokupets 2015
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in... | f975153dad4da627e31280ec1e1f5bd5568731e0 | 53,740 |
from typing import Tuple
def nearest_edge(energy: float)-> Tuple[str, str]:
"""Return nearest x-ray edge for a given energy.
Parameters
----------
energy
X-ray energy in eV.
Returns
-------
:
Absorption element.
:
Absorption edge.
Raises
------
Va... | bdcca15904c0ef937a3fb35ca591d3efa168619f | 53,741 |
def rect_break_or_contact_box(rect: Rect, box: Rect):
"""
Determine if the `rect` breaks the `box` or it contacts the border of `box`
@param rect The Rect of the target rectangle
@param box The target box
"""
return (
rect.left <= box.left or
rect.right >= box.right or
r... | 2e9652c7333c31bf8eb9cb135bcdb7c920a837ba | 53,742 |
def validate_keep(keep):
"""validates the value of the keep parameter
If it's not coercable to an int or equal to the special string values,
raise a ValueError. Otherwise, return `keep`.
:param keep: value to validate
:type keep: int or str
:return: the validated value of keep
:rtype: eith... | 5a1d03140eeab9bef1f3ae417c3d3fc77b8499bd | 53,743 |
import os
def default_database():
"""
Returns DATABASE if env is set
"""
return os.environ.get('DATABASE', '') | a4e1ccfd916e76e0ed8eea79ca519711cbcaced1 | 53,744 |
def __get_instruments(currency: str, kind: str, expired: bool):
"""
Create a message to get all positions for a given currency on delta.
:param currency: String symbol (e.g. 'BTC' or 'ETH')
:param kind: Type of contract (either 'future' or 'option')
:return: Message (dict)
"""
# Sanitize in... | ae084e7b6452bb16b7849425f605d46d41a25bd1 | 53,745 |
def posths_enrollment_factors(persons, posths):
"""
Post high school enrollment rates by county, age, income
and school type (public university, public community college, private university,
private trade and vocational).
TODO items:
- Right now this is done at the county-level does it make... | 50bbb2495205f3516a11038a2936381fb3f4a11f | 53,746 |
import hashlib
def sha256_file(fname):
"""
Return sha256 of a given filename
Copied from https://stackoverflow.com/a/3431838
"""
hash_sha256 = hashlib.sha256()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
return h... | 5c4b571922b1a2a4eaebe3bcd1436e7f7d85583f | 53,747 |
import collections
def create_iam_resources(env='dev', app='', **_):
"""Create the IAM Resources for the application.
Args:
env (str): Deployment environment/account, i.e. dev, stage, prod.
app (str): Spinnaker Application name.
Returns:
True upon successful completion.
"""
... | 52806a6426e1fd79baf743ce33058460abcb1ec1 | 53,748 |
def _calculate_vm_load(vm_list):
"""
Given a list of VMs,
Calculate the sum of the load.
"""
load = 0
for server in vm_list:
pos = server.rfind('-')
if pos < 0:
pos = len(server)-1
load += weight(server[:pos])
return load | 254a3a07134517cee1b3e81636d3f16539b9636c | 53,749 |
import os
def get_list_of_commands(svg_dirs):
"""
Get a list of commands for converting each svg to png using cairosvg
:param svg_dirs: the list of directories containing svg files
:return: a list of commands
"""
command_list = []
# Each directory must be processed separately so that PNGs... | 396f0d288bac04e3a9db9ff3b7e36fd7dde93c0a | 53,750 |
from typing import Type
import types
def build_ufunc_wrapper(library, context, fname, signature, objmode, cres):
"""
Wrap the scalar function with a loop that iterates over the arguments
"""
assert isinstance(fname, str)
byte_t = Type.int(8)
byte_ptr_t = Type.pointer(byte_t)
byte_ptr_ptr_t... | 4a9e29f412302c17fa47afa4eae729af6d0d1299 | 53,751 |
from scipy import weave
from scipy.weave import converters, build_tools
import numpy as np
import sys
from StringIO import StringIO
def __check_weave():
"""Apparently presence of scipy is not sufficient since some
versions experience problems. E.g. in Sep,Oct 2008 lenny's weave
failed to work. May be some... | df380231276203daf2dff9c90d4c2b13b2420d2d | 53,752 |
def levensthein_dist(input_command: str, candidate: str) -> int:
"""
Implement the Levenshtein distance algorithm to determine, in case of a non-existing handle,
if theres a very similar command to suggest.
:param input_command: The non-existing handle the user gave as input
:param candidate: The (... | 02506be8655f97a60665a507cfa62cb9703590ef | 53,753 |
def find_multiset_union(role1, role2, normalize=False, parameters=None):
"""
Finds the union of a multiset
Parameters
-------------
role1
First role originators
role2
Second role originators
normalize
Do the normalization of the roles
parameters
Parameter... | fa19df40ad1b351b93dbe069edb2409260dc48cd | 53,754 |
def Cijkl(C):
"""
Populates 4D elastic tensor from 6x6 elastic tensor
:param C: 6x6 elastic constants tensor
:return: 3x3x3x3 elastic Cijkl tensor
"""
c=np.zeros(shape=(3,3,3,3))
CC=np.zeros(shape=(9,9))
CC[0:6,0:6]=C[0:6,0:6]
CC[6:9,6:9]=C[3:6,3:6]
CC[0:6,6:9]=C[0:6,3:6]
CC[6:9,0:6]=C[3:6,0:6]
c[0,0,0,0]=... | 7378c88fbdaf86472166fd317d95974129561b05 | 53,755 |
def batch_reduce(x: Tensor):
"""return x.view(x.size(0), -1).sum(1)"""
return flatten(x).sum(1) | aa1477ac16bdc1aee5a251b14d60c0eff69b891a | 53,756 |
from typing import List
from typing import Dict
import torch
def _merge_flat_fsdp_opt_state(shards_to_load: List[Dict]) -> Dict:
"""Logic described here: https://tinyurl.com/2p86zffr"""
result = shards_to_load[0][OPT_KEY]
pad_info = _get_pad_info(shards_to_load[-1])
world_size = dist_utils.get_data_pa... | 6a8a89999e08f2b39e7bb0dd4214029f45e3eb96 | 53,757 |
def split_heads_2d(x, num_heads):
"""Split channels (dimension 4) into multiple heads (becomes dimension 1).
Args:
x: a Tensor with shape [batch, height, width, channels]
num_heads: an integer
Returns:
a Tensor with shape [batch, num_heads, height, width, channels / num_heads]
"""
return tf.transp... | 5cd4694188108ccf5b9814cb9dea1f3efb56f8e2 | 53,758 |
def read_df(df, metric):
"""
You can use `read_df(df,metric)` to load data from a `<class 'pandas.core.frame.DataFrame'>` object. It will return two objects.
1. a `DataFrame` with all hyperparameters' value and the value of metric you choose
2. a `list` of all hyperparameters' name
"""
p... | 1dfd7312bf98319effa2903097abce09f549a4f3 | 53,759 |
from typing import Sequence
from typing import Optional
def solve_fast_diag(v: Sequence[AlignedArray],
grid: grids.Grid,
q0: Optional[AlignedArray] = None,
implementation: Optional[str] = None) -> AlignedArray:
"""Solve for pressure using the fast diagonal... | 04d2003db5a551334ccd25e509c3fd62087c8722 | 53,760 |
from bs4 import BeautifulSoup
def extract_data():
"""Extract data from HTML file downloaded from AEIR website."""
cards = []
# HTML scraping
soup = BeautifulSoup(open(HTML_FILE), features="html.parser")
# Informations are in the recto of the card. The verso part is not relevant
divs = soup.... | 46f52f4efafe0b7a7211cc3119e245695a10657b | 53,761 |
def read_halos(path):
"""
Reads a list of halos with columns:
rho_s (Msun/kpc^3), r_s (kpc), v (km/s)
"""
data = np.loadtxt(path)
if data.shape[1] > 2:
return data[:,0], data[:,1], data[:,2]
else:
return data[:,0], data[:,1], None | 9e1c0edb69fd18918eb7630d61b1feafcb75c675 | 53,762 |
def simpleMultivariateNormalPdf(z, detFactorSigma):
""" Assuming z has been transformed to a mean of zero and an identity matrix of covariances.
Needs to provide the determinant of the factorized (real) covariance matrix. """
dim = len(z)
return exp(-0.5 * dot(z, z)) / (power(2.0 * pi, dim / 2.) * detFa... | b41c59489c8c228486b348a6c4c1c69bffcdda0b | 53,763 |
def _get_change_extent(str1, str2):
"""
Determines the extent of differences between two strings. Returns a tuple
containing the offset at which the changes start, and the negative offset
at which the changes end. If the two strings have neither a common prefix
nor a common suffix, (0, 0) is returne... | 5530ddb5aedda9aff5953ae7d5401e20e743b705 | 53,764 |
def _replace_file_in_command(command, specified_file, name):
""" Replace example file with cheetah variable name in supplied command
or command template. Be sure to quote the name.
"""
# TODO: check if the supplied variant was single quoted already.
if '"%s"' % specified_file in command:
# S... | 33860188349c17603b9eaabcc806027ccb39edae | 53,765 |
def FilterByLength(max_length, min_length=0, # pylint: disable=invalid-name
length_keys=None, length_axis=0):
"""Returns a function that filters out examples by length.
Args:
max_length: int. If not None, indicates maximum length.
min_length: int. If not None, indicates minimum length.
... | a714ed9447d27f90049f334ff54dd416a28d4f61 | 53,766 |
def set_attr(obj, path, value):
"""
SAME AS object.__setattr__(), BUT USES DOT-DELIMITED path
RETURN OLD VALUE
"""
try:
return _set_attr(obj, split_field(path), value)
except Exception as e:
Log = get_logger()
if PATH_NOT_FOUND in e:
Log.warning(PATH_NOT_FOUND... | 9a327e71b00accbd63744ecf52d56bad00f7f216 | 53,767 |
import logging
def get_res_dataframe_as_dict(which_results_table :str, sharelist :str, ov_audit_cols, suppression_spec :str = ''):
""" extract share dataframe from HDFStore """
data_store = None
data_store_key = None
# if ov_audit_cols has content, we're going to have to grab an Ov
ov_df = None
... | 0e30b1ec930e2603bcb195c8fa2845715d2c1d00 | 53,768 |
def brac(
transitions=None,
# Common settings
discount_factor=0.99,
# Adam optimizer settings
lr_q=1e-3,
lr_pi=1e-3,
# Training settings
bc_iters=5000,
minibatch_size=100,
polyak_rate=0.005,
alpha=0.1
):
"""
Bootstrapping er... | 928003ea7980573c4422ef7831f3e9e6fb8d77c5 | 53,769 |
def stddev(e):
"""
:rtype: Column
"""
return col(StddevSamp(column=parse(e))) | 2ec79721ab63c843de993c7ac0ac58dce2a0b123 | 53,770 |
import inspect
import subprocess
def process(execute_kwargs=None):
"""Function for execute a set of command lines"""
if not execute_kwargs:
execute_kwargs = {}
commands = execute_kwargs["commands"]
if not isinstance(commands, list):
commands = [execute_kwargs["commands"]]
output_... | 2c265bde354974a215085a897e57dd897528b095 | 53,771 |
from datetime import datetime
def _is_start_date_before_end_date(start: datetime, end: datetime) -> bool:
"""Whether the start date is before the end date.
Args:
start: The start date of an event.
end: The end date of an event.
Returns:
True if valid, otherwise returns False.
... | 4a296d6673f6beb704b590893088c50a97184764 | 53,772 |
import torch
def sens_expand(x: torch.Tensor, sens_maps: torch.Tensor) -> torch.Tensor:
"""
Expand a single image into num_coils individual coil images using estimates of the sensitivity maps.
This is the inverse of sens_reduce.
Args:
x: An image of shape (H, W, 2).
sens_maps: Sen... | e2929417792032f3ffda59df5b31b988b429122b | 53,773 |
def parseWithBioPython(path, props, chains_filter=None):
"""
Parse values from file that can be parsed using BioPython library
@return a dict containing the properties that were processed
"""
pdb = './pdb'
full_path = os.path.abspath(os.path.join(pdb, path))
chains = props['chains']
... | d2a2f935f0ffdd753eac0155f666f0f885afed05 | 53,774 |
def structure(self: Client) -> StructureProxy:
"""Delegates to a
:py:class:`mcipc.rcon.be.commands.structure.StructureProxy`
"""
return StructureProxy(self, 'structure') | a7c679a2873864c36cdf1e7f987dbc6359bbb635 | 53,775 |
import os
def get_data_folder():
"""
Returns the location of the folder containing data files.
"""
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'data')
return os.path.normpath(path) | 3c9e99506bbdaabc1449ca1da2ecaf6afc498b97 | 53,776 |
def _points_from_xy(x, y, z=None):
"""
Generate list of shapely Point geometries from x, y(, z) coordinates.
Parameters
----------
x, y, z : iterable
Returns
-------
list : list
"""
if not len(x) == len(y):
raise ValueError("x and y arrays must be equal length.")
if... | f5f4eb0bc4d499a86a328d9e763c3707a12ecac6 | 53,777 |
def box(width,depth,height,center=None,R=None,t=None,world=None,name=None,mass=float('inf'),type='TriangleMesh'):
"""Makes a box with dimensions width x depth x height. The box is centered
at (0,0,0) by default.
Args:
width,depth,height (float): x,y,z dimensions of the box
center (list of ... | 7af433c5ca2e61f30891652f48fe9720508e5a68 | 53,778 |
def get_disabled_container_list(duthost):
"""Gets the container/service names which are disabled.
Args:
duthost: Host DUT.
Return:
A list includes the names of disabled containers/services
"""
disabled_containers = []
container_status, succeeded = duthost.get_feature_status()
... | e5057c723cf0836be3144950c56d18242f3c8007 | 53,779 |
def _SignedVarintDecoder(mask):
"""Like _VarintDecoder() but decodes signed values."""
local_ord = ord
def DecodeVarint(buffer, pos):
result = 0
shift = 0
while 1:
if pos > len(buffer) - 1:
raise NotEnoughDataExcption("Not enough data to decode varint")
... | 6269d12970b4abbb7ef9290d5f1a254b77aefc2b | 53,780 |
def ConvertIndexListToSet(index_list):
"""Creates a set containing the indices of all '1' entries in the index
list
"""
return set(i + 1 for i, j in enumerate(index_list) if j == 1) | 78d0769de4b22aabd0d0ea2f906958a929da5299 | 53,781 |
from typing import Tuple
def decrypt(text_enc: Tuple[int, int]) -> str:
"""Function that decrypt the tuple of tokens
and re-convert them into string.
:param text_enc: the tuple of the text encrypted
:return: the text decrypted
"""
encrypted = text_enc[0] ^ text_enc[1]
decrypted = encrypte... | 0496d90818ef310b885341dad2d91823eadf97e2 | 53,782 |
def hypersphere_point(Gr, agent_pos):
"""
For each agent determines a random point inside the hypersphere (Gr,|Gr-X|),
where Gr is its center, |Gr-X| is its radius, and X is the agent position.
"""
nPop, nVar = agent_pos.shape
# Hypersphere radius of each agent
r_max = np.linalg.norm(Gr - a... | 278b993fc0394d9f32ffe334d4d56b24503342fa | 53,783 |
def iterable_validator(schema):
"""Return a validator for casting part of schema."""
return SchemaValidator(
Draft7Validator(
schema['definitions']['iterable'],
format_checker=draft7_format_checker,
),
) | 138318797dce715dc1fbcd03c08574d7c6ede33e | 53,784 |
def remove_suffix_ness(word: str):
"""Remove the suffix from the word while keeping spelling in mind.
:param word: str - of word to remove suffix from.
:return: str - of word with suffix removed & spelling adjusted.
For example: "heaviness" becomes "heavy", but "sadness" becomes "sad".
"""
suf... | 102afe196281adf27cf446443f4bc74a478b06f7 | 53,785 |
def train_nonsegmented(language_model, dataset_fnames, segment_filtering=False):
"""
Trains a classifier that maps document similarity to relevance labels.
The non-segmented version disregards segmentation and computes similarity directly between
documents.
If segment_filtering is n... | 645ff65a78ded8f22a12cb393321c16b2ee7ddca | 53,786 |
def count_words(text):
"""
this function counts words
param sentence: string containing words
"""
if not isinstance(text, str):
raise TypeError("word counter accepts only strings")
normal_word_splits = text.split(" ")
new_words = []
for asplit in normal_word_splits:
if "\... | 773d07a4092298b292601d19bba596f1e8e9bcc2 | 53,787 |
from datetime import datetime
def edit_food(id):
"""Update a food entry if the current user is the creator"""
db = get_db()
food_entry = get_food_entry(id)
old_food_name = food_entry['food_name']
old_food_code = food_entry['food_code']
if request.method == 'POST':
if request.form['act... | 1d69c684bdaec523d627a06e8fa6496d8660120c | 53,788 |
import operator
def run_simulation(sim_object, forest_dimension):
"""
Run a single simulation with RBF and report the filter accuracy.
:param sim_object: LatticeForest simulation object.
:param forest_dimension: int representing the size of one side of the square LatticeForest.
:return: tuple of ... | 966dd5438479331c448c6473a6e01daa2edd5227 | 53,789 |
def lisser(chaine):
"""Retourne la chaîne lisser.
On lisse une chaîne en remplaçant certains schémas comme
" de le " par " du ".
"""
schemas = (
(" le a", " l'a"),
(" le e", " l'e"),
(" le hom", " l'hom"),
(" le hum", " l'hum"),
(" le i", " l'i"),
("... | 39e6c406b3708e1f5c4fd6e9845fb3e860761ef4 | 53,790 |
def ignore_pred(pred_boxes, gt_ignored_index, gt_polys, precision_thr):
"""Ignore the predicted box if it hits any ignored ground truth.
Args:
pred_boxes (list[ndarray or list]): The predicted boxes of one image.
gt_ignored_index (list[int]): The ignored ground truth index list.
gt_poly... | 5d26cce51a1f2270f9a1f10272217162de8f4d64 | 53,791 |
import os
def crawl_ve_from_remote_logs(mi_info, dn):
"""
deprecated do not use
Args:
mi_info : a dict mapping from model iter to ModelSearchInfo
dn : directory path of the one that directly contains the server log.log, i.e.,
the remote logs are in {dn}/{model_iter}/log.log
"""
for mi... | 7d2c71d3c31a91c25b690771599c50b9201ec1ef | 53,792 |
def compareBamRecords(this, other):
"""Compare this (a BamAlignment object) with other
(a BamZmwRead object)"""
assert(isinstance(this, BamAlignment) and
isinstance(other, BamZmwRead))
return (this.readName == other.readName and
this.zmwName == other.zmw.zmwName and
... | 9623e4e67221e6ceecce429a8bec9cb6fc154464 | 53,793 |
def moveZeroes(nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
j = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[j] = nums[i]
j += 1
k = len(nums)-j
while (k > 0):
nums[-k] = 0
... | 909f0dcac374dd8242dae4a13460ced4383dde3b | 53,794 |
import re
def get_lag(feature, target_feature=None):
"""Return the lag duration as an integer.
Optionally a specific target feature can be required.
Args:
feature (str): Feature to extract month from.
target_feature (str): If given, this feature is required for a successful
m... | a78d238c6ddac4aa82ff48dea27c376a1580973e | 53,795 |
def _map_header(keymap, dold, nulldict=None):
"""
Returns a dictionary of values from dictionary dold,
mapped to new key, if provided.
Parameters
----------
keymap: dict
The map between old and new dictionary keys.
Of the form {oldkey: newkey, ...}
dold: dict
The val... | e4f797d16ee7f69c20f1aad61644013fd2a4f777 | 53,796 |
def avgpool(prev_layer):
"""
Return the AveragePooling layer.
"""
return tf.nn.avg_pool(prev_layer, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') | 2859192d34e83ca7d9405e2b10a64dee530d22a0 | 53,797 |
def vec3(*args):
"""Create 3D vector from input ``args``."""
if len(args) == 1: args = args[0]
return np.asarray(args, dtype='f8') | 1db6940b434735eb64c553a6be0b35eeb9e83edc | 53,798 |
import random
def full_jitter(value):
"""Jitter the value across the full range (0 to value).
Copied from https://github.com/litl/backoff/blob/master/backoff.py (MIT License)
This corresponds to the "Full Jitter" algorithm specified in the
AWS blog's post on the performance of various jitter algorit... | 18e747115ef055e78147232da1590521ff0ee568 | 53,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.