content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def construct_trace_net(trace, trace_name_key=xes_util.DEFAULT_NAME_KEY, activity_key=xes_util.DEFAULT_NAME_KEY):
"""
Creates a trace net, i.e. a trace in Petri net form.
Parameters
----------
trace: :class:`list` input trace, assumed to be a list of events
trace_name_key: :class:`str` key of t... | d59a02c50ab7241af2bbd70bed927943b2690c4b | 3,618,557 |
def MurtyPartition(N, a, type):
"""
MurtyPartition partitioin node N with its minimum assignment a
input:
N - in Murty's original paper, N is a "node", i.e. a non empty
subset of A, which contains all assignment schemes.
a - a nMeas*1 vector containing one assignment scheme.
type -... | 6a256d41081f3f2a501469435560c95ece32ef62 | 3,618,558 |
def create_dataset(param):
"""
Create a dataset given the parameters.
"""
dataset_class = find_dataset_using_name(param.dataset_mode)
# Get an instance of this dataset class
dataset = dataset_class(param)
print("Dataset [%s] was created" % type(dataset).__name__)
return dataset | 845ae2c70cca3a373c88e6dd7d98d7daedb9115f | 3,618,559 |
import six
def fully_connected(inputs,
num_outputs,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None... | ad5c8b569308e3e816b87e53c1fe2103270b851e | 3,618,561 |
async def get_snapshot(request):
""" get list of available snapshots
:Example:
curl -X GET http://localhost:8081/foglamp/snapshot/category
curl -X GET http://localhost:8081/foglamp/snapshot/schedule
When auth is mandatory:
curl -X GET http://localhost:8081/foglamp/snaps... | ca7fc806cc4c0e5ec1133a61c6ee4d5ed2e9a31b | 3,618,562 |
def score_sig_1A(sim, est_distrib):
"""
euclidian norm between normalized trinucleotide context counts (empirical),
and the reconstituted profile
"""
raw_data_distrib = np.zeros(96)
val, c = np.unique(sim.T, return_counts=True)
raw_data_distrib[val.astype(int)] = c
raw_data_distrib = raw... | 45e5cff15f545766652af11a75b81208206009cb | 3,618,563 |
def permission_to_edit_page(request, page, context={}):
"""Calls user.permission_to_edit_page() on the user in the request, or
returns False if no user in the request."""
if hasattr(request, 'user') and request.user.is_authenticated():
profile = get_profile(request.user)
if profile:
... | 3df73351c1a73d454b8c5bfcc495f4c3ba9b06b4 | 3,618,565 |
def is_admin_user():
"""判断是否是管理员用户分配不同的逻辑"""
# 访问管理员登录页面,不需要拦截处理
if request.url.endswith('/admin/login'):
pass
else:
# 每一次请求之前都进行拦截判断处理
# 1.用户id
user_id = session.get("user_id")
# 2.管理员标志位
is_admin = session.get("is_admin", False)
# 如果用户没有登录,或者登录... | 2a1c7d5f8955d7a28ea3b572e2b7a44ffcc07bdc | 3,618,566 |
def ecdf_formal(x, data):
"""
Compute the values of the formal ECDF generated from `data` at x.
I.e., if F is the ECDF, return F(x).
Parameters
----------
x : int, float, or array_like
Positions at which the formal ECDF is to be evaluated.
data : array_like
One-dimensional a... | 61fd43be4cbd762718ca3a51dac131ddaaf7c373 | 3,618,567 |
def AverageOverlap(l1, l2, depth = 10):
"""Calculates Average Overlap score.
l1 -- Ranked List 1
l2 -- Ranked List 2
depth -- depth
@author: Ritesh Agrawal
@Date: 13 Feb 2013
@Description: This is an implementation of average overlap measure for
comparing two score
(R... | 9cec7fcf500ae6e59eb44e6bad4a9b5c376f87c3 | 3,618,568 |
def _view_connections_cmd(options):
"""
Return the post_setup hook function for 'openmdao view_connections'.
Parameters
----------
options : argparse Namespace
Command line options.
Returns
-------
function
The post-setup hook function.
"""
def _viewconns(prob):... | 5bdfb53e8bd1053ae7f78fe4ca211f25d01ba479 | 3,618,569 |
def three_shouts(word1, word2, word3):
"""Returns a tuple of strings
concatenated with '!!!'."""
# Define inner
def inner(word):
"""Returns a string concatenated with '!!!'."""
return word + '!!!'
# Return a tuple of strings
return (inner(word1), inner(word2),inner(word3)) | d7986646a48fcdd3448d834d59ce497c292a984d | 3,618,570 |
import functools
def accepts(*accepted_arg_types):
"""
A decorator to validate the parameter types of a given function.
It is passed a tuple of types. eg. (<type 'tuple'>, <type 'int'>)
Note
-----
It doesn't do a deep check, for example checking through a
tuple of types. The argument pass... | 47173f7933714da5661c0841fe2479a6da147cbd | 3,618,571 |
from typing import Union
from typing import Dict
from typing import OrderedDict
def trigger_to_dict(trigger: Union[DateTrigger, IntervalTrigger, CronTrigger]) -> Dict:
"""Converts a trigger to an OrderedDict."""
data = OrderedDict()
if isinstance(trigger, DateTrigger):
data['trigger'] = 'date'
... | 6f25cf80218957519f36dae2bef25d9408a00f6a | 3,618,572 |
from datetime import datetime
import re
def run_sentiment(model, tokenizer, device):
"""
SECTION : sentiment
DESCRIPTION 1: Running sentiment analysis using comments from 'video_comment.pkl'
DESCRIPTION 2: Calling 'run_model' function to run BERT model
"""
# ====================== Setup ======... | 743cafb3b42a5c80d222d4f40c99c85a18316b09 | 3,618,573 |
from qmt.tasks import Task
import numpy as np
def fix_task_env():
"""
Set up a testing environment for tasks.
"""
class InputTaskExample(Task):
"""Simple example task. This is the first task in the chain.
:param dict options: Dictionary specifying the input parts. It should be of the... | 01edc228466f2ea6cdc52876a24b98cea3aef2d0 | 3,618,574 |
def adjacency_list_from_adjacency_list_bipartite(old_adj_list):
"""
Creates the adjacency list from another adjacency list, converting the data type to integers.
Method for bipartite networks.
Returns two dictionaries, each representing an adjacency list with the rows or columns as keys, respectively.
... | e21dd0eeaa2a4255605a79a3d6076d9c13b1c1c0 | 3,618,576 |
def is_integer(db_type):
"""Return True if the database type is an integer supported type, False otherwise.
"""
return db_type in ACCEPTED_INTEGER_DB_TYPES | ae499501da19dd01e10fc334911254446a01cbee | 3,618,577 |
def add_custom_header(res):
"""レスポンスにカスタムヘッダーを追加する。"""
res.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
res.headers["Expires"] = "0"
res.headers["Server"] = "Roppo-JSON"
return res | 7ed261a4aa9d4aa532bd2c07544a4ffe4ec1cafb | 3,618,578 |
import html
def render_form():
"""Render form for selecting genes and samples."""
genes_options = [
{"label": gene_symbol, "value": gene_symbol}
for gene_symbol in natsorted(
set((tx.gene_symbol for tx in genes.load_transcripts().values()))
)
]
samples_options = [
... | 5aa744916c98b4748b22e1bd502cbf4e2a03dd12 | 3,618,579 |
from typing import List
def _get_table_ids(
api: ThoughtSpot,
*,
db: str,
schema: str='falcon_default_schema',
table: str=None
) -> List[str]:
"""
Returns a list of table GUIDs.
"""
r = api._metadata.list(type='LOGICAL_TABLE', subtype=['ONE_TO_ONE_LOGICAL'])
table_details = r.j... | 0d0f82f4439a239750b00753664ae8af00d992cc | 3,618,580 |
def get_entity_heading(geopoint):
"""
Acquires heading based on spawn position in map.
Prompts user to select lane if multiple lanes exist at spawn position.
Throws error if spawn position is not on lane.
Args:
geopoint: [AD Map GEOPoint] point of click event
Returns:
lane_head... | 7e39f9b27355c6d4feed27e3b7f574103db77942 | 3,618,581 |
import warnings
def plot_face(
model=None,
au=None,
vectorfield=None,
muscles=None,
ax=None,
feature_range=False,
color="k",
linewidth=1,
linestyle="-",
gaze=None,
*args,
**kwargs
):
"""Function to plot facesself
Args:
model: sklearn PLSRegression insta... | e136bec9ae0a3e9a7dc3dc7da8dfef0d4b3fab77 | 3,618,582 |
def find_cell_with_tag(nb, tag):
"""
Find a cell with a given tag, returns a cell, index tuple. Otherwise
(None, None)
"""
out = find_cell_with_tags(nb, [tag])
if out:
located = out[tag]
return located['cell'], located['index']
else:
return None, None | bcfdbefbb9e0dd052a6da5ab8bda6ba48749bb9e | 3,618,583 |
def profile_to_node(src_profile):
"""convert source profile to graph node."""
return (src_profile['uid'], src_profile) | 970d349c2884dd57d10bef8f7e2649509e480a62 | 3,618,584 |
def instruction_interval_seconds():
""" returns every how many seconds there should be a check for new instructions """
if instruction_interval_overwrite is None:
return float(_get_option_with_default('instruction_check_interval_time_seconds', DEFAULT_INSTRUCTION_CHECK_INTERVAL_SECONDS))
else:
... | 98d417e0cbc8eecd995df0dc9c1294ee06fd3f10 | 3,618,585 |
from typing import Union
from typing import Callable
from typing import Optional
from typing import Tuple
def sample(
sampler: Sampler,
machine: Union[Callable, nn.Module],
parameters: PyTree,
*,
state: Optional[SamplerState] = None,
chain_length: int = 1,
) -> Tuple[jnp.ndarray, SamplerState]... | d0addc00b2759e35f19ddbbcd591225b60ab968e | 3,618,586 |
import psutil
def get_dist_usage():
"""得到硬盘使用"""
return psutil.disk_usage('/') | 72144a5e493d630a96a2ba92f35a836f9c76edb3 | 3,618,587 |
def set_center(data, origin, crop='maintain_size', axes=(0, 1), verbose=False,
center=_deprecated):
"""
Move image origin to mid-point of image.
Parameters
----------
data : 2D np.array
the image data
origin : tuple
(row, column) coordinates of the image origin
... | 86dca72f9de8927315efaa185c0a636f341354d8 | 3,618,588 |
def index():
"""Global index for the whole application."""
golab = app.config.get('GOLAB', False)
return render_template("index.html", golab = golab) | eb93523c02074cea28fe1594251cde255e2a4423 | 3,618,589 |
import base64
def compile_program(client, code):
"""This Functon helps to compile
our source code
Args:
client: [description]
code: source code
Returns:
Encoded compiled code
"""
compiler_response =client.compile(code)
return base64.b64decode(compiler_response["... | e666a420b0c2b96d46d6b096e1fb3f2e570dee87 | 3,618,590 |
import aiohttp
import json
async def make_request(model_id, message):
"""Make asynchronous call to model service
:param model_id: str
:param message: dict
:return: response for the service as dict
"""
async with aiohttp.ClientSession(headers={'Content-Type': 'application/json'}) as session:
... | d1567628853a29eff984ec33797e9484b2f3f3fb | 3,618,591 |
def load_image(img_path, df_info, reduce_factor=1):
"""
Load image and make sure sizes matches df_info
"""
image_fname = img_path.rsplit("/", -1)[-1]
W = int(df_info[df_info.image_file == image_fname]["width_pixels"])
H = int(df_info[df_info.image_file == image_fname]["height_pixels"])... | fde1cb2031a3614f082559040058e952bf80b624 | 3,618,593 |
def mult(v1, m):
"""multiplies a vector"""
return (v1[0]*m,v1[1]*m) | 5055a89c9e3175d103071c09a4553cc6b1528bae | 3,618,594 |
def linear_function_fa(A, W, B, b=None):
"""An alias for using class :class:`LinearFunctionFA`.
Args:
(....): See docstring of method :meth:`LinearFunctionFA.forward`.
"""
# Note, `apply()` doesn't allow keyword arguments, which is why we build
# this wrapper.
if b is None:
retu... | 77d34d876f9e49e16161ef4a5cfeb8f8ef06caf0 | 3,618,595 |
def dis_ten(fea):
"""fea: Series"""
fea_range = [fea.quantile(x) for x in np.arange(11)/10.]
fea_range[0] = fea_range[0] - 0.1
fea_range = set(fea_range)
fea_range = np.sort(list(fea_range))
return pd.cut(fea,fea_range,labels=np.arange(len(fea_range)-1)) | 336bc56c8bae0ade6ea72603785f90f553ab8305 | 3,618,596 |
def default_seed():
"""Default numpy.random.Generator seed.
Returns
-------
int
"""
return 7 | fb1b29d333ce36ca359002db761d50524438b671 | 3,618,597 |
def get_height_variable_name(obj, variable=None):
"""
Determines the height variable name in the Dataset using variable
coordinate information.
Parameters
----------
obj : Xarray.Dataset
Xarray Dataset containing data
variable : string
Varible name to correct
Returns
... | a302c2c0473eee6912eab95056836c30f153c889 | 3,618,598 |
def mass_metric(sat_size, sat_mass):
"""
This function calculates the metric for the mass of the satellite based upon the maximum allowed for its size.
:param sat_size: Either 1, 1.5, 2 or 3, to correlate to CubeSat sizes of 1U, 1.5U, 2U and 3U
:param sat_mass: the total mass of the satellite including ... | bc8a47aa3f1419eba8ce3dd5050e14e271d9a3f0 | 3,618,599 |
import pkg_resources
def get_electricity_generation_data():
"""Read in electricity generation and fuel use by individual power plants in the US for 2015.
:return: dataframe of electricity generation and fuel use values
"""
data = pkg_resources.resource_filename('interflow', "i... | 423b250e84518f3cc33914ab3bdc56e55910c68d | 3,618,600 |
def is_whitelist_violation(rules, policy):
"""Checks if the policy is not a subset of those allowed by the rules.
Args:
rules (list): A list of FirewallRule that the policy must be a subset of.
policy (FirweallRule): A FirewallRule.
Returns:
bool: If the policy is a subset of one of the ... | 00320174323d0827a201944a11a24be0bf0ce204 | 3,618,601 |
def main(args):
"""Start the upload command and return exit status code."""
return upload_command(args.directory, args.site, args.user, args.token) | aac3d8bfa44c17f6f3c6fecc1c34674f1f409c0f | 3,618,602 |
def get_k_mesh_by_cell(cell, kspace_per_in_ang=0.10):
"""
Args:
cell:
kspace_per_in_ang:
Returns:
"""
latlens = [np.linalg.norm(lat) for lat in cell]
kmesh = np.ceil(np.array([2 * np.pi / ll for ll in latlens]) / kspace_per_in_ang)
kmesh[kmesh < 1] = 1
return kmesh | e25d67116e45ea747cffe62cc2b8060f5c0cdbba | 3,618,603 |
def _required_params(param_list):
""" return params without a default"""
# params with defaults come last
for i, p in enumerate(param_list):
if p.default is not Parameter.empty:
return param_list[:i]
# no defaults
return param_list | 0002dec0d0156713ef4b127ea7f9cdf6682563cf | 3,618,604 |
def valid_token(response):
"""
Checks if token is valid.
"""
if ('detail' in response):
if (response['detail'] == 'Invalid token'):
echo("The authentication token you are using isn't valid. Please try again.")
return False
if (response['detail'] == 'Token has exp... | e44598c21f9a3a66681bd32f24fe32424f2e25c2 | 3,618,606 |
from cuml.utils.import_utils import has_treelite, has_xgboost
import treelite
import treelite.runtime
import xgboost as xgb
def _build_treelite_classifier(m, data, arg={}, tmpdir=None):
"""Setup function for treelite classification benchmarking"""
if has_treelite():
else:
raise ImportError("No tre... | db7fcb17be72034c5ef12e994e5bfa875fbea7af | 3,618,608 |
from typing import Dict
def name2fips(loc: Dict[str, str]) -> Dict[str, str]:
"""name2fips converts a dictionary with keys corresponding to geography types ("state", "msa", "county", "city").
Values are english names of locations. Note that the state must be included in each geography.
It's annoying, but ... | bac02e6b8a13e03648f07db9f05ef177a2bc5cc6 | 3,618,609 |
def filter_local_hams(new_hams: pd.DataFrame) -> pd.DataFrame:
"""
Return the subset of hams that are within 30km of Seattle downtown.
Parameters
----------
new_hams : pd.DataFrame
A dataframe containing new ham callsigns and email addresses.
Returns
-------
pd.DataFrame
... | d97e2a6f837d2512c6b999a7f0547860594cef69 | 3,618,611 |
def cria_peca(peca):
"""
cria_peca: str -> peca
Recebe um identificador de jogador (ou peca livre) e devolve um dicionario
que corresponde ah representacao interna da peca.
R[peca] -> {'peca': peca}
"""
if type(peca) != str or len(peca) != 1 or peca not in 'XO ':
raise ValueError('cr... | 6a74212f49695addab80c68f41a1e7e7d45e1ed6 | 3,618,613 |
def get_multiple_sources(filenames, **kwargs):
"""
Load multiple sources at once using multprocessing
Parameters:
filenames=filenames
kwargs: keyword arguemnts
"""
source_type=kwargs.get('source_type', 'source')
if source_type=='spectrum':
method=partial(getter_function... | f50633ed8cf79ef51636237ff31a0927852fdc4e | 3,618,615 |
def basic(s, coeffs):
"""Performs the "standard" de Casteljau algorithm."""
r = 1 - s
degree = len(coeffs) - 1
pk = list(coeffs)
for k in range(degree):
new_pk = []
for j in range(degree - k):
new_pk.append(r * pk[j] + s * pk[j + 1])
# Update the "current" values... | cd12b21a0b35752b67f26eba10ee54650d45c49d | 3,618,617 |
from typing import List
def min_max_normalize(mri_imgs: List[np.memmap]):
"""
Function which normalize the mri images with the min max method
Parameters
----------
mri_imgs: list of images
Returns
-------
list of normalized images
"""
for i in range(len(mri_imgs)):
... | 9c280a84ba3e3092b9b3858fb51fb7a62dd62ffd | 3,618,618 |
import logging
import math
def check_lorentz_process(process, evaluator,options=None):
"""Check gauge invariance for the process, unless it is already done."""
amp_results = []
model = process.get('model')
for i, leg in enumerate(process.get('legs')):
leg.set('number', i+1)
logger.info(... | 68064d91db23376b7ba7353077a90f7d9448706f | 3,618,619 |
def create_credential(account, user_name, account_password):
"""
Function to create new credential
"""
new_credential = Credentials(account, user_name, account_password)
return new_credential | 55972d09ecb2b8460241497e3688ff9af96bde58 | 3,618,620 |
import logging
import numpy
def form_stars_from_group_older_version(
group_index,
sink_particles,
newly_removed_gas,
lower_mass_limit=settings.stars_lower_mass_limit,
upper_mass_limit=settings.stars_upper_mass_limit,
local_sound_speed=0.2 | units.kms,
minimum_sink_mass=0.01 | units.MSun,
... | 035042e822a312bcce137d52227fe6d1a87cd696 | 3,618,621 |
def format_sentence_about_nodes(sentence, nodes):
"""
example 1:
input: sentence = '%s seems(seem) dead.', nodes = ['rpi0']
output: 'Node rpi0 seems dead.'
example 2:
input: sentence = '%s seems(seem) dead.', nodes = ['rpi0', 'rpi1', 'rpi2']
output: 'Nodes rpi0, rpi1 and rpi2... | 7dbf470f807a09111ddec65c14d089255773d78e | 3,618,622 |
from ray.autoscaler._private.util import fillout_defaults
from typing import Dict
from typing import Any
def fillout_defaults(config: Dict[str, Any]) -> Dict[str, Any]:
"""Fillout default values for a cluster_config based on the provider."""
return fillout_defaults(config) | a7ccaa357742bf02e8c2fcad6a24945b33b5a39e | 3,618,623 |
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
... | 4a4b5634016a98019ec03ea226cbe6fd000366b5 | 3,618,624 |
def has_group(user, group_name):
"""Tests if a user belongs to a given group.
Source:
https://www.abidibo.net/blog/2014/05/22/check-if-user-belongs-group-django-templates/#sthash.vGVYYdzi.dpuf
"""
group = Group.objects.get(name=group_name)
return True if group in user.groups.all() else Fals... | 94d3b3a599a7546d4cc679f1fcbfb6578f835123 | 3,618,625 |
def create_matrix(dataset, column_names=None, column_roles=None, receiver=None):
"""Returns a new Matrix object from the provided dataset.
Parameters:
$dataset_parameters
$receiver_parameter
"""
if receiver is None:
receiver = Receiver()
matrix = _create_matrix(dataset, co... | b38a3f217ee431372630f22124fba030adda2886 | 3,618,626 |
def function_call(f, *args, **kwargs):
"""Execute the function `f` with given arguments.
Intended to be used in conjunction with :func:`call`.
Arguments of type :class:`ObjectId` are transparently
mapped to the object they refer to.
"""
return f(*((get_object(arg) if type(arg) is ObjectId else ... | 40d5a4643c44ce7f54d6c9425e9aa0f3dbff469e | 3,618,627 |
def new_flow_logs(ec2, vpc_id, log_group_name, role_arn):
"""
Enable VPC Flow Logs
"""
try:
flow_logs = ec2.create_flow_logs(
ResourceIds = [vpc_id],
ResourceType = 'VPC',
TrafficType = 'ALL',
LogGroupName = log_group_name,
DeliverLogsPermissionArn = role_arn
)
except Cl... | 7c088a3ebf343a8a1ff5df0d0489367de7604946 | 3,618,628 |
def prime_vars(vrs):
"""Return `list` of primed variables from `vrs`."""
return [prime(var) for var in vrs] | 7d8fd77fa5331f7ec432bc35d632dde1a38d9267 | 3,618,629 |
def is_teacher_or_staff(original_function=None):
"""
Security decorator to detect if the user is teacher or part of the staff
team.
:returns: Boolean pair
.. versionadded:: 0.1
"""
def decorated(request, course_slug=None, *args, **kwargs):
course = get_object_or_404(Course, slug=... | 809334a2a6eace208f138a105505eb0384878687 | 3,618,630 |
def ring_substituents(gra):
""" Determine substituent groups on a ring
to produce a graph of graphs where the top level
key of a ring_gra is the order of the atm keys
that define the ring
aka (a1, a2, a3, a4, a5, a6) a1 is the 0th position of the ring
so a3-a5 have a 1-3 in... | 6865482c12b1486c9f7fcabdcaefc0ef70f5e988 | 3,618,631 |
def matchnocase(word, vocab):
"""
Match a word to a vocabulary while ignoring case
:param word: Word to try to match
:param vocab: Valid vocabulary
:return:
>>> matchnocase('mary', {'Alice', 'Bob', 'Mary'})
'Mary'
"""
lword = word.lower()
listvocab = list(vocab) # this trick catc... | ba0354d7669d08fbdedc926c11f446c26f401e89 | 3,618,632 |
def table_start_fn(ctx, token):
"""Handler for table start token "{|"."""
if ctx.pre_parse:
return text_fn(ctx, token)
close_begline_lists(ctx)
_parser_push(ctx, NodeKind.TABLE) | b3eb77ac5a1b90c3c8c1ab97f3d9341fdf921f77 | 3,618,633 |
from typing import cast
def theory_atom(s: str, mode: int=0) -> AST:
"""
Convert string to theory term.
"""
if mode==2:
v = Extractor(parse=True)
else:
v = Extractor()
def visit(stm):
v(stm)
if mode==0 or mode==2:
clingo.ast.parse_string(f"{s}.", visit)
... | a079acce8cca2fad3589640d5b248246d87eab59 | 3,618,634 |
import torch
def train_non_parametric_filter(nb_epochs, train_input, train_target, e, edge, f, gamma=1e-6, alter_thresh = False):
"""
Training process to learn a non parametric filter.
Attributes:
- nb_epochs : Number of epochs to train
- train_input : Initial filtered... | 2ec1dd4a99d8d32b5dace4fe1e789308955b5ea4 | 3,618,635 |
def read_cobs(years=('2020'), comet=None, start=None, stop=None,
allowed_methods=('S', 'B', 'M', 'I', 'E', 'Z', 'V', 'O'),):
"""Returns a `CometObservations` instance containing the COBS database."""
if years == 'all':
years = tuple(range(2018, 2020))
# Read the data
data = []
... | 6c69c556ce71eff99dbd2c774b2b17ff8344f5ad | 3,618,636 |
from typing import Optional
import typing
def Position(
line: _PrimitiveLineCharNumber,
character: Optional[_CharNumberOrMarker] = None,
*,
_default_character: _CharNumberOrMarker = CharNumber(0),
) -> typing.Position:
"""
Returns a [Position](https://microsoft.github.io/language-server-protoc... | 944094fe2ebe63c70675f064ebae3ca43fcca65b | 3,618,637 |
from datetime import datetime
def get_first_timestamp(log_file, search_text):
"""Get the first timestamp of `search_text' in the log_file
Args:
log_file
search_text (str)
Returns:
timestamp: datetime object
"""
timestamp = None
with open(log_file, "r") as f:
c... | fbf5f00ea0810788019ec081a67664393763a95c | 3,618,638 |
def velocity_r(trk, t_vel, r, on=True):
"""Randomly change the velocity of a note in a track"""
time = 0
j = 0
c_t_vel = t_vel[j][0]
if on:
msg_t = "note_on"
else:
msg_t = "note_off"
for msg in trk:
if msg.type == msg_t:
r_mod = c_t_vel*r
msg.v... | 0a8454443b3c3accf6c1f873bc574b2bd5763c69 | 3,618,639 |
def beinflumatred(infl_mat):
"""
Calculate a reduced influence coefficient matrix from a complete influence
coefficient matrix.
Parameters
----------
infl_mat: ndarray
The complete influence coefficient matrix.
Returns
-------
reduced_infl_mat: ndarray
The reduced ... | 6f51964f1339f4196fcab252f844b6627b6bae57 | 3,618,641 |
def get_fetaure_names(df, feature_name_substring) :
"""
Returns the list of features with name matching 'feature_name_substring'
"""
return [col_name for col_name in df.columns if col_name.find(feature_name_substring) != -1] | 14103620e89b282da026fd9f30c7491b63820c09 | 3,618,642 |
import glob
def load_data_from_experiment_root_dir(path, str_filter='/*/*/*/*/args.json', original_args=False,
target_fn=None, use_hash=False, sort_best_model_fn=None):
"""Entry point of almost all experiments reader
Here we load the full statistics of a given experiment.
Parameters
--... | e310ac3f805aa19f4dee1a5148f75e5536c05106 | 3,618,643 |
def gaussian_1st_deriv(sigma, t, amplitude=1, plot=False):
"""
Basic gaussian pulse with units in time
std_time is the standard deviation of the pulse with units of t
Example
-------
Example 1::
dt=1e-9
t=np.arange(0,0.001+dt/2,dt)
t-=t.mean()
std_time=1e-4
s=gaussian_1st_deriv(sigma = std_time, ... | 96e8d15a49d9fb53943461222956d37e0259166a | 3,618,644 |
import numbers
def ISNUMBER(value):
"""
Checks whether a value is a number.
>>> ISNUMBER(17)
True
>>> ISNUMBER(-123.123423)
True
>>> ISNUMBER(False)
True
>>> ISNUMBER(float('nan'))
True
>>> ISNUMBER(float('inf'))
True
>>> ISNUMBER('17')
False
>>> ISNUMBER(None)
False
>>> ISNUMBER(da... | 422c5bcd24a21a50bfefb1a00193387e725d435b | 3,618,645 |
def pearson_transform(
matrix: ExpMatrix, min_exp_thresh: float = 0.001) -> ExpMatrix:
"""Uses pearson residuals to stabilize variance."""
invalid_errstate = 'warn'
if np.issubdtype(matrix.values.dtype, np.float32):
if np.amin(matrix.values) >= 0:
invalid_errstate = 'ignore'
... | f47be6134ba878f88d9e60ff171c4359c909f4cf | 3,618,646 |
def get_domains_for_ip(ip):
"""
Get the list of domains associated with an IP address.
:param ip:
:return:
"""
return __scraper.run(ip) | fedb8ed93297ada60766a85c248f282dc05bea1c | 3,618,647 |
def sharesnet18(**kwargs):
"""
ShaResNet-18 model from 'ShaResNet: reducing residual network parameter number by sharing weights,'
https://arxiv.org/abs/1702.08782.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, ... | 31dcdfd003b0a37da05cdd8d95fcc64abca7c6c3 | 3,618,648 |
def dgraph2adjacency(dgraph: nx.DiGraph) -> np.ndarray:
"""Gets the dense adjancency matrix from the graph.
Args:
dgraph: Directed graph to compute its adjancency matrix.
Returns:
Adjacency matrix of the given dgraph in dense format (np.array(n * n)).
Raises:
None.
"""
... | dcb0bc5ca558fbc2356cc58bde9346848105b07b | 3,618,649 |
import random
def format_meters(cm):
"""Returns an example user-input meters string."""
if cm < 100:
return format_cm(100)
m = cm // 100
cm_part = format_cm(cm % 100)
suffixes = ["meters", "metres", "m", "ms"]
suffix = random.choice(suffixes)
spacing_1 = random.randrange(3)*" "
spacing_2 = random... | 4521302811011d0dacb82ab969884ff7c15d13e9 | 3,618,650 |
def convert_atts_to_list_of_quats(atts):
"""Convert ``atts`` to a flat list of Quat objects
Parameters
----------
atts : Quat, list
Attitudes
Returns
-------
list
Flat list of Quat objects
"""
if isinstance(atts, Quat):
out = [Quat(q) for q in atts.q.reshape... | 1b2f94b3e7bb167c4bf5d3319ff6d18387ee5f82 | 3,618,651 |
import torch
import logging
def process_evaluation_epoch(global_vars: dict, eval_metric=None, tag=None):
"""
Calculates the aggregated loss and WER across the entire evaluation dataset
"""
eloss = torch.mean(torch.stack(global_vars['EvalLoss'])).item()
hypotheses = global_vars['predictions']
r... | 1d53c7977d71ed8a18a4811fd41fd511e974a37e | 3,618,652 |
async def list_pop_communities(context, limit:int=25):
"""List communities by new subscriber count. Returns lite community list."""
limit = valid_limit(limit, 25, 25)
sql = "SELECT * FROM bridge_list_pop_communities( (:limit)::INT )"
out = await context['db'].query_all(sql, limit=limit)
return [(r[... | 9774e3fb34e1403e2ae20ffa128edaf77dd328a3 | 3,618,653 |
def api_methods():
"""
API symbols that should be available to users upon module import.
"""
return {
'point', 'scalar',
'scl', 'rnd', 'inv', 'smu',
'pnt', 'bas', 'mul', 'add', 'sub'
} | a5f23b48509adb966e10e3309ace93c31651ebd3 | 3,618,654 |
import logging
import numpy
from operator import or_
import math
def geo_rescore(pid, model, method):
"""Apply geographic rescoring."""
logging.info(str((pid, model, method)))
session = SESSION()
try:
numpy.seterr(all='raise')
session.query(Model) \
.filter_by(filename=mo... | e2623a58a34efff85594585f2b60571b49ab0805 | 3,618,655 |
def is_prime(n):
"""Determine if input number is prime number
Args:
n(int): input number
Return:
true or false(bool):
"""
for curr_num in range(2, n):
# if input is evenly divisible by the current number
if n % curr_num == 0:
# print("current num:", curr_n... | 518a0e78056668e9d8b0a708a05ba9bc9b9cf3d2 | 3,618,656 |
def eval_multiple(exprs,**kwargs):
"""Given a list of expressions, and keyword arguments that set variable
values, returns a list of the evaluations of the expressions.
This can leverage common subexpressions in exprs to speed up running times
compared to multiple eval() calls.
"""
for e in exp... | 2bc90dacb972d3315168638a4ea99f9cfbb13830 | 3,618,659 |
def create_user(**params):
# **: dynamic list of arguments.
# we can basically add as many arguments as we want
"""Helper function to create new user that you're testing with"""
return get_user_model().objects.create_user(**params) | 9527812043af8e338985230d88113eefb63d1f38 | 3,618,661 |
import time
def inner_loop_function(model, config):
""" Execute single cross-validation trial """
test_set, ds = config
tic = time.time()
df = execute_gluonts_dataframe(model, ds, test_set )
res = execute_gluonts_json(df)
toc = time.time()
res['time'] = toc-tic
return df, res | ec3c541202a5e114cf2abc51f9ba196ea97305b9 | 3,618,662 |
from datetime import datetime
def findSEH(modulecriteria={},criteria={}):
"""
Performs a search for pointers to gain code execution in a SEH overwrite exploit
Arguments:
modulecriteria - dictionary with criteria modules need to comply with.
Default settings are : ignore aslr, rebase and safeseh... | f32975e4382f03fb440d31abac9fde64fd6efefe | 3,618,663 |
from typing import Tuple
from typing import Dict
from typing import Any
def _to_instruction(idl_ix: _IdlInstruction, args: Tuple) -> Instruction:
"""Convert an IDL instruction and arguments to an Instruction object.
Args:
idl_ix: The IDL instruction object.
args: The instruction arguments.
... | 728a2aefe1c4e0af9ab1e165c69cff4958dca333 | 3,618,664 |
def sample_coordinates(mask, num_train_vols, num_val_vols, vol_dims=(96, 96, 96)):
"""
Sample random coordinates for train and validation volumes. The train and validation
volumes will not overlap. The volumes are only sampled from foreground regions in the mask.
Parameters
----------
mask... | 99896662638a6589a7ba70bbefce29433d5e714f | 3,618,665 |
import torch
def get_deformation(
screw_axis,
# Rotation params.
with_rotation = True,
fix_axis_vertical = False,
# Scaling params.
with_isotropic_scaling = False,
min_scale = 0.5,
max_scale = 1.5,
):
"""Get screw axis encoding of per-point rigid transformation.
Args:
screw_ax... | 09a16b5100d97cd24097a5160fb1608c557baf54 | 3,618,666 |
import yaml
from pathlib import Path
def load_component_entity_from_yaml(
path: str,
mock_machinelearning_client: MLClient,
context={},
is_anonymous=False,
fields_to_override=None,
) -> ParallelComponent:
"""Component yaml -> component entity -> rest component object -> component entity"""
... | c2539ab48671876df97472f9ffe953f042cd07f0 | 3,618,667 |
from operator import concat
def nash_do_transfer_from(ctx, Caller, args):
"""Transfers the approved token at the specified id from the
t_from address to the t_to address
Only a whitelisted DEX can invoke this function
:param StorageContext ctx: current store context
:param list args:
0: ... | edc1f4768f8b90b00c3a267b75bfc5490a6e9be4 | 3,618,668 |
import re
def convert_numbers(data):
"""
Function to replace numerical numbers with their text counterparts.
:param data: The text data to be searched.
:return: The text data with numerical numbers replaced with textual representation.
"""
inf = inflect.engine()
for word in data:
... | 003d74415677631a1a78e45a1f57fd2d0aa1884d | 3,618,670 |
def linear_discriminant_analysis(df):
"""
Determine weights for Fischer linear discriminant analysis of df.
@param df pandas dataframe with output in column 'state'
states must be 1 or -1;
@return list of weights and weight threshold.
"""
# separate df in states
group_by = df.... | 92fd43ba3771603d57a28e3f52f0e55b0d611ba9 | 3,618,671 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.