content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def MaybeGetHexShaOfLastExportedCommit(
repo: git.Repo, head_ref: str = "HEAD") -> typing.List[str]:
"""The the SHA1 of the most recently exported commit.
Args:
repo: The repo to iterate over.
head_ref: The starting point for iteration, e.g. the commit closest to
head.
Returns:
The hex SHA... | 2,900 |
def Quit():
"""
Closes the client
"""
pass | 2,901 |
def get_inchi(ID):
"""This function accept UNIQUE-ID and return InChI string of a certain compound"""
inchi = df_cpd['INCHI'][ID]
return inchi | 2,902 |
def run_samtools_faidx(job, ref_id):
"""
Use Samtools to create reference index file
:param JobFunctionWrappingJob job: passed automatically by Toil
:param str ref_id: FileStoreID for the reference genome
:return: FileStoreID for reference index
:rtype: str
"""
job.fileStore.logToMaster... | 2,903 |
def test_gdalversion_class_runtime():
"""Test the version of GDAL from this runtime"""
GDALVersion.runtime().major >= 1 | 2,904 |
def pad_to_multiple(array: Array,
factor: int,
axis: int,
mode: Optional[str] = 'constant',
constant_values=0) -> Array:
"""Pads `array` on a given `axis` to be a multiple of `factor`.
Padding will be concatenated to the end of the axi... | 2,905 |
def easy2dict(config: easydict.EasyDict):
"""
:param config: EasyDict参数
"""
# fix a Bug: cfg = dict(config) 仅仅转换第一层easydict
cfg = json.loads(json.dumps(config))
return cfg | 2,906 |
def define_request(
dataset,
query=None,
crs="epsg:4326",
bounds=None,
bounds_crs="EPSG:3005",
sortby=None,
pagesize=10000,
):
"""Define the getfeature request parameters required to download a dataset
References:
- http://www.opengeospatial.org/standards/wfs
- http://docs.g... | 2,907 |
def get_bert_input(
examples: List[tuple],
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Convert input list to torch tensor.
Args:
examples: (input_id_list, )
Returns:
attention_mask, input_ids_tensor, token_type_ids_tensor
"""
input_ids = examples[0]
token_type_... | 2,908 |
def _format_exception(e: BaseException):
"""
Shamelessly stolen from stdlib's logging module.
"""
with io.StringIO() as sio:
traceback.print_exception(e.__class__, e, e.__traceback__, None, sio)
return sio.getvalue().strip() | 2,909 |
def batch_deploy(blueprint_id,
parent_deployments,
group_id=None,
new_deployment_ids=None,
inputs=None,
labels=None,
**_):
"""
Create deployments for a batch from a single blueprint.
:param blueprint_id: Th... | 2,910 |
def compute_task_def(build, settings, fake_build):
"""Returns a swarming task definition for the |build|.
Args:
build (model.Build): the build to generate the task definition for.
build.proto.infra and build.proto.input.properties must be initialized.
settings (service_config_pb2.SettingsCfg): globa... | 2,911 |
def parse_markdown(page, target=None, pages=None, categories=[], mode="html",
current_time="", bypass_errors=False):
"""Takes a page object (must contain "md" attribute) and returns parsed
and filtered HTML."""
target = get_target(target)
logger.info("Preparing page %s" % page["name... | 2,912 |
def draw_bs_pairs(x, y, func, size=1):
"""Perform pairs bootstrap for replicates."""
# Set up array of indices to sample from: inds
inds = np.arange(len(x))
# Initialize replicates
bs_replicates = np.empty(size)
# Generate replicates
for i in range(size):
bs_inds = np.random.choice... | 2,913 |
def has_hole(feature):
"""
Detects the number of holes in a shapely polygon or multipolygon.
Parameters
----------
feature : shapely Polygon or Multipolygon
polygon to be analyzed for holes
Returns
-------
int
number of holes
"""
if feature.geom_typ... | 2,914 |
def linder_table(file=None, **kwargs):
"""Load Linder Model Table
Function to read in isochrone models from Linder et al. 2019.
Returns an astropy Table.
Parameters
----------
age : float
Age in Myr. If set to None, then an array of ages from the file
is used to generate dicti... | 2,915 |
def json_redirect(request, url, **kwargs):
"""
Returns a JSON response for redirecting to a new URL. This is very specific
to this project and depends on the JavaScript supporting the result that
is returned from this method.
"""
if not request.is_ajax():
raise PermissionDenied("Must be ... | 2,916 |
def unauthenticatedClient():
"""Retorna um api client sem ninguém autenticado"""
return APIClient() | 2,917 |
def filters_to_kcorrect(curve_file, verbose=False):
"""
Convert a filter response curve to the Kcorrect format.
This is used by Kcorrect and iSEDFit.
"""
if not os.path.isfile(curve_file):
raise IOError("# Cannot find the response curve file {}".format(curve_file))
# Read in the .txt r... | 2,918 |
def get_known_disk_attributes(model):
"""Get known NVMe/SMART attributes (model specific), returns str."""
known_attributes = KNOWN_DISK_ATTRIBUTES.copy()
# Apply model-specific data
for regex, data in KNOWN_DISK_MODELS.items():
if re.search(regex, model):
for attr, thresholds in data.items():
... | 2,919 |
def table_drop_nan_columns(table: Path, output_path: Path) -> None:
"""
Drop columns with only null values from the table.
Arguments:
table: Location of the input table.
output_path: Location of the output table.
"""
with open_file_like(table, mode="r") as fd:
reader = csv.r... | 2,920 |
def get_one_exemplar_per_class_proximity(proximity):
"""
unpack proximity object into X, y and random_state for picking exemplars.
----
Parameters
----
proximity : Proximity object
Proximity like object containing the X, y and random_state variables
required for picking exemplars... | 2,921 |
def annotation_layers(state):
"""Get all annotation layer names in the state
Parameters
----------
state : dict
Neuroglancer state as a JSON dict
Returns
-------
names : list
List of layer names
"""
return [l["name"] for l in state["layers"] if l["type"] == "annotat... | 2,922 |
def describe_bvals(bval_file) -> str:
"""Generate description of dMRI b-values."""
# Parse bval file
with open(bval_file, "r") as file_object:
raw_bvals = file_object.read().splitlines()
# Flatten list of space-separated values
bvals = [
item for sublist in [line.split(" ") for line ... | 2,923 |
def selectionToAbsoluteNames(selection, permissive='False'):
"""
Generator that converts selected nodes to long names.
i.e. absolute paths for dag nodes or instances and names for dependency (non-dag) nodes.
"selection" can either be a MSelectionList or an iterable of nodes.
if permissive, invalid n... | 2,924 |
def test_working_filter(test_microvm_with_api):
"""
Test --seccomp-filter, rejecting some dangerous syscalls.
@type: security
"""
test_microvm = test_microvm_with_api
_custom_filter_setup(test_microvm, """{
"Vmm": {
"default_action": "allow",
"filter_action": "k... | 2,925 |
def weight_update4(weights, x_white, bias1, lrate1, b_exp):
""" Update rule for infomax
This function recieves parameters to update W1
* Input
weights : unmixing matrix (must be a square matrix)
x_white: whitened data
bias1: current estimated bias
lrate1: current learning rate
b_exp : ex... | 2,926 |
def Dijkstra(graph, source):
"""
Dijkstra's algorithm for shortest path between two vertices on a graph.
Arguments
---------
graph -- directed graph; object of Graph class
source -- start vertex
>>> graph = Graph()
>>> graph.addVertex("A")
>>> conns = [ ("A", "B"), ("A", "C"), ("B"... | 2,927 |
def update_local(base, new_path):
"""On some systems virtualenv seems to have something like a local
directory with symlinks. It appears to happen on debian systems and
it causes havok if not updated. So do that.
"""
local_dir = os.path.join(base, 'local')
if not os.path.isdir(local_dir):
... | 2,928 |
def handle_post_actor_report(self, handle, connection, match, data, hdr):
"""
POST /actor/{actor-id}/report
Some actors accept external input using this function. Not always present.
Response status code: OK or NOT_FOUND
Response: Depends on actor
"""
self._actor_report(handle, connection, m... | 2,929 |
def check_data_dir(path):
"""
check cata_dir
"""
err = "Data path is not exist, please given a right path" \
"".format(path)
try:
assert os.isdir(path)
except AssertionError:
logger.error(err)
sys.exit(1) | 2,930 |
def test_find_number_max_repeating():
"""
Find the number which is repeated the largest number of times
"""
t = MapReduceTask(verbose=True, lazy=False)
# the order matters
@t.map
def m1(k, v):
yield v, 1
@t.reduce
def r1(k, v):
yield k, sum(v)
@t.map
def m2... | 2,931 |
def annealing_epsilon(episode: int, min_e: float, max_e: float, target_episode: int) -> float:
"""Return an linearly annealed epsilon
Epsilon will decrease over time until it reaches `target_episode`
(epsilon)
|
max_e ---|\
| \
| \
| \
mi... | 2,932 |
def ExtendWithDefault(validator_class):
"""Takes a validator and makes it set default values on properties.
Args:
validator_class: A class to add our overridden validators to
Returns:
A validator_class that will set default values
and ignore required fields
"""
validate_pro... | 2,933 |
def coach_input_line(call, school, f):
"""
Returns a properly formatted line about a coach.
:param call: (String) The beginning of the line, includes the gender, sport, and school abbreviation.
:param school:(String) The longform name of the school.
:param f: (String) The input line from the user.
... | 2,934 |
def pad_seq(seq, max_length, PAD=0):
"""
:param seq: list of int,
:param max_length: int,
:return seq: list of int,
"""
seq += [PAD for i in range(max_length - len(seq))]
return seq | 2,935 |
def test_import_protobuf():
"""
Ensure the generated protobuf file is successfully importable in a dev environment.
"""
from foxglove_websocket.examples.proto.ExampleMsg_pb2 import ExampleMsg
_ = ExampleMsg | 2,936 |
def complex_domain(spectrogram):
"""
Complex Domain.
Parameters
----------
spectrogram : :class:`Spectrogram` instance
:class:`Spectrogram` instance.
Returns
-------
complex_domain : numpy array
Complex domain onset detection function.
References
----------
... | 2,937 |
def toOneHot(action_space, actions):
"""
If action_space is "Discrete", return a one hot vector, otherwise just return the same `actions` vector.
actions: [batch_size, 1] or [batch_size, n, 1]
If action space is continuous, just return the same action vector.
"""
# One hot encoding buffer that... | 2,938 |
def find_triangle(n):
"""Find the first triangle number with N divisors."""
t, i = 1, 1
while True:
i += 1
t += i
if len(divisors(t)) > n:
return t | 2,939 |
def get_main_page_soup(home_url):
""" parse main page soup"""
user_agent= 'Mozilla / 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, ' \
'like Gecko) Chrome / 64.0.3282.140 Safari / 537.36 Edge / 18.17763 '
headers = {'User-agent':user_agent}
# request to javbus
res = r... | 2,940 |
def gen_task4() -> np.ndarray:
"""Task 4: main corner of a triangle."""
canv = blank_canvas()
r, c = np.random.randint(GRID-2, size=2, dtype=np.int8)
syms = rand_syms(6) # 6 symbols for triangle
# Which orientation? We'll create 4
rand = np.random.rand()
if rand < 0.25:
# top left
rows, cols = [r,... | 2,941 |
def pytest_funcarg__testname(request):
"""
The testname as string, or ``None``, if no testname is known.
This is the parameter added by the test generation hook, or ``None`` if no
parameter was set, because test generation didn't add a call for this test.
"""
return getattr(request, 'param', No... | 2,942 |
def try_log_conf_file(file_path: pathlib.Path) -> bool:
"""It tries to open a log configuration file.
filePath: filePath
return: boolean (True is succeed, False otherwise)
"""
global logger
try:
with file_path.open() as f:
logger_conf = json.load(f)
logging.confi... | 2,943 |
def combine_specific_viz_ids_pics(srcs: List[str], out: str = None, setup: List[str] = ('base', 'hsc', 'ae'),
skip_further=False, only_cls: List[int] = None):
"""
Combines heatmap images (visualization ids) for several old experiments for the same input images.
Depending on... | 2,944 |
def notes_to_editor_view(notes):
"""Convert notes object content to more readble view
Args:
notes (list): list of note object
Returns:
list: list of note object
"""
for note in notes:
note.content = to_editor(note.content)
return notes | 2,945 |
def cozmo_program(robot: cozmo.robot.Robot):
"""
Main entry point for running the scoring logic in the capture the flag game.
:param robot: judge robot in the game
"""
# get number of teams playing in the game
while True:
try:
teams: int = int(input("How many teams are play... | 2,946 |
def normalization(arr, normalize_mode, norm_range = [0,1]):
"""
Helper function: Normalizes the image based on the specified mode and range
Args:
arr: numpy array
normalize_mode: either "whiten", "normalize_clip", or "normalize" representing the type of normalization to use
norm_rang... | 2,947 |
def draw_mask(img, mask, col, alpha=0.4, show_border=True, border_thick=0):
"""Visualizes a single binary mask."""
was_pil = isinstance(img, (Image.Image))
img = np.array(img)
img = img.astype(np.float32)
idx = np.nonzero(mask)
img[idx[0], idx[1], :] *= 1.0 - alpha
img[idx[0], idx[1], ... | 2,948 |
def build_md_page(page_info: parser.PageInfo) -> str:
"""Given a PageInfo object, return markdown for the page.
Args:
page_info: Must be a `parser.FunctionPageInfo`, `parser.ClassPageInfo`, or
`parser.ModulePageInfo`.
Returns:
Markdown for the page
Raises:
ValueError: if `page_info` is an i... | 2,949 |
def print_all_errors():
""" prints all the errors in the db in a human friendly way"""
pass | 2,950 |
def transpose(data: NodeInput, input_order: NodeInput, name: Optional[str] = None) -> Node:
"""Return a node which transposes the data in the input tensor.
@param data: The input tensor to be transposed
@param input_order: Permutation of axes to be applied to the input tensor
@return Transpose node
... | 2,951 |
def find_opposite_reader(card_reader_list, find):
"""Returns the card reader on the opposite side of the door for the card reader in find"""
for c in card_reader_list:
if c.room_a == find.room_b and c.room_b == find.room_a:
return c
raise (Exception("No reader on opposite side found")) | 2,952 |
def send_mail_to_admin(email_subject, email_body):
"""Send an email to the admin email address.
The email is sent to the ADMIN_EMAIL_ADDRESS set in feconf.py.
Args:
email_subject: str. Subject of the email.
email_body: str. Body (message) of the email.
"""
app_id = app_identity_se... | 2,953 |
def _download_file(remote_url, target):
"""
Accepts a URL, downloads the file to a given open file object.
This is a modified version of astropy.utils.data.download_file that
downloads to an open file object instead of a cache directory.
"""
from contextlib import closing
from astropy.exte... | 2,954 |
def project_envs() -> None:
"""Projects Environments.""" | 2,955 |
def trigger_QUIT(code, origin, line, args, text):
"""
ID: QUIT
Decription: A client session is ended with a quit message. The server must close
the connection to a client which sends a QUIT message. If a "Quit
Message" is given, this will be sent inste... | 2,956 |
def tag_from_clark(name):
"""Get a human-readable variant of the XML Clark notation tag ``name``.
For a given name using the XML Clark notation, return a human-readable
variant of the tag name for known namespaces. Otherwise, return the name as
is.
"""
match = CLARK_TAG_REGEX.match(name)
i... | 2,957 |
def build_k_indices(y, k_fold, seed):
"""
Randomly partitions the indices of the data set into k groups
Args:
y: labels, used for indexing
k_fold: number of groups after the partitioning
seed: the random seed value
Returns:
k_indices: an array of k sub-indices that are ra... | 2,958 |
def update_fixtures(
request, index, received_output, comment, testname=None, additional_information=None
):
# pylint: disable=too-many-arguments
"""Used by action plugins to generate the fixtures"""
dir_path, file_name = fixture_path_from_request(request, index, testname=testname)
os.makedirs(dir_p... | 2,959 |
def get_parent(obj, default=_marker):
"""Returns the container the object was traversed via.
Returns None if the object is a containment root.
Raises TypeError if the object doesn't have enough context to get the
parent.
"""
if IRoot.providedBy(obj):
return None
parent = aq_parent(... | 2,960 |
def MRR(logits, target):
"""
Compute mean reciprocal rank.
:param logits: 2d array [batch_size x rel_docs_per_query]
:param target: 2d array [batch_size x rel_docs_per_query]
:return: mean reciprocal rank [a float value]
"""
assert logits.shape == target.shape
sorted, indices =... | 2,961 |
def resetSpotIndicator():
"""
This function is run as a thread and unsets the spot indicator of GameSense after a given wait time (in seconds).
"""
resetSpotIndicator.terminate = False
deltaSleep = 0.1
epsilon = 0.001
waitTime = 10.0
currentTimeSec = lambda: time.time()
startTime =... | 2,962 |
def stream_collector(api, args, storage):
"""Pull tweets from stream."""
total_tweets = 0
total_skipped = 0
last_skipped = 0
params = to_dict(args.parameters)
while True:
try:
iterator = api.request(args.endpoint, params).get_iterator()
for item in iterator:
if 'text' in item:
total_tweets += 1
... | 2,963 |
def range(starts,
limits=None,
deltas=1,
dtype=None,
name=None,
row_splits_dtype=dtypes.int64):
"""Returns a `RaggedTensor` containing the specified sequences of numbers.
Each row of the returned `RaggedTensor` contains a single sequence:
```python
ragged.rang... | 2,964 |
def ecef2enuv(u, v, w, lat0, lon0, deg=True):
"""
for VECTOR i.e. between two points
input
-----
x,y,z [meters] target ECEF location [0,Infinity)
"""
if deg:
lat0 = radians(lat0)
lon0 = radians(lon0)
t = cos(lon0) * u + sin(lon0) * v
... | 2,965 |
def interpolate_ray_dist(ray_dists, order='spline'):
""" interpolate ray distances
:param [float] ray_dists:
:param str order: degree of interpolation
:return [float]:
>>> vals = np.sin(np.linspace(0, 2 * np.pi, 20)) * 10
>>> np.round(vals).astype(int).tolist()
[0, 3, 6, 8, 10, 10, 9, 7, 5... | 2,966 |
def distance(left, right, pairwise=pairwise['prod'], distance_function=None):
"""
Calculate the distance between two *k*-mer profiles.
:arg left, right: Profiles to calculate distance
between.
:return: The distance between `left` and `right`.
:rtype: float
"""
if not distance_functio... | 2,967 |
def _rec_get_all_imports_exports(fips_dir, proj_dir, result) :
"""recursively get all imported projects, their exported and
imported modules in a dictionary object:
project-1:
url: git-url (not valid for first, top-level project)
exports:
header-dirs: ... | 2,968 |
def main():
"""Main entry point"""
current_time = datetime.now()
local_time = current_time.astimezone(get_localzone())
if is_day(local_time):
time_string = datetime.strftime(local_time, "%Y%m%d-%H%M%S")
date_string = datetime.strftime(local_time, "%Y%m%d")
picture_directory = PI... | 2,969 |
def get_database_cluster(name: Optional[str] = None,
tags: Optional[Sequence[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDatabaseClusterResult:
"""
Provides information on a DigitalOcean database cluster resource.
## Example Us... | 2,970 |
def caller_name(skip=2):
"""Get a name of a caller module
`skip` specifies how many levels of stack to skip while getting caller
name. skip=1 means "who calls me", skip=2 "who calls my caller" etc.
An empty string is returned if skipped levels exceed stack height
References:
----... | 2,971 |
def get_dataset():
"""Summary
Returns
-------
TYPE
Description
"""
stms = []
for dirpath, dirnames, filenames in os.walk('TEDLIUM_release2'):
for f in filenames:
if f.endswith('stm'):
stms.append(os.path.join(dirpath, f))
data = []
for st... | 2,972 |
def tesla_loadhook(h, *args, **kwargs):
"""
Converts a load hook into an application processor.
>>> app = auto_application()
>>> def f(*args, **kwargs): "something done before handling request"
...
>>> app.add_processor(loadhook(f, *args, **kwargs))
"""
def processor(han... | 2,973 |
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): #pragma: no cover
"""
Force a string to be unicode.
If strings_only is True, don't convert (some) non-string-like objects.
Originally copied from the Django source code, further modifications have
been made.
Origina... | 2,974 |
def extractYoloInfo(yolo_output_format_data):
""" Extract box, objectness, class from yolo output format data """
box = yolo_output_format_data[..., :6]
conf = yolo_output_format_data[..., 6:7]
category = yolo_output_format_data[..., 7:]
return box, conf, category | 2,975 |
def bbox_diou(bboxes1, bboxes2):
"""
Complete IoU
@param bboxes1: (a, b, ..., 4)
@param bboxes2: (A, B, ..., 4)
x:X is 1:n or n:n or n:1
@return (max(a,A), max(b,B), ...)
ex) (4,):(3,4) -> (3,)
(2,1,4):(2,3,4) -> (2,3)
"""
bboxes1_area = bboxes1[..., 2] * bboxes1[..., 3]
... | 2,976 |
def showp1rev(context, mapping):
"""Integer. The repository-local revision number of the changeset's
first parent, or -1 if the changeset has no parents. (DEPRECATED)"""
ctx = context.resource(mapping, b'ctx')
return ctx.p1().rev() | 2,977 |
def read_object(ctx, pin, object_id):
"""
Read arbitrary PIV object.
Read PIV object by providing the object id.
\b
OBJECT-ID Id of PIV object in HEX.
"""
controller = ctx.obj['controller']
def do_read_object(retry=True):
try:
click.echo(controller.get_data(... | 2,978 |
def erp_pretax(t,ma,st,ra,par):
""" early retirement pension (efterløn) pretax"""
# initialize
ERP = np.zeros(1)
# pre two year period
if par.T_erp <= t < par.T_two_year:
if ra == 1:
priv = priv_pension(ma,st,par)
ERP[:] = np.maximum(0,par.ERP_high - 0.6*0.05*np.max... | 2,979 |
def main(gen5tt_algo, fs_file, num_tracts, participant_label, session_label, t1_file, eddy_file, bvec_file, bval_file, template_file, atlas_file, output_dir):
"""Console script for tractify."""
work_dir = os.path.join(output_dir, "scratch")
# Set parameters based on CLI, pass through object
parameters... | 2,980 |
def add_missing_cmd(command_list):
"""Adds missing cmd tags to the given command list."""
# E.g.: given:
# ['a', '0', '0', '0', '0', '0', '0', '0',
# '0', '0', '0', '0', '0', '0', '0']
# Converts to:
# [['a', '0', '0', '0', '0', '0', '0', '0'],
# ['a', '0', '0', '0', '0', '0',... | 2,981 |
def replace_umlauts(s: str) -> str:
"""
Replace special symbols with the letters with umlauts (ä, ö and ü)
:param s: string with the special symbols (::)
:return: edited string
"""
out = s.replace('A::', 'Ä').replace('O::', 'Ö').replace('U::', 'Ü').replace('a::', 'ä').replace('o::', 'ö') \
... | 2,982 |
def bandstructure_flow(workdir, scf_input, nscf_input, dos_inputs=None, manager=None, flow_class=Flow, allocate=True):
"""
Build a :class:`Flow` for band structure calculations.
Args:
workdir: Working directory.
scf_input: Input for the GS SCF run.
nscf_input: Input for the NSCF run... | 2,983 |
def beautify_ax(ax, edge_color, face_color):
"""
Beautifies an ax object by adjusting axis and ticks and changing colors.
:param ax:
:return:
"""
# set ticks only on the left and the bottom
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
# change ticks leng... | 2,984 |
def get_modules():
"""Returns the list of module names
"""
def listdir(dir):
def clean(name):
name = os.path.basename(name)
if name[-4:] == '.zip':
name = name[:-4]
return name
def is_really_module(name):
for mname in MANIFEST_... | 2,985 |
def resnet_50(num_classes, data_format='channels_first', pruning_method=None):
"""Returns the ResNet model for a given size and number of output classes."""
return resnet_50_generator(
block_fn=bottleneck_block_,
lst_layers=[3, 4, 6, 3],
num_classes=num_classes,
pruning_method=pruning_method... | 2,986 |
def read_amuselabs_data(s):
"""
Read in an amuselabs string, return a dictionary of data
"""
# Data might be base64'd or not
try:
data = json.loads(s)
except json.JSONDecodeError:
s1 = base64.b64decode(s)
data = json.loads(s1)
ret = {}
# metadata
# technical... | 2,987 |
def calinski_harabasz(dataset_values:DatasetValues):
"""Calinski, T.; Harabasz, J. (1974). A dendrite method for cluster analysis.
Communications in Statistics - Theory and Methods, v.3, n.1, p.1�27.
The objective is maximize value [0, +Inf]"""
if dataset_values.K == 1:
return 0
re... | 2,988 |
def parse_version(version):
"""
input version string of the form:
'Major.Minor.Patch+CommitHash'
like:
'0.1.5+95ffef4'
------ or ------
'0.1.0'
returns version_info tuple of the form:
(major,minor,patch,hash)
li... | 2,989 |
def _location_sensitive_score(W_query, W_fil, W_keys):
"""Impelements Bahdanau-style (cumulative) scoring function.
This attention is described in:
J. K. Chorowski, D. Bahdanau, D. Serdyuk, K. Cho, and Y. Ben-
gio, “Attention-based models for speech recognition,” in Ad-
vances in Neural Info... | 2,990 |
def get_streamdecks():
"""
Retrieves all connected streamdecks
"""
streamdecks = DeviceManager().enumerate()
return streamdecks | 2,991 |
def clean_string(text):
"""
Remove Lucene reserved characters from query string
"""
if isinstance(text, six.string_types):
return text.translate(UNI_SPECIAL_CHARS).strip()
return text.translate(None, STR_SPECIAL_CHARS).strip() | 2,992 |
def convert_single_example(example_index, example, label_size, max_seq_length,
tokenizer, max_qa_length):
"""Loads a data file into a list of `InputBatch`s."""
# RACE is a multiple choice task. To perform this task using AlBERT,
# we will use the formatting proposed in "Improving Langu... | 2,993 |
def GetAllProperties(layers='core'):
"""Return all properties in the graph."""
global Utc
KEY = "AllProperties:%s" % layers
if DataCache.get(KEY,Utc):
#logging.debug("DataCache HIT: %s" % KEY)
return DataCache.get(KEY,Utc)
else:
#logging.debug("DataCache MISS: %s" % KEY)
... | 2,994 |
def _single_optimal_block(x: NDArray) -> Tuple[float, float]:
"""
Compute the optimal window length for a single series
Parameters
----------
x : ndarray
The data to use in the optimal window estimation
Returns
-------
stationary : float
Estimated optimal window length ... | 2,995 |
def predict(params, X):
"""
Using the learned parameters, predicts a class for each example in X
Arguments:
parameters -- python dictionary containing your parameters
X -- input data of size (n_x, m)
Returns
predictions -- vector of predictions of our model (red: 0 / blue: 1)
"""
... | 2,996 |
def RedirectFilterPageGenerator(generator):
"""
Wraps around another generator. Yields only those pages that are not redirects.
"""
for page in generator:
if not page.isRedirectPage():
yield page | 2,997 |
def response(request):
"""
返回相应对象
:param request:
:return:
"""
json_str = '{"name": "张三", "age": 18}' # 整体是个字符串
response = HttpResponse(json_str,
content_type="application/json",
status=200)
response["dev"] = "aGrass0825" # 向响应头中添加内容
... | 2,998 |
def nest_to_flat_dict(nest):
"""Convert a nested structure into a flat dictionary.
Args:
nest: A nested structure.
Returns:
flat_dict: A dictionary with strings keys that can be converted back into
the original structure via `flat_dict_to_nest`.
"""
flat_sequence = tf.nest.flatten(nes... | 2,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.