content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Dict
from typing import Any
def _validate_email(
value: Text,
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any],
) -> Dict[Text, Any]:
"""Validate email is in ticket system."""
if not value:
return {"1_email": None, "previous_email": None}
... | da3221007ae9c4abf179f85da946a229be12777b | 42,000 |
def build_buy_limit_option_order(symbol, quantity, price):
"""Build Buy Limit: Single Option
Buy to open {quanity} contracts of the {symbol with date and option info}
at a Limit of {price} good for the Day.
Args:
symbol: symbol you want to trade. Includes date e.g., XYZ_032015C49
quan... | b61cbb0464c9d60ed4deea22aef3cd945df2a563 | 42,001 |
import time
def gettime():
"""return timestamp"""
return time.time() | 38ac710463f03780c7289fd7746d137c51d6466e | 42,002 |
def parse_speech_in_segment(nlp, segment: Segment) -> list:
"""
Parses all speeches in a segment.
:param segment: segment
:param nlp: spacy nlp object
:return: list of found speeches and its speakers
"""
speeches = []
for i, line in enumerate(segment.lines):
spoken_line, speaker... | e69c22cf990ae5523689d073a76e813b27faecdc | 42,003 |
def parser_of_trace(data):
""" Given a dict of traceroute measurement, extract timestamps, valide hops and rtts to each hop
Args : data (dict)
{u'af': 4,
u'dst_addr': u'192.228.79.201', u'dst_name': u'192.228.79.201', u'endtime': 1483230652,
u'from': u'103.7.251.180', u'fw': 4740, u'lts': 551, u'... | ce582169e22626f1c59c2032d71e2f8fa1f4b89d | 42,004 |
def perceptron(X, y, max_iter=10):
"""
感知机 算法
"""
X = np.mat(X)
y = np.mat(y).T
n, m = X.shape
w = np.zeros((1, m))
b = 0
h = 0.0001
for k in range(max_iter):
for i in range(n):
xi = X[i]
yi = y[i]
if (-1) * yi * (w * xi.T + b) >= ... | 5294b303410e6b354f5991e867cadcf7a989531b | 42,005 |
def is_s3_bucket_global(session, bucket):
""" Return bool for S3 bucket global accessibility
:param session: AWS session
:param bucket: S3 bucket
"""
s3_client = session.client('s3')
try:
s3_acls = s3_client.get_bucket_acl(Bucket=bucket).get('Grants')
if s3_acls:
for ... | 384b4afe4547a5898ed160fe468b18e05ad33f6c | 42,006 |
def cumulative_integral(
control_points: ArrayLike, t: ArrayLike, *, axis: int = 0
) -> np.ndarray:
"""Estimate the cumulative integral along a curve.
Estimates the cumulative integral of a time-parameterized curve along the
chosen axis. The curve is given by a sequence of control points and their
... | 338226578532cd36e060b15df3cf9519ca7c66cc | 42,007 |
def _sqrt(x):
"""
Return square root of an ndarray.
This sqrt function for ndarrays tries to use the exponentiation operator
if the objects stored do not supply a sqrt method.
"""
x = np.clip(x, a_min=0, a_max=None)
try:
return np.sqrt(x)
except (AttributeError, TypeError):
... | 6ec224a4e2f251875bc6c5c11bb9f350deb176b9 | 42,008 |
def get_keyboard_session():
"""Create a new GET_KEYBOARD_SESSION_MESSAGE."""
return create(protobuf.ProtocolMessage.GET_KEYBOARD_SESSION_MESSAGE) | 44b2f10038c060ddf7cbbe59174579fbe2351d30 | 42,009 |
from typing import Tuple
def equilibrate(a: np.ndarray, b: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
""" Expand the shorter of two array by zero padding
"""
le = max(len(a), len(b))
tempa, tempb = np.zeros((le,)), np.zeros((le,))
tempa[:len(a)] = a
tempb[:len(b)] = b
return tempa, tem... | dd16dc8300170796ca8d5b4f9437d24529f69ee5 | 42,010 |
def countObjects(meshes, skel):
"""
Count the total number of vertex groups and shapes combined, as required
for all specified meshes. If no skeleton rig is attached to the mesh, no
vertex groups for bone weights are required.
"""
nVertexGroups, nShapes = getObjectCounts(meshes)
if skel:
... | f37f11cc6492a69d754d0b472d7cdeb79d541b17 | 42,011 |
from datetime import datetime
def create_container(block_blob_service, account_name, container_name):
"""
This function creates the container if it does not exist
:param block_blob_service: The storage blob service instance
:param account_name: The storage account name
:param container_name: The s... | ef28ef93fc5a91e7e8f8fd19b276dc6bd7588487 | 42,012 |
from watools.Products import ETens
from watools.Collect import MOD16
from watools.Collect import GLEAM
from watools.Collect import ALEXI
from watools.Collect import ETmonitor
from watools.Collect import SSEBop
from watools.Collect import CMRSET
import os
def Evapotranspiration(Dir, latlim, lonlim, Startdate, Enddate,... | 30383e4659f64419531ff300123dad611295a71f | 42,013 |
def abs_of_difference(num1: int, num2: int) -> int:
"""
precondition: parameters must be numbers
calculate difference between num1 and num2 and compute absolute value of the result
>>> abs_of_difference(-4,5)
9
>>> abs_of_difference(1,-3)
4
>>> abs_of_difference(2,2)
0
"""
r... | 6cb2ead6a3ed5899a84280f7356a44d515952c7b | 42,014 |
import os
def get_gpus():
"""
Get the number of gpus per node.
Args:
None
Returns:
num_gpus (int): number of gpus per node
"""
gpu_var = os.environ["SLURM_GPUS_PER_NODE"]
num_gpus = int(gpu_var)
return num_gpus | 667a2be1daf3472a1a30801936d635f8fdcb0a1d | 42,015 |
def snapshot_container(
container_ref: "str", repository: "str", tag: "str" = "latest"
) -> "str":
"""Create a snapshot of a running container.
This will store the container's file system in Glance as a new Image.
You can then specify the Image ID in container create requests.
Args:
contai... | a2807e4c76514b2a75183adfd3ae88f7180c4591 | 42,016 |
from datetime import datetime
import json
def lambda_handler(event, context):
"""
Parse the incoming SNS notification for a Deep Security event
"""
timestamp_format = "%Y-%m-%dT%H:%M:%S.%fZ"
if type(event) == type({}):
if 'Records' in event:
print("Processing {} records".f... | ce29d716fb1615acd30513a485acd5e1442606e3 | 42,017 |
import sys
import os
import platform
def eval_marker(value):
"""
Evaluate an distutils2 environment marker.
This code is unsafe when used with hostile setup.cfg files,
but that's not a problem for our own files.
"""
value = value.strip()
class M:
def __init__(self, **kwds):
... | cec4244ecf2e599be912b7573711369b754a088e | 42,018 |
def get_random_training_set(nenv):
"""Create a random training_set array with parameters
And generate four different kinds of hyperparameter sets:
* multi hypper parameters with two bond type and two triplet type
* constrained optimization, with noise parameter optimized
* constrained optimization, ... | 9e742bd518beae34a8d4bad50c0a7e993fb65231 | 42,019 |
def basic_ro(centers):
"""
sort the elements in the left-rigth-top-dowm order given its center
"""
return np.lexsort((centers[:,0],centers[:,1])) | d4f6659318f4e1b530e6d072bdf65a6a4bacd1e5 | 42,020 |
def get_constraints(
m,
foot_angles,
which_current_support,
next_foot_angles,
support_foot_pos,
swing_foot_pos,
stateX,
stateY,
N=16,
dt=0.1,
h=1.0,
g=9.81,
tPf=8,
):
"""
INPUTS
m (int): remaining time steps in current foot step;
foot_angles ([N, 1] ve... | cf021c87582db4a326e35208319c63f207a8cf8f | 42,021 |
import io
def compileHTMLTemplate (template, minimizeBooleanAtts = 0):
""" Reads the templateFile and produces a compiled template.
To use the resulting template object call:
template.expand (context, outputFile)
"""
if (isinstance (template, str)):
# It's a string!
templateFile = io.StringIO (template)
... | c9d7596f8d6679f5d91ae91c17e5c3fccdc1e4bc | 42,022 |
def singleton(cls):
"""Singleton pattern to avoid loading class multiple times
"""
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance | 1aeb8fae2f84000361a77ffef651e7eb14564c3e | 42,023 |
def lookup_tables(request):
"""A view to render tables with all of the lookup values."""
# NOTE - defer spatial fields!
# Management Units
# Strains and Raw Strains
agencies = Agency.objects.all()
lakes = Lake.objects.all()
jurisdictions = Jurisdiction.objects.all()
species = Species.... | 80c101eb6335370ee198e0574f181450fff0fadb | 42,024 |
import types
import smtplib
def send_template_mail(recipient, template, variables, sender=None, html=True, subject=None):
"""
Send an e-mail using a template.
Arguments:
recipient -- the address(es) of the recipient(s)
template -- the template name to use. See below for details.
variables --... | 0fb9e4b7a78407b51e3d97e04910a9d4658daa06 | 42,025 |
def combine_sample_data(gr):
"""Combine data from multiple sequencing runs for the same sample.
Take a pandas groupby object representing multiple data points
corresponding the same sequence and sample, from multiple sequence runs.
Sum the barcode and read counts for the combined result. Use the sequen... | 26efbaa1fb61929bfb8b0acf9453067110776ba8 | 42,026 |
import torch
def compute_loss(
nn: NNApproximator, x: torch.Tensor = None, verbose: bool = False
) -> torch.float:
"""Compute the full loss function as interior loss + boundary loss
This custom loss function is fully defined with differentiable tensors therefore
the .backward() method can be applied ... | ada043f979e80dbbd5f2a37dd0d1dee62ee91bfd | 42,027 |
import typing
import copy
def wikifier_for_ethiopia_dataset(input_dataset: d3m_Dataset) -> typing.Tuple[bool, d3m_Dataset]:
"""
wrapped version for d3m dataset
"""
res_id, input_dataframe = d3m_utils.get_tabular_resource(dataset=input_dataset, resource_id=None)
wikifiered_dataframe = wikifier_... | 2fcd8ff9bfe59e790a34035b4f8109fd4e060214 | 42,028 |
import os
def get_serial_num_from_filepath(filepath):
"""
Parse the serial number from the file path
:param filepath: The full path of the file to extract the serial number from the name
:return: serial number
"""
# get just the filename from the full path
filename = os.path.basename(file... | 3d2d6df29aae33d34382cd0ce14ea06d95bdf8ca | 42,029 |
def load_unknown(filepath):
"""Load any TSPLIB file.
This is particularly useful when you do not know in advance
whether the file contains a problem or a solution.
:param str filepath: path to a TSPLIB problem file
:return: either a problem or solution instance
"""
return load(filepath) | 91f651114b603587f84f7114723e5aa2735d4242 | 42,030 |
def admin_field_generator(verbose_name, function_changer=None, path_to_field=None, html=False,
boolean=False, limit=-1, wrap_white_space=True):
"""
This function generates admin_get decorators for being used in admin.py field methods.
:param function_changer: this function holds th... | cbbf9b9bfdf4ef2f16722f7a996a80db1fc39ecc | 42,031 |
def generate(parent_yaml, parent_name):
"""Generate child YAML configs as a dict {name: yaml_object}"""
# TODO documentation
hpsearch_config = parent_yaml['hpsearch']
if hpsearch_config.get('is_child', False):
raise RuntimeError('This YAML is itself a child config generated for an hyperpar... | 79d2a00d42dcad52ef8210308268cc70145d1c47 | 42,032 |
import argparse
import os
def getOptions():
""" Function to pull in arguments """
description = """"""
parser = argparse.ArgumentParser(
description=description, formatter_class=argparse.RawDescriptionHelpFormatter
)
# Standard Input
standard = parser.add_argument_group(description="R... | 7c6dac885a1b11a7c08ac0ff72a42ff1d1f58402 | 42,033 |
import collections
def get_mbc_objectives(doc):
"""Return dict of MBC results."""
objectives = collections.defaultdict(set)
for rule in rutils.capability_rules(doc):
if not rule["meta"].get("mbc"):
continue
mbcs = rule["meta"]["mbc"]
if not isinstance(mbcs, list):
... | a67ea5aa6fe4b933b781bcaa8152be8787ab8749 | 42,034 |
def combine_histograms(histograms):
"""Takes a list of histograms and returns a new Histogram object that sums
the values in each bin.
All histograms in the list must be identical except for the count.
Parameters
----------
histograms: sequence
A lst of Histogram objects to combine.
... | 211d83a885397baa806422a7c7e27fd6d6a806dc | 42,035 |
def stick_module():
"""
@api {post} /v1/interfacemodule/stick InterfaceModule_置顶模块
@apiName interfaceModuleStick
@apiGroup Interface
@apiDescription 置顶模块
@apiParam {int} id 模块id
@apiParam {string} projectName 项目名称
@apiParamExample {json} Request-Example:
{
"id": 27,
"... | 4938de0d704674d6963412d8698425329964d4d5 | 42,036 |
def int_to_float(value: int) -> float:
"""Converts a uniformly random [[64-bit computing|64-bit]]
integer to uniformly random floating point number on interval <math>[0, 1)</math>.
"""
fifty_three_ones = 0xFFFFFFFFFFFFFFFF >> (64 - 53)
fifty_three_zeros = float(1 << 53)
return (value & fifty_thr... | 7619ec8d0987d9cac06655cab4e2d0787f1e3232 | 42,037 |
def load_attributes_from_hdf5_group(group, name):
"""Loads attributes of the specified name from the HDF5 group.
This method deals with an inherent problem
of HDF5 file which is not able to store
data larger than HDF5_OBJECT_HEADER_LIMIT bytes.
Args:
group: A pointer to a HDF5 group.
name: A nam... | 02913eb7966bb82e6d81ecee83dd51dc63de591a | 42,038 |
import json
def login():
""" Login to user's account """
# Get login and password
login = request.authorization["username"]
password = request.authorization["password"]
# Do some check in the database
if True:
# Set username/password in the response
session["username"] = logi... | aacd87c8cbded34d08e7bdf8aeb3a16c19179038 | 42,039 |
def rank_mols(data, feature):
"""Ranks (or clusters) the molecules according to specified feature which must a column name of data
is pIC50
:param data: dataframe with processed data. Outputted by read_mols
:type data: :class:`pandas.DataFrame` with columns (minimally) ['mol','atag','btag',feature]
... | 441c02d6dc466257366658b6b71471cc407b5ab3 | 42,040 |
import re
def linux_ipv4_addr_get_from_console(target, ifname):
"""
Get the IPv4 address of a Linux Interface from the Linux shell
using the *ip addr show* command.
:param tcfl.tc.target_c target: target on which to find the IPv4
address.
:param str ifname: name of the interface for which w... | cafb08f6bb5504896573287cb920337aece2f880 | 42,041 |
import argparse
import logging
import os
def parse_args():
"""
usage: collect_ad_boilerplate.py [-h] [-t TARGET] [-d]
Utility for creating boilerplate areaDetector ophyd classes
optional arguments:
-h, --help show this help message and exit
-t TARGET, --target TARGET
... | 4479003d8dcb6b219075ff5235f0b192511eb4a0 | 42,042 |
def translate(bboxes, x, y):
"""Map bboxes from window coordinate back to original coordinate.
Args:
bboxes (np.array): bboxes with window coordinate.
x (float): Deviation value of x-axis.
y (float): Deviation value of y-axis
Returns:
np.array: bboxes with original coordina... | 412ab4561407e2823a1fc63d855c9c18658177a4 | 42,043 |
def position_encoding(sentence_size, embedding_size):
"""
Position Encoding described in section 4.1 [1]
"""
encoding = np.ones((embedding_size, sentence_size), dtype=np.float32)
ls = sentence_size+1
le = embedding_size+1
for i in range(1, le):
for j in range(1, ls):
enc... | be5819d38c1611f329f80097ef7e465d0fa54d2e | 42,044 |
def import_(path):
"""
Import string format module, e.g. 'uliweb.orm' or an object
return module object and object
"""
if isinstance(path, str):
v = path.split(':')
if len(v) == 1:
x = path.rsplit('.', 1)
if len(x) == 2:
module, func = x
... | 70327d474a10f1860012cad0de1bbe934840d9b2 | 42,045 |
def animate(i):
"""
Animation function. Paints each frame. Function for Matplotlib's
FuncAnimation.
"""
img.set_data(mod_psis[i]) # Fill img with the modulus data of the wave function.
img.set_zorder(1)
return img, | 825b062d85f9c5bcb8abe0709ad77ba7b1c74750 | 42,046 |
def linear(input_, output_size, stddev=0.02, bias_start=0.0, activation_fn=None, name='linear'):
"""
Fully connected linear layer
:param input_:
:param output_size:
:param stddev:
:param bias_start:
:param activation_fn:
:param name:
:return:
"""
shape = input_.get_shape().a... | 3e1bf3ca4affe6f07300961f05a1bc4d37a8726b | 42,047 |
def aupr(preds, labels):
"""Calculate and return the area under the Precision Recall curve using unthresholded predictions on the data and a binary true label.
preds: array, shape = [n_samples]
Target scores, can either be probability estimates of the positive class, confidence values, or non-thresh... | d4ecd587cefc5b632490308ae45fc457c961509f | 42,048 |
from utilities import helpers
from restapi.protocols.cors import cors
import warnings
def create_app(name=__name__,
init_mode=False, destroy_mode=False,
worker_mode=False, testing_mode=False,
skip_endpoint_mapping=False,
**kwargs):
""" Create the server ... | 964ec0e684aa33c67b38a55fe97c5ebaef0bedd0 | 42,049 |
def read_elementtree(xml_file):
"""Creates an ElementTree from an XML file"""
return ET.parse(xml_file) | 17d51576a568f6672249ed5c9476c5c706b89f4a | 42,050 |
import sys
def get_config_options():
"""
get config options list
"""
result = []
for class_name in dir(sys.modules['RepositoryModule']):
if class_name[0].isupper() and class_name != 'Repository':
result.append(class_name)
return result | ebbf9076b771a2522e4fdafee2e40749815d7251 | 42,051 |
import hashlib
def make_node() -> Node:
"""Make a dummy node."""
bel = f'p(HGNC:{n()})'
return Node(type=PROTEIN, bel=bel, md5=hashlib.md5(bel.encode('utf-8')).hexdigest(), data={}) | 55f9513efb5353369a96033ceb944fdea9566b09 | 42,052 |
def cryptoBook(symbol, token="", version="stable", filter="", format="json"):
"""This returns a current snapshot of the book for a specified cryptocurrency. For REST, you will receive a current snapshot of the current book for the specific cryptocurrency. For SSE Streaming, you will get a full representation of the... | 5291ecbb05d050a65b29d03cc425e6f3749c718e | 42,053 |
def noConsecDups(theList):
"""
noConsecDups is a function that takes a list of items or
a string and returns a copy of that string list with no
consecutive duplicates
produces: the same list with any consecutive duplicates remove
example: noConsecDups([2,3,3,3,4,4,5,6,6,2,2,1,5,3,3,2]
produ... | 3469b43ca2c661a6a6eaae8099f93c5af9f9384a | 42,054 |
def apply_repro_analysis_analysis(dataset, thresholds=[3.0], method = 'crfx'):
"""
perform the reproducibility analysis according to the
"""
nsubj, dimx, dimy = dataset.shape
func = np.reshape(dataset,(nsubj, dimx*dimy)).T
var = np.ones((dimx*dimy, nsubj))
xyz = np.reshape(np.indices(... | 706e99449f3181e65f070ddace26e4d88a409996 | 42,055 |
def run(config, Rs, Ts, cloud, tracks, masks):
"""
Entry point function for bundle adjustment. Parses input, feeds it to optimizes and parses the result back to same format
:param config: config object. See config.py for more information
:param Rs: list of R matrices
:param Ts: list of T vectors
... | b03ffee0bb8c74235176b7a7fbc25ba09878a1ad | 42,056 |
def get_notice(xml):
"""
Get NOTICE_DATA Information: some general information related to the
notice, or information which is extracted from the notice
:param xml:
:return: dictionary:
- NO_DOC_OJS: Notice number in TED
- ORIGINAL_NUTS: Region code(s) of the place of performance
... | 9a6677915a4a8527c6149731de95cea05c91b1a6 | 42,057 |
def dQ_dX(time):
"""Derivative of transformation matrix for nutation/presession with regards to the X coordinate of CIP in GCRS
"""
# Rotation matrices
R3_E = R3(E(time))
R3_s = R3(s(time))
R2_md = R2(-d(time))
R3_mE = R3(-E(time))
dR3_s = dR3(s(time))
dR3_E = dR3(E(time))
dR3_mE... | 0cec44bac5af7b69df25912afb87541c4ac5e68f | 42,058 |
def gcn(request, userDefinedListNumber):
"""Create a text only Discovery ATel list"""
userDefinedListRow = get_object_or_404(TcsObjectGroupDefinitions, pk=userDefinedListNumber)
listHeader = userDefinedListRow.description
initial_queryset = WebViewUserDefined.objects.filter(object_group_id = userDefin... | 983c95add2616b6831b98683c074b86d248b8161 | 42,059 |
def feature_action_values(feature, action, timestamp=None, request=None, response=None):
"""
**Recupero dello stato corrente per una specifica azione di una specifica feature**"""
return features_actions_values(feature, action, timestamp, request=request, response=response) | b2e624298c8194d471a8ad4d39b7a15215ce1c9a | 42,060 |
def compute_ctf(freqs,rots,akv,cs,wgh,dfmid1f,dfmid2f,angastf,dscale,bfactor=None):
""" Evaluate the CTF at a set of frequences, rotated by a certain amount """
av = akv * 1e3 # Convert kilovots to volts
cs = cs * 1e7 # Convert spherical aberation from mm to A
# wavelength of electrons
elambda... | 418371e9420e2ef399d9fbd3b5c0b18ea5f225da | 42,061 |
def sens_all(d_in, var, param_name, figure, func="mean"):
"""Plot seasonal sensitivity to a parameter."""
sens_out = {}
fig, axis = figure
cols_nh = ['2o', '3o', '2.', '1v']
cols_sh = ['2o', '0x', '1v', '2.']
param_vals = d_in[param_name]
nh_seas = d_in['{}_nh'.format(var)]
sh_seas = d_... | 5a6eb816efea372d3524fdb9e8f334387309128c | 42,062 |
def validate(value, ceiling):
"""
Checks if val is positive and less than the ceiling value.
:param value: The value to be checked (usually an int)
:param ceiling: The highest value "val" can be. (usually an int)
:return: True if val is less than ceiling and not negative
"""
value = int(val... | 0736674f74a38e0a583eeb2fae2ee1f441c1fda7 | 42,063 |
def tab_in_leading(s):
"""Returns True if there are tabs in the leading whitespace of a line,
including the whitespace of docstring code samples."""
n = len(s)-len(s.lstrip())
if not s[n:n+3] in ['...', '>>>']:
check = s[:n]
else:
smore = s[n+3:]
check = s[:n] + smore[:len(sm... | 84377a0e4737c1336d15b83d8011e4c2c054f365 | 42,064 |
def config_resolve_class_sorted(cookie, class_id, in_filter, in_size, in_hierarchical=YesOrNo.FALSE):
""" Auto-generated UCSC XML API Method. """
method = ExternalMethod("ConfigResolveClassSorted")
meta_class_id = coreutils.find_class_id_in_mo_meta_ignore_case(class_id)
if meta_class_id is not None:
... | 8d14ae5884185566e601603e50b6643d86a17b63 | 42,065 |
def mean_encoding(data: pd.DataFrame) -> Output(output_data=pd.DataFrame):
"""Mean encoding of categorical columns.
Args:
data: pd.DataFrame
"""
try:
data_processor = DataProcessor()
data = data_processor.mean_encoding(data)
return data
except ValueError:
log... | a6f9a7e7a1403a860321804a81ab1e11cb9b42f1 | 42,066 |
def erratum_check(agr_data, value):
"""
future: check a database reference has comment_and_corrections connection to another reference
:param agr_data:
:param value:
:return:
"""
# when comments and corrections loaded, check that an xref is made to value e.g. PMID:2 to PMID:8
return 'S... | f05b6835db3410b6e3705aab226571d916948594 | 42,067 |
def filter_features(ex):
"""Filters example features, keeping only valid model features."""
return {k: v for k, v in ex.items() if k in _MODEL_FEATURES} | 3f3ca6e8f018b44d694efcd1cb0cfc288863de54 | 42,068 |
def longestConsecutive3(list,missing=1):
""" assume list is a list
budget missing """
if len(list) == 0:
return 0
longest = 0
# print(range(len(list)-1))
starts = [ x for x in range(len(list)) ]
# print(starts)
for sindex in starts:
currentlen = 0
allow = missing
... | 52420837ee40be40e8d8d6ea9a6f25372bed8d55 | 42,069 |
def ComputeAncillaryFiles(cluster, redist):
"""Compute files external to Ganeti which need to be consistent.
@type redist: boolean
@param redist: Whether to include files which need to be redistributed
"""
# Compute files for all nodes
files_all = set([
pathutils.SSH_KNOWN_HOSTS_FILE,
pathutils.CO... | 09c4ada99162742ec62bd92557c2508624e88b0f | 42,070 |
import argparse
def parse_args() -> argparse.Namespace:
"""
Parse the arguments.
Returns:
The argument namespace.
"""
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--coords',
type=str,
h... | af41d88f0391a3b34569d3541209ec6450ba5c7e | 42,071 |
def GhostNet(annotation_type, fixed_positions=None, memory_demanding=False):
"""
Get the GhostNet pipeline which will crop the face :math:`112 \\times 112` and
use the :py:class:`GhostNet` to extract the features
.. warning::
If you are at Idiap, please use the option `-l sge-gpu` while runnin... | 72557f01d312d656d0edf16a459bda2ac1b97109 | 42,072 |
import math
def TrainBaumWelsch(init_start, transitions, emissions, weights, observations, mutrates):
"""
Trains the model once, using the forward-backward algorithm.
"""
fractorials = np.zeros(len(observations))
for i, obs in enumerate(observations):
fractorials[i] = np.log(math.factori... | 9a0067fc53af2ef604f196abd10a2a19c2151649 | 42,073 |
def locale_switcher(current_locale=None):
"""Locale dropdown to switch user locale on localizer pages."""
return {
'current_locale': current_locale,
'locales': settings.AMO_LANGUAGES + settings.HIDDEN_LANGUAGES,
'languages': product_details.languages,
} | 99d3295d187fb632634bacad7f0cbaf92bf9c5bd | 42,074 |
def gen_vocab_dict(train_data):
"""
generate dict from training set's caption file (txt)
format of txt file:
id1 video_id1 caption1
id2 video_id2 caption2
...
"""
vocab = {}
inv_vocab = {}
vocab[''] = len(vocab)
inv_vocab[len(vocab) - 1] = ''
for line in train_data:
... | 56e7e596f20e2da81f1e40a059fca1bc80d21bde | 42,075 |
def fork_count(self, repo_group_id, repo_id=None):
"""
Returns the latest fork count
:param repo_group_id: The repository's repo_group_id
:param repo_id: The repository's repo_id, defaults to None
:return: Fork count
"""
if not repo_id:
fork_count_SQL = s.sql.text("""
SE... | c468499c19fb4db8ad7974ad303a09de07f05344 | 42,076 |
import urllib
import json
import time
def get_cards():
"""Download card data"""
params = "?" + urllib.parse.urlencode({"q": consts.card_query, "order": "released"})
next_page = consts.api_root + consts.search_endpoint + params
total_cards = None
cards = {
"last_updated": time_now().strfti... | 32681a886c4383c242d79fad9a0b1cbb55ceffcf | 42,077 |
import itertools
def select_workloads(argv, # type: Iterable[str]
batch_size=None, # type: Optional[Union[Iterable[TBatchSize], TBatchSize]]
batch_num=None, # type: Optional[Union[Iterable[int], int]]
executor=None # type: Optional[Unio... | 40a60afeba55a19e82b840e4a0bc58a6b33a9e1f | 42,078 |
from typing import Dict
def calculate_frequency(lst: list) -> Dict[str, int]:
"""Calculate the frequency from a list."""
frequencies = {}
for item in lst:
if item in frequencies:
frequencies[item] += 1
else:
frequencies[item] = 1
return frequencies | b38deeddca3d57a9e4545a51feec0c245adce9b8 | 42,079 |
def return_on_equity(stock, date=None, lookback_period: timedelta = timedelta(days=0), period: str = 'FY'):
"""
The return on equity ratio measures how efficiently a company is using its equity to generate profit
:param stock: ticker(s) in question. Can be a string (i.e. 'AAPL') or a list of strings (i.e. ... | 026f8f7f62a85a38df75816161b30862d6fa67c4 | 42,080 |
import time
def _list_existing(filesystem, glob, paths):
"""
Get all the paths that do in fact exist. Returns a set of all existing paths.
Takes a luigi.target.FileSystem object, a str which represents a glob and
a list of strings representing paths.
"""
globs = _constrain_glob(glob, paths)
... | c61bdca00a1d39cccf82a067dd2e224956f096a0 | 42,081 |
def test_dataset_registry_registered_new_dataset() -> None:
"""
test, that the new generated dataset component "TestDataset" can be registered and retrieved from registry
"""
@dataset_registry.register("testdata")
class TestDataset(DatasetBase):
"""
TestDataset
"""
... | 04f3c49807e3210b9d459fd70b89c51959fb6ae5 | 42,082 |
from typing import Dict
from typing import Union
def adjust_match_start_offset(text: Dict[str, any], match_string: str,
match_offset: int) -> Union[int, None]:
"""Adjust the start offset if it is not at a word boundary.
:param text: the text object that contains the candidate ma... | 0ac326410d9a69be5613fea7acb176fcc8b94982 | 42,083 |
def val2str(val):
"""
Converts a float to the string format required for loading the CRRL models.
:param val: Value to convert to a string.
:type val: float
:returns: The value of val represented as a string in IDL double format.
:rtype: string
:Example:
>>> val2str(200)
... | 61121bc352fc286bda6eed61dc151d8f73143715 | 42,084 |
import dateutil
def get_sale_date(link):
"""Return the date of the livestock sale."""
sale_date = dateutil.parser.parse(link, fuzzy=True)
return sale_date | dfad936713a58ce46890380792e372fe911afc18 | 42,085 |
import locale
import subprocess
import os
import select
import sys
def run_task(cmd, logger, msg=None, check_error=False):
"""Run task, report errors and log overall status.
Run given task using ``subprocess.Popen``. Log the commands
used and any errors generated. Prints stdout to screen if
in verbos... | 84495d43b2e0a05448f3f94e091efe042666ffbf | 42,086 |
def count_tiles_amount(product_id, product_version, core):
"""
This method counting actual amount transferred and exists on storage
:param product_id: str -> resource id of the layer to sync
:param product_version: version of discrete
:param core: "A" [send] | "B" [received]
:return: int -> tota... | 21d13935335220ad67135a1c91aba6310b5acef5 | 42,087 |
import numpy
def getelts(nda, indices):
"""From the given nda(ndarray, list, or tuple), returns the list located at the given indices"""
ret = [];
for i in indices:
ret.extend([nda[i]]);
return numpy.array(ret); | 91383b0b40d33f3c197bcb5b9d20900ae963cc47 | 42,088 |
def get_template_attribute(template_name, attribute):
"""Loads a macro (or variable) a template exports. This can be used to
invoke a macro from within Python code. If you for example have a
template named `_cider.html` with the following contents:
.. sourcecode:: html+jinja
{% macro hello(na... | 3af1f85cd2b7465ff6dda167b1737d1450360bea | 42,089 |
def _RoundTowardZero(value, divider):
"""Truncates the remainder part after division."""
# For some languanges, the sign of the remainder is implementation
# dependent if any of the operands is negative. Here we enforce
# "rounded toward zero" semantics. For example, for (-5) / 2 an
# implementation may give ... | 2c9d70c30d135684b3016584ab9c61aad32b3f7d | 42,090 |
from typing import Optional
def check_args(method, args) -> Optional[BoundArguments]:
"""Checks if arguments are suitable for given method.
Returns BoundArguments, or None on failure.
"""
try:
bound_args = signature(method).bind(*args)
bound_args.apply_defaults()
for name, par... | 01d860d240de60c0e0d962647d9063abaf54d773 | 42,091 |
import torch
def prepare(img, label=False):
"""
:param img: img(3d) or lab(2d), np
:param label: whether label
:return:
"""
if not label:
img = norm(img.copy())
img = torch.FloatTensor(img).cuda().float()
img = img.transpose(1,2).transpose(0,1)
return img.unsqueeze(0)
else:
lab = im... | ba61e075ca5904e170a59f34d199cd0c3a60b5ac | 42,092 |
def rebin(bins):
"""
Take in an array of bin edges and convert them to bin centers.
"""
bins = np.array(bins)
result = np.zeros(bins.size - 1)
for i, element in enumerate(result):
result[i] = (bins[i] + bins[i + 1]) / 2.
return result | f3a28fafdaa1a3d54515091e4455b28ee60a3b43 | 42,093 |
from typing import List
def __load_exported_activities() -> List[DiscoveredActivities]:
"""
Extract metadata from actions and probes exposed by this extension.
"""
activities = []
activities.extend(discover_actions("chaosazure.machine.actions"))
activities.extend(discover_probes("chaosazure.ma... | 84dc18e43bb76d34e45b6e0938aefe6234ded081 | 42,094 |
def shuffling_MI(symbol_counts, number_of_bins_d):
"""
Estimate the mutual information between current and past activity
in a spike train using the shuffling estimator.
To obtain the shuffling estimate, compute the plug-in estimate and
a correction term to reduce its bias.
For the plug-in esti... | c656a8b84845816a052c897b74ab868ba9f4f43d | 42,095 |
def determine_component_investment_cost(component, eM):
"""ex post determination method of roi"""
return value(investment_cost(component, eM)) | b2a000ee1b9f9ad0f509f3c8da4334edc3b398ad | 42,096 |
import os
def should_stop(experiment_path):
""" Checks if liftoff should exit no mather how much is left to run.
"""
return os.path.exists(os.path.join(experiment_path, ".STOP")) | bb3f52a9560d42c52cedaea9ea8a1f848b64d4b7 | 42,097 |
def income_quintile(households):
"""
Household income quintile at the MSA level.
"""
return pd.Series(
pd.qcut(
households['income'], 5, [1, 2, 3, 4, 5]),
index=households.index
) | 593ce1d4f65f67358ffae0dd2d28eab06f35c1bd | 42,098 |
from pyhomee.const import ATTRIBUTE_TYPES_LOOKUP
def get_attr_type(attr):
"""get attribute name by its type"""
return ATTRIBUTE_TYPES_LOOKUP.get(attr.type, ATTRIBUTE_TYPES_LOOKUP[0]) | b00e00af269b523d3340d3d6661f2b1725ebf28e | 42,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.