content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import inspect
def GetUniqueClassMembers(Class, Ignore = [], AllowedOverrides = []):
"""
Args:
- Class {object}: reference to the class
- Ignore {List[str]}:
- AlwaysAllow {List[str]}: Always allowed members named x, even if they exists in the parent class
Returns: tuple("Name",... | bdd22e6ce7eaa12d2285f7ca7747a0210d3b98c9 | 3,651,973 |
def get_condition_keys_available_to_raw_arn(db_session, raw_arn):
"""
Get a list of condition keys available to a RAW ARN
:param db_session: SQLAlchemy database session object
:param raw_arn: The value in the database, like arn:${Partition}:s3:::${BucketName}/${ObjectName}
"""
rows = db_session... | 8f8025ffe1fd6f6fa750f826b0a3c5b8a4f655eb | 3,651,974 |
def get_reviewer(form):
""" Gets reviewer info, or adds if necessary
"""
reviewer = Reviewer.query.filter_by(email=form.get("reviewer-email")).first()
if reviewer:
reviewer_id = reviewer.reviewer_id
else:
reviewer_id = add_reviewer(form)
return reviewer_id | 641bb81e73bad7f0eeac8a5cbd5efde499535b77 | 3,651,975 |
def read_xyz(using):
"""Reads coordinates of an xyz file and return a list of |Atom| objects, one for each atom"""
coords = []
with open(using, "r") as f:
for coord in f.readlines()[2:]:
line = coord.split()
for val in PT.ptable.values():
if line[0] == val[0]:... | 9ed1b0de9fe4bd7bbabe63a2d808b08e44315113 | 3,651,976 |
def initialize_classification(model_name: str,
num_classes: int,
use_pretrained: bool =True
) -> (Module, int):
""" Initialize these variables which will be set in this if statement. Each of these
variables is mo... | 23958e7970022b2c0ed77353fa8b927510873bb7 | 3,651,977 |
def get_csc():
"""get Configuration Client"""
config_host = enstore_functions2.default_host()
config_port = enstore_functions2.default_port()
return configuration_client.ConfigurationClient((config_host,config_port)) | 49c2740ac9a654e700079d15f32421e32f8568c3 | 3,651,978 |
def findx(mu, lnum):
"""Obtains the Hill sphere and x-coordinate for a mu-value and lnum."""
hill = (mu/3)**(1.0/3.0)
if lnum == 1: #lnum is used to request one of the collinear Lagrange points.
guess = 1 - mu - hill * (1 - (1.0/3.0) * hill - (1.0/9.0) * hill ** 2)
elif lnum == 2:
... | 260f9dda3b5a494df15d3c0bbe7ce0ebd0351c9b | 3,651,979 |
def _f1_div_ ( self , other ) :
"""Operator for ``1D-function / other''"""
return _f1_op_ ( self , other , Ostap.MoreRooFit.Division , "Divide_" ) | 5278ec2036724f0bb263487b8880c16b161d8145 | 3,651,980 |
def test_interrupted_late_wait():
"""Test we can interrupt the wait during the timeout period.
"""
called = 0
def cond():
nonlocal called
called += 1
if called == 3:
return True
job = InstrJob(cond, 0)
assert not job.wait_for_completion(lambda: True, refresh... | 737df84c71efdaf0e52be5f42c0ae856f9fb1018 | 3,651,981 |
def set_prior_6(para):
"""
set prior before the first data came in
doc details to be added
"""
n_shape = para['n_shape']
log_prob = [ [] for i_shape in range(n_shape) ]
delta_mean = [ [] for i_shape in range(n_shape) ]
delta_var = [ [] for i_shape in range(n_shape) ]
time_since_last... | e97944e1c48ca6def16308584dfe04eaebae6259 | 3,651,982 |
def inf_set_af2(*args):
"""
inf_set_af2(_v) -> bool
"""
return _ida_ida.inf_set_af2(*args) | c9fa149ca8595d053db4eb4d4113e2493b8665de | 3,651,983 |
import pandas as pd
def json_find_matches_dataframe(df, filter_path, reverse_selectivity=False):
"""Iteratively filters a pandas.DataFrame df using the same sort of
filter_path used by json_extract.
Because of the tabular nature of pandas DataFrames, filters are treated as
being either 'down' ... | 33f3de47ffbe774d22e2dc9fb7c07f132272452f | 3,651,985 |
def contrast(arr, amount=0.2, split=0.5, normalize=True):
"""
General contrast booster or diffuser of normalized array-like data.
Parameters
----------
arr : ndarray
Input array (of floats on range [0, 1] if ``normalize=False``). If
values exist outside this range, with ``normalize=... | 94542fd4df7c65c98f818b652c733ad5a319f449 | 3,651,986 |
def get_group(items, total_groups, group_id):
"""
Get the items from the passed in group based on group size.
"""
if not 0 < group_id <= total_groups:
raise ValueError("Invalid test-group argument")
start, size = get_group_size_and_start(len(items), total_groups, group_id)
selected = it... | f236c9f26adfa5da5507e7ae91feb8858ac13c6c | 3,651,987 |
def read_nq_entry(entry, is_training):
"""
Converts a NQ entry into a list of NqExamples.
:param entry: dict
:param is_training: bool
:return: list[NqExample]
"""
def is_whitespace(c):
return c in " \t\r\n" or ord(c) == 0x202F
examples = []
contexts_id = entry["id"]
con... | a712ff6a2714798ee49fd90741f387d8cb3b4695 | 3,651,988 |
def calc_atoms(psi, vol_elem=1.0):
"""Calculate the total number of atoms.
Parameters
----------
psi : :obj:`list` of 2D NumPy :obj:`array` or PyTorch :obj:`Tensor`
The input spinor wavefunction.
vol_elem : :obj:`float`
2D volume element of the space.
Returns
-------
at... | 9e9d87c9445a6a03fe245b66c2ce1c104a276e7a | 3,651,989 |
def get_tcp_packet_payload_len(pkt: dpkt.ethernet.Ethernet) -> int:
"""
Return the length of only payload without options
:param pkt: dpkt.ethernet.Ethernet packet containing TCP header
:return: int
"""
if isinstance(pkt, dpkt.ethernet.Ethernet):
ip = pkt.data
elif isinstance(pkt... | 410ec3f76085647def33572cc35f951462dd9324 | 3,651,990 |
def overviewUsage(err=''):
""" default overview information highlighting active scripts"""
m = '%s\n' %err
m += ' The following scripts allow you to manage Team Branches (TmB) on SalesForce.\n'
m += ' Use one of the scripts below to meet your needs.\n'
m += ' \n'
m += ' 1. First link Task Br... | ba62773dd8be21d17c44e8e295c8228d568512a0 | 3,651,991 |
def min_distance(z_i, z_j, sc_size):
"""Calculates the minimum distance between the particle at
``z_i`` and all of the images of the particle at ``z_j``,
including this. The minimum distance is always less than
half of the size of the simulation supercell ``sc_size``.
:param z_i:
:param z_j:
... | b585eb8e813ca852c4538eea7a9a6f9028a969d7 | 3,651,992 |
import re
def prf(gold: str, pred: str, dic) -> tuple:
"""
计算P、R、F1
:param gold: 标准答案文件,比如“商品 和 服务”
:param pred: 分词结果文件,比如“商品 和服 务”
:param dic: 词典
:return: (P, R, F1, OOV_R, IV_R)
"""
A_size, B_size, A_cap_B_size, OOV, IV, OOV_R, IV_R = 0, 0, 0, 0, 0, 0, 0
with open(gold,encoding='... | a8767bbe4c60eea2433d2c8023a9d7a1af74a4bf | 3,651,993 |
def lorem():
"""Returns some sample latin text to use for prototyping."""
return """
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nis... | 6ddacdb23b7c62cf930e622a7fd801b514a419ae | 3,651,994 |
def read_gene2species(* filenames):
"""
Reads a gene2species file
Returns a function that will map gene names to species names.
"""
for filename in filenames:
maps = []
for filename in filenames:
maps.extend(util.read_delim(util.skip_comments(
util.open_... | 90e58b2089f2561642ac1ba6648256888b931080 | 3,651,995 |
def make_list_table(headers, data, title='', columns=None):
"""Build a list-table directive.
:param headers: List of header values.
:param data: Iterable of row data, yielding lists or tuples with rows.
:param title: Optional text to show as the table title.
:param columns: Optional widths for the ... | 569370b8359ad25bf255f940b5a89d93d896804d | 3,651,997 |
def toss_unbaised():
"""
toss 2 times:
assign 0-1 = 0
assign 1-0 = 1
discard 0-0 and 1-1
"""
while True:
first, second = toss_biased(), toss_biased()
if first == 0 and second == 1:
return 0
if first == 1 and second == 0:
return 1 | 971f3365fbc4f0de34cd51c8060aab5c5037c7b2 | 3,651,998 |
def split_val_condition(input_string):
"""
Split and return a {'value': v, 'condition': c} dict for the value and the condition.
Condition is empty if no condition was found.
@param input A string of the form XXX @ YYYY
"""
try:
(value, condition) = [x.strip() for x in input_string.s... | 97c5733a80b3348928b95e2430bf3630867b2050 | 3,651,999 |
def shimenreservoir_operation_rule_lower_limit():
"""
Real Name: ShiMenReservoir Operation Rule Lower Limit
Original Eqn: WITH LOOKUP ( Date, ([(1,190)-(366,250)],(1,240),(32,240),(152,220),(182,220),(244,225),(335,240),(365,\ 240) ))
Units: m
Limits: (None, None)
Type: component
"""
r... | 72830cd13bb411afe67398750f33c75a3a5bfba3 | 3,652,000 |
def pre_process(dd, df, dataset_len, batch_size):
"""Partition one dataframe to multiple small dataframes based on a given batch size."""
df = dd.str2ascii(df, dataset_len)
prev_chunk_offset = 0
partitioned_dfs = []
while prev_chunk_offset < dataset_len:
curr_chunk_offset = prev_chunk_offset... | a0a19916d60476430bdaf27f85f31620f2b5ae2a | 3,652,001 |
from datetime import datetime
import re
def fromisoformat(s):
"""
Hacky way to recover a datetime from an isoformat() string
Python 3.7 implements datetime.fromisoformat() which is the proper way
There are many other 3rd party modules out there, but should be good enough for testing
"""
return... | 7db362222f9da28f43eab5363336e0ca09b65960 | 3,652,002 |
def non_repeat(a, decimals=12):
"""
Функция возвращает матрицу А с различными строками.
"""
a = np.ascontiguousarray(a)
a = np.around(a, decimals = int(decimals))
_, index = np.unique(a.view([('', a.dtype)]*a.shape[1]), return_index=True)
index = sorted(index)
return a[index] | 312ce49fe275649c745ee22c79a08c0a2c1b798b | 3,652,003 |
def softmax_with_cross_entropy(predictions, target_index):
"""
Computes softmax and cross-entropy loss for model predictions,
including the gradient
Arguments:
predictions, np array, shape is either (N) or (batch_size, N) -
classifier output
target_index: np array of int, shape is (1... | 9683da852dae92a5dec1f4353f4d93b2243fd30d | 3,652,004 |
import re
def scraper_main_olx(url):
""" Reads pages with offers from OLX and provides URLS to said offers. """
def __create_url_olx(offs_ids, prefix="https://www.olx.pl"):
""" Method creates an olx offer link from parts read from a main page. """
return [
"/".join([
... | 4f209dd800124c3b59db31029141e4d37f98e7d8 | 3,652,005 |
import torch
from typing import Tuple
from typing import List
def accuracy(
output: torch.Tensor,
target: torch.tensor,
topk: Tuple[int] = (
1,
)) -> List[float]:
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad... | 73dd8a03e729fa89cea7abf535779dd45897113d | 3,652,007 |
def _make_unique(key, val):
"""
Make a tuple of key, value that is guaranteed hashable and should be unique per value
:param key: Key of tuple
:param val: Value of tuple
:return: Unique key tuple
"""
if type(val).__hash__ is None:
val = str(val)
return key, val | 65d746276f635c129aa0a5aeb9b9f467453c0b2a | 3,652,008 |
def replace_caps(x):
"""Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before."""
res = []
for t in x:
if t == '': continue
if t[0].isupper():
if len(t) == 1 and t[0] == 'I':
res.append(TK_MAJ)
if len(t) > 1 and (t[1:].is... | 72519c264a97b60b05d430fc86dce1069e3718a7 | 3,652,009 |
def computes_ts_coverage(k, outputs, two_symbols):
""" Computes the input coverage by Two Symbol schematas.
Args:
k (int): the number of inputs.
outpus (list): the list of transition outputs.
two_symbols (list): The final list of Two Symbol permutable schematas. This is returned by `fin... | 741718bb78ffc6840bb004eb80f096dc30d4df79 | 3,652,010 |
def create_measurements(nh, nv, offset, measurement_type):
"""Creates necessary measurement details for a given type on a given lattice.
Given the lattice size, whether odd or even pairs are being measured,
and the measurement type, this function returns a namedtuple
with the pairs of qubits to be meas... | ff4dbe1ee49a0db41c30fc9ba8fc6ab94c314c48 | 3,652,011 |
def headline(
in_string,
surround = False,
width = 72,
nr_spaces = 2,
spacesym = ' ',
char = '=',
border = None,
uppercase = True,
):
"""return in_string capitalized, spaced and sandwiched:
============================== T E S T... | 1848d91bbf6c9d2216338f35433a26bcd3854664 | 3,652,012 |
import itertools
import unicodedata
def rainbow_cmd(bot, trigger):
"""Make text colored. Options are "rainbow", "usa", "commie", and "spooky"."""
text = clean(trigger.group(2) or '')
scheme = trigger.group(1).lower()
if not text:
try:
msg = SCHEME_ERRORS[scheme]
except Key... | 292e55511b40c3c265e7ba87164cf179e54c16a6 | 3,652,013 |
def url_decode(s, charset='utf-8', decode_keys=False, include_empty=True,
errors='ignore', separator='&', cls=None):
"""Parse a querystring and return it as :class:`MultiDict`. Per default
only values are decoded into unicode strings. If `decode_keys` is set to
`True` the same will happen f... | 2b5b9598639ef600900dd1cb50c8ec6de892feff | 3,652,014 |
from typing import Type
def special_loader(as_type: type) -> Type[FullLoader]:
"""Construct new loader class supporting current class structure"""
class TypedLoader(FullLoader): # pylint: disable=too-many-ancestors
"""Custom loader with typed resolver"""
...
_add_path_resolvers(as_type,... | e60c96284334fc57cc32af557a86433bb5302526 | 3,652,015 |
def try_(func, *args, **kwargs):
"""Try to call a function and return `_default` if it fails
Note: be careful that in order to have a fallback, you can supply
the keyword argument `_default`. If you supply anything other
than a keyword arg, it will result in it being passed to the wrapped
function a... | 206b25bd2e345d9cd6423e2cbc2706c274f36c89 | 3,652,016 |
def _create_course_and_cohort_with_user_role(course_is_cohorted, user, role_name):
"""
Creates a course with the value of `course_is_cohorted`, plus `always_cohort_inline_discussions`
set to True (which is no longer the default value). Then 1) enrolls the user in that course,
2) creates a cohort that th... | 6f55d10d4b1dfa27c067298862e89a558c5618a1 | 3,652,017 |
def relative_vorticity(
u, v, wrap=None, one_sided_at_boundary=False, radius=6371229.0, cyclic=None
):
"""Calculate the relative vorticity using centred finite
differences.
The relative vorticity of wind defined on a Cartesian domain (such
as a plane projection) is defined as
ζcartesian = δv... | 6134a44594cd84174f44f00a57df2f7284c4a7e5 | 3,652,018 |
import torch_geometric
import torch
def coalesce(
edge_index: torch.Tensor,
edge_attr: _typing.Union[
torch.Tensor, _typing.Iterable[torch.Tensor], None
] = None,
num_nodes: _typing.Optional[int] = ...,
is_sorted: bool = False,
sort_by_row: bool = True
) -> ... | 00006971c06fc599edb6b3ff12b2e0a7700dd136 | 3,652,019 |
def get_label_names(l_json):
"""
Get names of all the labels in given json
:param l_json: list of labels jsons
:type l_json: list
:returns: list of labels names
:rtype: list
"""
llist = []
for j in l_json:
llist.append(j['name'])
return llist | bab12bedc8b5001b94d6c5f02264b1ebf4ab0e99 | 3,652,020 |
from ...niworkflows.engine.workflows import LiterateWorkflow as Workflow
from ...niworkflows.interfaces.utility import KeySelect
from ...smriprep.workflows.outputs import _bids_relative
from ...niworkflows.interfaces.space import SpaceDataSource
def init_asl_derivatives_wf(
bids_root,
metadata,
output_dir... | c5a5425dd38fd1b451b41a687a44c8edbb3d24b0 | 3,652,021 |
def makehash(w=dict):
"""autovivification like hash in perl
http://stackoverflow.com/questions/651794/whats-the-best-way-to-initialize-a-dict-of-dicts-in-python
use call it on hash like h = makehash()
then directly
h[1][2]= 3
useful ONLY for a 2 level hash
"""
# return defaultdict(m... | 5c772c07de9231c40053b29c545e25b611dd3b6e | 3,652,022 |
def sample_parameters(kmodel,
tmodel,
individual,
param_sampler,
scaling_parameters,
only_stable=True,
):
"""
Run sampling on first order model
"""
solution_raw = individu... | cc48f170c58c090844dbbf0e72aa2bc9f2a1598b | 3,652,023 |
import yaml
def load_yaml(fpath):
""" load settings from a yaml file and return them as a dictionary """
with open(fpath, 'r') as f:
settings = yaml.load(f)
return settings | bd9c19407c39e190f2d7fd734d118dbb4e9378ab | 3,652,024 |
import statistics
def recommendation(agent, other_agent, resource_id, scale, logger, discovery, recency_limit):
"""
Get recommendations on other agent of third agents and average them to one recommendation value.
:param agent: The agent which calculates the popularity.
:type agent: str
:param oth... | 0670ec3d388dc008f2c5315907fac11f80aa7ebe | 3,652,025 |
import time
import numpy
import pandas
import numpy.testing
import mhctools
def do_predictions_mhctools(work_item_dicts, constant_data=None):
"""
Each tuple of work items consists of:
(work_item_num, peptides, alleles)
"""
# This may run on the cluster in a way that misses all top level imports... | c42270f3b31b984973e9e668902ac2018f38b25f | 3,652,026 |
def inceptionresnetv2(**kwargs):
"""
InceptionResNetV2 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,'
https://arxiv.org/abs/1602.07261.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for mod... | 7c11c147d01b6551fa1b65cb5d24497efc2a3d3b | 3,652,027 |
def _n_pow_i(a, b, n):
"""
return (1+i)**k
"""
x = a
y = b
for i in range(1, n):
x1 = (x*a) - (y*b)
y1 = (y*a) + (x*b)
x = x1
y = y1
return x, y | 35b00c7bc76aaf19a5acdf012e63c9c0c50e5d1d | 3,652,029 |
def IsNameBased(link):
"""Finds whether the link is name based or not
:param str link:
:return:
True if link is name-based; otherwise, False.
:rtype: boolean
"""
if not link:
return False
# trimming the leading "/"
if link.startswith("/") and len(link) > 1:
lin... | e887fd6cd02c7ef71cbafa825014e1fca2c9d4d1 | 3,652,030 |
def register_submit(class_name, fire) -> None:
"""
Register on a form a handler
:param class_name: class name of the form
:param fire: function that will be fire on form submit
:return: None
"""
def submit_handler(event) -> None:
"""
Handle form submit and fire handler
... | f2f8b2b067a282b073d6cc13825aedc3509c8077 | 3,652,031 |
from typing import Any
def compile(obj: Any) -> Definition:
"""Extract a definition from a JSON-like object representation."""
return ConcreteValue(obj) | 5e82471be599e77739e485468571bee296bfca71 | 3,652,032 |
def policy_network(vocab_embed_variable, document_placeholder, label_placeholder):
"""Build the policy core network.
Args:
vocab_embed_variable: [vocab_size, FLAGS.wordembed_size], embeddings without PAD and UNK
document_placeholder: [None,(FLAGS.max_doc_length + FLAGS.max_title_length + FLAGS.max_image... | d59cf6d1d99fca7c654087d8fc720b64e419bced | 3,652,033 |
def get_feature(file_path: str):
""" Read and parse given feature file"""
print('Reading feature file ', file_path)
file_obj = open(file_path, "r")
steam = file_obj.read()
parser = Parser()
return parser.parse(TokenScanner(steam)) | e30e78afdb205aa2c26e3831ca7b0091579866a3 | 3,652,034 |
def hough_lines_draw(img, outfile, peaks, rhos, thetas):
"""
Returns the image with hough lines drawn.
Args
- img: Image on which lines will be drawn
- outfile: The output file. The file will be saved.
- peaks: peaks returned by hough_peaks
- rhos: array of rhos used in Hough Sp... | f1731adb7d90a69dc50721c03f9e2ab01b7e2078 | 3,652,035 |
def cg_file_h(tmpdir):
"""Get render config."""
return {
'cg_file': str(tmpdir.join('muti_layer_test.hip'))
} | caedb2324953e4ca90ebffdf80be60fed1b8026d | 3,652,036 |
from ._groupbyuntil import group_by_until_
from typing import Optional
from typing import Callable
from typing import Any
def group_by_until(
key_mapper: Mapper[_T, _TKey],
element_mapper: Optional[Mapper[_T, _TValue]],
duration_mapper: Callable[[GroupedObservable[_TKey, _TValue]], Observable[Any]],
s... | c4f54140dadbd0d043400a35f9be9f978460ae3c | 3,652,037 |
def GetFilesystemSize(options, image_type, layout_filename, num):
"""Returns the filesystem size of a given partition for a given layout type.
If no filesystem size is specified, returns the partition size.
Args:
options: Flags passed to the script
image_type: Type of image eg base/test/dev/factory_inst... | 1ea542366a11f9a00b648b5158282a4b5e39f633 | 3,652,038 |
def match_pairs(obj_match, params):
""" Matches objects into pairs given a disparity matrix and removes
bad matches. Bad matches have a disparity greater than the maximum
threshold. """
# Create a list of sets, where the i-th set will store the objects
# from image1 that have merged with objects in... | 42939faca3cc2a61e8dde1b00818da593aa89c7a | 3,652,039 |
def spike_train_convolution(spike_times, interval, dt, sigma):
"""
Needed for Schreiber reliability measure
"""
N = int(np.floor((interval[1]-interval[0])/dt)+1)
x = np.linspace(interval[0], interval[1], N)
s = np.zeros(N)
for spike in spike_times:
s = s + gaussian(x, spike, sigma)
... | 0dbd2ac6a3cc016ecb0ab7209256d1544b6acfd1 | 3,652,040 |
def interpolate_peak(spectrum: list, peak: int) -> float:
""" Uses quadratic interpolation of spectral peaks to get a better estimate of the peak.
Args:
- spectrum: the frequency bin to analyze.
- peak: the location of the estimated peak in the spectrum list.
Based off: htt... | 0e74057908e7839438325da9adafdf385012ce17 | 3,652,042 |
def _check_trunk_switchport(
dut, check, expd_status: SwitchportTrunkExpectation, msrd_status: dict
) -> tr.CheckResultsCollection:
"""
This function validates a trunk switchport against the expected values.
These checks include matching on the native-vlan and trunk-allowed-vlans.
"""
results =... | a739ae5897c4627ea78d27a07f831e528318f052 | 3,652,043 |
def is_valid_compressed(file):
"""Check tar gz or zip is valid."""
try:
archive = ZipFile(file, 'r')
try:
corrupt = archive.testzip()
except zlib_error:
corrupt = True
archive.close()
except BadZipfile:
corrupt = True
return not corrupt | 261a4fcdfa1117aa749b00805e323f21a04d0f57 | 3,652,044 |
def Krsol_SP_pt(SP,pt):
"""
Krsol_SP_pt solubility of Kr in seawater
==========================================================================
USAGE:
Krsol = sol.Krsol_SP_pt(SP,pt)
DESCRIPTION:
Calculates the krypton, Kr, concentration expected at equil... | 3402fdf5756ca9a54938211e67a57de1326bcc7f | 3,652,045 |
def find_title(item):
"""Title of the video"""
title = item['snippet']['title']
return title | 9c6f64e02d959d46cfd1e4536f5faf7ec0c281bd | 3,652,047 |
import hashlib
def calc_fingerprint(text):
"""Return a hex string that fingerprints `text`."""
return hashlib.sha1(text).hexdigest() | 8be154e4e32ae9412a73e73397f0e0198ae9c862 | 3,652,048 |
from typing import List
from typing import Any
from typing import Tuple
import torch
def yolo_collate_fn(
batch: List[Any],
) -> Tuple[Tensor, Tuple[Tensor, Tensor, List[Tuple[Tensor, Tensor]]]]:
"""
Collate function to be used for creating a DataLoader with values for Yolo model
input.
:param ba... | 599d4e9bbb91cf6d79225024cbcd9690cb55f8e6 | 3,652,049 |
def delete_category(category_id):
"""Delete a category."""
category = session.query(Category).filter_by(id=category_id).first()
if 'username' not in login_session:
flash("Please log in to continue.")
return redirect(url_for('login'))
if not exists_category(category_id):
flash(... | 979aabe5b6d7730c9f75a714266d6aad61e1cd41 | 3,652,050 |
from typing import List
def get_all_users_of(fx_module: GraphModule, index: int) -> List[int]:
"""Given the graph(fx_module) and an index, return a list of all node indexes that use this node"""
graph = fx_module.graph
current_node = graph.nodes[index]
user_indexes: List[int] = []
"""if the node A... | e3fc32aa7baf549bbfe4a2fb7558aa7bfb3d84b0 | 3,652,051 |
from operator import and_
def insert_from(
table_name, into_table_name, column_names=None, join_columns=None, create_if_not_exists=False, engine=None
):
"""
Inserts records from one table into another
:param table_name: the name of the table from which to insert records
:param into_table_name: th... | 8c013bdaeb1c16e1a487c4a90c0554e9b673f4d9 | 3,652,052 |
def format(color, style=''):
"""Return a QTextCharFormat with the given attributes.
"""
_color = QColor()
_color.setNamedColor(color)
_format = QTextCharFormat()
_format.setForeground(_color)
if 'bold' in style:
_format.setFontWeight(QFont.Bold)
if 'italic' in style:
_fo... | bd526cab85bd8909904af0c6e32b22d29c1de561 | 3,652,053 |
def array_to_mincvolume(filename, array, like,
volumeType=None, dtype=None, labels=None,
write=True, close=False):
"""
Create a mincVolume from a data array.
Create a mincVolume from a data array, using coordinate system information from another volume.
... | 16074668c1143091322969a501b23203378ca169 | 3,652,054 |
import random
def getRandomPipe():
"""returns a randomly generated pipe"""
# y of gap between upper and lower pipe
gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE))
gapY += int(BASEY * 0.2)
pipeHeight = IMAGES['pipe'][0].get_height()
pipeX = SCREENWIDTH + 10
return [
{'x'... | a5789a090ff7ab88b5cf6cbf4ad8e0943ea9ccdf | 3,652,055 |
from typing import Optional
def get_spot_market_price(facility: Optional[str] = None,
plan: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSpotMarketPriceResult:
"""
Use this data source to get Packet Spot Market Price.
... | 912f07ced8a12ba4df7992c8cbba2576673a893f | 3,652,056 |
def _get_cluster_id(emr: boto3.client("emr"), clusterName: str) -> str:
"""
Returns the id of a running cluster with given cluster name.
"""
clusters = emr.list_clusters()["Clusters"]
# choose the correct cluster
clusters = [c for c in clusters if c["Name"] == clusterName and c["Status"]["State... | 9fba31d05157411d8fddde7502e174433859898f | 3,652,057 |
def seed_student(request, i):
"""Returns the properties for a new student entity.
"""
gsoc2009 = Program.get_by_key_name('google/gsoc2009')
user = User.get_by_key_name('user_%d' % i)
if not gsoc2009:
raise Error('Run seed_db first')
if not user:
raise Error('Run seed_many for at least %d ... | 01f1923b4d1e5af74c6bbad2649f04be62f29c6f | 3,652,058 |
from typing import List
def apply(effect: List[float], signal: List[float]):
"""Given effect interpolated to length of given signal.
Args:
effect: effect to interpolate to signal length.
signal: length of which effect is interpolated to.
"""
max_len = max(len(effect), len(signal))
... | 11bd4938c997cbef445493274fa3ee7447f1821e | 3,652,059 |
from typing import List
def evaluate_features(features: np.ndarray, labels: np.ndarray, train_frac: float = 0.8) -> List[int]:
"""
Evaluates the marginal impact of each feature in the given array (by retraining).
Args:
features: A [N, T, D] array of input features for each sequence element
... | 88b9d7cab4723934f16ab59c43e41d5a4140daa5 | 3,652,061 |
import six
def pad_for_tpu(shapes_dict, hparams, max_length):
"""Pads unknown features' dimensions for TPU."""
padded_shapes = {}
def get_filler(specified_max_length):
if not specified_max_length:
return max_length
return min(specified_max_length, max_length)
inputs_none_filler = get_filler(hp... | b72e1463fad9740c8a265b795c4b3c5a45e42a9a | 3,652,062 |
from typing import Union
from typing import Tuple
from typing import List
def _get_child_query_node_and_out_name(
ast: Union[FieldNode, InlineFragmentNode],
child_type_name: str,
child_field_name: str,
name_assigner: IntermediateOutNameAssigner,
) -> Tuple[SubQueryNode, str]:
"""Create a query nod... | c99e2a1aa7ea56600203e1550dca6a0a59eed094 | 3,652,063 |
def has_balanced_parens(exp: str) -> bool:
"""
Checks if the parentheses in the given expression `exp` are balanced,
that is, if each opening parenthesis is matched by a corresponding
closing parenthesis.
**Example:**
::
>>> has_balanced_parens("(((a * b) + c)")
False
:par... | f76c7cafcf6aadd0c2cb947f0c49d23835a9f6e4 | 3,652,064 |
def _is_binary(c):
"""Ensures character is a binary digit."""
return c in '01' | b763a5a8ba591b100fea64a589dcb0aea9fbcf53 | 3,652,065 |
def read_frame_positions(lmp_trj):
""" Read stream positions in trajectory file corresponding to
time-step and atom-data.
"""
ts_pos, data_pos = [], []
with open(lmp_trj, 'r') as fid:
while True:
line = fid.readline()
if not line:
break
... | c168f08577e38758bf3d9d42bae8379125d7fc33 | 3,652,070 |
async def async_setup_entry(hass, config_entry):
"""Set up Enedis as config entry."""
hass.data.setdefault(DOMAIN, {})
pdl = config_entry.data.get(CONF_PDL)
token = config_entry.data.get(CONF_TOKEN)
session = async_create_clientsession(hass)
enedis = EnedisGateway(pdl=pdl, token=token, session=... | 93ee0360c509088b75935f6b94bf7d918658e86b | 3,652,071 |
import requests
def get_file_list(prefix):
""" Get file list from http prefix """
print("Fetching file list from", prefix)
k = requests.get(prefix)
if not k.ok:
raise Exception("Unable to get http directory listing")
parser = HRefParser()
parser.feed(k.content.decode())
k.clos... | ca559a20e6f35f31a07e25f7f2a9dbc5db450cc0 | 3,652,072 |
def train_model(model: nn.Module, trainDataLoader: DataLoader, testDataLoader: DataLoader, epochs: int, optimizer, lossFuction, metric, device) -> dict:
"""
Training model function: it will train the model for a number of epochs, with the corresponding optimizer.
It will return the corresponding losses an... | bd971d4d5063ad83188e3093f46a6dba86ac995b | 3,652,073 |
import builtins
def _has_profile():
"""Check whether we have kernprof & kernprof has given us global 'profile'
object."""
return kernprof is not None and hasattr(builtins, 'profile') | 3cbb4a0539efbadcea22e2d39ee520e14d7c6da3 | 3,652,074 |
from typing import OrderedDict
def routing_tree_to_tables(routes, net_keys):
"""Convert a set of
:py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip
set of routing tables.
.. warning::
A :py:exc:`rig.routing_table.MultisourceRouteError` will
be raised if entrie... | 50384fa0f834f6311cea3b2901b6723ca3fab3c7 | 3,652,076 |
def extract_response_objects(image_file, mask_file, stim_file, input_dict):
"""inputs are file names for aligned images, binary mask, and unprocessed stimulus file
outputs a list of response objects"""
# read files
I = read_tifs(image_file)
mask = read_tifs(mask_file)
labels = segment_ROIs(mask)
... | 95b7a5e831d9ab0703c51d41966b36babf52b24d | 3,652,077 |
import torch
def get_top_diff_loc(imgs, ref_imgs, crop_size, grid_size, device, topk=10):
"""Randomly get a crop bounding box."""
assert imgs.shape == ref_imgs.shape
batches = imgs.size(0)
img_size = imgs.shape[2:]
crop_size = _pair(crop_size)
grid_size = _pair(grid_size)
stride_h = (img_s... | 2e35cc56a484432dd1c1ef05f38e01079414eecb | 3,652,078 |
import json
def decode(file):
"""
This function creates a dictionnary out of a given file thanks to pre-existing json functions.
:param file: The file to decode.
:return: The corresponding Python dictionnary or None if something went wrong (i.e: the given file \
is invalid).
"""
# J... | bfd0671f9e6bb06faa02a3179c1a5e18a607882c | 3,652,079 |
def kron_compact(x):
"""Calculate the unique terms of the Kronecker product x ⊗ x.
Parameters
----------
x : (n,) or (n,k) ndarray
If two-dimensional, the product is computed column-wise (Khatri-Rao).
Returns
-------
x ⊗ x : (n(n+1)/2,) or (n(n+1)/2,k) ndarray
The "compact"... | 55c2c89fa7eb9f7c2c1a3a296798b022c158c399 | 3,652,080 |
def record_speech_sequentially(min_sound_lvl=0.01, speech_timeout_secs=1.):
"""Records audio in sequential audio files.
Args:
min_sound_lvl: The minimum sound level as measured by root mean square
speech_timeout_secs: Timeout of audio after that duration of silence as measured by min_sound_lvl
... | f726f90575cf49a7de0608473f16a12f2a80d3cf | 3,652,081 |
def home():
"""
Display Hello World in a local-host website
"""
return 'Hello World' | f65a035d679878cfd897c9ea9c79fc41cf76db95 | 3,652,082 |
def selecaoEscalar(Mcorr, criterios, N=0, a1=0.5, a2=0.5):
""" Performs a scalar feature selection which orders all features individually,
from the best to the worst to separate the classes.
INPUTS
- Mcorr: Correlation matrix of all features.
- criterios:
- N: Number of best features to be returned.
- a1: Weig... | 713a7c8543cefdef8f4a35dd970d326fb49229a1 | 3,652,084 |
def sum_by_letter(list_of_dicts, letter):
"""
:param list_of_dicts: A list of dictionaries.
:param letter: A value of the letter keyed by 'letter'.
"""
total = 0
for d in list_of_dicts:
if d['letter'] == letter:
total += d['number']
return total | bffc5990eaa9e352d60d86d40b8a8b7070fd00c0 | 3,652,085 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.