content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
from typing import Optional
def links(
items: List[Component],
label: Optional[str] = None,
inline: Optional[bool] = None,
width: Optional[str] = None,
) -> Component:
"""Create a collection of links.
Args:
items: The links contained in this gro... | a8823fc713047928c65955b7acff12ad4745c7e0 | 79,247 |
def get_stats(tp, fp, tn, fn):
"""
Computes performace measures using the correctness measures returned by
check_preds()
Parameters:
-----------------
tp: number of true positive predictions returned by check_preds()
fp: number of false positive predictions returned by check_preds()
tn... | 93d9c943de9d1485bec72047a61af74872920b23 | 79,248 |
def make_tokens(binary_parse):
"""
Convert a binary parse: ( ( The men ) ( ( are ( fighting ( outside ( a deli ) ) ) ) . ) )
to [The men are fighting outside a deli .]
@returns tuple
"""
return tuple(binary_parse.replace("(", "").replace(")", "").split()) | a76346b7df225969d2859f792dfe9131c92be533 | 79,249 |
import re
def pre_precess(msg: str) -> str:
"""对消息进行预处理"""
# 去除网址
msg = re.sub(r"https?://[\w/:%#\$&\?\(\)~\.=\+\-]+", "", msg)
# 去除 \u200b
msg = re.sub(r"\u200b", "", msg)
# 去除 emoji
# https://github.com/carpedm20/emoji
msg = replace_emoji(msg)
return msg | f08e28efcb492866b39d875781cd7fd31c4198ba | 79,250 |
def random_translation(max_offset=10):
""" Returns a random translation vector. """
return np.random.uniform(low=-max_offset, high=max_offset, size=3) | 3fa4d1f49067a0318c8d3a4b4ade119307fbacf7 | 79,251 |
def load_astropy_time_dataset(h_node,base_type,py_obj_type):
"""
loads astropy time
Parameters
----------
h_node (h5py.Dataset):
the hdf5 node to load data from
base_type (bytes):
bytes string denoting base_type
py_obj_type :
final type of restored dtype
Retur... | 78fa7c0f65106d8f56446703e12c9c4748bc2a18 | 79,252 |
def encrypt_passwd2(passwd):
"""Encrypt password with sha256"""
return sha256(passwd.encode('utf-8') + salt256).hexdigest() | 521506c7c9eddc60dea18c9d8cc8a010dfa59b34 | 79,253 |
from typing import Tuple
def terminator(identity: str, sequence: str, **kwargs) -> Tuple[sbol3.Component, sbol3.Sequence]:
"""Creates a Terminator Component and its Sequence.
:param identity: The identity of the Component. The identity of Sequence is also identity with the suffix '_seq'.
:param sequence:... | 449ae4ef02e19bd596b5c9f8ea2160f3921abdb2 | 79,255 |
from typing import Iterable
def get_nnz_union(mats: Iterable["sp.csr_matrix[float]"]) -> "np.ndarray[int]":
"""
Given a list of sparse matrices, return the union of their nonzero
coordinates, in the form of a 2D numpy array with 1 coordinate per
row, with 2 columns representing coordinates rows and co... | de09975b65f25267ad66dc4482054b06af722f4e | 79,256 |
from datetime import datetime
import string
import random
def interpolate(points, step_type="meters", step_pr=10):
""" Interpolates points
Keyword Arguments:
points {GeoDataFrame} -- A GeoDataFrame containing the track points
step_type {string} -- either "meters" or "seconds"
step_pr ... | e258ca7f83f7764fb44f9b06744f79f061c20d9d | 79,257 |
def polyfit(dates, levels, p):
"""Returns tuple of polynomial object and any date shift that represents the
water level of a station over time."""
t = matplotlib.dates.date2num(dates) #time
p_coeff = np.polyfit(t - t[0], levels, p)
poly = np.poly1d(p_coeff)
return poly, t[0] | ab72c36e20c6cdb6a828c001e64f1e875e01e87e | 79,258 |
def craft_packet(pkt):
"""craft a new/modified packet and only transfer some information
pkt: scapy network packet
returns: newpkt: newly created scapy network packet
"""
newpkt = Ether()/\
IP(src=pkt[IP].src, dst=pkt[IP].dst)/\
UDP(sport=pkt[UDP].sport, dport=pkt... | 2558deef999589a8ecd24eaf5901330a8de7e596 | 79,260 |
def get_actress_from_html(html, s):
"""Return a list of actresses from the html
actresses are strings that are formatted the way we can put them straight in the name"""
a_list = []
split_str = '<span class="star">'
# 1 to end because first will have nothing
for section in html.split(split_str)[... | f635509e1f2084bb98c5f3928cb4517d3fad0eba | 79,262 |
from typing import List
import aiohttp
async def map_rank(args: List[str], token: 'Player', _):
"""
SUPER UGLY CODE PORT FROM PEP.PY CMYUI !!!!! PREPARE YOUR EYES FOR BLOWN UP
I warned!
"""
if args:
if not args[0] in ['rank', 'love', 'unrank']:
return '-_-'
if l... | aa2fbea362e71f4698cd9a7395cacab59ffa4ea8 | 79,263 |
def _get2DOverlapBox(box1, box2):
"""Get 2D box where the two boxes overlap"""
result = {
'left': max(box1['left'], box2['left']),
'top': max(box1['top'], box2['top']),
'right': min(box1['right'], box2['right']),
'bottom': min(box1['bottom'], box2['bottom'... | 5c382ee3a651c24e812f43fdac9f82949361cf96 | 79,264 |
def get_dump_period():
"""How frequently should we dump?"""
return 86400 | df0053dd149e30e5d25522747e1ffb7bd98695a8 | 79,266 |
def greater(x, y):
"""Element-wise '>' (greater).
Warning: If one or both of the operators have variances (uncertainties)
there are ignored silently, i.e., comparison is based exclusively on
the values.
:param x: Left input.
:param y: Right input.
:raises: If the units of inputs are not th... | 3ac359f85ef099f17cd0b68da5d32d2b3e4f852b | 79,267 |
def squares_won(microboard, player):
"""
Return the number of squares won by the player on the microboard.
"""
return sum(map(lambda line: line.count(player), microboard.export_grid())) | ecbef6669badfb9ef597194892126ae452f01b2c | 79,268 |
async def request_user_middleware(app, handler):
""" Adds authorized user to each request object """
async def middleware(request):
request.session = await get_session(request)
request.user = None
user_id = request.session.get("user")
if user_id is not None:
request.... | 849cf29595b909318948378345f35e87633068ad | 79,269 |
def mask_iou_dice(maska, maskb):
"""IoU and Dice for mask"""
maska = maska > 0
maskb = maskb > 0
inter_area = sum(sum(np.logical_and(maska, maskb)))
maska_area = sum(sum(maska))
maskb_area = sum(sum(maskb))
iou = inter_area / float(maska_area + maskb_area - inter_area)
dice = (2 * inte... | dd5b581d5355d9e7d03a5b86b34a3c554055d321 | 79,271 |
def get_ratings(data):
"""Ratings of all the episodes of all the seasons"""
episodes = data['episodes']
ratings = {}
for season in episodes:
ratings[season] = collapse(episodes[season])
return co.OrderedDict(sorted(ratings.items())) | 14028cd2864a029742c5afc010f927381d70e327 | 79,273 |
def Jolanta_GTO_H(alphas, Ns, param):
"""
Hamiltonian matrix in the uncontracted GTO basis set
Parameters
----------
alphas : np.array of GTO exponents
Ns : np.array of normalization constants
param : (a, b, c): parameters of the Jolanta potential
Returns 3 numpy matrices
-----... | 83462f1b3483d44dcda6d5888f014723637fe1f4 | 79,274 |
def least_distance_only(annotation, new_annotations):
"""Condition function to keep only smallest distance annotation per image
Args:
annotation: Current annotation being examined
new_annotations: Dict of new annotations kept by image_name
Returns: True if annotation image is not yet in ne... | d9feeaac699a2527f43c96c65a6d61f4bfe1a2a9 | 79,275 |
import ctypes
from re import T
def initCamera(dll_path, xml_path, qtWidget, manual=False):
"""初始化相机, 传入qt的窗口handle
返回ic对象
"""
# ic 对象初始化
ic = ctypes.cdll.LoadLibrary("./tisgrabber_x64.dll")
declareFunctions(ic)
ic.IC_InitLibrary(0)
# 打开相机
if manual:
camera_handle = ic.... | 3cd4f7e05a879b32937475ef1082f4ec85136565 | 79,276 |
def maskIntersection(ip1,ip2):
""" Intersection of 2 images by their masks excluding zero pixels """
ip1Temp = ip1.duplicate()
ip1Temp = ip1Temp.convertToShort(0)
ip2Temp = ip2.duplicate()
ip2Temp = ip2Temp.convertToShort(0)
imp1 = mask(ip1Temp, 1, ip1Temp.maxValue())
imp2 = mask(ip2Temp, 1, ip2Temp.maxValue())... | d7f901fd2f2af9d9dee495406d6f1fe5c5b4fe2d | 79,278 |
def extract_card_name(response, data_block_id=None):
"""カード名を抽出する.
データブロックからカード名を取得する.
:param response: レスポンスオブジェクト
:param data_block_id: データブロックのID
:return: カードの名前
"""
# データブロックIDが指定されて居ない場合は探索をする
data_block_id = data_block_id or search_block_id(response, "データ")[0]
return response... | 6ba58339b2ac89dcbd299498611d0eb39e1e1dfa | 79,279 |
def nearmask_geo(array, ddsx, ddsy, XA, tol):
"""
Given an 2D array find nerest point to XA defined as [x,y]
ddsx and ddsy are np.arrays containing information about row and
columns. Mininum distance is calucalted using the Haversine formula
It masks the array before
"""
iy, ix = np.where(a... | fcb886035ba0fa8ed2d52708091e24e5b1b74854 | 79,280 |
def query_db_python(targname, filt, exp_length, flashlvl, ctecorr, aperture,
epoch, proposid='14012'):
"""
Alternative to :func:'read_python_slope_file'
Parameters:
targname : string
Name of the target cluster.
filt : string
Name of the filter.
exp_leng... | 8781e0cbf90a6106aa6686aa2dfcc24fdc9f7ba6 | 79,281 |
def as_iterable(iterable_or_scalar):
"""Utility for converting an object to an iterable.
Parameters
----------
iterable_or_scalar : anything
Returns
-------
l : iterable
If `obj` was None, return the empty tuple.
If `obj` was not iterable returns a 1-tuple containing `obj`.
Ot... | 88faae2df79c173eea28bf4fed071c526673ab2b | 79,282 |
from typing import List
def get_all_filters_from_project(pid: int) -> List[Filter]:
"""
Gets all filters in the project.
:param pid: The projects id.
:return: A list of all the project's filters.
"""
p = get_project_by_id(pid=pid)
assert p is not None
return p.filter_set.all()[::1] | 3f55e579d1a0f4b9f9017daba522cb1112bb8e1e | 79,283 |
def int32(params):
"""Define a string parameter to be used within this YAML file"""
return {params.name: params.value} | 463e3ae0af6a9a5a0c999ba08f6c77941c030e31 | 79,284 |
from datetime import datetime
def login():
"""Login user if not already logged in."""
form = UserPasswordForm()
if form.validate_on_submit():
# For convenience we create users while they login
user = User.query.filter_by(username=form.username.data).first()
if user:
if user.i... | 09607bfc58a6f2ffe971231f1935a29db26695f7 | 79,285 |
def floor_angle(attr_a):
"""Create math_FloorAngle-node to get rounded down value of given angle attr.
Args:
attr_a (NcNode or NcAttrs or string): Maya node attribute.
Returns:
NcNode: Instance with node and output-attribute(s)
"""
return _create_operation_node('floor_angle', attr_... | 57f9424d72b43c3f1663ae4b4bea739978fc7e80 | 79,286 |
def load_image(path):
"""Load the specified image and return a [H,W,3] Numpy array.
"""
# Load image
image = skimage.io.imread(path)
# If grayscale. Convert to RGB for consistency.
if image.ndim != 3:
image = skimage.color.gray2rgb(image)
# If has an alpha channel, remove it for cons... | f059812c0d5a1e786f6c6f3159dd1619387952f0 | 79,287 |
import json
def guest_services_set(token, instance_uuid, host_name, services):
"""
Set guest services
"""
url = token.get_service_url(PLATFORM_SERVICE.GUEST)
if url is None:
raise ValueError("OpenStack Guest URL is invalid")
api_cmd = url + "/v1/instances/%s" % instance_uuid
api_... | affb1bbf5ffa9fc88831a007bec19abf55e03c1b | 79,288 |
import requests
def get_lessons_from_n_to_m(from_n, to_m, current_token):
"""
:param from_n: starting lesson id
:param to_m: finish lesson id
:param current_token: token given by API
:return: json object with all existing lessons with id from from_n to to_m
"""
api_url = 'https://stepik.or... | 194f55806b3b1d252f0fb0d556032b916969523b | 79,289 |
def snak(datatype='', value='', prop='', snaktype='value'):
"""Create and return a snak (dict)"""
if datatype in ['', 'string', 'math', 'external-id', 'url', 'commonsMedia',
'localMedia', 'geo-shape', 'musical-notation', 'tabular-data']:
datavalue = {
'value': value,
... | c4378c165836e76f5339a5e76bb9a5e80b1a2860 | 79,290 |
def _get_project_rule(name, mode, resource_type, resource_ids, binding_dict):
"""Helper function to build a rule dictionary."""
# Use a stable ordering for roles to make comparing config diffs easier.
rule_bindings = [{
'role': role,
'members': binding_dict[role] or [_NOBODY],
} for role in sorted(b... | 6eb31a6a20823807577232c67edf5aed721a2bc6 | 79,291 |
def sso_test(request):
"""
Exposes a simple resource that requires authentication,
so that we can kick-off the SAML conversation.
"""
tv = {
'session': request.session,
}
return render_to_response('saml2sp/sso_test.html', tv) | bf7defee44fe788cf51504330ad6199c8fc32542 | 79,292 |
from unittest.mock import patch
def callable_http_patch():
"""This intented to stop some http requests inside some tests."""
return patch('plexapi.server.requests.sessions.Session.send',
return_value=MagicMock(status_code=200,
text='<xml><child></child></xml>')) | 620d880714dbae60da8f267cd98eef87c4b7bbd4 | 79,293 |
def not_worth_correcting(comment, error_regex):
"""True if our particular grammar issue isn't the commenter's main concern..."""
if comment.body == comment.body.lower(): # Everything is in lower case; it may be a stylistic choice
return True
if line_containing_regex(comment.body, error_regex).start... | 1565e78a57452a5ddde97423710986f929b81aff | 79,294 |
def poligon_non_convex_from_Points( points_li ):
"""
Create a random (no convex) poligon from the points
The algorithm returns a polygon creatated from the points, the
non convex part it is not always guaranteed.
:param list points_li: list of shapely.geometry.Point
:returns shapely.grometry.P... | 1763ad6aeb3b1e72407436a562498b78dbe80b40 | 79,295 |
import re
def read_newick(fh):
"""Read tree from a Newick-format file.
Parameters
----------
fh : file handle
Newick tree file.
Returns
-------
dict
Taxonomy tree.
Raises
------
ValueError
Missing internal node ID.
ValueError
Found non-uni... | fc127027b6fe5f00ee9f473c21727ac3f2f89481 | 79,296 |
import json
def federation(endpoint, request, return_mimetype, request_type='POST'):
"""
Federate the queries by iterating through the peer list and merging the
result.
Parameters:
===========
endpoint: method
Method of a datamodel object that populates the response
request: strin... | 424e16da6084f4cded8f87e08915fd1a3789b55c | 79,297 |
def __read_class_labels(classes_file):
"""
Returns a function -> class-label dictionary. Only supports single class labels.
:param functionclasses_file: A file with the format function-name class-label
:return: Dictionary of the form {fn: class}
"""
classes = {}
with open(classes_file, 'r') ... | 0962f499c1f75d4049c16aafe4922f4d2f843bc7 | 79,298 |
import torch
def predict(net, model_path, sample_image_path, use_cuda=False):
"""
Predicts output given a trained neural net model and an image.
Args:
net -> PyTorch neural network object
model_path -> return value from get_model_name()
sample_image_path -> return value from image... | 795ac05130346b17085d3f47b3fb844e22d1b4db | 79,300 |
def callable_for_test(*args, **kwargs):
"""A helper function for test when formatter is a complex callback function."""
return '{};{}'.format(';'.join([str(i) for i in args]),
';'.join(['{}:{}'.format(k, v) for k, v in kwargs.items()])) | 5c00bdf7f7b47129a1489eedd5a59280c1ba5582 | 79,301 |
import json
def go_check():
"""
Load data from ``package.json``file.
``postbump`` executex after the version is bumped.
:return: new version to replece
:rtype: str
"""
path_to_file = HERE / "package.json"
with open(path_to_file) as dt:
data_package = json.load(dt)
new_vers... | 31fefa8a46e26ee9de65e06831a27ab8ffc71403 | 79,302 |
def function_sum(function_1, function_2):
""" Returns the addition of 2 functions """
def summed_function(*args, **kwargs):
return function_1(*args, **kwargs) + function_2(*args, **kwargs)
return summed_function | 72b1f45694291b3aefc3f68df124359d10d018ff | 79,303 |
from typing import List
def get_players_valuation(agents: List[Agent], c : List[float]):
"""
this function calculates for each player its valuation of a discrete cut of the cake.
for each player, it calulates the valuation of each item.
:param agents: list of players
:param c: list of item, the di... | 96099b9c18c462143fe705440620b1c679af910f | 79,304 |
def getClasses():
"""
Finds the user defined classes in the code
:return: A dictionary with the user classes code:
{'name': str(line\nline\n...)}
"""
raw_code = getRawCode()
classes = {}
for block in raw_code:
lines = block.split('\n')
# Look for classes in the b... | 6e987a78da1dfbebd15d4aa540e8de57321c8eac | 79,305 |
import re
def _isContained (version, versionRangeExpr):
""" Compares version against given version range in order to see if
it matches given criteria.
"""
version = re.sub (r'\s+', '', version)
versionRangeExpr = re.sub (r'\s+', '', versionRangeExpr)
if version == versionRangeExpr:
return True
vers... | 539aaa717d5823b6f49c468e3f79f37a8c67db9a | 79,306 |
from puma.attribute.attribute.per_scope_value_scoped_attribute_value_factory import PerScopeValueScopedAttributeValueFactory
from re import T
from typing import cast
def per_scope_value(value: T) -> T:
"""
Return an ScopedAttributeValueFactory that sets the attribute to the given value at the beginning of eac... | 301e19698bba7d1cba615398664466bc974021af | 79,307 |
from typing import DefaultDict
def test_map_nested_value() -> None:
"""
map_nested_value should map functions on supported container types:
list, dict, set, tuple, nested tuple.
map_nested_value should not map functions to other types currently
"""
def func(value) -> str:
return str(... | 1846764134eb4b3dace77bd74a246346704d5690 | 79,308 |
def format_release(release: dict) -> dict:
"""
Format a raw release record from GitHub into a release usable by Virtool.
:param release: the GitHub release record
:return: a release for use within Virtool
"""
asset = release["assets"][0]
return {
"id": release["id"],
"name... | 06cf5f86b6274759fa12674fbedcd041278894a3 | 79,309 |
def get_references():
"""Collect all reference in the scene.
:rtype: list of pm.nt.Reference
"""
# exclude reference list
exclude_list = ['sharedReferenceNode']
# get all editable reference available
reference_list = pm.ls(type = 'reference', editable = True)
return [o for o in referenc... | f2898d15909a7c2e215d5c6bb920934f11ab1076 | 79,310 |
import math
from typing import Tuple
from typing import Mapping
from typing import Union
def get_xresnet_unet(in_channels: int,
image_size: Tuple[int, int],
downsampling_factors: Mapping[str, int],
hidden_channels: int,
embeddings_dim... | 838a560959d1b47ce4c7d32ceeb060254439d0db | 79,311 |
def lat_lon_to_index(lat_source,
lon_source,
lat_mapped,
lon_mapped):
"""
@ author: Shervan Gharari
@ Github: https://github.com/ShervanGharari/candex
@ author's email id: sh.gharari@gmail.com
@lic... | be761646eeb1d221815291febc186c78b67996ed | 79,312 |
def get_file_uploads():
"""
alias function
:return:
"""
return get_brain_files() | 9b9ab6a61859f4a09f370e6e3e1bd1191e1b65c5 | 79,313 |
def _load_matlab_result_pywt_coeffs(data, wavelet, mmode):
""" Load the precomputed result.
"""
N = len(data)
ma_key = '_'.join([mmode, wavelet, str(N), 'ma_pywtCoeffs'])
md_key = '_'.join([mmode, wavelet, str(N), 'md_pywtCoeffs'])
if (ma_key not in matlab_result_dict) or \
(md_key n... | 69aa64a1ac05c80c6758834d3af098fd63904764 | 79,314 |
def create_matrix_profile(fc, cc, kc):
"""Create the camera matrix and distortion profile.
Take in the focal lengths, principle points, and distortion coefficients
and return the camera matrix and distortion coefficients in the form
OpenCV needs.
Takes:
fc - the x and y focal lengths [focal... | f5e7cf2fd5fe60c8d06b907c124658d4b66a90b0 | 79,315 |
def global_species_completeness(tsn, as_dataframe=False, **kwargs):
"""
Get global species completeness from tsn
:param tsn: (int) TSN for a taxonomic group
:param as_dataframe: (bool) specify return type, if pandas is available
:param \*\*kwargs: Curl options passed on to `requests.get`
U... | f32bd84b3d8f93617d2d29e71054e516a780eac8 | 79,316 |
def generate_ticket_pdf(request, order):
"""
Generates a pdf of the tickets in a given order
Parameters:
request (Request): The request object
order (Order): The order to generate tickets for
Returns:
A byte buffer of the generated pdf
"""
# Get tickets for this order
tickets ... | 0a0c9865950fa52cd69a23089ff891af19547c75 | 79,317 |
def FetalInferences(FetalDetails):
"""
baseline value,accelerations,fetal_movement,uterine_contractions,light_decelerations,severe_decelerations,
prolongued_decelerations,abnormal_short_term_variability,mean_value_of_short_term_variability,
percentage_of_time_with_abnormal_long_term_variability,mean_val... | 26e1da4cc7abe24563a33a673ca7d4ad8bc42389 | 79,318 |
def _get_column_visualization_items(
workflow: Workflow,
column: Column,
):
"""Get the visualization items (scripts and HTML) for a column.
:param workflow: Workflow being processed
:param column: Column requested
:return: Tuple stat_data with descriptive stats, visualization scripts and
... | a561606037c9646a03d869ce00ff6b20a1ed30c1 | 79,319 |
def outliers_dbscan(data=None,
min_samples=5,
eps=0.5,
metric='euclidean',
metric_args=None):
"""Perform outlier removal using the DBSCAN algorithm.
Parameters
----------
data : array
An m by n array of m data sampl... | 85bd485b245ceff737925b09429c66235afe0c2f | 79,320 |
def train_and_eval_cnn(cfgs, activation='relu', batch_norm=False, title=None):
"""Train a CNN, evaluate it, and plot its performance."""
input_shape = (*ORIG_SHAPE, 1) # 1 for the greyscale color, for an RGB picture it would be 3
cfgs.model['input_shape'] = input_shape
cfgs.fit['x_train'] = cfgs.fit... | 2e7fd85f4c160dfc5309ddfcab6ab6612740183b | 79,321 |
def add_vectors_by_position(F, data, increment, positions):
"""Scatter each batch with the given positions.
data[i, positions[i, j], ...] += increment[i, j, ...]
Parameters
----------
F
data
Input tensor of the array to be updated.
Shape (batch_size, seq_length, ...)
increm... | 8181c3b42af8218a2b318ce832c102997e2fbaba | 79,322 |
def create_sf_maps_cpd(pixel_diameter=714, degree_diameter=7.4, origin=None, scale_factor=1,
stim_type='logpolar', w_r=None, w_a=None, w_x=None, w_y=None):
"""Create map of the spatial frequency in cycles per degree of visual angle
this function creates spatial frequency maps; that is, i... | beb1c893ed1f046a9a61c3ad345a5ae6f50c4fbb | 79,323 |
import copy
def combine(struct1, struct2, lat=True,
bonds=True,
bonds_kw={"mult": 1.20, "skin": 0.0, "update": False}):
"""
Combines two structures.
Arguments
---------
lat: bool
If True, keeps lattice vectors of first structure.
"""
if bonds:
... | 80abb8a3d5dcccfc1740d4828f3f87653735fd24 | 79,324 |
def _create_resume_checkpoint(artifact_dir: str) -> callbacks.ModelCheckpoint:
"""Create a callback that saves the model every epoch.
Args:
artifact_dir: str, path to artifact directory.
Returns:
ModelCheckpoint, callback that saves the model every epoch.
"""
filepath = get_resume_... | 1d23990369568980e3210f212fafd4f823872f64 | 79,325 |
from typing import List
from typing import Dict
def GetUserFPRankData(date: str = "latest", rank_type: str = "all") -> List[Dict]:
"""获取用户收益排行榜信息
目前只能获取 2020 年 6 月 20 日之后的数据。
Args:
date (str, optional): 日期,格式“YYYYMMDD”. Defaults to "latest".
Raises:
ResourceError: 对应日期的排行榜数据为空时抛出此异常... | c9ec36be43d62e8ad734d0a0e960cd6e7c6f2e42 | 79,326 |
def _severity_match(event_id: str) -> SeverityLabel:
"""
Match the event_id to a severity label.
"""
for rule in SEVERITY_RULES:
match = rule(event_id)
if match is not None:
return match
logger.warning(f"No rule matched for event_id: {event_id}. Defaulting to max severity... | 7d38a0b4de27447c4496b1026fb9378bddeb2432 | 79,327 |
def get_user_adjacency(user_index, adjacency_matrix):
"""helper function to retrieve the adjacent users for a certain user by passing the latter index to the function"""
adjacent_users = set()
for e, col in enumerate(adjacency_matrix[user_index]):
if adjacency_matrix[user_index][e] > 0:
... | 5a7d03dc028e507c194f551c84301d09b38c25e6 | 79,328 |
def set_indicator_type(indicator_id, itype, user):
"""
Set the Indicator type.
:param indicator_id: The ObjectId of the indicator to update.
:type indicator_id: str
:param itype: The new indicator type.
:type itype: str
:param user: The user updating the indicator.
:type user: CRITsUser... | 27963eeae92d8a7cb770b38e1a39b4dc46ff8965 | 79,329 |
def _preprocess_yolo(img, input_shape):
"""Preprocess an image before TRT YOLO inferencing.
# Args
img: int8 numpy array of shape (img_h, img_w, 3)
input_shape: a tuple of (H, W)
# Returns
preprocessed img: float32 numpy array of shape (3, H, W)
"""
img = cv2.resize(img, (i... | 09f0b0e56e5c9ae14fba4275ed7b13c4210ef084 | 79,330 |
def lchunks(n, step, seq=EMPTY):
"""Chunks seq into parts of length n or less.
Skips step items between parts if passed."""
return list(chunks(n, step, seq)) | a3cdac4a03dbca6145d0213cd5e87f7b5ebdbcf6 | 79,331 |
def get_runtime_coherence_protocol() -> CoherenceProtocol:
"""Gets the cache coherence protocol.
This can be inferred at runtime.
:returns: The cache coherence protocol.
"""
protocol_map = {
"mi_example": CoherenceProtocol.MI_EXAMPLE,
"moesi_hammer": CoherenceProtocol.ARM_MOESI_HAMM... | acf43f9c2e4a4cf9b11782ec2d232c0b4d4ab859 | 79,332 |
def _primal_decode(n, alpha, q, secret_distribution=True, m=oo, success_probability=0.99,
reduction_cost_model=reduction_default_cost, clocks_per_enum=2**15.1):
"""
Decoding attack as described in [LinPei11]_.
:param n: LWE dimension `n > 0`
:param alpha: noise rate `0 ≤ α < 1`, nois... | 7e8d3d3572dd38d7e83bb2b1ef0a1c92eaa221b0 | 79,333 |
from typing import Iterable
from typing import Optional
def m_around(center: complex,
basis: str,
order: Iterable[Optional[complex]],
*,
outward: Optional[complex] = None) -> StabilizerPlanElement:
"""Creates a StabilizerPlanElement that measures a stabilizer us... | 20cc19bf02014f330ee7d34977c47ab0757b3a2d | 79,334 |
from typing import List
def get_provisioning_nic(nics: List[Nic]):
"""
Returns first nic with boot flag enabled or None
"""
nics = [nic for nic in nics if nic.boot]
if not nics:
return None
# Choose the first one
return nics[0] | 4655b47b5fe29b158f985757a4c1722be79098bf | 79,335 |
def get_next_image(current_image, image_queryset, wrap=False):
"""
Get the next image in the image_queryset, relative to current_image.
image_queryset should already be ordered, with an unambiguous ordering
(no ties).
If wrap is True, then the definition of 'next' is extended to allow
wrapping ... | 4772517ad21812e7391e682bda6bdec9223259ae | 79,336 |
def dti6to33(dt6):
""" Full second order symmetric tensor from the six independent components.
dt6 must be a numpy array, NOT a medipy.base.Image
"""
dt33 = np.zeros(dt6.shape[:-1]+(3,3),dtype=dt6.dtype)
dt33[...,0,0] = dt6[...,0]
dt33[...,0,1] = dt6[...,1]
dt33[...,0,2] = dt6[...,2... | 84b47de38019e1160259718c358f1f6e5659076f | 79,337 |
def find_external_metabolites(model):
"""Return all metabolites in the external compartment."""
ex_comp = find_external_compartment(model)
return [met for met in model.metabolites if met.compartment == ex_comp] | f8ca8d9a3879ca67229acc76055a80bba28f58f0 | 79,339 |
def as_node(input_value: NodeInput) -> Node:
"""Return input values as nodes. Scalars will be converted to Constant nodes."""
if issubclass(type(input_value), Node):
return input_value
if issubclass(type(input_value), Output):
return input_value
return make_constant_node(input_value) | 1b868d9a5a8113e920d1a3e2d091e3779c9b7ac2 | 79,340 |
def load_old_configs(benchmark: Benchmark, scenario: Scenario):
"""
Load the module from configs.benchmark.scenario.old.
Args:
benchmark (Benchmark):
The benchmark of the config with diffs
scenario (Scenario):
The scenario of the config with diffs
"""
try:
... | 347fb3e32695d5c3bbbfc0f56851989135879e8a | 79,341 |
def join_result(
input_df: pd.DataFrame,
result_df: pd.DataFrame,
how: str,
left_on: str,
right_on: str,
ignore_case: bool,
) -> pd.DataFrame:
"""
Join input and result DFs, optionally ignoring case.
Parameters
----------
input_df : pd.DataFrame
Input DF
result_d... | c04ec8b1435ad8136674f9cda554da3051db4a23 | 79,342 |
import traceback
def exception_to_message(exception):
"""Given an exception 3-tuple as returned by run_experiment(), returns
a string formatted as Python would have formatted it.
This is a convenience function for handling the somewhat odd
exception info returned by run_experiment().
"""
# tr... | f3bf8a2bf5f39e40a5086319aa6af8e520f1f166 | 79,343 |
def update_action_tooltip(*args):
"""
update_action_tooltip(name, tooltip) -> bool
Update an action's tooltip ( 'ui_update_action_attr' ).
@param name: action name (C++: const char *)
@param tooltip: new tooltip (C++: const char *)
@return: success
"""
return _ida_kernwin.update_action_tooltip(*arg... | 42eee1d165fdb4bc365004dc93889d8ac97b63f3 | 79,344 |
def split_and_standardize(X, y, random_state=None):
"""
Split a dataset, check if it's standardized, and scale if not.
Args:
X (array): The training examples.
y (array): The target or labels.
random_state (int or None): The seed for the split.
Returns:
tuple of ndarray:... | c06201187fb61ab89f9131dbe2a60c4a0e208e93 | 79,345 |
def euclideanNorm(inVec):
"""
perform the euclidean 2 norm of the vector inVec
required because linalg.norm() provides incorrect results for
CS derivatives.
"""
inVec = np.array(inVec)
temp = 0.0
for i in range(inVec.shape[0]):
temp += inVec[i] ** 2
return np.sqrt(temp) | 3d4dd7c78b97c8ea473287ea523f75ec199db435 | 79,346 |
def transmit_code(code_id: int, db: Session = Depends(get_db)):
"""
Transmit the code
"""
code = crud.get_code(db=db, code_id=code_id)
adrsir.transmit(code.code)
return {"device_id": code.device_id, "code_id": code.id} | bf2d17e59c14e9d059691780ea68b6d22d29ff67 | 79,347 |
def list_user_projects(request):
"""
list all projects of the current user.
"""
projects_read = get_objects_for_user(request.user, 'nlpviewer_backend.read_project').all().values('id', 'name')
projects_user = request.user.projects.all().values('id', 'name')
projects_list = list(projects_use... | 4b913ff48e502c0de2004465e66527ce1fb072e0 | 79,348 |
def _get_queue_manager(hostname, portnr, auth_code):
"""
Connects to a running queue manager.
Returns None is queue manager is not running.
"""
try:
QueueServer.register("get_queue")
manager = QueueServer(address=(hostname, portnr), authkey=auth_code)
manager.connect()
... | 9b70f6d0d067339dcb17748bb60b602c8c9c2d8a | 79,349 |
from typing import Dict
import logging
def load_redirects(redirect_path: str) -> Dict[str, str]:
# pylint: disable=line-too-long
"""
Loads the Wikipedia link redirects as a Dictionary. The key is the page
directed from, and the value is the page being directed to.
Args:
redirect_path: A p... | 8ce85a04b8769751095d3856d7725e090cf28c96 | 79,350 |
def create(username, password, confirm_password, first_name, last_name, **options):
"""
creates a new internal user based on given inputs.
:param str username: username.
:param str password: password.
:param str confirm_password: confirm password.
:param str first_name: first name.
:param s... | 8070f9252409b7599062dab01f337334520be2b9 | 79,351 |
def Automatic_Colorization_Network():
"""
take in an gray imgae and transform it to color
Iput (256,)
"""
# A model can have more than one input
inputs_luminance = tf.keras.Input(shape=(224,224,1), name='fixed_size_img')
inputs_luminance_arbitrary = tf.keras.Input(shape=(448,448,1), name='ar... | 3d74bc85b9bb0d269af908e8a3e925c868af262e | 79,353 |
def filter_contexts(fcontent: dataset.TJson, min_num_alpha: int = 10) -> dataset.TJson:
"""Filter contexts of all articles in `fcontent`.
Parameters
----------
fcontent: json-like
Json-like container in default data format
min_num_alpha: int
Minimum number of letters if the context ... | 1543fbe517aa258b3d27db6e9828a02a2d805458 | 79,354 |
import math
def get_loss_ranges_per_classifier_dataset(losses, max_n_datasets=None):
"""
Extracts minimum and maximum losses per dataset and classifier
:param losses: dict of [classifier][parameters:frozenset][dataset_idx] mapping to a float loss
:param max_n_datasets: max number of datasets to look a... | 74a385d50304b8ad2e87bd9c149eaad47d3d7c89 | 79,355 |
def get_r(lon, lat):
"""
Vector from center of earth to the point in question assuming a spherical earth.
The XYZ coordinate system has x=0 at longitude=0 and z=0 at the equator with positive to the north.
:param lon: Longitude of initial point, in degrees
:type lon: float
:param lat: Latitude ... | 849688b0bf775bc92a398e7e02ef1984e1704a06 | 79,356 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.