content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def _hostnames() -> List[str]:
"""Returns all host names from the ansible inventory."""
return sorted(_ANSIBLE_RUNNER.get_hosts()) | 8c1ed3f61887ff637d9a9091a20cc3f9e4144dde | 12,300 |
def seabass_to_pandas(path):
"""SeaBASS to Pandas DataFrame converter
Parameters
----------
path : str
path to an FCHECKed SeaBASS file
Returns
-------
pandas.DataFrame
"""
sb = readSB(path)
dataframe = pd.DataFrame.from_dict(sb.data)
return dataframe | 7988da0adb19e59d7c898658d2fe659b2d145606 | 12,301 |
def countVisits(item, value=None):
"""This function takes a pandas.Series of item tags, and an optional string for a specific tag
and returns a numpy.ndarray of the same size as the input, which contains either
1) a running count of unique transitions of item, if no target tag is given, or
2) a running ... | dbb677cc356d867d7f861fe18e2d5c653598d20c | 12,302 |
import numpy as np
import torch
from pathlib import Path
def test_run_inference(ml_runner_with_container: MLRunner, tmp_path: Path) -> None:
"""
Test that run_inference gets called as expected.
"""
def _expected_files_exist() -> bool:
output_dir = ml_runner_with_container.container.outputs_fol... | dc38c5582f8d69ff53f24c34d403ed3f14f964f9 | 12,303 |
def gen_accel_table(table_def):
"""generate an acceleration table"""
table = []
for i in range(1001):
table.append(0)
for limit_def in table_def:
range_start, range_end, limit = limit_def
for i in range(range_start, range_end + 1):
table[i] = limit
return table | 53d96db86068d893dfbb216e9e1283535cad9412 | 12,304 |
from typing import Tuple
import torch
def dataset_constructor(
config: ml_collections.ConfigDict,
) -> Tuple[
torch.utils.data.Dataset, torch.utils.data.Dataset, torch.utils.data.Dataset
]:
"""
Create datasets loaders for the chosen datasets
:return: Tuple (training_set, validation_set, test_set)
... | 175e45640e85df7f76331dc99b60d73fccbbdc43 | 12,305 |
def ensemble_log_params(m, params, hess=None,
steps=scipy.inf, max_run_hours=scipy.inf,
temperature=1.0, step_scale=1.0,
sing_val_cutoff=0, seeds=None,
recalc_hess_alg = False, recalc_func=None,
save... | 2617b297ccb6d347b8a1b6afd8f09af5a1c7db81 | 12,306 |
import os
def issue_config_exists(repo_path):
"""
returns True if the issue template config.yml file exists in the repo_path
"""
path_to_config = repo_path + "/.github/ISSUE_TEMPLATE/config.yml"
return os.path.exists(path_to_config) | 129b5b47304a60a6c10a8740dda1459c816f6ea1 | 12,307 |
import os
def _read(fd):
"""Default read function."""
return os.read(fd, 1024) | 1763d3cceb6d55c257218dbbbb52209ab55de623 | 12,308 |
def get_metrics(actual_classes, pred_classes):
"""
Function to calculate performance metrics for the classifier
For each class, the following is calculated
TP: True positives = samples that were correctly put into the class
TN: True negatives = samples that were correctly not put into the class
... | 925d80d146ca29984886324338b9f99688c721b8 | 12,309 |
import dateutil
def extract_tika_meta(meta):
"""Extracts and normalizes metadata from Apache Tika.
Returns a dict with the following keys set:
- content-type
- author
- date-created
- date-modified
- original-tika-meta
The dates are encoded in the ISO format."""
... | d5e73afa3b7747d31f295acb840c3730a3e60ed1 | 12,310 |
def __gen_pause_flow(testbed_config,
src_port_id,
flow_name,
pause_prio_list,
flow_dur_sec):
"""
Generate the configuration for a PFC pause storm
Args:
testbed_config (obj): L2/L3 config of a T0 testbed
src_... | 953a6d3a3741b6af0b06bd8165abd7350b838b41 | 12,311 |
def parse_str_to_bio(str, dia_act):
""" parse str to BIO format """
intent = parse_intent(dia_act)
w_arr, bio_arr = parse_slots(str, dia_act)
bio_arr[-1] = intent
return ' '.join(w_arr), ' '.join(bio_arr), intent | 951cd110acd5fa53def9e781c0ab9b545d2931b8 | 12,312 |
def train_early_stop(
update_fn, validation_fn, optimizer, state, max_epochs=1e4, **early_stop_args
):
"""Run update_fn until given validation metric validation_fn increases.
"""
logger = Logger()
check_early_stop = mask_scheduler(**early_stop_args)
for epoch in jnp.arange(max_epochs):
(... | a9dc6e76d2796edacc0f55b06e9cf258a90dffea | 12,313 |
from typing import List
def get_povm_object_names() -> List[str]:
"""Return the list of valid povm-related object names.
Returns
-------
List[str]
the list of valid povm-related object names.
"""
names = ["pure_state_vectors", "matrices", "vectors", "povm"]
return names | cb80899b9b3a4aca4bfa1388c6ec9c61c59978a4 | 12,314 |
def choose(a,b):
""" n Choose r function """
a = op.abs(round(a))
b = op.abs(round(b))
if(b > a):
a, b = b, a
return factorial(a) / (factorial(b) * factorial(a-b)) | 30b70dc950e9f6d501cf5ef07bfed682dce41c43 | 12,315 |
from typing import List
import torch
from typing import Optional
def pad_and_stack_list_of_tensors(lst_embeddings: List[torch.Tensor], max_sequence_length: Optional[int] = None,
return_sequence_length: bool = False):
"""
it takes the list of embeddings as the input, then appl... | 78c3a11f7ff79798d9b86703318eabb8da32695a | 12,316 |
from typing import List
def bq_solid_for_queries(sql_queries):
"""
Executes BigQuery SQL queries.
Expects a BQ client to be provisioned in resources as context.resources.bigquery.
"""
sql_queries = check.list_param(sql_queries, 'sql queries', of_type=str)
@solid(
input_defs=[InputDe... | 0b7d71d6ec6aca87a581c8e0876bc1d88e7242c8 | 12,317 |
def mock_accession_unreplicated(
mocker: MockerFixture,
mock_accession_gc_backend,
mock_metadata,
lab: str,
award: str,
) -> Accession:
"""
Mocked accession instance with dummy __init__ that doesn't do anything and pre-baked
assembly property. @properties must be patched before instantia... | c221c34a72809737d22b76beff89a18eece128ff | 12,318 |
from typing import Optional
def get_prepared_statement(statement_name: Optional[str] = None,
work_group: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetPreparedStatementResult:
"""
Resource schema for AWS::Athena::Prepare... | e3bcd74b2bc9093a0fff822a4f35b0de4dab3e03 | 12,319 |
def handle_col(element, box, _get_image_from_uri, _base_url):
"""Handle the ``span`` attribute."""
if isinstance(box, boxes.TableColumnBox):
integer_attribute(element, box, 'span')
if box.span > 1:
# Generate multiple boxes
# http://lists.w3.org/Archives/Public/www-style/... | ef9fe04982bbb278df1453104823235ecf23113f | 12,320 |
def get_dotted_field(input_dict: dict, accessor_string: str) -> dict:
"""Gets data from a dictionary using a dotted accessor-string.
Parameters
----------
input_dict : dict
A nested dictionary.
accessor_string : str
The value in the nested dict.
Returns
-------
dict
... | 2c82c0512384810e77a5fb53c73f67d2055dc98e | 12,321 |
import re
def separa_frases(sentenca):
"""[A funcao recebe uma sentenca e devolve uma lista das frases dentro da sentenca]
Arguments:
sentenca {[str]} -- [recebe uma frase]
Returns:
[lista] -- [lista das frases contidas na sentença]
"""
return re.split(r'[,:;]+', sentenca) | d3ac427172e34054119659adc55295ac27965e6c | 12,322 |
import pathlib
import json
import importlib
def read_datasets(path=None, filename="datasets.json"):
"""Read the serialized (JSON) dataset list
"""
if path is None:
path = _MODULE_DIR
else:
path = pathlib.Path(path)
with open(path / filename, 'r') as fr:
ds = json.load(fr)
... | ade3b9169d0f1db45d3358f27a54ea634f6d883e | 12,323 |
def as_actor(input, actor) :
"""Takes input and actor, and returns [as
<$actor>]$input[endas]."""
if " " in actor :
repla = "<%s>"%actor
else :
repla = actor
return "[as %s]%s[endas]" % (repla, input) | dc9bd33bd6b2156f4fa353db2a0b01bfa6dd1357 | 12,324 |
def error_403(request):
"""View rendered when encountering a 403 error."""
return error_view(request, 403, _("Forbidden"),
_("You are not allowed to acces to the resource %(res)s.")
% {"res": request.path}) | 1e104b006100f296ab8f816abae8272b35c9399b | 12,325 |
def _format_param(name, optimizer, param):
"""Return correctly formatted lr/momentum for each param group."""
if isinstance(param, (list, tuple)):
if len(param) != len(optimizer.param_groups):
raise ValueError("expected {} values for {}, got {}".format(
len(optimizer.param_gr... | 52904bdfb1cba7fe3175606bf77f5e46b3c7df80 | 12,326 |
def as_binary_vector(labels, num_classes):
"""
Construct binary label vector given a list of label indices.
Args:
labels (list): The input label list.
num_classes (int): Number of classes of the label vector.
Returns:
labels (numpy array): the resulting binary vector.
"""
... | 176a1148d90dcd336ea29ac13b73cc7a6c0cdc60 | 12,327 |
def evaluation_lda(model, data, dictionary, corpus):
""" Compute coherence score and perplexity.
params:
model: lda model
data: list of lists (tokenized)
dictionary
corpus
returns: coherence score, perplexity score
"""
coherence_model_lda = CoherenceModel(model=model, texts=data, di... | c38e3ed3728b9a598ec0cf36c07d606daeb8f388 | 12,328 |
def get_map_with_square(map_info, square):
"""
build string of the map with its top left
bigger square without obstacle full
"""
map_string = ""
x_indices = list(range(square["x"], square["x"] + square["size"]))
y_indices = list(range(square["y"], square["y"] + square["size"]))
M = map_i... | 20d405edd8e5e86e943c297455ebfbeb54b669f8 | 12,329 |
def bgr_colormap():
"""
In cdict, the first column is interpolated between 0.0 & 1.0 - this indicates the value to be plotted
the second column specifies how interpolation should be done from below
the third column specifies how interpolation should be done from above
if the second column does not equal the t... | ffeb0d415c237a5f8cc180e86bb08d73e443b133 | 12,330 |
def autovalidation_from_docstring():
"""
Test validation using JsonSchema
The default payload is invalid, try it, then change the age to a
valid integer and try again
---
tags:
- officer
parameters:
- name: body
in: body
required: true
schema:
i... | 82cb9d043666b465226712e6b12be94291ac5792 | 12,331 |
import requests
def get_vlan_groups(url, headers):
"""
Get dictionary of existing vlan groups
"""
vlan_groups = []
api_url = f"{url}/api/ipam/vlan-groups/"
response = requests.request("GET", api_url, headers=headers)
all_vlan_groups = response.json()["results"]
for vlan_group in all_vl... | c0494708e4d2cb5b61a8e4c7ac4136051b1903c7 | 12,332 |
def getLastReading(session: Session) -> Reading:
"""
Finds the last reading associated with the session
NB: Always returns a Reading, because every Session has at least 1 Reading
Args:
session (Session): A Session object representing the session record in the database
Returns:
date... | 87f9e86316bf3975077797832225bbe9b027e648 | 12,333 |
def process_outlier(data, population_set):
"""
Parameters
----------
data
population_set
Returns
-------
"""
content = list()
for date in set(map(lambda x: x['date'], data)):
tmp_item = {
"date": date,
"value": list()
}
for val... | e793aa85bf6b14406d495775a89d37a68ae6bf8b | 12,334 |
import six
def valid_http(http_success=HTTPOk, # type: Union[Type[HTTPSuccessful], Type[HTTPRedirection]]
http_kwargs=None, # type: Optional[ParamsType]
detail="", # type: Optional[Str]
content=None, # typ... | 6c88712cd501291fe126b87086ee29700f44832b | 12,335 |
def operating_cf(cf_df):
"""Checks if the latest reported OCF (Cashflow) is positive.
Explanation of OCF: https://www.investopedia.com/terms/o/operatingcashflow.asp
cf_df = Cashflow Statement of the specified company
"""
cf = cf_df.iloc[cf_df.index.get_loc("Total Cash From Operating Activities"... | ed6a849fa504b79cd65c656d9a1318aaaeed52bf | 12,336 |
from io import StringIO
def generate_performance_scores(query_dataset, target_variable, candidate_datasets, params):
"""Generates all the performance scores.
"""
performance_scores = list()
# params
algorithm = params['regression_algorithm']
cluster_execution = params['cluster']
hdfs_add... | b8cb09973f17aab2c16515a026747c3e006bfd35 | 12,337 |
import cmath
import math
def correct_sparameters_twelve_term(sparameters_complex,twelve_term_correction,reciprocal=True):
"""Applies the twelve term correction to sparameters and returns a new sparameter list.
The sparameters should be a list of [frequency, S11, S21, S12, S22] where S terms are complex number... | e957c8eebd905b93b45e79a7349c1fca895c5430 | 12,338 |
def api_activity_logs(request):
"""Test utility."""
auth = get_auth(request)
obj = ActivityLogs(auth=auth)
check_apiobj(authobj=auth, apiobj=obj)
return obj | 7b13f382e71971b6ed93154a591a27f95fd81a2c | 12,339 |
def RNAshapes_parser(lines=None,order=True):
"""
Returns a list containing tuples of (sequence,pairs object,energy) for
every sequence
[[Seq,Pairs,Ene],[Seq,Pairs,Ene],...]
Structures will be ordered by the structure energy by default, of ordered
isnt desired set order to False
"""
resu... | 3c45a4f6efb190cb26512dea4a55c44292191e0f | 12,340 |
from typing import Callable
from typing import Optional
from typing import Union
from typing import Dict
from typing import Any
def get_case_strategy( # pylint: disable=too-many-locals
draw: Callable,
operation: APIOperation,
hooks: Optional[HookDispatcher] = None,
data_generation_method: DataGenerat... | d46fde928b0ceaa3886904e35876c245e7fcb245 | 12,341 |
def type_from_value(value, visitor=None, node=None):
"""Given a Value from resolving an annotation, return the type."""
ctx = _Context(visitor, node)
return _type_from_value(value, ctx) | 92568581d8f7b47ac469d0575f549acb1b67c857 | 12,342 |
def _accesslen(data) -> int:
"""This was inspired by the `default_collate` function.
https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/
"""
if isinstance(data, (tuple, list)):
item = data[0]
if not isinstance(item, (float, int, str)):
return len(item)
... | df709ee8a97c920a1413c9d7240f83d0406577a6 | 12,343 |
def createSkill(request, volunteer_id):
"""
Method to create skills and interests
:param request:
:param volunteer_id:
:return:
"""
if request.method == 'POST':
volunteer = Volunteer_User_Add_Ons.objects.get(pk=volunteer_id)
skills = request.POST.getlist('skills')
in... | f612ef94b02664526018fd2ea948a36587cb15bf | 12,344 |
def analyticJacobian(robot : object, dq = 0.001, symbolic = False):
"""Using Homogeneous Transformation Matrices, this function computes Analytic Jacobian Matrix of a serial robot given joints positions in radians. Serial robot's kinematic parameters have to be set before using this function
Args:
robot (Seria... | a906148f26fea9bb9d833ac95dffde87a704e372 | 12,345 |
def test_sharedmethod_reuse_on_subclasses():
"""
Regression test for an issue where sharedmethod would bind to one class
for all time, causing the same method not to work properly on other
subclasses of that class.
It has the same problem when the same sharedmethod is called on different
instan... | 829ad4fafb32cb18d8da7b8144be25746f892ce5 | 12,346 |
import os
import inspect
def get_subtask_spec_factory_classes():
"""Return dictionary with all factory classes defined in files in this directory.
This file is excluded from the search."""
this_file = os.path.split(__file__)[-1]
directory = os.path.dirname(__file__)
exclude = [this_file, "subtask... | 500e30e5ed3ba8a7aad660ad80fa123485a9f9b1 | 12,347 |
def triu_indices_from(arr, k=0):
"""
Returns the indices for the upper-triangle of `arr`.
Args:
arr (Union[Tensor, list, tuple]): 2-dimensional array.
k (int, optional): Diagonal offset, default is 0.
Returns:
triu_indices_from, tuple of 2 tensor, shape(N)
Indices for t... | b95a7ed3fac1810bdfe9659471cbcd2d14fc8c99 | 12,348 |
def is_debug():
"""Return true if xylem is set to debug console output."""
global _debug
return _debug | b605a56645aecbd995142d964efd1935ade29673 | 12,349 |
def func(var):
"""Function"""
return var + 1 | a6ca4247f7f7307c384708ed9535046e4ec7d4e3 | 12,350 |
def flanking_regions_fasta_deletion(genome, dataframe, flanking_region_size):
"""
Makes batch processing possible, pulls down small region
of genome for which to design primers around.
This is based on the chromosome and position of input file.
Each Fasta record will contain:
>Sample_Gene_chr:... | a20da206630d1f2fb002c5ca63eab9f240b1f1d5 | 12,351 |
import functools
def numpy_episodes(
train_dir, test_dir, shape, loader, preprocess_fn=None, scan_every=10,
num_chunks=None, **kwargs):
"""Read sequences stored as compressed Numpy files as a TensorFlow dataset.
Args:
train_dir: Directory containing NPZ files of the training dataset.
test... | fd9c727c64bdd725ef1615754d12b93f21568c2f | 12,352 |
def fft_convolve(ts, query):
"""
Computes the sliding dot product for query over the time series using
the quicker FFT convolution approach.
Parameters
----------
ts : array_like
The time series.
query : array_like
The query.
Returns
-------
array_like - The sli... | 7e1fec2a3b30770909d7c185bbc0b4885cb7eb22 | 12,353 |
from typing import List
from typing import Optional
def _add_merge_gvcfs_job(
b: hb.Batch,
gvcfs: List[hb.ResourceGroup],
output_gvcf_path: Optional[str],
sample_name: str,
) -> Job:
"""
Combine by-interval GVCFs into a single sample GVCF file
"""
job_name = f'Merge {len(gvcfs)} GVCFs... | d89fd051cd20bef7263b600ce3513ba858acbadd | 12,354 |
def register_permission(name, codename, ctypes=None):
"""Registers a permission to the framework. Returns the permission if the
registration was successfully, otherwise False.
**Parameters:**
name
The unique name of the permission. This is displayed to the customer.
codename
The u... | f09766685ac4690bd72739450977646d521a21d0 | 12,355 |
def calculate_outliers(tile_urls, num_outliers, cache, nprocs):
"""
Fetch tiles and calculate the outlier tiles per layer.
The number of outliers is per layer - the largest N.
Cache, if true, uses a local disk cache for the tiles. This can be very
useful if re-running percentile calculations.
... | 6e72820de2f954a9e349aa40d165817b3ab7c012 | 12,356 |
import random
def load_trigger_dataset(
fname,
templatizer,
limit=None,
train=False,
preprocessor_key=None,
priming_dataset=None,
max_priming_examples=64,
):
"""
Loads a MLM classification dataset.
Parameters
==========
fname : str
The filename.
templatizer... | 6ed4970dd0031bd33cf19414f439c69e5d5a079a | 12,357 |
def pmu2bids(physio_files, verbose=False):
"""
Function to read a list of Siemens PMU physio files and
save them as a BIDS physiological recording.
Parameters
----------
physio_files : list of str
list of paths to files with a Siemens PMU recording
verbose : bool
verbose fla... | 41e607c80955689e5a189652ba445bf0014a3893 | 12,358 |
def add_chain(length):
"""Adds a chain to the network so that"""
chained_works = []
chain = utils.generate_chain(length)
for i in range(len(chain)-1):
agent_id = get_random_agent().properties(ns.KEY_AGENT_ID).value().next()
work_id = g.create_work().properties(ns.KEY_WORK_ID).value().nex... | 80a176fb34460404c847f00dbeab963f1a0be71e | 12,359 |
from vartools.result import re_fit_data
import sys
def re_fit(file_name, top_c, bot_c):
""" re-fits a prepared oocyte file (-t and -b flags for top and bot constraints)"""
if top_c == "True":
top_c = True
elif top_c == "False":
top_c = False
else:
sys.exit("Invalid option: " + ... | e231c2415ce0ea54fd349f79f78783f71911bd8c | 12,360 |
def convert_graph_to_db_format(input_graph: nx.Graph, with_weights=False, cast_to_directed=False):
"""Converts a given graph into a DB format, which consists of two or three lists
1. **Index list:** a list where the i-th position contains the index of the beginning of the list of adjacent nodes (in the se... | 3f538f697df16b13aeb513dd60831a1252fffb6c | 12,361 |
def auxiliary_subfields():
"""Factory associated with AuxSubfieldsPoroelasticity.
"""
return AuxSubfieldsPoroelasticity() | bcbdaf5b6ee006a6380206ebd331f7e516593b83 | 12,362 |
def cassandra_get_unit_data():
"""
Basing function to obtain units from db and return as dict
:return: dictionary of units
"""
kpi_dict = {}
cassandra_cluster = Cluster()
session = cassandra_cluster.connect('pb2')
query = session.prepare('SELECT * FROM kpi_units')
query_data = sessio... | ab24e4e09f648a74cd16a140279da54aab3d4096 | 12,363 |
def read_cfg_float(cfgp, section, key, default):
"""
Read float from a config file
Args:
cfgp: Config parser
section: [section] of the config file
key: Key to be read
default: Value if couldn't be read
Returns: Resulting float
"""
if cfgp.has_option(section, key... | 0ed341c2d1436e3378e4e126735ac7306973ca8c | 12,364 |
def random(website):
"""
随机获取cookies
:param website:查询网站给 如:weibo
:return:随机获取的cookies
"""
g = get_conn()
cookies = getattr(g, website + '_cookies').random()
return cookies | 6db8d81f18e57af2a7d9294481e45d4ad38962ce | 12,365 |
import requests
def get_pid(referral_data):
""" Example getting PID using the same token used to query AD
NOTE! to get PID the referral information must exist in the BETA(UAT) instance of TOMS
"""
referral_uid = referral_data['referral_uid']
url = "https://api.beta.genomics.nhs.uk/reidentific... | 8e5e43c1a2c85826e03f0fd090fc235b0320aed7 | 12,366 |
from typing import Union
from pathlib import Path
from typing import Tuple
from typing import List
from datetime import datetime
def open_events(
fname: Union[Path, str], leap_sec: float, get_frame_rate: bool = False
) -> Tuple[
List[float], List[float], List[float], List[datetime], Union[List[float], None]
]... | 973b835b1df2aafba1a535b378434b6a532584d0 | 12,367 |
def intdags_permutations(draw, min_size:int=1, max_size:int=10):
""" Produce instances of a same DAG. Instances are not nesessarily
topologically sorted """
return draw(lists(permutations(draw(intdags())),
min_size=min_size,
max_size=max_size)) | 50377412dbd091afa98761e673a35f44acbeb60d | 12,368 |
def getConfiguredGraphClass(doer):
"""
In this class method, we must return a configured graph class
"""
# if options.bReified:
# DU_GRAPH = Graph_MultiSinglePageXml_Segmenter_Separator_DOM
if options.bSeparator:
DU_GRAPH = ConjugateSegmenterGraph_MultiSinglePageXml_Separator
els... | 3089572eb1aa4e7db505b5211d156d3e044aaed5 | 12,369 |
def find_amped_polys_for_syntheticidle(qubit_filter, idleStr, model, singleQfiducials=None,
prepLbl=None, effectLbls=None, initJ=None, initJrank=None,
wrtParams=None, algorithm="greedy", require_all_amped=True,
... | 47d7f684047a5b0379febe2fd64e964f805a2764 | 12,370 |
def _seed(x, deg=5, seeds=None):
"""Seed the greedy algorithm with (deg+1) evenly spaced indices"""
if seeds is None:
f = lambda m, n: [ii*n//m + n//(2*m) for ii in range(m)]
indices = np.sort(np.hstack([[0, len(x)-1], f(deg-1, len(x))]))
else:
indices = seeds
errors = []
return indices, errors | 7a5ff1e2e27b812f17196fbec1d7c6a2c867207c | 12,371 |
def get_ref(cube):
"""Gets the 8 reflection symmetries of a nd numpy array"""
L = []
L.append(cube[:,:,:])
L.append(cube[:,:,::-1])
L.append(cube[:,::-1,:])
L.append(cube[::-1,:,:])
L.append(cube[:,::-1,::-1])
L.append(cube[::-1,:,::-1])
L.append(cube[::-1,::-1,:])
L.append(cube[... | 683ef2c7c0a312e4cf891f191452f9c29f6bc1fd | 12,372 |
from typing import Collection
from typing import Tuple
from typing import Optional
from typing import Mapping
def get_relation_functionality(
mapped_triples: Collection[Tuple[int, int, int]],
add_labels: bool = True,
label_to_id: Optional[Mapping[str, int]] = None,
) -> pd.DataFrame:
"""Calculate rela... | 1e6aa6d9e61ebd788d8c1726ca8a75d551b654b8 | 12,373 |
import json
def df_to_vega_lite(df, path=None):
"""
Export a pandas.DataFrame to a vega-lite data JSON.
Params
------
df : pandas.DataFrame
dataframe to convert to JSON
path : None or str
if None, return the JSON str. Else write JSON to the file specified by
path.
... | 5cf5cf834d4113c05c4cc8b99aaa2a94e0a7b746 | 12,374 |
def _is_json_mimetype(mimetype):
"""Returns 'True' if a given mimetype implies JSON data."""
return any(
[
mimetype == "application/json",
mimetype.startswith("application/") and mimetype.endswith("+json"),
]
) | 9c2580ff4a783d9f79d6f6cac41befb516c52e9f | 12,375 |
from datetime import datetime
def make_request(action, data, token):
"""Make request based on passed arguments and timestamp."""
return {
'action': action,
'time': datetime.now().timestamp(),
'data': data,
'token': token
} | 60e511f7b067595bd698421adaafe37bbf8e59e1 | 12,376 |
def get_stats_historical_prices(timestamp, horizon):
"""
We assume here that the price is a random variable following a normal
distribution. We compute the mean and covariance of the price distribution.
"""
hist_prices_df = pd.read_csv(HISTORICAL_PRICES_CSV)
hist_prices_df["timestamp"] = pd.to_d... | bc6fdcbcb54f156d880ba2504a0ca0d50f889786 | 12,377 |
def _unflattify(values, shape):
"""
Unflattifies parameter values.
:param values: The flattened array of values that are to be unflattified
:type values: torch.Tensor
:param shape: The shape of the parameter prior
:type shape: torch.Size
:rtype: torch.Tensor
"""
if len(shape) < 1 or... | e885517419eb48fd1a4ebdf14a8fa3b19f3c5444 | 12,378 |
def theme_cmd(data, buffer, args):
"""Callback for /theme command."""
if args == '':
weechat.command('', '/help ' + SCRIPT_COMMAND)
return weechat.WEECHAT_RC_OK
argv = args.strip().split(' ', 1)
if len(argv) == 0:
return weechat.WEECHAT_RC_OK
if argv[0] in ('install',):
... | f361a56392320efac4bd1e4101b002c1e42d4b89 | 12,379 |
def get_unique_chemical_names(reagents):
"""Get the unique chemical species names in a list of reagents.
The concentrations of these species define the vector space in which we sample possible experiments
:param reagents: a list of perovskitereagent objects
:return: a list of the unique chemical names... | ae5d6b3bdd8e03c47b9c19c900760c8c2b83d0a0 | 12,380 |
def get_sorted_keys(dict_to_sort):
"""Gets the keys from a dict and sorts them in ascending order.
Assumes keys are of the form Ni, where N is a letter and i is an integer.
Args:
dict_to_sort (dict): dict whose keys need sorting
Returns:
list: list of sorted keys from dict_to_sort
... | 9614dee83723e21248381c61a60e92e78c121216 | 12,381 |
def model_3d(psrs, psd='powerlaw', noisedict=None, components=30,
gamma_common=None, upper_limit=False, bayesephem=False,
wideband=False):
"""
Reads in list of enterprise Pulsar instance and returns a PTA
instantiated with model 3D from the analysis paper:
per pulsar:
... | 37abad1016fadd82bcff1a55e9835db28a5c4eb8 | 12,382 |
def max_votes(x):
"""
Return the maximum occurrence of predicted class.
Notes
-----
If number of class 0 prediction is equal to number of class 1 predictions, NO_VOTE will be returned.
E.g.
Num_preds_0 = 25,
Num_preds_1 = 25,
Num_preds_NO_VOTE = 0,
... | 2eadafdaf9e9b4584cd81685a5c1b77a090e4f1c | 12,383 |
def misclassification_error(y_true: np.ndarray, y_pred: np.ndarray, normalize: bool = True) -> float:
"""
Calculate misclassification loss
Parameters
----------
y_true: ndarray of shape (n_samples, )
True response values
y_pred: ndarray of shape (n_samples, )
Predicted response ... | 676657fa4da7b4734077ba3a19878d8890f44815 | 12,384 |
from scipy.stats import uniform
def dunif(x, minimum=0,maximum=1):
"""
Calculates the point estimate of the uniform distribution
"""
result=uniform.pdf(x=x,loc=minimum,scale=maximum-minimum)
return result | 980ffb875cefec13bb78c3a3c779c68e7f510fb7 | 12,385 |
def _generate_upsert_sql(mon_loc):
"""
Generate SQL to insert/update.
"""
mon_loc_db = [(k, _manipulate_values(v, k in TIME_COLUMNS)) for k, v in mon_loc.items()]
all_columns = ','.join(col for (col, _) in mon_loc_db)
all_values = ','.join(value for (_, value) in mon_loc_db)
update_query = '... | 7cbfdc1dd8709a354e4e246324042c8cf02a703b | 12,386 |
import functools
def filtered_qs(func):
"""
#TODO: zrobić, obsługę funkcji z argumentami
:param func:
:return:
"""
@functools.wraps(func)
def wrapped(self, *args, **kwargs):
ret_qs = func(self)
return ret_qs.filter(*args, **kwargs)
return wrapped | 5d3330c44fc9e7f9bffc74d27a3ebb69bc35944e | 12,387 |
def dict2obj(d):
"""Given a dictionary, return an object with the keys mapped to attributes
and the values mapped to attribute values. This is recursive, so nested
dictionaries are nested objects."""
top = type('dict2obj', (object,), d)
seqs = tuple, list, set, frozenset
for k, v in d.items():
... | ccfa713dc130024427872eb6f2017a0383e3bc01 | 12,388 |
def customized_algorithm_plot(experiment_name='finite_simple_sanity', data_path=_DEFAULT_DATA_PATH):
"""Simple plot of average instantaneous regret by agent, per timestep.
Args:
experiment_name: string = name of experiment config.
data_path: string = where to look for the files.
Returns:
p: ggplot p... | bd046c14de1598672391bbcb134dfe8bcff0b558 | 12,389 |
def _get_log_time_scale(units):
"""Retrieves the ``log10()`` of the scale factor for a given time unit.
Args:
units (str): String specifying the units
(one of ``'fs'``, ``'ps'``, ``'ns'``, ``'us'``, ``'ms'``, ``'sec'``).
Returns:
The ``log10()`` of the scale factor for the time... | 2371aab923aacce9159bce6ea1470ed49ef2c72f | 12,390 |
def resolvermatch(request):
"""Add the name of the currently resolved pattern to the RequestContext"""
match = resolve(request.path)
if match:
return {'resolved': match}
else:
return {} | 41cc88633e0b207a53318c761c9849ad2d079994 | 12,391 |
def selection_sort(arr: list) -> list:
"""
Main sorting function. Using "find_smallest" function as part
of the algorythm.
:param arr: list to sort
:return: sorted list
"""
new_arr = []
for index in range(len(arr)):
smallest = find_smallest(arr)
new_arr.append(arr.pop(sma... | e618c5469ce77d830255dc16806f9499bed7ca9a | 12,392 |
def get_primary_monitor():
"""
Returns the primary monitor.
Wrapper for:
GLFWmonitor* glfwGetPrimaryMonitor(void);
"""
return _glfw.glfwGetPrimaryMonitor() | 0bcc55f64c1b8ce6bad31323e5a4bb6ff05eab47 | 12,393 |
def query_people_and_institutions(rc, names):
"""Get the people and institutions names."""
people, institutions = [], []
for person_name in names:
person_found = fuzzy_retrieval(all_docs_from_collection(
rc.client, "people"),
["name", "aka", "_id"],
person_name, c... | fd98a7557e2ee07b67ca8eddaf76c28b7b99033a | 12,394 |
from typing import Union
from typing import Tuple
def add_device(overlay_id) -> Union[str, Tuple[str, int]]:
"""
Add device to an overlay.
"""
manager = get_manager()
api_key = header_api_key(request)
if not manager.api_key_is_valid(api_key):
return jsonify(error="Not authorized"), 403... | b9652b8d99672d0219df4821decebded458719bd | 12,395 |
from math import sin, cos
def pvtol(t, x, u, params={}):
"""Reduced planar vertical takeoff and landing dynamics"""
m = params.get('m', 4.) # kg, system mass
J = params.get('J', 0.0475) # kg m^2, system inertia
r = params.get('r', 0.25) # m, thrust offset
g = params.get('g', 9.8) # m/... | ff3357e6e1fc1b6f878d9f16b14eba0b687642cd | 12,396 |
from typing import List
from typing import Any
from typing import Callable
def route(
path: str, methods: List[str], **kwargs: Any
) -> Callable[[AnyCallable], AnyCallable]:
"""General purpose route definition. Requires you to pass an array of HTTP methods like GET, POST, PUT, etc.
The remaining kwargs a... | 9e499d59b48a3562f46bdcbde76d87ceb199691e | 12,397 |
import wx
def canHaveGui():
"""Return ``True`` if a display is available, ``False`` otherwise. """
# We cache this because calling the
# IsDisplayAvailable function will cause the
# application to steal focus under OSX!
try:
return wx.App.IsDisplayAvailable()
except ImportError:
... | 9a9af0f46ca22faeb5f76e350d1c831bcba95343 | 12,398 |
def syntactic_analysis(input_fd):
"""
Realiza análisis léxico-gráfico y sintáctico de un programa Tiger.
@type input_fd: C{file}
@param input_fd: Descriptor de fichero del programa Tiger al cual se le debe
realizar el análisis sintáctico.
@rtype: C{LanguageNode}
@return: Como ... | 0d0481c8ac84ac1de1ff3f756f20f33bdc8a18e0 | 12,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.