content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _safe_isnan(x):
"""Wrapper for isnan() so it won't fail on non-numeric values."""
try:
return isnan(x)
except TypeError:
return False | 5,341,200 |
def get_system( context, system_id = None ):
"""
Finds a system matching the given identifier and returns its resource
Args:
context: The Redfish client object with an open session
system_id: The system to locate; if None, perform on the only system
Returns:
The system resource... | 5,341,201 |
def train_unloading_station_pop(station, train, escalator):
"""
calculate the population of the platform while people are disembarking
from the train. Each run reprisents the passing of one second in time.
"""
"""
People exit the train, but first we need to calculate the train boarding,
and ... | 5,341,202 |
def assert_no_cycle(
g: networkx.DiGraph
) -> None:
"""If the graph has cycles, throws AssertionError.
This can be used to make sure that a refinements graph is a DAG.
Parameters
----------
g :
A refinements graph.
"""
logger.debug('Looking for cycles in belief graph')
try:... | 5,341,203 |
def cartesian_to_polar(x, y, xorigin=0.0, yorigin=0.0):
"""
Helper function to convert Cartesian coordinates to polar coordinates
(centred at a defined origin). In the polar coordinates, theta is an
angle measured clockwise from the Y axis.
:Parameters:
x: float
X coordinate of po... | 5,341,204 |
def keypoint_dict_to_struct(keypoint_dict):
""" parse a keypoint dictionary form into a keypoint info structure """
keypoint_info_struct = KeypointInfo()
if 'keypoints' in keypoint_dict:
for k in keypoint_dict['keypoints']:
keypoint = keypoint_info_struct.keypoints.add()
key... | 5,341,205 |
def softmax_regression(img):
"""
定义softmax分类器:
只通过一层简单的以softmax为激活函数的全连接层,可以得到分类的结果
Args:
img -- 输入的原始图像数据
Return:
predict -- 分类的结果
"""
predict = paddle.layer.fc(
input=img, size=10, act=paddle.activation.Softmax())
return predict | 5,341,206 |
def BlockdevWipe(disk, offset, size):
"""Wipes a block device.
@type disk: L{objects.Disk}
@param disk: the disk object we want to wipe
@type offset: int
@param offset: The offset in MiB in the file
@type size: int
@param size: The size in MiB to write
"""
try:
rdev = _RecursiveFindBD(disk)
ex... | 5,341,207 |
def incremental_quality(
wavelength: ndarray,
flux: ndarray,
*,
mask: Optional[Union[Quantity, ndarray]] = None,
percent: Union[int, float] = 10,
**kwargs,
) -> Tuple[ndarray, ndarray]:
"""Determine spectral quality in incremental sections.
Parameters
----------
wavelength: arra... | 5,341,208 |
def plot_ci_forest(n, ci_term, estimator, features, targets):
"""confidence interval plot for forest estimator"""
"""
Parameters
----------
n: int
The n timestamp of prediction going to be plotted
ci_term:
"""
predictions = []
for est in estimator.estimators_:
... | 5,341,209 |
def get_platform():
"""Gets the users operating system.
Returns:
An `int` representing the users operating system.
0: Windows x86 (32 bit)
1: Windows x64 (64 bit)
2: Mac OS
3: Linux
If the operating system is unknown, -1 will be returned.
"""
... | 5,341,210 |
def count_number_of_digits_with_unique_segment_numbers(displays: str) -> int:
"""Counts the number of 1, 4, 7 or 8s in the displays."""
displays = [Display.from_string(d) for d in displays.splitlines()]
num_digits = 0
for display in displays:
num_digits += sum(len(c) in (2, 3, 4, 7) for c in dis... | 5,341,211 |
def svo_filter_url(telescope, photofilter, zeropoint='AB'):
"""
Returns the URL where the filter transmission curve is hiding.
Requires arguments:
telescope: SVO-like name of Telescope/Source of photometric system.
photofilter: SVO-like name of photometric filter.
Optional:
... | 5,341,212 |
def calculate_sampling_rate(timestamps):
"""
Parameters
----------
x : array_like of timestamps, float (unit second)
Returns
-------
float : sampling rate
"""
if isinstance(timestamps[0], float):
timestamps_second = timestamps
else:
try:
v_parse_date... | 5,341,213 |
async def main(inventory: List[str], macaddr: MacAddress):
"""
Given an inventory of devices and the MAC address to locate, try to find
the location of the end-host. As a result of checking the network, the
User will see an output of either "found" identifying the network device
and port, or "Not f... | 5,341,214 |
def compute_ss0(y, folds):
"""
Compute the sum of squares based on null models (i.e., always predict the average `y` of the training data).
Parameters
----------
y : ndarray
folds : list of ndarray
Each element is an ndarray of integers, which are the indices of members of the fold.
... | 5,341,215 |
def read_logging_data(folder_path):
"""
Description:\n
This function reads all csv files in the folder_path folder into one dataframe. The files should be in csv format and the name of each file should start with 'yrt' and contain '_food_data' in the middle. For example, yrt1999_food_data123.csv is a va... | 5,341,216 |
def get_user_strlist_options(*args):
"""
get_user_strlist_options(out)
"""
return _ida_kernwin.get_user_strlist_options(*args) | 5,341,217 |
def SendKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None:
"""
Simulate typing a key.
key: int, a value in class `Keys`.
"""
keybd_event(key, 0, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey, 0)
keybd_event(key, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0... | 5,341,218 |
def coord_sampler(img, coords):
""" Sample img batch at integer (x,y) coords
img: [B,C,H,W], coords: [B,2,N]
returns: [B,C,N] points
"""
B,C,H,W = img.shape
N = coords.shape[2]
batch_ref = torch.meshgrid(torch.arange(B), torch.arange(N))[0]
out = img[batch_ref, :, coords[:,1... | 5,341,219 |
def directory(name, *args):
"""
Returns the directory with the specified name, as an absolute path.
:param name: The name of the directory. One of "textures" or "models".
:args Elements that will be appended to the named directory.
:return: The full path of the named directory.
"""
top = os.... | 5,341,220 |
def adapt_ListOfX(adapt_X):
"""This will create a multi-column adapter for a particular type.
Note that the type must itself need to be in array form. Therefore
this function serves to seaprate out individual lists into multiple
big lists.
E.g. if the X adapter produces array (a,b,c)
then this ... | 5,341,221 |
def add_sighting(pokemon_name):
"""Add new sighting to a user's Pokédex."""
user_id = session.get('user_id')
user = User.query.get_or_404(user_id)
pokemon = Pokemon.query.filter_by(name=pokemon_name).first_or_404()
# 16% chance logging a sighting of a Pokémon with ditto_chance = True will
... | 5,341,222 |
def edit_colors_names_group(colors, names):
"""
idx map to colors and its names. names index is 1 increment up
based on new indexes (only 0 - 7)
"""
# wall
colors[0] = np.array([120, 120, 120], dtype = np.uint8)
names[1] = 'wall'
# floor
colors[1] = np.array([80, 50, 50], dt... | 5,341,223 |
def download_last_year():
"""下载当年国债利率数据至本地"""
content_type = 'application/x-msdownload'
url = 'http://yield.chinabond.com.cn/cbweb-mn/yield_main?locale=zh_CN#'
driver = make_headless_browser_with_auto_save_path(
DATA_DIR, content_type)
driver.get(url)
time.sleep(1)
# driver.execute_s... | 5,341,224 |
def check(a, b, obj_type):
"""
Check that the sent and recv'd data matches.
"""
if obj_type in ("bytes", "memoryview"):
assert a == b
elif obj_type == "numpy":
import numpy as np
np.testing.assert_array_equal(a, b)
elif obj_type == "cupy":
import cupy
cu... | 5,341,225 |
def semidoc_mass_dataset(params,
file_names,
num_hosts,
num_core_per_host,
seq_len,
num_predict,
is_training,
use_bfloat16=False,
... | 5,341,226 |
def ListChrootSnapshots(buildroot):
"""Wrapper around cros_sdk --snapshot-list."""
cmd = ['cros_sdk', '--snapshot-list']
cmd_snapshots = RunBuildScript(
buildroot, cmd, chromite_cmd=True, stdout=True)
return cmd_snapshots.output.splitlines() | 5,341,227 |
async def post_github_webhook(
request: Request,
logger: BoundLogger = Depends(logger_dependency),
http_client: httpx.AsyncClient = Depends(http_client_dependency),
arq_queue: ArqQueue = Depends(arq_dependency),
) -> Response:
"""Process GitHub webhook events."""
if not config.enable_github_app:... | 5,341,228 |
def _load_cache(b_cache_path):
""" Loads the cache file requested if possible. The file must not be world writable. """
cache_version = 1
if not os.path.isfile(b_cache_path):
display.vvvv("Creating Galaxy API response cache file at '%s'" % to_text(b_cache_path))
with open(b_cache_path, 'w')... | 5,341,229 |
def nmad_filter(
dh_array: np.ndarray, inlier_mask: np.ndarray, nmad_factor: float = 5, max_iter: int = 20, verbose: bool = False
) -> np.ndarray:
"""
Iteratively remove pixels where the elevation difference (dh_array) in stable terrain (inlier_mask) is larger \
than nmad_factor * NMAD.
Iterations w... | 5,341,230 |
def process_contexts(server, contexts, p_ctx, error=None):
"""Method to be called in the auxiliary context."""
for ctx in contexts:
ctx.descriptor.aux.initialize_context(ctx, p_ctx, error)
if error is None or ctx.descriptor.aux.process_exceptions:
ctx.descriptor.aux.process_context(... | 5,341,231 |
def setup_output_vcf(outname, t_vcf):
"""
Create an output vcf.Writer given the input vcf file as a templte
writes the full header and
Adds info fields:
sizeCat
MEF
Returns a file handler and a dict with {individual_id: column in vcf}
"""
out = open(outname, 'w')
line = t... | 5,341,232 |
def load_json_file():
"""loads the json file"""
dirname = os.path.dirname(os.path.abspath(__file__))
json_filepath = os.path.join(dirname, "rps101_data.json")
with open(json_filepath) as f:
json_load = json.load(f)
return json_load | 5,341,233 |
def validate_processing_hooks():
"""Validate the enabled processing hooks.
:raises: MissingHookError on missing or failed to load hooks
:raises: RuntimeError on validation failure
:returns: the list of hooks passed validation
"""
hooks = [ext for ext in processing_hooks_manager()]
enabled =... | 5,341,234 |
def rnn_stability_loss(rnn_output, beta):
"""
REGULARIZING RNNS BY STABILIZING ACTIVATIONS
https://arxiv.org/pdf/1511.08400.pdf
:param rnn_output: [time, batch, features]
:return: loss value
"""
if beta == 0.0:
return 0.0
# [time, batch, features] -> [time, batch]
l2 = tf.sqr... | 5,341,235 |
def test_http_request_proxy_error_based_on_status(mock_base_http_request, client):
"""
When http request return status code 407 then appropriate error message should display.
"""
# Configure
mock_base_http_request.return_value = mock_http_response(status=407)
# Execute
with pytest.raise... | 5,341,236 |
def import_csv_to_calendar_api():
"""The main route of the Project.\
If requested with a GET: renders the page of the import operation.
If requested with POST: Starts importing events in the file to be uploaded present in the POST data.
"""
if request.method == "GET":
return make_res... | 5,341,237 |
def xproto_fields(m, table):
""" Generate the full list of models for the xproto message `m` including fields from the classes it inherits.
Inserts the special field "id" at the very beginning.
Each time we descend a new level of inheritance, increment the offset field numbers by 100. The base
... | 5,341,238 |
def HyBO(objective=None, n_eval=200, path=None, parallel=False, store_data=True, problem_id=None, **kwargs):
"""
:param objective:
:param n_eval:
:param path:
:param parallel:
:param kwargs:
:return:
"""
acquisition_func = expected_improvement
n_vertices = adj_mat_list = None
... | 5,341,239 |
def write_asset(asset, target_directory):
"""Write file represented by asset to target_directory
Args:
asset (dict): an asset dict
target_directory (str): path to a directory in which all files will be written
"""
target_path = os.path.join(
target_directory, asset["target_loca... | 5,341,240 |
def test(all=False):
"""Alias of `invoke test_osf`.
"""
if all:
test_all()
else:
test_osf() | 5,341,241 |
def create_decomp_expand_fn(custom_decomps, dev, decomp_depth=10):
"""Creates a custom expansion function for a device that applies
a set of specified custom decompositions.
Args:
custom_decomps (Dict[Union(str, qml.operation.Operation), Callable]): Custom
decompositions to be applied b... | 5,341,242 |
def get_lats_map(floor: float, ceil: float) -> Dict[int, List[float]]:
"""
Get map of lats in full minutes with quarter minutes as keys.
Series considers lat range is [-70;69] and how objects are stored in s3.
"""
full = full_minutes([floor, ceil])
out = {d: [d + dd for dd in OBJ_COORD_PART... | 5,341,243 |
def format_dict(body: Dict[Any, Any]) -> str:
"""
Formats a dictionary into a multi-line bulleted string of key-value pairs.
"""
return "\n".join(
[f" - {k} = {getattr(v, 'value', v)}" for k, v in body.items()]
) | 5,341,244 |
def block3(x, filters, kernel_size=3, stride=1, groups=32,
conv_shortcut=True, name=None):
"""A residual block.
# Arguments
x: input tensor.
filters: integer, filters of the bottleneck layer.
kernel_size: default 3, kernel size of the bottleneck layer.
stride: default... | 5,341,245 |
def test_docstring_remove():
"""Test removal of docstrings with optimize=2."""
import ast
import marshal
code = """
'module_doc'
def f():
'func_doc'
class C:
'class_doc'
"""
tree = ast.parse(code)
for to_compile in [code, tree]:
compiled = compile(to_compile, "<test>", "exec",... | 5,341,246 |
def random_sleep(n):
"""io"""
time.sleep(2)
return n | 5,341,247 |
def yolo2_mobilenet_body(inputs, num_anchors, num_classes, alpha=1.0):
"""Create YOLO_V2 MobileNet model CNN body in Keras."""
mobilenet = MobileNet(input_tensor=inputs, weights='imagenet', include_top=False, alpha=alpha)
# input: 416 x 416 x 3
# mobilenet.output : 13 x 13 x (1024*alpha)
... | 5,341,248 |
def LeastSquare_nonlinearFit_general(
X,
Y,
func,
func_derv,
guess,
weights=None,
maxRelativeError=1.0e-5,
maxIteratitions=100,
):
"""Computes a non-linear fit using the least square method following: http://ned.ipac.caltech.edu/level5/Stetson/Stetson2_2_1.html
It takes the follo... | 5,341,249 |
def _get_extracted_csv_table(relevant_subnets, tablename, input_path, sep=";"):
""" Returns extracted csv data of the requested SimBench grid. """
csv_table = read_csv_data(input_path, sep=sep, tablename=tablename)
if tablename == "Switch":
node_table = read_csv_data(input_path, sep=sep, tablename="... | 5,341,250 |
def main():
""" Runs the main parsing function on each list of powers and saves the resulting data. """
for power_type in [ARCANA, ARCANE_DISCOVERY, DOMAIN, EXPLOIT, HEX, SPELL]:
powers = parse_powers(
power_type['requests'],
power_type['list_regex'],
power_type['defa... | 5,341,251 |
def has_prefix(sub_s):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid.
:return: (bool) If there is any words with prefix stored in sub_s.
"""
for word in vocabulary_list:
if word.strip().startswith(sub_s):
return True
# Check all vocabularies in dictionary... | 5,341,252 |
def test_prompt_for_both_mnemonics(mock_bitcoincore):
"""Test prompting for both mnemonic and recovery mnemonic"""
mock_bitcoincore.return_value = AuthServiceProxy('testnet_txs')
estimate = {'blocks': 3, 'feerate': 1, }
mock_bitcoincore.return_value.estimatesmartfee.return_value = estimate
with mo... | 5,341,253 |
def test_jenkinslts_repofile_isfile(host):
"""
Tests if jenkins repo files for DEBIAN/EL systems is file type.
"""
assert host.file(DEBIAN_REPO_FILE).is_file or \
host.file(EL_REPO_FILE).is_file | 5,341,254 |
def work_out_entity(context,entity):
"""
One of Arkestra's core functions
"""
# first, try to get the entity from the context
entity = context.get('entity', None)
if not entity:
# otherwise, see if we can get it from a cms page
request = context['request']
if request.curr... | 5,341,255 |
def rectify(link:str, parent:str, path:str):
"""A function to check a link and verify that it should be captured or not.
For e.g. any external URL would be blocked. It would also take care that all the urls are properly formatted.
Args:
**link (str)**: the link to rectify.
**parent (str)**: the complete url of ... | 5,341,256 |
def send_start_run_message(run_number: int,
instrument_name: str,
broker_address: str=default_broker_address,
broker_version: str=default_broker_version):
"""Send a run start message to topic <instrument_name>_runInfo on the given brok... | 5,341,257 |
def cleanup_3():
"""
1. Sort keys of each json file.
2. rename media filenames with zero padding.
"""
sorted_keys = [
"id",
"name",
"description",
"collection_name",
"collection_description",
"transaction_time",
"eth_price",
"eth_price... | 5,341,258 |
def nested_pids_and_relations(app, db):
"""Fixture for a nested PIDs and the expected serialized relations."""
# Create some PIDs and connect them into different nested PID relations
pids = {}
for idx in range(1, 12):
pid_value = str(idx)
p = PersistentIdentifier.create('recid', pid_valu... | 5,341,259 |
def test_siren_not_existing_year(host, siren, year):
"""
Test the /company/siren/year endpoint. Should return a JSON and RC 404.
:param host: Fixture of the API host.
:param siren: Parametrise fixture of a SIREN.
:param year: Parametrise fixture of the year to return.
"""
response... | 5,341,260 |
def get_classifier(classifier):
""" Run given classifier on GLoVe embedding model """
if classifier is None:
exit(1)
print('Running ', classifier)
get_predictive_model(classifier)
#return classifier | 5,341,261 |
def main():
"""Main entry point"""
algorithms = [
# selectionsort,
insertionsort,
# Uncommend these lines after implementing algorithms
# bubblesort,
# quicksort,
# mergesort,
# heapsort,
]
benchmark(algorithms, max_array_size, initial_array_size=100, step=5)
plot_time()
# plot_access() | 5,341,262 |
def indentsize(line):
"""Return the indent size, in spaces, at the start of a line of text."""
expline = line.expandtabs()
return len(expline) - len(expline.lstrip()) | 5,341,263 |
def keyup_events(event, debug,):
""" Check events for when a key is released """
debug.check_strokes(event.key) | 5,341,264 |
def reprocess_subtitle_file(path, max_chars=30, max_stretch_time=3, max_oldest_start=10):
"""Combine subtitles across a time period"""
file_name, ext = os.path.splitext(path)
compressed_subtitle_file = file_name + '.ass'
subs = pysubs2.load(path)
compressed_subs = compress(subs, max_chars, max_stret... | 5,341,265 |
def read_github_repos(repo_names):
"""ENTRY POINT: Yields GitHub repos information as dictionaries from database."""
for repo_name in repo_names:
repo = GitHubRepo.query.filter_by(name=repo_name).first()
yield {
"name": repo.name,
"full_name": repo.full_name,
... | 5,341,266 |
def load(dataFormat,path,ignoreEntities=[],ignoreComplexRelations=True):
"""
Load a corpus from a variety of formats. If path is a directory, it will try to load all files of the corresponding data type. For standoff format, it will use any associated annotations files (with suffixes .ann, .a1 or .a2)
:param dataF... | 5,341,267 |
def test_edit_report_change_invalid_date(client, user, db_setup):
"""verifty that we can post data with a different date and change the
report in the database."""
report = Report.objects.get(reported_by__first_name="Homer")
url = reverse("tfat:edit_report", kwargs={"report_id": report.id})
data = ... | 5,341,268 |
def read(*parts):
"""
Build an absolute path from *parts* and return the contents of the resulting file.
Assumes UTF-8 encoding.
"""
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, *parts), "rb", "utf-8") as f:
return f.read() | 5,341,269 |
def read_idl_catalog(filename_sav, expand_extended=True):
"""
Read in an FHD-readable IDL .sav file catalog.
Deprecated. Use `SkyModel.read_fhd_catalog` instead.
Parameters
----------
filename_sav: str
Path to IDL .sav file.
expand_extended: bool
If True, return extended s... | 5,341,270 |
def guid2bytes(s):
"""Converts a GUID to the serialized bytes representation"""
assert isinstance(s, str)
assert len(s) == 36
p = struct.pack
return b"".join([
p("<IHH", int(s[:8], 16), int(s[9:13], 16), int(s[14:18], 16)),
p(">H", int(s[19:23], 16)),
p(">Q", int(s[24:], 16... | 5,341,271 |
def config(config_class=None, name="config", group=None):
"""
Class decorator that registers a custom configuration class with
`Hydra's ConfigStore API <https://hydra.cc/docs/tutorials/structured_config/config_store>`_.
If defining your own custom configuration class, your class must do the following:
... | 5,341,272 |
def display_title_screen():
""" Displays the title screen """
global screen
_done = False
background_music.play()
screen = pygame.display.set_mode(size , FULLSCREEN)
while not _done:
_done = _button_press("return")
screen.blit(title_screen,(0,0))
pygame... | 5,341,273 |
def truncate_words(text, max_chars, break_words=False, padding=0):
"""
Truncate a string to max_chars, optionally truncating words
"""
if break_words:
return text[:-abs(max_chars - len(text)) - padding]
words = []
for word in text.split():
length = sum(map(len, words)) + len(wo... | 5,341,274 |
def test__save_to_cloud_storage(mocker):
"""
Test saving examples, outputs and meta to bucket
Args:
mocker: mocker fixture from pytest-mocker
"""
upload_blob_mock = mocker.patch(
"cd_helper.CDHelper._upload_blob", return_value=upload_blob)
write_to_os_mock = mocker.patch(
"cd_helper.CDHelp... | 5,341,275 |
def interpolate_mean_tpr(FPRs=None, TPRs=None, df_list=None):
"""
mean_fpr, mean_tpr = interpolate_mean_tpr(FPRs=None, TPRs=None, df_list=None)
FPRs: False positive rates (list of n arrays)
TPRs: True positive rates (list of n arrays)
df_list: DataFrames with TPR, FPR columns (list of n D... | 5,341,276 |
def _generate_copy_from_codegen_rule(plugin, target_name, thrift_src, file):
"""Generates a rule that copies a generated file from the plugin codegen output
directory out into its own target. Returns the name of the generated rule.
"""
invoke_codegen_rule_name = _invoke_codegen_rule_name(
plugin... | 5,341,277 |
def mir_right(data):
"""
Append Mirror to right
"""
return np.append(data[...,::-1],data,axis=-1) | 5,341,278 |
def simulate_master(
mpi_comm, n_simulation_problem_batches_per_process, origin_simulation_problem,
simulation_problem_variations, predecessor_node_lists, truth_tables, max_t,
n_simulation_problems, db_conn, output_directory):
"""
Top-level function of Simulate mode for master. For every... | 5,341,279 |
def _add_policies_to_role_authorization_scope(
scope_checker: RoleAuthorizationScopeChecker, system_id: str, policies: List[PolicyBean]
):
"""添加权限到分级管理员的范围里"""
# 需要被添加的策略列表
need_added_policies = []
# Note: 以下代码里有调用 scope_checker 的 protected 方法是因为暂时不侵入修改scope_checker来提供一个public方法
try:
sc... | 5,341,280 |
def mask_nms(masks, bbox_scores, instances_confidence_threshold=0.5, overlap_threshold=0.7):
"""
NMS-like procedure used in Panoptic Segmentation
Remove the overlap areas of different instances in Instance Segmentation
"""
panoptic_seg = np.zeros(masks.shape[:2], dtype=np.uint8)
sorted_inds = li... | 5,341,281 |
def table_to_lookup(table):
"""Converts the contents of a dynamodb table to a dictionary for reference.
Uses dump_table to download the contents of a specified table, then creates
a route lookup dictionary where each key is (route id, express code) and
contains elements for avg_speed, and historic... | 5,341,282 |
def yaml2bib(
bib_fname: str,
dois_yaml: str,
replacements_yaml: Optional[str],
static_bib: Optional[str],
doi2bib_database: str,
crossref_database: str,
email: str,
) -> None:
"""Convert a yaml file to bib file with the correct journal abbreviations.
Parameters
----------
b... | 5,341,283 |
def _initialize_weights(variable_scope, n_head, n_input, n_hidden):
""" initialize the weight of Encoder with multiple heads, and Decoder
"""
with tf.variable_scope(variable_scope, reuse=tf.AUTO_REUSE):
all_weights = dict()
## forward, Each head has the same dimension ad n_hidden
... | 5,341,284 |
def add_run_qc_command(cmdparser):
"""
Create a parser for the 'run_qc' command
"""
p = cmdparser.add_command('run_qc',help="Run QC procedures",
description="Run QC procedures for sequencing "
"projects in ANALYSIS_DIR.")
# Defaults
def... | 5,341,285 |
def sh(cmd, stdin="", sleep=False):
""" run a command, send stdin and capture stdout and exit status"""
if sleep:
time.sleep(0.5)
# process = Popen(cmd.split(), stdin=PIPE, stdout=PIPE)
process = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE)
process.stdin.write(bytes(stdin, "utf-8"))
s... | 5,341,286 |
def array_to_slide(arr: np.ndarray) -> openslide.OpenSlide:
"""converts a numpy array to a openslide.OpenSlide object
Args:
arr (np.ndarray): input image array
Returns:
openslide.OpenSlide: a slide object from openslide
"""
assert isinstance(arr, np.ndarray)
slide = op... | 5,341,287 |
def baseline_replacement_by_blur(arr: np.array, patch_slice: Sequence,
blur_kernel_size: int = 15, **kwargs) -> np.array:
"""
Replace a single patch in an array by a blurred version.
Blur is performed via a 2D convolution.
blur_kernel_size controls the kernel-size of tha... | 5,341,288 |
def admit_dir(file):
""" create the admit directory name from a filename
This filename can be a FITS file (usually with a .fits extension
or a directory, which would be assumed to be a CASA image or
a MIRIAD image. It can be an absolute or relative address
"""
loc = file.rfind('.')
ext = '... | 5,341,289 |
def grad(values: list[int], /) -> list[int]:
"""Compute the gradient of a sequence of values."""
return [v2 - v1 for v1, v2 in zip(values, values[1:])] | 5,341,290 |
def subtract(
num1: Union[int, float], num2: Union[int, float], *args
) -> Union[int, float]:
"""Subtracts given numbers"""
sub: Union[int, float] = num1 - num2
for num in args:
sub -= num
return sub | 5,341,291 |
def get_submodules(module):
"""
Attempts to find all submodules of a given module object
"""
_skip = [
"numpy.f2py",
"numpy.f2py.__main__",
"numpy.testing.print_coercion_tables",
]
try:
path = module.__path__
except Exception:
path = [getfile(module)]
... | 5,341,292 |
def ucr_context_cache(vary_on=()):
"""
Decorator which caches calculations performed during a UCR EvaluationContext
The decorated function or method must have a parameter called 'context'
which will be used by this decorator to store the cache.
"""
def decorator(fn):
assert 'context' in ... | 5,341,293 |
def extract_value(item, key):
"""Get the value for the given key or return an empty string if no value is found."""
value = item.find(key).text
if value is None:
value = ""
else:
value = sanitize_value(value)
return value | 5,341,294 |
def create_train_test_split(data: pd.DataFrame,
split_size: float = .8,
seed: int = 42) -> list:
"""
takes the final data set and splits it into random train and test subsets.
Returns a list containing train-test split of inputs
Args:
... | 5,341,295 |
def add_devices(session, devices):
""" Adds the devices in the list to the data store
Args:
session: Active database session
devices: list of Device classes
"""
_add(session, devices)
session.commit() | 5,341,296 |
def calcRotationVector(vertexSelection, norm):
"""None"""
pass | 5,341,297 |
def get_vec(text, model, stopwords):
"""
Transform text pandas series in array with the vector representation of the
sentence using fasttext model
"""
array_fasttext = np.array([sent2vec(x, model, stopwords) for x in text])
return array_fasttext | 5,341,298 |
def convert_to_npz(kwargs):
"""
:param kwargs: npy-file:path or name:namestr and destination:path
"""
assert "identifier" in kwargs.keys(), "you need to define at least a npyfile-identifier"
identifier = kwargs["identifier"]
if "folder" in kwargs.keys():
folder = kwargs["folder"]
... | 5,341,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.