content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def imwrite_indexed(filename, array, palette_path):
""" Save indexed png with palette."""
color_palette = np.loadtxt(palette_path, dtype=np.uint8).reshape(-1,3)
if np.atleast_3d(array).shape[2] != 1:
raise Exception("Saving indexed PNGs requires 2D array.")
im = Image.fromarray(array)
im.p... | 5,308,200 |
def pcr():
"""docstring."""
if request.method == "GET":
return render_template("pcr.html",
results=results,
version=version)
if 'clear' in request.form:
results.clear()
return redirect(url_for('pcr'))
user_data = req... | 5,308,201 |
def table(columns, values, header=None, transpose=False, edge="*", padding=1, printer=print):
"""Prints a table from the columns and values data."""
# making sure your inputs are kosher
transpose = transpose if type(transpose) is bool else False
header = None if type(header) is not str else header
e... | 5,308,202 |
def guild_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
"""A decorator that indicates this command can only be used in a guild context.
This is **not** implemented as a :func:`check`, and is instead verified by Discord server side.
Therefore, there is no error handler called when a command ... | 5,308,203 |
def discover_tree(urlconf=None):
"""Finds all ApiNode usage in given or default urlconf"""
if urlconf is None:
urlconf = settings.ROOT_URLCONF
if isinstance(urlconf, basestring):
urlconf = import_module(urlconf)
nodes = set()
for item in urlconf.urlpatterns:
for p in item.... | 5,308,204 |
def test_check_md5_command(mocker):
"""
Given:
- file command args
When:
- run check_md5_command
Then:
- Verify response outputs
- verify response readable output
"""
mock_args = {'file': 'file'}
test_data = util_load_json('test_da... | 5,308,205 |
def drawSphere(name,
location,
size,
material_name,
segments=32,
ring_count=16,
subsurf_render_levels=4):
""" Draw a sphere """
cpSphere = bpy.ops.mesh.primitive_uv_sphere_add(segments=segments,ring_count=ring_count,size... | 5,308,206 |
def _iterations_implicit_bwd(res, gr):
"""Runs Sinkhorn in backward mode, using implicit differentiation.
Args:
res: residual data sent from fwd pass, used for computations below. In this
case consists in the output itself, as well as inputs against which we
wish to differentiate.
gr: gradients... | 5,308,207 |
def huber_loss_temporal(dvf):
"""
Calculate approximated temporal Huber loss
Args:
dvf: (Tensor of shape (N, 2, H, W)) displacement vector field estimated
Returns:
loss: (Scalar) huber loss temporal
"""
eps = 1e-8 # numerical stability
# magnitude of the dvf
dvf_norm... | 5,308,208 |
def _check_header(swagger: swagger_to.swagger.Swagger) -> List[Complaint]:
"""
Check whether the swagger header conforms to our style guide.
:param swagger: parsed Swagger spec
:return: the list of failed checks
"""
complaints = [] # type: List[Complaint]
if swagger.name != swagger_to.sna... | 5,308,209 |
def is_cnf1(filename):
"""
Brute force detection if a SRF file is using CNF1/CNF4 records
"""
max_header = 1024 ** 2
PROGRAM_ID = b'PROGRAM_ID\000'
cnf4_apps = set((b"solexa2srf v1.4",
b"illumina2srf v1.11.5.Illumina.1.3"))
if not is_srf(filename):
raise ValueEr... | 5,308,210 |
def handler(msg):
"""
Writes input argument back-out to the standard output returning input as
output.
Generated by: `SQL Server Big Data Cluster`
:param msg: The message to echo.
:type msg: str
:return: The input message `msg` as output `out`.
"""
print(msg)
out = msg
return ... | 5,308,211 |
def temperal_cross_validation(
model,
X: pd.DataFrame,
y: pd.Series,
num_split: int = 5,
xls_path: str = None, # type: ignore
shuffle: bool = True,
):
"""
Implement temporal cross-validation and calculate the error metrics
:param model: Trained model
:param X: predictors
:... | 5,308,212 |
def update_sidecar_json(bids_path, entries, verbose=None):
"""Update sidecar files using a dictionary or JSON file.
Will update metadata fields inside the path defined by
``bids_path.fpath`` according to the ``entries``. If a
field does not exist in the corresponding sidecar file,
then that field w... | 5,308,213 |
def safeFormatSipUri(uri, default_proto='sip', default_user='', default_port=5060, default_params={}):
"""
Given a SIP URI of questionable validity, parse out the good stuff, and fill in the rest
:param uri: URI to format / validate
:type uri: str
:param default_proto: de... | 5,308,214 |
def _key_for_namespace(namespace, app):
"""Return the __namespace__ key for a namespace.
Args:
namespace: The namespace whose key is requested.
app: The id of the application that the key belongs to.
Returns:
A db.Key representing the namespace.
"""
if namespace:
return db.Key.from_path(meta... | 5,308,215 |
def _get_remote_or_bail(repo, name):
"""Get remote by name.
name may be None.
_get_remote_or_bail(Repo, str) -> Remote
"""
remote_name = name
if not remote_name:
# Default to origin since it's the convention.
remote_name = 'origin'
try:
return repo.remote(remote_nam... | 5,308,216 |
def get_file_path():
"""
固有名詞のdfのpathのリスト
"""
p = Path(__file__).parent.resolve() / ".." / "toots_log"
file_paths = sorted([f for f in p.iterdir() if f.is_file()])
return(file_paths) | 5,308,217 |
def readinput(filename):
"""Read input file contents and return it as one '\\n' separated string
Arguments:
filename {str} -- name of the file to be read
"""
path = os.path.join(INPUT_PATH, filename)
with open(path) as file:
contents = "\n".join(file.readlines())
return contents | 5,308,218 |
def jpm_wide_to_long(df, set_date_name, set_index_name, set_values_name):
"""
:param df:
:param set_date_name:
:param set_index_name:
:param set_values_name:
:return:
"""
return (
pd.melt(
(df
.replace('-', np.NaN)
.rename(columns={'Unnamed:... | 5,308,219 |
def plot_cov_matrix(mat, color_range=None, color="pwhite", file_name=None):
"""plot the covariance matrix at full resolution using pixell plotting routines
Parameters
----------
mat: 2d array
the covariance matrix
color_range: float
the range of the plot
color: pixell colormap
... | 5,308,220 |
def RerangeEulerAngle(angle,deadzone,max1):
"""
Rerange the angles to [-1 - +1]
If one angle is in the deadzone it is set to 0
Angles are cubed for better control
Deadzone and max is configurable
max1 ---/
/:
/ :
... | 5,308,221 |
def inf_set_min_ea(*args):
"""
inf_set_min_ea(_v) -> bool
"""
return _ida_ida.inf_set_min_ea(*args) | 5,308,222 |
def _add_months(date, months):
"""
Add ``months`` months to ``date``.
Unfortunately we can't use timedeltas to add months because timedelta counts in days
and there's no foolproof way to add N months in days without counting the number of
days per month.
"""
year = date.year + (date.month +... | 5,308,223 |
def _remove_router_from_agent_callback(to_agent_id, router_id):
"""
Remove router from agent callback
"""
response = (yield)
_remove_router_from_agent_callback_body(to_agent_id, router_id, response) | 5,308,224 |
def allowgames(bot, cmd, params, user, room):
""" Independent command for changing permissions for games in this room.
Reserved for room owners. They can decide to allow games/activities in their room.
Args:
bot: PokemonShowdownBot, the instance of PokemonShowdownBot that called this function.
... | 5,308,225 |
def populate_process_options(option_manager):
"""
Configure Galaxy's options.
Use `option_manager` to populate process (handler, manager, web) sections
for Galaxy. Also adjust job_conf.xml to account for process setup.
"""
log.debug("Populating Galaxy process options")
app = option_manager.... | 5,308,226 |
def str_basis(n, m):
"""Return analytic expression for a given Zernike in LaTeX syntax"""
signed_m = int(m)
m = int(np.abs(m))
n = int(np.abs(n))
terms = []
for k in range(int((n - m) / 2) + 1):
coef = ((-1) ** k * factorial(n - k) /
(factorial(k) * factorial((n + m) / 2... | 5,308,227 |
def get_frr_config(conn_obj, device="dut"):
"""
API to get frr config from frr.conf file
Author: Sooriya G (sooriya.gajendrababu@broadcom.com)
:param conn_obj:
:param device:
:return:
"""
command = " sudo cat /etc/sonic/frr/frr.conf"
if device=="dut":
return utils_obj.remove_... | 5,308,228 |
def generate_kml():
"""Generate KML file from geojson."""
uuid = request.values.get('uuid', None)
campaign_name = request.values.get('campaign_name', None)
campaign = Campaign(uuid)
# Get json for each type.
types = campaign.get_s3_types()
if types is None:
return Response(json.dump... | 5,308,229 |
def bilinear_pooling(x):
"""
实现双线性池化,双线性池化出要使用在细粒度图像分类中
具体参考论文:Bilinear CNN Models for Fine-grained Visual Recognition
论文链接:http://vis-www.cs.umass.edu/bcnn/docs/bcnn_iccv15.pdf
传入x:普通分类网络的最后一个卷积层的输出
如果想要放置在池化层之后需要进行适当的修改
可以直接插入,最后一个卷积层与全连接层之前
"""
shape_detector = x.shape
print(... | 5,308,230 |
def loadData(paths, reduce_zero_measurement=1, side_image_prob=1, correction_dist=40.0, gauss_noise=0.01,
measurement_threshhold=0):
""" Loads the cvs files from all given paths.
Args:
paths: list of paths which contain the training data
reduce_zero_measurem... | 5,308,231 |
def processMultiline(string, removeEmpty=True, removeComments=False, doStrip=True):
"""split a string into lines, with some default post-processing. Caution if using removeEmpty=False and removeComments==True, it will fail if empty lines are present"""
lines = string.split('\n')
if doStrip:
lines = (f.strip()... | 5,308,232 |
async def get_callback_commands(callback_id: int, loaded_only: bool = False):
"""
Get an array of dictionaries of all the possible commands for the specified callback
:param callback_id: the id of the callback in question
:param loaded_only: specify this as True to only include commands currently loaded... | 5,308,233 |
def load(f):
"""Load from pickle_file.
Which will be used by the listener and generator modules in another
Machine(VM , Host).
"""
with open(f, 'rb') as pickle_file:
return loads(pickle_file.read()) | 5,308,234 |
def pip_upgrade_all(line):
"""Attempt to upgrade all packages"""
from pip import get_installed_distributions
user = set(d.project_name for d in get_installed_distributions(user_only=True))
all = set(d.project_name for d in get_installed_distributions())
for dist in all - user:
do_pip(["insta... | 5,308,235 |
def split_ZH(orgin_path, write_path):
"""
对中文数据集进行处理,删除<title>等标签信息
:param orgin_path: 原始文件路径
:param write_path: 写入文件路径
:return: None
"""
splited_data = []
print("Reading origin file and split...")
# 原始数据集
with open(orgin_path, encoding='utf8') as file:
line = file.readli... | 5,308,236 |
def locked_view_with_ip_exception_ipv6_subnet(request):
"""View, locked except for the configured IPv6-subnet."""
return HttpResponse('A locked view.') | 5,308,237 |
def nouvel_item(title: str, link: str, description: str, author: str,
pubDate: Dt) -> parse:
"""
Crée un nouvel item (article) dans un flux RSS.
Parameters
----------
title : str
Titre de l'item.
link : str
Lien vers l'item.
description : str
Contenu ... | 5,308,238 |
def run() -> bool:
"""Runs the test.
:param out_name: name of the output file.
:param err_name: name of the error information file.
:return: True, if all went well.
"""
res = True
catalog = get_catalog()
for algorithm in catalog:
single_file = catalog[algorithm... | 5,308,239 |
def create_walls(space, sprite_list):
""" Create side walls """
# Left wall
for y in range(96, 2000, constants.SPRITE_SIZE): # was 96 - constants.SPRITE_SIZE
# x = constants.SPRITE_SIZE / 4
x = -1200 - constants.SPRITE_SIZE
sprite = PymunkSprite("./images/tiles/brickBrown.png", x, y,... | 5,308,240 |
def parse_arguments() -> argparse.Namespace:
"""
Parse arguments from the command line using argparse.
:return: command line arguments
:rtype: argparse.Namespace
"""
parser = argparse.ArgumentParser(__file__)
parser.add_argument('base_conf', type=Path, help='Path to the base config')
pa... | 5,308,241 |
def test_human_gene_has_mouse_ortho_disease_annotation():
"""Test human Gene has Mouse Ortho Disease Annotation"""
query = """MATCH (gene:Gene)--(d:DiseaseEntityJoin)-[:FROM_ORTHOLOGOUS_GENE]-(ortho:Gene),
(d)--(do:DOTerm)
WHERE ortho.primaryKey = 'MGI:1919338'
... | 5,308,242 |
def remove_words(text, pattern):
"""
This function removes words based on those found in the pattern.
test: String of text
pattern: List of words to remove
returns: new string with specified words removed
"""
new_string = re.sub(r"\b(%s)\b" % "|".join(pattern), "", text, flags=re.... | 5,308,243 |
def res_dict_to_excel(resDict, xcelPath):
"""export result dictionary of panda dfs to excel
"""
with pd.ExcelWriter(xcelPath, engine="xlsxwriter") as writer:
for key in resDict:
try:
resDict[key].to_excel(writer, key)
except ValueError:
pass | 5,308,244 |
def is_valid_slice(frame, pos, pizza, constraints):
"""
Validates whether the slice is valid in terms of position on the pizza, ingredient composition and overlaps.
:param frame:
:param pos:
:param pizza:
:param constraints:
:return: True if the slice is valid. False otherwise.
"""
d... | 5,308,245 |
def filter_ignore_regions(y_true, y_score):
""" Filter ignore regions.
"""
y_true = np.array(y_true)
y_score = np.array(y_score)
# with ignore regions, i.e. ignore regions labeled with '2'
valid_indices = np.where(y_true <= 1)[0]
y_true = y_true[valid_indices]
y_score = y_score[valid_i... | 5,308,246 |
def uniform_ring(a):
"""Return the standard uncertainty for a uniform ring
:arg float a: the radius
Convert the radius of a uniform ring distribution ``a``
to a standard uncertainty
See reference: B D Hall, *Metrologia* **48** (2011) 324-332
**Example**::
>>... | 5,308,247 |
def sent_to_ids(sent, word2id, tokens, oov):
"""
sent is a string of chars, return a list of word ids
"""
if tokens is None:
tokens = sent_to_tokens(sent)
ids = []
for w in tokens:
if w in ['!', '.', ':', '?', '@', '-', '"', "'"]: continue
if w in word2id:
... | 5,308,248 |
def _get_valid_filename(string):
"""Generate a valid filename from a string.
Strips all characters which are not alphanumeric or a period (.), dash (-)
or underscore (_).
Based on https://stackoverflow.com/a/295146/4798943
Args:
string (str): String file name to process.
Returns:
... | 5,308,249 |
def detrend(flux,centroid):
"""
Detrend flux against centroid points. Returns normalized flux.
"""
for f in range(flux.shape[0]):
p, cov = scipy.optimize.curve_fit(flatfunc, centroid[f], flux[f])
flux[f] /= flatfunc(centroid[f], *p)
flux[f] /= np.median(flux[f])
return flux | 5,308,250 |
def keras_dropout(layer, rate):
"""
Keras dropout layer.
"""
from keras import layers
input_dim = len(layer.input.shape)
if input_dim == 2:
return layers.SpatialDropout1D(rate)
elif input_dim == 3:
return layers.SpatialDropout2D(rate)
elif input_dim == 4:
return... | 5,308,251 |
def main(): # pragma: no cover
"""
This continues to exist only as a sanity test for schema and relations.
"""
recreate_tables()
with cogdb.session_scope(cogdb.Session) as session:
run_schema_queries(session)
recreate_tables() | 5,308,252 |
def save_raster_memory(array, path):
""" Save a raster into memory """
example = gdal.Open(path)
x_pixels = array.shape[1] # number of pixels in x
y_pixels = array.shape[0] # number of pixels in y
driver = gdal.GetDriverByName('MEM')
dataset = driver.Create('',x_pixels, y_pixels, 1,gdal.GDT_... | 5,308,253 |
def cleaned_json_data(rs,excludes=['_id']):
"""清除非json格式化的字段"""
for r in rs:
keys = []
for k,v in r:
if not isinstance(v,(str,unicode,float,int,bool)):
keys.append(k)
for ex in excludes:
keys.append(ex)
for k in keys:
if r.has_... | 5,308,254 |
def seasonal_nll(y, pred_mean, pred_std, time):
"""
Negative log-likelihood (NLL) for each season.
:type y: array_like
:param y: The true observation.
:type pred: array_like
:param pred: The prediction.
:type y: array_like
:param y: The corresponding time array for the target season.
... | 5,308,255 |
def distribution_filter_for(bijector):
"""Returns filter function f s.t. f(dist)=True => bijector can act on dist."""
if isinstance(bijector, tfb.CholeskyToInvCholesky):
def additional_check(dist):
return (tensorshape_util.rank(dist.event_shape) == 2 and
int(dist.event_shape[0]) == int(dist... | 5,308,256 |
def EI(mu, std, **kwargs):
"""
Expected improvement acquisition function
INPUT:
- mu: mean of predicted point in grid
- std: sigma (square root of variance) of predicted point in grid
- fMax: observed or predicted maximum value (depending on noise p.19 Brochu et al. 2010)
- epsilon: trade-o... | 5,308,257 |
def mail_pico_eth(porcentaje):
""" Called by detectar_picos() sendas a mail """
if porcentaje > 0:
resumen = "Ethereum is on a quick rise, now at U$S "
else:
resumen = "Ethereum is on a quick dip, now at U$S "
resumen += str(persistence.traer_ultimo_precio_eth()) + " , take a look!\n\n\... | 5,308,258 |
def test_mtc_decorator():
"""Test the MTC decorator."""
@utils.mtc(AUTHCRYPT_AFFIRMED, AUTHCRYPT_DENIED)
def mtc_test(msg):
assert msg
msg = Message({
'@type': 'doc_uri/protocol/0.1/test',
'@id': '12345',
'content': 'test'
})
msg.mtc = MessageTrustContext(AUTHCRY... | 5,308,259 |
def get_raw_html(chunk_id, doc_id):
"""
Given a chunk_id and doc_id, return the raw html contained in the document
If the chunk was not found when generating chunk_map, return None
:param chunk_id: string
:param doc_id: int
:return: dictionary or None
"""
path = PATH
chunk_path = os.... | 5,308,260 |
def merge(callgrind_files, srcs):
"""Calls callgrind_annotate over the set of callgrind output
|callgrind_files| using the sources |srcs| and merges the results
togsophy."""
out = ''
for file in callgrind_files:
data = subprocess.check_output(['callgrind_annotate', file] + srcs)
out += '%s\n%s\n' % (d... | 5,308,261 |
def test_parse_args_version(capfd):
"""
Should print the program name and version
:param capfd:
:return:
"""
with pytest.raises(SystemExit):
get_args(['-V'])
out, err = capfd.readouterr()
# https://bugs.python.org/issue18920
if sys.version_info >= (3, 4):
assert out ... | 5,308,262 |
def parse_output(filename):
"""
This function parses the output of a test run.
For each run of the test, the program should print the following:
## ID: result: [OK|FAIL]
## ID: cycles: N_CYCLES
## ID: instructions: N_INSTR
## ID: Key: Value
Multiple runs are allowed.
... | 5,308,263 |
def main():
"""Main function of this program."""
# Default arguments.
name = "Stranger"
# If no argument was provided, print the usage and exit.
if len(sys.argv) == 1:
print(USAGE)
sys.exit(0)
# Handle commandline arguments.
try:
opts, args = getopt.getopt(sys.argv[1:], 'hn:', ["help", "name="])
except ge... | 5,308,264 |
def get_username_existence_validation_error(username, api_version='v1'):
"""Get the built-in validation error message for when
the username has an existence conflict.
:param username: The proposed username (unicode).
:param api_version: registration validation api version
:param default: The messag... | 5,308,265 |
def MuellerMatrixThomson(azimuth, polar):
"""Mueller matrix for Thomson scattering
Args:
azimuth(num): scattering azimuth (degree)
polar(num): scattering angle (degree)
Returns:
array: Mueller matrix (4x4)
"""
costh = np.cos(np.radians(polar))
cossq_polar = costh ** 2
... | 5,308,266 |
def extract_meta_data(video_file_name, output_file=meta.txt, *args, **kwargs):
"""
#TODO
- Fill this with the documentation of the code. i.e. the docstring.
- Accomadate for the different video file types such as mp4, mkv, raw, etc.
- Add arguments to accomadate, if needed.
- Add requir... | 5,308,267 |
def _create_diagnostics(lang_temp, doc):
"""Creates diagnostics from TextXError objects."""
return [
Diagnostic(_get_diagnostic_range(err), _get_diagnostic_message(err))
for err in validate(lang_temp, doc.source)
] | 5,308,268 |
def revealed_attrs(proof: dict) -> dict:
"""
Fetches revealed attributes from input proof, returns dict mapping attribute names to [decoded, encoded] values,
for processing as further claims downstream
:param: indy-sdk proof as dict (proving exactly one claim)
:return: dict mapping revealed attribu... | 5,308,269 |
def sample_from_scipy_distribution(dist, size, **kwargs):
""" use a given distribution to and extract size samples from it."""
if kwargs:
return dist.rvs(**kwargs, size=size)
return dist.rvs(size=size) | 5,308,270 |
def cir_RsTLsQ_fit(params, w):
"""
Fit Function: -Rs-TLsQ-
TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance (Q)
See more under cir_RsTLsQ()
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params['Rs']
L = params['L']
Ri = pa... | 5,308,271 |
def test_block_structure_scalar_validity(n_rods):
"""
This function is testing validity of scalars. It is been tested that
for scalar variables, if the block structure memory and values are
set correctly and rods that belong to rod structure share the memory
with block structure.
Parameters
... | 5,308,272 |
def calculator():
""" Returns a Calculator instance """
print('calculator fixture')
return Calculator() | 5,308,273 |
def http_form_post_message(message, location, relay_state="",
typ="SAMLRequest", **kwargs):
"""The HTTP POST binding defines a mechanism by which SAML protocol
messages may be transmitted within the base64-encoded content of a
HTML form control.
:param message: The message
... | 5,308,274 |
def test_spatial_smoothing_xesmf_reduce_spatial_dims_MPI_curv(
PM_da_control_3d_full,
):
"""Test whether spatial dimsizes are properly reduced."""
da = PM_da_control_3d_full
step = 5
actual = spatial_smoothing_xesmf(
da,
d_lon_lat_kws={"lon": step},
)
expected_lat_s... | 5,308,275 |
def iterate_dirs(input_dir, output_dir):
"""
Iterate over all subdirectories and import every genome.
"""
for subdir in os.listdir(input_dir):
logging.info('generating import data for %s' % subdir)
# Subdirectory must match GCF accession ID format
if not re.search(r'GCF_\d\d\d\d\... | 5,308,276 |
def ensureUser():
"""Returns the current user account and associated user object.
"""
account = accounts.getCurrentAccount()
if not account:
account = users.User(email='test@example.com')
user_properties = {
'key_name': 'test',
'link_id': 'test',
'account': account,
'name': 'Tes... | 5,308,277 |
def get_json(file_name):
"""
Function for getting JSON data of Object
"""
global zipname
with ZipFile(zipname, 'r') as zip:
with zip.open(file_name) as file:
data=file.read()
data=data.decode('utf-8')
data=data.strip('\n')
#colorful_data=highlight(data, lexers.JsonLexer(), formatters.Te... | 5,308,278 |
def _read_eleme(f, label_length):
"""Read ELEME block data."""
fmt = block_to_format["ELEME"]
eleme = {"elements": {}, "elements_order": []}
line = f.next()
if not label_length:
label_length = get_label_length(line[:9])
label_format = "{{:>{}}}".format(label_length)
while True:
... | 5,308,279 |
def compress_errorbar_cxx(v, e, errdigits=2):
"""Temporary plug-hole measure to get python compress errorbars.
Using a small C++ executable to perform the task."""
#perl_lib_dir = sh.getenv("WORK_DIR", "HOME") + "/scripts"
return sh.pipe_out((COMPRESS_ERRORBAR_EXE, str(v), str(e), str(errdigits))).strip() | 5,308,280 |
def get_make_flags(user_args=None):
""" Get compiler and flags from a `make` dry run, and return them.
"""
# These flags don't make since for general snippet compiling.
# The ColrC dir is already taken care of, and -c/-o will be used when
# get_gcc_cmd() is called.
ignore_flags = {'-c', '-o', '-... | 5,308,281 |
def additive_weight_decay(weight_decay: float = 0.0) -> GradientTransformation:
"""Add parameter scaled by `weight_decay`, to all parameters with more than one dim (i.e. exclude ln, bias etc)
Args:
weight_decay: a scalar weight decay rate.
Returns:
An (init_fn, update_fn) tuple.
"""
d... | 5,308,282 |
def compute_heads_importance(
args, model, eval_dataloader, compute_entropy=True, compute_importance=True, head_mask=None, actually_pruned=False
):
""" This method shows how to compute:
- head attention entropy
- head importance scores according to http://arxiv.org/abs/1905.10650
"""
# P... | 5,308,283 |
def partitionwise_layer(
func: Callable,
name: str,
*args: Any,
**kwargs: Any,
) -> Blockwise:
"""Create a partitionwise graph layer.
Parameters
----------
func : Callable
Function to apply on all partitions.
name : str
Name for the layer.
*args : Any
Arg... | 5,308,284 |
def write(space, fd, w_data):
"""Write a string to a file descriptor. Return the number of bytes
actually written, which may be smaller than len(data)."""
data = space.charbuf_w(w_data)
while True:
try:
res = os.write(fd, data)
except OSError as e:
wrap_oserror(space... | 5,308,285 |
def resize(image,
label,
ratio,
image_method='bilinear',
label_method='nearest'):
"""Rescale image and label to the same size by the specified ratio.
The aspect ratio is remained the same after rescaling.
Args:
image: A 2-D/3-D tensor of shape `[height, width, chan... | 5,308,286 |
def get_init_fn(checkpoint_dir, continue_oncheck=False):
"""Loads the NN"""
if checkpoint_dir is None:
if continue_oncheck:
return None
else:
raise ValueError('No checkpoint provided, using --checkpoint_dir')
checkpoint_path = tf.train.latest_checkpoint(checkpoint_di... | 5,308,287 |
def _genUniqueModuleName(baseModuleName):
"""The calling code is responsible for concurrency locking.
"""
if baseModuleName not in sys.modules:
finalName = baseModuleName
else:
finalName = ('cheetah_%s_%s_%s'%(baseModuleName,
str(time.time()).repl... | 5,308,288 |
def pca(X):
"""Runs Principal Component Analysis on dataset
:param X: Features' dataset
:type X: numpy.array
:returns:
- U - eigenvectors of covariance matrix
- S - eigenvalues (on diagonal) of covariance matrix
:rtype:
- U (:py:class: numpy.array)
- S (:py:class: ... | 5,308,289 |
def load_test_data(apiobj):
"""Pass."""
apiobj.TEST_DATA = getattr(apiobj, "TEST_DATA", {})
if not apiobj.TEST_DATA.get("fields_map"):
apiobj.TEST_DATA["fields_map"] = fields_map = apiobj.fields.get()
if not apiobj.TEST_DATA.get("assets"):
apiobj.TEST_DATA["assets"] = apiobj.get(max_ro... | 5,308,290 |
def stochasticity(peaks):
""" Generate casually chosen arbitrary peak values based on originals
set by the user """
# in future, stochasticity percentage can be added to th QS parameters
# for users to define
stoch_percent = random.randint(70, 85) # over 70, below 85 would be good
orig_peaks =... | 5,308,291 |
def delete_family(adapter, family_id):
"""Delete a case object from the database"""
case = {'case_id': family_id}
adapter.delete_case(case) | 5,308,292 |
def register_multi_sampler(name):
"""
A decorator with a parameter.
This decorator returns a function which the class is passed.
"""
name = name.lower()
def _register(sampler):
if name in _registered_multi_sampler:
raise ValueError("Name {} already chosen, choose a different ... | 5,308,293 |
def overview():
"""Shows an overview page"""
# get a list of clients for the side bar
clients = redshift.get_sponsored_client_list(cache)
# get a list of all possible locales and countries
locales = redshift.get_all_locales(cache)
countries = redshift.get_all_countries(cache)
# get the pa... | 5,308,294 |
def get_attention_logger(file_path):
""" Make python logger """
logger = logging.getLogger("attention")
log_format = '%(message)s'
formatter = logging.Formatter(log_format)
file_handler = logging.FileHandler(file_path)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
... | 5,308,295 |
async def test_unload_config_entry(opp, device_factory):
"""Test the binary_sensor is removed when the config entry is unloaded."""
# Arrange
device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100})
config_entry = await setup_platform(opp, SENSOR_DOMAIN, devices=[device])
... | 5,308,296 |
def _acquire_lease_memcache(cache_arn, correlation_id, steps, retries, timeout=LEASE_DATA.LEASE_TIMEOUT):
"""
Acquires a lease from memcache.
# https://www.quora.com/What-is-the-best-way-to-implement-a-mutex-on-top-of-memcached
# http://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html... | 5,308,297 |
def transformer_tok2vec_v2(
name: str,
get_spans,
tokenizer_config: dict,
transformer_config: dict,
pooling: Model[Ragged, Floats2d],
grad_factor: float = 1.0,
) -> Model[List[Doc], List[Floats2d]]:
"""Use a transformer as a "Tok2Vec" layer directly. This does not allow
multiple componen... | 5,308,298 |
def uptime(values, router, logger):
""" Send authenticated message to get the system uptime for WAN and LAN """
if values['help']:
print()
print('hitron uptime [options]')
logger.log_columns([' ',
'--address',
'The IP address to reach your device. Defaults... | 5,308,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.