content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_base_info_for_selector(selection_dict, selector_type):
"""
Sets up the basic dictionary for data filters to be added on the data
:param selection_dict:
:param selector_type:
:return:
"""
base_info_dict_for_selector = {
OPTION_TYPE: selector_type,
COLUMN_NAME: selectio... | 5,295,500 |
def run(spark: SparkSession, environment: str, date: str):
"""Main ETL script definition.
:return: None
"""
# execute ETL pipeline
logger = SparkLogger(spark)
logger.info(f"Executing job for {environment} on {date}")
data = extract_data(spark, date)
transformed = transform_data(data, da... | 5,295,501 |
def loadTagContextOverlap(infile, outfile):
"""load results from GAT analysis into database.
"""
P.load(infile, outfile, options="--add-index=track") | 5,295,502 |
def delete_imported_key_material(KeyId=None):
"""
Deletes key material that you previously imported. This operation makes the specified customer master key (CMK) unusable. For more information about importing key material into AWS KMS, see Importing Key Material in the AWS Key Management Service Developer Guide... | 5,295,503 |
def make_datasets(dataset, train_batch=None, test_batch=None, train_transforms=None, test_transforms=None, num_workers=1, **custom_args):
""" Helper to make new instances of training and testing datasets.
Args:
dataset Case-sensitive dataset name
train_batch Training batch size, None or 0 for ... | 5,295,504 |
def main(time_series: str, config: dict = {}, train: bool = True, test: bool = True):
"""Read all Rolling Window iterarion training files from a given time-series and train a SKTIME model for each.
Parameters
----------
time_series : str
_description_
config : dict, optional
Configu... | 5,295,505 |
def setup_module():
"""
See https://docs.pytest.org/en/6.2.x/xunit_setup.html
"""
global FRONTEND_ADDRESS
frontend_port = find_next_free_port()
backend_port = find_next_free_port(exclude_ports={frontend_port})
FRONTEND_ADDRESS = get_website_address(frontend_port)
start_svelte_dev_server(... | 5,295,506 |
def get_sentiment_by_id(sentiment_id):
"""
Returns the sentiment with given id
:param: sentiment_id
ID of the sentiment
:returns:
Sentiment with given ID
"""
sentiments = []
cursor = current_app.mongo.keywords.find({"request_id": sentiment_id})
for record in list(cursor... | 5,295,507 |
def clean_software_config(config):
"""Take an individual `config` data structure (as specified by
config_validation.SoftwareSchema) and return a 'clean' version suitable for
internal use. This allows for a simplified schema to be available to users
whilst preserving consistent internal data structures b... | 5,295,508 |
def distance_A(A, D):
"""Takes distance matrix D and material attribute/category
matrix A and finds the sum of the pairwise distances of
each entry compared to D. This function should be used
in an optimizer to generate an optimal A matrix.
Implements first term of Equation 4
Parameters:
D... | 5,295,509 |
def get_word_by_name(name):
"""Get word detail by name
As title
---
tags: [word]
parameters:
- name: name
description: 单词名字
in: path
type: string
required: true
responses:
200:
description: Word matched.
schema:
$ref: '#/defin... | 5,295,510 |
def group_peaks_naive_1pass_centroid(df, ppmtol=1.0):
"""Compute groups of peaks, naive, one-pass, control distance to centroid ."""
# compute group indexes
glabel = 0
start = 0
glabels = [0]
reltol = ppmtol * 1.0e-6
m1 = df.loc[0, 'm/z']
samples = [df.loc[0, '_sample']]
masse... | 5,295,511 |
def run_firfilter(no_trick, duration=0.000001):
"""[summary]
Arguments:
no_trick ([type]): [description]
Keyword Arguments:
duration (float): [description] (default: {0.000001})
Raises:
Exception: [description]
"""
h0 = np.zeros(n) # initial x0
E = ell(10., h0)
... | 5,295,512 |
def test_atomic_string_enumeration_3_nistxml_sv_iv_atomic_string_enumeration_4_1(mode, save_output, output_format):
"""
Type atomic/string is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/string/Schema+Instance/NISTSchema-SV-IV-atomic-string-enumeration-4.xsd",
... | 5,295,513 |
def cdfinv_r(fName=None,pdf=None):
"""
Calculates the inverse of the cumulative distribution function for
probability as a function of r.
*** Arguments ***
* fName * File name for retrieving sigma(r). If None, the user must
define a function to calculate the inverse CDF. Otherw... | 5,295,514 |
def _base_down(x, base=10):
"""
Floor `x` to the nearest lower ``base^n``, where ``n`` is an integer.
Parameters
----------
x : float
Number to calculate the floor from.
base : float, optional
Base used to calculate the floor.
Return
------
float
The nearest... | 5,295,515 |
def get_periodic_frame():
"""
Construct a simple periodic table dataframe organised by group and row. Note that
the lanthanides and actinides are each found in a single cell.
Returns
-------
:class:`pandas.DataFrame`
"""
table = pd.DataFrame(columns=np.arange(1, 19), index=np... | 5,295,516 |
def miller_rabin_d(n: int) -> bool:
"""Check if n is a prime number via deterministic Miller-Rabin test.
Miller showed that it is possible to make the algorithm deterministic by
only checking all bases ≤ O(lg(n)^2). Bach later gave a concrete bound, it
is only necessary to test all bases a ≤ 2lg(n)^... | 5,295,517 |
def save_output(results, output_directory="output"):
"""
Save report data in the given directory
Args:
results (OrderedDict): Parsing results
output_directory: The patch to the directory to save in
"""
aggregate_reports = results["aggregate_reports"]
forensic_reports = results[... | 5,295,518 |
def get_path_upload_avatar(instance, file):
"""Построение пути к файлу, format: (media)/avatar/user_id/photo.jpg"""
return f"avatar/user_{instance.id}/{file}" | 5,295,519 |
def is_category_url(url, ignore_exceptions=False):
"""This function identifies if a provided URL is for a category in the environment.
.. versionadded:: 2.1.0
:param url: The URL to be evaluated
:type url: str
:param ignore_exceptions: Determines if exceptions should not be raised
:type ignore... | 5,295,520 |
def test_get_all_devices():
"""Test getting all device info"""
devices = UEM.get_all_devices()
assert devices["Devices"][0]['Id']['Value'] == TEST_DEVICE_ID | 5,295,521 |
def maximum_time(time: str) -> str:
"""
Takes in a time with a single digit of either the hour part or minute part hidden with ?. The format of the time
is hh:mm. This returns the maximum possible time from the given input.
@param time: time of format hh:mm with a single digit of either the hour part or... | 5,295,522 |
def get_fd(file_or_fd, default=None):
"""Helper function for getting a file descriptor."""
fd = file_or_fd
if fd is None:
fd = default
if hasattr(fd, "fileno"):
fd = fd.fileno()
return fd | 5,295,523 |
def main():
"""程序主入口"""
parser = argparse.ArgumentParser()
parser.add_argument(dest="host", action="store", help="specify server")
parser.add_argument(
"-t",
"--type",
action="store",
required=False,
dest="type",
default="default",
help="host type... | 5,295,524 |
def evaluate_predictions(preds: List[List[float]],
targets: List[List[float]],
metric_func: Callable) -> List[float]:
"""
Evaluates predictions using a metric function and filtering out invalid targets.
:param preds: A list of lists of shape (data_size, num... | 5,295,525 |
def recommend_size(args, img):
""" Recommend size (in pixels) for populated image to reach 300 dpi"""
current_ppi = 72.0/img.scale
target_ppi = args.normal_ppi
scale = target_ppi/current_ppi
return (int(img.image.width*scale), int(img.image.height*scale)) | 5,295,526 |
def _basic_blueprint_test(blueprint_file_name,
test_name,
inputs=None,
timeout=None,
endpoint_name=None,
endpoint_value=None):
"""
Simple blueprint install/uninstall test.
:param... | 5,295,527 |
def retain_top_pct(vals, pct_keep):
"""
Retain as many components as you need to capture `pct_keep` proportion
of the overall value
"""
if pct_keep > 1 or pct_keep <= 0:
raise ValueError(
"Must set pct_keep between 0 and 1 be when using "
"'retain_top_pct' retention ... | 5,295,528 |
def test_curve_plot():
"""
Tests mpl image of curve.
"""
well = Well.from_las(FNAME)
fig = well.data['GR'].plot(return_fig=True)
return fig | 5,295,529 |
def new(dbname: str = 'pgdumplib', encoding: str = 'UTF8',
converter=None):
"""Create a new :py:class:`pgdumplib.dump.Dump` instance
:param str dbname: The database name for the dump (Default: ``pgdumplib``)
:param str encoding: The data encoding (Default: ``UTF8``)
:param converter: The data c... | 5,295,530 |
def infer(output_path):
"""Run inference."""
tf.logging.info("Run inference")
checkpoint = FLAGS.checkpoint_dir
with tf.gfile.GFile(os.path.join(checkpoint, "config.json")) as f:
config = json.load(f)
if FLAGS.num_gpus > 1:
config["num_gpus"] = FLAGS.num_gpus
tf.logging.info("# infer config %s", co... | 5,295,531 |
def audio(sec=3):
""" Record audio for a given duration """
display(Javascript(RECORD_AUDIO))
s = output.eval_js('record(%d)' % (sec*1000))
b = b64decode(s.split(',')[1])
return Audio(b) | 5,295,532 |
def _colon(state):
"""Start a colon definition"""
_end_definition() # If we were already in one
state.interpreter_dictionary["WORD"].execution_token(state)
name = state.data_stack.pop()
state.state = State.Compiling
word_label = _get_label(name)
# Emit a prefix, and store (word_label, addr... | 5,295,533 |
def rename(location: str, file: str, new_name: str) -> str:
"""
Change file name via copy old file to file with new_name and delete(old_file)
:param location:
:param file:
:param new_name:
:return: str - new file path in s3 storage
"""
try:
location = remove_start(strip_str(locat... | 5,295,534 |
async def test_smartswitch(
hass: HomeAssistant, dimmer_switch_mock_data: SmartSwitchMockData
) -> None:
"""Test function."""
sys_info = dimmer_switch_mock_data.sys_info
await async_setup_component(hass, HA_DOMAIN, {})
await hass.async_block_till_done()
await async_setup_component(
has... | 5,295,535 |
def test_get_init_arguments_and_types():
"""Asserts a correctness of the `get_init_arguments_and_types` Trainer classmethod."""
args = Trainer.get_init_arguments_and_types()
parameters = inspect.signature(Trainer).parameters
assert len(parameters) == len(args)
for arg in args:
assert paramet... | 5,295,536 |
def get_latency(email, photo_name, processType):
"""This function returns latency for a processed image
Args:
email (string): user email for ID
photo_name (string): which photo to load latency for
processType (string): which process type to load
Returns:
latency (float): la... | 5,295,537 |
def detect_loop(image, mask=None, snr=3, npixels=3,
deblend=True, dilate=0, edge_cutoff=None,
max_iter=np.inf, group_name_format='sources{count}',
model=None, opt_kws=None, report=None):
"""
Multi-threshold image blob detection, segmentation and grouping. This
... | 5,295,538 |
def check_sage(min_version="9.0"):
"""
Check if the requirement for Sage is met
"""
try:
from distutils.version import StrictVersion
from sage.env import SAGE_VERSION, SAGE_DATE, SAGE_SRC
print('* SAGE: {}, release date: {}, in "{}"'
.format(SAGE_VERSION, SAGE_DATE... | 5,295,539 |
def isinstalled(name: str,
lib_loc=None):
"""
Find whether an R package is installed
:param name: name of an R package
:param lib_loc: specific location for the R library (default: None)
:rtype: a :class:`bool`
"""
instapack = InstalledPackages(lib_loc)
return instapack... | 5,295,540 |
def test_camera_success(mock_take_picture, api_client):
"""
Test that we return the contents of the file we direct camera to write
image to.
"""
state = {}
async def fake_picture(filename, loop=None):
# Save the filename
state['filename'] = filename
# Write some junk to ... | 5,295,541 |
def create_experiment(run_config,
hparams,
model_name,
problem_name,
data_dir,
train_steps,
eval_steps,
min_eval_frequency=2000,
schedule="train... | 5,295,542 |
def quit_hermit():
"""usage: quit
Exit Hermit.
"""
clear_screen()
return True | 5,295,543 |
def flatten(x: Union[list, tuple]) -> list:
"""
Flattening function for nested lists and tuples
Args:
x: List or tuple
Returns:
object (list): Flat list
"""
if not isinstance(x, list) and isinstance(x, tuple):
raise TypeError("input must be a list or tuple")
out: l... | 5,295,544 |
def update_nested(original_dict, update_dict):
"""Update a nested dictionary with another nested dictionary.
Has equivalent behaviour to :obj:`dict.update(self, update_dict)`.
Args:
original_dict (dict): The original dictionary to update.
update_dict (dict): The dictionary from which to ext... | 5,295,545 |
def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001,
num_epochs = 1500, minibatch_size = 32, print_cost = True):
"""
Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.
Arguments:
X_train -- training set, of shape (input size = 1... | 5,295,546 |
def test_setup(gc_when_done):
"""
Ensure we GC when tests finish.
""" | 5,295,547 |
def register_glob():
"""Register glob into default registry."""
registry.register('glob', fnmatch) | 5,295,548 |
def process_command_line_args():
"""
Returns:
tuple(str, str): Command line args for (config, output) files
"""
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--directory", required=True,
help="Path to dot file directory")
args = vars(ap.parse_args())
retu... | 5,295,549 |
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3):
"""
Compute c_v coherence for various number of topics
Parameters:
----------
dictionary : Gensim dictionary
corpus : Gensim corpus
texts : List of input texts
limit : Max num of topics
Returns:
--... | 5,295,550 |
def on_launch(launch_request, session):
""" Called when the user launches the skill without specifying what they want
"""
print("on_launch requestId=" + launch_request['requestId'] + ", sessionId=" + session['sessionId'])
# Dispatch to your skill's launch
return get_welcome_response() | 5,295,551 |
def callback(args: argparse.Namespace, config: plug.Config) -> None:
"""Run through a configuration wizard."""
if config.path.exists():
plug.echo(f"Editing config file at {str(config.path)}")
if plug.Config.CORE_SECTION_NAME not in config:
config.create_section(plug.Config.CORE_SECTION_NAME... | 5,295,552 |
def w2v_main():
"""
Method to execute training of word2Word2Vec
"""
corpus_path = '/gscratch/pfaendtner/dacj/nlp/fulltext_pOmOmOo/'
j_carbon = 'Carbon'
j_organometallic = 'Journal_of_Organometallic_Chemistry'
j_inorg_biochem = 'Journal_of_Inorganic_Biochemistry'
jlist = [corpus_path + j_... | 5,295,553 |
def test_salesforce_destination_commit_before_stopping(sdc_builder, sdc_executor, salesforce):
"""
Send text to Salesforce destination from Dev Raw Data Source and
confirm that Salesforce destination successfully reads them using Salesforce client.
It verifies that SalesForce destination is able to wri... | 5,295,554 |
def remove_comment(line):
"""Remove trailing comments from one line."""
start = 0
while True:
loc = line.find('#', start)
if loc == -1:
return line.replace('\\#', '#')
elif not (loc and line[loc - 1] == '\\'):
return line[:loc].replace('\\#', '#')
star... | 5,295,555 |
def GEEsmos(ptsFile,metric,timeStep,buf,poly,username,folderOut, scalePix = 25000,startYear = None,endYear = None):
"""
Calculates soil moisture at point OR mean within buffer of point if buf > 0 OR mean within polygon if poly = 1
Requires:
ptsfile - file name of uploaded shapefile to GEE.
... | 5,295,556 |
def test_06():
"""Test"""
run('citric', ['capric', 'choric', 'cleric', 'cupric', 'czaric']) | 5,295,557 |
def sphinx_license(opts):
"""
Template of license.rst
:param opts: mapping parameters as dictionary
:return: file content as string
"""
template = get_template("sphinx_license")
return template.substitute(opts) | 5,295,558 |
def entailment_internalization(df):
"""
new_ p = ''
new_h = 'p implies that h' (1,0)
new_h = 'p and h' (-1)
"""
contra_combine = " , "
not_contra_combine = " implies that "
df_not_contra = df.query("label!='contradiction'").copy()
df_contra = df.query("label=='contradiction'").copy()... | 5,295,559 |
def tcl_findprd_prepdict(prddict):
"""
Prepare dict of center:[ends] entries.
:param prddict: Device:PRD dictionary.
:type prddict: dict(str: list)
"""
prda = tcl_findprd_prepd_start(prddict)
prdx = tcl_findprd_prepd_middle(prda)
prdfinal = tcl_findprd_prepd_end(prdx)
return prdfina... | 5,295,560 |
def create_nn_cat(input_dim, nr_units, nr_layers, nr_classes):
"""Compile NN model with categories as outputs"""
print('Compiling NN model with {0} layers, {1} units, input dimension {2}...'.format(nr_layers, nr_units, input_dim))
model = keras.models.Sequential()
model.add(keras.layers.Dense(nr_units, ... | 5,295,561 |
def main():
"""
Creates the NetApp ONTAP Domain Tunnel and runs the correct playbook task
"""
obj = NetAppOntapDomainTunnel()
obj.apply() | 5,295,562 |
def augment(cls):
"""Add `time` to kwargs list."""
class New(cls):
@staticmethod
def _myfun(x, *args, time=0, **kwargs):
return super(New,New)._myfun(x)
return New | 5,295,563 |
async def led(command: Command[JaegerActor], fps: FPS, level: int):
"""Sets the level of the FVC LED."""
fvc_ieb = FVC_IEB.create()
led = fvc_ieb.get_device("LED1")
raw_value = 32 * int(1023 * (level / 100))
await led.write(raw_value)
await command.send_command("jaeger", "fvc status")
re... | 5,295,564 |
def ReverseSequence(a, seq_lengths, seq_dim, batch_dim):
"""
Sequential reverse op.
"""
r = np.copy(a)
invidxs = (len(r.shape) - 1) * [slice(None)]
if seq_dim < batch_dim:
invidxs[seq_dim] = slice(None, None, -1)
else:
invidxs[seq_dim - 1] = slice(None, None, -1)
_invidxs... | 5,295,565 |
def handle_none(func):
"""A decorator function to handle cases where partition values are `None` or "__HIVE_DEFAULT_PARTITION__"
Args:
func (Callable): A function registered to the singledispatch function `partition_to_py`
"""
def wrapper(primitive_type, value_str):
if value_str is Non... | 5,295,566 |
def distortion_score(X, labels, metric="euclidean"):
"""
Compute the mean distortion of all samples.
The distortion is computed as the the sum of the squared distances between
each observation and its closest centroid. Logically, this is the metric
that K-Means attempts to minimize as it is fitting... | 5,295,567 |
def save_checkpoint(state, is_best, checkpoint):
"""Saves model and training parameters at checkpoint + 'last.pth.tar'. If is_best==True, also saves
checkpoint + 'best.pth.tar'
Args:
state: (dict) contains model's state_dict, may contain other keys such as epoch, optimizer state_dict
is_best: (bool) True if it i... | 5,295,568 |
def get_location_replacements() -> List[Tuple[str,str]]:
"""Gets a list of location replacement tuples from csv"""
replacements = []
with open(os.path.join(os.path.dirname(__file__), '../config/location.replacements.csv'), 'r') as infile:
reader = csv.reader(infile)
next(reader, None) # skip the headers
replac... | 5,295,569 |
def encode_dexcode(dexid: str, effort: int, due: datetime.datetime, importance: int, status: str, flags: list) -> str:
"""
Create a dexcode from python objects which are easy to work with.
Args:
dexid (str): The dex ID (single letter followed by a number).
effort (int): The effort, which mu... | 5,295,570 |
def _to_kql(obj: ExpressionType, parentheses: bool = False) -> KQL:
"""
Convert the given expression to KQL. If this is a subexpression of a greater expression, neighboring operators might
take precedence over operators included in this expression, causing an incorrect evaluation order. This might not be a ... | 5,295,571 |
def sphere_mesh(n=512, radius=1.0, device="cpu"):
"""Return a unit sphere mesh discretization with *at least* n vertices.
Initially this returns a standard uv sphere but in the future we could
change it to return a more sophisticated discretization.
Code adapted from github.com/caosdoar/spheres/bl... | 5,295,572 |
def asInteger(epsg):
""" convert EPSG code to integer """
return int(epsg) | 5,295,573 |
def monitor_cb(ud, msg):
"""Callback for the MonitorStates, listening to /click/start_button"""
# Return False when you want the MonitorState to terminate
return False | 5,295,574 |
def findKeyframe(*args, **kwargs):
"""
This command operates on a keyset.
Returns: `time` Command result
"""
pass | 5,295,575 |
def compute_dx_from_cross_dispersion_profiles(xcoef,ycoef,wavemin,wavemax, image, fibers=None, width=7,deg=2) :
"""
Measure x offsets from a preprocessed image and a trace set
Args:
xcoef : 2D np.array of shape (nfibers,ncoef) containing Legendre coefficents for each fiber to convert wavelenght to ... | 5,295,576 |
def t1(value):
"""The effective T1 to be used for noisy qubits"""
simulaqron_settings.t1 = value | 5,295,577 |
def run(down_station, input_list, include_time, sample_size, network_type, nr_layers, nr_units):
"""Runner"""
result_dir = util.get_result_dir(down_station, network_type, nr_layers, nr_units, sample_size)
util.plot_training_performance(result_dir)
model_file = util.model_file_name(result_dir)
... | 5,295,578 |
def email_image_attribution(request, id=None, *args, **kwargs):
"""
GET request with an ID in the request that links to a notification ID (or other field),
and will mark that notification as having been opened.
"""
# mark the email
mark_email_as_read(id)
# create an image
img = Image.n... | 5,295,579 |
def build():
"""Builds any resources locally"""
bisi.interface.build() | 5,295,580 |
def see(self, args):
"""
Explore Object members
Usage:
%see <type> <object>
<type>
a : Print all object members
f : Print all object functions
m : Print all object modules
c : Print all classes defined in object
file : Se... | 5,295,581 |
def angular_distance_fast(ra1, dec1, ra2, dec2):
"""
Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at
their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for
antipodes.
:param lo... | 5,295,582 |
def resnet50(**kwargs):
"""
ResNet-50 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in ... | 5,295,583 |
def get_node_rb(graph, k=3, approx=np.inf):
"""
Get k nodes to defend based on Recalculated Betweenness (RB) Removal :cite:`holme2002attack`
:param graph: an undirected NetworkX graph
:param k: number of nodes to defend
:param approx: number of nodes to approximate the betweenness centrality, k=0.1... | 5,295,584 |
def excluir_usuario():
""" Exclui um usuario com id especificado pela url """
try:
if current_user.is_administrator():
cod_id = request.args.get('id')
usuario = Usuario.query.filter_by(cod_usuario = cod_id).one()
db.session.delete(usuario)
db.session.commi... | 5,295,585 |
def make_model():
"""
Generate the model used to make the saved test data.
"""
props = {'density': 1, 'magnetization': utils.ang2vec(1, 25, -10)}
return [Sphere(x=-100, y=200, z=500, radius=400, props=props)] | 5,295,586 |
def get_hrrr_mask(year = '2020', fdir = '/datadrive/hrrr/4km/'):
""" Function to get the hrrr mask from interpolation.
Not very elegantly coded: we compute the yearly maximum
at each grid point. Assuming that every valid grid point rains,
the mask is defined to exclude all grid points with zero precip... | 5,295,587 |
def get_version():
"""
Return package version as listed in env file
"""
if ENV_TYPE == PRD:
return version + "/" + build
return version + "/" + build + "/" + generate + ' (' + ENV_NAME + ')' | 5,295,588 |
def metarthunter_parse(driver: webdriver.Firefox) -> tuple[list[str], int, str]:
"""Read the html for hetarthunter.com"""
# Parses the html of the site
soup = soupify(driver)
image_list = soup.find("ul", class_="list-justified2").find_all("a")
images = [image.get("href") for image in image_list]
... | 5,295,589 |
def mag(initial, current):
"""
Calculates the magnification of a specified value
**Parameters**
intial: *float*
initial value (magnificiation of 1)
current: *float*
current value
**Returns**
magnification: *float*
the magnification of the current value
"""
... | 5,295,590 |
def conv2d(x, dim, stride=1, bn=True):
"""二维卷积
Args:
x ([type]): 输入数据
dim ([type]): 维度,一般为卷积核数量,一般为输出维度
stride (int, optional): 步长. Defaults to 1.
bn (bool, optional): 是否使用BN层. Defaults to True.
Returns:
[type]: slim.conv2d 默认pad模式是SAME ,卷积后的数据会变成和原来大小一样,比如n*m*w*h*c... | 5,295,591 |
def divergence(f):
"""Take the divergence of a vector array
Parameters
----------
f : np.ndarray
Vector array whose divergence should be taken.
Returns
-------
out : np.ndarray
Scalar array of divergence. Dimensionality one less
than the vector array.
"""
... | 5,295,592 |
def capitalize(word):
"""Only capitalize the first letter of a word, even when written in
CamlCase.
Args:
word (str): Input string.
Returns:
str: Input string with first letter capitalized.
"""
return re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), word, 1) | 5,295,593 |
def read_ini(fn: Path) -> dict[str, T.Any]:
"""parse .ini file
DEPRECATED
"""
fn = find.config(fn)
with fn.open("rt") as f:
date = list(map(int, f.readline().split()[0].split(",")))[::-1]
sec = float(f.readline().split()[0])
t0 = datetime(date[0], date[1], date[2]) + timede... | 5,295,594 |
def cassandra_ddl_repr(data):
"""Generate a string representation of a map suitable for use in Cassandra DDL."""
if isinstance(data, str):
return "'" + re.sub(r"(?<!\\)'", "\\'", data) + "'"
elif isinstance(data, dict):
pairs = []
for k, v in data.items():
if not isinstan... | 5,295,595 |
def gconnect():
"""Handles the data sent by the google signin ajax"""
# First validate state token to protect from CSRF
if request.args.get('state') != login_session['state']:
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers['Content-Type'] = 'applicatio... | 5,295,596 |
def get_errors(entries: List) -> List[str]:
"""Extracts error entry contents
The entries argument should be a list of demisto entries
Args:
entries (List[List[Dict]]): multiples entries of results of demisto.executeCommand()
Returns:
(List[str]): Error messages extracted from error en... | 5,295,597 |
def primes_up_to(n, ps = None):
"""Prime numbers <= n."""
if ps is None: ps = mprimes()
return itertools.takewhile(lambda p: p <= n, ps) | 5,295,598 |
def addtoqueue(config_file, message_queue, expressions, environment=None, limit=None):
"""
Search for Datasets and enqueue Tasks into an AWS SQS Queue for later processing.
"""
def _push_messages(queue, messages):
response = queue.send_messages(Entries=messages)
return response
_LO... | 5,295,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.