content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def capitalize_all(line):
"""Amos has a habit of capitalizing the first letter of all words in a statement."""
words = line.split(" ")
words = [word.capitalize() for word in words]
return " ".join(words) | ab2b02bc8df4eb010fb040368724879ac129e5c6 | 3,595,112 |
def createSquare(size):
"""Creates an N x N magic square
In a magic square, every row, column, and diagonal add up to the same number.
@param size The size of the magic square
@return A boolean representing if the square was created or not
"""
# The size must be odd
if size % ... | 266a9d632989fd2e65521816ad64d1e7bc81a212 | 3,595,113 |
from io import StringIO
def _():
"""
Generate qrcode used for login with token
"""
new = bottle.request.query.new
username = bottle.request.query.user
url = bottle.request.query.url
if username:
with MyS() as session:
obuser = session.query(Users).filter(Users.name ... | 12581233ba9c474cc4084d4f41a96b05f12c098b | 3,595,114 |
def _python2_dct_keys_to_unicode(data):
"""
Python 2 stores object __dict__ entries as bytes, not unicode, correct it
here. Python 2 can deal with both, Python 3 expects unicode.
"""
if isinstance(data, tuple):
return tuple(_python2_dct_keys_to_unicode(x) for x in data)
elif isinstance(d... | 868e2107b45a95d149183e230d33a4c47719ddcc | 3,595,115 |
def _add_scaled_colorbar(plot, aspect=20, pad_fraction=0.5, **kwargs):
"""Adds scaled colorbar to existing plot."""
divider = axes_grid1.make_axes_locatable(plot.axes)
width = axes_grid1.axes_size.AxesY(plot.axes, aspect=1. / aspect)
pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
current_a... | 0aecd6887187a7983045e1cd9cb2fc6074bbd8cb | 3,595,117 |
import re
def is_hash(text):
"""
>>> is_hash(sha256(b'blode'))
True
"""
return bool(re.match(r'^[0-9a-f]{64}$', text)) | 23d821357a794dadc86a9becad7d0da709c05b1e | 3,595,118 |
import yaml
def read_config_file():
"""
Parse the YAML configuration file into Python types.
Returns:
A Python dictionary representing the YAML.
"""
file = get_config_file()
with open(file) as stream:
yaml_dict = yaml.load(stream.read())
config = ConfigDict(file, yaml_dict... | 002063c1f5ec44ce457c89769f1e0b5603ea1172 | 3,595,119 |
def generalized_dice_loss(output, target, axis=(1, 2, 3), smooth=1e-12):
""" Returns the Generalized Soft Sørensen–Dice loss """
return 1.0 - generalized_dice_coe(output, target, axis=axis, smooth=smooth) | 4895678e9880baeb9280408e27030909ca6a298e | 3,595,120 |
def index():
"""Render the app"""
return render_template('serving_template.html') | 4dedd92d9eaa0b763ba6ce78026567df1ebf58c0 | 3,595,121 |
def _bits_to_bytestring(valuelist):
"""Build a bytestring from a list of bits.
This is used for functioncode 15.
Args:
* valuelist (list of int): 0 or 1
Returns a bytestring.
"""
if not isinstance(valuelist, list):
raise TypeError(
"The input should be a list. " +... | 8f81034369cd9bb72424f450b02dafc6015f93b2 | 3,595,122 |
from typing import Any
from typing import List
from pathlib import Path
async def scalar_coercer(
result: Any,
info: "ResolveInfo",
execution_context: "ExecutionContext",
field_nodes: List["FieldNode"],
path: "Path",
scalar_type: "GraphQLScalar",
) -> Any:
"""
Computes the value of a s... | 870aa44411b241719a6eba477afde053d6a72ea1 | 3,595,123 |
def euler(alpha, u0, step, lowerbound, upperbound):
"""
Implements the forward Euler's method
"""
x = np.linspace(lowerbound, upperbound, (upperbound - lowerbound) / step + 1)
u = np.zeros(len(x))
u[0] = u0
for i in range(len(x) - 1):
du = alpha * u[i]
u[i + 1] = u[i] + du * ... | 06e8ca33fe481a619123493a7e2cb71635078f81 | 3,595,124 |
def user_features(posts):
"""
1. Ratio of users in the conversation
2. Ratio of "directed" comments (those with mentions)
"""
result = []
for post in posts:
#n_comments = get_hostile_indices(post)[0] + 1
n_comments = post['n_comments_observed']
feature_list = []... | e3a7f0dc9c4518f53a252b67261364342849f0e9 | 3,595,125 |
def fault_ack_fault_by_dn(cookie, dn):
""" Auto-generated UCSC XML API Method. """
method = ExternalMethod("FaultAckFaultByDn")
method.cookie = cookie
method.dn = dn
xml_request = method.to_xml(option=WriteXmlOption.DIRTY)
return xml_request | d44456e6c377c356487f6467016b38b039b428f2 | 3,595,126 |
def infer_adj_color_subjects(token, be_verb=False):
"""infer function for adj_case 2~4"""
entity_indices = []
entity_signs = []
if token.children:
for child in token.children:
if (be_verb and child.dep_ == 'nsubj') or (not be_verb and child.dep_ == 'nsubjpass'):
entit... | 4895aaab9a285d2a2b065e82feff086c80621bac | 3,595,127 |
def delete_moderator(request):
"""
删除管理员
"""
if request.method == "POST":
mid = request.GET.get("mid")
if mid is None:
return render_to_response("admin/delete_moderator.html",{'status':1},RequestContext(request))
moderator = apps.admin.auth.get_moderator(mid)
... | daab2a61f7c893708f6799f63e17f7e090d329d3 | 3,595,128 |
def air_massfractionvap(airx):
"""Calculate water vapour mass fraction.
Calculate the mass fraction of water vapour in humid air for the
given dry air mole fraction.
:arg float airx: Dry air mole fraction in mol/mol.
:returns: Mass fraction of water vapour in kg/kg.
:Example:
... | 07df4ad57a8b1e377419840075712455f1472055 | 3,595,129 |
import torch
def tokenize(
seq,
tokenizer,
add_special_tokens=True,
max_length=10,
dynamic_padding=True,
truncation=True,
):
"""
:param seq: sequence of sequences of text
:param tokenizer: bert_tokenizer
:return: torch tensor padded up to length max_length of bert tokens
""... | 8573b19ab395c2957f8a95c80ca9e5514cdbea73 | 3,595,130 |
def get_peakdet_kernel(peak_width, background_width, norm_width=None, kernel_width=None, kernel="lorentzian"):
"""
Get a peak detection kernel.
Return 1D array of length ``2*kernel_width+1`` containing the kernel.
The kernel is a sum of narrow positive peak (with the width `peak_width`) and a broad neg... | d1c34a2367b327be477c8e7d7742e1968f8a0e34 | 3,595,131 |
from scipy.stats import ttest_ind
def bland_altman_metric_plot(metric, ax=None):
"""
Plots a Bland Altmann plot for a evaluation dataframe from the acdc scripts
:param metric: pd.Dataframe
:return: plt.ax
"""
if ax is None:
fig, ax = plt.subplots(figsize=(20, 15))
my_colors = {"LV... | e0bb45b2c1b5113460f1d77b5131c6988f9e1fd3 | 3,595,132 |
def my_sum(x_val: int, y_val: int) -> int:
"""Sum 2 integers.
Args:
x_val (int): integer to sum.
y_val (int): integer to sum.
Returns:
int: result of the summation.
"""
assert isinstance(x_val, int) and isinstance(
y_val, int
), "Input parameters should be integ... | c10001f9ff720ce3d180aaa89af555ac1860ae33 | 3,595,133 |
def entropies(partition_1, partition_2):
""" parameters: partition_1 (list / array) - a partitioning of a dataset
according to some clustering method. Cluster labels are arbitrary.
partition_2 (list / array) - another partitioning of the same dataset.
Labels don't need to match, nor do the number of clu... | 758c1094621d6682068effb3dcb4ae9100ddff14 | 3,595,135 |
from typing import Optional
def is_continuous(
plot_segments: list[PlotSegment]
) -> Optional[tuple[float, float]]:
"""プロットセグメントが連続であるかを検証します。
連続であった場合はNoneを返し、連続でなかった場合は、連続ではない箇所の熱量を返します。
Args:
plot_segments (list[PlotSegment]): プロットセグメントのリスト。
Returns:
Optional[tuple[float, fl... | a3ae629efd9d181379267c68bee9f5c4c66cd384 | 3,595,136 |
def markdown_toclify(input_file, output_file=None, github=False,
back_to_top=False, no_link=False,
no_toc_header=False, spacer=0, placeholder=None,
exclude_h=None):
""" Function to add table of contents to markdown files.
Parameters
-----------
... | e52108a06a81ef00cd34fefc6bca8ff09fa84d81 | 3,595,137 |
import urllib
def url_encoding_to_utf_8(url):
"""url_encoding_to_utf_8(url)"""
url = urllib.parse.unquote(url)
return url | e4ddd7efba0ea67dd72701e797983ac58df38484 | 3,595,138 |
def _stringify_hash(
d,
maxDepth=None,
maxItems=-1,
maxStrlen=-1,
callingDepth=0,
recursionMap=None):
"""
Private implementation for stringify_hash(), with extra parameters for internal use only.
Parameters:
callingDepth (int|-1): keeps track of the c... | e41e2d520661eb754f6fbce5bd55e6ed6fbd68b8 | 3,595,139 |
def primitive_vertices_cube_mpl(width=1,
height=1,
depth=1,
width_segments=1,
height_segments=1,
depth_segments=1,
origin=np.arr... | 8902dc47c26a54929fd97f72232a8f7e4c7d6193 | 3,595,140 |
import time
def forward_pass(images, net, transformer, batch_size=None):
"""
Returns scores for each image as an np.ndarray (nImages x nClasses)
Arguments:
images -- a list of np.ndarrays
net -- a caffe.Net
transformer -- a caffe.io.Transformer
Keyword arguments:
batch_size -- how ma... | a3ebbdce0ffe8b3025d05a16e1d15ff7482ed1dc | 3,595,141 |
from typing import Set
def optimize_year(df, first_model_hour=0, last_model_hour=8759):
"""
Optimize the charge/discharge behavior of a battery storage unit over a
full year. Assume perfect foresight of electricity prices. The battery
has a discharge constraint equal to its storage capacity and round-... | 35310c305dc4ac9c79d1aa2b795e45b6118d64cd | 3,595,143 |
def vit_large_patch32_224_in21k(pretrained=False, progress=True, **kwargs):
"""
Constructs the ViT-Large-patch32-224 ImageNet21k pretrained model.
.. note::
ViT-Large-patch32-224 ImageNet21k pretrained model from `"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale" <https:/... | 315ba1bdec44190c08a30bebe928a7d7b3e9d0bb | 3,595,145 |
def get_activation_fn(name):
"""Returns an activation function."""
act_fns = {
'sigmoid': tf.nn.sigmoid,
'relu': tf.nn.relu,
'leaky_relu': tf.nn.leaky_relu,
'tanh': tf.nn.tanh,
'prelu': prelu,
'linear': None,
}
if name not in act_fns:
raise ValueError('Unsupported activat... | 5f94a662f6877dcbc16445c67ab0d18b77320fc2 | 3,595,146 |
def get_bounding_box(conture, img=None):
""" Calculates the bounding box of a ndarray"""
# get approx, return index
# epsilon = 0.1 * cv2.arcLength(x, True)
# approx_box = cv2.approxPolyDP(x, epsilon, True)
# print 'app box', approx_box # Min [[[ 56 85]] [[318 231]]]
# leftpointX = approx_box[0][0][0]
# print... | b70b89be60b71edc0996125332c3368b58f8c4af | 3,595,147 |
def get_jsonfield_validation_choices(model, field_name, include_values=False):
"""Return the set of legal values for a given JSONField
In this project we are using JSONField to store arrays of values in order
to emulate a many-to-many relationship. In order to enforce that only
legal values are inserte... | cd6e2c9b319132fc36a1adcc7b1ea1a1b955788b | 3,595,148 |
import torch
def _ssim_multichannel(
x: Tensor,
y: Tensor,
data_range: float,
window_size: int,
k1: float,
k2: float,
gaussian_std: float,
) -> Tensor:
"""
Applies SSIM independently to each channel.
Given a multi-channel image, applies single-channel SSIM calculations
to ... | 9382291698e7c0cf49e0445a956165fe1653ec86 | 3,595,149 |
def import_csv_to_df(filename):
"""
Imports a csv file into a Pandas dataframe
:params: an xls file and a sheetname from that file
:return: a df
"""
return pd.read_csv(filename, index_col=0) | 4c8ed341bb96e30465a0f27339cd3edf27e57a4c | 3,595,150 |
import urllib
import json
def get_res(claim):
"""
get results for a claim,
using the API
"""
url = 'http://www.cs.utexas.edu/~atn/cgi-bin/api.cgi?'
final_url = url + urllib.urlencode({'claim': claim})
response = urllib2.urlopen(final_url)
html = response.read()
... | 21cb265099288e9d221c20dde88cfd7cf4f89b8b | 3,595,151 |
def migrate_doc(doc: DocCursor) -> DocCursor:
"""Apply all transforms to a given document. Save it and return."""
for transform in transforms:
doc = transform(doc)
doc.nested_set_renumber(bulk_create=False)
for node in doc.walk():
node.save()
return doc | 6b269861d6afbc8e6a7db7669d93c987580edb8e | 3,595,152 |
def cosine_similarity (a, b):
""" Computes cosine similarity for two vector inputs.
cosine(X, Y) = <X, Y> / (||X||*||Y||)
:param vector a, b: vectors to calculate cosine for
:returns: cosine of a, b
"""
if a is None:
a = 0
if b is None:
b = 0
norm_a = np.l... | 48e52305373602be5ee30859c7535165ada6528c | 3,595,153 |
from typing import List
def F_oneway(lists:List(List(float)))->(float,float):
"""
Performs a 1-way ANOVA, returning an F-value and probability given
any number of groups. From Heiman, pp.394-7.
Usage: F_oneway(*lists) where *lists is any number of lists, one per
treatment ... | 3e5ba3fbe7cde270fef75eb90ce5f82ec2276186 | 3,595,154 |
def which_axis(df, series):
"""Returns the axis matching the series' index (0=rows, 1=columns) or None if no
match.
Not exact, but sufficient.
"""
series_indices = set(series.index)
if series_indices == set(df.index):
return 0
elif series_indices == set(df.columns):
return 1
... | ebc28c2a5f0e796e1a1c95c0e0efdaf31783f76a | 3,595,155 |
def _predict(coeffs, t):
""" Given OLS coefficients, predict the corresponding v values for the given
t values.
"""
return np.sum(np.array(coeffs) * np.array([1.0, t])) | 29ea32933aca8681adf2a80fa2d9751471ff513a | 3,595,156 |
def get_api_result(uri, user_email=None, user_enc_pass=None, **kwargs):
"""Make a GET API request to the server"""
return _api_result(
uri, 'get', user_email=user_email, user_enc_pass=user_enc_pass, **kwargs
) | a37e463416a8023ed316f8ddabefd1146f3ff4f8 | 3,595,157 |
def get_us_mask():
"""Returns contiguous U.S. mask as a dataframe
Columns of dataframe are lat, lon, and mask, where mask is a {0,1} variable
indicating whether the grid point should be included (1) or excluded (0).
"""
return createmaskdf("data/masks/us_mask.nc") | 20b430bcc86df1c07291b7fee8ece0abcf18e703 | 3,595,158 |
def rlmf_eval_dist():
"""Distributional set of hparams for model-free PPO."""
hparams = rlmf_eval()
hparams.distributional_size = 4096
hparams.distributional_subscale = 0.08
hparams.base_algo_params = "ppo_dist_params"
return hparams | 1007e58346647fdde5ed68a0aeb74568a30c7da3 | 3,595,159 |
def _get_first_stacked_classifier_no(model_families=None):
"""Gets the number of iterations necessary before the stacked ensemble will be used."""
num_classifiers = len(get_estimators(ProblemTypes.BINARY, model_families=model_families))
# Baseline + first batch + each pipeline iteration (5 is current defaul... | 0a216bcf24eb04357be14c4d992af27530bd53e1 | 3,595,160 |
def run_depth_ode_1(a,b,c,uu_v,eta_v,rhos,cd,cl,mu,CmA,slope_l,delta_l,stoptime,nt):
"""
Runnning the Monte-Carlo type simulations for different flow depths and
Froude numbers. To solve the equations, odespy is emplpoyed.
"""
from numpy import linspace,shape,arctan,zeros,pi,sqrt
import ode... | 8142188b7ff48d8fd115d439a229b89db8b57094 | 3,595,161 |
def handle_http_exception(e):
"""
Handle for HTTPException.
Defaulted in Flask-LogEx error handlers.
Built to handle AppException below, looking
for custom properties such as error_message
and error_type.
Parameters
----------
e : Exception
An exception that is raised in th... | 99645451817e84558ae86002110707136ee50855 | 3,595,162 |
def get_beta(matrix_list, List=True):
"""function to get a beta from a list of cov matrices"""
if List:
beta_list = []
for matrix in matrix_list:
beta = matrix[1][1]/matrix[0][1]
beta_list.append(beta)
return beta_list
else:
beta = matrix_list[1][1... | c43607162dd70439e04fea66eda8cc18b703673c | 3,595,163 |
def configure_tpu(run_internal):
"""Create TPU RunConfig."""
if FLAGS.use_tpu:
strategy = None
tf.logging.info("Use TPU without distribute strategy.")
elif FLAGS.num_core_per_host == 1:
strategy = None
tf.logging.info("Single device mode.")
else:
strategy = tf.contrib.distribute.MirroredStr... | 6fa91c819c963e2739be4006918212fce0fa1d03 | 3,595,164 |
def analyseClusters(binary, newlabels):
"""
Calculates the sizes and porosities of the clusters.
"""
# dilate particles to find cluster
dilated = ndimage.binary_dilation(binary, iterations=_DILATIONFACTOR_TO_FIND_CLUSTER)
labels, num = label(dilated, background=0, return_num=True)
pxAre... | 4bd75c0bf8b98c0600c217f9630372ffcb916591 | 3,595,166 |
import tokenize
def build_model():
""" Build Pipeline
Args:
None
Returs:
(sklearn.pipeline.Pipeline):
"""
# The classes are highly imbalanced, that's why a
# class_weight='balanced' parameter was added to
# the RandomForestClassifier
pipeline = Pipeline([
('vec... | e3c1f50f4fb90e0c0a5bdcb473dd4bfa8ee9af20 | 3,595,167 |
def _patch_remains(image, masks):
"""inpaint remaining parts of the image"""
for mask in masks:
mask = cv2.split(mask)[0]
image = cv2.inpaint(image, mask, 3, cv2.INPAINT_NS)
return image | c013439599869242afa20f490b3f9884c545a326 | 3,595,168 |
def cidr_to_mask(cidr):
"""
Converts decimal CIDR notation to a quad dotted subnetmask.
:param cidr: Decimal CIDR number
:return: Quad dotted subnetmask as string
"""
cidr = int(cidr)
mask = (0xffffffff >> (32 - cidr)) << (32 - cidr)
return (str((0xff000000 & mask) >> 24) + '.' +
str((0x00ff00... | 037e1cacfb392fad4a06edf1d9c16c4f27c0468b | 3,595,169 |
def dpr():
"""
Return the number of degrees per radian.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dpr_c.html
:return: The number of degrees per radian.
:rtype: float
"""
return libspice.dpr_c() | b6f8dab90b864b5c8ae79bc96665aea26a74ec74 | 3,595,170 |
from re import T
def Hc(x: Array) -> Array:
"""
Returns the is_hermitian conjugate
`Hc(x) == jax.numpy.transpose(x.conjugate())`
"""
return T(Cc(x)) | e5883778c695e612d4904b4e38983457faa8211f | 3,595,171 |
from typing import OrderedDict
def build_hashtag_counts_by_state(tweet_collection, state_collection, shpfile,
skip_users=None, dry_run=True):
"""
Example
-------
Build state counts using hashtagged tweets and skip bots.
>>> skip = get_skip_users()
>>> build_h... | c5b0ca4b3251e7251f0c7e8d9dd1ec4f4bede340 | 3,595,172 |
import csv
def generate_patient_info_json(patient_info_file_name):
"""Given a properly formatted csv file containing the patient information,
generate and return a JSON object representing its contents.
"""
patient_info = {}
with open(patient_info_file_name, 'rU') as f:
reader = csv.reader... | cefdaee5ff5ec33721a30f7f15c8691b380ef55e | 3,595,173 |
def parse_program_line(line: str):
"""
Parse the program line in the LS-Dyna output.
Data we need:
- ``program``: license name
- ``max``: total amount of licenses in the server
The ``used``value will be evaluated later.
"""
parsed_program = RX_PROGRAM.match(line)
if parsed_program is... | be298f00208b314d6caeab108978f122419d37de | 3,595,174 |
import random
def computer_choice() -> str:
"""
This function takes no inputs and returns either "rock", "paper", or
"scissors" randomly to simulate the computer's decision.
"""
# 'random' is a library. A library is essentially a collection of code that
# contains some kind of feature(s) that we want to use in... | 1f8e064adfbd6242f2bb199caf98b77acf38c596 | 3,595,175 |
def create_actor():
"""Route handler for the endpoint for creating a new actor.
Returns:
response: A json object representing info about the created actor
"""
try:
actor = Actor(
name=request.json.get("name"),
birthdate=request.json.get("birthdate"),
... | 43dce82ded040304baa9bb395e2a4f5812fcf010 | 3,595,176 |
def get_legacy_dispatcher(reactor, authenticator, log, service_configs):
"""
Return a dispatcher that can perform effects that are needed by the old
worker code.
"""
return ComposedDispatcher([
get_cloud_client_dispatcher(
reactor, authenticator, log, service_configs),
ge... | cc3cbc070e2aaf8a55d0121c7a73a9ba7ec9797e | 3,595,177 |
async def get_did_endpoint(request: web.BaseRequest):
"""
Request handler for getting a verkey for a DID from the ledger.
Args:
request: aiohttp request object
"""
context = request.app["request_context"]
ledger = await context.inject(BaseLedger, required=False)
if not ledger:
... | 0eb0963002bd2798f7fdf94b000e7e5a5e019b77 | 3,595,178 |
async def async_setup(hass, config):
"""Component to allow users to login."""
store_result, retrieve_result = _create_auth_code_store()
hass.http.register_view(TokenView(retrieve_result))
hass.http.register_view(LinkUserView(retrieve_result))
hass.components.websocket_api.async_register_command(
... | fa53054e41b00528c38a16bab9a4db704fd13895 | 3,595,179 |
def get_settings(application, force_instance=False):
"""
Retrieve the media type settings for a application.
:param tornado.web.Application application:
:keyword bool force_instance: if :data:`True` then create the
instance if it does not exist
:return: the content settings instance
:r... | 79707322ae1eaf27a75734f208e7fea1acb97133 | 3,595,180 |
def get_dstat_provider_args(provider, project):
"""A string with the arguments to point dstat to the same provider+project."""
provider_name = get_provider_name(provider)
args = []
if provider_name == 'google':
args.append('--project %s' % project)
elif provider_name == 'google-v2':
args.append('--pr... | 45e51799af25e7b9775dab85e469538355a41d96 | 3,595,181 |
def interpolate(mass, feh, phase, **kwargs):
"""
Returns the requested values from the stellar evolution grids at the given
values for the input parameters (mass, feh, phase)
"""
global defaults
if 'grid' in kwargs:
axis_values, pixelgrid, variables = kwargs['grid']
elif not defaults... | 04144b3999c110766e0cd36a3062b5e73e255077 | 3,595,182 |
from typing import Counter
def get_bootstrap_symbol_counts_from_symbols_array(symbols_array,
symbol_block_length):
"""
Given an array of symbols (cf get_symbols_array), get bootstrap
replications of the symbol counts.
"""
num_symbols = len(symbo... | 4cd5e7d54bd175824a2cc7f54deebdcabc7c1b18 | 3,595,184 |
def ASSD_and_MSSD(ref, test, **metrics_kwargs):
"""Average Symmetric Surface Distance"""
affine = metrics_kwargs.pop("affine")
num_class = metrics_kwargs.pop("num_class")
ASSD, MSSD = [], []
for c in range(1, num_class):
ref_c = np.int32(ref==c)
test_c = np.int32(test==c)
if ... | 4621b1eb7cde7c3c600875dd37f6b83119654870 | 3,595,185 |
def apply_colour_to_mask(mask, colour):
"""Set the mask colour equal to a given colour.
"""
colour = mcolors.to_rgba(colour)
colour = np.asarray(colour)
colour = colour[tuple(np.newaxis for _ in range(mask.ndim))]
mask = mask[..., np.newaxis]
return mask*colour | 6370dce58da9e387e302fdc48117b23bdc2e1b8a | 3,595,186 |
import re
def take_diff(diff_type, old, new, full_replace):
"""
Find differences between original and modified DataFrame instances.
Parameters
----------
old, new : pandas.DataFrame
DataFrame instances to compare.
Results
-------
result : dict
Dict containing keys '... | 4e92adf826326e6359d36f86f2cececeedb425c5 | 3,595,187 |
import time
import requests
import six
def post(url, params):
"""
Make a POST request to the URL using the key-value pairs. Return
a set of key-value pairs.
:url: URL to post to
:params: Dict of parameters to include in post payload
"""
payload = urlencode(params)
start_time = time.t... | d968a715a9dfb2b5006b389a3ecca4275f667f33 | 3,595,189 |
import time
def google_search(search_term):
"""
Used to check if a research on Google give some results with Google api
:param search_term: str
:return: bool
"""
try:
try:
service = build("customsearch", "v1", developerKey=my_api_key_custom_search, cache_discovery=False)
... | 9902c0b71fa44dfdcc4bc8fd09e91f492e437444 | 3,595,190 |
from typing import Tuple
def keygen(n_bits: int = 64,
s: int = 1,
threshold: int = 3,
n_shares: int = 3) -> Tuple[PublicKey, PrivateKeyRing]:
"""Generates a PublicKey and a PrivateKeyRing using the threshold variant of Damgard-Jurik.
The PublicKey is a single key which can be... | 24d277da7f98e3b8cd19e233c522bee2277649e4 | 3,595,192 |
import json
def list_constellations():
"""
Returns a list that contains all the constellations in the Redis db
"""
r = redis.Redis()
constellations = []
for key in r.keys():
s = r.get(key)
if key.find('cloudsim/') == 0:
c = json.loads(s)
constellations.a... | 5f624631c982f8c91743b53792b2e59f81203de6 | 3,595,193 |
def product_list(request, template):
"""View to select a product to see related questions."""
return render(request, template, {
'products': Product.objects.filter(
questions_locales__locale__in=[request.LANGUAGE_CODE])
}) | 78fedb24735e2f99b0a5a6ef8cd6b99b4f90efc8 | 3,595,194 |
import xmlrpc
def do_update_script(server, sid, phase):
"""
execute script before and after maintenance
"""
script = ""
list_channel = []
(script, list_channel, timeout) = read_update_script(phase, "general", script, list_channel)
(script, list_channel, timeout) = read_update_script(phase,... | 223b604e1d8434dcc0c60d1938ff94ee74a6f216 | 3,595,195 |
def sinify(x: float) -> float:
"""Run through a sin function that returns values \\in [0, 1]"""
return 1 - (cos(x * pi * 2) + 1) / 2 | b6680d389ffe26472f89eba5225f0b7c1c5aa06b | 3,595,196 |
def connect_exploits():
"""Connects Vulnerability IDs and Exploits together in t_exploit_references"""
db = current.globalenv['db']
cache = current.globalenv['cache']
exploits_db = db.t_exploits
exprefs_db = db.t_exploit_references
vd = db.t_vulndata
vr = db.t_vuln_refs
vrefs = db.t_vul... | bf8cbd8d9dd96fe6315095e426442976fff77d25 | 3,595,197 |
def filter_ps(ps):
"""
ps -> List of paths
Out of all the paths, select only the lowest weight paths that lead to the same end.
"""
best_ps = {}
for p in ps:
w_4 = p[0][1]
w_5 = p[1][1]
x = (w_4 + w_5, w_4)
state_5 = p[1][0]
if (state_5 not in best_ps) o... | d534d47a5faa04a5d207a8dff54c43c8ef966626 | 3,595,198 |
from re import T
def gradient(objective, argument):
"""
Wrapper for theano.tensor.grad().
Compute the gradient of 'objective' with respect to 'argument' and return
compiled version.
"""
g = T.grad(objective, argument)
return compile(g, argument) | 22218c3aaf2723e26949270e967a61493b07a936 | 3,595,199 |
async def add_messages_to_buffer(tab, top: bool, results, amount: int) -> bool:
"""Prepends or appends messages to the tab text_buffer"""
text_buffer = tab._text_buffer
msg_count = 0
msgs = []
async for rsm in results:
if top:
for msg in rsm['mam']['results']:
if... | bf09f1ff943ead5c5631333d539950dbc21e3a43 | 3,595,200 |
def calculate_weight(level=0):
""" calculate weight alpha
"""
img_coord = get_unfold_imgcoord(level, False)
vertices, _ = get_icosahedron(level)
key = 0
vi_idx = img_coord[key][1:, 1:]
vn1_idx = img_coord[key][1:, :-1]
vn6_idx = img_coord[key][:-1, 1:]
vi = vertices[vi_idx]
vn1 =... | c833a8a70e486347617d0b183f4223d71bd852ec | 3,595,201 |
import warnings
def get_units(facility_id=None, country=None):
"""
params
------
country: str
The ISO2 code of the country to retrieve units list from.
facility_id: str or list
The ids of the facilities to retrieve units list from.
"""
session = scoped_session(sessionmaker(... | a078f5f928ec118c3c9267f6044770b20395eed5 | 3,595,202 |
def tupgetter(*idxs):
"""Like itemgetter, but return a 1-tuple if the input is one index."""
if len(idxs) == 0:
return tuple
if len(idxs) == 1:
def tupgetter_(obj, _idx=idxs[0]):
return (obj[_idx],)
return tupgetter_
else:
return itemgetter(*idxs) | 10f356158c1ead7d7623bb8a0061dc21ded079d5 | 3,595,203 |
def center_km(KM):
"""
Centers a given kernel matrix.
Implements the definition according to Lemma 1 in Section 2.2 in
Cortes, Corinna, Mehryar Mohri, and Afshin Rostamizadeh, 2012, "Algorithms for
Learning Kernels Based on Centered Alignment", Journal of Machine Learning
Research 13(Mar): 795–... | 2dbfb9ed54ff14a320a3bf4291461bc4fe3cab73 | 3,595,204 |
from datetime import datetime
import json
def geo_match2(location_names):
"""
This function match US city names with corresponding coordinates
:param location_names: str, content of input file
:return: str
"""
def data_preprocess(data):
"""
this function preprocess the input da... | ff4e2149d089f8e74f16e73c531ada476c058e60 | 3,595,206 |
from pathlib import Path
from typing import Optional
import warnings
def get_release_path(dataset_path: Path, release_name: Optional[str] = None):
"""
Given a dataset path and a release name, returns the path to the release
Parameters
----------
dataset_path
Path to the location of the da... | e3381deab798595289b7a685887cf49420ecbc2a | 3,595,207 |
def convert_training_shape(args_training_shape):
"""Convert training shape"""
training_shape = [int(args_training_shape), int(args_training_shape)]
return training_shape | 391a85eed34483461910be9bf0f94b936660abb0 | 3,595,208 |
def batch_insert_url(db, urls_with_depths, visited, queued):
"""Inser batch of urls into db"""
url_documents = []
for url in urls_with_depths:
url_object = _prepare_url_object(url.get('url'),
visited,
queued,
... | 93333c4130def793e927b727209d81f0b6b7e850 | 3,595,209 |
def unescape(text):
"""Convert Trados text to normal Unicode string"""
for trados_escape, char in RTF_ESCAPES.iteritems():
text = text.replace(trados_escape, char)
return text | ca9a30dbcb641a7b5957a40b8bf882c33d5193db | 3,595,210 |
def csm_value_repr(self):
"""
String representation for the CSMValue namedtuple which excludes
the "created" attribute that changes with each execution. Needed for
consistency of ddt-generated test methods across pytest-xdist workers.
"""
return f'<CSMValue exists={self.exists} raw_earned={self... | 07917e16e6e3539916aac6e114375b598fad446b | 3,595,211 |
import re
def _MakeApiDict(message_module, collection_dict):
"""Returns a dictionary of API attributes from its messages module.
Args:
message_module: the messages module for the API (default version)
collection_dict: a dictionary containing collection info from registry
"""
api_dict = {}
try:
... | a86eff9d509130baf4c983d4c111026fafaab4e8 | 3,595,212 |
def is_good_license(detected_license):
"""
Return True if a `detected license` mapping is consider to a high quality
conclusive match.
"""
score = detected_license['score']
rule = detected_license['matched_rule']
coverage = rule.get('match_coverage') or 0
relevance = rule.get('rule_relev... | d3e74752feb69a8ed298eca306ecfe3df0009c44 | 3,595,213 |
from typing import List
def is_import_targetted_by_commit(import_dir: str, import_name: str,
import_targets: List[str]) -> bool:
"""Checks if an import should be executed upon the commit.
See module docstring for the rules.
Args:
import_dir: Path to the director... | 4fd6a6127bd2e88aeaa308d098b669158a0b8dbb | 3,595,214 |
import requests
import click
def random_authors(count: int = 10, gender: str = "a") -> AuthorList:
"""Return a author set of size n.
Args:
count (int): Decides the size of the returned set. Defaults to 10.
gender (str): Decides which gender names should be returned from the
'rando... | d9fccaf2a6d5b797eb7ff29e0f0702cb8ca234e2 | 3,595,215 |
def wants_child_support(responses, derived):
""" Return whether or not the user wants an order for child_support """
return 'Child support' in derived['orders_wanted'] | 3468f83f541eee7cba2e8ee3664c9efee1c0225a | 3,595,216 |
def rad2deg360(x):
"""
"""
d = np.rad2deg(x)
d[d < 0] += 360
return d | 5f63c96bf17885ec42c9a0c999adb07f170c0e78 | 3,595,217 |
from typing import TypeVar
from typing import Union
from typing import Any
def unpack_typevar(value: TypeVar) -> type:
"""Unpack `TypeVar` into a union of possible types.
:param value: A type var instance.
:return: A union of types.
"""
return Union[value.__constraints__ or (value.__bound__ or An... | 971b2fa634943bd603b9905a0d4729c2761d61bc | 3,595,218 |
def get_valid_config():
"""Helper function to return a valid config for the rule processor. This
simulates what stream_alert.rule_processor.load_config will return in a
very simplified format.
Returns:
dict: contents of a valid config file
"""
return {
'logs': {
'jso... | 774e0d9b40b8b0ea25ce10907b0f9954d0b7f966 | 3,595,219 |
def get_template_id(template_name, auth, url):
"""
Helper function takes str input of folder name and returns str numerical id of the folder.
:param folder_name: str name of the folder
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC R... | a0fa6a148de71ea8ef415d7df270ce5410210728 | 3,595,220 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.