content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def parallel_sequential_generation(seed_text, batch_size=10, max_len=15, top_k=0, temperature=None, max_iter=300, burnin=200,
cuda=False, print_every=10, verbose=True):
""" Generate for one random position at a timestep
args:
- burnin: during burn-i... | efb64c13422092072000f5cd5c5a4bb94733416e | 57,900 |
def _check_state_from_log(pid, log_abspath, start_pos=0):
"""
Check the service startup status based on the log file.
Args:
pid (int): The gunicorn process ID.
log_abspath (str): Absolute path of the log file.
start_pos (int): Offset position of the log file.
Returns:
d... | 98e4c41eaccf932a12f4d0520223bdab78ed1630 | 57,901 |
def compute_lap_embedding_from_laplacian(L, num_proj_dimensions=None,
proj_to_sphere=True):
""" Returns the representation using Laplacian eigenvectors and in the unit cube. """
num_proj_dimensions = num_proj_dimensions if num_proj_dimensions is not None \
else L... | ec136ab69e383926985bd6483e62ffe63e7b6785 | 57,902 |
def grab_features(apk) :
"""
@param apk : an APK instance
@rtype : a list of features
"""
features = []
xml = {}
for i in apk.zip.namelist() :
if i == "AndroidManifest.xml" :
xml[i] = minidom.parseString( AXMLPrinter( apk.zip.read( i ) ).getBuff() )
for item in xml[i].getElementsByTagName('uses-featu... | cb8012c1b2dab2b5a837f4e9460f5e4ae7dc1e74 | 57,903 |
import scipy
def detect_beats(ECG, # The raw ECG signal
rate, # Sampling rate in HZ
# Low frequency of the band pass filter
lowfreq=5.0,
# High frequency of the band pass filter
highfreq=15.0
):
"""
ECG ... | 262057d56e70278535f7d2356c28945daddaedc5 | 57,904 |
import typing
def part_one(puzzle: Puzzle) -> typing.Optional[typing.Union[str, int]]:
"""Return the number of occupied seats after the seating arrangements stabilizes."""
seats, neighbors = parse_seats(puzzle.lines, adjacent_neighbors)
return seating_simulation(seats, neighbors, neighbor_limit=4) | 1bf324c34dc363b7a9b9517f75a71ce7f44fc2a0 | 57,905 |
def parse(opt):
"""This function parses the options to --download and returns a set such as { icu: true }, etc. """
if not opt:
opt = download_default
theOpts = set(opt.split(','))
if 'all' in theOpts:
# all on
return set2dict(download_types, True)
elif 'none' in theOpts:
# all off
retur... | 0619db205f31b95b54ef24136dbef63b1edf6f91 | 57,906 |
def plot_processed_data(df, title, xlabel, ylabel, process, num):
"""Make a figure with subplots after processing the data."""
num = len(df.index)
fig, axes = plt.subplots(num, 1, sharex=True, figsize=(8, 2.5 * num))
fig.suptitle(title)
for idx in range(num):
axes[idx].title.set_text("Sampl... | ab554236c4acc8bdabccd21daf7a9598168c855a | 57,907 |
def alerts_run_tag_filter(run, begin, end):
"""Create a RunTagFilter for Alerts.
Args:
run: tfdbg2 run name.
begin: Beginning index of alerts.
end: Ending index of alerts.
Returns:
`RunTagFilter` for the run and range of Alerts.
"""
# TODO(cais): Add filter for alert type.
... | 442ce2a7f62bacb0d6f5f9a26c1b5868cc857069 | 57,908 |
def jinja_loader_from_django_loader(django_loader, args=None):
"""Attempts to make a conversion from the given Django loader to an
similarly-behaving Jinja loader.
:param django_loader: Django loader module string.
:return: The similarly-behaving Jinja loader, or None if a similar loader
could ... | c2942da0b537fbaa637efad3649d29725900e3dc | 57,909 |
def _dtype_to_stata_type(dtype: np.dtype, column: Series) -> int:
"""
Convert dtype types to stata types. Returns the byte of the given ordinal.
See TYPE_MAP and comments for an explanation. This is also explained in
the dta spec.
1 - 244 are strings of this length
Pandas ... | 5b553b9979484a38300e0ed2b6e1b10ade10883e | 57,910 |
def envelope():
"""Create and return a simple SOAP envelope as string.
Simple envelope includes wsse:Security header with wsu:Timestamp token, and
a body with a single child element, as required by py-wsse.
"""
return """
<soap:Envelope
xmlns:soap="%(soap_ns)s"
xmln... | 4d34f82123e9eecae8b4161af8164a4414ac01e1 | 57,911 |
def to_utf8(s):
"""
Convert the given Unicode string into an UTF-8 encoded string.
If the argument is already a normal Python string, nothing is done.
So this function can be used as a filter to normalize string arguments.
:param s: Unicode string to convert.
:type s: basestring
:returns:... | b1fdac84982e25d1c327de5d9bb526ca41e0601f | 57,912 |
def _generate_flame_clip_name(context, publish_fields):
"""
Generates a name which will be displayed in the dropdown in Flame.
:param publish_fields: Publish fields
:returns: name string
"""
# this implementation generates names on the following form:
#
# Comp, scene.nk (output backgro... | 91d49612815830c3260920f6f87a6d4eada1006f | 57,913 |
def sync(path, previous_date, current_date,branches,dry_run=True):
"""
The 'main' function that gets invoked by AWS Lambda.
Performs three main tasks:
- Deactivate people who were on the old list, but not the new list
- Update people who are on both lists
- Create people who were not on the ol... | d19fd6b96a6e4f5f4cd6cc7889cab10b90477bee | 57,914 |
def shuffleCopyMatrix(lins, louts, msize):
"""Returns a matrix P that represents switch and copy operations
on the rows of a matrix.
param msize: the size (of the square matrix).
param lins: row indices to be replaced.
param louts: row that replace the ones listed in lins.
lins and louts must be... | 976d16a63709eba244472b104ba228f16ba703e7 | 57,915 |
def _safe_sandwich_dot(X, d, intercept=False):
"""Compute sandwich product X.T @ diag(d) @ X.
With ``intercept=True``, X is treated as if a column of 1 were appended as
first column of X.
X can be sparse, d must be an ndarray. Always returns a ndarray."""
if sparse.issparse(X):
temp = X.tra... | 2403047e2aa83dfc9c1c43e9039b64404531797b | 57,916 |
from typing import List
from typing import Tuple
from typing import Optional
def aggregate_changes(
query_result: List[Tuple[int, int]], initial: Optional[Tuple[int, int, int]] = None
) -> Tuple[int, int, int]:
"""Add a changeset to the aggregated diff result"""
result = list(initial) if initial else [0, ... | ac31c0424ca26fd2bfb5d035b1fea436cbe7d008 | 57,917 |
def formatFamily(guid):
"""
Given a Format family's GUID, display information about it from the Format Policy Registry
* <uri>/api/par/format-families/c94ce0e6-c275-4c09-b802-695a18b7bf2a
"""
formatGroup = fpr_format_groups.query.get(guid)
formats = fpr_formats.query.filter_by(group=formatGro... | 8eaeaacfdc17d3f1356a1a5eeffa58953da91ed4 | 57,918 |
import copy
def test_actions(cbcsdk_mock):
"""Tests the three "action" methods."""
count_put = 0
count_post = 0
def put_validate(url, body, **kwargs):
nonlocal count_put
assert body == ACTION_REQS[count_put]
count_put += 1
return None
def post_validate(url, body, ... | 649ee8bf7adffc1722b16dbd8ff4eeb6ce366366 | 57,919 |
import imghdr
import struct
def get_image_size(fname):
"""
Determine the image type of fhandle and return its size. From draco
Code copied from https://stackoverflow.com/a/20380514 and made by https://stackoverflow.com/users/2372270/fred-the-fantastic
:param fname: Name of the file to open with the path.
:typ... | ce46cc383365e6a1c9e516e6ea9361e8b38a314a | 57,920 |
def add_items(inventory, items):
"""
:param inventory: dict - dictionary of existing inventory.
:param items: list - list of items to update the inventory with.
:return: dict - the inventory dictionary update with the new items.
"""
inventory = defaultdict(int, inventory)
for item in items... | 2b875f6654a613669066c6c752c0eb15495cb18a | 57,921 |
def project_to_sphere(pts,radius,center):
"""
params:
something like
radius = 5
center = np.array([0,0,-10])
https://stackoverflow.com/questions/9604132/how-to-project-a-point-on-to-a-sphere
For the simplest projection (along the line connecting the point to the center of the sphere):
... | cf8caa81a3e39cc70b4153f31ea8a5155cef3b31 | 57,922 |
def calc_air_density(temperature, pressure, elevation_ref=None, elevation_site=None, lapse_rate=-0.113,
specific_gas_constant=286.9):
"""
Calculates air density for a given temperature and pressure and extrapolates that to the site if both reference
and site elevations are given.
:... | 964bff72d67354abeff9a355788d3624d7ec230c | 57,923 |
import warnings
def choose_ingestor(filename, mimetype):
"""
Take in a filename and its mimetype; return an ingestor.
If multiple are found, return the first one (deterministic but arbitrary).
If none are found, raise.
"""
ingestors = applicable_ingestors(filename, mimetype)
if not ingesto... | 4f43c6f9a705ac7ea482bead33cd018bbf77e912 | 57,924 |
from typing import List
def compute_num_nonzero(charges: List[BaseCharge], flows: List[bool]) -> int:
"""
Compute the number of non-zero elements, given the meta-data of
a symmetric tensor.
Args:
charges: List of `BaseCharge`, one for each leg of a
tensor.
flows: A list of bool, one for each ... | 6e37f39f5dc6c71933bb0872b255d015f4d14a8c | 57,925 |
import os
def RemoveFile( path,
optional_retry_iterations=5,
):
"""Removes a file in the most efficient way possible."""
if not os.path.isfile(path):
return False
_RemoveImpl(os.remove, path, optional_retry_iterations)
return True | 9b8d061e7a9cc29a9710911ad75716704f74e385 | 57,926 |
def sitemap():
"""Display sitemap XML."""
config = flask.current_app.config
start = int(request.args.get("start", config.get("SITEMAP_DEFAULT_START")))
max_size = int(config.get("SITEMAP_MAX_SIZE"))
size = int(request.args.get("size", config.get("SITEMAP_DEFAULT_SIZE")))
if size > max_size:
... | f99355ca487b9a953c72e3fbb1cad8e5f578c795 | 57,927 |
import argparse
import pathlib
def parse_command_line(argv):
"""Parse the script's command line."""
parser = argparse.ArgumentParser(
description="""\
Convert a mesh to Neuroglancer pre-computed mesh format.
This tool can convert any mesh format that is readable by nibabel, e.g. Gifti.
The resulting... | 5a562c6f7319d1a133b8c391e3788e5efb5ce26f | 57,928 |
def attach_sandbox(cmd, sandbox = None):
"""Attach sandbox arguments to command"""
if not sandbox:
sandbox = get_setting_async('cabal_dev_sandbox')
if len(sandbox) > 0:
return cmd + ['-s', sandbox]
return cmd | bf292685eee280b651599d70c39cbece5579ca73 | 57,929 |
def drop_subtree(dep_graph, token_idx):
"""
Drop the node and subtree rooted at @token_idx.
"""
graph = deepcopy(dep_graph.graph)
roots = list(dep_graph.roots)
if dep_graph.inv_graph[token_idx]:
for parent, label in dep_graph.inv_graph[token_idx]:
graph[parent].remove((token_... | f4fdd5a33f540eb40b41869f4c009009ea607d3a | 57,930 |
def scan_line (line):
"""Scans a line of Greek poetry, as best as possible without knowing
whether ambiguous vowels are long by nature. Returns the meter as a list of
syllables marked LONG ('L'), SHORT ('S') or UNKNOWN ('X').
"""
line = line.strip()
meter = []
syl_list = syllabify(line)
... | 71de69a46f9b7b1c1e1cf6d60268d8b32865a316 | 57,931 |
def get_parser():
"""Construct the argument parser."""
prs = ap.ArgumentParser(
description="Extension (un)install helper for jupyter-tempvars"
)
prs.add_argument("command", choices=["install", "enable", "disable"])
return prs | 9c969f609c6a91db1175c1032d0dc4c26f34b452 | 57,932 |
def get_recommend(user_id, columns, session):
"""
Based on the history list, get the recommended level for the given user.
:param user_id: target user_id
:param columns: columns
:return:recommend dictionary
"""
history_list = find_list(10, session) # TODO: 期限を設定ファイルに抜き出し
# Generate a us... | 6cb473626fb4e52987c93d749719f5274f548001 | 57,933 |
def env_message(in_message):
"""
Arguments
---------
inMessage : string
the message being passed
Returns
-------
string : the response to the message
"""
return "" | 83a7077f928461dcc45b28792a18786c238600d4 | 57,934 |
def add_options(options):
# type: (List[Callable]) -> Callable
"""
Used as an annotation for click commands.
Allow to add a list of options to the command
From https://stackoverflow.com/questions/40182157/python-click-shared-options-and-flags-between-commands
:param options: List of options to ... | 50745ce82804dca83883d7550f78988c8392f80f | 57,935 |
from typing import Union
from datetime import datetime
from typing import Optional
from typing import Callable
from typing import Dict
from typing import Any
def weekly_partitioned_config(
start_date: Union[datetime, str],
timezone: Optional[str] = None,
fmt: Optional[str] = None,
) -> Callable[[Callable[... | 7250535b414c80ed886b45bcff51bd3965028c13 | 57,936 |
import time
def unix_time():
""" Returns the current Unix timestamp. """
t = str(int(time.time()))
return Response("%s\n" % t, media_type="text/plain") | 1b316789ee9e6a1b9f451700c0485d4d9c05798b | 57,937 |
import os
import requests
def get_source_repo(target, auth=None):
"""Get the source repo for a given repo.
Parameters
----------
target : str
The GitHub organization/repo
auth : str, optional
The GitHub authorization token
Returns
-------
str
A formatted PR en... | 285636537155979fbaa31f53f313de75540223a2 | 57,938 |
import forge
def copy_signature(template_function: Callable, include=None, exclude=None) -> Callable:
"""A wrapper around :py:func:`forge.copy` that silently fails if ``forge`` is not installed"""
def wrapper(target_function: Callable):
try:
except ImportError:
return target_funct... | 7fbb1a3f2d26d77d7d8fa9ec4442a008602f3ba0 | 57,939 |
def pretty_plattforms(value: dict) -> str:
"""Pretty prints the plattform dictionary"""
items = [
'\n' + ' ' * 4 + repr(key) + ': ' + _pretty_list(value[key], len(repr(key)))
for key in value
]
return '{%s}' % (','.join(items) + ',\n') | 627f8148deb31e2eea41e8be7cf84d49d85d726c | 57,940 |
def group_data_on_stations(place_data, outfile=None):
"""Organize the precipitation data on stations.
Parameters
----------
place_data : list of dicts
The precipitation data, grouped on places.
outfile : string, optional
A file to write the grouped data to.
Returns
-------
... | c5d80151a3543ba191336b2a80b4c8cda90b0054 | 57,941 |
def create_filter(attributes, model):
"""
Helper function that creates filter condition based on available attributes
:param attributes: attributes consisting of model attributes and values
:rtype attributes: dict
:param model: Model instance that handles filtering
:rtype model: pynamodb.models... | 70b51c5696e2f54d5b1b23cf59309140770a73ea | 57,942 |
import argparse
def parse_args():
""" Prepare the parser for the CLI. """
parser = argparse.ArgumentParser(
description=DESCRIPTION
)
parser.add_argument(
"--module-path",
required=True,
help="Path to the module that contains the python package that the PYTHONPATH shoul... | a7c80ad75aea5747c4cd8819a276664eda2c571b | 57,943 |
def _create_machine_packet(conn, public_key, machine_name, image,
size, location, cloud_init, project_id=None):
"""Create a machine in Packet.net.
Here there is no checking done, all parameters are expected to be
sanitized by create_machine.
"""
key = public_key.replace(... | f556a9e33cceec493e7e4b9b8910e0a7a210e4c6 | 57,944 |
def gauss(mu=0, si=25, length=100, maxv=30000):
"""
Create a numpy array containing a Gaussian function
:param mu: Mu (peak offset) of Gaussian
:type mu: float
:param sigma: Sigma (standard deviation) of Gaussian
:type sigma: float
:param length: Length of array
:type length: int
:p... | 6716981bfa73f8795a9fb1364edc173e1783c68f | 57,945 |
import os
import json
def load_dataset(kind):
"""Loads a dataset from the Olympus dataset library.
Args:
kind (str): kind of Olympus dataset to load.
Returns:
(tuple): tuple containing:
data (array): numpy array where each row is a sample and each column is a feature/target. ... | 8489cb6a7d6bec104fca7eac91d6b1a8c1630a73 | 57,946 |
def _polygon_array_non_empty(dtype):
"""
Create an example length 2 array to register with Dask.
See https://docs.dask.org/en/latest/dataframe-extend.html#extension-arrays
"""
return PolygonArray(
[
[[1.0, 1.0, 2.0, 1.0, 2.0, 2.0, 1.0, 2.0, 1.0, 1.0],
[1.1, 1.1, 1.5,... | 50dcc985ea6678c4f3fa9813d306872228a3fc93 | 57,947 |
import numpy
def replace_df_nulls(DF, null_list):
"""For each column in input DataFrame, replace with null and values in null_list.
Args:
DataFrame to replace missing values with null,
List of values to replace with null.
Returns:
Cleaned DataFrame."""
for col in... | 62637bf2ef33884bc6bb4dd6dd0d8270e3a4e84b | 57,948 |
def describe_token(token):
"""Returns a description of the token."""
if token.type == TOKEN_NAME:
return token.value
return _describe_token_type(token.type) | 9b493b81f5674bde7ca264a25bcc54a78720d882 | 57,949 |
def market_keys():
"""Standard keys for storage"""
return ['player_id', 'player_name', 'price', 'amount'] | 0a514f5ae1d138a1e84700ab15b88380186f70b0 | 57,950 |
def build_cnt_mask(np_arr, mask_size=None):
""" Build an exterior rectangle mask based on contour
Parameters
-------
np_arr : np.array
contour with standard numpy 2d array format
mask_size: None, scalar, list, or tuple
desired mask size for contour
Returns
-------
mask:... | fe859555a9348c19291432947b0483b50127f97d | 57,951 |
def consume_key(collection, key, use_key):
"""Consume key from collection based on use_key"""
if use_key is True:
return consume(collection, key)
elif use_key:
return consume(collection, use_key)
else:
return collection.get(key) | cc6afa1174cbb50834fb93e82d868734efc56246 | 57,952 |
def compute_average_atom_from_vol(DataMatrix, atom_pos, atom_ind, boxhalfsize):
"""
compute_average_atom_from_vol(DataMatrix,atom_pos,atom_ind,boxhalfsize)
Computes the average atom based on given DataMatrix and atom positions and
indices with the boxhalfsize.
DataMatrix - a 3D array for reconstruc... | f5f7d47928a22cb8af49214b635435ffe37ea21b | 57,953 |
def payment_label(value):
"""convert a payment key into its translated text"""
payments = config_get("PAYMENT", "MODULES")
for mod in payments.value:
config = config_get_group(mod)
if config.KEY.value == value:
return translation.ugettext(config.LABEL)
return value.capit... | aff4f23ac4e53ef5013257ac5829186b7b5debd0 | 57,954 |
import re
def ansi_to_curses(line: str) -> CursesLine:
# pylint: disable=too-many-branches
# pylint: disable=too-many-locals
"""Convert ansible color codes to curses colors
:param line: A string with ansi colors
:type line: string
:return: A list of str tuples [(x, s, c), (x, s, c)...]
:... | ef0d3995839870b137558fa0369d7ce0839fe85d | 57,955 |
def get_ads_from_path(path_i):
"""
"""
#| - get_ads_from_path
ads_i = None
# if "run_o_covered" in path_rel_to_proj_i:
if "run_o_covered" in path_i:
ads_i = "o"
elif "run_bare_oh_covered" in path_i:
if "/bare/" in path_i:
ads_i = "difjsi"
# elif "/oh"
... | 910ede094dd92c180724a950bce80c2d3e69f9b0 | 57,956 |
def consolidate_results(year_month, issues_for_period, resolved_in_month, reporters_config, simulation_metrics,
project_keys,
debug=False):
"""
It consolidates the results from the simulation with the information contained in the data.
:param debug: Detailed ... | 73c90a920be888a1e18739e05eec712e6f3b6029 | 57,957 |
def expected_queue(wires):
"""Expected queue for the dummy template."""
return [qml.RX(2 * i, wires=[wire]) for i, wire in enumerate(wires)] + [
qml.RY(3 * i, wires=[wire]) for i, wire in enumerate(wires)
] | 36ff6ff2369fd3bfecd12391e6c1602a958dd0af | 57,958 |
import pathlib
def module_to_path(module: str, suffix=".py") -> pathlib.Path:
"""convert module a.b.c to path(a/b/c)"""
return pathlib.Path(*module.split(".")).with_suffix(suffix) | 682fd05379e81a5d8d24f5d0f4ab8134cbbce0e7 | 57,959 |
def fetch_channel_list():
"""
チャンネル、DM、マルチDM一覧取得
"""
# channels_response = sc.api_call(
# api_method="channels.list",
# json={'exclude_members': True}
# )
channels_response = sc.conversations_list(
types="public_channel, private_channel, mpim, im",
limit=1000 ... | 601a3bf74c5ecc9a3c80abd99069786191a16c23 | 57,960 |
def ConvertValues_front_nose( TrackerLine , coordsNose , coordsNeck ):
"""
Parameters
----------
TrackerLine : TYPE
DESCRIPTION.
coordsNose : TYPE
DESCRIPTION.
coordsNeck : TYPE
DESCRIPTION.
Returns
-------
TYPE
DESCRIPTION.
"""
NoseNeckLine ... | 74f4640fb97c02496d33b772e9256411936f1867 | 57,961 |
def generate_graphlets(n, gtype = 'undirected'):
"""Generate all 2- to n-nodes graphlets"""
# n - number maximal of nodes to consider
# gtype - type of graphlet ('undirected','directed', or 'mixed')
if ( gtype == 'undirected' ):
x = [0, 2];
elif ( gtype == 'directed' ):
... | f4cbfbb47fcae107a5ec93d7709cb1ade8c88bbe | 57,962 |
async def get_comments_in_post(post: models.Post = Depends(resolve_post), db: Session = Depends(get_db),
page: int = 0, page_size: int = 100):
"""Get all comments in post."""
return crud.get_comments(db, post.id, offset=page * page_size, limit=page_size) | 5c7441ab32f6291bcdb14d7c199846b8ec4eff35 | 57,963 |
def infer_data_classes(df):
"""
Helper function to infer unique classes from data
"""
unique_class_groups = list(df[TARGET_LABEL].unique())
unique_classes = set()
for group in unique_class_groups:
for class_name in util.convert_str_to_list(group):
unique_classes.add(class_nam... | 1d26683640244364ff342fa7ae2423fa0be3510a | 57,964 |
import ctypes
import platform
import os
def get_space(folder, free=True):
"""get free or total space in MB for the folder"""
if platform.system() == 'Windows':
free_bytes = ctypes.c_ulonglong(0)
total_bytes = ctypes.c_ulonglong(0)
ctypes.windll.kernel32.GetDiskFreeSpaceExW(
... | b3ea592e215d0120df4d94813524c90a7ef3deaa | 57,965 |
def damped_sine(t, X, Y, f, k, x0):
"""Sine wave with variable phase (X, Y), frequency f,
damping rate k, and DC offset x0."""
return np.exp(-k * t) * (X * np.cos(2*np.pi*f*t) + Y * np.sin(2*np.pi*f*t)) + x0 | b826e42632a63f8a94a3783857c025cb761c5cb9 | 57,966 |
def index():
"""
Index View.
Landing page for the app at root of the site.
"""
render = make_response(render_template('spellcheck/index.html'))
render.headers.set('Content-Security-Policy', "default-src 'self'")
render.headers.set('X-Content-Type-Options', 'nosniff')
render.headers.set(... | 03439990c9df6c8ba27acc317919e566434a19e9 | 57,967 |
def file_queue(file_name, shuffle_data):
""" data_file_name_queue
Args:
file_name: txt file, file name or a list of file name
shuffle: True or False
"""
if type(file_name) is not list:
file_name = [file_name]
data_filenamequeue = tf.train.string_input_producer(file_name, shuffle=shuffle_data)
return data... | 553b73890887e915cc7efa5e47f503c485b1251b | 57,968 |
def clear_dots(image, dots=1, N=1):
"""清除噪点 clear noise dots
:param dots: number for near dots
:param N: clear times
:return: image
"""
image = image.convert('L') # black is 0, white is 255
image = clear_frame(image)
for i in range(0, N):
for y in range(1, image.size[1] - 1... | c401c8e8305c2897dcd083678f7f3c3d39f33e3c | 57,969 |
import torch
def calculate_accuracy(model, data_iterator, key=None):
"""Calculate the classification accuracy.
Parameters
----------
model : pytorch object
A pytorch model.
data_iterator : dict
A dictionary containing data iterator object.
key : str
A key to select whi... | ba6bb26a94b6e80febd942e2c54cccf3819d0647 | 57,970 |
def _load_search_bindings(pymux):
"""
Load the key bindings for searching. (Vi and Emacs)
This is different from the ones of prompt_toolkit, because we have a
individual search buffers for each pane.
"""
registry = Registry()
is_searching = InScrollBufferSearching(pymux)
in_scroll_buffe... | a9ee767f3cdccfa6b97e7eaf80e39ba28fca4634 | 57,971 |
import json
def dropTable(database: str, table: str) -> int:
"""Deletes a table in a database (including all of its content)
Parameters:\n
database (str): name of the database
table (str): name of the table
Returns:\n
0: successful operation
1: an ... | 5f0d30a73f7e1a1abe9ec885534a718982a82b0f | 57,972 |
from typing import List
from typing import Dict
def construct_tree(cells: List,
spatialIndex: rtree.index.Index = rtree.index.Index(),
count: int = 0, idToNum: Dict = dict()):
"""
Builds or adds to an rtree with a list of cells
Args:
cells: list of spatial fe... | 80cdb34f05a30540f05d4b81a0dba0db6fab8362 | 57,973 |
def load_para_from_saved_model(model_path, verbose=False):
"""load the all parameters from the saved TensorFlow checkpoint
the format is dict -> {var_name(str): var_value(numpy array)}"""
reader = pywrap_tensorflow.NewCheckpointReader(model_path)
var_to_map = reader.get_variable_to_shape_map()
prin... | 6fedd677e20c7ec6d166ce07e7614c99cad968ea | 57,974 |
import yaml
import sys
def analysis_yaml(full_conf_path):
"""
解析yaml文件
Args:
full_conf_path: yaml配置文件路径
Returns:
"""
with open(full_conf_path, 'rt', encoding="utf8") as f:
try:
conf = yaml.load(f, Loader=Loader)
except yaml.YAMLError as e:
print(... | 6deb43245c96f93097c28a6c83da7e9d818d9d2a | 57,975 |
def _insert_into_block(index, level, block, current_rev, current_hex):
"""insert a new revision in a block
index: the index we are adding revision for
level: the depth of the current block in the trie
block: the block currently being considered
current_rev: the revision number we are adding
cur... | 349dedcf0276e75dca18a21d76f7599f8422a7be | 57,976 |
def right_ascending_super_operator(hamiltonian, isometry, unitary):
"""
binary mera right ascending super operator
Args:
hamiltonian (tf.Tensor): hamiltonian
isometry (tf.Tensor): isometry of the binary mera
unitary (tf.Tensor): disentanlger of the mera
Returns:
tf.Tens... | e94eac32bd7b7a569befd05464f7c2f7e779e611 | 57,977 |
def resattnet236(**kwargs):
"""
ResAttNet-236 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.chainer/mod... | 0525a23c4a9c3369d57a0c50c61eba0db30ae34b | 57,978 |
from datetime import datetime
def StringToTime(time):
"""
String To Time
Converts a string, provided by essentials or in same format, to a time for storage use in a program
time - String: the string you'd like to convert to a datetime object.
1999-09-24 12:00:00 >> Datetime (Object)
... | 28895a607ba2c2986de5c120252f0cb926bae8f3 | 57,979 |
def _exec_query_for_values(func, func_kwargs, func_params, parent_kwargs):
"""Execute `func` for value (scalar or iterable) inputs."""
var_iter_params, simple_params = _check_var_params_require_iter(
func_params, func_kwargs, **parent_kwargs
)
if not var_iter_params or var_iter_params.keys() ==... | 33e551f7c6b7e0c98a31f484715f88bf0ac5cec8 | 57,980 |
from pathlib import Path
from typing import Optional
def get_default_branch_from_local(repo_path: Path, remote: str) -> Optional[str]:
"""Get default branch from local repo"""
try:
command = ['git', 'symbolic-ref', f'refs/remotes/{remote}/HEAD']
result = execute_command(command, repo_path, pr... | 00c336974a5f75ad8ab686a043259635393f8abf | 57,981 |
def Fragment_get_decorator_type_name():
"""Fragment_get_decorator_type_name() -> std::string"""
return _RMF.Fragment_get_decorator_type_name() | 690cd0ba00f9415fd99f8a5be68482d511ac7455 | 57,982 |
def get_new_configured_app(dispatchers,
default_response_or_text=DEFAULT_ERROR_RESPONSE_TEXT, cors=None):
"""
Create new :class:`aiohttp.web.Application` and configure it.
:param dispatchers: list of Dispatcher instance
:param path: Path to your webhook.
:param default_re... | 60246b01d3987fbf37ac74f41f6bbbc6e3d14a56 | 57,983 |
from datetime import datetime
def parse_mars_syntax(block: str) -> t.List[str]:
"""Parses MARS list or range into a list of arguments; ranges are inclusive.
Types for the range and value are inferred.
Examples:
>>> parse_mars_syntax("10/to/12")
['10', '11', '12']
>>> parse_mars_s... | 497aea503702ce1ec565693b2ea10b2da6bb2475 | 57,984 |
def is_chain(curves):
"""
Description:
Tests if curves is an elliptic curve chain
Input:
curves - a list of elliptic curves (q,t,r,k,D)
Output:
bool - true iff curves is an elliptic curve chain
"""
try:
for c in curves:
as... | ea340972a6656b1b4744165ffb4874e3e4bb678a | 57,985 |
def byte(value):
"""Converts a char or int to its byte representation."""
if isinstance(value, str) and len(value) == 1:
return ord(value)
elif isinstance(value, int):
if value > 127:
return byte(value - 256)
if value < -128:
return byte(256 + value)
r... | 6ef59f49a5d0d49ee7222387a8615567ff9d6267 | 57,986 |
import random
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
""" 生成随机的字符串, 默认长度12个字符 """
return ''.join(random.choice(allowed_chars) for i in range(length)) | e3b3d5fafdb6617cda425aa08cf804381f5cece9 | 57,987 |
def ratio_banxinwpp_at_houchiweir():
"""
Real Name: Ratio BanXinWPP At HouChiWeir
Original Eqn: Allocation BanXin WPP/Total WPP Allocation At HouChiWeir
Units: m3/m3
Limits: (None, None)
Type: component
"""
return allocation_banxin_wpp() / total_wpp_allocation_at_houchiweir() | af5a1ca2c9414d4c63dd8c75b28b3fe85c63d9e3 | 57,988 |
def get_assets(game):
"""Gets the embed colour and thumbnail"""
colour = None
thumbnail = None
wilds = ["wild", "wild+4"]
if game.current_card[0] in wilds:
colour = hex_colours[game.current_card[1]]
thumbnail = wild if game.current_card[0] == "wild" else wild_plus_four
else:
... | c7676e621bb7326063f06e25be1afcb3f52b9773 | 57,989 |
import math
def obs_lidar_pseudo(self, observation, lidar_num_bins=16, lidar_max_dist=0.9, lidar_alias=True, lidar_exp_gain=1.0,
distance=None):
"""
based on: https://github.com/openai/safety-gym/blob/master/safety_gym/envs/engine.py line 993
Return a robot-centric lidar observation o... | 55d178c683b0c59c84b68c2bdb8e3e58d863b5e4 | 57,990 |
def get_loss_criterion(name, weight=None):
"""
Returns the loss function based on the loss_str.
:param name: specifies the loss function to be used
:param weight: a manual rescaling weight given to each class
:param ignore_index: specifies a target value that is ignored and does not contribute to th... | bfa76386e53bdf66177e16d1ad3ddc1aeac0eefd | 57,991 |
from datetime import datetime
def pymongo_client(request):
"""Get a client to the mongo database"""
logger.info("Get a mongomock client")
start_time = datetime.datetime.now()
mock_client = MongoClient()
def teardown():
print('\n')
logger.info("Deleting database")
mock_cli... | af71ad51ed5bb936de1584bfa352358067cb20ab | 57,992 |
def rmse_metric_np(y_true, y_pred):
"""
numpy compliant rmse metric
"""
y_true = y_true
y_pred = y_pred
diff = y_true - y_pred
square = np.square(diff)
mean = np.mean(np.mean(square, axis=0))
rmse_error = np.sqrt(mean + 0.00001)
return rmse_error | ab8afaed97ed5b2c5585783ebe070322d859db90 | 57,993 |
import warnings
import math
def geographic_to_spherical(geographic: np.ndarray) -> np.ndarray:
"""
Converts coordinates in (latitude, longitude) format with angles in degrees
to spherical coordinates with angles in radians
:param geographic: An array of shape (N, 3) with rows being (latitude, longitud... | e615ede64882df5fb5ff5200267a66d5effb87cc | 57,994 |
def select_frame(**params):
"""切换Frame"""
return [
'self.driver.switch_to.default_content()',
"self.driver.switch_to.frame('{target}')".format(**params)
] | 76939cadb680554fecd5bf481970a70a37be13a7 | 57,995 |
def _create_doc_string(ESI_parameters, function_dict):
"""
Create a docstring for the function
:param ESI_parameters:
:param function_dict:
:return: docstring
:rtype: string
"""
parameter_description = _get_parameters_with_description(function_dict,
... | 9850c0b780a50e423b98d916c84f3c1254c6abed | 57,996 |
def meta_columns(model,exclude=[], get_metacolumns=None, fields = None):
"""
Generate columns metadata for a given Django model.
You could provide the `get_metacolumns` function to generate
custom metadata for some fields.
"""
if not fields:
fields = get_field_list(model, exclude = exclu... | 8408efa91f59e6e1a8c983bb6f8f434d9068e87f | 57,997 |
def mlist(self, node1="", node2="", ninc="", **kwargs):
"""Lists the MDOF of freedom.
APDL Command: MLIST
Parameters
----------
node1, node2, ninc
List master degrees of freedom from NODE1 to NODE2 (defaults
toNODE1) in steps of NINC (defaults to 1). If NODE1 = ALL
(defaul... | 611cd462d34cd4de0e34cb262549fc6cff40127d | 57,998 |
import yaml
def _get_benchmark(platform: str, command: str) -> dict:
"""Get benchmark structured datas."""
# template_index = parser.search_template_index(platform, command)
command = str(command.replace(" ", "_"))
with open(
"tests/" + platform + "_" + command + "/" + platform + "_" + command... | 4d98fac166a979343d0bb849eb2000e434edea78 | 57,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.