content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def compute_rhat_regression(samples, n_chains):
"""A wrapper function for computing R-hat statistics for regression tasks.
Args:
samples: numpy array [n_chains * n_samples, n_vars], the samples
taken from MCMC sampling.
n_chains: int, the number of sampling chains.
Return:
... | 436655868282421b702fe8e156c1e765af553744 | 70,416 |
import torch
def binary_loss_function(recon_x, x, z_mu, z_var, z_0, z_k, ldj, beta=1.):
"""
Computes the binary loss function while summing over batch dimension, not averaged!
:param recon_x: shape: (batch_size, num_channels, pixel_width, pixel_height), bernoulli parameters p(x=1)
:param x: shape (bat... | 5009cc3c881f3b6b71495efe516dd038b9ca92f9 | 70,417 |
def update_create_front_page_groups(request_ctx, group_id, wiki_page_body, wiki_page_title=None, wiki_page_hide_from_students=None, wiki_page_editing_roles=None, wiki_page_notify_of_update=None, wiki_page_published=None, **request_kwargs):
"""
Update the title or contents of the front page
:param reque... | 64a6ecc66d6ec63c35c2d20e9610f9814dbd60d6 | 70,418 |
def default_copy(original_content):
"""Copy all fields of the original content object exactly as they are
and return a new content object which is different only in its pk.
NOTE: This will only work for very simple content objects. This will
throw exceptions on one2one and m2m relationships. And it mig... | d0a6fca858e34b8a7ae26ed9693a894cf2b2473f | 70,419 |
def build_normalized_request_string(ts, nonce, http_method, host, port, request_path, ext):
"""Implements the notion of a normalized request string as described in
http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-02#section-3.2.1"""
normalized_request_string = \
ts + '\n' + \
nonce +... | 6a7f397738b852116cbaf249c846f58b482fdca1 | 70,420 |
def get_merged_coverage_eval():
"""Merges and returns all active coverage data as a single dict.
Returns: coverage eval dict.
"""
if not _coverage_eval:
return {}
coverage_eval_list = list(_coverage_eval.values())
merged_eval = deepcopy(coverage_eval_list.pop())
for coverage_eval in... | e4f5b227f7dab9ce50513bc29eec30172af7d77e | 70,421 |
from operator import setitem
def xmlparse(source, parsing_method=XMLParsingMethods.C_ELEMENTTREE, **kwargs):
"""Parses a XML document into a dictionary.
Details about how the XML is converted into this dictionary (json)
representation is described in reference [3] in the README.
:param str,file-like... | 155a1f44f3b0393235693626e53ce63a750fcce7 | 70,422 |
def print_exception(
type=None, value=None, traceback=None, limit=LIMIT, as_html=False,
with_filenames=False, stream=None
):
"""Print the exception to the given `stream`."""
info = format_exception(
type, value, traceback, limit, as_html, with_filenames
)
if stream is None:
... | ff6c184b40d6fba2ff197832a40456658d66ce04 | 70,423 |
def authenticate(f):
"""
Decorator for checking if a user is authenticated
"""
@wraps(f)
def wrapper(self):
"""
:type self: RequestHandler
"""
try:
self.request.session = Session.get(Session.secret == self.get_cookie('session'))
f(self)
... | 9814d4180cf0a11de7ede9d862a953b744d161a7 | 70,424 |
def _average_gradients(tower_grads):
"""Calculates average of gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list is
over individual gradients. T... | 67c143dbdae01ca1dfdeff345861e0e0aca0bc1c | 70,425 |
from datetime import datetime
def home():
"""Show user info"""
# Get today's date
date_now = datetime.datetime.strptime(get_time(), "%Y-%m-%d %H:%M")
# Get user event info
events = db.execute("SELECT * FROM events WHERE event_id IN (SELECT event_id FROM event_members WHERE user_id = ?) ORDER BY ... | 4b327ed7309909560ef59302a272ae4d8090c60a | 70,426 |
import ast
import re
def extract_from_grid(field_soup, form_info):
"""Return list of Samples, extracted from grid portion of form xml.
Arguments:
field_soup (BeautifulSoup object): The soup of the grid field.
form_info (api_types.CustomForm): dataclass holding information for the
... | 2fbd16c4f288733011eac6f2f06e59c2666e690e | 70,427 |
def instance_get_oper_state(vm_state, task_state, power_state):
"""
Convert the nfvi vm states to an instance operational state
"""
oper_state = nfvi_objs.INSTANCE_OPER_STATE.ENABLED
if nova.VM_STATE.ERROR == vm_state:
oper_state = nfvi_objs.INSTANCE_OPER_STATE.DISABLED
elif nova.VM_ST... | 831ccfd9cc6e67a52d144297f8e851a9c1ae4176 | 70,429 |
def _force_list(value):
"""If the value is not a list, make it one."""
if value is None:
return []
try:
if isinstance(value, basestring):
raise TypeError()
return list(value)
except TypeError:
return [value] | 88a70d870a2c5c4a3c537b5b25247e852ed3af7c | 70,430 |
import google.datalab.utils as du
def batch_predict_async(training_dir, prediction_input_file, output_dir,
mode, batch_size=16, shard_files=True, output_format='csv', cloud=False):
"""Local and cloud batch prediction.
Args:
training_dir: The output folder of training.
prediction_i... | bc1da3a7a1c1f6dc28f96bfad326eaf212da2531 | 70,432 |
def make_sphere_a():
""" Create a sphere"""
mesh_a = trimesh.creation.icosphere(subdivisions=1, radius=1.0)
return mesh_a | 69c034884c6280411764d86cadcb81308d957416 | 70,435 |
def title():
"""
(None) -> None
Function that loads the error page
"""
title = request.args.get('title')
if title in TITLES:
return render_template(f"books/{title}.html")
else:
return redirect(url_for(error)) | 32b9a317bcbb9905e63934b5ca61b2914da06865 | 70,436 |
from typing import Tuple
def load_sets(directory, suffix: str = '', file_type: str = 'csv') -> Tuple[
pd.DataFrame,
pd.DataFrame,
pd.Series,
pd.Series,
pd.DataFrame
]:
"""
"""
# Cater for empty suffix and not having a dangling underscore
if suffix:
suffix = f'_{suffix}... | 8ac7357a9e994d1cf6e025baeac35a0369dbbfbd | 70,437 |
def resnet101(**kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
return model | 5e40c374f07025d07ff385a229c487851e6464ec | 70,438 |
import json
def load_game(file_name):
"""
Loads game information from a json file and populates the input layer of the LSTM
Parameters
----------
file_name : str
Name of json file to be parsed and converted to input layer
Returns
-------
list
List of containing one el... | bc4da931ca469a32d544a988b103afe7f5c97981 | 70,439 |
def test_hard_requirements():
""" Returns any errors resulting from hard config requirement violations
"""
output = {}
for k in hardRequirements:
hardRequirements[k](output)
return output | 1805f54b58431840d80ffaef0b5d139299614176 | 70,440 |
def Lt(left: Expr, right: Expr) -> BinaryExpr:
"""Less than expression.
Checks if left < right.
Args:
left: Must evaluate to uint64.
right: Must evaluate to uint64.
"""
return BinaryExpr(Op.lt, TealType.uint64, TealType.uint64, left, right) | f982a1386ded20da9b8c13355512e83e0a786809 | 70,442 |
def first_prime_greater_than(k: int) -> int:
"""
return the first prime greater than k
Called by the InputParams constructor
"""
if k < 1:
raise FuzzyError("k < 1")
while True:
k += 1
if isprime(k):
return k | 92a563b97987b526a6e3d01ee73475cb60df24b8 | 70,444 |
import pickle
def to_bytes(graph: BELGraph, protocol: int = pickle.HIGHEST_PROTOCOL) -> bytes:
"""Convert a graph to bytes with pickle.
Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable
pickle, choose 0, 1, or 2.
:param graph: A BEL gra... | 5af28070f1a5eb4cf666c3014968dcf41f552251 | 70,445 |
import pickle
import math
def genr_item_univ(config: dict, size_res_path='data/item_size.pkl', cls_res_path='data/cls_item.pkl'):
"""Generate universe of items (queries).
Generate and save result as <Item Size Table>. Item number and size range
specified by params in config. Compute and save <Class Item... | c5716e03b43c178b9bdc44c79463ca33e8fef9a9 | 70,446 |
def trace_stream(stream_port, request_message = None, response_message = None):
"""Allows tracing the input stream within the resulting stream."""
s = stream_port
expect_stream(stream_port)
model = s.get_model()
item_data_type = s.get_item_data_type()
code = 'return $ traceStream '
code += e... | c7a9d7c26c25ac3c050f312bd5b827022f6c832a | 70,448 |
import requests
def get_mobility(city):
"""Gets the latest mobility data from city mapper
Arguments:
city {String} -- Which city to get data from
Returns:
Pandas Series -- Series of mobility index
"""
url = "https://www.data.gouv.fr/en/datasets/citymapper-mobility-index/"
u... | ded9e90604b346ebdc8bc702d26c64cbe4b8050a | 70,450 |
def rivers_with_station(stations):
"""Given list of stations (MonitoringStation object), return the
names of the rivers that are being monitored"""
# Collect all the names of the rivers in a set to avoid duplicate entries
rivers = {station.river for station in stations}
# Return a list for conveni... | c099af2eb0f869c6f1e3270ee089f54246779e2d | 70,451 |
from typing import List
def expand_time_windows(periods: List[TimeWindow]) -> List[pd.Timestamp]:
"""Return a list of days to exclude from a list of TimeWindows.
Args:
periods: List of time windows (first day, last day).
Returns:
days_exclude: a List of obtained by expanding the list in input.
"""
d... | 1179926b7eb335be3e606db19b33bb819069f69c | 70,452 |
def _clean_str(words):
"""
heavily borrowed from github
https://github.com/LukeZhuang/Hierarchical-Attention-Network/blob/master/yelp-preprocess.ipynb
:param sentence: is a str
:return:
"""
words_collection = []
for word in words:
if word in ['-lrb-', '-rrb-', '<sssss>', '-r', '... | 7b69764bbdab2c5226163f31f365194a7cb1fac5 | 70,453 |
def from_text(text, origin=None, rdclass=dns.rdataclass.IN,
relativize=True, zone_factory=Zone, filename=None,
allow_include=False, check_origin=True, idna_codec=None):
"""Build a zone object from a master file format string.
*text*, a ``str``, the master file format input.
*or... | f78d8ea626029c25e819bfe4e61f36a2f2be6de3 | 70,454 |
from MoinMoin.widget import html
def makeSelection(name, values, selectedval=None, size=1, multiple=False, enabled=True):
""" Make a HTML <select> element named `name` from a value list.
The list can either be a list of strings, or a list of
(value, label) tuples.
`selectedval` is the val... | 5aea7545d4213915bd3fba9cf0b2908ad938cb40 | 70,455 |
def find_anagrams(s, diction):
"""
:param s:
:param diction:
:return:
"""
ans = []
permutation(s, '', len(s), ans, diction)
return ans | a1ee705426963ea393479c366d6ff7e5a4a110a4 | 70,456 |
async def del_schema(event_type: str):
"""
Deletes event validation schema for given event type
"""
try:
result = await storage.driver.validation_schema.del_schema(event_type)
await storage.driver.validation_schema.refresh()
except ElasticsearchException as e:
raise HTTPExcep... | 9167a0424ba7dd6a83f66f49835640b7fe44e795 | 70,457 |
import requests
import json
def pinterest_shares(url):
"""pinterest share count"""
try:
pinterest_url = 'http://api.pinterest.com/v1/urls/count.json?url=' \
+ url
response = requests.get(pinterest_url).text\
.replace('receiveCount(', '')\
... | 097a587778b1b21ceb84664b644cdbc6bb4619c3 | 70,458 |
import math
def get_deltas(radians):
"""
gets delta x and y for any angle in radians
"""
dx = math.sin(radians)
dy = -math.cos(radians)
return dx, dy | 032acb537373d0ee18b721f04c95e75bb1572b1b | 70,459 |
def global_min_temp(year):
""" Finds the minimum temperature from the minimum temperatures from all
the observations for a given year from 1929 to 2009 inclusive.
"""
return sc.textFile(server_name + dir_name + str(year))\
.filter(lambda line: "STN" not in line)\
... | 8daad6ac0ac7f96ae672ae7ce8b0136f6c8e9a96 | 70,460 |
import logging
def tok_sentence_to_vec(tok_sentences, vocabulary, model, normalize_sentence=1,
normalize_word=True, alpha=1e-4, show_logs=0):
"""
Maps a list of tokenized sentences to their vectorial representation.
> tok_sentences: List of tokenized sentences
> vocabulary: Lis... | 6634262922235a3e8f21648200257d22fa1626c2 | 70,461 |
from typing import Dict
def mrr(benchmark: Dict, results: Dict, repo: str) -> float:
"""
Calculate the MRR of the prediction for a repo.
:param benchmark: dictionary with the real libraries from benchmark.
:param results: dictionary with the predicted libraries.
:param repo: full name of the repo.... | b057c93cc807244e4d5e8e94772877273ac1041c | 70,462 |
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Union
from typing import cast
def netlist(
*,
instances: Instances,
connections: Dict[str, str],
ports: Dict[str, str],
models: Optional[Models] = None,
settings: Optional[Settings] = None,
defa... | add686735ddebe819e7d494f0feb78008248e10c | 70,463 |
from datetime import datetime
import time
import requests
import json
def get_interlanguage_links(page_names,
languages_of_interest={'it', 'nl'},
sleep=1,
verbose=0):
"""
mapping of English page name to its equivalent pages in... | 8bcd458dd9ae6fb857d57535897701c017d11252 | 70,464 |
from typing import Callable
def is_similar_callables(t: Callable, s: Callable) -> bool:
"""Return True if t and s are equivalent and have identical numbers of
arguments, default arguments and varargs.
"""
return (len(t.arg_types) == len(s.arg_types) and t.min_args == s.min_args
and t.is_v... | 861ae7265a7ad8e2b5b4c83d8e17a8c33195acf9 | 70,465 |
import hashlib
def hashmd5mod(*args):
"""
.. function:: hashmd5mod(args, divisor) -> int
Returns the *modulo* with divisor number of the MD5 hash of args.
Numbers are converted to text before hashing is performed.
Examples:
>>> sql("select hashmd5mod(65, 3)")
hashmd5mod(65, 3)
-----... | 13507127ab561a79b14ef5afac181760270226ba | 70,466 |
def get_total_gpu_memory(units="Mb"):
"""Get the memory of the GPUs in the system
Returns:
list: List of strings with the GPU memory in Mb
Examples:
>>> get_total_gpu_memory() #doctest: +SKIP
[16280.875]
"""
try:
memory_list = []
for gpu in cuda.gpus... | 848c208bc310ed641e441f096342326f6dc75905 | 70,467 |
def dictTagging(word, tag):
"""
Use language dictionaries to tag words
"""
global language_1_dicts
global language_2_dicts
global lang1
global lang2
dhin, den0, den1 = 0, 0, 0
word = word
if word.lower() in language_1_dicts["hindict1"].keys():
dhin = 1
if word.low... | 2a5fc15cbff2480c5c9e9336ac6a4feaa62112e1 | 70,468 |
def extract_dependencies(depends_content, exclude=None):
"""
Extract the Bazel project name from the BUILD file.
:param set depends_content: The Bazel BUILD files merged content.
:param str exclude: exclude self references.
:returns: List of dependencies, otherwise None.
:rtype: set
"""
... | 1d923a87f7ce7f5343242c756e5b0ab4bf59f90a | 70,469 |
def hook_get_load_batch_query(table: str, start_index: int,
end_index: int) -> str:
"""Returns the query that loads the BQ data.
Here it's possible to filter just new customers or other customer
groups.
Args:
table: A string representing the full path of the BQ table where th... | 6a99cf04214a815249a01b6cf5040bdb93b73fb8 | 70,470 |
def soft_nms(boxes, scores, method, gaussian_sigma, linear_threshold, prune_threshold, topk_per_image):
"""
Performs soft non-maximum suppression algorithm on axis aligned boxes
Args:
boxes (Tensor[N, 5]):
boxes where NMS will be performed. They
are expected to be in (x_ctr, y_... | 39c61258f913d6f943754c2f6a911d7bde577b5b | 70,471 |
def getSourceDefaultSettings(sourceKind: str):
"""
Get the default settings for a given source type.
:param sourceKind: String - Source kind. Also called "source id" in libobs terminology.
"""
return __createJSON("GetSourceDefaultSettings", {'sourceKind': sourceKind}) | 142f26c3e300b6f034f17ebfef4dba7d1eb1cb9e | 70,472 |
def get_spearman_rho(word2id1, embeddings1, path, lower,
word2id2=None, embeddings2=None):
"""
Compute monolingual or cross-lingual word similarity score.
"""
assert not ((word2id2 is None) ^ (embeddings2 is None))
word2id2 = word2id1 if word2id2 is None else word2id2
embedd... | 25921c17209fea11ae95f7a62858eb90ae198b6d | 70,473 |
def elf_segment_names(elf):
"""Return a hash of elf segment names, indexed by segment number."""
table = {}
seg_names_sect = elf.find_section_named(".segment_names")
if seg_names_sect is not None:
names = seg_names_sect.get_strings()[1:]
for i in range(len(names)):
table[i... | 4af46fb35c9808f8f90509417d52e7ce4eb2770e | 70,474 |
def line_line_closest_points(A1, C1, A2, C2):
"""
>>> print line_line_closest_points(Ux,Ux,Uy,Uy)
(Vec( 0.000000, 0.000000, 0.000000 ), Vec( 0.000000, 0.000000, 0.000000 ))
>>> print line_line_closest_points(Ux,Uy,Uy,Uz)
(Vec( 0.000000, 1.000000, 0.000000 ), Vec( 0.000000, 1.000000, 1.000000 ))
... | 211d19b67fb56d00ae1276ebd62e9e979c4d5295 | 70,475 |
def load_data(args):
"""
Load dataset
Args:
args: arguments set by the user
"""
dst = args.dataset
if dst == 'mnist':
return load_mnist(args)
if dst == 'fashion-mnist':
return load_fmnist(args)
if dst == 'cifar10':
return load_cifar10(args)
if dst ==... | 9215008fb0545b79b3b8da14b21520908e1fe321 | 70,477 |
def segment_spectrum_batch(spectra_mat, w=50, dw=25):
"""
Segment multiple raman spectra into overlapping windows
Args:
spectra_mat (2D numpy array): array of input raman spectrum
w (int, optional): length of window. Defaults to 50.
dw (int, optional): step size. Defaults to 25.
... | 956791e2957f4810726d1d94549f79f3d83c8d21 | 70,478 |
from pathlib import Path
def _get_params() -> dict:
"""
Parse Commandline Arguments and return them as options.
Returns:
dict
"""
return EntryPointParameters(
inputdir=dict(
type=Path,
required=True,
help="Measurements path."
),
... | 2a208207a09a2de87f51d5e5432893e4feeb5941 | 70,479 |
def complete_annotation(program, dist_context=None):
""" Complete annotation for the partial annotated program.
Arguments:
program: partial annotated program.
dist_context: the distributed context is used to store distributed attributes for program.
If not provided, the default one ... | 5abb68e06243b935f0dec0070758390d3b513d7f | 70,481 |
def generate_hashes(peaks, hash_style):
"""
Hash list structure:
sha1_hash[0:30] time_offset
[(e05b341a9b77a51fd26..., 32), ... ]
"""
peaks = list(peaks)
if peak_sort:
peaks = sorted(peaks, key=lambda x: x[1])
# print("Length of Peaks List is: {}".format(len(peaks)))
i... | 9d6919dac3e1910eb173028ad0cc0bef6c265c12 | 70,482 |
def _create_serialized_example(features, label):
"""Helper for creating a serialized Example proto."""
example = tf.train.Example(features=tf.train.Features(feature={
"features": _float_feature(features),
"label": _int64_feature(label),
}))
return example.SerializeToString() | 835558f340ee23bd8280e26de7b128c3ee824eed | 70,483 |
from typing import Dict
def sparsity_loss(X_hat_cf: tf.Tensor, X: tf.Tensor) -> Dict[str, tf.Tensor]:
"""
Default L1 sparsity loss.
Parameters
----------
X_hat_cf
Autoencoder counterfactual reconstruction.
X
Input instance
Returns
-------
L1 sparsity loss.
... | 2ef5e83277b541506b030ca56c1690aad6f4d22b | 70,484 |
def proxies_get_number():
"""
获取代理IP数量
:return:
"""
number_10 = redis_pool.redis_llen(GRADEKEY10)
number_8 = redis_pool.redis_llen(GRADEKEY8)
number_6 = redis_pool.redis_llen(GRADEKEY6)
number_4 = redis_pool.redis_llen(GRADEKEY4)
number_grade = redis_pool.redis_llen(GRADEKEY) # 使用完待... | 1efff3b0cefa9b90d3d5674a66ce544d5eae7132 | 70,485 |
from typing import Union
from typing import Tuple
from typing import Dict
from typing import List
def rnns(
draw, return_kwargs: bool = False
) -> Union[
st.SearchStrategy[rnn_pb2.RNN], st.SearchStrategy[Tuple[rnn_pb2.RNN, Dict]]
]:
"""Returns a SearchStrategy for RNN plus maybe the kwargs."""
kwargs ... | ebfbbb2c1e04a51f504a0bd9b278602f2ac045e2 | 70,486 |
def readvar(fni,varname,latrange=[],prange=[]):
"""reads variable from netcdf object in varname
fni is a Dataset variable"""
tsv = fni.variables[varname]
ts=tsv[:]
# try:
# ts = np.array(ts,dtype='float32')*float(tsv.scale_factor)+float(tsv.add_offset)
# except AttributeError:
# x=0 # dummy statement
tr... | 2c987fa20c76911442cdcbba48f7b215350e0484 | 70,487 |
import time
import email
def date_time_string(timestamp=None):
"""Return the current date and time formatted for a message header."""
if timestamp is None:
timestamp = time.time()
return email.utils.formatdate(timestamp, usegmt=True) | 0b2c319f341979b29ad6ca76eb6a93771e48e56e | 70,488 |
def dot_product_attention_relative(q,
k,
v,
bias,
max_relative_position,
dropout_rate=0.0,
image_shapes=None,
... | 211725c6a62c8258db6d6ec77c1bc726a5dccb90 | 70,489 |
from operator import add
def do_query(documents, config_file=None, logger=None, context=None):
"""
Iterate through documents and count total size of document files
in bytes.
Returns result of form:
{"total_size": total_size}
:param documents: RDD of defoe.document.Document
:type docu... | f505940b0c5b628bb2eea6c7bbbf3be28da41734 | 70,490 |
def get_bond(bond_id: str) -> Bond:
"""Return a specific bond.
Args:
bond_id (str): The bond id of the bond to fetch.
Raises:
HTTPException(400) if the bond does not exist.
Returns:
The requested bond."""
logger.info(f"Get bond: bond_id={bond_id}")
try:
bond: B... | d7883c89a4c625f71e2286787892a2c54ff2195a | 70,491 |
def _convert_dtype_string(dtype):
"""Get the String from type.
# Arguments
dtype: Type.
# Returns
A stromg representation of a type.
# Raises
ValueError: if `dtype` is not supported.
"""
mapping = {np.float16: 'float16',
np.float32: 'float32',
... | f49673e5f66b2f433c1932abaeaefe6a40f30dcc | 70,493 |
def splitCubicAtT(pt1, pt2, pt3, pt4, *ts):
"""Split the cubic curve between pt1, pt2, pt3 and pt4 at one or more
values of t. Return a list of curve segments.
>>> printSegments(splitCubicAtT((0, 0), (25, 100), (75, 100), (100, 0), 0.5))
((0.0, 0.0), (12.5, 50.0), (31.25, 75.0), (50.0, 75.0))
((50.0, 75.0), (6... | 8e21ee2c71456b4bedd3304df83868e0471ef380 | 70,496 |
def optimal_assignment_adv(adv_input):
"""
Calculate optimal assignment based on euclidean distance
"""
a_1 = calc_distance((adv_input[0], adv_input[1]),
(adv_input[4], adv_input[5]))
b_1 = calc_distance((adv_input[2], adv_input[3]),
(adv_input[4], adv... | 5b265f2601e123ad4a07b017d3da93460e3131e0 | 70,498 |
def increase_brightness(img, value=30):
"""Increase image brightness by increase V channel of HSV"""
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)
lim = 255 - value
v[v > lim] = 255
v[v <= lim] += value
final_hsv = cv2.merge((h, s, v))
img = cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
retu... | 1e4eae5f41e5a88dda476adcd6cedd0042d6fb19 | 70,500 |
def logbasechange(a,b):
"""
There is a one-to-one transformation of the entropy value from
a np.log base b to a np.log base a :
H_{b}(X)=np.log_{b}(a)[H_{a}(X)]
Returns
-------
np.log_{b}(a)
"""
return np.log(b)/np.log(a) | 3acdc740ec076ac6614f3fefee67523c98643031 | 70,501 |
def discount_arpu(arpu, timestep, global_parameters):
"""
Discount arpu based on return period.
192,744 = 23,773 / (1 + 0.05) ** (0:9)
Parameters
----------
arpu : float
Average revenue per user.
timestep : int
Time period (year) to discount against.
global_parameters : d... | 591051e285a4b6c5fa8ffd5db81c52e162985289 | 70,502 |
def build_cnn(image_input, image_output, tag_size):
"""
Implement a cnn to embed the images in relation to their tags. For a walkthough
on how to build cnns, please refer to this tensorflow tutorial:
https://www.tensorflow.org/versions/master/tutorials/mnist/pros/index.html#build-a-multilaye... | f55f07e2a6d228a56db7233d6427fb9c4a8b6809 | 70,503 |
import types
from typing import Tuple
from typing import Callable
def init(
typingctx: Context,
inst_typ: types.ClassInstanceType,
user_data: types.Integer,
) -> Tuple[
Signature,
Callable[[BaseContext, Builder, Signature, Tuple[Value, Value]], None],
]:
"""Initialize a `jitclass` by calling i... | 1eb481e659a102fbffdc072311fd856d6c9e038d | 70,504 |
def load_objects(file_name, layer_name, first_gid):
""" loads tiles in object layer from a tmx file.
Returns list of Item objects """
tree = ET.parse(file_name)
root = tree.getroot()
for child in root.findall("objectgroup"):
name = child.get("name")
if name == layer_name:
... | c0dbf51db828e29562d249ff545d2e29adad1fd4 | 70,505 |
from web import morguefile
def morguefile(query, n=10, top=10):
""" Returns a list of colors drawn from a morgueFile image.
With the Web library installed,
downloads a thumbnail from morgueFile and retrieves pixel colors.
"""
images = morguefile.search(query)[:top]
path = choic... | eb89a92ab047ce9f14e230c485fa07fde9ca5024 | 70,506 |
def to_sequence(value: list, shape: list, dtype: DType) -> Tensor:
""" Convert `VALUES` result from RedisAI to `Tensor` """
dtype = DType.__members__[dtype.lower()]
convert_to_num(dtype, value)
return Tensor(value, tuple(shape), dtype, 'VALUES') | b1df3fcb91fd3c7085e93038c2a819dd69ecd5d7 | 70,507 |
import asyncio
async def vif_list(cluster_id: str):
"""Get All from Storage Repos"""
try:
session = create_session(
_id=cluster_id, get_xen_clusters=Settings.get_xen_clusters()
)
vifs = VIF.get_all(session=session)
__santilized_vifs = await asyncio.gather(*[serial... | d632678c580b809f98f2dad91c70e8db254c0795 | 70,508 |
def transform_url(private_urls):
"""
Transforms URL returned by removing the public/ (name of the local folder with all hugo html files)
into "real" documentation links for Algolia
:param private_urls: Array of file links in public/ to transform into doc links.
:return new_private_urls: A list of do... | 17a5c720103294b7535c76d0e8994c433cfe7de3 | 70,509 |
def query_store(request, store_name, query):
"""Queries the store; Returns the result of the query in the form of:
[
{
"oid": <document_id>,
"data": <document_data>,
},
...
]
Keyword arguments:
request -- Django HttpRequest object
store_name -- th... | 5190a2a10bbea6212b26c16066bda0392600c517 | 70,510 |
def gene_MOMA(model, reference=None, constraints=None, reactions=None, solver=None):
""" Perform a gene-wise version of MOMA.
This method minimizes the metabolic adjustment at gene level (rather than reaction level).
It is also possible to introduce constraints directly at gene level as well.
Notes:
... | a2341ab7b327b66d39c28dfa4e82d678a12b2436 | 70,511 |
def _3dsmax_main_window():
"""Return 3dsmax's main window"""
return MaxPlus.GetQMaxMainWindow() | ddf7141a6a08bf44c4438307ff601028105d23a6 | 70,512 |
def one_hot(x, n_classes=None):
"""
Returns one_hot encoding of the input vector
Parameters
- x: t.tensor, size=[n], dtype=t.long, integer values range [0, n_classes)
- n_classes: number or None. if None, this value is determined automatically
Returns: t.tensor, size=[n, n_classes], ... | 730103dc166ef5e59c58ecab553a17455c766fc3 | 70,515 |
def get_settings():
"""Expose the settings
:return: Return the settings
:rtype: Settings
"""
return Settings() | 09bd14525d059a9c42cc7c08a5eafa6894fa1286 | 70,516 |
from typing import Dict
from typing import Optional
from typing import Any
from typing import Union
def test_logger_after_fit_predict_test_calls(tmpdir):
"""Make sure logger outputs are finalized after fit, prediction, and test calls."""
class BufferLogger(LightningLoggerBase):
def __init__(self):
... | dab1944789be3eaca8ef5641a5fd2e82d74b8b9d | 70,517 |
def calc_value_counts(
a_gpu, stride, min_value, data_points, custom_binning=False
):
"""
description:
main function to calculate histograms
input:
- a_gpu: gpu array(cuda ndarray) -> 1-column only
- bins: number of bins
output:
frequencies(ndarray), bin_edge_values(n... | c9281828c7db63086fd461d1636df85c27983c7a | 70,518 |
def subscribe_vk():
"""Function for enable subscribe news by vk"""
try:
if 'status' in request.form:
session = create_session()
status = request.form.get('status')
status = bool(int(status))
user = session.query(User).get(current_user.id)
if no... | 073b284eca619cfe6403bcc34b59286862313113 | 70,519 |
def get_scheduler(optimizer, opt):
"""Return a learning rate scheduler
Parameters:
optimizer -- the optimizer of the network
opt (option class) -- stores all the experiment flags needs to be a subclass of BaseOptions.
opt.lr_policy is the name of learnin... | f03bc50eb5e27d2f28a28d82e30e6471f49ffec5 | 70,520 |
def send_feedback_email_task(message):
"""sends an email when feedback form is filled successfully"""
logger.info("Sent feedback email")
#return send_feedback_email(email, message)
print("got %s" % message)
return message | bbc96b60124369ae284fd899c09a654e5c0eaba5 | 70,521 |
def mcat(i):
"""Concatenate a list of matrices into a single matrix using separators
',' and ';'. The ',' means horizontal concatenation and the ';' means
vertical concatenation.
"""
if i is None:
return marray()
# calculate the shape
rows = [[]]
final_rows = 0
final_cols = ... | 238218c7fc63c555a7ef033132eae5eddc52fd80 | 70,522 |
def isolated_recovery_rate_80():
"""
Real Name: b'isolated recovery rate 80'
Original Eqn: b'Isolated 80*(1-fraction of critical cases 80)/isolation duration 80'
Units: b'person/Day'
Limits: (None, None)
Type: component
b''
"""
return isolated_80() * (1 - fraction_of_critical_cases_... | 43ce6d43fd7b1dc27e8dd30ccfe615f7ea318f3f | 70,523 |
def setup_reports_close_tab(qtbot):
"""Set up reports widget, witha handy function to close tabs."""
reports = setup_reports(qtbot)
def close_tab(index):
"""Find the close button and click it."""
for i in [0, 1]: # LeftSide, RightSide
close_button = reports.tabs.tabBar().tabBut... | 370a42260daa04ea901d02b8f645e5f6a9687f23 | 70,524 |
def get_localization_metrics(true_pos, largest_dip_pos):
"""Helper to get accuracy and point spread
Accuracy: Euclidean distance between centroid of top n dipoles and the true
center of activation.
Point Spread: Average Euclidean distance between each of the top n dipoles
and the true cente... | 1219522189c9126320c9b4fb287eee92cb775566 | 70,525 |
def checkinGraph(node_to_check, graph_to_check_in):
"""
Checks for teh nnode in the graph, by looking at all the
keys / parent nodes
:param node_to_check: The node to check for
:type node_to_check: Node type
:param graph_to_check_in: The graph to check in
:ty... | f9a4ffb384bfbe1a7dab05929971ce8142dbe9d4 | 70,526 |
import html
def score_wrapper(log, markup=False):
"""Determine the type of log file and passes the log to the appropriate logchecker."""
try:
analyze_log(log)
except UnrecognizedException as exception:
log.unrecognized = str(exception)
log.full_contents = [html.escape(line) for li... | 5f848270e73b23d4591f259ad0aabb2718fdb89a | 70,527 |
def gen_clustree(cluster_df):
"""
Generates a nx.Digraph based clustree.
Can be plotted with:
```python
dg = gen_clustree(cluster_df)
nx.draw_networkx(dg, pos=nx.nx_agraph.graphviz_layout(dg, prog="dot"))
```
Args:
cluster_df (pd.DataFrame):
Dataframe where column ... | 9f2854c1a8e1de7b5a5928e20e2faa72ab3620f6 | 70,529 |
import importlib
import inspect
def pytask_collect_file(session, path, reports):
"""Collect a file."""
if any(path.match(pattern) for pattern in session.config["task_files"]):
spec = importlib.util.spec_from_file_location(path.stem, str(path))
if spec is None:
raise ImportError(f"... | 7e154c75c402e729b69c1611ff7b001f7fca57f1 | 70,530 |
import functools
def to_yaml_tree_metadata(func):
"""Wrapper that will add the metadata and userdata field for ``to_yaml_tree`` methods.
Also removes all "None" values from the initial tree.
Behavior should be similar to ASDF defaults pre v2.8 (ASDF GH #863).
"""
@functools.wraps(func)
def t... | ad58c6cbebeaece4702e1e87084a46dadfdf2777 | 70,531 |
from pathlib import Path
async def get_installation(
installation_id: int = Path(..., gt=0),
requester=Security(get_current_access, scopes=[AccessType.admin, AccessType.user])
):
"""
Based on a installation_id, retrieves information about the specified installation
"""
requested_group_id = awa... | 3af3835afbbf3a3f1e1be2da3b7cc756f1eef533 | 70,532 |
import re
def fingerprint(source=None):
"""Create a new fingerprint of current repositories.
The source argument is parsed to look for the expected output
from a `sync-all` command. If the source is `None` then the
`sync-all` command will be run to get the current fingerprint.
"""
if source is None:
... | b486593150de10f39ba66458644fb7d9fbddb69e | 70,533 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.