content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def A_real_deph(Q_deph, Kt_real_deph, deltaT_diff_deph):
"""
Calculates the real heatransfer area.
Parameters
----------
Q_deph : float
The heat load of dephlegmator, [W] , [J/s]
deltaT_diff_deph : float
The coefficient difference of temperatures, [degrees celcium]
Kt_real_de... | 5c70a6e179922f90fbb4fda859d6911eb1f048e6 | 3,648,000 |
from typing import Union
def is_1d_like(oned_like_object: Union[np.ndarray, np.void]) -> bool:
"""
Checks if the input is either a 1D numpy array or a structured numpy row.
Parameters
----------
oned_like_object : Union[numpy.ndarray, numpy.void]
The object to be checked.
Raises
... | c55a3e0e56d9cdce16bd478b882c72fdda5b6eba | 3,648,001 |
def PDef (inDict):
""" Create TableDesc from the contents of a Python Dictionary
Returns new Table Descriptor
inDict = Python dictionary with values, must be in the form produced
by PGetDict
"""
################################################################
#
outTD = TableDe... | b2024e0926b1484cf0eabc2874397b38eab39900 | 3,648,002 |
def minf(ar, min_val=nan):
"""
Gets the minimum value in the entire N-D array.
@param ar The array.
"""
sa = shape(ar)
np = 1
for n in sa:
np *= n
ar2 = reshape(ar, np)
ar2 = delete(ar2, get_nan_inds(ar2), 0)
cinds = []
if not isnan(min_val):
... | ee6bf44da7960d63702673d25c4582472190032b | 3,648,003 |
import os
import numpy
def read_from_netcdf(netcdf_file_name=None):
"""Reads boundary from NetCDF file.
:param netcdf_file_name: Path to input file. If None, will look for file in
repository.
:return: latitudes_deg: See doc for `_check_boundary`.
:return: longitudes_deg: Same.
"""
i... | ac2547a65eb1884216a95ab173d6b170c98a1dbb | 3,648,004 |
import random
import bisect
def generate_sector(size: int, object_weight: list) -> dict:
"""
Generates an Sector with Weighted Spawns
Args:
size: Int Representing the Size of the Sector (Size X Size)
object_weight: An Nested List with Object / Value Types
Examples:
generate_s... | 514195b66c707b2e0dd67ea47b57fe56c1d28a86 | 3,648,005 |
def rbf_kernel(theta, h=-1):
"""Radial basis function kernel."""
sq_dist = _pdist(theta)
pairwise_dists = _squareform(sq_dist) ** 2
if h < 0: # if h < 0, using median trick
h = _numpy.median(pairwise_dists)
h = _numpy.sqrt(0.5 * h / _numpy.log(theta.shape[0] + 1))
# compute the rbf... | 734c24724191693f47438e470784947252acc8bd | 3,648,006 |
def get_default_out_of_workspace_subcommands():
"""Returns a dict of default out-of-workspace subcommands as <name: `CliCommand`>s
:return: A dict of <name: `CliCommand`>
"""
new_cmd = NewCommand()
return {new_cmd.name(): new_cmd} | 533adb3b268aea407055917a137b0b58b19e422e | 3,648,007 |
import http
def test_json_view():
"""Turns a Python object into a response."""
def func(request):
return {'x': 1}
response = decorators.json_view(func)(mock.Mock())
assert isinstance(response, http.HttpResponse)
eq_(response.content, '{"x": 1}')
eq_(response['Content-Type'], 'applicat... | 4b4470d5cac3a5fd7bbefef67dc80beeacdcb384 | 3,648,008 |
def compile(what, mimetype, cwd=None, uri_cwd=None, debug=None):
"""
Compile a given text based on mimetype.
The text to compile must be provided as a Unicode object and this
function must return the compiled text as a Unicode object.
"""
try:
compiler = compilers[mimetype.lower()]
... | 17875ce5f760132e7e856bd2a7c062142d27364f | 3,648,009 |
def run_model(idx):
"""
Run BART on idx index from dataset.
Args:
idx (int): The index of the dataset.
Returns:
tuple: tuple with
fname: Filename
slice_num: Slice number.
prediction: Reconstructed image.
"""
masked_kspace, reg_wt, fname, slic... | 57913d5236af9d13d89a2de0e10a74c684c178cf | 3,648,010 |
def is_tt_tensor(arg) -> bool:
"""Determine whether the object is a `TT-Tensor` or `WrappedTT` with underlying `TT-Tensor`.
:return: `True` if `TT-Tensor` or `WrappedTT(TT-Tensor)`, `False` otherwise
:rtype: bool
"""
return isinstance(arg, TT) or (isinstance(arg, WrappedTT) and
not arg.tt.is_tt_m... | 767890ca0d8aca96deb6d777e7f972b5be99e11a | 3,648,011 |
def top_predicted_outcomes(proba_pred, index_to_outcome_dict, N_top = 3):
""" extract the most likely outcomes based on a 1d-array of predicted probabilities
Parameters
----------
proba_pred: numpy 1d-array
array containing the predicted probabilities
index_to_outcome_dict: dict
r... | 6f67140b6d50c5c7b7b43947d33cb1934d76440b | 3,648,012 |
def parse_kafka_table(beamsqltable, name, logger):
# loop through the kafka structure
# map all key value pairs to 'key' = 'value',
# except properties
"""
parse kafka parameter
"""
ddl = ""
kafka = beamsqltable.spec.get("kafka")
if not kafka:
message = f"Beamsqltable {name} ... | 5a8baf4ee5ef935b12cd90957854c6c1aed3c4e5 | 3,648,013 |
def linear_operator_from_num_variables(num_variables, type_, W):
"""Generates the linear operator for the TV lasso Nesterov function
from number of variables.
Parameters:
----------
num_variables : Integer. The total number of variables, including the
intercept variable(s).
"""
... | b91eea3a2adcfac27a0ae2635f7059ff1e7b5dad | 3,648,014 |
def hdi_of_mcmc(sample_vec, cred_mass=0.95):
"""
Highest density interval of sample.
"""
assert len(sample_vec), 'need points to find HDI'
sorted_pts = np.sort(sample_vec)
ci_idx_inc = int(np.floor(cred_mass * len(sorted_pts)))
n_cis = len(sorted_pts) - ci_idx_inc
ci_width = sorted_pts... | cbe3478be80ecef9a7f45df31b289400352284b8 | 3,648,015 |
def compare_AlphaFz(sq_amp,sq_amp_baseline):
"""
Compare the baseline alpha squared amplitude with that of a single epoch.
Parameters
----------
sq_amp: float
Alpha squared amplitude (Fz) from a single epoch
cnt_baseline: float
Baseline alpha squared amplitude (Fz)
... | 290560dc815393799d61f51a7684b4bde309dbac | 3,648,016 |
def get_filtered_acc_gas(database_year, start_year, end_year):
"""Returns gas avoided costs data
Parameters
----------
database_year: str
The year corresponding to the database that contains the avoided costs data.
Requires that year's database to have already been downloaded
us... | 7b6db413e25135c72864664ccd7e0b371dae7cd9 | 3,648,017 |
import os
import sys
def FindZ(outContoursPolygons, in_raster, tempWs, sessid):
""" Use the point within the polygon to determine the low and high
sides of the polygon"""
outEVT = os.path.join(tempWs,'outEVT' + sessid)
outEVTjoinedLayer = os.path.join(tempWs,'outEVTjoinedLayer')
outPolygPoints = os.path.join(te... | 9ad14240bdb9045e47080304abb87d8af017a868 | 3,648,018 |
import logging
import locale
def emr_app(config_name):
""" Application Factories
"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
handler = RotatingFileHandler('emr.log')
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)... | e2ba6ec0f186baf79ccf87b6ce9360afe93b17f4 | 3,648,019 |
from datetime import datetime
def _split_datetime_from_line(line):
"""Docker timestamps are in RFC3339 format: 2015-08-03T09:12:43.143757463Z, with everything up to the first space
being the timestamp.
"""
log_line = line
dt = datetime.datetime.utcnow()
pos = line.find(" ")
if pos > 0:
... | a5e373218d9a7c80562afb91a79e27a02647f89e | 3,648,020 |
def set_signal_winch(handler):
""" return the old signal handler """
global winch_handler
old_handler=winch_handler
winch_handler=handler
return old_handler | 1635090e9601dff4c132c1e26bd3072d8c5752c8 | 3,648,021 |
import argparse
from typing import Dict
from typing import Tuple
from typing import Optional
import uuid
import os
def entry_text_to_file(
args: argparse.Namespace,
entry: Dict) -> Tuple[Optional[Text], Optional[Text]]:
"""Extract the entry content and write it to the proper file.
Return the w... | 1a95bfa43e5375d4c8488b97df7d91b283aa063b | 3,648,022 |
import logging
from datetime import datetime
def visdom_loss_handler(modules_dict, model_name):
"""
Attaches plots and metrics to trainer.
This handler creates or connects to an environment on a running Visdom dashboard and creates a line plot that tracks the loss function of a
training loop as a func... | 4e53d1c3a1bd8b571960ea959a234f88c0f30c0b | 3,648,023 |
from rdkit.Chem.Draw.qtCanvas import Canvas
from rdkit import Chem
from rdkit.Chem import AllChem
def MolToQPixmap(mol, size=(300, 300), kekulize=True, wedgeBonds=True, fitImage=False, options=None,
**kwargs):
""" Generates a drawing of a molecule on a Qt QPixmap
"""
if not mol:
raise Val... | 8947edf412cd960c0c2735922db6a84a84622d06 | 3,648,024 |
def _unpad(string: str) -> str:
"""Un-pad string."""
return string[: -ord(string[len(string) - 1 :])] | dbd036afabc29047201a9ed2d6b299bb5fe3ba0f | 3,648,025 |
from pathlib import Path
import shutil
def copy_dir_to_target(source_directory: Path, destination_directory: Path) -> bool:
"""
Args:
source_directory: a folder to copy
destination_directory: the parent directory to copy source_directory into
Returns: True if copy was successful, False o... | 2dd67db56c17c787ea69189c52db11edcfcb0d3c | 3,648,026 |
import re
def vlanlist_to_config(vlan_list, first_line_len=48, other_line_len=44, min_grouping_size=3):
"""Given a List of VLANs, build the IOS-like vlan list of configurations.
Args:
vlan_list (list): Unsorted list of vlan integers.
first_line_len (int, optional): The maximum length of the l... | 7af9dd8f0572a0105b04a87ce6ab889c380a886b | 3,648,027 |
from typing import Optional
def get_next_url(bundle: dict) -> Optional[str]:
"""
Returns the URL for the next page of a paginated ``bundle``.
>>> bundle = {
... 'link': [
... {'relation': 'self', 'url': 'https://example.com/page/2'},
... {'relation': 'next', 'url': 'https:... | 0fafa4dc56fb5e03838652419e94dceb8aed9e75 | 3,648,028 |
def convert_sklearn_variance_threshold(operator, device, extra_config):
"""
Converter for `sklearn.feature_selection.VarianceThreshold`.
Args:
operator: An operator wrapping a `sklearn.feature_selection.VarianceThreshold` model
device: String defining the type of device the converted operat... | fc5d87e2fd27b8e40bb82689651f4a81ac64f1a5 | 3,648,029 |
def query_merchant_users(bc_app, merchant=None, start_time=None, end_time=None):
"""
query merchant users
:param bc_app: beecloud.entity.BCApp
:param merchant: merchant account, if not passed, only users associated with app will be returned
:param start_time: if passed, only users registered after i... | edf7df004bf97dbeb4e629ed8b1a3c2802519b91 | 3,648,030 |
def getUIQM(x):
"""
Function to return UIQM to be called from other programs
x: image
"""
x = x.astype(np.float32)
### UCIQE: https://ieeexplore.ieee.org/abstract/document/7300447
#c1 = 0.4680; c2 = 0.2745; c3 = 0.2576
### UIQM https://ieeexplore.ieee.org/abstract/document/7305804
... | e3e0c06ef5a08c232829afc196a973d6ff02b915 | 3,648,031 |
def cart2spher(x, y, z):
"""Cartesian to Spherical coordinate conversion."""
hxy = np.hypot(x, y)
rho = np.hypot(hxy, z)
#if not rho:
# return np.array([0,0,0])
theta = np.arctan2(hxy, z)
phi = np.arctan2(y, x)
return rho, theta, phi | bafd7e0cb6c0d152f0fbb9b7deaf16ce85114065 | 3,648,032 |
def get_mean_and_stdv(dataset):
"""return means and standard
deviations along 0th axis of tensor"""
means = dataset.mean(0)
stdvs = dataset.std(0)
return means, stdvs | 562f883d809f034be66244ad593a6f8a0bbe2ba5 | 3,648,033 |
from ToolBOSCore.Settings.ToolBOSConf import getConfigOption
from typing import Any
def getBuildRequirements():
"""
Returns a list of essential packages needed for a minimalistic
software installation tree (SIT).
Opposed to getMinRequirements() this contains everything needed to
b... | 1f0c91bd284d0249eaa0016792297a15c04323d5 | 3,648,034 |
import torch
def nms_3d(boxes, scores, nms_threshold):
"""
包装一下nms_gpu,该函数接收的数据维度是y1,x1,y2,x2,z1,z2 ,sores
:param boxes: tensor [n,(y1,x1,z1,y2,x2,z2)]
:param scores: tensor [n]
:param nms_threshold: 浮点标量
:return: keep: nms后保留的索引 tensor [m]
"""
# [n,(y1,x1,z1,y2,x2,z2)] => [n,(y1,x1,y2... | 4fbcd24309a50af1064ddd3eb5956b6b783f78c9 | 3,648,035 |
import re
def report_install_status(ctx, op_id):
"""
:param ctx: CSM Context object
:param op_id: operational ID
Peeks into the install log to see if the install operation is successful or not
"""
failed_oper = r'Install operation {} aborted'.format(op_id)
output = ctx.send("show install l... | 67e02e892029204679c4e766cbd0272f4eb08a3d | 3,648,036 |
def spltime(tseconds):
""" This gets the time in hours, mins and seconds """
hours = tseconds // 3600
minutes = int(tseconds / 60) % 60
seconds = tseconds % 60
return hours, minutes, seconds | a8ba14879da51ebbeac2ba201fc562a22fe13364 | 3,648,037 |
import re
import os
def _getShortName(filePath, classPath):
"""Returns the shortest reference to a class within a file.
Args:
filePath: file path relative to the library root path (e.g., `Buildings/package.mo`).
classPath: full library path of the class to be shortened (e.g., `Buildings.Class... | 3381b49aaa6e8b9f213bd1b6b6af0afa294f87a5 | 3,648,038 |
import time
import requests
def mine():
"""
This function will try to mine a new block by joining the negotiation process.
If we are the winner address, we will check the negotiation winner of the neighbour nodes, to grant that no node
has a different winner address.
"""
if blockchain is not N... | a7a313020d930d3fed1826e1e89165ee5b411311 | 3,648,039 |
def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0):
"""
Resolve host and port into list of address info entries.
Translate the host/port argument into a sequence of 5-tuples that contain
all the necessary arguments for creating a socket connected to that service.
host is a domain n... | 35ecba554f92b02645f9ba50eea8d8c70abf7723 | 3,648,040 |
def atomic_log(using=None):
"""
Decorator that surrounds atomic block, ensures that logged output requests will be stored inside database in case
of DB rollback
"""
if callable(using):
return AtomicLog(DEFAULT_DB_ALIAS)(using)
else:
return AtomicLog(using) | a1076ff275ab3c55e803bc78b1dcb31d5761335f | 3,648,041 |
import imp
def _readConfigFile(config_file, verbose):
"""Read configuration file options into a dictionary."""
if not os.path.exists(config_file):
raise RuntimeError("Couldn't open configuration file '%s'." % config_file)
try:
conf = {}
configmodule = imp.load_source("configu... | 22aff77a384f3c69d8f4ffa2cfafcb9662d54398 | 3,648,042 |
def run_street_queries(es, params_list, queries, formats):
"""Punto de entrada del módulo 'street.py'. Toma una lista de consultas de
calles y las ejecuta, devolviendo los resultados QueryResult.
Args:
es (Elasticsearch): Conexión a Elasticsearch.
params_list (list): Lista de ParametersPars... | bf052e7ea63280fde950d1663900f8420b6f4e97 | 3,648,043 |
def draw_text(text, bgcolor, plt_ax, text_plt):
"""
Render the text
:param str text: text to render
:param str bgcolor: backgroundcolor used to render text
:param matplotlib.axes.Axes plt_ax: figure sub plot instance
:param matplotlib.text.Text text_plt: plot of text
:return matplotlib.text.... | 478ada3b4fbb3add935713268415cd4606ef58b3 | 3,648,044 |
def compute_95confidence_intervals(
record, episode, num_episodes, store_accuracies, metrics=["AccuracyNovel",]
):
"""Computes the 95% confidence interval for the novel class accuracy."""
if episode == 0:
store_accuracies = {metric: [] for metric in metrics}
for metric in metrics:
stor... | 32e9c971c1396fb663e1b940a6d5cd7a09ab6c03 | 3,648,045 |
def _pytype(dtype):
""" return a python type for a numpy object """
if dtype in ("int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"):
return int
elif dtype in ("float16", "float32", "float64", "float128"):
return float
elif dtype in ("complex64", "complex128", "comp... | 47ed12c47ee4fa5986795b8f432e72cdd7ee945f | 3,648,046 |
def pca(x, output_dim, dtype, name=None):
"""Computes pca on the dataset using biased covariance.
The pca analyzer computes output_dim orthonormal vectors that capture
directions/axes corresponding to the highest variances in the input vectors of
x. The output vectors are returned as a rank-2 tensor with shape... | a4103450fd1d6c2175be5c546a75a9a3fe217786 | 3,648,047 |
def preorder(root: Node):
"""
Pre-order traversal visits root node, left subtree, right subtree.
>>> preorder(make_tree())
[1, 2, 4, 5, 3]
"""
return [root.data] + preorder(root.left) + preorder(root.right) if root else [] | af68cfc6d4434cad7908125504592253e6bacf46 | 3,648,048 |
import os
def main(argv=None):
"""Search a Cheshire3 database based on query in argv."""
global argparser, session, server, db
if argv is None:
args = argparser.parse_args()
else:
args = argparser.parse_args(argv)
session = Session()
server = SimpleServer(session, args.serverco... | 82e25cbc6f02c2c57191e35e3c9c356a72a02b65 | 3,648,049 |
import uuid
def generate_uuid() -> str:
"""
Generate UUIDs to use as `sim.base_models.Node` and `sim.base_models.Item` ids.
"""
return str(uuid.uuid4()) | 9428676bb633873a2f32c53172146486f1421234 | 3,648,050 |
def new_key_generator():
"""Generator of new keys.
Yields: str
"""
def _rnd_key():
return ''.join(nchoice(key_chars, size=next(key_lengths)))
while True:
key = _rnd_key()
while key in storage:
key = _rnd_key()
yield key | 111f523a5548e4e99ae9f3dcdeeafc73e4037693 | 3,648,051 |
def _style_mixture(which_styles, num_styles):
"""Returns a 1-D array mapping style indexes to weights."""
if not isinstance(which_styles, dict):
raise ValueError('Style mixture must be a dictionary.')
mixture = np.zeros([num_styles], dtype=np.float32)
for index in which_styles:
mixture[index] = which_styles[i... | 4bcb3dab052f171e514e9ba6abf10a74edcf612f | 3,648,052 |
def merge_dicts(a, b):
"""combine two dictionaries, assuming components are arrays"""
result = a
for k, v in b.items():
if k not in result:
result[k] = []
result[k].extend(v)
return result | de465179faf1bd9ace312fa4b21d332ac994b72b | 3,648,053 |
def parser_content_labelling_Descriptor(data,i,length,end):
"""\
parser_content_labelling_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "content_labelling", "contents" : unparsed_descriptor_contents... | 1aa9c68fd186df4dbda7200f2b40f617479a09d9 | 3,648,054 |
def is_norm(modules):
"""Check if is one of the norms."""
if isinstance(modules, (_BatchNorm, )):
return True
return False | 0f43c3691f3f5aeddd0ce21ff726cfa3ad25a856 | 3,648,055 |
def scheduler(system = system()):
"""Job scheduler for OLCF system."""
if not is_olcf_system(system):
raise RuntimeError('unknown system (' + system + ')')
return _system_params[system].scheduler | 5456cce3dc6ac46ac979983bb77c1645b05ba7f2 | 3,648,056 |
def simple_decoder_fn_inference(output_fn, encoder_state, embeddings,
start_of_sequence_id, end_of_sequence_id,
maximum_length, num_decoder_symbols,
dtype=dtypes.int32, name=None):
""" Simple decoder function for a sequenc... | 72436f6d866d78c5dc0c867fa950312f1baab0ef | 3,648,057 |
def listdir(path):
"""listdir(path) -> list_of_strings
Return a list containing the names of the entries in the directory.
path: path of directory to list
The list is in arbitrary order. It does not include the special
entries '.' and '..' even if they are present in the directory.
"""
... | d9096c979ffaa7c6d399822f4cf8aebc7e520415 | 3,648,058 |
import pathlib
def get_scripts_folder():
"""
return data folder to use for future processing
"""
return (pathlib.Path(__file__).parent.parent) | db236b35a06a0506f441ce6f11d8d93807592b04 | 3,648,059 |
def preresnet110(**kwargs):
"""Constructs a PreResNet-110 model.
"""
model = PreResNet(Bottleneck, [18, 18, 18], **kwargs)
return model | 814fc1aa82bd06155311d37a13a1108684a861ae | 3,648,060 |
def if_action(hass, config):
""" Wraps action method with state based condition. """
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is None:
_LOGGER.error("Missing configuration key %s", CONF_VALUE_TEMPLATE)
return False
return lambda: _check_template(hass, value_t... | d696ddd624b37f2dc8114b7da40a902409d8d61d | 3,648,061 |
from typing import Union
from typing import List
import re
def get_indy_cli_command_output(output: str, match: str,
return_line_offset: int = 1, remove_ansi_escape_sequences: bool = True,
multi: bool = False) -> Union[List[str],str]:
"""
Get the output for a specific indy cli command from STDOUT captu... | ff417bcace255cb89a5f4c9850939b18c7a2007f | 3,648,062 |
def reports():
"""Returns all reports in the system"""
reports = crud.report.get_reports()
return reports | 489b13cea39f6cfdd5e799e0586f81cc60cf0627 | 3,648,063 |
from sys import stderr
def md_to_rst(s, fname='?'):
"""
Return reStructuredText equiv string contents of Markdown string.
If conversion (via 'pandoc' cmdline) fails, returns raw Markdown.
Requires pandoc system utility: http://johnmacfarlane.net/pandoc/
Optional fname arg used only for logging/er... | 9d4d6f1a253916932e9dfd587f9ad9fc1c09478f | 3,648,064 |
import re
def parse_signature(signature):
"""
Parses one signature
:param signature: stanc3 function signature
:return: return type, fucntion name and list of function argument types
"""
return_type, rest = signature.split(" ", 1)
function_name, rest = rest.split("(", 1)
args = re.find... | 11da2fb6008274f8d9a959651a181f127c85a34e | 3,648,065 |
def logger(context, name):
"""Get PySpark configured logger
Args:
context: SparkContext
name (str): Name of the logger (category)
Returns:
Logger instance
"""
# TODO: add ccdc version to name
return context._jvm.org.apache.log4j.LogManager.getLogger(name) | c4dfb377c385008eba703bfff1564b922d09b1ac | 3,648,066 |
import torch
import time
def compute_fps(model, shape, epoch=100, device=None):
"""
frames per second
:param shape: 输入数据大小
"""
total_time = 0.0
if device:
model = model.to(device)
for i in range(epoch):
data = torch.randn(shape)
if device:
data = data.t... | b2e80cf695fe4e4be8890c4f28db8ae37e2f8dfe | 3,648,067 |
def onboarding_ml_app_patterns_post(ml_app_pattern): # noqa: E501
"""Create a new MLApp pattern
# noqa: E501
:param ml_app_pattern: MLApp pattern detail description
:type ml_app_pattern: dict | bytes
:rtype: MLAppPattern
"""
if connexion.request.is_json:
ml_app_pattern = MLAppPa... | 9d72c61c9fa04e387db72f67acf3bab9f88caaad | 3,648,068 |
def get_stats(ns_profnum, clear=False, **kwargs):
""""
Returns and optionally clears the Polyglot-to-ISY stats
:param ns_profnum: Node Server ID (for future use)
:param clear: optional, zero out stats if True
"""
global SLOCK, STATS
SLOCK.acquire()
st = STATS
if clear:
STATS[... | e8dbd350b9d9befe7b2c584c84f268a0c27decd5 | 3,648,069 |
def read_log_json():
""" Get all log documents/records from MondoDB """
limit = int(demisto.args().get('limit'))
# Point to all the documents
cursor = COLLECTION.find({}, {'_id': False}).limit(limit)
# Create an empty log list
entries = []
# Iterate through those documents
if cursor is n... | febef55ff06360148f5c87a875fd3f001e0f778a | 3,648,070 |
import json
def RecogniseForm(access_token, image, templateSign=None, classifierId=None):
"""
自定义模板文字识别
:param access_token:
:param image:图像数据(string),base64编码,注意大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式
:param templateSign:模板ID(string)
:param classifierId:分类器ID(int),这个参数与templateSign至少存在一... | 9a316a595c65b805970b1c0e5324b2b5c9342b31 | 3,648,071 |
from typing import Callable
def rectangle(
func: Callable[..., float], a: float, b: float, eps: float = 0.0001, *args, **kwargs
) -> float:
"""
Metode segi empat adalah metode integrasi paling sederhana.
Metode ini membagi domain integrasi sebanyak n buah
dan menjumlahkan seluruh luas segi empat ... | 11e844f59ce5bcbdffed59de0188c63eec7571ac | 3,648,072 |
def _rearrange_axis(data: np.ndarray,
axis: int = 0) -> tuple([np.ndarray, tuple]):
"""rearranges the `numpy.ndarray` as a two-dimensional array of size (n,
-1), where n is the number of elements of the dimension defined by `axis`.
Parameters
----------
data : :class:`numpy.nda... | 07310b1ddc287f949f439dcb1ac66b8b7d41e421 | 3,648,073 |
def landmarks_json():
"""Send landmark data for map layer as Geojson from database."""
features = []
for landmark in Landmark.query.all():
# get the first image of a landmark, if any
image = ""
if len(landmark.images) > 0:
image = landmark.images[0].imageurl
#... | 9ab914c3c5e54728f4ec5346c32acbb846091244 | 3,648,074 |
def extractTuples(data):
""" Saca las tuplas (palabra,prediccion),
y las devuelve como dos arrays entradas y
salidas """
inp = []
out = []
for r in data:
for i in range(len(r)):
for j in range(-CONTEXT_WINDOW,CONTEXT_WINDOW+1):
if j == CONTEXT_WINDOW or i+j <0... | 191e980808f65c6f4acd116e14eba44f0f1792a4 | 3,648,075 |
def _GetKeyKind(key):
"""Return the kind of the given key."""
return key.path().element_list()[-1].type() | c37f1d889e484390449de682e3d6c6b9d4521ce4 | 3,648,076 |
import yaml
def load_config() -> dict:
"""
Loads the config.yml file to memory and returns it as dictionary.
:return: Dictionary containing the config.
"""
with open('config.yml', 'r') as ymlfile:
return yaml.load(ymlfile, Loader=yaml.FullLoader) | 6e05aa4eb6a7d9862814f595ecdc89ffab145ee5 | 3,648,077 |
from typing import Tuple
from typing import List
from typing import Sequence
def find_column_equivalence(matrix, do_not_care) -> Tuple[List[int], List[Sequence]]:
""" Adapt find_row_equivalence (above) to work on columns instead of rows. """
index, classes = find_row_equivalence(zip(*matrix), do_not_care)
return i... | c47a3d2d3663fb0d52bdbf81b111416ab1f2f41d | 3,648,078 |
import re
import sys
def getBaseCount(reads, varPos):
"""
:param reads:
:param varPos:
"""
'''
returns the baseCount for the
'''
baseCount = {'A': 0, 'C': 0, 'G': 0, 'T': 0}
for read in reads:
readPos = 0
mmReadPos = 0
startPos = read.pos
try:... | 26503aebeb47ff949b09fdb4b8ada170f827d4f5 | 3,648,079 |
import inspect
def RegisterSpecs(func):
"""The decorator to register the specification for each check item object.
The decorator first tests whether it is involved in the outmost call of the
check item object. If so, it then goes through the args, kwargs, and defaults
to populate the specification.
Args:
... | 15c8275968a510a7e57993446a7b5f9f7eadeff4 | 3,648,080 |
from typing import Set
from pathlib import Path
def get_changes_to_be_committed() -> Set[Path]:
"""After every time `add` is performed, the filepath is added to this text file."""
return {Path(path) for path in path_to.changes_to_be_committed.read_text().split("\n") if path} | 84878432310511ae79dccebc7c66e0c658917616 | 3,648,081 |
def concatenate_weather_files(dir_path):
"""Concatenate all .nc files found in the directory set by path."""
# import all the files as datasets
fnames = get_weather_files(dir_path)
ds_list = []
for f in fnames:
with xr.open_dataset(f, engine='netcdf4') as ds:
ds_list.append(ds)
... | c644a8d69b71c9cd06467757f1cddc5589ff3680 | 3,648,082 |
def homepage(module=None, *match, **attr):
"""
Shortcut for module homepage menu items using the MM layout,
retrieves the module's nice name.
@param module: the module's prefix (controller)
@param match: additional prefixes
@param attr: attributes for the navigation item
... | 5523f87b16ab09c18deb3f915d4feea29e269540 | 3,648,083 |
def handle_fallthrough(event, path, query):
"""
Handles the fallthrough cases where no redirects were matched
"""
# If no fallthough response provider, 302 the whole website to the HOST that
# was input
if variables.FALLTHROUGH == None:
return redirect('//' + variables.HOST + path + quer... | 4568aeec2061eb947839d63472c23b565afd3c0c | 3,648,084 |
def vowel_space_area(F1a, F1i, F1u, F2a, F2i, F2u):
"""
Return vowel space area
Args:
F1a: (float) the 1. formant frequency of the vowel /a [Hz]
F1i: (float) the 1. formant frequency of the vowel /i [Hz]
F1u: (float) the 1. formant frequency of the vowel /u [Hz]
F2a: (float)... | 59649803154fdddcfd6173f68fcf4e9054f34343 | 3,648,085 |
def get_hosted_zone(domain):
"""Return a domain's hosted zone."""
return api.get(f"/api/domain/{domain['_id']}/records/") | 7d3d91a81563ab6918a85c39fb47b4e28de4f5d5 | 3,648,086 |
def align_spikes(spike_data, spt_dict, sp_win, type="max", resample=1,
contact=0, remove=True):
"""Aligns spike waves and returns corrected spike times
Parameters
----------
spike_data : dict
spt_dict : dict
sp_win : list of int
type : {'max', 'min'}, optional
resamp... | 38c62474e6c19c7492066254a7075ff4a34573ca | 3,648,087 |
def rgb2hsi(rgb: np.ndarray,
*,
axis: int=None) -> np.ndarray:
"""
Convert RGB to Hue Saturation Intensity
:param rgb:
:param axis:
:return:
"""
if axis is None:
axis = get_matching_axis(rgb.shape, 3)
big_m, little_m, chroma = _compute_chroma(rgb, ... | 55734347d1d102a183dd736a4d832b33ce17115c | 3,648,088 |
def get_movie_brief_actor(actor, soup):
"""
Getting brief data from individual movie webpage (for actor dictionary)
"""
headers=['actor','title','year','rating','vote','genre_list','budget','opening','gross_usa',\
'gross_cw','runtime','director','writer','star','distributor']
... | ceaaa05ae26681eddcc8f9ed1a28f43bcc83473f | 3,648,089 |
def mul(a: TensorableType, b: TensorableType) -> Tensor:
"""Returns the product of input tensor_objects with their local gradients"""
a = enforceTensor(a)
b = enforceTensor(b)
output = Tensor(a.data * b.data, requires_grad=(a.requires_grad or b.requires_grad))
output.save_for_backward([a, b])
... | dfa75b511b29360589bec594ef464b804dfa298b | 3,648,090 |
def split_multi(vds: 'VariantDataset', *, filter_changed_loci: bool = False) -> 'VariantDataset':
"""Split the multiallelic variants in a :class:`.VariantDataset`.
Parameters
----------
vds : :class:`.VariantDataset`
Dataset in VariantDataset representation.
filter_changed_loci : :obj:`bool... | 4c15b45806fbbb6782a27a2d123529e9b63ef622 | 3,648,091 |
from theano import tensor as T
import tensorflow as tf
def zeros(shape, dtype=K.floatx()):
"""Return all-zeros tensor of given shape and type."""
# As of Keras version 1.1.0, Keras zeros() requires integer values
# in shape (e.g. calling np.zeros() with the Theano backend) and
# thus can't be called w... | 5e48871e8c0183d6feb3f68b2275fb5abc7ff55e | 3,648,092 |
from sys import path
import csv
from typing import Counter
import tqdm
def nrc_emo_lex(headlines, bodies):
"""
Counts Number of words in a text associated with 8 different emotions.
Uses EmoLex lexicon: http://saifmohammad.com/WebPages/lexicons.html#EmoLex
"""
lexicon_path = "%s/../data/lexicons... | 71a7f26e3d0bfe1e5145f90b3e87bdaa1f66defd | 3,648,093 |
def accretion_cylinder(mbh, mdot, r):
"""rschw, omega, facc, teff, zscale = accretion_cylinder(mbh, mdot, r)"""
GM = cgs_graw * mbh * sol_mass
rschw = 2 * GM / cgs_c**2
omega = sqrt( GM / (r * rschw)**3 )
facc = 3 * GM * (mdot * mdot_edd(mbh)) / (8 * pi * (r * rschw)**3) \
* (1 - ... | b89573fc361d83dbb288cfa0760e844e611fac44 | 3,648,094 |
def cost_function_wrapper(theta, cost_function_parameters):
"""Wrapper for the Cost Function"""
cost_function_parameters['theta'] = theta
return cost_function(cost_function_parameters) | 1bd2e5e403514590e174ddd4198880320be80b99 | 3,648,095 |
def make_img_tile(imgs, path, epoch, aspect_ratio=1.0,
tile_shape=None, border=1, border_color=0):
"""
"""
if imgs.ndim != 3 and imgs.ndim != 4:
raise ValueError('imgs has wrong number of dimensions.')
n_imgs = imgs.shape[0]
tile_shape = None
# Grid shape
img_shape = np.array(imgs.shape[1:3])
... | 0e468b0d99e4419e8cbb4c53dce5ea1cfcbfb513 | 3,648,096 |
import pkg_resources
def dummy_plugin_distribution(dummy_plugin_distribution_name, save_sys_path):
"""Add a dummy plugin distribution to the current working_set."""
dist = pkg_resources.Distribution(
project_name=dummy_plugin_distribution_name,
metadata=DummyEntryPointMetadata(
f""... | cb79ad0c4cd1b8824afe592cef38bc002f44087a | 3,648,097 |
def parse_temperature_item(item):
"""Parse item for time and temperature
:param item: Definition, eg. '17.0 > 07:00'
:returns: dict with temperature and minutes"""
temp_time_tupel = item.split(">")
temperature = float(temp_time_tupel[0].strip())
minutes_from_midnight = calculate_minutes_from_mi... | ec1a8f501c392b68c559aa11d03995a44e09c1fd | 3,648,098 |
from pathlib import Path
import json
def add_file_to_dataset_view(user_data, cache):
"""Add the uploaded file to cloned repository."""
ctx = DatasetAddRequest().load(request.json)
user = cache.ensure_user(user_data)
project = cache.get_project(user, ctx['project_id'])
if not ctx['commit_message']... | bf253bbbfe183ef6f5a218831f17ba856d2cf2bc | 3,648,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.