content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def GetDistinguishableNames(keys, delimiter, prefixes_to_remove):
"""Reduce keys to a concise and distinguishable form.
Example:
GetDistinguishableNames(['Day.NewYork.BigApple', 'Night.NewYork.BigMelon'],
'.', ['Big'])
results in {'Day.NewYork.BigApple': 'Day.Apple',
... | 13cc78b172d0ae074fa3bfa3d9ff93f5877c557d | 3,606,867 |
def sabr_receivers_swaption_value(
init_swap_rate,
option_strike,
swap_annuity,
option_maturity,
alpha,
beta,
rho,
nu):
"""sabr_receivers_swaption_value
calculate european reciever's swaption value.
This value is calculated by put-call parity.
... | 95f01a7d05601393715d5427a0a6afcd4266a5b3 | 3,606,868 |
def format_filing_path(**kwargs):
"""
"If at first you don\'t succeed, don\'t try skydiving."
That makes about as much sense as a docstring as the workaround below.
It\'s... horrifying what I\'ve done here.
So lemme splain the what and why.
We want a conf file that is useful for paths and whate... | e61a98762952afc9a815ec8bdfadf2de2586e111 | 3,606,869 |
import random
def randomized_parameter_test(
egg_data: pd.DataFrame,
param: str,
t1: str,
t2: str,
save_pic_flags: dict,
figs_dir: str,
permutation_total: int = 1000,
plot_stuff: bool = False,
verbose: bool = False,
):
"""
Conducts a randomization-based hypothesis test of w... | f86e6f0f6f140afa3fb3922daa77aff926788129 | 3,606,870 |
def Create(environment_ref, flags, is_composer_v1):
"""Calls the Composer Environments.Create method.
Args:
environment_ref: Resource, the Composer environment resource to create.
flags: CreateEnvironmentFlags, the flags provided for environment creation.
is_composer_v1: boolean representing if creatio... | 9c7c258a76e1912a512887ee79f957aab12f1ee6 | 3,606,871 |
def uu_get_industries():
"""
按照行业分类获取行业列表
:param :name: 行业代码, 取值如下:
"sw_l1": 申万一级行业
"sw_l2": 申万二级行业
"sw_l3": 申万三级行业
"jq_l1": 聚宽一级行业
"jq_l2": 聚宽二级行业
"zjw": 证监会行业
:rtype :pandas.DataFrame
:return:index: 行业代码
name: 行业名称... | 56cafe1bc0afbd82a5a7ff3c49d3ffcf90a6b362 | 3,606,872 |
import torch
def load_single_op(model_name):
"""Given a model name, returns a single-operator model in eval
mode as well as an example input."""
model = getattr(single_op, model_name)().float().eval()
input_shape = [1, 3, 224, 224]
input_data = torch.rand(input_shape).float()
return model, inp... | 490eb4a09d00d1f189ffac18549211ab9dac9e48 | 3,606,873 |
import binascii
import re
def humanhexlify(data, n=-1):
"""Hexlify given data with 1 space char btw hex values for easier reading for humans
:param data: binary data to hexlify
:param n: If n is a positive integer then shorten the output of this function to n hexlified bytes.
Input like
'ab\x... | 883323524ecc8b9f55138d290a38666e5c06bac3 | 3,606,874 |
import re
def yes_workload_no_snippet_target_line(patterns, painted_lines, split_text):
"""Find line to use for scan process in yes workload, no code snippet use case"""
faultable_line_list = []
faultable_line_number_list = []
for line_number in painted_lines:
detected_parts_list_line = split... | bcfdee07500c564c3b2bd82e2fefa24533e06e67 | 3,606,875 |
def make_arc_consistent(Xj, Xk, csp):
"""Make arc between parent (Xj) and child (Xk) consistent under the csp's constraints,
by removing the possible values of Xj that cause inconsistencies."""
# csp.curr_domains[Xj] = []
for val1 in csp.domains[Xj]:
keep = False # Keep or remove val1
f... | 12f75686cf18fdb9b976f36c7e985593bc0aaf10 | 3,606,876 |
from functools import reduce
def deal_edge(the_sample_train, the_dat_edge):
"""
提取出每一个用户的“流出”特征: 向量长度、times之和、times的中位数、最小值、最大值
weight之和、weight的中位数、最小值、最大值,这样就用9个特征提取出了“流出”特征
"""
col_names = (['length', 'unique_count', 'times_sum', 'weight_sum']
+ ['dup_ratio_left', 'dup_ratio_1',... | d21933bcde6ed6cf05090b6b15b2974f3e0299b8 | 3,606,878 |
def encode_pixel(pixel, bit):
"""Encodes given bit in given pixel luma value.
Args:
pixel: tuple representing pixel's rgb/rgba values
bit: bit to encode
Returns:
tuple: tuple representing encoded pixel's rgb/rgba values
"""
pix_ycc = _ycc(*pixel)
sec = pix_ycc[0]
se... | 83c8044ff7b64f7b290826172e13005adc2c4288 | 3,606,879 |
def get_subfiles(root_path, is_recursive=False):
"""
Returns all files (non-directory) in the given root_path.
:param root_path: The path of the folder from which we will begin traversing.
Remember that if this is not a folder, an error will be thrown.
:param is_recursive: If true, w... | 5c20d73f9332a4839bce5e18e546982f9f8f64ed | 3,606,880 |
import math
def resolveToJamoIndex(syllable):
"""
음절로부터 자보 배열을 생성한다.
:param syllable:
"""
code = syllable.charCodeAt(0) - 0xAC00
choseong = math.floor(((code - code % 28) / 28) / 21)
jungseong = math.floor(((code - code % 28) / 28) % 21)
jongseong = code % 28
def isValid(n):
... | ac65b58e02a5190f087a34db3efb2656726a6c77 | 3,606,882 |
def page_body_class(context):
"""
Get the CSS class for a given resolved URL.
"""
try:
return "url-{}".format(context.request.resolver_match.url_name)
except AttributeError:
return "404" | ec998cc7c4710837944e72130a3e7e761290cdde | 3,606,883 |
from re import T
from re import M
def get_search_request_filter(folder_ids, subject=None, sender=None, body=None, int_msg_id=None, restriction=None, email_range="0-10"):
"""
Link for Restriction node
https://msdn.microsoft.com/en-us/library/office/aa563791(v=exchg.150).aspx
Link for the FieldURI's
... | 14ba6d398a41bc602cdaf7673ba5f60c9fe19d0c | 3,606,885 |
async def upload_file(
request: web.Request,
upload_token,
uploaded_file
) -> web.Response:
"""Uploading of a specified file from a local computer.
:param request:
:type request: web.Request
:param upload_token: Upload token associated with a given file for Archive uploading as ... | e8b11960dac7fd5bdd7413711a32a6ec1bd7be3f | 3,606,886 |
def hier_softmax(true_dict=None, pred_dict=None,
hier_graph=None, weight_mode="exp",
criterions=None, verbose=0):
""" Returns weighted softmax loss for hierarchical clf results.
Inputs:
* true_dict: dict containing pairs of (classes, preds) for every level
... | 3f611c3a255f2cd6cc7deec9bf26ede829daead7 | 3,606,887 |
def do_full_tree(md_trees, subsystem_id, compact):
"""
Merge each tree in md_trees and generate the full landscape product tree
"""
full_tree = Tree()
node0 = Product('full_' + subsystem_id, # 1 (0 is self)
'Full ' + subsystem_id + ' Tree', # 2
... | 71fe9e06b86d1ca8ed5b51bfe62c2970cdf6c2cb | 3,606,888 |
def list_versions(schema_type):
"""
Lists all current JSON schema versions.
"""
if schema_type == "input":
return list(_input_version_list)
elif schema_type == "output":
return list(_output_version_list)
elif schema_type == "molecule":
return list(_molecule_version_list)
... | e3f0e5165c6229d4d7f29adc99af071d882ad2e4 | 3,606,891 |
import collections
def readUncertainties(root, nodeTag, paramsDict):
"""
Read xml node "Uncertainties" in the input file
@ In, root, xml.etree.ElementTree.Element, root xml element node
@ In, nodeTag, str, node tag that is used to find the node
@ In, paramsDict, dict, paramsDict returned by readPara... | 85d707cdc110f5561028de52a5ab47da57c59d9f | 3,606,892 |
import json
def load_class_map(file_path):
""" Returns class names map. """
if file_path is not None and exists(file_path):
with open(file_path, 'r') as input_stream:
data = json.load(input_stream)
class_map = dict(enumerate(data))
else:
class_map = None
retur... | f5a6b0086b50860cf446ba5457b3a36e71f0b646 | 3,606,893 |
def csvfile_out(csvfile):
"""Returns a function that will write out connections from a {_ConnectionKey->{key->value}}
dictionary (where their keys are the properties of the connection).
The function is used as a callback for writing 'buckets'. Note that prior to using that
function, the passed ... | fc82fb038d6d70ef12f455dcb1bc923b3c02042b | 3,606,894 |
def vstack_maps(obj, nfm):
"""
Stack the feature maps vertically.
"""
assert obj.shape[1] % nfm == 0
return np.vstack(np.hsplit(obj, nfm)) | 279537b34c930bd1bd33bdc8ae686ae8279e312b | 3,606,895 |
def custom_connect(hook_point, module_path, original_connect, *args, **kwargs):
""" Replacement to the connect function of a DBApi2 module. It will
instantiate a connection via the original connect function and proxy it
via CustomConnection defined earlier.
"""
def wrapper(*args, **kwargs):
... | 75224bc76e1849287adc1c68dc7de3a9e76ac1d7 | 3,606,896 |
def CreateHTMLStringBody(pre_HTML_d):
"""
Inputs:
pre_HTML_d: (dict)
MultiCodes_reports_list: (list) Each element is a MC_report_d:
MC_report_d: (dict)
fastq_fp: The path to the fastq file
nReads: i
nOff: d
... | db116bff0d8c15d12121ec57251b75732cb85f40 | 3,606,897 |
from datetime import datetime
def add(investor_id, amount, frequency=TransferFrequency.NOW,
start_date=None, end_date=None):
"""
Add fund to the account
:param investor_id: int - the investor account id
:param amount: float - amount to withdraw
:param frequency: member of lendingclub2.con... | f07912c5d810ae0adb3b8984fcc15cc36a314233 | 3,606,898 |
def determine_next_openstack_release(release):
"""Determine the next release after the one passed as a str.
The returned value is a tuple of the form: ('2020.1', 'ussuri')
:param release: the release to use as the base
:type release: str
:returns: the release tuple immediately after the current on... | 71c06182781a3c6287f2636f2ce9f81489d8f54f | 3,606,899 |
def azimuthalAverage(image, center=None, stddev=False, returnradii=False, return_nr=False,
binsize=0.5, weights=None, steps=False, interpnan=False, left=None, right=None, return_max=False):
"""
Calculate the azimuthally averaged radial profile.
NB: This was found online and should be properly credi... | a2a36dc2398ad9a2eabee3adb6eb785c386a1130 | 3,606,901 |
def get_constraints_D(D_topright, anchors, basis, vectorized=False, A=None, b=None):
""" Get constraints on Z given by the distances.
.. math::
t_{mn}^T Z t_{mn} = d_{mn}^2
where :math:`t_{mn} = (a_m^T -f_n^T)^T`
:param D_topright: squared distsance measurements, shape (n_positions x n_anchor... | 6d101509ab044c83bcb0dd17ddc8c623ec8cf70a | 3,606,902 |
def mmd_poly(X, Y, degree=2, gamma=1, coef0=0):
"""MMD 多项式核 即 k(x,y) = (gamma <X, Y> + coef0)^degree
参数:
X {[n_sample1, dim]} -- [X matrix]
Y {[n_sample2, dim]} -- [Y matrix]
参数关键字:
degree {int} -- [degree] (default: {2})
gamma {int} -- [gamma] (default: {1})
coef0 ... | 329eca1200b14e2debdbddf4b07d70a956851095 | 3,606,903 |
def delete(id):
"""
deletes a director with given id.
:param uuid.UUID id: person id.
:returns: count of deleted items.
:rtype: int
"""
return get_component(DirectorsPackage.COMPONENT_NAME).delete(id) | 251a9f47b1377900bd4124d7b72bd9d8ea6ccbf7 | 3,606,904 |
def should_build(
req, # type: InstallRequirement
need_wheel, # type: bool
check_binary_allowed, # type: BinaryAllowedPredicate
):
# type: (...) -> Optional[bool]
"""Return whether an InstallRequirement should be built into a wheel."""
if req.constraint:
# never build requirements tha... | 3f25479fad5cd792f4bcfe9ee2dfa38f62a64a7b | 3,606,905 |
def kill_multiedges_reaxis(f, v, fg):
"""Combine all multiedges between f and v in fg.
DOES NOT PERFORM COMPUTATION. This is a helper function and should only be
used in other functions which perform the appropriate computation.
No indexing is performed on the factor of f. This purely deals with the
... | 89de0ae46d84952d6c2d90aa9cc488f9976e5e75 | 3,606,906 |
async def authorize():
"""Redirects to spotify authorization."""
url = await authorize_spotify()
return RedirectResponse(url.get('spotify')) | 80d4d5c15a2180ea1f7ffb7a61ef537bb26a36dd | 3,606,907 |
import json
def guest_clone(hypervisor, host, guest_id):
"""
Clone a guest
::
POST /:hypervisor/:host/guests/:guest_id/clone
"""
response.content_type = "application/json"
manager = create_manager(hypervisor, host)
data = request.body.readline()
if not data:
abort(400,... | 62f074a475305b0fec4cb0507ef03f3336c58ec5 | 3,606,909 |
def parse_date(s):
"""Parse date from string.
If no timezone is specified, default is assumed to be local time zone.
:param s: The date to parse.
:type s: str
"""
return iso8601.parse_date(s, LOCAL_TIMEZONE) | 76cd438facc18167593b95dd6428f1dddfe34988 | 3,606,910 |
def build_ip_dict(ip):
"""
Takes in ip address as string, if valid IP, builds a dictionary
:param ip:
:return:
"""
inner_ip = ip
def _build_ip_dict(inner_ip):
if valid_ip(inner_ip):
return {"ip_address": inner_ip}
if type(inner_ip) is dict:
if 'entry_ip_add... | 246a21891143c42386354654018d0302a33380d0 | 3,606,911 |
def calc_anchor(sam, scaf_to_ref):
"""anchoring、染色体を突き止めた度合い"""
# scafs[scaf_name] = {T:0, F:0}
scafs = defaultdict(lambda: {"T": 0, "F": 0})
refs = defaultdict(lambda: {"T": 0, "F": 0})
for ref_name, ref_start, scaf_name, scaf_start, mapq, ori in sam:
if mapq >= 60 and scaf_name in scaf_to_... | 821fec9eeb3a95b6b4e6758b29c87a4a7ef22b46 | 3,606,912 |
def pca(U, centre=False):
"""Compute the PCA basis for columns of input array `U`.
Parameters
----------
U : array_like
2D data array with rows corresponding to different variables and
columns corresponding to different observations
center : bool, optional (default False)
Flag ind... | 491e64f4316e6be8db5c8359345a46ad370b5c42 | 3,606,913 |
def set_heads(doc, heads):
"""Set heads to doc in UD annotation style.
If fail to set, return doc without doing anything.
"""
if max(heads) > len(doc) or min(heads) < 0:
return doc
for head, token in zip(heads, doc):
if head == 0:
token.head = token
else:
... | bad84ae29c0f5000d02243c55350df0a2dc698f4 | 3,606,914 |
def get_feed_renderer(engines, name):
"""
From engine name, load the engine path and return the renderer class
Raise 'FeedparserError' if any loading error
"""
if name not in engines:
raise FeedparserError("Given feed name '{}' does not exists in 'settings.FEED_RENDER_ENGINES'".format(n... | 3f9b8c68904b2abae6dddb27b286bd5502adddd9 | 3,606,915 |
from app import bcrypt
from app import cors
from app import db
from app import migrate
from app.api import api
def create_app(environemnt):
"""
App factory for the server.
Instantiates a Flask object.
Configures the app according to the environment.
Initializes the extensions.
Adds the middle... | 3ae92139a0c75d8405bb06f0f0746904a9ce110c | 3,606,916 |
def ping(request):
"""
Ping view for Service health checks
Service is healthy if we can query database
"""
db_status = False
try:
Enquiry.objects.exists()
db_status = True
except OperationalError:
pass
return HttpResponse(
"OK" if db_status else "ERROR"... | 4cdc652e5eab990a6a0a3455361a07acd849fc23 | 3,606,918 |
def main(arguments):
"""
Main function that sets the functionality
of the software that will be used [Pele, Adaptive, glide...]
and launch the respective job
"""
#arguments = YamlParser(arguments.input_file)
set_software_to_use(arguments)
job = Launcher(arguments)
job.launch()
re... | f50434a5b5d958989399d3cddf6f491cdbbdb555 | 3,606,919 |
def sammenlign( kandidat, neste, koordinattoleranse = 1e-6):
"""
Regler for nå to oppføringer kan slås sammen: Samme koordinat, samme vegref-verdi og tilstøtende datoer
"""
dx = kandidat['geometry']['coordinates'][0] - neste['geometry']['coordinates'][0]
dy = kandidat['geometry']['coordinates'... | d23b7ca13177255c135ead3687443d8693841022 | 3,606,920 |
def _get_vacuum_device_charging():
"""Return a vacuum device charging."""
device = mock.Mock(spec=Dyson360Eye)
device.name = "Device_Vacuum"
device.state = mock.MagicMock()
device.state.state = Dyson360EyeMode.INACTIVE_CHARGING
device.state.battery_level = 40
device.state.power_mode = PowerM... | 614b7a33e9c07cf026b7568aeffa0aa9ff91bf27 | 3,606,922 |
import random
def gen(n_frames, n_points):
"""
Generate frames, each contains points with random y value
n_frames -- Number of frames
n_points -- Number of points
"""
frames = array_init(n_frames)
for i in range(n_frames):
points = array_init(n_points) # initialize a list with size
for j in ran... | d58be345b9512fbbe3de35553fdd2620a4bec015 | 3,606,923 |
def proper_fits_shapes(qname, uname, frequencyname):
"""
Verify that the Q and U FITS cubes and the file with frequency
data have compatible shapes. *qname* and *uname* are the filenames
of the Q and U FITS files, respectively; *frequencyname* is the
filename of the frequency file.
Returns True... | 019db6b7dab5ed05b41c2c86d7d00cc99beaaf55 | 3,606,924 |
def is_row(y):
"""
Checks if input array is a row
Parameters
----------
y : array_like
Input array
"""
y = np.asarray(y)
shape = y.shape
if len(shape) == 1:
return True
return shape[0] == 1 | c7f68ab0c8f0e1229e56509e609f353f86137c79 | 3,606,925 |
def input_fn_builder(input_files,
max_seq_length,
max_predictions_per_seq,
is_training,
vocab_size,
num_cpu_threads=4):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
def input_fn(params):
... | 9ae6cb71cad68a110ce1b884b5126a45dfdde932 | 3,606,927 |
def conv2d_transpose(inputs,
num_output_channels,
kernel_size,
scope,
stride=[1, 1],
padding='SAME',
data_format='NHWC',
use_xavier=True,
stddev=1e-3,
... | a062e3b5f8060e3a92b3a06125be2b1e39153c45 | 3,606,928 |
def is_valid(number):
"""Check if the number provided is a valid tax identification number.
This checks the length, formatting and check digit."""
try:
return bool(validate(number))
except ValidationError:
return False | dfb03a49c109a9971d4d9c09921593de1f4ba420 | 3,606,931 |
def pack_bits(bits):
"""
Pack tf.uint8 bit arrays into arrays of tf.int64 by interpreting blocks of 64 bits
as an int64.
Args:
bits: A tf.uint8 `Tensor` of shape (None, n_bits). `n_bits` must be a multiple of 64.
Returns:
bits: A tf.int64 `Tensor` of shape (None, n_bits // 64)
""... | f0ee8369f1836ce71bbebf225709b254e08cfeda | 3,606,932 |
def gateway_info(country, language):
"""Load information about the hosts to use for API interaction.
`country` and `language` are codes, like "US" and "en-US,"
respectively.
"""
return lgedm_post(GATEWAY_URL, {"countryCode": country, "langCode": language},) | b79a2d93e8a4ef334c08e77d4f96f89679966987 | 3,606,933 |
import torch
def validate_inf(
model,
config,
val_images,
log_folder=None,
use_full_size=True,
global_threshold=None,
use_tta=False,
save=False,
save_all_tta=False,
):
"""
Performs inference with a model on a list of train images.
Args:
model (torch model): Seg... | 7b13a8c926679a94d2daf55515120ad4fd6b2cfb | 3,606,934 |
import numpy as np
import pandas as pd
from scipy.special import erfcinv, gammaln
from . import CiaoEnvironment
def compute_bgband (evtpath, srcreg, bkgreg, ebins, env=None):
"""Compute background information for a source in one or more energy bands.
evtpath
Path to a CIAO events file
srcreg
... | a1dc0abe9fbad4bc9e0a3cd7211f5e10cf95e17d | 3,606,935 |
def compute_fs(photspec, x, dE_dVdt_inj, dt, method='old', cross_check=False):
""" Compute f(z) fractions for continuum photons, photoexcitation of HI, and photoionization of HI, HeI, HeII
Given a spectrum of deposited photons, resolve its energy into continuum photons,
continuum photons, HI excitation, an... | 46fe61a4584f898fdbf6534f70d109c950d11f3d | 3,606,936 |
def tokenize(text):
"""Simple tokenizer, change for something more sophisticated
"""
return text.lower().split() | ce7269ebfe3446c70346cef38a526393accda8b8 | 3,606,937 |
from typing import Optional
def build_compound(smiles: Optional[str] = None,
name: Optional[str] = None,
amount: Optional[str] = None,
role: Optional[str] = None,
is_limiting: Optional[bool] = None,
prep: Optional[str] = No... | 6802831b277c8d213e3b93c886264bd3d5457130 | 3,606,938 |
def num_components():
"""Get the number of components available on the system.
:rtype: int
"""
return lib.PAPI_num_components() | fdc2fe8cf766e48832c643fddab2f90aa7c8b1d1 | 3,606,939 |
def route_not_found(error):
"""route to handle error"""
return error | 83b1f52de8ed92e8b8a833ba85ce725cbb5d3757 | 3,606,940 |
def _task_to_entry_point_ids(meta_task):
"""Generate entry points from a meta-task. $entry:e_0, $entry:e_1, ...
From the commandline, the usage would be
-e e_0:/path/to/file1.txt -e e_1:/path/to/file2.txt
This is used to automatically create pipeline entry points from the
positional inputs of the... | 768971a4b6f43bb13a56497c25de698abd9196ba | 3,606,941 |
import torch
def genomepredict(
sequence, mchr, mpos=-1, wpos=-1, models=["h1esc", "hff"], targets=None, annotation=None, use_cuda=True, nan_thresh=1,
):
"""Multiscale prediction for a 32Mb sequence
input, zooming into the position specified when generating a series
of 32Mb, 16Mb, 8Mb, 4Mb, 2Mb and 1M... | 6285c222924dd1c8d1993214f262b242431e214c | 3,606,943 |
def clean_mentions(line):
"""Escape anything that could resolve to mention."""
return line.replace("@", "@\u200b") | b23ae6f9f0d54c5c2d210cf9f8a14732acd5b532 | 3,606,944 |
def _parse_function(filename, label, n_channels, size):
"""
Returns resized and normalized image and its label
"""
resized_image = _parse_image(filename, n_channels, size)
return resized_image, label | e8307e33a5a9ef39890b9c8bafc2bed8e2c5ed57 | 3,606,945 |
def delete(isamAppliance, name, check_mode=False, force=False):
"""
Delete a management authorization role
"""
if force is True or _check(isamAppliance, name) is True:
if check_mode is True:
return isamAppliance.create_return_object(changed=True)
else:
return isam... | e362caf8c34430a3d662cbf01bd8aff6fc4a5a50 | 3,606,946 |
def test_no_extra_meta(wrapper_class, build_fn):
"""Check that wrappers do not create any unexpected meta parameters.
"""
n, d = 20, 3
n_classes = 3
X = np.random.uniform(size=(n, d)).astype(float)
y = np.random.choice(n_classes, size=n).astype(int)
# with user kwargs
clf = wrapper_clas... | 14a72cf5f35136b7507da32df3e210acd151a59b | 3,606,947 |
import re
def _tf_model_node_name_reformat(node, node_name):
"""
Rename the node name by combining scope name and its original name.
Args:
node (OnnxGraphNode): OnnxGraphNode instance.
node_name (str): node name saved in Graph.
Returns:
str, re-formatted node name.
"""
... | 3103ad87eaa4d923274f5f9aa529188879d48a7a | 3,606,948 |
import time
def ctime():
"""
Get time now
Returns:
time_string (str): current time in string
"""
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) | 57dfa3f2c9e4c7dbff51e18cdc63011df37a7241 | 3,606,949 |
def mean_percentage_error(y_true: np.ndarray, y_pred: np.ndarray):
"""
Mean Percentage Error
Formula taken from:
https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5365136/
Parameters
----------
* y_true : pd.Series
The observations of the time series
* y_pred : pd.Series
The val... | c5d3e7502dac6849629f8743a40ffc149c59304b | 3,606,950 |
def conn_ravel_directed(da, sep='-', drop_within=False):
"""Ravel a directed array.
This function reorganize a directed array that contains the coordinates
x->y and y->x to a single coordinate 'x->y'.
Parameters
----------
da : xarray.DataArray
Xarray DataArray that should at least con... | ce4e9019a9282248f294cae1b5bb11f29287e692 | 3,606,951 |
def verify_credentials_command(
client: Client,
account_id: str,
) -> str:
"""Mark an account for verification by the CPM.
:param client: The client object with an access token
:param account_id: The unique ID of the account.
:return: Action was succeeded notice
"""
client.verify... | 9edd0ee67e326f63e9570674aea8463df41a6847 | 3,606,952 |
def is_clique(S, A):
"""Check if the subgraph of A induced by nodes S is a clique.
Parameters
----------
S : set of ints
set containing the nodes' indices
A : np.array
the adjacency matrix of the graph, where A[i,j] != 0 => i -> j
and A[i,j] != 0 & A[j,i] != 0 => i - j.
... | 4b4d54fe6df226def988069c421c03fd088461b3 | 3,606,953 |
from typing import List
def mention_to_tokens(
mention: Mention, token_type: str = "words", lowercase: bool = False
) -> List[str]:
"""
Extract tokens from the mention
:param mention: mention object.
:param token_type: token type that wants to extract (e.g. words, lemmas, poses).
:type token_... | 927e10cecd6dde28f2595ed594807a77d615c376 | 3,606,954 |
import ast
def is_valid_ast(tree):
"""Make sure an ast is valid by trying to compile it"""
try:
ast.fix_missing_locations(tree)
compiled = compile(tree, "<test-ast>", "exec")
except (SyntaxError, ValueError, TypeError) as e:
return (False, e)
return (True, None) | ede0c703e463d9bfbe15831e03de474d669aba44 | 3,606,955 |
import math
def solve_elbow_xy(xpos, ypos, parity, length1, length1sq, length2, length2sq):
"""
Helper function to solve the elbow location given a target position
(xpos, ypos), parity choice (-1 or 1) and arm radii.
In the polar coordinates, theta is an angle measured clockwise from
the Y ax... | d69be29233d6906693135a28e9bf357ce1eac76c | 3,606,956 |
def getCommonsMembersBetween(startDate, endDate, outputParameters= \
['Constituencies', 'Parties', 'HouseMemberships']):
"""
Returns all Commons members between startDate and endDate,
which must be instances of datetime.date.
"""
s = '{0}-{1}-{2}'.format(startDate.year, startDate.month, startDate.day)
e = '{0}... | 5fa9e76bb2c92f3c305f8fa1c1188c66ca50b6fb | 3,606,958 |
def rstar_minmax(blk, crvlist):
"""
Allow only valid values of rstar in the given block.
"""
## get min and max rstar values
j = blk.j
lims = rstar_limits(blk.master.metfunc)
left, right = lims[j], lims[j+1]
rstar_min, rstar_max = np.sort(np.array([left, right]))
## proceed to mask curves
out = []
for crv in... | 0dbea61f7c462d122dbd02b01e3f9aadf74b9d46 | 3,606,959 |
from typing import List
def get_characters_surrounding_index(password: str, index: int) -> List[str]:
"""
:param password: str
:param index: int, index representing index from param password
:return: list in form [str, optional str] where first index is character before the param index and the second ... | c78610300092d46fcc9ed171279f0025188cb98c | 3,606,961 |
import re
def param_name_is_valid(p, q):
"""Checks correct formatting of parameter name.
Markup allowed: <> <{}> <[]> <()>
Characters allowed: $,a-z,A-z,0-9,\-,_
:param p: pre-processed parameter name for JS <script> compatibility
:param q: original parameter name in template
:return:
""... | 2415f0a198518f113fcfe10a671b9225619eb978 | 3,606,962 |
def HasTargetArch():
"""Returns True if the user specified an architecture to compile for."""
return HAS_TARGET_ARCH | 7b6917159853541881f7dff322c30fdcc7e476e9 | 3,606,964 |
def instance_has_suspended(instance, log_files, alarms, event_logs, alarm_history,
start_datetime, end_datetime, action=False,
guest_hb=False):
"""
Returns true if the instance has suspended
"""
success, reason = instance_is_suspended(instance)
i... | 9fcb0e394d94c3e2feb7f35c68dcbd26d5c6388b | 3,606,965 |
def frame_predicate_distribution(collections,
xlsx_path,
output_folder,
json_path,
start_from_scratch=False,
verbose=0):
"""extracts a d... | 667d5f12e3ac36862c9033757b97de7130f72d16 | 3,606,966 |
import struct
import hmac
import hashlib
import base64
def to_wire(message, secret=None):
"""Convert a message from dictionary format to wire format
If the secret is not None, it will be used to sign the message.
"""
# Ensure there's no _auth section in the message
message.pop('_auth', None)
... | 1e6e38d80a311b38c4d2b9abbc0289f961498317 | 3,606,967 |
def clip_raster (in_raster, out_raster, extent, datatpye=gdal.GDT_Float32):
"""Clip a raster to extent
Parameters:
in_raster: path
input raster file
out_raster: path
output raster file
extent: tuple
(minX, maxY, maxX, minY)
"""
tiff = gdal.Translate(
out... | 8b4dab0c624659ade9222a21abed590ea7f616bf | 3,606,968 |
from django.http import HttpResponse
from django.utils import simplejson
from .decorators import _JSON_MIME_TYPE
def render_to_json_response(data, **kwargs):
""" Render data as JSON.
:param encoder: custom `JSONEncoder` subclass to serialize additional
types. This argument is an alias to `cls... | cad946b19353b82a05c6535361e354e8035336ce | 3,606,969 |
import torch
def data_loader(pcap_file, statistic_file, label_file, trimed_file_len, batch_size=256, workers=1, pin_memory=True):
"""读取处理好的 npy 文件, 并返回 pytorch 训练使用的 dataloader 数据
Args:
pcap_file (str): pcap 文件转换得到的 npy 文件的路径
statistic_file (str): 统计特征对应的 npy 文件路径
label_file (str): 上面... | 56e240031bcd7f0938b8dd5a0abd859582f44963 | 3,606,971 |
def TriclosestPoint(TRI, P):
"""[Calculate the distance of a given point P from a triangle TRI.]
Args:
TRI ([[P1;P2;P3]]): [The triangle is a matrix
# formed by three rows of points TRI = [P1;P2;P3] each of size 1x3]
P ([P0 = [0.5 -0.3 0.5]]): [Point P is a row vector of the form 1x3]
"""... | ea2c77fd470f76193f21834a1b6b76dd71f25875 | 3,606,972 |
def sample_labels(labels, num_samples, label_value, ignore_label=-1):
"""sample N labels with label value = sample_labels
Args:
labels(Tensor): shape of label is (N,)
num_samples(int):
label_value(int):
Returns:
label(Tensor): label after sampling
"""
assert labels.... | 923a762162a8136845abf7e41f6737b8aa06bd99 | 3,606,973 |
def get_settings() -> Settings:
"""get_settings() -> ahkpy.Settings
Return the current settings for the active thread.
"""
try:
return _current_settings.get()
except LookupError:
settings = default_settings.copy()
_current_settings.set(settings)
return settings | 985ec62c5bfdcfcb848a96cf49b9eef1b2c4176c | 3,606,974 |
def from_note_representation(
array: ndarray,
resolution: int = DEFAULT_RESOLUTION,
program: int = 0,
is_drum: bool = False,
use_start_end: bool = False,
encode_velocity: bool = True,
default_velocity: int = 64,
) -> Music:
"""Decode note-based representation into a Music object.
Pa... | 5c2e89caece939130a21625b5d9dbee268efa3c1 | 3,606,975 |
def string2number(i):
""" Convert a string to a number
Input: string (big-endian)
Output: long or integer
"""
return int(i.encode('hex'),16) | ced0537bea856822da630b565cfdeef2c22d1d8a | 3,606,976 |
def j(x, w, y, alpha=0):
"""The loss function, the aim of LogisticRegression is to minimize it. """
scores = h(x, w)
log_score = np.log(scores)
log_one_min_h = np.log(1 - scores)
log_score[y == 0] = 0
log_one_min_h[y == 1] = 0
trimed_biases = bias_to_0(w)
data_loss = (-np.sum(log_score +... | 7d05f1082eea000b268119ebf5cf35e4c5e94467 | 3,606,978 |
def _process_group(group, window):
"""Find the patterns from given group.
Args:
group: Group of note pairs to find the patterns from.
window: the number of notes there can be in between
consecutive notes of a pattern. Notes played at the
same time are counted as "one note".
Returns:
The patterns in the... | 33ffa3b9384378d3ce374a95dd13527b5d37f802 | 3,606,979 |
def get_reference_data(p):
"""Summarise the bibliographic data of an article from an ADS query
Returns dict of 'author' (list of strings), 'title' (string), and
'ref' (string giving journal, first page, and year).
"""
data = {}
try:
data['author'] = p.author
except:
data['author'] =... | f8f792d15bade96881e87c3a7e1047dddc125d15 | 3,606,980 |
def generate_junit_result(logdata):
""" Generate results in JUnit format for Jenkins from the log data written by application
<testsuite>
<testcase classname="foo" name="ASuccessfulTest"/>
<testcase classname="foo" name="AnotherSuccessfulTest"/>
<testcase classname="foo" name="AFailingT... | d2ef152399f08165e923a17575db952581a5209b | 3,606,983 |
def getGoldTradePartners(playerOrID):
"""
Returns a list of CyPlayers that can trade gold with <player>.
"""
return getTradePartnersByTeam(playerOrID, lambda fromTeam, toTeam: fromTeam.isGoldTrading() or toTeam.isGoldTrading()) | 8ea901bbeb4297972222b5602aec012326f4907b | 3,606,986 |
from functools import reduce
def build_stream_function(*funcs):
"""
构建流处理函数 函数参数更严格 只接受一个参数 d 字典值
函数执行的顺序是从左到右
:param funcs:
:return:
"""
return reduce(lambda f, g: lambda d: g(f(d)), funcs) | 0f09c3f39e8a469f60748a60da5013cfb2cc3758 | 3,606,987 |
def is_url(path):
"""Test if path represents a valid URL string.
:param str path: Path to file.
:return: True if path is valid url string, False otherwise.
:rtype: :py:obj:`True` or :py:obj:`False`
"""
try:
parse_result = urlparse(path)
return all((parse_result.scheme, parse_res... | bf3d5959a376d4e8242a602d3d5ac7cc1f00dee7 | 3,606,988 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.