content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def getWarrenData(dF, outSnowVar, outDensityVar='None'):
"""
Assign Warren1999 snow dept/density climatology to dataframe
Added
Args:
dF (data frame): Pandas dataframe
outSnowVar (string): name of Warren snow depth variable
outDensityVar (string): name of Warren snow density v... | ac7531faeb75ceb88646bf11f0048b7fd5ea96c5 | 3,607,108 |
def detections_boxes(detections):
"""
Converts center x, center y, width and height values to coordinates of top left and bottom right points.
:param detections: outputs of YOLO v3 detector of shape (?, 10647, (num_classes + 5))
:return: converted detections of same shape as input
"""
# center_... | 161c64b2d30e68db3c8227eca6e20bf5046a4a3a | 3,607,109 |
def indefinite_article(word, gender=MALE):
""" Returns the indefinite article (un/una/unos/unas) for a given word.
"""
if MASCULINE in gender:
return PLURAL in gender and "unos" or "un"
return PLURAL in gender and "unas" or "una" | 80c8c566f4de58f647ec7ba864e1de4c8eb842e5 | 3,607,110 |
def conv_repoids_to_list(repo_ids):
"""
Convert repo ids seperated by "\n" to list.
"""
if not repo_ids:
return []
repoid_list = []
for repo_id in repo_ids.split("\n"):
if repo_id == '':
continue
repoid_list.append(repo_id)
return repoid_list | 6a76a8ae4f565ac27839478f068f9e9a13276263 | 3,607,111 |
def truncate_seq_pair(tokens_a, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequ... | c2d1772b0c727071dc8cb13a5313860278ece294 | 3,607,112 |
import itertools
def _select_iterables(elements):
"""expand tables into individual columns in the
given list of column expressions.
"""
return itertools.chain.from_iterable(
[c._select_iterable for c in elements]
) | 12ecce590ab7d599e62b1105f7a405263cb7022c | 3,607,113 |
def create_grammar(string):
"""Creates a grammar from a string"""
return walk(grammar.parse(string, start="grammar_start")[0]) | 82663f420e8145ae00aa965468f86156545860bd | 3,607,114 |
def _run_on_proxy(role=None, host=None):
"""
Decorator that creates the actual decorator to route tasks through proxy.
This is necessary in order to be able to pass parameters to the actual decorator.
Usage:
@hosts(env.proxy_server)
@_run_on_proxy([host='somehost'|role='somerole'])
... | 962a6c9039e1db86f883d9e4f127c22424e0349d | 3,607,115 |
from typing import Union
from typing import Tuple
from typing import Optional
def parse_constrained_string_or_bytes(
field: Union[ConstrainedStr, ConstrainedBytes]
) -> Tuple[Optional[int], Optional[int], bool]:
"""Parses and validates the given field"""
lower_case = field.to_lower
min_length = field.... | df3e344fac8f68e0a06d7f0e3f55a6f6f81edb1e | 3,607,116 |
def roundAllFloats(lista, l):
"""Round to 3 decimals"""
nlista = []
for ii in lista:
tt = ii[:l + 1]
for jj in ii[l + 1:]:
if jj > 100.0:
jj = round(jj, -1)
nn = round(jj, 3)
tt.append(nn)
nlista.append(tt)
return nlista | 47707449128215bc2288fc1b033f05a74eef51f4 | 3,607,118 |
def read_clustal_alignment(filename):
""" Read in the alignment stored in the CLUSTAL file, filename. Return
two lists: the names and sequences. """
names = []
alignment = []
f = open(filename)
for line in f:
if line[-1].upper() not in iupac_alphabet:
line = line[:-1]
if... | 456845a7091430adc5aa3f0e09b5a16d78b5f38a | 3,607,119 |
def rename(term):
"""
Re-format feature terms after they've been formated by the vectorizer.
Parameters:
----------
term : str
Mutilated term in string format.
Returns
-------
str
The normalised term.
"""
term = term.upper()
if 'IPR' in term:
return ... | ec7f963ea37a0057f9a5b92ed3f4d9fc37167d17 | 3,607,120 |
def engine_status(engine_name: str):
"""Returns the status of a given engine
"""
if engine_name in template_db.engines:
if template_db.engines[engine_name].is_up():
return 'OK', 200
else:
return 'KO', 402
else:
return 'KO', 404 | b7159db0de9b7ccd84aed09fcd63bd77682deb2c | 3,607,121 |
def _get_pos_from_key(key, char):
""" Returns a list of the indices where char appears in the string.
Pass in a list of only the pulses no residuals (ie capital letters)
+1 is because the pulses are index from 1.
"""
return [i+1 for i, c in enumerate(key) if c == char] | 6870266a92db59bf3f5dd9f69211e13297321e7c | 3,607,123 |
from typing import Optional
from typing import List
def layout_rects(base_rect: Rect, cols: Optional[int]=None, rows: Optional[int]=None, item_width: Optional[int]=None, item_height: Optional[int]=None, padding: Optional[int]=None, padding_top: int=0, padding_bottom: int=0, padding_left: int=0, padding_right: int=0, ... | 18d0ba61fc19c362548bb89be657118f2627319e | 3,607,124 |
from datetime import datetime
def _datetime2timestamp(datetime_str: str) -> int:
"""Convert UTC datetime string to timestamp."""
converted_time = datetime.strptime(datetime_str, "%Y-%m-%dT%H:%M:%SZ")
timestamp = converted_time.replace(tzinfo=timezone.utc).timestamp()
return int(timestamp) | 0475544baab406d7583633bf20f71ca5dad6d3f9 | 3,607,125 |
def to_litho_class_num(lithology, kv):
"""Get a numeric code for a lithology, or NaN if not in the dictionary mapping lithologies to numeric code
Args:
lithology (str): Name of the lithology
kv (dict[str,float]): lithologies keywords to numeric code
"""
if lithol... | 601b1fc65c113fa4d3f6d97cc3a0eb101b3d997f | 3,607,127 |
def sandwiched_Renyi_rel_ent(rho, sigma, alpha):
"""
Computes the sandwiched Renyi relative entropy for either 0<=alpha<=1,
or for alpha>=1 provided that supp(rho) is contained in supp(sigma).
"""
sigma_a = np.matrix(fractional_matrix_power(sigma, (1.0 - alpha) / (2 * alpha)))
Q = np.real(Tr(f... | a28f8d96886a7ba95c0ec78007cbdb0f09bd4a1d | 3,607,128 |
import array
import struct
def melt(
df,
id_vars, value_vars,
var_name, value_name):
"""Convert :class:`DataFrame` from wide to long format."""
# Create array<struct<variable: str, value: ...>>
_vars_and_vals = array(*(
struct(lit(c).alias(var_name), col(c).alias(value_nam... | 3c17e2673a33bf09586a1828080c9cd6b4910afb | 3,607,129 |
def bpstr(ts, accum):
"""Make a string representation of this breakpoint and accumulation"""
return "%02i.%02i %6.2f" % (ts.hour, ts.minute / 60.0 * 100.0, accum) | bd2ae124b5ef094ea7927124b86f100749bf0405 | 3,607,130 |
def __unique_prefix(values):
"""
Obtain shortest unique prefix for all values in list by means of sorting
:param values: list of string values
:return: list
"""
# Instantiate output list
output = {}
# Sort array
values = sorted(values)
# Save first character in first string as a... | 2a8e5867ef986b04a6e1e6acf89c2a16ff6deacd | 3,607,131 |
def dist_soergel(datamtx, strict=True):
""" Calculate soergel distance between rows of a matrix
see for example Evaluation of Distance Metrics..., Fechner 2004
dist(a,b) = sum on i( abs(a_i - b_i) ) / sum on i( max(a_i, b_i) )
returns: a symmetric distance matrix, numrows X numrows
* comparisons a... | 21ce9ee3fedca34ff67f01a7bbfbfa319136e71b | 3,607,132 |
def sigma_lambda_to_Sigma(sigma, l, eps2=0):
"""
Parameters
----------
Sigma: shape (m, k)
Returns
-------
sigma: shape (m, k)
l: shape (m, k)
l-parameter ready for gradient computation
"""
m = len(l)
return sigma ** 2 / (m * (l ** 2 + eps2)) | 808b970802938cd3f30187bea993cfe1ae1933c5 | 3,607,133 |
import torch
def preprocessing(image, expected_size=224, pad_value=0):
"""
Pre-processing steps to use pre-trained model on images
"""
imgnet_mean = np.array([0.485, 0.456, 0.406])[None, None, :]
imgnet_std = np.array([0.229, 0.224, 0.225])[None, None, :]
image, pad_up, pad_left, h_new, w_n... | 57d5dd14cbaa7bf08de3f34b75e48419e3fb8d1c | 3,607,134 |
async def get_zone(name=None,resource_group_name=None,opts=None):
"""
Use this data source to access information about an existing DNS Zone.
"""
__args__ = dict()
__args__['name'] = name
__args__['resourceGroupName'] = resource_group_name
__ret__ = await pulumi.runtime.invoke('azure:dns/get... | a7d4e1c9ff1775f2e1ab8c51eaa9a954135ae218 | 3,607,136 |
import numpy
def one_body_basis_change(one_body_tensor, rotation_matrix):
"""Change the basis of an 1-body interaction tensor such as the 1-RDM.
M' = R^T.M.R where R is the rotation matrix, M is the 1-body tensor
and M' is the transformed 1-body tensor.
Args:
one_body_tensor: A square numpy ... | 6082a7ca5620dd7e00a545e86867d85b254b4304 | 3,607,137 |
import math
def CalculateDistanceT92(info):
"""
P,Q: transitions, transversions frequencies
q: G+C content
d = -2q(1 - q)loge(1 - P/[2q(1 - q)] - Q) -[1 -2q(1 -q)]loge(1 - 2Q)/2,(4.18)
V(d) = [c12P + c32Q - (c1P + c3Q)2]/n,(4.19)
where c1 = 1/(1 - P/[2q(1 - q)] - Q), c2 = 1/(1 - 2Q), c3 = 2q(... | 90242b905283785524d6b96682abc854346b2d11 | 3,607,138 |
import requests
from datetime import datetime, timedelta
def update_data_covid_states(cursor):
"""
Summary: Adds in the table "covid_states" daily data of Covid to home Brazilian state.
* Ir first sets the API base URL and make a request
* Third creates a loop that adds the data returned from JSON re... | 6266390dd79275e1428ee9d432952d58efe8c743 | 3,607,140 |
from typing import List
from typing import Union
def convert(raw_data: List[str]) -> List[Union[int, float]]:
"""Helper method to convert numerical strings in their appropriate type"""
return [numerical_conversion(value.strip()) for value in raw_data] | 3be0d3a938aaeced172fcb043e42758324a3d968 | 3,607,141 |
def nnPredict(w1, w2, data):
"""% nnPredict predicts the label of data given the parameter w1, w2 of Neural
% Network.
% Input:
% w1: matrix of weights of connections from input layer to hidden layers.
% w1(i, j) represents the weight of connection from unit i in input
% layer to unit ... | f88bc6a0b4edd1316ce0b4cc211e3655a270afe2 | 3,607,142 |
def physical_to_comoving(dist_physical, redshift):
"""
Converts a physical distance to a comoving distance.
This assume a Flat Lambda CDM Cosmology.
dist_comoving = dist_physical / scale_factor
Parameters
----------
dist_physical: array-like
redshift:
Returns
-------
dis... | 1afb9367b6f37c21eabe620bb86c775d33bac001 | 3,607,143 |
def dup_to_dict(f, K=None, zero=False):
"""
Convert ``K[x]`` polynomial to a ``dict``.
Examples
========
>>> from sympy.polys.densebasic import dup_to_dict
>>> dup_to_dict([1, 0, 5, 0, 7])
{(0,): 7, (2,): 5, (4,): 1}
>>> dup_to_dict([])
{}
"""
if not f and zero:
r... | c67684ea9133ffc3d42267a117534819410113ab | 3,607,145 |
import torch
def sparse_softmax_cross_entropy_with_logits_pytorch(logits, labels):
"""
# onehot
labels = labels.squeeze().long()
num_classes = logits.shape[1]
labels_onehot = torch.zeros(labels.shape[0], num_classes, device=labels.device).scatter_(1, labels.view(-1, 1), 1)
"""
num_classes... | ac77252aa6deec987238f7f3e22368882f4464b4 | 3,607,146 |
def create_outcubes(metric_dict, atts, units, time_coord):
"""Create an iris cube for each metric."""
cube_list = []
for hemisphere, data in metric_dict.items():
standard_name = 'pe_amplitude_%s' %(hemisphere)
long_name = 'pe amplitude %s' %(hemisphere)
var_name = 'pe_amp_%s' %(h... | d84f565d727cb24af467b0408e31d1890e5f58d4 | 3,607,147 |
def linear_warmup_lr(current_step, warmup_steps, base_lr, init_lr):
"""Linear learning rate"""
lr_inc = (float(base_lr) - float(init_lr)) / float(warmup_steps)
lr = float(init_lr) + lr_inc * current_step
return lr | 0ea43c8cf815d25d8caf4d3e5ee8f0f027c5cd41 | 3,607,148 |
import pickle
def unpickle(filename):
"""
Parse CIFAR10 data.
Return a dict containing {data, filenames, labels, batch_label}
"""
with open(filename, 'rb') as fo:
data = pickle.load(fo, encoding='bytes')
return data | 48cb766df6ffc0e448d1c4937a5097bae83c8b78 | 3,607,149 |
def __compute_sf(fit_type,
frequency,
log_luminosity,
dlog_luminosity,
dof,
break_frequency,
injection_index,
remnant_ratio,
b_field=None,
redshift=None):
"""
"""
... | ca256a7bbf6130f97fcb885290e788175a0ca940 | 3,607,150 |
from datetime import datetime
def utc_this_hour() -> datetime.datetime:
"""Get offset-aware beginning of the current hour in the utc time zone."""
now = datetime.datetime.now(datetime.timezone.utc)
return datetime.datetime(year=now.year,
month=now.month,
... | 5380f7f6b25ded7f52f2e6254c3002f748cae406 | 3,607,153 |
def getHeadangle(axisP,axisD):
"""Head angle calculation function.
This function takes in two axis and returns three angles.
and It uses the inverse Euler rotation matrix in YXZ order.
the output shows the angle in degrees.
Parameters
----------
axisP : list
Shows the unit ... | a7ea561c2223c37ed37cec8f2268eb6ea36db0f3 | 3,607,154 |
def getCitiesData():
"""
This function gets the data from the file and formats it in this format:
{ format }: 'City/Country'
"""
print('(Info): Select the name of the file you will work with.')
print('(Notice): Example the file name `test.txt`.')
fileName = input('> ')
if fileName == 'exit':
exit()
try... | 8385e5dd25aab13b279680062e4862e0dbcc81df | 3,607,155 |
def func_str2hex(*args):
"""字符串 -> Hex"""
return func_byte2hex(func_str2byte(*args)) | e314954344c8ed531c5a57b8f53dfce47c24b011 | 3,607,156 |
def oadrCreatedPartyRegistration(response_code, response_description, response_requestId, registrationID, venID, vtnID,
profiles, poll_freq, specific_info, extensions):
"""
Generates the oadrCreatedPartiRegistration with the vtnInfo
:param response_code:
:param response_... | 44b774d1bfafc3cab312bc4fbdabc1ad14107c01 | 3,607,157 |
def _get_docs_to_update(update_set, leaf_count, leaf_docs, remove_idx, da):
"""
Return a set of document indices to be udpated for this tree.
Return
- Set of training indices.
Note
-Parallelizable method.
"""
# update only the remove example
if update_set == 0:
res... | 03480413a4a93e68c24942329f3ac3af0ea6d4f2 | 3,607,158 |
def get_prediction_vs_actual_data(y_true, y_pred, outlier_threshold=None):
"""Combines y_true and y_pred into a single dataframe and adds a column for outliers. Used in `graph_prediction_vs_actual()`.
Arguments:
y_true (pd.Series, ww.DataColumn, or np.ndarray): The real target values of the data
... | c1e47f82f4bfaea2c7bb44d62e97a4f37ffbe9d4 | 3,607,159 |
def h5base():
"""Fixture for forming basic HDF5Base object"""
return HDF5Base(FILE_VERSION_MAJOR, FILE_VERSION_MINOR) | e7a9567d5fa3aee6f401668bfea6b3fbf97c9c5e | 3,607,160 |
def mark(name: str, episode: int) -> ControllerResult:
"""
:param name: name of the bangumi you want to mark
:param episode: bangumi episode you want to mark
"""
result = {}
try:
followed_obj = Followed.get(bangumi_name=name)
except Followed.DoesNotExist:
runner = ScriptRunn... | 1b61271f813efaaf7bd0fff0e902cfddc0f1815e | 3,607,161 |
import json
def get_object_manifest(api_root, collection_id):
"""
Defines TAXII API - Collections:
Get Object Manifests section (5.3) `here <https://docs.oasis-open.org/cti/taxii/v2.1/cs01/taxii-v2.1-cs01.html#_Toc31107537>`__
Args:
api_root (str): the base URL of the API Root
collect... | 4bd65246a2c75f15254f592390ed10ed82d9e599 | 3,607,162 |
import typing
import base64
def decode_inline_pronunciation(
word: str,
) -> typing.Optional[typing.Tuple[InlinePronunciationType, str]]:
"""Return encoded inline phonemes from word encoded as __phonemes_<base32-phonemes>__"""
match = ENCODED_PHONEMES_PATTERN.match(word)
if match:
phonemes = b... | 855b487c1e9e3ed8a1341aee2f2a26c5b7e4f518 | 3,607,163 |
def get_axes_list(self):
"""Get the value of variables stored in Solution.
Parameters
----------
self : SolutionMat
an SolutionMat object
Returns
-------
axis_dict: list
a list of axis names containing axis sizes
"""
return self.axis_name, self.axis_size | 812de306267af3daf6713bfdff8ecef05c1a5a0e | 3,607,164 |
def syntactic_roles_to_semantic_match(syntactical_sentence,
voice_is_active=True):
"""
Selects which elements of the syntactical sentence must match the
verb, agent and patient, respectively.
Args:
syntactical_sentence: a list of tuples (symbol, attributes)
... | 84ade39bf48bcc0b065680ac2094da76bde0a5d5 | 3,607,165 |
from typing import Optional
from typing import Callable
from typing import Any
from typing import Mapping
def get_postprocess_fn(
task_name: str,
task_path: str,
subtask_name: Optional[str] = None,
bigbench_task_type: BigBenchTaskType = BigBenchTaskType.GENERATIVE,
json_util: json_utils.JsonUtils ... | 038b191a587217e6a625d4eafbc49ded2a2ede7e | 3,607,167 |
def test_iter_batch(
dataset,
dataloader,
batch_size=1,
shuffle=False,
drop_last=False
):
"""Test DataLoader class"""
if drop_last:
test = IterBatchTest(
dataloader,
batch_size=batch_size,
len_=len(dataset) // batch_size,
... | f85b8ae8d95ef81343862c377d76450aebb16ada | 3,607,170 |
def no_data_full_shape_func(attrs, inputs, out_ndims):
"""
Shape func for zeros and ones.
"""
if len(inputs) == 0:
return [_convert_shape(convert(attrs.shape))]
return [_full_shape_func(inputs[0])] | d78aa710fb6e8cf0c43de0cf73b85d5d01bb0bdb | 3,607,172 |
def get_tool_study_max_java_heap_size():
"""
Some of the tools allow you to specify the java heap size. We want to ensure all of the tools
use the same heap size (if they allow it to be specified), so the run_analysis scripts
should use this method to retrieve the size
"""
return "4096m" | 8d180d76052bacdbc7350cc2efacc0a55acdb29e | 3,607,173 |
def schedule_for(current_track, task, client_index):
"""
Calculates a client's schedule for a given task.
:param current_track: The current track.
:param task: The task that should be executed.
:param client_index: The current client index. Must be in the range [0, `task.clients').
:return: A ... | f2d096c92f639ae13bdf9cfac02deed74c98cc18 | 3,607,174 |
def roi_align_nchw(data, rois, pooled_size, spatial_scale, sample_ratio=-1):
"""ROI align operator in NCHW layout.
Parameters
----------
data : tvm.Tensor
4-D with shape [batch, channel, height, width]
rois : tvm.Tensor
2-D with shape [num_roi, 5]. The last dimension should be in f... | 6e83f10722d6d7779dd6792407ef4399f256fb66 | 3,607,175 |
def CCNOT(control1: QubitDesignator, control2: QubitDesignator, target: QubitDesignator) -> Gate:
"""Produces a doubly-controlled NOT gate::
CCNOT = [[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0],
... | 8f6c56fae1b4f4044818f174ce008bdf993d7b75 | 3,607,176 |
import torch
def evaluateCNN(df, artifacts, device=torch.device("cpu")):
"""
Perform model evaluation on unseen data
:param df: dataset
:param artifacts: run artifacts to evaluate
:param device: torch device
:return y_true, y_pred, performance
"""
# Get artifacts (load model, encoder a... | abdbb86764cab0c9aef14e37c38a5f8d07eb0198 | 3,607,177 |
def _distance(n, m, mesh):
"""
Calculate the distance (in number of cells) between cells n and m in mesh.
"""
ni, nj, nk = _index2ijk(n, mesh)
mi, mj, mk = _index2ijk(m, mesh)
return sqrt((ni - mi) ** 2 + (nj - mj) ** 2 + (nk - mk) ** 2) | 5f71b37e0eb5723e9fc203f82b83b33f3b62692c | 3,607,178 |
def generate_random_phase_field(diffracted_pattern):
"""
Initiate random phase.
Parameters
----------
diffracted_pattern : array
diffraction pattern from experiments
Returns
-------
sample_obj : array
sample information with phase
"""
pha_tmp = np.random.uniform... | 0dd869e74aa2d11e1e9c58bba5dfb06a2b753fad | 3,607,180 |
def is_holiday(date):
"""
判断是否为节假日,放假的日子
"""
return date in cs.holidays | 8686b8e0c2a475354b4bde809c00dfa0a8b4c956 | 3,607,182 |
def cbf(dic,data,last=10,reg=False,slice=slice(None)):
"""
Constant Baseline correction
Parameters ref and slice should be python slice objects if explicit
correction is desired (recall python arrays start at 0 not 1). The
noseq and nodmx parameters are not implemented.
Parameters:
... | 24c9683c2bdf3f038be6e690ccb967376c3226ac | 3,607,183 |
def creation(create_db_instance):
"""Return a CreationStage instance."""
stage = CreationStage(None)
stage.instance = create_db_instance
return stage | 862574e84dd9ce1ad2cc54f1f199905580138e50 | 3,607,184 |
def undo_preemphasis(preemphasized_signal, coeff=0.95):
"""Undo the preemphasis of an input signal. The preemphasised
signal p is computed from the signal s by the relation
p(n) = s(n) - coeff*s(n-1)
with p(0) = s(0). The inverse operation constructs the signal from the
preemphasize... | 11cb93c67672c9b2003d2e7b9eed931dffeffcf5 | 3,607,185 |
def apply_dropout2(computation_graph, variables, drop_prob,
rng=None, seed=None, dropout_mask=None):
"""Support using the same dropout mask at all time steps"""
divisor = (1 - drop_prob)
replacements = []
for var in variables:
if dropout_mask:
var_dropout_mask = d... | 9b7d52f808cd532c96c499fd13724ab6efe036b2 | 3,607,186 |
def shapeprior_head_generator(params):
"""Generator function for shape prior head architecture."""
head_params = params.shapemask_head
return heads.ShapemaskPriorHead(
head_params.num_classes,
head_params.num_downsample_channels,
head_params.mask_crop_size,
head_params.use_category_for_mas... | a62490539e74ee5e4e89a5308501046736c33939 | 3,607,187 |
def utils_sample_from_networks_on_batch(speaker_model, listener_model, target_input, candidates, target_candidate_idx, sampled_target_idx, candidate_idx_set):
"""
All inputs: Just one instance. No bs dimensize.
"""
speaker_message, speaker_probs = speaker_model.sample_from_speaker_policy(target_input)
chosen_targe... | 1f105ab531b4adfa44408ca8b3bbc1d3b6bde7fd | 3,607,188 |
import requests
def is_holiday(day):
"""
判断是否节假日, api 来自百度 apistore: http://apistore.baidu.com/apiworks/servicedetail/1116.html
:param day: 日期, 格式为 '20160404'
:return: bool
"""
params = {'d': day, 'apiserviceid': 1116}
api = 'http://tool.bitefu.net/jiari/'
rep = requests.get(api, para... | fffc20ef2b8d882e3bf03162a9113a61a45e3f8a | 3,607,190 |
def hostile_ship_near(x, y, player, m, cargo):
""" check if hostile ship is in one move away from game_map[x][y] and has less or equal halite """
# m = game map
n = get_c(y - 1)
e = get_c(x + 1)
s = get_c(y + 1)
w = get_c(x - 1)
if (
(m[x][n]["ship"] != player and m[x][n]["ship"]... | dc16208e838d32cde9b335f5bbccc367f35e7c39 | 3,607,191 |
def _calc_pairwise(args):
"""
Helper function to calculate a pairwise alignment.
Args:
args: Tuple of two sequence objects.
Returns:
List [1st sequence id, 2nd sequence id, percentage identity].
"""
seq_i, seq_j = args
ident = 0
matrix = MatrixInfo.blosum62
for a i... | d85d6f25789bfa93faf852a27e25a29d5883546e | 3,607,192 |
import csv
def openCSVfile(filepath, delimiter = ","):
"""
Returns the lists for csv file
"""
with open(filepath,"r") as csvfile:
rows = csv.reader(csvfile,delimiter = delimiter)
return list(rows) | 5d8beda891862281976ec48ea117d3c768a553a6 | 3,607,193 |
def main(global_config, **settings):
"""This function returns a Pyramid WSGI application.
"""
# Initialize Authentication/Authorization
authn_policy = AuthTktAuthenticationPolicy(settings['secret'])
authz_policy = ACLAuthorizationPolicy()
# Configure Pyramid
config = Configurator(settings=se... | 2412595e962b7c1e3c0f428e3a95132fb5147301 | 3,607,194 |
def find_direction(start, end):
"""
Find direction from start to end
"""
if start[0] == end[0]:
if start[1] < end[1]:
return 5
else:
return 1
elif start[1] == end[1]:
if start[0] < end[0]:
return 3
else:
return 7
eli... | ff282de669832159d236cd5fe805b1832b990bb6 | 3,607,195 |
def load_lookup(data):
"""
Load output area lookup.
"""
output = {}
for idx, row in data.iterrows():
output[row['msoa']] = {
'lad': row['lad'],
'region': row['region'],
'population': row['population'],
'area_km2': row['area_km2'],
... | 77e3b88b1d4a270860b4ce328fd1e3d53f3af45a | 3,607,196 |
def adain(net1, net2, epsilon=1e-9, name='in'):
"""use shape NCHW"""
with tf.variable_scope(name):
mu, sigma_sq = tf.nn.moments(net1, [2, 3], keep_dims=True)
normalized = (net1 - mu) / tf.sqrt(sigma_sq + epsilon)
shift, scale = tf.nn.moments(net2, [2, 3], keep_dims=True)
normali... | 8dabc5be35751994b2de428bb00cb8d16c334eb0 | 3,607,197 |
def day_date(src):
"""
Returns the date string for the given day.
:param src:
:return:
"""
return src.xpath('./h4[1]')[0] | f71343c8f63941e0ab4045e2d94febf4aaebfa5b | 3,607,198 |
from typing import Dict
from typing import Hashable
from typing import Set
from typing import List
from typing import Tuple
def set_closure(
sets: Dict[Hashable, Set[Hashable]]
) -> Dict[Hashable, Set[Hashable]]:
"""Computes the closure for each element of a antisymmetric relation.
The relatio... | fdd498ae0d4cd0bb0a0067cd8a6c61bd6c5d8ef7 | 3,607,199 |
def instancemethod(f):
"""Decorator to indicate that the method is a method of an instance rather than
a model."""
@wraps(f)
def f_wrapped(self, *args, **kw_args):
if not self.instantiated:
# Attempt to automatically instantiate.
self = self()
return f(self, *arg... | a0f5e6eb65df69809d02e217e0f37cbc81734c51 | 3,607,200 |
def _principal_from_token(token):
"""Determine a principal from a JWT
Args:
token: The JWT
Returns:
Brewtils principal if JWT is valid, None otherwise
"""
try:
decoded = jwt.decode(
token,
key=brew_view.config.auth.token.secret,
algorithm... | df908c5d5186f035c8e2fc26bcf1ef1eeccb4f17 | 3,607,201 |
def email_attendees(request, slug):
"""Send email to event attendees."""
event = get_object_or_404(Event, slug=slug)
attendees = event.attendees.all()
if request.method == 'POST':
email_form = EmailUsersForm(attendees, request.POST)
if email_form.is_valid():
statsd.incr('eve... | 4c7731e619aba6952bd2767a52ab47dc82ebe0ec | 3,607,202 |
from typing import Tuple
from typing import Union
def json_types(max_size: int = 5, *, max_leaves: int = 25) -> st.SearchStrategy:
"""
Return a recursive stategie for generating JSON type-hints inputs
Arguments:
max_size: maximum size of the lists and dicts created
max_leaves: maximum num... | f6108973a7cb8818a390a3ba4ac1f08b6cc83390 | 3,607,203 |
def one(n = 10):
"""
a strange function with an ambiguous name
Parameters
----------
:param n: int
the number of points to test
"""
sum = 0.0
for i in range(n):
denom = 1.0
sum += 1/n
return sum | 2b8ce5aa198ad1139165fbabf02b89f2d9f7cf73 | 3,607,204 |
def SInverse(box, output):
"""Apply S-box number 'box' in reverse to 4-bit bitstring 'output' and
return a 4-bit bitstring (the input) as the result."""
return SBoxBitstringInverse[box%8][output] | ad33cbb10ce7db13710d3beb62e97ac063e45f84 | 3,607,205 |
from typing import Dict
def exposure(population: np.ndarray = None) -> Dict[int, int]:
"""Returns dict of index: count of individuals
Args:
population (np.ndarray): the population
Returns:
Dict[int, int]: key is index, value is count of lineup
Examples:
>>> fittest_populatio... | 55d112b049efdb9982d26dbd92d423e6adfb12d7 | 3,607,207 |
def allcorner(samples, labels, axes, weights=None, span=None,
smooth=0.02, color="grey", qcolor=None, show_titles=False,
hist_kwargs={"alpha": 0.5, "histtype": "stepfilled"},
hist2d_kwargs={}, max_n_ticks=3,
label_kwargs={"fontsize": 12}, tick_kwargs={"labelsize":... | 885f14994508e822892d139874da8582b1f7bee1 | 3,607,208 |
def PersistentPickler(persistent_id, *args, **kwargs):
"""
Returns a :class:`Pickler` that will use the given ``persistent_id``
to get persistent IDs. The remainder of the arguments are passed to the
Pickler itself.
This covers the differences between Python 2 and 3 and PyPy/zodbpickle.
"""
... | 114a6a6454005336ecdad89b2b26605fc58b4e3e | 3,607,209 |
def isFactGroup(arg: str) -> bool:
"""Function to determine whether a string is a registered fact group
"""
if arg in RegisteredFactGroups.keys():
return True
return False | 2a6511d25aa8c6f95ba4f92362cb14cb36a8c20d | 3,607,210 |
def infection_rate_asymptomatic_self_30():
"""
Real Name: b'infection rate asymptomatic self 30'
Original Eqn: b'Infected asymptomatic 30*Susceptible 30*contact infectivity asymptomatic self 30*(social distancing policy SWITCH self 30\\\\ *social distancing policy 30+(1-social distancing policy SWITCH self ... | 9c837aac9d5b01d226d0615b38e89d39cfba7be6 | 3,607,211 |
from typing import Tuple
import torch
from typing import List
def long_tensor_2d(shape: Tuple[int, int], fill_value: int = 0) -> torch.Tensor:
"""Return a new 2d torch.LongTensor with size according to shape.
The values of this tensor will be fill_value."""
outer = torch.jit.annotate(List[List[int]], [])
... | c1aaeb01058b9153c31e911f31eae6217f03eb64 | 3,607,212 |
def five_twos_simple():
"""Five Twos going only left to right, operations: +-*/^"""
global N
N = []
global S
S = []
def five_twos_inner(val,sq,depth):
if depth == 5:
if int(val) == val and val >= 0:
N.append(int(val))
S.appen... | 38aeea1d325f7db6975d13411c3958bbe4ee6d1c | 3,607,213 |
def _pad_digits(text: str) -> str:
"""A str method with hacks to support better lexicographic ordering.
The output strings are not intended to be human readable.
The returned string will have digit-runs zero-padded up to at least 8
digits. That way, instead of 'a10' coming before 'a2', 'a000010' will ... | 7e842669747919a3bbc9fd40e45a4bfc7641cc3a | 3,607,214 |
from typing import List
def get_missing_settings(settings_class) -> List[str]:
"""Used to validate required settings.
Verifies that all attributes which don't start with ``_`` and aren't named
in ``_optional_settings`` are not set to None.
Args:
settings_class: The global settings class to v... | efbb2dc3078fc5221e8ce327b078d42eff167d65 | 3,607,215 |
def generate_coverage_config(args): # type: (TestConfig) -> str
"""Generate code coverage configuration for tests."""
if data_context().content.collection:
coverage_config = generate_collection_coverage_config(args)
else:
coverage_config = generate_ansible_coverage_config()
return cove... | 276058105dfae112e5f8908fbd297ae8203909df | 3,607,216 |
def _check_equal_list(iterator):
""" Check that all elements in list are equal """
return len(set(iterator)) <= 1 | 94bd94a203819965d95105e7f978ecb496ce97bc | 3,607,217 |
import re
def error_052_category_in_article(text):
"""Fix all wrong categories and return (new_text, fixed_errors_count) tuple."""
ignore_filter = re.compile(r"""(
<noinclude>.*?</noinclude>|
<onlyinclude>.*?</onlyinclude>|
<includeonly>.*?</includeonly>
)""", re.I | re.DOTALL | re... | 1d21a2e49b0a3684a54ad0c0d4153fe771b9f4f7 | 3,607,218 |
from typing import Dict
from typing import Any
def format_date_and_target(
df_input: pd.DataFrame,
date_col: str,
target_col: str,
config: Dict[Any, Any],
load_options: Dict[Any, Any],
) -> pd.DataFrame:
"""Formats date and target columns of input dataframe.
Parameters
----------
... | a610da8098f54fda4a17dba000498249056aa7fa | 3,607,220 |
def standard_timeseries_reader(*args, **kwargs):
"""
Wrapper for :any:`standard_time_series_reader`
"""
return standard_time_series_reader(*args, **kwargs) | 254e7a63619a649cd327bc8cf4d0506e45a6e42b | 3,607,222 |
def jam_solver(graph, loads, timeout=None):
""" an ensemble solver for the routing problem.
:param graph network available for routing.
:param loads: dictionary with load id and preferred route. Example:
loads = {1: [1, 2, 3], 2: [3, 2, 1]}
:param timeout: None, float or int timeout in millis... | ddc6cfab546f2c8aa531b1568495d05591580076 | 3,607,223 |
import re
def createCogList(args):
"""Returns an Autovivification of the COGs in the MLTreeMap COG list file, and a list of output text precursors based on the analysis type."""
cog_list = Autovivify()
text_of_analysis_type = Autovivify()
alignment_set = args.reftree
kind_of_cog = ''
# F... | 4c80ed3078af52afe20e44f568cacf06cbcbabd7 | 3,607,225 |
def _load_permissions_from_database(user):
"""Calculate permissions based on DB queries"""
permissions = {}
with benchmark("load_permissions > load default permissions"):
load_default_permissions(permissions)
with benchmark("load_permissions > load bootstrap admins"):
load_bootstrap_admin(user, permi... | e9568d124eb8df73dbfc5d09223639ecca62bb5a | 3,607,226 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.