content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import cuml
from cuml.metrics import confusion_matrix
def build_and_predict_model(ml_input_df):
"""
Create a standardized feature matrix X and target array y.
Returns the model and accuracy statistics
"""
feature_names = ["college_education", "male"] + [
"clicks_in_%d" % i for i in range(... | 2d3e192986c680d910a401c9a4da295595fe236e | 3,652,400 |
def codes_new_from_file(fileobj, product_kind, headers_only=False):
"""
@brief Load in memory a message from a file for a given product.
The message can be accessed through its id and will be available\n
until @ref grib_release is called.\n
\b Examples: \ref get_product_kind.py "get_product_kind.p... | 47ed09dbf5bf59160dcab4c36dfd202ae7b190a5 | 3,652,401 |
from datetime import datetime
def list_resources(path, long_format=None, relations=False):
"""List resources in a given DMF workspace.
Args:
path (str): Path to the workspace
long_format (bool): List in long format flag
relations (bool): Show relationships, in long format
Returns... | 904f04a008efb8add2d7744bfe1dc71009faff17 | 3,652,402 |
def calc_streamtemp(tas):
""" Global standard regression equation from Punzet et al. (2012)
Calculates grid cell stream temperature based on air temperature
Both input and output temperature are in K"""
# global constants, taken from Punzet et al., 2012
c0 = 32; c1 = -0.13; c2 = 1.94
... | 493d1ca3b3543db9bfabc8c0e2a4f013da794028 | 3,652,403 |
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured data to conform to the schema.
"""
# nothing more to process
return proc_data | 7585a8810667f39d6d6a787f2617590aee1ec8cf | 3,652,404 |
import requests
def get_station_info(my_token, station_id):
"""
This function gets all the information on the station
----------
Input:
my_token (str)
token generated from "token request page"
station_id (str)
----------
Output:
dictionary of station information
"""
station_url = '{}stations/{}'.... | 9abcb5b74cb0be45396c1b182845467e3fc0829c | 3,652,405 |
import sys
import traceback
def json_response(f, *args, **kwargs):
"""Wrap a view in JSON.
This decorator runs the given function and looks out for ajax.AJAXError's,
which it encodes into a proper HttpResponse object. If an unknown error
is thrown it's encoded as a 500.
All errors are then packa... | fd80b5e3d259b9ef69f5278936d8d0dbccae6636 | 3,652,406 |
def check_fit_input(coordinates, data, weights, unpack=True):
"""
Validate the inputs to the fit method of gridders.
Checks that the coordinates, data, and weights (if given) all have the same
shape. Weights arrays are raveled.
Parameters
----------
coordinates : tuple of arrays
Ar... | eef22bb026aad657f096ac4de00a6d2a5a6fa0f8 | 3,652,407 |
import logging
import sys
def get_logger(name, handler=logging.StreamHandler(sys.stderr), level=logging.DEBUG):
"""
encapsulate get logger operation
:param name: logger name
:param handler: logger handler, default is stderr
:param level: logger level, default is debug
:return: logger
"""
... | 576827fa36ee4e2dae1073653612c1604b953200 | 3,652,408 |
def get_local_beneficiaries(map_lat: float, map_lng: float, map_zoom: int) -> DataFrame:
"""Return only projects that are fairly close to the map's centre."""
return beneficiaries[
(map_lat - 100 / map_zoom < beneficiaries.lat) &
(beneficiaries.lat < map_lat + 100 / map_zoom) &
(map_lng... | 30e0d7255a70c15a25f499e867974c711ae3f750 | 3,652,409 |
import argparse
def parse_args(args):
"""
Parse command line parameters
:param args: command line parameters as list of strings
:return: command line parameters as :obj:`argparse.Namespace`
"""
parser = argparse.ArgumentParser(
description="Build html reveal.js slides from markdown in... | ce1d6f0132876263bd7af5456c8a3596a3a49bdf | 3,652,410 |
def create_atoms(atoms, atom_dict):
"""Transform the atom types in a molecule (e.g., H, C, and O)
into the indices (e.g., H=0, C=1, and O=2).
"""
atoms = [atom_dict[a] for a in atoms]
return np.array(atoms) | 10f0e0d0669c2148db7cdcd487a6b72ade2e2f06 | 3,652,411 |
def uint2float(A,bits,x_min,x_max=None):
"""
Converts uint[bits] to the corresponding floating point value in the range [x_min,x_max].
"""
if x_max is None:
x_min,x_max = x_range(x_min)
return x_min + (x_max - x_min) * A / ((1 << bits) - 1) | 242b72824309a7e0724c42f29e259e52b11a90d2 | 3,652,412 |
def partCmp(verA: str, verB: str) -> int:
"""Compare parts of a semver.
Args:
verA (str): lhs part to compare
verB (str): rhs part to compare
Returns:
int: 0 if equal, 1 if verA > verB and -1 if verA < verB
"""
if verA == verB or verA == "*" or verB == "*":
return 0
if int(verA) > int(verB):
return 1
... | d9417ce482bf0c2332175412ba3125435f884336 | 3,652,413 |
import io
def OrigPosLemConcordancer(sentences, annots, textMnt, wordType="word", nrows=10):
"""Output HTML for the text (including lemma and pos tags) identified by the AQAnnotation (typically a sentence annotation).
Below the sentence (in successive rows) output the original terms, parts of speech, and lem... | f11f0240cbee58954901bd57e728cd54ab51b6dd | 3,652,414 |
import argparse
def get_args(**kwargs):
"""Generate cli args
Arguments:
kwargs[dict]: Pair value in which key is the arg and value a tuple with the help message and default value
Returns:
Namespace: Args namespace object
"""
parser = argparse.ArgumentParser()
for key, (hel... | f2cade1e0ec3b5a1fccd7ea94090c719de2849b6 | 3,652,415 |
def show_hidden_article(request, id):
"""
展示隐藏的文章
"""
db = connect_mongodb_database(request)
article = db.articles.find_one({
'Id':int(id), 'IsPublic': False
})
if article is None:
return HttpResponse(404)
return render_admin_and_back(request, 'show-hidden-article.html',... | 5f9f9c3bc21ed267d8c13226d51a7f44877af976 | 3,652,416 |
def MakeNormalPmf(mu, sigma, num_sigmas, n=201):
"""Makes a PMF discrete approx to a Normal distribution.
mu: float mean
sigma: float standard deviation
num_sigmas: how many sigmas to extend in each direction
n: number of values in the Pmf
returns: normalized Pmf
"""
pmf = Pmf()
... | 9bca22cfd3b3b94fa233be9f78696361d9e36726 | 3,652,417 |
import os
def _val_from_env(env, attr):
"""Transforms env-strings to python."""
val = os.environ[env]
if attr == 'rules':
val = _rules_from_env(val)
elif attr == 'wait_command':
val = int(val)
elif attr in ('require_confirmation', 'no_colors'):
val = val.lower() == 'true'
... | 023dc8eea2c9ed034f19c6ba89d57a815bc52903 | 3,652,418 |
def histogram(a, bins, ranges):
"""
Examples
--------
>>> x = np.random.uniform(0., 1., 100)
>>> H, xedges = np.histogram(x, bins=5, range=[0., 1.])
>>> Hn = histogram(x, bins=5, ranges=[0., 1.])
>>> assert np.all(H == Hn)
"""
hist_arr = np.zeros((bins,), dtype=a.dtype)
return ... | a53a8204180c8f9d2a3fb36595d14c07da262cbd | 3,652,419 |
import os
import test
def testfile(path, shell='/bin/sh', indent=2, env=None, cleanenv=True,
debug=False, testname=None):
"""Run test at path and return input, output, and diff.
This returns a 3-tuple containing the following:
(list of lines in test, same list with actual output, diff)
... | 05a397c09228fddfa61aba554f6d89cc62c5c59b | 3,652,420 |
def is_valid_python_code(src_string: str):
"""True if, and only if, ``src_string`` is valid python.
Valid python is defined as 'ast.parse(src_string)` doesn't raise a ``SyntaxError``'
"""
try:
ast_parse(src_string)
return True
except SyntaxError:
return False | 03ee9d915797ba1cfcbcaf8630d38df529744f1b | 3,652,421 |
def rss_format_export_post():
"""
:return:
"""
try:
payload = request.get_json(force=True) # post data in json
except:
payload = dict(request.form) # post data in form encoding
if 'link' in payload:
link = read_value_list_or_not(payload, 'link')
else:
link... | 2ddc5b814cabec3fd84f024d44cb04b0063890c5 | 3,652,422 |
from typing import Union
from typing import Callable
from typing import Iterable
import asyncio
def on_command(name: Union[str, CommandName_T],
*,
logger: Logger,
checkfunc: Callable[[CommandSession], bool] = None,
wait_for: Callable[[], bool] = None,
... | 5550188f41a3a8fcfee8ca0fc541f05222d6454e | 3,652,423 |
import os
def SetUp(filename, rel_path=RELATIVE_TEST_PATH):
""" SetUp returns a parsed C Program."""
if not os.path.exists(PICKLE_FILE):
KVStore.CreateNewStore(PICKLE_FILE, redhawk.GetVersion())
return G.GetLanguageSpecificTree(os.path.join(rel_path, filename),
PICKLE_FILE, language='c') | 259d7f2e8abe61a409c14359b155b25170e70762 | 3,652,424 |
def setup_agents(model, initial_locations):
"""Load the simulated initial locations and return a list
that holds all agents.
"""
initial_locations = initial_locations.reshape(2, model["n_types"], 30000)
agents = []
for typ in range(model["n_types"]):
for i in range(model["n_agents_by_t... | 40368819f0968b3fcaed6a1953f7e4fec453f471 | 3,652,425 |
async def get_active_infraction(
ctx: Context,
user: MemberOrUser,
infr_type: str,
send_msg: bool = True
) -> t.Optional[dict]:
"""
Retrieves an active infraction of the given type for the user.
If `send_msg` is True and the user has an active infraction matching the `infr_t... | 63361319b75e072489544e2956d21ff5cbe08590 | 3,652,426 |
def __compute_optical_function_vs_s(transporter, particles, optical_function_name):
# todo Adjust
"""
Compute values of optical function vs s for one particle, which coordinates are x_min, theta_x_min, ...
or x_mean - delta_x, ...
:param transporter: transport function
:param particles: BunchCon... | f4a68dad10184cc8c1c6185e49ef2e488a831fbb | 3,652,427 |
def plot_arb_images(label, data, label_string):
"""
Neatly displays arbitrary numbers of images from the camera
returns fig
Parameters:
-----------
label: array of values that each image is labeled by, e.g. time
data: array of arrays of image data
label_string: string describing label,... | 56e22d9f7a0651d56e93873b95c2228162f4a602 | 3,652,428 |
def listGslbServer(**kargs):
""" List the Servers of KT Cloud GSLB.
* Args:
- zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2]
* Examples: print(gslb.listGslbServer(zone='KR-M'))
"""
my_apikey, my_secretkey = c.read_config()
if not 'zone' in kargs:
return c.printZoneHelp()
... | 18d8f0e6699b7cb3080eef5a3d040420ea45329d | 3,652,429 |
import numpy
def imencode(image, pix_fmt=IM_RGB, quality=DEFAULT_QUALITY):
"""
Encode image into jpeg codec
Adapt convert image pixel color with pix_fmt
Parameters
----------
image: source
pix_fmt: format of pixel color. Default: RGB
quality: JPEG quality image.
Retur... | 65750d176275e56da55c0660370a56f44baa6e48 | 3,652,430 |
def split_train_test_data(X, Y, train_rate):
"""
将数据集划分为训练集与测试集
:param X: 数据集的特征
:param Y: 数据集的标签
:param train_rate: 训练集的比例
:return: 训练集的特征;训练集的标签;测试集的特征;测试集的标签
"""
number = len(X)
number_train = int(number * train_rate)
number_test = number - number_train
train_X = []
tr... | 7943278bc662968f8e019368ed8744d9e2a23929 | 3,652,431 |
def nonsingular_concat(X, vector):
"""Appends vector to matrix X iff the resulting matrix is nonsingular.
Args:
X (np.array): NxM Matrix to be appended to
vector (np.array): Nx1 vector to be appended to X
Returns:
new_X (np.array): Nx(M+1) Matrix or None
"""
# Cast vector to matrix
... | 68a1f6f8b0ea5e14fbbcacc618f2d19b07814813 | 3,652,432 |
from typing import Union
def get_oxidation_state(element: Union[str, Element]) -> int:
"""Get a typical oxidation state
If it doesn't exist in the database, 0 is returned.
Args:
element (str/ Element): Input element
Return:
Oxidation state of the element.
"""
try:
... | 24187bd8eb5c6d5794f1e287c676b0f16c170d55 | 3,652,433 |
from typing import Callable
def __quality_indexes(
graph: nx.Graph,
communities: object,
scoring_function: Callable[[object, object], float],
summary: bool = True,
) -> object:
"""
:param graph: NetworkX/igraph graph
:param communities: NodeClustering object
:param summary: boolean. I... | a328ec08bef43248c6e8fd7a0f11901801b0e2a5 | 3,652,434 |
from re import DEBUG
import os
def serve_scripts(scripts):
""" Combines one or more script files into one and embeds them in the
small autoCSP JavaScript framework. """
debug = DEBUG and not LOCKED_MODE
views_path = os.path.expanduser(PATHS['VIEWS'])
with open(views_path + 'static/sha256.js', ... | 27c4faedd7de71c1943250706c8ffca2e30251b3 | 3,652,435 |
def readFromDB_DSC_authorityKey(authorityKey: bytes, connection: Connection) -> DocumentSignerCertificate:
"""Reading from database"""
try:
logger.info("Reading DSC object from database with authority key.")
return connection.getSession().query(DocumentSignerCertificateStorage).filter(DocumentSi... | 34cff097201af92d337568094b8d48577f7e440f | 3,652,436 |
def history_report(history, config=None, html=True):
"""
Test a model and save a history report.
Parameters
----------
history : memote.HistoryManager
The manager grants access to previous results.
config : dict, optional
The final test report configuration.
html : bool, opt... | 8ba956c959b72f37b570b91ea4f01287eb8783c6 | 3,652,437 |
def derive_from_dem(dem):
"""derive slope and flow direction from a DEM.
Results are returned in a dictionary that contains references to
ArcPy Raster objects stored in the "in_memory" (temporary) workspace
"""
# set the snap raster for subsequent operations
env.snapRaster = dem
# ... | 4563e4ccd6695865c05c7a945dcc6244fb8af012 | 3,652,438 |
from typing import Optional
def from_error_details(error: str, message: str, stacktrace: Optional[str]) -> BidiException:
"""Create specific WebDriver BiDi exception class from error details.
Defaults to ``UnknownErrorException`` if `error` is unknown.
"""
cls = get(error)
return cls(error, messa... | 238566bcf1092b685deebcadcf60c1905e585cb9 | 3,652,439 |
def tangential_proj(u, n):
"""
See for instance:
https://link.springer.com/content/pdf/10.1023/A:1022235512626.pdf
"""
return (ufl.Identity(u.ufl_shape[0]) - ufl.outer(n, n)) * u | 92c8eafa222418221b2fb0e1b242dbd76696407d | 3,652,440 |
def _RemoveEdges(tris, match):
"""tris is list of triangles.
er is as returned from _MaxMatch or _GreedyMatch.
Return list of (A,D,B,C) resulting from deleting edge (A,B) causing a merge
of two triangles; append to that list the remaining unmatched triangles."""
ans = []
triset = set(tris)
... | d2415f7275652254ca87a7621e483a29816a8083 | 3,652,441 |
def get_course_authoring_url(course_locator):
"""
Gets course authoring microfrontend URL
"""
return configuration_helpers.get_value_for_org(
course_locator.org,
'COURSE_AUTHORING_MICROFRONTEND_URL',
settings.COURSE_AUTHORING_MICROFRONTEND_URL
) | cea917ca211be1fdd1b4cf028652101392fd80ab | 3,652,442 |
def sumDwellStateSub(params):
"""Threaded, sums dwell times with 1 day seeing no change & accounting for fractional days"""
(dfIn,dwellTime,weight) = params
dfOut = dfIn.copy(deep=True)
while dwellTime > 1:
if dwellTime > 2:
increment = 1
else:
increment = dwellT... | 47ab530bfad9a321bf349e7542f279aae0958a9b | 3,652,443 |
def launch_attacker_view():
"""
Accepts a JSON payload with the following structure:
{
"target": "nlb-something.fqdn.com",
"attacker": "1.2.3.4"
}
If the payload parses correctly, then launch a reverse shell listener using pexpect.spawn
then spawn the auto-sploit.sh tool and ente... | 2c987a2b552fa5cfc6e85240c71d496fe43785c3 | 3,652,444 |
import copy
def stretch(alignment, factor):
"""Time-stretch the alignment by a constant factor"""
# Get phoneme durations
durations = [factor * p.duration() for p in alignment.phonemes()]
alignment = copy.deepcopy(alignment)
alignment.update(durations=durations)
return alignment | 1ea58c32509365d503379df616edd00718cfca19 | 3,652,445 |
import time
import torch
import sys
def train(epoch, train_loader, model, contrast, criterion_l, criterion_ab, optimizer, opt):
"""
one epoch training
"""
model.train()
contrast.train()
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
l_loss_meter = A... | 8c1b5bc514f4013939b6403fe5c9860288492a8b | 3,652,446 |
import itertools
import sys
def create_issue_digraph(epics_stories):
"""Return a graph representation of all issues.
Blocking dependencies are modelled as graph edges.
"""
log.info('creating graph...')
graph = nx.DiGraph()
for epic, stories in epics_stories.items():
for issue in ... | f497341846a030e4e9be3235191f812593518c73 | 3,652,447 |
import os
def loadmesh(basedirMesh, ptcode=None, meshname=None, invertZ=True, fname=None):
""" Load Mesh object, flip z and return Mesh
meshname includes ctcode
"""
if fname is None:
try:
mesh = vv.meshRead(os.path.join(basedirMesh, ptcode, meshname))
except FileNotFoundErr... | f1940a07f8cb8949eb7cbbed822a4a57f400146d | 3,652,448 |
from thrift_sasl import TSaslClientTransport
from impala.sasl_compat import PureSASLClient
import getpass
def get_transport(socket, host, kerberos_service_name, auth_mechanism='NOSASL',
user=None, password=None):
"""
Creates a new Thrift Transport using the specified auth_mechanism.
Supp... | 71e7763066eaf5234b767101930505077954939f | 3,652,449 |
def _read_node( data, pos, md_total ):
"""
2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2
The quantity of child nodes.
The quantity of metadata entries.
Zero or more child nodes (as specified in the header).
"""
child_count = data[ pos ]
pos += 1
md_count = data[ pos ]
pos += 1
for i in range( child_count ):
pos, m... | 768036031ab75b532d667769477f8d3144129ac8 | 3,652,450 |
def _large_flag_fit(x, yDat, yFit, initz, speciesDict, minSize, errBound):
"""
Attempts to more robustly fit saturated lyman alpha regions that have
not converged to satisfactory fits using the standard tools.
Uses a preselected sample of a wide range of initial parameter guesses
designed to fit sa... | c065e9e1500977dfa1a522ebd238d2e71e188c6a | 3,652,451 |
from typing import Type
def mse_large_arrays_masked(dataA: 'LargeArray', dataB: 'LargeArray', mask: 'LargeArray',
dtype: Type, batchSizeFlat=1e8):
"""
Compute MSE between two HDF datasets, considering elements where the mask is set to true (one).
Computation is performed in bat... | 27636fc32d208d544b0b2f9790015e6f3d86a69d | 3,652,452 |
import copy
def xml_elem_or_str_to_text(elem_or_xmlstr, default_return=""):
"""
Return string with all tags stripped out from either etree element or xml marked up string
If string is empty or None, return the default_return
>>> root = etree.fromstring(test_xml)
>>> xml_elem_or_str_to_text(t... | 1e13c74d3d7d69fdd1ce8011384e1ee564f366f1 | 3,652,453 |
def sequence_equals(sequence1, sequence2):
"""
Inspired by django's self.assertSequenceEquals
Useful for comparing lists with querysets and similar situations where
simple == fails because of different type.
"""
assert len(sequence1) == len(sequence2), (len(sequence1), len(sequence2))
for i... | 38016a347caf79458bb2a872d0fd80d6b813ba33 | 3,652,454 |
def statistical_features(ds, exclude_col_names: list = [],
feature_names=['mean', 'median', 'stddev', 'variance', 'max', 'min', 'skew',
'kurt', 'sqr']):
"""
Compute statistical features.
Args:
ds (DataStream): Windowed/grouped DataStr... | 544b32b3f909c8f98ae18ae43006719105627a85 | 3,652,455 |
def second_order_difference(t, y):
""" Calculate the second order difference.
Args:
t: ndarray, the list of the three independent variables
y: ndarray, three values of the function at every t
Returns:
double: the second order difference of given points
"""
# claculate the f... | 40e37d2b34104772966afc34e41c1ebc742c9adf | 3,652,456 |
def timeDelay( gpsTime, rightAscension, declination, unit, det1, det2 ):
"""
timeDelay( gpsTime, rightAscension, declination, unit, det1, det2 )
Calculates the time delay in seconds between the detectors
'det1' and 'det2' (e.g. 'H1') for a sky location at (rightAscension
and declination) which must be give... | eb0f444ad2a2be0cf10d62fdbe8b41c8d924c798 | 3,652,457 |
def RngBinStr(n):
"""
Takes a int which represents the length of the final binary number.
Returns a string which represents a number in binary where each char was randomly generated and has lenght n.
"""
num = ""
for i in range(n):
if rng.random() < 0.5:
num += "0"
el... | cf063532425b51243f3ba95f90df892bda121363 | 3,652,458 |
def get_bdbox_from_heatmap(heatmap, threshold=0.2, smooth_radius=20):
"""
Function to extract bounding boxes of objects in heatmap
Input :
Heatmap : matrix extracted with GradCAM.
threshold : value defining the values we consider , increasing it increases the size of bounding boxes.
... | 0a7397263cf2b8b238679f3cd54b8bcb67553387 | 3,652,459 |
def get_request(request_id, to_json=False, session=None):
"""
Get a request or raise a NoObject exception.
:param request_id: The id of the request.
:param to_json: return json format.
:param session: The database session in use.
:raises NoObject: If no request is founded.
:returns: Requ... | 41d34057b859a88818866a03392ec6f96d2b4983 | 3,652,460 |
def gen_multi_correlated(N, n, c_mat, p_arr, use_zscc=False, verify=False, test_sat=False, pack_output=True, print_stat=False):
"""Generate a set of bitstreams that are correlated according to the supplied correlation matrix"""
#Test if the desired parameters are satisfiable
sat_result = corr_sat(N, n, c_m... | 0b1cf206e92363910877b0202b9fb94d377358a3 | 3,652,461 |
def rxzero_traj_eval_grad(parms, t_idx):
"""
Analytical gradient for evaluated trajectory with respect to the log-normal parameters
It is expected to boost the optimization performance when the parameters are high-dimensional...
"""
v_amp_array = np.array([rxzero_vel_amp_eval(parm, t_idx) for parm i... | 47aa04aa2096f472dd0f5612c95903fd638cb1d0 | 3,652,462 |
import traceback
def exec_geoprocessing_model():
"""算法模型试运行测试
根据算法模型的guid标识,算法模型的输入参数,运行算法模型
---
tags:
- system_manage_api/geoprocessing_model
parameters:
- in: string
name: guid
type: string
required: true
description: 流程模型的guid
- in: array
... | 8cfcc56117747c78d8b2c4fc10dc29fa8115aa67 | 3,652,463 |
import requests
def perform_extra_url_query(url):
"""Performs a request to the URL supplied
Arguments:
url {string} -- A URL directing to another page of results from the NASA API
Returns:
Response object -- The response received from the NASA API
"""
response = requests.request... | 7d5fe2d6467d90e1f7e85d2fc51187a36f62305d | 3,652,464 |
from org.optaplanner.optapy import PythonWrapperGenerator # noqa
from org.optaplanner.core.api.domain.solution import \
def problem_fact_property(fact_type: Type) -> Callable[[Callable[[], List]],
Callable[[], List]]:
"""Specifies that a property on a @plann... | 068cdbc1a8dab95b5a742740195b4fdaf595de2a | 3,652,465 |
def _load_method_arguments(name, argtypes, args):
"""Preload argument values to avoid freeing any intermediate data."""
if not argtypes:
return args
if len(args) != len(argtypes):
raise ValueError(f"{name}: Arguments length does not match argtypes length")
return [
arg if hasattr... | 0eb6a16c2e4c1cd46a114923f81e93af331c3d6e | 3,652,466 |
import json
def crash_document_add(key=None):
"""
POST: api/vX/crash/<application_key>
add a crash document by web service
"""
if 'Content-Type' not in request.headers or request.headers['Content-Type'].find('multipart/form-data') < 0:
return jsonify({ 'success': False, 'message': 'input e... | 669c30141d5fb50128b3c60577433938daec5a2a | 3,652,467 |
def log_data(model, action, before, after, instance):
"""Logs mutation signals for Favourite and Category models
Args:
model(str): the target class of the audit-log: favourite or category
action(str): the type of mutation to be logged: create, update, delete
before(dict): the previous v... | f23ef8d2a759130ac55d3dc55f4497099776414f | 3,652,468 |
import requests
def download(url, local_filename, chunk_size=1024 * 10):
"""Download `url` into `local_filename'.
:param url: The URL to download from.
:type url: str
:param local_filename: The local filename to save into.
:type local_filename: str
:param chunk_size: The size to download chun... | 0a86b8600e72e349a4e1344d2ce1ad2bb00b889d | 3,652,469 |
import glob
import os
def main(args=None):
"""Command line interface.
:param list args: command line options (defaults to sys.argv)
:returns: exit code
:rtype: int
"""
parser = ArgumentParser(
prog='baseline',
description='Overwrite script with baseline update.')
parser.... | 8af697724070557fbf0df669ad9b324e51e19a39 | 3,652,470 |
def tokenize(data, tok="space", lang="en"):
"""Tokenize text data.
There are 5 tokenizers supported:
- "space": split along whitespaces
- "char": split in characters
- "13a": Official WMT tokenization
- "zh": Chinese tokenization (See ``sacrebleu`` doc)
- "moses": Moses tokenizer (you can ... | 0974edc3a4d66b90add101002fbcc1486c21e5ce | 3,652,471 |
def ift2(x, dim=(-2, -1)):
"""
Process the inverse 2D fast fourier transform and swaps the axis to get correct results using ftAxis
Parameters
----------
x: (ndarray) the array on which the FFT should be done
dim: the axis (or a tuple of axes) over which is done the FFT (default is the last of t... | 50377bb81fa17c152f8b8053cdae1502dbc791ad | 3,652,472 |
def chi2_test_independence(prediction_files: list, confidence_level: float):
"""Given a list of prediction files and a required confidence level,
return whether the sentiment probability is independent on which prediction
file it comes from.
Returns True if the sentiment probability is independent of s... | 870a91afa202b19398c620756492bd5297c4eb69 | 3,652,473 |
import os
import yaml
import shutil
def fetch_all_device_paths():
"""
Return all device paths inside worker nodes
Returns:
list : List containing all device paths
"""
path = os.path.join(constants.EXTERNAL_DIR, "device-by-id-ocp")
clone_repo(constants.OCP_QE_DEVICEPATH_REPO, path)
... | ff2086b2b17aa41af5d775b6007757bdab32ad3c | 3,652,474 |
import os
def align(fastq_file, pair_file, index_dir, names, align_dir, data):
"""Perform piped alignment of fastq input files, generating sorted, deduplicated BAM.
"""
umi_ext = "-cumi" if "umi_bam" in data else ""
out_file = os.path.join(align_dir, "{0}-sort{1}.bam".format(dd.get_sample_name(data), ... | 0725dc73016e6b58af6948f7ca8611ab1c9819dd | 3,652,475 |
import json
async def insert(cls:"PhaazeDatabase", WebRequest:Request, DBReq:DBRequest) -> Response:
""" Used to insert a new entry into a existing container """
# prepare request for a valid insert
try:
DBInsertRequest:InsertRequest = InsertRequest(DBReq)
return await performInsert(cls, DBInsertRequest)
ex... | 20772f847137422a1da227da38946c9b1a01106a | 3,652,476 |
def eulerAngleXYZ(t123, unit=np.pi/180., dtype=np.float32):
"""
::
In [14]: eulerAngleXYZ([45,0,0])
Out[14]:
array([[ 1. , 0. , 0. , 0. ],
[-0. , 0.7071, 0.7071, 0. ],
[ 0. , -0.7071, 0.7071, 0. ],
[ 0. , ... | a0e6f0b58c1510aa27cb5064ddebd40b3688de37 | 3,652,477 |
def is_on_cooldown(data):
""" Checks to see if user is on cooldown. Based on Castorr91's Gamble"""
# check if command is on cooldown
cooldown = Parent.IsOnCooldown(ScriptName, CGSettings.Command)
user_cool_down = Parent.IsOnUserCooldown(ScriptName, CGSettings.Command, data.User)
caster = Parent.HasP... | b15180c7e890298cc1949ddfb199b42156ee66d9 | 3,652,478 |
def human_readable_size(num):
"""
To show size as 100K, 100M, 10G instead of
showing in bytes.
"""
for s in reversed(SYMBOLS):
power = SYMBOLS.index(s)+1
if num >= 1024**power:
value = float(num) / (1024**power)
return '%.1f%s' % (value, s)
# if size less... | 3c4ad148bc717b7058e90b3abf5efd67f6d92651 | 3,652,479 |
def sum_2_level_dict(two_level_dict):
"""Sum all entries in a two level dict
Parameters
----------
two_level_dict : dict
Nested dict
Returns
-------
tot_sum : float
Number of all entries in nested dict
"""
'''tot_sum = 0
for i in two_level_dict:
for j in... | 6b5be015fb84fa20006c11e9a3e0f094a6761e74 | 3,652,480 |
import os
def file_ref(name):
"""Helper function for getting paths to testing spectra."""
file = os.path.join(os.path.dirname(test_analyzer.__file__),
"test_analyzer", name)
return file | 60d6ef96ada77c2f0fe7b1d9e9012fec9f7f415c | 3,652,481 |
def q_values_from_q_func(q_func, num_grid_cells, state_bounds, action_n):
"""Computes q value tensor from a q value function
Args:
q_func (funct): function from state to q value
num_grid_cells (int): number of grid_cells for resulting q value tensor
state_bounds (list of tuples): state bounds for... | 2378f2021e16678b75622a23c9e57ba6b2f6d1d7 | 3,652,482 |
import requests
import sys
def list_keypairs(k5token, project_id, region):
"""Summary - list K5 project keypairs
Args:
k5token (TYPE): valid regional domain scoped token
project_id (TYPE): Description
region (TYPE): K5 region
Returns:
TYPE: http response object
Dele... | 9b7851ffbec5bb46f88a767ca5caca8368ead0eb | 3,652,483 |
import re
def check_ip(ip):
"""
Check whether the IP is valid or not.
Args:
IP (str): IP to check
Raises:
None
Returns:
bool: True if valid, else False
"""
ip = ip.strip()
if re.match(r'^(?:(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])'
'... | 2ff9a9262e46546fcb8854edee4b3b18ae1e2cc4 | 3,652,484 |
from typing import Iterator
from typing import Optional
def _stream_lines(blob: bytes) -> Iterator[bytes]:
"""
Split bytes into lines (newline (\\n) character) on demand.
>>> iter = _stream_lines(b"foo\\nbar\\n")
>>> next(iter)
b'foo'
>>> next(iter)
b'bar'
>>> next(iter)
Traceback... | 8a166af1f765ca9eb70728d4c4bb21c00d7ddbf8 | 3,652,485 |
from typing import Dict
async def fetch_all_organizations(session: ClientSession) -> Dict:
"""Fetch all organizations from organization-catalog."""
url = f"{Config.org_cat_uri()}/organizations"
org_list = await fetch_json_data(url, None, session)
return {org["organizationId"]: org for org in org_list}... | bf033ed85671214d9282acba3361fbdc1e6d4f6e | 3,652,486 |
from typing import Optional
import tqdm
def create_splits_random(df: pd.DataFrame, val_frac: float,
test_frac: float = 0.,
test_split: Optional[set[tuple[str, str]]] = None,
) -> dict[str, list[tuple[str, str]]]:
"""
Args:
df: ... | b8410d8672d11c8133b7d6d8dcdead46e668b3aa | 3,652,487 |
def ha_close(close,high,low,open, n=2, fillna=False):
"""Relative Strength Index (RSI)
Compares the magnitude of recent gains and losses over a specified time
period to measure speed and change of price movements of a security. It is
primarily used to attempt to identify overbought or oversold condit... | 655ce9be20f56a22cbe32ed0eaf7615d2b891577 | 3,652,488 |
def PLUGIN_ENTRY():
"""
Required plugin entry point for IDAPython Plugins.
"""
return funcref_t() | 5c669321d8fc890b8b352e4041dc75773d191664 | 3,652,489 |
def chao1_var_no_doubletons(singles, chao1):
"""Calculates chao1 variance in absence of doubletons.
From EstimateS manual, equation 7.
chao1 is the estimate of the mean of Chao1 from the same dataset.
"""
s = float(singles)
return s*(s-1)/2 + s*(2*s-1)**2/4 - s**4/(4*chao1) | 6b93743a35c70c9ed5b9f3fc9bece1e9363c5802 | 3,652,490 |
def inBarrel(chain, index):
"""
Establish if the outer hit of a muon is in the barrel region.
"""
if abs(chain.muon_outerPositionz[index]) < 108:
return True | 9cbc5dad868d6e0ca221524ef8fc5ed5501adaa4 | 3,652,491 |
import logging
def load_pretrained_embeddings(pretrained_fname: str) -> np.array:
"""
Load float matrix from one file
"""
logging.log(logging.INFO, "Loading pre-trained embedding file: %s" % pretrained_fname)
# TODO: np.loadtxt refuses to work for some reason
# pretrained_embeddings = np.loadtxt(self.arg... | 7d64851b9e602a7f588abec6fd88908e695f0c5c | 3,652,492 |
from typing import Union
from typing import Callable
from typing import Optional
from typing import Any
def text(message: Text,
default: Text = "",
validate: Union[Validator,
Callable[[Text], bool],
None] = None, # noqa
qmark: Text = DEFAUL... | 74a79a0ce10503cf10841e8370de870c7e42f8e9 | 3,652,493 |
def nav_bar(context):
"""
Define an active tab for the navigation bar
"""
home_active = ''
about_active = ''
detail_active = ''
list_active = ''
logout_active = ''
signup_active = ''
login_active = ''
friends_active = ''
snippets_active = ''
request = context['reque... | 77b5a8bb367228cc31a0f2454e494d97a5e2b411 | 3,652,494 |
def setup_models(basedir, name, lc=True):
"""
Setup model container for simulation
Parameters
----------
basedir : string
Base directory
name : string
Name of source component
Returns
-------
models : `~gammalib.GModels()`
Model container
"""
# Initi... | 8b8db045d5c7b669f579a8f3b74abe204c82c285 | 3,652,495 |
def create_csm(image):
"""
Given an image file create a Community Sensor Model.
Parameters
----------
image : str
The image filename to create a CSM for
Returns
-------
model : object
A CSM sensor model (or None if no associated model is available.)
"""
... | 681c3b5886346e793b26d2e7c801b924ca82b546 | 3,652,496 |
def walk(obj, path='', skiphidden=True):
"""Returns a recursive iterator over all Nodes starting from
findnode(obj, path).
If skiphidden is True (the default) then structure branches starting with
an underscore will be ignored.
"""
node = findnode(obj, path)
return walknode(node, s... | efd3e10329d7e8832fa33c9425974ea2cd80938c | 3,652,497 |
import os
import requests
def setThermalMode(host, args, session):
"""
Set thermal control mode
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used for setting the thermal
control mode
@param session: the active ... | 198b5c112e1f217665c78d6b9a8b87551844e073 | 3,652,498 |
def to_string(class_name):
"""
Magic method that is used by the Metaclass created for Itop object.
"""
string = "%s : { " % type(class_name)
for attribute, value in class_name.__dict__.iteritems():
string += "%s : %s, " % (attribute, value)
string += "}"
return string | a7e155c92c4e62c1f070a474905a7e0c654f45ff | 3,652,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.